github.com/zhongdalu/gf@v1.0.0/g/database/gdb/gdb_pgsql.go (about) 1 // Copyright 2017 gf Author(https://github.com/zhongdalu/gf). All Rights Reserved. 2 // 3 // This Source Code Form is subject to the terms of the MIT License. 4 // If a copy of the MIT was not distributed with this file, 5 // You can obtain one at https://github.com/zhongdalu/gf. 6 7 package gdb 8 9 import ( 10 "database/sql" 11 "fmt" 12 13 "github.com/zhongdalu/gf/g/text/gregex" 14 ) 15 16 // PostgreSQL的适配. 17 // 18 // 使用时需要import: 19 // 20 // _ "github.com/zhongdalu/gf/third/github.com/lib/pq" 21 // 22 // @todo 需要完善replace和save的操作覆盖 23 24 // 数据库链接对象 25 type dbPgsql struct { 26 *dbBase 27 } 28 29 // 创建SQL操作对象,内部采用了lazy link处理 30 func (db *dbPgsql) Open(config *ConfigNode) (*sql.DB, error) { 31 var source string 32 if config.LinkInfo != "" { 33 source = config.LinkInfo 34 } else { 35 source = fmt.Sprintf("user=%s password=%s host=%s port=%s dbname=%s", config.User, config.Pass, config.Host, config.Port, config.Name) 36 } 37 if db, err := sql.Open("postgres", source); err == nil { 38 return db, nil 39 } else { 40 return nil, err 41 } 42 } 43 44 // 动态切换数据库 45 func (db *dbPgsql) setSchema(sqlDb *sql.DB, schema string) error { 46 _, err := sqlDb.Exec("SET search_path TO " + schema) 47 return err 48 } 49 50 // 获得关键字操作符 51 func (db *dbPgsql) getChars() (charLeft string, charRight string) { 52 return "\"", "\"" 53 } 54 55 // 在执行sql之前对sql进行进一步处理 56 func (db *dbPgsql) handleSqlBeforeExec(query string) string { 57 index := 0 58 query, _ = gregex.ReplaceStringFunc("\\?", query, func(s string) string { 59 index++ 60 return fmt.Sprintf("$%d", index) 61 }) 62 // 分页语法替换 63 query, _ = gregex.ReplaceString(` LIMIT (\d+),\s*(\d+)`, ` LIMIT $1 OFFSET $2`, query) 64 return query 65 }