diff --git a/.gitignore b/.gitignore index 115f324..9191adc 100644 --- a/.gitignore +++ b/.gitignore @@ -28,16 +28,10 @@ tmp/ !.env.example # Project build -backend -tui +backend_bin +tui_bin .data/ # Log files logs/ - -# DB -*.db - -# UI Test file -ui/screen/test.go diff --git a/README.md b/README.md index 2dacb28..d0176ca 100644 --- a/README.md +++ b/README.md @@ -24,11 +24,12 @@ Displays the cammie chat along with some other statistics. ## DB -This project uses an SQLite database. +This project uses a postgres database. SQLC is used to generate statically typed queries and goose is responsible for the database migrations. ### Usefull commands +- `make db`: Start the database - `make migrate`: Run database migrations to update your database schema (watch out, migrations might result in minor data loss). - `make create-migration`: Create a new migration in the [db/migrations](./db/migrations/) directory. - `make sqlc`: Generate statically typed queries based on the .sql files in the [db/queries](./db/queries/) directory. Add new queries to this directory as needed. @@ -60,9 +61,9 @@ To build and run the TUI, use the following commands: - `make build-tui`: Build the TUI binary. - `make run-tui`: Run the TUI. - -The TUI requires one argument: the screen name to display. You can create new screens in the [screens directory](./ui/screen/), and you must add them to the startup command list in [tui.go](./internal/cmd/tui.go). +The TUI requires one argument: the screen name to display. You can create new screens in the [screens directory](./tui/screen/), and you must add them to the startup command list in [tui.go](./internal/cmd/tui.go). -A screen is responsible for creating and managing the layout, consisting of various [views](./ui/view/). +A screen is responsible for creating and managing the layout, consisting of various [views](./tui/view/). ### Logs diff --git a/cmd/backend/backend.go b/cmd/backend/backend.go new file mode 100644 index 0000000..678b4e4 --- /dev/null +++ b/cmd/backend/backend.go @@ -0,0 +1,54 @@ +// Main entry point for the backend +package main + +import ( + "github.com/zeusWPI/scc/internal/cmd" + "github.com/zeusWPI/scc/internal/pkg/db" + "github.com/zeusWPI/scc/pkg/config" + "github.com/zeusWPI/scc/pkg/logger" + "go.uber.org/zap" +) + +func main() { + // Config + err := config.Init() + if err != nil { + panic(err) + } + + // Logger + zapLogger, err := logger.New("backend", true) + if err != nil { + panic(err) + } + zap.ReplaceGlobals(zapLogger) + + zap.S().Info("Initializing backend") + + // Database + db, err := db.New() + if err != nil { + zap.S().Fatal("DB: Fatal error\n", err) + } + + // // Tap + // _, _ = cmd.Tap(db) + + // // Zess + // _, _, _ = cmd.Zess(db) + + // // Gamification + // _, _ = cmd.Gamification(db) + + // Event + _, _ = cmd.Event(db) + + // Spotify + spotify, err := cmd.Song(db) + if err != nil { + zap.S().Error("Spotify: Initiating error, integration will not work.\n", err) + } + + // API + cmd.API(db, spotify) +} diff --git a/cmd/tui/tui.go b/cmd/tui/tui.go new file mode 100644 index 0000000..b2d6669 --- /dev/null +++ b/cmd/tui/tui.go @@ -0,0 +1,39 @@ +// Main entry point for the tui +package main + +import ( + "github.com/zeusWPI/scc/internal/cmd" + "github.com/zeusWPI/scc/internal/pkg/db" + "github.com/zeusWPI/scc/pkg/config" + "github.com/zeusWPI/scc/pkg/logger" + "go.uber.org/zap" +) + +func main() { + // Config + err := config.Init() + if err != nil { + panic(err) + } + + // Logger + zapLogger, err := logger.New("tui", false) + if err != nil { + panic(err) + } + zap.ReplaceGlobals(zapLogger) + + zap.S().Info("Initializing TUI") + + // Database + db, err := db.New() + if err != nil { + zap.S().Fatal("DB: Fatal error\n", err) + } + + // TUI + err = cmd.TUI(db) + if err != nil { + zap.S().Fatal("TUI: Fatal error\n", err) + } +} diff --git a/db/migrations/20241114125504_add_messages_table.sql b/db/migrations/20241114125504_add_messages_table.sql index 2777928..8060357 100644 --- a/db/migrations/20241114125504_add_messages_table.sql +++ b/db/migrations/20241114125504_add_messages_table.sql @@ -1,11 +1,11 @@ -- +goose Up -- +goose StatementBegin CREATE TABLE IF NOT EXISTS message ( - id INTEGER PRIMARY KEY, + id SERIAL PRIMARY KEY, name TEXT NOT NULL, ip TEXT NOT NULL, message TEXT NOT NULL, - created_at TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP + created_at TIMESTAMP WITH TIME ZONE NOT NULL DEFAULT CURRENT_TIMESTAMP ); -- +goose StatementEnd diff --git a/db/migrations/20241114135818_add_spotify_table.sql b/db/migrations/20241114135818_add_spotify_table.sql index acbee16..35802e9 100644 --- a/db/migrations/20241114135818_add_spotify_table.sql +++ b/db/migrations/20241114135818_add_spotify_table.sql @@ -1,12 +1,12 @@ -- +goose Up -- +goose StatementBegin CREATE TABLE IF NOT EXISTS spotify ( - id INTEGER PRIMARY KEY, + id SERIAL PRIMARY KEY, title TEXT NOT NULL, artists TEXT NOT NULL, spotify_id TEXT NOT NULL, duration_ms INTEGER NOT NULL, - created_at TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP + created_at TIMESTAMP WITH TIME ZONE NOT NULL DEFAULT CURRENT_TIMESTAMP ); -- +goose StatementEnd diff --git a/db/migrations/20241114152122_add_tap_table.sql b/db/migrations/20241114152122_add_tap_table.sql index 0492937..61d6a24 100644 --- a/db/migrations/20241114152122_add_tap_table.sql +++ b/db/migrations/20241114152122_add_tap_table.sql @@ -1,12 +1,12 @@ -- +goose Up -- +goose StatementBegin CREATE TABLE IF NOT EXISTS tap ( - id INTEGER PRIMARY KEY, + id SERIAL PRIMARY KEY, order_id INTEGER NOT NULL, - order_created_at TIMESTAMP NOT NULL, + order_created_at TIMESTAMP WITH TIME ZONE NOT NULL, name TEXT NOT NULL, category TEXT NOT NULL, - created_at TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP + created_at TIMESTAMP WITH TIME ZONE NOT NULL DEFAULT CURRENT_TIMESTAMP ) -- +goose StatementEnd diff --git a/db/migrations/20241121141143_add_zess_table.sql b/db/migrations/20241121141143_add_zess_table.sql index d679be8..a5a6f67 100644 --- a/db/migrations/20241121141143_add_zess_table.sql +++ b/db/migrations/20241121141143_add_zess_table.sql @@ -1,15 +1,15 @@ -- +goose Up -- +goose StatementBegin CREATE TABLE IF NOT EXISTS season ( - id INTEGER PRIMARY KEY, + id SERIAL PRIMARY KEY, name VARCHAR(255) NOT NULL, - start TIMESTAMP NOT NULL, - end TIMESTAMP NOT NULL + start TIMESTAMP WITH TIME ZONE NOT NULL, + "end" TIMESTAMP WITH TIME ZONE NOT NULL ); CREATE TABLE IF NOT EXISTS scan ( id INTEGER PRIMARY KEY, - scan_time TIMESTAMP NOT NULL + scan_time TIMESTAMP WITH TIME ZONE NOT NULL ); -- +goose StatementEnd diff --git a/db/migrations/20241125113707_add_gamification_table.sql b/db/migrations/20241125113707_add_gamification_table.sql index 46ba33f..2da01bf 100644 --- a/db/migrations/20241125113707_add_gamification_table.sql +++ b/db/migrations/20241125113707_add_gamification_table.sql @@ -1,7 +1,7 @@ -- +goose Up -- +goose StatementBegin CREATE TABLE IF NOT EXISTS gamification ( - id INTEGER PRIMARY KEY, + id SERIAL PRIMARY KEY, name VARCHAR(255) NOT NULL, score INTEGER NOT NULL, avatar VARCHAR(255) NOT NULL diff --git a/db/migrations/20241127133125_add_events_table.sql b/db/migrations/20241127133125_add_events_table.sql index a083569..11369d4 100644 --- a/db/migrations/20241127133125_add_events_table.sql +++ b/db/migrations/20241127133125_add_events_table.sql @@ -1,9 +1,9 @@ -- +goose Up -- +goose StatementBegin CREATE TABLE IF NOT EXISTS event ( - id INTEGER PRIMARY KEY, + id SERIAL PRIMARY KEY, name TEXT NOT NULL, - date TIMESTAMP NOT NULL, + date TIMESTAMP WITH TIME ZONE NOT NULL, academic_year TEXT NOT NULL, location TEXT NOT NULL ); diff --git a/db/migrations/20241127162048_add_song_history_table.sql b/db/migrations/20241127162048_add_song_history_table.sql index 03cc0a6..aedaaa9 100644 --- a/db/migrations/20241127162048_add_song_history_table.sql +++ b/db/migrations/20241127162048_add_song_history_table.sql @@ -6,9 +6,9 @@ DROP COLUMN created_at; ALTER TABLE spotify RENAME TO song; CREATE TABLE IF NOT EXISTS song_history ( - id INTEGER PRIMARY KEY, + id SERIAL PRIMARY KEY, song_id INTEGER NOT NULL, - created_at TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP, + created_at TIMESTAMP WITH TIME ZONE NOT NULL DEFAULT CURRENT_TIMESTAMP, FOREIGN KEY(song_id) REFERENCES song(id) ); -- +goose StatementEnd @@ -20,5 +20,5 @@ DROP TABLE IF EXISTS song_history; ALTER TABLE song RENAME TO spotify; ALTER TABLE spotify -ADD COLUMN created_at TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP; +ADD COLUMN created_at TIMESTAMP WITH TIME ZONE NOT NULL DEFAULT CURRENT_TIMESTAMP; -- +goose StatementEnd diff --git a/db/migrations/20241127165609_add_song_genre.sql b/db/migrations/20241127165609_add_song_genre.sql index 75b1b12..5f214b4 100644 --- a/db/migrations/20241127165609_add_song_genre.sql +++ b/db/migrations/20241127165609_add_song_genre.sql @@ -4,12 +4,12 @@ ALTER TABLE song DROP COLUMN artists; CREATE TABLE IF NOT EXISTS song_genre ( - id INTEGER PRIMARY KEY, + id SERIAL PRIMARY KEY, genre TEXT NOT NULL ); CREATE TABLE IF NOT EXISTS song_artist ( - id INTEGER PRIMARY KEY, + id SERIAL PRIMARY KEY, name TEXT NOT NULL, spotify_id TEXT NOT NULL, followers INTEGER NOT NULL, @@ -17,19 +17,19 @@ CREATE TABLE IF NOT EXISTS song_artist ( ); CREATE TABLE IF NOT EXISTS song_artist_song ( - id INTEGER PRIMARY KEY, + id SERIAL PRIMARY KEY, artist_id INTEGER NOT NULL, song_id INTEGER NOT NULL, - FOREIGN KEY(artist_id) REFERENCES artist(id), - FOREIGN KEY(song_id) REFERENCES song(id) + FOREIGN KEY(artist_id) REFERENCES song_artist(id) ON DELETE CASCADE, + FOREIGN KEY(song_id) REFERENCES song(id) ON DELETE CASCADE ); CREATE TABLE IF NOT EXISTS song_artist_genre ( - id INTEGER PRIMARY KEY, + id SERIAL PRIMARY KEY, artist_id INTEGER NOT NULL, genre_id INTEGER NOT NULL, - FOREIGN KEY(artist_id) REFERENCES artist(id), - FOREIGN KEY(genre_id) REFERENCES genre(id) + FOREIGN KEY(artist_id) REFERENCES song_artist(id) ON DELETE CASCADE, + FOREIGN KEY(genre_id) REFERENCES song_genre(id) ON DELETE CASCADE ); -- +goose StatementEnd diff --git a/db/migrations/20241203173952_event_add_poster.sql b/db/migrations/20241203173952_event_add_poster.sql index e063186..3e195e5 100644 --- a/db/migrations/20241203173952_event_add_poster.sql +++ b/db/migrations/20241203173952_event_add_poster.sql @@ -1,7 +1,7 @@ -- +goose Up -- +goose StatementBegin ALTER TABLE event -ADD COLUMN poster BLOB; +ADD COLUMN poster BYTEA; -- +goose StatementEnd -- +goose Down diff --git a/db/migrations/20241203231431_gamification_add_avatar.sql b/db/migrations/20241203231431_gamification_add_avatar.sql index bcaab0b..0da53a0 100644 --- a/db/migrations/20241203231431_gamification_add_avatar.sql +++ b/db/migrations/20241203231431_gamification_add_avatar.sql @@ -4,7 +4,7 @@ ALTER TABLE gamification DROP COLUMN avatar; ALTER TABLE gamification -ADD COLUMN avatar BLOB; +ADD COLUMN avatar BYTEA; -- +goose StatementEnd -- +goose Down diff --git a/db/queries/event.sql b/db/queries/event.sql index c5b52e5..9646c2b 100644 --- a/db/queries/event.sql +++ b/db/queries/event.sql @@ -7,12 +7,12 @@ FROM event; -- name: CreateEvent :one INSERT INTO event (name, date, academic_year, location, poster) -VALUES (?, ?, ?, ?, ?) +VALUES ($1, $2, $3, $4, $5) RETURNING *; -- name: DeleteEvent :exec DELETE FROM event -WHERE id = ?; +WHERE id = $1; -- Other @@ -21,11 +21,11 @@ WHERE id = ?; -- name: GetEventByAcademicYear :many SELECT * FROM event -WHERE academic_year = ?; +WHERE academic_year = $1; -- name: DeleteEventByAcademicYear :exec DELETE FROM event -WHERE academic_year = ?; +WHERE academic_year = $1; -- name: GetEventsCurrentAcademicYear :many SELECT * diff --git a/db/queries/gamification.sql b/db/queries/gamification.sql index 3d54972..3113a19 100644 --- a/db/queries/gamification.sql +++ b/db/queries/gamification.sql @@ -6,12 +6,12 @@ FROM gamification; -- name: CreateGamification :one INSERT INTO gamification (name, score, avatar) -VALUES (?, ?, ?) +VALUES ($1, $2, $3) RETURNING *; -- name: DeleteGamification :execrows DELETE FROM gamification -WHERE id = ?; +WHERE id = $1; -- name: DeleteGamificationAll :execrows DELETE FROM gamification; @@ -22,8 +22,8 @@ DELETE FROM gamification; -- name: UpdateGamificationScore :one UPDATE gamification -SET score = ? -WHERE id = ? +SET score = $1 +WHERE id = $2 RETURNING *; -- name: GetAllGamificationByScore :many diff --git a/db/queries/message.sql b/db/queries/message.sql index 5617dd1..2b615ed 100644 --- a/db/queries/message.sql +++ b/db/queries/message.sql @@ -7,22 +7,22 @@ FROM message; -- name: GetMessageByID :one SELECT * FROM message -WHERE id = ?; +WHERE id = $1; -- name: CreateMessage :one INSERT INTO message (name, ip, message) -VALUES (?, ?, ?) +VALUES ($1, $2, $3) RETURNING *; -- name: UpdateMessage :one UPDATE message -SET name = ?, ip = ?, message = ? -WHERE id = ? +SET name = $1, ip = $2, message = $3 +WHERE id = $4 RETURNING *; -- name: DeleteMessage :execrows DELETE FROM message -WHERE id = ?; +WHERE id = $1; -- Other @@ -37,5 +37,5 @@ LIMIT 1; -- name: GetMessageSinceID :many SELECT * FROM message -WHERE id > ? +WHERE id > $1 ORDER BY created_at ASC; diff --git a/db/queries/scan.sql b/db/queries/scan.sql index f30cecf..7c9665a 100644 --- a/db/queries/scan.sql +++ b/db/queries/scan.sql @@ -7,22 +7,22 @@ FROM scan; -- name: GetScanByID :one SELECT * FROM scan -WHERE id = ?; +WHERE id = $1; -- name: CreateScan :one INSERT INTO scan (scan_time) -VALUES (?) +VALUES ($1) RETURNING *; -- name: UpdateScan :one UPDATE scan -SET scan_time = ? -WHERE id = ? +SET scan_time = $1 +WHERE id = $2 RETURNING *; -- name: DeleteScan :execrows DELETE FROM scan -WHERE id = ?; +WHERE id = $1; -- Other @@ -37,7 +37,7 @@ LIMIT 1; -- name: GetAllScansSinceID :many SELECT * FROM scan -WHERE id > ? +WHERE id > $1 ORDER BY scan_time ASC; -- name: GetScansInCurrentSeason :one diff --git a/db/queries/season.sql b/db/queries/season.sql index a39f2fc..90682ad 100644 --- a/db/queries/season.sql +++ b/db/queries/season.sql @@ -7,22 +7,22 @@ FROM season; -- name: GetSeasonByID :one SELECT * FROM season -WHERE id = ?; +WHERE id = $1; -- name: CreateSeason :one -INSERT INTO season (name, start, end, current) -VALUES (?, ?, ?, ?) +INSERT INTO season (name, start, "end", current) +VALUES ($1, $2, $3, $4) RETURNING *; -- name: UpdateSeason :one UPDATE season -SET name = ?, start = ?, end = ?, current = ? -WHERE id = ? +SET name = $1, start = $2, "end" = $3, current = $4 +WHERE id = $5 RETURNING *; -- name: DeleteSeason :execrows DELETE FROM season -WHERE id = ?; +WHERE id = $1; -- Other diff --git a/db/queries/song.sql b/db/queries/song.sql index 02db229..7e03b50 100644 --- a/db/queries/song.sql +++ b/db/queries/song.sql @@ -2,32 +2,32 @@ -- name: CreateSong :one INSERT INTO song (title, album, spotify_id, duration_ms, lyrics_type, lyrics) -VALUES (?, ?, ?, ?, ?, ?) +VALUES ($1, $2, $3, $4, $5, $6) RETURNING *; -- name: CreateSongHistory :one INSERT INTO song_history (song_id) -VALUES (?) +VALUES ($1) RETURNING *; -- name: CreateSongGenre :one INSERT INTO song_genre (genre) -VALUES (?) +VALUES ($1) RETURNING *; -- name: CreateSongArtist :one INSERT INTO song_artist (name, spotify_id, followers, popularity) -VALUES (?, ?, ?, ?) +VALUES ($1, $2, $3, $4) RETURNING *; -- name: CreateSongArtistSong :one INSERT INTO song_artist_song (artist_id, song_id) -VALUES (?, ?) +VALUES ($1, $2) RETURNING *; -- name: CreateSongArtistGenre :one INSERT INTO song_artist_genre (artist_id, genre_id) -VALUES (?, ?) +VALUES ($1, $2) RETURNING *; @@ -36,12 +36,12 @@ RETURNING *; -- name: GetSongBySpotifyID :one SELECT * FROM song -WHERE spotify_id = ?; +WHERE spotify_id = $1; -- name: GetSongArtistBySpotifyID :one SELECT * FROM song_artist -WHERE spotify_id = ?; +WHERE spotify_id = $1; -- name: GetLastSongHistory :one SELECT * @@ -52,12 +52,12 @@ LIMIT 1; -- name: GetSongGenreByName :one SELECT * FROM song_genre -WHERE genre = ?; +WHERE genre = $1; -- name: GetSongArtistByName :one SELECT * FROM song_artist -WHERE name = ?; +WHERE name = $1; -- name: GetLastSongFull :many SELECT s.id, s.title AS song_title, s.spotify_id, s.album, s.duration_ms, s.lyrics_type, s.lyrics, sh.created_at, a.id AS artist_id, a.name AS artist_name, a.spotify_id AS artist_spotify_id, a.followers AS artist_followers, a.popularity AS artist_popularity, g.id AS genre_id, g.genre AS genre, sh.created_at diff --git a/db/queries/tap.sql b/db/queries/tap.sql index 742aa7f..88394e7 100644 --- a/db/queries/tap.sql +++ b/db/queries/tap.sql @@ -7,22 +7,22 @@ FROM tap; -- name: GetTapByID :one SELECT * FROM tap -WHERE id = ?; +WHERE id = $1; -- name: CreateTap :one INSERT INTO tap (order_id, order_created_at, name, category) -VALUES (?, ?, ?, ?) +VALUES ($1, $2, $3, $4) RETURNING *; -- name: UpdateTap :one UPDATE tap -SET order_id = ?, order_created_at = ?, name = ?, category = ? -WHERE id = ? +SET order_id = $1, order_created_at = $2, name = $3, category = $4 +WHERE id = $5 RETURNING *; -- name: DeleteTap :execrows DELETE FROM tap -WHERE id = ?; +WHERE id = $1; -- Other @@ -31,12 +31,12 @@ WHERE id = ?; -- name: GetTapByOrderID :one SELECT * FROM tap -WHERE order_id = ?; +WHERE order_id = $1; -- name: GetTapByCategory :many SELECT * FROM tap -WHERE category = ?; +WHERE category = $1; -- name: GetLastOrderByOrderID :one SELECT * @@ -52,5 +52,5 @@ GROUP BY category; -- name: GetOrderCountByCategorySinceOrderID :many SELECT category, COUNT(*), CAST(MAX(order_created_at) AS INTEGER) AS latest_order_created_at FROM tap -WHERE order_id >= ? +WHERE order_id >= $1 GROUP BY category; diff --git a/docker-compose.yml b/docker-compose.yml new file mode 100644 index 0000000..fd4be99 --- /dev/null +++ b/docker-compose.yml @@ -0,0 +1,14 @@ +services: + db: + image: postgres:16 + environment: + POSTGRES_DB: scc + POSTGRES_USER: postgres + POSTGRES_PASSWORD: postgres + volumes: + - scc_data:/var/lib/postgresql/data + ports: + - "5432:5432" + +volumes: + scc_data: diff --git a/go.mod b/go.mod index 409d5d2..202bb50 100644 --- a/go.mod +++ b/go.mod @@ -4,6 +4,7 @@ go 1.23.1 require ( github.com/NimbleMarkets/ntcharts v0.1.2 + github.com/charmbracelet/bubbles v0.20.0 github.com/charmbracelet/bubbletea v1.1.0 github.com/charmbracelet/lipgloss v1.0.0 github.com/disintegration/imaging v1.6.2 @@ -11,14 +12,20 @@ require ( github.com/gocolly/colly v1.2.0 github.com/gofiber/contrib/fiberzap v1.0.2 github.com/gofiber/fiber/v2 v2.52.5 + github.com/jackc/pgx/v5 v5.7.1 github.com/joho/godotenv v1.5.1 github.com/lucasb-eyer/go-colorful v1.2.0 - github.com/mattn/go-sqlite3 v1.14.24 github.com/spf13/viper v1.19.0 go.uber.org/zap v1.27.0 ) +require ( + github.com/jackc/pgpassfile v1.0.0 // indirect + github.com/jackc/pgservicefile v0.0.0-20240606120523-5a60cdf6a761 // indirect + github.com/jackc/puddle/v2 v2.2.2 // indirect +) + require ( github.com/PuerkitoBio/goquery v1.10.0 // indirect github.com/andybalholm/brotli v1.0.5 // indirect @@ -27,11 +34,9 @@ require ( github.com/antchfx/xmlquery v1.4.2 // indirect github.com/antchfx/xpath v1.3.2 // indirect github.com/aymanbagabas/go-osc52/v2 v2.0.1 // indirect - github.com/charmbracelet/bubbles v0.20.0 // indirect github.com/charmbracelet/harmonica v0.2.0 // indirect github.com/charmbracelet/x/ansi v0.4.2 // indirect github.com/charmbracelet/x/term v0.2.0 // indirect - github.com/containerd/console v1.0.4 // indirect github.com/erikgeiser/coninput v0.0.0-20211004153227-1c3628e74d0f // indirect github.com/fsnotify/fsnotify v1.7.0 // indirect github.com/gabriel-vasile/mimetype v1.4.3 // indirect @@ -54,7 +59,6 @@ require ( github.com/mitchellh/mapstructure v1.5.0 // indirect github.com/muesli/ansi v0.0.0-20230316100256-276c6243b2f6 // indirect github.com/muesli/cancelreader v0.2.2 // indirect - github.com/muesli/reflow v0.3.0 // indirect github.com/muesli/termenv v0.15.2 // indirect github.com/pelletier/go-toml/v2 v2.2.2 // indirect github.com/rivo/uniseg v0.4.7 // indirect @@ -77,7 +81,6 @@ require ( golang.org/x/net v0.29.0 // indirect golang.org/x/sync v0.8.0 // indirect golang.org/x/sys v0.25.0 // indirect - golang.org/x/term v0.24.0 // indirect golang.org/x/text v0.18.0 // indirect google.golang.org/appengine v1.6.8 // indirect google.golang.org/protobuf v1.33.0 // indirect diff --git a/go.sum b/go.sum index b07f473..f5151f6 100644 --- a/go.sum +++ b/go.sum @@ -14,14 +14,8 @@ github.com/antchfx/xpath v1.3.2 h1:LNjzlsSjinu3bQpw9hWMY9ocB80oLOWuQqFvO6xt51U= github.com/antchfx/xpath v1.3.2/go.mod h1:i54GszH55fYfBmoZXapTHN8T8tkcHfRgLyVwwqzXNcs= github.com/aymanbagabas/go-osc52/v2 v2.0.1 h1:HwpRHbFMcZLEVr42D4p7XBqjyuxQH5SMiErDT4WkJ2k= github.com/aymanbagabas/go-osc52/v2 v2.0.1/go.mod h1:uYgXzlJ7ZpABp8OJ+exZzJJhRNQ2ASbcXHWsFqH8hp8= -github.com/aymanbagabas/go-udiff v0.2.0 h1:TK0fH4MteXUDspT88n8CKzvK0X9O2xu9yQjWpi6yML8= -github.com/aymanbagabas/go-udiff v0.2.0/go.mod h1:RE4Ex0qsGkTAJoQdQQCA0uG+nAzJO/pI/QwceO5fgrA= -github.com/charmbracelet/bubbles v0.18.0 h1:PYv1A036luoBGroX6VWjQIE9Syf2Wby2oOl/39KLfy0= -github.com/charmbracelet/bubbles v0.18.0/go.mod h1:08qhZhtIwzgrtBjAcJnij1t1H0ZRjwHyGsy6AL11PSw= github.com/charmbracelet/bubbles v0.20.0 h1:jSZu6qD8cRQ6k9OMfR1WlM+ruM8fkPWkHvQWD9LIutE= github.com/charmbracelet/bubbles v0.20.0/go.mod h1:39slydyswPy+uVOHZ5x/GjwVAFkCsV8IIVy+4MhzwwU= -github.com/charmbracelet/bubbletea v0.25.0 h1:bAfwk7jRz7FKFl9RzlIULPkStffg5k6pNt5dywy4TcM= -github.com/charmbracelet/bubbletea v0.25.0/go.mod h1:EN3QDR1T5ZdWmdfDzYcqOCAps45+QIJbLOBxmVNWNNg= github.com/charmbracelet/bubbletea v1.1.0 h1:FjAl9eAL3HBCHenhz/ZPjkKdScmaS5SK69JAK2YJK9c= github.com/charmbracelet/bubbletea v1.1.0/go.mod h1:9Ogk0HrdbHolIKHdjfFpyXJmiCzGwy+FesYkZr7hYU4= github.com/charmbracelet/harmonica v0.2.0 h1:8NxJWRWg/bzKqqEaaeFNipOu77YR5t8aSwG4pgaUBiQ= @@ -30,13 +24,8 @@ github.com/charmbracelet/lipgloss v1.0.0 h1:O7VkGDvqEdGi93X+DeqsQ7PKHDgtQfF8j8/O github.com/charmbracelet/lipgloss v1.0.0/go.mod h1:U5fy9Z+C38obMs+T+tJqst9VGzlOYGj4ri9reL3qUlo= github.com/charmbracelet/x/ansi v0.4.2 h1:0JM6Aj/g/KC154/gOP4vfxun0ff6itogDYk41kof+qk= github.com/charmbracelet/x/ansi v0.4.2/go.mod h1:dk73KoMTT5AX5BsX0KrqhsTqAnhZZoCBjs7dGWp4Ktw= -github.com/charmbracelet/x/exp/golden v0.0.0-20240806155701-69247e0abc2a h1:G99klV19u0QnhiizODirwVksQB91TJKV/UaTnACcG30= -github.com/charmbracelet/x/exp/golden v0.0.0-20240806155701-69247e0abc2a/go.mod h1:wDlXFlCrmJ8J+swcL/MnGUuYnqgQdW9rhSD61oNMb6U= -github.com/charmbracelet/x/exp/golden v0.0.0-20240815200342-61de596daa2b h1:MnAMdlwSltxJyULnrYbkZpp4k58Co7Tah3ciKhSNo0Q= github.com/charmbracelet/x/term v0.2.0 h1:cNB9Ot9q8I711MyZ7myUR5HFWL/lc3OpU8jZ4hwm0x0= github.com/charmbracelet/x/term v0.2.0/go.mod h1:GVxgxAbjUrmpvIINHIQnJJKpMlHiZ4cktEQCN6GWyF0= -github.com/containerd/console v1.0.4 h1:F2g4+oChYvBTsASRTz8NP6iIAi97J3TtSAsLbIFn4ro= -github.com/containerd/console v1.0.4/go.mod h1:YynlIjWYF8myEu6sdkwKIvGQq+cOckRm6So2avqoYAk= github.com/davecgh/go-spew v1.1.0/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38= github.com/davecgh/go-spew v1.1.1/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38= github.com/davecgh/go-spew v1.1.2-0.20180830191138-d8f796af33cc h1:U9qPSI2PIWSS1VwoXQT9A3Wy9MM3WgvqSxFWenqJduM= @@ -80,6 +69,14 @@ github.com/google/uuid v1.5.0 h1:1p67kYwdtXjb0gL0BPiP1Av9wiZPo5A8z2cWkTZ+eyU= github.com/google/uuid v1.5.0/go.mod h1:TIyPZe4MgqvfeYDBFedMoGGpEw/LqOeaOT+nhxU+yHo= github.com/hashicorp/hcl v1.0.0 h1:0Anlzjpi4vEasTeNFn2mLJgTSwt0+6sfsiTG8qcWGx4= github.com/hashicorp/hcl v1.0.0/go.mod h1:E5yfLk+7swimpb2L/Alb/PJmXilQ/rhwaUYs4T20WEQ= +github.com/jackc/pgpassfile v1.0.0 h1:/6Hmqy13Ss2zCq62VdNG8tM1wchn8zjSGOBJ6icpsIM= +github.com/jackc/pgpassfile v1.0.0/go.mod h1:CEx0iS5ambNFdcRtxPj5JhEz+xB6uRky5eyVu/W2HEg= +github.com/jackc/pgservicefile v0.0.0-20240606120523-5a60cdf6a761 h1:iCEnooe7UlwOQYpKFhBabPMi4aNAfoODPEFNiAnClxo= +github.com/jackc/pgservicefile v0.0.0-20240606120523-5a60cdf6a761/go.mod h1:5TJZWKEWniPve33vlWYSoGYefn3gLQRzjfDlhSJ9ZKM= +github.com/jackc/pgx/v5 v5.7.1 h1:x7SYsPBYDkHDksogeSmZZ5xzThcTgRz++I5E+ePFUcs= +github.com/jackc/pgx/v5 v5.7.1/go.mod h1:e7O26IywZZ+naJtWWos6i6fvWK+29etgITqrqHLfoZA= +github.com/jackc/puddle/v2 v2.2.2 h1:PR8nw+E/1w0GLuRFSmiioY6UooMp6KJv0/61nB7icHo= +github.com/jackc/puddle/v2 v2.2.2/go.mod h1:vriiEXHvEE654aYKXXjOvZM39qJ0q+azkZFrfEOc3H4= github.com/joho/godotenv v1.5.1 h1:7eLL/+HRGLY0ldzfGMeQkb7vMd0as4CfYvUVzLqw0N0= github.com/joho/godotenv v1.5.1/go.mod h1:f4LDr5Voq0i2e/R5DDNOoa2zzDfwtkZa6DnEwAbqwq4= github.com/kennygrant/sanitize v1.2.4 h1:gN25/otpP5vAsO2djbMhF/LQX6R7+O1TB4yv8NzpJ3o= @@ -105,21 +102,14 @@ github.com/mattn/go-isatty v0.0.20 h1:xfD0iDuEKnDkl03q4limB+vH+GxLEtL/jb4xVJSWWE github.com/mattn/go-isatty v0.0.20/go.mod h1:W+V8PltTTMOvKvAeJH7IuucS94S2C6jfK/D7dTCTo3Y= github.com/mattn/go-localereader v0.0.1 h1:ygSAOl7ZXTx4RdPYinUpg6W99U8jWvWi9Ye2JC/oIi4= github.com/mattn/go-localereader v0.0.1/go.mod h1:8fBrzywKY7BI3czFoHkuzRoWE9C+EiG4R1k4Cjx5p88= -github.com/mattn/go-runewidth v0.0.12/go.mod h1:RAqKPSqVFrSLVXbA8x7dzmKdmGzieGRCM46jaSJTDAk= -github.com/mattn/go-runewidth v0.0.15 h1:UNAjwbU9l54TA3KzvqLGxwWjHmMgBUVhBiTjelZgg3U= -github.com/mattn/go-runewidth v0.0.15/go.mod h1:Jdepj2loyihRzMpdS35Xk/zdY8IAYHsh153qUoGf23w= github.com/mattn/go-runewidth v0.0.16 h1:E5ScNMtiwvlvB5paMFdw9p4kSQzbXFikJ5SQO6TULQc= github.com/mattn/go-runewidth v0.0.16/go.mod h1:Jdepj2loyihRzMpdS35Xk/zdY8IAYHsh153qUoGf23w= -github.com/mattn/go-sqlite3 v1.14.24 h1:tpSp2G2KyMnnQu99ngJ47EIkWVmliIizyZBfPrBWDRM= -github.com/mattn/go-sqlite3 v1.14.24/go.mod h1:Uh1q+B4BYcTPb+yiD3kU8Ct7aC0hY9fxUwlHK0RXw+Y= github.com/mitchellh/mapstructure v1.5.0 h1:jeMsZIYE/09sWLaz43PL7Gy6RuMjD2eJVyuac5Z2hdY= github.com/mitchellh/mapstructure v1.5.0/go.mod h1:bFUtVrKA4DC2yAKiSyO/QUcy7e+RRV2QTWOzhPopBRo= github.com/muesli/ansi v0.0.0-20230316100256-276c6243b2f6 h1:ZK8zHtRHOkbHy6Mmr5D264iyp3TiX5OmNcI5cIARiQI= github.com/muesli/ansi v0.0.0-20230316100256-276c6243b2f6/go.mod h1:CJlz5H+gyd6CUWT45Oy4q24RdLyn7Md9Vj2/ldJBSIo= github.com/muesli/cancelreader v0.2.2 h1:3I4Kt4BQjOR54NavqnDogx/MIoWBFa0StPA8ELUXHmA= github.com/muesli/cancelreader v0.2.2/go.mod h1:3XuTXfFS2VjM+HTLZY9Ak0l6eUKfijIfMUZ4EgX0QYo= -github.com/muesli/reflow v0.3.0 h1:IFsN6K9NfGtjeggFP+68I4chLZV2yIKsXJFNZ+eWh6s= -github.com/muesli/reflow v0.3.0/go.mod h1:pbwTDkVPibjO2kyvBQRBxTWEEGDGq0FlB1BIKtnHY/8= github.com/muesli/termenv v0.15.2 h1:GohcuySI0QmI3wN8Ok9PtKGkgkFIk7y6Vpb5PvrY+Wo= github.com/muesli/termenv v0.15.2/go.mod h1:Epx+iuz8sNs7mNKhxzH4fWXGNpZwUaJKRS1noLXviQ8= github.com/pelletier/go-toml/v2 v2.2.2 h1:aYUidT7k73Pcl9nb2gScu7NSrKCSHIDE89b3+6Wq+LM= @@ -127,7 +117,6 @@ github.com/pelletier/go-toml/v2 v2.2.2/go.mod h1:1t835xjRzz80PqgE6HHgN2JOsmgYu/h github.com/pmezard/go-difflib v1.0.0/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4= github.com/pmezard/go-difflib v1.0.1-0.20181226105442-5d4384ee4fb2 h1:Jamvg5psRIccs7FGNTlIRMkT8wgtp5eCXdBlqhYGL6U= github.com/pmezard/go-difflib v1.0.1-0.20181226105442-5d4384ee4fb2/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4= -github.com/rivo/uniseg v0.1.0/go.mod h1:J6wj4VEh+S6ZtnVlnTBMWIodfgj8LQOQFoIToxlJtxc= github.com/rivo/uniseg v0.2.0/go.mod h1:J6wj4VEh+S6ZtnVlnTBMWIodfgj8LQOQFoIToxlJtxc= github.com/rivo/uniseg v0.4.7 h1:WUdvkW8uEhrYfLC4ZzdpI2ztxP1I582+49Oc5Mq64VQ= github.com/rivo/uniseg v0.4.7/go.mod h1:FN3SvrM+Zdj16jyLfmOkMNblXMcoc8DfTHruCPUcx88= @@ -154,6 +143,7 @@ github.com/stretchr/objx v0.4.0/go.mod h1:YvHI0jy2hoMjB+UWwv71VJQ9isScKT/TqJzVSS github.com/stretchr/objx v0.5.0/go.mod h1:Yh+to48EsGEfYuaHDzXPcE3xhTkx73EhmCGUpEOglKo= github.com/stretchr/objx v0.5.2/go.mod h1:FRsXN1f5AsAjCGJKqEizvkpNtU+EGNCLh3NxZ/8L+MA= github.com/stretchr/testify v1.3.0/go.mod h1:M5WIy9Dh21IEIfnGCwXGc5bZfKNJtfHm1UVUgZn+9EI= +github.com/stretchr/testify v1.7.0/go.mod h1:6Fq8oRcR53rry900zMqJjRRixrwX3KX962/h/Wwjteg= github.com/stretchr/testify v1.7.1/go.mod h1:6Fq8oRcR53rry900zMqJjRRixrwX3KX962/h/Wwjteg= github.com/stretchr/testify v1.8.0/go.mod h1:yNjHg4UonilssWZ8iaSj1OCr/vHnekPRkoO+kdMU+MU= github.com/stretchr/testify v1.8.4/go.mod h1:sz/lmYIOXD/1dqDmKjjqLyZ2RngseejIcXlSw2iwfAo= @@ -206,7 +196,6 @@ golang.org/x/sys v0.0.0-20210809222454-d867a43fc93e/go.mod h1:oPkhp1MJrh7nUepCBc golang.org/x/sys v0.0.0-20220520151302-bc2c85ada10a/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= golang.org/x/sys v0.0.0-20220722155257-8c9f86f7a55f/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= golang.org/x/sys v0.0.0-20220811171246-fbc7d0a398ab/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= -golang.org/x/sys v0.1.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= golang.org/x/sys v0.5.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= golang.org/x/sys v0.6.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= golang.org/x/sys v0.7.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= @@ -216,8 +205,6 @@ golang.org/x/term v0.0.0-20201126162022-7de9c90e9dd1/go.mod h1:bj7SfCRtBDWHUb9sn golang.org/x/term v0.0.0-20210927222741-03fcf44c2211/go.mod h1:jbD1KX2456YbFQfuXm/mYQcufACuNUgVhRMnK/tPxf8= golang.org/x/term v0.5.0/go.mod h1:jMB1sMXY+tzblOD4FWmEbocvup2/aLOaQEp7JmGp78k= golang.org/x/term v0.7.0/go.mod h1:P32HKFT3hSsZrRxla30E9HqToFYAQPCMs/zFMBUFqPY= -golang.org/x/term v0.24.0 h1:Mh5cbb+Zk2hqqXNO7S1iTjEphVL+jb8ZWaqh/g+JWkM= -golang.org/x/term v0.24.0/go.mod h1:lOBK/LVxemqiMij05LGJ0tzNr8xlmwBRJ81PX6wVLH8= golang.org/x/text v0.3.0/go.mod h1:NqM8EUOU14njkJ3fqMW+pc6Ldnwhi/IjpwHt7yyuwOQ= golang.org/x/text v0.3.3/go.mod h1:5Zoc/QRtKVWzQhOtBMvqHzDpF6irO9z98xDceosuGiQ= golang.org/x/text v0.3.7/go.mod h1:u+2+/6zg+i71rQMx5EYifcz6MCKuco9NR6JIITiCfzQ= @@ -239,8 +226,8 @@ google.golang.org/protobuf v1.26.0/go.mod h1:9q0QmTI4eRPtz6boOQmLYwt+qCgq0jsYwAQ google.golang.org/protobuf v1.33.0 h1:uNO2rsAINq/JlFpSdYEKIZ0uKD/R9cpdv0T+yoGwGmI= google.golang.org/protobuf v1.33.0/go.mod h1:c6P6GXX6sHbq/GpV6MGZEdwhWPcYBgnhAHhKbcUYpos= gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0= -gopkg.in/check.v1 v1.0.0-20190902080502-41f04d3bba15 h1:YR8cESwS4TdDjEe65xsg0ogRM/Nc3DYOhEAlW+xobZo= -gopkg.in/check.v1 v1.0.0-20190902080502-41f04d3bba15/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0= +gopkg.in/check.v1 v1.0.0-20201130134442-10cb98267c6c h1:Hei/4ADfdWqJk1ZMxUNpqntNwaWcugrBjAiHlqqRiVk= +gopkg.in/check.v1 v1.0.0-20201130134442-10cb98267c6c/go.mod h1:JHkPIbrfpd72SG/EVd6muEfDQjcINNoR0C8j2r3qZ4Q= gopkg.in/ini.v1 v1.67.0 h1:Dgnx+6+nfE+IfzjUEISNeydPJh9AXNNsWbGP9KzCsOA= gopkg.in/ini.v1 v1.67.0/go.mod h1:pNLf8WUiyNEtQjuu5G5vTm06TEv9tsIgeAvK8hOrP4k= gopkg.in/yaml.v3 v3.0.0-20200313102051-9f266ea9e77c/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM= diff --git a/internal/cmd/tui.go b/internal/cmd/tui.go index 98cfb46..ea097d5 100644 --- a/internal/cmd/tui.go +++ b/internal/cmd/tui.go @@ -9,11 +9,11 @@ import ( tea "github.com/charmbracelet/bubbletea" "github.com/zeusWPI/scc/internal/pkg/db" "github.com/zeusWPI/scc/pkg/util" - tui "github.com/zeusWPI/scc/ui" - "github.com/zeusWPI/scc/ui/screen" - "github.com/zeusWPI/scc/ui/screen/cammie" - songScreen "github.com/zeusWPI/scc/ui/screen/song" - "github.com/zeusWPI/scc/ui/view" + "github.com/zeusWPI/scc/tui" + "github.com/zeusWPI/scc/tui/screen" + "github.com/zeusWPI/scc/tui/screen/cammie" + songScreen "github.com/zeusWPI/scc/tui/screen/song" + "github.com/zeusWPI/scc/tui/view" "go.uber.org/zap" ) diff --git a/internal/pkg/db/db.go b/internal/pkg/db/db.go index 6de1d04..35b2223 100644 --- a/internal/pkg/db/db.go +++ b/internal/pkg/db/db.go @@ -2,30 +2,42 @@ package db import ( - "database/sql" + "context" - _ "github.com/mattn/go-sqlite3" // SQLite driver + "github.com/jackc/pgx/v5/pgxpool" "github.com/zeusWPI/scc/internal/pkg/db/sqlc" + "github.com/zeusWPI/scc/pkg/config" ) // DB represents a database connection type DB struct { - DB *sql.DB + Pool *pgxpool.Pool Queries *sqlc.Queries } // New creates a new database connection func New() (*DB, error) { - db, err := sql.Open("sqlite3", "./sqlite.db") + pgConfig, err := pgxpool.ParseConfig("") if err != nil { return nil, err } - if err := db.Ping(); err != nil { + pgConfig.ConnConfig.Host = config.GetDefaultString("db.host", "localhost") + pgConfig.ConnConfig.Port = config.GetDefaultUint16("db.port", 5432) + pgConfig.ConnConfig.Database = config.GetDefaultString("db.database", "scc") + pgConfig.ConnConfig.User = config.GetDefaultString("db.user", "postgres") + pgConfig.ConnConfig.Password = config.GetDefaultString("db.password", "postgres") + + pool, err := pgxpool.NewWithConfig(context.Background(), pgConfig) + if err != nil { + return nil, err + } + + if err := pool.Ping(context.TODO()); err != nil { return nil, err } - queries := sqlc.New(db) + queries := sqlc.New(pool) - return &DB{DB: db, Queries: queries}, nil + return &DB{Pool: pool, Queries: queries}, nil } diff --git a/internal/pkg/db/dto/event.go b/internal/pkg/db/dto/event.go index 59226c9..5fb2614 100644 --- a/internal/pkg/db/dto/event.go +++ b/internal/pkg/db/dto/event.go @@ -3,12 +3,13 @@ package dto import ( "time" + "github.com/jackc/pgx/v5/pgtype" "github.com/zeusWPI/scc/internal/pkg/db/sqlc" ) // Event represents the DTO object for event type Event struct { - ID int64 + ID int32 Name string Date time.Time AcademicYear string @@ -21,7 +22,7 @@ func EventDTO(e sqlc.Event) *Event { return &Event{ ID: e.ID, Name: e.Name, - Date: e.Date, + Date: e.Date.Time, AcademicYear: e.AcademicYear, Location: e.Location, Poster: e.Poster, @@ -37,7 +38,7 @@ func (e *Event) Equal(e2 Event) bool { func (e *Event) CreateParams() sqlc.CreateEventParams { return sqlc.CreateEventParams{ Name: e.Name, - Date: e.Date, + Date: pgtype.Timestamptz{Time: e.Date, Valid: true}, AcademicYear: e.AcademicYear, Location: e.Location, Poster: e.Poster, diff --git a/internal/pkg/db/dto/gamification.go b/internal/pkg/db/dto/gamification.go index 3ee8548..bb2181e 100644 --- a/internal/pkg/db/dto/gamification.go +++ b/internal/pkg/db/dto/gamification.go @@ -8,9 +8,9 @@ import ( // Gamification represents the DTO object for gamification type Gamification struct { - ID int64 `json:"id"` + ID int32 `json:"id"` Name string `json:"github_name"` - Score int64 `json:"score"` + Score int32 `json:"score"` Avatar []byte `json:"avatar"` } diff --git a/internal/pkg/db/dto/message.go b/internal/pkg/db/dto/message.go index fa20de9..75672a8 100644 --- a/internal/pkg/db/dto/message.go +++ b/internal/pkg/db/dto/message.go @@ -8,7 +8,7 @@ import ( // Message is the DTO for the message type Message struct { - ID int64 `json:"id"` + ID int32 `json:"id"` Name string `json:"name" validate:"required"` IP string `json:"ip" validate:"required"` Message string `json:"message" validate:"required"` @@ -22,7 +22,7 @@ func MessageDTO(message sqlc.Message) *Message { Name: message.Name, IP: message.Ip, Message: message.Message, - CreatedAt: message.CreatedAt, + CreatedAt: message.CreatedAt.Time, } } diff --git a/internal/pkg/db/dto/scan.go b/internal/pkg/db/dto/scan.go index 63628fc..ea0183c 100644 --- a/internal/pkg/db/dto/scan.go +++ b/internal/pkg/db/dto/scan.go @@ -3,12 +3,13 @@ package dto import ( "time" + "github.com/jackc/pgx/v5/pgtype" "github.com/zeusWPI/scc/internal/pkg/db/sqlc" ) // Scan is the DTO for the scan type Scan struct { - ID int64 `json:"id"` + ID int32 `json:"id"` ScanTime time.Time `json:"scan_time" validate:"required"` } @@ -16,19 +17,19 @@ type Scan struct { func ScanDTO(scan sqlc.Scan) *Scan { return &Scan{ ID: scan.ID, - ScanTime: scan.ScanTime, + ScanTime: scan.ScanTime.Time, } } // CreateParams converts a Scan to sqlc.CreateScanParams -func (s *Scan) CreateParams() time.Time { - return s.ScanTime +func (s *Scan) CreateParams() pgtype.Timestamptz { + return pgtype.Timestamptz{Time: s.ScanTime} } // UpdateParams converts a Scan to sqlc.UpdateScanParams func (s *Scan) UpdateParams() sqlc.UpdateScanParams { return sqlc.UpdateScanParams{ ID: s.ID, - ScanTime: s.ScanTime, + ScanTime: pgtype.Timestamptz{Time: s.ScanTime, Valid: true}, } } diff --git a/internal/pkg/db/dto/season.go b/internal/pkg/db/dto/season.go index 9dbab42..6b33e17 100644 --- a/internal/pkg/db/dto/season.go +++ b/internal/pkg/db/dto/season.go @@ -3,12 +3,13 @@ package dto import ( "time" + "github.com/jackc/pgx/v5/pgtype" "github.com/zeusWPI/scc/internal/pkg/db/sqlc" ) // Season is the DTO for the season type Season struct { - ID int64 `json:"id"` + ID int32 `json:"id"` Name string `json:"name" validate:"required"` Start time.Time `json:"start" validate:"required"` End time.Time `json:"end" validate:"required"` @@ -20,8 +21,8 @@ func SeasonDTO(season sqlc.Season) *Season { return &Season{ ID: season.ID, Name: season.Name, - Start: season.Start, - End: season.End, + Start: season.Start.Time, + End: season.End.Time, Current: season.Current, } } @@ -40,8 +41,8 @@ func SeasonCmp(s1, s2 *Season) int { func (s *Season) CreateParams() sqlc.CreateSeasonParams { return sqlc.CreateSeasonParams{ Name: s.Name, - Start: s.Start, - End: s.End, + Start: pgtype.Timestamptz{Time: s.Start, Valid: true}, + End: pgtype.Timestamptz{Time: s.End, Valid: true}, Current: s.Current, } } @@ -51,8 +52,8 @@ func (s *Season) UpdateParams() sqlc.UpdateSeasonParams { return sqlc.UpdateSeasonParams{ ID: s.ID, Name: s.Name, - Start: s.Start, - End: s.End, + Start: pgtype.Timestamptz{Time: s.Start, Valid: true}, + End: pgtype.Timestamptz{Time: s.End, Valid: true}, Current: s.Current, } } diff --git a/internal/pkg/db/dto/song.go b/internal/pkg/db/dto/song.go index 4839db0..b678297 100644 --- a/internal/pkg/db/dto/song.go +++ b/internal/pkg/db/dto/song.go @@ -1,19 +1,19 @@ package dto import ( - "database/sql" "time" + "github.com/jackc/pgx/v5/pgtype" "github.com/zeusWPI/scc/internal/pkg/db/sqlc" ) // Song is the DTO for a song type Song struct { - ID int64 `json:"id"` + ID int32 `json:"id"` Title string `json:"title"` Album string `json:"album"` SpotifyID string `json:"spotify_id" validate:"required"` - DurationMS int64 `json:"duration_ms"` + DurationMS int32 `json:"duration_ms"` LyricsType string `json:"lyrics_type"` // Either 'synced' or 'plain' Lyrics string `json:"lyrics"` CreatedAt time.Time `json:"created_at"` @@ -22,17 +22,17 @@ type Song struct { // SongArtist is the DTO for a song artist type SongArtist struct { - ID int64 `json:"id"` + ID int32 `json:"id"` Name string `json:"name"` SpotifyID string `json:"spotify_id"` - Followers int64 `json:"followers"` - Popularity int64 `json:"popularity"` + Followers int32 `json:"followers"` + Popularity int32 `json:"popularity"` Genres []SongGenre `json:"genres"` } // SongGenre is the DTO for a song genre type SongGenre struct { - ID int64 `json:"id"` + ID int32 `json:"id"` Genre string `json:"genre"` } @@ -73,30 +73,30 @@ func SongDTOHistory(songs []sqlc.GetLastSongFullRow) *Song { lyrics = songs[0].Lyrics.String } - artistsMap := make(map[int64]SongArtist) + artistsMap := make(map[int32]SongArtist) for _, song := range songs { if !song.ArtistID.Valid { continue } // Get artist - artist, ok := artistsMap[song.ArtistID.Int64] + artist, ok := artistsMap[song.ArtistID.Int32] if !ok { // Artist doesn't exist yet, add him artist = SongArtist{ - ID: song.ArtistID.Int64, + ID: song.ArtistID.Int32, Name: song.ArtistName.String, SpotifyID: song.ArtistSpotifyID.String, - Followers: song.ArtistFollowers.Int64, - Popularity: song.ArtistPopularity.Int64, + Followers: song.ArtistFollowers.Int32, + Popularity: song.ArtistPopularity.Int32, Genres: make([]SongGenre, 0), } - artistsMap[song.ArtistID.Int64] = artist + artistsMap[song.ArtistID.Int32] = artist } // Add genre artist.Genres = append(artist.Genres, SongGenre{ - ID: song.GenreID.Int64, + ID: song.GenreID.Int32, Genre: song.Genre.String, }) } @@ -114,28 +114,20 @@ func SongDTOHistory(songs []sqlc.GetLastSongFullRow) *Song { DurationMS: songs[0].DurationMs, LyricsType: lyricsType, Lyrics: lyrics, - CreatedAt: songs[0].CreatedAt, + CreatedAt: songs[0].CreatedAt.Time, Artists: artists, } } // CreateSongParams converts a Song DTO to a sqlc CreateSongParams object func (s *Song) CreateSongParams() *sqlc.CreateSongParams { - lyricsType := sql.NullString{String: s.LyricsType, Valid: false} - if s.LyricsType != "" { - lyricsType.Valid = true - } - lyrics := sql.NullString{String: s.Lyrics, Valid: false} - if s.Lyrics != "" { - lyrics.Valid = true - } return &sqlc.CreateSongParams{ Title: s.Title, Album: s.Album, SpotifyID: s.SpotifyID, DurationMs: s.DurationMS, - LyricsType: lyricsType, - Lyrics: lyrics, + LyricsType: pgtype.Text{String: s.LyricsType, Valid: true}, + Lyrics: pgtype.Text{String: s.Lyrics, Valid: true}, } } diff --git a/internal/pkg/db/sqlc/db.go b/internal/pkg/db/sqlc/db.go index 2248616..b931bc5 100644 --- a/internal/pkg/db/sqlc/db.go +++ b/internal/pkg/db/sqlc/db.go @@ -6,14 +6,15 @@ package sqlc import ( "context" - "database/sql" + + "github.com/jackc/pgx/v5" + "github.com/jackc/pgx/v5/pgconn" ) type DBTX interface { - ExecContext(context.Context, string, ...interface{}) (sql.Result, error) - PrepareContext(context.Context, string) (*sql.Stmt, error) - QueryContext(context.Context, string, ...interface{}) (*sql.Rows, error) - QueryRowContext(context.Context, string, ...interface{}) *sql.Row + Exec(context.Context, string, ...interface{}) (pgconn.CommandTag, error) + Query(context.Context, string, ...interface{}) (pgx.Rows, error) + QueryRow(context.Context, string, ...interface{}) pgx.Row } func New(db DBTX) *Queries { @@ -24,7 +25,7 @@ type Queries struct { db DBTX } -func (q *Queries) WithTx(tx *sql.Tx) *Queries { +func (q *Queries) WithTx(tx pgx.Tx) *Queries { return &Queries{ db: tx, } diff --git a/internal/pkg/db/sqlc/event.sql.go b/internal/pkg/db/sqlc/event.sql.go index a6983e4..02a56b8 100644 --- a/internal/pkg/db/sqlc/event.sql.go +++ b/internal/pkg/db/sqlc/event.sql.go @@ -7,25 +7,26 @@ package sqlc import ( "context" - "time" + + "github.com/jackc/pgx/v5/pgtype" ) const createEvent = `-- name: CreateEvent :one INSERT INTO event (name, date, academic_year, location, poster) -VALUES (?, ?, ?, ?, ?) +VALUES ($1, $2, $3, $4, $5) RETURNING id, name, date, academic_year, location, poster ` type CreateEventParams struct { Name string - Date time.Time + Date pgtype.Timestamptz AcademicYear string Location string Poster []byte } func (q *Queries) CreateEvent(ctx context.Context, arg CreateEventParams) (Event, error) { - row := q.db.QueryRowContext(ctx, createEvent, + row := q.db.QueryRow(ctx, createEvent, arg.Name, arg.Date, arg.AcademicYear, @@ -46,21 +47,21 @@ func (q *Queries) CreateEvent(ctx context.Context, arg CreateEventParams) (Event const deleteEvent = `-- name: DeleteEvent :exec DELETE FROM event -WHERE id = ? +WHERE id = $1 ` -func (q *Queries) DeleteEvent(ctx context.Context, id int64) error { - _, err := q.db.ExecContext(ctx, deleteEvent, id) +func (q *Queries) DeleteEvent(ctx context.Context, id int32) error { + _, err := q.db.Exec(ctx, deleteEvent, id) return err } const deleteEventByAcademicYear = `-- name: DeleteEventByAcademicYear :exec DELETE FROM event -WHERE academic_year = ? +WHERE academic_year = $1 ` func (q *Queries) DeleteEventByAcademicYear(ctx context.Context, academicYear string) error { - _, err := q.db.ExecContext(ctx, deleteEventByAcademicYear, academicYear) + _, err := q.db.Exec(ctx, deleteEventByAcademicYear, academicYear) return err } @@ -73,7 +74,7 @@ FROM event // CRUD func (q *Queries) GetAllEvents(ctx context.Context) ([]Event, error) { - rows, err := q.db.QueryContext(ctx, getAllEvents) + rows, err := q.db.Query(ctx, getAllEvents) if err != nil { return nil, err } @@ -93,9 +94,6 @@ func (q *Queries) GetAllEvents(ctx context.Context) ([]Event, error) { } items = append(items, i) } - if err := rows.Close(); err != nil { - return nil, err - } if err := rows.Err(); err != nil { return nil, err } @@ -107,12 +105,12 @@ const getEventByAcademicYear = `-- name: GetEventByAcademicYear :many SELECT id, name, date, academic_year, location, poster FROM event -WHERE academic_year = ? +WHERE academic_year = $1 ` // Other func (q *Queries) GetEventByAcademicYear(ctx context.Context, academicYear string) ([]Event, error) { - rows, err := q.db.QueryContext(ctx, getEventByAcademicYear, academicYear) + rows, err := q.db.Query(ctx, getEventByAcademicYear, academicYear) if err != nil { return nil, err } @@ -132,9 +130,6 @@ func (q *Queries) GetEventByAcademicYear(ctx context.Context, academicYear strin } items = append(items, i) } - if err := rows.Close(); err != nil { - return nil, err - } if err := rows.Err(); err != nil { return nil, err } @@ -152,7 +147,7 @@ ORDER BY date ASC ` func (q *Queries) GetEventsCurrentAcademicYear(ctx context.Context) ([]Event, error) { - rows, err := q.db.QueryContext(ctx, getEventsCurrentAcademicYear) + rows, err := q.db.Query(ctx, getEventsCurrentAcademicYear) if err != nil { return nil, err } @@ -172,9 +167,6 @@ func (q *Queries) GetEventsCurrentAcademicYear(ctx context.Context) ([]Event, er } items = append(items, i) } - if err := rows.Close(); err != nil { - return nil, err - } if err := rows.Err(); err != nil { return nil, err } diff --git a/internal/pkg/db/sqlc/gamification.sql.go b/internal/pkg/db/sqlc/gamification.sql.go index 87a8735..50d75df 100644 --- a/internal/pkg/db/sqlc/gamification.sql.go +++ b/internal/pkg/db/sqlc/gamification.sql.go @@ -11,18 +11,18 @@ import ( const createGamification = `-- name: CreateGamification :one INSERT INTO gamification (name, score, avatar) -VALUES (?, ?, ?) +VALUES ($1, $2, $3) RETURNING id, name, score, avatar ` type CreateGamificationParams struct { Name string - Score int64 + Score int32 Avatar []byte } func (q *Queries) CreateGamification(ctx context.Context, arg CreateGamificationParams) (Gamification, error) { - row := q.db.QueryRowContext(ctx, createGamification, arg.Name, arg.Score, arg.Avatar) + row := q.db.QueryRow(ctx, createGamification, arg.Name, arg.Score, arg.Avatar) var i Gamification err := row.Scan( &i.ID, @@ -35,15 +35,15 @@ func (q *Queries) CreateGamification(ctx context.Context, arg CreateGamification const deleteGamification = `-- name: DeleteGamification :execrows DELETE FROM gamification -WHERE id = ? +WHERE id = $1 ` -func (q *Queries) DeleteGamification(ctx context.Context, id int64) (int64, error) { - result, err := q.db.ExecContext(ctx, deleteGamification, id) +func (q *Queries) DeleteGamification(ctx context.Context, id int32) (int64, error) { + result, err := q.db.Exec(ctx, deleteGamification, id) if err != nil { return 0, err } - return result.RowsAffected() + return result.RowsAffected(), nil } const deleteGamificationAll = `-- name: DeleteGamificationAll :execrows @@ -51,11 +51,11 @@ DELETE FROM gamification ` func (q *Queries) DeleteGamificationAll(ctx context.Context) (int64, error) { - result, err := q.db.ExecContext(ctx, deleteGamificationAll) + result, err := q.db.Exec(ctx, deleteGamificationAll) if err != nil { return 0, err } - return result.RowsAffected() + return result.RowsAffected(), nil } const getAllGamification = `-- name: GetAllGamification :many @@ -66,7 +66,7 @@ FROM gamification // CRUD func (q *Queries) GetAllGamification(ctx context.Context) ([]Gamification, error) { - rows, err := q.db.QueryContext(ctx, getAllGamification) + rows, err := q.db.Query(ctx, getAllGamification) if err != nil { return nil, err } @@ -84,9 +84,6 @@ func (q *Queries) GetAllGamification(ctx context.Context) ([]Gamification, error } items = append(items, i) } - if err := rows.Close(); err != nil { - return nil, err - } if err := rows.Err(); err != nil { return nil, err } @@ -100,7 +97,7 @@ ORDER BY score DESC ` func (q *Queries) GetAllGamificationByScore(ctx context.Context) ([]Gamification, error) { - rows, err := q.db.QueryContext(ctx, getAllGamificationByScore) + rows, err := q.db.Query(ctx, getAllGamificationByScore) if err != nil { return nil, err } @@ -118,9 +115,6 @@ func (q *Queries) GetAllGamificationByScore(ctx context.Context) ([]Gamification } items = append(items, i) } - if err := rows.Close(); err != nil { - return nil, err - } if err := rows.Err(); err != nil { return nil, err } @@ -131,19 +125,19 @@ const updateGamificationScore = `-- name: UpdateGamificationScore :one UPDATE gamification -SET score = ? -WHERE id = ? +SET score = $1 +WHERE id = $2 RETURNING id, name, score, avatar ` type UpdateGamificationScoreParams struct { - Score int64 - ID int64 + Score int32 + ID int32 } // Other func (q *Queries) UpdateGamificationScore(ctx context.Context, arg UpdateGamificationScoreParams) (Gamification, error) { - row := q.db.QueryRowContext(ctx, updateGamificationScore, arg.Score, arg.ID) + row := q.db.QueryRow(ctx, updateGamificationScore, arg.Score, arg.ID) var i Gamification err := row.Scan( &i.ID, diff --git a/internal/pkg/db/sqlc/message.sql.go b/internal/pkg/db/sqlc/message.sql.go index 14626f9..194b970 100644 --- a/internal/pkg/db/sqlc/message.sql.go +++ b/internal/pkg/db/sqlc/message.sql.go @@ -11,7 +11,7 @@ import ( const createMessage = `-- name: CreateMessage :one INSERT INTO message (name, ip, message) -VALUES (?, ?, ?) +VALUES ($1, $2, $3) RETURNING id, name, ip, message, created_at ` @@ -22,7 +22,7 @@ type CreateMessageParams struct { } func (q *Queries) CreateMessage(ctx context.Context, arg CreateMessageParams) (Message, error) { - row := q.db.QueryRowContext(ctx, createMessage, arg.Name, arg.Ip, arg.Message) + row := q.db.QueryRow(ctx, createMessage, arg.Name, arg.Ip, arg.Message) var i Message err := row.Scan( &i.ID, @@ -36,15 +36,15 @@ func (q *Queries) CreateMessage(ctx context.Context, arg CreateMessageParams) (M const deleteMessage = `-- name: DeleteMessage :execrows DELETE FROM message -WHERE id = ? +WHERE id = $1 ` -func (q *Queries) DeleteMessage(ctx context.Context, id int64) (int64, error) { - result, err := q.db.ExecContext(ctx, deleteMessage, id) +func (q *Queries) DeleteMessage(ctx context.Context, id int32) (int64, error) { + result, err := q.db.Exec(ctx, deleteMessage, id) if err != nil { return 0, err } - return result.RowsAffected() + return result.RowsAffected(), nil } const getAllMessages = `-- name: GetAllMessages :many @@ -55,7 +55,7 @@ FROM message // CRUD func (q *Queries) GetAllMessages(ctx context.Context) ([]Message, error) { - rows, err := q.db.QueryContext(ctx, getAllMessages) + rows, err := q.db.Query(ctx, getAllMessages) if err != nil { return nil, err } @@ -74,9 +74,6 @@ func (q *Queries) GetAllMessages(ctx context.Context) ([]Message, error) { } items = append(items, i) } - if err := rows.Close(); err != nil { - return nil, err - } if err := rows.Err(); err != nil { return nil, err } @@ -94,7 +91,7 @@ LIMIT 1 // Other func (q *Queries) GetLastMessage(ctx context.Context) (Message, error) { - row := q.db.QueryRowContext(ctx, getLastMessage) + row := q.db.QueryRow(ctx, getLastMessage) var i Message err := row.Scan( &i.ID, @@ -109,11 +106,11 @@ func (q *Queries) GetLastMessage(ctx context.Context) (Message, error) { const getMessageByID = `-- name: GetMessageByID :one SELECT id, name, ip, message, created_at FROM message -WHERE id = ? +WHERE id = $1 ` -func (q *Queries) GetMessageByID(ctx context.Context, id int64) (Message, error) { - row := q.db.QueryRowContext(ctx, getMessageByID, id) +func (q *Queries) GetMessageByID(ctx context.Context, id int32) (Message, error) { + row := q.db.QueryRow(ctx, getMessageByID, id) var i Message err := row.Scan( &i.ID, @@ -128,12 +125,12 @@ func (q *Queries) GetMessageByID(ctx context.Context, id int64) (Message, error) const getMessageSinceID = `-- name: GetMessageSinceID :many SELECT id, name, ip, message, created_at FROM message -WHERE id > ? +WHERE id > $1 ORDER BY created_at ASC ` -func (q *Queries) GetMessageSinceID(ctx context.Context, id int64) ([]Message, error) { - rows, err := q.db.QueryContext(ctx, getMessageSinceID, id) +func (q *Queries) GetMessageSinceID(ctx context.Context, id int32) ([]Message, error) { + rows, err := q.db.Query(ctx, getMessageSinceID, id) if err != nil { return nil, err } @@ -152,9 +149,6 @@ func (q *Queries) GetMessageSinceID(ctx context.Context, id int64) ([]Message, e } items = append(items, i) } - if err := rows.Close(); err != nil { - return nil, err - } if err := rows.Err(); err != nil { return nil, err } @@ -163,8 +157,8 @@ func (q *Queries) GetMessageSinceID(ctx context.Context, id int64) ([]Message, e const updateMessage = `-- name: UpdateMessage :one UPDATE message -SET name = ?, ip = ?, message = ? -WHERE id = ? +SET name = $1, ip = $2, message = $3 +WHERE id = $4 RETURNING id, name, ip, message, created_at ` @@ -172,11 +166,11 @@ type UpdateMessageParams struct { Name string Ip string Message string - ID int64 + ID int32 } func (q *Queries) UpdateMessage(ctx context.Context, arg UpdateMessageParams) (Message, error) { - row := q.db.QueryRowContext(ctx, updateMessage, + row := q.db.QueryRow(ctx, updateMessage, arg.Name, arg.Ip, arg.Message, diff --git a/internal/pkg/db/sqlc/models.go b/internal/pkg/db/sqlc/models.go index 4a7cb71..ac286c0 100644 --- a/internal/pkg/db/sqlc/models.go +++ b/internal/pkg/db/sqlc/models.go @@ -5,93 +5,92 @@ package sqlc import ( - "database/sql" - "time" + "github.com/jackc/pgx/v5/pgtype" ) type Event struct { - ID int64 + ID int32 Name string - Date time.Time + Date pgtype.Timestamptz AcademicYear string Location string Poster []byte } type Gamification struct { - ID int64 + ID int32 Name string - Score int64 + Score int32 Avatar []byte } type Message struct { - ID int64 + ID int32 Name string Ip string Message string - CreatedAt time.Time + CreatedAt pgtype.Timestamptz } type Scan struct { - ID int64 - ScanTime time.Time + ID int32 + ScanTime pgtype.Timestamptz } type Season struct { - ID int64 + ID int32 Name string - Start time.Time - End time.Time + Start pgtype.Timestamptz + End pgtype.Timestamptz Current bool } type Song struct { - ID int64 + ID int32 Title string SpotifyID string - DurationMs int64 + DurationMs int32 Album string - LyricsType sql.NullString - Lyrics sql.NullString + LyricsType pgtype.Text + Lyrics pgtype.Text } type SongArtist struct { - ID int64 + ID int32 Name string SpotifyID string - Followers int64 - Popularity int64 + Followers int32 + Popularity int32 } type SongArtistGenre struct { - ID int64 - ArtistID int64 - GenreID int64 + ID int32 + ArtistID int32 + GenreID int32 } type SongArtistSong struct { - ID int64 - ArtistID int64 - SongID int64 + ID int32 + ArtistID int32 + SongID int32 } type SongGenre struct { - ID int64 + ID int32 Genre string } type SongHistory struct { - ID int64 - SongID int64 - CreatedAt time.Time + ID int32 + SongID int32 + CreatedAt pgtype.Timestamptz } type Tap struct { - ID int64 - OrderID int64 - OrderCreatedAt time.Time + ID int32 + OrderID int32 + OrderCreatedAt pgtype.Timestamptz Name string Category string - CreatedAt time.Time + CreatedAt pgtype.Timestamptz } diff --git a/internal/pkg/db/sqlc/scan.sql.go b/internal/pkg/db/sqlc/scan.sql.go index 58f294e..6782c7f 100644 --- a/internal/pkg/db/sqlc/scan.sql.go +++ b/internal/pkg/db/sqlc/scan.sql.go @@ -7,17 +7,18 @@ package sqlc import ( "context" - "time" + + "github.com/jackc/pgx/v5/pgtype" ) const createScan = `-- name: CreateScan :one INSERT INTO scan (scan_time) -VALUES (?) +VALUES ($1) RETURNING id, scan_time ` -func (q *Queries) CreateScan(ctx context.Context, scanTime time.Time) (Scan, error) { - row := q.db.QueryRowContext(ctx, createScan, scanTime) +func (q *Queries) CreateScan(ctx context.Context, scanTime pgtype.Timestamptz) (Scan, error) { + row := q.db.QueryRow(ctx, createScan, scanTime) var i Scan err := row.Scan(&i.ID, &i.ScanTime) return i, err @@ -25,15 +26,15 @@ func (q *Queries) CreateScan(ctx context.Context, scanTime time.Time) (Scan, err const deleteScan = `-- name: DeleteScan :execrows DELETE FROM scan -WHERE id = ? +WHERE id = $1 ` -func (q *Queries) DeleteScan(ctx context.Context, id int64) (int64, error) { - result, err := q.db.ExecContext(ctx, deleteScan, id) +func (q *Queries) DeleteScan(ctx context.Context, id int32) (int64, error) { + result, err := q.db.Exec(ctx, deleteScan, id) if err != nil { return 0, err } - return result.RowsAffected() + return result.RowsAffected(), nil } const getAllScans = `-- name: GetAllScans :many @@ -44,7 +45,7 @@ FROM scan // CRUD func (q *Queries) GetAllScans(ctx context.Context) ([]Scan, error) { - rows, err := q.db.QueryContext(ctx, getAllScans) + rows, err := q.db.Query(ctx, getAllScans) if err != nil { return nil, err } @@ -57,9 +58,6 @@ func (q *Queries) GetAllScans(ctx context.Context) ([]Scan, error) { } items = append(items, i) } - if err := rows.Close(); err != nil { - return nil, err - } if err := rows.Err(); err != nil { return nil, err } @@ -69,12 +67,12 @@ func (q *Queries) GetAllScans(ctx context.Context) ([]Scan, error) { const getAllScansSinceID = `-- name: GetAllScansSinceID :many SELECT id, scan_time FROM scan -WHERE id > ? +WHERE id > $1 ORDER BY scan_time ASC ` -func (q *Queries) GetAllScansSinceID(ctx context.Context, id int64) ([]Scan, error) { - rows, err := q.db.QueryContext(ctx, getAllScansSinceID, id) +func (q *Queries) GetAllScansSinceID(ctx context.Context, id int32) ([]Scan, error) { + rows, err := q.db.Query(ctx, getAllScansSinceID, id) if err != nil { return nil, err } @@ -87,9 +85,6 @@ func (q *Queries) GetAllScansSinceID(ctx context.Context, id int64) ([]Scan, err } items = append(items, i) } - if err := rows.Close(); err != nil { - return nil, err - } if err := rows.Err(); err != nil { return nil, err } @@ -107,7 +102,7 @@ LIMIT 1 // Other func (q *Queries) GetLastScan(ctx context.Context) (Scan, error) { - row := q.db.QueryRowContext(ctx, getLastScan) + row := q.db.QueryRow(ctx, getLastScan) var i Scan err := row.Scan(&i.ID, &i.ScanTime) return i, err @@ -116,11 +111,11 @@ func (q *Queries) GetLastScan(ctx context.Context) (Scan, error) { const getScanByID = `-- name: GetScanByID :one SELECT id, scan_time FROM scan -WHERE id = ? +WHERE id = $1 ` -func (q *Queries) GetScanByID(ctx context.Context, id int64) (Scan, error) { - row := q.db.QueryRowContext(ctx, getScanByID, id) +func (q *Queries) GetScanByID(ctx context.Context, id int32) (Scan, error) { + row := q.db.QueryRow(ctx, getScanByID, id) var i Scan err := row.Scan(&i.ID, &i.ScanTime) return i, err @@ -134,7 +129,7 @@ WHERE scan_time >= (SELECT start_date FROM season WHERE current = true) AND ` func (q *Queries) GetScansInCurrentSeason(ctx context.Context) (int64, error) { - row := q.db.QueryRowContext(ctx, getScansInCurrentSeason) + row := q.db.QueryRow(ctx, getScansInCurrentSeason) var amount int64 err := row.Scan(&amount) return amount, err @@ -142,18 +137,18 @@ func (q *Queries) GetScansInCurrentSeason(ctx context.Context) (int64, error) { const updateScan = `-- name: UpdateScan :one UPDATE scan -SET scan_time = ? -WHERE id = ? +SET scan_time = $1 +WHERE id = $2 RETURNING id, scan_time ` type UpdateScanParams struct { - ScanTime time.Time - ID int64 + ScanTime pgtype.Timestamptz + ID int32 } func (q *Queries) UpdateScan(ctx context.Context, arg UpdateScanParams) (Scan, error) { - row := q.db.QueryRowContext(ctx, updateScan, arg.ScanTime, arg.ID) + row := q.db.QueryRow(ctx, updateScan, arg.ScanTime, arg.ID) var i Scan err := row.Scan(&i.ID, &i.ScanTime) return i, err diff --git a/internal/pkg/db/sqlc/season.sql.go b/internal/pkg/db/sqlc/season.sql.go index 7da8781..dec33ce 100644 --- a/internal/pkg/db/sqlc/season.sql.go +++ b/internal/pkg/db/sqlc/season.sql.go @@ -7,24 +7,25 @@ package sqlc import ( "context" - "time" + + "github.com/jackc/pgx/v5/pgtype" ) const createSeason = `-- name: CreateSeason :one -INSERT INTO season (name, start, end, current) -VALUES (?, ?, ?, ?) -RETURNING id, name, start, "end", "current" +INSERT INTO season (name, start, "end", current) +VALUES ($1, $2, $3, $4) +RETURNING id, name, start, "end", current ` type CreateSeasonParams struct { Name string - Start time.Time - End time.Time + Start pgtype.Timestamptz + End pgtype.Timestamptz Current bool } func (q *Queries) CreateSeason(ctx context.Context, arg CreateSeasonParams) (Season, error) { - row := q.db.QueryRowContext(ctx, createSeason, + row := q.db.QueryRow(ctx, createSeason, arg.Name, arg.Start, arg.End, @@ -43,26 +44,26 @@ func (q *Queries) CreateSeason(ctx context.Context, arg CreateSeasonParams) (Sea const deleteSeason = `-- name: DeleteSeason :execrows DELETE FROM season -WHERE id = ? +WHERE id = $1 ` -func (q *Queries) DeleteSeason(ctx context.Context, id int64) (int64, error) { - result, err := q.db.ExecContext(ctx, deleteSeason, id) +func (q *Queries) DeleteSeason(ctx context.Context, id int32) (int64, error) { + result, err := q.db.Exec(ctx, deleteSeason, id) if err != nil { return 0, err } - return result.RowsAffected() + return result.RowsAffected(), nil } const getAllSeasons = `-- name: GetAllSeasons :many -SELECT id, name, start, "end", "current" +SELECT id, name, start, "end", current FROM season ` // CRUD func (q *Queries) GetAllSeasons(ctx context.Context) ([]Season, error) { - rows, err := q.db.QueryContext(ctx, getAllSeasons) + rows, err := q.db.Query(ctx, getAllSeasons) if err != nil { return nil, err } @@ -81,9 +82,6 @@ func (q *Queries) GetAllSeasons(ctx context.Context) ([]Season, error) { } items = append(items, i) } - if err := rows.Close(); err != nil { - return nil, err - } if err := rows.Err(); err != nil { return nil, err } @@ -91,13 +89,13 @@ func (q *Queries) GetAllSeasons(ctx context.Context) ([]Season, error) { } const getSeasonByID = `-- name: GetSeasonByID :one -SELECT id, name, start, "end", "current" +SELECT id, name, start, "end", current FROM season -WHERE id = ? +WHERE id = $1 ` -func (q *Queries) GetSeasonByID(ctx context.Context, id int64) (Season, error) { - row := q.db.QueryRowContext(ctx, getSeasonByID, id) +func (q *Queries) GetSeasonByID(ctx context.Context, id int32) (Season, error) { + row := q.db.QueryRow(ctx, getSeasonByID, id) var i Season err := row.Scan( &i.ID, @@ -112,14 +110,14 @@ func (q *Queries) GetSeasonByID(ctx context.Context, id int64) (Season, error) { const getSeasonCurrent = `-- name: GetSeasonCurrent :one -SELECT id, name, start, "end", "current" +SELECT id, name, start, "end", current FROM season WHERE current = true ` // Other func (q *Queries) GetSeasonCurrent(ctx context.Context) (Season, error) { - row := q.db.QueryRowContext(ctx, getSeasonCurrent) + row := q.db.QueryRow(ctx, getSeasonCurrent) var i Season err := row.Scan( &i.ID, @@ -133,21 +131,21 @@ func (q *Queries) GetSeasonCurrent(ctx context.Context) (Season, error) { const updateSeason = `-- name: UpdateSeason :one UPDATE season -SET name = ?, start = ?, end = ?, current = ? -WHERE id = ? -RETURNING id, name, start, "end", "current" +SET name = $1, start = $2, "end" = $3, current = $4 +WHERE id = $5 +RETURNING id, name, start, "end", current ` type UpdateSeasonParams struct { Name string - Start time.Time - End time.Time + Start pgtype.Timestamptz + End pgtype.Timestamptz Current bool - ID int64 + ID int32 } func (q *Queries) UpdateSeason(ctx context.Context, arg UpdateSeasonParams) (Season, error) { - row := q.db.QueryRowContext(ctx, updateSeason, + row := q.db.QueryRow(ctx, updateSeason, arg.Name, arg.Start, arg.End, diff --git a/internal/pkg/db/sqlc/song.sql.go b/internal/pkg/db/sqlc/song.sql.go index d9947c0..fa718f5 100644 --- a/internal/pkg/db/sqlc/song.sql.go +++ b/internal/pkg/db/sqlc/song.sql.go @@ -7,14 +7,14 @@ package sqlc import ( "context" - "database/sql" - "time" + + "github.com/jackc/pgx/v5/pgtype" ) const createSong = `-- name: CreateSong :one INSERT INTO song (title, album, spotify_id, duration_ms, lyrics_type, lyrics) -VALUES (?, ?, ?, ?, ?, ?) +VALUES ($1, $2, $3, $4, $5, $6) RETURNING id, title, spotify_id, duration_ms, album, lyrics_type, lyrics ` @@ -22,14 +22,14 @@ type CreateSongParams struct { Title string Album string SpotifyID string - DurationMs int64 - LyricsType sql.NullString - Lyrics sql.NullString + DurationMs int32 + LyricsType pgtype.Text + Lyrics pgtype.Text } // CRUD func (q *Queries) CreateSong(ctx context.Context, arg CreateSongParams) (Song, error) { - row := q.db.QueryRowContext(ctx, createSong, + row := q.db.QueryRow(ctx, createSong, arg.Title, arg.Album, arg.SpotifyID, @@ -52,19 +52,19 @@ func (q *Queries) CreateSong(ctx context.Context, arg CreateSongParams) (Song, e const createSongArtist = `-- name: CreateSongArtist :one INSERT INTO song_artist (name, spotify_id, followers, popularity) -VALUES (?, ?, ?, ?) +VALUES ($1, $2, $3, $4) RETURNING id, name, spotify_id, followers, popularity ` type CreateSongArtistParams struct { Name string SpotifyID string - Followers int64 - Popularity int64 + Followers int32 + Popularity int32 } func (q *Queries) CreateSongArtist(ctx context.Context, arg CreateSongArtistParams) (SongArtist, error) { - row := q.db.QueryRowContext(ctx, createSongArtist, + row := q.db.QueryRow(ctx, createSongArtist, arg.Name, arg.SpotifyID, arg.Followers, @@ -83,17 +83,17 @@ func (q *Queries) CreateSongArtist(ctx context.Context, arg CreateSongArtistPara const createSongArtistGenre = `-- name: CreateSongArtistGenre :one INSERT INTO song_artist_genre (artist_id, genre_id) -VALUES (?, ?) +VALUES ($1, $2) RETURNING id, artist_id, genre_id ` type CreateSongArtistGenreParams struct { - ArtistID int64 - GenreID int64 + ArtistID int32 + GenreID int32 } func (q *Queries) CreateSongArtistGenre(ctx context.Context, arg CreateSongArtistGenreParams) (SongArtistGenre, error) { - row := q.db.QueryRowContext(ctx, createSongArtistGenre, arg.ArtistID, arg.GenreID) + row := q.db.QueryRow(ctx, createSongArtistGenre, arg.ArtistID, arg.GenreID) var i SongArtistGenre err := row.Scan(&i.ID, &i.ArtistID, &i.GenreID) return i, err @@ -101,17 +101,17 @@ func (q *Queries) CreateSongArtistGenre(ctx context.Context, arg CreateSongArtis const createSongArtistSong = `-- name: CreateSongArtistSong :one INSERT INTO song_artist_song (artist_id, song_id) -VALUES (?, ?) +VALUES ($1, $2) RETURNING id, artist_id, song_id ` type CreateSongArtistSongParams struct { - ArtistID int64 - SongID int64 + ArtistID int32 + SongID int32 } func (q *Queries) CreateSongArtistSong(ctx context.Context, arg CreateSongArtistSongParams) (SongArtistSong, error) { - row := q.db.QueryRowContext(ctx, createSongArtistSong, arg.ArtistID, arg.SongID) + row := q.db.QueryRow(ctx, createSongArtistSong, arg.ArtistID, arg.SongID) var i SongArtistSong err := row.Scan(&i.ID, &i.ArtistID, &i.SongID) return i, err @@ -119,12 +119,12 @@ func (q *Queries) CreateSongArtistSong(ctx context.Context, arg CreateSongArtist const createSongGenre = `-- name: CreateSongGenre :one INSERT INTO song_genre (genre) -VALUES (?) +VALUES ($1) RETURNING id, genre ` func (q *Queries) CreateSongGenre(ctx context.Context, genre string) (SongGenre, error) { - row := q.db.QueryRowContext(ctx, createSongGenre, genre) + row := q.db.QueryRow(ctx, createSongGenre, genre) var i SongGenre err := row.Scan(&i.ID, &i.Genre) return i, err @@ -132,12 +132,12 @@ func (q *Queries) CreateSongGenre(ctx context.Context, genre string) (SongGenre, const createSongHistory = `-- name: CreateSongHistory :one INSERT INTO song_history (song_id) -VALUES (?) +VALUES ($1) RETURNING id, song_id, created_at ` -func (q *Queries) CreateSongHistory(ctx context.Context, songID int64) (SongHistory, error) { - row := q.db.QueryRowContext(ctx, createSongHistory, songID) +func (q *Queries) CreateSongHistory(ctx context.Context, songID int32) (SongHistory, error) { + row := q.db.QueryRow(ctx, createSongHistory, songID) var i SongHistory err := row.Scan(&i.ID, &i.SongID, &i.CreatedAt) return i, err @@ -156,26 +156,26 @@ ORDER BY a.name, g.genre ` type GetLastSongFullRow struct { - ID int64 + ID int32 SongTitle string SpotifyID string Album string - DurationMs int64 - LyricsType sql.NullString - Lyrics sql.NullString - CreatedAt time.Time - ArtistID sql.NullInt64 - ArtistName sql.NullString - ArtistSpotifyID sql.NullString - ArtistFollowers sql.NullInt64 - ArtistPopularity sql.NullInt64 - GenreID sql.NullInt64 - Genre sql.NullString - CreatedAt_2 time.Time + DurationMs int32 + LyricsType pgtype.Text + Lyrics pgtype.Text + CreatedAt pgtype.Timestamptz + ArtistID pgtype.Int4 + ArtistName pgtype.Text + ArtistSpotifyID pgtype.Text + ArtistFollowers pgtype.Int4 + ArtistPopularity pgtype.Int4 + GenreID pgtype.Int4 + Genre pgtype.Text + CreatedAt_2 pgtype.Timestamptz } func (q *Queries) GetLastSongFull(ctx context.Context) ([]GetLastSongFullRow, error) { - rows, err := q.db.QueryContext(ctx, getLastSongFull) + rows, err := q.db.Query(ctx, getLastSongFull) if err != nil { return nil, err } @@ -205,9 +205,6 @@ func (q *Queries) GetLastSongFull(ctx context.Context) ([]GetLastSongFullRow, er } items = append(items, i) } - if err := rows.Close(); err != nil { - return nil, err - } if err := rows.Err(); err != nil { return nil, err } @@ -222,7 +219,7 @@ LIMIT 1 ` func (q *Queries) GetLastSongHistory(ctx context.Context) (SongHistory, error) { - row := q.db.QueryRowContext(ctx, getLastSongHistory) + row := q.db.QueryRow(ctx, getLastSongHistory) var i SongHistory err := row.Scan(&i.ID, &i.SongID, &i.CreatedAt) return i, err @@ -231,11 +228,11 @@ func (q *Queries) GetLastSongHistory(ctx context.Context) (SongHistory, error) { const getSongArtistByName = `-- name: GetSongArtistByName :one SELECT id, name, spotify_id, followers, popularity FROM song_artist -WHERE name = ? +WHERE name = $1 ` func (q *Queries) GetSongArtistByName(ctx context.Context, name string) (SongArtist, error) { - row := q.db.QueryRowContext(ctx, getSongArtistByName, name) + row := q.db.QueryRow(ctx, getSongArtistByName, name) var i SongArtist err := row.Scan( &i.ID, @@ -250,11 +247,11 @@ func (q *Queries) GetSongArtistByName(ctx context.Context, name string) (SongArt const getSongArtistBySpotifyID = `-- name: GetSongArtistBySpotifyID :one SELECT id, name, spotify_id, followers, popularity FROM song_artist -WHERE spotify_id = ? +WHERE spotify_id = $1 ` func (q *Queries) GetSongArtistBySpotifyID(ctx context.Context, spotifyID string) (SongArtist, error) { - row := q.db.QueryRowContext(ctx, getSongArtistBySpotifyID, spotifyID) + row := q.db.QueryRow(ctx, getSongArtistBySpotifyID, spotifyID) var i SongArtist err := row.Scan( &i.ID, @@ -270,12 +267,12 @@ const getSongBySpotifyID = `-- name: GetSongBySpotifyID :one SELECT id, title, spotify_id, duration_ms, album, lyrics_type, lyrics FROM song -WHERE spotify_id = ? +WHERE spotify_id = $1 ` // Other func (q *Queries) GetSongBySpotifyID(ctx context.Context, spotifyID string) (Song, error) { - row := q.db.QueryRowContext(ctx, getSongBySpotifyID, spotifyID) + row := q.db.QueryRow(ctx, getSongBySpotifyID, spotifyID) var i Song err := row.Scan( &i.ID, @@ -292,11 +289,11 @@ func (q *Queries) GetSongBySpotifyID(ctx context.Context, spotifyID string) (Son const getSongGenreByName = `-- name: GetSongGenreByName :one SELECT id, genre FROM song_genre -WHERE genre = ? +WHERE genre = $1 ` func (q *Queries) GetSongGenreByName(ctx context.Context, genre string) (SongGenre, error) { - row := q.db.QueryRowContext(ctx, getSongGenreByName, genre) + row := q.db.QueryRow(ctx, getSongGenreByName, genre) var i SongGenre err := row.Scan(&i.ID, &i.Genre) return i, err @@ -311,7 +308,7 @@ LIMIT 5 ` func (q *Queries) GetSongHistory(ctx context.Context) ([]string, error) { - rows, err := q.db.QueryContext(ctx, getSongHistory) + rows, err := q.db.Query(ctx, getSongHistory) if err != nil { return nil, err } @@ -324,9 +321,6 @@ func (q *Queries) GetSongHistory(ctx context.Context) ([]string, error) { } items = append(items, title) } - if err := rows.Close(); err != nil { - return nil, err - } if err := rows.Err(); err != nil { return nil, err } @@ -345,13 +339,13 @@ LIMIT 5 ` type GetTopArtistsRow struct { - ArtistID int64 + ArtistID int32 ArtistName string TotalPlays int64 } func (q *Queries) GetTopArtists(ctx context.Context) ([]GetTopArtistsRow, error) { - rows, err := q.db.QueryContext(ctx, getTopArtists) + rows, err := q.db.Query(ctx, getTopArtists) if err != nil { return nil, err } @@ -364,9 +358,6 @@ func (q *Queries) GetTopArtists(ctx context.Context) ([]GetTopArtistsRow, error) } items = append(items, i) } - if err := rows.Close(); err != nil { - return nil, err - } if err := rows.Err(); err != nil { return nil, err } @@ -392,7 +383,7 @@ type GetTopGenresRow struct { } func (q *Queries) GetTopGenres(ctx context.Context) ([]GetTopGenresRow, error) { - rows, err := q.db.QueryContext(ctx, getTopGenres) + rows, err := q.db.Query(ctx, getTopGenres) if err != nil { return nil, err } @@ -405,9 +396,6 @@ func (q *Queries) GetTopGenres(ctx context.Context) ([]GetTopGenresRow, error) { } items = append(items, i) } - if err := rows.Close(); err != nil { - return nil, err - } if err := rows.Err(); err != nil { return nil, err } @@ -424,13 +412,13 @@ LIMIT 5 ` type GetTopSongsRow struct { - SongID int64 + SongID int32 Title string PlayCount int64 } func (q *Queries) GetTopSongs(ctx context.Context) ([]GetTopSongsRow, error) { - rows, err := q.db.QueryContext(ctx, getTopSongs) + rows, err := q.db.Query(ctx, getTopSongs) if err != nil { return nil, err } @@ -443,9 +431,6 @@ func (q *Queries) GetTopSongs(ctx context.Context) ([]GetTopSongsRow, error) { } items = append(items, i) } - if err := rows.Close(); err != nil { - return nil, err - } if err := rows.Err(); err != nil { return nil, err } diff --git a/internal/pkg/db/sqlc/tap.sql.go b/internal/pkg/db/sqlc/tap.sql.go index 33664e2..8a5c7e1 100644 --- a/internal/pkg/db/sqlc/tap.sql.go +++ b/internal/pkg/db/sqlc/tap.sql.go @@ -7,24 +7,25 @@ package sqlc import ( "context" - "time" + + "github.com/jackc/pgx/v5/pgtype" ) const createTap = `-- name: CreateTap :one INSERT INTO tap (order_id, order_created_at, name, category) -VALUES (?, ?, ?, ?) +VALUES ($1, $2, $3, $4) RETURNING id, order_id, order_created_at, name, category, created_at ` type CreateTapParams struct { - OrderID int64 - OrderCreatedAt time.Time + OrderID int32 + OrderCreatedAt pgtype.Timestamptz Name string Category string } func (q *Queries) CreateTap(ctx context.Context, arg CreateTapParams) (Tap, error) { - row := q.db.QueryRowContext(ctx, createTap, + row := q.db.QueryRow(ctx, createTap, arg.OrderID, arg.OrderCreatedAt, arg.Name, @@ -44,15 +45,15 @@ func (q *Queries) CreateTap(ctx context.Context, arg CreateTapParams) (Tap, erro const deleteTap = `-- name: DeleteTap :execrows DELETE FROM tap -WHERE id = ? +WHERE id = $1 ` -func (q *Queries) DeleteTap(ctx context.Context, id int64) (int64, error) { - result, err := q.db.ExecContext(ctx, deleteTap, id) +func (q *Queries) DeleteTap(ctx context.Context, id int32) (int64, error) { + result, err := q.db.Exec(ctx, deleteTap, id) if err != nil { return 0, err } - return result.RowsAffected() + return result.RowsAffected(), nil } const getAllTaps = `-- name: GetAllTaps :many @@ -63,7 +64,7 @@ FROM tap // CRUD func (q *Queries) GetAllTaps(ctx context.Context) ([]Tap, error) { - rows, err := q.db.QueryContext(ctx, getAllTaps) + rows, err := q.db.Query(ctx, getAllTaps) if err != nil { return nil, err } @@ -83,9 +84,6 @@ func (q *Queries) GetAllTaps(ctx context.Context) ([]Tap, error) { } items = append(items, i) } - if err := rows.Close(); err != nil { - return nil, err - } if err := rows.Err(); err != nil { return nil, err } @@ -100,7 +98,7 @@ LIMIT 1 ` func (q *Queries) GetLastOrderByOrderID(ctx context.Context) (Tap, error) { - row := q.db.QueryRowContext(ctx, getLastOrderByOrderID) + row := q.db.QueryRow(ctx, getLastOrderByOrderID) var i Tap err := row.Scan( &i.ID, @@ -125,7 +123,7 @@ type GetOrderCountRow struct { } func (q *Queries) GetOrderCount(ctx context.Context) ([]GetOrderCountRow, error) { - rows, err := q.db.QueryContext(ctx, getOrderCount) + rows, err := q.db.Query(ctx, getOrderCount) if err != nil { return nil, err } @@ -138,9 +136,6 @@ func (q *Queries) GetOrderCount(ctx context.Context) ([]GetOrderCountRow, error) } items = append(items, i) } - if err := rows.Close(); err != nil { - return nil, err - } if err := rows.Err(); err != nil { return nil, err } @@ -150,18 +145,18 @@ func (q *Queries) GetOrderCount(ctx context.Context) ([]GetOrderCountRow, error) const getOrderCountByCategorySinceOrderID = `-- name: GetOrderCountByCategorySinceOrderID :many SELECT category, COUNT(*), CAST(MAX(order_created_at) AS INTEGER) AS latest_order_created_at FROM tap -WHERE order_id >= ? +WHERE order_id >= $1 GROUP BY category ` type GetOrderCountByCategorySinceOrderIDRow struct { Category string Count int64 - LatestOrderCreatedAt int64 + LatestOrderCreatedAt int32 } -func (q *Queries) GetOrderCountByCategorySinceOrderID(ctx context.Context, orderID int64) ([]GetOrderCountByCategorySinceOrderIDRow, error) { - rows, err := q.db.QueryContext(ctx, getOrderCountByCategorySinceOrderID, orderID) +func (q *Queries) GetOrderCountByCategorySinceOrderID(ctx context.Context, orderID int32) ([]GetOrderCountByCategorySinceOrderIDRow, error) { + rows, err := q.db.Query(ctx, getOrderCountByCategorySinceOrderID, orderID) if err != nil { return nil, err } @@ -174,9 +169,6 @@ func (q *Queries) GetOrderCountByCategorySinceOrderID(ctx context.Context, order } items = append(items, i) } - if err := rows.Close(); err != nil { - return nil, err - } if err := rows.Err(); err != nil { return nil, err } @@ -186,11 +178,11 @@ func (q *Queries) GetOrderCountByCategorySinceOrderID(ctx context.Context, order const getTapByCategory = `-- name: GetTapByCategory :many SELECT id, order_id, order_created_at, name, category, created_at FROM tap -WHERE category = ? +WHERE category = $1 ` func (q *Queries) GetTapByCategory(ctx context.Context, category string) ([]Tap, error) { - rows, err := q.db.QueryContext(ctx, getTapByCategory, category) + rows, err := q.db.Query(ctx, getTapByCategory, category) if err != nil { return nil, err } @@ -210,9 +202,6 @@ func (q *Queries) GetTapByCategory(ctx context.Context, category string) ([]Tap, } items = append(items, i) } - if err := rows.Close(); err != nil { - return nil, err - } if err := rows.Err(); err != nil { return nil, err } @@ -222,11 +211,11 @@ func (q *Queries) GetTapByCategory(ctx context.Context, category string) ([]Tap, const getTapByID = `-- name: GetTapByID :one SELECT id, order_id, order_created_at, name, category, created_at FROM tap -WHERE id = ? +WHERE id = $1 ` -func (q *Queries) GetTapByID(ctx context.Context, id int64) (Tap, error) { - row := q.db.QueryRowContext(ctx, getTapByID, id) +func (q *Queries) GetTapByID(ctx context.Context, id int32) (Tap, error) { + row := q.db.QueryRow(ctx, getTapByID, id) var i Tap err := row.Scan( &i.ID, @@ -244,12 +233,12 @@ const getTapByOrderID = `-- name: GetTapByOrderID :one SELECT id, order_id, order_created_at, name, category, created_at FROM tap -WHERE order_id = ? +WHERE order_id = $1 ` // Other -func (q *Queries) GetTapByOrderID(ctx context.Context, orderID int64) (Tap, error) { - row := q.db.QueryRowContext(ctx, getTapByOrderID, orderID) +func (q *Queries) GetTapByOrderID(ctx context.Context, orderID int32) (Tap, error) { + row := q.db.QueryRow(ctx, getTapByOrderID, orderID) var i Tap err := row.Scan( &i.ID, @@ -264,21 +253,21 @@ func (q *Queries) GetTapByOrderID(ctx context.Context, orderID int64) (Tap, erro const updateTap = `-- name: UpdateTap :one UPDATE tap -SET order_id = ?, order_created_at = ?, name = ?, category = ? -WHERE id = ? +SET order_id = $1, order_created_at = $2, name = $3, category = $4 +WHERE id = $5 RETURNING id, order_id, order_created_at, name, category, created_at ` type UpdateTapParams struct { - OrderID int64 - OrderCreatedAt time.Time + OrderID int32 + OrderCreatedAt pgtype.Timestamptz Name string Category string - ID int64 + ID int32 } func (q *Queries) UpdateTap(ctx context.Context, arg UpdateTapParams) (Tap, error) { - row := q.db.QueryRowContext(ctx, updateTap, + row := q.db.QueryRow(ctx, updateTap, arg.OrderID, arg.OrderCreatedAt, arg.Name, diff --git a/internal/pkg/gamification/api.go b/internal/pkg/gamification/api.go index 5ac1382..b899fb8 100644 --- a/internal/pkg/gamification/api.go +++ b/internal/pkg/gamification/api.go @@ -10,9 +10,9 @@ import ( ) type gamificationItem struct { - ID int64 `json:"id"` + ID int32 `json:"id"` Name string `json:"github_name"` - Score int64 `json:"score"` + Score int32 `json:"score"` AvatarURL string `json:"avatar_url"` } diff --git a/internal/pkg/song/api.go b/internal/pkg/song/api.go index c0d0869..b4eef5c 100644 --- a/internal/pkg/song/api.go +++ b/internal/pkg/song/api.go @@ -26,7 +26,7 @@ type trackResponse struct { Name string `json:"name"` Album trackAlbum `json:"album"` Artists []trackArtist `json:"artists"` - DurationMS int64 `json:"duration_ms"` + DurationMS int32 `json:"duration_ms"` } func (s *Song) getTrack(track *dto.Song) error { @@ -83,8 +83,8 @@ func (s *Song) getArtist(artist *dto.SongArtist) error { return fmt.Errorf("Song: Artist request wrong status code %d", status) } - artist.Popularity = int64(res.Popularity) - artist.Followers = int64(res.Followers.Total) + artist.Popularity = int32(res.Popularity) + artist.Followers = int32(res.Followers.Total) for _, genre := range res.Genres { artist.Genres = append(artist.Genres, dto.SongGenre{Genre: genre}) diff --git a/internal/pkg/song/song.go b/internal/pkg/song/song.go index 3abdbb7..ccdd76e 100644 --- a/internal/pkg/song/song.go +++ b/internal/pkg/song/song.go @@ -3,10 +3,10 @@ package song import ( "context" - "database/sql" "errors" "time" + "github.com/jackc/pgx/v5" "github.com/zeusWPI/scc/internal/pkg/db" "github.com/zeusWPI/scc/internal/pkg/db/dto" "github.com/zeusWPI/scc/internal/pkg/db/sqlc" @@ -44,7 +44,7 @@ func (s *Song) Track(track *dto.Song) error { // Check if song is already in DB trackDB, err := s.db.Queries.GetSongBySpotifyID(context.Background(), track.SpotifyID) - if err != nil && err != sql.ErrNoRows { + if err != nil && err != pgx.ErrNoRows { return err } @@ -52,7 +52,7 @@ func (s *Song) Track(track *dto.Song) error { // Already in DB // Add to song history if it's not the latest song songHistory, err := s.db.Queries.GetLastSongHistory(context.Background()) - if err != nil && err != sql.ErrNoRows { + if err != nil && err != pgx.ErrNoRows { return err } @@ -96,7 +96,7 @@ func (s *Song) Track(track *dto.Song) error { // Handle artists for i, artist := range track.Artists { a, err := s.db.Queries.GetSongArtistBySpotifyID(context.Background(), artist.SpotifyID) - if err != nil && err != sql.ErrNoRows { + if err != nil && err != pgx.ErrNoRows { errs = append(errs, err) continue } @@ -133,7 +133,7 @@ func (s *Song) Track(track *dto.Song) error { // Check if the artists genres are in db for j, genre := range track.Artists[i].Genres { g, err := s.db.Queries.GetSongGenreByName(context.Background(), genre.Genre) - if err != nil && err != sql.ErrNoRows { + if err != nil && err != pgx.ErrNoRows { errs = append(errs, err) continue } diff --git a/internal/pkg/tap/api.go b/internal/pkg/tap/api.go index 8dd1cca..522b16e 100644 --- a/internal/pkg/tap/api.go +++ b/internal/pkg/tap/api.go @@ -9,7 +9,7 @@ import ( ) type orderResponseItem struct { - OrderID int64 `json:"order_id"` + OrderID int32 `json:"order_id"` OrderCreatedAt time.Time `json:"order_created_at"` ProductName string `json:"product_name"` ProductCategory string `json:"product_category"` diff --git a/internal/pkg/tap/tap.go b/internal/pkg/tap/tap.go index 2dd2cd2..678d0fa 100644 --- a/internal/pkg/tap/tap.go +++ b/internal/pkg/tap/tap.go @@ -3,11 +3,12 @@ package tap import ( "context" - "database/sql" "errors" "slices" "strings" + "github.com/jackc/pgx/v5" + "github.com/jackc/pgx/v5/pgtype" "github.com/zeusWPI/scc/internal/pkg/db" "github.com/zeusWPI/scc/internal/pkg/db/sqlc" "github.com/zeusWPI/scc/pkg/config" @@ -48,7 +49,7 @@ func (t *Tap) Update() error { // Get latest order lastOrder, err := t.db.Queries.GetLastOrderByOrderID(context.Background()) if err != nil { - if err != sql.ErrNoRows { + if err != pgx.ErrNoRows { return err } @@ -76,7 +77,7 @@ func (t *Tap) Update() error { for _, order := range orders { _, err := t.db.Queries.CreateTap(context.Background(), sqlc.CreateTapParams{ OrderID: order.OrderID, - OrderCreatedAt: order.OrderCreatedAt, + OrderCreatedAt: pgtype.Timestamptz{Time: order.OrderCreatedAt}, Name: order.ProductName, Category: order.ProductCategory, }) diff --git a/internal/pkg/zess/zess.go b/internal/pkg/zess/zess.go index 47a8d72..c524b2c 100644 --- a/internal/pkg/zess/zess.go +++ b/internal/pkg/zess/zess.go @@ -3,10 +3,11 @@ package zess import ( "context" - "database/sql" "errors" "slices" + "github.com/jackc/pgx/v5" + "github.com/jackc/pgx/v5/pgtype" "github.com/zeusWPI/scc/internal/pkg/db" "github.com/zeusWPI/scc/internal/pkg/db/dto" "github.com/zeusWPI/scc/internal/pkg/db/sqlc" @@ -30,7 +31,7 @@ func New(db *db.DB) *Zess { func (z *Zess) UpdateSeasons() error { seasons, err := z.db.Queries.GetAllSeasons(context.Background()) if err != nil { - if err != sql.ErrNoRows { + if err != pgx.ErrNoRows { return err } } @@ -56,8 +57,8 @@ func (z *Zess) UpdateSeasons() error { // Update seasons seasons[i].ID = season.ID seasons[i].Name = season.Name - seasons[i].Start = season.Start - seasons[i].End = season.End + seasons[i].Start = pgtype.Timestamptz{Time: season.Start} + seasons[i].End = pgtype.Timestamptz{Time: season.End} _, err := z.db.Queries.UpdateSeason(context.Background(), dto.SeasonDTO(seasons[i]).UpdateParams()) if err != nil { @@ -87,7 +88,7 @@ func (z *Zess) UpdateSeasons() error { func (z *Zess) UpdateScans() error { lastScan, err := z.db.Queries.GetLastScan(context.Background()) if err != nil { - if err != sql.ErrNoRows { + if err != pgx.ErrNoRows { return err } diff --git a/makefile b/makefile index 6900102..cda5bb3 100644 --- a/makefile +++ b/makefile @@ -1,13 +1,15 @@ # Variables -BACKEND_BIN := backend -TUI_BIN := tui +BACKEND_BIN := backend_bin +TUI_BIN := tui_bin BACKEND_SRC := cmd/backend/backend.go TUI_SRC := cmd/tui/tui.go DB_DIR := ./db/migrations -DB_FILE := ./sqlite.db +DB_USER := postgres +DB_PASSWORD := postgres +DB_NAME := scc # Phony targets -.PHONY: all build clean run run-backend run-tui sqlc create-migration goose migrate watch +.PHONY: all build build-backed build-tui clean run run-backend run-tui db sqlc create-migration goose migrate watch # Default target: build everything all: build @@ -15,14 +17,12 @@ all: build # Build targets build: clean build-backend build-tui -build-backend: +build-backend: clean-backend @echo "Building $(BACKEND_BIN)..." - @rm -f $(BACKEND_BIN) @go build -o $(BACKEND_BIN) $(BACKEND_SRC) -build-tui: +build-tui: clean-tui @echo "Building $(TUI_BIN)..." - @rm -f $(TUI_BIN) @go build -o $(TUI_BIN) $(TUI_SRC) # Run targets @@ -37,16 +37,24 @@ run-tui: @read -p "Enter screen name: " screen; \ ./$(TUI_BIN) $$screen +# Run db +db: + @docker compose up + # Clean targets clean: clean-backend clean-tui clean-backend: - @echo "Cleaning $(BACKEND_BIN)..." - @rm -f $(BACKEND_BIN) + @if [ -f "$(BACKEND_BIN)" ]; then \ + echo "Cleaning $(BACKEND_BIN)..."; \ + rm -f "$(BACKEND_BIN)"; \ + fi clean-tui: - @echo "Cleaning $(TUI_BIN)..." - @rm -f $(TUI_BIN) + @if [ -f "$(TUI_BIN)" ]; then \ + echo "Cleaning $(TUI_BIN)..."; \ + rm -f "$(TUI_BIN)"; \ + fi # SQL and migration targets sqlc: @@ -57,8 +65,8 @@ create-migration: goose -dir $(DB_DIR) create $$name sql migrate: - @goose -dir $(DB_DIR) sqlite3 $(DB_FILE) up + @goose -dir $(DB_DIR) postgres "user=$(DB_USER) password=$(DB_PASSWORD) dbname=$(DB_NAME) host=localhost sslmode=disable" up goose: @read -p "Action: " action; \ - goose -dir $(DB_DIR) sqlite3 $(DB_FILE) $$action + goose -dir $(DB_DIR) postgres "user=$(DB_USER) password=$(DB_PASSWORD) dbname=$(DB_NAME) host=localhost sslmode=disable" $$action diff --git a/sqlc.yml b/sqlc.yml index 2fe8046..a4821a6 100644 --- a/sqlc.yml +++ b/sqlc.yml @@ -1,6 +1,6 @@ version: "2" sql: - - engine: "sqlite" + - engine: "postgresql" queries: - "db/queries/*.sql" schema: "db/migrations" @@ -8,3 +8,4 @@ sql: go: package: "sqlc" out: "internal/pkg/db/sqlc" + sql_package: "pgx/v5" diff --git a/ui/components/stopwatch/stopwatch.go b/tui/components/stopwatch/stopwatch.go similarity index 100% rename from ui/components/stopwatch/stopwatch.go rename to tui/components/stopwatch/stopwatch.go diff --git a/ui/screen/cammie/cammie.go b/tui/screen/cammie/cammie.go similarity index 94% rename from ui/screen/cammie/cammie.go rename to tui/screen/cammie/cammie.go index 22e78b7..f3d763b 100644 --- a/ui/screen/cammie/cammie.go +++ b/tui/screen/cammie/cammie.go @@ -9,13 +9,13 @@ import ( "github.com/charmbracelet/lipgloss" "github.com/zeusWPI/scc/internal/pkg/db" "github.com/zeusWPI/scc/pkg/config" - "github.com/zeusWPI/scc/ui/screen" - "github.com/zeusWPI/scc/ui/view" - "github.com/zeusWPI/scc/ui/view/event" - "github.com/zeusWPI/scc/ui/view/gamification" - "github.com/zeusWPI/scc/ui/view/message" - "github.com/zeusWPI/scc/ui/view/tap" - "github.com/zeusWPI/scc/ui/view/zess" + "github.com/zeusWPI/scc/tui/screen" + "github.com/zeusWPI/scc/tui/view" + "github.com/zeusWPI/scc/tui/view/event" + "github.com/zeusWPI/scc/tui/view/gamification" + "github.com/zeusWPI/scc/tui/view/message" + "github.com/zeusWPI/scc/tui/view/tap" + "github.com/zeusWPI/scc/tui/view/zess" ) // Cammie represents the cammie screen diff --git a/ui/screen/cammie/style.go b/tui/screen/cammie/style.go similarity index 100% rename from ui/screen/cammie/style.go rename to tui/screen/cammie/style.go diff --git a/ui/screen/screen.go b/tui/screen/screen.go similarity index 89% rename from ui/screen/screen.go rename to tui/screen/screen.go index e4edd1c..b6c0a37 100644 --- a/ui/screen/screen.go +++ b/tui/screen/screen.go @@ -3,7 +3,7 @@ package screen import ( tea "github.com/charmbracelet/bubbletea" - "github.com/zeusWPI/scc/ui/view" + "github.com/zeusWPI/scc/tui/view" ) // Screen represents a screen diff --git a/ui/screen/song/song.go b/tui/screen/song/song.go similarity index 94% rename from ui/screen/song/song.go rename to tui/screen/song/song.go index 3532205..a7c8b50 100644 --- a/ui/screen/song/song.go +++ b/tui/screen/song/song.go @@ -4,9 +4,9 @@ package song import ( tea "github.com/charmbracelet/bubbletea" "github.com/zeusWPI/scc/internal/pkg/db" - "github.com/zeusWPI/scc/ui/screen" - "github.com/zeusWPI/scc/ui/view" - "github.com/zeusWPI/scc/ui/view/song" + "github.com/zeusWPI/scc/tui/screen" + "github.com/zeusWPI/scc/tui/view" + "github.com/zeusWPI/scc/tui/view/song" ) // Song represents the song screen diff --git a/ui/screen/song/style.go b/tui/screen/song/style.go similarity index 100% rename from ui/screen/song/style.go rename to tui/screen/song/style.go diff --git a/ui/tui.go b/tui/tui.go similarity index 96% rename from ui/tui.go rename to tui/tui.go index b5b4635..eb7008e 100644 --- a/ui/tui.go +++ b/tui/tui.go @@ -3,7 +3,7 @@ package tui import ( tea "github.com/charmbracelet/bubbletea" - "github.com/zeusWPI/scc/ui/screen" + "github.com/zeusWPI/scc/tui/screen" "go.uber.org/zap" ) diff --git a/ui/view/event/event.go b/tui/view/event/event.go similarity index 98% rename from ui/view/event/event.go rename to tui/view/event/event.go index b6bf13f..6dcf550 100644 --- a/ui/view/event/event.go +++ b/tui/view/event/event.go @@ -10,7 +10,7 @@ import ( "github.com/zeusWPI/scc/internal/pkg/db/dto" "github.com/zeusWPI/scc/pkg/config" "github.com/zeusWPI/scc/pkg/util" - "github.com/zeusWPI/scc/ui/view" + "github.com/zeusWPI/scc/tui/view" ) var ( diff --git a/ui/view/event/style.go b/tui/view/event/style.go similarity index 100% rename from ui/view/event/style.go rename to tui/view/event/style.go diff --git a/ui/view/event/view.go b/tui/view/event/view.go similarity index 98% rename from ui/view/event/view.go rename to tui/view/event/view.go index 16deb16..79b75fc 100644 --- a/ui/view/event/view.go +++ b/tui/view/event/view.go @@ -5,7 +5,7 @@ import ( "image" "github.com/charmbracelet/lipgloss" - "github.com/zeusWPI/scc/ui/view" + "github.com/zeusWPI/scc/tui/view" ) func (m *Model) viewToday() string { diff --git a/ui/view/gamification/gamification.go b/tui/view/gamification/gamification.go similarity index 97% rename from ui/view/gamification/gamification.go rename to tui/view/gamification/gamification.go index 43eb54c..15d7282 100644 --- a/ui/view/gamification/gamification.go +++ b/tui/view/gamification/gamification.go @@ -4,17 +4,17 @@ package gamification import ( "bytes" "context" - "database/sql" "fmt" "image" "strconv" tea "github.com/charmbracelet/bubbletea" "github.com/charmbracelet/lipgloss" + "github.com/jackc/pgx/v5" "github.com/zeusWPI/scc/internal/pkg/db" "github.com/zeusWPI/scc/internal/pkg/db/dto" "github.com/zeusWPI/scc/pkg/config" - "github.com/zeusWPI/scc/ui/view" + "github.com/zeusWPI/scc/tui/view" ) // Model represents the view model for gamification @@ -96,7 +96,7 @@ func updateLeaderboard(view view.View) (tea.Msg, error) { gams, err := m.db.Queries.GetAllGamificationByScore(context.Background()) if err != nil { - if err == sql.ErrNoRows { + if err == pgx.ErrNoRows { err = nil } return nil, err diff --git a/ui/view/gamification/styles.go b/tui/view/gamification/styles.go similarity index 100% rename from ui/view/gamification/styles.go rename to tui/view/gamification/styles.go diff --git a/ui/view/message/message.go b/tui/view/message/message.go similarity index 94% rename from ui/view/message/message.go rename to tui/view/message/message.go index d30b770..0ed52df 100644 --- a/ui/view/message/message.go +++ b/tui/view/message/message.go @@ -3,14 +3,14 @@ package message import ( "context" - "database/sql" "hash/fnv" "time" tea "github.com/charmbracelet/bubbletea" + "github.com/jackc/pgx/v5" "github.com/zeusWPI/scc/internal/pkg/db" "github.com/zeusWPI/scc/pkg/config" - "github.com/zeusWPI/scc/ui/view" + "github.com/zeusWPI/scc/tui/view" ) // Model represents the model for the message view @@ -18,7 +18,7 @@ type Model struct { width int height int db *db.DB - lastMessageID int64 + lastMessageID int32 messages []message } @@ -31,7 +31,7 @@ type message struct { // Msg represents the message to update the message view type Msg struct { - lastMessageID int64 + lastMessageID int32 messages []message } @@ -98,7 +98,7 @@ func updateMessages(view view.View) (tea.Msg, error) { messagesDB, err := m.db.Queries.GetMessageSinceID(context.Background(), lastMessageID) if err != nil { - if err == sql.ErrNoRows { + if err == pgx.ErrNoRows { err = nil } return nil, err @@ -119,7 +119,7 @@ func updateMessages(view view.View) (tea.Msg, error) { sender: m.Name, message: m.Message, color: hashColor(m.Name), - date: m.CreatedAt, + date: m.CreatedAt.Time, }) } diff --git a/ui/view/message/style.go b/tui/view/message/style.go similarity index 100% rename from ui/view/message/style.go rename to tui/view/message/style.go diff --git a/ui/view/message/view.go b/tui/view/message/view.go similarity index 100% rename from ui/view/message/view.go rename to tui/view/message/view.go diff --git a/ui/view/song/song.go b/tui/view/song/song.go similarity index 94% rename from ui/view/song/song.go rename to tui/view/song/song.go index 7b6d7fa..1a4e33a 100644 --- a/ui/view/song/song.go +++ b/tui/view/song/song.go @@ -3,17 +3,17 @@ package song import ( "context" - "database/sql" "time" "github.com/charmbracelet/bubbles/progress" tea "github.com/charmbracelet/bubbletea" + "github.com/jackc/pgx/v5" "github.com/zeusWPI/scc/internal/pkg/db" "github.com/zeusWPI/scc/internal/pkg/db/dto" "github.com/zeusWPI/scc/internal/pkg/lyrics" "github.com/zeusWPI/scc/pkg/config" - "github.com/zeusWPI/scc/ui/components/stopwatch" - "github.com/zeusWPI/scc/ui/view" + "github.com/zeusWPI/scc/tui/components/stopwatch" + "github.com/zeusWPI/scc/tui/view" ) var ( @@ -219,7 +219,7 @@ func updateCurrentSong(view view.View) (tea.Msg, error) { songs, err := m.db.Queries.GetLastSongFull(context.Background()) if err != nil { - if err == sql.ErrNoRows { + if err == pgx.ErrNoRows { err = nil } return nil, err @@ -229,7 +229,7 @@ func updateCurrentSong(view view.View) (tea.Msg, error) { } // Check if song is still playing - if songs[0].CreatedAt.Add(time.Duration(songs[0].DurationMs) * time.Millisecond).Before(time.Now()) { + if songs[0].CreatedAt.Time.Add(time.Duration(songs[0].DurationMs) * time.Millisecond).Before(time.Now()) { // Song is finished return nil, nil } @@ -250,7 +250,7 @@ func updateTopStats(view view.View) (tea.Msg, error) { change := false songs, err := m.db.Queries.GetTopSongs(context.Background()) - if err != nil && err != sql.ErrNoRows { + if err != nil && err != pgx.ErrNoRows { return nil, err } @@ -260,7 +260,7 @@ func updateTopStats(view view.View) (tea.Msg, error) { } genres, err := m.db.Queries.GetTopGenres(context.Background()) - if err != nil && err != sql.ErrNoRows { + if err != nil && err != pgx.ErrNoRows { return nil, err } @@ -270,7 +270,7 @@ func updateTopStats(view view.View) (tea.Msg, error) { } artists, err := m.db.Queries.GetTopArtists(context.Background()) - if err != nil && err != sql.ErrNoRows { + if err != nil && err != pgx.ErrNoRows { return nil, err } diff --git a/ui/view/song/style.go b/tui/view/song/style.go similarity index 100% rename from ui/view/song/style.go rename to tui/view/song/style.go diff --git a/ui/view/song/util.go b/tui/view/song/util.go similarity index 100% rename from ui/view/song/util.go rename to tui/view/song/util.go diff --git a/ui/view/song/view.go b/tui/view/song/view.go similarity index 100% rename from ui/view/song/view.go rename to tui/view/song/view.go diff --git a/ui/view/tap/style.go b/tui/view/tap/style.go similarity index 100% rename from ui/view/tap/style.go rename to tui/view/tap/style.go diff --git a/ui/view/tap/tap.go b/tui/view/tap/tap.go similarity index 94% rename from ui/view/tap/tap.go rename to tui/view/tap/tap.go index b46ce69..d752685 100644 --- a/ui/view/tap/tap.go +++ b/tui/view/tap/tap.go @@ -3,15 +3,15 @@ package tap import ( "context" - "database/sql" "slices" "time" tea "github.com/charmbracelet/bubbletea" "github.com/charmbracelet/lipgloss" + "github.com/jackc/pgx/v5" "github.com/zeusWPI/scc/internal/pkg/db" "github.com/zeusWPI/scc/pkg/config" - "github.com/zeusWPI/scc/ui/view" + "github.com/zeusWPI/scc/tui/view" ) type category string @@ -33,13 +33,13 @@ var categoryToStyle = map[category]lipgloss.Style{ // Model represents the tap model type Model struct { db *db.DB - lastOrderID int64 + lastOrderID int32 items []tapItem } // Msg represents a tap message type Msg struct { - lastOrderID int64 + lastOrderID int32 items []tapItem } @@ -128,7 +128,7 @@ func updateOrders(view view.View) (tea.Msg, error) { order, err := m.db.Queries.GetLastOrderByOrderID(context.Background()) if err != nil { - if err == sql.ErrNoRows { + if err == pgx.ErrNoRows { err = nil } return nil, err @@ -155,7 +155,7 @@ func updateOrders(view view.View) (tea.Msg, error) { counts[category(order.Category)] = tapItem{ category: category(order.Category), amount: int(order.Count), - last: time.Unix(order.LatestOrderCreatedAt, 0), + last: time.Unix(int64(order.LatestOrderCreatedAt), 0), } } diff --git a/ui/view/tap/view.go b/tui/view/tap/view.go similarity index 100% rename from ui/view/tap/view.go rename to tui/view/tap/view.go diff --git a/ui/view/util.go b/tui/view/util.go similarity index 100% rename from ui/view/util.go rename to tui/view/util.go diff --git a/ui/view/view.go b/tui/view/view.go similarity index 100% rename from ui/view/view.go rename to tui/view/view.go diff --git a/ui/view/zess/style.go b/tui/view/zess/style.go similarity index 100% rename from ui/view/zess/style.go rename to tui/view/zess/style.go diff --git a/ui/view/zess/view.go b/tui/view/zess/view.go similarity index 100% rename from ui/view/zess/view.go rename to tui/view/zess/view.go diff --git a/ui/view/zess/zess.go b/tui/view/zess/zess.go similarity index 94% rename from ui/view/zess/zess.go rename to tui/view/zess/zess.go index cd04ed2..2d672b6 100644 --- a/ui/view/zess/zess.go +++ b/tui/view/zess/zess.go @@ -3,13 +3,13 @@ package zess import ( "context" - "database/sql" tea "github.com/charmbracelet/bubbletea" "github.com/charmbracelet/lipgloss" + "github.com/jackc/pgx/v5" "github.com/zeusWPI/scc/internal/pkg/db" "github.com/zeusWPI/scc/pkg/config" - "github.com/zeusWPI/scc/ui/view" + "github.com/zeusWPI/scc/tui/view" "go.uber.org/zap" ) @@ -28,7 +28,7 @@ type weekScan struct { // Model represents the Model for the zess view type Model struct { db *db.DB - lastScanID int64 + lastScanID int32 scans []weekScan // Scans per week maxWeekScans int64 currentSeason yearWeek // Start week of the season @@ -41,7 +41,7 @@ type Msg struct{} // scanMsg is used to indicate that the zess view should be updated with new scans type scanMsg struct { Msg - lastScanID int64 + lastScanID int32 scans []weekScan } @@ -196,7 +196,7 @@ func updateScans(view view.View) (tea.Msg, error) { // Get new scans scans, err := m.db.Queries.GetAllScansSinceID(context.Background(), lastScanID) if err != nil { - if err == sql.ErrNoRows { + if err == pgx.ErrNoRows { // No rows shouldn't be considered an error err = nil } @@ -212,7 +212,7 @@ func updateScans(view view.View) (tea.Msg, error) { // Add new scans to scan msg for _, newScan := range scans { - yearNumber, weekNumber := newScan.ScanTime.ISOWeek() + yearNumber, weekNumber := newScan.ScanTime.Time.ISOWeek() newTime := yearWeek{year: yearNumber, week: weekNumber} found := false @@ -225,7 +225,7 @@ func updateScans(view view.View) (tea.Msg, error) { } if !found { - zessScanMsg.scans = append(zessScanMsg.scans, weekScan{time: newTime, amount: 1, label: newScan.ScanTime.Format("02/01")}) + zessScanMsg.scans = append(zessScanMsg.scans, weekScan{time: newTime, amount: 1, label: newScan.ScanTime.Time.Format("02/01")}) } // Update scan ID @@ -244,7 +244,7 @@ func updateSeason(view view.View) (tea.Msg, error) { season, err := m.db.Queries.GetSeasonCurrent(context.Background()) if err != nil { - if err == sql.ErrNoRows { + if err == pgx.ErrNoRows { // No rows shouldn't be considered an error err = nil } @@ -252,7 +252,7 @@ func updateSeason(view view.View) (tea.Msg, error) { } // Check if we have a new season - yearNumber, weekNumber := season.Start.ISOWeek() + yearNumber, weekNumber := season.Start.Time.ISOWeek() seasonStart := yearWeek{year: yearNumber, week: weekNumber} if m.currentSeason.equal(seasonStart) { // Same season