package schema import ( "git.fsdpf.net/go/db" ) 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) ModifyComment(table, comment string) error { bp := NewBlueprint(table) bp.ModifyComment(comment) 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 }