



-- This file contains the SQL script to generate the file gmm_migration-generated_insertions.sql.
-- The file gmm_migration-generated_insertions.sql contains the INSERTIONS lines to run to initialize all the _aud tables (CLIENT or SERVER side)


-- To obtain the insertions lines (written in the file gmm_migration-generated_insertions.sql), please perform the following steps :
--     - Run this gmm_migration-script_to_generate_insertions.sql script
-- From the generated lines : 
--     - Remove the id information for all the generated lines of the CROSS tables (because CROSS table has no id column, ie : tm_test_test_steps_aud )
--     - Change "method_id" and "paramater_id" columns by "id" for the tables tm_object_xxx (because the id columns are called 'method_id' or 'parameter_id' in object tables)
--     - Remove profile_content and gazelle_language_id of the attributes (because they are not audited)
--     - Execute : "update tm_test_type_aud set revtype = 0 ;" (if it is not done, because entries were like id=1, rev=1, revtype=1, so it was impossible to create entries id=1, rev=1, revtype=0 because of the constraints)


-- FUNCTIONS :
 create language plpgsql ;

DROP  FUNCTION fill_aud_missing_data ( text) ; -- tablename 
CREATE FUNCTION fill_aud_missing_data ( text)  RETURNS text AS $$ 
DECLARE
  command text ;
BEGIN
SELECT INTO command 'insert into ' || $1 ||'_aud (rev,revtype, '|| list(a.attname) || ') SELECT  1 as rev , 0 as revtype, ' || list(a.attname) || ' from ' || $1 ||' where id not in  (select ipo.id from ' || $1 ||' ipo, ' || $1 ||'_aud ipoa where ipo.id = ipoa.id and ipoa.revtype = 0);' FROM pg_catalog.pg_attribute a WHERE a.attnum > 0 AND a.attisdropped='f' AND a.attrelid =(SELECT c.oid FROM pg_catalog.pg_class c 
LEFT JOIN pg_catalog.pg_namespace n ON n.oid=c.relnamespace WHERE  
pg_catalog.pg_table_is_visible(c.oid) and c.relname = $1);
RETURN command ;
END;
$$ 
LANGUAGE plpgsql;


SELECT fill_aud_missing_data(replace(tablename, '_aud', '') ) from pg_catalog.pg_tables where tablename like '%_aud' ;
