fix: model gen issues

This commit is contained in:
Rogee
2024-12-25 18:15:27 +08:00
parent 28735f506f
commit 2ec0c73ba3
4 changed files with 79 additions and 41 deletions

View File

@@ -1,8 +1,44 @@
package database
import (
"context"
"database/sql"
"embed"
"fmt"
"github.com/go-jet/jet/v2/qrm"
)
//go:embed migrations/*
var MigrationFS embed.FS
type CtxDB struct{}
func FromContext(ctx context.Context, db *sql.DB) qrm.DB {
if tx, ok := ctx.Value(CtxDB{}).(*sql.Tx); ok {
return tx
}
return db
}
func TruncateAllTables(ctx context.Context, db *sql.DB, tableName ...string) error {
for _, name := range tableName {
sql := fmt.Sprintf("TRUNCATE TABLE %s RESTART IDENTITY", name)
if _, err := db.ExecContext(ctx, sql); err != nil {
return err
}
}
return nil
}
func WrapLike(v string) string {
return "%" + v + "%"
}
func WrapLikeLeft(v string) string {
return "%" + v
}
func WrapLikeRight(v string) string {
return "%" + v
}

View File

@@ -0,0 +1,32 @@
package fields
import (
"database/sql/driver"
"encoding/json"
"errors"
"github.com/samber/lo"
)
// implement sql.Scanner interface
type field struct{}
func (x *field) Scan(value interface{}) (err error) {
switch v := value.(type) {
case string:
return json.Unmarshal([]byte(v), &x)
case []byte:
return json.Unmarshal(v, &x)
case *string:
return json.Unmarshal([]byte(*v), &x)
}
return errors.New("Unknown type for ")
}
func (x field) Value() (driver.Value, error) {
return json.Marshal(x)
}
func (x field) MustValue() driver.Value {
return lo.Must(json.Marshal(x))
}

View File

@@ -1,40 +0,0 @@
package db
import (
"context"
"database/sql"
"fmt"
"github.com/go-jet/jet/v2/qrm"
)
const CtxDB = "__db__tx:"
func FromContext(ctx context.Context, db *sql.DB) qrm.DB {
if tx, ok := ctx.Value(CtxDB).(*sql.Tx); ok {
return tx
}
return db
}
func TruncateAllTables(ctx context.Context, db *sql.DB, tableName ...string) error {
for _, name := range tableName {
sql := fmt.Sprintf("TRUNCATE TABLE %s RESTART IDENTITY", name)
if _, err := db.ExecContext(ctx, sql); err != nil {
return err
}
}
return nil
}
func WrapLike(v string) string {
return "%" + v + "%"
}
func WrapLikeLeft(v string) string {
return "%" + v
}
func WrapLikeRight(v string) string {
return "%" + v
}