style: move the initialization database code to internal/database and add the sgorm library

This commit is contained in:
zhuyasen
2024-11-07 16:00:02 +08:00
parent 6eb9e51b9d
commit 46ac48152d
114 changed files with 3090 additions and 874 deletions

View File

@@ -63,6 +63,10 @@ func setCrudInfo(field tmplField) *CrudInfo {
}
func newCrudInfo(data tmplData) *CrudInfo {
if len(data.Fields) == 0 {
return nil
}
var info *CrudInfo
for _, field := range data.Fields {
if field.IsPrimaryKey {
@@ -81,7 +85,7 @@ func newCrudInfo(data tmplData) *CrudInfo {
}
}
// if not found xxx_id field, use the first column as primary key
// if not found xxx_id field, use the first field of integer or string type
if info == nil {
for _, field := range data.Fields {
if isDesiredGoType(field.GoType) {
@@ -89,11 +93,11 @@ func newCrudInfo(data tmplData) *CrudInfo {
break
}
}
if len(data.Fields) > 0 {
info = setCrudInfo(data.Fields[0])
} else {
return nil
}
}
// use the first column as primary key
if info == nil {
info = setCrudInfo(data.Fields[0])
}
info.TableNameCamel = data.TableName

View File

@@ -310,7 +310,7 @@ const (
)
var replaceFields = map[string]string{
__mysqlModel__: "ggorm.Model",
__mysqlModel__: "sgorm.Model",
__type__: "",
}
@@ -395,6 +395,9 @@ func makeCode(stmt *ast.CreateTableStmt, opt options) (*codeText, error) {
if con.Tp == ast.ConstraintPrimaryKey {
isPrimaryKey[con.Keys[0].Column.String()] = true
}
if con.Tp == ast.ConstraintForeignKey {
// TODO: foreign key support
}
}
columnPrefix := opt.ColumnPrefix
@@ -633,7 +636,7 @@ func getModelStructCode(data tmplData, importPaths []string, isEmbed bool, jsonN
newImportPaths = append(newImportPaths, path)
}
}
newImportPaths = append(newImportPaths, "github.com/zhufuyi/sponge/pkg/ggorm")
newImportPaths = append(newImportPaths, "github.com/zhufuyi/sponge/pkg/sgorm")
} else {
for i, field := range data.Fields {
switch field.DBDriver {
@@ -683,7 +686,7 @@ func getModelStructCode(data tmplData, importPaths []string, isEmbed bool, jsonN
if isEmbed {
gormEmbed := replaceFields[__mysqlModel__]
if jsonNamedType == 0 { // snake case
gormEmbed += "2" // ggorm.Model2
gormEmbed += "2" // sgorm.Model2
}
structCode = strings.ReplaceAll(structCode, __mysqlModel__, gormEmbed)
structCode = strings.ReplaceAll(structCode, __type__, replaceFields[__type__])

View File

@@ -4,16 +4,16 @@ import (
"fmt"
"strings"
"github.com/zhufuyi/sponge/pkg/ggorm"
"github.com/zhufuyi/sponge/pkg/sgorm/sqlite"
)
// GetSqliteTableInfo get table info from sqlite
func GetSqliteTableInfo(dbFile string, tableName string) (string, error) {
db, err := ggorm.InitSqlite(dbFile)
db, err := sqlite.Init(dbFile)
if err != nil {
return "", err
}
defer closeDB(db)
defer sqlite.Close(db) //nolint
var sqliteFields SqliteFields
sql := fmt.Sprintf("PRAGMA table_info('%s')", tableName)