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
import (
"context"
"database/sql"
"github.com/pressly/goose/v3"
)
func init() {
goose.AddMigration(Up00002, Down00002)
goose.AddMigrationContext(Up00002, Down00002)
}
func Up00002(tx *sql.Tx) error {
_, err := tx.Exec("UPDATE users SET username='admin' WHERE username='root';")
if err != nil {
return err
}
return nil
func Up00002(ctx context.Context, tx *sql.Tx) error {
_, err := tx.ExecContext(ctx, "UPDATE users SET username='admin' WHERE username='root';")
return err
}
func Down00002(tx *sql.Tx) error {
_, err := tx.Exec("UPDATE users SET username='root' WHERE username='admin';")
if err != nil {
return err
}
return nil
func Down00002(ctx context.Context, tx *sql.Tx) error {
_, err := tx.ExecContext(ctx, "UPDATE users SET username='root' WHERE username='admin';")
return err
}

View File

@ -1,6 +1,7 @@
package main
import (
"context"
"database/sql"
"errors"
@ -8,17 +9,17 @@ import (
)
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")
if err != nil {
return err
}
if id == 0 {
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
}
}
@ -34,9 +35,9 @@ func getUserID(db *sql.DB, username string) (int, error) {
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"
if _, err := db.Exec(query, "jamesbond"); err != nil {
if _, err := db.ExecContext(ctx, query, "jamesbond"); err != nil {
return err
}
return nil