package sqlite3 import ( "fmt" "strings" "time" "git.fsdpf.net/go/db" "git.fsdpf.net/go/db/dialect/sqlite3" "git.fsdpf.net/go/db/internal/sb" "git.fsdpf.net/go/db/schema" "git.fsdpf.net/go/db/sqlgen" ) var ( sqlite3DefaultModifiers = []string{"Hidden", "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) } prefix := "? TABLE IF NOT EXISTS ? (\n?\n)" if comment := bp.Comment; comment != "" { prefix = "? TABLE IF NOT EXISTS ? ( -- " + comment + "\n?\n)" } sqls = append(sqls, this.GenerateSQL(prefix, 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) CompileModifyComment(bp *schema.Blueprint) []string { return []string{} } 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 "Hidden": if column.IsHidden() { return "HIDDEN" } case "Nullable": // HIDDEN 列和生成列不加 NULL/NOT NULL if column.GetVirtualAs() == "" && column.GetStoredAs() == "" && !column.IsHidden() { if column.IsNullable() { return "NULL" } return "NOT NULL" } case "Default": if column.IsHidden() { return "" } 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": if column.Length > 0 { return this.GenerateSQL("INTEGER(?)", column.Length) } return "INTEGER" 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)" case "vector": return this.GenerateSQL("float[?]", column.Length) } 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() { sc := func(db *db.Database) schema.Schema { return &Sqlite3{ db: db, esg: sqlgen.NewExpressionSQLGenerator("sqlite3", sqlite3.DialectOptions()), } } schema.RegisterDialect("sqlite3", sc) schema.RegisterDialect("vtable", sc) }