github.com/ecodeclub/eorm@v0.0.2-0.20231001112437-dae71da914d0/internal/datasource/single/db.go (about) 1 // Copyright 2021 ecodeclub 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 single 16 17 import ( 18 "context" 19 "database/sql" 20 "database/sql/driver" 21 "log" 22 "time" 23 24 "github.com/ecodeclub/eorm/internal/datasource" 25 26 "github.com/ecodeclub/eorm/internal/datasource/transaction" 27 ) 28 29 var _ datasource.TxBeginner = &DB{} 30 var _ datasource.DataSource = &DB{} 31 32 // DB represents a database 33 type DB struct { 34 db *sql.DB 35 multiStatements bool 36 } 37 38 func (db *DB) Query(ctx context.Context, query datasource.Query) (*sql.Rows, error) { 39 return db.db.QueryContext(ctx, query.SQL, query.Args...) 40 } 41 42 func (db *DB) Exec(ctx context.Context, query datasource.Query) (sql.Result, error) { 43 return db.db.ExecContext(ctx, query.SQL, query.Args...) 44 } 45 46 func OpenDB(driver string, dsn string, opts ...Option) (*DB, error) { 47 res := &DB{} 48 for _, o := range opts { 49 o(res) 50 } 51 52 if res.multiStatements { 53 dsn = dsn + "?multiStatements=true" 54 } 55 56 db, err := sql.Open(driver, dsn) 57 if err != nil { 58 return nil, err 59 } 60 res.db = db 61 return res, nil 62 } 63 64 func NewDB(db *sql.DB) *DB { 65 return &DB{db: db} 66 } 67 68 func (db *DB) BeginTx(ctx context.Context, opts *sql.TxOptions) (datasource.Tx, error) { 69 tx, err := db.db.BeginTx(ctx, opts) 70 if err != nil { 71 return nil, err 72 } 73 return transaction.NewTx(tx, db), nil 74 } 75 76 // Wait 会等待数据库连接 77 // 注意只能用于测试 78 func (db *DB) Wait() error { 79 err := db.db.Ping() 80 for err == driver.ErrBadConn { 81 log.Printf("等待数据库启动...") 82 err = db.db.Ping() 83 time.Sleep(time.Second) 84 } 85 return err 86 } 87 88 func (db *DB) Close() error { 89 return db.db.Close() 90 } 91 92 type Option func(db *DB) 93 94 // DBWithMultiStatements 在创建连接时 加入参数 multiStatements=true,允许多条语句查询 95 // 当然 multi statements 可能会增加sql注入的风险,故该操作只允许一次性业务操作,连接使用完成后需要关闭连接 96 func DBWithMultiStatements(m bool) Option { 97 return func(db *DB) { 98 db.multiStatements = m 99 } 100 }