-
-
Notifications
You must be signed in to change notification settings - Fork 1.6k
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
feat(contrib/drivers/gaussdb): add gaussdb driver support #3925
Open
okyer
wants to merge
2
commits into
gogf:master
Choose a base branch
from
okyer:master
base: master
Could not load branches
Branch not found: {{ refName }}
Loading
Could not load tags
Nothing to show
Loading
Are you sure you want to change the base?
Some commits from the old base branch may be removed from the timeline,
and old review comments may become outdated.
Open
Changes from all commits
Commits
Show all changes
2 commits
Select commit
Hold shift + click to select a range
File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,54 @@ | ||
// Copyright GoFrame Author(https://goframe.org). 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://github.com/gogf/gf. | ||
|
||
// Package gaussdb implements gdb.Driver, which supports operations for database PostgreSQL. | ||
// | ||
// Note: | ||
// 1. It does not support Replace features. | ||
// 2. It does not support Insert Ignore features. | ||
package gaussdb | ||
|
||
import ( | ||
_ "gitee.com/opengauss/openGauss-connector-go-pq" | ||
|
||
"github.com/gogf/gf/v2/database/gdb" | ||
"github.com/gogf/gf/v2/os/gctx" | ||
) | ||
|
||
// Driver is the driver for postgresql database. | ||
type Driver struct { | ||
*gdb.Core | ||
} | ||
|
||
const ( | ||
internalPrimaryKeyInCtx gctx.StrKey = "primary_key" | ||
defaultSchema string = "public" | ||
quoteChar string = `"` | ||
) | ||
|
||
func init() { | ||
if err := gdb.Register(`gaussdb`, New()); err != nil { | ||
panic(err) | ||
} | ||
} | ||
|
||
// New create and returns a driver that implements gdb.Driver, which supports operations for PostgreSql. | ||
func New() gdb.Driver { | ||
return &Driver{} | ||
} | ||
|
||
// New creates and returns a database object for postgresql. | ||
// It implements the interface of gdb.Driver for extra database driver installation. | ||
func (d *Driver) New(core *gdb.Core, node *gdb.ConfigNode) (gdb.DB, error) { | ||
return &Driver{ | ||
Core: core, | ||
}, nil | ||
} | ||
|
||
// GetChars returns the security char for this type of database. | ||
func (d *Driver) GetChars() (charLeft string, charRight string) { | ||
return quoteChar, quoteChar | ||
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,122 @@ | ||
// Copyright GoFrame Author(https://goframe.org). 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://github.com/gogf/gf. | ||
|
||
package gaussdb | ||
|
||
import ( | ||
"context" | ||
"reflect" | ||
"strings" | ||
|
||
"github.com/gogf/gf/v2/database/gdb" | ||
"github.com/gogf/gf/v2/frame/g" | ||
"github.com/gogf/gf/v2/text/gregex" | ||
"github.com/gogf/gf/v2/text/gstr" | ||
"github.com/gogf/gf/v2/util/gconv" | ||
) | ||
|
||
// ConvertValueForField converts value to database acceptable value. | ||
func (d *Driver) ConvertValueForField(ctx context.Context, fieldType string, fieldValue interface{}) (interface{}, error) { | ||
if g.IsNil(fieldValue) { | ||
return d.Core.ConvertValueForField(ctx, fieldType, fieldValue) | ||
} | ||
|
||
var fieldValueKind = reflect.TypeOf(fieldValue).Kind() | ||
|
||
if fieldValueKind == reflect.Slice { | ||
// For gaussdb, json or jsonb require '[]' | ||
if !gstr.Contains(fieldType, "json") { | ||
fieldValue = gstr.ReplaceByMap(gconv.String(fieldValue), | ||
map[string]string{ | ||
"[": "{", | ||
"]": "}", | ||
}, | ||
) | ||
} | ||
} | ||
return d.Core.ConvertValueForField(ctx, fieldType, fieldValue) | ||
} | ||
|
||
// CheckLocalTypeForField checks and returns corresponding local golang type for given db type. | ||
func (d *Driver) CheckLocalTypeForField(ctx context.Context, fieldType string, fieldValue interface{}) (gdb.LocalType, error) { | ||
var typeName string | ||
match, _ := gregex.MatchString(`(.+?)\((.+)\)`, fieldType) | ||
if len(match) == 3 { | ||
typeName = gstr.Trim(match[1]) | ||
} else { | ||
typeName = fieldType | ||
} | ||
typeName = strings.ToLower(typeName) | ||
switch typeName { | ||
case | ||
// For gaussdb, int2 = smallint. | ||
"int2", | ||
// For gaussdb, int4 = integer | ||
"int4": | ||
return gdb.LocalTypeInt, nil | ||
|
||
case | ||
// For gaussdb, int8 = bigint | ||
"int8": | ||
return gdb.LocalTypeInt64, nil | ||
|
||
case | ||
"_int2", | ||
"_int4": | ||
return gdb.LocalTypeIntSlice, nil | ||
|
||
case | ||
"_int8": | ||
return gdb.LocalTypeInt64Slice, nil | ||
|
||
default: | ||
return d.Core.CheckLocalTypeForField(ctx, fieldType, fieldValue) | ||
} | ||
} | ||
|
||
// ConvertValueForLocal converts value to local Golang type of value according field type name from database. | ||
// The parameter `fieldType` is in lower case, like: | ||
// `float(5,2)`, `unsigned double(5,2)`, `decimal(10,2)`, `char(45)`, `varchar(100)`, etc. | ||
func (d *Driver) ConvertValueForLocal(ctx context.Context, fieldType string, fieldValue interface{}) (interface{}, error) { | ||
typeName, _ := gregex.ReplaceString(`\(.+\)`, "", fieldType) | ||
typeName = strings.ToLower(typeName) | ||
switch typeName { | ||
// For gaussdb, int2 = smallint and int4 = integer. | ||
case "int2", "int4": | ||
return gconv.Int(gconv.String(fieldValue)), nil | ||
|
||
// For gaussdb, int8 = bigint. | ||
case "int8": | ||
return gconv.Int64(gconv.String(fieldValue)), nil | ||
|
||
// Int32 slice. | ||
case | ||
"_int2", "_int4": | ||
return gconv.Ints( | ||
gstr.ReplaceByMap(gconv.String(fieldValue), | ||
map[string]string{ | ||
"{": "[", | ||
"}": "]", | ||
}, | ||
), | ||
), nil | ||
|
||
// Int64 slice. | ||
case | ||
"_int8": | ||
return gconv.Int64s( | ||
gstr.ReplaceByMap(gconv.String(fieldValue), | ||
map[string]string{ | ||
"{": "[", | ||
"}": "]", | ||
}, | ||
), | ||
), nil | ||
|
||
default: | ||
return d.Core.ConvertValueForLocal(ctx, fieldType, fieldValue) | ||
} | ||
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,116 @@ | ||
// Copyright GoFrame Author(https://goframe.org). 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://github.com/gogf/gf. | ||
|
||
package gaussdb | ||
|
||
import ( | ||
"context" | ||
"database/sql" | ||
"fmt" | ||
"strings" | ||
|
||
"github.com/gogf/gf/v2/database/gdb" | ||
"github.com/gogf/gf/v2/errors/gcode" | ||
"github.com/gogf/gf/v2/errors/gerror" | ||
) | ||
|
||
// DoExec commits the sql string and its arguments to underlying driver | ||
// through given link object and returns the execution result. | ||
func (d *Driver) DoExec(ctx context.Context, link gdb.Link, sql string, args ...interface{}) (result sql.Result, err error) { | ||
var ( | ||
isUseCoreDoExec bool = false // Check whether the default method needs to be used | ||
primaryKey string = "" | ||
pkField gdb.TableField | ||
) | ||
|
||
// Transaction checks. | ||
if link == nil { | ||
if tx := gdb.TXFromCtx(ctx, d.GetGroup()); tx != nil { | ||
// Firstly, check and retrieve transaction link from context. | ||
link = tx | ||
} else if link, err = d.MasterLink(); err != nil { | ||
// Or else it creates one from master node. | ||
return nil, err | ||
} | ||
} else if !link.IsTransaction() { | ||
// If current link is not transaction link, it checks and retrieves transaction from context. | ||
if tx := gdb.TXFromCtx(ctx, d.GetGroup()); tx != nil { | ||
link = tx | ||
} | ||
} | ||
|
||
// Check if it is an insert operation with primary key. | ||
if value := ctx.Value(internalPrimaryKeyInCtx); value != nil { | ||
var ok bool | ||
pkField, ok = value.(gdb.TableField) | ||
if !ok { | ||
isUseCoreDoExec = true | ||
} | ||
} else { | ||
isUseCoreDoExec = true | ||
} | ||
|
||
// check if it is an insert operation. | ||
if !isUseCoreDoExec && pkField.Name != "" && strings.Contains(sql, "INSERT INTO") { | ||
primaryKey = pkField.Name | ||
sql += fmt.Sprintf(` RETURNING "%s"`, primaryKey) | ||
} else { | ||
// use default DoExec | ||
return d.Core.DoExec(ctx, link, sql, args...) | ||
} | ||
|
||
// Only the insert operation with primary key can execute the following code | ||
|
||
if d.GetConfig().ExecTimeout > 0 { | ||
var cancelFunc context.CancelFunc | ||
ctx, cancelFunc = context.WithTimeout(ctx, d.GetConfig().ExecTimeout) | ||
defer cancelFunc() | ||
} | ||
|
||
// Sql filtering. | ||
sql, args = d.FormatSqlBeforeExecuting(sql, args) | ||
sql, args, err = d.DoFilter(ctx, link, sql, args) | ||
if err != nil { | ||
return nil, err | ||
} | ||
|
||
// Link execution. | ||
var out gdb.DoCommitOutput | ||
out, err = d.DoCommit(ctx, gdb.DoCommitInput{ | ||
Link: link, | ||
Sql: sql, | ||
Args: args, | ||
Stmt: nil, | ||
Type: gdb.SqlTypeQueryContext, | ||
IsTransaction: link.IsTransaction(), | ||
}) | ||
|
||
if err != nil { | ||
return nil, err | ||
} | ||
affected := len(out.Records) | ||
if affected > 0 { | ||
if !strings.Contains(pkField.Type, "int") { | ||
return Result{ | ||
affected: int64(affected), | ||
lastInsertId: 0, | ||
lastInsertIdError: gerror.NewCodef( | ||
gcode.CodeNotSupported, | ||
"LastInsertId is not supported by primary key type: %s", pkField.Type), | ||
}, nil | ||
} | ||
|
||
if out.Records[affected-1][primaryKey] != nil { | ||
lastInsertId := out.Records[affected-1][primaryKey].Int64() | ||
return Result{ | ||
affected: int64(affected), | ||
lastInsertId: lastInsertId, | ||
}, nil | ||
} | ||
} | ||
|
||
return Result{}, nil | ||
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,58 @@ | ||
// Copyright GoFrame Author(https://goframe.org). 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://github.com/gogf/gf. | ||
|
||
package gaussdb | ||
|
||
import ( | ||
"context" | ||
"fmt" | ||
|
||
"github.com/gogf/gf/v2/database/gdb" | ||
"github.com/gogf/gf/v2/text/gregex" | ||
"github.com/gogf/gf/v2/text/gstr" | ||
) | ||
|
||
// DoFilter deals with the sql string before commits it to underlying sql driver. | ||
func (d *Driver) DoFilter( | ||
ctx context.Context, link gdb.Link, sql string, args []interface{}, | ||
) (newSql string, newArgs []interface{}, err error) { | ||
var index int | ||
// Convert placeholder char '?' to string "$x". | ||
newSql, err = gregex.ReplaceStringFunc(`\?`, sql, func(s string) string { | ||
index++ | ||
return fmt.Sprintf(`$%d`, index) | ||
}) | ||
if err != nil { | ||
return "", nil, err | ||
} | ||
// Handle gaussdb jsonb feature support, which contains place-holder char '?'. | ||
// Refer: | ||
// https://github.com/gogf/gf/issues/1537 | ||
// https://www.postgresql.org/docs/12/functions-json.html | ||
newSql, err = gregex.ReplaceStringFuncMatch( | ||
`(::jsonb([^\w\d]*)\$\d)`, | ||
newSql, | ||
func(match []string) string { | ||
return fmt.Sprintf(`::jsonb%s?`, match[2]) | ||
}, | ||
) | ||
if err != nil { | ||
return "", nil, err | ||
} | ||
newSql, err = gregex.ReplaceString(` LIMIT (\d+),\s*(\d+)`, ` LIMIT $2 OFFSET $1`, newSql) | ||
if err != nil { | ||
return "", nil, err | ||
} | ||
|
||
// Add support for gaussdb INSERT. | ||
if gstr.HasPrefix(newSql, gdb.InsertOperationIgnore) { | ||
newSql = "INSERT" + newSql[len(gdb.InsertOperationIgnore):] | ||
} | ||
|
||
newArgs = args | ||
|
||
return d.Core.DoFilter(ctx, link, newSql, newArgs) | ||
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,40 @@ | ||
// Copyright GoFrame Author(https://goframe.org). 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://github.com/gogf/gf. | ||
|
||
package gaussdb | ||
|
||
import ( | ||
"context" | ||
"database/sql" | ||
|
||
"github.com/gogf/gf/v2/database/gdb" | ||
"github.com/gogf/gf/v2/errors/gcode" | ||
"github.com/gogf/gf/v2/errors/gerror" | ||
) | ||
|
||
// DoInsert inserts or updates data for given table. | ||
func (d *Driver) DoInsert(ctx context.Context, link gdb.Link, table string, list gdb.List, option gdb.DoInsertOption) (result sql.Result, err error) { | ||
switch option.InsertOption { | ||
case gdb.InsertOptionReplace: | ||
return nil, gerror.NewCode( | ||
gcode.CodeNotSupported, | ||
`Replace operation is not supported by gaussdb driver`, | ||
) | ||
|
||
case gdb.InsertOptionDefault: | ||
tableFields, err := d.GetCore().GetDB().TableFields(ctx, table) | ||
if err == nil { | ||
for _, field := range tableFields { | ||
if field.Key == "pri" { | ||
pkField := *field | ||
ctx = context.WithValue(ctx, internalPrimaryKeyInCtx, pkField) | ||
break | ||
} | ||
} | ||
} | ||
} | ||
return d.Core.DoInsert(ctx, link, table, list, option) | ||
} |
Oops, something went wrong.
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
@okyer Hello, I see the CI of this PR failed, as the docker service is missing for unit testing cases of gaussdb. You can add your gaussdb docker service in CI yaml here https://github.com/gogf/gf/blob/master/.github/workflows/ci-main.yml . You can refer to the existing docker service in CI yaml.