Files
food-ai/backend/migrations/014_create_units.sql
dbastrikin 55d01400b0 feat: dynamic units table with localized names via GET /units
- Add units + unit_translations tables with FK constraints on products and ingredient_mappings
- Normalize products.unit from Russian strings (г, кг) to English codes (g, kg)
- Load units at startup (in-memory registry) and serve via GET /units (language-aware)
- Replace hardcoded _units lists and _mapUnit() functions in Flutter with unitsProvider FutureProvider
- Re-fetches automatically when language changes

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-03-15 16:15:33 +02:00

59 lines
1.9 KiB
SQL
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
-- +goose Up
CREATE TABLE units (
code VARCHAR(20) PRIMARY KEY,
sort_order SMALLINT NOT NULL DEFAULT 0
);
INSERT INTO units (code, sort_order) VALUES
('g', 1),
('kg', 2),
('ml', 3),
('l', 4),
('pcs', 5),
('pack', 6);
CREATE TABLE unit_translations (
unit_code VARCHAR(20) NOT NULL REFERENCES units(code) ON DELETE CASCADE,
lang VARCHAR(10) NOT NULL,
name TEXT NOT NULL,
PRIMARY KEY (unit_code, lang)
);
INSERT INTO unit_translations (unit_code, lang, name) VALUES
('g', 'ru', 'г'),
('kg', 'ru', 'кг'),
('ml', 'ru', 'мл'),
('l', 'ru', 'л'),
('pcs', 'ru', 'шт'),
('pack', 'ru', 'уп');
-- Normalize products.unit from Russian display strings to English codes
UPDATE products SET unit = 'g' WHERE unit = 'г';
UPDATE products SET unit = 'kg' WHERE unit = 'кг';
UPDATE products SET unit = 'ml' WHERE unit = 'мл';
UPDATE products SET unit = 'l' WHERE unit = 'л';
UPDATE products SET unit = 'pcs' WHERE unit = 'шт';
UPDATE products SET unit = 'pack' WHERE unit = 'уп';
-- Normalize any remaining unknown values
UPDATE products SET unit = 'pcs' WHERE unit NOT IN (SELECT code FROM units);
-- Nullify unknown default_unit values in ingredient_mappings before adding FK
UPDATE ingredient_mappings
SET default_unit = NULL
WHERE default_unit IS NOT NULL
AND default_unit NOT IN (SELECT code FROM units);
-- Foreign key constraints
ALTER TABLE products
ADD CONSTRAINT fk_product_unit
FOREIGN KEY (unit) REFERENCES units(code);
ALTER TABLE ingredient_mappings
ADD CONSTRAINT fk_default_unit
FOREIGN KEY (default_unit) REFERENCES units(code);
-- +goose Down
ALTER TABLE ingredient_mappings DROP CONSTRAINT IF EXISTS fk_default_unit;
ALTER TABLE products DROP CONSTRAINT IF EXISTS fk_product_unit;
DROP TABLE IF EXISTS unit_translations;
DROP TABLE IF EXISTS units;