From 9f9a33cbf55d38987a66b709284d2bb4ffea0fe9 Mon Sep 17 00:00:00 2001
From: Doog <157747121+doogongithub@users.noreply.github.com>
Date: Thu, 29 Feb 2024 20:13:48 -0500
Subject: modify api, build additional FE components, add types

---
 db/scripts/water_init.sql | 40 +++++++++++++++++++++++++++++++++++-----
 1 file changed, 35 insertions(+), 5 deletions(-)

(limited to 'db/scripts/water_init.sql')

diff --git a/db/scripts/water_init.sql b/db/scripts/water_init.sql
index 0751c41..6a4de24 100644
--- a/db/scripts/water_init.sql
+++ b/db/scripts/water_init.sql
@@ -1,8 +1,9 @@
 -- user table for users.
 CREATE TABLE IF NOT EXISTS Users (
     id INTEGER PRIMARY KEY,
-    name TEXT NOT NULL,
-    UNIQUE(name)
+    password TEXT UNIQUE NOT NULL,
+    uuid TEXT UNIQUE NOT NULL,
+    name TEXT UNIQUE NOT NULL
 );
 
 -- statistics table for users to log their consumption
@@ -19,7 +20,7 @@ CREATE TABLE IF NOT EXISTS Preferences (
     color TEXT NOT NULL DEFAULT "#000000",
     user_id INT NOT NULL,
     size_id INT NOT NULL DEFAULT 1,
-    FOREIGN KEY(user_id) REFERENCES Users(id) ON DELETE CASCADE
+    FOREIGN KEY(user_id) REFERENCES Users(id) ON DELETE CASCADE,
     FOREIGN KEY(size_id) REFERENCES Sizes(id)
 );
 
@@ -30,13 +31,42 @@ CREATE TABLE IF NOT EXISTS Sizes (
     unit TEXT DEFAULT "oz"
 );
 
+CREATE TABLE IF NOT EXISTS APIToken (
+    id INTEGER PRIMARY KEY,
+    token TEXT NOT NULL,
+    user_id INTEGER NOT NULL,
+    FOREIGN KEY(user_id) REFERENCES Users(id) ON DELETE CASCADE
+);
+
 -- create default sizes for sizes lookup table.
 INSERT OR IGNORE INTO Sizes (id, size) VALUES (1, 8), (2, 16), (3, 24), (4, 32), (5, 40), (6, 48); 
 
 -- create default users.
-INSERT OR IGNORE INTO Users (id, name) VALUES (1, 'Parker'), (2, 'Zach');
+INSERT OR IGNORE INTO Users (name, password, uuid) VALUES (
+    'parker',
+    '$2y$10$2UlKrQJQV5cQOo/8VcFlq.ai3MWf7mA4//knEs2xVnHTeB.RnfN.m',
+    '1aa668f3-7527-4a67-9c24-fdf307542eeb'
+), (
+    'zach',
+    '$2y$10$35UJnLpBj8ulhqN/3G4qKe0GYBOa/YunXit11n7ET6zknZpNeKpRS',
+    'be3fd6b7-cf55-4eb8-92d8-1b745b439f34'
+);
 
 -- create default preferences.
-INSERT OR IGNORE INTO Preferences (id, user_id) VALUES (1, 1), (2, 2);
+INSERT OR IGNORE INTO Preferences (user_id) VALUES (1), (2);
 
+CREATE TRIGGER IF NOT EXISTS enforce_size_id
+BEFORE INSERT ON Preferences
+BEGIN
+    SELECT
+        CASE
+            WHEN (
+                SELECT COUNT(*) FROM Sizes WHERE id = new.size_id
+            ) = 0
+            THEN RAISE(ABORT, 'Size does not exist')
+        END;
+END;
 
+-- 
+CREATE VIEW IF NOT EXISTS aggregated_stats AS
+    SELECT u.uuid, SUM(s.quantity * s.size) from Statistics s INNER JOIN Users u ON u.id = s.user_id INNER JOIN Preferences p ON p.user_id = u.id INNER JOIN Size s ON s.id = p.size_id;
-- 
cgit v1.1

