add logger, rearrange database initialization

This commit is contained in:
katefort 2025-04-08 17:10:49 -05:00
parent d26e7b8345
commit 735de8d657
7 changed files with 131 additions and 14 deletions

View file

@ -4,8 +4,8 @@ import (
"context"
"fmt"
"os"
"time"
"github.com/sirupsen/logrus"
"github.com/vingarcia/ksql"
"github.com/vingarcia/ksql/adapters/kpgx"
)
@ -16,27 +16,43 @@ 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")
database := os.Getenv("DB_NAME")
dbName := os.Getenv("DB_NAME")
connectString :=
fmt.Sprintf("postgres:///?host=%s&database=%s", host, database)
connectString := fmt.Sprintf("postgres:///?host=%s&database=%s", host, dbName)
db, err := kpgx.New(ctx, connectString, ksql.Config{})
if err != nil {
fmt.Fprintf(os.Stderr, "Unable to connect to database: %v\n", err)
os.Exit(1)
log.Fatalf("Unable to connect to database: %v\n", err)
}
defer db.Close()
createTables(ctx, db)
}
func createTables(db) {
_, err = db.Exec(ctx, `
// 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,
@ -45,7 +61,7 @@ func createTables(db) {
);
`)
if err != nil {
panic(err.Error())
log.Fatal(err)
}
_, err = db.Exec(ctx, `
CREATE TABLE IF NOT EXISTS user_claims (
@ -64,7 +80,7 @@ func createTables(db) {
CREATE INDEX idx_user_claims_product_id ON user_claims USING HASH (product_id);
`)
if err != nil {
panic(err.Error())
log.Fatal(err)
}
_, err = db.Exec(ctx, `
CREATE TABLE IF NOT EXISTS automated_claims (
@ -82,6 +98,6 @@ func createTables(db) {
CREATE INDEX idx_automated_claims_product_id ON automated_claims USING HASH (product_id);
`)
if err != nil {
panic(err.Error())
log.Fatal(err)
}
}

View file

@ -1,7 +1,7 @@
package main
import (
"github.com/vingarcia/ksql"
"time"
)
type Product struct {