2019-02-02 16:18:25 +08:00
|
|
|
|
// Copyright 2017 gf Author(https://github.com/gogf/gf). All Rights Reserved.
|
2017-12-29 16:03:30 +08:00
|
|
|
|
//
|
|
|
|
|
|
// This Source Code Form is subject to the terms of the MIT License.
|
|
|
|
|
|
// If a copy of the MIT was not distributed with this file,
|
2019-02-02 16:18:25 +08:00
|
|
|
|
// You can obtain one at https://github.com/gogf/gf.
|
2017-12-29 16:03:30 +08:00
|
|
|
|
|
2017-11-23 10:21:28 +08:00
|
|
|
|
package gdb
|
|
|
|
|
|
|
|
|
|
|
|
import (
|
2019-06-19 09:06:52 +08:00
|
|
|
|
"database/sql"
|
|
|
|
|
|
"fmt"
|
|
|
|
|
|
"regexp"
|
2017-11-23 10:21:28 +08:00
|
|
|
|
)
|
|
|
|
|
|
|
2018-08-08 20:09:52 +08:00
|
|
|
|
// PostgreSQL的适配.
|
|
|
|
|
|
// 使用时需要import:
|
2019-02-02 16:18:25 +08:00
|
|
|
|
// _ "github.com/gogf/gf/third/github.com/lib/pq"
|
2017-11-23 10:21:28 +08:00
|
|
|
|
// @todo 需要完善replace和save的操作覆盖
|
|
|
|
|
|
|
|
|
|
|
|
// 数据库链接对象
|
2018-12-14 18:35:51 +08:00
|
|
|
|
type dbPgsql struct {
|
2019-06-19 09:06:52 +08:00
|
|
|
|
*dbBase
|
2017-11-23 10:21:28 +08:00
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
|
|
// 创建SQL操作对象,内部采用了lazy link处理
|
2019-06-19 09:06:52 +08:00
|
|
|
|
func (db *dbPgsql) Open(config *ConfigNode) (*sql.DB, error) {
|
|
|
|
|
|
var source string
|
|
|
|
|
|
if config.LinkInfo != "" {
|
|
|
|
|
|
source = config.LinkInfo
|
|
|
|
|
|
} else {
|
|
|
|
|
|
source = fmt.Sprintf("user=%s password=%s host=%s port=%s dbname=%s", config.User, config.Pass, config.Host, config.Port, config.Name)
|
|
|
|
|
|
}
|
|
|
|
|
|
if db, err := sql.Open("postgres", source); err == nil {
|
|
|
|
|
|
return db, nil
|
|
|
|
|
|
} else {
|
|
|
|
|
|
return nil, err
|
|
|
|
|
|
}
|
2017-11-23 10:21:28 +08:00
|
|
|
|
}
|
|
|
|
|
|
|
2018-12-14 18:35:51 +08:00
|
|
|
|
// 获得关键字操作符
|
2019-06-19 09:06:52 +08:00
|
|
|
|
func (db *dbPgsql) getChars() (charLeft string, charRight string) {
|
|
|
|
|
|
return "\"", "\""
|
2017-11-23 10:21:28 +08:00
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
|
|
// 在执行sql之前对sql进行进一步处理
|
2018-12-14 18:35:51 +08:00
|
|
|
|
func (db *dbPgsql) handleSqlBeforeExec(query string) string {
|
2019-06-19 09:06:52 +08:00
|
|
|
|
reg := regexp.MustCompile("\\?")
|
|
|
|
|
|
index := 0
|
|
|
|
|
|
str := reg.ReplaceAllStringFunc(query, func(s string) string {
|
|
|
|
|
|
index++
|
|
|
|
|
|
return fmt.Sprintf("$%d", index)
|
|
|
|
|
|
})
|
|
|
|
|
|
return str
|
|
|
|
|
|
}
|