+---------- nodegroups table - start
+-- nodegroup_id is preserved for conf_files and other references
+-- former nodegroups table was (nodegroup_id,name,description)
+-- new table is now (nodegroup_id, groupname, tag_type_id, tagvalue)
+
+-- rename column
+ALTER TABLE nodegroups RENAME name TO groupname;
+
+---------- create missing tag types
+-- change default for the entries about to be created
+ALTER TABLE tag_types ALTER COLUMN category SET DEFAULT 'nodegroup/migration';
+
+-- do it
+INSERT INTO tag_types (tagname)
+ SELECT DISTINCT tagname FROM mgn_site_nodegroup
+ WHERE tagname NOT IN (SELECT tagname from tag_types);
+
+-- xxx drop description in former nodegroups for now, could be attached to newly created tag types..
+ALTER TABLE nodegroups DROP COLUMN description;
+
+---------- set the right tags so as to recover former nodegroups
+INSERT INTO node_tag (node_id, tag_type_id, tagvalue)
+ SELECT node_id, tag_type_id, tagvalue FROM
+ nodegroup_node LEFT JOIN nodegroups USING (nodegroup_id)
+ INNER JOIN mgn_site_nodegroup USING (groupname)
+ LEFT JOIN tag_types using (tagname);
+
+---------- nodegroups table - conclusion
+ALTER TABLE nodegroups ADD COLUMN tag_type_id INTEGER;
+ALTER TABLE nodegroups ADD COLUMN tagvalue TEXT;
+
+CREATE OR REPLACE VIEW mgn_nodegroups AS
+ SELECT groupname, tag_types.tag_type_id, mgn_site_nodegroup.tagvalue
+ FROM nodegroups INNER JOIN mgn_site_nodegroup USING (groupname)
+ INNER JOIN tag_types USING (tagname);
+
+UPDATE nodegroups SET tag_type_id = (SELECT tag_type_id FROM mgn_nodegroups WHERE nodegroups.groupname=mgn_nodegroups.groupname);
+UPDATE nodegroups SET tagvalue = (SELECT tagvalue FROM mgn_nodegroups WHERE nodegroups.groupname=mgn_nodegroups.groupname);
+
+-- install corresponding constraints
+ALTER TABLE nodegroups ADD CONSTRAINT nodegroups_tag_type_id_fkey
+ FOREIGN KEY (tag_type_id) REFERENCES tag_types (tag_type_id);