feat: add db management scripts
This commit is contained in:
48
scripts/setup-db/main.go
Normal file
48
scripts/setup-db/main.go
Normal file
@@ -0,0 +1,48 @@
|
||||
package main
|
||||
|
||||
import (
|
||||
"context"
|
||||
"fmt"
|
||||
"log"
|
||||
"time"
|
||||
|
||||
"git.ksdemosapps.com/kylesoda/pgx-learning/internal/config"
|
||||
"github.com/jackc/pgx/v5/pgxpool"
|
||||
)
|
||||
|
||||
func createTasksTable(db *pgxpool.Pool, ctx context.Context) error {
|
||||
createTableSQL := `
|
||||
CREATE TABLE IF NOT EXISTS tasks (
|
||||
id BIGSERIAL PRIMARY KEY,
|
||||
text TEXT NOT NULL,
|
||||
completed BOOLEAN NOT NULL DEFAULT FALSE,
|
||||
created_at TIMESTAMPTZ NOT NULL DEFAULT CURRENT_TIMESTAMP,
|
||||
updated_at TIMESTAMPTZ
|
||||
);
|
||||
`
|
||||
|
||||
_, err := db.Exec(ctx, createTableSQL)
|
||||
if err != nil {
|
||||
return fmt.Errorf("error creating tasks table: %w", err)
|
||||
}
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
func main() {
|
||||
ctx, cancel := context.WithTimeout(context.Background(), 20*time.Second)
|
||||
defer cancel()
|
||||
|
||||
db, err := pgxpool.New(ctx, config.Db.Url)
|
||||
if err != nil {
|
||||
log.Fatalf("Unable to create connection pool: %v", err)
|
||||
}
|
||||
|
||||
if err := createTasksTable(db, ctx); err != nil {
|
||||
log.Fatalf("Unexpected error: %v", err)
|
||||
} else {
|
||||
fmt.Println("Database setup completed succesfully")
|
||||
}
|
||||
|
||||
defer db.Close()
|
||||
}
|
||||
Reference in New Issue
Block a user