vegan-barcode/internal/database/database.go
2025-04-17 15:54:33 -05:00

88 lines
2.1 KiB
Go

package database
import (
"context"
"fmt"
"log"
"os"
"github.com/vingarcia/ksql"
"github.com/vingarcia/ksql/adapters/kpgx"
)
var ProductsTable = ksql.NewTable("products", "product_id")
var UserClaimsTable = ksql.NewTable("user_claims", "user_claim_id")
var AutomatedClaimsTable = ksql.NewTable("automated_claims", "automated_claim_id")
// initializeDatabase creates the database and calls createTables.
func InitializeDatabase() *ksql.DB {
ctx := context.Background()
// urlExample := "postgres://username:password@localhost:5432/database_name"
host := os.Getenv("PGHOST")
dbName := os.Getenv("DB_NAME")
connectString := fmt.Sprintf("postgres:///?host=%s&database=%s", host, dbName)
db, err := kpgx.New(ctx, connectString, ksql.Config{})
if err != nil {
log.Fatalf("Unable to connect to database: %v\n", err)
}
createTables(ctx, db)
return &db
}
// createTables adds the product, automated_claims, and user_claims tables to the initialized database.
func createTables(ctx context.Context, db ksql.DB) {
_, err := db.Exec(ctx, `
CREATE TABLE IF NOT EXISTS products (
id INTEGER PRIMARY KEY,
system TEXT,
barcode TEXT,
created_at TIMESTAMPTZ
);
`)
if err != nil {
log.Fatal(err)
}
_, err = db.Exec(ctx, `
CREATE TABLE IF NOT EXISTS user_claims (
id INTEGER PRIMARY KEY,
product_id INTEGER,
evidence_type INTEGER,
evidence JSONB,
claim INTEGER,
counter_claim INTEGER,
created_at TIMESTAMPTZ,
created_by TEXT,
CONSTRAINT fk_product_id FOREIGN KEY(product_id) REFERENCES products(id)
);
CREATE INDEX idx_user_claims_product_id ON user_claims USING HASH (product_id);
`)
if err != nil {
log.Fatal(err)
}
_, err = db.Exec(ctx, `
CREATE TABLE IF NOT EXISTS automated_claims (
id INTEGER PRIMARY KEY,
product_id INTEGER,
worker_type INTEGER,
evidence JSONB,
claim INTEGER,
counter_claim INTEGER,
created_at TIMESTAMPTZ,
CONSTRAINT fk_product_id FOREIGN KEY(product_id) REFERENCES products(id)
);
CREATE INDEX idx_automated_claims_product_id ON automated_claims USING HASH (product_id);
`)
if err != nil {
log.Fatal(err)
}
}