feat(db): button up migrations
All checks were successful
continuous-integration/drone/push Build is passing

This commit is contained in:
2024-02-01 20:05:35 -05:00
parent 4a5464853b
commit 5865fe3c13
11 changed files with 197 additions and 134 deletions

View File

@@ -14,16 +14,14 @@ func init() {
}
func upUserAuthHash(ctx context.Context, tx *sql.Tx) error {
// Validate column doesn't already exist
hasCol, err := hasColumn(tx, "users", "auth_hash")
if err != nil {
return err
} else if hasCol {
// Determine if we have a new DB or not
isNew := ctx.Value("isNew").(bool)
if isNew {
return nil
}
// Copy table & create column
_, err = tx.Exec(`
_, err := tx.Exec(`
-- Create Copy Table
CREATE TABLE temp_users AS SELECT * FROM users;
ALTER TABLE temp_users ADD COLUMN auth_hash TEXT;

View File

@@ -1,9 +1,9 @@
# DB Migrations
```bash
# SQL migration
goose create migration_name sql
# Go migration
goose create migration_name
```
## Note
Since we update both the `schema.sql`, as well as the migration files, when we create a new DB it will inherently be up-to-date. We don't want to run the migrations if it's already up-to-date. Instead each migration checks if we have a new DB (via a value passed into the context), and if we do we simply return.

View File

@@ -1,38 +0,0 @@
package migrations
import (
"database/sql"
"fmt"
)
type columnInfo struct {
CID int
Name string
Type string
NotNull int
DefaultVal sql.NullString
PK int
}
func hasColumn(tx *sql.Tx, table string, column string) (bool, error) {
rows, err := tx.Query(fmt.Sprintf("PRAGMA table_info(%s)", table))
if err != nil {
return false, err
}
defer rows.Close()
colExists := false
for rows.Next() {
var col columnInfo
if err := rows.Scan(&col.CID, &col.Name, &col.Type, &col.NotNull, &col.DefaultVal, &col.PK); err != nil {
return false, err
}
if col.Name == column {
colExists = true
break
}
}
return colExists, nil
}