github.com/blend/go-sdk@v1.20220411.3/examples/db/migration/custom/main.go (about) 1 /* 2 3 Copyright (c) 2022 - Present. Blend Labs, Inc. All rights reserved 4 Use of this source code is governed by a MIT license that can be found in the LICENSE file. 5 6 */ 7 8 package main 9 10 import ( 11 "context" 12 "database/sql" 13 "fmt" 14 "strings" 15 16 "github.com/blend/go-sdk/db" 17 "github.com/blend/go-sdk/db/migration" 18 "github.com/blend/go-sdk/logger" 19 ) 20 21 // UserNotExists creates a index on the given connection if it does not exist. 22 func UserNotExists(username string) migration.GuardFunc { 23 return migration.Guard(fmt.Sprintf("create user `%s`", username), func(ctx context.Context, c *db.Connection, tx *sql.Tx) (bool, error) { 24 return c.Invoke(db.OptContext(ctx), db.OptTx(tx)).Query(`SELECT 1 FROM users WHERE username = $1`, strings.ToLower(username)).None() 25 }) 26 } 27 28 func main() { 29 suite := migration.New( 30 migration.OptGroups( 31 migration.NewGroupWithAction( 32 migration.TableNotExists("users"), 33 migration.Statements( 34 "CREATE TABLE users (username varchar(255) primary key);", 35 ), 36 ), 37 migration.NewGroupWithAction( 38 UserNotExists("example-string"), 39 migration.Exec("INSERT INTO users (username) VALUES ($1)", "example-string"), 40 ), 41 migration.NewGroupWithAction( 42 UserNotExists("example-string"), 43 migration.Exec("INSERT INTO users (username) VALUES ($1)", "example-string"), 44 ), 45 migration.NewGroupWithAction( 46 migration.TableExists("users"), 47 migration.Statements( 48 "DROP TABLE users;", 49 ), 50 ), 51 ), 52 ) 53 suite.Log = logger.All() 54 55 conn, err := db.Open(db.New(db.OptConfigFromEnv())) 56 if err != nil { 57 logger.FatalExit(err) 58 } 59 60 if err := suite.Apply(context.Background(), conn); err != nil { 61 logger.FatalExit(err) 62 } 63 }