33 lines
1.1 KiB
Go
33 lines
1.1 KiB
Go
package database
|
|||
|
|
|
||
|
|
import (
|
||
|
|
"context"
|
||
|
|
"database/sql"
|
||
|
|
"fmt"
|
||
|
|
)
|
||
|
|
|
||
|
|
// Migrate creates the tables this application needs, if they don't already
|
||
|
|
// exist. This is intentionally the simplest possible approach
|
||
|
|
// (CREATE TABLE IF NOT EXISTS run on every startup) and is fine for a
|
||
|
|
// learning project with a single table.
|
||
|
|
//
|
||
|
|
// For a real production project you'd want a proper migration tool (e.g.
|
||
|
|
// golang-migrate/migrate) that tracks a version number, supports
|
||
|
|
// incremental "up"/"down" migrations, and can safely evolve a schema that
|
||
|
|
// already has production data in it. This function is a deliberate
|
||
|
|
// shortcut around that complexity for now.
|
||
|
|
func Migrate(ctx context.Context, db *sql.DB) error {
|
||
|
|
_, err := db.ExecContext(ctx, `
|
||
|
|
CREATE TABLE IF NOT EXISTS users (
|
||
|
|
id INT AUTO_INCREMENT PRIMARY KEY,
|
||
|
|
email VARCHAR(255) NOT NULL UNIQUE,
|
||
|
|
password_hash VARCHAR(255) NOT NULL DEFAULT '',
|
||
|
|
google_id VARCHAR(255) NOT NULL DEFAULT '',
|
||
|
|
created_at DATETIME NOT NULL
|
||
|
|
)`)
|
||
|
|
if err != nil {
|
||
|
|
return fmt.Errorf("migrate users table: %w", err)
|
||
|
|
}
|
||
|
|
return nil
|
||
|
|
}
|