[feat] 新增 表结构操作
This commit is contained in:
Executable
+95
@@ -0,0 +1,95 @@
|
||||
package schema
|
||||
|
||||
import (
|
||||
"git.fsdpf.net/go/db/v2"
|
||||
)
|
||||
|
||||
type Builder struct {
|
||||
db *db.Database // The database connection instance
|
||||
schema Schema // The schema grammar instance
|
||||
}
|
||||
|
||||
func New(db *db.Database) *Builder {
|
||||
return &Builder{
|
||||
db: db,
|
||||
schema: GetSchemaDialect(db),
|
||||
}
|
||||
}
|
||||
|
||||
// 判断数据表是否存在
|
||||
func (this Builder) HasTable(table string) (bool, error) {
|
||||
return this.schema.TableExists(table)
|
||||
}
|
||||
|
||||
// 判断数据库列是否存在
|
||||
func (this Builder) GetColumnListing(table string) (columns []string, err error) {
|
||||
return this.schema.GetColumnListing(table)
|
||||
}
|
||||
|
||||
// 修改表
|
||||
func (this Builder) Table(table string, cb func(*Blueprint)) error {
|
||||
bp := NewBlueprint(table)
|
||||
cb(bp)
|
||||
return this.Build(bp)
|
||||
}
|
||||
|
||||
// 创建表
|
||||
func (this Builder) Create(table string, cb func(*Blueprint)) error {
|
||||
bp := NewBlueprint(table)
|
||||
bp.Create()
|
||||
cb(bp)
|
||||
return this.Build(bp)
|
||||
}
|
||||
|
||||
// 修改表名
|
||||
func (this Builder) Rename(from, to string) error {
|
||||
bp := NewBlueprint(from)
|
||||
bp.Rename(to)
|
||||
return this.Build(bp)
|
||||
}
|
||||
|
||||
// 删除表
|
||||
func (this Builder) Drop(table string) error {
|
||||
bp := NewBlueprint(table)
|
||||
bp.Drop()
|
||||
return this.Build(bp)
|
||||
}
|
||||
|
||||
// 删除表, 先判断再删除
|
||||
func (this Builder) DropIfExists(table string) error {
|
||||
bp := NewBlueprint(table)
|
||||
bp.DropIfExists()
|
||||
return this.Build(bp)
|
||||
}
|
||||
|
||||
// toSql
|
||||
func (this Builder) ToSQL(bp *Blueprint) []string {
|
||||
return bp.ToSql(this.schema)
|
||||
}
|
||||
|
||||
// Build execute the blueprint to build / modify the table
|
||||
func (this Builder) Build(bp *Blueprint) error {
|
||||
sqls := this.ToSQL(bp)
|
||||
|
||||
if len(sqls) == 0 {
|
||||
return nil
|
||||
}
|
||||
|
||||
tx, err := this.db.Begin()
|
||||
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
err = tx.Wrap(func() error {
|
||||
for _, sql := range sqls {
|
||||
if _, err := tx.Exec(sql); err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
|
||||
return nil
|
||||
})
|
||||
|
||||
return err
|
||||
}
|
||||
Reference in New Issue
Block a user