github.com/Azareal/Gosora@v0.0.0-20210729070923-553e66b59003/pgsql.go (about) 1 // +build pgsql 2 3 /* Copyright Azareal 2016 - 2020 */ 4 /* Super experimental and incomplete. DON'T USE IT YET! */ 5 package main 6 7 import ( 8 "database/sql" 9 "strings" 10 11 c "github.com/Azareal/Gosora/common" 12 qgen "github.com/Azareal/Gosora/query_gen" 13 _ "github.com/lib/pq" 14 ) 15 16 // TODO: Add support for SSL for all database drivers, not just pgsql 17 var dbSslmode = "disable" // verify-full 18 19 func init() { 20 dbAdapter = "pgsql" 21 _initDatabase = initPgsql 22 } 23 24 func initPgsql() (err error) { 25 // TODO: Investigate connect_timeout to see what it does exactly and whether it's relevant to us 26 var _dbpassword string 27 if c.DbConfig.Password != "" { 28 _dbpassword = " password='" + _escape_bit(c.DbConfig.Password) + "'" 29 } 30 // TODO: Move this bit to the query gen lib 31 db, err = sql.Open("postgres", "host='"+_escape_bit(c.DbConfig.Host)+"' port='"+_escape_bit(c.DbConfig.Port)+"' user='"+_escape_bit(c.DbConfig.Username)+"' dbname='"+_escape_bit(c.DbConfig.Dbname)+"'"+_dbpassword+" sslmode='"+dbSslmode+"'") 32 if err != nil { 33 return err 34 } 35 36 // Make sure that the connection is alive 37 err = db.Ping() 38 if err != nil { 39 return err 40 } 41 42 // Set the number of max open connections. How many do we need? Might need to do some tests. 43 db.SetMaxOpenConns(64) 44 db.SetMaxIdleConns(32) 45 46 // Only hold connections open for five seconds to avoid accumulating a large number of stale connections 47 //db.SetConnMaxLifetime(5 * time.Second) 48 db.SetConnMaxLifetime(c.DBTimeout()) 49 50 err = _gen_pgsql() 51 if err != nil { 52 return err 53 } 54 55 // Ready the query builder 56 qgen.Builder.SetConn(db) 57 err = qgen.Builder.SetAdapter("pgsql") 58 if err != nil { 59 return err 60 } 61 62 // TO-DO Handle the queries which the query generator can't handle yet 63 64 return nil 65 } 66 67 func _escape_bit(bit string) string { 68 // TODO: Write a custom parser, so that backslashes work properly in the sql.Open string. Do something similar for the database driver, if possible? 69 return strings.Replace(bit, "'", "\\'", -1) 70 }