docs: update the go-migrations examples (#583)

pull/584/head
Feng Ce 2023-08-11 20:35:22 +08:00 committed by GitHub
parent d67f26cb2e
commit 75ba38920f
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
2 changed files with 14 additions and 18 deletions

View File

@ -1,27 +1,22 @@
package main package main
import ( import (
"context"
"database/sql" "database/sql"
"github.com/pressly/goose/v3" "github.com/pressly/goose/v3"
) )
func init() { func init() {
goose.AddMigration(Up00002, Down00002) goose.AddMigrationContext(Up00002, Down00002)
} }
func Up00002(tx *sql.Tx) error { func Up00002(ctx context.Context, tx *sql.Tx) error {
_, err := tx.Exec("UPDATE users SET username='admin' WHERE username='root';") _, err := tx.ExecContext(ctx, "UPDATE users SET username='admin' WHERE username='root';")
if err != nil { return err
return err
}
return nil
} }
func Down00002(tx *sql.Tx) error { func Down00002(ctx context.Context, tx *sql.Tx) error {
_, err := tx.Exec("UPDATE users SET username='root' WHERE username='admin';") _, err := tx.ExecContext(ctx, "UPDATE users SET username='root' WHERE username='admin';")
if err != nil { return err
return err
}
return nil
} }

View File

@ -1,6 +1,7 @@
package main package main
import ( import (
"context"
"database/sql" "database/sql"
"errors" "errors"
@ -8,17 +9,17 @@ import (
) )
func init() { func init() {
goose.AddMigrationNoTx(Up00003, Down00003) goose.AddMigrationNoTxContext(Up00003, Down00003)
} }
func Up00003(db *sql.DB) error { func Up00003(ctx context.Context, db *sql.DB) error {
id, err := getUserID(db, "jamesbond") id, err := getUserID(db, "jamesbond")
if err != nil { if err != nil {
return err return err
} }
if id == 0 { if id == 0 {
query := "INSERT INTO users (username, name, surname) VALUES ($1, $2, $3)" query := "INSERT INTO users (username, name, surname) VALUES ($1, $2, $3)"
if _, err := db.Exec(query, "jamesbond", "James", "Bond"); err != nil { if _, err := db.ExecContext(ctx, query, "jamesbond", "James", "Bond"); err != nil {
return err return err
} }
} }
@ -34,9 +35,9 @@ func getUserID(db *sql.DB, username string) (int, error) {
return id, nil return id, nil
} }
func Down00003(db *sql.DB) error { func Down00003(ctx context.Context, db *sql.DB) error {
query := "DELETE FROM users WHERE username = $1" query := "DELETE FROM users WHERE username = $1"
if _, err := db.Exec(query, "jamesbond"); err != nil { if _, err := db.ExecContext(ctx, query, "jamesbond"); err != nil {
return err return err
} }
return nil return nil