+CREATE OR REPLACE VIEW _word_tree AS
+ WITH RECURSIVE r AS (
+ SELECT w.ref, w.lang, w.cat, w.grade, w.form, NULL::int trans
+ FROM _word_ref w
+ UNION ALL
+ SELECT r.ref, r.lang, w.cat,
+ CASE WHEN w.lang=r.lang OR t.lang=r.lang THEN r.grade ELSE w.grade END,
+ CASE WHEN w.lang=r.lang OR t.lang=r.lang THEN r.form ELSE w.form END,
+ CASE WHEN w.lang=r.lang OR t.lang=r.lang THEN w.id END
+ FROM r JOIN word w ON w.id = r.cat
+ LEFT JOIN word t ON w.id = t.ref AND t.lang = r.lang
+ WHERE r.trans IS NULL
+ )
+ SELECT ref, lang, trans cat, grade, form FROM r WHERE trans IS NOT NULL
+ ORDER BY cat, grade, form, ref;
+
+CREATE OR REPLACE VIEW _word AS
+ SELECT
+ (SELECT array_agg(coalesce(ref, id)) FROM _word_tree
+ WHERE cat = w.ref AND lang = w.lang) sub,
+ w.*
+ FROM _word_ref w
+ ;
+