How to use Open method of db Package

Best Syzkaller code snippet using db.Open

mysql_pool.go

Source:mysql_pool.go Github

copy

Full Screen

...94 sync.Mutex95 connChan chan *client.Conn96 threadMap sync.Map // key:thread id. value: 链接使用时间戳97 cfg *dbConfig98 minOpen int3299 maxOpen int32100 numOpen int32101}102func Open(103 host string,104 port uint16,105 username string,106 password string,107 DBName string,108 charset string,109 isAutoCommit bool,110 minOpen int32,111 maxOpen int32,112) (*MySQLPool, error) {113 cfg := NewDBConfig(host, port, username, password, DBName, charset, isAutoCommit)114 p := new(MySQLPool)115 p.cfg = cfg116 p.connChan = make(chan *client.Conn, MYSQL_POOL_MAX_OPEN_LIMIT)117 // 初始化 链接打开最小值118 if minOpen < 1 {119 p.minOpen = MYSQL_POOL_MIN_OPEN120 seelog.Warnf("最小使用链接数不能小于1, 默认值:%d", MYSQL_POOL_MIN_OPEN)121 } else {122 p.minOpen = minOpen123 }124 // 初始化 链接打开最大值125 if maxOpen < 1 {126 p.maxOpen = MYSQL_POOL_MAX_OPEN127 seelog.Warnf("最大使用链接数不能小于1, 默认值:%d", MYSQL_POOL_MIN_OPEN)128 } else {129 p.maxOpen = maxOpen130 }131 // 判断最大链接数是否大于系统允许的最大链接132 if maxOpen > MYSQL_POOL_MAX_OPEN_LIMIT {133 p.maxOpen = MYSQL_POOL_MAX_OPEN_LIMIT134 seelog.Warnf("指定最大链接数:%d, 大于系统允许最大连接数:%d, 默认设置最大链接数为:%d",135 maxOpen, MYSQL_POOL_MAX_OPEN_LIMIT, MYSQL_POOL_MAX_OPEN_LIMIT)136 }137 // 最小链接数不能大于最大链接数138 if p.minOpen > p.maxOpen {139 p.minOpen = p.maxOpen140 seelog.Warnf("最小链接数:%d 大于 最大链接数:%d. 设置最小链接为:%d",141 p.minOpen, p.maxOpen, p.maxOpen)142 }143 return p, nil144}145// 关闭连接池146func (this *MySQLPool) Close() {147 close(this.connChan)148 for conn := range this.connChan {149 this.Lock()150 if err := this.closeConn(conn); err != nil {151 seelog.Errorf("链接(thread id): %d. 关闭失败. %s", conn.GetConnectionID(), err.Error())152 }153 this.Unlock()154 }155}156func (this *MySQLPool) incrNumOpen() {157 atomic.AddInt32(&this.numOpen, 1)158}159func (this *MySQLPool) decrNumOpen() {160 atomic.AddInt32(&this.numOpen, -1)161}162// 关闭指定链接 // 序号在获取 mutex lock 使用, 不然会出现死锁163func (this *MySQLPool) closeConn(conn *client.Conn) error {164 threadID := conn.GetConnectionID()165 err := conn.Close()166 this.decrNumOpen()167 this.deleteThreadMapItem(threadID)168 return err169}170// 删除 thread id map 元素171func (this *MySQLPool) deleteThreadMapItem(threadID uint32) {172 if val, ok := this.threadMap.Load(threadID); ok {173 startTimestamp := val.(int64)174 currentTimstamp := time.Now().Unix()175 seelog.Infof("%s. thread id:%d, 运行了%d秒",176 this.cfg.addr(), threadID, currentTimstamp-startTimestamp)177 } else {178 seelog.Infof("%s. thread id:%d. 已经不存在")179 }180 this.threadMap.Delete(threadID)181}182// 获取链接183func (this *MySQLPool) Get() (*client.Conn, error) {184 // 先从chan中获取资源185 select {186 case conn, ok := <-this.connChan:187 if ok {188 return conn, nil189 }190 default:191 }192 this.Lock()193 // 等待获取资源194 if this.NumOpen() >= this.maxOpen {195 this.Unlock()196 conn := <-this.connChan197 return conn, nil198 }199 // 新键资源200 this.incrNumOpen() // 添加已经使用资源201 // 新键链接202 conn, err := client.Connect(this.cfg.addr(), this.cfg.Username, this.cfg.Password, this.cfg.DBName)203 if err != nil {204 this.Unlock()205 this.decrNumOpen() // 链接没有成功删除已经使用资源206 return nil, fmt.Errorf("链接数据库出错: %s", err.Error())207 }208 // 设置链接开始使用时间戳209 this.threadMap.Store(conn.GetConnectionID(), time.Now().Unix())210 // 链接设置211 if err = conn.SetAutoCommit(this.cfg.IsAutoCommit); err != nil {212 this.closeConn(conn)213 this.Unlock()214 return nil, fmt.Errorf("(新建链接)执行 set autocommit: %t 出错. %s",215 this.cfg.IsAutoCommit, err.Error())216 }217 // 设置链接的 charset218 if err = conn.SetCharset(this.cfg.Charset); err != nil {219 this.closeConn(conn)220 this.Unlock()221 return nil, fmt.Errorf("(新建链接)执行 set names %s 出错. %s",222 this.cfg.Charset, err.Error())223 }224 this.Unlock()225 return conn, nil226}227// 归还链接228func (this *MySQLPool) Release(conn *client.Conn) error {229 this.Lock()230 if this.NumOpen() > this.maxOpen { // 关闭资源231 this.closeConn(conn)232 this.Unlock()233 return nil234 }235 this.Unlock()236 this.connChan <- conn237 return nil238}239// 获取允许最大打开数240func (this *MySQLPool) MaxOpen() int32 {241 return this.maxOpen242}243// 获取允许最小打开数244func (this *MySQLPool) MinOpen() int32 {245 return this.minOpen246}247// 当前已经打开的数量248func (this *MySQLPool) NumOpen() int32 {249 return atomic.LoadInt32(&this.numOpen)250}251// 设置最大允许的链接数252func (this *MySQLPool) SetMaxOpen(maxOpen int32) error {253 if maxOpen > MYSQL_POOL_MAX_OPEN_LIMIT {254 return fmt.Errorf("设置最大允许链接数:%d, 超过了系统限制:%d", maxOpen, MYSQL_POOL_MAX_OPEN_LIMIT)255 }256 atomic.StoreInt32(&this.maxOpen, maxOpen)257 return nil258}...

Full Screen

Full Screen

driver_test.go

Source:driver_test.go Github

copy

Full Screen

...11 _ "github.com/btcsuite/btcwallet/walletdb/bdb"12)13// dbType is the database type name for this driver.14const dbType = "bdb"15// TestCreateOpenFail ensures that errors related to creating and opening a16// database are handled properly.17func TestCreateOpenFail(t *testing.T) {18 // Ensure that attempting to open a database that doesn't exist returns19 // the expected error.20 wantErr := walletdb.ErrDbDoesNotExist21 if _, err := walletdb.Open(dbType, "noexist.db"); err != wantErr {22 t.Errorf("Open: did not receive expected error - got %v, "+23 "want %v", err, wantErr)24 return25 }26 // Ensure that attempting to open a database with the wrong number of27 // parameters returns the expected error.28 wantErr = fmt.Errorf("invalid arguments to %s.Open -- expected "+29 "database path", dbType)30 if _, err := walletdb.Open(dbType, 1, 2, 3); err.Error() != wantErr.Error() {31 t.Errorf("Open: did not receive expected error - got %v, "+32 "want %v", err, wantErr)33 return34 }35 // Ensure that attempting to open a database with an invalid type for36 // the first parameter returns the expected error.37 wantErr = fmt.Errorf("first argument to %s.Open is invalid -- "+38 "expected database path string", dbType)39 if _, err := walletdb.Open(dbType, 1); err.Error() != wantErr.Error() {40 t.Errorf("Open: did not receive expected error - got %v, "+41 "want %v", err, wantErr)42 return43 }44 // Ensure that attempting to create a database with the wrong number of45 // parameters returns the expected error.46 wantErr = fmt.Errorf("invalid arguments to %s.Create -- expected "+47 "database path", dbType)48 if _, err := walletdb.Create(dbType, 1, 2, 3); err.Error() != wantErr.Error() {49 t.Errorf("Create: did not receive expected error - got %v, "+50 "want %v", err, wantErr)51 return52 }53 // Ensure that attempting to open a database with an invalid type for54 // the first parameter returns the expected error.55 wantErr = fmt.Errorf("first argument to %s.Create is invalid -- "+56 "expected database path string", dbType)57 if _, err := walletdb.Create(dbType, 1); err.Error() != wantErr.Error() {58 t.Errorf("Create: did not receive expected error - got %v, "+59 "want %v", err, wantErr)60 return61 }62 // Ensure operations against a closed database return the expected63 // error.64 dbPath := "createfail.db"65 db, err := walletdb.Create(dbType, dbPath)66 if err != nil {67 t.Errorf("Create: unexpected error: %v", err)68 return69 }70 defer os.Remove(dbPath)71 db.Close()72 wantErr = walletdb.ErrDbNotOpen73 if _, err := db.BeginReadTx(); err != wantErr {74 t.Errorf("Namespace: did not receive expected error - got %v, "+75 "want %v", err, wantErr)76 return77 }78}79// TestPersistence ensures that values stored are still valid after closing and80// reopening the database.81func TestPersistence(t *testing.T) {82 // Create a new database to run tests against.83 dbPath := "persistencetest.db"84 db, err := walletdb.Create(dbType, dbPath)85 if err != nil {86 t.Errorf("Failed to create test database (%s) %v", dbType, err)87 return88 }89 defer os.Remove(dbPath)90 defer db.Close()91 // Create a namespace and put some values into it so they can be tested92 // for existence on re-open.93 storeValues := map[string]string{94 "ns1key1": "foo1",95 "ns1key2": "foo2",96 "ns1key3": "foo3",97 }98 ns1Key := []byte("ns1")99 err = walletdb.Update(db, func(tx walletdb.ReadWriteTx) error {100 ns1, err := tx.CreateTopLevelBucket(ns1Key)101 if err != nil {102 return err103 }104 for k, v := range storeValues {105 if err := ns1.Put([]byte(k), []byte(v)); err != nil {106 return fmt.Errorf("Put: unexpected error: %v", err)107 }108 }109 return nil110 })111 if err != nil {112 t.Errorf("ns1 Update: unexpected error: %v", err)113 return114 }115 // Close and reopen the database to ensure the values persist.116 db.Close()117 db, err = walletdb.Open(dbType, dbPath)118 if err != nil {119 t.Errorf("Failed to open test database (%s) %v", dbType, err)120 return121 }122 defer db.Close()123 // Ensure the values previously stored in the 3rd namespace still exist124 // and are correct.125 err = walletdb.View(db, func(tx walletdb.ReadTx) error {126 ns1 := tx.ReadBucket(ns1Key)127 if ns1 == nil {128 return fmt.Errorf("ReadTx.ReadBucket: unexpected nil root bucket")129 }130 for k, v := range storeValues {131 gotVal := ns1.Get([]byte(k))...

Full Screen

Full Screen

db_test.go

Source:db_test.go Github

copy

Full Screen

...38 // they are invoked.39 driver := walletdb.Driver{40 DbType: dbType,41 Create: bogusCreateDB,42 Open: bogusCreateDB,43 }44 err := walletdb.RegisterDriver(driver)45 if err != walletdb.ErrDbTypeRegistered {46 t.Errorf("unexpected duplicate driver registration error - "+47 "got %v, want %v", err, walletdb.ErrDbTypeRegistered)48 }49 dbPath := "dupdrivertest.db"50 db, err := walletdb.Create(dbType, dbPath)51 if err != nil {52 t.Errorf("failed to create database: %v", err)53 return54 }55 db.Close()56 _ = os.Remove(dbPath)57}58// TestCreateOpenFail ensures that errors which occur while opening or closing59// a database are handled properly.60func TestCreateOpenFail(t *testing.T) {61 // bogusCreateDB is a function which acts as a bogus create and open62 // driver function that intentionally returns a failure which can be63 // detected.64 dbType := "createopenfail"65 openError := fmt.Errorf("failed to create or open database for "+66 "database type [%v]", dbType)67 bogusCreateDB := func(args ...interface{}) (walletdb.DB, error) {68 return nil, openError69 }70 // Create and add driver that intentionally fails when created or opened71 // to ensure errors on database open and create are handled properly.72 driver := walletdb.Driver{73 DbType: dbType,74 Create: bogusCreateDB,75 Open: bogusCreateDB,76 }77 walletdb.RegisterDriver(driver)78 // Ensure creating a database with the new type fails with the expected79 // error.80 _, err := walletdb.Create(dbType)81 if err != openError {82 t.Errorf("expected error not received - got: %v, want %v", err,83 openError)84 return85 }86 // Ensure opening a database with the new type fails with the expected87 // error.88 _, err = walletdb.Open(dbType)89 if err != openError {90 t.Errorf("expected error not received - got: %v, want %v", err,91 openError)92 return93 }94}95// TestCreateOpenUnsupported ensures that attempting to create or open an96// unsupported database type is handled properly.97func TestCreateOpenUnsupported(t *testing.T) {98 // Ensure creating a database with an unsupported type fails with the99 // expected error.100 dbType := "unsupported"101 _, err := walletdb.Create(dbType)102 if err != walletdb.ErrDbUnknownType {103 t.Errorf("expected error not received - got: %v, want %v", err,104 walletdb.ErrDbUnknownType)105 return106 }107 // Ensure opening a database with the an unsupported type fails with the108 // expected error.109 _, err = walletdb.Open(dbType)110 if err != walletdb.ErrDbUnknownType {111 t.Errorf("expected error not received - got: %v, want %v", err,112 walletdb.ErrDbUnknownType)113 return114 }115}...

Full Screen

Full Screen

Open

Using AI Code Generation

copy

Full Screen

1import (2func main() {3 db, err := sql.Open("sqlite3", "./foo.db")4 if err != nil {5 panic(err)6 }7 defer db.Close()8 fmt.Println("Connection Established")9}10import (11func main() {12 db, err := sql.Open("sqlite3", "./foo.db")13 if err != nil {14 panic(err)15 }16 defer db.Close()17 create table foo (id integer not null primary key, name text);18 delete from foo;19 _, err = db.Exec(sqlStmt)20 if err != nil {21 panic(err)22 }23 fmt.Println("Table created")24}25import (26func main() {27 db, err := sql.Open("sqlite3", "./foo.db")28 if err != nil {29 panic(err)30 }31 defer db.Close()32 tx, err := db.Begin()33 if err != nil {34 panic(err)35 }36 stmt, err := tx.Prepare("insert into foo(id, name) values(?, ?)")37 if err != nil {38 panic(err)39 }40 defer stmt.Close()41 for i := 0; i < 10; i++ {42 _, err = stmt.Exec(i, fmt.Sprintf("Hi %d", i))43 if err != nil {44 panic(err)45 }46 }47 tx.Commit()48 fmt.Println("Data inserted")49}

Full Screen

Full Screen

Open

Using AI Code Generation

copy

Full Screen

1import (2func main() {3 db, err := sql.Open("sqlite3", "./foo.db")4 if err != nil {5 fmt.Println(err)6 }7 fmt.Println("Successfully Connected to Database")8 defer db.Close()9}10import (11func main() {12 db, err := sql.Open("sqlite3", "./foo.db")13 if err != nil {14 fmt.Println(err)15 }16 fmt.Println("Successfully Connected to Database")17 defer db.Close()18 createTable := `CREATE TABLE IF NOT EXISTS employee (19 );`20 statement, err := db.Prepare(createTable)21 if err != nil {22 fmt.Println(err)23 }24 statement.Exec()25 fmt.Println("Successfully Created Table")26}27import (28func main() {29 db, err := sql.Open("sqlite3", "./foo.db")30 if err != nil {31 fmt.Println(err)32 }33 fmt.Println("Successfully Connected to Database")34 defer db.Close()35 createTable := `CREATE TABLE IF NOT EXISTS employee (36 );`37 statement, err := db.Prepare(createTable)38 if err != nil {39 fmt.Println(err)40 }41 statement.Exec()42 fmt.Println("Successfully Created Table")43 insert, err := db.Query("INSERT INTO employee (first_name, last_name, age) VALUES ('John', 'Doe', 25)")44 if err != nil {45 fmt.Println(err)46 }47 defer insert.Close()48 fmt.Println("

Full Screen

Full Screen

Open

Using AI Code Generation

copy

Full Screen

1import (2func main() {3 db, err := sql.Open("sqlite3", "./foo.db")4 if err != nil {5 panic(err)6 }7 defer db.Close()8 fmt.Println("Opened database successfully")9}10import (11func main() {12 db, err := sql.Open("sqlite3", "./foo.db")13 if err != nil {14 panic(err)15 }16 defer db.Close()17 create table foo (id integer not null primary key, name text);18 delete from foo;19 _, err = db.Exec(sqlStmt)20 if err != nil {21 panic(err)22 }23 fmt.Println("Table created successfully")24}25import (26func main() {27 db, err := sql.Open("sqlite3", "./foo.db")28 if err != nil {29 panic(err)30 }31 defer db.Close()32 tx, err := db.Begin()33 if err != nil {34 panic(err)35 }36 stmt, err := tx.Prepare("insert into foo(id, name) values(?, ?)")37 if err != nil {38 panic(err)39 }40 defer stmt.Close()41 for i := 0; i < 10; i++ {42 _, err = stmt.Exec(i, fmt.Sprintf("Name %d", i))43 if err != nil {44 panic(err)45 }46 }47 tx.Commit()48 fmt.Println("Inserted data successfully")49}50import (

Full Screen

Full Screen

Open

Using AI Code Generation

copy

Full Screen

1import (2func main() {3 db, err := sql.Open("sqlite3", "./foo.db")4 if err != nil {5 fmt.Println(err)6 }7 defer db.Close()8 create table foo (id integer not null primary key, name text);9 delete from foo;10 _, err = db.Exec(sqlStmt)11 if err != nil {12 fmt.Printf("%q: %s13 }14 tx, err := db.Begin()15 if err != nil {16 fmt.Println(err)17 }18 stmt, err := tx.Prepare("insert into foo(id, name) values(?, ?)")19 if err != nil {20 fmt.Println(err)21 }22 defer stmt.Close()23 for i := 0; i < 10; i++ {24 _, err = stmt.Exec(i, fmt.Sprintf("astaxie%d", i))25 if err != nil {26 fmt.Println(err)27 }28 }29 tx.Commit()30 rows, err := db.Query("select id, name from foo")31 if err != nil {32 fmt.Println(err)33 }34 defer rows.Close()35 for rows.Next() {36 err = rows.Scan(&id, &name)37 if err != nil {38 fmt.Println(err)39 }40 fmt.Println(id)41 fmt.Println(name)42 }43 err = rows.Err()44 if err != nil {45 fmt.Println(err)46 }47}48import (

Full Screen

Full Screen

Automation Testing Tutorials

Learn to execute automation testing from scratch with LambdaTest Learning Hub. Right from setting up the prerequisites to run your first automation test, to following best practices and diving deeper into advanced test scenarios. LambdaTest Learning Hubs compile a list of step-by-step guides to help you be proficient with different test automation frameworks i.e. Selenium, Cypress, TestNG etc.

LambdaTest Learning Hubs:

YouTube

You could also refer to video tutorials over LambdaTest YouTube channel to get step by step demonstration from industry experts.

Try LambdaTest Now !!

Get 100 minutes of automation test minutes FREE!!

Next-Gen App & Browser Testing Cloud

Was this article helpful?

Helpful

NotHelpful