How to use Type method of migrations Package

Best Testkube code snippet using migrations.Type

migrate.go

Source:migrate.go Github

copy

Full Screen

1package migrate2import (3 "bytes"4 "database/sql"5 "errors"6 "fmt"7 "io"8 "net/http"9 "os"10 "path"11 "regexp"12 "sort"13 "strconv"14 "strings"15 "time"16 "github.com/rubenv/sql-migrate/sqlparse"17 "gopkg.in/gorp.v1"18)19type MigrationDirection int20const (21 Up MigrationDirection = iota22 Down23)24// MigrationSet provides database parameters for a migration execution25type MigrationSet struct {26 // TableName name of the table used to store migration info.27 TableName string28 // SchemaName schema that the migration table be referenced.29 SchemaName string30 // IgnoreUnknown skips the check to see if there is a migration31 // ran in the database that is not in MigrationSource.32 //33 // This should be used sparingly as it is removing a safety check.34 IgnoreUnknown bool35}36var migSet = MigrationSet{}37// NewMigrationSet returns a parametrized Migration object38func (ms MigrationSet) getTableName() string {39 if ms.TableName == "" {40 return "gorp_migrations"41 }42 return ms.TableName43}44var numberPrefixRegex = regexp.MustCompile(`^(\d+).*$`)45// PlanError happens where no migration plan could be created between the sets46// of already applied migrations and the currently found. For example, when the database47// contains a migration which is not among the migrations list found for an operation.48type PlanError struct {49 Migration *Migration50 ErrorMessage string51}52func newPlanError(migration *Migration, errorMessage string) error {53 return &PlanError{54 Migration: migration,55 ErrorMessage: errorMessage,56 }57}58func (p *PlanError) Error() string {59 return fmt.Sprintf("Unable to create migration plan because of %s: %s",60 p.Migration.Id, p.ErrorMessage)61}62// TxError is returned when any error is encountered during a database63// transaction. It contains the relevant *Migration and notes it's Id in the64// Error function output.65type TxError struct {66 Migration *Migration67 Err error68}69func newTxError(migration *PlannedMigration, err error) error {70 return &TxError{71 Migration: migration.Migration,72 Err: err,73 }74}75func (e *TxError) Error() string {76 return e.Err.Error() + " handling " + e.Migration.Id77}78// Set the name of the table used to store migration info.79//80// Should be called before any other call such as (Exec, ExecMax, ...).81func SetTable(name string) {82 if name != "" {83 migSet.TableName = name84 }85}86// SetSchema sets the name of a schema that the migration table be referenced.87func SetSchema(name string) {88 if name != "" {89 migSet.SchemaName = name90 }91}92// SetIgnoreUnknown sets the flag that skips database check to see if there is a93// migration in the database that is not in migration source.94//95// This should be used sparingly as it is removing a safety check.96func SetIgnoreUnknown(v bool) {97 migSet.IgnoreUnknown = v98}99type Migration struct {100 Id string101 Up []string102 Down []string103 DisableTransactionUp bool104 DisableTransactionDown bool105}106func (m Migration) Less(other *Migration) bool {107 switch {108 case m.isNumeric() && other.isNumeric() && m.VersionInt() != other.VersionInt():109 return m.VersionInt() < other.VersionInt()110 case m.isNumeric() && !other.isNumeric():111 return true112 case !m.isNumeric() && other.isNumeric():113 return false114 default:115 return m.Id < other.Id116 }117}118func (m Migration) isNumeric() bool {119 return len(m.NumberPrefixMatches()) > 0120}121func (m Migration) NumberPrefixMatches() []string {122 return numberPrefixRegex.FindStringSubmatch(m.Id)123}124func (m Migration) VersionInt() int64 {125 v := m.NumberPrefixMatches()[1]126 value, err := strconv.ParseInt(v, 10, 64)127 if err != nil {128 panic(fmt.Sprintf("Could not parse %q into int64: %s", v, err))129 }130 return value131}132type PlannedMigration struct {133 *Migration134 DisableTransaction bool135 Queries []string136}137type byId []*Migration138func (b byId) Len() int { return len(b) }139func (b byId) Swap(i, j int) { b[i], b[j] = b[j], b[i] }140func (b byId) Less(i, j int) bool { return b[i].Less(b[j]) }141type MigrationRecord struct {142 Id string `db:"id"`143 AppliedAt time.Time `db:"applied_at"`144}145type OracleDialect struct {146 gorp.OracleDialect147}148func (d OracleDialect) IfTableNotExists(command, schema, table string) string {149 return command150}151func (d OracleDialect) IfSchemaNotExists(command, schema string) string {152 return command153}154func (d OracleDialect) IfTableExists(command, schema, table string) string {155 return command156}157var MigrationDialects = map[string]gorp.Dialect{158 "sqlite3": gorp.SqliteDialect{},159 "postgres": gorp.PostgresDialect{},160 "mysql": gorp.MySQLDialect{Engine: "InnoDB", Encoding: "UTF8"},161 "mssql": gorp.SqlServerDialect{},162 "oci8": OracleDialect{},163 "godror": OracleDialect{},164}165type MigrationSource interface {166 // Finds the migrations.167 //168 // The resulting slice of migrations should be sorted by Id.169 FindMigrations() ([]*Migration, error)170}171// A hardcoded set of migrations, in-memory.172type MemoryMigrationSource struct {173 Migrations []*Migration174}175var _ MigrationSource = (*MemoryMigrationSource)(nil)176func (m MemoryMigrationSource) FindMigrations() ([]*Migration, error) {177 // Make sure migrations are sorted. In order to make the MemoryMigrationSource safe for178 // concurrent use we should not mutate it in place. So `FindMigrations` would sort a copy179 // of the m.Migrations.180 migrations := make([]*Migration, len(m.Migrations))181 copy(migrations, m.Migrations)182 sort.Sort(byId(migrations))183 return migrations, nil184}185// A set of migrations loaded from an http.FileServer186type HttpFileSystemMigrationSource struct {187 FileSystem http.FileSystem188}189var _ MigrationSource = (*HttpFileSystemMigrationSource)(nil)190func (f HttpFileSystemMigrationSource) FindMigrations() ([]*Migration, error) {191 return findMigrations(f.FileSystem)192}193// A set of migrations loaded from a directory.194type FileMigrationSource struct {195 Dir string196}197var _ MigrationSource = (*FileMigrationSource)(nil)198func (f FileMigrationSource) FindMigrations() ([]*Migration, error) {199 filesystem := http.Dir(f.Dir)200 return findMigrations(filesystem)201}202func findMigrations(dir http.FileSystem) ([]*Migration, error) {203 migrations := make([]*Migration, 0)204 file, err := dir.Open("/")205 if err != nil {206 return nil, err207 }208 files, err := file.Readdir(0)209 if err != nil {210 return nil, err211 }212 for _, info := range files {213 if strings.HasSuffix(info.Name(), ".sql") {214 migration, err := migrationFromFile(dir, info)215 if err != nil {216 return nil, err217 }218 migrations = append(migrations, migration)219 }220 }221 // Make sure migrations are sorted222 sort.Sort(byId(migrations))223 return migrations, nil224}225func migrationFromFile(dir http.FileSystem, info os.FileInfo) (*Migration, error) {226 path := fmt.Sprintf("/%s", strings.TrimPrefix(info.Name(), "/"))227 file, err := dir.Open(path)228 if err != nil {229 return nil, fmt.Errorf("Error while opening %s: %s", info.Name(), err)230 }231 defer func() { _ = file.Close() }()232 migration, err := ParseMigration(info.Name(), file)233 if err != nil {234 return nil, fmt.Errorf("Error while parsing %s: %s", info.Name(), err)235 }236 return migration, nil237}238// Migrations from a bindata asset set.239type AssetMigrationSource struct {240 // Asset should return content of file in path if exists241 Asset func(path string) ([]byte, error)242 // AssetDir should return list of files in the path243 AssetDir func(path string) ([]string, error)244 // Path in the bindata to use.245 Dir string246}247var _ MigrationSource = (*AssetMigrationSource)(nil)248func (a AssetMigrationSource) FindMigrations() ([]*Migration, error) {249 migrations := make([]*Migration, 0)250 files, err := a.AssetDir(a.Dir)251 if err != nil {252 return nil, err253 }254 for _, name := range files {255 if strings.HasSuffix(name, ".sql") {256 file, err := a.Asset(path.Join(a.Dir, name))257 if err != nil {258 return nil, err259 }260 migration, err := ParseMigration(name, bytes.NewReader(file))261 if err != nil {262 return nil, err263 }264 migrations = append(migrations, migration)265 }266 }267 // Make sure migrations are sorted268 sort.Sort(byId(migrations))269 return migrations, nil270}271// Avoids pulling in the packr library for everyone, mimicks the bits of272// packr.Box that we need.273type PackrBox interface {274 List() []string275 Find(name string) ([]byte, error)276}277// Migrations from a packr box.278type PackrMigrationSource struct {279 Box PackrBox280 // Path in the box to use.281 Dir string282}283var _ MigrationSource = (*PackrMigrationSource)(nil)284func (p PackrMigrationSource) FindMigrations() ([]*Migration, error) {285 migrations := make([]*Migration, 0)286 items := p.Box.List()287 prefix := ""288 dir := path.Clean(p.Dir)289 if dir != "." {290 prefix = fmt.Sprintf("%s/", dir)291 }292 for _, item := range items {293 if !strings.HasPrefix(item, prefix) {294 continue295 }296 name := strings.TrimPrefix(item, prefix)297 if strings.Contains(name, "/") {298 continue299 }300 if strings.HasSuffix(name, ".sql") {301 file, err := p.Box.Find(item)302 if err != nil {303 return nil, err304 }305 migration, err := ParseMigration(name, bytes.NewReader(file))306 if err != nil {307 return nil, err308 }309 migrations = append(migrations, migration)310 }311 }312 // Make sure migrations are sorted313 sort.Sort(byId(migrations))314 return migrations, nil315}316// Migration parsing317func ParseMigration(id string, r io.ReadSeeker) (*Migration, error) {318 m := &Migration{319 Id: id,320 }321 parsed, err := sqlparse.ParseMigration(r)322 if err != nil {323 return nil, fmt.Errorf("Error parsing migration (%s): %s", id, err)324 }325 m.Up = parsed.UpStatements326 m.Down = parsed.DownStatements327 m.DisableTransactionUp = parsed.DisableTransactionUp328 m.DisableTransactionDown = parsed.DisableTransactionDown329 return m, nil330}331type SqlExecutor interface {332 Exec(query string, args ...interface{}) (sql.Result, error)333 Insert(list ...interface{}) error334 Delete(list ...interface{}) (int64, error)335}336// Execute a set of migrations337//338// Returns the number of applied migrations.339func Exec(db *sql.DB, dialect string, m MigrationSource, dir MigrationDirection) (int, error) {340 return ExecMax(db, dialect, m, dir, 0)341}342// Returns the number of applied migrations.343func (ms MigrationSet) Exec(db *sql.DB, dialect string, m MigrationSource, dir MigrationDirection) (int, error) {344 return ms.ExecMax(db, dialect, m, dir, 0)345}346// Execute a set of migrations347//348// Will apply at most `max` migrations. Pass 0 for no limit (or use Exec).349//350// Returns the number of applied migrations.351func ExecMax(db *sql.DB, dialect string, m MigrationSource, dir MigrationDirection, max int) (int, error) {352 return migSet.ExecMax(db, dialect, m, dir, max)353}354// Returns the number of applied migrations.355func (ms MigrationSet) ExecMax(db *sql.DB, dialect string, m MigrationSource, dir MigrationDirection, max int) (int, error) {356 migrations, dbMap, err := ms.PlanMigration(db, dialect, m, dir, max)357 if err != nil {358 return 0, err359 }360 // Apply migrations361 applied := 0362 for _, migration := range migrations {363 var executor SqlExecutor364 if migration.DisableTransaction {365 executor = dbMap366 } else {367 executor, err = dbMap.Begin()368 if err != nil {369 return applied, newTxError(migration, err)370 }371 }372 for _, stmt := range migration.Queries {373 // remove the semicolon from stmt, fix ORA-00922 issue in database oracle374 stmt = strings.TrimSuffix(stmt, "\n")375 stmt = strings.TrimSuffix(stmt, " ")376 stmt = strings.TrimSuffix(stmt, ";")377 if _, err := executor.Exec(stmt); err != nil {378 if trans, ok := executor.(*gorp.Transaction); ok {379 _ = trans.Rollback()380 }381 return applied, newTxError(migration, err)382 }383 }384 switch dir {385 case Up:386 err = executor.Insert(&MigrationRecord{387 Id: migration.Id,388 AppliedAt: time.Now(),389 })390 if err != nil {391 if trans, ok := executor.(*gorp.Transaction); ok {392 _ = trans.Rollback()393 }394 return applied, newTxError(migration, err)395 }396 case Down:397 _, err := executor.Delete(&MigrationRecord{398 Id: migration.Id,399 })400 if err != nil {401 if trans, ok := executor.(*gorp.Transaction); ok {402 _ = trans.Rollback()403 }404 return applied, newTxError(migration, err)405 }406 default:407 panic("Not possible")408 }409 if trans, ok := executor.(*gorp.Transaction); ok {410 if err := trans.Commit(); err != nil {411 return applied, newTxError(migration, err)412 }413 }414 applied++415 }416 return applied, nil417}418// Plan a migration.419func PlanMigration(db *sql.DB, dialect string, m MigrationSource, dir MigrationDirection, max int) ([]*PlannedMigration, *gorp.DbMap, error) {420 return migSet.PlanMigration(db, dialect, m, dir, max)421}422func (ms MigrationSet) PlanMigration(db *sql.DB, dialect string, m MigrationSource, dir MigrationDirection, max int) ([]*PlannedMigration, *gorp.DbMap, error) {423 dbMap, err := ms.getMigrationDbMap(db, dialect)424 if err != nil {425 return nil, nil, err426 }427 migrations, err := m.FindMigrations()428 if err != nil {429 return nil, nil, err430 }431 var migrationRecords []MigrationRecord432 _, err = dbMap.Select(&migrationRecords, fmt.Sprintf("SELECT * FROM %s", dbMap.Dialect.QuotedTableForQuery(ms.SchemaName, ms.getTableName())))433 if err != nil {434 return nil, nil, err435 }436 // Sort migrations that have been run by Id.437 var existingMigrations []*Migration438 for _, migrationRecord := range migrationRecords {439 existingMigrations = append(existingMigrations, &Migration{440 Id: migrationRecord.Id,441 })442 }443 sort.Sort(byId(existingMigrations))444 // Make sure all migrations in the database are among the found migrations which445 // are to be applied.446 if !ms.IgnoreUnknown {447 migrationsSearch := make(map[string]struct{})448 for _, migration := range migrations {449 migrationsSearch[migration.Id] = struct{}{}450 }451 for _, existingMigration := range existingMigrations {452 if _, ok := migrationsSearch[existingMigration.Id]; !ok {453 return nil, nil, newPlanError(existingMigration, "unknown migration in database")454 }455 }456 }457 // Get last migration that was run458 record := &Migration{}459 if len(existingMigrations) > 0 {460 record = existingMigrations[len(existingMigrations)-1]461 }462 result := make([]*PlannedMigration, 0)463 // Add missing migrations up to the last run migration.464 // This can happen for example when merges happened.465 if len(existingMigrations) > 0 {466 result = append(result, ToCatchup(migrations, existingMigrations, record)...)467 }468 // Figure out which migrations to apply469 toApply := ToApply(migrations, record.Id, dir)470 toApplyCount := len(toApply)471 if max > 0 && max < toApplyCount {472 toApplyCount = max473 }474 for _, v := range toApply[0:toApplyCount] {475 if dir == Up {476 result = append(result, &PlannedMigration{477 Migration: v,478 Queries: v.Up,479 DisableTransaction: v.DisableTransactionUp,480 })481 } else if dir == Down {482 result = append(result, &PlannedMigration{483 Migration: v,484 Queries: v.Down,485 DisableTransaction: v.DisableTransactionDown,486 })487 }488 }489 return result, dbMap, nil490}491// Skip a set of migrations492//493// Will skip at most `max` migrations. Pass 0 for no limit.494//495// Returns the number of skipped migrations.496func SkipMax(db *sql.DB, dialect string, m MigrationSource, dir MigrationDirection, max int) (int, error) {497 migrations, dbMap, err := PlanMigration(db, dialect, m, dir, max)498 if err != nil {499 return 0, err500 }501 // Skip migrations502 applied := 0503 for _, migration := range migrations {504 var executor SqlExecutor505 if migration.DisableTransaction {506 executor = dbMap507 } else {508 executor, err = dbMap.Begin()509 if err != nil {510 return applied, newTxError(migration, err)511 }512 }513 err = executor.Insert(&MigrationRecord{514 Id: migration.Id,515 AppliedAt: time.Now(),516 })517 if err != nil {518 if trans, ok := executor.(*gorp.Transaction); ok {519 _ = trans.Rollback()520 }521 return applied, newTxError(migration, err)522 }523 if trans, ok := executor.(*gorp.Transaction); ok {524 if err := trans.Commit(); err != nil {525 return applied, newTxError(migration, err)526 }527 }528 applied++529 }530 return applied, nil531}532// Filter a slice of migrations into ones that should be applied.533func ToApply(migrations []*Migration, current string, direction MigrationDirection) []*Migration {534 var index = -1535 if current != "" {536 for index < len(migrations)-1 {537 index++538 if migrations[index].Id == current {539 break540 }541 }542 }543 if direction == Up {544 return migrations[index+1:]545 } else if direction == Down {546 if index == -1 {547 return []*Migration{}548 }549 // Add in reverse order550 toApply := make([]*Migration, index+1)551 for i := 0; i < index+1; i++ {552 toApply[index-i] = migrations[i]553 }554 return toApply555 }556 panic("Not possible")557}558func ToCatchup(migrations, existingMigrations []*Migration, lastRun *Migration) []*PlannedMigration {559 missing := make([]*PlannedMigration, 0)560 for _, migration := range migrations {561 found := false562 for _, existing := range existingMigrations {563 if existing.Id == migration.Id {564 found = true565 break566 }567 }568 if !found && migration.Less(lastRun) {569 missing = append(missing, &PlannedMigration{570 Migration: migration,571 Queries: migration.Up,572 DisableTransaction: migration.DisableTransactionUp,573 })574 }575 }576 return missing577}578func GetMigrationRecords(db *sql.DB, dialect string) ([]*MigrationRecord, error) {579 return migSet.GetMigrationRecords(db, dialect)580}581func (ms MigrationSet) GetMigrationRecords(db *sql.DB, dialect string) ([]*MigrationRecord, error) {582 dbMap, err := ms.getMigrationDbMap(db, dialect)583 if err != nil {584 return nil, err585 }586 var records []*MigrationRecord587 query := fmt.Sprintf("SELECT * FROM %s ORDER BY %s ASC", dbMap.Dialect.QuotedTableForQuery(ms.SchemaName, ms.getTableName()), dbMap.Dialect.QuoteField("id"))588 _, err = dbMap.Select(&records, query)589 if err != nil {590 return nil, err591 }592 return records, nil593}594func (ms MigrationSet) getMigrationDbMap(db *sql.DB, dialect string) (*gorp.DbMap, error) {595 d, ok := MigrationDialects[dialect]596 if !ok {597 return nil, fmt.Errorf("Unknown dialect: %s", dialect)598 }599 // When using the mysql driver, make sure that the parseTime option is600 // configured, otherwise it won't map time columns to time.Time. See601 // https://github.com/rubenv/sql-migrate/issues/2602 if dialect == "mysql" {603 var out *time.Time604 err := db.QueryRow("SELECT NOW()").Scan(&out)605 if err != nil {606 if err.Error() == "sql: Scan error on column index 0: unsupported driver -> Scan pair: []uint8 -> *time.Time" ||607 err.Error() == "sql: Scan error on column index 0: unsupported Scan, storing driver.Value type []uint8 into type *time.Time" ||608 err.Error() == "sql: Scan error on column index 0, name \"NOW()\": unsupported Scan, storing driver.Value type []uint8 into type *time.Time" {609 return nil, errors.New(`Cannot parse dates.610Make sure that the parseTime option is supplied to your database connection.611Check https://github.com/go-sql-driver/mysql#parsetime for more info.`)612 } else {613 return nil, err614 }615 }616 }617 // Create migration database map618 dbMap := &gorp.DbMap{Db: db, Dialect: d}619 table := dbMap.AddTableWithNameAndSchema(MigrationRecord{}, ms.SchemaName, ms.getTableName()).SetKeys(false, "Id")620 //dbMap.TraceOn("", log.New(os.Stdout, "migrate: ", log.Lmicroseconds))621 if dialect == "oci8" || dialect == "godror" {622 table.ColMap("Id").SetMaxSize(4000)623 }624 err := dbMap.CreateTablesIfNotExists()625 if err != nil {626 // Oracle database does not support `if not exists`, so use `ORA-00955:` error code627 // to check if the table exists.628 if (dialect == "oci8" || dialect == "godror") && strings.Contains(err.Error(), "ORA-00955:") {629 return dbMap, nil630 }631 return nil, err632 }633 return dbMap, nil634}635// TODO: Run migration + record insert in transaction....

Full Screen

Full Screen

migrations.go

Source:migrations.go Github

copy

Full Screen

...32func addMigrationLogMigrations(mg *Migrator) {33 migrationLogV1 := Table{34 Name: "migration_log",35 Columns: []*Column{36 {Name: "id", Type: DB_BigInt, IsPrimaryKey: true, IsAutoIncrement: true},37 {Name: "migration_id", Type: DB_NVarchar, Length: 255},38 {Name: "sql", Type: DB_Text},39 {Name: "success", Type: DB_Bool},40 {Name: "error", Type: DB_Text},41 {Name: "timestamp", Type: DB_DateTime},42 },43 }44 mg.AddMigration("create migration_log table", NewAddTableMigration(migrationLogV1))45}46func addStarMigrations(mg *Migrator) {47 starV1 := Table{48 Name: "star",49 Columns: []*Column{50 {Name: "id", Type: DB_BigInt, IsPrimaryKey: true, IsAutoIncrement: true},51 {Name: "user_id", Type: DB_BigInt, Nullable: false},52 {Name: "dashboard_id", Type: DB_BigInt, Nullable: false},53 },54 Indices: []*Index{55 {Cols: []string{"user_id", "dashboard_id"}, Type: UniqueIndex},56 },57 }58 mg.AddMigration("create star table", NewAddTableMigration(starV1))59 mg.AddMigration("add unique index star.user_id_dashboard_id", NewAddIndexMigration(starV1, starV1.Indices[0]))60}...

Full Screen

Full Screen

Type

Using AI Code Generation

copy

Full Screen

1import (2func main() {3 if err != nil {4 log.Fatal(err)5 }6 defer db.Close()7 if err := db.Ping(); err != nil {8 log.Fatal(err)9 }10 driver, err := postgres.WithInstance(db, &postgres.Config{})11 if err != nil {12 log.Fatal(err)13 }14 m, err := migrate.NewWithDatabaseInstance(15 if err != nil {16 log.Fatal(err)17 }18 if err := m.Up(); err != nil && err != migrate.ErrNoChange {19 log.Fatal(err)20 }21 fmt.Println("Migration successful!")22}23SELECT pg_advisory_unlock_all();

Full Screen

Full Screen

Type

Using AI Code Generation

copy

Full Screen

1func main() {2 migrations := migrations.NewMigrations()3 migrations.Type()4}5func main() {6 migrations := migrations.NewMigrations()7 migrations.Type()8}9func main() {10 migrations := migrations.NewMigrations()11 migrations.Type()12}13func main() {14 migrations := migrations.NewMigrations()15 migrations.Type()16}17func main() {18 migrations := migrations.NewMigrations()19 migrations.Type()20}21func main() {22 migrations := migrations.NewMigrations()23 migrations.Type()24}25func main() {26 migrations := migrations.NewMigrations()27 migrations.Type()28}29func main() {30 migrations := migrations.NewMigrations()31 migrations.Type()32}33func main() {34 migrations := migrations.NewMigrations()35 migrations.Type()36}37func main() {38 migrations := migrations.NewMigrations()39 migrations.Type()40}41func main() {42 migrations := migrations.NewMigrations()43 migrations.Type()44}45func main() {46 migrations := migrations.NewMigrations()47 migrations.Type()48}49func main() {50 migrations := migrations.NewMigrations()51 migrations.Type()52}53func main() {54 migrations := migrations.NewMigrations()55 migrations.Type()56}57func main() {58 migrations := migrations.NewMigrations()59 migrations.Type()60}

Full Screen

Full Screen

Type

Using AI Code Generation

copy

Full Screen

1import (2func init() {3 migrations.MustRegisterTx(func(db migrations.DB) error {4 _, err := db.Exec("ALTER TABLE users ADD COLUMN name text")5 }, func(db migrations.DB) error {6 _, err := db.Exec("ALTER TABLE users DROP COLUMN name")7 })8}9import (10func init() {11 migrations.MustRegisterTx(func(db migrations.DB) error {12 _, err := db.Exec("ALTER TABLE users ADD COLUMN name text")13 }, func(db migrations.DB) error {14 _, err := db.Exec("ALTER TABLE users DROP COLUMN name")15 })16}17import (18func init() {19 migrations.MustRegisterTx(func(db migrations.DB) error {20 _, err := db.Exec("ALTER TABLE users ADD COLUMN name text")21 }, func(db migrations.DB) error {22 _, err := db.Exec("ALTER TABLE users DROP COLUMN name")23 })24}25import (26func init() {27 migrations.MustRegisterTx(func(db migrations.DB) error {28 _, err := db.Exec("ALTER TABLE users ADD COLUMN name text")29 }, func(db migrations.DB) error {30 _, err := db.Exec("ALTER TABLE users DROP COLUMN name")31 })32}33import (34func init() {35 migrations.MustRegisterTx(func(db migrations.DB) error {36 _, err := db.Exec("ALTER TABLE users ADD COLUMN name text")37 }, func(db migrations.DB) error {38 _, err := db.Exec("ALTER TABLE users DROP COLUMN name")39 })40}

Full Screen

Full Screen

Type

Using AI Code Generation

copy

Full Screen

1import (2func main() {3 m := new(migration.Migration)4 fmt.Println(m.Type())5}6import (7func main() {8 m := new(migration.Migration)9 fmt.Println(m.Up())10}11import (12func main() {13 m := new(migration.Migration)14 fmt.Println(m.Down())15}16import (17func main() {18 m := new(migration.Migration)19 m.SetID("202010131647")20 fmt.Println(m.ID)21}22import (23func main() {24 m := new(migration.Migration)25 m.SetID("202010131647")26 fmt.Println(m.ID)27}28import (29func main() {30 m := new(migration.Migration)31 m.SetID("202010131647")32 fmt.Println(m.ID)33}34import (35func main() {36 m := new(migration.Migration)37 m.SetID("202010131647")38 fmt.Println(m.ID)39}40import (

Full Screen

Full Screen

Type

Using AI Code Generation

copy

Full Screen

1import (2func main() {3 m := &migrations{}4 m.Type()5}6import (7type migrations struct {8}9func (m *migrations) Up() {10}11func (m *migrations) Down() {12}13func init() {14 m := &migrations{}

Full Screen

Full Screen

Type

Using AI Code Generation

copy

Full Screen

1migrations := NewMigrations()2migrations.Type("path")3migrations.Up()4migrations.Down()5migrations.Reset()6migrations.Redo()7migrations.Refresh()8migrations.Version()9migrations.Status()10migrations.Create()11migrations.CreateWithTimestamp()12migrations.CreateWithTimestamp()13migrations.CreateWithTimestamp()14migrations.CreateWithTimestamp()15migrations.CreateWithTimestamp()16migrations.CreateWithTimestamp()17migrations.CreateWithTimestamp()18migrations.CreateWithTimestamp()19migrations.CreateWithTimestamp()20migrations.CreateWithTimestamp()21migrations.CreateWithTimestamp()22migrations.CreateWithTimestamp()

Full Screen

Full Screen

Type

Using AI Code Generation

copy

Full Screen

1func main() {2 migrations := migrations.NewMigrations()3 migrations.Type()4}5func main() {6 migrations := migrations.NewMigrations()7 migrations.Type()8}9func main() {10 migrations := migrations.NewMigrations()11 migrations.Type()12}13func main() {14 migrations := migrations.NewMigrations()15 migrations.Type()16}17func main() {18 migrations := migrations.NewMigrations()19 migrations.Type()20}21func main() {22 migrations := migrations.NewMigrations()23 migrations.Type()24}25func main() {26 migrations := migrations.NewMigrations()27 migrations.Type()28}29func main() {30 migrations := migrations.NewMigrations()31 migrations.Type()32}33func main() {34 migrations := migrations.NewMigrations()35 migrations.Type()36}37func main() {38 migrations := migrations.NewMigrations()39 migrations.Type()40}41func main() {42 migrations := migrations.NewMigrations()43 migrations.Type()44}

Full Screen

Full Screen

Type

Using AI Code Generation

copy

Full Screen

1import (2type User_20180917_111202 struct {3}4func init() {5 m := &User_20180917_111202{}6 migration.Register("User_20180917_111202", m)7}8func (m *User_20180917_111202) Up() {9 m.SQL("CREATE TABLE `user` (`id` int(11) NOT NULL AUTO_INCREMENT,`username` varchar(45) DEFAULT NULL,`password` varchar(45) DEFAULT NULL,`phone` varchar(45) DEFAULT NULL,`email` varchar(45) DEFAULT NULL,`created_at` datetime DEFAULT NULL,`updated_at` datetime DEFAULT NULL,PRIMARY KEY (`id`)) ENGINE=InnoDB AUTO_INCREMENT=2 DEFAULT CHARSET=utf8;")10}11func (m *User_20180917_111202) Down() {12 m.SQL("DROP TABLE `user`;")13}

Full Screen

Full Screen

Type

Using AI Code Generation

copy

Full Screen

1import (2type AddColumn_20180521_092350 struct {3}4func init() {5 m := &AddColumn_20180521_092350{}6 migration.Register("AddColumn_20180521_092350", m)7}8func (m *AddColumn_20180521_092350) Up() {9 m.SQL("ALTER TABLE `user` ADD COLUMN `age` INT(11) NULL DEFAULT NULL COMMENT '年龄' AFTER `name`;")10}11func (m *AddColumn_20180521_092350) Down() {12 m.SQL("ALTER TABLE `user` DROP COLUMN `age`;")13}14import (15type DropColumn_20180521_092350 struct {16}17func init() {18 m := &DropColumn_20180521_092350{}19 migration.Register("DropColumn_20180521_092350", m)20}21func (m *DropColumn_20180521_092350) Up() {22 m.SQL("ALTER TABLE `user` DROP COLUMN `age`;")23}24func (m *DropColumn_20180521_092350) Down() {25 m.SQL("ALTER TABLE `user` ADD COLUMN `age` INT(11) NULL DEFAULT NULL COMMENT '年龄' AFTER `name`;")26}27import (28type AddIndex_20180521_092350 struct {29}30func init() {

Full Screen

Full Screen

Type

Using AI Code Generation

copy

Full Screen

1migrations := migrations.NewMigrations()2migrations.Type("1.0.0", "create table users (name varchar(255), age int)")3migrations.Type("1.0.1", "create table users (name varchar(255), age int)")4migrations.Type("1.0.2", "create table users (name varchar(255), age int)")5migrations.Type("1.0.3", "create table users (name varchar(255), age int)")6migrations.Type("1.0.4", "create table users (name varchar(255), age int)")7migrations.Type("1.0.5", "create table users (name varchar(255), age int)")8migrations.Type("1.0.6", "create table users (name varchar(255), age int)")9migrations.Type("1.0.7", "create table users (name varchar(255), age int)")10migrations.Type("1.0.8", "create table users (name varchar(255), age int)")11migrations.Type("1.0.9", "create table users (name varchar(255), age int)")12migrations.Type("1.0.10", "create table users (name varchar(255), age int)")13migrations.Type("1.0.11", "create table users (name varchar(255), age int)")14migrations.Type("1.0.12", "create table users (name varchar(255), age int)")15migrations.Type("1.0.13", "create table users (name varchar(255), age int)")16migrations.Type("1.0.14", "create table users (name varchar(255), age int)")17migrations.Type("1.0.15", "create table users (name varchar(255), age int)")18migrations.Type("1.0.16", "create table users (name varchar(255), age int)")19migrations.Type("1.0.17", "create table users (name varchar(255), age int)")20migrations.Type("1.0.18", "create table users (name varchar(255), age int)")21migrations.Type("1.0.19", "create table users (name varchar(255), age int)")22migrations.Type("1.0.20", "create table users (name varchar(255), age int)")23migrations.Type("1.0

Full Screen

Full Screen

Automation Testing Tutorials

Learn to execute automation testing from scratch with LambdaTest Learning Hub. Right from setting up the prerequisites to run your first automation test, to following best practices and diving deeper into advanced test scenarios. LambdaTest Learning Hubs compile a list of step-by-step guides to help you be proficient with different test automation frameworks i.e. Selenium, Cypress, TestNG etc.

LambdaTest Learning Hubs:

YouTube

You could also refer to video tutorials over LambdaTest YouTube channel to get step by step demonstration from industry experts.

Run Testkube automation tests on LambdaTest cloud grid

Perform automation testing on 3000+ real desktop and mobile devices online.

Try LambdaTest Now !!

Get 100 minutes of automation test minutes FREE!!

Next-Gen App & Browser Testing Cloud

Was this article helpful?

Helpful

NotHelpful