2017-12-29 16:03:30 +08:00
|
|
|
|
// Copyright 2017 gf Author(https://gitee.com/johng/gf). All Rights Reserved.
|
|
|
|
|
|
//
|
|
|
|
|
|
// 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,
|
|
|
|
|
|
// You can obtain one at https://gitee.com/johng/gf.
|
|
|
|
|
|
|
2017-12-31 18:19:58 +08:00
|
|
|
|
|
2017-11-23 10:21:28 +08:00
|
|
|
|
package gdb
|
|
|
|
|
|
|
|
|
|
|
|
import (
|
|
|
|
|
|
"fmt"
|
|
|
|
|
|
"regexp"
|
2018-03-09 17:55:42 +08:00
|
|
|
|
"database/sql"
|
2017-11-23 10:21:28 +08:00
|
|
|
|
)
|
|
|
|
|
|
|
|
|
|
|
|
// postgresql的适配
|
|
|
|
|
|
// @todo 需要完善replace和save的操作覆盖
|
|
|
|
|
|
|
|
|
|
|
|
// 数据库链接对象
|
2018-03-09 17:55:42 +08:00
|
|
|
|
type dbpgsql struct {
|
|
|
|
|
|
Db
|
2017-11-23 10:21:28 +08:00
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
|
|
// 创建SQL操作对象,内部采用了lazy link处理
|
2018-03-09 17:55:42 +08:00
|
|
|
|
func (db *dbpgsql) Open (c *ConfigNode) (*sql.DB, error) {
|
2018-04-27 11:38:26 +08:00
|
|
|
|
var source string
|
2017-11-23 10:21:28 +08:00
|
|
|
|
if c.Linkinfo != "" {
|
2018-04-27 11:38:26 +08:00
|
|
|
|
source = c.Linkinfo
|
2017-11-23 10:21:28 +08:00
|
|
|
|
} else {
|
2018-04-27 11:38:26 +08:00
|
|
|
|
source = fmt.Sprintf("user=%s password=%s host=%s port=%s dbname=%s", c.User, c.Pass, c.Host, c.Port, c.Name)
|
2017-11-23 10:21:28 +08:00
|
|
|
|
}
|
2018-04-27 11:38:26 +08:00
|
|
|
|
if db, err := sql.Open("postgres", source); err == nil {
|
2018-03-09 17:55:42 +08:00
|
|
|
|
return db, nil
|
|
|
|
|
|
} else {
|
|
|
|
|
|
return nil, err
|
2017-11-23 10:21:28 +08:00
|
|
|
|
}
|
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
|
|
// 获得关键字操作符 - 左
|
2018-03-09 17:55:42 +08:00
|
|
|
|
func (db *dbpgsql) getQuoteCharLeft () string {
|
2017-11-23 10:21:28 +08:00
|
|
|
|
return "\""
|
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
|
|
// 获得关键字操作符 - 右
|
2018-03-09 17:55:42 +08:00
|
|
|
|
func (db *dbpgsql) getQuoteCharRight () string {
|
2017-11-23 10:21:28 +08:00
|
|
|
|
return "\""
|
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
|
|
// 在执行sql之前对sql进行进一步处理
|
2018-03-09 17:55:42 +08:00
|
|
|
|
func (db *dbpgsql) handleSqlBeforeExec(q *string) *string {
|
2017-11-23 10:21:28 +08:00
|
|
|
|
reg := regexp.MustCompile("\\?")
|
|
|
|
|
|
index := 0
|
|
|
|
|
|
str := reg.ReplaceAllStringFunc(*q, func (s string) string {
|
|
|
|
|
|
index ++
|
|
|
|
|
|
return fmt.Sprintf("$%d", index)
|
|
|
|
|
|
})
|
|
|
|
|
|
return &str
|
|
|
|
|
|
}
|
|
|
|
|
|
|