Version 1
This commit is contained in:
@@ -0,0 +1,134 @@
|
||||
package database
|
||||
|
||||
import (
|
||||
"context"
|
||||
"time"
|
||||
|
||||
"github.com/jackc/pgx/v5/pgxpool"
|
||||
)
|
||||
|
||||
type DB struct {
|
||||
Pool *pgxpool.Pool
|
||||
}
|
||||
|
||||
func NewPostgres(databaseURL string) (*DB, error) {
|
||||
ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second)
|
||||
defer cancel()
|
||||
|
||||
config, err := pgxpool.ParseConfig(databaseURL)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
config.MaxConns = 10
|
||||
config.MinConns = 1
|
||||
config.MaxConnLifetime = time.Hour
|
||||
config.MaxConnIdleTime = 30 * time.Minute
|
||||
|
||||
pool, err := pgxpool.NewWithConfig(ctx, config)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
if err := pool.Ping(ctx); err != nil {
|
||||
pool.Close()
|
||||
return nil, err
|
||||
}
|
||||
|
||||
return &DB{Pool: pool}, nil
|
||||
}
|
||||
|
||||
func (d *DB) EnsureSchema(ctx context.Context) error {
|
||||
if d == nil || d.Pool == nil {
|
||||
return nil
|
||||
}
|
||||
|
||||
statements := []string{
|
||||
`CREATE TABLE IF NOT EXISTS orders (
|
||||
id TEXT PRIMARY KEY,
|
||||
status TEXT NOT NULL,
|
||||
fulfillment_status TEXT NOT NULL DEFAULT 'pending',
|
||||
email TEXT NOT NULL,
|
||||
phone TEXT NOT NULL,
|
||||
first_name TEXT NOT NULL,
|
||||
last_name TEXT NOT NULL,
|
||||
address_line_1 TEXT NOT NULL,
|
||||
address_line_2 TEXT NOT NULL DEFAULT '',
|
||||
city TEXT NOT NULL,
|
||||
region TEXT NOT NULL,
|
||||
postal_code TEXT NOT NULL,
|
||||
country TEXT NOT NULL,
|
||||
notes TEXT NOT NULL DEFAULT '',
|
||||
currency TEXT NOT NULL,
|
||||
amount BIGINT NOT NULL,
|
||||
stripe_price_id TEXT NOT NULL,
|
||||
stripe_payment_intent_id TEXT NOT NULL UNIQUE,
|
||||
shipping_carrier TEXT NOT NULL DEFAULT '',
|
||||
tracking_number TEXT NOT NULL DEFAULT '',
|
||||
fulfillment_notes TEXT NOT NULL DEFAULT '',
|
||||
shipped_at TIMESTAMPTZ NULL,
|
||||
webhook_status TEXT NOT NULL DEFAULT 'awaiting_webhook',
|
||||
webhook_event_id TEXT NOT NULL DEFAULT '',
|
||||
webhook_event_type TEXT NOT NULL DEFAULT '',
|
||||
webhook_message TEXT NOT NULL DEFAULT 'Waiting for Stripe webhook verification.',
|
||||
created_at TIMESTAMPTZ NOT NULL DEFAULT NOW(),
|
||||
updated_at TIMESTAMPTZ NOT NULL DEFAULT NOW()
|
||||
)`,
|
||||
`ALTER TABLE orders ADD COLUMN IF NOT EXISTS fulfillment_status TEXT NOT NULL DEFAULT 'pending'`,
|
||||
`ALTER TABLE orders ADD COLUMN IF NOT EXISTS shipping_carrier TEXT NOT NULL DEFAULT ''`,
|
||||
`ALTER TABLE orders ADD COLUMN IF NOT EXISTS tracking_number TEXT NOT NULL DEFAULT ''`,
|
||||
`ALTER TABLE orders ADD COLUMN IF NOT EXISTS fulfillment_notes TEXT NOT NULL DEFAULT ''`,
|
||||
`ALTER TABLE orders ADD COLUMN IF NOT EXISTS shipped_at TIMESTAMPTZ NULL`,
|
||||
`CREATE TABLE IF NOT EXISTS order_items (
|
||||
id BIGSERIAL PRIMARY KEY,
|
||||
order_id TEXT NOT NULL REFERENCES orders(id) ON DELETE CASCADE,
|
||||
item_id TEXT NOT NULL,
|
||||
style TEXT NOT NULL,
|
||||
colorway_id TEXT NOT NULL,
|
||||
finish_id TEXT NOT NULL,
|
||||
quantity BIGINT NOT NULL,
|
||||
unit_amount BIGINT NOT NULL,
|
||||
created_at TIMESTAMPTZ NOT NULL DEFAULT NOW()
|
||||
)`,
|
||||
`CREATE INDEX IF NOT EXISTS idx_order_items_order_id ON order_items(order_id)`,
|
||||
`CREATE INDEX IF NOT EXISTS idx_orders_status ON orders(status)`,
|
||||
`CREATE INDEX IF NOT EXISTS idx_orders_fulfillment_status ON orders(fulfillment_status)`,
|
||||
`CREATE INDEX IF NOT EXISTS idx_orders_tracking_number ON orders(tracking_number)`,
|
||||
`CREATE TABLE IF NOT EXISTS inventory_levels (
|
||||
id BIGSERIAL PRIMARY KEY,
|
||||
style TEXT NOT NULL,
|
||||
colorway_id TEXT NOT NULL,
|
||||
finish_id TEXT NOT NULL,
|
||||
quantity_on_hand BIGINT NOT NULL DEFAULT 0,
|
||||
notes TEXT NOT NULL DEFAULT '',
|
||||
created_at TIMESTAMPTZ NOT NULL DEFAULT NOW(),
|
||||
updated_at TIMESTAMPTZ NOT NULL DEFAULT NOW(),
|
||||
UNIQUE(style, colorway_id, finish_id)
|
||||
)`,
|
||||
`CREATE INDEX IF NOT EXISTS idx_inventory_levels_colorway ON inventory_levels(colorway_id)`,
|
||||
}
|
||||
|
||||
for _, statement := range statements {
|
||||
if _, err := d.Pool.Exec(ctx, statement); err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
func (d *DB) Health(ctx context.Context) error {
|
||||
if d == nil || d.Pool == nil {
|
||||
return nil
|
||||
}
|
||||
|
||||
return d.Pool.Ping(ctx)
|
||||
}
|
||||
|
||||
func (d *DB) Close() {
|
||||
if d == nil || d.Pool == nil {
|
||||
return
|
||||
}
|
||||
|
||||
d.Pool.Close()
|
||||
}
|
||||
@@ -0,0 +1,164 @@
|
||||
package database
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"context"
|
||||
"fmt"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"time"
|
||||
|
||||
"github.com/jackc/pgx/v5"
|
||||
)
|
||||
|
||||
type ReseedSummary struct {
|
||||
BackupPath string
|
||||
OrdersCount int
|
||||
OrderItemsCount int
|
||||
InventoryCount int
|
||||
}
|
||||
|
||||
func (d *DB) BackupAndResetAppData(ctx context.Context) (*ReseedSummary, error) {
|
||||
if d == nil || d.Pool == nil {
|
||||
return nil, fmt.Errorf("database is not configured")
|
||||
}
|
||||
|
||||
tx, err := d.Pool.BeginTx(ctx, pgx.TxOptions{IsoLevel: pgx.RepeatableRead})
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
committed := false
|
||||
defer func() {
|
||||
if !committed {
|
||||
_ = tx.Rollback(ctx)
|
||||
}
|
||||
}()
|
||||
|
||||
ordersStatements, err := collectStatements(ctx, tx, `
|
||||
SELECT format(
|
||||
'INSERT INTO orders (id, status, fulfillment_status, email, phone, first_name, last_name, address_line_1, address_line_2, city, region, postal_code, country, notes, currency, amount, stripe_price_id, stripe_payment_intent_id, shipping_carrier, tracking_number, fulfillment_notes, shipped_at, webhook_status, webhook_event_id, webhook_event_type, webhook_message, created_at, updated_at) VALUES (%L, %L, %L, %L, %L, %L, %L, %L, %L, %L, %L, %L, %L, %L, %L, %L, %L, %L, %L, %L, %L, %L, %L, %L, %L, %L, %L, %L);',
|
||||
id, status, fulfillment_status, email, phone, first_name, last_name, address_line_1, address_line_2, city, region, postal_code, country, notes, currency, amount, stripe_price_id, stripe_payment_intent_id, shipping_carrier, tracking_number, fulfillment_notes, shipped_at, webhook_status, webhook_event_id, webhook_event_type, webhook_message, created_at, updated_at
|
||||
)
|
||||
FROM orders
|
||||
ORDER BY created_at ASC, id ASC
|
||||
`)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
orderItemsStatements, err := collectStatements(ctx, tx, `
|
||||
SELECT format(
|
||||
'INSERT INTO order_items (order_id, item_id, style, colorway_id, finish_id, quantity, unit_amount, created_at) VALUES (%L, %L, %L, %L, %L, %L, %L, %L);',
|
||||
order_id, item_id, style, colorway_id, finish_id, quantity, unit_amount, created_at
|
||||
)
|
||||
FROM order_items
|
||||
ORDER BY created_at ASC, order_id ASC
|
||||
`)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
inventoryStatements, err := collectStatements(ctx, tx, `
|
||||
SELECT format(
|
||||
'INSERT INTO inventory_levels (style, colorway_id, finish_id, quantity_on_hand, notes, created_at, updated_at) VALUES (%L, %L, %L, %L, %L, %L, %L);',
|
||||
style, colorway_id, finish_id, quantity_on_hand, notes, created_at, updated_at
|
||||
)
|
||||
FROM inventory_levels
|
||||
ORDER BY style ASC, colorway_id ASC, finish_id ASC
|
||||
`)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
backupContent := buildReseedBackupSQL(ordersStatements, orderItemsStatements, inventoryStatements)
|
||||
backupPath, err := writeReseedBackupFile(backupContent)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
if _, err := tx.Exec(ctx, `TRUNCATE TABLE order_items, orders, inventory_levels RESTART IDENTITY CASCADE`); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
if err := tx.Commit(ctx); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
committed = true
|
||||
|
||||
return &ReseedSummary{
|
||||
BackupPath: backupPath,
|
||||
OrdersCount: len(ordersStatements),
|
||||
OrderItemsCount: len(orderItemsStatements),
|
||||
InventoryCount: len(inventoryStatements),
|
||||
}, nil
|
||||
}
|
||||
|
||||
func collectStatements(ctx context.Context, tx pgx.Tx, query string) ([]string, error) {
|
||||
rows, err := tx.Query(ctx, query)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
defer rows.Close()
|
||||
|
||||
statements := make([]string, 0)
|
||||
for rows.Next() {
|
||||
var statement string
|
||||
if err := rows.Scan(&statement); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
statements = append(statements, statement)
|
||||
}
|
||||
|
||||
if err := rows.Err(); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
return statements, nil
|
||||
}
|
||||
|
||||
func buildReseedBackupSQL(ordersStatements, orderItemsStatements, inventoryStatements []string) []byte {
|
||||
var buffer bytes.Buffer
|
||||
timestamp := time.Now().UTC().Format(time.RFC3339)
|
||||
|
||||
buffer.WriteString("-- Royal Pop local reseed backup\n")
|
||||
buffer.WriteString("-- Created at: " + timestamp + "\n")
|
||||
buffer.WriteString(fmt.Sprintf("-- Orders: %d | Order items: %d | Inventory rows: %d\n\n", len(ordersStatements), len(orderItemsStatements), len(inventoryStatements)))
|
||||
buffer.WriteString("BEGIN;\n")
|
||||
buffer.WriteString("TRUNCATE TABLE order_items, orders, inventory_levels RESTART IDENTITY CASCADE;\n\n")
|
||||
|
||||
appendSection := func(title string, statements []string) {
|
||||
buffer.WriteString("-- " + title + "\n")
|
||||
if len(statements) == 0 {
|
||||
buffer.WriteString("-- (no rows)\n\n")
|
||||
return
|
||||
}
|
||||
for _, statement := range statements {
|
||||
buffer.WriteString(statement)
|
||||
buffer.WriteString("\n")
|
||||
}
|
||||
buffer.WriteString("\n")
|
||||
}
|
||||
|
||||
appendSection("orders", ordersStatements)
|
||||
appendSection("order_items", orderItemsStatements)
|
||||
appendSection("inventory_levels", inventoryStatements)
|
||||
buffer.WriteString("COMMIT;\n")
|
||||
|
||||
return buffer.Bytes()
|
||||
}
|
||||
|
||||
func writeReseedBackupFile(content []byte) (string, error) {
|
||||
backupDir := filepath.Join("Backups", "reseed")
|
||||
if err := os.MkdirAll(backupDir, 0o755); err != nil {
|
||||
return "", err
|
||||
}
|
||||
|
||||
filename := fmt.Sprintf("royal-pop-reseed-%s.sql", time.Now().UTC().Format("20060102-150405"))
|
||||
path := filepath.Join(backupDir, filename)
|
||||
if err := os.WriteFile(path, content, 0o600); err != nil {
|
||||
return "", err
|
||||
}
|
||||
|
||||
return path, nil
|
||||
}
|
||||
Reference in New Issue
Block a user