package main import ( "context" "fmt" "os" "github.com/sirupsen/logrus" "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") // log is the global error logging interface. var log *logrus.Logger func main() { setupLogger() // Do we want to handle the error here instead? db := initializeDatabase() } func setupLogger() { log = logrus.New() log.SetFormatter(&logrus.TextFormatter{ FullTimestamp: true, // Include the full timestamp (with date and time) }) } // initializeDatabase creates the database and then 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) } // 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) } }