github.com/erda-project/erda-infra@v1.0.10-0.20240327085753-f3a249292aeb/providers/mysqlxorm/sqlite3/provider.go (about) 1 // Copyright (c) 2021 Terminus, Inc. 2 // 3 // Licensed under the Apache License, Version 2.0 (the "License"); 4 // you may not use this file except in compliance with the License. 5 // You may obtain a copy of the License at 6 // 7 // http://www.apache.org/licenses/LICENSE-2.0 8 // 9 // Unless required by applicable law or agreed to in writing, software 10 // distributed under the License is distributed on an "AS IS" BASIS, 11 // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 12 // See the License for the specific language governing permissions and 13 // limitations under the License. 14 15 package sqlite3 16 17 import ( 18 "fmt" 19 "reflect" 20 21 "xorm.io/xorm" 22 "xorm.io/xorm/names" 23 24 "github.com/erda-project/erda-infra/base/logs" 25 "github.com/erda-project/erda-infra/base/servicehub" 26 "github.com/erda-project/erda-infra/providers/mysqlxorm" 27 ) 28 29 type config struct { 30 DbSourceName string `file:"dbSourceName" env:"SQLITE3_DB_SOURCE_NAME" default:"test.sqlite3"` 31 JournalMode string `file:"journalMode" env:"SQLITE3_JOURNAL_MODE" default:""` 32 RandomName bool `file:"randomName" env:"SQLITE3_RANDOM_NAME" default:"false"` 33 } 34 35 type provider struct { 36 Cfg *config 37 Log logs.Logger 38 *Sqlite3 39 } 40 41 var _ servicehub.ProviderInitializer = (*provider)(nil) 42 43 // Init . 44 func (p *provider) Init(ctx servicehub.Context) error { 45 var dbSourceName = p.Cfg.DbSourceName 46 var err error 47 if p.Cfg.RandomName { 48 dbSourceName, err = randomName(p.Cfg.DbSourceName) 49 if err != nil { 50 return err 51 } 52 } 53 54 engine, err := xorm.NewEngine("sqlite3", dbSourceName) 55 if err != nil { 56 return fmt.Errorf("failed to connect to sqlite3 engine,err : %s", err) 57 } 58 59 engine.SetMapper(names.GonicMapper{}) 60 61 if p.Cfg.JournalMode != "" { 62 _, err = engine.Exec(fmt.Sprintf("PRAGMA journal_mode = %s", p.Cfg.JournalMode)) 63 if err != nil { 64 return err 65 } 66 } 67 68 p.Sqlite3 = &Sqlite3{db: engine} 69 70 return nil 71 } 72 73 func init() { 74 servicehub.Register("sqlite3-xorm", &servicehub.Spec{ 75 Services: []string{"sqlite3-xorm"}, 76 Types: []reflect.Type{ 77 reflect.TypeOf((*mysqlxorm.Interface)(nil)).Elem(), 78 }, 79 Description: "sqlite3-xorm", 80 ConfigFunc: func() interface{} { return &config{} }, 81 Creator: func() servicehub.Provider { 82 return &provider{} 83 }, 84 }) 85 }