diff --git a/README.md b/README.md index 8b21aa0..81bb534 100644 --- a/README.md +++ b/README.md @@ -71,6 +71,10 @@ Security trade-off: localStorage is readable by JavaScript on the same origin. A `/cookbook` and `/recipes/new` require a validated session. On refresh, the router waits for session restoration before rendering protected content or redirecting to login. A temporary API/network error shows a retry action and preserves the token. Successful login or registration returns to the requested protected URL, including its query and hash. Explore and recipe details remain public. This is client-side routing; future protected API operations must enforce authentication and ownership on the server. +## Database + +Se [databasemodellen](docs/database-model.md) for tabeller, ER-diagram, regler, migrasjon og tester. Modellen utvider autentiseringen og er klar for CRUD i neste steg. + ## Nyttige kommandoer | Kommando | Bruk | diff --git a/apps/api/migrations/0002_recipe_model.sql b/apps/api/migrations/0002_recipe_model.sql new file mode 100644 index 0000000..5065027 --- /dev/null +++ b/apps/api/migrations/0002_recipe_model.sql @@ -0,0 +1,105 @@ +-- Existing placeholder recipes need a deliberate author/content backfill. +-- Stop before changing tables rather than inventing ownership or losing data. +DO $$ +BEGIN + IF EXISTS (SELECT 1 FROM "project2"."recipes") THEN + RAISE EXCEPTION 'Recipe migration requires an empty legacy recipes table. Back up existing rows and prepare an explicit author/content backfill before retrying.'; + END IF; +END $$; +--> statement-breakpoint +CREATE TABLE "project2"."ratings" ( + "user_id" uuid NOT NULL, + "recipe_id" uuid NOT NULL, + "score" integer NOT NULL, + "created_at" timestamp with time zone DEFAULT now() NOT NULL, + "updated_at" timestamp with time zone DEFAULT now() NOT NULL, + CONSTRAINT "ratings_user_id_recipe_id_pk" PRIMARY KEY("user_id","recipe_id"), + CONSTRAINT "ratings_score_valid" CHECK ("project2"."ratings"."score" BETWEEN 1 AND 5) +); +--> statement-breakpoint +CREATE TABLE "project2"."recipe_ingredients" ( + "id" uuid PRIMARY KEY DEFAULT gen_random_uuid() NOT NULL, + "recipe_id" uuid NOT NULL, + "name" text NOT NULL, + "amount" numeric(12, 4) NOT NULL, + "unit" text NOT NULL, + "note" text, + "position" integer NOT NULL, + CONSTRAINT "recipe_ingredients_name_not_blank" CHECK (length(trim("project2"."recipe_ingredients"."name")) > 0), + CONSTRAINT "recipe_ingredients_amount_positive" CHECK ("project2"."recipe_ingredients"."amount" > 0 AND "project2"."recipe_ingredients"."amount" <> 'NaN'::numeric), + CONSTRAINT "recipe_ingredients_position_positive" CHECK ("project2"."recipe_ingredients"."position" > 0) +); +--> statement-breakpoint +CREATE TABLE "project2"."recipe_instructions" ( + "id" uuid PRIMARY KEY DEFAULT gen_random_uuid() NOT NULL, + "recipe_id" uuid NOT NULL, + "text" text NOT NULL, + "position" integer NOT NULL, + CONSTRAINT "recipe_instructions_text_not_blank" CHECK (length(trim("project2"."recipe_instructions"."text")) > 0), + CONSTRAINT "recipe_instructions_position_positive" CHECK ("project2"."recipe_instructions"."position" > 0) +); +--> statement-breakpoint +CREATE TABLE "project2"."recipe_tags" ( + "recipe_id" uuid NOT NULL, + "tag" text NOT NULL, + CONSTRAINT "recipe_tags_recipe_id_tag_pk" PRIMARY KEY("recipe_id","tag"), + CONSTRAINT "recipe_tags_normalized" CHECK (length("project2"."recipe_tags"."tag") > 0 AND "project2"."recipe_tags"."tag" = lower(trim("project2"."recipe_tags"."tag"))) +); +--> statement-breakpoint +CREATE TABLE "project2"."saved_recipes" ( + "user_id" uuid NOT NULL, + "recipe_id" uuid NOT NULL, + "created_at" timestamp with time zone DEFAULT now() NOT NULL, + CONSTRAINT "saved_recipes_user_id_recipe_id_pk" PRIMARY KEY("user_id","recipe_id") +); +--> statement-breakpoint +ALTER TABLE "project2"."recipes" ADD COLUMN "author_id" uuid NOT NULL;--> statement-breakpoint +ALTER TABLE "project2"."recipes" ADD COLUMN "description" text NOT NULL;--> statement-breakpoint +ALTER TABLE "project2"."recipes" ADD COLUMN "image_url" text;--> statement-breakpoint +ALTER TABLE "project2"."recipes" ADD COLUMN "category" text NOT NULL;--> statement-breakpoint +ALTER TABLE "project2"."recipes" ADD COLUMN "cuisine" text NOT NULL;--> statement-breakpoint +ALTER TABLE "project2"."recipes" ADD COLUMN "difficulty" text NOT NULL;--> statement-breakpoint +ALTER TABLE "project2"."recipes" ADD COLUMN "visibility" text DEFAULT 'private' NOT NULL;--> statement-breakpoint +ALTER TABLE "project2"."recipes" ADD COLUMN "prep_minutes" integer NOT NULL;--> statement-breakpoint +ALTER TABLE "project2"."recipes" ADD COLUMN "cook_minutes" integer NOT NULL;--> statement-breakpoint +ALTER TABLE "project2"."recipes" ADD COLUMN "servings" integer NOT NULL;--> statement-breakpoint +ALTER TABLE "project2"."recipes" ADD COLUMN "created_at" timestamp with time zone DEFAULT now() NOT NULL;--> statement-breakpoint +ALTER TABLE "project2"."recipes" ADD COLUMN "updated_at" timestamp with time zone DEFAULT now() NOT NULL;--> statement-breakpoint +ALTER TABLE "project2"."ratings" ADD CONSTRAINT "ratings_user_id_users_id_fk" FOREIGN KEY ("user_id") REFERENCES "project2"."users"("id") ON DELETE cascade ON UPDATE no action;--> statement-breakpoint +ALTER TABLE "project2"."ratings" ADD CONSTRAINT "ratings_recipe_id_recipes_id_fk" FOREIGN KEY ("recipe_id") REFERENCES "project2"."recipes"("id") ON DELETE cascade ON UPDATE no action;--> statement-breakpoint +ALTER TABLE "project2"."recipe_ingredients" ADD CONSTRAINT "recipe_ingredients_recipe_id_recipes_id_fk" FOREIGN KEY ("recipe_id") REFERENCES "project2"."recipes"("id") ON DELETE cascade ON UPDATE no action;--> statement-breakpoint +ALTER TABLE "project2"."recipe_instructions" ADD CONSTRAINT "recipe_instructions_recipe_id_recipes_id_fk" FOREIGN KEY ("recipe_id") REFERENCES "project2"."recipes"("id") ON DELETE cascade ON UPDATE no action;--> statement-breakpoint +ALTER TABLE "project2"."recipe_tags" ADD CONSTRAINT "recipe_tags_recipe_id_recipes_id_fk" FOREIGN KEY ("recipe_id") REFERENCES "project2"."recipes"("id") ON DELETE cascade ON UPDATE no action;--> statement-breakpoint +ALTER TABLE "project2"."saved_recipes" ADD CONSTRAINT "saved_recipes_user_id_users_id_fk" FOREIGN KEY ("user_id") REFERENCES "project2"."users"("id") ON DELETE cascade ON UPDATE no action;--> statement-breakpoint +ALTER TABLE "project2"."saved_recipes" ADD CONSTRAINT "saved_recipes_recipe_id_recipes_id_fk" FOREIGN KEY ("recipe_id") REFERENCES "project2"."recipes"("id") ON DELETE cascade ON UPDATE no action;--> statement-breakpoint +CREATE INDEX "ratings_recipe_idx" ON "project2"."ratings" USING btree ("recipe_id");--> statement-breakpoint +CREATE UNIQUE INDEX "recipe_ingredients_recipe_position_unique" ON "project2"."recipe_ingredients" USING btree ("recipe_id","position");--> statement-breakpoint +CREATE UNIQUE INDEX "recipe_instructions_recipe_position_unique" ON "project2"."recipe_instructions" USING btree ("recipe_id","position");--> statement-breakpoint +CREATE INDEX "saved_recipes_recipe_idx" ON "project2"."saved_recipes" USING btree ("recipe_id");--> statement-breakpoint +ALTER TABLE "project2"."recipes" ADD CONSTRAINT "recipes_author_id_users_id_fk" FOREIGN KEY ("author_id") REFERENCES "project2"."users"("id") ON DELETE cascade ON UPDATE no action;--> statement-breakpoint +CREATE INDEX "recipes_author_idx" ON "project2"."recipes" USING btree ("author_id");--> statement-breakpoint +CREATE INDEX "recipes_public_created_idx" ON "project2"."recipes" USING btree ("created_at","id") WHERE "project2"."recipes"."visibility" = 'public';--> statement-breakpoint +ALTER TABLE "project2"."recipes" ADD CONSTRAINT "recipes_title_not_blank" CHECK (length(trim("project2"."recipes"."title")) > 0);--> statement-breakpoint +ALTER TABLE "project2"."recipes" ADD CONSTRAINT "recipes_category_not_blank" CHECK (length(trim("project2"."recipes"."category")) > 0);--> statement-breakpoint +ALTER TABLE "project2"."recipes" ADD CONSTRAINT "recipes_cuisine_not_blank" CHECK (length(trim("project2"."recipes"."cuisine")) > 0);--> statement-breakpoint +ALTER TABLE "project2"."recipes" ADD CONSTRAINT "recipes_difficulty_valid" CHECK ("project2"."recipes"."difficulty" IN ('easy', 'medium', 'hard'));--> statement-breakpoint +ALTER TABLE "project2"."recipes" ADD CONSTRAINT "recipes_visibility_valid" CHECK ("project2"."recipes"."visibility" IN ('public', 'private'));--> statement-breakpoint +ALTER TABLE "project2"."recipes" ADD CONSTRAINT "recipes_prep_minutes_nonnegative" CHECK ("project2"."recipes"."prep_minutes" >= 0);--> statement-breakpoint +ALTER TABLE "project2"."recipes" ADD CONSTRAINT "recipes_cook_minutes_nonnegative" CHECK ("project2"."recipes"."cook_minutes" >= 0);--> statement-breakpoint +ALTER TABLE "project2"."recipes" ADD CONSTRAINT "recipes_servings_positive" CHECK ("project2"."recipes"."servings" > 0); +--> statement-breakpoint +-- Database triggers also cover writes made through raw SQL (as in auth). +CREATE FUNCTION "project2"."touch_updated_at"() RETURNS trigger +LANGUAGE plpgsql AS $$ +BEGIN + NEW.updated_at = clock_timestamp(); + RETURN NEW; +END $$; +--> statement-breakpoint +CREATE TRIGGER recipes_touch_updated_at +BEFORE UPDATE ON "project2"."recipes" +FOR EACH ROW EXECUTE FUNCTION "project2"."touch_updated_at"(); +--> statement-breakpoint +CREATE TRIGGER ratings_touch_updated_at +BEFORE UPDATE ON "project2"."ratings" +FOR EACH ROW EXECUTE FUNCTION "project2"."touch_updated_at"(); diff --git a/apps/api/migrations/0003_recipe_review.sql b/apps/api/migrations/0003_recipe_review.sql new file mode 100644 index 0000000..df53def --- /dev/null +++ b/apps/api/migrations/0003_recipe_review.sql @@ -0,0 +1,10 @@ +ALTER TABLE "project2"."recipes" DROP CONSTRAINT "recipes_category_not_blank";--> statement-breakpoint +ALTER TABLE "project2"."recipes" ALTER COLUMN "cuisine" DROP NOT NULL;--> statement-breakpoint +ALTER TABLE "project2"."recipes" ADD COLUMN "source_recipe_id" uuid;--> statement-breakpoint +ALTER TABLE "project2"."recipes" ADD CONSTRAINT "recipes_source_recipe_id_recipes_id_fk" FOREIGN KEY ("source_recipe_id") REFERENCES "project2"."recipes"("id") ON DELETE set null ON UPDATE no action;--> statement-breakpoint +CREATE INDEX "recipes_source_idx" ON "project2"."recipes" USING btree ("source_recipe_id");--> statement-breakpoint +-- Normalize known category labels without guessing mappings for unknown values. +-- Unknown categories abort the migration and require an explicit correction. +UPDATE "project2"."recipes" SET "category" = lower(trim("category")) +WHERE "category" <> lower(trim("category"));--> statement-breakpoint +ALTER TABLE "project2"."recipes" ADD CONSTRAINT "recipes_category_valid" CHECK ("project2"."recipes"."category" IN ('breakfast', 'lunch', 'dinner', 'dessert', 'soup')); diff --git a/apps/api/migrations/meta/0002_snapshot.json b/apps/api/migrations/meta/0002_snapshot.json new file mode 100644 index 0000000..742398e --- /dev/null +++ b/apps/api/migrations/meta/0002_snapshot.json @@ -0,0 +1,700 @@ +{ + "id": "078adb6f-bfdc-42b6-9e70-e621fc612161", + "prevId": "8106c561-4f83-4ec4-9119-840e77bd557d", + "version": "7", + "dialect": "postgresql", + "tables": { + "project2.ratings": { + "name": "ratings", + "schema": "project2", + "columns": { + "user_id": { + "name": "user_id", + "type": "uuid", + "primaryKey": false, + "notNull": true + }, + "recipe_id": { + "name": "recipe_id", + "type": "uuid", + "primaryKey": false, + "notNull": true + }, + "score": { + "name": "score", + "type": "integer", + "primaryKey": false, + "notNull": true + }, + "created_at": { + "name": "created_at", + "type": "timestamp with time zone", + "primaryKey": false, + "notNull": true, + "default": "now()" + }, + "updated_at": { + "name": "updated_at", + "type": "timestamp with time zone", + "primaryKey": false, + "notNull": true, + "default": "now()" + } + }, + "indexes": { + "ratings_recipe_idx": { + "name": "ratings_recipe_idx", + "columns": [ + { + "expression": "recipe_id", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + } + }, + "foreignKeys": { + "ratings_user_id_users_id_fk": { + "name": "ratings_user_id_users_id_fk", + "tableFrom": "ratings", + "tableTo": "users", + "schemaTo": "project2", + "columnsFrom": ["user_id"], + "columnsTo": ["id"], + "onDelete": "cascade", + "onUpdate": "no action" + }, + "ratings_recipe_id_recipes_id_fk": { + "name": "ratings_recipe_id_recipes_id_fk", + "tableFrom": "ratings", + "tableTo": "recipes", + "schemaTo": "project2", + "columnsFrom": ["recipe_id"], + "columnsTo": ["id"], + "onDelete": "cascade", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": { + "ratings_user_id_recipe_id_pk": { + "name": "ratings_user_id_recipe_id_pk", + "columns": ["user_id", "recipe_id"] + } + }, + "uniqueConstraints": {}, + "policies": {}, + "checkConstraints": { + "ratings_score_valid": { + "name": "ratings_score_valid", + "value": "\"project2\".\"ratings\".\"score\" BETWEEN 1 AND 5" + } + }, + "isRLSEnabled": false + }, + "project2.recipe_ingredients": { + "name": "recipe_ingredients", + "schema": "project2", + "columns": { + "id": { + "name": "id", + "type": "uuid", + "primaryKey": true, + "notNull": true, + "default": "gen_random_uuid()" + }, + "recipe_id": { + "name": "recipe_id", + "type": "uuid", + "primaryKey": false, + "notNull": true + }, + "name": { + "name": "name", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "amount": { + "name": "amount", + "type": "numeric(12, 4)", + "primaryKey": false, + "notNull": true + }, + "unit": { + "name": "unit", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "note": { + "name": "note", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "position": { + "name": "position", + "type": "integer", + "primaryKey": false, + "notNull": true + } + }, + "indexes": { + "recipe_ingredients_recipe_position_unique": { + "name": "recipe_ingredients_recipe_position_unique", + "columns": [ + { + "expression": "recipe_id", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "position", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": true, + "concurrently": false, + "method": "btree", + "with": {} + } + }, + "foreignKeys": { + "recipe_ingredients_recipe_id_recipes_id_fk": { + "name": "recipe_ingredients_recipe_id_recipes_id_fk", + "tableFrom": "recipe_ingredients", + "tableTo": "recipes", + "schemaTo": "project2", + "columnsFrom": ["recipe_id"], + "columnsTo": ["id"], + "onDelete": "cascade", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "policies": {}, + "checkConstraints": { + "recipe_ingredients_name_not_blank": { + "name": "recipe_ingredients_name_not_blank", + "value": "length(trim(\"project2\".\"recipe_ingredients\".\"name\")) > 0" + }, + "recipe_ingredients_amount_positive": { + "name": "recipe_ingredients_amount_positive", + "value": "\"project2\".\"recipe_ingredients\".\"amount\" > 0 AND \"project2\".\"recipe_ingredients\".\"amount\" <> 'NaN'::numeric" + }, + "recipe_ingredients_position_positive": { + "name": "recipe_ingredients_position_positive", + "value": "\"project2\".\"recipe_ingredients\".\"position\" > 0" + } + }, + "isRLSEnabled": false + }, + "project2.recipe_instructions": { + "name": "recipe_instructions", + "schema": "project2", + "columns": { + "id": { + "name": "id", + "type": "uuid", + "primaryKey": true, + "notNull": true, + "default": "gen_random_uuid()" + }, + "recipe_id": { + "name": "recipe_id", + "type": "uuid", + "primaryKey": false, + "notNull": true + }, + "text": { + "name": "text", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "position": { + "name": "position", + "type": "integer", + "primaryKey": false, + "notNull": true + } + }, + "indexes": { + "recipe_instructions_recipe_position_unique": { + "name": "recipe_instructions_recipe_position_unique", + "columns": [ + { + "expression": "recipe_id", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "position", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": true, + "concurrently": false, + "method": "btree", + "with": {} + } + }, + "foreignKeys": { + "recipe_instructions_recipe_id_recipes_id_fk": { + "name": "recipe_instructions_recipe_id_recipes_id_fk", + "tableFrom": "recipe_instructions", + "tableTo": "recipes", + "schemaTo": "project2", + "columnsFrom": ["recipe_id"], + "columnsTo": ["id"], + "onDelete": "cascade", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "policies": {}, + "checkConstraints": { + "recipe_instructions_text_not_blank": { + "name": "recipe_instructions_text_not_blank", + "value": "length(trim(\"project2\".\"recipe_instructions\".\"text\")) > 0" + }, + "recipe_instructions_position_positive": { + "name": "recipe_instructions_position_positive", + "value": "\"project2\".\"recipe_instructions\".\"position\" > 0" + } + }, + "isRLSEnabled": false + }, + "project2.recipe_tags": { + "name": "recipe_tags", + "schema": "project2", + "columns": { + "recipe_id": { + "name": "recipe_id", + "type": "uuid", + "primaryKey": false, + "notNull": true + }, + "tag": { + "name": "tag", + "type": "text", + "primaryKey": false, + "notNull": true + } + }, + "indexes": {}, + "foreignKeys": { + "recipe_tags_recipe_id_recipes_id_fk": { + "name": "recipe_tags_recipe_id_recipes_id_fk", + "tableFrom": "recipe_tags", + "tableTo": "recipes", + "schemaTo": "project2", + "columnsFrom": ["recipe_id"], + "columnsTo": ["id"], + "onDelete": "cascade", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": { + "recipe_tags_recipe_id_tag_pk": { + "name": "recipe_tags_recipe_id_tag_pk", + "columns": ["recipe_id", "tag"] + } + }, + "uniqueConstraints": {}, + "policies": {}, + "checkConstraints": { + "recipe_tags_normalized": { + "name": "recipe_tags_normalized", + "value": "length(\"project2\".\"recipe_tags\".\"tag\") > 0 AND \"project2\".\"recipe_tags\".\"tag\" = lower(trim(\"project2\".\"recipe_tags\".\"tag\"))" + } + }, + "isRLSEnabled": false + }, + "project2.recipes": { + "name": "recipes", + "schema": "project2", + "columns": { + "id": { + "name": "id", + "type": "uuid", + "primaryKey": true, + "notNull": true, + "default": "gen_random_uuid()" + }, + "author_id": { + "name": "author_id", + "type": "uuid", + "primaryKey": false, + "notNull": true + }, + "title": { + "name": "title", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "description": { + "name": "description", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "image_url": { + "name": "image_url", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "category": { + "name": "category", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "cuisine": { + "name": "cuisine", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "difficulty": { + "name": "difficulty", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "visibility": { + "name": "visibility", + "type": "text", + "primaryKey": false, + "notNull": true, + "default": "'private'" + }, + "prep_minutes": { + "name": "prep_minutes", + "type": "integer", + "primaryKey": false, + "notNull": true + }, + "cook_minutes": { + "name": "cook_minutes", + "type": "integer", + "primaryKey": false, + "notNull": true + }, + "servings": { + "name": "servings", + "type": "integer", + "primaryKey": false, + "notNull": true + }, + "created_at": { + "name": "created_at", + "type": "timestamp with time zone", + "primaryKey": false, + "notNull": true, + "default": "now()" + }, + "updated_at": { + "name": "updated_at", + "type": "timestamp with time zone", + "primaryKey": false, + "notNull": true, + "default": "now()" + } + }, + "indexes": { + "recipes_author_idx": { + "name": "recipes_author_idx", + "columns": [ + { + "expression": "author_id", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + }, + "recipes_public_created_idx": { + "name": "recipes_public_created_idx", + "columns": [ + { + "expression": "created_at", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "id", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "where": "\"project2\".\"recipes\".\"visibility\" = 'public'", + "concurrently": false, + "method": "btree", + "with": {} + } + }, + "foreignKeys": { + "recipes_author_id_users_id_fk": { + "name": "recipes_author_id_users_id_fk", + "tableFrom": "recipes", + "tableTo": "users", + "schemaTo": "project2", + "columnsFrom": ["author_id"], + "columnsTo": ["id"], + "onDelete": "cascade", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "policies": {}, + "checkConstraints": { + "recipes_title_not_blank": { + "name": "recipes_title_not_blank", + "value": "length(trim(\"project2\".\"recipes\".\"title\")) > 0" + }, + "recipes_category_not_blank": { + "name": "recipes_category_not_blank", + "value": "length(trim(\"project2\".\"recipes\".\"category\")) > 0" + }, + "recipes_cuisine_not_blank": { + "name": "recipes_cuisine_not_blank", + "value": "length(trim(\"project2\".\"recipes\".\"cuisine\")) > 0" + }, + "recipes_difficulty_valid": { + "name": "recipes_difficulty_valid", + "value": "\"project2\".\"recipes\".\"difficulty\" IN ('easy', 'medium', 'hard')" + }, + "recipes_visibility_valid": { + "name": "recipes_visibility_valid", + "value": "\"project2\".\"recipes\".\"visibility\" IN ('public', 'private')" + }, + "recipes_prep_minutes_nonnegative": { + "name": "recipes_prep_minutes_nonnegative", + "value": "\"project2\".\"recipes\".\"prep_minutes\" >= 0" + }, + "recipes_cook_minutes_nonnegative": { + "name": "recipes_cook_minutes_nonnegative", + "value": "\"project2\".\"recipes\".\"cook_minutes\" >= 0" + }, + "recipes_servings_positive": { + "name": "recipes_servings_positive", + "value": "\"project2\".\"recipes\".\"servings\" > 0" + } + }, + "isRLSEnabled": false + }, + "project2.saved_recipes": { + "name": "saved_recipes", + "schema": "project2", + "columns": { + "user_id": { + "name": "user_id", + "type": "uuid", + "primaryKey": false, + "notNull": true + }, + "recipe_id": { + "name": "recipe_id", + "type": "uuid", + "primaryKey": false, + "notNull": true + }, + "created_at": { + "name": "created_at", + "type": "timestamp with time zone", + "primaryKey": false, + "notNull": true, + "default": "now()" + } + }, + "indexes": { + "saved_recipes_recipe_idx": { + "name": "saved_recipes_recipe_idx", + "columns": [ + { + "expression": "recipe_id", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + } + }, + "foreignKeys": { + "saved_recipes_user_id_users_id_fk": { + "name": "saved_recipes_user_id_users_id_fk", + "tableFrom": "saved_recipes", + "tableTo": "users", + "schemaTo": "project2", + "columnsFrom": ["user_id"], + "columnsTo": ["id"], + "onDelete": "cascade", + "onUpdate": "no action" + }, + "saved_recipes_recipe_id_recipes_id_fk": { + "name": "saved_recipes_recipe_id_recipes_id_fk", + "tableFrom": "saved_recipes", + "tableTo": "recipes", + "schemaTo": "project2", + "columnsFrom": ["recipe_id"], + "columnsTo": ["id"], + "onDelete": "cascade", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": { + "saved_recipes_user_id_recipe_id_pk": { + "name": "saved_recipes_user_id_recipe_id_pk", + "columns": ["user_id", "recipe_id"] + } + }, + "uniqueConstraints": {}, + "policies": {}, + "checkConstraints": {}, + "isRLSEnabled": false + }, + "project2.sessions": { + "name": "sessions", + "schema": "project2", + "columns": { + "id": { + "name": "id", + "type": "uuid", + "primaryKey": true, + "notNull": true, + "default": "gen_random_uuid()" + }, + "user_id": { + "name": "user_id", + "type": "uuid", + "primaryKey": false, + "notNull": true + }, + "expires_at": { + "name": "expires_at", + "type": "timestamp with time zone", + "primaryKey": false, + "notNull": true + } + }, + "indexes": {}, + "foreignKeys": { + "sessions_user_id_users_id_fk": { + "name": "sessions_user_id_users_id_fk", + "tableFrom": "sessions", + "tableTo": "users", + "schemaTo": "project2", + "columnsFrom": ["user_id"], + "columnsTo": ["id"], + "onDelete": "cascade", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "policies": {}, + "checkConstraints": {}, + "isRLSEnabled": false + }, + "project2.users": { + "name": "users", + "schema": "project2", + "columns": { + "id": { + "name": "id", + "type": "uuid", + "primaryKey": true, + "notNull": true, + "default": "gen_random_uuid()" + }, + "name": { + "name": "name", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "email": { + "name": "email", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "password_hash": { + "name": "password_hash", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "created_at": { + "name": "created_at", + "type": "timestamp with time zone", + "primaryKey": false, + "notNull": true, + "default": "now()" + } + }, + "indexes": { + "users_email_unique": { + "name": "users_email_unique", + "columns": [ + { + "expression": "email", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": true, + "concurrently": false, + "method": "btree", + "with": {} + } + }, + "foreignKeys": {}, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "policies": {}, + "checkConstraints": {}, + "isRLSEnabled": false + } + }, + "enums": {}, + "schemas": {}, + "sequences": {}, + "roles": {}, + "policies": {}, + "views": {}, + "_meta": { + "columns": {}, + "schemas": {}, + "tables": {} + } +} diff --git a/apps/api/migrations/meta/0003_snapshot.json b/apps/api/migrations/meta/0003_snapshot.json new file mode 100644 index 0000000..ef92bf5 --- /dev/null +++ b/apps/api/migrations/meta/0003_snapshot.json @@ -0,0 +1,731 @@ +{ + "id": "c0ecbb19-5a20-4d7a-808d-836ae2992c9e", + "prevId": "078adb6f-bfdc-42b6-9e70-e621fc612161", + "version": "7", + "dialect": "postgresql", + "tables": { + "project2.ratings": { + "name": "ratings", + "schema": "project2", + "columns": { + "user_id": { + "name": "user_id", + "type": "uuid", + "primaryKey": false, + "notNull": true + }, + "recipe_id": { + "name": "recipe_id", + "type": "uuid", + "primaryKey": false, + "notNull": true + }, + "score": { + "name": "score", + "type": "integer", + "primaryKey": false, + "notNull": true + }, + "created_at": { + "name": "created_at", + "type": "timestamp with time zone", + "primaryKey": false, + "notNull": true, + "default": "now()" + }, + "updated_at": { + "name": "updated_at", + "type": "timestamp with time zone", + "primaryKey": false, + "notNull": true, + "default": "now()" + } + }, + "indexes": { + "ratings_recipe_idx": { + "name": "ratings_recipe_idx", + "columns": [ + { + "expression": "recipe_id", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + } + }, + "foreignKeys": { + "ratings_user_id_users_id_fk": { + "name": "ratings_user_id_users_id_fk", + "tableFrom": "ratings", + "tableTo": "users", + "schemaTo": "project2", + "columnsFrom": ["user_id"], + "columnsTo": ["id"], + "onDelete": "cascade", + "onUpdate": "no action" + }, + "ratings_recipe_id_recipes_id_fk": { + "name": "ratings_recipe_id_recipes_id_fk", + "tableFrom": "ratings", + "tableTo": "recipes", + "schemaTo": "project2", + "columnsFrom": ["recipe_id"], + "columnsTo": ["id"], + "onDelete": "cascade", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": { + "ratings_user_id_recipe_id_pk": { + "name": "ratings_user_id_recipe_id_pk", + "columns": ["user_id", "recipe_id"] + } + }, + "uniqueConstraints": {}, + "policies": {}, + "checkConstraints": { + "ratings_score_valid": { + "name": "ratings_score_valid", + "value": "\"project2\".\"ratings\".\"score\" BETWEEN 1 AND 5" + } + }, + "isRLSEnabled": false + }, + "project2.recipe_ingredients": { + "name": "recipe_ingredients", + "schema": "project2", + "columns": { + "id": { + "name": "id", + "type": "uuid", + "primaryKey": true, + "notNull": true, + "default": "gen_random_uuid()" + }, + "recipe_id": { + "name": "recipe_id", + "type": "uuid", + "primaryKey": false, + "notNull": true + }, + "name": { + "name": "name", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "amount": { + "name": "amount", + "type": "numeric(12, 4)", + "primaryKey": false, + "notNull": true + }, + "unit": { + "name": "unit", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "note": { + "name": "note", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "position": { + "name": "position", + "type": "integer", + "primaryKey": false, + "notNull": true + } + }, + "indexes": { + "recipe_ingredients_recipe_position_unique": { + "name": "recipe_ingredients_recipe_position_unique", + "columns": [ + { + "expression": "recipe_id", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "position", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": true, + "concurrently": false, + "method": "btree", + "with": {} + } + }, + "foreignKeys": { + "recipe_ingredients_recipe_id_recipes_id_fk": { + "name": "recipe_ingredients_recipe_id_recipes_id_fk", + "tableFrom": "recipe_ingredients", + "tableTo": "recipes", + "schemaTo": "project2", + "columnsFrom": ["recipe_id"], + "columnsTo": ["id"], + "onDelete": "cascade", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "policies": {}, + "checkConstraints": { + "recipe_ingredients_name_not_blank": { + "name": "recipe_ingredients_name_not_blank", + "value": "length(trim(\"project2\".\"recipe_ingredients\".\"name\")) > 0" + }, + "recipe_ingredients_amount_positive": { + "name": "recipe_ingredients_amount_positive", + "value": "\"project2\".\"recipe_ingredients\".\"amount\" > 0 AND \"project2\".\"recipe_ingredients\".\"amount\" <> 'NaN'::numeric" + }, + "recipe_ingredients_position_positive": { + "name": "recipe_ingredients_position_positive", + "value": "\"project2\".\"recipe_ingredients\".\"position\" > 0" + } + }, + "isRLSEnabled": false + }, + "project2.recipe_instructions": { + "name": "recipe_instructions", + "schema": "project2", + "columns": { + "id": { + "name": "id", + "type": "uuid", + "primaryKey": true, + "notNull": true, + "default": "gen_random_uuid()" + }, + "recipe_id": { + "name": "recipe_id", + "type": "uuid", + "primaryKey": false, + "notNull": true + }, + "text": { + "name": "text", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "position": { + "name": "position", + "type": "integer", + "primaryKey": false, + "notNull": true + } + }, + "indexes": { + "recipe_instructions_recipe_position_unique": { + "name": "recipe_instructions_recipe_position_unique", + "columns": [ + { + "expression": "recipe_id", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "position", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": true, + "concurrently": false, + "method": "btree", + "with": {} + } + }, + "foreignKeys": { + "recipe_instructions_recipe_id_recipes_id_fk": { + "name": "recipe_instructions_recipe_id_recipes_id_fk", + "tableFrom": "recipe_instructions", + "tableTo": "recipes", + "schemaTo": "project2", + "columnsFrom": ["recipe_id"], + "columnsTo": ["id"], + "onDelete": "cascade", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "policies": {}, + "checkConstraints": { + "recipe_instructions_text_not_blank": { + "name": "recipe_instructions_text_not_blank", + "value": "length(trim(\"project2\".\"recipe_instructions\".\"text\")) > 0" + }, + "recipe_instructions_position_positive": { + "name": "recipe_instructions_position_positive", + "value": "\"project2\".\"recipe_instructions\".\"position\" > 0" + } + }, + "isRLSEnabled": false + }, + "project2.recipe_tags": { + "name": "recipe_tags", + "schema": "project2", + "columns": { + "recipe_id": { + "name": "recipe_id", + "type": "uuid", + "primaryKey": false, + "notNull": true + }, + "tag": { + "name": "tag", + "type": "text", + "primaryKey": false, + "notNull": true + } + }, + "indexes": {}, + "foreignKeys": { + "recipe_tags_recipe_id_recipes_id_fk": { + "name": "recipe_tags_recipe_id_recipes_id_fk", + "tableFrom": "recipe_tags", + "tableTo": "recipes", + "schemaTo": "project2", + "columnsFrom": ["recipe_id"], + "columnsTo": ["id"], + "onDelete": "cascade", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": { + "recipe_tags_recipe_id_tag_pk": { + "name": "recipe_tags_recipe_id_tag_pk", + "columns": ["recipe_id", "tag"] + } + }, + "uniqueConstraints": {}, + "policies": {}, + "checkConstraints": { + "recipe_tags_normalized": { + "name": "recipe_tags_normalized", + "value": "length(\"project2\".\"recipe_tags\".\"tag\") > 0 AND \"project2\".\"recipe_tags\".\"tag\" = lower(trim(\"project2\".\"recipe_tags\".\"tag\"))" + } + }, + "isRLSEnabled": false + }, + "project2.recipes": { + "name": "recipes", + "schema": "project2", + "columns": { + "id": { + "name": "id", + "type": "uuid", + "primaryKey": true, + "notNull": true, + "default": "gen_random_uuid()" + }, + "author_id": { + "name": "author_id", + "type": "uuid", + "primaryKey": false, + "notNull": true + }, + "source_recipe_id": { + "name": "source_recipe_id", + "type": "uuid", + "primaryKey": false, + "notNull": false + }, + "title": { + "name": "title", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "description": { + "name": "description", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "image_url": { + "name": "image_url", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "category": { + "name": "category", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "cuisine": { + "name": "cuisine", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "difficulty": { + "name": "difficulty", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "visibility": { + "name": "visibility", + "type": "text", + "primaryKey": false, + "notNull": true, + "default": "'private'" + }, + "prep_minutes": { + "name": "prep_minutes", + "type": "integer", + "primaryKey": false, + "notNull": true + }, + "cook_minutes": { + "name": "cook_minutes", + "type": "integer", + "primaryKey": false, + "notNull": true + }, + "servings": { + "name": "servings", + "type": "integer", + "primaryKey": false, + "notNull": true + }, + "created_at": { + "name": "created_at", + "type": "timestamp with time zone", + "primaryKey": false, + "notNull": true, + "default": "now()" + }, + "updated_at": { + "name": "updated_at", + "type": "timestamp with time zone", + "primaryKey": false, + "notNull": true, + "default": "now()" + } + }, + "indexes": { + "recipes_author_idx": { + "name": "recipes_author_idx", + "columns": [ + { + "expression": "author_id", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + }, + "recipes_source_idx": { + "name": "recipes_source_idx", + "columns": [ + { + "expression": "source_recipe_id", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + }, + "recipes_public_created_idx": { + "name": "recipes_public_created_idx", + "columns": [ + { + "expression": "created_at", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "id", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "where": "\"project2\".\"recipes\".\"visibility\" = 'public'", + "concurrently": false, + "method": "btree", + "with": {} + } + }, + "foreignKeys": { + "recipes_author_id_users_id_fk": { + "name": "recipes_author_id_users_id_fk", + "tableFrom": "recipes", + "tableTo": "users", + "schemaTo": "project2", + "columnsFrom": ["author_id"], + "columnsTo": ["id"], + "onDelete": "cascade", + "onUpdate": "no action" + }, + "recipes_source_recipe_id_recipes_id_fk": { + "name": "recipes_source_recipe_id_recipes_id_fk", + "tableFrom": "recipes", + "tableTo": "recipes", + "schemaTo": "project2", + "columnsFrom": ["source_recipe_id"], + "columnsTo": ["id"], + "onDelete": "set null", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "policies": {}, + "checkConstraints": { + "recipes_title_not_blank": { + "name": "recipes_title_not_blank", + "value": "length(trim(\"project2\".\"recipes\".\"title\")) > 0" + }, + "recipes_category_valid": { + "name": "recipes_category_valid", + "value": "\"project2\".\"recipes\".\"category\" IN ('breakfast', 'lunch', 'dinner', 'dessert', 'soup')" + }, + "recipes_cuisine_not_blank": { + "name": "recipes_cuisine_not_blank", + "value": "length(trim(\"project2\".\"recipes\".\"cuisine\")) > 0" + }, + "recipes_difficulty_valid": { + "name": "recipes_difficulty_valid", + "value": "\"project2\".\"recipes\".\"difficulty\" IN ('easy', 'medium', 'hard')" + }, + "recipes_visibility_valid": { + "name": "recipes_visibility_valid", + "value": "\"project2\".\"recipes\".\"visibility\" IN ('public', 'private')" + }, + "recipes_prep_minutes_nonnegative": { + "name": "recipes_prep_minutes_nonnegative", + "value": "\"project2\".\"recipes\".\"prep_minutes\" >= 0" + }, + "recipes_cook_minutes_nonnegative": { + "name": "recipes_cook_minutes_nonnegative", + "value": "\"project2\".\"recipes\".\"cook_minutes\" >= 0" + }, + "recipes_servings_positive": { + "name": "recipes_servings_positive", + "value": "\"project2\".\"recipes\".\"servings\" > 0" + } + }, + "isRLSEnabled": false + }, + "project2.saved_recipes": { + "name": "saved_recipes", + "schema": "project2", + "columns": { + "user_id": { + "name": "user_id", + "type": "uuid", + "primaryKey": false, + "notNull": true + }, + "recipe_id": { + "name": "recipe_id", + "type": "uuid", + "primaryKey": false, + "notNull": true + }, + "created_at": { + "name": "created_at", + "type": "timestamp with time zone", + "primaryKey": false, + "notNull": true, + "default": "now()" + } + }, + "indexes": { + "saved_recipes_recipe_idx": { + "name": "saved_recipes_recipe_idx", + "columns": [ + { + "expression": "recipe_id", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + } + }, + "foreignKeys": { + "saved_recipes_user_id_users_id_fk": { + "name": "saved_recipes_user_id_users_id_fk", + "tableFrom": "saved_recipes", + "tableTo": "users", + "schemaTo": "project2", + "columnsFrom": ["user_id"], + "columnsTo": ["id"], + "onDelete": "cascade", + "onUpdate": "no action" + }, + "saved_recipes_recipe_id_recipes_id_fk": { + "name": "saved_recipes_recipe_id_recipes_id_fk", + "tableFrom": "saved_recipes", + "tableTo": "recipes", + "schemaTo": "project2", + "columnsFrom": ["recipe_id"], + "columnsTo": ["id"], + "onDelete": "cascade", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": { + "saved_recipes_user_id_recipe_id_pk": { + "name": "saved_recipes_user_id_recipe_id_pk", + "columns": ["user_id", "recipe_id"] + } + }, + "uniqueConstraints": {}, + "policies": {}, + "checkConstraints": {}, + "isRLSEnabled": false + }, + "project2.sessions": { + "name": "sessions", + "schema": "project2", + "columns": { + "id": { + "name": "id", + "type": "uuid", + "primaryKey": true, + "notNull": true, + "default": "gen_random_uuid()" + }, + "user_id": { + "name": "user_id", + "type": "uuid", + "primaryKey": false, + "notNull": true + }, + "expires_at": { + "name": "expires_at", + "type": "timestamp with time zone", + "primaryKey": false, + "notNull": true + } + }, + "indexes": {}, + "foreignKeys": { + "sessions_user_id_users_id_fk": { + "name": "sessions_user_id_users_id_fk", + "tableFrom": "sessions", + "tableTo": "users", + "schemaTo": "project2", + "columnsFrom": ["user_id"], + "columnsTo": ["id"], + "onDelete": "cascade", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "policies": {}, + "checkConstraints": {}, + "isRLSEnabled": false + }, + "project2.users": { + "name": "users", + "schema": "project2", + "columns": { + "id": { + "name": "id", + "type": "uuid", + "primaryKey": true, + "notNull": true, + "default": "gen_random_uuid()" + }, + "name": { + "name": "name", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "email": { + "name": "email", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "password_hash": { + "name": "password_hash", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "created_at": { + "name": "created_at", + "type": "timestamp with time zone", + "primaryKey": false, + "notNull": true, + "default": "now()" + } + }, + "indexes": { + "users_email_unique": { + "name": "users_email_unique", + "columns": [ + { + "expression": "email", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": true, + "concurrently": false, + "method": "btree", + "with": {} + } + }, + "foreignKeys": {}, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "policies": {}, + "checkConstraints": {}, + "isRLSEnabled": false + } + }, + "enums": {}, + "schemas": {}, + "sequences": {}, + "roles": {}, + "policies": {}, + "views": {}, + "_meta": { + "columns": {}, + "schemas": {}, + "tables": {} + } +} diff --git a/apps/api/migrations/meta/_journal.json b/apps/api/migrations/meta/_journal.json index ebc2b8a..4d08ec8 100644 --- a/apps/api/migrations/meta/_journal.json +++ b/apps/api/migrations/meta/_journal.json @@ -15,6 +15,20 @@ "when": 1791418622259, "tag": "0001_familiar_shocker", "breakpoints": true + }, + { + "idx": 2, + "version": "7", + "when": 1791729925525, + "tag": "0002_recipe_model", + "breakpoints": true + }, + { + "idx": 3, + "version": "7", + "when": 1791796199161, + "tag": "0003_recipe_review", + "breakpoints": true } ] } diff --git a/apps/api/package.json b/apps/api/package.json index 8755d13..2f379ff 100644 --- a/apps/api/package.json +++ b/apps/api/package.json @@ -4,7 +4,7 @@ "type": "module", "scripts": { "dev": "tsx watch --env-file-if-exists=../../.env src/server.ts", - "build": "tsc && cp src/schema.graphql dist/schema.graphql", + "build": "tsc && node -e \"require('node:fs').copyFileSync('src/schema.graphql', 'dist/schema.graphql')\"", "start": "node --env-file-if-exists=../../.env dist/server.js" }, "dependencies": { diff --git a/apps/api/src/db/migrate.ts b/apps/api/src/db/migrate.ts index 9f29dfd..1491bbb 100644 --- a/apps/api/src/db/migrate.ts +++ b/apps/api/src/db/migrate.ts @@ -2,5 +2,10 @@ import { drizzle } from 'drizzle-orm/node-postgres'; import { migrate } from 'drizzle-orm/node-postgres/migrator'; import { db } from './client.js'; -await migrate(drizzle(db), { migrationsFolder: 'apps/api/migrations' }); -await db.end(); +try { + // The original migrations reference project2 without creating it. + await db.query('CREATE SCHEMA IF NOT EXISTS project2'); + await migrate(drizzle(db), { migrationsFolder: 'apps/api/migrations' }); +} finally { + await db.end(); +} diff --git a/apps/api/src/db/schema.ts b/apps/api/src/db/schema.ts index 01f90f1..cc6c5f3 100644 --- a/apps/api/src/db/schema.ts +++ b/apps/api/src/db/schema.ts @@ -1,4 +1,11 @@ +import { sql } from 'drizzle-orm'; import { + type AnyPgColumn, + check, + index, + integer, + numeric, + primaryKey, pgSchema, text, timestamp, @@ -8,11 +15,6 @@ import { const project2 = pgSchema('project2'); -export const recipes = project2.table('recipes', { - id: uuid().primaryKey().defaultRandom(), - title: text().notNull(), -}); - export const users = project2.table( 'users', { @@ -34,3 +36,177 @@ export const sessions = project2.table('sessions', { .references(() => users.id, { onDelete: 'cascade' }), expiresAt: timestamp('expires_at', { withTimezone: true }).notNull(), }); + +// Each recipe belongs to one user. Ingredient and instruction rows belong to +// the recipe and are removed automatically when that recipe is deleted. +export const recipes = project2.table( + 'recipes', + { + id: uuid().primaryKey().defaultRandom(), + authorId: uuid('author_id') + .notNull() + .references(() => users.id, { onDelete: 'cascade' }), + sourceRecipeId: uuid('source_recipe_id').references( + (): AnyPgColumn => recipes.id, + { onDelete: 'set null' }, + ), + title: text().notNull(), + description: text().notNull(), + imageUrl: text('image_url'), + category: text({ + enum: ['breakfast', 'lunch', 'dinner', 'dessert', 'soup'], + }).notNull(), + cuisine: text(), + difficulty: text({ enum: ['easy', 'medium', 'hard'] }).notNull(), + visibility: text({ enum: ['public', 'private'] }) + .notNull() + .default('private'), + prepMinutes: integer('prep_minutes').notNull(), + cookMinutes: integer('cook_minutes').notNull(), + servings: integer().notNull(), + createdAt: timestamp('created_at', { withTimezone: true }) + .defaultNow() + .notNull(), + updatedAt: timestamp('updated_at', { withTimezone: true }) + .defaultNow() + .notNull(), + }, + (table) => [ + index('recipes_author_idx').on(table.authorId), + index('recipes_source_idx').on(table.sourceRecipeId), + index('recipes_public_created_idx') + .on(table.createdAt, table.id) + .where(sql`${table.visibility} = 'public'`), + check('recipes_title_not_blank', sql`length(trim(${table.title})) > 0`), + check( + 'recipes_category_valid', + sql`${table.category} IN ('breakfast', 'lunch', 'dinner', 'dessert', 'soup')`, + ), + check('recipes_cuisine_not_blank', sql`length(trim(${table.cuisine})) > 0`), + check( + 'recipes_difficulty_valid', + sql`${table.difficulty} IN ('easy', 'medium', 'hard')`, + ), + check( + 'recipes_visibility_valid', + sql`${table.visibility} IN ('public', 'private')`, + ), + check('recipes_prep_minutes_nonnegative', sql`${table.prepMinutes} >= 0`), + check('recipes_cook_minutes_nonnegative', sql`${table.cookMinutes} >= 0`), + check('recipes_servings_positive', sql`${table.servings} > 0`), + ], +); + +export const recipeIngredients = project2.table( + 'recipe_ingredients', + { + id: uuid().primaryKey().defaultRandom(), + recipeId: uuid('recipe_id') + .notNull() + .references(() => recipes.id, { onDelete: 'cascade' }), + name: text().notNull(), + // PostgreSQL numeric preserves decimal quantities; Drizzle returns strings. + amount: numeric({ precision: 12, scale: 4 }).notNull(), + unit: text().notNull(), + note: text(), + position: integer().notNull(), + }, + (table) => [ + uniqueIndex('recipe_ingredients_recipe_position_unique').on( + table.recipeId, + table.position, + ), + check( + 'recipe_ingredients_name_not_blank', + sql`length(trim(${table.name})) > 0`, + ), + check( + 'recipe_ingredients_amount_positive', + sql`${table.amount} > 0 AND ${table.amount} <> 'NaN'::numeric`, + ), + check('recipe_ingredients_position_positive', sql`${table.position} > 0`), + ], +); + +export const recipeInstructions = project2.table( + 'recipe_instructions', + { + id: uuid().primaryKey().defaultRandom(), + recipeId: uuid('recipe_id') + .notNull() + .references(() => recipes.id, { onDelete: 'cascade' }), + text: text().notNull(), + position: integer().notNull(), + }, + (table) => [ + uniqueIndex('recipe_instructions_recipe_position_unique').on( + table.recipeId, + table.position, + ), + check( + 'recipe_instructions_text_not_blank', + sql`length(trim(${table.text})) > 0`, + ), + check('recipe_instructions_position_positive', sql`${table.position} > 0`), + ], +); + +export const recipeTags = project2.table( + 'recipe_tags', + { + recipeId: uuid('recipe_id') + .notNull() + .references(() => recipes.id, { onDelete: 'cascade' }), + tag: text().notNull(), + }, + (table) => [ + primaryKey({ columns: [table.recipeId, table.tag] }), + check( + 'recipe_tags_normalized', + sql`length(${table.tag}) > 0 AND ${table.tag} = lower(trim(${table.tag}))`, + ), + ], +); + +export const savedRecipes = project2.table( + 'saved_recipes', + { + userId: uuid('user_id') + .notNull() + .references(() => users.id, { onDelete: 'cascade' }), + recipeId: uuid('recipe_id') + .notNull() + .references(() => recipes.id, { onDelete: 'cascade' }), + createdAt: timestamp('created_at', { withTimezone: true }) + .defaultNow() + .notNull(), + }, + (table) => [ + primaryKey({ columns: [table.userId, table.recipeId] }), + index('saved_recipes_recipe_idx').on(table.recipeId), + ], +); + +export const ratings = project2.table( + 'ratings', + { + userId: uuid('user_id') + .notNull() + .references(() => users.id, { onDelete: 'cascade' }), + recipeId: uuid('recipe_id') + .notNull() + .references(() => recipes.id, { onDelete: 'cascade' }), + score: integer().notNull(), + createdAt: timestamp('created_at', { withTimezone: true }) + .defaultNow() + .notNull(), + updatedAt: timestamp('updated_at', { withTimezone: true }) + .defaultNow() + .notNull(), + }, + (table) => [ + primaryKey({ columns: [table.userId, table.recipeId] }), + index('ratings_recipe_idx').on(table.recipeId), + check('ratings_score_valid', sql`${table.score} BETWEEN 1 AND 5`), + ], +); diff --git a/docs/database-model.md b/docs/database-model.md new file mode 100644 index 0000000..f90830d --- /dev/null +++ b/docs/database-model.md @@ -0,0 +1,123 @@ +# Databasemodell + +Modellen bruker PostgreSQL og Drizzle i skjemaet `project2`. Brukere og sesjoner +fra autentiseringen er beholdt. API-operasjoner kommer i neste steg. + +```mermaid +erDiagram + users ||--o{ sessions : har + users ||--o{ recipes : eier + recipes |o--o{ recipes : kopiert_fra + recipes ||--o{ recipe_ingredients : inneholder + recipes ||--o{ recipe_instructions : inneholder + recipes ||--o{ recipe_tags : har + users ||--o{ saved_recipes : lagrer + recipes ||--o{ saved_recipes : lagres + users ||--o{ ratings : vurderer + recipes ||--o{ ratings : vurderes +``` + +`||--o{` betyr at én rad kan ha null eller flere tilknyttede rader. + +| Tabell | Innhold og regler | +| --------------------- | ----------------------------------------------------------------------------------------------------------------------- | +| `users` | Eksisterende brukere med unik e-post og passordhash. | +| `sessions` | Eksisterende innloggingssesjoner med bruker og utløpstid. | +| `recipes` | Forfatter, tittel, beskrivelse, bilde-URL, kategori, kjøkken, vanskelighetsgrad, synlighet, tider, porsjoner og datoer. | +| `recipe_ingredients` | Navn, mengde, enhet, valgfri merknad og rekkefølge i oppskriften. | +| `recipe_instructions` | Tekst og rekkefølge for hvert steg. | +| `recipe_tags` | Enkle tagger per oppskrift, uten duplikater. | +| `saved_recipes` | Hvilke brukere som har lagret hvilke oppskrifter. | +| `ratings` | Én vurdering mellom 1 og 5 per bruker per oppskrift. | + +## Viktige valg + +- `recipes.author_id` peker på `users.id`. Oppskrifter er private som standard. +- Vanskelighetsgrad er `easy`, `medium` eller `hard`; synlighet er `public` eller + `private`. Både TypeScript og databasekontroller begrenser verdiene. +- Kategori bruker faste nøkler: `breakfast`, `lunch`, `dinner`, `dessert`, `soup`. + En databasekontroll avviser andre verdier; klienten viser lesbare etiketter. +- `cuisine` er valgfri fritekst (`NULL` når ukjent); oppgitt tekst må være ikke-tom. +- `source_recipe_id` er en valgfri henvisning til originaloppskriften. Kopier er + egne oppskrifter, uavhengige av bokmerker. Ved sletting av originalen settes + henvisningen til `NULL`, mens kopien beholdes. Varig kildeattribusjon med + lagret forfatternavn/tittel kan legges til senere. +- `image_url` er valgfri. Selve bildefilen lagres ikke i databasen. +- Ingrediensmengder bruker `numeric(12,4)`, som gir nøyaktige desimaltall med + opptil åtte sifre før komma. Drizzle/pg returnerer verdiene som strenger. + API-et må konvertere dem til frontendens tallformat ved behov. +- Mengder og porsjoner må være positive. Tider kan være null, men ikke negative. +- Ingredienser og steg har en unik, positiv `position` innenfor hver oppskrift. + Hent alltid med `ORDER BY position`; databasen krever ikke sammenhengende tall. + Tom ingrediensenhet er tillatt for for eksempel «2 egg». +- Tagger lagres med små bokstaver uten innledende/avsluttende mellomrom. +- Gjennomsnittsvurdering, antall vurderinger og antall lagringer beregnes fra + tabellene. De lagres ikke som ekstra tellere på oppskriften. +- `isSaved` og `isCreatedByCurrentUser` beregnes ut fra innlogget bruker. +- Databasetriggere oppdaterer `updated_at` ved endring av oppskrifter og + vurderinger, også gjennom vanlig SQL. Endring av bare ingredienser, steg eller + tagger må også oppdatere foreldreraden i den senere API-transaksjonen. + +## Sletting og indekser + +Sletting av en oppskrift sletter automatisk ingredienser, steg, tagger, lagringer +og vurderinger. Sletting av en bruker sletter brukerens oppskrifter, sesjoner, +lagringer og vurderinger. Dette er bevisst valgt med `ON DELETE CASCADE`. +Brukersletting bør derfor behandles som en tydelig, destruktiv handling i et +senere API. + +Indekser støtter oppslag etter forfatter, offentlige oppskrifter sortert etter +opprettelsesdato og ID, og lagringer/vurderinger per oppskrift. De sammensatte +primærnøklene støtter brukerens egne lagringer og vurderinger. Unike indekser +støtter ordnede ingredienser og steg. Flere søke- og filterindekser bør velges +etter at API-spørringene finnes og kan måles. + +## Klar for CRUD + +1. **Opprett:** Bruk innlogget bruker som forfatter. Sett inn oppskrift, + ingredienser, steg og tagger i én transaksjon. +2. **Les:** Returner offentlige oppskrifter eller brukerens egne private + oppskrifter. Hent ingredienser/steg i riktig rekkefølge. +3. **Oppdater:** Kontroller eierskap og oppdater hele oppskriften i én transaksjon. + Ved erstatning av ingredienser/steg: slett de gamle radene og sett inn de nye + innenfor samme transaksjon for å unngå midlertidige posisjonskonflikter. +4. **Slett:** Kontroller eierskap før oppskriften slettes. Databasen rydder barna. + +Bruk `INSERT ... ON CONFLICT` for idempotent lagring eller endring av en +vurdering. Bruk `DELETE` for å fjerne lagring/vurdering. API-et må validere tilgang +til oppskriften, og håndheve at eiere ikke vurderer eller lagrer egne oppskrifter. +Fremmednøkler kontrollerer koblinger, ikke hvem som er innlogget. API-et må også +kreve minst én ingrediens og ett steg dersom dette er et produktkrav. + +## Migrasjon og tester + +Kjør fra prosjektroten med `DATABASE_URL` i `.env`: + +```powershell +npm.cmd run db:check +npm.cmd run test:db +npm.cmd run db:migrate +``` + +`test:db` krever lokal PostgreSQL og rettighet til å opprette skjemaer. Den bruker +et tilfeldig skjema i én transaksjon og ruller alt tilbake, inkludert tabellene. +Den endrer ikke `project2` eller migrasjonshistorikken. Testen kontrollerer +migrasjoner, bevaring av auth-data, datakvalitet, unike koblinger, desimaltall, +tidsstempler og automatisk sletting. + +`db:migrate` gjør de faktiske endringene. Migrasjon `0002_recipe_model.sql` +forutsetter at den gamle `recipes`-tabellen med bare ID og tittel er tom. Hvis +den inneholder rader, stopper migrasjonen med en forklarende feil. Ta vare på +dataene og lag en eksplisitt overgang med riktig forfatter og innhold før +migrasjonen kjøres videre; migrasjonen gjetter ikke eierskap eller sletter data. +Eksisterende brukere og sesjoner beholdes. + +Triggere og migrasjonens kontroll av gamle oppskrifter er håndskrevet SQL i +`0002_recipe_model.sql`. Drizzle-snapshotet beskriver tabeller, indekser og +constraints; behold de håndskrevne delene ved senere endringer. + +Migrasjon `0003_recipe_review.sql` gjør kjøkken valgfritt, legger til kildehenvisning +og håndhever kategorinøklene. Eksisterende kategorier normaliseres til små +bokstaver uten ytre mellomrom. Ukjente kategorier stopper migrasjonen og m? +korrigeres eksplisitt. `0002` er beholdt uendret. API-et må kontrollere tilgang +til originalen ved kopiering og kopiere ingredienser/steg i samme transaksjon. diff --git a/package.json b/package.json index eb80514..4c96a1d 100644 --- a/package.json +++ b/package.json @@ -25,7 +25,8 @@ "typecheck": "tsc -p apps/web/tsconfig.json && tsc -p apps/api/tsconfig.json --noEmit", "test": "vitest run --passWithNoTests", "test:e2e": "playwright test", - "check": "npm run format:check && npm run lint && npm run types:check && npm run db:check && npm run typecheck && npm test && npm run build" + "check": "npm run format:check && npm run lint && npm run types:check && npm run db:check && npm run typecheck && npm test && npm run build", + "test:db": "tsx --env-file-if-exists=.env scripts/test-database.ts" }, "devDependencies": { "@eslint/js": "9.39.5", diff --git a/scripts/test-database.ts b/scripts/test-database.ts new file mode 100644 index 0000000..23badab --- /dev/null +++ b/scripts/test-database.ts @@ -0,0 +1,431 @@ +import assert from 'node:assert/strict'; +import { randomUUID } from 'node:crypto'; +import { readFile } from 'node:fs/promises'; +import { test } from 'node:test'; +import { Pool } from 'pg'; + +// Run separately from unit tests: requires PostgreSQL and schema-create rights. +// Every change, including DDL, is rolled back; project2 is never touched. +await test('recipe model against PostgreSQL', async (t) => { + assert.ok( + process.env.DATABASE_URL, + 'Set DATABASE_URL in .env before running test:db.', + ); + const pool = new Pool({ + connectionString: process.env.DATABASE_URL, + connectionTimeoutMillis: 5000, + }); + const client = await pool.connect(); + const schema = 'model_test_' + randomUUID().replaceAll('-', ''); + const table = (name: string) => '"' + schema + '"."' + name + '"'; + const journal = JSON.parse( + await readFile('apps/api/migrations/meta/_journal.json', 'utf8'), + ) as { entries: { tag: string }[] }; + const migrations = await Promise.all( + journal.entries.map(async ({ tag }) => + ( + await readFile('apps/api/migrations/' + tag + '.sql', 'utf8') + ).replaceAll('"project2"', '"' + schema + '"'), + ), + ); + async function rejectsSql(sql: string, values: unknown[], code: string) { + await client.query('SAVEPOINT invalid_write'); + try { + await assert.rejects( + client.query(sql, values), + (error: unknown) => + typeof error === 'object' && + error !== null && + 'code' in error && + error.code === code, + ); + } finally { + await client.query('ROLLBACK TO SAVEPOINT invalid_write'); + await client.query('RELEASE SAVEPOINT invalid_write'); + } + } + try { + await client.query('BEGIN'); + await client.query('CREATE SCHEMA "' + schema + '"'); + for (const migration of migrations.slice(0, 2)) + await client.query(migration); + const users = await client.query<{ id: string }>( + 'INSERT INTO ' + + table('users') + + ' (name, email, password_hash) VALUES ($1,$2,$3),($4,$5,$6) RETURNING id', + [ + 'Author', + 'author@test.local', + 'hash', + 'Reader', + 'reader@test.local', + 'hash', + ], + ); + const authorId = users.rows[0]!.id; + const readerId = users.rows[1]!.id; + await client.query( + 'INSERT INTO ' + + table('sessions') + + ' (user_id, expires_at) VALUES ($1, $2)', + [authorId, new Date(Date.now() + 86400000)], + ); + const recipeMigration = migrations[2]!; + await t.test( + 'legacy recipe data blocks migration without losing auth data', + async () => { + await client.query('SAVEPOINT legacy_data'); + await client.query( + 'INSERT INTO ' + table('recipes') + ' (title) VALUES ($1)', + ['Legacy recipe'], + ); + await assert.rejects( + client.query(recipeMigration), + /empty legacy recipes table/, + ); + await client.query('ROLLBACK TO SAVEPOINT legacy_data'); + await client.query('RELEASE SAVEPOINT legacy_data'); + }, + ); + await t.test( + 'migrations preserve existing users and sessions', + async () => { + await client.query(recipeMigration); + assert.equal( + ( + await client.query( + 'SELECT count(*)::int AS count FROM ' + table('users'), + ) + ).rows[0].count, + 2, + ); + assert.equal( + ( + await client.query( + 'SELECT count(*)::int AS count FROM ' + table('sessions'), + ) + ).rows[0].count, + 1, + ); + }, + ); + await client.query( + 'INSERT INTO ' + + table('recipes') + + ' (author_id,title,description,category,cuisine,difficulty,prep_minutes,cook_minutes,servings) VALUES ($1,$2,$3,$4,$5,$6,$7,$8,$9)', + [authorId, 'Legacy soup', '', ' Soup ', 'Norwegian', 'easy', 0, 10, 1], + ); + await t.test( + 'review migration normalizes existing category labels', + async () => { + for (const migration of migrations.slice(3)) + await client.query(migration); + assert.equal( + (await client.query('SELECT category FROM ' + table('recipes'))) + .rows[0].category, + 'soup', + ); + await client.query('DELETE FROM ' + table('recipes')); + }, + ); + const insertRecipe = + 'INSERT INTO ' + + table('recipes') + + ' (author_id,title,description,category,cuisine,difficulty,prep_minutes,cook_minutes,servings) VALUES ($1,$2,$3,$4,$5,$6,$7,$8,$9) RETURNING id,visibility'; + const recipeValues = [ + authorId, + 'Soup', + 'Simple soup', + 'soup', + 'Norwegian', + 'easy', + 5, + 20, + 4, + ]; + const recipe = ( + await client.query<{ id: string; visibility: string }>( + insertRecipe, + recipeValues, + ) + ).rows[0]!; + const recipeId = recipe.id; + await t.test( + 'recipe defaults to private and rejects invalid fields/author', + async () => { + assert.equal(recipe.visibility, 'private'); + for (const [field, value] of [ + [8, 0], + [6, -1], + [7, -1], + [5, 'impossible'], + [1, ' '], + [3, 'Soup'], + [3, ' dinner '], + [3, 'unknown'], + ] as const) { + const values = [...recipeValues]; + values[field] = value; + await rejectsSql(insertRecipe, values, '23514'); + } + await rejectsSql( + insertRecipe, + [randomUUID(), ...recipeValues.slice(1)], + '23503', + ); + await rejectsSql( + 'UPDATE ' + table('recipes') + ' SET visibility=$1 WHERE id=$2', + ['invalid', recipeId], + '23514', + ); + }, + ); + await t.test('optional cuisine and canonical categories', async () => { + await client.query('SAVEPOINT optional_fields'); + for (const category of [ + 'breakfast', + 'lunch', + 'dinner', + 'dessert', + 'soup', + ]) { + const values: unknown[] = [...recipeValues]; + values[3] = category; + values[4] = null; + const row = (await client.query(insertRecipe, values)).rows[0]; + assert.equal( + ( + await client.query( + 'SELECT cuisine FROM ' + table('recipes') + ' WHERE id=$1', + [row.id], + ) + ).rows[0].cuisine, + null, + ); + } + await client.query('ROLLBACK TO SAVEPOINT optional_fields'); + await client.query('RELEASE SAVEPOINT optional_fields'); + }); + await t.test('copies survive unsaving and source deletion', async () => { + await client.query('SAVEPOINT copies'); + const sourceId = (await client.query(insertRecipe, recipeValues)).rows[0] + .id; + const copyId = ( + await client.query(insertRecipe, [readerId, ...recipeValues.slice(1)]) + ).rows[0].id; + await client.query( + 'UPDATE ' + table('recipes') + ' SET source_recipe_id=$1 WHERE id=$2', + [sourceId, copyId], + ); + await rejectsSql( + 'UPDATE ' + table('recipes') + ' SET source_recipe_id=$1 WHERE id=$2', + [randomUUID(), copyId], + '23503', + ); + await client.query( + 'INSERT INTO ' + + table('saved_recipes') + + ' (user_id,recipe_id) VALUES ($1,$2)', + [readerId, sourceId], + ); + await client.query( + 'DELETE FROM ' + + table('saved_recipes') + + ' WHERE user_id=$1 AND recipe_id=$2', + [readerId, sourceId], + ); + assert.equal( + ( + await client.query( + 'SELECT source_recipe_id FROM ' + table('recipes') + ' WHERE id=$1', + [copyId], + ) + ).rows[0].source_recipe_id, + sourceId, + ); + await client.query('DELETE FROM ' + table('recipes') + ' WHERE id=$1', [ + sourceId, + ]); + const copy = ( + await client.query( + 'SELECT author_id,source_recipe_id,title FROM ' + + table('recipes') + + ' WHERE id=$1', + [copyId], + ) + ).rows[0]; + assert.equal(copy.author_id, readerId); + assert.equal(copy.source_recipe_id, null); + assert.equal(copy.title, 'Soup'); + await client.query('ROLLBACK TO SAVEPOINT copies'); + await client.query('RELEASE SAVEPOINT copies'); + }); + const ingredientSql = + 'INSERT INTO ' + + table('recipe_ingredients') + + ' (recipe_id,name,amount,unit,position) VALUES ($1,$2,$3,$4,$5)'; + await t.test( + 'decimal amounts and ordered ingredients/instructions', + async () => { + await client.query(ingredientSql, [ + recipeId, + 'Salt', + '0.125', + 'tsp', + 1, + ]); + assert.equal( + ( + await client.query( + 'SELECT amount FROM ' + table('recipe_ingredients'), + ) + ).rows[0].amount, + '0.1250', + ); + await rejectsSql( + ingredientSql, + [recipeId, 'Salt', '1', 'tsp', 1], + '23505', + ); + await rejectsSql( + ingredientSql, + [recipeId, 'Salt', '-1', 'tsp', 2], + '23514', + ); + await rejectsSql( + ingredientSql, + [recipeId, 'Salt', 'NaN', 'tsp', 2], + '23514', + ); + await rejectsSql( + ingredientSql, + [recipeId, 'Salt', '1', 'tsp', 0], + '23514', + ); + const instructionSql = + 'INSERT INTO ' + + table('recipe_instructions') + + ' (recipe_id,text,position) VALUES ($1,$2,$3)'; + await client.query(instructionSql, [recipeId, 'Stir', 1]); + await rejectsSql(instructionSql, [recipeId, 'Stir again', 1], '23505'); + await rejectsSql(instructionSql, [recipeId, ' ', 2], '23514'); + }, + ); + await t.test( + 'unique tags, saves and ratings with valid scores', + async () => { + const tagSql = + 'INSERT INTO ' + + table('recipe_tags') + + ' (recipe_id,tag) VALUES ($1,$2)'; + await client.query(tagSql, [recipeId, 'quick']); + await rejectsSql(tagSql, [recipeId, 'quick'], '23505'); + await rejectsSql(tagSql, [recipeId, ' Quick '], '23514'); + const saveSql = + 'INSERT INTO ' + + table('saved_recipes') + + ' (user_id,recipe_id) VALUES ($1,$2)'; + await client.query(saveSql, [readerId, recipeId]); + await rejectsSql(saveSql, [readerId, recipeId], '23505'); + const ratingSql = + 'INSERT INTO ' + + table('ratings') + + ' (user_id,recipe_id,score) VALUES ($1,$2,$3)'; + await client.query(ratingSql, [readerId, recipeId, 4]); + await rejectsSql(ratingSql, [readerId, recipeId, 5], '23505'); + await rejectsSql(ratingSql, [authorId, recipeId, 0], '23514'); + await rejectsSql(ratingSql, [authorId, recipeId, 6], '23514'); + }, + ); + await t.test( + 'updates touch timestamps through SQL and ratings can be changed', + async () => { + for (const name of ['recipes', 'ratings']) { + await client.query('UPDATE ' + table(name) + ' SET updated_at=$1', [ + '2000-01-01', + ]); + assert.ok( + ( + await client.query('SELECT updated_at FROM ' + table(name)) + ).rows[0].updated_at.getFullYear() > 2000, + ); + } + await client.query( + 'UPDATE ' + + table('ratings') + + ' SET score=5 WHERE user_id=$1 AND recipe_id=$2', + [readerId, recipeId], + ); + assert.equal( + ( + await client.query( + 'SELECT avg(score)::float AS average FROM ' + table('ratings'), + ) + ).rows[0].average, + 5, + ); + }, + ); + await t.test( + 'recipe deletion cascades to dependent rows, preserving users', + async () => { + await client.query('DELETE FROM ' + table('recipes') + ' WHERE id=$1', [ + recipeId, + ]); + for (const name of [ + 'recipe_ingredients', + 'recipe_instructions', + 'recipe_tags', + 'saved_recipes', + 'ratings', + ]) { + assert.equal( + ( + await client.query( + 'SELECT count(*)::int AS count FROM ' + table(name), + ) + ).rows[0].count, + 0, + ); + } + assert.equal( + ( + await client.query( + 'SELECT count(*)::int AS count FROM ' + table('users'), + ) + ).rows[0].count, + 2, + ); + }, + ); + await t.test( + 'user deletion removes owned recipes and sessions', + async () => { + await client.query(insertRecipe, recipeValues); + await client.query('DELETE FROM ' + table('users') + ' WHERE id=$1', [ + authorId, + ]); + assert.equal( + ( + await client.query( + 'SELECT count(*)::int AS count FROM ' + table('recipes'), + ) + ).rows[0].count, + 0, + ); + assert.equal( + ( + await client.query( + 'SELECT count(*)::int AS count FROM ' + table('sessions'), + ) + ).rows[0].count, + 0, + ); + }, + ); + } finally { + await client.query('ROLLBACK'); + client.release(); + await pool.end(); + } +});