[feat] 新增 表结构操作
This commit is contained in:
@@ -0,0 +1,264 @@
|
||||
package sqlite3
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
"git.fsdpf.net/go/db/v2"
|
||||
"git.fsdpf.net/go/db/v2/dialect/sqlite3"
|
||||
"git.fsdpf.net/go/db/v2/internal/sb"
|
||||
"git.fsdpf.net/go/db/v2/schema"
|
||||
"git.fsdpf.net/go/db/v2/sqlgen"
|
||||
)
|
||||
|
||||
var (
|
||||
sqlite3DefaultModifiers = []string{"VirtualAs", "StoredAs", "Nullable", "Default", "Increment"}
|
||||
sqlite3Serials = []string{"bigInteger", "integer", "mediumInteger", "smallInteger", "tinyInteger"}
|
||||
)
|
||||
|
||||
type Sqlite3 struct {
|
||||
db *db.Database
|
||||
esg sqlgen.ExpressionSQLGenerator
|
||||
}
|
||||
|
||||
// 判断表是否存在
|
||||
func (this Sqlite3) TableExists(table string) (bool, error) {
|
||||
result, err := this.db.From(db.T("sqlite_master")).Where(db.Ex{
|
||||
"name": table,
|
||||
"type": "table",
|
||||
}).Count()
|
||||
return result > 0, err
|
||||
}
|
||||
|
||||
// 字段列
|
||||
func (this Sqlite3) GetColumnListing(table string) ([]string, error) {
|
||||
cols := []struct {
|
||||
Cid string `db:"cid"`
|
||||
Name string `db:"name"`
|
||||
Type string `db:"type"`
|
||||
Notnull int32 `db:"notnull"`
|
||||
DfltValue string `db:"dflt_value"`
|
||||
Pk string `db:"pk"`
|
||||
}{}
|
||||
|
||||
err := this.db.ScanStructs(&cols, "PRAGMA table_info(entry)")
|
||||
|
||||
columns := []string{}
|
||||
|
||||
for _, item := range cols {
|
||||
columns = append(columns, item.Name)
|
||||
}
|
||||
|
||||
return columns, err
|
||||
}
|
||||
|
||||
// 创建表
|
||||
func (this Sqlite3) CompileCreate(bp *schema.Blueprint) (sqls []string) {
|
||||
temporary := db.L("CREATE")
|
||||
columns := []string{}
|
||||
|
||||
count := len(bp.GetAddedColumns()) - 1
|
||||
for i, column := range bp.GetAddedColumns() {
|
||||
sql := this.GenerateSQL(this.addModifiers("? ? ", bp, column),
|
||||
db.C(column.Name),
|
||||
db.L(this.GetColumnType(column)),
|
||||
)
|
||||
if v := column.GetComment(); v != "" {
|
||||
if i != count {
|
||||
sql += ","
|
||||
}
|
||||
sql += " -- " + v
|
||||
}
|
||||
columns = append(columns, sql)
|
||||
}
|
||||
sqls = append(sqls,
|
||||
this.GenerateSQL("? TABLE ? (\n?\n)",
|
||||
temporary,
|
||||
db.T(bp.GetTable()),
|
||||
db.L(strings.Join(columns, "\n")),
|
||||
),
|
||||
)
|
||||
return sqls
|
||||
}
|
||||
|
||||
// 添加字段
|
||||
func (this Sqlite3) CompileAdd(bp *schema.Blueprint) (sqls []string) {
|
||||
for _, column := range bp.GetAddedColumns() {
|
||||
sqls = append(sqls, this.addModifiers(
|
||||
this.GenerateSQL("ALTER TABLE ? ADD COLUMN ? ? ",
|
||||
db.T(bp.GetTable()),
|
||||
db.C(column.Name),
|
||||
db.L(this.GetColumnType(column)),
|
||||
), bp, column),
|
||||
)
|
||||
}
|
||||
return sqls
|
||||
}
|
||||
|
||||
// 修改字段
|
||||
func (this Sqlite3) CompileChange(bp *schema.Blueprint) (sqls []string) {
|
||||
for _, column := range bp.GetChangedColumns() {
|
||||
name := column.Name
|
||||
rename := column.Name
|
||||
old_name := fmt.Sprintf("%s_%d", name, time.Now().UnixNano())
|
||||
|
||||
sql := this.GenerateSQL("ALTER TABLE ? ADD COLUMN ? ? ", db.T(bp.GetTable()), db.C(old_name), db.L(this.GetColumnType(column)))
|
||||
sqls = append(sqls, this.addModifiers(sql, bp, column))
|
||||
if name := column.GetRename(); name != "" {
|
||||
rename = name
|
||||
}
|
||||
sqls = append(sqls, this.GenerateSQL("UPDATE ? SET ?=?", db.T(bp.GetTable()), db.C(old_name), db.C(name)))
|
||||
sqls = append(sqls, this.GenerateSQL("ALTER TABLE ? DROP COLUMN ?", db.T(bp.GetTable()), db.C(name)))
|
||||
sqls = append(sqls, this.GenerateSQL("ALTER TABLE ? RENAME COLUMN ? TO ?", db.T(bp.GetTable()), db.T(old_name), db.T(rename)))
|
||||
}
|
||||
return sqls
|
||||
}
|
||||
|
||||
// 删除表
|
||||
func (this Sqlite3) CompileDrop(bp *schema.Blueprint) []string {
|
||||
return []string{this.GenerateSQL("DROP TABLE ?", db.T(bp.GetTable()))}
|
||||
}
|
||||
|
||||
// 删除表, 先判断再删除
|
||||
func (this Sqlite3) CompileDropIfExists(bp *schema.Blueprint) []string {
|
||||
return []string{this.GenerateSQL("DROP TABLE IF EXISTS ?", db.T(bp.GetTable()))}
|
||||
}
|
||||
|
||||
// 删除表, 删除列
|
||||
func (this Sqlite3) CompileDropColumn(bp *schema.Blueprint) (sqls []string) {
|
||||
for _, item := range bp.GetCommands() {
|
||||
if item.Type != "dropColumn" {
|
||||
continue
|
||||
}
|
||||
for _, col := range item.Columns {
|
||||
sqls = append(sqls, this.GenerateSQL("ALTER TABLE ? DROP COLUMN ?", db.T(bp.GetTable()), db.C(col)))
|
||||
}
|
||||
}
|
||||
return sqls
|
||||
}
|
||||
|
||||
// 表重命名
|
||||
func (this Sqlite3) CompileRename(bp *schema.Blueprint) []string {
|
||||
toName := ""
|
||||
commands := bp.GetCommands()
|
||||
if len(commands) == 0 {
|
||||
panic("new table undefined")
|
||||
}
|
||||
toName = bp.GetCommands()[0].To
|
||||
if toName == "" {
|
||||
panic("new table undefined")
|
||||
}
|
||||
return []string{this.GenerateSQL("RENAME TABLE ? TO ?", db.T(bp.GetTable()), db.T(toName))}
|
||||
}
|
||||
|
||||
func (this Sqlite3) GetColumnModifier(modifier string, bp *schema.Blueprint, column *schema.ColumnDefinition) string {
|
||||
switch modifier {
|
||||
case "Collate":
|
||||
if v := column.GetCollaction(); v != "" {
|
||||
return this.GenerateSQL(" COLLATE ?", v)
|
||||
}
|
||||
case "VirtualAs":
|
||||
if v := column.GetVirtualAs(); v != "" {
|
||||
return this.GenerateSQL(" GENERATED ALWAYS AS (?) VIRTUAL", db.L(v))
|
||||
}
|
||||
case "StoredAs":
|
||||
if v := column.GetStoredAs(); v != "" {
|
||||
return this.GenerateSQL(" GENERATED ALWAYS AS (?) STORED", db.L(v))
|
||||
}
|
||||
case "Nullable":
|
||||
if column.GetVirtualAs() == "" && column.GetStoredAs() == "" {
|
||||
if column.IsNullable() {
|
||||
return "NULL"
|
||||
}
|
||||
return "NOT NULL"
|
||||
}
|
||||
case "Default":
|
||||
if column.IsUseCurrent() {
|
||||
return " DEFAULT CURRENT_TIMESTAMP"
|
||||
}
|
||||
v := column.GetDefault()
|
||||
if v == nil {
|
||||
return ""
|
||||
}
|
||||
return this.GenerateSQL(" DEFAULT ?", v)
|
||||
case "Increment":
|
||||
if column.IsAutoIncrement() {
|
||||
return " PRIMARY KEY AUTOINCREMENT"
|
||||
}
|
||||
case "Comment":
|
||||
if v := column.GetComment(); v != "" {
|
||||
return this.GenerateSQL(" COMMENT ?", v)
|
||||
}
|
||||
}
|
||||
return ""
|
||||
}
|
||||
|
||||
func (this Sqlite3) GetColumnType(column *schema.ColumnDefinition) string {
|
||||
if column.IsAutoIncrement() {
|
||||
return "INTEGER"
|
||||
}
|
||||
switch column.Type {
|
||||
case "char":
|
||||
return this.GenerateSQL("char(?)", column.Length)
|
||||
case "string":
|
||||
return this.GenerateSQL("varchar(?)", column.Length)
|
||||
case "text":
|
||||
return "text"
|
||||
case "integer":
|
||||
return this.GenerateSQL("INTEGER(?)", column.Length)
|
||||
case "bigInteger":
|
||||
return "bigint(20)"
|
||||
case "tinyInteger":
|
||||
return "tinyint(1)"
|
||||
case "smallInteger":
|
||||
return "smallint(4)"
|
||||
case "decimal":
|
||||
return this.GenerateSQL("numeric(?,?)", column.Total, column.Places)
|
||||
case "boolean":
|
||||
return "tinyint(1)"
|
||||
case "enum":
|
||||
return this.GenerateSQL("varchar check(? in?)", column.Name, column.Allowed)
|
||||
case "json":
|
||||
return "json"
|
||||
case "binary":
|
||||
return "binary"
|
||||
case "datetime":
|
||||
return "datetime"
|
||||
case "timestamp":
|
||||
return "timestamp"
|
||||
case "date":
|
||||
return "date"
|
||||
case "time":
|
||||
return "time"
|
||||
case "year":
|
||||
return "year"
|
||||
case "uuid":
|
||||
return "char(36)"
|
||||
}
|
||||
panic("Unsupported data type: " + column.Type)
|
||||
}
|
||||
|
||||
func (this Sqlite3) addModifiers(sql string, bp *schema.Blueprint, column *schema.ColumnDefinition) string {
|
||||
for _, modifier := range sqlite3DefaultModifiers {
|
||||
sql += this.GetColumnModifier(modifier, bp, column)
|
||||
}
|
||||
return sql
|
||||
}
|
||||
|
||||
// 生成SQL
|
||||
func (this Sqlite3) GenerateSQL(sql string, args ...any) string {
|
||||
sb := sb.NewSQLBuilder(false)
|
||||
this.esg.Generate(sb, db.L(sql, args...))
|
||||
result, _, _ := sb.ToSQL()
|
||||
return result
|
||||
}
|
||||
|
||||
func init() {
|
||||
schema.RegisterDialect("sqlite3", func(db *db.Database) schema.Schema {
|
||||
return &Sqlite3{
|
||||
db: db,
|
||||
esg: sqlgen.NewExpressionSQLGenerator("sqlite3", sqlite3.DialectOptions()),
|
||||
}
|
||||
})
|
||||
}
|
||||
@@ -0,0 +1,192 @@
|
||||
package sqlite3_test
|
||||
|
||||
import (
|
||||
"os"
|
||||
"testing"
|
||||
|
||||
"git.fsdpf.net/go/db/v2"
|
||||
"git.fsdpf.net/go/db/v2/engine"
|
||||
"git.fsdpf.net/go/db/v2/schema"
|
||||
"github.com/stretchr/testify/suite"
|
||||
|
||||
_ "github.com/mattn/go-sqlite3"
|
||||
)
|
||||
|
||||
var (
|
||||
tableName = "entry"
|
||||
|
||||
dropTable = "DROP TABLE IF EXISTS `entry`;"
|
||||
|
||||
createTable = "CREATE TABLE IF NOT EXISTS `entry` (" +
|
||||
"`id` INTEGER PRIMARY KEY AUTOINCREMENT," +
|
||||
"`int` INT NOT NULL ," +
|
||||
"`float` FLOAT NOT NULL ," +
|
||||
"`string` VARCHAR(255) NOT NULL ," +
|
||||
"`time` DATETIME NOT NULL ," +
|
||||
"`bool` TINYINT NOT NULL ," +
|
||||
"`bytes` BLOB NOT NULL" +
|
||||
");"
|
||||
)
|
||||
|
||||
type sqlite3Test struct {
|
||||
suite.Suite
|
||||
schema schema.Schema
|
||||
}
|
||||
|
||||
func TestSqlite3Suite(t *testing.T) {
|
||||
suite.Run(t, new(sqlite3Test))
|
||||
}
|
||||
|
||||
func (t *sqlite3Test) SetupSuite() {
|
||||
db := engine.Open(map[string]engine.DBConfig{
|
||||
"test-sqlite3": engine.NewDBConfig("sqlite3",
|
||||
engine.WithSQLiteFile(os.Getenv("DB_FILE")),
|
||||
),
|
||||
}).Connection("test-sqlite3")
|
||||
|
||||
t.schema = schema.GetSchemaDialect(db)
|
||||
|
||||
// db.Exec(dropTable)
|
||||
if _, err := db.Exec(createTable); err != nil {
|
||||
t.Require().NoError(err)
|
||||
}
|
||||
}
|
||||
|
||||
func (t *sqlite3Test) TestTableExists() {
|
||||
result, err := t.schema.TableExists(tableName)
|
||||
t.Require().NoError(err)
|
||||
t.Require().Equal(result, true)
|
||||
}
|
||||
|
||||
func (t *sqlite3Test) TestGetColumnListing() {
|
||||
result, err := t.schema.GetColumnListing(tableName)
|
||||
t.Require().NoError(err)
|
||||
t.Require().ElementsMatch([]string{"bool", "bytes", "float", "id", "int", "string", "time"}, result)
|
||||
}
|
||||
|
||||
// 创建列表
|
||||
func (t *sqlite3Test) TestCompileCreate() {
|
||||
bp := schema.NewBlueprint("users")
|
||||
bp.Create()
|
||||
bp.Charset("utf8mb4")
|
||||
|
||||
bp.BigIncrements("id").AutoIncrement().Comment("ID")
|
||||
bp.Boolean("enabled").Default("1").Comment("是否有效")
|
||||
bp.Char("created_user", 36).Default("00000000-0000-0000-0000-000000000000").Comment("创建者")
|
||||
bp.Char("owned_user", 36).Default("00000000-0000-0000-0000-000000000000").Comment("拥有者")
|
||||
bp.Timestamp("created_at").UseCurrent().Comment("创建时间")
|
||||
bp.Timestamp("updated_at").UseCurrent().Default(db.L("ON UPDATE CURRENT_TIMESTAMP")).Comment("更新时间")
|
||||
bp.DateTime("deleted_at").Nullable().Comment("删除时间")
|
||||
|
||||
sql := t.schema.CompileCreate(bp)
|
||||
|
||||
t.Equal([]string{
|
||||
"CREATE TABLE `users` (\n" +
|
||||
"`id` INTEGER NOT NULL PRIMARY KEY AUTOINCREMENT, -- ID\n" +
|
||||
"`enabled` tinyint(1) NOT NULL DEFAULT '1', -- 是否有效\n" +
|
||||
"`created_user` char(36) NOT NULL DEFAULT '00000000-0000-0000-0000-000000000000', -- 创建者\n" +
|
||||
"`owned_user` char(36) NOT NULL DEFAULT '00000000-0000-0000-0000-000000000000', -- 拥有者\n" +
|
||||
"`created_at` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP, -- 创建时间\n" +
|
||||
"`updated_at` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP, -- 更新时间\n" +
|
||||
"`deleted_at` datetime NULL -- 删除时间\n" +
|
||||
")",
|
||||
}, sql)
|
||||
|
||||
t.T().Log(sql)
|
||||
}
|
||||
|
||||
// 添加字段
|
||||
func (t *sqlite3Test) TestCompileAdd() {
|
||||
bp := schema.NewBlueprint("users")
|
||||
|
||||
bp.String("name", 50).Comment("用户名")
|
||||
bp.SmallInteger("age").Default("18").Comment("年龄")
|
||||
bp.Enum("sex", []string{"0", "1"}).Default("0").Comment("性别")
|
||||
|
||||
sql := t.schema.CompileAdd(bp)
|
||||
|
||||
t.Equal([]string{
|
||||
"ALTER TABLE `users` ADD COLUMN `name` varchar(50) NOT NULL",
|
||||
"ALTER TABLE `users` ADD COLUMN `age` smallint(4) NOT NULL DEFAULT '18'",
|
||||
"ALTER TABLE `users` ADD COLUMN `sex` varchar check('sex' in('0', '1')) NOT NULL DEFAULT '0'",
|
||||
}, sql)
|
||||
|
||||
t.T().Log(sql)
|
||||
}
|
||||
|
||||
// 修改字段
|
||||
func (t *sqlite3Test) TestCompileChange() {
|
||||
bp := schema.NewBlueprint("users")
|
||||
|
||||
bp.String("name", 50).Change("username")
|
||||
bp.SmallInteger("age").Default("19").Comment("年龄").Change()
|
||||
|
||||
sql := t.schema.CompileChange(bp)
|
||||
t.Equal(len([]string{
|
||||
"ALTER TABLE `users` ADD COLUMN `name_1742738970482105700` varchar(50) NOT NULL",
|
||||
"UPDATE `users` SET `name_1742738970482105700`=`name`",
|
||||
"ALTER TABLE `users` DROP COLUMN `name`",
|
||||
"ALTER TABLE `users` RENAME COLUMN `name_1742738970482105700` TO `username`",
|
||||
"ALTER TABLE `users` ADD COLUMN `age_1742738970482151800` smallint(4) NOT NULL DEFAULT '19'",
|
||||
"UPDATE `users` SET `age_1742738970482151800`=`age`",
|
||||
"ALTER TABLE `users` DROP COLUMN `age`",
|
||||
"ALTER TABLE `users` RENAME COLUMN `age_1742738970482151800` TO `age`",
|
||||
}), len(sql))
|
||||
|
||||
t.T().Log(sql)
|
||||
}
|
||||
|
||||
// 删除字段
|
||||
func (t *sqlite3Test) TestCompileDropColumn() {
|
||||
bp := schema.NewBlueprint("users")
|
||||
|
||||
bp.DropColumn("age", "sex")
|
||||
|
||||
sql := t.schema.CompileDropColumn(bp)
|
||||
|
||||
t.Equal([]string{
|
||||
"ALTER TABLE `users` DROP COLUMN `age`",
|
||||
"ALTER TABLE `users` DROP COLUMN `sex`",
|
||||
}, sql)
|
||||
|
||||
t.T().Log(sql)
|
||||
}
|
||||
|
||||
// 删除表
|
||||
func (t *sqlite3Test) TestCompileDrop() {
|
||||
bp := schema.NewBlueprint("users")
|
||||
|
||||
bp.Drop()
|
||||
|
||||
sql := t.schema.CompileDrop(bp)
|
||||
|
||||
t.Equal([]string{"DROP TABLE `users`"}, sql)
|
||||
|
||||
t.T().Log(sql)
|
||||
}
|
||||
|
||||
// 删除表
|
||||
func (t *sqlite3Test) TestCompileDropIfExists() {
|
||||
bp := schema.NewBlueprint("users")
|
||||
|
||||
bp.Drop()
|
||||
|
||||
sql := t.schema.CompileDropIfExists(bp)
|
||||
|
||||
t.Equal([]string{"DROP TABLE IF EXISTS `users`"}, sql)
|
||||
|
||||
t.T().Log(sql)
|
||||
}
|
||||
|
||||
// 表重命名
|
||||
func (t *sqlite3Test) TestCompileRename() {
|
||||
bp := schema.NewBlueprint("users")
|
||||
|
||||
bp.Rename("user")
|
||||
|
||||
sql := t.schema.CompileRename(bp)
|
||||
|
||||
t.Equal([]string{"RENAME TABLE `users` TO `user`"}, sql)
|
||||
|
||||
t.T().Log(sql)
|
||||
}
|
||||
Reference in New Issue
Block a user