mirror of
https://gitee.com/johng/gf
synced 2026-06-08 10:37:44 +08:00
Compare commits
21 Commits
| Author | SHA1 | Date | |
|---|---|---|---|
| d64a31fd1a | |||
| 6cdf044320 | |||
| 5307f0742e | |||
| 51326f3d02 | |||
| e1fa99013a | |||
| 72014689e4 | |||
| 2acdf4bb47 | |||
| 85c5b7f19e | |||
| 42ec1a0076 | |||
| 553cc45e54 | |||
| 7415ec32c8 | |||
| 14568562e3 | |||
| cc79d23334 | |||
| ef2b47d180 | |||
| adc056f547 | |||
| 8266a16b4e | |||
| c4a51f4c2f | |||
| 4ddc9c3909 | |||
| 0a2f8abb40 | |||
| 81de5d3f25 | |||
| e6d61e6e14 |
33
.github/workflows/ci-main.yml
vendored
33
.github/workflows/ci-main.yml
vendored
@ -67,9 +67,13 @@ jobs:
|
||||
- 3306:3306
|
||||
|
||||
# PostgreSQL backend server.
|
||||
# docker run -d --name postgres -p 5432:5432 \
|
||||
# -e POSTGRES_PASSWORD=12345678 -e POSTGRES_USER=postgres -e POSTGRES_DB=test \
|
||||
# -v postgres:/Users/john/Temp/postgresql/data loads/postgres:13
|
||||
# docker run -d --name postgres \
|
||||
# -p 5432:5432 \
|
||||
# -e POSTGRES_PASSWORD=12345678 \
|
||||
# -e POSTGRES_USER=postgres \
|
||||
# -e POSTGRES_DB=test \
|
||||
# -v postgres:/Users/john/Temp/postgresql/data \
|
||||
# loads/postgres:13
|
||||
postgres:
|
||||
image: loads/postgres:13
|
||||
env:
|
||||
@ -87,7 +91,8 @@ jobs:
|
||||
--health-retries 5
|
||||
|
||||
# MSSQL backend server.
|
||||
# docker run -d --name mssql -p 1433:1433 \
|
||||
# docker run \
|
||||
# -p 1433:1433 \
|
||||
# -e ACCEPT_EULA=Y \
|
||||
# -e SA_PASSWORD=LoremIpsum86 \
|
||||
# -e MSSQL_DB=test \
|
||||
@ -123,8 +128,13 @@ jobs:
|
||||
- 9001:9001
|
||||
|
||||
# Polaris backend server.
|
||||
# docker run -d --name polaris -p 8090:8090 -p 8091:8091 -p 8093:8093 -p 9090:9090 -p 9091:9091 loads/polaris-server-standalone:1.11.2
|
||||
# docker run -d --name polaris -p 8090:8090 -p 8091:8091 -p 8093:8093 -p 9090:9090 -p 9091:9091 loads/polaris-standalone:v1.16.3
|
||||
# docker run -d --name polaris \
|
||||
# -p 8090:8090 -p 8091:8091 -p 8093:8093 -p 9090:9090 -p 9091:9091 \
|
||||
# loads/polaris-server-standalone:1.11.2
|
||||
#
|
||||
# docker run -d --name polaris \
|
||||
# -p 8090:8090 -p 8091:8091 -p 8093:8093 -p 9090:9090 -p 9091:9091 \
|
||||
# loads/polaris-standalone:v1.16.3
|
||||
polaris:
|
||||
image: loads/polaris-standalone:v1.17.2
|
||||
ports:
|
||||
@ -134,7 +144,14 @@ jobs:
|
||||
- 9090:9090
|
||||
- 9091:9091
|
||||
|
||||
# Oracle 11g server
|
||||
# Oracle 11g server.
|
||||
# docker run \
|
||||
# -e ORACLE_ALLOW_REMOTE=true \
|
||||
# -e ORACLE_SID=XE \
|
||||
# -e ORACLE_DB_USER_NAME=system \
|
||||
# -e ORACLE_DB_PASSWORD=oracle \
|
||||
# -p 1521:1521 \
|
||||
# loads/oracle-xe-11g-r2:11.2.0
|
||||
oracle-server:
|
||||
image: loads/oracle-xe-11g-r2:11.2.0
|
||||
env:
|
||||
@ -146,7 +163,7 @@ jobs:
|
||||
- 1521:1521
|
||||
|
||||
# dm8 server
|
||||
# docker run -d --name dm -p 5236:5236 loads/dm:v8.1.2.128_ent_x86_64_ctm_pack4
|
||||
# docker run -p 5236:5236 loads/dm:v8.1.2.128_ent_x86_64_ctm_pack4
|
||||
dm-server:
|
||||
image: loads/dm:v8.1.2.128_ent_x86_64_ctm_pack4
|
||||
ports:
|
||||
|
||||
2
.github/workflows/release.yml
vendored
2
.github/workflows/release.yml
vendored
@ -34,7 +34,7 @@ jobs:
|
||||
- name: Build CLI Binary For All Platform
|
||||
run: |
|
||||
cd cmd/gf
|
||||
gf build main.go -n gf -a all -s all
|
||||
gf build main.go -n gf -a all -s all -p temp
|
||||
|
||||
- name: Move Files Before Release
|
||||
run: |
|
||||
|
||||
@ -62,6 +62,7 @@ golang version >= 1.18
|
||||
# Documentation
|
||||
|
||||
- Chinese Official Site(中文官网): [https://goframe.org](https://goframe.org/display/gf)
|
||||
- Offline Document(中文离线文档): [https://github.com/gogf/goframe.org-pdf](https://github.com/gogf/goframe.org-pdf)
|
||||
- GoDoc API: [https://pkg.go.dev/github.com/gogf/gf/v2](https://pkg.go.dev/github.com/gogf/gf/v2)
|
||||
|
||||
# License
|
||||
|
||||
@ -3,13 +3,13 @@ module github.com/gogf/gf/cmd/gf/v2
|
||||
go 1.18
|
||||
|
||||
require (
|
||||
github.com/gogf/gf/contrib/drivers/clickhouse/v2 v2.6.2
|
||||
github.com/gogf/gf/contrib/drivers/mssql/v2 v2.6.2
|
||||
github.com/gogf/gf/contrib/drivers/mysql/v2 v2.6.2
|
||||
github.com/gogf/gf/contrib/drivers/oracle/v2 v2.6.2
|
||||
github.com/gogf/gf/contrib/drivers/pgsql/v2 v2.6.2
|
||||
github.com/gogf/gf/contrib/drivers/sqlite/v2 v2.6.2
|
||||
github.com/gogf/gf/v2 v2.6.2
|
||||
github.com/gogf/gf/contrib/drivers/clickhouse/v2 v2.6.3
|
||||
github.com/gogf/gf/contrib/drivers/mssql/v2 v2.6.3
|
||||
github.com/gogf/gf/contrib/drivers/mysql/v2 v2.6.3
|
||||
github.com/gogf/gf/contrib/drivers/oracle/v2 v2.6.3
|
||||
github.com/gogf/gf/contrib/drivers/pgsql/v2 v2.6.3
|
||||
github.com/gogf/gf/contrib/drivers/sqlite/v2 v2.6.3
|
||||
github.com/gogf/gf/v2 v2.6.3
|
||||
github.com/gogf/selfupdate v0.0.0-20231215043001-5c48c528462f
|
||||
github.com/olekukonko/tablewriter v0.0.5
|
||||
golang.org/x/mod v0.9.0
|
||||
|
||||
@ -12,6 +12,7 @@ import (
|
||||
"testing"
|
||||
|
||||
"github.com/gogf/gf/cmd/gf/v2/internal/cmd/gendao"
|
||||
"github.com/gogf/gf/v2/database/gdb"
|
||||
"github.com/gogf/gf/v2/os/gfile"
|
||||
"github.com/gogf/gf/v2/test/gtest"
|
||||
"github.com/gogf/gf/v2/text/gstr"
|
||||
@ -209,3 +210,186 @@ func Test_Gen_Dao_TypeMapping(t *testing.T) {
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
func execSqlFile(db gdb.DB, filePath string, args ...any) error {
|
||||
sqlContent := fmt.Sprintf(
|
||||
gfile.GetContents(filePath),
|
||||
args...,
|
||||
)
|
||||
array := gstr.SplitAndTrim(sqlContent, ";")
|
||||
for _, v := range array {
|
||||
if _, err := db.Exec(ctx, v); err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func Test_Gen_Dao_Issue2572(t *testing.T) {
|
||||
gtest.C(t, func(t *gtest.T) {
|
||||
var (
|
||||
err error
|
||||
db = testDB
|
||||
table1 = "user1"
|
||||
table2 = "user2"
|
||||
issueDirPath = gtest.DataPath(`issue`, `2572`)
|
||||
)
|
||||
t.AssertNil(execSqlFile(db, gtest.DataPath(`issue`, `2572`, `sql1.sql`)))
|
||||
t.AssertNil(execSqlFile(db, gtest.DataPath(`issue`, `2572`, `sql2.sql`)))
|
||||
defer dropTableWithDb(db, table1)
|
||||
defer dropTableWithDb(db, table2)
|
||||
|
||||
var (
|
||||
path = gfile.Temp(guid.S())
|
||||
group = "test"
|
||||
in = gendao.CGenDaoInput{
|
||||
Path: path,
|
||||
Link: link,
|
||||
Tables: "",
|
||||
TablesEx: "",
|
||||
Group: group,
|
||||
Prefix: "",
|
||||
RemovePrefix: "",
|
||||
JsonCase: "SnakeScreaming",
|
||||
ImportPrefix: "",
|
||||
DaoPath: "",
|
||||
DoPath: "",
|
||||
EntityPath: "",
|
||||
TplDaoIndexPath: "",
|
||||
TplDaoInternalPath: "",
|
||||
TplDaoDoPath: "",
|
||||
TplDaoEntityPath: "",
|
||||
StdTime: false,
|
||||
WithTime: false,
|
||||
GJsonSupport: false,
|
||||
OverwriteDao: false,
|
||||
DescriptionTag: false,
|
||||
NoJsonTag: false,
|
||||
NoModelComment: false,
|
||||
Clear: false,
|
||||
TypeMapping: nil,
|
||||
}
|
||||
)
|
||||
err = gutil.FillStructWithDefault(&in)
|
||||
t.AssertNil(err)
|
||||
|
||||
err = gfile.Copy(issueDirPath, path)
|
||||
t.AssertNil(err)
|
||||
|
||||
defer gfile.Remove(path)
|
||||
|
||||
pwd := gfile.Pwd()
|
||||
err = gfile.Chdir(path)
|
||||
t.AssertNil(err)
|
||||
|
||||
defer gfile.Chdir(pwd)
|
||||
|
||||
_, err = gendao.CGenDao{}.Dao(ctx, in)
|
||||
t.AssertNil(err)
|
||||
|
||||
generatedFiles, err := gfile.ScanDir(path, "*.go", true)
|
||||
t.AssertNil(err)
|
||||
t.Assert(len(generatedFiles), 8)
|
||||
for i, generatedFile := range generatedFiles {
|
||||
generatedFiles[i] = gstr.TrimLeftStr(generatedFile, path)
|
||||
}
|
||||
t.Assert(gstr.InArray(generatedFiles, "/dao/internal/user_1.go"), true)
|
||||
t.Assert(gstr.InArray(generatedFiles, "/dao/internal/user_2.go"), true)
|
||||
t.Assert(gstr.InArray(generatedFiles, "/dao/user_1.go"), true)
|
||||
t.Assert(gstr.InArray(generatedFiles, "/dao/user_2.go"), true)
|
||||
t.Assert(gstr.InArray(generatedFiles, "/model/do/user_1.go"), true)
|
||||
t.Assert(gstr.InArray(generatedFiles, "/model/do/user_2.go"), true)
|
||||
t.Assert(gstr.InArray(generatedFiles, "/model/entity/user_1.go"), true)
|
||||
t.Assert(gstr.InArray(generatedFiles, "/model/entity/user_2.go"), true)
|
||||
})
|
||||
}
|
||||
|
||||
func Test_Gen_Dao_Issue2616(t *testing.T) {
|
||||
gtest.C(t, func(t *gtest.T) {
|
||||
var (
|
||||
err error
|
||||
db = testDB
|
||||
table1 = "user1"
|
||||
table2 = "user2"
|
||||
issueDirPath = gtest.DataPath(`issue`, `2616`)
|
||||
)
|
||||
t.AssertNil(execSqlFile(db, gtest.DataPath(`issue`, `2616`, `sql1.sql`)))
|
||||
t.AssertNil(execSqlFile(db, gtest.DataPath(`issue`, `2616`, `sql2.sql`)))
|
||||
defer dropTableWithDb(db, table1)
|
||||
defer dropTableWithDb(db, table2)
|
||||
|
||||
var (
|
||||
path = gfile.Temp(guid.S())
|
||||
group = "test"
|
||||
in = gendao.CGenDaoInput{
|
||||
Path: path,
|
||||
Link: link,
|
||||
Tables: "",
|
||||
TablesEx: "",
|
||||
Group: group,
|
||||
Prefix: "",
|
||||
RemovePrefix: "",
|
||||
JsonCase: "SnakeScreaming",
|
||||
ImportPrefix: "",
|
||||
DaoPath: "",
|
||||
DoPath: "",
|
||||
EntityPath: "",
|
||||
TplDaoIndexPath: "",
|
||||
TplDaoInternalPath: "",
|
||||
TplDaoDoPath: "",
|
||||
TplDaoEntityPath: "",
|
||||
StdTime: false,
|
||||
WithTime: false,
|
||||
GJsonSupport: false,
|
||||
OverwriteDao: false,
|
||||
DescriptionTag: false,
|
||||
NoJsonTag: false,
|
||||
NoModelComment: false,
|
||||
Clear: false,
|
||||
TypeMapping: nil,
|
||||
}
|
||||
)
|
||||
err = gutil.FillStructWithDefault(&in)
|
||||
t.AssertNil(err)
|
||||
|
||||
err = gfile.Copy(issueDirPath, path)
|
||||
t.AssertNil(err)
|
||||
|
||||
defer gfile.Remove(path)
|
||||
|
||||
pwd := gfile.Pwd()
|
||||
err = gfile.Chdir(path)
|
||||
t.AssertNil(err)
|
||||
|
||||
defer gfile.Chdir(pwd)
|
||||
|
||||
_, err = gendao.CGenDao{}.Dao(ctx, in)
|
||||
t.AssertNil(err)
|
||||
|
||||
generatedFiles, err := gfile.ScanDir(path, "*.go", true)
|
||||
t.AssertNil(err)
|
||||
t.Assert(len(generatedFiles), 8)
|
||||
for i, generatedFile := range generatedFiles {
|
||||
generatedFiles[i] = gstr.TrimLeftStr(generatedFile, path)
|
||||
}
|
||||
t.Assert(gstr.InArray(generatedFiles, "/dao/internal/user_1.go"), true)
|
||||
t.Assert(gstr.InArray(generatedFiles, "/dao/internal/user_2.go"), true)
|
||||
t.Assert(gstr.InArray(generatedFiles, "/dao/user_1.go"), true)
|
||||
t.Assert(gstr.InArray(generatedFiles, "/dao/user_2.go"), true)
|
||||
t.Assert(gstr.InArray(generatedFiles, "/model/do/user_1.go"), true)
|
||||
t.Assert(gstr.InArray(generatedFiles, "/model/do/user_2.go"), true)
|
||||
t.Assert(gstr.InArray(generatedFiles, "/model/entity/user_1.go"), true)
|
||||
t.Assert(gstr.InArray(generatedFiles, "/model/entity/user_2.go"), true)
|
||||
|
||||
// Key string to check if overwrite the dao files.
|
||||
// dao user1 is not be overwritten as configured in config.yaml.
|
||||
// dao user2 is to be overwritten as configured in config.yaml.
|
||||
var (
|
||||
keyStr = `// I am not overwritten.`
|
||||
daoUser1Content = gfile.GetContents(path + "/dao/user_1.go")
|
||||
daoUser2Content = gfile.GetContents(path + "/dao/user_2.go")
|
||||
)
|
||||
t.Assert(gstr.Contains(daoUser1Content, keyStr), true)
|
||||
t.Assert(gstr.Contains(daoUser2Content, keyStr), false)
|
||||
})
|
||||
}
|
||||
|
||||
@ -201,7 +201,8 @@ type (
|
||||
NoModelComment bool `name:"noModelComment" short:"m" brief:"{CGenDaoBriefNoModelComment}" orphan:"true"`
|
||||
Clear bool `name:"clear" short:"a" brief:"{CGenDaoBriefClear}" orphan:"true"`
|
||||
|
||||
TypeMapping map[DBFieldTypeName]CustomAttributeType `name:"typeMapping" short:"y" brief:"{CGenDaoBriefTypeMapping}" orphan:"true"`
|
||||
TypeMapping map[DBFieldTypeName]CustomAttributeType `name:"typeMapping" short:"y" brief:"{CGenDaoBriefTypeMapping}" orphan:"true"`
|
||||
generatedFilePaths *CGenDaoInternalGeneratedFilePaths
|
||||
}
|
||||
CGenDaoOutput struct{}
|
||||
|
||||
@ -212,6 +213,13 @@ type (
|
||||
NewTableNames []string
|
||||
}
|
||||
|
||||
CGenDaoInternalGeneratedFilePaths struct {
|
||||
DaoFilePaths []string
|
||||
DaoInternalFilePaths []string
|
||||
DoFilePaths []string
|
||||
EntityFilePaths []string
|
||||
}
|
||||
|
||||
DBFieldTypeName = string
|
||||
CustomAttributeType struct {
|
||||
Type string `brief:"custom attribute type name"`
|
||||
@ -220,6 +228,12 @@ type (
|
||||
)
|
||||
|
||||
func (c CGenDao) Dao(ctx context.Context, in CGenDaoInput) (out *CGenDaoOutput, err error) {
|
||||
in.generatedFilePaths = &CGenDaoInternalGeneratedFilePaths{
|
||||
DaoFilePaths: make([]string, 0),
|
||||
DaoInternalFilePaths: make([]string, 0),
|
||||
DoFilePaths: make([]string, 0),
|
||||
EntityFilePaths: make([]string, 0),
|
||||
}
|
||||
if g.Cfg().Available(ctx) {
|
||||
v := g.Cfg().MustGet(ctx, CGenDaoConfig)
|
||||
if v.IsSlice() {
|
||||
@ -333,6 +347,10 @@ func doGenDaoForArray(ctx context.Context, index int, in CGenDaoInput) {
|
||||
TableNames: tableNames,
|
||||
NewTableNames: newTableNames,
|
||||
})
|
||||
|
||||
if in.Clear {
|
||||
doClear(ctx, in)
|
||||
}
|
||||
}
|
||||
|
||||
func getImportPartContent(ctx context.Context, source string, isDo bool, appendImports []string) string {
|
||||
|
||||
@ -10,19 +10,24 @@ import (
|
||||
"context"
|
||||
|
||||
"github.com/gogf/gf/v2/os/gfile"
|
||||
"github.com/gogf/gf/v2/text/gstr"
|
||||
|
||||
"github.com/gogf/gf/cmd/gf/v2/internal/utility/mlog"
|
||||
"github.com/gogf/gf/cmd/gf/v2/internal/utility/utils"
|
||||
)
|
||||
|
||||
func doClear(ctx context.Context, dirPath string, force bool) {
|
||||
files, err := gfile.ScanDirFile(dirPath, "*.go", true)
|
||||
func doClear(ctx context.Context, in CGenDaoInput) {
|
||||
filePaths, err := gfile.ScanDirFile(in.Path, "*.go", true)
|
||||
if err != nil {
|
||||
mlog.Fatal(err)
|
||||
}
|
||||
for _, file := range files {
|
||||
if force || utils.IsFileDoNotEdit(file) {
|
||||
if err = gfile.Remove(file); err != nil {
|
||||
var allGeneratedFilePaths = make([]string, 0)
|
||||
allGeneratedFilePaths = append(allGeneratedFilePaths, in.generatedFilePaths.DaoFilePaths...)
|
||||
allGeneratedFilePaths = append(allGeneratedFilePaths, in.generatedFilePaths.DaoInternalFilePaths...)
|
||||
allGeneratedFilePaths = append(allGeneratedFilePaths, in.generatedFilePaths.EntityFilePaths...)
|
||||
allGeneratedFilePaths = append(allGeneratedFilePaths, in.generatedFilePaths.DoFilePaths...)
|
||||
for _, filePath := range filePaths {
|
||||
if !gstr.InArray(allGeneratedFilePaths, filePath) {
|
||||
if err = gfile.Remove(filePath); err != nil {
|
||||
mlog.Print(err)
|
||||
}
|
||||
}
|
||||
|
||||
@ -30,9 +30,6 @@ func generateDao(ctx context.Context, in CGenDaoInternalInput) {
|
||||
dirPathDao = gfile.Join(in.Path, in.DaoPath)
|
||||
dirPathDaoInternal = gfile.Join(dirPathDao, "internal")
|
||||
)
|
||||
if in.Clear {
|
||||
doClear(ctx, dirPathDao, true)
|
||||
}
|
||||
for i := 0; i < len(in.TableNames); i++ {
|
||||
generateDaoSingle(ctx, generateDaoSingleInput{
|
||||
CGenDaoInternalInput: in,
|
||||
@ -108,6 +105,11 @@ type generateDaoIndexInput struct {
|
||||
|
||||
func generateDaoIndex(in generateDaoIndexInput) {
|
||||
path := filepath.FromSlash(gfile.Join(in.DirPathDao, in.FileName+".go"))
|
||||
// It should add path to result slice whenever it would generate the path file or not.
|
||||
in.generatedFilePaths.DaoFilePaths = append(
|
||||
in.generatedFilePaths.DaoFilePaths,
|
||||
path,
|
||||
)
|
||||
if in.OverwriteDao || !gfile.Exists(path) {
|
||||
indexContent := gstr.ReplaceByMap(
|
||||
getTemplateFromPathOrDefault(in.TplDaoIndexPath, consts.TemplateGenDaoIndexContent),
|
||||
@ -151,6 +153,10 @@ func generateDaoInternal(in generateDaoInternalInput) {
|
||||
tplVarColumnNames: gstr.Trim(generateColumnNamesForDao(in.FieldMap, removeFieldPrefixArray)),
|
||||
})
|
||||
modelContent = replaceDefaultVar(in.CGenDaoInternalInput, modelContent)
|
||||
in.generatedFilePaths.DaoInternalFilePaths = append(
|
||||
in.generatedFilePaths.DaoInternalFilePaths,
|
||||
path,
|
||||
)
|
||||
if err := gfile.PutContents(path, strings.TrimSpace(modelContent)); err != nil {
|
||||
mlog.Fatalf("writing content to '%s' failed: %v", path, err)
|
||||
} else {
|
||||
|
||||
@ -24,9 +24,6 @@ import (
|
||||
|
||||
func generateDo(ctx context.Context, in CGenDaoInternalInput) {
|
||||
var dirPathDo = filepath.FromSlash(gfile.Join(in.Path, in.DoPath))
|
||||
if in.Clear {
|
||||
doClear(ctx, dirPathDo, false)
|
||||
}
|
||||
in.NoJsonTag = true
|
||||
in.DescriptionTag = false
|
||||
in.NoModelComment = false
|
||||
@ -66,6 +63,10 @@ func generateDo(ctx context.Context, in CGenDaoInternalInput) {
|
||||
gstr.CaseCamel(newTableName),
|
||||
structDefinition,
|
||||
)
|
||||
in.generatedFilePaths.DoFilePaths = append(
|
||||
in.generatedFilePaths.DoFilePaths,
|
||||
doFilePath,
|
||||
)
|
||||
err = gfile.PutContents(doFilePath, strings.TrimSpace(modelContent))
|
||||
if err != nil {
|
||||
mlog.Fatalf(`writing content to "%s" failed: %v`, doFilePath, err)
|
||||
|
||||
@ -22,9 +22,6 @@ import (
|
||||
|
||||
func generateEntity(ctx context.Context, in CGenDaoInternalInput) {
|
||||
var dirPathEntity = gfile.Join(in.Path, in.EntityPath)
|
||||
if in.Clear {
|
||||
doClear(ctx, dirPathEntity, false)
|
||||
}
|
||||
// Model content.
|
||||
for i, tableName := range in.TableNames {
|
||||
fieldMap, err := in.DB.TableFields(ctx, tableName)
|
||||
@ -51,7 +48,10 @@ func generateEntity(ctx context.Context, in CGenDaoInternalInput) {
|
||||
appendImports,
|
||||
)
|
||||
)
|
||||
|
||||
in.generatedFilePaths.EntityFilePaths = append(
|
||||
in.generatedFilePaths.EntityFilePaths,
|
||||
entityFilePath,
|
||||
)
|
||||
err = gfile.PutContents(entityFilePath, strings.TrimSpace(entityContent))
|
||||
if err != nil {
|
||||
mlog.Fatalf("writing content to '%s' failed: %v", entityFilePath, err)
|
||||
|
||||
20
cmd/gf/internal/cmd/testdata/issue/2572/config.yaml
vendored
Normal file
20
cmd/gf/internal/cmd/testdata/issue/2572/config.yaml
vendored
Normal file
@ -0,0 +1,20 @@
|
||||
gfcli:
|
||||
gen:
|
||||
dao:
|
||||
- link: "mysql:root:12345678@tcp(127.0.0.1:3306)/test"
|
||||
tables: "user1"
|
||||
descriptionTag: true
|
||||
noModelComment: true
|
||||
group: "sys"
|
||||
clear: true
|
||||
overwriteDao: true
|
||||
- link: "mysql:root:12345678@tcp(127.0.0.1:3306)/test"
|
||||
tables: "user2"
|
||||
descriptionTag: true
|
||||
noModelComment: true
|
||||
group: "book"
|
||||
clear: true
|
||||
overwriteDao: true
|
||||
|
||||
|
||||
|
||||
85
cmd/gf/internal/cmd/testdata/issue/2572/dao/internal/user_3.go
vendored
Normal file
85
cmd/gf/internal/cmd/testdata/issue/2572/dao/internal/user_3.go
vendored
Normal file
@ -0,0 +1,85 @@
|
||||
// ==========================================================================
|
||||
// Code generated and maintained by GoFrame CLI tool. DO NOT EDIT.
|
||||
// ==========================================================================
|
||||
|
||||
package internal
|
||||
|
||||
import (
|
||||
"context"
|
||||
|
||||
"github.com/gogf/gf/v2/database/gdb"
|
||||
"github.com/gogf/gf/v2/frame/g"
|
||||
)
|
||||
|
||||
// User3Dao is the data access object for table user3.
|
||||
type User3Dao struct {
|
||||
table string // table is the underlying table name of the DAO.
|
||||
group string // group is the database configuration group name of current DAO.
|
||||
columns User3Columns // columns contains all the column names of Table for convenient usage.
|
||||
}
|
||||
|
||||
// User3Columns defines and stores column names for table user3.
|
||||
type User3Columns struct {
|
||||
Id string // User ID
|
||||
Passport string // User Passport
|
||||
Password string // User Password
|
||||
Nickname string // User Nickname
|
||||
Score string // Total score amount.
|
||||
CreateAt string // Created Time
|
||||
UpdateAt string // Updated Time
|
||||
}
|
||||
|
||||
// user3Columns holds the columns for table user3.
|
||||
var user3Columns = User3Columns{
|
||||
Id: "id",
|
||||
Passport: "passport",
|
||||
Password: "password",
|
||||
Nickname: "nickname",
|
||||
Score: "score",
|
||||
CreateAt: "create_at",
|
||||
UpdateAt: "update_at",
|
||||
}
|
||||
|
||||
// NewUser3Dao creates and returns a new DAO object for table data access.
|
||||
func NewUser3Dao() *User3Dao {
|
||||
return &User3Dao{
|
||||
group: "sys",
|
||||
table: "user3",
|
||||
columns: user3Columns,
|
||||
}
|
||||
}
|
||||
|
||||
// DB retrieves and returns the underlying raw database management object of current DAO.
|
||||
func (dao *User3Dao) DB() gdb.DB {
|
||||
return g.DB(dao.group)
|
||||
}
|
||||
|
||||
// Table returns the table name of current dao.
|
||||
func (dao *User3Dao) Table() string {
|
||||
return dao.table
|
||||
}
|
||||
|
||||
// Columns returns all column names of current dao.
|
||||
func (dao *User3Dao) Columns() User3Columns {
|
||||
return dao.columns
|
||||
}
|
||||
|
||||
// Group returns the configuration group name of database of current dao.
|
||||
func (dao *User3Dao) Group() string {
|
||||
return dao.group
|
||||
}
|
||||
|
||||
// Ctx creates and returns the Model for current DAO, It automatically sets the context for current operation.
|
||||
func (dao *User3Dao) Ctx(ctx context.Context) *gdb.Model {
|
||||
return dao.DB().Model(dao.table).Safe().Ctx(ctx)
|
||||
}
|
||||
|
||||
// Transaction wraps the transaction logic using function f.
|
||||
// It rollbacks the transaction and returns the error from function f if it returns non-nil error.
|
||||
// It commits the transaction and returns nil if function f returns nil.
|
||||
//
|
||||
// Note that, you should not Commit or Rollback the transaction in function f
|
||||
// as it is automatically handled by this function.
|
||||
func (dao *User3Dao) Transaction(ctx context.Context, f func(ctx context.Context, tx gdb.TX) error) (err error) {
|
||||
return dao.Ctx(ctx).Transaction(ctx, f)
|
||||
}
|
||||
85
cmd/gf/internal/cmd/testdata/issue/2572/dao/internal/user_4.go
vendored
Normal file
85
cmd/gf/internal/cmd/testdata/issue/2572/dao/internal/user_4.go
vendored
Normal file
@ -0,0 +1,85 @@
|
||||
// ==========================================================================
|
||||
// Code generated and maintained by GoFrame CLI tool. DO NOT EDIT.
|
||||
// ==========================================================================
|
||||
|
||||
package internal
|
||||
|
||||
import (
|
||||
"context"
|
||||
|
||||
"github.com/gogf/gf/v2/database/gdb"
|
||||
"github.com/gogf/gf/v2/frame/g"
|
||||
)
|
||||
|
||||
// User4Dao is the data access object for table user4.
|
||||
type User4Dao struct {
|
||||
table string // table is the underlying table name of the DAO.
|
||||
group string // group is the database configuration group name of current DAO.
|
||||
columns User4Columns // columns contains all the column names of Table for convenient usage.
|
||||
}
|
||||
|
||||
// User4Columns defines and stores column names for table user4.
|
||||
type User4Columns struct {
|
||||
Id string // User ID
|
||||
Passport string // User Passport
|
||||
Password string // User Password
|
||||
Nickname string // User Nickname
|
||||
Score string // Total score amount.
|
||||
CreateAt string // Created Time
|
||||
UpdateAt string // Updated Time
|
||||
}
|
||||
|
||||
// user4Columns holds the columns for table user4.
|
||||
var user4Columns = User4Columns{
|
||||
Id: "id",
|
||||
Passport: "passport",
|
||||
Password: "password",
|
||||
Nickname: "nickname",
|
||||
Score: "score",
|
||||
CreateAt: "create_at",
|
||||
UpdateAt: "update_at",
|
||||
}
|
||||
|
||||
// NewUser4Dao creates and returns a new DAO object for table data access.
|
||||
func NewUser4Dao() *User4Dao {
|
||||
return &User4Dao{
|
||||
group: "book",
|
||||
table: "user4",
|
||||
columns: user4Columns,
|
||||
}
|
||||
}
|
||||
|
||||
// DB retrieves and returns the underlying raw database management object of current DAO.
|
||||
func (dao *User4Dao) DB() gdb.DB {
|
||||
return g.DB(dao.group)
|
||||
}
|
||||
|
||||
// Table returns the table name of current dao.
|
||||
func (dao *User4Dao) Table() string {
|
||||
return dao.table
|
||||
}
|
||||
|
||||
// Columns returns all column names of current dao.
|
||||
func (dao *User4Dao) Columns() User4Columns {
|
||||
return dao.columns
|
||||
}
|
||||
|
||||
// Group returns the configuration group name of database of current dao.
|
||||
func (dao *User4Dao) Group() string {
|
||||
return dao.group
|
||||
}
|
||||
|
||||
// Ctx creates and returns the Model for current DAO, It automatically sets the context for current operation.
|
||||
func (dao *User4Dao) Ctx(ctx context.Context) *gdb.Model {
|
||||
return dao.DB().Model(dao.table).Safe().Ctx(ctx)
|
||||
}
|
||||
|
||||
// Transaction wraps the transaction logic using function f.
|
||||
// It rollbacks the transaction and returns the error from function f if it returns non-nil error.
|
||||
// It commits the transaction and returns nil if function f returns nil.
|
||||
//
|
||||
// Note that, you should not Commit or Rollback the transaction in function f
|
||||
// as it is automatically handled by this function.
|
||||
func (dao *User4Dao) Transaction(ctx context.Context, f func(ctx context.Context, tx gdb.TX) error) (err error) {
|
||||
return dao.Ctx(ctx).Transaction(ctx, f)
|
||||
}
|
||||
27
cmd/gf/internal/cmd/testdata/issue/2572/dao/user_3.go
vendored
Normal file
27
cmd/gf/internal/cmd/testdata/issue/2572/dao/user_3.go
vendored
Normal file
@ -0,0 +1,27 @@
|
||||
// =================================================================================
|
||||
// This is auto-generated by GoFrame CLI tool only once. Fill this file as you wish.
|
||||
// =================================================================================
|
||||
|
||||
package dao
|
||||
|
||||
import (
|
||||
"/internal"
|
||||
)
|
||||
|
||||
// internalUser3Dao is internal type for wrapping internal DAO implements.
|
||||
type internalUser3Dao = *internal.User3Dao
|
||||
|
||||
// user3Dao is the data access object for table user3.
|
||||
// You can define custom methods on it to extend its functionality as you wish.
|
||||
type user3Dao struct {
|
||||
internalUser3Dao
|
||||
}
|
||||
|
||||
var (
|
||||
// User3 is globally public accessible object for table user3 operations.
|
||||
User3 = user3Dao{
|
||||
internal.NewUser3Dao(),
|
||||
}
|
||||
)
|
||||
|
||||
// Fill with you ideas below.
|
||||
27
cmd/gf/internal/cmd/testdata/issue/2572/dao/user_4.go
vendored
Normal file
27
cmd/gf/internal/cmd/testdata/issue/2572/dao/user_4.go
vendored
Normal file
@ -0,0 +1,27 @@
|
||||
// =================================================================================
|
||||
// This is auto-generated by GoFrame CLI tool only once. Fill this file as you wish.
|
||||
// =================================================================================
|
||||
|
||||
package dao
|
||||
|
||||
import (
|
||||
"/internal"
|
||||
)
|
||||
|
||||
// internalUser4Dao is internal type for wrapping internal DAO implements.
|
||||
type internalUser4Dao = *internal.User4Dao
|
||||
|
||||
// user4Dao is the data access object for table user4.
|
||||
// You can define custom methods on it to extend its functionality as you wish.
|
||||
type user4Dao struct {
|
||||
internalUser4Dao
|
||||
}
|
||||
|
||||
var (
|
||||
// User4 is globally public accessible object for table user4 operations.
|
||||
User4 = user4Dao{
|
||||
internal.NewUser4Dao(),
|
||||
}
|
||||
)
|
||||
|
||||
// Fill with you ideas below.
|
||||
22
cmd/gf/internal/cmd/testdata/issue/2572/model/do/user_3.go
vendored
Normal file
22
cmd/gf/internal/cmd/testdata/issue/2572/model/do/user_3.go
vendored
Normal file
@ -0,0 +1,22 @@
|
||||
// =================================================================================
|
||||
// Code generated and maintained by GoFrame CLI tool. DO NOT EDIT.
|
||||
// =================================================================================
|
||||
|
||||
package do
|
||||
|
||||
import (
|
||||
"github.com/gogf/gf/v2/frame/g"
|
||||
"github.com/gogf/gf/v2/os/gtime"
|
||||
)
|
||||
|
||||
// User1 is the golang structure of table user1 for DAO operations like Where/Data.
|
||||
type User1 struct {
|
||||
g.Meta `orm:"table:user1, do:true"`
|
||||
Id interface{} // User ID
|
||||
Passport interface{} // User Passport
|
||||
Password interface{} // User Password
|
||||
Nickname interface{} // User Nickname
|
||||
Score interface{} // Total score amount.
|
||||
CreateAt *gtime.Time // Created Time
|
||||
UpdateAt *gtime.Time // Updated Time
|
||||
}
|
||||
22
cmd/gf/internal/cmd/testdata/issue/2572/model/do/user_4.go
vendored
Normal file
22
cmd/gf/internal/cmd/testdata/issue/2572/model/do/user_4.go
vendored
Normal file
@ -0,0 +1,22 @@
|
||||
// =================================================================================
|
||||
// Code generated and maintained by GoFrame CLI tool. DO NOT EDIT.
|
||||
// =================================================================================
|
||||
|
||||
package do
|
||||
|
||||
import (
|
||||
"github.com/gogf/gf/v2/frame/g"
|
||||
"github.com/gogf/gf/v2/os/gtime"
|
||||
)
|
||||
|
||||
// User2 is the golang structure of table user2 for DAO operations like Where/Data.
|
||||
type User2 struct {
|
||||
g.Meta `orm:"table:user2, do:true"`
|
||||
Id interface{} // User ID
|
||||
Passport interface{} // User Passport
|
||||
Password interface{} // User Password
|
||||
Nickname interface{} // User Nickname
|
||||
Score interface{} // Total score amount.
|
||||
CreateAt *gtime.Time // Created Time
|
||||
UpdateAt *gtime.Time // Updated Time
|
||||
}
|
||||
20
cmd/gf/internal/cmd/testdata/issue/2572/model/entity/user_3.go
vendored
Normal file
20
cmd/gf/internal/cmd/testdata/issue/2572/model/entity/user_3.go
vendored
Normal file
@ -0,0 +1,20 @@
|
||||
// =================================================================================
|
||||
// Code generated and maintained by GoFrame CLI tool. DO NOT EDIT.
|
||||
// =================================================================================
|
||||
|
||||
package entity
|
||||
|
||||
import (
|
||||
"github.com/gogf/gf/v2/os/gtime"
|
||||
)
|
||||
|
||||
// User1 is the golang structure for table user1.
|
||||
type User1 struct {
|
||||
Id uint `json:"ID" description:"User ID"`
|
||||
Passport string `json:"PASSPORT" description:"User Passport"`
|
||||
Password string `json:"PASSWORD" description:"User Password"`
|
||||
Nickname string `json:"NICKNAME" description:"User Nickname"`
|
||||
Score float64 `json:"SCORE" description:"Total score amount."`
|
||||
CreateAt *gtime.Time `json:"CREATE_AT" description:"Created Time"`
|
||||
UpdateAt *gtime.Time `json:"UPDATE_AT" description:"Updated Time"`
|
||||
}
|
||||
20
cmd/gf/internal/cmd/testdata/issue/2572/model/entity/user_4.go
vendored
Normal file
20
cmd/gf/internal/cmd/testdata/issue/2572/model/entity/user_4.go
vendored
Normal file
@ -0,0 +1,20 @@
|
||||
// =================================================================================
|
||||
// Code generated and maintained by GoFrame CLI tool. DO NOT EDIT.
|
||||
// =================================================================================
|
||||
|
||||
package entity
|
||||
|
||||
import (
|
||||
"github.com/gogf/gf/v2/os/gtime"
|
||||
)
|
||||
|
||||
// User2 is the golang structure for table user2.
|
||||
type User2 struct {
|
||||
Id uint `json:"ID" description:"User ID"`
|
||||
Passport string `json:"PASSPORT" description:"User Passport"`
|
||||
Password string `json:"PASSWORD" description:"User Password"`
|
||||
Nickname string `json:"NICKNAME" description:"User Nickname"`
|
||||
Score float64 `json:"SCORE" description:"Total score amount."`
|
||||
CreateAt *gtime.Time `json:"CREATE_AT" description:"Created Time"`
|
||||
UpdateAt *gtime.Time `json:"UPDATE_AT" description:"Updated Time"`
|
||||
}
|
||||
10
cmd/gf/internal/cmd/testdata/issue/2572/sql1.sql
vendored
Normal file
10
cmd/gf/internal/cmd/testdata/issue/2572/sql1.sql
vendored
Normal file
@ -0,0 +1,10 @@
|
||||
CREATE TABLE `user1` (
|
||||
`id` int unsigned NOT NULL AUTO_INCREMENT COMMENT 'User ID',
|
||||
`passport` varchar(45) NOT NULL COMMENT 'User Passport',
|
||||
`password` varchar(45) NOT NULL COMMENT 'User Password',
|
||||
`nickname` varchar(45) NOT NULL COMMENT 'User Nickname',
|
||||
`score` decimal(10,2) unsigned DEFAULT NULL COMMENT 'Total score amount.',
|
||||
`create_at` datetime DEFAULT NULL COMMENT 'Created Time',
|
||||
`update_at` datetime DEFAULT NULL COMMENT 'Updated Time',
|
||||
PRIMARY KEY (`id`)
|
||||
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
|
||||
10
cmd/gf/internal/cmd/testdata/issue/2572/sql2.sql
vendored
Normal file
10
cmd/gf/internal/cmd/testdata/issue/2572/sql2.sql
vendored
Normal file
@ -0,0 +1,10 @@
|
||||
CREATE TABLE `user2` (
|
||||
`id` int unsigned NOT NULL AUTO_INCREMENT COMMENT 'User ID',
|
||||
`passport` varchar(45) NOT NULL COMMENT 'User Passport',
|
||||
`password` varchar(45) NOT NULL COMMENT 'User Password',
|
||||
`nickname` varchar(45) NOT NULL COMMENT 'User Nickname',
|
||||
`score` decimal(10,2) unsigned DEFAULT NULL COMMENT 'Total score amount.',
|
||||
`create_at` datetime DEFAULT NULL COMMENT 'Created Time',
|
||||
`update_at` datetime DEFAULT NULL COMMENT 'Updated Time',
|
||||
PRIMARY KEY (`id`)
|
||||
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
|
||||
20
cmd/gf/internal/cmd/testdata/issue/2616/config.yaml
vendored
Normal file
20
cmd/gf/internal/cmd/testdata/issue/2616/config.yaml
vendored
Normal file
@ -0,0 +1,20 @@
|
||||
gfcli:
|
||||
gen:
|
||||
dao:
|
||||
- link: "mysql:root:12345678@tcp(127.0.0.1:3306)/test"
|
||||
tables: "user1"
|
||||
descriptionTag: true
|
||||
noModelComment: true
|
||||
group: "sys"
|
||||
clear: true
|
||||
overwriteDao: false
|
||||
- link: "mysql:root:12345678@tcp(127.0.0.1:3306)/test"
|
||||
tables: "user2"
|
||||
descriptionTag: true
|
||||
noModelComment: true
|
||||
group: "book"
|
||||
clear: true
|
||||
overwriteDao: true
|
||||
|
||||
|
||||
|
||||
85
cmd/gf/internal/cmd/testdata/issue/2616/dao/internal/user_1.go
vendored
Normal file
85
cmd/gf/internal/cmd/testdata/issue/2616/dao/internal/user_1.go
vendored
Normal file
@ -0,0 +1,85 @@
|
||||
// ==========================================================================
|
||||
// Code generated and maintained by GoFrame CLI tool. DO NOT EDIT.
|
||||
// ==========================================================================
|
||||
|
||||
package internal
|
||||
|
||||
import (
|
||||
"context"
|
||||
|
||||
"github.com/gogf/gf/v2/database/gdb"
|
||||
"github.com/gogf/gf/v2/frame/g"
|
||||
)
|
||||
|
||||
// User1Dao is the data access object for table user1.
|
||||
type User1Dao struct {
|
||||
table string // table is the underlying table name of the DAO.
|
||||
group string // group is the database configuration group name of current DAO.
|
||||
columns User1Columns // columns contains all the column names of Table for convenient usage.
|
||||
}
|
||||
|
||||
// User1Columns defines and stores column names for table user1.
|
||||
type User1Columns struct {
|
||||
Id string // User ID
|
||||
Passport string // User Passport
|
||||
Password string // User Password
|
||||
Nickname string // User Nickname
|
||||
Score string // Total score amount.
|
||||
CreateAt string // Created Time
|
||||
UpdateAt string // Updated Time
|
||||
}
|
||||
|
||||
// user1Columns holds the columns for table user1.
|
||||
var user1Columns = User1Columns{
|
||||
Id: "id",
|
||||
Passport: "passport",
|
||||
Password: "password",
|
||||
Nickname: "nickname",
|
||||
Score: "score",
|
||||
CreateAt: "create_at",
|
||||
UpdateAt: "update_at",
|
||||
}
|
||||
|
||||
// NewUser1Dao creates and returns a new DAO object for table data access.
|
||||
func NewUser1Dao() *User1Dao {
|
||||
return &User1Dao{
|
||||
group: "sys",
|
||||
table: "user1",
|
||||
columns: user1Columns,
|
||||
}
|
||||
}
|
||||
|
||||
// DB retrieves and returns the underlying raw database management object of current DAO.
|
||||
func (dao *User1Dao) DB() gdb.DB {
|
||||
return g.DB(dao.group)
|
||||
}
|
||||
|
||||
// Table returns the table name of current dao.
|
||||
func (dao *User1Dao) Table() string {
|
||||
return dao.table
|
||||
}
|
||||
|
||||
// Columns returns all column names of current dao.
|
||||
func (dao *User1Dao) Columns() User1Columns {
|
||||
return dao.columns
|
||||
}
|
||||
|
||||
// Group returns the configuration group name of database of current dao.
|
||||
func (dao *User1Dao) Group() string {
|
||||
return dao.group
|
||||
}
|
||||
|
||||
// Ctx creates and returns the Model for current DAO, It automatically sets the context for current operation.
|
||||
func (dao *User1Dao) Ctx(ctx context.Context) *gdb.Model {
|
||||
return dao.DB().Model(dao.table).Safe().Ctx(ctx)
|
||||
}
|
||||
|
||||
// Transaction wraps the transaction logic using function f.
|
||||
// It rollbacks the transaction and returns the error from function f if it returns non-nil error.
|
||||
// It commits the transaction and returns nil if function f returns nil.
|
||||
//
|
||||
// Note that, you should not Commit or Rollback the transaction in function f
|
||||
// as it is automatically handled by this function.
|
||||
func (dao *User1Dao) Transaction(ctx context.Context, f func(ctx context.Context, tx gdb.TX) error) (err error) {
|
||||
return dao.Ctx(ctx).Transaction(ctx, f)
|
||||
}
|
||||
85
cmd/gf/internal/cmd/testdata/issue/2616/dao/internal/user_2.go
vendored
Normal file
85
cmd/gf/internal/cmd/testdata/issue/2616/dao/internal/user_2.go
vendored
Normal file
@ -0,0 +1,85 @@
|
||||
// ==========================================================================
|
||||
// Code generated and maintained by GoFrame CLI tool. DO NOT EDIT.
|
||||
// ==========================================================================
|
||||
|
||||
package internal
|
||||
|
||||
import (
|
||||
"context"
|
||||
|
||||
"github.com/gogf/gf/v2/database/gdb"
|
||||
"github.com/gogf/gf/v2/frame/g"
|
||||
)
|
||||
|
||||
// User2Dao is the data access object for table user2.
|
||||
type User2Dao struct {
|
||||
table string // table is the underlying table name of the DAO.
|
||||
group string // group is the database configuration group name of current DAO.
|
||||
columns User2Columns // columns contains all the column names of Table for convenient usage.
|
||||
}
|
||||
|
||||
// User2Columns defines and stores column names for table user2.
|
||||
type User2Columns struct {
|
||||
Id string // User ID
|
||||
Passport string // User Passport
|
||||
Password string // User Password
|
||||
Nickname string // User Nickname
|
||||
Score string // Total score amount.
|
||||
CreateAt string // Created Time
|
||||
UpdateAt string // Updated Time
|
||||
}
|
||||
|
||||
// user2Columns holds the columns for table user2.
|
||||
var user2Columns = User2Columns{
|
||||
Id: "id",
|
||||
Passport: "passport",
|
||||
Password: "password",
|
||||
Nickname: "nickname",
|
||||
Score: "score",
|
||||
CreateAt: "create_at",
|
||||
UpdateAt: "update_at",
|
||||
}
|
||||
|
||||
// NewUser2Dao creates and returns a new DAO object for table data access.
|
||||
func NewUser2Dao() *User2Dao {
|
||||
return &User2Dao{
|
||||
group: "sys",
|
||||
table: "user2",
|
||||
columns: user2Columns,
|
||||
}
|
||||
}
|
||||
|
||||
// DB retrieves and returns the underlying raw database management object of current DAO.
|
||||
func (dao *User2Dao) DB() gdb.DB {
|
||||
return g.DB(dao.group)
|
||||
}
|
||||
|
||||
// Table returns the table name of current dao.
|
||||
func (dao *User2Dao) Table() string {
|
||||
return dao.table
|
||||
}
|
||||
|
||||
// Columns returns all column names of current dao.
|
||||
func (dao *User2Dao) Columns() User2Columns {
|
||||
return dao.columns
|
||||
}
|
||||
|
||||
// Group returns the configuration group name of database of current dao.
|
||||
func (dao *User2Dao) Group() string {
|
||||
return dao.group
|
||||
}
|
||||
|
||||
// Ctx creates and returns the Model for current DAO, It automatically sets the context for current operation.
|
||||
func (dao *User2Dao) Ctx(ctx context.Context) *gdb.Model {
|
||||
return dao.DB().Model(dao.table).Safe().Ctx(ctx)
|
||||
}
|
||||
|
||||
// Transaction wraps the transaction logic using function f.
|
||||
// It rollbacks the transaction and returns the error from function f if it returns non-nil error.
|
||||
// It commits the transaction and returns nil if function f returns nil.
|
||||
//
|
||||
// Note that, you should not Commit or Rollback the transaction in function f
|
||||
// as it is automatically handled by this function.
|
||||
func (dao *User2Dao) Transaction(ctx context.Context, f func(ctx context.Context, tx gdb.TX) error) (err error) {
|
||||
return dao.Ctx(ctx).Transaction(ctx, f)
|
||||
}
|
||||
85
cmd/gf/internal/cmd/testdata/issue/2616/dao/internal/user_3.go
vendored
Normal file
85
cmd/gf/internal/cmd/testdata/issue/2616/dao/internal/user_3.go
vendored
Normal file
@ -0,0 +1,85 @@
|
||||
// ==========================================================================
|
||||
// Code generated and maintained by GoFrame CLI tool. DO NOT EDIT.
|
||||
// ==========================================================================
|
||||
|
||||
package internal
|
||||
|
||||
import (
|
||||
"context"
|
||||
|
||||
"github.com/gogf/gf/v2/database/gdb"
|
||||
"github.com/gogf/gf/v2/frame/g"
|
||||
)
|
||||
|
||||
// User3Dao is the data access object for table user3.
|
||||
type User3Dao struct {
|
||||
table string // table is the underlying table name of the DAO.
|
||||
group string // group is the database configuration group name of current DAO.
|
||||
columns User3Columns // columns contains all the column names of Table for convenient usage.
|
||||
}
|
||||
|
||||
// User3Columns defines and stores column names for table user3.
|
||||
type User3Columns struct {
|
||||
Id string // User ID
|
||||
Passport string // User Passport
|
||||
Password string // User Password
|
||||
Nickname string // User Nickname
|
||||
Score string // Total score amount.
|
||||
CreateAt string // Created Time
|
||||
UpdateAt string // Updated Time
|
||||
}
|
||||
|
||||
// user3Columns holds the columns for table user3.
|
||||
var user3Columns = User3Columns{
|
||||
Id: "id",
|
||||
Passport: "passport",
|
||||
Password: "password",
|
||||
Nickname: "nickname",
|
||||
Score: "score",
|
||||
CreateAt: "create_at",
|
||||
UpdateAt: "update_at",
|
||||
}
|
||||
|
||||
// NewUser3Dao creates and returns a new DAO object for table data access.
|
||||
func NewUser3Dao() *User3Dao {
|
||||
return &User3Dao{
|
||||
group: "sys",
|
||||
table: "user3",
|
||||
columns: user3Columns,
|
||||
}
|
||||
}
|
||||
|
||||
// DB retrieves and returns the underlying raw database management object of current DAO.
|
||||
func (dao *User3Dao) DB() gdb.DB {
|
||||
return g.DB(dao.group)
|
||||
}
|
||||
|
||||
// Table returns the table name of current dao.
|
||||
func (dao *User3Dao) Table() string {
|
||||
return dao.table
|
||||
}
|
||||
|
||||
// Columns returns all column names of current dao.
|
||||
func (dao *User3Dao) Columns() User3Columns {
|
||||
return dao.columns
|
||||
}
|
||||
|
||||
// Group returns the configuration group name of database of current dao.
|
||||
func (dao *User3Dao) Group() string {
|
||||
return dao.group
|
||||
}
|
||||
|
||||
// Ctx creates and returns the Model for current DAO, It automatically sets the context for current operation.
|
||||
func (dao *User3Dao) Ctx(ctx context.Context) *gdb.Model {
|
||||
return dao.DB().Model(dao.table).Safe().Ctx(ctx)
|
||||
}
|
||||
|
||||
// Transaction wraps the transaction logic using function f.
|
||||
// It rollbacks the transaction and returns the error from function f if it returns non-nil error.
|
||||
// It commits the transaction and returns nil if function f returns nil.
|
||||
//
|
||||
// Note that, you should not Commit or Rollback the transaction in function f
|
||||
// as it is automatically handled by this function.
|
||||
func (dao *User3Dao) Transaction(ctx context.Context, f func(ctx context.Context, tx gdb.TX) error) (err error) {
|
||||
return dao.Ctx(ctx).Transaction(ctx, f)
|
||||
}
|
||||
85
cmd/gf/internal/cmd/testdata/issue/2616/dao/internal/user_4.go
vendored
Normal file
85
cmd/gf/internal/cmd/testdata/issue/2616/dao/internal/user_4.go
vendored
Normal file
@ -0,0 +1,85 @@
|
||||
// ==========================================================================
|
||||
// Code generated and maintained by GoFrame CLI tool. DO NOT EDIT.
|
||||
// ==========================================================================
|
||||
|
||||
package internal
|
||||
|
||||
import (
|
||||
"context"
|
||||
|
||||
"github.com/gogf/gf/v2/database/gdb"
|
||||
"github.com/gogf/gf/v2/frame/g"
|
||||
)
|
||||
|
||||
// User4Dao is the data access object for table user4.
|
||||
type User4Dao struct {
|
||||
table string // table is the underlying table name of the DAO.
|
||||
group string // group is the database configuration group name of current DAO.
|
||||
columns User4Columns // columns contains all the column names of Table for convenient usage.
|
||||
}
|
||||
|
||||
// User4Columns defines and stores column names for table user4.
|
||||
type User4Columns struct {
|
||||
Id string // User ID
|
||||
Passport string // User Passport
|
||||
Password string // User Password
|
||||
Nickname string // User Nickname
|
||||
Score string // Total score amount.
|
||||
CreateAt string // Created Time
|
||||
UpdateAt string // Updated Time
|
||||
}
|
||||
|
||||
// user4Columns holds the columns for table user4.
|
||||
var user4Columns = User4Columns{
|
||||
Id: "id",
|
||||
Passport: "passport",
|
||||
Password: "password",
|
||||
Nickname: "nickname",
|
||||
Score: "score",
|
||||
CreateAt: "create_at",
|
||||
UpdateAt: "update_at",
|
||||
}
|
||||
|
||||
// NewUser4Dao creates and returns a new DAO object for table data access.
|
||||
func NewUser4Dao() *User4Dao {
|
||||
return &User4Dao{
|
||||
group: "book",
|
||||
table: "user4",
|
||||
columns: user4Columns,
|
||||
}
|
||||
}
|
||||
|
||||
// DB retrieves and returns the underlying raw database management object of current DAO.
|
||||
func (dao *User4Dao) DB() gdb.DB {
|
||||
return g.DB(dao.group)
|
||||
}
|
||||
|
||||
// Table returns the table name of current dao.
|
||||
func (dao *User4Dao) Table() string {
|
||||
return dao.table
|
||||
}
|
||||
|
||||
// Columns returns all column names of current dao.
|
||||
func (dao *User4Dao) Columns() User4Columns {
|
||||
return dao.columns
|
||||
}
|
||||
|
||||
// Group returns the configuration group name of database of current dao.
|
||||
func (dao *User4Dao) Group() string {
|
||||
return dao.group
|
||||
}
|
||||
|
||||
// Ctx creates and returns the Model for current DAO, It automatically sets the context for current operation.
|
||||
func (dao *User4Dao) Ctx(ctx context.Context) *gdb.Model {
|
||||
return dao.DB().Model(dao.table).Safe().Ctx(ctx)
|
||||
}
|
||||
|
||||
// Transaction wraps the transaction logic using function f.
|
||||
// It rollbacks the transaction and returns the error from function f if it returns non-nil error.
|
||||
// It commits the transaction and returns nil if function f returns nil.
|
||||
//
|
||||
// Note that, you should not Commit or Rollback the transaction in function f
|
||||
// as it is automatically handled by this function.
|
||||
func (dao *User4Dao) Transaction(ctx context.Context, f func(ctx context.Context, tx gdb.TX) error) (err error) {
|
||||
return dao.Ctx(ctx).Transaction(ctx, f)
|
||||
}
|
||||
29
cmd/gf/internal/cmd/testdata/issue/2616/dao/user_1.go
vendored
Normal file
29
cmd/gf/internal/cmd/testdata/issue/2616/dao/user_1.go
vendored
Normal file
@ -0,0 +1,29 @@
|
||||
// =================================================================================
|
||||
// This is auto-generated by GoFrame CLI tool only once. Fill this file as you wish.
|
||||
// =================================================================================
|
||||
|
||||
// I am not overwritten.
|
||||
|
||||
package dao
|
||||
|
||||
import (
|
||||
"/internal"
|
||||
)
|
||||
|
||||
// internalUser1Dao is internal type for wrapping internal DAO implements.
|
||||
type internalUser1Dao = *internal.User1Dao
|
||||
|
||||
// user1Dao is the data access object for table user1.
|
||||
// You can define custom methods on it to extend its functionality as you wish.
|
||||
type user1Dao struct {
|
||||
internalUser1Dao
|
||||
}
|
||||
|
||||
var (
|
||||
// User1 is globally public accessible object for table user1 operations.
|
||||
User1 = user1Dao{
|
||||
internal.NewUser1Dao(),
|
||||
}
|
||||
)
|
||||
|
||||
// Fill with you ideas below.
|
||||
29
cmd/gf/internal/cmd/testdata/issue/2616/dao/user_2.go
vendored
Normal file
29
cmd/gf/internal/cmd/testdata/issue/2616/dao/user_2.go
vendored
Normal file
@ -0,0 +1,29 @@
|
||||
// =================================================================================
|
||||
// This is auto-generated by GoFrame CLI tool only once. Fill this file as you wish.
|
||||
// =================================================================================
|
||||
|
||||
// I am not overwritten.
|
||||
|
||||
package dao
|
||||
|
||||
import (
|
||||
"/internal"
|
||||
)
|
||||
|
||||
// internalUser2Dao is internal type for wrapping internal DAO implements.
|
||||
type internalUser2Dao = *internal.User2Dao
|
||||
|
||||
// user2Dao is the data access object for table user2.
|
||||
// You can define custom methods on it to extend its functionality as you wish.
|
||||
type user2Dao struct {
|
||||
internalUser2Dao
|
||||
}
|
||||
|
||||
var (
|
||||
// User2 is globally public accessible object for table user2 operations.
|
||||
User2 = user2Dao{
|
||||
internal.NewUser2Dao(),
|
||||
}
|
||||
)
|
||||
|
||||
// Fill with you ideas below.
|
||||
27
cmd/gf/internal/cmd/testdata/issue/2616/dao/user_3.go
vendored
Normal file
27
cmd/gf/internal/cmd/testdata/issue/2616/dao/user_3.go
vendored
Normal file
@ -0,0 +1,27 @@
|
||||
// =================================================================================
|
||||
// This is auto-generated by GoFrame CLI tool only once. Fill this file as you wish.
|
||||
// =================================================================================
|
||||
|
||||
package dao
|
||||
|
||||
import (
|
||||
"/internal"
|
||||
)
|
||||
|
||||
// internalUser3Dao is internal type for wrapping internal DAO implements.
|
||||
type internalUser3Dao = *internal.User3Dao
|
||||
|
||||
// user3Dao is the data access object for table user3.
|
||||
// You can define custom methods on it to extend its functionality as you wish.
|
||||
type user3Dao struct {
|
||||
internalUser3Dao
|
||||
}
|
||||
|
||||
var (
|
||||
// User3 is globally public accessible object for table user3 operations.
|
||||
User3 = user3Dao{
|
||||
internal.NewUser3Dao(),
|
||||
}
|
||||
)
|
||||
|
||||
// Fill with you ideas below.
|
||||
27
cmd/gf/internal/cmd/testdata/issue/2616/dao/user_4.go
vendored
Normal file
27
cmd/gf/internal/cmd/testdata/issue/2616/dao/user_4.go
vendored
Normal file
@ -0,0 +1,27 @@
|
||||
// =================================================================================
|
||||
// This is auto-generated by GoFrame CLI tool only once. Fill this file as you wish.
|
||||
// =================================================================================
|
||||
|
||||
package dao
|
||||
|
||||
import (
|
||||
"/internal"
|
||||
)
|
||||
|
||||
// internalUser4Dao is internal type for wrapping internal DAO implements.
|
||||
type internalUser4Dao = *internal.User4Dao
|
||||
|
||||
// user4Dao is the data access object for table user4.
|
||||
// You can define custom methods on it to extend its functionality as you wish.
|
||||
type user4Dao struct {
|
||||
internalUser4Dao
|
||||
}
|
||||
|
||||
var (
|
||||
// User4 is globally public accessible object for table user4 operations.
|
||||
User4 = user4Dao{
|
||||
internal.NewUser4Dao(),
|
||||
}
|
||||
)
|
||||
|
||||
// Fill with you ideas below.
|
||||
22
cmd/gf/internal/cmd/testdata/issue/2616/model/do/user_3.go
vendored
Normal file
22
cmd/gf/internal/cmd/testdata/issue/2616/model/do/user_3.go
vendored
Normal file
@ -0,0 +1,22 @@
|
||||
// =================================================================================
|
||||
// Code generated and maintained by GoFrame CLI tool. DO NOT EDIT.
|
||||
// =================================================================================
|
||||
|
||||
package do
|
||||
|
||||
import (
|
||||
"github.com/gogf/gf/v2/frame/g"
|
||||
"github.com/gogf/gf/v2/os/gtime"
|
||||
)
|
||||
|
||||
// User1 is the golang structure of table user1 for DAO operations like Where/Data.
|
||||
type User1 struct {
|
||||
g.Meta `orm:"table:user1, do:true"`
|
||||
Id interface{} // User ID
|
||||
Passport interface{} // User Passport
|
||||
Password interface{} // User Password
|
||||
Nickname interface{} // User Nickname
|
||||
Score interface{} // Total score amount.
|
||||
CreateAt *gtime.Time // Created Time
|
||||
UpdateAt *gtime.Time // Updated Time
|
||||
}
|
||||
22
cmd/gf/internal/cmd/testdata/issue/2616/model/do/user_4.go
vendored
Normal file
22
cmd/gf/internal/cmd/testdata/issue/2616/model/do/user_4.go
vendored
Normal file
@ -0,0 +1,22 @@
|
||||
// =================================================================================
|
||||
// Code generated and maintained by GoFrame CLI tool. DO NOT EDIT.
|
||||
// =================================================================================
|
||||
|
||||
package do
|
||||
|
||||
import (
|
||||
"github.com/gogf/gf/v2/frame/g"
|
||||
"github.com/gogf/gf/v2/os/gtime"
|
||||
)
|
||||
|
||||
// User2 is the golang structure of table user2 for DAO operations like Where/Data.
|
||||
type User2 struct {
|
||||
g.Meta `orm:"table:user2, do:true"`
|
||||
Id interface{} // User ID
|
||||
Passport interface{} // User Passport
|
||||
Password interface{} // User Password
|
||||
Nickname interface{} // User Nickname
|
||||
Score interface{} // Total score amount.
|
||||
CreateAt *gtime.Time // Created Time
|
||||
UpdateAt *gtime.Time // Updated Time
|
||||
}
|
||||
20
cmd/gf/internal/cmd/testdata/issue/2616/model/entity/user_3.go
vendored
Normal file
20
cmd/gf/internal/cmd/testdata/issue/2616/model/entity/user_3.go
vendored
Normal file
@ -0,0 +1,20 @@
|
||||
// =================================================================================
|
||||
// Code generated and maintained by GoFrame CLI tool. DO NOT EDIT.
|
||||
// =================================================================================
|
||||
|
||||
package entity
|
||||
|
||||
import (
|
||||
"github.com/gogf/gf/v2/os/gtime"
|
||||
)
|
||||
|
||||
// User1 is the golang structure for table user1.
|
||||
type User1 struct {
|
||||
Id uint `json:"ID" description:"User ID"`
|
||||
Passport string `json:"PASSPORT" description:"User Passport"`
|
||||
Password string `json:"PASSWORD" description:"User Password"`
|
||||
Nickname string `json:"NICKNAME" description:"User Nickname"`
|
||||
Score float64 `json:"SCORE" description:"Total score amount."`
|
||||
CreateAt *gtime.Time `json:"CREATE_AT" description:"Created Time"`
|
||||
UpdateAt *gtime.Time `json:"UPDATE_AT" description:"Updated Time"`
|
||||
}
|
||||
20
cmd/gf/internal/cmd/testdata/issue/2616/model/entity/user_4.go
vendored
Normal file
20
cmd/gf/internal/cmd/testdata/issue/2616/model/entity/user_4.go
vendored
Normal file
@ -0,0 +1,20 @@
|
||||
// =================================================================================
|
||||
// Code generated and maintained by GoFrame CLI tool. DO NOT EDIT.
|
||||
// =================================================================================
|
||||
|
||||
package entity
|
||||
|
||||
import (
|
||||
"github.com/gogf/gf/v2/os/gtime"
|
||||
)
|
||||
|
||||
// User2 is the golang structure for table user2.
|
||||
type User2 struct {
|
||||
Id uint `json:"ID" description:"User ID"`
|
||||
Passport string `json:"PASSPORT" description:"User Passport"`
|
||||
Password string `json:"PASSWORD" description:"User Password"`
|
||||
Nickname string `json:"NICKNAME" description:"User Nickname"`
|
||||
Score float64 `json:"SCORE" description:"Total score amount."`
|
||||
CreateAt *gtime.Time `json:"CREATE_AT" description:"Created Time"`
|
||||
UpdateAt *gtime.Time `json:"UPDATE_AT" description:"Updated Time"`
|
||||
}
|
||||
10
cmd/gf/internal/cmd/testdata/issue/2616/sql1.sql
vendored
Normal file
10
cmd/gf/internal/cmd/testdata/issue/2616/sql1.sql
vendored
Normal file
@ -0,0 +1,10 @@
|
||||
CREATE TABLE `user1` (
|
||||
`id` int unsigned NOT NULL AUTO_INCREMENT COMMENT 'User ID',
|
||||
`passport` varchar(45) NOT NULL COMMENT 'User Passport',
|
||||
`password` varchar(45) NOT NULL COMMENT 'User Password',
|
||||
`nickname` varchar(45) NOT NULL COMMENT 'User Nickname',
|
||||
`score` decimal(10,2) unsigned DEFAULT NULL COMMENT 'Total score amount.',
|
||||
`create_at` datetime DEFAULT NULL COMMENT 'Created Time',
|
||||
`update_at` datetime DEFAULT NULL COMMENT 'Updated Time',
|
||||
PRIMARY KEY (`id`)
|
||||
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
|
||||
10
cmd/gf/internal/cmd/testdata/issue/2616/sql2.sql
vendored
Normal file
10
cmd/gf/internal/cmd/testdata/issue/2616/sql2.sql
vendored
Normal file
@ -0,0 +1,10 @@
|
||||
CREATE TABLE `user2` (
|
||||
`id` int unsigned NOT NULL AUTO_INCREMENT COMMENT 'User ID',
|
||||
`passport` varchar(45) NOT NULL COMMENT 'User Passport',
|
||||
`password` varchar(45) NOT NULL COMMENT 'User Password',
|
||||
`nickname` varchar(45) NOT NULL COMMENT 'User Nickname',
|
||||
`score` decimal(10,2) unsigned DEFAULT NULL COMMENT 'Total score amount.',
|
||||
`create_at` datetime DEFAULT NULL COMMENT 'Created Time',
|
||||
`update_at` datetime DEFAULT NULL COMMENT 'Updated Time',
|
||||
PRIMARY KEY (`id`)
|
||||
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
|
||||
@ -4,7 +4,7 @@ go 1.18
|
||||
|
||||
require (
|
||||
github.com/apolloconfig/agollo/v4 v4.3.1
|
||||
github.com/gogf/gf/v2 v2.6.2
|
||||
github.com/gogf/gf/v2 v2.6.3
|
||||
)
|
||||
|
||||
require (
|
||||
|
||||
@ -3,7 +3,7 @@ module github.com/gogf/gf/contrib/config/consul/v2
|
||||
go 1.19
|
||||
|
||||
require (
|
||||
github.com/gogf/gf/v2 v2.6.2
|
||||
github.com/gogf/gf/v2 v2.6.3
|
||||
github.com/hashicorp/consul/api v1.24.0
|
||||
github.com/hashicorp/go-cleanhttp v0.5.2
|
||||
)
|
||||
|
||||
@ -3,7 +3,7 @@ module github.com/gogf/gf/contrib/config/kubecm/v2
|
||||
go 1.19
|
||||
|
||||
require (
|
||||
github.com/gogf/gf/v2 v2.6.2
|
||||
github.com/gogf/gf/v2 v2.6.3
|
||||
k8s.io/api v0.27.4
|
||||
k8s.io/apimachinery v0.27.4
|
||||
k8s.io/client-go v0.27.4
|
||||
|
||||
@ -3,7 +3,7 @@ module github.com/gogf/gf/contrib/config/nacos/v2
|
||||
go 1.18
|
||||
|
||||
require (
|
||||
github.com/gogf/gf/v2 v2.6.2
|
||||
github.com/gogf/gf/v2 v2.6.3
|
||||
github.com/nacos-group/nacos-sdk-go v1.1.4
|
||||
)
|
||||
|
||||
|
||||
@ -3,7 +3,7 @@ module github.com/gogf/gf/contrib/config/polaris/v2
|
||||
go 1.18
|
||||
|
||||
require (
|
||||
github.com/gogf/gf/v2 v2.6.2
|
||||
github.com/gogf/gf/v2 v2.6.3
|
||||
github.com/polarismesh/polaris-go v1.5.5
|
||||
)
|
||||
|
||||
|
||||
@ -9,25 +9,10 @@ package clickhouse
|
||||
|
||||
import (
|
||||
"context"
|
||||
"database/sql"
|
||||
"database/sql/driver"
|
||||
"errors"
|
||||
"fmt"
|
||||
"net/url"
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
"github.com/ClickHouse/clickhouse-go/v2"
|
||||
"github.com/google/uuid"
|
||||
"github.com/shopspring/decimal"
|
||||
|
||||
"github.com/gogf/gf/v2/database/gdb"
|
||||
"github.com/gogf/gf/v2/errors/gcode"
|
||||
"github.com/gogf/gf/v2/errors/gerror"
|
||||
"github.com/gogf/gf/v2/os/gctx"
|
||||
"github.com/gogf/gf/v2/os/gtime"
|
||||
"github.com/gogf/gf/v2/text/gregex"
|
||||
"github.com/gogf/gf/v2/util/gutil"
|
||||
)
|
||||
|
||||
// Driver is the driver for postgresql database.
|
||||
@ -71,386 +56,9 @@ func (d *Driver) New(core *gdb.Core, node *gdb.ConfigNode) (gdb.DB, error) {
|
||||
}, nil
|
||||
}
|
||||
|
||||
// Open creates and returns an underlying sql.DB object for clickhouse.
|
||||
func (d *Driver) Open(config *gdb.ConfigNode) (db *sql.DB, err error) {
|
||||
source := config.Link
|
||||
// clickhouse://username:password@host1:9000,host2:9000/database?dial_timeout=200ms&max_execution_time=60
|
||||
if config.Link != "" {
|
||||
// ============================================================================
|
||||
// Deprecated from v2.2.0.
|
||||
// ============================================================================
|
||||
// Custom changing the schema in runtime.
|
||||
if config.Name != "" {
|
||||
source, _ = gregex.ReplaceString(replaceSchemaPattern, "@$1/"+config.Name, config.Link)
|
||||
} else {
|
||||
// If no schema, the link is matched for replacement
|
||||
dbName, _ := gregex.MatchString(replaceSchemaPattern, config.Link)
|
||||
if len(dbName) > 0 {
|
||||
config.Name = dbName[len(dbName)-1]
|
||||
}
|
||||
}
|
||||
} else {
|
||||
if config.Pass != "" {
|
||||
source = fmt.Sprintf(
|
||||
"clickhouse://%s:%s@%s:%s/%s?debug=%t",
|
||||
config.User, url.PathEscape(config.Pass),
|
||||
config.Host, config.Port, config.Name, config.Debug,
|
||||
)
|
||||
} else {
|
||||
source = fmt.Sprintf(
|
||||
"clickhouse://%s@%s:%s/%s?debug=%t",
|
||||
config.User, config.Host, config.Port, config.Name, config.Debug,
|
||||
)
|
||||
}
|
||||
if config.Extra != "" {
|
||||
source = fmt.Sprintf("%s&%s", source, config.Extra)
|
||||
}
|
||||
}
|
||||
if db, err = sql.Open(driverName, source); err != nil {
|
||||
err = gerror.WrapCodef(
|
||||
gcode.CodeDbOperationError, err,
|
||||
`sql.Open failed for driver "%s" by source "%s"`, driverName, source,
|
||||
)
|
||||
return nil, err
|
||||
}
|
||||
return
|
||||
}
|
||||
|
||||
// Tables retrieves and returns the tables of current schema.
|
||||
// It's mainly used in cli tool chain for automatically generating the models.
|
||||
func (d *Driver) Tables(ctx context.Context, schema ...string) (tables []string, err error) {
|
||||
var result gdb.Result
|
||||
link, err := d.SlaveLink(schema...)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
query := fmt.Sprintf("select name from `system`.tables where database = '%s'", d.GetConfig().Name)
|
||||
result, err = d.DoSelect(ctx, link, query)
|
||||
if err != nil {
|
||||
return
|
||||
}
|
||||
for _, m := range result {
|
||||
tables = append(tables, m["name"].String())
|
||||
}
|
||||
return
|
||||
}
|
||||
|
||||
// TableFields retrieves and returns the fields' information of specified table of current schema.
|
||||
// Also see DriverMysql.TableFields.
|
||||
func (d *Driver) TableFields(ctx context.Context, table string, schema ...string) (fields map[string]*gdb.TableField, err error) {
|
||||
var (
|
||||
result gdb.Result
|
||||
link gdb.Link
|
||||
usedSchema = gutil.GetOrDefaultStr(d.GetSchema(), schema...)
|
||||
)
|
||||
if link, err = d.SlaveLink(usedSchema); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
var (
|
||||
columns = "name,position,default_expression,comment,type,is_in_partition_key,is_in_sorting_key,is_in_primary_key,is_in_sampling_key"
|
||||
getColumnsSql = fmt.Sprintf(
|
||||
"select %s from `system`.columns c where `table` = '%s'",
|
||||
columns, table,
|
||||
)
|
||||
)
|
||||
result, err = d.DoSelect(ctx, link, getColumnsSql)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
fields = make(map[string]*gdb.TableField)
|
||||
for _, m := range result {
|
||||
var (
|
||||
isNull = false
|
||||
fieldType = m["type"].String()
|
||||
)
|
||||
// in clickhouse , field type like is Nullable(int)
|
||||
fieldsResult, _ := gregex.MatchString(`^Nullable\((.*?)\)`, fieldType)
|
||||
if len(fieldsResult) == 2 {
|
||||
isNull = true
|
||||
fieldType = fieldsResult[1]
|
||||
}
|
||||
position := m["position"].Int()
|
||||
if result[0]["position"].Int() != 0 {
|
||||
position -= 1
|
||||
}
|
||||
fields[m["name"].String()] = &gdb.TableField{
|
||||
Index: position,
|
||||
Name: m["name"].String(),
|
||||
Default: m["default_expression"].Val(),
|
||||
Comment: m["comment"].String(),
|
||||
// Key: m["Key"].String(),
|
||||
Type: fieldType,
|
||||
Null: isNull,
|
||||
}
|
||||
}
|
||||
return fields, nil
|
||||
}
|
||||
|
||||
// PingMaster pings the master node to check authentication or keeps the connection alive.
|
||||
func (d *Driver) PingMaster() error {
|
||||
conn, err := d.Master()
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
return d.ping(conn)
|
||||
}
|
||||
|
||||
// PingSlave pings the slave node to check authentication or keeps the connection alive.
|
||||
func (d *Driver) PingSlave() error {
|
||||
conn, err := d.Slave()
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
return d.ping(conn)
|
||||
}
|
||||
|
||||
// ping Returns the Clickhouse specific error.
|
||||
func (d *Driver) ping(conn *sql.DB) error {
|
||||
err := conn.Ping()
|
||||
if exception, ok := err.(*clickhouse.Exception); ok {
|
||||
return fmt.Errorf("[%d]%s", exception.Code, exception.Message)
|
||||
}
|
||||
return err
|
||||
}
|
||||
|
||||
// DoFilter handles the sql before posts it to database.
|
||||
func (d *Driver) DoFilter(
|
||||
ctx context.Context, link gdb.Link, originSql string, args []interface{},
|
||||
) (newSql string, newArgs []interface{}, err error) {
|
||||
if len(args) == 0 {
|
||||
return originSql, args, nil
|
||||
}
|
||||
// Convert placeholder char '?' to string "$x".
|
||||
var index int
|
||||
originSql, _ = gregex.ReplaceStringFunc(`\?`, originSql, func(s string) string {
|
||||
index++
|
||||
return fmt.Sprintf(`$%d`, index)
|
||||
})
|
||||
|
||||
// Only SQL generated through the framework is processed.
|
||||
if !d.getNeedParsedSqlFromCtx(ctx) {
|
||||
return originSql, args, nil
|
||||
}
|
||||
|
||||
// replace STD SQL to Clickhouse SQL grammar
|
||||
modeRes, err := gregex.MatchString(filterTypePattern, strings.TrimSpace(originSql))
|
||||
if err != nil {
|
||||
return "", nil, err
|
||||
}
|
||||
if len(modeRes) == 0 {
|
||||
return originSql, args, nil
|
||||
}
|
||||
|
||||
// Only delete/ UPDATE statements require filter
|
||||
switch strings.ToUpper(modeRes[0]) {
|
||||
case "UPDATE":
|
||||
// MySQL eg: UPDATE table_name SET field1=new-value1, field2=new-value2 [WHERE Clause]
|
||||
// Clickhouse eg: ALTER TABLE [db.]table UPDATE column1 = expr1 [, ...] WHERE filter_expr
|
||||
newSql, err = gregex.ReplaceStringFuncMatch(
|
||||
updateFilterPattern, originSql,
|
||||
func(s []string) string {
|
||||
return fmt.Sprintf("ALTER TABLE %s UPDATE", s[1])
|
||||
},
|
||||
)
|
||||
if err != nil {
|
||||
return "", nil, err
|
||||
}
|
||||
return newSql, args, nil
|
||||
|
||||
case "DELETE":
|
||||
// MySQL eg: DELETE FROM table_name [WHERE Clause]
|
||||
// Clickhouse eg: ALTER TABLE [db.]table [ON CLUSTER cluster] DELETE WHERE filter_expr
|
||||
newSql, err = gregex.ReplaceStringFuncMatch(
|
||||
deleteFilterPattern, originSql,
|
||||
func(s []string) string {
|
||||
return fmt.Sprintf("ALTER TABLE %s DELETE", s[1])
|
||||
},
|
||||
)
|
||||
if err != nil {
|
||||
return "", nil, err
|
||||
}
|
||||
return newSql, args, nil
|
||||
|
||||
}
|
||||
return originSql, args, nil
|
||||
}
|
||||
|
||||
// DoCommit commits current sql and arguments to underlying sql driver.
|
||||
func (d *Driver) DoCommit(ctx context.Context, in gdb.DoCommitInput) (out gdb.DoCommitOutput, err error) {
|
||||
ctx = d.InjectIgnoreResult(ctx)
|
||||
return d.Core.DoCommit(ctx, in)
|
||||
}
|
||||
|
||||
// DoInsert inserts or updates data forF 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) {
|
||||
var (
|
||||
keys []string // Field names.
|
||||
valueHolder = make([]string, 0)
|
||||
)
|
||||
// Handle the field names and placeholders.
|
||||
for k := range list[0] {
|
||||
keys = append(keys, k)
|
||||
valueHolder = append(valueHolder, "?")
|
||||
}
|
||||
// Prepare the batch result pointer.
|
||||
var (
|
||||
charL, charR = d.Core.GetChars()
|
||||
keysStr = charL + strings.Join(keys, charR+","+charL) + charR
|
||||
holderStr = strings.Join(valueHolder, ",")
|
||||
tx gdb.TX
|
||||
stmt *gdb.Stmt
|
||||
)
|
||||
tx, err = d.Core.Begin(ctx)
|
||||
if err != nil {
|
||||
return
|
||||
}
|
||||
// It here uses defer to guarantee transaction be committed or roll-backed.
|
||||
defer func() {
|
||||
if err == nil {
|
||||
_ = tx.Commit()
|
||||
} else {
|
||||
_ = tx.Rollback()
|
||||
}
|
||||
}()
|
||||
stmt, err = tx.Prepare(fmt.Sprintf(
|
||||
"INSERT INTO %s(%s) VALUES (%s)",
|
||||
d.QuotePrefixTableName(table), keysStr,
|
||||
holderStr,
|
||||
))
|
||||
if err != nil {
|
||||
return
|
||||
}
|
||||
for i := 0; i < len(list); i++ {
|
||||
// Values that will be committed to underlying database driver.
|
||||
params := make([]interface{}, 0)
|
||||
for _, k := range keys {
|
||||
params = append(params, list[i][k])
|
||||
}
|
||||
// Prepare is allowed to execute only once in a transaction opened by clickhouse
|
||||
result, err = stmt.ExecContext(ctx, params...)
|
||||
if err != nil {
|
||||
return
|
||||
}
|
||||
}
|
||||
return
|
||||
}
|
||||
|
||||
// ConvertValueForField converts value to the type of the record field.
|
||||
func (d *Driver) ConvertValueForField(ctx context.Context, fieldType string, fieldValue interface{}) (interface{}, error) {
|
||||
switch itemValue := fieldValue.(type) {
|
||||
case time.Time:
|
||||
// If the time is zero, it then updates it to nil,
|
||||
// which will insert/update the value to database as "null".
|
||||
if itemValue.IsZero() {
|
||||
return nil, nil
|
||||
}
|
||||
|
||||
case uuid.UUID:
|
||||
return itemValue, nil
|
||||
|
||||
case *time.Time:
|
||||
// If the time is zero, it then updates it to nil,
|
||||
// which will insert/update the value to database as "null".
|
||||
if itemValue == nil || itemValue.IsZero() {
|
||||
return nil, nil
|
||||
}
|
||||
return itemValue, nil
|
||||
|
||||
case gtime.Time:
|
||||
// If the time is zero, it then updates it to nil,
|
||||
// which will insert/update the value to database as "null".
|
||||
if itemValue.IsZero() {
|
||||
return nil, nil
|
||||
}
|
||||
// for gtime type, needs to get time.Time
|
||||
return itemValue.Time, nil
|
||||
|
||||
case *gtime.Time:
|
||||
// for gtime type, needs to get time.Time
|
||||
if itemValue != nil {
|
||||
return itemValue.Time, nil
|
||||
}
|
||||
// If the time is zero, it then updates it to nil,
|
||||
// which will insert/update the value to database as "null".
|
||||
if itemValue == nil || itemValue.IsZero() {
|
||||
return nil, nil
|
||||
}
|
||||
|
||||
case decimal.Decimal:
|
||||
return itemValue, nil
|
||||
|
||||
case *decimal.Decimal:
|
||||
if itemValue != nil {
|
||||
return *itemValue, nil
|
||||
}
|
||||
return nil, nil
|
||||
|
||||
default:
|
||||
// if the other type implements valuer for the driver package
|
||||
// the converted result is used
|
||||
// otherwise the interface data is committed
|
||||
valuer, ok := itemValue.(driver.Valuer)
|
||||
if !ok {
|
||||
return itemValue, nil
|
||||
}
|
||||
convertedValue, err := valuer.Value()
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return convertedValue, nil
|
||||
}
|
||||
return fieldValue, nil
|
||||
}
|
||||
|
||||
// DoDelete does "DELETE FROM ... " statement for the table.
|
||||
func (d *Driver) DoDelete(ctx context.Context, link gdb.Link, table string, condition string, args ...interface{}) (result sql.Result, err error) {
|
||||
ctx = d.injectNeedParsedSql(ctx)
|
||||
return d.Core.DoDelete(ctx, link, table, condition, args...)
|
||||
}
|
||||
|
||||
// DoUpdate does "UPDATE ... " statement for the table.
|
||||
func (d *Driver) DoUpdate(ctx context.Context, link gdb.Link, table string, data interface{}, condition string, args ...interface{}) (result sql.Result, err error) {
|
||||
ctx = d.injectNeedParsedSql(ctx)
|
||||
return d.Core.DoUpdate(ctx, link, table, data, condition, args...)
|
||||
}
|
||||
|
||||
// InsertIgnore Other queries for modifying data parts are not supported: REPLACE, MERGE, UPSERT, INSERT UPDATE.
|
||||
func (d *Driver) InsertIgnore(ctx context.Context, table string, data interface{}, batch ...int) (sql.Result, error) {
|
||||
return nil, errUnsupportedInsertIgnore
|
||||
}
|
||||
|
||||
// InsertAndGetId Other queries for modifying data parts are not supported: REPLACE, MERGE, UPSERT, INSERT UPDATE.
|
||||
func (d *Driver) InsertAndGetId(ctx context.Context, table string, data interface{}, batch ...int) (int64, error) {
|
||||
return 0, errUnsupportedInsertGetId
|
||||
}
|
||||
|
||||
// Replace Other queries for modifying data parts are not supported: REPLACE, MERGE, UPSERT, INSERT UPDATE.
|
||||
func (d *Driver) Replace(ctx context.Context, table string, data interface{}, batch ...int) (sql.Result, error) {
|
||||
return nil, errUnsupportedReplace
|
||||
}
|
||||
|
||||
// Begin starts and returns the transaction object.
|
||||
func (d *Driver) Begin(ctx context.Context) (tx gdb.TX, err error) {
|
||||
return nil, errUnsupportedBegin
|
||||
}
|
||||
|
||||
// Transaction wraps the transaction logic using function `f`.
|
||||
func (d *Driver) Transaction(ctx context.Context, f func(ctx context.Context, tx gdb.TX) error) error {
|
||||
return errUnsupportedTransaction
|
||||
}
|
||||
|
||||
func (d *Driver) injectNeedParsedSql(ctx context.Context) context.Context {
|
||||
if ctx.Value(needParsedSqlInCtx) != nil {
|
||||
return ctx
|
||||
}
|
||||
return context.WithValue(ctx, needParsedSqlInCtx, true)
|
||||
}
|
||||
|
||||
func (d *Driver) getNeedParsedSqlFromCtx(ctx context.Context) bool {
|
||||
if ctx.Value(needParsedSqlInCtx) != nil {
|
||||
return true
|
||||
}
|
||||
return false
|
||||
}
|
||||
|
||||
85
contrib/drivers/clickhouse/clickhouse_convert.go
Normal file
85
contrib/drivers/clickhouse/clickhouse_convert.go
Normal file
@ -0,0 +1,85 @@
|
||||
// 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 clickhouse
|
||||
|
||||
import (
|
||||
"context"
|
||||
"database/sql/driver"
|
||||
"time"
|
||||
|
||||
"github.com/google/uuid"
|
||||
"github.com/shopspring/decimal"
|
||||
|
||||
"github.com/gogf/gf/v2/os/gtime"
|
||||
)
|
||||
|
||||
// ConvertValueForField converts value to the type of the record field.
|
||||
func (d *Driver) ConvertValueForField(ctx context.Context, fieldType string, fieldValue interface{}) (interface{}, error) {
|
||||
switch itemValue := fieldValue.(type) {
|
||||
case time.Time:
|
||||
// If the time is zero, it then updates it to nil,
|
||||
// which will insert/update the value to database as "null".
|
||||
if itemValue.IsZero() {
|
||||
return nil, nil
|
||||
}
|
||||
|
||||
case uuid.UUID:
|
||||
return itemValue, nil
|
||||
|
||||
case *time.Time:
|
||||
// If the time is zero, it then updates it to nil,
|
||||
// which will insert/update the value to database as "null".
|
||||
if itemValue == nil || itemValue.IsZero() {
|
||||
return nil, nil
|
||||
}
|
||||
return itemValue, nil
|
||||
|
||||
case gtime.Time:
|
||||
// If the time is zero, it then updates it to nil,
|
||||
// which will insert/update the value to database as "null".
|
||||
if itemValue.IsZero() {
|
||||
return nil, nil
|
||||
}
|
||||
// for gtime type, needs to get time.Time
|
||||
return itemValue.Time, nil
|
||||
|
||||
case *gtime.Time:
|
||||
// for gtime type, needs to get time.Time
|
||||
if itemValue != nil {
|
||||
return itemValue.Time, nil
|
||||
}
|
||||
// If the time is zero, it then updates it to nil,
|
||||
// which will insert/update the value to database as "null".
|
||||
if itemValue == nil || itemValue.IsZero() {
|
||||
return nil, nil
|
||||
}
|
||||
|
||||
case decimal.Decimal:
|
||||
return itemValue, nil
|
||||
|
||||
case *decimal.Decimal:
|
||||
if itemValue != nil {
|
||||
return *itemValue, nil
|
||||
}
|
||||
return nil, nil
|
||||
|
||||
default:
|
||||
// if the other type implements valuer for the driver package
|
||||
// the converted result is used
|
||||
// otherwise the interface data is committed
|
||||
valuer, ok := itemValue.(driver.Valuer)
|
||||
if !ok {
|
||||
return itemValue, nil
|
||||
}
|
||||
convertedValue, err := valuer.Value()
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return convertedValue, nil
|
||||
}
|
||||
return fieldValue, nil
|
||||
}
|
||||
19
contrib/drivers/clickhouse/clickhouse_do_commit.go
Normal file
19
contrib/drivers/clickhouse/clickhouse_do_commit.go
Normal file
@ -0,0 +1,19 @@
|
||||
// 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 clickhouse
|
||||
|
||||
import (
|
||||
"context"
|
||||
|
||||
"github.com/gogf/gf/v2/database/gdb"
|
||||
)
|
||||
|
||||
// DoCommit commits current sql and arguments to underlying sql driver.
|
||||
func (d *Driver) DoCommit(ctx context.Context, in gdb.DoCommitInput) (out gdb.DoCommitOutput, err error) {
|
||||
ctx = d.InjectIgnoreResult(ctx)
|
||||
return d.Core.DoCommit(ctx, in)
|
||||
}
|
||||
20
contrib/drivers/clickhouse/clickhouse_do_delete.go
Normal file
20
contrib/drivers/clickhouse/clickhouse_do_delete.go
Normal file
@ -0,0 +1,20 @@
|
||||
// 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 clickhouse
|
||||
|
||||
import (
|
||||
"context"
|
||||
"database/sql"
|
||||
|
||||
"github.com/gogf/gf/v2/database/gdb"
|
||||
)
|
||||
|
||||
// DoDelete does "DELETE FROM ... " statement for the table.
|
||||
func (d *Driver) DoDelete(ctx context.Context, link gdb.Link, table string, condition string, args ...interface{}) (result sql.Result, err error) {
|
||||
ctx = d.injectNeedParsedSql(ctx)
|
||||
return d.Core.DoDelete(ctx, link, table, condition, args...)
|
||||
}
|
||||
85
contrib/drivers/clickhouse/clickhouse_do_filter.go
Normal file
85
contrib/drivers/clickhouse/clickhouse_do_filter.go
Normal file
@ -0,0 +1,85 @@
|
||||
// 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 clickhouse
|
||||
|
||||
import (
|
||||
"context"
|
||||
"fmt"
|
||||
"strings"
|
||||
|
||||
"github.com/gogf/gf/v2/database/gdb"
|
||||
"github.com/gogf/gf/v2/text/gregex"
|
||||
)
|
||||
|
||||
// DoFilter handles the sql before posts it to database.
|
||||
func (d *Driver) DoFilter(
|
||||
ctx context.Context, link gdb.Link, originSql string, args []interface{},
|
||||
) (newSql string, newArgs []interface{}, err error) {
|
||||
if len(args) == 0 {
|
||||
return originSql, args, nil
|
||||
}
|
||||
// Convert placeholder char '?' to string "$x".
|
||||
var index int
|
||||
originSql, _ = gregex.ReplaceStringFunc(`\?`, originSql, func(s string) string {
|
||||
index++
|
||||
return fmt.Sprintf(`$%d`, index)
|
||||
})
|
||||
|
||||
// Only SQL generated through the framework is processed.
|
||||
if !d.getNeedParsedSqlFromCtx(ctx) {
|
||||
return originSql, args, nil
|
||||
}
|
||||
|
||||
// replace STD SQL to Clickhouse SQL grammar
|
||||
modeRes, err := gregex.MatchString(filterTypePattern, strings.TrimSpace(originSql))
|
||||
if err != nil {
|
||||
return "", nil, err
|
||||
}
|
||||
if len(modeRes) == 0 {
|
||||
return originSql, args, nil
|
||||
}
|
||||
|
||||
// Only delete/ UPDATE statements require filter
|
||||
switch strings.ToUpper(modeRes[0]) {
|
||||
case "UPDATE":
|
||||
// MySQL eg: UPDATE table_name SET field1=new-value1, field2=new-value2 [WHERE Clause]
|
||||
// Clickhouse eg: ALTER TABLE [db.]table UPDATE column1 = expr1 [, ...] WHERE filter_expr
|
||||
newSql, err = gregex.ReplaceStringFuncMatch(
|
||||
updateFilterPattern, originSql,
|
||||
func(s []string) string {
|
||||
return fmt.Sprintf("ALTER TABLE %s UPDATE", s[1])
|
||||
},
|
||||
)
|
||||
if err != nil {
|
||||
return "", nil, err
|
||||
}
|
||||
return newSql, args, nil
|
||||
|
||||
case "DELETE":
|
||||
// MySQL eg: DELETE FROM table_name [WHERE Clause]
|
||||
// Clickhouse eg: ALTER TABLE [db.]table [ON CLUSTER cluster] DELETE WHERE filter_expr
|
||||
newSql, err = gregex.ReplaceStringFuncMatch(
|
||||
deleteFilterPattern, originSql,
|
||||
func(s []string) string {
|
||||
return fmt.Sprintf("ALTER TABLE %s DELETE", s[1])
|
||||
},
|
||||
)
|
||||
if err != nil {
|
||||
return "", nil, err
|
||||
}
|
||||
return newSql, args, nil
|
||||
|
||||
}
|
||||
return originSql, args, nil
|
||||
}
|
||||
|
||||
func (d *Driver) getNeedParsedSqlFromCtx(ctx context.Context) bool {
|
||||
if ctx.Value(needParsedSqlInCtx) != nil {
|
||||
return true
|
||||
}
|
||||
return false
|
||||
}
|
||||
72
contrib/drivers/clickhouse/clickhouse_do_insert.go
Normal file
72
contrib/drivers/clickhouse/clickhouse_do_insert.go
Normal file
@ -0,0 +1,72 @@
|
||||
// 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 clickhouse
|
||||
|
||||
import (
|
||||
"context"
|
||||
"database/sql"
|
||||
"fmt"
|
||||
"strings"
|
||||
|
||||
"github.com/gogf/gf/v2/database/gdb"
|
||||
)
|
||||
|
||||
// DoInsert inserts or updates data forF 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) {
|
||||
var (
|
||||
keys []string // Field names.
|
||||
valueHolder = make([]string, 0)
|
||||
)
|
||||
// Handle the field names and placeholders.
|
||||
for k := range list[0] {
|
||||
keys = append(keys, k)
|
||||
valueHolder = append(valueHolder, "?")
|
||||
}
|
||||
// Prepare the batch result pointer.
|
||||
var (
|
||||
charL, charR = d.Core.GetChars()
|
||||
keysStr = charL + strings.Join(keys, charR+","+charL) + charR
|
||||
holderStr = strings.Join(valueHolder, ",")
|
||||
tx gdb.TX
|
||||
stmt *gdb.Stmt
|
||||
)
|
||||
tx, err = d.Core.Begin(ctx)
|
||||
if err != nil {
|
||||
return
|
||||
}
|
||||
// It here uses defer to guarantee transaction be committed or roll-backed.
|
||||
defer func() {
|
||||
if err == nil {
|
||||
_ = tx.Commit()
|
||||
} else {
|
||||
_ = tx.Rollback()
|
||||
}
|
||||
}()
|
||||
stmt, err = tx.Prepare(fmt.Sprintf(
|
||||
"INSERT INTO %s(%s) VALUES (%s)",
|
||||
d.QuotePrefixTableName(table), keysStr,
|
||||
holderStr,
|
||||
))
|
||||
if err != nil {
|
||||
return
|
||||
}
|
||||
for i := 0; i < len(list); i++ {
|
||||
// Values that will be committed to underlying database driver.
|
||||
params := make([]interface{}, 0)
|
||||
for _, k := range keys {
|
||||
params = append(params, list[i][k])
|
||||
}
|
||||
// Prepare is allowed to execute only once in a transaction opened by clickhouse
|
||||
result, err = stmt.ExecContext(ctx, params...)
|
||||
if err != nil {
|
||||
return
|
||||
}
|
||||
}
|
||||
return
|
||||
}
|
||||
20
contrib/drivers/clickhouse/clickhouse_do_update.go
Normal file
20
contrib/drivers/clickhouse/clickhouse_do_update.go
Normal file
@ -0,0 +1,20 @@
|
||||
// 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 clickhouse
|
||||
|
||||
import (
|
||||
"context"
|
||||
"database/sql"
|
||||
|
||||
"github.com/gogf/gf/v2/database/gdb"
|
||||
)
|
||||
|
||||
// DoUpdate does "UPDATE ... " statement for the table.
|
||||
func (d *Driver) DoUpdate(ctx context.Context, link gdb.Link, table string, data interface{}, condition string, args ...interface{}) (result sql.Result, err error) {
|
||||
ctx = d.injectNeedParsedSql(ctx)
|
||||
return d.Core.DoUpdate(ctx, link, table, data, condition, args...)
|
||||
}
|
||||
27
contrib/drivers/clickhouse/clickhouse_insert.go
Normal file
27
contrib/drivers/clickhouse/clickhouse_insert.go
Normal file
@ -0,0 +1,27 @@
|
||||
// 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 clickhouse
|
||||
|
||||
import (
|
||||
"context"
|
||||
"database/sql"
|
||||
)
|
||||
|
||||
// InsertIgnore Other queries for modifying data parts are not supported: REPLACE, MERGE, UPSERT, INSERT UPDATE.
|
||||
func (d *Driver) InsertIgnore(ctx context.Context, table string, data interface{}, batch ...int) (sql.Result, error) {
|
||||
return nil, errUnsupportedInsertIgnore
|
||||
}
|
||||
|
||||
// InsertAndGetId Other queries for modifying data parts are not supported: REPLACE, MERGE, UPSERT, INSERT UPDATE.
|
||||
func (d *Driver) InsertAndGetId(ctx context.Context, table string, data interface{}, batch ...int) (int64, error) {
|
||||
return 0, errUnsupportedInsertGetId
|
||||
}
|
||||
|
||||
// Replace Other queries for modifying data parts are not supported: REPLACE, MERGE, UPSERT, INSERT UPDATE.
|
||||
func (d *Driver) Replace(ctx context.Context, table string, data interface{}, batch ...int) (sql.Result, error) {
|
||||
return nil, errUnsupportedReplace
|
||||
}
|
||||
63
contrib/drivers/clickhouse/clickhouse_open.go
Normal file
63
contrib/drivers/clickhouse/clickhouse_open.go
Normal file
@ -0,0 +1,63 @@
|
||||
// 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 clickhouse
|
||||
|
||||
import (
|
||||
"database/sql"
|
||||
"fmt"
|
||||
"net/url"
|
||||
|
||||
"github.com/gogf/gf/v2/database/gdb"
|
||||
"github.com/gogf/gf/v2/errors/gcode"
|
||||
"github.com/gogf/gf/v2/errors/gerror"
|
||||
"github.com/gogf/gf/v2/text/gregex"
|
||||
)
|
||||
|
||||
// Open creates and returns an underlying sql.DB object for clickhouse.
|
||||
func (d *Driver) Open(config *gdb.ConfigNode) (db *sql.DB, err error) {
|
||||
source := config.Link
|
||||
// clickhouse://username:password@host1:9000,host2:9000/database?dial_timeout=200ms&max_execution_time=60
|
||||
if config.Link != "" {
|
||||
// ============================================================================
|
||||
// Deprecated from v2.2.0.
|
||||
// ============================================================================
|
||||
// Custom changing the schema in runtime.
|
||||
if config.Name != "" {
|
||||
source, _ = gregex.ReplaceString(replaceSchemaPattern, "@$1/"+config.Name, config.Link)
|
||||
} else {
|
||||
// If no schema, the link is matched for replacement
|
||||
dbName, _ := gregex.MatchString(replaceSchemaPattern, config.Link)
|
||||
if len(dbName) > 0 {
|
||||
config.Name = dbName[len(dbName)-1]
|
||||
}
|
||||
}
|
||||
} else {
|
||||
if config.Pass != "" {
|
||||
source = fmt.Sprintf(
|
||||
"clickhouse://%s:%s@%s:%s/%s?debug=%t",
|
||||
config.User, url.PathEscape(config.Pass),
|
||||
config.Host, config.Port, config.Name, config.Debug,
|
||||
)
|
||||
} else {
|
||||
source = fmt.Sprintf(
|
||||
"clickhouse://%s@%s:%s/%s?debug=%t",
|
||||
config.User, config.Host, config.Port, config.Name, config.Debug,
|
||||
)
|
||||
}
|
||||
if config.Extra != "" {
|
||||
source = fmt.Sprintf("%s&%s", source, config.Extra)
|
||||
}
|
||||
}
|
||||
if db, err = sql.Open(driverName, source); err != nil {
|
||||
err = gerror.WrapCodef(
|
||||
gcode.CodeDbOperationError, err,
|
||||
`sql.Open failed for driver "%s" by source "%s"`, driverName, source,
|
||||
)
|
||||
return nil, err
|
||||
}
|
||||
return
|
||||
}
|
||||
41
contrib/drivers/clickhouse/clickhouse_ping.go
Normal file
41
contrib/drivers/clickhouse/clickhouse_ping.go
Normal file
@ -0,0 +1,41 @@
|
||||
// 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 clickhouse
|
||||
|
||||
import (
|
||||
"database/sql"
|
||||
"fmt"
|
||||
|
||||
"github.com/ClickHouse/clickhouse-go/v2"
|
||||
)
|
||||
|
||||
// PingMaster pings the master node to check authentication or keeps the connection alive.
|
||||
func (d *Driver) PingMaster() error {
|
||||
conn, err := d.Master()
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
return d.ping(conn)
|
||||
}
|
||||
|
||||
// PingSlave pings the slave node to check authentication or keeps the connection alive.
|
||||
func (d *Driver) PingSlave() error {
|
||||
conn, err := d.Slave()
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
return d.ping(conn)
|
||||
}
|
||||
|
||||
// ping Returns the Clickhouse specific error.
|
||||
func (d *Driver) ping(conn *sql.DB) error {
|
||||
err := conn.Ping()
|
||||
if exception, ok := err.(*clickhouse.Exception); ok {
|
||||
return fmt.Errorf("[%d]%s", exception.Code, exception.Message)
|
||||
}
|
||||
return err
|
||||
}
|
||||
70
contrib/drivers/clickhouse/clickhouse_table_fields.go
Normal file
70
contrib/drivers/clickhouse/clickhouse_table_fields.go
Normal file
@ -0,0 +1,70 @@
|
||||
// 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 clickhouse
|
||||
|
||||
import (
|
||||
"context"
|
||||
"fmt"
|
||||
|
||||
"github.com/gogf/gf/v2/database/gdb"
|
||||
"github.com/gogf/gf/v2/text/gregex"
|
||||
"github.com/gogf/gf/v2/util/gutil"
|
||||
)
|
||||
|
||||
const (
|
||||
tableFieldsColumns = `name,position,default_expression,comment,type,is_in_partition_key,is_in_sorting_key,is_in_primary_key,is_in_sampling_key`
|
||||
)
|
||||
|
||||
// TableFields retrieves and returns the fields' information of specified table of current schema.
|
||||
// Also see DriverMysql.TableFields.
|
||||
func (d *Driver) TableFields(ctx context.Context, table string, schema ...string) (fields map[string]*gdb.TableField, err error) {
|
||||
var (
|
||||
result gdb.Result
|
||||
link gdb.Link
|
||||
usedSchema = gutil.GetOrDefaultStr(d.GetSchema(), schema...)
|
||||
)
|
||||
if link, err = d.SlaveLink(usedSchema); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
var (
|
||||
getColumnsSql = fmt.Sprintf(
|
||||
"select %s from `system`.columns c where `table` = '%s'",
|
||||
tableFieldsColumns, table,
|
||||
)
|
||||
)
|
||||
result, err = d.DoSelect(ctx, link, getColumnsSql)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
fields = make(map[string]*gdb.TableField)
|
||||
for _, m := range result {
|
||||
var (
|
||||
isNull = false
|
||||
fieldType = m["type"].String()
|
||||
)
|
||||
// in clickhouse , field type like is Nullable(int)
|
||||
fieldsResult, _ := gregex.MatchString(`^Nullable\((.*?)\)`, fieldType)
|
||||
if len(fieldsResult) == 2 {
|
||||
isNull = true
|
||||
fieldType = fieldsResult[1]
|
||||
}
|
||||
position := m["position"].Int()
|
||||
if result[0]["position"].Int() != 0 {
|
||||
position -= 1
|
||||
}
|
||||
fields[m["name"].String()] = &gdb.TableField{
|
||||
Index: position,
|
||||
Name: m["name"].String(),
|
||||
Default: m["default_expression"].Val(),
|
||||
Comment: m["comment"].String(),
|
||||
// Key: m["Key"].String(),
|
||||
Type: fieldType,
|
||||
Null: isNull,
|
||||
}
|
||||
}
|
||||
return fields, nil
|
||||
}
|
||||
36
contrib/drivers/clickhouse/clickhouse_tables.go
Normal file
36
contrib/drivers/clickhouse/clickhouse_tables.go
Normal file
@ -0,0 +1,36 @@
|
||||
// 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 clickhouse
|
||||
|
||||
import (
|
||||
"context"
|
||||
"fmt"
|
||||
|
||||
"github.com/gogf/gf/v2/database/gdb"
|
||||
)
|
||||
|
||||
const (
|
||||
tablesSqlTmp = "select name from `system`.tables where database = '%s'"
|
||||
)
|
||||
|
||||
// Tables retrieves and returns the tables of current schema.
|
||||
// It's mainly used in cli tool chain for automatically generating the models.
|
||||
func (d *Driver) Tables(ctx context.Context, schema ...string) (tables []string, err error) {
|
||||
var result gdb.Result
|
||||
link, err := d.SlaveLink(schema...)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
result, err = d.DoSelect(ctx, link, fmt.Sprintf(tablesSqlTmp, d.GetConfig().Name))
|
||||
if err != nil {
|
||||
return
|
||||
}
|
||||
for _, m := range result {
|
||||
tables = append(tables, m["name"].String())
|
||||
}
|
||||
return
|
||||
}
|
||||
23
contrib/drivers/clickhouse/clickhouse_transaction.go
Normal file
23
contrib/drivers/clickhouse/clickhouse_transaction.go
Normal file
@ -0,0 +1,23 @@
|
||||
// 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 clickhouse
|
||||
|
||||
import (
|
||||
"context"
|
||||
|
||||
"github.com/gogf/gf/v2/database/gdb"
|
||||
)
|
||||
|
||||
// Begin starts and returns the transaction object.
|
||||
func (d *Driver) Begin(ctx context.Context) (tx gdb.TX, err error) {
|
||||
return nil, errUnsupportedBegin
|
||||
}
|
||||
|
||||
// Transaction wraps the transaction logic using function `f`.
|
||||
func (d *Driver) Transaction(ctx context.Context, f func(ctx context.Context, tx gdb.TX) error) error {
|
||||
return errUnsupportedTransaction
|
||||
}
|
||||
@ -4,7 +4,7 @@ go 1.18
|
||||
|
||||
require (
|
||||
github.com/ClickHouse/clickhouse-go/v2 v2.0.15
|
||||
github.com/gogf/gf/v2 v2.6.2
|
||||
github.com/gogf/gf/v2 v2.6.3
|
||||
github.com/google/uuid v1.3.0
|
||||
github.com/shopspring/decimal v1.3.1
|
||||
)
|
||||
|
||||
@ -8,24 +8,10 @@
|
||||
package dm
|
||||
|
||||
import (
|
||||
"context"
|
||||
"database/sql"
|
||||
"fmt"
|
||||
"net/url"
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
_ "gitee.com/chunanyong/dm"
|
||||
|
||||
"github.com/gogf/gf/v2/database/gdb"
|
||||
"github.com/gogf/gf/v2/errors/gcode"
|
||||
"github.com/gogf/gf/v2/errors/gerror"
|
||||
"github.com/gogf/gf/v2/frame/g"
|
||||
"github.com/gogf/gf/v2/os/gtime"
|
||||
"github.com/gogf/gf/v2/text/gregex"
|
||||
"github.com/gogf/gf/v2/text/gstr"
|
||||
"github.com/gogf/gf/v2/util/gconv"
|
||||
"github.com/gogf/gf/v2/util/gutil"
|
||||
)
|
||||
|
||||
type Driver struct {
|
||||
@ -61,390 +47,7 @@ func (d *Driver) New(core *gdb.Core, node *gdb.ConfigNode) (gdb.DB, error) {
|
||||
}, nil
|
||||
}
|
||||
|
||||
// Open creates and returns an underlying sql.DB object for pgsql.
|
||||
func (d *Driver) Open(config *gdb.ConfigNode) (db *sql.DB, err error) {
|
||||
var (
|
||||
source string
|
||||
underlyingDriverName = "dm"
|
||||
)
|
||||
if config.Name == "" {
|
||||
return nil, fmt.Errorf(
|
||||
`dm.Open failed for driver "%s" without DB Name`, underlyingDriverName,
|
||||
)
|
||||
}
|
||||
// Data Source Name of DM8:
|
||||
// dm://userName:password@ip:port/dbname
|
||||
// dm://userName:password@DW/dbname?DW=(192.168.1.1:5236,192.168.1.2:5236)
|
||||
var domain string
|
||||
if config.Port != "" {
|
||||
domain = fmt.Sprintf("%s:%s", config.Host, config.Port)
|
||||
} else {
|
||||
domain = config.Host
|
||||
}
|
||||
source = fmt.Sprintf(
|
||||
"dm://%s:%s@%s/%s?charset=%s&schema=%s",
|
||||
config.User, config.Pass, domain, config.Name, config.Charset, config.Name,
|
||||
)
|
||||
// Demo of timezone setting:
|
||||
// &loc=Asia/Shanghai
|
||||
if config.Timezone != "" {
|
||||
if strings.Contains(config.Timezone, "/") {
|
||||
config.Timezone = url.QueryEscape(config.Timezone)
|
||||
}
|
||||
source = fmt.Sprintf("%s&loc%s", source, config.Timezone)
|
||||
}
|
||||
if config.Extra != "" {
|
||||
source = fmt.Sprintf("%s&%s", source, config.Extra)
|
||||
}
|
||||
|
||||
if db, err = sql.Open(underlyingDriverName, source); err != nil {
|
||||
err = gerror.WrapCodef(
|
||||
gcode.CodeDbOperationError, err,
|
||||
`dm.Open failed for driver "%s" by source "%s"`, underlyingDriverName, source,
|
||||
)
|
||||
return nil, err
|
||||
}
|
||||
return
|
||||
}
|
||||
|
||||
// GetChars returns the security char for this type of database.
|
||||
func (d *Driver) GetChars() (charLeft string, charRight string) {
|
||||
return quoteChar, quoteChar
|
||||
}
|
||||
|
||||
// Tables retrieves and returns the tables of current schema.
|
||||
// It's mainly used in cli tool chain for automatically generating the models.
|
||||
func (d *Driver) Tables(ctx context.Context, schema ...string) (tables []string, err error) {
|
||||
var result gdb.Result
|
||||
// When schema is empty, return the default link
|
||||
link, err := d.SlaveLink(schema...)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
// The link has been distinguished and no longer needs to judge the owner
|
||||
result, err = d.DoSelect(
|
||||
ctx, link, `SELECT * FROM ALL_TABLES`,
|
||||
)
|
||||
if err != nil {
|
||||
return
|
||||
}
|
||||
for _, m := range result {
|
||||
if v, ok := m["IOT_NAME"]; ok {
|
||||
tables = append(tables, v.String())
|
||||
}
|
||||
}
|
||||
return
|
||||
}
|
||||
|
||||
// TableFields retrieves and returns the fields' information of specified table of current schema.
|
||||
func (d *Driver) TableFields(ctx context.Context, table string, schema ...string) (fields map[string]*gdb.TableField, err error) {
|
||||
var (
|
||||
result gdb.Result
|
||||
link gdb.Link
|
||||
// When no schema is specified, the configuration item is returned by default
|
||||
usedSchema = gutil.GetOrDefaultStr(d.GetSchema(), schema...)
|
||||
)
|
||||
// When usedSchema is empty, return the default link
|
||||
if link, err = d.SlaveLink(usedSchema); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
// The link has been distinguished and no longer needs to judge the owner
|
||||
result, err = d.DoSelect(
|
||||
ctx, link,
|
||||
fmt.Sprintf(
|
||||
`SELECT * FROM ALL_TAB_COLUMNS WHERE Table_Name= '%s' AND OWNER = '%s'`,
|
||||
strings.ToUpper(table),
|
||||
strings.ToUpper(d.GetSchema()),
|
||||
),
|
||||
)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
fields = make(map[string]*gdb.TableField)
|
||||
for i, m := range result {
|
||||
// m[NULLABLE] returns "N" "Y"
|
||||
// "N" means not null
|
||||
// "Y" means could be null
|
||||
var nullable bool
|
||||
if m["NULLABLE"].String() != "N" {
|
||||
nullable = true
|
||||
}
|
||||
fields[m["COLUMN_NAME"].String()] = &gdb.TableField{
|
||||
Index: i,
|
||||
Name: m["COLUMN_NAME"].String(),
|
||||
Type: m["DATA_TYPE"].String(),
|
||||
Null: nullable,
|
||||
Default: m["DATA_DEFAULT"].Val(),
|
||||
// Key: m["Key"].String(),
|
||||
// Extra: m["Extra"].String(),
|
||||
// Comment: m["Comment"].String(),
|
||||
}
|
||||
}
|
||||
return fields, nil
|
||||
}
|
||||
|
||||
// ConvertValueForField converts value to the type of the record field.
|
||||
func (d *Driver) ConvertValueForField(ctx context.Context, fieldType string, fieldValue interface{}) (interface{}, error) {
|
||||
switch itemValue := fieldValue.(type) {
|
||||
// dm does not support time.Time, it so here converts it to time string that it supports.
|
||||
case time.Time:
|
||||
// If the time is zero, it then updates it to nil,
|
||||
// which will insert/update the value to database as "null".
|
||||
if itemValue.IsZero() {
|
||||
return nil, nil
|
||||
}
|
||||
return gtime.New(itemValue).String(), nil
|
||||
|
||||
// dm does not support time.Time, it so here converts it to time string that it supports.
|
||||
case *time.Time:
|
||||
// If the time is zero, it then updates it to nil,
|
||||
// which will insert/update the value to database as "null".
|
||||
if itemValue == nil || itemValue.IsZero() {
|
||||
return nil, nil
|
||||
}
|
||||
return gtime.New(itemValue).String(), nil
|
||||
}
|
||||
|
||||
return fieldValue, nil
|
||||
}
|
||||
|
||||
// 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) {
|
||||
// There should be no need to capitalize, because it has been done from field processing before
|
||||
newSql, _ = gregex.ReplaceString(`["\n\t]`, "", sql)
|
||||
newSql = gstr.ReplaceI(gstr.ReplaceI(newSql, "GROUP_CONCAT", "LISTAGG"), "SEPARATOR", ",")
|
||||
|
||||
// TODO The current approach is too rough. We should deal with the GROUP_CONCAT function and the parsing of the index field from within the select from match.
|
||||
// (GROUP_CONCAT DM does not approve; index cannot be used as a query column name, and security characters need to be added, such as "index")
|
||||
l, r := d.GetChars()
|
||||
if strings.Contains(newSql, "INDEX") || strings.Contains(newSql, "index") {
|
||||
if !(strings.Contains(newSql, "_INDEX") || strings.Contains(newSql, "_index")) {
|
||||
newSql = gstr.ReplaceI(newSql, "INDEX", l+"INDEX"+r)
|
||||
}
|
||||
}
|
||||
|
||||
// TODO i tried to do but it never work:
|
||||
// array, err := gregex.MatchAllString(`SELECT (.*INDEX.*) FROM .*`, newSql)
|
||||
// g.Dump("err:", err)
|
||||
// g.Dump("array:", array)
|
||||
// g.Dump("array:", array[0][1])
|
||||
|
||||
// newSql, err = gregex.ReplaceString(`SELECT (.*INDEX.*) FROM .*`, l+"INDEX"+r, newSql)
|
||||
// g.Dump("err:", err)
|
||||
// g.Dump("newSql:", newSql)
|
||||
|
||||
// re, err := regexp.Compile(`.*SELECT (.*INDEX.*) FROM .*`)
|
||||
// newSql = re.ReplaceAllStringFunc(newSql, func(data string) string {
|
||||
// fmt.Println("data:", data)
|
||||
// return data
|
||||
// })
|
||||
|
||||
return d.Core.DoFilter(
|
||||
ctx,
|
||||
link,
|
||||
newSql,
|
||||
args,
|
||||
)
|
||||
}
|
||||
|
||||
// TODO I originally wanted to only convert keywords in select
|
||||
// 但是我发现 DoQuery 中会对 sql 会对 " " 达梦的安全字符 进行 / 转义,最后还是导致达梦无法正常解析
|
||||
// However, I found that DoQuery() will perform / escape on sql with " " Dameng's safe characters, which ultimately caused Dameng to be unable to parse normally.
|
||||
// But processing in DoFilter() is OK
|
||||
// func (d *Driver) DoQuery(ctx context.Context, link gdb.Link, sql string, args ...interface{}) (gdb.Result, error) {
|
||||
// l, r := d.GetChars()
|
||||
// new := gstr.ReplaceI(sql, "INDEX", l+"INDEX"+r)
|
||||
// g.Dump("new:", new)
|
||||
// return d.Core.DoQuery(
|
||||
// ctx,
|
||||
// link,
|
||||
// new,
|
||||
// args,
|
||||
// )
|
||||
// }
|
||||
|
||||
// DoInsert inserts or updates data forF 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:
|
||||
// TODO:: Should be Supported
|
||||
return nil, gerror.NewCode(
|
||||
gcode.CodeNotSupported, `Replace operation is not supported by dm driver`,
|
||||
)
|
||||
|
||||
case gdb.InsertOptionSave:
|
||||
// This syntax currently only supports design tables whose primary key is ID.
|
||||
listLength := len(list)
|
||||
if listLength == 0 {
|
||||
return nil, gerror.NewCode(
|
||||
gcode.CodeInvalidRequest, `Save operation list is empty by dm driver`,
|
||||
)
|
||||
}
|
||||
var (
|
||||
keysSort []string
|
||||
charL, charR = d.GetChars()
|
||||
)
|
||||
// Column names need to be aligned in the syntax
|
||||
for k := range list[0] {
|
||||
keysSort = append(keysSort, k)
|
||||
}
|
||||
var char = struct {
|
||||
charL string
|
||||
charR string
|
||||
valueCharL string
|
||||
valueCharR string
|
||||
duplicateKey string
|
||||
keys []string
|
||||
}{
|
||||
charL: charL,
|
||||
charR: charR,
|
||||
valueCharL: "'",
|
||||
valueCharR: "'",
|
||||
// TODO:: Need to dynamically set the primary key of the table
|
||||
duplicateKey: "ID",
|
||||
keys: keysSort,
|
||||
}
|
||||
|
||||
// insertKeys: Handle valid keys that need to be inserted and updated
|
||||
// insertValues: Handle values that need to be inserted
|
||||
// updateValues: Handle values that need to be updated
|
||||
// queryValues: Handle only one insert with column name
|
||||
insertKeys, insertValues, updateValues, queryValues := parseValue(list[0], char)
|
||||
// unionValues: Handling values that need to be inserted and updated
|
||||
unionValues := parseUnion(list[1:], char)
|
||||
|
||||
batchResult := new(gdb.SqlResult)
|
||||
// parseSql():
|
||||
// MERGE INTO {{table}} T1
|
||||
// USING ( SELECT {{queryValues}} FROM DUAL
|
||||
// {{unionValues}} ) T2
|
||||
// ON (T1.{{duplicateKey}} = T2.{{duplicateKey}})
|
||||
// WHEN NOT MATCHED THEN
|
||||
// INSERT {{insertKeys}} VALUES {{insertValues}}
|
||||
// WHEN MATCHED THEN
|
||||
// UPDATE SET {{updateValues}}
|
||||
sqlStr := parseSql(
|
||||
insertKeys, insertValues, updateValues, queryValues, unionValues, table, char.duplicateKey,
|
||||
)
|
||||
r, err := d.DoExec(ctx, link, sqlStr)
|
||||
if err != nil {
|
||||
return r, err
|
||||
}
|
||||
if n, err := r.RowsAffected(); err != nil {
|
||||
return r, err
|
||||
} else {
|
||||
batchResult.Result = r
|
||||
batchResult.Affected += n
|
||||
}
|
||||
return batchResult, nil
|
||||
}
|
||||
return d.Core.DoInsert(ctx, link, table, list, option)
|
||||
}
|
||||
|
||||
func parseValue(listOne gdb.Map, char struct {
|
||||
charL string
|
||||
charR string
|
||||
valueCharL string
|
||||
valueCharR string
|
||||
duplicateKey string
|
||||
keys []string
|
||||
}) (insertKeys []string, insertValues []string, updateValues []string, queryValues []string) {
|
||||
for _, column := range char.keys {
|
||||
if listOne[column] == nil {
|
||||
// remove unassigned struct object
|
||||
continue
|
||||
}
|
||||
insertKeys = append(insertKeys, char.charL+column+char.charR)
|
||||
insertValues = append(insertValues, "T2."+char.charL+column+char.charR)
|
||||
if column != char.duplicateKey {
|
||||
updateValues = append(
|
||||
updateValues,
|
||||
fmt.Sprintf(`T1.%s = T2.%s`, char.charL+column+char.charR, char.charL+column+char.charR),
|
||||
)
|
||||
}
|
||||
|
||||
saveValue := gconv.String(listOne[column])
|
||||
queryValues = append(
|
||||
queryValues,
|
||||
fmt.Sprintf(
|
||||
char.valueCharL+"%s"+char.valueCharR+" AS "+char.charL+"%s"+char.charR,
|
||||
saveValue, column,
|
||||
),
|
||||
)
|
||||
}
|
||||
return
|
||||
}
|
||||
|
||||
func parseUnion(list gdb.List, char struct {
|
||||
charL string
|
||||
charR string
|
||||
valueCharL string
|
||||
valueCharR string
|
||||
duplicateKey string
|
||||
keys []string
|
||||
}) (unionValues []string) {
|
||||
for _, mapper := range list {
|
||||
var saveValue []string
|
||||
for _, column := range char.keys {
|
||||
if mapper[column] == nil {
|
||||
continue
|
||||
}
|
||||
// va := reflect.ValueOf(mapper[column])
|
||||
// ty := reflect.TypeOf(mapper[column])
|
||||
// switch ty.Kind() {
|
||||
// case reflect.String:
|
||||
// saveValue = append(saveValue, char.valueCharL+va.String()+char.valueCharR)
|
||||
|
||||
// case reflect.Int:
|
||||
// saveValue = append(saveValue, strconv.FormatInt(va.Int(), 10))
|
||||
|
||||
// case reflect.Int64:
|
||||
// saveValue = append(saveValue, strconv.FormatInt(va.Int(), 10))
|
||||
|
||||
// default:
|
||||
// // The fish has no chance getting here.
|
||||
// // Nothing to do.
|
||||
// }
|
||||
saveValue = append(saveValue,
|
||||
fmt.Sprintf(
|
||||
char.valueCharL+"%s"+char.valueCharR,
|
||||
gconv.String(mapper[column]),
|
||||
))
|
||||
}
|
||||
unionValues = append(
|
||||
unionValues,
|
||||
fmt.Sprintf(`UNION ALL SELECT %s FROM DUAL`, strings.Join(saveValue, ",")),
|
||||
)
|
||||
}
|
||||
return
|
||||
}
|
||||
|
||||
func parseSql(
|
||||
insertKeys, insertValues, updateValues, queryValues, unionValues []string, table, duplicateKey string,
|
||||
) (sqlStr string) {
|
||||
var (
|
||||
queryValueStr = strings.Join(queryValues, ",")
|
||||
unionValueStr = strings.Join(unionValues, " ")
|
||||
insertKeyStr = strings.Join(insertKeys, ",")
|
||||
insertValueStr = strings.Join(insertValues, ",")
|
||||
updateValueStr = strings.Join(updateValues, ",")
|
||||
pattern = gstr.Trim(`
|
||||
MERGE INTO %s T1 USING (SELECT %s FROM DUAL %s) T2 ON %s
|
||||
WHEN NOT MATCHED
|
||||
THEN
|
||||
INSERT(%s) VALUES (%s)
|
||||
WHEN MATCHED
|
||||
THEN
|
||||
UPDATE SET %s;
|
||||
COMMIT;
|
||||
`)
|
||||
)
|
||||
return fmt.Sprintf(
|
||||
pattern,
|
||||
table, queryValueStr, unionValueStr,
|
||||
fmt.Sprintf("(T1.%s = T2.%s)", duplicateKey, duplicateKey),
|
||||
insertKeyStr, insertValueStr, updateValueStr,
|
||||
)
|
||||
}
|
||||
|
||||
40
contrib/drivers/dm/dm_convert.go
Normal file
40
contrib/drivers/dm/dm_convert.go
Normal file
@ -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 dm
|
||||
|
||||
import (
|
||||
"context"
|
||||
|
||||
"time"
|
||||
|
||||
"github.com/gogf/gf/v2/os/gtime"
|
||||
)
|
||||
|
||||
// ConvertValueForField converts value to the type of the record field.
|
||||
func (d *Driver) ConvertValueForField(ctx context.Context, fieldType string, fieldValue interface{}) (interface{}, error) {
|
||||
switch itemValue := fieldValue.(type) {
|
||||
// dm does not support time.Time, it so here converts it to time string that it supports.
|
||||
case time.Time:
|
||||
// If the time is zero, it then updates it to nil,
|
||||
// which will insert/update the value to database as "null".
|
||||
if itemValue.IsZero() {
|
||||
return nil, nil
|
||||
}
|
||||
return gtime.New(itemValue).String(), nil
|
||||
|
||||
// dm does not support time.Time, it so here converts it to time string that it supports.
|
||||
case *time.Time:
|
||||
// If the time is zero, it then updates it to nil,
|
||||
// which will insert/update the value to database as "null".
|
||||
if itemValue == nil || itemValue.IsZero() {
|
||||
return nil, nil
|
||||
}
|
||||
return gtime.New(itemValue).String(), nil
|
||||
}
|
||||
|
||||
return fieldValue, nil
|
||||
}
|
||||
59
contrib/drivers/dm/dm_do_filter.go
Normal file
59
contrib/drivers/dm/dm_do_filter.go
Normal file
@ -0,0 +1,59 @@
|
||||
// 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 dm
|
||||
|
||||
import (
|
||||
"context"
|
||||
|
||||
"strings"
|
||||
|
||||
"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) {
|
||||
// There should be no need to capitalize, because it has been done from field processing before
|
||||
newSql, _ = gregex.ReplaceString(`["\n\t]`, "", sql)
|
||||
newSql = gstr.ReplaceI(gstr.ReplaceI(newSql, "GROUP_CONCAT", "LISTAGG"), "SEPARATOR", ",")
|
||||
|
||||
// TODO The current approach is too rough. We should deal with the GROUP_CONCAT function and the
|
||||
// parsing of the index field from within the select from match.
|
||||
// (GROUP_CONCAT DM does not approve; index cannot be used as a query column name, and security characters need to be added, such as "index")
|
||||
l, r := d.GetChars()
|
||||
if strings.Contains(newSql, "INDEX") || strings.Contains(newSql, "index") {
|
||||
if !(strings.Contains(newSql, "_INDEX") || strings.Contains(newSql, "_index")) {
|
||||
newSql = gstr.ReplaceI(newSql, "INDEX", l+"INDEX"+r)
|
||||
}
|
||||
}
|
||||
|
||||
// TODO i tried to do but it never work:
|
||||
// array, err := gregex.MatchAllString(`SELECT (.*INDEX.*) FROM .*`, newSql)
|
||||
// g.Dump("err:", err)
|
||||
// g.Dump("array:", array)
|
||||
// g.Dump("array:", array[0][1])
|
||||
|
||||
// newSql, err = gregex.ReplaceString(`SELECT (.*INDEX.*) FROM .*`, l+"INDEX"+r, newSql)
|
||||
// g.Dump("err:", err)
|
||||
// g.Dump("newSql:", newSql)
|
||||
|
||||
// re, err := regexp.Compile(`.*SELECT (.*INDEX.*) FROM .*`)
|
||||
// newSql = re.ReplaceAllStringFunc(newSql, func(data string) string {
|
||||
// fmt.Println("data:", data)
|
||||
// return data
|
||||
// })
|
||||
|
||||
return d.Core.DoFilter(
|
||||
ctx,
|
||||
link,
|
||||
newSql,
|
||||
args,
|
||||
)
|
||||
}
|
||||
207
contrib/drivers/dm/dm_do_insert.go
Normal file
207
contrib/drivers/dm/dm_do_insert.go
Normal file
@ -0,0 +1,207 @@
|
||||
// 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 dm
|
||||
|
||||
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"
|
||||
"github.com/gogf/gf/v2/text/gstr"
|
||||
"github.com/gogf/gf/v2/util/gconv"
|
||||
)
|
||||
|
||||
// DoInsert inserts or updates data forF 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:
|
||||
// TODO:: Should be Supported
|
||||
return nil, gerror.NewCode(
|
||||
gcode.CodeNotSupported, `Replace operation is not supported by dm driver`,
|
||||
)
|
||||
|
||||
case gdb.InsertOptionSave:
|
||||
// This syntax currently only supports design tables whose primary key is ID.
|
||||
listLength := len(list)
|
||||
if listLength == 0 {
|
||||
return nil, gerror.NewCode(
|
||||
gcode.CodeInvalidRequest, `Save operation list is empty by dm driver`,
|
||||
)
|
||||
}
|
||||
var (
|
||||
keysSort []string
|
||||
charL, charR = d.GetChars()
|
||||
)
|
||||
// Column names need to be aligned in the syntax
|
||||
for k := range list[0] {
|
||||
keysSort = append(keysSort, k)
|
||||
}
|
||||
var char = struct {
|
||||
charL string
|
||||
charR string
|
||||
valueCharL string
|
||||
valueCharR string
|
||||
duplicateKey string
|
||||
keys []string
|
||||
}{
|
||||
charL: charL,
|
||||
charR: charR,
|
||||
valueCharL: "'",
|
||||
valueCharR: "'",
|
||||
// TODO:: Need to dynamically set the primary key of the table
|
||||
duplicateKey: "ID",
|
||||
keys: keysSort,
|
||||
}
|
||||
|
||||
// insertKeys: Handle valid keys that need to be inserted and updated
|
||||
// insertValues: Handle values that need to be inserted
|
||||
// updateValues: Handle values that need to be updated
|
||||
// queryValues: Handle only one insert with column name
|
||||
insertKeys, insertValues, updateValues, queryValues := parseValue(list[0], char)
|
||||
// unionValues: Handling values that need to be inserted and updated
|
||||
unionValues := parseUnion(list[1:], char)
|
||||
|
||||
batchResult := new(gdb.SqlResult)
|
||||
// parseSql():
|
||||
// MERGE INTO {{table}} T1
|
||||
// USING ( SELECT {{queryValues}} FROM DUAL
|
||||
// {{unionValues}} ) T2
|
||||
// ON (T1.{{duplicateKey}} = T2.{{duplicateKey}})
|
||||
// WHEN NOT MATCHED THEN
|
||||
// INSERT {{insertKeys}} VALUES {{insertValues}}
|
||||
// WHEN MATCHED THEN
|
||||
// UPDATE SET {{updateValues}}
|
||||
sqlStr := parseSql(
|
||||
insertKeys, insertValues, updateValues, queryValues, unionValues, table, char.duplicateKey,
|
||||
)
|
||||
r, err := d.DoExec(ctx, link, sqlStr)
|
||||
if err != nil {
|
||||
return r, err
|
||||
}
|
||||
if n, err := r.RowsAffected(); err != nil {
|
||||
return r, err
|
||||
} else {
|
||||
batchResult.Result = r
|
||||
batchResult.Affected += n
|
||||
}
|
||||
return batchResult, nil
|
||||
}
|
||||
return d.Core.DoInsert(ctx, link, table, list, option)
|
||||
}
|
||||
|
||||
func parseValue(listOne gdb.Map, char struct {
|
||||
charL string
|
||||
charR string
|
||||
valueCharL string
|
||||
valueCharR string
|
||||
duplicateKey string
|
||||
keys []string
|
||||
}) (insertKeys []string, insertValues []string, updateValues []string, queryValues []string) {
|
||||
for _, column := range char.keys {
|
||||
if listOne[column] == nil {
|
||||
// remove unassigned struct object
|
||||
continue
|
||||
}
|
||||
insertKeys = append(insertKeys, char.charL+column+char.charR)
|
||||
insertValues = append(insertValues, "T2."+char.charL+column+char.charR)
|
||||
if column != char.duplicateKey {
|
||||
updateValues = append(
|
||||
updateValues,
|
||||
fmt.Sprintf(`T1.%s = T2.%s`, char.charL+column+char.charR, char.charL+column+char.charR),
|
||||
)
|
||||
}
|
||||
|
||||
saveValue := gconv.String(listOne[column])
|
||||
queryValues = append(
|
||||
queryValues,
|
||||
fmt.Sprintf(
|
||||
char.valueCharL+"%s"+char.valueCharR+" AS "+char.charL+"%s"+char.charR,
|
||||
saveValue, column,
|
||||
),
|
||||
)
|
||||
}
|
||||
return
|
||||
}
|
||||
|
||||
func parseUnion(list gdb.List, char struct {
|
||||
charL string
|
||||
charR string
|
||||
valueCharL string
|
||||
valueCharR string
|
||||
duplicateKey string
|
||||
keys []string
|
||||
}) (unionValues []string) {
|
||||
for _, mapper := range list {
|
||||
var saveValue []string
|
||||
for _, column := range char.keys {
|
||||
if mapper[column] == nil {
|
||||
continue
|
||||
}
|
||||
// va := reflect.ValueOf(mapper[column])
|
||||
// ty := reflect.TypeOf(mapper[column])
|
||||
// switch ty.Kind() {
|
||||
// case reflect.String:
|
||||
// saveValue = append(saveValue, char.valueCharL+va.String()+char.valueCharR)
|
||||
|
||||
// case reflect.Int:
|
||||
// saveValue = append(saveValue, strconv.FormatInt(va.Int(), 10))
|
||||
|
||||
// case reflect.Int64:
|
||||
// saveValue = append(saveValue, strconv.FormatInt(va.Int(), 10))
|
||||
|
||||
// default:
|
||||
// // The fish has no chance getting here.
|
||||
// // Nothing to do.
|
||||
// }
|
||||
saveValue = append(saveValue,
|
||||
fmt.Sprintf(
|
||||
char.valueCharL+"%s"+char.valueCharR,
|
||||
gconv.String(mapper[column]),
|
||||
))
|
||||
}
|
||||
unionValues = append(
|
||||
unionValues,
|
||||
fmt.Sprintf(`UNION ALL SELECT %s FROM DUAL`, strings.Join(saveValue, ",")),
|
||||
)
|
||||
}
|
||||
return
|
||||
}
|
||||
|
||||
func parseSql(
|
||||
insertKeys, insertValues, updateValues, queryValues, unionValues []string, table, duplicateKey string,
|
||||
) (sqlStr string) {
|
||||
var (
|
||||
queryValueStr = strings.Join(queryValues, ",")
|
||||
unionValueStr = strings.Join(unionValues, " ")
|
||||
insertKeyStr = strings.Join(insertKeys, ",")
|
||||
insertValueStr = strings.Join(insertValues, ",")
|
||||
updateValueStr = strings.Join(updateValues, ",")
|
||||
pattern = gstr.Trim(`
|
||||
MERGE INTO %s T1 USING (SELECT %s FROM DUAL %s) T2 ON %s
|
||||
WHEN NOT MATCHED
|
||||
THEN
|
||||
INSERT(%s) VALUES (%s)
|
||||
WHEN MATCHED
|
||||
THEN
|
||||
UPDATE SET %s;
|
||||
COMMIT;
|
||||
`)
|
||||
)
|
||||
return fmt.Sprintf(
|
||||
pattern,
|
||||
table, queryValueStr, unionValueStr,
|
||||
fmt.Sprintf("(T1.%s = T2.%s)", duplicateKey, duplicateKey),
|
||||
insertKeyStr, insertValueStr, updateValueStr,
|
||||
)
|
||||
}
|
||||
23
contrib/drivers/dm/dm_do_query.go
Normal file
23
contrib/drivers/dm/dm_do_query.go
Normal file
@ -0,0 +1,23 @@
|
||||
// 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 dm
|
||||
|
||||
// TODO I originally wanted to only convert keywords in select
|
||||
// 但是我发现 DoQuery 中会对 sql 会对 " " 达梦的安全字符 进行 / 转义,最后还是导致达梦无法正常解析
|
||||
// However, I found that DoQuery() will perform / escape on sql with " " Dameng's safe characters, which ultimately caused Dameng to be unable to parse normally.
|
||||
// But processing in DoFilter() is OK
|
||||
// func (d *Driver) DoQuery(ctx context.Context, link gdb.Link, sql string, args ...interface{}) (gdb.Result, error) {
|
||||
// l, r := d.GetChars()
|
||||
// new := gstr.ReplaceI(sql, "INDEX", l+"INDEX"+r)
|
||||
// g.Dump("new:", new)
|
||||
// return d.Core.DoQuery(
|
||||
// ctx,
|
||||
// link,
|
||||
// new,
|
||||
// args,
|
||||
// )
|
||||
// }
|
||||
65
contrib/drivers/dm/dm_open.go
Normal file
65
contrib/drivers/dm/dm_open.go
Normal file
@ -0,0 +1,65 @@
|
||||
// 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 dm
|
||||
|
||||
import (
|
||||
"database/sql"
|
||||
"fmt"
|
||||
|
||||
"net/url"
|
||||
"strings"
|
||||
|
||||
"github.com/gogf/gf/v2/database/gdb"
|
||||
"github.com/gogf/gf/v2/errors/gcode"
|
||||
"github.com/gogf/gf/v2/errors/gerror"
|
||||
)
|
||||
|
||||
// Open creates and returns an underlying sql.DB object for pgsql.
|
||||
func (d *Driver) Open(config *gdb.ConfigNode) (db *sql.DB, err error) {
|
||||
var (
|
||||
source string
|
||||
underlyingDriverName = "dm"
|
||||
)
|
||||
if config.Name == "" {
|
||||
return nil, fmt.Errorf(
|
||||
`dm.Open failed for driver "%s" without DB Name`, underlyingDriverName,
|
||||
)
|
||||
}
|
||||
// Data Source Name of DM8:
|
||||
// dm://userName:password@ip:port/dbname
|
||||
// dm://userName:password@DW/dbname?DW=(192.168.1.1:5236,192.168.1.2:5236)
|
||||
var domain string
|
||||
if config.Port != "" {
|
||||
domain = fmt.Sprintf("%s:%s", config.Host, config.Port)
|
||||
} else {
|
||||
domain = config.Host
|
||||
}
|
||||
source = fmt.Sprintf(
|
||||
"dm://%s:%s@%s/%s?charset=%s&schema=%s",
|
||||
config.User, config.Pass, domain, config.Name, config.Charset, config.Name,
|
||||
)
|
||||
// Demo of timezone setting:
|
||||
// &loc=Asia/Shanghai
|
||||
if config.Timezone != "" {
|
||||
if strings.Contains(config.Timezone, "/") {
|
||||
config.Timezone = url.QueryEscape(config.Timezone)
|
||||
}
|
||||
source = fmt.Sprintf("%s&loc%s", source, config.Timezone)
|
||||
}
|
||||
if config.Extra != "" {
|
||||
source = fmt.Sprintf("%s&%s", source, config.Extra)
|
||||
}
|
||||
|
||||
if db, err = sql.Open(underlyingDriverName, source); err != nil {
|
||||
err = gerror.WrapCodef(
|
||||
gcode.CodeDbOperationError, err,
|
||||
`dm.Open failed for driver "%s" by source "%s"`, underlyingDriverName, source,
|
||||
)
|
||||
return nil, err
|
||||
}
|
||||
return
|
||||
}
|
||||
70
contrib/drivers/dm/dm_table_fields.go
Normal file
70
contrib/drivers/dm/dm_table_fields.go
Normal file
@ -0,0 +1,70 @@
|
||||
// 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 dm
|
||||
|
||||
import (
|
||||
"context"
|
||||
"fmt"
|
||||
|
||||
"strings"
|
||||
|
||||
"github.com/gogf/gf/v2/database/gdb"
|
||||
"github.com/gogf/gf/v2/util/gutil"
|
||||
)
|
||||
|
||||
const (
|
||||
tableFieldsSqlTmp = `SELECT * FROM ALL_TAB_COLUMNS WHERE Table_Name= '%s' AND OWNER = '%s'`
|
||||
)
|
||||
|
||||
// TableFields retrieves and returns the fields' information of specified table of current schema.
|
||||
func (d *Driver) TableFields(
|
||||
ctx context.Context, table string, schema ...string,
|
||||
) (fields map[string]*gdb.TableField, err error) {
|
||||
var (
|
||||
result gdb.Result
|
||||
link gdb.Link
|
||||
// When no schema is specified, the configuration item is returned by default
|
||||
usedSchema = gutil.GetOrDefaultStr(d.GetSchema(), schema...)
|
||||
)
|
||||
// When usedSchema is empty, return the default link
|
||||
if link, err = d.SlaveLink(usedSchema); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
// The link has been distinguished and no longer needs to judge the owner
|
||||
result, err = d.DoSelect(
|
||||
ctx, link,
|
||||
fmt.Sprintf(
|
||||
tableFieldsSqlTmp,
|
||||
strings.ToUpper(table),
|
||||
strings.ToUpper(d.GetSchema()),
|
||||
),
|
||||
)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
fields = make(map[string]*gdb.TableField)
|
||||
for i, m := range result {
|
||||
// m[NULLABLE] returns "N" "Y"
|
||||
// "N" means not null
|
||||
// "Y" means could be null
|
||||
var nullable bool
|
||||
if m["NULLABLE"].String() != "N" {
|
||||
nullable = true
|
||||
}
|
||||
fields[m["COLUMN_NAME"].String()] = &gdb.TableField{
|
||||
Index: i,
|
||||
Name: m["COLUMN_NAME"].String(),
|
||||
Type: m["DATA_TYPE"].String(),
|
||||
Null: nullable,
|
||||
Default: m["DATA_DEFAULT"].Val(),
|
||||
// Key: m["Key"].String(),
|
||||
// Extra: m["Extra"].String(),
|
||||
// Comment: m["Comment"].String(),
|
||||
}
|
||||
}
|
||||
return fields, nil
|
||||
}
|
||||
39
contrib/drivers/dm/dm_tables.go
Normal file
39
contrib/drivers/dm/dm_tables.go
Normal file
@ -0,0 +1,39 @@
|
||||
// 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 dm
|
||||
|
||||
import (
|
||||
"context"
|
||||
|
||||
"github.com/gogf/gf/v2/database/gdb"
|
||||
)
|
||||
|
||||
const (
|
||||
tablesSqlTmp = `SELECT * FROM ALL_TABLES`
|
||||
)
|
||||
|
||||
// Tables retrieves and returns the tables of current schema.
|
||||
// It's mainly used in cli tool chain for automatically generating the models.
|
||||
func (d *Driver) Tables(ctx context.Context, schema ...string) (tables []string, err error) {
|
||||
var result gdb.Result
|
||||
// When schema is empty, return the default link
|
||||
link, err := d.SlaveLink(schema...)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
// The link has been distinguished and no longer needs to judge the owner
|
||||
result, err = d.DoSelect(ctx, link, tablesSqlTmp)
|
||||
if err != nil {
|
||||
return
|
||||
}
|
||||
for _, m := range result {
|
||||
if v, ok := m["IOT_NAME"]; ok {
|
||||
tables = append(tables, v.String())
|
||||
}
|
||||
}
|
||||
return
|
||||
}
|
||||
@ -12,7 +12,6 @@ import (
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
_ "gitee.com/chunanyong/dm"
|
||||
"github.com/gogf/gf/v2/container/garray"
|
||||
"github.com/gogf/gf/v2/database/gdb"
|
||||
"github.com/gogf/gf/v2/frame/g"
|
||||
73
contrib/drivers/dm/dm_z_unit_issue_test.go
Normal file
73
contrib/drivers/dm/dm_z_unit_issue_test.go
Normal file
@ -0,0 +1,73 @@
|
||||
// Copyright 2019 gf Author(https://github.com/gogf/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://github.com/gogf/gf.
|
||||
|
||||
package dm_test
|
||||
|
||||
import (
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"github.com/gogf/gf/v2/os/gtime"
|
||||
"github.com/gogf/gf/v2/test/gtest"
|
||||
"github.com/gogf/gf/v2/text/gstr"
|
||||
)
|
||||
|
||||
func Test_Issue2594(t *testing.T) {
|
||||
table := "HANDLE_INFO"
|
||||
array := gstr.SplitAndTrim(gtest.DataContent(`issue`, `2594`, `sql.sql`), ";")
|
||||
for _, v := range array {
|
||||
if _, err := db.Exec(ctx, v); err != nil {
|
||||
gtest.Error(err)
|
||||
}
|
||||
}
|
||||
defer dropTable(table)
|
||||
|
||||
type HandleValueMysql struct {
|
||||
Index int64 `orm:"index"`
|
||||
Type string `orm:"type"`
|
||||
Data []byte `orm:"data"`
|
||||
}
|
||||
type HandleInfoMysql struct {
|
||||
Id int `orm:"id,primary" json:"id"`
|
||||
SubPrefix string `orm:"sub_prefix"`
|
||||
Prefix string `orm:"prefix"`
|
||||
HandleName string `orm:"handle_name"`
|
||||
CreateTime time.Time `orm:"create_time"`
|
||||
UpdateTime time.Time `orm:"update_time"`
|
||||
Value []HandleValueMysql `orm:"value"`
|
||||
}
|
||||
|
||||
gtest.C(t, func(t *gtest.T) {
|
||||
var h1 = HandleInfoMysql{
|
||||
SubPrefix: "p_",
|
||||
Prefix: "m_",
|
||||
HandleName: "name",
|
||||
CreateTime: gtime.Now().FormatTo("Y-m-d H:i:s").Time,
|
||||
UpdateTime: gtime.Now().FormatTo("Y-m-d H:i:s").Time,
|
||||
Value: []HandleValueMysql{
|
||||
{
|
||||
Index: 10,
|
||||
Type: "t1",
|
||||
Data: []byte("abc"),
|
||||
},
|
||||
{
|
||||
Index: 20,
|
||||
Type: "t2",
|
||||
Data: []byte("def"),
|
||||
},
|
||||
},
|
||||
}
|
||||
_, err := db.Model(table).OmitEmptyData().Insert(h1)
|
||||
t.AssertNil(err)
|
||||
|
||||
var h2 HandleInfoMysql
|
||||
err = db.Model(table).Scan(&h2)
|
||||
t.AssertNil(err)
|
||||
|
||||
h1.Id = 1
|
||||
t.Assert(h1, h2)
|
||||
})
|
||||
}
|
||||
@ -6,7 +6,7 @@ replace github.com/gogf/gf/v2 => ../../../
|
||||
|
||||
require (
|
||||
gitee.com/chunanyong/dm v1.8.12
|
||||
github.com/gogf/gf/v2 v2.6.2
|
||||
github.com/gogf/gf/v2 v2.6.3
|
||||
)
|
||||
|
||||
require (
|
||||
|
||||
10
contrib/drivers/dm/testdata/issue/2594/sql.sql
vendored
Normal file
10
contrib/drivers/dm/testdata/issue/2594/sql.sql
vendored
Normal file
@ -0,0 +1,10 @@
|
||||
CREATE TABLE HANDLE_INFO (
|
||||
ID INT IDENTITY (1, 1) NOT NULL,
|
||||
SUB_PREFIX VARCHAR(128),
|
||||
PREFIX VARCHAR(256),
|
||||
HANDLE_NAME VARCHAR(1024) NOT NULL,
|
||||
CREATE_TIME TIMESTAMP,
|
||||
UPDATE_TIME TIMESTAMP,
|
||||
VALUE BLOB ,
|
||||
NOT CLUSTER PRIMARY KEY (ID)
|
||||
);
|
||||
@ -4,7 +4,7 @@ go 1.18
|
||||
|
||||
require (
|
||||
github.com/denisenkom/go-mssqldb v0.12.3
|
||||
github.com/gogf/gf/v2 v2.6.2
|
||||
github.com/gogf/gf/v2 v2.6.3
|
||||
)
|
||||
|
||||
require (
|
||||
|
||||
@ -12,20 +12,11 @@
|
||||
package mssql
|
||||
|
||||
import (
|
||||
"context"
|
||||
"database/sql"
|
||||
"fmt"
|
||||
"strconv"
|
||||
"strings"
|
||||
|
||||
_ "github.com/denisenkom/go-mssqldb"
|
||||
|
||||
"github.com/gogf/gf/v2/database/gdb"
|
||||
"github.com/gogf/gf/v2/errors/gcode"
|
||||
"github.com/gogf/gf/v2/errors/gerror"
|
||||
"github.com/gogf/gf/v2/text/gregex"
|
||||
"github.com/gogf/gf/v2/text/gstr"
|
||||
"github.com/gogf/gf/v2/util/gutil"
|
||||
)
|
||||
|
||||
// Driver is the driver for SQL server database.
|
||||
@ -43,6 +34,21 @@ func init() {
|
||||
}
|
||||
}
|
||||
|
||||
// formatSqlTmp formats sql template string into one line.
|
||||
func formatSqlTmp(sqlTmp string) string {
|
||||
var err error
|
||||
// format sql template string.
|
||||
sqlTmp, err = gregex.ReplaceString(`[\n\r\s]+`, " ", gstr.Trim(sqlTmp))
|
||||
if err != nil {
|
||||
panic(err)
|
||||
}
|
||||
sqlTmp, err = gregex.ReplaceString(`\s{2,}`, " ", gstr.Trim(sqlTmp))
|
||||
if err != nil {
|
||||
panic(err)
|
||||
}
|
||||
return sqlTmp
|
||||
}
|
||||
|
||||
// New create and returns a driver that implements gdb.Driver, which supports operations for Mssql.
|
||||
func New() gdb.Driver {
|
||||
return &Driver{}
|
||||
@ -56,262 +62,7 @@ func (d *Driver) New(core *gdb.Core, node *gdb.ConfigNode) (gdb.DB, error) {
|
||||
}, nil
|
||||
}
|
||||
|
||||
// Open creates and returns an underlying sql.DB object for mssql.
|
||||
func (d *Driver) Open(config *gdb.ConfigNode) (db *sql.DB, err error) {
|
||||
var (
|
||||
source string
|
||||
underlyingDriverName = "sqlserver"
|
||||
)
|
||||
if config.Link != "" {
|
||||
// ============================================================================
|
||||
// Deprecated from v2.2.0.
|
||||
// ============================================================================
|
||||
source = config.Link
|
||||
// Custom changing the schema in runtime.
|
||||
if config.Name != "" {
|
||||
source, _ = gregex.ReplaceString(`database=([\w\.\-]+)+`, "database="+config.Name, source)
|
||||
}
|
||||
} else {
|
||||
source = fmt.Sprintf(
|
||||
"user id=%s;password=%s;server=%s;port=%s;database=%s;encrypt=disable",
|
||||
config.User, config.Pass, config.Host, config.Port, config.Name,
|
||||
)
|
||||
if config.Extra != "" {
|
||||
var extraMap map[string]interface{}
|
||||
if extraMap, err = gstr.Parse(config.Extra); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
for k, v := range extraMap {
|
||||
source += fmt.Sprintf(`;%s=%s`, k, v)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
if db, err = sql.Open(underlyingDriverName, source); err != nil {
|
||||
err = gerror.WrapCodef(
|
||||
gcode.CodeDbOperationError, err,
|
||||
`sql.Open failed for driver "%s" by source "%s"`, underlyingDriverName, source,
|
||||
)
|
||||
return nil, err
|
||||
}
|
||||
return
|
||||
}
|
||||
|
||||
// GetChars returns the security char for this type of database.
|
||||
func (d *Driver) GetChars() (charLeft string, charRight string) {
|
||||
return quoteChar, quoteChar
|
||||
}
|
||||
|
||||
// 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 "@px".
|
||||
newSql, _ = gregex.ReplaceStringFunc("\\?", sql, func(s string) string {
|
||||
index++
|
||||
return fmt.Sprintf("@p%d", index)
|
||||
})
|
||||
newSql, _ = gregex.ReplaceString("\"", "", newSql)
|
||||
return d.Core.DoFilter(ctx, link, d.parseSql(newSql), args)
|
||||
}
|
||||
|
||||
// parseSql does some replacement of the sql before commits it to underlying driver,
|
||||
// for support of microsoft sql server.
|
||||
func (d *Driver) parseSql(sql string) string {
|
||||
// SELECT * FROM USER WHERE ID=1 LIMIT 1
|
||||
if m, _ := gregex.MatchString(`^SELECT(.+)LIMIT 1$`, sql); len(m) > 1 {
|
||||
return fmt.Sprintf(`SELECT TOP 1 %s`, m[1])
|
||||
}
|
||||
// SELECT * FROM USER WHERE AGE>18 ORDER BY ID DESC LIMIT 100, 200
|
||||
patten := `^\s*(?i)(SELECT)|(LIMIT\s*(\d+)\s*,\s*(\d+))`
|
||||
if gregex.IsMatchString(patten, sql) == false {
|
||||
return sql
|
||||
}
|
||||
res, err := gregex.MatchAllString(patten, sql)
|
||||
if err != nil {
|
||||
return ""
|
||||
}
|
||||
var (
|
||||
index = 0
|
||||
keyword = strings.TrimSpace(res[index][0])
|
||||
)
|
||||
index++
|
||||
switch strings.ToUpper(keyword) {
|
||||
case "SELECT":
|
||||
// LIMIT statement checks.
|
||||
if len(res) < 2 ||
|
||||
(strings.HasPrefix(res[index][0], "LIMIT") == false &&
|
||||
strings.HasPrefix(res[index][0], "limit") == false) {
|
||||
break
|
||||
}
|
||||
if gregex.IsMatchString("((?i)SELECT)(.+)((?i)LIMIT)", sql) == false {
|
||||
break
|
||||
}
|
||||
// ORDER BY statement checks.
|
||||
var (
|
||||
selectStr = ""
|
||||
orderStr = ""
|
||||
haveOrder = gregex.IsMatchString("((?i)SELECT)(.+)((?i)ORDER BY)", sql)
|
||||
)
|
||||
if haveOrder {
|
||||
queryExpr, _ := gregex.MatchString("((?i)SELECT)(.+)((?i)ORDER BY)", sql)
|
||||
if len(queryExpr) != 4 ||
|
||||
strings.EqualFold(queryExpr[1], "SELECT") == false ||
|
||||
strings.EqualFold(queryExpr[3], "ORDER BY") == false {
|
||||
break
|
||||
}
|
||||
selectStr = queryExpr[2]
|
||||
orderExpr, _ := gregex.MatchString("((?i)ORDER BY)(.+)((?i)LIMIT)", sql)
|
||||
if len(orderExpr) != 4 ||
|
||||
strings.EqualFold(orderExpr[1], "ORDER BY") == false ||
|
||||
strings.EqualFold(orderExpr[3], "LIMIT") == false {
|
||||
break
|
||||
}
|
||||
orderStr = orderExpr[2]
|
||||
} else {
|
||||
queryExpr, _ := gregex.MatchString("((?i)SELECT)(.+)((?i)LIMIT)", sql)
|
||||
if len(queryExpr) != 4 ||
|
||||
strings.EqualFold(queryExpr[1], "SELECT") == false ||
|
||||
strings.EqualFold(queryExpr[3], "LIMIT") == false {
|
||||
break
|
||||
}
|
||||
selectStr = queryExpr[2]
|
||||
}
|
||||
first, limit := 0, 0
|
||||
for i := 1; i < len(res[index]); i++ {
|
||||
if len(strings.TrimSpace(res[index][i])) == 0 {
|
||||
continue
|
||||
}
|
||||
|
||||
if strings.HasPrefix(res[index][i], "LIMIT") ||
|
||||
strings.HasPrefix(res[index][i], "limit") {
|
||||
first, _ = strconv.Atoi(res[index][i+1])
|
||||
limit, _ = strconv.Atoi(res[index][i+2])
|
||||
break
|
||||
}
|
||||
}
|
||||
if haveOrder {
|
||||
sql = fmt.Sprintf(
|
||||
"SELECT * FROM "+
|
||||
"(SELECT ROW_NUMBER() OVER (ORDER BY %s) as ROWNUMBER_, %s ) as TMP_ "+
|
||||
"WHERE TMP_.ROWNUMBER_ > %d AND TMP_.ROWNUMBER_ <= %d",
|
||||
orderStr, selectStr, first, first+limit,
|
||||
)
|
||||
} else {
|
||||
if first == 0 {
|
||||
first = limit
|
||||
}
|
||||
sql = fmt.Sprintf(
|
||||
"SELECT * FROM (SELECT TOP %d * FROM (SELECT TOP %d %s) as TMP1_ ) as TMP2_ ",
|
||||
limit, first+limit, selectStr,
|
||||
)
|
||||
}
|
||||
default:
|
||||
}
|
||||
return sql
|
||||
}
|
||||
|
||||
// Tables retrieves and returns the tables of current schema.
|
||||
// It's mainly used in cli tool chain for automatically generating the models.
|
||||
func (d *Driver) Tables(ctx context.Context, schema ...string) (tables []string, err error) {
|
||||
var result gdb.Result
|
||||
link, err := d.SlaveLink(schema...)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
result, err = d.DoSelect(
|
||||
ctx, link, `SELECT NAME FROM SYSOBJECTS WHERE XTYPE='U' AND STATUS >= 0 ORDER BY NAME`,
|
||||
)
|
||||
if err != nil {
|
||||
return
|
||||
}
|
||||
for _, m := range result {
|
||||
for _, v := range m {
|
||||
tables = append(tables, v.String())
|
||||
}
|
||||
}
|
||||
return
|
||||
}
|
||||
|
||||
// TableFields retrieves and returns the fields' information of specified table of current schema.
|
||||
//
|
||||
// Also see DriverMysql.TableFields.
|
||||
func (d *Driver) TableFields(ctx context.Context, table string, schema ...string) (fields map[string]*gdb.TableField, err error) {
|
||||
var (
|
||||
result gdb.Result
|
||||
link gdb.Link
|
||||
usedSchema = gutil.GetOrDefaultStr(d.GetSchema(), schema...)
|
||||
)
|
||||
if link, err = d.SlaveLink(usedSchema); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
structureSql := fmt.Sprintf(`
|
||||
SELECT
|
||||
a.name Field,
|
||||
CASE b.name
|
||||
WHEN 'datetime' THEN 'datetime'
|
||||
WHEN 'numeric' THEN b.name + '(' + convert(varchar(20), a.xprec) + ',' + convert(varchar(20), a.xscale) + ')'
|
||||
WHEN 'char' THEN b.name + '(' + convert(varchar(20), a.length)+ ')'
|
||||
WHEN 'varchar' THEN b.name + '(' + convert(varchar(20), a.length)+ ')'
|
||||
ELSE b.name + '(' + convert(varchar(20),a.length)+ ')' END AS Type,
|
||||
CASE WHEN a.isnullable=1 THEN 'YES' ELSE 'NO' end AS [Null],
|
||||
CASE WHEN exists (
|
||||
SELECT 1 FROM sysobjects WHERE xtype='PK' AND name IN (
|
||||
SELECT name FROM sysindexes WHERE indid IN (
|
||||
SELECT indid FROM sysindexkeys WHERE id = a.id AND colid=a.colid
|
||||
)
|
||||
)
|
||||
) THEN 'PRI' ELSE '' END AS [Key],
|
||||
CASE WHEN COLUMNPROPERTY(a.id,a.name,'IsIdentity')=1 THEN 'auto_increment' ELSE '' END Extra,
|
||||
isnull(e.text,'') AS [Default],
|
||||
isnull(g.[value],'') AS [Comment]
|
||||
FROM syscolumns a
|
||||
LEFT JOIN systypes b ON a.xtype=b.xtype AND a.xusertype=b.xusertype
|
||||
INNER JOIN sysobjects d ON a.id=d.id AND d.xtype='U' AND d.name<>'dtproperties'
|
||||
LEFT JOIN syscomments e ON a.cdefault=e.id
|
||||
LEFT JOIN sys.extended_properties g ON a.id=g.major_id AND a.colid=g.minor_id
|
||||
LEFT JOIN sys.extended_properties f ON d.id=f.major_id AND f.minor_id =0
|
||||
WHERE d.name='%s'
|
||||
ORDER BY a.id,a.colorder`,
|
||||
table,
|
||||
)
|
||||
structureSql, _ = gregex.ReplaceString(`[\n\r\s]+`, " ", gstr.Trim(structureSql))
|
||||
result, err = d.DoSelect(ctx, link, structureSql)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
fields = make(map[string]*gdb.TableField)
|
||||
for i, m := range result {
|
||||
fields[m["Field"].String()] = &gdb.TableField{
|
||||
Index: i,
|
||||
Name: m["Field"].String(),
|
||||
Type: m["Type"].String(),
|
||||
Null: m["Null"].Bool(),
|
||||
Key: m["Key"].String(),
|
||||
Default: m["Default"].Val(),
|
||||
Extra: m["Extra"].String(),
|
||||
Comment: m["Comment"].String(),
|
||||
}
|
||||
}
|
||||
return fields, nil
|
||||
}
|
||||
|
||||
// DoInsert inserts or updates data forF 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.InsertOptionSave:
|
||||
return nil, gerror.NewCode(
|
||||
gcode.CodeNotSupported,
|
||||
`Save operation is not supported by mssql driver`,
|
||||
)
|
||||
|
||||
case gdb.InsertOptionReplace:
|
||||
return nil, gerror.NewCode(
|
||||
gcode.CodeNotSupported,
|
||||
`Replace operation is not supported by mssql driver`,
|
||||
)
|
||||
|
||||
default:
|
||||
return d.Core.DoInsert(ctx, link, table, list, option)
|
||||
}
|
||||
}
|
||||
|
||||
163
contrib/drivers/mssql/mssql_do_filter.go
Normal file
163
contrib/drivers/mssql/mssql_do_filter.go
Normal file
@ -0,0 +1,163 @@
|
||||
// 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 mssql
|
||||
|
||||
import (
|
||||
"context"
|
||||
"fmt"
|
||||
|
||||
"strconv"
|
||||
"strings"
|
||||
|
||||
"github.com/gogf/gf/v2/database/gdb"
|
||||
"github.com/gogf/gf/v2/text/gregex"
|
||||
"github.com/gogf/gf/v2/text/gstr"
|
||||
)
|
||||
|
||||
var (
|
||||
selectSqlTmp = `SELECT * FROM (SELECT TOP %d * FROM (SELECT TOP %d %s) as TMP1_ ) as TMP2_ `
|
||||
selectWithOrderSqlTmp = `
|
||||
SELECT * FROM (SELECT ROW_NUMBER() OVER (ORDER BY %s) as ROWNUMBER_, %s ) as TMP_
|
||||
WHERE TMP_.ROWNUMBER_ > %d AND TMP_.ROWNUMBER_ <= %d
|
||||
`
|
||||
)
|
||||
|
||||
func init() {
|
||||
selectWithOrderSqlTmp = formatSqlTmp(selectWithOrderSqlTmp)
|
||||
}
|
||||
|
||||
// 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 "@px".
|
||||
newSql, err = gregex.ReplaceStringFunc("\\?", sql, func(s string) string {
|
||||
index++
|
||||
return fmt.Sprintf("@p%d", index)
|
||||
})
|
||||
if err != nil {
|
||||
return "", nil, err
|
||||
}
|
||||
newSql, err = gregex.ReplaceString("\"", "", newSql)
|
||||
if err != nil {
|
||||
return "", nil, err
|
||||
}
|
||||
newSql, err = d.parseSql(newSql)
|
||||
if err != nil {
|
||||
return "", nil, err
|
||||
}
|
||||
newArgs = args
|
||||
return d.Core.DoFilter(ctx, link, newSql, newArgs)
|
||||
}
|
||||
|
||||
// parseSql does some replacement of the sql before commits it to underlying driver,
|
||||
// for support of microsoft sql server.
|
||||
func (d *Driver) parseSql(toBeCommittedSql string) (string, error) {
|
||||
var (
|
||||
err error
|
||||
operation = gstr.StrTillEx(toBeCommittedSql, " ")
|
||||
keyword = strings.ToUpper(gstr.Trim(operation))
|
||||
)
|
||||
switch keyword {
|
||||
case "SELECT":
|
||||
toBeCommittedSql, err = d.handleSelectSqlReplacement(toBeCommittedSql)
|
||||
if err != nil {
|
||||
return "", err
|
||||
}
|
||||
}
|
||||
return toBeCommittedSql, nil
|
||||
}
|
||||
|
||||
func (d *Driver) handleSelectSqlReplacement(toBeCommittedSql string) (newSql string, err error) {
|
||||
// SELECT * FROM USER WHERE ID=1 LIMIT 1
|
||||
match, err := gregex.MatchString(`^SELECT(.+)LIMIT 1$`, toBeCommittedSql)
|
||||
if err != nil {
|
||||
return "", err
|
||||
}
|
||||
if len(match) > 1 {
|
||||
return fmt.Sprintf(`SELECT TOP 1 %s`, match[1]), nil
|
||||
}
|
||||
|
||||
// SELECT * FROM USER WHERE AGE>18 ORDER BY ID DESC LIMIT 100, 200
|
||||
patten := `^\s*(?i)(SELECT)|(LIMIT\s*(\d+)\s*,\s*(\d+))`
|
||||
if gregex.IsMatchString(patten, toBeCommittedSql) == false {
|
||||
return toBeCommittedSql, nil
|
||||
}
|
||||
allMatch, err := gregex.MatchAllString(patten, toBeCommittedSql)
|
||||
if err != nil {
|
||||
return "", err
|
||||
}
|
||||
var index = 1
|
||||
// LIMIT statement checks.
|
||||
if len(allMatch) < 2 ||
|
||||
(strings.HasPrefix(allMatch[index][0], "LIMIT") == false &&
|
||||
strings.HasPrefix(allMatch[index][0], "limit") == false) {
|
||||
return toBeCommittedSql, nil
|
||||
}
|
||||
if gregex.IsMatchString("((?i)SELECT)(.+)((?i)LIMIT)", toBeCommittedSql) == false {
|
||||
return toBeCommittedSql, nil
|
||||
}
|
||||
// ORDER BY statement checks.
|
||||
var (
|
||||
selectStr = ""
|
||||
orderStr = ""
|
||||
haveOrder = gregex.IsMatchString("((?i)SELECT)(.+)((?i)ORDER BY)", toBeCommittedSql)
|
||||
)
|
||||
if haveOrder {
|
||||
queryExpr, _ := gregex.MatchString("((?i)SELECT)(.+)((?i)ORDER BY)", toBeCommittedSql)
|
||||
if len(queryExpr) != 4 ||
|
||||
strings.EqualFold(queryExpr[1], "SELECT") == false ||
|
||||
strings.EqualFold(queryExpr[3], "ORDER BY") == false {
|
||||
return toBeCommittedSql, nil
|
||||
}
|
||||
selectStr = queryExpr[2]
|
||||
orderExpr, _ := gregex.MatchString("((?i)ORDER BY)(.+)((?i)LIMIT)", toBeCommittedSql)
|
||||
if len(orderExpr) != 4 ||
|
||||
strings.EqualFold(orderExpr[1], "ORDER BY") == false ||
|
||||
strings.EqualFold(orderExpr[3], "LIMIT") == false {
|
||||
return toBeCommittedSql, nil
|
||||
}
|
||||
orderStr = orderExpr[2]
|
||||
} else {
|
||||
queryExpr, _ := gregex.MatchString("((?i)SELECT)(.+)((?i)LIMIT)", toBeCommittedSql)
|
||||
if len(queryExpr) != 4 ||
|
||||
strings.EqualFold(queryExpr[1], "SELECT") == false ||
|
||||
strings.EqualFold(queryExpr[3], "LIMIT") == false {
|
||||
return toBeCommittedSql, nil
|
||||
}
|
||||
selectStr = queryExpr[2]
|
||||
}
|
||||
first, limit := 0, 0
|
||||
for i := 1; i < len(allMatch[index]); i++ {
|
||||
if len(strings.TrimSpace(allMatch[index][i])) == 0 {
|
||||
continue
|
||||
}
|
||||
if strings.HasPrefix(allMatch[index][i], "LIMIT") ||
|
||||
strings.HasPrefix(allMatch[index][i], "limit") {
|
||||
first, _ = strconv.Atoi(allMatch[index][i+1])
|
||||
limit, _ = strconv.Atoi(allMatch[index][i+2])
|
||||
break
|
||||
}
|
||||
}
|
||||
if haveOrder {
|
||||
toBeCommittedSql = fmt.Sprintf(
|
||||
selectWithOrderSqlTmp,
|
||||
orderStr, selectStr, first, first+limit,
|
||||
)
|
||||
return toBeCommittedSql, nil
|
||||
}
|
||||
|
||||
if first == 0 {
|
||||
first = limit
|
||||
}
|
||||
toBeCommittedSql = fmt.Sprintf(
|
||||
selectSqlTmp,
|
||||
limit, first+limit, selectStr,
|
||||
)
|
||||
return toBeCommittedSql, nil
|
||||
}
|
||||
36
contrib/drivers/mssql/mssql_do_insert.go
Normal file
36
contrib/drivers/mssql/mssql_do_insert.go
Normal file
@ -0,0 +1,36 @@
|
||||
// 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 mssql
|
||||
|
||||
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 forF 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.InsertOptionSave:
|
||||
return nil, gerror.NewCode(
|
||||
gcode.CodeNotSupported,
|
||||
`Save operation is not supported by mssql driver`,
|
||||
)
|
||||
|
||||
case gdb.InsertOptionReplace:
|
||||
return nil, gerror.NewCode(
|
||||
gcode.CodeNotSupported,
|
||||
`Replace operation is not supported by mssql driver`,
|
||||
)
|
||||
|
||||
default:
|
||||
return d.Core.DoInsert(ctx, link, table, list, option)
|
||||
}
|
||||
}
|
||||
59
contrib/drivers/mssql/mssql_open.go
Normal file
59
contrib/drivers/mssql/mssql_open.go
Normal file
@ -0,0 +1,59 @@
|
||||
// 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 mssql
|
||||
|
||||
import (
|
||||
"database/sql"
|
||||
"fmt"
|
||||
|
||||
"github.com/gogf/gf/v2/database/gdb"
|
||||
"github.com/gogf/gf/v2/errors/gcode"
|
||||
"github.com/gogf/gf/v2/errors/gerror"
|
||||
"github.com/gogf/gf/v2/text/gregex"
|
||||
"github.com/gogf/gf/v2/text/gstr"
|
||||
)
|
||||
|
||||
// Open creates and returns an underlying sql.DB object for mssql.
|
||||
func (d *Driver) Open(config *gdb.ConfigNode) (db *sql.DB, err error) {
|
||||
var (
|
||||
source string
|
||||
underlyingDriverName = "sqlserver"
|
||||
)
|
||||
if config.Link != "" {
|
||||
// ============================================================================
|
||||
// Deprecated from v2.2.0.
|
||||
// ============================================================================
|
||||
source = config.Link
|
||||
// Custom changing the schema in runtime.
|
||||
if config.Name != "" {
|
||||
source, _ = gregex.ReplaceString(`database=([\w\.\-]+)+`, "database="+config.Name, source)
|
||||
}
|
||||
} else {
|
||||
source = fmt.Sprintf(
|
||||
"user id=%s;password=%s;server=%s;port=%s;database=%s;encrypt=disable",
|
||||
config.User, config.Pass, config.Host, config.Port, config.Name,
|
||||
)
|
||||
if config.Extra != "" {
|
||||
var extraMap map[string]interface{}
|
||||
if extraMap, err = gstr.Parse(config.Extra); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
for k, v := range extraMap {
|
||||
source += fmt.Sprintf(`;%s=%s`, k, v)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
if db, err = sql.Open(underlyingDriverName, source); err != nil {
|
||||
err = gerror.WrapCodef(
|
||||
gcode.CodeDbOperationError, err,
|
||||
`sql.Open failed for driver "%s" by source "%s"`, underlyingDriverName, source,
|
||||
)
|
||||
return nil, err
|
||||
}
|
||||
return
|
||||
}
|
||||
84
contrib/drivers/mssql/mssql_table_fields.go
Normal file
84
contrib/drivers/mssql/mssql_table_fields.go
Normal file
@ -0,0 +1,84 @@
|
||||
// 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 mssql
|
||||
|
||||
import (
|
||||
"context"
|
||||
"fmt"
|
||||
|
||||
"github.com/gogf/gf/v2/database/gdb"
|
||||
"github.com/gogf/gf/v2/util/gutil"
|
||||
)
|
||||
|
||||
var (
|
||||
tableFieldsSqlTmp = `
|
||||
SELECT
|
||||
a.name Field,
|
||||
CASE b.name
|
||||
WHEN 'datetime' THEN 'datetime'
|
||||
WHEN 'numeric' THEN b.name + '(' + convert(varchar(20), a.xprec) + ',' + convert(varchar(20), a.xscale) + ')'
|
||||
WHEN 'char' THEN b.name + '(' + convert(varchar(20), a.length)+ ')'
|
||||
WHEN 'varchar' THEN b.name + '(' + convert(varchar(20), a.length)+ ')'
|
||||
ELSE b.name + '(' + convert(varchar(20),a.length)+ ')' END AS Type,
|
||||
CASE WHEN a.isnullable=1 THEN 'YES' ELSE 'NO' end AS [Null],
|
||||
CASE WHEN exists (
|
||||
SELECT 1 FROM sysobjects WHERE xtype='PK' AND name IN (
|
||||
SELECT name FROM sysindexes WHERE indid IN (
|
||||
SELECT indid FROM sysindexkeys WHERE id = a.id AND colid=a.colid
|
||||
)
|
||||
)
|
||||
) THEN 'PRI' ELSE '' END AS [Key],
|
||||
CASE WHEN COLUMNPROPERTY(a.id,a.name,'IsIdentity')=1 THEN 'auto_increment' ELSE '' END Extra,
|
||||
isnull(e.text,'') AS [Default],
|
||||
isnull(g.[value],'') AS [Comment]
|
||||
FROM syscolumns a
|
||||
LEFT JOIN systypes b ON a.xtype=b.xtype AND a.xusertype=b.xusertype
|
||||
INNER JOIN sysobjects d ON a.id=d.id AND d.xtype='U' AND d.name<>'dtproperties'
|
||||
LEFT JOIN syscomments e ON a.cdefault=e.id
|
||||
LEFT JOIN sys.extended_properties g ON a.id=g.major_id AND a.colid=g.minor_id
|
||||
LEFT JOIN sys.extended_properties f ON d.id=f.major_id AND f.minor_id =0
|
||||
WHERE d.name='%s'
|
||||
ORDER BY a.id,a.colorder
|
||||
`
|
||||
)
|
||||
|
||||
func init() {
|
||||
tableFieldsSqlTmp = formatSqlTmp(tableFieldsSqlTmp)
|
||||
}
|
||||
|
||||
// TableFields retrieves and returns the fields' information of specified table of current schema.
|
||||
//
|
||||
// Also see DriverMysql.TableFields.
|
||||
func (d *Driver) TableFields(ctx context.Context, table string, schema ...string) (fields map[string]*gdb.TableField, err error) {
|
||||
var (
|
||||
result gdb.Result
|
||||
link gdb.Link
|
||||
usedSchema = gutil.GetOrDefaultStr(d.GetSchema(), schema...)
|
||||
)
|
||||
if link, err = d.SlaveLink(usedSchema); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
structureSql := fmt.Sprintf(tableFieldsSqlTmp, table)
|
||||
result, err = d.DoSelect(ctx, link, structureSql)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
fields = make(map[string]*gdb.TableField)
|
||||
for i, m := range result {
|
||||
fields[m["Field"].String()] = &gdb.TableField{
|
||||
Index: i,
|
||||
Name: m["Field"].String(),
|
||||
Type: m["Type"].String(),
|
||||
Null: m["Null"].Bool(),
|
||||
Key: m["Key"].String(),
|
||||
Default: m["Default"].Val(),
|
||||
Extra: m["Extra"].String(),
|
||||
Comment: m["Comment"].String(),
|
||||
}
|
||||
}
|
||||
return fields, nil
|
||||
}
|
||||
38
contrib/drivers/mssql/mssql_tables.go
Normal file
38
contrib/drivers/mssql/mssql_tables.go
Normal file
@ -0,0 +1,38 @@
|
||||
// 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 mssql
|
||||
|
||||
import (
|
||||
"context"
|
||||
|
||||
"github.com/gogf/gf/v2/database/gdb"
|
||||
)
|
||||
|
||||
const (
|
||||
tablesSqlTmp = `SELECT NAME FROM SYSOBJECTS WHERE XTYPE='U' AND STATUS >= 0 ORDER BY NAME`
|
||||
)
|
||||
|
||||
// Tables retrieves and returns the tables of current schema.
|
||||
// It's mainly used in cli tool chain for automatically generating the models.
|
||||
func (d *Driver) Tables(ctx context.Context, schema ...string) (tables []string, err error) {
|
||||
var result gdb.Result
|
||||
link, err := d.SlaveLink(schema...)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
result, err = d.DoSelect(ctx, link, tablesSqlTmp)
|
||||
if err != nil {
|
||||
return
|
||||
}
|
||||
for _, m := range result {
|
||||
for _, v := range m {
|
||||
tables = append(tables, v.String())
|
||||
}
|
||||
}
|
||||
return
|
||||
}
|
||||
@ -10,7 +10,6 @@ import (
|
||||
"context"
|
||||
"fmt"
|
||||
|
||||
_ "github.com/denisenkom/go-mssqldb"
|
||||
"github.com/gogf/gf/v2/container/garray"
|
||||
"github.com/gogf/gf/v2/database/gdb"
|
||||
"github.com/gogf/gf/v2/frame/g"
|
||||
@ -4,7 +4,7 @@ go 1.18
|
||||
|
||||
require (
|
||||
github.com/go-sql-driver/mysql v1.7.1
|
||||
github.com/gogf/gf/v2 v2.6.2
|
||||
github.com/gogf/gf/v2 v2.6.3
|
||||
)
|
||||
|
||||
require (
|
||||
|
||||
@ -8,20 +8,10 @@
|
||||
package mysql
|
||||
|
||||
import (
|
||||
"context"
|
||||
"database/sql"
|
||||
"fmt"
|
||||
"net/url"
|
||||
"strings"
|
||||
|
||||
_ "github.com/go-sql-driver/mysql"
|
||||
|
||||
"github.com/gogf/gf/v2/database/gdb"
|
||||
"github.com/gogf/gf/v2/errors/gcode"
|
||||
"github.com/gogf/gf/v2/errors/gerror"
|
||||
"github.com/gogf/gf/v2/frame/g"
|
||||
"github.com/gogf/gf/v2/text/gregex"
|
||||
"github.com/gogf/gf/v2/util/gutil"
|
||||
)
|
||||
|
||||
// Driver is the driver for mysql database.
|
||||
@ -59,119 +49,7 @@ func (d *Driver) New(core *gdb.Core, node *gdb.ConfigNode) (gdb.DB, error) {
|
||||
}, nil
|
||||
}
|
||||
|
||||
// Open creates and returns an underlying sql.DB object for mysql.
|
||||
// Note that it converts time.Time argument to local timezone in default.
|
||||
func (d *Driver) Open(config *gdb.ConfigNode) (db *sql.DB, err error) {
|
||||
var (
|
||||
source string
|
||||
underlyingDriverName = "mysql"
|
||||
)
|
||||
// [username[:password]@][protocol[(address)]]/dbname[?param1=value1&...¶mN=valueN]
|
||||
if config.Link != "" {
|
||||
// ============================================================================
|
||||
// Deprecated from v2.2.0.
|
||||
// ============================================================================
|
||||
source = config.Link
|
||||
// Custom changing the schema in runtime.
|
||||
if config.Name != "" {
|
||||
source, _ = gregex.ReplaceString(`/([\w\.\-]+)+`, "/"+config.Name, source)
|
||||
}
|
||||
} else {
|
||||
// TODO: Do not set charset when charset is not specified (in v2.5.0)
|
||||
source = fmt.Sprintf(
|
||||
"%s:%s@%s(%s:%s)/%s?charset=%s",
|
||||
config.User, config.Pass, config.Protocol, config.Host, config.Port, config.Name, config.Charset,
|
||||
)
|
||||
if config.Timezone != "" {
|
||||
if strings.Contains(config.Timezone, "/") {
|
||||
config.Timezone = url.QueryEscape(config.Timezone)
|
||||
}
|
||||
source = fmt.Sprintf("%s&loc=%s", source, config.Timezone)
|
||||
}
|
||||
if config.Extra != "" {
|
||||
source = fmt.Sprintf("%s&%s", source, config.Extra)
|
||||
}
|
||||
}
|
||||
if db, err = sql.Open(underlyingDriverName, source); err != nil {
|
||||
err = gerror.WrapCodef(
|
||||
gcode.CodeDbOperationError, err,
|
||||
`sql.Open failed for driver "%s" by source "%s"`, underlyingDriverName, source,
|
||||
)
|
||||
return nil, err
|
||||
}
|
||||
return
|
||||
}
|
||||
|
||||
// GetChars returns the security char for this type of database.
|
||||
func (d *Driver) GetChars() (charLeft string, charRight string) {
|
||||
return quoteChar, quoteChar
|
||||
}
|
||||
|
||||
// DoFilter handles the sql before posts it to database.
|
||||
func (d *Driver) DoFilter(ctx context.Context, link gdb.Link, sql string, args []interface{}) (newSql string, newArgs []interface{}, err error) {
|
||||
return d.Core.DoFilter(ctx, link, sql, args)
|
||||
}
|
||||
|
||||
// Tables retrieves and returns the tables of current schema.
|
||||
// It's mainly used in cli tool chain for automatically generating the models.
|
||||
func (d *Driver) Tables(ctx context.Context, schema ...string) (tables []string, err error) {
|
||||
var result gdb.Result
|
||||
link, err := d.SlaveLink(schema...)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
result, err = d.DoSelect(ctx, link, `SHOW TABLES`)
|
||||
if err != nil {
|
||||
return
|
||||
}
|
||||
for _, m := range result {
|
||||
for _, v := range m {
|
||||
tables = append(tables, v.String())
|
||||
}
|
||||
}
|
||||
return
|
||||
}
|
||||
|
||||
// TableFields retrieves and returns the fields' information of specified table of current
|
||||
// schema.
|
||||
//
|
||||
// The parameter `link` is optional, if given nil it automatically retrieves a raw sql connection
|
||||
// as its link to proceed necessary sql query.
|
||||
//
|
||||
// Note that it returns a map containing the field name and its corresponding fields.
|
||||
// As a map is unsorted, the TableField struct has a "Index" field marks its sequence in
|
||||
// the fields.
|
||||
//
|
||||
// It's using cache feature to enhance the performance, which is never expired util the
|
||||
// process restarts.
|
||||
func (d *Driver) TableFields(ctx context.Context, table string, schema ...string) (fields map[string]*gdb.TableField, err error) {
|
||||
var (
|
||||
result gdb.Result
|
||||
link gdb.Link
|
||||
usedSchema = gutil.GetOrDefaultStr(d.GetSchema(), schema...)
|
||||
)
|
||||
if link, err = d.SlaveLink(usedSchema); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
result, err = d.DoSelect(
|
||||
ctx, link,
|
||||
fmt.Sprintf(`SHOW FULL COLUMNS FROM %s`, d.QuoteWord(table)),
|
||||
)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
fields = make(map[string]*gdb.TableField)
|
||||
for i, m := range result {
|
||||
fields[m["Field"].String()] = &gdb.TableField{
|
||||
Index: i,
|
||||
Name: m["Field"].String(),
|
||||
Type: m["Type"].String(),
|
||||
Null: m["Null"].Bool(),
|
||||
Key: m["Key"].String(),
|
||||
Default: m["Default"].Val(),
|
||||
Extra: m["Extra"].String(),
|
||||
Comment: m["Comment"].String(),
|
||||
}
|
||||
}
|
||||
return fields, nil
|
||||
}
|
||||
|
||||
18
contrib/drivers/mysql/mysql_do_filter.go
Normal file
18
contrib/drivers/mysql/mysql_do_filter.go
Normal file
@ -0,0 +1,18 @@
|
||||
// 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 mysql
|
||||
|
||||
import (
|
||||
"context"
|
||||
|
||||
"github.com/gogf/gf/v2/database/gdb"
|
||||
)
|
||||
|
||||
// DoFilter handles the sql before posts it to database.
|
||||
func (d *Driver) DoFilter(ctx context.Context, link gdb.Link, sql string, args []interface{}) (newSql string, newArgs []interface{}, err error) {
|
||||
return d.Core.DoFilter(ctx, link, sql, args)
|
||||
}
|
||||
63
contrib/drivers/mysql/mysql_open.go
Normal file
63
contrib/drivers/mysql/mysql_open.go
Normal file
@ -0,0 +1,63 @@
|
||||
// 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 mysql
|
||||
|
||||
import (
|
||||
"database/sql"
|
||||
"fmt"
|
||||
|
||||
"net/url"
|
||||
"strings"
|
||||
|
||||
"github.com/gogf/gf/v2/database/gdb"
|
||||
"github.com/gogf/gf/v2/errors/gcode"
|
||||
"github.com/gogf/gf/v2/errors/gerror"
|
||||
"github.com/gogf/gf/v2/text/gregex"
|
||||
)
|
||||
|
||||
// Open creates and returns an underlying sql.DB object for mysql.
|
||||
// Note that it converts time.Time argument to local timezone in default.
|
||||
func (d *Driver) Open(config *gdb.ConfigNode) (db *sql.DB, err error) {
|
||||
var (
|
||||
source string
|
||||
underlyingDriverName = "mysql"
|
||||
)
|
||||
// [username[:password]@][protocol[(address)]]/dbname[?param1=value1&...¶mN=valueN]
|
||||
if config.Link != "" {
|
||||
// ============================================================================
|
||||
// Deprecated from v2.2.0.
|
||||
// ============================================================================
|
||||
source = config.Link
|
||||
// Custom changing the schema in runtime.
|
||||
if config.Name != "" {
|
||||
source, _ = gregex.ReplaceString(`/([\w\.\-]+)+`, "/"+config.Name, source)
|
||||
}
|
||||
} else {
|
||||
// TODO: Do not set charset when charset is not specified (in v2.5.0)
|
||||
source = fmt.Sprintf(
|
||||
"%s:%s@%s(%s:%s)/%s?charset=%s",
|
||||
config.User, config.Pass, config.Protocol, config.Host, config.Port, config.Name, config.Charset,
|
||||
)
|
||||
if config.Timezone != "" {
|
||||
if strings.Contains(config.Timezone, "/") {
|
||||
config.Timezone = url.QueryEscape(config.Timezone)
|
||||
}
|
||||
source = fmt.Sprintf("%s&loc=%s", source, config.Timezone)
|
||||
}
|
||||
if config.Extra != "" {
|
||||
source = fmt.Sprintf("%s&%s", source, config.Extra)
|
||||
}
|
||||
}
|
||||
if db, err = sql.Open(underlyingDriverName, source); err != nil {
|
||||
err = gerror.WrapCodef(
|
||||
gcode.CodeDbOperationError, err,
|
||||
`sql.Open failed for driver "%s" by source "%s"`, underlyingDriverName, source,
|
||||
)
|
||||
return nil, err
|
||||
}
|
||||
return
|
||||
}
|
||||
59
contrib/drivers/mysql/mysql_table_fields.go
Normal file
59
contrib/drivers/mysql/mysql_table_fields.go
Normal file
@ -0,0 +1,59 @@
|
||||
// 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 mysql
|
||||
|
||||
import (
|
||||
"context"
|
||||
"fmt"
|
||||
|
||||
"github.com/gogf/gf/v2/database/gdb"
|
||||
"github.com/gogf/gf/v2/util/gutil"
|
||||
)
|
||||
|
||||
// TableFields retrieves and returns the fields' information of specified table of current
|
||||
// schema.
|
||||
//
|
||||
// The parameter `link` is optional, if given nil it automatically retrieves a raw sql connection
|
||||
// as its link to proceed necessary sql query.
|
||||
//
|
||||
// Note that it returns a map containing the field name and its corresponding fields.
|
||||
// As a map is unsorted, the TableField struct has a "Index" field marks its sequence in
|
||||
// the fields.
|
||||
//
|
||||
// It's using cache feature to enhance the performance, which is never expired util the
|
||||
// process restarts.
|
||||
func (d *Driver) TableFields(ctx context.Context, table string, schema ...string) (fields map[string]*gdb.TableField, err error) {
|
||||
var (
|
||||
result gdb.Result
|
||||
link gdb.Link
|
||||
usedSchema = gutil.GetOrDefaultStr(d.GetSchema(), schema...)
|
||||
)
|
||||
if link, err = d.SlaveLink(usedSchema); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
result, err = d.DoSelect(
|
||||
ctx, link,
|
||||
fmt.Sprintf(`SHOW FULL COLUMNS FROM %s`, d.QuoteWord(table)),
|
||||
)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
fields = make(map[string]*gdb.TableField)
|
||||
for i, m := range result {
|
||||
fields[m["Field"].String()] = &gdb.TableField{
|
||||
Index: i,
|
||||
Name: m["Field"].String(),
|
||||
Type: m["Type"].String(),
|
||||
Null: m["Null"].Bool(),
|
||||
Key: m["Key"].String(),
|
||||
Default: m["Default"].Val(),
|
||||
Extra: m["Extra"].String(),
|
||||
Comment: m["Comment"].String(),
|
||||
}
|
||||
}
|
||||
return fields, nil
|
||||
}
|
||||
33
contrib/drivers/mysql/mysql_tables.go
Normal file
33
contrib/drivers/mysql/mysql_tables.go
Normal file
@ -0,0 +1,33 @@
|
||||
// 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 mysql
|
||||
|
||||
import (
|
||||
"context"
|
||||
|
||||
"github.com/gogf/gf/v2/database/gdb"
|
||||
)
|
||||
|
||||
// Tables retrieves and returns the tables of current schema.
|
||||
// It's mainly used in cli tool chain for automatically generating the models.
|
||||
func (d *Driver) Tables(ctx context.Context, schema ...string) (tables []string, err error) {
|
||||
var result gdb.Result
|
||||
link, err := d.SlaveLink(schema...)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
result, err = d.DoSelect(ctx, link, `SHOW TABLES`)
|
||||
if err != nil {
|
||||
return
|
||||
}
|
||||
for _, m := range result {
|
||||
for _, v := range m {
|
||||
tables = append(tables, v.String())
|
||||
}
|
||||
}
|
||||
return
|
||||
}
|
||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user