refactor(schema): invert relationship between items and recipes
Move item_id to recipes table and drop recipe_id from items Update backend queries and admin UI to reflect the new domain model
This commit is contained in:
@@ -48,23 +48,11 @@ CREATE TABLE IF NOT EXISTS acquisition_methods (
|
||||
name text NOT NULL UNIQUE
|
||||
);
|
||||
|
||||
CREATE TABLE IF NOT EXISTS recipes (
|
||||
id integer GENERATED BY DEFAULT AS IDENTITY PRIMARY KEY,
|
||||
name text NOT NULL UNIQUE
|
||||
);
|
||||
|
||||
CREATE TABLE IF NOT EXISTS recipe_acquisition_methods (
|
||||
recipe_id integer NOT NULL REFERENCES recipes(id) ON DELETE CASCADE,
|
||||
acquisition_method_id integer NOT NULL REFERENCES acquisition_methods(id),
|
||||
PRIMARY KEY (recipe_id, acquisition_method_id)
|
||||
);
|
||||
|
||||
CREATE TABLE IF NOT EXISTS items (
|
||||
id integer GENERATED BY DEFAULT AS IDENTITY PRIMARY KEY,
|
||||
name text NOT NULL UNIQUE,
|
||||
category_id integer NOT NULL REFERENCES item_categories(id),
|
||||
usage_id integer REFERENCES item_usages(id),
|
||||
recipe_id integer REFERENCES recipes(id),
|
||||
dyeable boolean NOT NULL DEFAULT false,
|
||||
dual_dyeable boolean NOT NULL DEFAULT false,
|
||||
pattern_editable boolean NOT NULL DEFAULT false
|
||||
@@ -72,6 +60,49 @@ CREATE TABLE IF NOT EXISTS items (
|
||||
|
||||
ALTER TABLE items ALTER COLUMN usage_id DROP NOT NULL;
|
||||
|
||||
CREATE TABLE IF NOT EXISTS recipes (
|
||||
id integer GENERATED BY DEFAULT AS IDENTITY PRIMARY KEY,
|
||||
item_id integer NOT NULL UNIQUE REFERENCES items(id)
|
||||
);
|
||||
|
||||
ALTER TABLE recipes ADD COLUMN IF NOT EXISTS item_id integer REFERENCES items(id);
|
||||
|
||||
DO $$
|
||||
BEGIN
|
||||
IF EXISTS (
|
||||
SELECT 1
|
||||
FROM information_schema.columns
|
||||
WHERE table_name = 'items'
|
||||
AND column_name = 'recipe_id'
|
||||
) THEN
|
||||
EXECUTE '
|
||||
UPDATE recipes r
|
||||
SET item_id = linked.item_id
|
||||
FROM (
|
||||
SELECT DISTINCT ON (recipe_id) recipe_id, id AS item_id
|
||||
FROM items
|
||||
WHERE recipe_id IS NOT NULL
|
||||
ORDER BY recipe_id, id
|
||||
) linked
|
||||
WHERE r.id = linked.recipe_id
|
||||
AND r.item_id IS NULL
|
||||
';
|
||||
END IF;
|
||||
END $$;
|
||||
|
||||
DELETE FROM recipes WHERE item_id IS NULL;
|
||||
|
||||
ALTER TABLE recipes ALTER COLUMN item_id SET NOT NULL;
|
||||
CREATE UNIQUE INDEX IF NOT EXISTS recipes_item_id_key ON recipes(item_id);
|
||||
ALTER TABLE recipes DROP COLUMN IF EXISTS name;
|
||||
ALTER TABLE items DROP COLUMN IF EXISTS recipe_id;
|
||||
|
||||
CREATE TABLE IF NOT EXISTS recipe_acquisition_methods (
|
||||
recipe_id integer NOT NULL REFERENCES recipes(id) ON DELETE CASCADE,
|
||||
acquisition_method_id integer NOT NULL REFERENCES acquisition_methods(id),
|
||||
PRIMARY KEY (recipe_id, acquisition_method_id)
|
||||
);
|
||||
|
||||
DROP TABLE IF EXISTS item_item_tags;
|
||||
DROP TABLE IF EXISTS item_tags;
|
||||
|
||||
|
||||
Reference in New Issue
Block a user