PGDMP   w cmdbuild_48419.6.1511.5d00ENCODINGENCODINGSET client_encoding = 'UTF8'; false00 STDSTRINGS STDSTRINGS(SET standard_conforming_strings = 'on'; false00 SEARCHPATH SEARCHPATH8SELECT pg_catalog.set_config('search_path', '', false); false1262229969 cmdbuild_4841DATABASECREATE DATABASE cmdbuild_4841 WITH TEMPLATE = template0 ENCODING = 'UTF8' LC_COLLATE = 'en_ZA.UTF-8' LC_CTYPE = 'en_ZA.UTF-8'; DROP DATABASE cmdbuild_4841; postgresfalse00 cmdbuild_4841DATABASE PROPERTIESJALTER DATABASE cmdbuild_4841 SET search_path TO '$user', 'public', 'gis'; postgresfalse4299 2615232730bimSCHEMACREATE SCHEMA bim; DROP SCHEMA bim; postgresfalse 2615248423 connectorSCHEMACREATE SCHEMA connector; DROP SCHEMA connector; postgresfalse 2615229970gisSCHEMACREATE SCHEMA gis; DROP SCHEMA gis; postgresfalse2615248424lldp_connectorSCHEMACREATE SCHEMA lldp_connector; DROP SCHEMA lldp_connector; postgresfalse 2615232729quartzSCHEMACREATE SCHEMA quartz; DROP SCHEMA quartz; postgresfalse 2615231470sharkSCHEMACREATE SCHEMA shark; DROP SCHEMA shark; postgresfalse00 SCHEMA sharkACL$GRANT ALL ON SCHEMA shark TO shark; postgresfalse103079229971postgis EXTENSION8CREATE EXTENSION IF NOT EXISTS postgis WITH SCHEMA gis; DROP EXTENSION postgis; false900EXTENSION postgisCOMMENTgCOMMENT ON EXTENSION postgis IS 'PostGIS geometry, geography, and raster spatial types and functions'; false2 1247232733mapTYPE0CREATE TYPE public.map AS ( k text, v text ); DROP TYPE public.map; publicpostgresfalse1255232734._bim_carddata_from_globalid(character varying)FUNCTIONCREATE FUNCTION public._bim_carddata_from_globalid(globalid character varying, OUT "Id" integer, OUT "IdClass" integer, OUT "Description" character varying, OUT "ClassName" character varying) RETURNS record LANGUAGE plpgsql AS $$ DECLARE query varchar; table_name varchar; tables CURSOR FOR SELECT tablename FROM pg_tables WHERE schemaname = 'bim' ORDER BY tablename; BEGIN query=''; FOR table_record IN tables LOOP query= query || ' SELECT b."Master" as "Id" , p."Description" AS "Description", p."IdClass"::integer as "IdClass" , replace(p."IdClass"::text,''"'','''') as "ClassName" FROM bim."' || table_record.tablename || '" AS b JOIN public."' || table_record.tablename || '" AS p ON b."Master"=p."Id" WHERE p."Status"=''A'' AND b."GlobalId" = ''' || globalid || ''' UNION ALL'; END LOOP; SELECT substring(query from 0 for LENGTH(query)-9) INTO query; RAISE NOTICE 'execute query : %', query; EXECUTE(query) INTO "Id","Description","IdClass","ClassName"; END; $$; DROP FUNCTION public._bim_carddata_from_globalid(globalid character varying, OUT "Id" integer, OUT "IdClass" integer, OUT "Description" character varying, OUT "ClassName" character varying); publicpostgresfalse00FUNCTION _bim_carddata_from_globalid(globalid character varying, OUT "Id" integer, OUT "IdClass" integer, OUT "Description" character varying, OUT "ClassName" character varying)COMMENTCOMMENT ON FUNCTION public._bim_carddata_from_globalid(globalid character varying, OUT "Id" integer, OUT "IdClass" integer, OUT "Description" character varying, OUT "ClassName" character varying) IS 'TYPE: function'; publicpostgresfalse14121255232735M_cm3_attribute_comment_delete(regclass, character varying, character varying)FUNCTIONCREATE FUNCTION public._cm3_attribute_comment_delete(_class regclass, _attr character varying, _key character varying) RETURNS void LANGUAGE sql AS $$ SELECT _cm3_attribute_comment_set(_class, _attr, _cm3_attribute_comment_get(_class, _attr) - _key); $$; vDROP FUNCTION public._cm3_attribute_comment_delete(_class regclass, _attr character varying, _key character varying); publicpostgresfalse12552327367_cm3_attribute_comment_get(regclass, character varying)FUNCTIONCREATE FUNCTION public._cm3_attribute_comment_get(_class regclass, _attr character varying) RETURNS jsonb LANGUAGE sql AS $$ SELECT _cm3_comment_to_jsonb(_cm3_attribute_comment_get_raw(_class, _attr)); $$; [DROP FUNCTION public._cm3_attribute_comment_get(_class regclass, _attr character varying); publicpostgresfalse1255232737J_cm3_attribute_comment_get(regclass, character varying, character varying)FUNCTIONCREATE FUNCTION public._cm3_attribute_comment_get(_class regclass, _attr character varying, _part character varying) RETURNS character varying LANGUAGE sql STABLE AS $$ SELECT coalesce(_cm3_attribute_comment_get(_class,_attr)->>_part,''); $$; tDROP FUNCTION public._cm3_attribute_comment_get(_class regclass, _attr character varying, _part character varying); publicpostgresfalse1255232738;_cm3_attribute_comment_get_raw(regclass, character varying)FUNCTIONnCREATE FUNCTION public._cm3_attribute_comment_get_raw(_class regclass, _attr character varying) RETURNS character varying LANGUAGE sql STABLE AS $$ SELECT description FROM pg_description JOIN pg_attribute ON pg_description.objoid = pg_attribute.attrelid AND pg_description.objsubid = pg_attribute.attnum WHERE attrelid = _class and attname = _attr; $$; _DROP FUNCTION public._cm3_attribute_comment_get_raw(_class regclass, _attr character varying); publicpostgresfalse1255232739_cm3_attribute_comment_keys()FUNCTION8CREATE FUNCTION public._cm3_attribute_comment_keys() RETURNS SETOF character varying LANGUAGE sql IMMUTABLE AS $$ SELECT unnest(ARRAY['DESCR','BASEDSP','CLASSORDER','EDITORTYPE','GROUP','INDEX','LOOKUP','REFERENCEDIR','REFERENCEDOM','FKTARGETCLASS','FILTER','IP_TYPE','ACTIVE','MODE','DOMAINKEY']); $$; 4DROP FUNCTION public._cm3_attribute_comment_keys(); publicpostgresfalse1255232740>_cm3_attribute_comment_set(regclass, character varying, jsonb)FUNCTIONCREATE FUNCTION public._cm3_attribute_comment_set(_class regclass, _attr character varying, _comment jsonb) RETURNS void LANGUAGE plpgsql AS $$ DECLARE _ref_attr int; _key varchar; BEGIN _comment = _cm3_utils_strip_null_or_empty(_comment); FOR _key IN SELECT x FROM jsonb_object_keys(_comment) x WHERE x NOT IN (SELECT _cm3_attribute_comment_keys()) LOOP RAISE WARNING 'CM: invalid comment for class = % attr = %: invalid comment key = %', _class, _attr, _key; END LOOP; _ref_attr = (SELECT count(x) FROM jsonb_object_keys(_comment) x WHERE x IN ('REFERENCEDOM','LOOKUP','FKTARGETCLASS') AND NULLIF(_comment->>x, '') IS NOT NULL ); IF _ref_attr > 1 THEN RAISE EXCEPTION 'CM: invalid comment for class = % attr = %, comment = %: attribute type error (too many attribute type specified)', _class, _attr, _comment; END IF; RAISE NOTICE 'update class attribute comment %.% = %', _class, _attr, _comment; EXECUTE format('COMMENT ON COLUMN %s.%I IS %L', _class, _attr, _cm3_comment_from_jsonb(_comment)); END $$; kDROP FUNCTION public._cm3_attribute_comment_set(_class regclass, _attr character varying, _comment jsonb); publicpostgresfalse1255232741]_cm3_attribute_comment_set(regclass, character varying, character varying, character varying)FUNCTIONCREATE FUNCTION public._cm3_attribute_comment_set(_class regclass, _attr character varying, _key character varying, _value character varying) RETURNS void LANGUAGE sql AS $$ SELECT _cm3_attribute_comment_update(_class, _attr, jsonb_build_object(_key, _value)); $$; DROP FUNCTION public._cm3_attribute_comment_set(_class regclass, _attr character varying, _key character varying, _value character varying); publicpostgresfalse1255232742A_cm3_attribute_comment_update(regclass, character varying, jsonb)FUNCTIONCREATE FUNCTION public._cm3_attribute_comment_update(_class regclass, _attr character varying, _comment jsonb) RETURNS void LANGUAGE plpgsql AS $$ BEGIN PERFORM _cm3_attribute_comment_set(_class, _attr, _cm3_attribute_comment_get(_class, _attr) || _comment); END $$; nDROP FUNCTION public._cm3_attribute_comment_update(_class regclass, _attr character varying, _comment jsonb); publicpostgresfalse12552327434_cm3_attribute_copy_all_comments(regclass, regclass)FUNCTIONXCREATE FUNCTION public._cm3_attribute_copy_all_comments(_source regclass, _target regclass) RETURNS void LANGUAGE plpgsql AS $$ DECLARE _attr varchar; BEGIN FOR _attr IN SELECT * FROM _cm3_attribute_list(_source) LOOP PERFORM _cm3_attribute_comment_set(_target, _attr, _cm3_attribute_comment_get(_source,_attr)); END LOOP; END $$; [DROP FUNCTION public._cm3_attribute_copy_all_comments(_source regclass, _target regclass); publicpostgresfalse1255232744_cm3_attribute_create(jsonb)FUNCTIONCREATE FUNCTION public._cm3_attribute_create(_features jsonb) RETURNS void LANGUAGE plpgsql AS $$ BEGIN PERFORM _cm3_attribute_create(_cm3_utils_name_to_regclass(_features->>'OWNER'), _features->>'NAME', _features - 'OWNER' - 'NAME'); END $$; =DROP FUNCTION public._cm3_attribute_create(_features jsonb); publicpostgresfalse1255232745(_cm3_attribute_create(character varying)FUNCTIONCREATE FUNCTION public._cm3_attribute_create(_features character varying) RETURNS void LANGUAGE plpgsql AS $$ BEGIN PERFORM _cm3_attribute_create(_cm3_comment_to_jsonb(_features)); END $$; IDROP FUNCTION public._cm3_attribute_create(_features character varying); publicpostgresfalse12552327469_cm3_attribute_create(regclass, character varying, jsonb)FUNCTIONCREATE FUNCTION public._cm3_attribute_create(_class regclass, _attr character varying, _features jsonb) RETURNS void LANGUAGE plpgsql AS $$ BEGIN PERFORM _cm3_attribute_create(_class, _attr, _features->>'TYPE', _features - 'TYPE'); END $$; gDROP FUNCTION public._cm3_attribute_create(_class regclass, _attr character varying, _features jsonb); publicpostgresfalse1255232747E_cm3_attribute_create(regclass, character varying, character varying)FUNCTIONCREATE FUNCTION public._cm3_attribute_create(_class regclass, _attr character varying, _features character varying) RETURNS void LANGUAGE plpgsql AS $$ BEGIN PERFORM _cm3_attribute_create(_class, _attr, _cm3_comment_to_jsonb(_features)); END $$; sDROP FUNCTION public._cm3_attribute_create(_class regclass, _attr character varying, _features character varying); publicpostgresfalse1255232748L_cm3_attribute_create(regclass, character varying, character varying, jsonb)FUNCTIONCREATE FUNCTION public._cm3_attribute_create(_class regclass, _attr character varying, _type character varying, _features jsonb) RETURNS void LANGUAGE plpgsql AS $$ DECLARE _not_null boolean; _unique boolean; _default varchar; _fk_target regclass; _sub_class regclass; _domain regclass; _direction varchar; _cardin varchar; _attr_features jsonb; BEGIN RAISE NOTICE 'creating attribute for class = % name = % type = %', _cm3_utils_regclass_to_name(_class), _attr, _type; IF _type = 'timestamp' THEN _type = 'timestamp with time zone'; END IF; _features = _cm3_utils_strip_null_or_empty(_features); -- IF _cm3_class_is_simple(_class) AND _attr IN (SELECT _cm3_attribute_list('"Class"')) THEN -- RAISE 'CM: cannot create attribute with name = %s: reserved name', _attr; -- END IF; _not_null = coalesce(_features->>'NOTNULL','false')::boolean; _unique = coalesce(_features->>'UNIQUE','false')::boolean; _default = _features->>'DEFAULT'; _attr_features = _features - 'NOTNULL' - 'UNIQUE' - 'DEFAULT'; PERFORM _cm3_attribute_validate_features_and_type(_attr_features, _type); -- IF _cm_is_geometry_type(_type) THEN -- TODO -- PERFORM _cm_add_spherical_mercator(); -- PERFORM AddGeometryColumn(_cm_cmschema(_class), _cm_cmtable(_class), _attr, 900913, _type, 2); -- ELSE EXECUTE format('ALTER TABLE %s ADD COLUMN %I %s', _class, _attr, _type); -- END IF; PERFORM _cm3_attribute_default_set(_class, _attr, _default, TRUE); PERFORM _cm3_attribute_features_set(_class, _attr, _attr_features); PERFORM _cm3_class_utils_attribute_groups_fix(_class, _attr); FOR _sub_class IN SELECT _cm3_class_list_descendant_classes(_class) LOOP PERFORM _cm3_attribute_features_set(_sub_class, _attr, _attr_features); PERFORM _cm3_class_utils_attribute_groups_fix(_sub_class, _attr); END LOOP; PERFORM _cm3_attribute_notnull_set(_class, _attr, _not_null); PERFORM _cm3_attribute_unique_set(_class, _attr, _unique); IF _cm3_attribute_is_foreignkey(_class, _attr) OR _cm3_attribute_is_reference(_class, _attr) THEN RAISE NOTICE 'attr is foreignkey or reference: activating fk triggers'; _fk_target = _cm3_attribute_foreignkey_or_reference_target_class_get(_class, _attr); FOR _sub_class IN SELECT _cm3_class_list_descendant_classes_and_self(_class) LOOP IF _cm3_class_is_simple(_sub_class) THEN EXECUTE format('CREATE TRIGGER "_cm3_card_enforce_fk_%s" BEFORE INSERT OR UPDATE ON %s FOR EACH ROW EXECUTE PROCEDURE _cm3_trigger_simplecard_enforce_foreign_key_for_source(%L,%L,%L)', _cm3_utils_shrink_name_lon(_attr), _sub_class, _attr, _fk_target, _type); ELSE EXECUTE format('CREATE TRIGGER "_cm3_card_enforce_fk_%s" BEFORE INSERT OR UPDATE ON %s FOR EACH ROW EXECUTE PROCEDURE _cm3_trigger_card_enforce_foreign_key_for_source(%L,%L,%L)', _cm3_utils_shrink_name_lon(_attr), _sub_class, _attr, _fk_target, _type); END IF; END LOOP; FOR _sub_class IN SELECT _cm3_class_list_descendant_classes_and_self(_fk_target) LOOP EXECUTE format('CREATE TRIGGER "_cm3_card_enforce_fk_%s_%s" BEFORE UPDATE OR DELETE ON %s FOR EACH ROW EXECUTE PROCEDURE _cm3_trigger_card_enforce_foreign_key_for_target(%L,%L,%L)', _cm3_utils_shrink_name(_cm3_utils_regclass_to_name(_class)), _cm3_utils_shrink_name(_attr), _sub_class, _class, _attr, _type); END LOOP; END IF; IF _cm3_attribute_is_reference(_class, _attr) THEN RAISE NOTICE 'attr is reference: activating reference triggers'; _domain = _cm3_attribute_reference_domain_get(_class, _attr); _direction = _cm3_attribute_reference_direction_get(_class, _attr); _cardin = _cm3_class_comment_get(_domain, 'CARDIN'); IF ( _direction = 'direct' AND _cardin NOT LIKE '%:1' ) OR ( _direction = 'inverse' AND _cardin NOT LIKE '1:%' ) THEN RAISE 'CM: invalid domain = % and direction = % for reference attr of class = % (domain cardin = %)', _cm3_utils_regclass_to_domain_name(_domain), _direction, _cm3_utils_regclass_to_name(_class), _cardin; END IF; IF NOT _class IN (SELECT _cm3_domain_source_classes_get(_domain, _direction)) THEN RAISE 'CM: invalid domain = % and direction = % for reference attr of class = % (source class is not valid for this domain/direction)', _cm3_utils_regclass_to_domain_name(_domain), _direction, _cm3_utils_regclass_to_name(_class); END IF; IF _direction = 'direct' THEN EXECUTE format('UPDATE %s c SET %I = d."IdObj2" FROM %s d WHERE c."Status" = ''A'' AND d."Status" = ''A'' AND c."Id" = d."IdObj1"', _class, _attr, _domain); ELSE EXECUTE format('UPDATE %s c SET %I = d."IdObj1" FROM %s d WHERE c."Status" = ''A'' AND d."Status" = ''A'' AND c."Id" = d."IdObj2"', _class, _attr, _domain); END IF; FOR _sub_class IN SELECT _cm3_class_list_descendant_classes_and_self(_class) LOOP EXECUTE format('CREATE TRIGGER "_cm3_card_update_rels_%s" AFTER INSERT OR UPDATE ON %s FOR EACH ROW EXECUTE PROCEDURE _cm3_trigger_card_update_relations(%L,%L,%L)', _cm3_utils_shrink_name_lon(_attr), _sub_class, _attr, _domain, _direction); END LOOP; EXECUTE format('CREATE TRIGGER "_cm3_rel_update_refs_%s_%s" AFTER INSERT OR UPDATE ON %s FOR EACH ROW EXECUTE PROCEDURE _cm3_trigger_relation_update_references(%L,%L,%L)', _cm3_utils_shrink_name(_cm3_utils_regclass_to_name(_class)), _cm3_utils_shrink_name(_attr), _domain, _class, _attr, _direction); END IF; IF _cm3_class_is_domain(_class) THEN PERFORM _cm3_domain_composite_index_rebuild(_class); END IF; END $$; DROP FUNCTION public._cm3_attribute_create(_class regclass, _attr character varying, _type character varying, _features jsonb); publicpostgresfalse1255232750X_cm3_attribute_create(regclass, character varying, character varying, character varying)FUNCTIONCREATE FUNCTION public._cm3_attribute_create(_class regclass, _attr character varying, _type character varying, _features character varying) RETURNS void LANGUAGE plpgsql AS $$ BEGIN PERFORM _cm3_attribute_create(_class, _attr, _type, _cm3_comment_to_jsonb(_features)); END $$; DROP FUNCTION public._cm3_attribute_create(_class regclass, _attr character varying, _type character varying, _features character varying); publicpostgresfalse12552327517_cm3_attribute_default_get(regclass, character varying)FUNCTIONwCREATE FUNCTION public._cm3_attribute_default_get(_class regclass, _attr character varying) RETURNS character varying LANGUAGE sql STABLE AS $$ SELECT pg_attrdef.adsrc FROM pg_attribute JOIN pg_attrdef ON pg_attrdef.adrelid = pg_attribute.attrelid AND pg_attrdef.adnum = pg_attribute.attnum WHERE pg_attribute.attrelid = _class AND pg_attribute.attname = _attr; $$; [DROP FUNCTION public._cm3_attribute_default_get(_class regclass, _attr character varying); publicpostgresfalse1255232752J_cm3_attribute_default_set(regclass, character varying, character varying)FUNCTIONCREATE FUNCTION public._cm3_attribute_default_set(_class regclass, _attr character varying, _value character varying) RETURNS void LANGUAGE plpgsql AS $$ BEGIN PERFORM _cm3_attribute_default_set(_class, _attr, _value, FALSE); END $$; uDROP FUNCTION public._cm3_attribute_default_set(_class regclass, _attr character varying, _value character varying); publicpostgresfalse1255232753S_cm3_attribute_default_set(regclass, character varying, character varying, boolean)FUNCTION5CREATE FUNCTION public._cm3_attribute_default_set(_class regclass, _attr character varying, _value character varying, _update_records boolean) RETURNS void LANGUAGE plpgsql AS $$ DECLARE _current_value varchar; _attr_sqltype varchar; _trigger_enabled boolean; BEGIN _value = NULLIF(TRIM(_value), ''); _attr_sqltype = LOWER(_cm3_attribute_sqltype_get(_class, _attr)); IF _value IS NOT NULL AND ( _attr_sqltype LIKE 'varchar%' OR _attr_sqltype = 'text' OR ( ( _attr_sqltype = 'date' OR _attr_sqltype LIKE 'timestamp%' ) AND TRIM(_value) <> 'now()' ) ) THEN _value = quote_literal(_value); END IF; _current_value = _cm3_attribute_default_get(_class, _attr); IF _value IS DISTINCT FROM _current_value THEN IF _value IS NULL THEN EXECUTE format('ALTER TABLE %s ALTER COLUMN %I DROP DEFAULT', _class, _attr); ELSE EXECUTE format('ALTER TABLE %s ALTER COLUMN %I SET DEFAULT %s', _class, _attr, _value); IF _update_records THEN _trigger_enabled = _cm3_class_triggers_are_enabled(_class); IF _trigger_enabled THEN PERFORM _cm3_class_triggers_disable(_class); END IF; EXECUTE format('UPDATE %s SET %I = %s', _class, _attr, _value); IF _trigger_enabled THEN PERFORM _cm3_class_triggers_enable(_class); END IF; END IF; END IF; END IF; END $$; DROP FUNCTION public._cm3_attribute_default_set(_class regclass, _attr character varying, _value character varying, _update_records boolean); publicpostgresfalse12552327542_cm3_attribute_delete(regclass, character varying)FUNCTIONYCREATE FUNCTION public._cm3_attribute_delete(_class regclass, _attr character varying) RETURNS void LANGUAGE plpgsql AS $$ DECLARE -- GeoType text := _cm_get_geometry_type(_class, _attr); TODO _fk_target regclass; _sub_class regclass; _domain regclass; BEGIN IF _cm3_attribute_is_inherited(_class, _attr) THEN RAISE EXCEPTION 'CM_FORBIDDEN_OPERATION: cannot remove attribute %.%: attribute is inherited', _class, _attr; END IF; IF _cm3_attribute_has_data(_class, _attr) THEN RAISE EXCEPTION 'CM_CONTAINS_DATA: cannot remove attribute %.%: attribute contains data', _class, _attr; END IF; IF _cm3_attribute_is_foreignkey(_class, _attr) OR _cm3_attribute_is_reference(_class, _attr) THEN _fk_target = _cm3_attribute_foreignkey_or_reference_target_class_get(_class, _attr); FOR _sub_class IN SELECT _cm3_class_list_descendant_classes_and_self(_class) LOOP EXECUTE format('DROP TRIGGER "_cm3_card_enforce_fk_%s" ON %s', _cm3_utils_shrink_name_lon(_attr), _sub_class); END LOOP; FOR _sub_class IN SELECT _cm3_class_list_descendant_classes_and_self(_fk_target) LOOP EXECUTE format('DROP TRIGGER "_cm3_card_enforce_fk_%s_%s" ON %s', _cm3_utils_shrink_name(_cm3_utils_regclass_to_name(_class)), _cm3_utils_shrink_name(_attr), _sub_class); END LOOP; END IF; IF _cm3_attribute_is_reference(_class, _attr) THEN _domain = _cm3_attribute_reference_domain_get(_class, _attr); FOR _sub_class IN SELECT _cm3_class_list_descendant_classes_and_self(_class) LOOP EXECUTE format('DROP TRIGGER "_cm3_card_update_rels_%s" ON %s', _cm3_utils_shrink_name_lon(_attr), _sub_class); END LOOP; EXECUTE format('DROP TRIGGER "_cm3_rel_update_refs_%s_%s" ON %s', _cm3_utils_shrink_name(_cm3_utils_regclass_to_name(_class)), _cm3_utils_shrink_name(_attr), _domain); END IF; -- IF GeoType IS NOT NULL THEN --TODO -- PERFORM DropGeometryColumn(_cm_cmschema(_class), _cm_cmtable(_class), _attr); -- ELSE EXECUTE format('ALTER TABLE %s DROP COLUMN %I CASCADE', _class, _attr); -- END IF; IF _cm3_class_is_domain(_class) THEN PERFORM _cm3_domain_composite_index_rebuild(_class); END IF; END $$; VDROP FUNCTION public._cm3_attribute_delete(_class regclass, _attr character varying); publicpostgresfalse1255232755#_cm3_attribute_delete_all(regclass)FUNCTION?CREATE FUNCTION public._cm3_attribute_delete_all(_class regclass) RETURNS void LANGUAGE plpgsql AS $$ DECLARE _attr varchar; BEGIN FOR _attr IN SELECT a FROM _cm3_attribute_list(_class) a WHERE NOT _cm3_attribute_is_inherited(_class, a) LOOP PERFORM _cm3_attribute_delete(_class, _attr); END LOOP; END $$; ADROP FUNCTION public._cm3_attribute_delete_all(_class regclass); publicpostgresfalsen12552327562_cm3_attribute_exists(regclass, character varying)FUNCTIONCREATE FUNCTION public._cm3_attribute_exists(_class regclass, _attr character varying) RETURNS boolean LANGUAGE sql STABLE AS $$ SELECT EXISTS (SELECT * FROM pg_attribute WHERE attrelid = _class AND attnum > 0 AND atttypid > 0 AND attname::varchar = _attr); $$; VDROP FUNCTION public._cm3_attribute_exists(_class regclass, _attr character varying); publicpostgresfalse1255232757N_cm3_attribute_features_delete(regclass, character varying, character varying)FUNCTIONCREATE FUNCTION public._cm3_attribute_features_delete(_classe regclass, _attr character varying, _key character varying) RETURNS void LANGUAGE plpgsql AS $$ BEGIN PERFORM _cm3_attribute_features_set(_classe, _attr, _cm3_attribute_features_get(_classe, _attr) - _key); END $$; xDROP FUNCTION public._cm3_attribute_features_delete(_classe regclass, _attr character varying, _key character varying); publicpostgresfalse12552327588_cm3_attribute_features_get(regclass, character varying)FUNCTIONCREATE FUNCTION public._cm3_attribute_features_get(_classe regclass, _attr character varying) RETURNS jsonb LANGUAGE plpgsql AS $$ BEGIN RETURN _cm3_attribute_metadata_get(_classe, _attr) || _cm3_attribute_comment_get(_classe, _attr); END $$; ]DROP FUNCTION public._cm3_attribute_features_get(_classe regclass, _attr character varying); publicpostgresfalse1255232759K_cm3_attribute_features_get(regclass, character varying, character varying)FUNCTIONCREATE FUNCTION public._cm3_attribute_features_get(_classe regclass, _attr character varying, _key character varying) RETURNS character varying LANGUAGE plpgsql AS $$ BEGIN RETURN coalesce(_cm3_attribute_features_get(_classe, _attr)->>_key, ''); END $$; uDROP FUNCTION public._cm3_attribute_features_get(_classe regclass, _attr character varying, _key character varying); publicpostgresfalse1255232760?_cm3_attribute_features_set(regclass, character varying, jsonb)FUNCTION<CREATE FUNCTION public._cm3_attribute_features_set(_classe regclass, _attr character varying, _features jsonb) RETURNS void LANGUAGE plpgsql AS $$ BEGIN PERFORM _cm3_attribute_comment_set(_classe, _attr, (SELECT coalesce(jsonb_object_agg(key, value), '{}'::jsonb) FROM jsonb_each_text(_features) WHERE key IN (SELECT _cm3_attribute_comment_keys()))); PERFORM _cm3_attribute_metadata_set(_classe, _attr, (SELECT coalesce(jsonb_object_agg(key, value), '{}'::jsonb) FROM jsonb_each_text(_features) WHERE key NOT IN (SELECT _cm3_attribute_comment_keys()))); END $$; nDROP FUNCTION public._cm3_attribute_features_set(_classe regclass, _attr character varying, _features jsonb); publicpostgresfalse1255232761^_cm3_attribute_features_set(regclass, character varying, character varying, character varying)FUNCTIONQCREATE FUNCTION public._cm3_attribute_features_set(_classe regclass, _attr character varying, _key character varying, _value character varying) RETURNS void LANGUAGE plpgsql AS $$ BEGIN PERFORM _cm3_attribute_features_set(_classe, _attr, _cm3_attribute_features_get(_classe, _attr) || jsonb_build_object(_key, _value)); END $$; DROP FUNCTION public._cm3_attribute_features_set(_classe regclass, _attr character varying, _key character varying, _value character varying); publicpostgresfalse1255232762B_cm3_attribute_features_update(regclass, character varying, jsonb)FUNCTIONCREATE FUNCTION public._cm3_attribute_features_update(_classe regclass, _attr character varying, _features jsonb) RETURNS void LANGUAGE plpgsql AS $$ BEGIN PERFORM _cm3_attribute_features_set(_classe, _attr, _cm3_attribute_features_get(_classe, _attr) || _features); END $$; qDROP FUNCTION public._cm3_attribute_features_update(_classe regclass, _attr character varying, _features jsonb); publicpostgresfalse1255232763T_cm3_attribute_foreignkey_or_reference_target_class_get(regclass, character varying)FUNCTION!CREATE FUNCTION public._cm3_attribute_foreignkey_or_reference_target_class_get(_class regclass, _attr character varying) RETURNS regclass LANGUAGE plpgsql STABLE AS $$ BEGIN IF _cm3_attribute_is_foreignkey(_class, _attr) THEN RETURN _cm3_attribute_foreignkey_target_get(_class, _attr); ELSEIF _cm3_attribute_is_reference(_class, _attr) THEN RETURN _cm3_attribute_reference_target_class_get(_class, _attr); ELSE RAISE EXCEPTION 'attribute is not reference nor foreignkey for class = % attr = %', _class, _attr; END IF; END $$; xDROP FUNCTION public._cm3_attribute_foreignkey_or_reference_target_class_get(_class regclass, _attr character varying); publicpostgresfalse1255232764A_cm3_attribute_foreignkey_target_get(regclass, character varying)FUNCTIONCREATE FUNCTION public._cm3_attribute_foreignkey_target_get(_class regclass, _attr character varying) RETURNS regclass LANGUAGE sql AS $$ SELECT _cm3_utils_name_to_regclass(_cm3_attribute_comment_get(_class, _attr, 'FKTARGETCLASS')) $$; eDROP FUNCTION public._cm3_attribute_foreignkey_target_get(_class regclass, _attr character varying); publicpostgresfalse12552327654_cm3_attribute_has_data(regclass, character varying)FUNCTIONCREATE FUNCTION public._cm3_attribute_has_data(_class regclass, _attr character varying) RETURNS boolean LANGUAGE plpgsql AS $$ DECLARE _has_data boolean; BEGIN IF _cm3_class_is_simple(_class) THEN EXECUTE format('SELECT EXISTS (SELECT 1 FROM %s WHERE %I IS NOT NULL AND %I::text <> '''')', _class, _attr, _attr) INTO _has_data; ELSE EXECUTE format('SELECT EXISTS (SELECT 1 FROM %s WHERE %I IS NOT NULL AND %I::text <> '''' AND "Status" = ''A'')', _class, _attr, _attr) INTO _has_data; END IF; RETURN _has_data; END $$; XDROP FUNCTION public._cm3_attribute_has_data(_class regclass, _attr character varying); publicpostgresfalse1255232766=_cm3_attribute_has_value(regclass, character varying, bigint)FUNCTIONCREATE FUNCTION public._cm3_attribute_has_value(_class regclass, _attr character varying, _value bigint) RETURNS boolean LANGUAGE plpgsql AS $$ DECLARE _has_value boolean; BEGIN IF _cm3_class_is_simple(_class) THEN EXECUTE format('SELECT EXISTS (SELECT 1 FROM %s WHERE %I = %L)', _class, _attr, _value) INTO _has_value; ELSE EXECUTE format('SELECT EXISTS (SELECT 1 FROM %s WHERE %I = %L AND "Status" = ''A'')', _class, _attr, _value) INTO _has_value; END IF; RETURN _has_value; END $$; hDROP FUNCTION public._cm3_attribute_has_value(_class regclass, _attr character varying, _value bigint); publicpostgresfalse1255232767H_cm3_attribute_has_value(regclass, character varying, character varying)FUNCTIONCREATE FUNCTION public._cm3_attribute_has_value(_class regclass, _attr character varying, _value character varying) RETURNS boolean LANGUAGE plpgsql AS $$ DECLARE _has_value boolean; BEGIN IF _cm3_class_is_simple(_class) THEN EXECUTE format('SELECT EXISTS (SELECT 1 FROM %s WHERE %I = %L)', _class, _attr, _value) INTO _has_value; ELSE EXECUTE format('SELECT EXISTS (SELECT 1 FROM %s WHERE %I = %L AND "Status" = ''A'')', _class, _attr, _value) INTO _has_value; END IF; RETURN _has_value; END $$; sDROP FUNCTION public._cm3_attribute_has_value(_class regclass, _attr character varying, _value character varying); publicpostgresfalse1255232768:_cm3_attribute_index_create(regclass, character varying[])FUNCTIONCREATE FUNCTION public._cm3_attribute_index_create(_class regclass, VARIADIC _attrs character varying[]) RETURNS void LANGUAGE sql AS $$ SELECT _cm3_attribute_index_create(_class, FALSE, VARIADIC _attrs); $$; hDROP FUNCTION public._cm3_attribute_index_create(_class regclass, VARIADIC _attrs character varying[]); publicpostgresfalse1255232769C_cm3_attribute_index_create(regclass, boolean, character varying[])FUNCTIONCREATE FUNCTION public._cm3_attribute_index_create(_class regclass, _unique boolean, VARIADIC _attrs character varying[]) RETURNS void LANGUAGE plpgsql AS $$ DECLARE _indexexpr varchar; _indexname varchar; _whereexpr varchar; BEGIN _indexname = format('_cm3_%s_%s', _cm3_utils_shrink_name(_cm3_utils_regclass_to_name(_class)), _cm3_utils_shrink_name((WITH _attr_names AS (SELECT unnest(_attrs) AS _attr_name ORDER BY _attr_name) SELECT string_agg(_attr_name, '_') from _attr_names))); _indexexpr = CASE WHEN _unique THEN 'UNIQUE INDEX' ELSE 'INDEX' END; _whereexpr = CASE WHEN _cm3_class_has_history(_class) THEN ' WHERE "Status" = ''A''' ELSE '' END; -- IF _unique THEN -- IF _cm3_class_is_domain(_class) THEN -- IF _cm3_class_comment_get(_class, 'CARDIN') = '1:N' THEN -- _attrs = _attrs || ARRAY['IdClass2', 'IdObj2']; -- ELSEIF _cm3_class_comment_get(_class, 'CARDIN') = 'N:1' THEN -- _attrs = _attrs || ARRAY['IdClass1', 'IdObj1']; -- ELSE -- RAISE EXCEPTION 'cannot create unique index on attributes = % for domain = % with cardinality = %', _attrs, _class, _cm3_class_comment_get(_class,'CARDIN'); -- END IF; -- END IF; -- END IF; IF array_length(_attrs, 1) = 0 THEN RAISE EXCEPTION 'missing attrs value'; ELSEIF array_length(_attrs, 1) = 1 THEN EXECUTE format('DROP INDEX IF EXISTS %I.%I', (SELECT nspname FROM pg_catalog.pg_class AS c JOIN pg_catalog.pg_namespace AS ns ON c.relnamespace = ns.oid WHERE c.oid = _class::oid), _indexname); EXECUTE format('CREATE %s %I ON %s (%I)%s', _indexexpr, _indexname, _class, _attrs[1], _whereexpr); ELSE EXECUTE format('DROP INDEX IF EXISTS %I.%I', (SELECT nspname FROM pg_catalog.pg_class AS c JOIN pg_catalog.pg_namespace AS ns ON c.relnamespace = ns.oid WHERE c.oid = _class::oid), _indexname); EXECUTE format('CREATE %s %I ON %s (%s)%s', _indexexpr, _indexname, _class, (SELECT string_agg(format('%I', x), ',') from unnest(_attrs) x), _whereexpr); END IF; END $$; yDROP FUNCTION public._cm3_attribute_index_create(_class regclass, _unique boolean, VARIADIC _attrs character varying[]); publicpostgresfalse1255232770:_cm3_attribute_index_delete(regclass, character varying[])FUNCTIONCREATE FUNCTION public._cm3_attribute_index_delete(_class regclass, VARIADIC _attrs character varying[]) RETURNS void LANGUAGE plpgsql AS $$ DECLARE _indexname varchar; BEGIN _indexname = format('_cm3_%s_%s', _cm3_utils_shrink_name(_cm3_utils_regclass_to_name(_class)), _cm3_utils_shrink_name((WITH _attr_names AS (SELECT unnest(_attrs) AS _attr_name ORDER BY _attr_name) SELECT string_agg(_attr_name, '_') from _attr_names))); EXECUTE format('DROP INDEX IF EXISTS %I', _indexname); END $$; hDROP FUNCTION public._cm3_attribute_index_delete(_class regclass, VARIADIC _attrs character varying[]); publicpostgresfalse1255232771A_cm3_attribute_index_unique_create(regclass, character varying[])FUNCTIONCREATE FUNCTION public._cm3_attribute_index_unique_create(_class regclass, VARIADIC _attrs character varying[]) RETURNS void LANGUAGE sql AS $$ SELECT _cm3_attribute_index_create(_class, TRUE, VARIADIC _attrs); $$; oDROP FUNCTION public._cm3_attribute_index_unique_create(_class regclass, VARIADIC _attrs character varying[]); publicpostgresfalse12552327729_cm3_attribute_is_foreignkey(regclass, character varying)FUNCTIONCREATE FUNCTION public._cm3_attribute_is_foreignkey(_class regclass, _attr character varying) RETURNS boolean LANGUAGE sql AS $$ SELECT _cm3_attribute_comment_get(_class, _attr, 'FKTARGETCLASS') <> ''; $$; ]DROP FUNCTION public._cm3_attribute_is_foreignkey(_class regclass, _attr character varying); publicpostgresfalse12552327738_cm3_attribute_is_inherited(regclass, character varying)FUNCTION CREATE FUNCTION public._cm3_attribute_is_inherited(_class regclass, _attr character varying) RETURNS boolean LANGUAGE sql AS $$ SELECT pg_attribute.attinhcount <> 0 FROM pg_attribute WHERE pg_attribute.attrelid = _class AND pg_attribute.attname = _attr; $$; \DROP FUNCTION public._cm3_attribute_is_inherited(_class regclass, _attr character varying); publicpostgresfalse312552327745_cm3_attribute_is_lookup(regclass, character varying)FUNCTIONCREATE FUNCTION public._cm3_attribute_is_lookup(_class regclass, _attr character varying) RETURNS boolean LANGUAGE sql AS $$ SELECT _cm3_attribute_comment_get(_class, _attr, 'LOOKUP') <> ''; $$; YDROP FUNCTION public._cm3_attribute_is_lookup(_class regclass, _attr character varying); publicpostgresfalse12552327758_cm3_attribute_is_reference(regclass, character varying)FUNCTIONCREATE FUNCTION public._cm3_attribute_is_reference(_class regclass, _attr character varying) RETURNS boolean LANGUAGE sql AS $$ SELECT _cm3_attribute_comment_get(_class, _attr, 'REFERENCEDOM') <> ''; $$; \DROP FUNCTION public._cm3_attribute_is_reference(_class regclass, _attr character varying); publicpostgresfalse1255232776_cm3_attribute_list()FUNCTIONCREATE FUNCTION public._cm3_attribute_list() RETURNS TABLE(owner regclass, name character varying) LANGUAGE plpgsql AS $$ BEGIN RETURN QUERY EXECUTE (SELECT string_agg(format('SELECT %L::regclass,* FROM _cm3_attribute_list(%L) x',c.x,c.x),' UNION ALL ') FROM (SELECT x FROM _cm3_class_list() x UNION SELECT x FROM _cm3_domain_list() x) c); --TODO improve this query, rewrite wihtout string_agg/format END $$; ,DROP FUNCTION public._cm3_attribute_list(); publicpostgresfalse1255232777_cm3_attribute_list(regclass)FUNCTIONCREATE FUNCTION public._cm3_attribute_list(_class regclass) RETURNS SETOF character varying LANGUAGE sql STABLE AS $$ SELECT attname::varchar FROM pg_attribute WHERE attrelid = _class AND attnum > 0 AND atttypid > 0 ORDER BY attnum; $$; ;DROP FUNCTION public._cm3_attribute_list(_class regclass); publicpostgresfalse1255232778_cm3_attribute_list_detailed()FUNCTIONICREATE FUNCTION public._cm3_attribute_list_detailed() RETURNS TABLE(owner regclass, name character varying, comment jsonb, not_null_constraint boolean, unique_constraint boolean, sql_type character varying, inherited boolean, default_value character varying, metadata jsonb) LANGUAGE plpgsql AS $$ BEGIN RETURN QUERY EXECUTE (SELECT string_agg(format('SELECT * FROM _cm3_attribute_list_detailed(%L)',c.x),' UNION ALL ') FROM (SELECT x FROM _cm3_class_list() x UNION SELECT x FROM _cm3_domain_list() x) c); --TODO improve this query, rewrite wihtout string_agg/format END $$; 5DROP FUNCTION public._cm3_attribute_list_detailed(); publicpostgresfalse1255232779&_cm3_attribute_list_detailed(regclass)FUNCTIONCREATE FUNCTION public._cm3_attribute_list_detailed(_class regclass) RETURNS TABLE(owner regclass, name character varying, comment jsonb, not_null_constraint boolean, unique_constraint boolean, sql_type character varying, inherited boolean, default_value character varying, metadata jsonb) LANGUAGE plpgsql AS $$ BEGIN RETURN QUERY WITH q AS (SELECT _class::regclass AS owner, attr_name::varchar AS name, _cm3_attribute_comment_get(_class, attr_name) AS comment, _cm3_attribute_notnull_get(_class, attr_name) AS not_null_constraint, _cm3_attribute_unique_get(_class, attr_name) AS unique_constraint, _cm3_attribute_sqltype_get(_class, attr_name)::varchar AS sql_type, _cm3_attribute_is_inherited(_class, attr_name) AS inherited, _cm3_attribute_default_get(_class, attr_name)::varchar AS default_value, _cm3_attribute_metadata_get(_class, attr_name) AS metadata, COALESCE(NULLIF(_cm3_attribute_comment_get(_class, attr_name, 'INDEX'), ''), '2147483647')::int AS _index FROM (SELECT attr_name FROM _cm3_attribute_list(_class) attr_name) x ) SELECT q.owner,q.name,q.comment,q.not_null_constraint,q.unique_constraint,q.sql_type,q.inherited,q.default_value,q.metadata FROM q ORDER BY _index; END $$; DDROP FUNCTION public._cm3_attribute_list_detailed(_class regclass); publicpostgresfalse12552327808_cm3_attribute_metadata_get(regclass, character varying)FUNCTION$CREATE FUNCTION public._cm3_attribute_metadata_get(_classe regclass, _attr character varying) RETURNS jsonb LANGUAGE plpgsql AS $$ BEGIN RETURN COALESCE((SELECT "Metadata" FROM "_AttributeMetadata" WHERE "Owner" = _classe AND "Code" = _attr AND "Status" = 'A'),'{}'::jsonb); END $$; ]DROP FUNCTION public._cm3_attribute_metadata_get(_classe regclass, _attr character varying); publicpostgresfalse1255232781?_cm3_attribute_metadata_set(regclass, character varying, jsonb)FUNCTIONCREATE FUNCTION public._cm3_attribute_metadata_set(_class regclass, _attr character varying, _metadata jsonb) RETURNS void LANGUAGE plpgsql AS $$ BEGIN _metadata = _cm3_utils_strip_null_or_empty(_metadata); IF EXISTS (SELECT * FROM "_AttributeMetadata" WHERE "Owner" = _class AND "Code" = _attr AND "Status" = 'A') THEN IF _metadata = '{}'::jsonb THEN UPDATE "_AttributeMetadata" SET "Status" = 'N' WHERE "Owner" = _class AND "Code" = _attr AND "Status" = 'A'; ELSE UPDATE "_AttributeMetadata" SET "Metadata" = _metadata WHERE "Owner" = _class AND "Code" = _attr AND "Status" = 'A'; END IF; ELSE IF _metadata <> '{}'::jsonb THEN INSERT INTO "_AttributeMetadata" ("Owner","Code","Status","Metadata") VALUES (_class,_attr,'A',_metadata); END IF; END IF; END $$; mDROP FUNCTION public._cm3_attribute_metadata_set(_class regclass, _attr character varying, _metadata jsonb); publicpostgresfalse1255232782^_cm3_attribute_metadata_set(regclass, character varying, character varying, character varying)FUNCTION?CREATE FUNCTION public._cm3_attribute_metadata_set(_class regclass, _attr character varying, _key character varying, _value character varying) RETURNS void LANGUAGE sql AS $$ SELECT _cm3_attribute_metadata_set(_class, _attr, _cm3_attribute_metadata_get(_class, _attr) || jsonb_build_object(_key, _value)); $$; DROP FUNCTION public._cm3_attribute_metadata_set(_class regclass, _attr character varying, _key character varying, _value character varying); publicpostgresfalse1255232783_cm3_attribute_modify(jsonb)FUNCTIONCREATE FUNCTION public._cm3_attribute_modify(_features jsonb) RETURNS void LANGUAGE plpgsql AS $$ BEGIN PERFORM _cm3_attribute_modify(_cm3_utils_name_to_regclass(_features->>'OWNER'), _features->>'NAME', _features->>'TYPE', _features - 'OWNER' - 'NAME' - 'TYPE'); END $$; =DROP FUNCTION public._cm3_attribute_modify(_features jsonb); publicpostgresfalse1255232784(_cm3_attribute_modify(character varying)FUNCTIONCREATE FUNCTION public._cm3_attribute_modify(_features character varying) RETURNS void LANGUAGE plpgsql AS $$ BEGIN PERFORM _cm3_attribute_modify(_cm3_comment_to_jsonb(_features)); END $$; IDROP FUNCTION public._cm3_attribute_modify(_features character varying); publicpostgresfalse1255232785L_cm3_attribute_modify(regclass, character varying, character varying, jsonb)FUNCTION/ CREATE FUNCTION public._cm3_attribute_modify(_class regclass, _attr character varying, _type character varying, _features jsonb) RETURNS void LANGUAGE plpgsql AS $$ DECLARE _not_null boolean; _unique boolean; _default varchar; _current_features jsonb; _attr_features jsonb; _changes_in_features jsonb; _sub_class regclass; BEGIN _not_null = coalesce(_features->>'NOTNULL', 'false')::boolean; _unique = coalesce(_features->>'UNIQUE', 'false')::boolean; _default = _features->>'DEFAULT'; _attr_features = _features - 'NOTNULL' - 'UNIQUE' - 'DEFAULT'; _current_features = _cm3_attribute_features_get(_class, _attr); WITH compare AS ( SELECT c.k comment_key, coalesce(_current_features->>c.k, '') current_value, coalesce(_attr_features->>c.k, '') new_value FROM (SELECT jsonb_object_keys(_attr_features) k UNION SELECT jsonb_object_keys(_current_features) k ) c ) SELECT INTO _changes_in_features coalesce(jsonb_object_agg(comment_key, new_value), '{}'::jsonb) FROM compare WHERE current_value <> new_value; -- TODO check -- IF COALESCE(_cm_read_reference_domain_features(OldComment), '') IS DISTINCT FROM COALESCE(_cm_read_reference_domain_features(NewComment), '') -- OR _cm_read_reference_type_features(OldComment) IS DISTINCT FROM _cm_read_reference_type_features(NewComment) -- OR COALESCE(_cm_get_fk_target_features(OldComment), '') IS DISTINCT FROM COALESCE(_cm_get_fk_target_features(NewComment), '') -- THEN -- RAISE EXCEPTION 'CM_FORBIDDEN_OPERATION'; -- END IF; PERFORM _cm3_attribute_validate_features_and_type(_attr_features, _type); IF _cm3_attribute_sqltype_get(_class, _attr) <> trim(_type) THEN IF _cm3_attribute_is_inherited(_class, _attr) THEN RAISE 'CM: cannot alter type of attr %.%: attribute is inherited from parent class', _class, _attr; ELSE EXECUTE format('ALTER TABLE %s ALTER COLUMN %I TYPE %s', _class, _attr, _type); END IF; END IF; PERFORM _cm3_attribute_default_set(_class, _attr, _default, FALSE); PERFORM _cm3_attribute_features_set(_class, _attr, _attr_features); PERFORM _cm3_class_utils_attribute_groups_fix(_class, _attr); FOR _sub_class IN SELECT _cm3_class_list_descendant_classes(_class) LOOP PERFORM _cm3_attribute_features_update(_sub_class, _attr, _changes_in_features); PERFORM _cm3_class_utils_attribute_groups_fix(_sub_class, _attr); END LOOP; PERFORM _cm3_attribute_notnull_set(_class, _attr, _not_null); PERFORM _cm3_attribute_unique_set(_class, _attr, _unique); IF _cm3_class_is_domain(_class) THEN PERFORM _cm3_domain_composite_index_rebuild(_class); END IF; END $$; DROP FUNCTION public._cm3_attribute_modify(_class regclass, _attr character varying, _type character varying, _features jsonb); publicpostgresfalse1255232786X_cm3_attribute_modify(regclass, character varying, character varying, character varying)FUNCTIONCREATE FUNCTION public._cm3_attribute_modify(_class regclass, _attr character varying, _type character varying, _comment character varying) RETURNS void LANGUAGE plpgsql AS $$ BEGIN PERFORM _cm3_attribute_modify(_class, _attr, _type, _cm3_comment_to_jsonb(_comment)); END $$; DROP FUNCTION public._cm3_attribute_modify(_class regclass, _attr character varying, _type character varying, _comment character varying); publicpostgresfalse12552327877_cm3_attribute_notnull_get(regclass, character varying)FUNCTIONCREATE FUNCTION public._cm3_attribute_notnull_get(_class regclass, _attr character varying) RETURNS boolean LANGUAGE sql AS $$ SELECT pg_attribute.attnotnull OR c.oid IS NOT NULL FROM pg_attribute LEFT JOIN pg_constraint AS c ON c.conrelid = pg_attribute.attrelid AND c.conname::text = format('_cm3_%s_notnull', pg_attribute.attname) WHERE pg_attribute.attrelid = _class AND pg_attribute.attname = _attr; $$; [DROP FUNCTION public._cm3_attribute_notnull_get(_class regclass, _attr character varying); publicpostgresfalse12552327887_cm3_attribute_notnull_set(regclass, character varying)FUNCTIONCREATE FUNCTION public._cm3_attribute_notnull_set(_class regclass, _attr character varying) RETURNS void LANGUAGE plpgsql AS $$ BEGIN PERFORM _cm3_attribute_notnull_set(_class, _attr, TRUE); END $$; [DROP FUNCTION public._cm3_attribute_notnull_set(_class regclass, _attr character varying); publicpostgresfalse1255232789@_cm3_attribute_notnull_set(regclass, character varying, boolean)FUNCTIONCREATE FUNCTION public._cm3_attribute_notnull_set(_class regclass, _attr character varying, _notnull boolean) RETURNS void LANGUAGE plpgsql AS $$ DECLARE _hasnull_any boolean; _hasnull_active boolean; _default varchar; BEGIN IF _notnull <> _cm3_attribute_notnull_get(_class, _attr) THEN IF _notnull THEN IF _cm3_class_is_superclass(_class) THEN RAISE EXCEPTION 'CM_FORBIDDEN_OPERATION: error setting notnull flag on attribute %.%; superclass attributes cannot be notnull', _class, _attr; END IF; _default = _cm3_attribute_default_get(_class, _attr); IF _default IS NOT NULL THEN IF _cm3_class_is_simple(_class) THEN EXECUTE format('UPDATE %s SET %I = %s WHERE %I IS NULL', _class, _attr, _default, _attr); ELSE EXECUTE format('UPDATE %s SET %I = %s WHERE "Status" = ''A'' AND %I IS NULL', _class, _attr, _default, _attr); END IF; END IF; EXECUTE format('SELECT EXISTS(SELECT * FROM %s WHERE %I IS NULL)', _class, _attr) INTO _hasnull_any; IF _cm3_class_is_simple(_class) THEN _hasnull_active = _hasnull_any; ELSE EXECUTE format('SELECT EXISTS(SELECT * FROM %s WHERE %I IS NULL AND "Status" = ''A'')', _class, _attr) INTO _hasnull_active; END IF; IF _hasnull_active THEN RAISE EXCEPTION 'CM_FORBIDDEN_OPERATION: error setting notnull flag on attribute %.%: there are active cards with null values for this attribute', _class, _attr; END IF; IF _cm3_class_is_simple(_class) OR NOT _hasnull_any THEN EXECUTE format('ALTER TABLE %s ALTER COLUMN %I SET NOT NULL', _class, _attr); ELSE EXECUTE format('ALTER TABLE %s ADD CONSTRAINT "_cm3_%s_notnull" CHECK ("Status"<>''A'' OR %I IS NOT NULL)', _class, _attr, _attr); END IF; ELSE EXECUTE format('ALTER TABLE %s ALTER COLUMN %I DROP NOT NULL', _class, _attr); EXECUTE format('ALTER TABLE %s DROP CONSTRAINT IF EXISTS "_cm3_%s_notnull"', _class, _attr); END IF; END IF; END $$; mDROP FUNCTION public._cm3_attribute_notnull_set(_class regclass, _attr character varying, _notnull boolean); publicpostgresfalse1255232790C_cm3_attribute_reference_direction_get(regclass, character varying)FUNCTIONCREATE FUNCTION public._cm3_attribute_reference_direction_get(_class regclass, _attr character varying) RETURNS character varying LANGUAGE plpgsql AS $$ DECLARE _direction varchar; BEGIN _direction = _cm3_attribute_comment_get(_class, _attr, 'REFERENCEDIR'); IF NOT _direction IN ('direct','inverse') THEN RAISE EXCEPTION 'invalid reference dir for class = % attr = % value = %', _class, _attr, _direction; END IF; RETURN _direction; END $$; gDROP FUNCTION public._cm3_attribute_reference_direction_get(_class regclass, _attr character varying); publicpostgresfalse1255232791@_cm3_attribute_reference_domain_get(regclass, character varying)FUNCTIONCREATE FUNCTION public._cm3_attribute_reference_domain_get(_class regclass, _attr character varying) RETURNS regclass LANGUAGE sql AS $$ SELECT _cm3_utils_name_to_regclass('Map_' || _cm3_attribute_comment_get(_class, _attr, 'REFERENCEDOM')) $$; dDROP FUNCTION public._cm3_attribute_reference_domain_get(_class regclass, _attr character varying); publicpostgresfalse1255232792?_cm3_attribute_reference_is_direct(regclass, character varying)FUNCTIONCREATE FUNCTION public._cm3_attribute_reference_is_direct(_class regclass, _attr character varying) RETURNS boolean LANGUAGE plpgsql AS $$ BEGIN RETURN _cm3_attribute_reference_direction_get(_class, _attr) = 'direct'; END $$; cDROP FUNCTION public._cm3_attribute_reference_is_direct(_class regclass, _attr character varying); publicpostgresfalse1255232793F_cm3_attribute_reference_target_class_get(regclass, character varying)FUNCTION=CREATE FUNCTION public._cm3_attribute_reference_target_class_get(_class regclass, _attr character varying) RETURNS regclass LANGUAGE plpgsql STABLE AS $$ BEGIN RETURN _cm3_domain_target_class_get(_cm3_attribute_reference_domain_get(_class, _attr), _cm3_attribute_reference_is_direct(_class, _attr)); END $$; jDROP FUNCTION public._cm3_attribute_reference_target_class_get(_class regclass, _attr character varying); publicpostgresfalse12552327947_cm3_attribute_sqltype_get(regclass, character varying)FUNCTIONLCREATE FUNCTION public._cm3_attribute_sqltype_get(_class regclass, _attr character varying) RETURNS character varying LANGUAGE sql STABLE AS $$ SELECT _cm3_utils_build_sqltype_string(pg_attribute.atttypid, pg_attribute.atttypmod) FROM pg_attribute WHERE pg_attribute.attrelid = _class AND pg_attribute.attname = _attr; $$; [DROP FUNCTION public._cm3_attribute_sqltype_get(_class regclass, _attr character varying); publicpostgresfalse12552327956_cm3_attribute_unique_get(regclass, character varying)FUNCTIONeCREATE FUNCTION public._cm3_attribute_unique_get(_class regclass, _attr character varying) RETURNS boolean LANGUAGE plpgsql AS $$ BEGIN RETURN EXISTS (SELECT * FROM pg_attribute a JOIN pg_index i ON a.attrelid = i.indrelid AND a.attnum = i.indkey[0] WHERE i.indnatts = 1 AND i.indisunique AND a.attrelid = _class AND a.attname = _attr); END $$; ZDROP FUNCTION public._cm3_attribute_unique_get(_class regclass, _attr character varying); publicpostgresfalse12552327966_cm3_attribute_unique_set(regclass, character varying)FUNCTIONCREATE FUNCTION public._cm3_attribute_unique_set(_class regclass, _attr character varying) RETURNS void LANGUAGE plpgsql AS $$ BEGIN PERFORM _cm3_attribute_unique_set(_class, _attr, TRUE); END $$; ZDROP FUNCTION public._cm3_attribute_unique_set(_class regclass, _attr character varying); publicpostgresfalse1255232797?_cm3_attribute_unique_set(regclass, character varying, boolean)FUNCTIONCREATE FUNCTION public._cm3_attribute_unique_set(_class regclass, _attr character varying, _unique boolean) RETURNS void LANGUAGE plpgsql AS $$ DECLARE c1 int; c2 int; BEGIN IF _cm3_attribute_unique_get(_class, _attr) <> _unique THEN IF _unique THEN IF _cm3_class_is_superclass(_class) THEN RAISE EXCEPTION 'CM_FORBIDDEN_OPERATION: error setting unique flag on attribute %.%; superclass attributes cannot be unique', _class, _attr; END IF; IF _cm3_class_is_simple(_class) THEN EXECUTE format('SELECT COUNT(DISTINCT %I) FROM %s', _attr, _class) INTO c1; EXECUTE format('SELECT COUNT(%I) FROM %s', _attr, _class) INTO c2; ELSE EXECUTE format('SELECT COUNT(DISTINCT %I) FROM %s WHERE "Status" = ''A''', _attr, _class) INTO c1; EXECUTE format('SELECT COUNT(%I) FROM %s WHERE "Status" = ''A''', _attr, _class) INTO c2; END IF; IF c1 <> c2 THEN RAISE EXCEPTION 'CM_FORBIDDEN_OPERATION: error setting unique flag on attribute %.%: there are active cards with non unique values for this attribute', _class, _attr; END IF; IF _cm3_class_is_simple(_class) THEN PERFORM _cm3_attribute_index_delete(_class, _attr); EXECUTE format('ALTER TABLE %s ADD UNIQUE (%I)', _class, _attr); ELSE PERFORM _cm3_attribute_index_unique_create(_class, _attr); END IF; ELSE PERFORM _cm3_attribute_index_delete(_class, _attr); IF _cm3_class_is_simple(_class) THEN EXECUTE format('ALTER TABLE %s DROP UNIQUE (%I)', _class, _attr); END IF; END IF; END IF; END $$; kDROP FUNCTION public._cm3_attribute_unique_set(_class regclass, _attr character varying, _unique boolean); publicpostgresfalse12552327986_cm3_attribute_validate_features_and_type(jsonb, text)FUNCTIONCREATE FUNCTION public._cm3_attribute_validate_features_and_type(_comment jsonb, _type text) RETURNS void LANGUAGE plpgsql AS $$ BEGIN IF (SELECT EXISTS (SELECT * FROM jsonb_each_text(_comment) WHERE key IN ('REFERENCEDOM','LOOKUP','FKTARGETCLASS') AND coalesce(value,'') <> '' )) AND _type NOT IN ('int8','bigint') THEN RAISE EXCEPTION 'CM: attribute type error: this attribute should have sql type int8/bigint, has type % instead', _type; END IF; END $$; \DROP FUNCTION public._cm3_attribute_validate_features_and_type(_comment jsonb, _type text); publicpostgresfalse1255232799"_cm3_card_delete(regclass, bigint)FUNCTIONCREATE FUNCTION public._cm3_card_delete(_class regclass, _card_id bigint) RETURNS void LANGUAGE plpgsql AS $$ BEGIN IF _cm3_class_is_simple(_class) THEN RAISE DEBUG 'deleting card from simple class = % with id = %', _class, _card_id; EXECUTE format('DELETE FROM %s WHERE "Id" = %L', _class, _card_id); ELSE RAISE DEBUG 'deleting card from standard class = % with id = %', _class, _card_id; EXECUTE format('UPDATE %s SET "Status" = ''N'' WHERE "Id" = %L', _class, _card_id); END IF; END $$; IDROP FUNCTION public._cm3_card_delete(_class regclass, _card_id bigint); publicpostgresfalse1255232800+_cm3_card_description_get(regclass, bigint)FUNCTIONCREATE FUNCTION public._cm3_card_description_get(_class regclass, _card_id bigint) RETURNS character varying LANGUAGE plpgsql AS $$ DECLARE _description VARCHAR; _ignore_tenant_policies VARCHAR; BEGIN IF _card_id IS NULL THEN RETURN NULL; ELSE _ignore_tenant_policies = current_setting('cmdbuild.ignore_tenant_policies'); SET SESSION cmdbuild.ignore_tenant_policies = 'true'; IF _cm3_class_is_simple(_class) THEN EXECUTE format('SELECT "Description" FROM %s WHERE "Id" = %L', _class, _card_id) INTO _description; ELSE EXECUTE format('SELECT "Description" FROM %s WHERE "Id" = %L AND "Status" = ''A''', _class, _card_id) INTO _description; END IF; SET SESSION cmdbuild.ignore_tenant_policies = _ignore_tenant_policies; RETURN _description; END IF; END $$; RDROP FUNCTION public._cm3_card_description_get(_class regclass, _card_id bigint); publicpostgresfalse1255232801@_cm3_card_exists_with_code(regclass, character varying, boolean)FUNCTIONCREATE FUNCTION public._cm3_card_exists_with_code(_class regclass, _code character varying, _include_deleted boolean) RETURNS boolean LANGUAGE sql STABLE AS $$ SELECT _cm3_card_exists_with_value(_class, 'Code', _code, _include_deleted); $$; uDROP FUNCTION public._cm3_card_exists_with_code(_class regclass, _code character varying, _include_deleted boolean); publicpostgresfalse12552328023_cm3_card_exists_with_id(regclass, bigint, boolean)FUNCTIONCREATE FUNCTION public._cm3_card_exists_with_id(_class regclass, _card_id bigint, _include_deleted boolean) RETURNS boolean LANGUAGE sql STABLE AS $$ SELECT _cm3_card_exists_with_value(_class, 'Id', _card_id, _include_deleted); $$; kDROP FUNCTION public._cm3_card_exists_with_id(_class regclass, _card_id bigint, _include_deleted boolean); publicpostgresfalse1255232803@_cm3_card_exists_with_value(regclass, character varying, bigint)FUNCTIONCREATE FUNCTION public._cm3_card_exists_with_value(_class regclass, _attr character varying, _value bigint) RETURNS boolean LANGUAGE plpgsql AS $$ BEGIN RETURN _cm3_card_exists_with_value(_class,_attr,_value,FALSE); END $$; kDROP FUNCTION public._cm3_card_exists_with_value(_class regclass, _attr character varying, _value bigint); publicpostgresfalse1255232804K_cm3_card_exists_with_value(regclass, character varying, character varying)FUNCTIONCREATE FUNCTION public._cm3_card_exists_with_value(_class regclass, _attr character varying, _value character varying) RETURNS boolean LANGUAGE plpgsql AS $$ BEGIN RETURN _cm3_card_exists_with_value(_class,_attr,_value,FALSE); END $$; vDROP FUNCTION public._cm3_card_exists_with_value(_class regclass, _attr character varying, _value character varying); publicpostgresfalse1255232805I_cm3_card_exists_with_value(regclass, character varying, bigint, boolean)FUNCTIONdCREATE FUNCTION public._cm3_card_exists_with_value(_class regclass, _attr character varying, _value bigint, _include_deleted boolean) RETURNS boolean LANGUAGE plpgsql AS $$ DECLARE _res boolean; BEGIN IF _value IS NULL THEN RETURN FALSE; ELSEIF _cm3_class_is_standard(_class) AND NOT _include_deleted THEN EXECUTE format('SELECT EXISTS ( SELECT "Id" FROM %s WHERE %I = %L AND "Status"=''A'' )', _class, _attr, _value) INTO _res; ELSE EXECUTE format('SELECT EXISTS ( SELECT "Id" FROM %s WHERE %I = %L )', _class, _attr, _value) INTO _res; END IF; RETURN _res; END $$; DROP FUNCTION public._cm3_card_exists_with_value(_class regclass, _attr character varying, _value bigint, _include_deleted boolean); publicpostgresfalse1255232806T_cm3_card_exists_with_value(regclass, character varying, character varying, boolean)FUNCTIONoCREATE FUNCTION public._cm3_card_exists_with_value(_class regclass, _attr character varying, _value character varying, _include_deleted boolean) RETURNS boolean LANGUAGE plpgsql AS $$ DECLARE _res boolean; BEGIN IF _value IS NULL THEN RETURN FALSE; ELSEIF _cm3_class_is_standard(_class) AND NOT _include_deleted THEN EXECUTE format('SELECT EXISTS ( SELECT "Id" FROM %s WHERE %I = %L AND "Status"=''A'' )', _class, _attr, _value) INTO _res; ELSE EXECUTE format('SELECT EXISTS ( SELECT "Id" FROM %s WHERE %I = %L )', _class, _attr, _value) INTO _res; END IF; RETURN _res; END $$; DROP FUNCTION public._cm3_card_exists_with_value(_class regclass, _attr character varying, _value character varying, _include_deleted boolean); publicpostgresfalse1255232807(_cm3_card_list_at_date(anyelement, date)FUNCTION~CREATE FUNCTION public._cm3_card_list_at_date(_any anyelement, _date date) RETURNS SETOF anyelement LANGUAGE plpgsql AS $$ BEGIN RETURN QUERY EXECUTE format('SELECT * FROM %s WHERE "BeginDate" < (%L::date+1)::timestamptz AND ("Status" = ''A'' OR ("Status" = ''U'' AND "EndDate" >= (%L::date+1)::timestamptz))', pg_typeof(_any)::varchar::regclass, _date, _date); END $$; JDROP FUNCTION public._cm3_card_list_at_date(_any anyelement, _date date); publicpostgresfalse1255232808(_cm3_card_metadata_get(regclass, bigint)FUNCTIONCREATE FUNCTION public._cm3_card_metadata_get(_classe regclass, _card bigint) RETURNS jsonb LANGUAGE plpgsql AS $$ BEGIN RETURN COALESCE((SELECT "Data" FROM "_CardMetadata" WHERE "OwnerClass" = _classe AND "OwnerCard" = _card AND "Status" = 'A'),'{}'::jsonb); END $$; MDROP FUNCTION public._cm3_card_metadata_get(_classe regclass, _card bigint); publicpostgresfalse1255232809/_cm3_card_metadata_set(regclass, bigint, jsonb)FUNCTIONCREATE FUNCTION public._cm3_card_metadata_set(_classe regclass, _card bigint, _metadata jsonb) RETURNS void LANGUAGE plpgsql AS $$ BEGIN IF NOT EXISTS (SELECT * FROM "_CardMetadata" WHERE "OwnerClass" = _classe AND "OwnerCard" = _card AND "Status" = 'A') THEN INSERT INTO "_CardMetadata" ("OwnerClass","OwnerCard","Data") VALUES (_classe,_card,_metadata); ELSE UPDATE "_CardMetadata" SET "Data" = _metadata WHERE "OwnerClass" = _classe AND "OwnerCard" = _card AND "Status" = 'A'; END IF; END $$; ^DROP FUNCTION public._cm3_card_metadata_set(_classe regclass, _card bigint, _metadata jsonb); publicpostgresfalse1255232810N_cm3_card_metadata_set(regclass, bigint, character varying, character varying)FUNCTION*CREATE FUNCTION public._cm3_card_metadata_set(_classe regclass, _card bigint, _key character varying, _value character varying) RETURNS void LANGUAGE sql AS $$ SELECT _cm3_card_metadata_set( _classe, _card, _cm3_card_metadata_get(_classe, _card) || jsonb_build_object(_key, _value)); $$; DROP FUNCTION public._cm3_card_metadata_set(_classe regclass, _card bigint, _key character varying, _value character varying); publicpostgresfalse1255232811"_cm3_class_ancestor_list(regclass)FUNCTIONCREATE FUNCTION public._cm3_class_ancestor_list(_class regclass) RETURNS SETOF regclass LANGUAGE plpgsql AS $$ DECLARE _ancestor regclass; _parent regclass; BEGIN IF _cm3_utils_regclass_to_name(_class) <> 'Class' THEN _parent = _cm3_class_parent_get(_class); IF _parent IS NOT NULL THEN FOR _ancestor IN SELECT _cm3_class_ancestor_list(_parent) LOOP RETURN NEXT _ancestor; END LOOP; RETURN NEXT _parent; END IF; END IF; END $$; @DROP FUNCTION public._cm3_class_ancestor_list(_class regclass); publicpostgresfalse12552328126_cm3_class_comment_delete(regclass, character varying)FUNCTIONCREATE FUNCTION public._cm3_class_comment_delete(_class regclass, _key character varying) RETURNS void LANGUAGE sql AS $$ SELECT _cm3_class_comment_set(_class, _cm3_class_comment_get_jsonb(_class) - _key); $$; YDROP FUNCTION public._cm3_class_comment_delete(_class regclass, _key character varying); publicpostgresfalse1255232813 _cm3_class_comment_get(regclass)FUNCTIONCREATE FUNCTION public._cm3_class_comment_get(_class regclass) RETURNS character varying LANGUAGE sql STABLE AS $$ SELECT description FROM pg_description WHERE objoid = _class AND objsubid = 0; $$; >DROP FUNCTION public._cm3_class_comment_get(_class regclass); publicpostgresfalse12552328143_cm3_class_comment_get(regclass, character varying)FUNCTIONCREATE FUNCTION public._cm3_class_comment_get(_class regclass, _key character varying) RETURNS character varying LANGUAGE sql STABLE AS $$ SELECT coalesce(_cm3_class_comment_get_jsonb(_class)->>_key, ''); $$; VDROP FUNCTION public._cm3_class_comment_get(_class regclass, _key character varying); publicpostgresfalse1255232815&_cm3_class_comment_get_jsonb(regclass)FUNCTIONCREATE FUNCTION public._cm3_class_comment_get_jsonb(_class regclass) RETURNS jsonb LANGUAGE sql STABLE AS $$ SELECT _cm3_comment_to_jsonb(_cm3_class_comment_get(_class)); $$; DDROP FUNCTION public._cm3_class_comment_get_jsonb(_class regclass); publicpostgresfalse1255232816_cm3_class_comment_keys()FUNCTIONCREATE FUNCTION public._cm3_class_comment_keys() RETURNS SETOF character varying LANGUAGE sql IMMUTABLE AS $$ SELECT DISTINCT unnest(ARRAY[ 'LABEL','CLASS1','CLASS2','TYPE','DESCRDIR','DESCRINV','CARDIN','MASTERDETAIL','MDLABEL','MDFILTER','DISABLED1','DISABLED2','INDEX1','INDEX2','ACTIVE','MODE', -- domain 'DESCR','SUPERCLASS','TYPE','MTMODE','USERSTOPPABLE','WFSTATUSATTR','WFSAVE','ATTACHMENT_TYPE_LOOKUP','ATTACHMENT_DESCRIPTION_MODE','ACTIVE','MODE' -- class ]); $$; 0DROP FUNCTION public._cm3_class_comment_keys(); publicpostgresfalse1255232817'_cm3_class_comment_set(regclass, jsonb)FUNCTIONyCREATE FUNCTION public._cm3_class_comment_set(_class regclass, _comment jsonb) RETURNS void LANGUAGE plpgsql AS $$ DECLARE _key varchar; BEGIN FOR _key IN SELECT x FROM jsonb_object_keys(_comment) x WHERE CASE WHEN _cm3_utils_regclass_to_name(_class) LIKE 'Map_%' THEN x NOT IN ('LABEL','CLASS1','CLASS2','TYPE','DESCRDIR','DESCRINV','CARDIN','MASTERDETAIL','MDLABEL','MDFILTER','DISABLED1','DISABLED2','INDEX1','INDEX2','ACTIVE','MODE') ELSE x NOT IN ('DESCR','SUPERCLASS','TYPE','MTMODE','USERSTOPPABLE','WFSTATUSATTR','WFSAVE','ATTACHMENT_TYPE_LOOKUP','ATTACHMENT_DESCRIPTION_MODE','ACTIVE','MODE') END LOOP RAISE WARNING 'CM: invalid comment for class = %: invalid comment key = %', _class, _key; END LOOP; RAISE NOTICE 'set class comment % = %', _class, _comment; EXECUTE format('COMMENT ON TABLE %s IS %L', _class, _cm3_comment_from_jsonb(_comment)); END $$; NDROP FUNCTION public._cm3_class_comment_set(_class regclass, _comment jsonb); publicpostgresfalse1255232818F_cm3_class_comment_set(regclass, character varying, character varying)FUNCTIONCREATE FUNCTION public._cm3_class_comment_set(_class regclass, _key character varying, _value character varying) RETURNS void LANGUAGE sql AS $$ SELECT _cm3_class_comment_set(_class, _cm3_class_comment_get_jsonb(_class) || jsonb_build_object(_key, _value)); $$; pDROP FUNCTION public._cm3_class_comment_set(_class regclass, _key character varying, _value character varying); publicpostgresfalse1255232819$_cm3_class_create(character varying)FUNCTIONCREATE FUNCTION public._cm3_class_create(_class_name character varying) RETURNS regclass LANGUAGE plpgsql AS $$ BEGIN RETURN _cm3_class_create(_class_name, '{}'::jsonb); END $$; GDROP FUNCTION public._cm3_class_create(_class_name character varying); publicpostgresfalse1255232820+_cm3_class_create(character varying, jsonb)FUNCTIONCREATE FUNCTION public._cm3_class_create(_class_name character varying, _features jsonb) RETURNS regclass LANGUAGE plpgsql AS $$ BEGIN RETURN _cm3_class_create(_class_name, _cm3_utils_name_to_regclass(_features->>'PARENT'), _features - 'PARENT'); END $$; XDROP FUNCTION public._cm3_class_create(_class_name character varying, _features jsonb); publicpostgresfalse1255232821._cm3_class_create(character varying, regclass)FUNCTIONCREATE FUNCTION public._cm3_class_create(_class_name character varying, _class_parent regclass) RETURNS regclass LANGUAGE plpgsql AS $$ BEGIN RETURN _cm3_class_create(_class_name, _class_parent, '{}'); END $$; _DROP FUNCTION public._cm3_class_create(_class_name character varying, _class_parent regclass); publicpostgresfalse12552328227_cm3_class_create(character varying, character varying)FUNCTIONCREATE FUNCTION public._cm3_class_create(_class_name character varying, _features character varying) RETURNS regclass LANGUAGE plpgsql AS $$ BEGIN RETURN _cm3_class_create(_class_name, _cm3_comment_to_jsonb(_features)); END $$; dDROP FUNCTION public._cm3_class_create(_class_name character varying, _features character varying); publicpostgresfalse12552328235_cm3_class_create(character varying, regclass, jsonb)FUNCTIONCREATE FUNCTION public._cm3_class_create(_class_name character varying, _class_parent regclass, _features jsonb) RETURNS regclass LANGUAGE plpgsql AS $_$ DECLARE _class_type varchar; _class_is_simple boolean; _class_is_standard boolean; _class_is_superclass boolean; _class regclass; _history regclass; BEGIN _class_type = coalesce(_features->>'TYPE', 'class'); _features = _features || jsonb_build_object('TYPE', _class_type); IF _class_type !~ '^(simpleclass|class)$' THEN RAISE EXCEPTION 'CM: invalid class type = "%"', _class_type; END IF; _class_is_simple = _class_type = 'simpleclass'; _class_is_standard = _class_type = 'class'; IF _class_is_simple THEN IF _class_parent IS NOT NULL THEN RAISE EXCEPTION 'CM: cannot create simple class with a parent'; END IF; _class_parent = '"SimpleClass"'::regclass; END IF; IF _class_is_standard THEN _class_parent = coalesce(_class_parent, '"Class"'::regclass); IF NOT _cm3_class_is_superclass(_class_parent) THEN RAISE EXCEPTION 'CM: cannot extend class = % (it is not a superclass)', _class_parent; END IF; END IF; EXECUTE format('CREATE TABLE %s (CONSTRAINT "%s_pkey" PRIMARY KEY ("Id")) INHERITS (%s)', _cm3_utils_name_escape(_class_name), _cm3_utils_name_to_basename(_class_name), _class_parent); _class = _cm3_utils_name_to_regclass(_class_name); PERFORM _cm3_class_features_set(_class, _features); EXECUTE format('COMMENT ON COLUMN %s."Id" IS ''MODE: reserved''', _class); _class_is_superclass = _cm3_class_is_superclass(_class); RAISE NOTICE 'create class = % parent = % features = % ', _class, _class_parent, _features; PERFORM _cm3_class_utils_copy_superclass_attribute_groups(_class, _class_parent); PERFORM _cm3_class_utils_copy_superclass_attribute_features(_class, _class_parent); IF _class_is_simple THEN EXECUTE format('CREATE TRIGGER "_cm3_card_prepare_record" BEFORE INSERT OR UPDATE ON %s FOR EACH ROW EXECUTE PROCEDURE _cm3_trigger_simplecard_prepare_record()', _class); EXECUTE format('CREATE TRIGGER "_cm3_card_cascade_delete_on_relations" AFTER DELETE ON %s FOR EACH ROW EXECUTE PROCEDURE _cm3_trigger_simplecard_cascade_delete_on_relations()', _class); PERFORM _cm3_attribute_index_create(_class, 'BeginDate'); END IF; IF _class_is_standard THEN PERFORM _cm3_utils_class_trigger_copy(_class_parent, _class); END IF; IF _class_is_standard AND NOT _class_is_superclass THEN EXECUTE format('CREATE TRIGGER "_cm3_card_prepare_record" BEFORE INSERT OR UPDATE OR DELETE ON %s FOR EACH ROW EXECUTE PROCEDURE _cm3_trigger_card_prepare_record()', _class); EXECUTE format('CREATE TRIGGER "_cm3_card_create_history" AFTER UPDATE ON %s FOR EACH ROW EXECUTE PROCEDURE _cm3_trigger_card_create_history()', _class); EXECUTE format('CREATE TRIGGER "_cm3_card_cascade_delete_on_relations" AFTER UPDATE ON %s FOR EACH ROW EXECUTE PROCEDURE _cm3_trigger_card_cascade_delete_on_relations()', _class); PERFORM _cm3_attribute_index_create(_class, 'Code'); PERFORM _cm3_attribute_index_create(_class, 'Description'); PERFORM _cm3_attribute_index_create(_class, 'IdClass'); EXECUTE format('CREATE TABLE "%s_history" ( PRIMARY KEY ("Id"), CONSTRAINT "_cm3_CurrentId_foreign_key" FOREIGN KEY ("CurrentId") REFERENCES %s ("Id"), CONSTRAINT "_cm3_Status_check" CHECK ("Status" = ''U'') ) INHERITS (%s)', _class_name, _class, _class); _history = _cm3_utils_regclass_to_history(_class); PERFORM _cm3_attribute_index_create(_history, 'CurrentId'); END IF; IF _class_is_superclass THEN EXECUTE format('CREATE TRIGGER "_cm3_superclass_forbid_operations" BEFORE INSERT OR DELETE ON %s FOR EACH ROW EXECUTE PROCEDURE _cm3_trigger_superclass_forbid_operations()', _class); END IF; PERFORM _cm3_multitenant_mode_change(_class, NULL, _features->>'MTMODE'); RETURN _class; END $_$; pDROP FUNCTION public._cm3_class_create(_class_name character varying, _class_parent regclass, _features jsonb); publicpostgresfalse1255232824A_cm3_class_create(character varying, regclass, character varying)FUNCTIONCREATE FUNCTION public._cm3_class_create(_class_name character varying, _class_parent regclass, _comment character varying) RETURNS regclass LANGUAGE plpgsql AS $$ BEGIN RETURN _cm3_class_create(_class_name, _class_parent, _cm3_comment_to_jsonb(_comment)); END $$; {DROP FUNCTION public._cm3_class_create(_class_name character varying, _class_parent regclass, _comment character varying); publicpostgresfalse1255232825_cm3_class_delete(regclass)FUNCTION,CREATE FUNCTION public._cm3_class_delete(_class regclass) RETURNS void LANGUAGE plpgsql AS $$ DECLARE _record record; _found boolean; BEGIN IF EXISTS (SELECT d FROM _cm3_domain_list() d WHERE _cm3_class_comment_get(d,'CLASS1') = _cm3_utils_regclass_to_name(_class) OR _cm3_class_comment_get(d,'CLASS2') = _cm3_utils_regclass_to_name(_class)) THEN RAISE EXCEPTION 'CM: cannot delete class = %: class has domains', _class; ELSEIF _cm3_class_has_descendants(_class) THEN RAISE EXCEPTION 'CM: cannot delete class = %: class has descendants', _class; ELSEIF _cm3_class_has_records(_class) THEN RAISE EXCEPTION 'CM: cannot delete class = %: class has cards', _class; ELSEIF EXISTS ( SELECT * FROM _cm3_attribute_list_detailed() a WHERE a.owner <> _class AND a.comment->>'FKTARGETCLASS' = _cm3_utils_regclass_to_name(_class) ) THEN RAISE EXCEPTION 'CM: cannot delete class = %: class is foreignkey target', _class; END IF; PERFORM _cm3_attribute_delete_all(_class); UPDATE "_AttributeMetadata" SET "Status" = 'N' WHERE "Owner" = _class AND "Status" = 'A'; UPDATE "_ClassMetadata" SET "Status" = 'N' WHERE "Owner" = _class AND "Status" = 'A'; FOR _record IN SELECT * FROM _cm3_attribute_list_detailed() a WHERE a.owner <> _class AND a.sql_type = 'regclass' AND a.name <> 'IdClass' LOOP IF _cm3_class_has_history(_record.owner) THEN EXECUTE format('SELECT EXISTS ( SELECT * FROM %s WHERE %I = %L::regclass AND "Status" = ''A'' )', _record.owner, _record.name, _class) INTO _found; ELSE EXECUTE format('SELECT EXISTS ( SELECT * FROM %s WHERE %I = %L::regclass )', _record.owner, _record.name, _class) INTO _found; END IF; IF _found THEN RAISE EXCEPTION 'CM: cannot delete class = %: class oid is referenced from record[s] of class = % attr = %', _class, _record.owner, _record.name; END IF; END LOOP; IF _cm3_class_has_history(_class) THEN EXECUTE format('DROP TABLE %s', _cm3_utils_regclass_to_history(_class)); END IF; EXECUTE format('DROP TABLE %s', _class); END $$; 9DROP FUNCTION public._cm3_class_delete(_class regclass); publicpostgresfalse1255232826_cm3_class_exists(regclass)FUNCTIONCREATE FUNCTION public._cm3_class_exists(_class regclass) RETURNS boolean LANGUAGE sql STABLE AS $$ SELECT NULLIF(_cm3_class_comment_get(_class, 'TYPE'), '') IS NOT NULL;--TODO check this $$; 9DROP FUNCTION public._cm3_class_exists(_class regclass); publicpostgresfalse1255232827_cm3_class_exists(text)FUNCTIONCREATE FUNCTION public._cm3_class_exists(_class_name text) RETURNS boolean LANGUAGE sql STABLE AS $$ SELECT _cm3_class_exists(_class_name::varchar); $$; :DROP FUNCTION public._cm3_class_exists(_class_name text); publicpostgresfalse1255232828$_cm3_class_exists(character varying)FUNCTIONCREATE FUNCTION public._cm3_class_exists(_class_name character varying) RETURNS boolean LANGUAGE sql STABLE AS $$ SELECT _cm3_utils_name_to_regclass(_class_name) IS NOT NULL; $$; GDROP FUNCTION public._cm3_class_exists(_class_name character varying); publicpostgresfalse12552328297_cm3_class_features_delete(regclass, character varying)FUNCTIONCREATE FUNCTION public._cm3_class_features_delete(_classe regclass, _key character varying) RETURNS void LANGUAGE plpgsql AS $$ BEGIN PERFORM _cm3_class_features_set(_classe, _cm3_class_features_get(_classe) - _key); END $$; [DROP FUNCTION public._cm3_class_features_delete(_classe regclass, _key character varying); publicpostgresfalse1255232830!_cm3_class_features_get(regclass)FUNCTIONCREATE FUNCTION public._cm3_class_features_get(_classe regclass) RETURNS jsonb LANGUAGE plpgsql AS $$ BEGIN RETURN _cm3_class_metadata_get(_classe) || _cm3_class_comment_get_jsonb(_classe); END $$; @DROP FUNCTION public._cm3_class_features_get(_classe regclass); publicpostgresfalse12552328314_cm3_class_features_get(regclass, character varying)FUNCTIONCREATE FUNCTION public._cm3_class_features_get(_classe regclass, _key character varying) RETURNS character varying LANGUAGE plpgsql AS $$ BEGIN RETURN coalesce(_cm3_class_features_get(_classe)->>_key, ''); END $$; XDROP FUNCTION public._cm3_class_features_get(_classe regclass, _key character varying); publicpostgresfalse1255232832(_cm3_class_features_set(regclass, jsonb)FUNCTIONCREATE FUNCTION public._cm3_class_features_set(_classe regclass, _features jsonb) RETURNS void LANGUAGE plpgsql AS $$ BEGIN PERFORM _cm3_class_comment_set(_classe, (SELECT coalesce(jsonb_object_agg(key, value), '{}'::jsonb) FROM jsonb_each_text(_features) WHERE key IN (SELECT _cm3_class_comment_keys()))); PERFORM _cm3_class_metadata_set(_classe, (SELECT coalesce(jsonb_object_agg(key, value), '{}'::jsonb) FROM jsonb_each_text(_features) WHERE key NOT IN (SELECT _cm3_class_comment_keys()))); END $$; QDROP FUNCTION public._cm3_class_features_set(_classe regclass, _features jsonb); publicpostgresfalse1255232833G_cm3_class_features_set(regclass, character varying, character varying)FUNCTIONCREATE FUNCTION public._cm3_class_features_set(_classe regclass, _key character varying, _value character varying) RETURNS void LANGUAGE plpgsql AS $$ BEGIN PERFORM _cm3_class_features_set(_classe, _cm3_class_features_get(_classe) || jsonb_build_object(_key, _value)); END $$; rDROP FUNCTION public._cm3_class_features_set(_classe regclass, _key character varying, _value character varying); publicpostgresfalse1255232834+_cm3_class_features_update(regclass, jsonb)FUNCTIONCREATE FUNCTION public._cm3_class_features_update(_classe regclass, _features jsonb) RETURNS void LANGUAGE plpgsql AS $$ BEGIN PERFORM _cm3_class_features_set(_classe, _cm3_class_features_get(_classe) || _features); END $$; TDROP FUNCTION public._cm3_class_features_update(_classe regclass, _features jsonb); publicpostgresfalse1255232835$_cm3_class_has_descendants(regclass)FUNCTIONCREATE FUNCTION public._cm3_class_has_descendants(_class regclass) RETURNS boolean LANGUAGE sql AS $$ SELECT EXISTS(SELECT c FROM _cm3_class_list_descendant_classes_and_self(_class) c WHERE c <> _class); $$; BDROP FUNCTION public._cm3_class_has_descendants(_class regclass); publicpostgresfalse1255232836 _cm3_class_has_history(regclass)FUNCTIONCREATE FUNCTION public._cm3_class_has_history(_class regclass) RETURNS boolean LANGUAGE sql STABLE AS $$ SELECT ( _cm3_class_is_standard(_class) OR _cm3_class_is_domain(_class) ) AND NOT _cm3_class_is_superclass(_class); $$; >DROP FUNCTION public._cm3_class_has_history(_class regclass); publicpostgresfalse1255232837 _cm3_class_has_records(regclass)FUNCTIONCREATE FUNCTION public._cm3_class_has_records(_class regclass) RETURNS boolean LANGUAGE plpgsql AS $$ DECLARE _has_records boolean; BEGIN EXECUTE format('SELECT EXISTS (SELECT 1 FROM %s)', _class) INTO _has_records; RETURN _has_records; END $$; >DROP FUNCTION public._cm3_class_has_records(_class regclass); publicpostgresfalse1255232838_cm3_class_is_domain(regclass)FUNCTIONCREATE FUNCTION public._cm3_class_is_domain(_class regclass) RETURNS boolean LANGUAGE sql STABLE AS $$ SELECT _cm3_class_comment_get(_class,'TYPE') = 'domain'; $$; <DROP FUNCTION public._cm3_class_is_domain(_class regclass); publicpostgresfalse1255232839_cm3_class_is_history(regclass)FUNCTIONCREATE FUNCTION public._cm3_class_is_history(_class regclass) RETURNS boolean LANGUAGE sql STABLE AS $$ SELECT _cm3_utils_regclass_to_name(_class) LIKE '%_history'; $$; =DROP FUNCTION public._cm3_class_is_history(_class regclass); publicpostgresfalse1255232840_cm3_class_is_process(regclass)FUNCTIONCREATE FUNCTION public._cm3_class_is_process(_class regclass) RETURNS boolean LANGUAGE sql AS $$ SELECT '"Activity"'::regclass IN (SELECT _cm3_class_list_ancestors_and_self(_class)); $$; =DROP FUNCTION public._cm3_class_is_process(_class regclass); publicpostgresfalse1255232841_cm3_class_is_simple(regclass)FUNCTIONCREATE FUNCTION public._cm3_class_is_simple(_class regclass) RETURNS boolean LANGUAGE sql STABLE AS $$ SELECT _cm3_class_comment_get(_class,'TYPE') = 'simpleclass'; $$; <DROP FUNCTION public._cm3_class_is_simple(_class regclass); publicpostgresfalse1255232842*_cm3_class_is_simple_or_standard(regclass)FUNCTIONCREATE FUNCTION public._cm3_class_is_simple_or_standard(_class regclass) RETURNS boolean LANGUAGE sql STABLE AS $$ SELECT _cm3_class_comment_get(_class,'TYPE') IN ('class','simpleclass'); $$; HDROP FUNCTION public._cm3_class_is_simple_or_standard(_class regclass); publicpostgresfalse1255232843 _cm3_class_is_standard(regclass)FUNCTIONCREATE FUNCTION public._cm3_class_is_standard(_class regclass) RETURNS boolean LANGUAGE sql STABLE AS $$ SELECT _cm3_class_comment_get(_class,'TYPE') = 'class'; $$; >DROP FUNCTION public._cm3_class_is_standard(_class regclass); publicpostgresfalse1255232844"_cm3_class_is_superclass(regclass)FUNCTIONCREATE FUNCTION public._cm3_class_is_superclass(_class regclass) RETURNS boolean LANGUAGE sql STABLE AS $$ SELECT _cm3_class_comment_get(_class,'SUPERCLASS') = 'true'; $$; @DROP FUNCTION public._cm3_class_is_superclass(_class regclass); publicpostgresfalse1255232845_cm3_class_list()FUNCTION/CREATE FUNCTION public._cm3_class_list() RETURNS SETOF regclass LANGUAGE sql STABLE AS $$ SELECT oid::regclass FROM pg_class WHERE _cm3_class_is_simple_or_standard(oid) AND relnamespace = (SELECT oid FROM pg_namespace WHERE nspname='public') AND oid::regclass <> '"SimpleClass"'::regclass; $$; (DROP FUNCTION public._cm3_class_list(); publicpostgresfalse1255232846#_cm3_class_list_ancestors(regclass)FUNCTIONZCREATE FUNCTION public._cm3_class_list_ancestors(_class regclass) RETURNS SETOF regclass LANGUAGE plpgsql AS $$ DECLARE _parent regclass; BEGIN _parent = _cm3_class_parent_get(_class); IF _parent IS NOT NULL THEN RETURN QUERY SELECT _cm3_class_list_ancestors(_parent); RETURN NEXT _parent; END IF; END $$; ADROP FUNCTION public._cm3_class_list_ancestors(_class regclass); publicpostgresfalse1255232847,_cm3_class_list_ancestors_and_self(regclass)FUNCTIONCREATE FUNCTION public._cm3_class_list_ancestors_and_self(_class regclass) RETURNS SETOF regclass LANGUAGE plpgsql AS $$ BEGIN RETURN QUERY SELECT _cm3_class_list_ancestors(_class); RETURN NEXT _class; END $$; JDROP FUNCTION public._cm3_class_list_ancestors_and_self(_class regclass); publicpostgresfalse1255232848,_cm3_class_list_descendant_classes(regclass)FUNCTIONCREATE FUNCTION public._cm3_class_list_descendant_classes(_class regclass) RETURNS SETOF regclass LANGUAGE sql AS $$ SELECT c FROM _cm3_class_list_descendant_classes_and_self(_class) c WHERE c <> _class; $$; JDROP FUNCTION public._cm3_class_list_descendant_classes(_class regclass); publicpostgresfalse12552328495_cm3_class_list_descendant_classes_and_self(regclass)FUNCTIONCREATE FUNCTION public._cm3_class_list_descendant_classes_and_self(_class regclass) RETURNS SETOF regclass LANGUAGE sql AS $$ SELECT c FROM _cm3_class_list_descendants_and_self(_class) c WHERE _cm3_class_is_standard(c); $$; SDROP FUNCTION public._cm3_class_list_descendant_classes_and_self(_class regclass); publicpostgresfalse1255232850D_cm3_class_list_descendant_classes_and_self_not_superclass(regclass)FUNCTIONCREATE FUNCTION public._cm3_class_list_descendant_classes_and_self_not_superclass(_class regclass) RETURNS SETOF regclass LANGUAGE sql AS $$ SELECT c FROM _cm3_class_list_descendant_classes_and_self(_class) c WHERE NOT _cm3_class_is_superclass(c); $$; bDROP FUNCTION public._cm3_class_list_descendant_classes_and_self_not_superclass(_class regclass); publicpostgresfalse1255232851._cm3_class_list_descendants_and_self(regclass)FUNCTIONkCREATE FUNCTION public._cm3_class_list_descendants_and_self(_class regclass) RETURNS SETOF regclass LANGUAGE sql AS $$ SELECT _class UNION SELECT i.inhrelid::regclass FROM pg_catalog.pg_inherits i WHERE i.inhparent = _class UNION SELECT _cm3_class_list_descendants_and_self(i.inhrelid) FROM pg_catalog.pg_inherits i WHERE i.inhparent = _class; $$; LDROP FUNCTION public._cm3_class_list_descendants_and_self(_class regclass); publicpostgresfalse1255232852_cm3_class_list_detailed()FUNCTIONCREATE FUNCTION public._cm3_class_list_detailed() RETURNS TABLE(table_id integer, table_name character varying, features jsonb, is_process boolean, parent_id integer, parent_name character varying, ancestor_ids integer[], ancestor_names character varying[]) LANGUAGE sql STABLE AS $$ WITH _classes AS (SELECT c, _cm3_class_parent_get(c) AS p, _cm3_class_features_get(c) AS features, (SELECT array_agg(a) FROM _cm3_class_list_ancestors(c) a) ancestors FROM _cm3_class_list() c) SELECT c::oid::int, _cm3_utils_regclass_to_name(c), features, (SELECT '"Activity"'::regclass = ANY (ancestors) OR '"Activity"'::regclass = c), p::oid::int, _cm3_utils_regclass_to_name(p), (SELECT array_agg(a::oid::int) FROM unnest(ancestors) a), (SELECT array_agg(_cm3_utils_regclass_to_name(a)) FROM unnest(ancestors) a) FROM _classes; $$; 1DROP FUNCTION public._cm3_class_list_detailed(); publicpostgresfalse1255232853#_cm3_class_list_hierarchy(regclass)FUNCTIONCREATE FUNCTION public._cm3_class_list_hierarchy(_class regclass) RETURNS SETOF regclass LANGUAGE plpgsql AS $$ BEGIN RETURN QUERY SELECT * FROM _cm3_class_list_ancestors_and_self(_class) UNION SELECT * FROM _cm3_class_list_descendants_and_self(_class); END $$; ADROP FUNCTION public._cm3_class_list_hierarchy(_class regclass); publicpostgresfalse1255232854_cm3_class_list_simple()FUNCTION*CREATE FUNCTION public._cm3_class_list_simple() RETURNS SETOF regclass LANGUAGE sql STABLE AS $$ SELECT oid::regclass FROM pg_class WHERE _cm3_class_is_simple(oid) AND relnamespace = (SELECT oid FROM pg_namespace WHERE nspname='public') AND oid::regclass <> '"SimpleClass"'::regclass; $$; /DROP FUNCTION public._cm3_class_list_simple(); publicpostgresfalse1255232855_cm3_class_list_standard()FUNCTIONCREATE FUNCTION public._cm3_class_list_standard() RETURNS SETOF regclass LANGUAGE sql STABLE AS $$ SELECT oid::regclass FROM pg_class WHERE _cm3_class_is_standard(oid) AND relnamespace = (SELECT oid FROM pg_namespace WHERE nspname='public'); $$; 1DROP FUNCTION public._cm3_class_list_standard(); publicpostgresfalse1255232856!_cm3_class_metadata_get(regclass)FUNCTIONCREATE FUNCTION public._cm3_class_metadata_get(_classe regclass) RETURNS jsonb LANGUAGE plpgsql AS $$ BEGIN RETURN COALESCE((SELECT "Metadata" FROM "_ClassMetadata" WHERE "Owner" = _classe AND "Status" = 'A'),'{}'::jsonb); END $$; @DROP FUNCTION public._cm3_class_metadata_get(_classe regclass); publicpostgresfalse12552328574_cm3_class_metadata_get(regclass, character varying)FUNCTIONCREATE FUNCTION public._cm3_class_metadata_get(_classe regclass, _key character varying) RETURNS character varying LANGUAGE plpgsql AS $$ BEGIN RETURN jsonb_extract_path_text(_cm3_class_metadata_get(_classe),_key::text); END $$; XDROP FUNCTION public._cm3_class_metadata_get(_classe regclass, _key character varying); publicpostgresfalse1255232858(_cm3_class_metadata_set(regclass, jsonb)FUNCTIONCREATE FUNCTION public._cm3_class_metadata_set(_classe regclass, _metadata jsonb) RETURNS void LANGUAGE plpgsql AS $$ BEGIN _metadata = _cm3_utils_strip_null_or_empty(_metadata); IF EXISTS (SELECT 1 FROM "_ClassMetadata" WHERE "Owner" = _classe AND "Status" = 'A') THEN IF _metadata = '{}'::jsonb THEN UPDATE "_ClassMetadata" SET "Status" = 'N' WHERE "Owner" = _classe AND "Status" = 'A'; ELSE UPDATE "_ClassMetadata" SET "Metadata" = _metadata WHERE "Owner" = _classe AND "Status" = 'A'; END IF; ELSE IF _metadata <> '{}'::jsonb THEN INSERT INTO "_ClassMetadata" ("Owner","Metadata") VALUES (_classe,_metadata); END IF; END IF; END $$; QDROP FUNCTION public._cm3_class_metadata_set(_classe regclass, _metadata jsonb); publicpostgresfalse1255232859G_cm3_class_metadata_set(regclass, character varying, character varying)FUNCTIONqCREATE FUNCTION public._cm3_class_metadata_set(_classe regclass, _key character varying, _value character varying) RETURNS void LANGUAGE plpgsql AS $$ DECLARE _metadata jsonb; BEGIN _metadata = _cm3_class_metadata_get(_classe); _metadata = jsonb_set(_metadata,ARRAY[_key::text],to_jsonb(_value)); PERFORM _cm3_class_metadata_set(_classe,_metadata); END $$; rDROP FUNCTION public._cm3_class_metadata_set(_classe regclass, _key character varying, _value character varying); publicpostgresfalse1255232860"_cm3_class_modify(regclass, jsonb)FUNCTIONCREATE FUNCTION public._cm3_class_modify(_class regclass, _features jsonb) RETURNS void LANGUAGE plpgsql AS $$ DECLARE _current_features jsonb; BEGIN _current_features = _cm3_class_features_get(_class); IF _current_features->>'SUPERCLASS' <> _features->>'SUPERCLASS' THEN RAISE EXCEPTION 'CM: unable to change SUPERCLASS status of existing class: operation not allowed'; END IF; IF _current_features->>'TYPE' <> _features->>'TYPE' THEN RAISE EXCEPTION 'CM: unable to change TYPE of existing class: operation not allowed'; END IF; PERFORM _cm3_class_features_set(_class, _features); PERFORM _cm3_multitenant_mode_change(_class, _current_features->>'MTMODE', _features->>'MTMODE'); END $$; JDROP FUNCTION public._cm3_class_modify(_class regclass, _features jsonb); publicpostgresfalse1255232861._cm3_class_modify(regclass, character varying)FUNCTIONCREATE FUNCTION public._cm3_class_modify(_class regclass, _features character varying) RETURNS void LANGUAGE plpgsql AS $$ BEGIN PERFORM _cm3_class_modify(_class, _cm3_comment_to_jsonb(_features)); END $$; VDROP FUNCTION public._cm3_class_modify(_class regclass, _features character varying); publicpostgresfalse1255232862_cm3_class_parent_get(regclass)FUNCTIONCREATE FUNCTION public._cm3_class_parent_get(_classe regclass) RETURNS regclass LANGUAGE plpgsql AS $$ BEGIN RETURN (SELECT inhparent::regclass FROM pg_inherits WHERE inhrelid = _classe) ; END $$; >DROP FUNCTION public._cm3_class_parent_get(_classe regclass); publicpostgresfalse1255232863)_cm3_class_triggers_are_enabled(regclass)FUNCTIONCREATE FUNCTION public._cm3_class_triggers_are_enabled(_class regclass) RETURNS boolean LANGUAGE sql AS $$ SELECT (SELECT DISTINCT tgenabled FROM pg_trigger where tgrelid = _class AND tgisinternal = false) <> 'D'; --TODO check only cm triggers (??) $$; GDROP FUNCTION public._cm3_class_triggers_are_enabled(_class regclass); publicpostgresfalse1255232864%_cm3_class_triggers_disable(regclass)FUNCTIONSCREATE FUNCTION public._cm3_class_triggers_disable(_class regclass) RETURNS void LANGUAGE plpgsql AS $$ DECLARE _subclass regclass; BEGIN IF _cm3_class_is_superclass(_class) THEN FOR _subclass IN SELECT _cm3_class_list_descendant_classes_and_self_not_superclass(_class) LOOP PERFORM _cm3_class_triggers_disable(_subclass); END LOOP; ELSE EXECUTE format('ALTER TABLE %s DISABLE TRIGGER USER', _class); IF _cm3_class_has_history(_class) THEN EXECUTE format('ALTER TABLE "%s_history" DISABLE TRIGGER USER', _cm3_utils_regclass_to_name(_class)); END IF; END IF; END $$; CDROP FUNCTION public._cm3_class_triggers_disable(_class regclass); publicpostgresfalse1255232865$_cm3_class_triggers_enable(regclass)FUNCTIONOCREATE FUNCTION public._cm3_class_triggers_enable(_class regclass) RETURNS void LANGUAGE plpgsql AS $$ DECLARE _subclass regclass; BEGIN IF _cm3_class_is_superclass(_class) THEN FOR _subclass IN SELECT _cm3_class_list_descendant_classes_and_self_not_superclass(_class) LOOP PERFORM _cm3_class_triggers_enable(_subclass); END LOOP; ELSE EXECUTE format('ALTER TABLE %s ENABLE TRIGGER USER', _class); IF _cm3_class_has_history(_class) THEN EXECUTE format('ALTER TABLE "%s_history" ENABLE TRIGGER USER', _cm3_utils_regclass_to_name(_class)); END IF; END IF; END $$; BDROP FUNCTION public._cm3_class_triggers_enable(_class regclass); publicpostgresfalse1255232866#_cm3_class_triggers_list_detailed()FUNCTION0CREATE FUNCTION public._cm3_class_triggers_list_detailed() RETURNS TABLE(owner regclass, trigger_name character varying, trigger_when character varying, trigger_for_each character varying, trigger_function character varying, trigger_params character varying[]) LANGUAGE plpgsql AS $$ BEGIN RETURN QUERY EXECUTE (SELECT string_agg(format('SELECT %L::regclass AS owner,* FROM _cm3_class_triggers_list_detailed(%L)',c.x,c.x),' UNION ALL ') FROM (SELECT x FROM _cm3_class_list() x UNION SELECT x FROM _cm3_domain_list() x) c);--TODO improve this END $$; :DROP FUNCTION public._cm3_class_triggers_list_detailed(); publicpostgresfalse1255232867+_cm3_class_triggers_list_detailed(regclass)FUNCTIONaCREATE FUNCTION public._cm3_class_triggers_list_detailed(_class regclass) RETURNS TABLE(trigger_name character varying, trigger_when character varying, trigger_for_each character varying, trigger_function character varying, trigger_params character varying[]) LANGUAGE plpgsql AS $$ BEGIN RETURN QUERY SELECT t.tgname::varchar AS trigger_name, (CASE t.tgtype::int2 & cast(2 as int2) WHEN 0 THEN 'AFTER' ELSE 'BEFORE' END || ' ' || CASE t.tgtype::int2 & cast(28 as int2) WHEN 16 THEN 'UPDATE' WHEN 8 THEN 'DELETE' WHEN 4 THEN 'INSERT' WHEN 20 THEN 'INSERT OR UPDATE' WHEN 28 THEN 'INSERT OR UPDATE OR DELETE' WHEN 24 THEN 'UPDATE OR DELETE' WHEN 12 THEN 'INSERT OR DELETE' END)::varchar AS trigger_when, (CASE t.tgtype::int2 & cast(1 as int2) WHEN 0 THEN 'STATEMENT' ELSE 'ROW' END)::varchar AS trigger_for_each, p.proname::varchar AS trigger_function, _cm3_trigger_utils_tgargs_to_string_array(tgargs) AS trigger_params FROM pg_trigger t, pg_proc p WHERE tgrelid = _class AND t.tgfoid = p.oid AND tgisinternal = false ORDER BY t.tgname; END $$; IDROP FUNCTION public._cm3_class_triggers_list_detailed(_class regclass); publicpostgresfalse1255232868_cm3_class_type_get(regclass)FUNCTIONeCREATE FUNCTION public._cm3_class_type_get(_class regclass) RETURNS character varying LANGUAGE sql STABLE AS $$ SELECT CASE _cm3_class_comment_get(_class,'TYPE') WHEN 'domain' THEN 'domain' WHEN 'class' THEN 'class' WHEN 'simpleclass' THEN 'class' WHEN 'function' THEN 'function' ELSE 'unknown' END; $$; ;DROP FUNCTION public._cm3_class_type_get(_class regclass); publicpostgresfalse1255232869B_cm3_class_utils_attribute_groups_fix(regclass, character varying)FUNCTION<CREATE FUNCTION public._cm3_class_utils_attribute_groups_fix(_class regclass, _attr character varying) RETURNS void LANGUAGE plpgsql AS $$ DECLARE --TODO improve this (multiple function version) _group varchar; _super_class regclass; BEGIN _group = _cm3_attribute_features_get(_class, _attr, 'GROUP'); IF _group <> '' AND NOT EXISTS (SELECT * FROM "_AttributeGroup" WHERE "Code" = _group AND "Owner" = _class AND "Status" = 'A') THEN FOR _super_class IN WITH q AS (SELECT c,row_number() over() rn FROM _cm3_class_list_ancestors(_class) c) SELECT c FROM q ORDER BY rn DESC LOOP IF EXISTS (SELECT * FROM "_AttributeGroup" WHERE "Code" = _group AND "Owner" = _super_class AND "Status" = 'A') THEN RAISE NOTICE 'copy attribute group = % from class = % to class = %', _group, _super_class, _class; INSERT INTO "_AttributeGroup" ("Code", "Description", "Index", "Owner") SELECT "Code", "Description", COALESCE((SELECT MAX("Index")+1 FROM "_AttributeGroup" WHERE "Status" = 'A' AND "Owner" = _class), 1), _class FROM "_AttributeGroup" WHERE "Code" = _group AND "Owner" = _super_class AND "Status" = 'A'; RETURN; END IF; END LOOP; RAISE NOTICE 'auto create attribute group = % for class = %', _group, _class; INSERT INTO "_AttributeGroup" ("Code", "Description", "Index", "Owner") SELECT _group, _group, COALESCE((SELECT MAX("Index")+1 FROM "_AttributeGroup" WHERE "Status" = 'A' AND "Owner" = _class), 1), _class; END IF; END $$; fDROP FUNCTION public._cm3_class_utils_attribute_groups_fix(_class regclass, _attr character varying); publicpostgresfalse12552328701_cm3_class_utils_class_for_card(regclass, bigint)FUNCTION;CREATE FUNCTION public._cm3_class_utils_class_for_card(_superclass regclass, _card_id bigint) RETURNS regclass LANGUAGE plpgsql STABLE STRICT AS $_$ DECLARE _res regclass; BEGIN EXECUTE format('SELECT tableoid FROM %s WHERE "Id"= $1 LIMIT 1', _superclass) USING _card_id INTO _res; RETURN _res; END $_$; ]DROP FUNCTION public._cm3_class_utils_class_for_card(_superclass regclass, _card_id bigint); publicpostgresfalse 1255232871G_cm3_class_utils_copy_superclass_attribute_features(regclass, regclass)FUNCTION~CREATE FUNCTION public._cm3_class_utils_copy_superclass_attribute_features(_class regclass, _parent_class regclass) RETURNS void LANGUAGE plpgsql AS $$ DECLARE _attr varchar; BEGIN FOR _attr IN SELECT * FROM _cm3_attribute_list(_parent_class) LOOP PERFORM _cm3_attribute_features_set(_class, _attr, _cm3_attribute_features_get(_parent_class, _attr)); END LOOP; END $$; sDROP FUNCTION public._cm3_class_utils_copy_superclass_attribute_features(_class regclass, _parent_class regclass); publicpostgresfalse 1255232872E_cm3_class_utils_copy_superclass_attribute_groups(regclass, regclass)FUNCTIONCREATE FUNCTION public._cm3_class_utils_copy_superclass_attribute_groups(_class regclass, _parent_class regclass) RETURNS void LANGUAGE plpgsql AS $$ DECLARE _record record; BEGIN RAISE NOTICE 'copy attribute groups from class = % to class = %', _parent_class, _class; FOR _record IN SELECT "Code", "Description", "Index" FROM "_AttributeGroup" WHERE "Status" = 'A' AND "Owner" = _parent_class LOOP RAISE NOTICE 'copy attribute group = % from class = % to class = %', _record."Code", _parent_class, _class; INSERT INTO "_AttributeGroup" ("Code", "Description", "Index", "Owner") VALUES (_record."Code", _record."Description", _record."Index", _class); END LOOP; END $$; qDROP FUNCTION public._cm3_class_utils_copy_superclass_attribute_groups(_class regclass, _parent_class regclass); publicpostgresfalse 1255232873_cm3_comment_from_jsonb(jsonb)FUNCTIONCREATE FUNCTION public._cm3_comment_from_jsonb(_map jsonb) RETURNS character varying LANGUAGE sql IMMUTABLE AS $$ SELECT COALESCE((SELECT string_agg(format('%s: %s',key,value),'|') from jsonb_each_text(_map)), ''); $$; :DROP FUNCTION public._cm3_comment_from_jsonb(_map jsonb); publicpostgresfalse 1255232874;_cm3_comment_get_part(character varying, character varying)FUNCTIONCREATE FUNCTION public._cm3_comment_get_part(_comment character varying, _key character varying) RETURNS character varying LANGUAGE sql IMMUTABLE AS $$ SELECT _cm3_comment_to_jsonb(_comment)->>_key; $$; `DROP FUNCTION public._cm3_comment_get_part(_comment character varying, _key character varying); publicpostgresfalse 1255232875(_cm3_comment_to_jsonb(character varying)FUNCTIONCREATE FUNCTION public._cm3_comment_to_jsonb(_comment character varying) RETURNS jsonb LANGUAGE plpgsql IMMUTABLE AS $_$ DECLARE _map jsonb; _part varchar[]; BEGIN _map = '{}'::jsonb; FOR _part IN SELECT regexp_matches(unnest(string_to_array(_comment,'|')),'^ *([^:]+) *: *(.*)$') LOOP _map = jsonb_set(_map,ARRAY[(_part[1])],to_jsonb(_part[2])); END LOOP; RETURN _map; END $_$; HDROP FUNCTION public._cm3_comment_to_jsonb(_comment character varying); publicpostgresfalse1255232876-_cm3_domain_composite_index_rebuild(regclass)FUNCTIONCREATE FUNCTION public._cm3_domain_composite_index_rebuild(_domain regclass) RETURNS void LANGUAGE plpgsql AS $$ DECLARE _index_name varchar = format('_cm3_%s_relations', _cm3_utils_shrink_name_lon(_cm3_utils_regclass_to_name(_domain))); BEGIN EXECUTE format('DROP INDEX IF EXISTS %I', _index_name); EXECUTE format('CREATE UNIQUE INDEX %I ON %s ("IdDomain","IdClass1","IdObj1","IdClass2","IdObj2"%s) WHERE "Status" = ''A''', _index_name, _domain,( WITH q AS (SELECT string_agg(quote_ident(name),',') a FROM _cm3_attribute_list_detailed(_domain) WHERE comment->>'DOMAINKEY' = 'true') SELECT CASE a WHEN NULL THEN '' ELSE ','||a END FROM q)); END $$; LDROP FUNCTION public._cm3_domain_composite_index_rebuild(_domain regclass); publicpostgresfalse1255232877,_cm3_domain_create(character varying, jsonb)FUNCTIONQ CREATE FUNCTION public._cm3_domain_create(_name character varying, _features jsonb) RETURNS integer LANGUAGE plpgsql AS $_$ DECLARE _attr varchar; _domain regclass; _cardinality varchar; _history regclass; BEGIN IF NOT _name LIKE 'Map_%' THEN _name = format('Map_%s', _name); END IF; _features = _features || jsonb_build_object('TYPE', 'domain'); IF NOT _cm3_class_exists(_features->>'CLASS1') THEN RAISE 'invalid domain definition: class not found for name = %', _features->>'CLASS1'; END IF; IF NOT _cm3_class_exists(_features->>'CLASS2') THEN RAISE 'invalid domain definition: class not found for name = %', _features->>'CLASS2'; END IF; EXECUTE format('CREATE TABLE "%s" (PRIMARY KEY ("Id")) INHERITS ("Map")', _name, _name); _domain = _cm3_utils_name_to_regclass(_name); PERFORM _cm3_class_features_set(_domain, _features); PERFORM _cm3_attribute_copy_all_comments('"Map"'::regclass, _domain); EXECUTE format('CREATE TABLE "%s_history" (PRIMARY KEY ("Id")) INHERITS (%s)', _name, _domain); _history = _cm3_utils_regclass_to_history(_domain); EXECUTE format('ALTER TABLE %s ALTER COLUMN "EndDate" SET DEFAULT now()', _history); EXECUTE format('ALTER TABLE %s ADD CONSTRAINT "_cm3_CurrentId_fkey" FOREIGN KEY ("CurrentId") REFERENCES %s("Id")', _history, _domain); EXECUTE format('ALTER TABLE %s ADD CONSTRAINT "_cm3_Status_check" CHECK ("Status" = ''U'')', _history); PERFORM _cm3_attribute_index_create(_history, 'CurrentId'); _cardinality = _cm3_class_comment_get(_domain, 'CARDIN'); IF _cardinality !~ '^[1N]:[1N]$' THEN RAISE 'invalid domain CARDIN value = %', _cardinality; END IF; PERFORM _cm3_attribute_index_create(_domain, 'IdDomain'); PERFORM _cm3_attribute_index_create(_domain, 'IdObj1'); PERFORM _cm3_attribute_index_create(_domain, 'IdObj2'); PERFORM _cm3_domain_composite_index_rebuild(_domain); IF _cardinality LIKE '%:1' THEN EXECUTE format('CREATE UNIQUE INDEX "_cm3_%s_source" ON %s ("IdClass1", "IdObj1") WHERE "Status" = ''A''', _cm3_utils_shrink_name_lon(_name), _domain); END IF; IF _cardinality LIKE '1:%' THEN EXECUTE format('CREATE UNIQUE INDEX "_cm3_%s_target" ON %s ("IdClass2", "IdObj2") WHERE "Status" = ''A''', _cm3_utils_shrink_name_lon(_name), _domain); END IF; EXECUTE format('CREATE TRIGGER "_cm3_card_prepare_record" BEFORE INSERT OR UPDATE OR DELETE ON %s FOR EACH ROW EXECUTE PROCEDURE _cm3_trigger_card_prepare_record()', _domain); EXECUTE format('CREATE TRIGGER "_cm3_card_create_history" AFTER UPDATE ON %s FOR EACH ROW EXECUTE PROCEDURE _cm3_trigger_card_create_history()', _domain); RETURN _domain::oid::int; END $_$; SDROP FUNCTION public._cm3_domain_create(_name character varying, _features jsonb); publicpostgresfalse12552328788_cm3_domain_create(character varying, character varying)FUNCTIONCREATE FUNCTION public._cm3_domain_create(_name character varying, _comment character varying) RETURNS integer LANGUAGE sql AS $$ SELECT _cm3_domain_create(_name, _cm3_comment_to_jsonb(_comment)) $$; ^DROP FUNCTION public._cm3_domain_create(_name character varying, _comment character varying); publicpostgresfalse1255232879_cm3_domain_delete(regclass)FUNCTIONCREATE FUNCTION public._cm3_domain_delete(_domain regclass) RETURNS void LANGUAGE plpgsql AS $$ DECLARE _class regclass; _attr varchar; BEGIN IF _cm3_class_has_records(_domain) THEN RAISE EXCEPTION 'CM_CONTAINS_DATA: cannot delete domain %: table is not empty', _domain; END IF; FOR _class, _attr IN SELECT owner, name FROM _cm3_attribute_list() WHERE _cm3_attribute_features_get(owner, name, 'REFERENCEDOM') = _cm3_utils_regclass_to_domain_name(_domain) LOOP RAISE EXCEPTION 'CM: cannot delete domain %: found reference in class = % attr = %', _domain, _class, _attr; END LOOP; PERFORM _cm3_attribute_delete_all(_domain); EXECUTE format('DROP TABLE %s CASCADE', _domain); END $$; ;DROP FUNCTION public._cm3_domain_delete(_domain regclass); publicpostgresfalse1255232880_cm3_domain_list()FUNCTIONCREATE FUNCTION public._cm3_domain_list() RETURNS SETOF regclass LANGUAGE sql STABLE AS $$ SELECT oid::regclass FROM pg_class WHERE _cm3_class_is_domain(oid) AND relnamespace = (SELECT oid FROM pg_namespace WHERE nspname = 'public') AND oid <> '"Map"'::regclass; $$; )DROP FUNCTION public._cm3_domain_list(); publicpostgresfalse1255232881#_cm3_domain_modify(regclass, jsonb)FUNCTIONCREATE FUNCTION public._cm3_domain_modify(_domain regclass, _features jsonb) RETURNS void LANGUAGE plpgsql AS $$ DECLARE _current_features jsonb; BEGIN _current_features = _cm3_class_features_get(_domain); IF _current_features->'CARDIN' <> _features->'CARDIN' OR _current_features->'CLASS1' <> _features->'CLASS1' OR _current_features->'CLASS2' <> _features->'CLASS2' OR _current_features->'TYPE' <> _features->'TYPE' THEN RAISE EXCEPTION 'CM_FORBIDDEN_OPERATION: invalid comment features on domain = % current features = "%" new features = "%"', _domain, _cm3_comemnt_from_jsonb(_current_features), _cm3_comemnt_from_jsonb(_features); END IF; PERFORM _cm3_class_features_set(_domain, _features); END $$; LDROP FUNCTION public._cm3_domain_modify(_domain regclass, _features jsonb); publicpostgresfalse1255232882,_cm3_domain_source_check(regclass, regclass)FUNCTION@CREATE FUNCTION public._cm3_domain_source_check(_domain regclass, _source_class regclass) RETURNS void LANGUAGE plpgsql AS $$ BEGIN IF _source_class IS NULL OR NOT EXISTS (SELECT c FROM _cm3_class_list_descendant_classes_and_self_not_superclass(_cm3_utils_name_to_regclass(_cm3_class_comment_get(_domain, 'CLASS1'))) c WHERE c = _source_class) THEN --TODO check also disabled classes RAISE EXCEPTION 'CM: invalid source class = % for domain = %', _cm3_utils_regclass_to_name(_source_class), _cm3_utils_regclass_to_domain_name(_domain); END IF; END $$; YDROP FUNCTION public._cm3_domain_source_check(_domain regclass, _source_class regclass); publicpostgresfalse1255232883(_cm3_domain_source_classes_get(regclass)FUNCTIONCREATE FUNCTION public._cm3_domain_source_classes_get(_domain regclass) RETURNS SETOF regclass LANGUAGE plpgsql STABLE AS $$ BEGIN RETURN QUERY SELECT _cm3_domain_source_classes_get(_domain, true); END $$; GDROP FUNCTION public._cm3_domain_source_classes_get(_domain regclass); publicpostgresfalse12552328841_cm3_domain_source_classes_get(regclass, boolean)FUNCTIONCREATE FUNCTION public._cm3_domain_source_classes_get(_domain regclass, _direct boolean) RETURNS SETOF regclass LANGUAGE plpgsql STABLE AS $$ BEGIN RETURN QUERY SELECT _cm3_domain_target_classes_get(_domain, NOT _direct); END $$; XDROP FUNCTION public._cm3_domain_source_classes_get(_domain regclass, _direct boolean); publicpostgresfalse1255232885;_cm3_domain_source_classes_get(regclass, character varying)FUNCTIONCREATE FUNCTION public._cm3_domain_source_classes_get(_domain regclass, _direction character varying) RETURNS SETOF regclass LANGUAGE plpgsql STABLE AS $$ BEGIN RETURN QUERY SELECT _cm3_domain_target_classes_get(_domain, _cm3_utils_direction_inverse(_direction)); END $$; eDROP FUNCTION public._cm3_domain_source_classes_get(_domain regclass, _direction character varying); publicpostgresfalse1255232886,_cm3_domain_target_check(regclass, regclass)FUNCTIONDCREATE FUNCTION public._cm3_domain_target_check(_domain regclass, _target_class regclass) RETURNS void LANGUAGE plpgsql AS $$ BEGIN IF _target_class IS NULL OR NOT EXISTS (SELECT c FROM _cm3_class_list_descendant_classes_and_self_not_superclass(_cm3_utils_name_to_regclass(_cm3_class_comment_get(_domain, 'CLASS2'))) c WHERE c = _target_class) THEN --TODO check also disabled classes RAISE EXCEPTION 'CM: invalid target class = % for domain = %', _cm3_utils_regclass_to_name(_target_class), _cm3_utils_regclass_to_domain_name(_domain); END IF; END $$; YDROP FUNCTION public._cm3_domain_target_check(_domain regclass, _target_class regclass); publicpostgresfalse1255232887/_cm3_domain_target_class_get(regclass, boolean)FUNCTION]CREATE FUNCTION public._cm3_domain_target_class_get(_domain regclass, _direct boolean) RETURNS regclass LANGUAGE plpgsql STABLE AS $$ BEGIN RETURN CASE WHEN _direct THEN _cm3_utils_name_to_regclass(_cm3_class_comment_get(_domain, 'CLASS2')) ELSE _cm3_utils_name_to_regclass(_cm3_class_comment_get(_domain, 'CLASS1')) END; END $$; VDROP FUNCTION public._cm3_domain_target_class_get(_domain regclass, _direct boolean); publicpostgresfalse1255232888(_cm3_domain_target_classes_get(regclass)FUNCTIONCREATE FUNCTION public._cm3_domain_target_classes_get(_domain regclass) RETURNS SETOF regclass LANGUAGE plpgsql STABLE AS $$ BEGIN RETURN QUERY SELECT _cm3_domain_target_classes_get(_domain, true); END $$; GDROP FUNCTION public._cm3_domain_target_classes_get(_domain regclass); publicpostgresfalse12552328891_cm3_domain_target_classes_get(regclass, boolean)FUNCTIONRCREATE FUNCTION public._cm3_domain_target_classes_get(_domain regclass, _direct boolean) RETURNS SETOF regclass LANGUAGE plpgsql STABLE AS $$ DECLARE _target_class regclass; _disabled_classes_attr varchar; _disabled_classes regclass[]; BEGIN _target_class = _cm3_domain_target_class_get(_domain, _direct); _disabled_classes_attr = CASE WHEN _direct THEN _cm3_class_comment_get(_domain, 'DISABLED2') ELSE _cm3_class_comment_get(_domain, 'DISABLED1') END; IF _cm3_utils_is_blank(_disabled_classes_attr) THEN _disabled_classes = ARRAY[]::regclass[]; ELSE RAISE DEBUG 'disabled classes attr =< % >', _disabled_classes_attr; SELECT INTO _disabled_classes coalesce(array_agg(c), ARRAY[]::regclass[]) FROM (SELECT _cm3_utils_name_to_regclass(s) c FROM regexp_split_to_table(_disabled_classes_attr, ' *, *') s) x WHERE c IS NOT NULL; RAISE DEBUG 'disabled classes =< % >', _disabled_classes; END IF; RETURN QUERY SELECT c FROM _cm3_class_list_descendant_classes_and_self(_target_class) c WHERE c <> ALL (_disabled_classes); END $$; XDROP FUNCTION public._cm3_domain_target_classes_get(_domain regclass, _direct boolean); publicpostgresfalse1255232890;_cm3_domain_target_classes_get(regclass, character varying)FUNCTION*CREATE FUNCTION public._cm3_domain_target_classes_get(_domain regclass, _direction character varying) RETURNS SETOF regclass LANGUAGE plpgsql STABLE AS $$ BEGIN RETURN QUERY SELECT _cm3_domain_target_classes_get(_domain, CASE _direction WHEN 'direct' THEN true ELSE false END); END $$; eDROP FUNCTION public._cm3_domain_target_classes_get(_domain regclass, _direction character varying); publicpostgresfalse1255232891K_cm3_email_utils_field_contains_value(character varying, character varying)FUNCTION9CREATE FUNCTION public._cm3_email_utils_field_contains_value(_field_value character varying, _email character varying) RETURNS boolean LANGUAGE plpgsql IMMUTABLE AS $_$ DECLARE _res boolean; BEGIN _email = regexp_replace(_email, '^ *(.*<)?(.*?)>? *$', '\2'); IF _field_value IS NULL THEN RETURN FALSE; ELSE SELECT INTO _res EXISTS (WITH q AS (SELECT regexp_replace(x, '^ *(.*<)?(.*?)>? *$', '\2') e FROM regexp_split_to_table(_field_value, ',') x) SELECT * FROM q WHERE e ILIKE _email); RETURN _res; END IF; END $_$; vDROP FUNCTION public._cm3_email_utils_field_contains_value(_field_value character varying, _email character varying); publicpostgresfalse12552328924_cm3_function_comment_delete(oid, character varying)FUNCTIONCREATE FUNCTION public._cm3_function_comment_delete(_fun oid, _key character varying) RETURNS void LANGUAGE sql AS $$ SELECT _cm3_function_comment_set(_fun, _cm3_function_comment_get_jsonb(_fun) - _key); $$; UDROP FUNCTION public._cm3_function_comment_delete(_fun oid, _key character varying); publicpostgresfalse1255232893_cm3_function_comment_get(oid)FUNCTIONCREATE FUNCTION public._cm3_function_comment_get(_function oid) RETURNS character varying LANGUAGE sql STABLE AS $$ SELECT description FROM pg_description WHERE objoid = _function; $$; ?DROP FUNCTION public._cm3_function_comment_get(_function oid); publicpostgresfalse 12552328941_cm3_function_comment_get(oid, character varying)FUNCTIONCREATE FUNCTION public._cm3_function_comment_get(_function oid, _key character varying) RETURNS character varying LANGUAGE sql STABLE AS $$ SELECT _cm3_function_comment_get_jsonb(_function)->>_key; $$; WDROP FUNCTION public._cm3_function_comment_get(_function oid, _key character varying); publicpostgresfalse!1255232895$_cm3_function_comment_get_jsonb(oid)FUNCTIONCREATE FUNCTION public._cm3_function_comment_get_jsonb(_function oid) RETURNS jsonb LANGUAGE sql STABLE AS $$ SELECT _cm3_comment_to_jsonb(_cm3_function_comment_get(_function)); $$; EDROP FUNCTION public._cm3_function_comment_get_jsonb(_function oid); publicpostgresfalse"1255232896%_cm3_function_comment_set(oid, jsonb)FUNCTIONCREATE FUNCTION public._cm3_function_comment_set(_fun oid, _comment jsonb) RETURNS void LANGUAGE plpgsql AS $$ DECLARE _ref_attr int; _key varchar; BEGIN FOR _key IN SELECT x FROM jsonb_object_keys(_comment) x WHERE x NOT IN ('CATEGORIES','MASTERTABLE','TAGS','ACTIVE','MODE','TYPE') LOOP RAISE WARNING 'CM: invalid comment for function = %: invalid comment key = %', _fun, _key; END LOOP; EXECUTE format('COMMENT ON FUNCTION %s IS %L', _cm3_function_definition_get(_fun), _cm3_comment_from_jsonb(_comment)); END $$; JDROP FUNCTION public._cm3_function_comment_set(_fun oid, _comment jsonb); publicpostgresfalse#1255232897D_cm3_function_comment_set(oid, character varying, character varying)FUNCTION CREATE FUNCTION public._cm3_function_comment_set(_fun oid, _key character varying, _value character varying) RETURNS void LANGUAGE sql AS $$ SELECT _cm3_function_comment_set(_fun, _cm3_function_comment_get_jsonb(_fun) || jsonb_build_object(_key, _value)); $$; lDROP FUNCTION public._cm3_function_comment_set(_fun oid, _key character varying, _value character varying); publicpostgresfalse$1255232898!_cm3_function_definition_get(oid)FUNCTIONCREATE FUNCTION public._cm3_function_definition_get(_fun oid) RETURNS character varying LANGUAGE sql AS $$ SELECT format('%I(%s)', (SELECT proname FROM pg_proc WHERE oid = _fun), pg_get_function_identity_arguments(_fun)); $$; =DROP FUNCTION public._cm3_function_definition_get(_fun oid); publicpostgresfalse%1255232899_cm3_function_list()FUNCTION CREATE FUNCTION public._cm3_function_list() RETURNS SETOF oid LANGUAGE sql AS $$ SELECT oid FROM pg_proc WHERE LOWER(_cm3_function_comment_get_jsonb(oid)->>'TYPE') = 'function' AND pronamespace = (SELECT oid FROM pg_namespace WHERE nspname = 'public'); $$; +DROP FUNCTION public._cm3_function_list(); publicpostgresfalse&1255232900_cm3_function_list_detailed()FUNCTIONsCREATE FUNCTION public._cm3_function_list_detailed() RETURNS TABLE(function_name character varying, function_id oid, arg_io character[], arg_names character varying[], arg_types character varying[], returns_set boolean, comment jsonb, metadata jsonb) LANGUAGE plpgsql STABLE AS $_$ DECLARE _arg_io char[]; _arg_names varchar[]; _arg_types varchar[]; _record record; _index integer; BEGIN FOR _record IN SELECT *,oid FROM pg_proc WHERE oid IN (SELECT _cm3_function_list()) LOOP IF _record.proargmodes IS NULL THEN _arg_io = '{}'::char[]; _arg_types = '{}'::varchar[]; _arg_names = '{}'::varchar[]; FOR _index IN SELECT generate_series(1, array_upper(_record.proargtypes,1)) LOOP _arg_io = _arg_io || 'i'::char; _arg_types = _arg_types || _cm3_utils_build_sqltype_string(_record.proargtypes[_index], NULL); _arg_names = _arg_names || COALESCE(_record.proargnames[_index]::varchar,('$'||_index)::varchar); END LOOP; _arg_io = _arg_io || 'o'::char; _arg_types = _arg_types || _cm3_utils_build_sqltype_string(_record.prorettype, NULL); _arg_names = _arg_names || _record.proname::varchar; ELSE _arg_io = _record.proargmodes; _arg_types = '{}'::varchar[]; _arg_names = _record.proargnames; FOR _index IN SELECT generate_series(1, array_upper(_arg_io,1)) LOOP IF _arg_io[_index] = 't' THEN _arg_io[_index] = 'o'; ELSEIF _arg_io[_index] = 'b' THEN _arg_io[_index] = 'io'; ELSEIF _arg_io[_index] NOT IN ('i','o') THEN RAISE 'unsupported arg io value = % for function = %', _arg_io[_index], _record.proname; END IF; _arg_types = _arg_types || _cm3_utils_build_sqltype_string(_record.proallargtypes[_index], NULL); IF _arg_names[_index] = '' THEN IF _arg_io[_index] = 'i' THEN _arg_names[_index] = '$'||_index; ELSE _arg_names[_index] = 'column'||_index; END IF; END IF; END LOOP; END IF; RETURN QUERY SELECT _record.proname::varchar, _record.oid, _arg_io, _arg_names, _arg_types, _record.proretset, _cm3_function_comment_get_jsonb(_record.oid), _cm3_function_metadata_get(_record.oid); END LOOP; END $_$; 4DROP FUNCTION public._cm3_function_list_detailed(); publicpostgresfalse'1255232901_cm3_function_metadata_get(oid)FUNCTIONCREATE FUNCTION public._cm3_function_metadata_get(_function oid) RETURNS jsonb LANGUAGE plpgsql AS $$ BEGIN RETURN COALESCE((SELECT "Data" FROM "_FunctionMetadata" WHERE "OwnerFunction" = _function AND "Status" = 'A'),'{}'::jsonb); END $$; @DROP FUNCTION public._cm3_function_metadata_get(_function oid); publicpostgresfalse(12552329022_cm3_function_metadata_get(oid, character varying)FUNCTIONCREATE FUNCTION public._cm3_function_metadata_get(_function oid, _key character varying) RETURNS character varying LANGUAGE plpgsql AS $$ BEGIN RETURN jsonb_extract_path_text(_cm3_class_metadata_get(_function),_key::text); END $$; XDROP FUNCTION public._cm3_function_metadata_get(_function oid, _key character varying); publicpostgresfalse)1255232903&_cm3_function_metadata_set(oid, jsonb)FUNCTIONCREATE FUNCTION public._cm3_function_metadata_set(_function oid, _metadata jsonb) RETURNS void LANGUAGE plpgsql AS $$ BEGIN IF EXISTS (SELECT 1 FROM "_FunctionMetadata" WHERE "Owner" = _function AND "Status" = 'A') THEN UPDATE "_FunctionMetadata" SET "Data" = _metadata WHERE "OwnerFunction" = _function AND "Status" = 'A'; ELSE INSERT INTO "_FunctionMetadata" ("OwnerFunction","Data") VALUES (_function,_metadata); END IF; END $$; QDROP FUNCTION public._cm3_function_metadata_set(_function oid, _metadata jsonb); publicpostgresfalse*1255232904_cm3_gis_class_list()FUNCTIONCREATE FUNCTION public._cm3_gis_class_list() RETURNS SETOF regclass LANGUAGE sql STABLE AS $$ SELECT oid::regclass FROM pg_class WHERE _cm3_class_is_simple_or_standard(oid) AND relnamespace = (SELECT oid FROM pg_namespace WHERE nspname='gis'); $$; ,DROP FUNCTION public._cm3_gis_class_list(); publicpostgresfalse+12552329051_cm3_gis_find_values(bigint[], character varying)FUNCTIONCREATE FUNCTION public._cm3_gis_find_values(_gis_attributes bigint[], _area character varying) RETURNS TABLE(ownerclass regclass, attrname character varying, ownercard bigint, geometry text) LANGUAGE plpgsql AS $$ DECLARE _ownerclass regclass; _attrname varchar; BEGIN FOR _ownerclass, _attrname IN SELECT "Owner", "Code" FROM "_GisAttribute" WHERE "Id" = ANY (_gis_attributes) LOOP RETURN QUERY EXECUTE format('SELECT %L::regclass ownerclass,%L::varchar attrname, "Master" ownercard, gis.st_astext("Geometry") geometry FROM gis."Gis_%s_%s" AS g WHERE g."Geometry" operator(gis.&&) gis.st_makeenvelope(%s,900913)', _ownerclass::regclass, _attrname, _cm3_utils_regclass_to_name(_ownerclass), _attrname, _area); END LOOP; END $$; ^DROP FUNCTION public._cm3_gis_find_values(_gis_attributes bigint[], _area character varying); publicpostgresfalse,1255232906E_cm3_gis_table_create(regclass, character varying, character varying)FUNCTIONvCREATE FUNCTION public._cm3_gis_table_create(_master regclass, _attr character varying, _type character varying) RETURNS regclass LANGUAGE plpgsql AS $$ DECLARE _class regclass; BEGIN SELECT _cm3_class_create(format('gis.Gis_%s_%s', _cm3_utils_regclass_to_name(_master), _attr), NULL, 'MODE: reserved|TYPE: simpleclass') INTO _class; PERFORM _cm3_attribute_create(_class, 'Master', 'bigint', format('NOTNULL: true|UNIQUE: true|FKTARGETCLASS: %s', _cm3_utils_regclass_to_name(_master))); EXECUTE format('ALTER TABLE %s ADD COLUMN "Geometry" gis.geometry(%s,900913) NOT NULL', _class, _type); RETURN _class; END $$; pDROP FUNCTION public._cm3_gis_table_create(_master regclass, _attr character varying, _type character varying); publicpostgresfalse-1255232907:_cm3_gis_value_delete(regclass, character varying, bigint)FUNCTION_CREATE FUNCTION public._cm3_gis_value_delete(_class regclass, _attr character varying, _card bigint) RETURNS void LANGUAGE plpgsql AS $$ DECLARE _gis_table regclass = format('gis."Gis_%s_%s"', _cm3_utils_regclass_to_name(_class), _attr)::regclass; BEGIN EXECUTE format('DELETE FROM %s WHERE "Master" = %s', _gis_table, _card); END $$; dDROP FUNCTION public._cm3_gis_value_delete(_class regclass, _attr character varying, _card bigint); publicpostgresfalse.12552329087_cm3_gis_value_get(regclass, character varying, bigint)FUNCTIONCREATE FUNCTION public._cm3_gis_value_get(_class regclass, _attr character varying, _card bigint) RETURNS character varying LANGUAGE plpgsql AS $$ DECLARE _gis_table regclass = format('gis."Gis_%s_%s"', _cm3_utils_regclass_to_name(_class), _attr)::regclass; _value varchar; BEGIN EXECUTE format('SELECT gis.st_astext("Geometry") FROM %s WHERE "Master" = %s', _gis_table, _card) INTO _value; RETURN _value; END $$; aDROP FUNCTION public._cm3_gis_value_get(_class regclass, _attr character varying, _card bigint); publicpostgresfalse/1255232909J_cm3_gis_value_set(regclass, character varying, bigint, character varying)FUNCTIONCREATE FUNCTION public._cm3_gis_value_set(_class regclass, _attr character varying, _card bigint, _value_astext character varying) RETURNS void LANGUAGE plpgsql AS $$ DECLARE _gis_table regclass = format('gis."Gis_%s_%s"', _cm3_utils_regclass_to_name(_class), _attr)::regclass; BEGIN EXECUTE format('INSERT INTO %s ("Master", "Geometry") VALUES (%L, gis.st_geomfromtext(%L, 900913)) ON CONFLICT ("Master") DO UPDATE SET "Geometry" = EXCLUDED."Geometry"', _gis_table, _card, _value_astext); END $$; DROP FUNCTION public._cm3_gis_value_set(_class regclass, _attr character varying, _card bigint, _value_astext character varying); publicpostgresfalse01255232910-_cm3_grant_attribute_priviledges_check(jsonb)FUNCTIONCREATE FUNCTION public._cm3_grant_attribute_priviledges_check(attribute_priviledge jsonb) RETURNS boolean LANGUAGE plpgsql AS $$ DECLARE element record; BEGIN FOR element IN (SELECT value FROM jsonb_each(attribute_priviledge)) LOOP IF (element.value NOT IN ('"write"', '"read"', '"none"')) THEN RAISE WARNING 'GrantAttributePrivilege % is not valid', element.value; RETURN false; END IF; END LOOP; RETURN true; END $$; YDROP FUNCTION public._cm3_grant_attribute_priviledges_check(attribute_priviledge jsonb); publicpostgresfalse11255232911i_cm3_lock_aquire_try(character varying, character varying, character varying, character varying, integer)FUNCTIONxCREATE FUNCTION public._cm3_lock_aquire_try(_item_id character varying, _session_id character varying, _request_id character varying, _scope character varying, _time_to_live_seconds integer) RETURNS TABLE(is_aquired boolean, lock_id bigint) LANGUAGE plpgsql AS $$ DECLARE _current record; BEGIN IF _scope NOT IN ('session', 'request') THEN RAISE 'invalid scope = %', _scope; END IF; LOCK TABLE "_Lock" IN ACCESS EXCLUSIVE MODE; SELECT INTO _current * FROM "_Lock" WHERE "ItemId" = _item_id; IF _current IS NOT NULL AND _current."LastActiveDate" + format('%s seconds', _current."TimeToLive")::interval < now() THEN DELETE FROM "_Lock" WHERE "Id" = _current."Id"; RAISE NOTICE 'removed expired lock = %', _current; _current = NULL; END IF; IF _current IS NULL THEN INSERT INTO "_Lock" ("ItemId", "SessionId", "RequestId", "Scope", "TimeToLive", "LastActiveDate") VALUES (_item_id, _session_id, _request_id, _scope, _time_to_live_seconds, now()); SELECT INTO _current * FROM "_Lock" WHERE "ItemId" = _item_id; RAISE NOTICE 'aquired new lock = %', _current; RETURN QUERY SELECT TRUE, _current."Id"; ELSE IF ( _current."Scope" = 'session' AND _scope = 'session' AND _current."SessionId" = _session_id ) OR ( _current."Scope" = 'request' AND _scope = 'request' AND _current."SessionId" = _session_id AND _current."RequestId" = _request_id ) THEN UPDATE "_Lock" SET "LastActiveDate" = now(), "TimeToLive" = _time_to_live_seconds WHERE "Id" = _current."Id"; RAISE NOTICE 'aquired existing lock = %', _current; RETURN QUERY SELECT TRUE, _current."Id"; ELSE RAISE NOTICE 'unable to aquire lock, already aquired by = %', _current; RETURN QUERY SELECT FALSE, _current."Id"; END IF; END IF; END $$; DROP FUNCTION public._cm3_lock_aquire_try(_item_id character varying, _session_id character varying, _request_id character varying, _scope character varying, _time_to_live_seconds integer); publicpostgresfalse21255232912_cm3_multitenant_get(bigint)FUNCTIONCREATE FUNCTION public._cm3_multitenant_get(_user_id bigint) RETURNS SETOF bigint LANGUAGE plpgsql AS $$ BEGIN IF _user_id = -1 THEN -- RETURN QUERY SELECT "Tenant"."Id" FROM "Tenant" WHERE "Tenant"."Status" = 'A'; RETURN; -- all tenants ELSE -- RETURN QUERY SELECT "Tenant"."Id" FROM "Tenant" JOIN "Map_UserTenant" ON "Tenant"."Id" = "Map_UserTenant"."IdObj2" WHERE "Map_UserTenant"."IdObj1" = _user_id AND "Tenant"."Status" = 'A' AND "Map_UserTenant"."Status" = 'A'; RETURN; -- user tenants END IF; END $$; <DROP FUNCTION public._cm3_multitenant_get(_user_id bigint); publicpostgresfalse71255232913L_cm3_multitenant_mode_change(regclass, character varying, character varying)FUNCTION2CREATE FUNCTION public._cm3_multitenant_mode_change(_class regclass, _previous_mode character varying, _mode character varying) RETURNS void LANGUAGE plpgsql AS $$ DECLARE _has_data boolean; BEGIN _mode = coalesce(_mode, 'never'); _previous_mode = coalesce(_previous_mode, 'never'); IF _mode NOT IN ('never','mixed','always') THEN RAISE EXCEPTION 'CM: error configuring multitenant for class = % : unsupported multitenant mode = %', _class, _mode; END IF; IF _mode <> _previous_mode THEN RAISE NOTICE 'set multitenant mode for class = %, cur mode = %, new mode = %', _class, _previous_mode, _mode; IF _cm3_class_is_superclass(_class) THEN RAISE 'CM: unable to set multitenant mode on superclass % : operation not allowed', _cm3_utils_regclass_to_name(_class); ELSE IF _mode = 'never' THEN IF _cm3_class_is_simple(_class) THEN EXECUTE format('SELECT EXISTS (SELECT 1 FROM %s WHERE "IdTenant" IS NOT NULL AND "IdTenant" <> -1)', _class) INTO _has_data; ELSE EXECUTE format('SELECT EXISTS (SELECT 1 FROM %s WHERE "IdTenant" IS NOT NULL AND "IdTenant" <> -1 AND "Status" = ''A'')', _class) INTO _has_data; END IF; IF _has_data THEN RAISE 'CM: unable to set multitenant mode to "never" for class % : class contains some cards with non-null IdTenant (suggestion: set mode to "mixed" and set all card tenants to NULL, then set mode to "never")', _class; END IF; END IF; IF _previous_mode IN ('mixed','always') THEN EXECUTE format('DROP POLICY IF EXISTS "%s_policy" ON %s', _cm3_utils_regclass_to_name(_class), _class); EXECUTE format('ALTER TABLE %s DISABLE ROW LEVEL SECURITY', _class); END IF; IF _mode IN ('mixed','always') THEN EXECUTE format('CREATE INDEX IF NOT EXISTS "%s_idtenant" ON %s ("IdTenant")', _cm3_utils_regclass_to_name(_class), _class); EXECUTE format('ALTER TABLE %s ENABLE ROW LEVEL SECURITY, FORCE ROW LEVEL SECURITY', _class); EXECUTE format('CREATE POLICY "%s_policy" ON %s USING (current_setting(''cmdbuild.ignore_tenant_policies'') = ''true'' OR "IdTenant" IS NULL OR "IdTenant" = ANY (current_setting(''cmdbuild.user_tenants'')::bigint[]))', _cm3_utils_regclass_to_name(_class), _class); EXECUTE format('ALTER TABLE %s DISABLE TRIGGER USER', _class); EXECUTE format('ALTER TABLE %s DISABLE TRIGGER USER', _cm3_utils_regclass_to_history(_class)); IF _mode = 'always' THEN EXECUTE format('UPDATE %s SET "IdTenant" = -1 WHERE "IdTenant" IS NULL', _class); ELSEIF _mode = 'mixed' THEN EXECUTE format('UPDATE %s SET "IdTenant" = NULL WHERE "IdTenant" = -1', _class); END IF; EXECUTE format('ALTER TABLE %s ENABLE TRIGGER USER', _class); EXECUTE format('ALTER TABLE %s ENABLE TRIGGER USER', _cm3_utils_regclass_to_history(_class)); PERFORM _cm3_class_comment_set(_class, 'MTMODE', _mode); ELSEIF _mode = 'never' THEN IF _previous_mode = 'always' THEN EXECUTE format('ALTER TABLE %s DISABLE TRIGGER USER', _class); EXECUTE format('UPDATE %s SET "IdTenant" = NULL WHERE "IdTenant" = -1', _class); EXECUTE format('ALTER TABLE %s ENABLE TRIGGER USER', _class); END IF; EXECUTE format('DROP INDEX IF EXISTS "%s_idtenant"', _cm3_utils_regclass_to_name(_class), _class); PERFORM _cm3_class_comment_delete(_class, 'MTMODE'); END IF; PERFORM _cm3_multitenant_superclass_policy_update(c) FROM _cm3_class_list_ancestors(_class) c WHERE _cm3_class_is_superclass(c); END IF; ELSE RAISE DEBUG 'no need to set multitenant mode for class = %, cur mode = %, new mode = %', _class, _previous_mode, _mode; END IF; END $$; DROP FUNCTION public._cm3_multitenant_mode_change(_class regclass, _previous_mode character varying, _mode character varying); publicpostgresfalse812552329146_cm3_multitenant_mode_set(regclass, character varying)FUNCTIONCREATE FUNCTION public._cm3_multitenant_mode_set(_class regclass, _mode character varying) RETURNS void LANGUAGE plpgsql AS $$ BEGIN PERFORM _cm3_multitenant_mode_change(_class, _cm3_class_comment_get(_class, 'MTMODE'), _mode); END $$; ZDROP FUNCTION public._cm3_multitenant_mode_set(_class regclass, _mode character varying); publicpostgresfalse912552329150_cm3_multitenant_superclass_policy_set(regclass)FUNCTIONCREATE FUNCTION public._cm3_multitenant_superclass_policy_set(_class regclass) RETURNS void LANGUAGE plpgsql AS $$ BEGIN IF NOT _cm3_class_is_superclass(_class) THEN RAISE 'CM: unable to set multitenant superclassclass policy on class % : operation not allowed', _cm3_utils_regclass_to_name(_class); END IF; EXECUTE format('ALTER TABLE %s ENABLE ROW LEVEL SECURITY, FORCE ROW LEVEL SECURITY', _class); EXECUTE format('CREATE POLICY "%s_policy" ON %s USING (current_setting(''cmdbuild.ignore_tenant_policies'') = ''true'' OR "IdTenant" IS NULL OR "IdTenant" = ANY (current_setting(''cmdbuild.user_tenants'')::bigint[]))', _cm3_utils_regclass_to_name(_class), _class); END $$; NDROP FUNCTION public._cm3_multitenant_superclass_policy_set(_class regclass); publicpostgresfalse:12552329163_cm3_multitenant_superclass_policy_update(regclass)FUNCTIONCREATE FUNCTION public._cm3_multitenant_superclass_policy_update(_class regclass) RETURNS void LANGUAGE plpgsql AS $$ DECLARE _has_policy boolean; _should_set_policy boolean; BEGIN IF NOT _cm3_class_is_superclass(_class) THEN RAISE 'CM: unable to set multitenant superclassclass policy on class % : operation not allowed', _cm3_utils_regclass_to_name(_class); END IF; _has_policy = ( SELECT EXISTS ( SELECT * FROM pg_catalog.pg_policies WHERE schemaname = 'public' AND tablename = _cm3_utils_regclass_to_name(_class) AND policyname = format('%s_policy', _cm3_utils_regclass_to_name(_class)) ) ); _should_set_policy = ( SELECT EXISTS ( SELECT * FROM _cm3_class_list_descendant_classes(_class) c WHERE _cm3_class_comment_get(c, 'MTMODE') IN ('mixed','always') ) ); IF _should_set_policy <> _has_policy THEN IF _should_set_policy THEN EXECUTE format('ALTER TABLE %s ENABLE ROW LEVEL SECURITY, FORCE ROW LEVEL SECURITY', _class); EXECUTE format('CREATE POLICY "%s_policy" ON %s USING (current_setting(''cmdbuild.ignore_tenant_policies'') = ''true'' OR "IdTenant" IS NULL OR "IdTenant" = ANY (current_setting(''cmdbuild.user_tenants'')::bigint[]))', _cm3_utils_regclass_to_name(_class), _class); ELSE EXECUTE format('ALTER TABLE %s DISABLE ROW LEVEL SECURITY', _class); EXECUTE format('DROP POLICY "%s_policy" ON %s', _cm3_utils_regclass_to_name(_class), _class); END IF; END IF; END $$; QDROP FUNCTION public._cm3_multitenant_superclass_policy_update(_class regclass); publicpostgresfalse;1255232917._cm3_multitenant_tenant_class_helper_trigger()FUNCTIONgCREATE FUNCTION public._cm3_multitenant_tenant_class_helper_trigger() RETURNS trigger LANGUAGE plpgsql AS $$ DECLARE _class_mode varchar; BEGIN _class_mode = coalesce(_cm3_class_comment_get(TG_RELID::regclass, 'MTMODE'), 'never'); IF _class_mode = 'always' AND NEW."IdTenant" IS NULL THEN NEW."IdTenant" = NEW."Id"; END IF; RETURN NEW; END $$; EDROP FUNCTION public._cm3_multitenant_tenant_class_helper_trigger(); publicpostgresfalse<12552329187_cm3_multitenant_tenant_class_trigger_install(regclass)FUNCTIONNCREATE FUNCTION public._cm3_multitenant_tenant_class_trigger_install(_class regclass) RETURNS void LANGUAGE plpgsql AS $$ BEGIN EXECUTE format('CREATE TRIGGER "_cm3_multitenant_tenant_class_helper" BEFORE INSERT OR UPDATE ON %s FOR EACH ROW EXECUTE PROCEDURE _cm3_multitenant_tenant_class_helper_trigger()', _class); END $$; UDROP FUNCTION public._cm3_multitenant_tenant_class_trigger_install(_class regclass); publicpostgresfalse=1255232919_cm3_process_list()FUNCTIONCREATE FUNCTION public._cm3_process_list() RETURNS SETOF regclass LANGUAGE sql STABLE AS $$ SELECT _cm3_class_list_descendant_classes_and_self_not_superclass('"Activity"'::regclass); $$; *DROP FUNCTION public._cm3_process_list(); publicpostgresfalse>1255232920B_cm3_reference_update(regclass, character varying, bigint, bigint)FUNCTIONCREATE FUNCTION public._cm3_reference_update(_class regclass, _attr character varying, _card bigint, _value bigint) RETURNS void LANGUAGE plpgsql AS $$ BEGIN IF _value IS NULL THEN EXECUTE format('UPDATE %s SET %I = NULL WHERE "Status" = ''A'' AND "Id" = %L AND %I IS NOT NULL', _class, _attr, _card, _attr); ELSE EXECUTE format('UPDATE %s SET %I = %L WHERE "Status" = ''A'' AND "Id" = %L AND %I IS DISTINCT FROM %L', _class, _attr, _value, _card, _attr, _value); END IF; END $$; sDROP FUNCTION public._cm3_reference_update(_class regclass, _attr character varying, _card bigint, _value bigint); publicpostgresfalse?1255232921+_cm3_system_command_send(character varying)FUNCTIONCREATE FUNCTION public._cm3_system_command_send(_action character varying) RETURNS void LANGUAGE sql AS $$ SELECT _cm3_system_command_send(_action, '{}'::jsonb); $$; JDROP FUNCTION public._cm3_system_command_send(_action character varying); publicpostgresfalse@1255232922@_cm3_system_command_send(character varying, character varying[])FUNCTIONCREATE FUNCTION public._cm3_system_command_send(_action character varying, VARIADIC _args character varying[]) RETURNS void LANGUAGE sql AS $$ SELECT _cm3_system_command_send(_action, jsonb_build_object('args', _args)); $$; nDROP FUNCTION public._cm3_system_command_send(_action character varying, VARIADIC _args character varying[]); publicpostgresfalseA12552329232_cm3_system_command_send(character varying, jsonb)FUNCTIONCREATE FUNCTION public._cm3_system_command_send(_action character varying, _data jsonb) RETURNS void LANGUAGE sql AS $$ SELECT _cm3_system_message_send('command', _data || jsonb_build_object('action', _action)); $$; WDROP FUNCTION public._cm3_system_command_send(_action character varying, _data jsonb); publicpostgresfalseB1255232924,_cm3_system_config_delete(character varying)FUNCTIONCREATE FUNCTION public._cm3_system_config_delete(_key character varying) RETURNS void LANGUAGE plpgsql AS $$ BEGIN UPDATE "_SystemConfig" SET "Status" = 'N' WHERE "Code" = _key AND "Status" = 'A'; END $$; HDROP FUNCTION public._cm3_system_config_delete(_key character varying); publicpostgresfalseC1255232925_cm3_system_config_get()FUNCTIONCREATE FUNCTION public._cm3_system_config_get() RETURNS jsonb LANGUAGE plpgsql AS $$ BEGIN RETURN (SELECT coalesce(jsonb_object_agg("Code", "Value"), '{}'::jsonb) FROM "_SystemConfig" WHERE "Status" = 'A'); END $$; /DROP FUNCTION public._cm3_system_config_get(); publicpostgresfalseD1255232926)_cm3_system_config_get(character varying)FUNCTIONCREATE FUNCTION public._cm3_system_config_get(_key character varying) RETURNS character varying LANGUAGE plpgsql AS $$ BEGIN RETURN (SELECT coalesce("Value",'') FROM "_SystemConfig" WHERE "Code" = _key AND "Status" = 'A'); END $$; EDROP FUNCTION public._cm3_system_config_get(_key character varying); publicpostgresfalseE1255232927<_cm3_system_config_set(character varying, character varying)FUNCTION6CREATE FUNCTION public._cm3_system_config_set(_key character varying, _value character varying) RETURNS void LANGUAGE plpgsql AS $$ BEGIN INSERT INTO "_SystemConfig" ("Code", "Value") VALUES (_key, _value) ON CONFLICT ("Code") WHERE "Status" = 'A' DO UPDATE SET "Value" = EXCLUDED."Value"; END $$; _DROP FUNCTION public._cm3_system_config_set(_key character varying, _value character varying); publicpostgresfalse31255232928_cm3_system_email_send()FUNCTIONCREATE FUNCTION public._cm3_system_email_send() RETURNS void LANGUAGE sql AS $$ SELECT _cm3_system_command_send('email_queue_trigger', jsonb_build_object('cluster_mode', 'run_on_single_node')); $$; /DROP FUNCTION public._cm3_system_email_send(); publicpostgresfalse41255232929_cm3_system_email_send(bigint)FUNCTIONCREATE FUNCTION public._cm3_system_email_send(_id bigint) RETURNS void LANGUAGE sql AS $$ SELECT _cm3_system_command_send('email_queue_send_single', jsonb_build_object('cluster_mode', 'run_on_single_node', '_email_id', _id)); $$; 9DROP FUNCTION public._cm3_system_email_send(_id bigint); publicpostgresfalse51255232930)_cm3_system_event_send(character varying)FUNCTIONCREATE FUNCTION public._cm3_system_event_send(_event character varying) RETURNS void LANGUAGE sql AS $$ SELECT _cm3_system_message_send('event', jsonb_build_object('event', _event)); $$; GDROP FUNCTION public._cm3_system_event_send(_event character varying); publicpostgresfalse61255232931>_cm3_system_event_send(character varying, character varying[])FUNCTIONCREATE FUNCTION public._cm3_system_event_send(_event character varying, VARIADIC _args character varying[]) RETURNS void LANGUAGE plpgsql AS $$ BEGIN SELECT _cm3_system_message_send('event', jsonb_build_object(_args) || jsonb_build_object('event', _event)); END $$; kDROP FUNCTION public._cm3_system_event_send(_event character varying, VARIADIC _args character varying[]); publicpostgresfalseF1255232932_cm3_system_housekeeping()FUNCTIONh CREATE FUNCTION public._cm3_system_housekeeping() RETURNS void LANGUAGE plpgsql AS $$ DECLARE _record RECORD; _invalid_record RECORD; BEGIN PERFORM _cm3_system_lock_aquire('housekeeping'); FOR _record IN SELECT * FROM "_Grant" WHERE "Status" = 'A' AND (( "Type" = 'Class' AND NOT _cm3_class_exists("ObjectClass") ) OR ( "Type" = 'Report' AND NOT EXISTS (SELECT * FROM "_Report" WHERE "Id" = "_Grant"."ObjectId" AND "Status" = 'A') )) LOOP RAISE WARNING 'removing invalid grant record = %', _record; UPDATE "_Grant" SET "Status" = 'N' WHERE "Id" = _record."Id" AND "Status" = 'A'; END LOOP; FOR _record IN SELECT owner class_name, name attribute_name, comment->>'LOOKUP' _lookupType FROM _cm3_attribute_list_detailed() AS x WHERE NULLIF(comment->>'LOOKUP','') IS NOT NULL ORDER BY owner, name LOOP FOR _invalid_record IN EXECUTE format('SELECT "Id" id, %I attributeId FROM %s WHERE %I IS NOT NULL AND %I NOT IN (SELECT "Id" FROM "LookUp" WHERE "Type" = %L AND "Status" = ''A'')' || CASE WHEN _cm3_class_is_simple(_record.class_name) THEN '' ELSE ' AND "Status" = ''A''' END, _record.attribute_name, _record.class_name::regclass, _record.attribute_name, _record.attribute_name, _record._lookupType) LOOP RAISE WARNING 'found invalid LookUp value for attr = %.% card = %, invalid value = %: will set value to NULL', _cm3_utils_regclass_to_name(_record.class_name), _record.attribute_name, _invalid_record.id, _invalid_record.attributeId; BEGIN EXECUTE format('UPDATE %s SET "%s" = NULL WHERE "Id" = %s', _record.class_name, _record.attribute_name, _invalid_record.id); EXCEPTION WHEN others THEN RAISE WARNING 'unable to clear invalid value for attr = %.% card = %: %', _cm3_utils_regclass_to_name(_record.class_name), _record.attribute_name, _invalid_record.id, SQLERRM; END; END LOOP; END LOOP; FOR _record IN SELECT * FROM "Class" WHERE "Id" IN (WITH _records AS (SELECT "Id",COUNT(*) "Count" FROM (SELECT "Id" FROM "Class" UNION ALL SELECT "Id" FROM "Map" UNION ALL SELECT "Id" FROM "SimpleClass") x GROUP BY "Id") SELECT "Id" FROM _records WHERE "Count" > 1) ORDER BY "Id","IdClass"::varchar LOOP RAISE WARNING 'found duplicate card id = % for record = %', _record."Id", _record; END LOOP; FOR _record IN SELECT * FROM "Map" WHERE "Id" IN (WITH _records AS (SELECT "Id",COUNT(*) "Count" FROM (SELECT "Id" FROM "Class" UNION ALL SELECT "Id" FROM "Map" UNION ALL SELECT "Id" FROM "SimpleClass") x GROUP BY "Id") SELECT "Id" FROM _records WHERE "Count" > 1) ORDER BY "Id","IdDomain"::varchar LOOP RAISE WARNING 'found duplicate map id = % for record = %', _record."Id", _record; END LOOP; FOR _record IN SELECT * FROM "SimpleClass" WHERE "Id" IN (WITH _records AS (SELECT "Id",COUNT(*) "Count" FROM (SELECT "Id" FROM "Class" UNION ALL SELECT "Id" FROM "Map" UNION ALL SELECT "Id" FROM "SimpleClass") x GROUP BY "Id") SELECT "Id" FROM _records WHERE "Count" > 1) ORDER BY "Id","IdClass"::varchar LOOP RAISE WARNING 'found duplicate simple class id = % for record = %', _record."Id", _record; END LOOP; PERFORM _cm3_system_lock_release('housekeeping'); END $$; 1DROP FUNCTION public._cm3_system_housekeeping(); publicpostgresfalse11255232933*_cm3_system_lock_aquire(character varying)FUNCTIONnCREATE FUNCTION public._cm3_system_lock_aquire(_name character varying) RETURNS void LANGUAGE plpgsql AS $$ DECLARE _aquired boolean; BEGIN RAISE DEBUG 'aquiring system lock = %', _name; _aquired = _cm3_system_lock_aquire_try(_name); IF NOT _aquired THEN RAISE NOTICE 'unable to aquire system lock = %: lock already aquired by another thread; waiting for lock release', _name; WHILE NOT _aquired LOOP PERFORM pg_sleep(1); _aquired = _cm3_system_lock_aquire_try(_name); END LOOP; END IF; RAISE NOTICE 'aquired system lock = %', _name; END $$; GDROP FUNCTION public._cm3_system_lock_aquire(_name character varying); publicpostgresfalse01255232934._cm3_system_lock_aquire_try(character varying)FUNCTIONCREATE FUNCTION public._cm3_system_lock_aquire_try(_name character varying) RETURNS boolean LANGUAGE plpgsql AS $$ DECLARE _aquired boolean; BEGIN PERFORM pg_advisory_lock(1313); IF EXISTS (SELECT * FROM "_SysLock" WHERE "Code" = _name) THEN _aquired = FALSE; ELSE INSERT INTO "_SysLock" ("Code") VALUES (_name); _aquired = TRUE; END IF; PERFORM pg_advisory_unlock(1313); RETURN _aquired; END $$; KDROP FUNCTION public._cm3_system_lock_aquire_try(_name character varying); publicpostgresfalse/1255232935+_cm3_system_lock_release(character varying)FUNCTIONCREATE FUNCTION public._cm3_system_lock_release(_name character varying) RETURNS void LANGUAGE plpgsql AS $$ BEGIN RAISE NOTICE 'release system lock = %', _name; DELETE FROM "_SysLock" WHERE "Code" = _name; END $$; HDROP FUNCTION public._cm3_system_lock_release(_name character varying); publicpostgresfalseG1255232936_cm3_system_login()FUNCTION-CREATE FUNCTION public._cm3_system_login() RETURNS void LANGUAGE plpgsql AS $$ BEGIN SET SESSION cmdbuild.operation_user = 'postgres'; SET SESSION cmdbuild.operation_scope = 'default'; SET SESSION cmdbuild.user_tenants = '{}'; SET SESSION cmdbuild.ignore_tenant_policies = 'true'; END $$; *DROP FUNCTION public._cm3_system_login(); publicpostgresfalseH1255232937_cm3_system_message_send(jsonb)FUNCTIONCREATE FUNCTION public._cm3_system_message_send(_data jsonb) RETURNS void LANGUAGE sql AS $$ LISTEN cminfo; SELECT pg_notify('cmevents', _data::varchar); $$; <DROP FUNCTION public._cm3_system_message_send(_data jsonb); publicpostgresfalseI12552329382_cm3_system_message_send(character varying, jsonb)FUNCTIONCREATE FUNCTION public._cm3_system_message_send(_type character varying, _data jsonb) RETURNS void LANGUAGE sql AS $$ SELECT _cm3_system_message_send(_data || jsonb_build_object('type', _type, 'id', (SELECT substring(_cm3_utils_random_id() from 0 for 8)))); $$; UDROP FUNCTION public._cm3_system_message_send(_type character varying, _data jsonb); publicpostgresfalseJ1255232939_cm3_system_reload()FUNCTIONCREATE FUNCTION public._cm3_system_reload() RETURNS void LANGUAGE sql AS $$ SELECT _cm3_system_command_send('reload'); $$; +DROP FUNCTION public._cm3_system_reload(); publicpostgresfalseK1255232940_cm3_system_restart()FUNCTIONCREATE FUNCTION public._cm3_system_restart() RETURNS void LANGUAGE sql AS $$ SELECT _cm3_system_command_send('restart'); $$; ,DROP FUNCTION public._cm3_system_restart(); publicpostgresfalseL1255232941_cm3_system_shutdown()FUNCTIONCREATE FUNCTION public._cm3_system_shutdown() RETURNS void LANGUAGE sql AS $$ SELECT _cm3_system_command_send('shutdown'); $$; -DROP FUNCTION public._cm3_system_shutdown(); publicpostgresfalseM1255232942:_cm3_translation_get(character varying, character varying)FUNCTIONCREATE FUNCTION public._cm3_translation_get(_key character varying, _lang character varying) RETURNS character varying LANGUAGE sql AS $$ SELECT "Value" FROM "_Translation" WHERE "Code" = _key AND "Lang" = _lang AND "Status" = 'A'; $$; \DROP FUNCTION public._cm3_translation_get(_key character varying, _lang character varying); publicpostgresfalseN1255232943M_cm3_translation_get(character varying, character varying, character varying)FUNCTION2CREATE FUNCTION public._cm3_translation_get(_key character varying, _lang character varying, _default character varying) RETURNS character varying LANGUAGE sql AS $$ SELECT COALESCE((SELECT "Value" FROM "_Translation" WHERE "Code" = _key AND "Lang" = _lang AND "Status" = 'A'), _default); $$; xDROP FUNCTION public._cm3_translation_get(_key character varying, _lang character varying, _default character varying); publicpostgresfalseO12552329446_cm3_translation_lookup_get(bigint, character varying)FUNCTIONCREATE FUNCTION public._cm3_translation_lookup_get(_id bigint, _lang character varying) RETURNS character varying LANGUAGE plpgsql AS $$ DECLARE _type varchar; _code varchar; _desc varchar; BEGIN SELECT "Type", "Code", "Description" INTO _type, _code, _desc FROM "LookUp" WHERE "Id" = _id AND "Status" = 'A'; RETURN _cm3_translation_get(format('lookup.%s.%s.description', _type, _code), _lang, _desc); END $$; WDROP FUNCTION public._cm3_translation_lookup_get(_id bigint, _lang character varying); publicpostgresfalseP1255232945_cm3_trigger_attribute_group()FUNCTIONCREATE FUNCTION public._cm3_trigger_attribute_group() RETURNS trigger LANGUAGE plpgsql AS $$ DECLARE _sub_class regclass; BEGIN FOR _sub_class IN SELECT _cm3_class_list_descendant_classes(NEW."Owner") LOOP IF NOT EXISTS (SELECT * FROM "_AttributeGroup" WHERE "Status" = 'A' AND "Owner" = _sub_class AND "Code" = NEW."Code") THEN INSERT INTO "_AttributeGroup" ("Code", "Description", "Index", "Owner") VALUES (NEW."Code", NEW."Description", COALESCE((SELECT MAX("Index")+1 FROM "_AttributeGroup" WHERE "Status" = 'A' AND "Owner" = _sub_class), 1), _sub_class); RAISE NOTICE 'copy attribute group = % from class = % to class = %', NEW."Code", NEW."Owner", _sub_class; ELSEIF TG_OP = 'UPDATE' THEN IF NEW."Description" <> OLD."Description" THEN UPDATE "_AttributeGroup" SET "Description" = NEW."Description" WHERE "Status" = 'A' AND "Owner" = _sub_class AND "Code" = NEW."Code"; END IF; IF NEW."Index" <> OLD."Index" THEN UPDATE "_AttributeGroup" SET "Index" = NEW."Index" WHERE "Status" = 'A' AND "Owner" = _sub_class AND "Code" = NEW."Code"; --TODO improve index processing END IF; END IF; END LOOP; RETURN NULL; END $$; 5DROP FUNCTION public._cm3_trigger_attribute_group(); publicpostgresfalseQ1255232946/_cm3_trigger_card_cascade_delete_on_relations()FUNCTION8CREATE FUNCTION public._cm3_trigger_card_cascade_delete_on_relations() RETURNS trigger LANGUAGE plpgsql AS $$ BEGIN IF NEW."Status" = 'N' AND OLD."Status" = 'A' THEN UPDATE "Map" SET "Status" = 'N' WHERE "Status" = 'A' AND ( "IdObj1" = OLD."Id" OR "IdObj2" = OLD."Id" ); END IF; RETURN NEW; END $$; FDROP FUNCTION public._cm3_trigger_card_cascade_delete_on_relations(); publicpostgresfalseR1255232947"_cm3_trigger_card_create_history()FUNCTIONCREATE FUNCTION public._cm3_trigger_card_create_history() RETURNS trigger LANGUAGE plpgsql AS $$ DECLARE _attr_list_str varchar; BEGIN OLD."Id" = _cm3_utils_new_card_id(); OLD."Status" = 'U'; OLD."EndDate" = now(); SELECT INTO _attr_list_str string_agg(x.x,',') from (select quote_ident(x) x from _cm3_attribute_list(TG_RELID::regclass) x) x; EXECUTE format('INSERT INTO "%s_history" (%s) VALUES ( (%L::%s).* )', _cm3_utils_regclass_to_name(TG_RELID::regclass), _attr_list_str, OLD, TG_RELID::regclass); RETURN NEW; END $$; 9DROP FUNCTION public._cm3_trigger_card_create_history(); publicpostgresfalseS12552329482_cm3_trigger_card_enforce_foreign_key_for_source()FUNCTIONvCREATE FUNCTION public._cm3_trigger_card_enforce_foreign_key_for_source() RETURNS trigger LANGUAGE plpgsql AS $$ DECLARE _attribute_name varchar = TG_ARGV[0]; _class regclass = TG_ARGV[1]::regclass; _reference_id bigint; _reference_code varchar; _attribute_type varchar = coalesce(TG_ARGV[2],'bigint'); BEGIN IF _attribute_type ~ 'varchar|text' THEN EXECUTE format('SELECT (%L::%s).%I', NEW, TG_RELID::regclass, _attribute_name) INTO _reference_code; IF _cm3_utils_is_not_blank(_reference_code) AND NOT _cm3_card_exists_with_code(_class, _reference_code, NEW."Status" = 'A') THEN RAISE 'CM: error while inserting new % record: card not found for class = % code = % (referenced from attr %.% )', TG_RELID::regclass, _class, _reference_code, _cm3_utils_regclass_to_name(TG_RELID::regclass), _attribute_name; END IF; ELSE EXECUTE format('SELECT (%L::%s).%I', NEW, TG_RELID::regclass, _attribute_name) INTO _reference_id; IF _reference_id IS NOT NULL AND NOT _cm3_card_exists_with_id(_class, _reference_id, NEW."Status" = 'A') THEN RAISE 'CM: error while inserting new % record: card not found for class = % card_id = % (referenced from attr %.% )', TG_RELID::regclass, _class, _reference_id, _cm3_utils_regclass_to_name(TG_RELID::regclass), _attribute_name; END IF; END IF; RETURN NEW; END $$; IDROP FUNCTION public._cm3_trigger_card_enforce_foreign_key_for_source(); publicpostgresfalseT12552329492_cm3_trigger_card_enforce_foreign_key_for_target()FUNCTIONCREATE FUNCTION public._cm3_trigger_card_enforce_foreign_key_for_target() RETURNS trigger LANGUAGE plpgsql AS $$ DECLARE _class regclass = TG_ARGV[0]::regclass; _attr varchar = TG_ARGV[1]; _attribute_type varchar = coalesce(TG_ARGV[2], 'bigint'); BEGIN IF (TG_OP='UPDATE') THEN IF( NEW."Status"='N') THEN IF _attribute_type ~ 'varchar|text' THEN --TODO improve attr by type PERFORM _cm3_trigger_fail_if_reference_value_exists(_class, _attr, OLD."Code"); ELSE PERFORM _cm3_trigger_fail_if_reference_value_exists(_class, _attr, OLD."Id"); END IF; END IF; RETURN NEW; ELSE -- TG_OP='DELETE' RETURN OLD; END IF; END $$; IDROP FUNCTION public._cm3_trigger_card_enforce_foreign_key_for_target(); publicpostgresfalseU1255232950"_cm3_trigger_card_prepare_record()FUNCTIONCREATE FUNCTION public._cm3_trigger_card_prepare_record() RETURNS trigger LANGUAGE plpgsql AS $_$ BEGIN IF TG_OP = 'UPDATE' THEN IF NEW."Id" <> OLD."Id" THEN RAISE EXCEPTION 'CM: operation not allowed: cannot modify card id'; END IF; IF NEW."Status" = 'N' AND OLD."Status" = 'N' THEN RAISE EXCEPTION 'CM: operation not allowed: cannot modify this card because its "Status" is ''N'''; END IF; ELSEIF TG_OP = 'INSERT' THEN IF NEW."Status" IS NULL THEN NEW."Status" = 'A'; ELSEIF NEW."Status" = 'N' THEN RAISE EXCEPTION 'CM: operation not allowed: cannot INSERT a card with status "N"'; END IF; NEW."Id" = _cm3_utils_new_card_id(); IF _cm3_class_is_domain(TG_RELID::regclass) THEN NEW."IdDomain" = TG_RELID; IF NEW."IdClass1" IS NULL THEN NEW."IdClass1" = (SELECT "IdClass" FROM "Class" WHERE "Id" = NEW."IdObj1" AND "Status" = 'A'); END IF; IF NEW."IdClass2" IS NULL THEN NEW."IdClass2" = (SELECT "IdClass" FROM "Class" WHERE "Id" = NEW."IdObj2" AND "Status" = 'A'); END IF; PERFORM _cm3_domain_source_check(TG_RELID::regclass, NEW."IdClass1"); PERFORM _cm3_domain_target_check(TG_RELID::regclass, NEW."IdClass2"); ELSE NEW."IdClass" = TG_RELID; END IF; ELSEIF TG_OP = 'DELETE' AND OLD."Status" = 'N' THEN IF NOT _cm3_class_is_domain(TG_RELID::regclass) THEN EXECUTE format('DELETE FROM "Map" WHERE ( "IdObj1" = %s OR "IdObj2" = %s ) AND "Status" = ''N''', OLD."Id", OLD."Id"); EXECUTE format('DELETE FROM "Map" WHERE ( "IdObj1" = %s OR "IdObj2" = %s ) AND "Status" = ''U''', OLD."Id", OLD."Id"); END IF; EXECUTE format('DELETE FROM "%s_history" WHERE "CurrentId" = %s', _cm3_utils_regclass_to_name(TG_RELID::regclass), OLD."Id"); RETURN OLD; ELSE RAISE EXCEPTION 'CM: operation not allowed: you cannot execute % on this table', TG_OP; END IF; IF NEW."Status" !~ '^[AN]$' THEN RAISE EXCEPTION 'CM: operation not allowed: invalid card status = %', NEW."Status"; END IF; NEW."CurrentId" = NEW."Id"; NEW."BeginDate" = now(); NEW."User" = _cm3_utils_operation_context_get(); RETURN NEW; END $_$; 9DROP FUNCTION public._cm3_trigger_card_prepare_record(); publicpostgresfalseV1255232951$_cm3_trigger_card_update_relations()FUNCTION CREATE FUNCTION public._cm3_trigger_card_update_relations() RETURNS trigger LANGUAGE plpgsql AS $$ DECLARE _attribute_name text = TG_ARGV[0]; _domain regclass = TG_ARGV[1]::regclass; _direction varchar = lower(TG_ARGV[2]); _target_id_old bigint; _target_id_new bigint; _source_id bigint = NEW."Id"; _source_class regclass = TG_RELID::regclass; _target_class regclass = _cm3_utils_name_to_regclass(_cm3_class_comment_get(_domain, CASE _direction WHEN 'direct' THEN 'CLASS2' ELSE 'CLASS1' END)); BEGIN IF TG_OP = 'UPDATE' THEN EXECUTE format('SELECT (%L::%s).%I', OLD, TG_RELID::regclass, _attribute_name) INTO _target_id_old; END IF; EXECUTE format('SELECT (%L::%s).%I', NEW, TG_RELID::regclass, _attribute_name) INTO _target_id_new; IF _target_id_new IS NOT NULL AND _cm3_class_is_superclass(_target_class) THEN EXECUTE format('SELECT "IdClass" FROM %s WHERE "Id" = %L AND "Status" = ''A''', _target_class, _target_id_new) INTO _target_class; END IF; RAISE DEBUG 'card_update_relations: direction = %, old target = %, new target = % %', _direction, _target_id_old, _target_class, _target_id_new; IF _target_id_new IS DISTINCT FROM _target_id_old AND (_target_id_new IS NOT NULL OR _target_id_old IS NOT NULL) THEN IF _target_id_old IS NULL THEN RAISE DEBUG 'card_update_relations: insert relation record = % -> % (%)', _source_id, _target_id_new, _direction; IF _direction = 'direct' THEN EXECUTE format('INSERT INTO %s ("IdDomain","IdClass1","IdObj1","IdClass2","IdObj2","Status") VALUES (%L,%L,%L,%L,%L,''A'') ON CONFLICT DO NOTHING', _domain, _domain, _source_class, _source_id, _target_class, _target_id_new); ELSE EXECUTE format('INSERT INTO %s ("IdDomain","IdClass2","IdObj2","IdClass1","IdObj1","Status") VALUES (%L,%L,%L,%L,%L,''A'' ) ON CONFLICT DO NOTHING', _domain, _domain, _source_class, _source_id, _target_class, _target_id_new); END IF; ELSEIF _target_id_new IS NULL THEN RAISE DEBUG 'card_update_relations: delete relation record = % -> % (%)', _source_id, _target_id_old, _direction; IF _direction = 'direct' THEN EXECUTE format('UPDATE %s SET "Status" = ''N'' WHERE "Status" = ''A'' AND "IdObj1" = %L', _domain, _source_id); ELSE EXECUTE format('UPDATE %s SET "Status" = ''N'' WHERE "Status" = ''A'' AND "IdObj2" = %L', _domain, _source_id); END IF; ELSE RAISE DEBUG 'card_update_relations: update relation record = % -> % (%)', _source_id, _target_id_new, _direction; IF _direction = 'direct' THEN EXECUTE format('UPDATE %s SET "IdClass2" = %L, "IdObj2" = %L WHERE "IdObj1" = %L AND "Status" = ''A'' AND "IdObj2" <> %L', _domain, _target_class, _target_id_new, _source_id, _target_id_new); ELSE EXECUTE format('UPDATE %s SET "IdClass1" = %L, "IdObj1" = %L WHERE "IdObj2" = %L AND "Status" = ''A'' AND "IdObj1" <> %L', _domain, _target_class, _target_id_new, _source_id, _target_id_new); END IF; END IF; END IF; RETURN NEW; END $$; ;DROP FUNCTION public._cm3_trigger_card_update_relations(); publicpostgresfalseW1255232952!_cm3_trigger_custompage_cleanup()FUNCTIONCREATE FUNCTION public._cm3_trigger_custompage_cleanup() RETURNS trigger LANGUAGE plpgsql AS $$ DECLARE _record RECORD; BEGIN FOR _record IN SELECT * FROM "_Grant" WHERE "Type" = 'CustomPage' AND "Status" = 'A' AND "ObjectId" = OLD."Id" LOOP RAISE NOTICE 'cascade drop grant record = %', _record; EXECUTE format('UPDATE "_Grant" SET "Status" = ''N'' WHERE "Id" = %s', _record."Id"); --TODO cache drop ?? END LOOP; --TODO menu cleanup? other cleanup? RETURN NEW; END $$; 8DROP FUNCTION public._cm3_trigger_custompage_cleanup(); publicpostgresfalseX1255232953P_cm3_trigger_fail_if_reference_value_exists(regclass, character varying, bigint)FUNCTIONvCREATE FUNCTION public._cm3_trigger_fail_if_reference_value_exists(_class regclass, _attr character varying, _value bigint) RETURNS void LANGUAGE plpgsql AS $$ BEGIN IF _cm3_attribute_has_value(_class, _attr, _value) THEN RAISE EXCEPTION 'CM: cannot complete operation: found referencing card of type = % with attr % = %', _class, _attr, _value; END IF; END $$; {DROP FUNCTION public._cm3_trigger_fail_if_reference_value_exists(_class regclass, _attr character varying, _value bigint); publicpostgresfalseY1255232954[_cm3_trigger_fail_if_reference_value_exists(regclass, character varying, character varying)FUNCTIONCREATE FUNCTION public._cm3_trigger_fail_if_reference_value_exists(_class regclass, _attr character varying, _value character varying) RETURNS void LANGUAGE plpgsql AS $$ BEGIN IF _cm3_attribute_has_value(_class, _attr, _value) THEN RAISE EXCEPTION 'CM: cannot complete operation: found referencing card of type = % with attr % = %', _class, _attr, _value; END IF; END $$; DROP FUNCTION public._cm3_trigger_fail_if_reference_value_exists(_class regclass, _attr character varying, _value character varying); publicpostgresfalseZ1255232955_cm3_trigger_filter_cleanup()FUNCTIONCREATE FUNCTION public._cm3_trigger_filter_cleanup() RETURNS trigger LANGUAGE plpgsql AS $$ DECLARE _record RECORD; BEGIN FOR _record IN SELECT * FROM "_Grant" WHERE "Type" = 'Filter' AND "Status" = 'A' AND "ObjectId" = OLD."Id" LOOP RAISE NOTICE 'cascade drop grant record = %', _record; EXECUTE format('UPDATE "_Grant" SET "Status" = ''N'' WHERE "Id" = %s', _record."Id"); --TODO cache drop ?? END LOOP; --TODO default filter cleanup from classes ?? RETURN NEW; END $$; 4DROP FUNCTION public._cm3_trigger_filter_cleanup(); publicpostgresfalse[1255232956!_cm3_trigger_ietemplate_cleanup()FUNCTION CREATE FUNCTION public._cm3_trigger_ietemplate_cleanup() RETURNS trigger LANGUAGE plpgsql AS $$ DECLARE _record RECORD; BEGIN FOR _record IN SELECT * FROM "_Grant" WHERE "Type" = 'IETemplate' AND "Status" = 'A' AND "ObjectId" = OLD."Id" LOOP RAISE NOTICE 'cascade drop grant record = %', _record; EXECUTE format('UPDATE "_Grant" SET "Status" = ''N'' WHERE "Id" = %s', _record."Id"); --TODO cache drop ?? END LOOP; --TODO trigger config cleanup? other cleanup? RETURN NEW; END $$; 8DROP FUNCTION public._cm3_trigger_ietemplate_cleanup(); publicpostgresfalse\1255232957_cm3_trigger_lookup()FUNCTIONCREATE FUNCTION public._cm3_trigger_lookup() RETURNS trigger LANGUAGE plpgsql AS $$ DECLARE _type varchar; BEGIN FOR _type IN SELECT DISTINCT "Type" FROM "LookUp" l1 WHERE "Status" = 'A' AND NOT EXISTS (SELECT * FROM "LookUp" l2 WHERE l1."Type" = l2."Type" AND "Status" = 'A' AND "Code" = 'org.cmdbuild.LOOKUPTYPE') LOOP INSERT INTO "LookUp" ("Code", "Type") VALUES ('org.cmdbuild.LOOKUPTYPE', _type); END LOOP; RETURN NULL; END $$; ,DROP FUNCTION public._cm3_trigger_lookup(); publicpostgresfalse_1255232958_cm3_trigger_menu_validation()FUNCTIONCREATE FUNCTION public._cm3_trigger_menu_validation() RETURNS trigger LANGUAGE plpgsql AS $$ DECLARE _record record; _to_process jsonb; _element jsonb; _codes varchar[]; _duplicates varchar[]; BEGIN _to_process = NEW."Data"->'children'; _codes = ARRAY[]::varchar[]; WHILE jsonb_array_length(_to_process) > 0 LOOP _element = _to_process->0; _codes = array_append(_codes, (_element->>'code')::varchar); _to_process = ( _to_process - 0 ) || ( _element->'children' ); END LOOP; SELECT array_agg(_code) INTO _duplicates FROM (SELECT x _code, count(*) _count FROM unnest(_codes) x GROUP BY x) q WHERE _count > 1; IF cardinality(_duplicates) > 0 THEN RAISE EXCEPTION 'CM: invalid menu data for record = %, duplicate node ids = %', NEW."Id", _duplicates; END IF; _to_process = NEW."Data"->'children'; _codes = ARRAY[]::varchar[]; FOR _record IN SELECT * FROM "_Menu" WHERE "Status" = 'A' LOOP _to_process = _to_process || ( _record."Data"->'children' ); END LOOP; WHILE jsonb_array_length(_to_process) > 0 LOOP _element = _to_process->0; _codes = array_append(_codes, (_element->>'code')::varchar); _to_process = ( _to_process - 0 ) || ( _element->'children' ); END LOOP; SELECT array_agg(_code) INTO _duplicates FROM (SELECT x _code, count(*) _count FROM unnest(_codes) x GROUP BY x) q WHERE _count > 1; IF cardinality(_duplicates) > 0 THEN RAISE EXCEPTION 'CM: invalid menu data, duplicate node ids = %', _duplicates; END IF; RAISE NOTICE 'menu data is OK for menu = %', NEW."Id"; RETURN NEW; END $$; 5DROP FUNCTION public._cm3_trigger_menu_validation(); publicpostgresfalse`1255232959)_cm3_trigger_relation_update_references()FUNCTIONCREATE FUNCTION public._cm3_trigger_relation_update_references() RETURNS trigger LANGUAGE plpgsql AS $$ DECLARE _attribute_name text = TG_ARGV[1]; _class regclass = TG_ARGV[0]::regclass; _direction varchar = TG_ARGV[2]; _card_column text = CASE WHEN _direction = 'direct' THEN 'IdObj1' ELSE 'IdObj2' END; _reference_column text = CASE WHEN _direction = 'direct' THEN 'IdObj2' ELSE 'IdObj1' END; _old_card_id bigint; _new_card_id bigint; _old_ref_value bigint; _new_ref_value bigint; BEGIN IF NEW."Status" IN ('A','N') THEN RAISE DEBUG 'relation_update_references domain = % to attr = %.%', _cm3_utils_regclass_to_domain_name(TG_RELID::regclass), _cm3_utils_regclass_to_name(_class), _attribute_name; EXECUTE format('SELECT (%L::%s).%I', NEW, TG_RELID::regclass, _card_column) INTO _new_card_id; IF NEW."Status" = 'A' THEN EXECUTE format('SELECT (%L::%s).%I', NEW, TG_RELID::regclass, _reference_column) INTO _new_ref_value; END IF; IF TG_OP = 'UPDATE' THEN EXECUTE format('SELECT (%L::%s).%I', OLD, TG_RELID::regclass, _card_column) INTO _old_card_id; IF _old_card_id <> _new_card_id THEN PERFORM _cm3_reference_update(_class, _attribute_name, _old_card_id, NULL); ELSE EXECUTE format('SELECT (%L::%s).%I', OLD, TG_RELID::regclass, _reference_column) INTO _old_ref_value; END IF; END IF; RAISE DEBUG 'relation_update_references domain = %: old rel = % -> %, new rel = % -> % (direction = %)', _cm3_utils_regclass_to_domain_name(TG_RELID::regclass), _old_card_id, _old_ref_value, _new_card_id, _new_ref_value, _direction; IF _new_ref_value IS DISTINCT FROM _old_ref_value THEN PERFORM _cm3_reference_update( _class, _attribute_name, _new_card_id, _new_ref_value); END IF; END IF; RETURN NEW; END $$; @DROP FUNCTION public._cm3_trigger_relation_update_references(); publicpostgresfalsea1255232960_cm3_trigger_report_cleanup()FUNCTIONCREATE FUNCTION public._cm3_trigger_report_cleanup() RETURNS trigger LANGUAGE plpgsql AS $$ DECLARE _record RECORD; BEGIN FOR _record IN SELECT * FROM "_Grant" WHERE "Type" = 'Report' AND "Status" = 'A' AND "ObjectId" = OLD."Id" LOOP RAISE NOTICE 'cascade drop grant record = %', _record; EXECUTE format('UPDATE "_Grant" SET "Status" = ''N'' WHERE "Id" = %s', _record."Id"); --TODO cache drop ?? END LOOP; --TODO menu cleanup? other cleanup? RETURN NEW; END $$; 4DROP FUNCTION public._cm3_trigger_report_cleanup(); publicpostgresfalseb12552329615_cm3_trigger_simplecard_cascade_delete_on_relations()FUNCTIONCREATE FUNCTION public._cm3_trigger_simplecard_cascade_delete_on_relations() RETURNS trigger LANGUAGE plpgsql AS $$ BEGIN UPDATE "Map" SET "Status" = 'N' WHERE "Status" = 'A' AND ( "IdObj1" = OLD."Id" OR "IdObj2" = OLD."Id" ); RETURN NEW; END $$; LDROP FUNCTION public._cm3_trigger_simplecard_cascade_delete_on_relations(); publicpostgresfalsec12552329628_cm3_trigger_simplecard_enforce_foreign_key_for_source()FUNCTION_CREATE FUNCTION public._cm3_trigger_simplecard_enforce_foreign_key_for_source() RETURNS trigger LANGUAGE plpgsql AS $$ DECLARE _attribute_name varchar = TG_ARGV[0]; _class regclass = TG_ARGV[1]::regclass; _reference_id bigint; _reference_code varchar; _attribute_type varchar = coalesce(TG_ARGV[2],'bigint'); BEGIN IF _attribute_type ~ 'varchar|text' THEN EXECUTE format('SELECT (%L::%s).%I', NEW, TG_RELID::regclass, _attribute_name) INTO _reference_code; IF _cm3_utils_is_not_blank(_reference_code) AND NOT _cm3_card_exists_with_code(_class, _reference_code, FALSE) THEN RAISE 'CM: error while inserting new % record: card not found for class = % code = % (referenced from attr %.% )', TG_RELID::regclass, _class, _reference_code, _cm3_utils_regclass_to_name(TG_RELID::regclass), _attribute_name; END IF; ELSE EXECUTE format('SELECT (%L::%s).%I', NEW, TG_RELID::regclass, _attribute_name) INTO _reference_id; IF _reference_id IS NOT NULL AND NOT _cm3_card_exists_with_id(_class, _reference_id, FALSE) THEN RAISE 'CM: error while inserting new % record: card not found for class = % card_id = % (referenced from attr %.% )', TG_RELID::regclass, _class, _reference_id, _cm3_utils_regclass_to_name(TG_RELID::regclass), _attribute_name; END IF; END IF; RETURN NEW; END $$; ODROP FUNCTION public._cm3_trigger_simplecard_enforce_foreign_key_for_source(); publicpostgresfalsed1255232963(_cm3_trigger_simplecard_prepare_record()FUNCTIONCREATE FUNCTION public._cm3_trigger_simplecard_prepare_record() RETURNS trigger LANGUAGE plpgsql AS $$ BEGIN IF (TG_OP='UPDATE') THEN IF (NEW."Id" <> OLD."Id") THEN -- Id change RAISE EXCEPTION 'CM_FORBIDDEN_OPERATION'; END IF; ELSE NEW."IdClass" = TG_RELID; END IF; NEW."BeginDate" = now(); NEW."User" = _cm3_utils_operation_context_get(); RETURN NEW; END $$; ?DROP FUNCTION public._cm3_trigger_simplecard_prepare_record(); publicpostgresfalsee1255232964+_cm3_trigger_superclass_forbid_operations()FUNCTIONCREATE FUNCTION public._cm3_trigger_superclass_forbid_operations() RETURNS trigger LANGUAGE plpgsql AS $$ BEGIN RAISE EXCEPTION 'CM: operation not allowed: you cannot execute % on superclass table', TG_OP; END $$; BDROP FUNCTION public._cm3_trigger_superclass_forbid_operations(); publicpostgresfalsef12552329650_cm3_trigger_utils_tgargs_to_string_array(bytea)FUNCTION'CREATE FUNCTION public._cm3_trigger_utils_tgargs_to_string_array(_args bytea) RETURNS character varying[] LANGUAGE sql IMMUTABLE AS $$ SELECT array(SELECT param FROM(SELECT regexp_split_to_table(encode(_args, 'escape'), E'\\\\000') AS param) AS q WHERE q.param <> '')::varchar[] $$; MDROP FUNCTION public._cm3_trigger_utils_tgargs_to_string_array(_args bytea); publicpostgresfalseg1255232966_cm3_trigger_view_cleanup()FUNCTIONCREATE FUNCTION public._cm3_trigger_view_cleanup() RETURNS trigger LANGUAGE plpgsql AS $$ DECLARE _record RECORD; BEGIN FOR _record IN SELECT * FROM "_Grant" WHERE "Type" = 'View' AND "Status" = 'A' AND "ObjectId" = OLD."Id" LOOP RAISE NOTICE 'cascade drop grant record = %', _record; EXECUTE format('UPDATE "_Grant" SET "Status" = ''N'' WHERE "Id" = %s', _record."Id"); --TODO cache drop ?? END LOOP; --TODO menu cleanup? other cleanup? RETURN NEW; END $$; 2DROP FUNCTION public._cm3_trigger_view_cleanup(); publicpostgresfalseh1255232967_cm3_user_config_get(bigint)FUNCTIONCREATE FUNCTION public._cm3_user_config_get(_userid bigint) RETURNS jsonb LANGUAGE plpgsql AS $$ BEGIN RETURN COALESCE((SELECT "Data" FROM "_UserConfig" WHERE "Owner" = _userid AND "Status" = 'A'),'{}'::jsonb); END $$; ;DROP FUNCTION public._cm3_user_config_get(_userid bigint); publicpostgresfalse]1255232968'_cm3_user_config_get(character varying)FUNCTIONCREATE FUNCTION public._cm3_user_config_get(_username character varying) RETURNS jsonb LANGUAGE plpgsql AS $$ BEGIN RETURN (SELECT _cm3_user_config_get((SELECT "Id" FROM "User" WHERE "Username" = _username AND "Status" = 'A'))); END $$; HDROP FUNCTION public._cm3_user_config_get(_username character varying); publicpostgresfalsej1255232969#_cm3_user_config_set(bigint, jsonb)FUNCTIONCREATE FUNCTION public._cm3_user_config_set(_userid bigint, _data jsonb) RETURNS void LANGUAGE plpgsql AS $$ BEGIN IF EXISTS (SELECT 1 FROM "_UserConfig" WHERE "Owner" = _userid AND "Status" = 'A') THEN UPDATE "_UserConfig" SET "Data" = _data WHERE "Owner" = _userid AND "Status" = 'A'; ELSE INSERT INTO "_UserConfig" ("Owner","Data") VALUES (_userid,_data); END IF; END $$; HDROP FUNCTION public._cm3_user_config_set(_userid bigint, _data jsonb); publicpostgresfalsek1255232970._cm3_user_config_set(character varying, jsonb)FUNCTIONCREATE FUNCTION public._cm3_user_config_set(_username character varying, _data jsonb) RETURNS void LANGUAGE plpgsql AS $$ BEGIN PERFORM _cm3_user_config_set((SELECT "Id" FROM "User" WHERE "Username" = _username AND "Status" = 'A'),_data); END $$; UDROP FUNCTION public._cm3_user_config_set(_username character varying, _data jsonb); publicpostgresfalsel1255232971M_cm3_user_config_set(character varying, character varying, character varying)FUNCTION$CREATE FUNCTION public._cm3_user_config_set(_username character varying, _key character varying, _value character varying) RETURNS void LANGUAGE plpgsql AS $$ BEGIN PERFORM _cm3_user_config_set(_username, _cm3_user_config_get(_username) || jsonb_build_object(_key, _value)); END $$; zDROP FUNCTION public._cm3_user_config_set(_username character varying, _key character varying, _value character varying); publicpostgresfalsem12552329728_cm3_user_create(character varying, character varying[])FUNCTIONCREATE FUNCTION public._cm3_user_create(_username character varying, VARIADIC _groups character varying[]) RETURNS bigint LANGUAGE plpgsql AS $$ BEGIN RETURN _cm3_user_create(_username, NULL, variadic _groups); END $$; jDROP FUNCTION public._cm3_user_create(_username character varying, VARIADIC _groups character varying[]); publicpostgresfalsen1255232973K_cm3_user_create(character varying, character varying, character varying[])FUNCTION(CREATE FUNCTION public._cm3_user_create(_username character varying, _password character varying, VARIADIC _groups character varying[]) RETURNS bigint LANGUAGE plpgsql AS $$ DECLARE _userid bigint; _role varchar; _roleid bigint; BEGIN RAISE NOTICE 'create user %', _username; INSERT INTO "User" ("Username","Password") VALUES (_username, _password) RETURNING "Id" INTO _userid; FOREACH _role IN ARRAY _groups LOOP RAISE NOTICE 'add group % to user %', _role, _username; _roleid = (SELECT "Id" FROM "Role" WHERE "Code" = _role); IF _roleid IS NULL THEN RAISE 'group not found for code =< % >', _role; END IF; INSERT INTO "Map_UserRole" ("IdObj1","IdObj2") VALUES (_userid, _roleid); END LOOP; RETURN _userid; END $$; DROP FUNCTION public._cm3_user_create(_username character varying, _password character varying, VARIADIC _groups character varying[]); publicpostgresfalseo1255232974-_cm3_utils_build_sqltype_string(oid, integer)FUNCTION&CREATE FUNCTION public._cm3_utils_build_sqltype_string(_sqltype oid, _typemod integer) RETURNS character varying LANGUAGE sql STABLE AS $$ SELECT pg_type.typname::text || CASE WHEN _typemod IS NULL THEN '' WHEN pg_type.typname IN ('varchar','bpchar') AND _typemod < 0 THEN '' WHEN pg_type.typname IN ('varchar','bpchar') THEN '(' || _typemod - 4 || ')' WHEN pg_type.typname = 'numeric' THEN '(' || _typemod / 65536 || ',' || _typemod - _typemod / 65536 * 65536 - 4|| ')' ELSE '' END FROM pg_type WHERE pg_type.oid = _sqltype; $$; VDROP FUNCTION public._cm3_utils_build_sqltype_string(_sqltype oid, _typemod integer); publicpostgresfalsep1255232975"_cm3_utils_bytea_to_varchar(bytea)FUNCTIONCREATE FUNCTION public._cm3_utils_bytea_to_varchar(_value bytea) RETURNS character varying LANGUAGE sql IMMUTABLE AS $$ SELECT convert_from(_value, 'UTF8'); $$; @DROP FUNCTION public._cm3_utils_bytea_to_varchar(_value bytea); publicpostgresfalseq12552329761_cm3_utils_class_trigger_copy(regclass, regclass)FUNCTIONWCREATE FUNCTION public._cm3_utils_class_trigger_copy(_source_class regclass, _target_class regclass) RETURNS void LANGUAGE plpgsql AS $$ DECLARE _trigger record; BEGIN FOR _trigger IN SELECT * FROM _cm3_class_triggers_list_detailed(_source_class) WHERE trigger_function IN ('_cm3_trigger_card_enforce_foreign_key_for_target', '_cm3_trigger_card_enforce_foreign_key_for_source', '_cm3_trigger_card_update_relations') LOOP RAISE NOTICE 'copy trigger = % from class = % to class = %', _trigger.trigger_name, _source_class, _target_class; EXECUTE format('CREATE TRIGGER %I %s ON %s FOR EACH %s EXECUTE PROCEDURE %I(%s)', _trigger.trigger_name, _trigger.trigger_when, _target_class, _trigger.trigger_for_each, _trigger.trigger_function, (SELECT string_agg(quote_ident(x),',') FROM unnest(_trigger.trigger_params) x)); END LOOP; END $$; dDROP FUNCTION public._cm3_utils_class_trigger_copy(_source_class regclass, _target_class regclass); publicpostgresfalser1255232977/_cm3_utils_direction_inverse(character varying)FUNCTIONCREATE FUNCTION public._cm3_utils_direction_inverse(_direction character varying) RETURNS character varying LANGUAGE plpgsql AS $$ BEGIN RETURN CASE _direction WHEN 'direct' THEN 'inverse' ELSE 'direct' END; END $$; QDROP FUNCTION public._cm3_utils_direction_inverse(_direction character varying); publicpostgresfalses1255232978 _cm3_utils_disk_usage_detailed()FUNCTIONJCREATE FUNCTION public._cm3_utils_disk_usage_detailed() RETURNS TABLE(schema character varying, item regclass, type character varying, row_estimate real, total_size bigint, total_size_pretty character varying) LANGUAGE plpgsql AS $$ BEGIN RETURN QUERY WITH q AS (SELECT a.schema, oid::regclass item, (CASE WHEN _cm3_class_is_simple(oid) THEN 'simpleclass' WHEN _cm3_class_is_standard(oid) THEN 'class' WHEN _cm3_class_is_domain(oid) THEN 'map' WHEN _cm3_class_is_history(oid) THEN 'history' ELSE 'other' END)::varchar AS type, a.row_estimate, total_bytes, pg_size_pretty(total_bytes)::varchar AS total FROM ( SELECT c.oid oid, nspname::varchar AS schema, c.reltuples AS row_estimate, pg_total_relation_size(c.oid) AS total_bytes, pg_indexes_size(c.oid) AS index_bytes, COALESCE(pg_total_relation_size(reltoastrelid),0) AS toast_bytes FROM pg_class c LEFT JOIN pg_namespace n ON n.oid = c.relnamespace WHERE relkind = 'r' AND nspname IN ('public','gis') ) a ) SELECT * FROM q ORDER BY schema, type, q.item::varchar; END $$; 7DROP FUNCTION public._cm3_utils_disk_usage_detailed(); publicpostgresfalset1255232979(_cm3_utils_drop_class_triggers(regclass)FUNCTIONHCREATE FUNCTION public._cm3_utils_drop_class_triggers(_table regclass) RETURNS void LANGUAGE plpgsql AS $$ DECLARE _trigger varchar; BEGIN FOR _trigger IN SELECT t.tgname FROM pg_trigger t WHERE t.tgrelid = _table AND NOT tgisinternal LOOP EXECUTE format('DROP TRIGGER %I ON %s',_trigger,_table); END LOOP; END $$; FDROP FUNCTION public._cm3_utils_drop_class_triggers(_table regclass); publicpostgresfalseu1255232980&_cm3_utils_is_blank(character varying)FUNCTIONCREATE FUNCTION public._cm3_utils_is_blank(_value character varying) RETURNS boolean LANGUAGE sql IMMUTABLE AS $_$ SELECT _value IS NULL OR _value ~ '^[\s]*$'; $_$; DDROP FUNCTION public._cm3_utils_is_blank(_value character varying); publicpostgresfalsev1255232981*_cm3_utils_is_not_blank(character varying)FUNCTIONCREATE FUNCTION public._cm3_utils_is_not_blank(_value character varying) RETURNS boolean LANGUAGE sql IMMUTABLE AS $_$ SELECT _value IS NOT NULL AND _value !~ '^[\s]*$'; $_$; HDROP FUNCTION public._cm3_utils_is_not_blank(_value character varying); publicpostgresfalsew1255232982)_cm3_utils_name_escape(character varying)FUNCTIONCREATE FUNCTION public._cm3_utils_name_escape(_class_name character varying) RETURNS character varying LANGUAGE plpgsql IMMUTABLE STRICT AS $_$ BEGIN IF _class_name ~ '^".*"$' THEN RETURN _class_name; ELSE IF _class_name ~ '^[^.]+[.][^.]+$' THEN RETURN regexp_replace(_class_name, '^([^.]+)[.]([^.]+)$', '"\1"."\2"'); ELSE RETURN format('"%s"', _class_name); END IF; END IF; END $_$; LDROP FUNCTION public._cm3_utils_name_escape(_class_name character varying); publicpostgresfalsex1255232983._cm3_utils_name_to_basename(character varying)FUNCTIONCREATE FUNCTION public._cm3_utils_name_to_basename(_class_name character varying) RETURNS character varying LANGUAGE plpgsql IMMUTABLE STRICT AS $$ BEGIN return regexp_replace(regexp_replace(_class_name,'"','','g'),'^([^.]+)[.]',''); END $$; QDROP FUNCTION public._cm3_utils_name_to_basename(_class_name character varying); publicpostgresfalsey1255232984._cm3_utils_name_to_regclass(character varying)FUNCTIONCREATE FUNCTION public._cm3_utils_name_to_regclass(_class_name character varying) RETURNS regclass LANGUAGE plpgsql IMMUTABLE STRICT AS $$ BEGIN _class_name = _cm3_utils_name_escape(_class_name); IF (SELECT pg_get_function_arguments(oid) FROM pg_proc WHERE proname = 'to_regclass') = 'cstring' THEN RETURN to_regclass(_class_name::cstring); ELSE RETURN to_regclass(_class_name::text); END IF; END $$; QDROP FUNCTION public._cm3_utils_name_to_regclass(_class_name character varying); publicpostgresfalsei1255232985_cm3_utils_new_card_id()FUNCTIONCREATE FUNCTION public._cm3_utils_new_card_id() RETURNS bigint LANGUAGE sql AS $$ SELECT nextval('class_seq')::bigint; $$; /DROP FUNCTION public._cm3_utils_new_card_id(); publicpostgresfalsez1255232986"_cm3_utils_operation_context_get()FUNCTIONxCREATE FUNCTION public._cm3_utils_operation_context_get() RETURNS character varying LANGUAGE plpgsql AS $_$ DECLARE _user varchar = _cm3_utils_operation_user_get(); _scope varchar = _cm3_utils_operation_scope_get(); BEGIN IF _scope ~ '^(|default)$' THEN RETURN _user; ELSE RETURN format('%s / %s', _scope, _user); END IF; END $_$; 9DROP FUNCTION public._cm3_utils_operation_context_get(); publicpostgresfalse{1255232987 _cm3_utils_operation_scope_get()FUNCTIONCREATE FUNCTION public._cm3_utils_operation_scope_get() RETURNS character varying LANGUAGE plpgsql AS $$ BEGIN RETURN current_setting('cmdbuild.operation_scope'); EXCEPTION WHEN undefined_object THEN RETURN 'default'; END $$; 7DROP FUNCTION public._cm3_utils_operation_scope_get(); publicpostgresfalse|1255232988_cm3_utils_operation_user_get()FUNCTIONCREATE FUNCTION public._cm3_utils_operation_user_get() RETURNS character varying LANGUAGE plpgsql AS $$ BEGIN RETURN current_setting('cmdbuild.operation_user'); EXCEPTION WHEN undefined_object THEN RETURN 'postgres'; END $$; 6DROP FUNCTION public._cm3_utils_operation_user_get(); publicpostgresfalse}12552329891_cm3_utils_prepare_class_triggers_query(regclass)FUNCTION CREATE FUNCTION public._cm3_utils_prepare_class_triggers_query(_table regclass) RETURNS character varying LANGUAGE sql AS $$ SELECT coalesce((SELECT string_agg(pg_get_triggerdef(t.oid),';') FROM pg_trigger t WHERE t.tgrelid = _table AND NOT tgisinternal),'SELECT 1') || ';'; $$; ODROP FUNCTION public._cm3_utils_prepare_class_triggers_query(_table regclass); publicpostgresfalse~1255232990_cm3_utils_random_id()FUNCTIONCREATE FUNCTION public._cm3_utils_random_id() RETURNS character varying LANGUAGE sql AS $$ SELECT md5(random()::text); $$; -DROP FUNCTION public._cm3_utils_random_id(); publicpostgresfalse1255232991,_cm3_utils_regclass_to_domain_name(regclass)FUNCTIONCREATE FUNCTION public._cm3_utils_regclass_to_domain_name(_class regclass) RETURNS character varying LANGUAGE plpgsql IMMUTABLE AS $$ BEGIN RETURN regexp_replace(_cm3_utils_regclass_to_name(_class), '^Map_', ''); END $$; JDROP FUNCTION public._cm3_utils_regclass_to_domain_name(_class regclass); publicpostgresfalse1255232992(_cm3_utils_regclass_to_history(regclass)FUNCTIONCREATE FUNCTION public._cm3_utils_regclass_to_history(_class regclass) RETURNS regclass LANGUAGE sql AS $$ SELECT format('"%s_history"',_cm3_utils_regclass_to_name(_class))::regclass; $$; FDROP FUNCTION public._cm3_utils_regclass_to_history(_class regclass); publicpostgresfalse1255232993%_cm3_utils_regclass_to_name(regclass)FUNCTIONCREATE FUNCTION public._cm3_utils_regclass_to_name(_class regclass) RETURNS character varying LANGUAGE plpgsql IMMUTABLE AS $$ BEGIN RETURN _cm3_utils_name_to_basename(_class::varchar); END $$; CDROP FUNCTION public._cm3_utils_regclass_to_name(_class regclass); publicpostgresfalse1255232994$_cm3_utils_restore_dependant_views()FUNCTIONCREATE FUNCTION public._cm3_utils_restore_dependant_views() RETURNS void LANGUAGE plpgsql AS $$ DECLARE _record record; BEGIN FOR _record IN SELECT * FROM _utils_dependant_views_aux ORDER BY index DESC LOOP RAISE NOTICE 'restore view %', _record.viewname; EXECUTE format('CREATE VIEW %s AS %s', _record.viewname, _record.viewdef); END LOOP; DROP TABLE _utils_dependant_views_aux; END $$; ;DROP FUNCTION public._cm3_utils_restore_dependant_views(); publicpostgresfalse1255232995)_cm3_utils_shrink_name(character varying)FUNCTIONCREATE FUNCTION public._cm3_utils_shrink_name(_name character varying) RETURNS character varying LANGUAGE sql AS $$ SELECT _cm3_utils_shrink_name(_name, 20); $$; FDROP FUNCTION public._cm3_utils_shrink_name(_name character varying); publicpostgresfalse12552329962_cm3_utils_shrink_name(character varying, integer)FUNCTIONCREATE FUNCTION public._cm3_utils_shrink_name(_name character varying, _maxlength integer) RETURNS character varying LANGUAGE plpgsql AS $$ BEGIN IF length(_name) <= _maxlength THEN RETURN _name; ELSE RETURN substring( _name from 1 for ( _maxlength / 3 ) ) || substring( md5(_name) from 1 for ( _maxlength / 3 + _maxlength % 3 ) ) || substring( _name from ( length(_name) - _maxlength / 3 + 1 ) for ( _maxlength / 3 ) ); END IF; END $$; ZDROP FUNCTION public._cm3_utils_shrink_name(_name character varying, _maxlength integer); publicpostgresfalse1255232997-_cm3_utils_shrink_name_lon(character varying)FUNCTIONCREATE FUNCTION public._cm3_utils_shrink_name_lon(_name character varying) RETURNS character varying LANGUAGE sql AS $$ SELECT _cm3_utils_shrink_name(_name, 40); $$; JDROP FUNCTION public._cm3_utils_shrink_name_lon(_name character varying); publicpostgresfalse12552329983_cm3_utils_store_and_drop_dependant_views(regclass)FUNCTIONCREATE FUNCTION public._cm3_utils_store_and_drop_dependant_views(_table regclass) RETURNS void LANGUAGE plpgsql AS $$ DECLARE _view regclass; _sub_table regclass; BEGIN IF to_regclass('_utils_dependant_views_aux') IS NULL THEN CREATE TEMPORARY TABLE _utils_dependant_views_aux(index int, viewname varchar, viewdef varchar); END IF; FOR _view IN select distinct(r.ev_class::regclass) as views from pg_depend d join pg_rewrite r on r.oid = d.objid where refclassid = 'pg_class'::regclass and refobjid = _table and classid = 'pg_rewrite'::regclass and ev_class != _table LOOP PERFORM _cm3_utils_store_and_drop_dependant_views(_view); IF _view::varchar <> _view::int::varchar THEN --TODO check this INSERT INTO _utils_dependant_views_aux (index, viewname, viewdef) VALUES ( (SELECT COALESCE(MAX(index)+1,0) FROM _utils_dependant_views_aux), _view::varchar, pg_get_viewdef(_view, true) ); RAISE NOTICE 'store and drop view %', _view; EXECUTE format('DROP VIEW %s', _view); END IF; END LOOP; FOR _sub_table IN SELECT i.inhrelid::regclass FROM pg_catalog.pg_inherits i WHERE i.inhparent = _table LOOP PERFORM _cm3_utils_store_and_drop_dependant_views(_sub_table); END LOOP; END $$; QDROP FUNCTION public._cm3_utils_store_and_drop_dependant_views(_table regclass); publicpostgresfalse1255232999%_cm3_utils_strip_null_or_empty(jsonb)FUNCTIONCREATE FUNCTION public._cm3_utils_strip_null_or_empty(_data jsonb) RETURNS jsonb LANGUAGE sql AS $$ SELECT coalesce(jsonb_object_agg(key, value), '{}'::jsonb) FROM jsonb_each(_data) WHERE coalesce(_data->>key,'') <> ''; $$; BDROP FUNCTION public._cm3_utils_strip_null_or_empty(_data jsonb); publicpostgresfalse1255233000._cm3_utils_varchar_to_bytea(character varying)FUNCTIONCREATE FUNCTION public._cm3_utils_varchar_to_bytea(_value character varying) RETURNS bytea LANGUAGE sql IMMUTABLE AS $$ SELECT convert_to(_value, 'UTF8'); $$; LDROP FUNCTION public._cm3_utils_varchar_to_bytea(_value character varying); publicpostgresfalse12552330016_cm_add_class_cascade_delete_on_relations_trigger(oid)FUNCTIONMCREATE FUNCTION public._cm_add_class_cascade_delete_on_relations_trigger(tableid oid) RETURNS void LANGUAGE plpgsql AS $$ BEGIN EXECUTE ' CREATE TRIGGER "_CascadeDeleteOnRelations" AFTER UPDATE ON '|| TableId::regclass ||' FOR EACH ROW EXECUTE PROCEDURE _cm_trigger_cascade_delete_on_relations(); '; END; $$; UDROP FUNCTION public._cm_add_class_cascade_delete_on_relations_trigger(tableid oid); publicpostgresfalse1255233002"_cm_add_class_history_trigger(oid)FUNCTION6CREATE FUNCTION public._cm_add_class_history_trigger(tableid oid) RETURNS void LANGUAGE plpgsql AS $$ BEGIN EXECUTE ' CREATE TRIGGER "_CreateHistoryRow" AFTER DELETE OR UPDATE ON '|| TableId::regclass ||' FOR EACH ROW EXECUTE PROCEDURE _cm_trigger_create_card_history_row() '; END; $$; ADROP FUNCTION public._cm_add_class_history_trigger(tableid oid); publicpostgresfalse1255233003'_cm_add_class_sanity_check_trigger(oid)FUNCTION7CREATE FUNCTION public._cm_add_class_sanity_check_trigger(tableid oid) RETURNS void LANGUAGE plpgsql AS $$ BEGIN EXECUTE ' CREATE TRIGGER "_SanityCheck" BEFORE INSERT OR UPDATE OR DELETE ON '|| TableId::regclass ||' FOR EACH ROW EXECUTE PROCEDURE _cm_trigger_sanity_check(); '; END; $$; FDROP FUNCTION public._cm_add_class_sanity_check_trigger(tableid oid); publicpostgresfalse1255233004#_cm_add_domain_history_trigger(oid)FUNCTION=CREATE FUNCTION public._cm_add_domain_history_trigger(domainid oid) RETURNS void LANGUAGE plpgsql AS $$ BEGIN EXECUTE ' CREATE TRIGGER "_CreateHistoryRow" AFTER DELETE OR UPDATE ON '|| DomainId::regclass ||' FOR EACH ROW EXECUTE PROCEDURE _cm_trigger_create_relation_history_row() '; END; $$; CDROP FUNCTION public._cm_add_domain_history_trigger(domainid oid); publicpostgresfalse1255233005(_cm_add_domain_sanity_check_trigger(oid)FUNCTION9CREATE FUNCTION public._cm_add_domain_sanity_check_trigger(domainid oid) RETURNS void LANGUAGE plpgsql AS $$ BEGIN EXECUTE ' CREATE TRIGGER "_SanityCheck" BEFORE INSERT OR UPDATE OR DELETE ON '|| DomainId::regclass ||' FOR EACH ROW EXECUTE PROCEDURE _cm_trigger_sanity_check(); '; END $$; HDROP FUNCTION public._cm_add_domain_sanity_check_trigger(domainid oid); publicpostgresfalse1255233006!_cm_add_fk_constraints(oid, text)FUNCTION[CREATE FUNCTION public._cm_add_fk_constraints(fksourceid oid, attributename text) RETURNS void LANGUAGE plpgsql AS $$ DECLARE FKTargetId oid := _cm_get_fk_target_table_id(FKSourceId, AttributeName); SubTableId oid; BEGIN IF FKTargetId IS NULL THEN RETURN; END IF; FOR SubTableId IN SELECT _cm_subtables_and_itself(FKSourceId) LOOP PERFORM _cm_add_fk_trigger(SubTableId, FKSourceId, AttributeName, FKTargetId); END LOOP; FOR SubTableId IN SELECT _cm_subtables_and_itself(FKTargetId) LOOP PERFORM _cm_add_restrict_trigger(SubTableId, FKSourceId, AttributeName); END LOOP; END; $$; QDROP FUNCTION public._cm_add_fk_constraints(fksourceid oid, attributename text); publicpostgresfalse1255233007'_cm_add_fk_trigger(oid, oid, text, oid)FUNCTIONCREATE FUNCTION public._cm_add_fk_trigger(tableid oid, fksourceid oid, fkattribute text, fktargetid oid) RETURNS void LANGUAGE plpgsql AS $$ DECLARE TriggerVariant text; BEGIN IF _cm_is_simpleclass(FKSourceId) THEN TriggerVariant := 'simple'; ELSE TriggerVariant := ''; END IF; EXECUTE ' CREATE TRIGGER ' || quote_ident(_cm_classfk_name(FKSourceId, FKAttribute)) || ' BEFORE INSERT OR UPDATE ON ' || TableId::regclass || ' FOR EACH ROW EXECUTE PROCEDURE _cm_trigger_fk('|| quote_literal(FKAttribute) || ',' || quote_literal(FKTargetId::regclass) || ',' || quote_literal(TriggerVariant) || '); '; END; $$; hDROP FUNCTION public._cm_add_fk_trigger(tableid oid, fksourceid oid, fkattribute text, fktargetid oid); publicpostgresfalse1255233008%_cm_add_reference_handling(oid, text)FUNCTIONCREATE FUNCTION public._cm_add_reference_handling(tableid oid, attributename text) RETURNS void LANGUAGE plpgsql AS $$ DECLARE objid integer; referencedid integer; ctrlint integer; AttributeComment text := _cm_comment_for_attribute(TableId, AttributeName); ReferenceTargetId oid := _cm_read_reference_target_id_comment(AttributeComment); AttributeReferenceType text := _cm_read_reference_type_comment(AttributeComment); ReferenceDomainId oid := _cm_read_reference_domain_id_comment(AttributeComment); RefSourceIdAttribute text := _cm_get_ref_source_id_domain_attribute(TableId, AttributeName); RefSourceClassIdAttribute text := _cm_get_ref_source_class_domain_attribute(TableId, AttributeName); RefTargetIdAttribute text := _cm_get_ref_target_id_domain_attribute(TableId, AttributeName); ChildId oid; BEGIN IF ReferenceTargetId IS NULL OR AttributeReferenceType IS NULL OR ReferenceDomainId IS NULL THEN RETURN; END IF; -- Updates the reference for every relation -- TODO: UNDERSTAND WHAT IT DOES AND MAKE IT READABLE! FOR objid IN EXECUTE 'SELECT "Id" from '||TableId::regclass||' WHERE "Status"=''A''' LOOP FOR referencedid IN EXECUTE ' SELECT '|| quote_ident(RefTargetIdAttribute) || ' FROM '|| ReferenceDomainId::regclass || ' WHERE '|| quote_ident(RefSourceClassIdAttribute) ||'='|| TableId || ' AND '|| quote_ident(RefSourceIdAttribute) ||'='|| objid || ' AND "Status"=''A''' LOOP EXECUTE 'SELECT count(*) FROM '||ReferenceTargetId::regclass||' where "Id"='||referencedid INTO ctrlint; IF(ctrlint<>0) THEN EXECUTE 'UPDATE '|| TableId::regclass || ' SET '|| quote_ident(AttributeName) ||'='|| referencedid || ' WHERE "Id"='|| objid; END IF; END LOOP; END LOOP; -- Trigger on reference class (reference -> relation) FOR ChildId IN SELECT _cm_subtables_and_itself(TableId) LOOP PERFORM _cm_add_update_relation_trigger(ChildId, TableId, AttributeName); END LOOP; -- Trigger on domain (relation -> reference) PERFORM _cm_add_update_reference_trigger(TableId, AttributeName); END; $$; RDROP FUNCTION public._cm_add_reference_handling(tableid oid, attributename text); publicpostgresfalse1255233009(_cm_add_restrict_trigger(oid, oid, text)FUNCTIONCREATE FUNCTION public._cm_add_restrict_trigger(fktargetclassid oid, fkclassid oid, fkattribute text) RETURNS void LANGUAGE plpgsql AS $$ BEGIN IF FKClassId IS NULL THEN RETURN; END IF; EXECUTE ' CREATE TRIGGER ' || quote_ident('_Constr_'||_cm_cmtable(FKClassId)||'_'||FKAttribute) || ' BEFORE UPDATE OR DELETE ON ' || FKTargetClassId::regclass || ' FOR EACH ROW EXECUTE PROCEDURE _cm_trigger_restrict(' || quote_literal(FKClassId::regclass) || ',' || quote_literal(FKAttribute) || '); '; END; $$; eDROP FUNCTION public._cm_add_restrict_trigger(fktargetclassid oid, fkclassid oid, fkattribute text); publicpostgresfalse1255233010-_cm_add_simpleclass_sanity_check_trigger(oid)FUNCTIONDCREATE FUNCTION public._cm_add_simpleclass_sanity_check_trigger(tableid oid) RETURNS void LANGUAGE plpgsql AS $$ BEGIN EXECUTE ' CREATE TRIGGER "_SanityCheck" BEFORE INSERT OR UPDATE OR DELETE ON '|| TableId::regclass ||' FOR EACH ROW EXECUTE PROCEDURE _cm_trigger_sanity_check_simple(); '; END; $$; LDROP FUNCTION public._cm_add_simpleclass_sanity_check_trigger(tableid oid); publicpostgresfalse1255233011_cm_add_spherical_mercator()FUNCTIONCREATE FUNCTION public._cm_add_spherical_mercator() RETURNS void LANGUAGE plpgsql AS $$ DECLARE FoundSrid integer; BEGIN SELECT "srid" INTO FoundSrid FROM "spatial_ref_sys" WHERE "srid" = 900913 LIMIT 1; IF NOT FOUND THEN INSERT INTO "spatial_ref_sys" ("srid","auth_name","auth_srid","srtext","proj4text") VALUES (900913,'spatialreferencing.org',900913,'','+proj=merc +a=6378137 +b=6378137 +lat_ts=0.0 +lon_0=0.0 +x_0=0.0 +y_0=0 +units=m +k=1.0 +nadgrids=@null +no_defs'); END IF; END; $$; 3DROP FUNCTION public._cm_add_spherical_mercator(); publicpostgresfalse1255233012+_cm_add_update_reference_trigger(oid, text)FUNCTIONCREATE FUNCTION public._cm_add_update_reference_trigger(tableid oid, refattribute text) RETURNS void LANGUAGE plpgsql AS $$ DECLARE DomainId oid := _cm_get_reference_domain_id(TableId, RefAttribute); DomainSourceIdAttribute text := _cm_get_ref_source_id_domain_attribute(TableId, RefAttribute); DomainTargetIdAttribute text := _cm_get_ref_target_id_domain_attribute(TableId, RefAttribute); BEGIN IF DomainId IS NULL OR DomainSourceIdAttribute IS NULL OR DomainTargetIdAttribute IS NULL THEN RETURN; END IF; EXECUTE ' CREATE TRIGGER ' || quote_ident(_cm_update_reference_trigger_name(TableId, RefAttribute)) || ' AFTER INSERT OR UPDATE ON ' || DomainId::regclass || ' FOR EACH ROW EXECUTE PROCEDURE _cm_trigger_update_reference(' || quote_literal(RefAttribute) || ',' || quote_literal(TableId::regclass) || ',' || quote_literal(DomainSourceIdAttribute) || ',' || quote_literal(DomainTargetIdAttribute) || '); '; END; $$; WDROP FUNCTION public._cm_add_update_reference_trigger(tableid oid, refattribute text); publicpostgresfalse1255233013/_cm_add_update_relation_trigger(oid, oid, text)FUNCTIONCREATE FUNCTION public._cm_add_update_relation_trigger(tableid oid, reftableid oid, refattribute text) RETURNS void LANGUAGE plpgsql AS $$ DECLARE DomainId oid := _cm_get_reference_domain_id(RefTableId, RefAttribute); DomainSourceIdAttribute text := _cm_get_ref_source_id_domain_attribute(RefTableId, RefAttribute); DomainTargetIdAttribute text := _cm_get_ref_target_id_domain_attribute(RefTableId, RefAttribute); BEGIN IF DomainId IS NULL OR DomainSourceIdAttribute IS NULL OR DomainTargetIdAttribute IS NULL THEN RETURN; END IF; EXECUTE ' CREATE TRIGGER ' || quote_ident(_cm_update_relation_trigger_name(RefTableId, RefAttribute)) || ' AFTER INSERT OR UPDATE ON ' || TableId::regclass || ' FOR EACH ROW EXECUTE PROCEDURE _cm_trigger_update_relation(' || quote_literal(RefAttribute) || ',' || quote_literal(DomainId::regclass) || ',' || quote_literal(DomainSourceIdAttribute) || ',' || quote_literal(DomainTargetIdAttribute) || '); '; END; $$; fDROP FUNCTION public._cm_add_update_relation_trigger(tableid oid, reftableid oid, refattribute text); publicpostgresfalse1255233014-_cm_attribute_default_to_src(oid, text, text)FUNCTIONCREATE FUNCTION public._cm_attribute_default_to_src(tableid oid, attributename text, newdefault text) RETURNS text LANGUAGE plpgsql AS $$ DECLARE SQLType text := _cm_get_attribute_sqltype(TableId, AttributeName); BEGIN IF (NewDefault IS NULL OR TRIM(NewDefault) = '') THEN RETURN NULL; END IF; IF SQLType ILIKE 'varchar%' OR SQLType = 'text' OR ((SQLType = 'date' OR SQLType = 'timestamp') AND TRIM(NewDefault) <> 'now()') THEN RETURN quote_literal(NewDefault); ELSE RETURN NewDefault; END IF; END; $$; eDROP FUNCTION public._cm_attribute_default_to_src(tableid oid, attributename text, newdefault text); publicpostgresfalse1255233015!_cm_attribute_is_empty(oid, text)FUNCTION{CREATE FUNCTION public._cm_attribute_is_empty(tableid oid, attributename text) RETURNS boolean LANGUAGE plpgsql AS $$ DECLARE Out boolean; BEGIN EXECUTE 'SELECT (COUNT(*) = 0) FROM '|| TableId::regclass || ' WHERE '|| quote_ident(AttributeName) ||' IS NOT NULL' || ' AND '|| quote_ident(AttributeName) ||'::text <> '''' LIMIT 1' INTO Out; RETURN Out; END; $$; NDROP FUNCTION public._cm_attribute_is_empty(tableid oid, attributename text); publicpostgresfalse1255233016%_cm_attribute_is_inherited(oid, text)FUNCTIONCREATE FUNCTION public._cm_attribute_is_inherited(tableid oid, attributename text) RETURNS boolean LANGUAGE sql AS $_$ SELECT pg_attribute.attinhcount <> 0 FROM pg_attribute WHERE pg_attribute.attrelid = $1 AND pg_attribute.attname = $2; $_$; RDROP FUNCTION public._cm_attribute_is_inherited(tableid oid, attributename text); publicpostgresfalse1255233017!_cm_attribute_is_local(oid, text)FUNCTIONCREATE FUNCTION public._cm_attribute_is_local(tableid oid, attributename text) RETURNS boolean LANGUAGE sql STABLE AS $_$ SELECT (attinhcount = 0) FROM pg_attribute WHERE attrelid = $1 AND attname = $2 LIMIT 1; $_$; NDROP FUNCTION public._cm_attribute_is_local(tableid oid, attributename text); publicpostgresfalse1255233018#_cm_attribute_is_notnull(oid, text)FUNCTIONCREATE FUNCTION public._cm_attribute_is_notnull(tableid oid, attributename text) RETURNS boolean LANGUAGE sql AS $_$ SELECT pg_attribute.attnotnull OR c.oid IS NOT NULL FROM pg_attribute LEFT JOIN pg_constraint AS c ON c.conrelid = pg_attribute.attrelid AND c.conname::text = _cm_notnull_constraint_name(pg_attribute.attname::text) WHERE pg_attribute.attrelid = $1 AND pg_attribute.attname = $2; $_$; PDROP FUNCTION public._cm_attribute_is_notnull(tableid oid, attributename text); publicpostgresfalse1255233019"_cm_attribute_is_unique(oid, text)FUNCTIONCREATE FUNCTION public._cm_attribute_is_unique(tableid oid, attributename text) RETURNS boolean LANGUAGE plpgsql STABLE AS $$ DECLARE IsUnique boolean; BEGIN SELECT INTO IsUnique (count(*) > 0) FROM pg_class JOIN pg_index ON pg_class.oid = pg_index.indexrelid WHERE pg_index.indrelid = TableId AND relname = _cm_unique_index_name(TableId, AttributeName); RETURN IsUnique; END; $$; ODROP FUNCTION public._cm_attribute_is_unique(tableid oid, attributename text); publicpostgresfalse1255233020_cm_attribute_list(oid)FUNCTIONCREATE FUNCTION public._cm_attribute_list(tableid oid) RETURNS SETOF text LANGUAGE sql STABLE AS $_$ SELECT attname::text FROM pg_attribute WHERE attrelid = $1 AND attnum > 0 AND atttypid > 0 ORDER BY attnum; $_$; 6DROP FUNCTION public._cm_attribute_list(tableid oid); publicpostgresfalse1255233021_cm_attribute_list_cs(oid)FUNCTIONCREATE FUNCTION public._cm_attribute_list_cs(classid oid) RETURNS text LANGUAGE sql STABLE AS $_$ SELECT array_to_string(array( SELECT quote_ident(name) FROM _cm_attribute_list($1) AS name ),','); $_$; 9DROP FUNCTION public._cm_attribute_list_cs(classid oid); publicpostgresfalse1255233022)_cm_attribute_notnull_is_check(oid, text)FUNCTIONCREATE FUNCTION public._cm_attribute_notnull_is_check(tableid oid, attributename text) RETURNS boolean LANGUAGE plpgsql AS $$ DECLARE AttributeComment text := _cm_comment_for_attribute(TableId, AttributeName); BEGIN RETURN NOT ( _cm_is_simpleclass(TableId) OR _cm_is_system(TableId) OR _cm_check_comment(_cm_comment_for_attribute(TableId, AttributeName), 'MODE', 'reserved') ); END $$; VDROP FUNCTION public._cm_attribute_notnull_is_check(tableid oid, attributename text); publicpostgresfalse1255233023&_cm_attribute_root_table_id(oid, text)FUNCTIONqCREATE FUNCTION public._cm_attribute_root_table_id(tableid oid, attributename text) RETURNS oid LANGUAGE plpgsql AS $$ DECLARE CurrentTableId oid := TableId; BEGIN LOOP EXIT WHEN CurrentTableId IS NULL OR _cm_attribute_is_local(CurrentTableId, AttributeName); CurrentTableId := _cm_parent_id(CurrentTableId); END LOOP; RETURN CurrentTableId; END $$; SDROP FUNCTION public._cm_attribute_root_table_id(tableid oid, attributename text); publicpostgresfalse1255233024-_cm_attribute_set_notnull(oid, text, boolean)FUNCTIONCREATE FUNCTION public._cm_attribute_set_notnull(tableid oid, attributename text, willbenotnull boolean) RETURNS void LANGUAGE plpgsql AS $$ DECLARE AttributeComment text := _cm_comment_for_attribute(TableId, AttributeName); BEGIN IF WillBeNotNull = _cm_attribute_is_notnull(TableId, AttributeName) THEN RETURN; END IF; IF WillBeNotNull AND _cm_is_superclass(TableId) AND _cm_check_comment(AttributeComment, 'MODE', 'write') THEN RAISE NOTICE 'Non-system superclass attributes cannot be not null'; RAISE EXCEPTION 'CM_FORBIDDEN_OPERATION'; END IF; PERFORM _cm_attribute_set_notnull_unsafe(TableId, AttributeName, WillBeNotNull); END; $$; hDROP FUNCTION public._cm_attribute_set_notnull(tableid oid, attributename text, willbenotnull boolean); publicpostgresfalse12552330254_cm_attribute_set_notnull_unsafe(oid, text, boolean)FUNCTIONCREATE FUNCTION public._cm_attribute_set_notnull_unsafe(tableid oid, attributename text, willbenotnull boolean) RETURNS void LANGUAGE plpgsql AS $$ DECLARE IsCheck boolean := _cm_attribute_notnull_is_check(TableId, AttributeName); BEGIN IF (WillBeNotNull) THEN IF (IsCheck) THEN EXECUTE 'ALTER TABLE '|| TableId::regclass || ' ADD CONSTRAINT ' || quote_ident(_cm_notnull_constraint_name(AttributeName)) || ' CHECK ("Status"<>''A'' OR ' || quote_ident(AttributeName) || ' IS NOT NULL)'; ELSE EXECUTE 'ALTER TABLE '|| TableId::regclass ||' ALTER COLUMN '|| quote_ident(AttributeName) ||' SET NOT NULL'; END IF; ELSE IF (IsCheck) THEN EXECUTE 'ALTER TABLE '|| TableId::regclass ||' DROP CONSTRAINT '|| quote_ident(_cm_notnull_constraint_name(AttributeName)); ELSE EXECUTE 'ALTER TABLE '|| TableId::regclass ||' ALTER COLUMN '|| quote_ident(AttributeName) ||' DROP NOT NULL'; END IF; END IF; END; $$; oDROP FUNCTION public._cm_attribute_set_notnull_unsafe(tableid oid, attributename text, willbenotnull boolean); publicpostgresfalse12552330260_cm_attribute_set_uniqueness(oid, text, boolean)FUNCTION^CREATE FUNCTION public._cm_attribute_set_uniqueness(tableid oid, attributename text, attributeunique boolean) RETURNS void LANGUAGE plpgsql AS $$ BEGIN IF _cm_attribute_is_unique(TableId, AttributeName) <> AttributeUnique THEN IF AttributeUnique AND (_cm_is_simpleclass(TableId) OR _cm_is_superclass(TableId)) AND NOT _cm_is_system(TableId) THEN RAISE NOTICE 'User defined superclass or simple class attributes cannot be unique'; RAISE EXCEPTION 'CM_FORBIDDEN_OPERATION'; END IF; PERFORM _cm_attribute_set_uniqueness_unsafe(TableId, AttributeName, AttributeUnique); END IF; END; $$; mDROP FUNCTION public._cm_attribute_set_uniqueness(tableid oid, attributename text, attributeunique boolean); publicpostgresfalse12552330277_cm_attribute_set_uniqueness_unsafe(oid, text, boolean)FUNCTIONbCREATE FUNCTION public._cm_attribute_set_uniqueness_unsafe(tableid oid, attributename text, attributeunique boolean) RETURNS void LANGUAGE plpgsql AS $$ BEGIN IF _cm_is_simpleclass(TableId) THEN IF AttributeUnique THEN EXECUTE 'ALTER TABLE '|| TableId::regclass ||' ADD UNIQUE ('|| quote_ident(AttributeName) || ')'; ELSE EXECUTE 'ALTER TABLE '|| TableId::regclass ||' DROP UNIQUE ('|| quote_ident(AttributeName) || ')'; END IF; ELSE IF AttributeUnique THEN EXECUTE 'CREATE UNIQUE INDEX '|| quote_ident(_cm_unique_index_name(TableId, AttributeName)) || ' ON '|| TableId::regclass ||' USING btree (('|| ' CASE WHEN "Status"::text = ''N''::text THEN NULL'|| ' ELSE '|| quote_ident(AttributeName) || ' END))'; ELSE EXECUTE 'DROP INDEX '|| _cm_unique_index_id(TableId, AttributeName)::regclass; END IF; END IF; END $$; tDROP FUNCTION public._cm_attribute_set_uniqueness_unsafe(tableid oid, attributename text, attributeunique boolean); publicpostgresfalse1255233028_cm_cascade(integer, oid, text)FUNCTIONCREATE FUNCTION public._cm_cascade(id integer, tableid oid, attributename text) RETURNS void LANGUAGE plpgsql AS $$ BEGIN EXECUTE 'DELETE FROM '|| TableId::regclass || ' WHERE '||quote_ident(AttributeName)||' = '||Id::text; END; $$; ODROP FUNCTION public._cm_cascade(id integer, tableid oid, attributename text); publicpostgresfalse12552330290_cm_check_attribute_comment_and_type(text, text)FUNCTIONtCREATE FUNCTION public._cm_check_attribute_comment_and_type(attributecomment text, sqltype text) RETURNS void LANGUAGE plpgsql AS $$ DECLARE SpecialTypeCount integer := 0; BEGIN IF _cm_read_reference_domain_comment(AttributeComment) IS NOT NULL THEN SpecialTypeCount := SpecialTypeCount +1; END IF; IF _cm_get_fk_target_comment(AttributeComment) IS NOT NULL THEN SpecialTypeCount := SpecialTypeCount +1; END IF; IF _cm_get_lookup_type_comment(AttributeComment) IS NOT NULL THEN SpecialTypeCount := SpecialTypeCount +1; END IF; IF (SpecialTypeCount > 1) THEN RAISE NOTICE 'Too many CMDBuild types specified'; RAISE EXCEPTION 'CM_FORBIDDEN_OPERATION'; END IF; IF SpecialTypeCount = 1 AND SQLType NOT IN ('int4','integer') THEN RAISE NOTICE 'The SQL type does not match the CMDBuild type'; RAISE EXCEPTION 'CM_FORBIDDEN_OPERATION'; END IF; END; $$; `DROP FUNCTION public._cm_check_attribute_comment_and_type(attributecomment text, sqltype text); publicpostgresfalse1255233030#_cm_check_comment(text, text, text)FUNCTIONCREATE FUNCTION public._cm_check_comment(classcomment text, key text, value text) RETURNS boolean LANGUAGE sql STABLE AS $_$ SELECT (_cm_read_comment($1, $2) ILIKE $3); $_$; QDROP FUNCTION public._cm_check_comment(classcomment text, key text, value text); publicpostgresfalse^1255233031*_cm_check_id_exists(integer, oid, boolean)FUNCTIONCREATE FUNCTION public._cm_check_id_exists(id integer, tableid oid, deletedalso boolean) RETURNS boolean LANGUAGE sql STABLE AS $_$ SELECT _cm_check_value_exists($1, $2, 'Id', $3); $_$; XDROP FUNCTION public._cm_check_id_exists(id integer, tableid oid, deletedalso boolean); publicpostgresfalse12552330323_cm_check_value_exists(integer, oid, text, boolean)FUNCTION"CREATE FUNCTION public._cm_check_value_exists(id integer, tableid oid, attributename text, deletedalso boolean) RETURNS boolean LANGUAGE plpgsql STABLE AS $$ DECLARE Out BOOLEAN := TRUE; StatusPart TEXT; BEGIN IF _cm_is_simpleclass(TableId) OR DeletedAlso THEN StatusPart := ''; ELSE StatusPart := ' AND "Status"=''A'''; END IF; IF Id IS NOT NULL THEN EXECUTE 'SELECT (COUNT(*) > 0) FROM '|| TableId::regclass ||' WHERE '|| quote_ident(AttributeName)||'='||Id||StatusPart||' LIMIT 1' INTO Out; END IF; RETURN Out; END $$; oDROP FUNCTION public._cm_check_value_exists(id integer, tableid oid, attributename text, deletedalso boolean); publicpostgresfalse1255233033_cm_class_has_children(oid)FUNCTIONfCREATE FUNCTION public._cm_class_has_children(tableid oid) RETURNS boolean LANGUAGE sql STABLE AS $_$ -- Without separate history table -- SELECT (COUNT(*) > 0) FROM pg_inherits WHERE inhparent = $1 LIMIT 1; -- With history table design mistake SELECT (COUNT(*) > 0) FROM pg_inherits WHERE inhparent = $1 AND _cm_is_cmobject(inhrelid) LIMIT 1; $_$; :DROP FUNCTION public._cm_class_has_children(tableid oid); publicpostgresfalse1255233034_cm_class_has_domains(oid)FUNCTIONACREATE FUNCTION public._cm_class_has_domains(tableid oid) RETURNS boolean LANGUAGE sql AS $_$ SELECT (COUNT(*) > 0) FROM _cm_domain_list() AS d WHERE _cm_table_id(_cm_read_comment(_cm_comment_for_cmobject(d), 'CLASS1')) = $1 OR _cm_table_id(_cm_read_comment(_cm_comment_for_cmobject(d), 'CLASS2')) = $1; $_$; 9DROP FUNCTION public._cm_class_has_domains(tableid oid); publicpostgresfalse1255233035_cm_class_list()FUNCTIONCREATE FUNCTION public._cm_class_list() RETURNS SETOF oid LANGUAGE sql STABLE AS $$ SELECT oid FROM pg_class WHERE _cm_is_any_class_comment(_cm_comment_for_cmobject(oid)); $$; 'DROP FUNCTION public._cm_class_list(); publicpostgresfalse1255233036_cm_classfk_name(oid, text)FUNCTIONCREATE FUNCTION public._cm_classfk_name(tableid oid, attributename text) RETURNS text LANGUAGE sql IMMUTABLE AS $_$ SELECT _cm_cmtable($1) || '_' || $2 || '_fkey'; $_$; HDROP FUNCTION public._cm_classfk_name(tableid oid, attributename text); publicpostgresfalse1255233037_cm_classfk_name(text, text)FUNCTIONCREATE FUNCTION public._cm_classfk_name(cmclassname text, attributename text) RETURNS text LANGUAGE sql IMMUTABLE AS $_$ SELECT _cm_cmtable($1) || '_' || $2 || '_fkey'; $_$; MDROP FUNCTION public._cm_classfk_name(cmclassname text, attributename text); publicpostgresfalse1255233038_cm_classidx_name(oid, text)FUNCTIONCREATE FUNCTION public._cm_classidx_name(tableid oid, attributename text) RETURNS text LANGUAGE sql IMMUTABLE AS $_$ SELECT 'idx_' || REPLACE(_cm_cmtable_lc($1), '_', '') || '_' || lower($2); $_$; IDROP FUNCTION public._cm_classidx_name(tableid oid, attributename text); publicpostgresfalse1255233039_cm_classpk_name(text)FUNCTIONCREATE FUNCTION public._cm_classpk_name(cmclassname text) RETURNS text LANGUAGE sql IMMUTABLE AS $_$ SELECT _cm_cmtable($1) || '_pkey'; $_$; 9DROP FUNCTION public._cm_classpk_name(cmclassname text); publicpostgresfalse1255233040_cm_cmschema(oid)FUNCTIONCREATE FUNCTION public._cm_cmschema(tableid oid) RETURNS text LANGUAGE sql STABLE AS $_$ SELECT pg_namespace.nspname::text FROM pg_class JOIN pg_namespace ON pg_class.relnamespace = pg_namespace.oid WHERE pg_class.oid=$1 $_$; 0DROP FUNCTION public._cm_cmschema(tableid oid); publicpostgresfalse1255233041_cm_cmschema(text)FUNCTIONCREATE FUNCTION public._cm_cmschema(cmname text) RETURNS text LANGUAGE sql IMMUTABLE AS $_$ SELECT (_cm_split_cmname($1))[1]; $_$; 0DROP FUNCTION public._cm_cmschema(cmname text); publicpostgresfalse1255233042_cm_cmtable(oid)FUNCTIONCREATE FUNCTION public._cm_cmtable(tableid oid) RETURNS text LANGUAGE sql STABLE AS $_$ SELECT pg_class.relname::text FROM pg_class WHERE pg_class.oid=$1 $_$; /DROP FUNCTION public._cm_cmtable(tableid oid); publicpostgresfalse1255233043_cm_cmtable(text)FUNCTIONCREATE FUNCTION public._cm_cmtable(cmname text) RETURNS text LANGUAGE sql IMMUTABLE AS $_$ SELECT (_cm_split_cmname($1))[2]; $_$; /DROP FUNCTION public._cm_cmtable(cmname text); publicpostgresfalse1255233044_cm_cmtable_lc(oid)FUNCTIONCREATE FUNCTION public._cm_cmtable_lc(tableid oid) RETURNS text LANGUAGE sql IMMUTABLE AS $_$ SELECT lower(_cm_cmtable($1)); $_$; 2DROP FUNCTION public._cm_cmtable_lc(tableid oid); publicpostgresfalse1255233045_cm_cmtable_lc(text)FUNCTIONCREATE FUNCTION public._cm_cmtable_lc(cmname text) RETURNS text LANGUAGE sql IMMUTABLE AS $_$ SELECT lower(_cm_cmtable($1)); $_$; 2DROP FUNCTION public._cm_cmtable_lc(cmname text); publicpostgresfalse1255233046,_cm_comment_add_parts(text, text[], boolean)FUNCTIONyCREATE FUNCTION public._cm_comment_add_parts(comment text, parts text[], missingonly boolean) RETURNS text LANGUAGE plpgsql AS $$ DECLARE part text; key text; value text; BEGIN RAISE INFO 'adding comment parts % inside "%" (missing only is %)', parts, comment, missingOnly; RAISE DEBUG 'comment (before): "%"', comment; -- we MUST use coalesce since "array_" functions handle empty array in some funny way FOR i IN COALESCE(array_lower(parts, 1),0) .. COALESCE(array_upper(parts, 1),-1) LOOP part = parts[i]; RAISE DEBUG 'comment part: "%"', part; key = split_part(part, ': ', 1); value = split_part(part, ': ', 2); IF NOT (missingOnly AND substring(comment, key || ': [^|]+') IS NOT NULL) THEN comment = _cm_concat('|', ARRAY[comment, key || ': ' || value]); ELSE END IF; END LOOP; RAISE DEBUG 'comment (after): "%"', comment; RETURN comment; END $$; ]DROP FUNCTION public._cm_comment_add_parts(comment text, parts text[], missingonly boolean); publicpostgresfalse1255233047$_cm_comment_for_attribute(oid, text)FUNCTIONQCREATE FUNCTION public._cm_comment_for_attribute(tableid oid, attributename text) RETURNS text LANGUAGE sql STABLE AS $_$ SELECT description FROM pg_description JOIN pg_attribute ON pg_description.objoid = pg_attribute.attrelid AND pg_description.objsubid = pg_attribute.attnum WHERE attrelid = $1 and attname = $2 LIMIT 1; $_$; QDROP FUNCTION public._cm_comment_for_attribute(tableid oid, attributename text); publicpostgresfalse1255233048_cm_comment_for_class(text)FUNCTIONCREATE FUNCTION public._cm_comment_for_class(cmclass text) RETURNS text LANGUAGE sql STABLE AS $_$ SELECT _cm_comment_for_table_id(_cm_table_id($1)); $_$; :DROP FUNCTION public._cm_comment_for_class(cmclass text); publicpostgresfalse1255233049_cm_comment_for_cmobject(oid)FUNCTIONCREATE FUNCTION public._cm_comment_for_cmobject(tableid oid) RETURNS text LANGUAGE sql STABLE AS $_$ SELECT description FROM pg_description WHERE objoid = $1 AND objsubid = 0 AND _cm_read_comment(description, 'TYPE') IS NOT NULL LIMIT 1; $_$; <DROP FUNCTION public._cm_comment_for_cmobject(tableid oid); publicpostgresfalse1255233050_cm_comment_for_domain(text)FUNCTIONCREATE FUNCTION public._cm_comment_for_domain(cmdomain text) RETURNS text LANGUAGE sql STABLE STRICT AS $_$ SELECT _cm_comment_for_table_id(_cm_domain_id($1)); $_$; <DROP FUNCTION public._cm_comment_for_domain(cmdomain text); publicpostgresfalse1255233051_cm_comment_for_table_id(oid)FUNCTIONCREATE FUNCTION public._cm_comment_for_table_id(tableid oid) RETURNS text LANGUAGE sql STABLE AS $_$ SELECT description FROM pg_description WHERE objoid = $1; $_$; <DROP FUNCTION public._cm_comment_for_table_id(tableid oid); publicpostgresfalse1255233052#_cm_comment_set_parts(text, text[])FUNCTIONCREATE FUNCTION public._cm_comment_set_parts(comment text, parts text[]) RETURNS text LANGUAGE plpgsql AS $$ DECLARE part text; key text; value text; BEGIN RAISE INFO 'setting comment parts % inside "%"', parts, comment; RAISE DEBUG 'comment (before): "%"', comment; -- we MUST use coalesce since "array_" functions handle empty array in some funny way FOR i IN COALESCE(array_lower(parts, 1),0) .. COALESCE(array_upper(parts, 1),-1) LOOP part = parts[i]; RAISE DEBUG 'comment part: "%"', part; key = split_part(part, ': ', 1); value = split_part(part, ': ', 2); comment = regexp_replace(comment, key || ': [^|]+', key || ': ' || value); END LOOP; RAISE DEBUG 'comment (after): "%"', comment; RETURN comment; END $$; HDROP FUNCTION public._cm_comment_set_parts(comment text, parts text[]); publicpostgresfalse1255233053_cm_concat(text, text[])FUNCTIONCREATE FUNCTION public._cm_concat(separator text, elements text[]) RETURNS text LANGUAGE sql AS $_$ SELECT case WHEN $1 IS NULL OR trim(array_to_string($2, coalesce($1, ''))) = '' THEN null ELSE array_to_string($2, coalesce($1, '')) END $_$; BDROP FUNCTION public._cm_concat(separator text, elements text[]); publicpostgresfalse1255233054_cm_copy_fk_trigger(oid, oid)FUNCTIONCREATE FUNCTION public._cm_copy_fk_trigger(fromid oid, toid oid) RETURNS void LANGUAGE sql AS $_$ SELECT _cm_copy_trigger($1, $2, '%_fkey'); $_$; @DROP FUNCTION public._cm_copy_fk_trigger(fromid oid, toid oid); publicpostgresfalse1255233055#_cm_copy_restrict_trigger(oid, oid)FUNCTIONCREATE FUNCTION public._cm_copy_restrict_trigger(fromid oid, toid oid) RETURNS void LANGUAGE sql AS $_$ SELECT _cm_copy_trigger($1, $2, '_Constr_%'); $_$; FDROP FUNCTION public._cm_copy_restrict_trigger(fromid oid, toid oid); publicpostgresfalse12552330560_cm_copy_superclass_attribute_comments(oid, oid)FUNCTIONCREATE FUNCTION public._cm_copy_superclass_attribute_comments(tableid oid, parenttableid oid) RETURNS void LANGUAGE plpgsql AS $$ DECLARE AttributeName text; BEGIN FOR AttributeName IN SELECT * FROM _cm_attribute_list(ParentTableId) LOOP EXECUTE 'COMMENT ON COLUMN '|| TableId::regclass || '.' || quote_ident(AttributeName) || ' IS '|| quote_literal(_cm_comment_for_attribute(ParentTableId, AttributeName)); END LOOP; END $$; ]DROP FUNCTION public._cm_copy_superclass_attribute_comments(tableid oid, parenttableid oid); publicpostgresfalse1255233057 _cm_copy_trigger(oid, oid, text)FUNCTIONCREATE FUNCTION public._cm_copy_trigger(fromid oid, toid oid, triggernamematcher text) RETURNS void LANGUAGE plpgsql AS $$ DECLARE TriggerData record; BEGIN FOR TriggerData IN SELECT t.tgname AS TriggerName, t.tgtype AS TriggerType, p.proname AS TriggerFunction, array_to_string(array( SELECT quote_literal(q.param) FROM (SELECT regexp_split_to_table(encode(tgargs, 'escape'), E'\\\\000') AS param) AS q WHERE q.param <> '' ),',') AS TriggerParams FROM pg_trigger t, pg_proc p WHERE tgrelid = FromId AND tgname LIKE TriggerNameMatcher AND t.tgfoid = p.oid LOOP EXECUTE ' CREATE TRIGGER '|| quote_ident(TriggerData.TriggerName) ||' '|| _cm_trigger_when(TriggerData.TriggerType) ||' ON '|| ToId::regclass ||' FOR EACH '|| _cm_trigger_row_or_statement(TriggerData.TriggerType) ||' EXECUTE PROCEDURE '|| quote_ident(TriggerData.TriggerFunction) ||'('|| TriggerData.TriggerParams ||') '; END LOOP; END; $$; VDROP FUNCTION public._cm_copy_trigger(fromid oid, toid oid, triggernamematcher text); publicpostgresfalse1255233058*_cm_copy_update_relation_trigger(oid, oid)FUNCTIONCREATE FUNCTION public._cm_copy_update_relation_trigger(fromid oid, toid oid) RETURNS void LANGUAGE sql AS $_$ SELECT _cm_copy_trigger($1, $2, '_UpdRel_%'); $_$; MDROP FUNCTION public._cm_copy_update_relation_trigger(fromid oid, toid oid); publicpostgresfalse1255233059+_cm_create_class_default_order_indexes(oid)FUNCTION]CREATE FUNCTION public._cm_create_class_default_order_indexes(tableid oid) RETURNS void LANGUAGE plpgsql AS $$ DECLARE classindex text; sqlcommand text; BEGIN SELECT INTO classindex coalesce(_cm_string_agg(attname || ' ' || ordermode), '"Description" asc') FROM ( SELECT quote_ident(attname) AS attname, abs(_cm_read_comment(_cm_comment_for_attribute(tableid, attname), 'CLASSORDER')::integer), CASE WHEN (_cm_get_safe_classorder(tableid, attname) > 0) THEN 'asc' ELSE 'desc' END AS ordermode FROM ( SELECT _cm_attribute_list(tableid) AS attname) AS a WHERE _cm_get_safe_classorder(tableid, attname) <> 0 ORDER by 2 ) AS b; RAISE NOTICE '% %', tableid::regclass, classindex; sqlcommand = 'DROP INDEX IF EXISTS idx_' || REPLACE(_cm_cmtable_lc(tableid), '_', '') || '_defaultorder;'; RAISE NOTICE '... %', sqlcommand; EXECUTE sqlcommand; sqlcommand = 'CREATE INDEX idx_' || REPLACE(_cm_cmtable_lc(tableid), '_', '') || '_defaultorder' || ' ON ' || tableid::regclass || ' USING btree (' || classindex || ', "Id" asc);'; RAISE NOTICE '... %', sqlcommand; EXECUTE sqlcommand; END; $$; JDROP FUNCTION public._cm_create_class_default_order_indexes(tableid oid); publicpostgresfalse12552330609_cm_create_class_default_order_indexes(character varying)FUNCTION CREATE FUNCTION public._cm_create_class_default_order_indexes(cmclass character varying, OUT always_true boolean) RETURNS boolean LANGUAGE plpgsql AS $$ BEGIN PERFORM _cm_create_class_default_order_indexes(_cm_table_id(cmclass)); always_true = TRUE; END; $$; qDROP FUNCTION public._cm_create_class_default_order_indexes(cmclass character varying, OUT always_true boolean); publicpostgresfalse00cFUNCTION _cm_create_class_default_order_indexes(cmclass character varying, OUT always_true boolean)COMMENTCOMMENT ON FUNCTION public._cm_create_class_default_order_indexes(cmclass character varying, OUT always_true boolean) IS 'TYPE: function|CATEGORIES: system'; publicpostgresfalse17311255233061_cm_create_class_history(text)FUNCTION>CREATE FUNCTION public._cm_create_class_history(cmclassname text) RETURNS void LANGUAGE plpgsql AS $$ BEGIN EXECUTE ' CREATE TABLE '|| _cm_history_dbname_unsafe(CMClassName) ||' ( "CurrentId" int4 NOT NULL, "EndDate" timestamp NOT NULL DEFAULT now(), CONSTRAINT ' || quote_ident(_cm_historypk_name(CMClassName)) ||' PRIMARY KEY ("Id"), CONSTRAINT '|| quote_ident(_cm_historyfk_name(CMClassName, 'CurrentId')) ||' FOREIGN KEY ("CurrentId") REFERENCES '||_cm_table_dbname(CMClassName)||' ("Id") ON UPDATE RESTRICT ON DELETE SET NULL ) INHERITS ('||_cm_table_dbname(CMClassName)||'); '; PERFORM _cm_create_index(_cm_history_id(CMClassName), 'CurrentId'); EXECUTE 'ALTER TABLE '|| _cm_history_dbname_unsafe(CMClassName) ||' ADD CONSTRAINT "_Check_Status" CHECK ("Status" = ''U''::bpchar);'; END; $$; ADROP FUNCTION public._cm_create_class_history(cmclassname text); publicpostgresfalse1255233062_cm_create_class_indexes(oid)FUNCTIONCREATE FUNCTION public._cm_create_class_indexes(tableid oid) RETURNS void LANGUAGE plpgsql AS $$ BEGIN PERFORM _cm_create_index(TableId, 'Code'); PERFORM _cm_create_index(TableId, 'Description'); PERFORM _cm_create_index(TableId, 'IdClass'); END; $$; <DROP FUNCTION public._cm_create_class_indexes(tableid oid); publicpostgresfalse1255233063_cm_create_class_triggers(oid)FUNCTIONCREATE FUNCTION public._cm_create_class_triggers(tableid oid) RETURNS void LANGUAGE plpgsql AS $$ BEGIN IF _cm_is_superclass(TableId) THEN RAISE DEBUG 'Not creating triggers for class %', TableId::regclass; ELSIF _cm_is_simpleclass(TableId) THEN PERFORM _cm_add_simpleclass_sanity_check_trigger(TableId); ELSE PERFORM _cm_add_class_sanity_check_trigger(TableId); PERFORM _cm_add_class_history_trigger(TableId); PERFORM _cm_add_class_cascade_delete_on_relations_trigger(TableId); END IF; END; $$; =DROP FUNCTION public._cm_create_class_triggers(tableid oid); publicpostgresfalse1255233064_cm_create_domain_indexes(oid)FUNCTIONCREATE FUNCTION public._cm_create_domain_indexes(domainid oid) RETURNS void LANGUAGE plpgsql AS $$ DECLARE Cardinality text := _cm_domain_cardinality(DomainId); BEGIN PERFORM _cm_create_index(DomainId, 'IdDomain'); PERFORM _cm_create_index(DomainId, 'IdObj1'); PERFORM _cm_create_index(DomainId, 'IdObj2'); EXECUTE 'CREATE UNIQUE INDEX ' || quote_ident(_cm_domainidx_name(DomainId, 'ActiveRows')) || ' ON ' || DomainId::regclass || ' USING btree ('|| '(CASE WHEN "Status" = ''N'' THEN NULL ELSE "IdDomain" END),'|| '(CASE WHEN "Status" = ''N'' THEN NULL ELSE "IdClass1" END),'|| '(CASE WHEN "Status" = ''N'' THEN NULL ELSE "IdObj1" END),'|| '(CASE WHEN "Status" = ''N'' THEN NULL ELSE "IdClass2" END),'|| '(CASE WHEN "Status" = ''N'' THEN NULL ELSE "IdObj2" END)'|| ')'; IF substring(Cardinality, 3, 1) = '1' THEN EXECUTE 'CREATE UNIQUE INDEX ' || quote_ident(_cm_domainidx_name(DomainId,'UniqueLeft')) || ' ON ' || DomainId::regclass || ' USING btree ( '|| '(CASE WHEN "Status"::text = ''A'' THEN "IdClass1" ELSE NULL END),'|| '(CASE WHEN "Status"::text = ''A'' THEN "IdObj1" ELSE NULL END)'|| ' )'; END IF; IF substring(Cardinality, 1, 1) = '1' THEN EXECUTE 'CREATE UNIQUE INDEX ' || quote_ident(_cm_domainidx_name(DomainId,'UniqueRight')) || ' ON ' || DomainId::regclass || ' USING btree ( '|| '(CASE WHEN "Status"::text = ''A'' THEN "IdClass2" ELSE NULL END),'|| '(CASE WHEN "Status"::text = ''A'' THEN "IdObj2" ELSE NULL END)'|| ' )'; END IF; END $$; >DROP FUNCTION public._cm_create_domain_indexes(domainid oid); publicpostgresfalse1255233065_cm_create_domain_triggers(oid)FUNCTIONCREATE FUNCTION public._cm_create_domain_triggers(domainid oid) RETURNS void LANGUAGE plpgsql AS $$ BEGIN PERFORM _cm_add_domain_sanity_check_trigger(DomainId); PERFORM _cm_add_domain_history_trigger(DomainId); END; $$; ?DROP FUNCTION public._cm_create_domain_triggers(domainid oid); publicpostgresfalse1255233066_cm_create_index(oid, text)FUNCTIONCREATE FUNCTION public._cm_create_index(tableid oid, attributename text) RETURNS void LANGUAGE plpgsql AS $$ BEGIN EXECUTE 'CREATE INDEX ' || quote_ident(_cm_classidx_name(TableId, AttributeName)) || ' ON ' || TableId::regclass || ' USING btree (' || quote_ident(AttributeName) || ')'; EXCEPTION WHEN undefined_column THEN RAISE LOG 'Index for attribute %.% not created because the attribute does not exist', TableId::regclass, quote_ident(AttributeName); END $$; HDROP FUNCTION public._cm_create_index(tableid oid, attributename text); publicpostgresfalse1255233067!_cm_create_schema_if_needed(text)FUNCTIONCREATE FUNCTION public._cm_create_schema_if_needed(cmname text) RETURNS void LANGUAGE plpgsql AS $$ BEGIN IF _cm_cmschema(CMName) IS NOT NULL THEN EXECUTE 'CREATE SCHEMA '||quote_ident(_cm_cmschema(CMName)); END IF; EXCEPTION WHEN duplicate_schema THEN RETURN; END; $$; ?DROP FUNCTION public._cm_create_schema_if_needed(cmname text); publicpostgresfalse1255233068 _cm_delete_local_attributes(oid)FUNCTIONcCREATE FUNCTION public._cm_delete_local_attributes(tableid oid) RETURNS void LANGUAGE plpgsql AS $$ DECLARE AttributeName text; BEGIN FOR AttributeName IN SELECT _cm_attribute_list(TableId) LOOP IF NOT _cm_attribute_is_inherited(TableId, AttributeName) THEN PERFORM cm_delete_attribute(TableId, AttributeName); END IF; END LOOP; END $$; ?DROP FUNCTION public._cm_delete_local_attributes(tableid oid); publicpostgresfalse1255233069-_cm_delete_relation(text, oid, text, integer)FUNCTIONCREATE FUNCTION public._cm_delete_relation(username text, domainid oid, cardidcolumn text, cardid integer) RETURNS void LANGUAGE plpgsql AS $$ DECLARE BEGIN -- coalesce(quote_literal(UserName),'NULL') -> quote_nullable(UserName) -- pg84 EXECUTE 'UPDATE ' || DomainId::regclass || ' SET "Status" = ''N'', "User" = ' || coalesce(quote_literal(UserName),'NULL') || ' WHERE "Status" = ''A'' AND ' || quote_ident(CardIdColumn) || ' = ' || CardId; END; $$; jDROP FUNCTION public._cm_delete_relation(username text, domainid oid, cardidcolumn text, cardid integer); publicpostgresfalse12552330700_cm_dest_classid_for_domain_attribute(oid, text)FUNCTIONVCREATE FUNCTION public._cm_dest_classid_for_domain_attribute(domainid oid, attributename text) RETURNS oid LANGUAGE sql STABLE STRICT AS $_$ SELECT _cm_table_id( _cm_read_comment( _cm_comment_for_table_id($1), CASE $2 WHEN 'IdObj1' THEN 'CLASS1' WHEN 'IdObj2' THEN 'CLASS2' ELSE NULL END ) ); $_$; ^DROP FUNCTION public._cm_dest_classid_for_domain_attribute(domainid oid, attributename text); publicpostgresfalse1255233071._cm_dest_reference_classid(oid, text, integer)FUNCTIONCREATE FUNCTION public._cm_dest_reference_classid(domainid oid, refidcolumn text, refid integer) RETURNS oid LANGUAGE sql STABLE STRICT AS $_$ SELECT _cm_subclassid(_cm_dest_classid_for_domain_attribute($1, $2), $3) $_$; `DROP FUNCTION public._cm_dest_reference_classid(domainid oid, refidcolumn text, refid integer); publicpostgresfalse1255233072*_cm_disable_triggers_recursively(regclass)FUNCTIONNCREATE FUNCTION public._cm_disable_triggers_recursively(superclass regclass) RETURNS void LANGUAGE plpgsql AS $_$ DECLARE CurrentClass regclass := $1; BEGIN FOR CurrentClass IN SELECT _cm_subtables_and_itself(SuperClass) LOOP EXECUTE 'ALTER TABLE '|| CurrentClass::regclass ||' DISABLE TRIGGER USER'; END LOOP; END; $_$; LDROP FUNCTION public._cm_disable_triggers_recursively(superclass regclass); publicpostgresfalse1255233073_cm_domain_cardinality(oid)FUNCTIONCREATE FUNCTION public._cm_domain_cardinality(domainid oid) RETURNS text LANGUAGE sql STABLE AS $_$ SELECT _cm_read_domain_cardinality(_cm_comment_for_table_id($1)); $_$; ;DROP FUNCTION public._cm_domain_cardinality(domainid oid); publicpostgresfalse1255233074_cm_domain_cmname(text)FUNCTIONCREATE FUNCTION public._cm_domain_cmname(cmdomain text) RETURNS text LANGUAGE sql IMMUTABLE AS $_$ SELECT coalesce(_cm_cmschema($1)||'.','')||coalesce('Map_'||_cm_cmtable($1),'Map'); $_$; 7DROP FUNCTION public._cm_domain_cmname(cmdomain text); publicpostgresfalse1255233075_cm_domain_cmname_lc(text)FUNCTIONCREATE FUNCTION public._cm_domain_cmname_lc(cmdomainname text) RETURNS text LANGUAGE sql IMMUTABLE AS $_$ SELECT lower(_cm_domain_cmname($1)); $_$; >DROP FUNCTION public._cm_domain_cmname_lc(cmdomainname text); publicpostgresfalse1255233076_cm_domain_dbname(text)FUNCTIONCREATE FUNCTION public._cm_domain_dbname(cmdomain text) RETURNS regclass LANGUAGE sql STABLE AS $_$ SELECT _cm_table_dbname(_cm_domain_cmname($1)); $_$; 7DROP FUNCTION public._cm_domain_dbname(cmdomain text); publicpostgresfalse1255233077_cm_domain_dbname_unsafe(text)FUNCTIONCREATE FUNCTION public._cm_domain_dbname_unsafe(cmdomain text) RETURNS text LANGUAGE sql IMMUTABLE AS $_$ SELECT _cm_table_dbname_unsafe(_cm_domain_cmname($1)); $_$; >DROP FUNCTION public._cm_domain_dbname_unsafe(cmdomain text); publicpostgresfalse1255233078_cm_domain_direction(oid)FUNCTION>CREATE FUNCTION public._cm_domain_direction(domainid oid) RETURNS boolean LANGUAGE plpgsql STABLE STRICT AS $$ DECLARE Cardinality text := _cm_domain_cardinality(DomainId); BEGIN IF Cardinality = 'N:1' THEN RETURN TRUE; ELSIF Cardinality = '1:N' THEN RETURN FALSE; ELSE RETURN NULL; END IF; END $$; 9DROP FUNCTION public._cm_domain_direction(domainid oid); publicpostgresfalse1255233079_cm_domain_id(text)FUNCTIONCREATE FUNCTION public._cm_domain_id(cmdomain text) RETURNS oid LANGUAGE sql STABLE STRICT AS $_$ SELECT _cm_table_id(_cm_domain_cmname($1)); $_$; 3DROP FUNCTION public._cm_domain_id(cmdomain text); publicpostgresfalse1255233080_cm_domain_list()FUNCTIONCREATE FUNCTION public._cm_domain_list() RETURNS SETOF oid LANGUAGE sql STABLE AS $$ SELECT oid FROM pg_class WHERE _cm_is_domain_comment(_cm_comment_for_cmobject(oid)); $$; (DROP FUNCTION public._cm_domain_list(); publicpostgresfalse1255233081_cm_domainidx_name(oid, text)FUNCTIONCREATE FUNCTION public._cm_domainidx_name(domainid oid, type text) RETURNS text LANGUAGE sql IMMUTABLE AS $_$ SELECT 'idx_' || _cm_cmtable_lc($1) || '_' || lower($2); $_$; BDROP FUNCTION public._cm_domainidx_name(domainid oid, type text); publicpostgresfalse1255233082_cm_domainpk_name(text)FUNCTIONCREATE FUNCTION public._cm_domainpk_name(cmdomainname text) RETURNS text LANGUAGE sql IMMUTABLE AS $_$ SELECT _cm_classpk_name(_cm_domain_cmname($1)); $_$; ;DROP FUNCTION public._cm_domainpk_name(cmdomainname text); publicpostgresfalse1255233083(_cm_drop_triggers_recursively(oid, text)FUNCTIONTCREATE FUNCTION public._cm_drop_triggers_recursively(tableid oid, triggername text) RETURNS void LANGUAGE plpgsql AS $$ DECLARE SubClassId oid; BEGIN FOR SubClassId IN SELECT _cm_subtables_and_itself(TableId) LOOP EXECUTE 'DROP TRIGGER IF EXISTS '|| quote_ident(TriggerName) ||' ON '|| SubClassId::regclass; END LOOP; END; $$; SDROP FUNCTION public._cm_drop_triggers_recursively(tableid oid, triggername text); publicpostgresfalse1255233084)_cm_enable_triggers_recursively(regclass)FUNCTIONHCREATE FUNCTION public._cm_enable_triggers_recursively(superclass regclass) RETURNS void LANGUAGE plpgsql AS $_$ DECLARE CurrentClass regclass := $1; BEGIN FOR CurrentClass IN SELECT _cm_subtables_and_itself(SuperClass) LOOP EXECUTE 'ALTER TABLE '|| CurrentClass::text ||' ENABLE TRIGGER USER'; END LOOP; END; $_$; KDROP FUNCTION public._cm_enable_triggers_recursively(superclass regclass); publicpostgresfalse1255233085_cm_function_list()FUNCTIONCREATE FUNCTION public._cm_function_list(OUT function_name text, OUT function_id oid, OUT arg_io character[], OUT arg_names text[], OUT arg_types text[], OUT returns_set boolean, OUT comment text) RETURNS SETOF record LANGUAGE plpgsql STABLE AS $_$ DECLARE R record; i integer; BEGIN FOR R IN SELECT * FROM pg_proc WHERE _cm_comment_for_cmobject(oid) IS NOT NULL LOOP function_name := R.proname::text; function_id := R.oid; returns_set := R.proretset; comment := _cm_comment_for_cmobject(R.oid); IF R.proargmodes IS NULL THEN arg_io := '{}'::char[]; arg_types := '{}'::text[]; arg_names := '{}'::text[]; -- add input columns FOR i IN SELECT generate_series(1, array_upper(R.proargtypes,1)) LOOP arg_io := arg_io || 'i'::char; arg_types := arg_types || _cm_get_sqltype_string(R.proargtypes[i], NULL); arg_names := arg_names || COALESCE(R.proargnames[i], '$'||i); END LOOP; -- add single output column arg_io := arg_io || 'o'::char; arg_types := arg_types || _cm_get_sqltype_string(R.prorettype, NULL); arg_names := arg_names || function_name; ELSE -- just normalize existing columns arg_io := R.proargmodes; arg_types := '{}'::text[]; arg_names := R.proargnames; FOR i IN SELECT generate_series(1, array_upper(arg_io,1)) LOOP -- normalize table output IF arg_io[i] = 't' THEN arg_io[i] := 'o'; ELSIF arg_io[i] = 'b' THEN arg_io[i] := 'io'; END IF; arg_types := arg_types || _cm_get_sqltype_string(R.proallargtypes[i], NULL); IF arg_names[i] = '' THEN IF arg_io[i] = 'i' THEN arg_names[i] = '$'||i; ELSE arg_names[i] = 'column'||i; END IF; END IF; END LOOP; END IF; RETURN NEXT; END LOOP; RETURN; END $_$; DROP FUNCTION public._cm_function_list(OUT function_name text, OUT function_id oid, OUT arg_io character[], OUT arg_names text[], OUT arg_types text[], OUT returns_set boolean, OUT comment text); publicpostgresfalse1255233086$_cm_get_attribute_default(oid, text)FUNCTION_CREATE FUNCTION public._cm_get_attribute_default(tableid oid, attributename text) RETURNS text LANGUAGE sql STABLE AS $_$ SELECT pg_attrdef.adsrc FROM pg_attribute JOIN pg_attrdef ON pg_attrdef.adrelid = pg_attribute.attrelid AND pg_attrdef.adnum = pg_attribute.attnum WHERE pg_attribute.attrelid = $1 AND pg_attribute.attname = $2; $_$; QDROP FUNCTION public._cm_get_attribute_default(tableid oid, attributename text); publicpostgresfalse1255233087$_cm_get_attribute_sqltype(oid, text)FUNCTION+CREATE FUNCTION public._cm_get_attribute_sqltype(tableid oid, attributename text) RETURNS text LANGUAGE sql STABLE AS $_$ SELECT _cm_get_sqltype_string(pg_attribute.atttypid, pg_attribute.atttypmod) FROM pg_attribute WHERE pg_attribute.attrelid = $1 AND pg_attribute.attname = $2; $_$; QDROP FUNCTION public._cm_get_attribute_sqltype(tableid oid, attributename text); publicpostgresfalse1255233088-_cm_get_domain_reference_target_comment(text)FUNCTION/CREATE FUNCTION public._cm_get_domain_reference_target_comment(domaincomment text) RETURNS text LANGUAGE sql STABLE STRICT AS $_$ SELECT CASE _cm_read_domain_cardinality($1) WHEN '1:N' THEN _cm_read_comment($1, 'CLASS1') WHEN 'N:1' THEN _cm_read_comment($1, 'CLASS2') ELSE NULL END $_$; RDROP FUNCTION public._cm_get_domain_reference_target_comment(domaincomment text); publicpostgresfalse1255233089_cm_get_fk_target(oid, text)FUNCTIONbCREATE FUNCTION public._cm_get_fk_target(tableid oid, attributename text) RETURNS text LANGUAGE plpgsql STABLE STRICT AS $$ DECLARE AttributeComment text := _cm_comment_for_attribute(TableId, AttributeName); BEGIN RETURN COALESCE( _cm_get_fk_target_comment(AttributeComment), _cm_read_reference_target_comment(AttributeComment) ); END $$; IDROP FUNCTION public._cm_get_fk_target(tableid oid, attributename text); publicpostgresfalse1255233090_cm_get_fk_target_comment(text)FUNCTIONCREATE FUNCTION public._cm_get_fk_target_comment(attributecomment text) RETURNS text LANGUAGE sql STABLE STRICT AS $_$ SELECT _cm_read_comment($1, 'FKTARGETCLASS'); $_$; GDROP FUNCTION public._cm_get_fk_target_comment(attributecomment text); publicpostgresfalse1255233091%_cm_get_fk_target_table_id(oid, text)FUNCTIONCREATE FUNCTION public._cm_get_fk_target_table_id(tableid oid, attributename text) RETURNS oid LANGUAGE plpgsql STABLE STRICT AS $_$ BEGIN RETURN _cm_table_id(_cm_get_fk_target($1, $2)); END $_$; RDROP FUNCTION public._cm_get_fk_target_table_id(tableid oid, attributename text); publicpostgresfalse1255233092 _cm_get_geometry_type(oid, text)FUNCTIONCREATE FUNCTION public._cm_get_geometry_type(tableid oid, attribute text) RETURNS text LANGUAGE plpgsql STABLE AS $_$ DECLARE GeoType text; BEGIN SELECT geometry_columns.type INTO GeoType FROM pg_attribute LEFT JOIN geometry_columns ON f_table_schema = _cm_cmschema($1) AND f_table_name = _cm_cmtable($1) AND f_geometry_column = $2 WHERE attrelid = $1 AND attname = $2 AND attnum > 0 AND atttypid > 0; RETURN GeoType; EXCEPTION WHEN undefined_table THEN RETURN NULL; END $_$; IDROP FUNCTION public._cm_get_geometry_type(tableid oid, attribute text); publicpostgresfalse1255233093!_cm_get_lookup_type_comment(text)FUNCTIONCREATE FUNCTION public._cm_get_lookup_type_comment(attributecomment text) RETURNS text LANGUAGE sql AS $_$ SELECT _cm_read_comment($1, 'LOOKUP'); $_$; IDROP FUNCTION public._cm_get_lookup_type_comment(attributecomment text); publicpostgresfalse12552330944_cm_get_ref_source_class_domain_attribute(oid, text)FUNCTION)CREATE FUNCTION public._cm_get_ref_source_class_domain_attribute(tableid oid, attributename text) RETURNS text LANGUAGE sql STABLE AS $_$ SELECT CASE _cm_domain_direction(_cm_get_reference_domain_id($1, $2)) WHEN TRUE THEN 'IdClass1' WHEN FALSE THEN 'IdClass2' ELSE NULL END; $_$; aDROP FUNCTION public._cm_get_ref_source_class_domain_attribute(tableid oid, attributename text); publicpostgresfalse12552330951_cm_get_ref_source_id_domain_attribute(oid, text)FUNCTION"CREATE FUNCTION public._cm_get_ref_source_id_domain_attribute(tableid oid, attributename text) RETURNS text LANGUAGE sql STABLE AS $_$ SELECT CASE _cm_domain_direction(_cm_get_reference_domain_id($1, $2)) WHEN TRUE THEN 'IdObj1' WHEN FALSE THEN 'IdObj2' ELSE NULL END; $_$; ^DROP FUNCTION public._cm_get_ref_source_id_domain_attribute(tableid oid, attributename text); publicpostgresfalse12552330961_cm_get_ref_target_id_domain_attribute(oid, text)FUNCTION"CREATE FUNCTION public._cm_get_ref_target_id_domain_attribute(tableid oid, attributename text) RETURNS text LANGUAGE sql STABLE AS $_$ SELECT CASE _cm_domain_direction(_cm_get_reference_domain_id($1, $2)) WHEN TRUE THEN 'IdObj2' WHEN FALSE THEN 'IdObj1' ELSE NULL END; $_$; ^DROP FUNCTION public._cm_get_ref_target_id_domain_attribute(tableid oid, attributename text); publicpostgresfalse1255233097&_cm_get_reference_domain_id(oid, text)FUNCTIONCREATE FUNCTION public._cm_get_reference_domain_id(tableid oid, attributename text) RETURNS oid LANGUAGE sql STABLE AS $_$ SELECT _cm_read_reference_domain_id_comment(_cm_comment_for_attribute($1, $2)); $_$; SDROP FUNCTION public._cm_get_reference_domain_id(tableid oid, attributename text); publicpostgresfalse12552330984_cm_get_safe_classorder(regclass, character varying)FUNCTIONCREATE FUNCTION public._cm_get_safe_classorder(tableid regclass, attname character varying, OUT classorder integer) RETURNS integer LANGUAGE plpgsql AS $$ BEGIN SELECT INTO classorder CASE WHEN (coalesce(_cm_read_comment(_cm_comment_for_attribute(tableid, attname), 'CLASSORDER'), '')<>'') THEN _cm_read_comment(_cm_comment_for_attribute(tableid, attname), 'CLASSORDER')::integer ELSE 0 END; END; $$; sDROP FUNCTION public._cm_get_safe_classorder(tableid regclass, attname character varying, OUT classorder integer); publicpostgresfalse1255233099$_cm_get_sqltype_string(oid, integer)FUNCTIONCREATE FUNCTION public._cm_get_sqltype_string(sqltypeid oid, typemod integer) RETURNS text LANGUAGE sql STABLE AS $_$ SELECT pg_type.typname::text || COALESCE( CASE WHEN pg_type.typname IN ('varchar','bpchar') THEN '(' || $2 - 4 || ')' WHEN pg_type.typname = 'numeric' THEN '(' || $2 / 65536 || ',' || $2 - $2 / 65536 * 65536 - 4|| ')' END, '') FROM pg_type WHERE pg_type.oid = $1; $_$; MDROP FUNCTION public._cm_get_sqltype_string(sqltypeid oid, typemod integer); publicpostgresfalse1255233100_cm_get_type_comment(text)FUNCTIONCREATE FUNCTION public._cm_get_type_comment(classcomment text) RETURNS text LANGUAGE sql STABLE STRICT AS $_$ SELECT _cm_read_comment($1, 'TYPE'); $_$; >DROP FUNCTION public._cm_get_type_comment(classcomment text); publicpostgresfalse1255233101$_cm_get_value_infrastructure(bigint)FUNCTIONCREATE FUNCTION public._cm_get_value_infrastructure(ciid bigint, OUT descr character varying) RETURNS character varying LANGUAGE plpgsql STABLE AS $$ DECLARE INFRASTRUCTUREDESCR character varying ; BEGIN SELECT i."Code" INTO INFRASTRUCTUREDESCR FROM "Map_InfrastructureCI" r INNER JOIN "Infrastructure" i on r."IdObj1" = i."Id" inner join "LookUp" l on i."Type" = l."Id" where r."Status" = 'A' AND l."Notes" = 'Singularity Context' AND r."IdObj2" = ciid limit 1; descr := INFRASTRUCTUREDESCR; END $$; ]DROP FUNCTION public._cm_get_value_infrastructure(ciid bigint, OUT descr character varying); publicpostgresfalse1255233102_cm_history_cmname(text)FUNCTIONCREATE FUNCTION public._cm_history_cmname(cmclass text) RETURNS text LANGUAGE sql IMMUTABLE AS $_$ SELECT $1 || '_history'; $_$; 7DROP FUNCTION public._cm_history_cmname(cmclass text); publicpostgresfalse1255233103_cm_history_dbname(text)FUNCTIONCREATE FUNCTION public._cm_history_dbname(cmtable text) RETURNS regclass LANGUAGE sql STABLE AS $_$ SELECT _cm_table_dbname(_cm_history_cmname($1)); $_$; 7DROP FUNCTION public._cm_history_dbname(cmtable text); publicpostgresfalse1255233104_cm_history_dbname_unsafe(text)FUNCTIONCREATE FUNCTION public._cm_history_dbname_unsafe(cmtable text) RETURNS text LANGUAGE sql IMMUTABLE AS $_$ SELECT _cm_table_dbname_unsafe(_cm_history_cmname($1)); $_$; >DROP FUNCTION public._cm_history_dbname_unsafe(cmtable text); publicpostgresfalse1255233105_cm_history_id(text)FUNCTIONCREATE FUNCTION public._cm_history_id(cmtable text) RETURNS oid LANGUAGE sql STABLE AS $_$ SELECT _cm_table_id(_cm_history_cmname($1)); $_$; 3DROP FUNCTION public._cm_history_id(cmtable text); publicpostgresfalse1255233106_cm_historyfk_name(text, text)FUNCTIONCREATE FUNCTION public._cm_historyfk_name(cmclassname text, attributename text) RETURNS text LANGUAGE sql IMMUTABLE AS $_$ SELECT _cm_classfk_name(_cm_history_cmname($1), $2); $_$; ODROP FUNCTION public._cm_historyfk_name(cmclassname text, attributename text); publicpostgresfalse1255233107_cm_historypk_name(text)FUNCTIONCREATE FUNCTION public._cm_historypk_name(cmclassname text) RETURNS text LANGUAGE sql IMMUTABLE AS $_$ SELECT _cm_classpk_name(_cm_history_cmname($1)); $_$; ;DROP FUNCTION public._cm_historypk_name(cmclassname text); publicpostgresfalse1255233108A_cm_insert_relation(text, oid, text, integer, text, integer, oid)FUNCTIONACREATE FUNCTION public._cm_insert_relation(username text, domainid oid, cardidcolumn text, cardid integer, refidcolumn text, refid integer, cardclassid oid) RETURNS void LANGUAGE plpgsql AS $$ DECLARE CardClassIdColumnPart text; RefClassIdColumnPart text; CardClassIdValuePart text; RefClassIdValuePart text; StopRecursion boolean; BEGIN IF (CardId IS NULL OR RefId IS NULL) THEN RAISE EXCEPTION 'CM_FORBIDDEN_OPERATION'; END IF; -- Needed for backward compatibility CardClassIdColumnPart := coalesce(quote_ident('IdClass'||substring(CardIdColumn from '^IdObj(.)+')) || ', ', ''); RefClassIdColumnPart := coalesce(quote_ident('IdClass'||substring(RefIdColumn from '^IdObj(.)+')) || ', ', ''); CardClassIdValuePart := CASE WHEN CardClassIdColumnPart IS NOT NULL THEN (coalesce(CardClassId::text, 'NULL') || ', ') ELSE '' END; RefClassIdValuePart := coalesce(_cm_dest_reference_classid(DomainId, RefIdColumn, RefId)::text, 'NULL') || ', '; -- Stop trigger recursion EXECUTE 'SELECT (COUNT(*) > 0) FROM ' || DomainId::regclass || ' WHERE' || ' "IdDomain" = ' || DomainId::text || -- NOTE: why is this check done? ' AND ' || quote_ident(CardIdColumn) || ' = ' || CardId::text || ' AND ' || quote_ident(RefIdColumn) || ' = ' || RefId::text || ' AND "Status" = ''A''' INTO StopRecursion; IF NOT StopRecursion THEN EXECUTE 'INSERT INTO ' || DomainId::regclass || ' (' || '"IdDomain", ' || quote_ident(CardIdColumn) || ', ' || quote_ident(RefIdColumn) || ', ' || CardClassIdColumnPart || RefClassIdColumnPart || '"Status", ' || '"User"' || ') VALUES (' || DomainId::text || ', ' || CardId::text || ', ' || RefId::text || ', ' || CardClassIdValuePart || RefClassIdValuePart || '''A'', ' || coalesce(quote_literal(UserName), 'NULL') || ')'; END IF; END; $$; DROP FUNCTION public._cm_insert_relation(username text, domainid oid, cardidcolumn text, cardid integer, refidcolumn text, refid integer, cardclassid oid); publicpostgresfalse1255233109_cm_is_active_comment(text)FUNCTIONCREATE FUNCTION public._cm_is_active_comment(classcomment text) RETURNS boolean LANGUAGE sql STABLE AS $_$ SELECT _cm_check_comment($1, 'STATUS', 'active'); $_$; ?DROP FUNCTION public._cm_is_active_comment(classcomment text); publicpostgresfalse1255233110_cm_is_any_class(oid)FUNCTIONCREATE FUNCTION public._cm_is_any_class(classid oid) RETURNS boolean LANGUAGE sql STABLE AS $_$ SELECT _cm_is_any_class_comment(_cm_comment_for_table_id($1)) $_$; 4DROP FUNCTION public._cm_is_any_class(classid oid); publicpostgresfalse1255233111_cm_is_any_class_comment(text)FUNCTIONCREATE FUNCTION public._cm_is_any_class_comment(classcomment text) RETURNS boolean LANGUAGE sql STABLE AS $_$ SELECT _cm_check_comment($1, 'TYPE', '%class'); $_$; BDROP FUNCTION public._cm_is_any_class_comment(classcomment text); publicpostgresfalse1255233112_cm_is_cmobject(oid)FUNCTIONCREATE FUNCTION public._cm_is_cmobject(tableid oid) RETURNS boolean LANGUAGE sql STABLE AS $_$ SELECT _cm_comment_for_cmobject($1) IS NOT NULL; $_$; 3DROP FUNCTION public._cm_is_cmobject(tableid oid); publicpostgresfalse1255233113_cm_is_domain_comment(text)FUNCTIONCREATE FUNCTION public._cm_is_domain_comment(classcomment text) RETURNS boolean LANGUAGE sql STABLE AS $_$ SELECT _cm_check_comment($1, 'TYPE', 'domain'); $_$; ?DROP FUNCTION public._cm_is_domain_comment(classcomment text); publicpostgresfalse1255233114_cm_is_geometry_type(text)FUNCTIONCREATE FUNCTION public._cm_is_geometry_type(cmattributetype text) RETURNS boolean LANGUAGE sql STABLE AS $_$ SELECT $1 IN ('POINT','LINESTRING','POLYGON'); $_$; ADROP FUNCTION public._cm_is_geometry_type(cmattributetype text); publicpostgresfalse1255233115_cm_is_process(oid)FUNCTIONCREATE FUNCTION public._cm_is_process(classid oid) RETURNS boolean LANGUAGE sql STABLE AS $_$ SELECT $1 IN (SELECT _cm_subtables_and_itself(_cm_table_id('Activity'))); $_$; 2DROP FUNCTION public._cm_is_process(classid oid); publicpostgresfalse1255233116_cm_is_process(text)FUNCTIONCREATE FUNCTION public._cm_is_process(cmclass text) RETURNS boolean LANGUAGE sql STABLE AS $_$ SELECT _cm_is_process(_cm_table_id($1)); $_$; 3DROP FUNCTION public._cm_is_process(cmclass text); publicpostgresfalse1255233117_cm_is_reference_comment(text)FUNCTIONCREATE FUNCTION public._cm_is_reference_comment(attributecomment text) RETURNS boolean LANGUAGE sql STABLE STRICT AS $_$ SELECT COALESCE(_cm_read_reference_domain_comment($1),'') != ''; $_$; FDROP FUNCTION public._cm_is_reference_comment(attributecomment text); publicpostgresfalse1255233118_cm_is_simpleclass(oid)FUNCTIONCREATE FUNCTION public._cm_is_simpleclass(classid oid) RETURNS boolean LANGUAGE sql STABLE AS $_$ SELECT _cm_is_simpleclass_comment(_cm_comment_for_table_id($1)) $_$; 6DROP FUNCTION public._cm_is_simpleclass(classid oid); publicpostgresfalse1255233119_cm_is_simpleclass(text)FUNCTIONCREATE FUNCTION public._cm_is_simpleclass(cmclass text) RETURNS boolean LANGUAGE sql STABLE AS $_$ SELECT _cm_is_simpleclass_comment(_cm_comment_for_class($1)); $_$; 7DROP FUNCTION public._cm_is_simpleclass(cmclass text); publicpostgresfalse1255233120 _cm_is_simpleclass_comment(text)FUNCTIONCREATE FUNCTION public._cm_is_simpleclass_comment(classcomment text) RETURNS boolean LANGUAGE sql STABLE AS $_$ SELECT _cm_check_comment($1, 'TYPE', 'simpleclass'); $_$; DDROP FUNCTION public._cm_is_simpleclass_comment(classcomment text); publicpostgresfalse1255233121_cm_is_superclass(oid)FUNCTIONCREATE FUNCTION public._cm_is_superclass(classid oid) RETURNS boolean LANGUAGE sql STABLE AS $_$ SELECT _cm_is_superclass_comment(_cm_comment_for_table_id($1)); $_$; 5DROP FUNCTION public._cm_is_superclass(classid oid); publicpostgresfalse1255233122_cm_is_superclass(text)FUNCTIONCREATE FUNCTION public._cm_is_superclass(cmclass text) RETURNS boolean LANGUAGE sql STABLE AS $_$ SELECT _cm_is_superclass_comment(_cm_comment_for_class($1)); $_$; 6DROP FUNCTION public._cm_is_superclass(cmclass text); publicpostgresfalse1255233123_cm_is_superclass_comment(text)FUNCTIONCREATE FUNCTION public._cm_is_superclass_comment(classcomment text) RETURNS boolean LANGUAGE sql STABLE AS $_$ SELECT _cm_check_comment($1, 'SUPERCLASS', 'true'); $_$; CDROP FUNCTION public._cm_is_superclass_comment(classcomment text); publicpostgresfalse1255233124_cm_is_system(oid)FUNCTIONCREATE FUNCTION public._cm_is_system(tableid oid) RETURNS boolean LANGUAGE sql STABLE AS $_$ SELECT _cm_check_comment(_cm_comment_for_table_id($1), 'MODE', 'reserved') $_$; 1DROP FUNCTION public._cm_is_system(tableid oid); publicpostgresfalse1255233125_cm_join_cmname(name, name)FUNCTIONCREATE FUNCTION public._cm_join_cmname(cmschema name, cmtable name) RETURNS text LANGUAGE sql IMMUTABLE AS $_$ SELECT $1 || '.' || $2; $_$; CDROP FUNCTION public._cm_join_cmname(cmschema name, cmtable name); publicpostgresfalse1255233126<_cm_legacy_get_menu_code(boolean, boolean, boolean, boolean)FUNCTIONdCREATE FUNCTION public._cm_legacy_get_menu_code(boolean, boolean, boolean, boolean) RETURNS character varying LANGUAGE plpgsql AS $_$ DECLARE issuperclass ALIAS FOR $1; isprocess ALIAS FOR $2; isreport ALIAS FOR $3; isview ALIAS FOR $4; menucode varchar; BEGIN IF (issuperclass) THEN IF (isprocess) THEN menucode='superclassprocess'; ELSE menucode='superclass'; END IF; ELSIF(isview) THEN menucode='view'; ELSIF(isreport) THEN menucode='report'; ELSIF (isprocess) THEN menucode='processclass'; ELSE menucode='class'; END IF; RETURN menucode; END; $_$; SDROP FUNCTION public._cm_legacy_get_menu_code(boolean, boolean, boolean, boolean); publicpostgresfalse1255233127<_cm_legacy_get_menu_type(boolean, boolean, boolean, boolean)FUNCTIONCREATE FUNCTION public._cm_legacy_get_menu_type(boolean, boolean, boolean, boolean) RETURNS character varying LANGUAGE plpgsql AS $_$ DECLARE issuperclass ALIAS FOR $1; isprocess ALIAS FOR $2; isreport ALIAS FOR $3; isview ALIAS FOR $4; menutype varchar; BEGIN IF (isprocess) THEN menutype='processclass'; ELSIF(isview) THEN menutype='view'; ELSIF(isreport) THEN menutype='report'; ELSE menutype='class'; END IF; RETURN menutype; END; $_$; SDROP FUNCTION public._cm_legacy_get_menu_type(boolean, boolean, boolean, boolean); publicpostgresfalse1255233128#_cm_legacy_read_comment(text, text)FUNCTIONCREATE FUNCTION public._cm_legacy_read_comment(text, text) RETURNS character varying LANGUAGE sql STABLE AS $_$ SELECT COALESCE(_cm_read_comment($1, $2), ''); $_$; :DROP FUNCTION public._cm_legacy_read_comment(text, text); publicpostgresfalse 1255233129_cm_new_card_id()FUNCTIONCREATE FUNCTION public._cm_new_card_id() RETURNS integer LANGUAGE sql AS $$ SELECT nextval(('class_seq'::text)::regclass)::integer; $$; (DROP FUNCTION public._cm_new_card_id(); publicpostgresfalse 1255233130!_cm_notnull_constraint_name(text)FUNCTIONCREATE FUNCTION public._cm_notnull_constraint_name(attributename text) RETURNS text LANGUAGE sql IMMUTABLE AS $_$ SELECT '_NotNull_'||$1; $_$; FDROP FUNCTION public._cm_notnull_constraint_name(attributename text); publicpostgresfalse 1255233131_cm_parent_id(oid)FUNCTIONCREATE FUNCTION public._cm_parent_id(tableid oid) RETURNS SETOF oid LANGUAGE sql AS $_$ SELECT COALESCE((SELECT inhparent FROM pg_inherits WHERE inhrelid = $1 AND _cm_is_cmobject(inhparent) LIMIT 1), NULL); $_$; 1DROP FUNCTION public._cm_parent_id(tableid oid); publicpostgresfalse 1255233132&_cm_propagate_superclass_triggers(oid)FUNCTIONWCREATE FUNCTION public._cm_propagate_superclass_triggers(tableid oid) RETURNS void LANGUAGE plpgsql AS $$ DECLARE ParentId oid := _cm_parent_id(TableId); BEGIN PERFORM _cm_copy_restrict_trigger(ParentId, TableId); PERFORM _cm_copy_update_relation_trigger(ParentId, TableId); PERFORM _cm_copy_fk_trigger(ParentId, TableId); END $$; EDROP FUNCTION public._cm_propagate_superclass_triggers(tableid oid); publicpostgresfalse 1255233133_cm_read_comment(text, text)FUNCTIONCREATE FUNCTION public._cm_read_comment(comment text, key text) RETURNS text LANGUAGE sql STABLE STRICT AS $_$ SELECT TRIM(SUBSTRING($1 FROM E'(?:^|\\|)'||$2||E':[ ]*([^\\|]+)')); $_$; ?DROP FUNCTION public._cm_read_comment(comment text, key text); publicpostgresfalse1255233134!_cm_read_domain_cardinality(text)FUNCTIONCREATE FUNCTION public._cm_read_domain_cardinality(attributecomment text) RETURNS text LANGUAGE sql STABLE AS $_$ SELECT _cm_read_comment($1, 'CARDIN'); $_$; IDROP FUNCTION public._cm_read_domain_cardinality(attributecomment text); publicpostgresfalse1255233135'_cm_read_reference_domain_comment(text)FUNCTIONCREATE FUNCTION public._cm_read_reference_domain_comment(attributecomment text) RETURNS text LANGUAGE sql STABLE STRICT AS $_$ SELECT _cm_read_comment($1, 'REFERENCEDOM'); $_$; ODROP FUNCTION public._cm_read_reference_domain_comment(attributecomment text); publicpostgresfalse1255233136*_cm_read_reference_domain_id_comment(text)FUNCTIONCREATE FUNCTION public._cm_read_reference_domain_id_comment(attributecomment text) RETURNS oid LANGUAGE sql STABLE STRICT AS $_$ SELECT _cm_domain_id(_cm_read_reference_domain_comment($1)); $_$; RDROP FUNCTION public._cm_read_reference_domain_id_comment(attributecomment text); publicpostgresfalse1255233137'_cm_read_reference_target_comment(text)FUNCTIONCREATE FUNCTION public._cm_read_reference_target_comment(attributecomment text) RETURNS text LANGUAGE sql STABLE STRICT AS $_$ SELECT _cm_get_domain_reference_target_comment(_cm_comment_for_domain(_cm_read_reference_domain_comment($1))); $_$; ODROP FUNCTION public._cm_read_reference_target_comment(attributecomment text); publicpostgresfalse1255233138*_cm_read_reference_target_id_comment(text)FUNCTIONCREATE FUNCTION public._cm_read_reference_target_id_comment(attributecomment text) RETURNS oid LANGUAGE sql STABLE STRICT AS $_$ SELECT _cm_table_id(_cm_read_reference_target_comment($1)); $_$; RDROP FUNCTION public._cm_read_reference_target_id_comment(attributecomment text); publicpostgresfalse1255233139%_cm_read_reference_type_comment(text)FUNCTIONCREATE FUNCTION public._cm_read_reference_type_comment(attributecomment text) RETURNS text LANGUAGE sql STABLE STRICT AS $_$ SELECT COALESCE(NULLIF(_cm_read_comment($1, 'REFERENCETYPE'), ''), 'restrict'); $_$; MDROP FUNCTION public._cm_read_reference_type_comment(attributecomment text); publicpostgresfalse1255233140(_cm_remove_attribute_triggers(oid, text)FUNCTION CREATE FUNCTION public._cm_remove_attribute_triggers(tableid oid, attributename text) RETURNS void LANGUAGE plpgsql AS $$ BEGIN PERFORM _cm_remove_fk_constraints(TableId, AttributeName); PERFORM _cm_remove_reference_handling(TableId, AttributeName); END; $$; UDROP FUNCTION public._cm_remove_attribute_triggers(tableid oid, attributename text); publicpostgresfalse1255233141-_cm_remove_constraint_trigger(oid, oid, text)FUNCTION;CREATE FUNCTION public._cm_remove_constraint_trigger(fktargetclassid oid, fkclassid oid, fkattribute text) RETURNS void LANGUAGE plpgsql AS $$ BEGIN EXECUTE ' DROP TRIGGER ' || quote_ident('_Constr_'||_cm_cmtable(FKClassId)||'_'||FKAttribute) || ' ON ' || FKTargetClassId::regclass || '; '; END; $$; jDROP FUNCTION public._cm_remove_constraint_trigger(fktargetclassid oid, fkclassid oid, fkattribute text); publicpostgresfalse1255233142$_cm_remove_fk_constraints(oid, text)FUNCTIONCREATE FUNCTION public._cm_remove_fk_constraints(fksourceid oid, attributename text) RETURNS void LANGUAGE plpgsql AS $$ DECLARE TargetId oid := _cm_get_fk_target_table_id(FKSourceId, AttributeName); SubTableId oid; BEGIN IF TargetId IS NULL THEN RETURN; END IF; FOR SubTableId IN SELECT _cm_subtables_and_itself(FKSourceId) LOOP EXECUTE 'DROP TRIGGER '|| quote_ident(_cm_classfk_name(FKSourceId, AttributeName)) || ' ON '|| SubTableId::regclass; END LOOP; FOR SubTableId IN SELECT _cm_subtables_and_itself(TargetId) LOOP PERFORM _cm_remove_constraint_trigger(SubTableId, FKSourceId, AttributeName); END LOOP; END; $$; TDROP FUNCTION public._cm_remove_fk_constraints(fksourceid oid, attributename text); publicpostgresfalse1255233143(_cm_remove_reference_handling(oid, text)FUNCTIONCREATE FUNCTION public._cm_remove_reference_handling(tableid oid, attributename text) RETURNS void LANGUAGE plpgsql AS $$ BEGIN -- remove UpdRel and UpdRef triggers PERFORM _cm_drop_triggers_recursively( TableId, _cm_update_relation_trigger_name(TableId, AttributeName) ); PERFORM _cm_drop_triggers_recursively( _cm_get_reference_domain_id(TableId, AttributeName), _cm_update_reference_trigger_name(TableId, AttributeName) ); END $$; UDROP FUNCTION public._cm_remove_reference_handling(tableid oid, attributename text); publicpostgresfalse1255233144 _cm_restrict(integer, oid, text)FUNCTIONCREATE FUNCTION public._cm_restrict(id integer, tableid oid, attributename text) RETURNS void LANGUAGE plpgsql AS $_$ BEGIN IF _cm_check_value_exists($1, $2, $3, FALSE) THEN -- RAISE restrict_violation; -- pg84 RAISE EXCEPTION 'CM_RESTRICT_VIOLATION'; END IF; END; $_$; PDROP FUNCTION public._cm_restrict(id integer, tableid oid, attributename text); publicpostgresfalse1255233145*_cm_set_attribute_comment(oid, text, text)FUNCTION|CREATE FUNCTION public._cm_set_attribute_comment(tableid oid, attributename text, comment text) RETURNS void LANGUAGE plpgsql AS $$ DECLARE SubClassId oid; BEGIN FOR SubClassId IN SELECT _cm_subtables_and_itself(TableId) LOOP EXECUTE 'COMMENT ON COLUMN '|| SubClassId::regclass ||'.'|| quote_ident(AttributeName) ||' IS '|| quote_literal(Comment); END LOOP; END; $$; _DROP FUNCTION public._cm_set_attribute_comment(tableid oid, attributename text, comment text); publicpostgresfalse12552331463_cm_set_attribute_default(oid, text, text, boolean)FUNCTIONCREATE FUNCTION public._cm_set_attribute_default(tableid oid, attributename text, newdefault text, updateexisting boolean) RETURNS void LANGUAGE plpgsql AS $$ DECLARE CurrentDefaultSrc text := _cm_get_attribute_default(TableId, AttributeName); NewDefaultSrc text := _cm_attribute_default_to_src(TableId, AttributeName, NewDefault); BEGIN IF (NewDefaultSrc IS DISTINCT FROM CurrentDefaultSrc) THEN IF (CurrentDefaultSrc IS NULL) THEN EXECUTE 'ALTER TABLE ' || TableId::regclass || ' ALTER COLUMN ' || quote_ident(AttributeName) || ' SET DEFAULT ' || NewDefaultSrc; IF UpdateExisting THEN EXECUTE 'UPDATE '|| TableId::regclass ||' SET '|| quote_ident(AttributeName) ||' = '|| NewDefaultSrc; END IF; ELSE EXECUTE 'ALTER TABLE '|| TableId::regclass ||' ALTER COLUMN '|| quote_ident(AttributeName) ||' DROP DEFAULT'; END IF; END IF; END; $$; zDROP FUNCTION public._cm_set_attribute_default(tableid oid, attributename text, newdefault text, updateexisting boolean); publicpostgresfalse1255233147_cm_setnull(integer, oid, text)FUNCTION"CREATE FUNCTION public._cm_setnull(id integer, tableid oid, attributename text) RETURNS void LANGUAGE plpgsql AS $$ BEGIN EXECUTE 'UPDATE '|| TableId::regclass || ' SET '||quote_ident(AttributeName)||' = NULL'|| ' WHERE '||quote_ident(AttributeName)||' = '||Id::text; END; $$; ODROP FUNCTION public._cm_setnull(id integer, tableid oid, attributename text); publicpostgresfalse1255233148_cm_split_cmname(text)FUNCTIONCREATE FUNCTION public._cm_split_cmname(cmname text) RETURNS text[] LANGUAGE sql IMMUTABLE AS $_$ SELECT regexp_matches($1,E'(?:([^\\.]+)\\.)?([^\\.]+)?'); $_$; 4DROP FUNCTION public._cm_split_cmname(cmname text); publicpostgresfalse1255233149_cm_string_agg(anyarray)FUNCTIONCREATE FUNCTION public._cm_string_agg(anyarray) RETURNS text LANGUAGE sql AS $_$ SELECT case when trim(array_to_string($1, ', ')) = '' THEN null else array_to_string($1, ', ') END $_$; /DROP FUNCTION public._cm_string_agg(anyarray); publicpostgresfalse1255233150_cm_subclassid(oid, integer)FUNCTIONCREATE FUNCTION public._cm_subclassid(superclassid oid, cardid integer) RETURNS oid LANGUAGE plpgsql STABLE STRICT AS $$ DECLARE Out integer; BEGIN EXECUTE 'SELECT tableoid FROM '||SuperClassId::regclass||' WHERE "Id"='||CardId||' LIMIT 1' INTO Out; RETURN Out; END; $$; GDROP FUNCTION public._cm_subclassid(superclassid oid, cardid integer); publicpostgresfalse 1255233151_cm_subtables_and_itself(oid)FUNCTIONCREATE FUNCTION public._cm_subtables_and_itself(tableid oid) RETURNS SETOF oid LANGUAGE sql AS $_$ SELECT $1 WHERE _cm_is_cmobject($1) UNION SELECT _cm_subtables_and_itself(inhrelid) FROM pg_inherits WHERE inhparent = $1 $_$; <DROP FUNCTION public._cm_subtables_and_itself(tableid oid); publicpostgresfalse!1255233152_cm_table_dbname(text)FUNCTIONCREATE FUNCTION public._cm_table_dbname(cmname text) RETURNS regclass LANGUAGE sql STABLE AS $_$ SELECT _cm_table_dbname_unsafe($1)::regclass; $_$; 4DROP FUNCTION public._cm_table_dbname(cmname text); publicpostgresfalse"1255233153_cm_table_dbname_unsafe(text)FUNCTIONCREATE FUNCTION public._cm_table_dbname_unsafe(cmname text) RETURNS text LANGUAGE sql IMMUTABLE AS $_$ SELECT coalesce(quote_ident(_cm_cmschema($1))||'.','')||quote_ident(_cm_cmtable($1)); $_$; ;DROP FUNCTION public._cm_table_dbname_unsafe(cmname text); publicpostgresfalse#1255233154_cm_table_id(text)FUNCTIONCREATE FUNCTION public._cm_table_id(cmname text) RETURNS oid LANGUAGE sql STABLE AS $_$ SELECT _cm_table_dbname_unsafe($1)::regclass::oid; $_$; 0DROP FUNCTION public._cm_table_id(cmname text); publicpostgresfalse$1255233155_cm_table_is_empty(oid)FUNCTION=CREATE FUNCTION public._cm_table_is_empty(tableid oid) RETURNS boolean LANGUAGE plpgsql AS $$ DECLARE NotFound boolean; BEGIN -- Note: FOUND variable is not set on EXECUTE, so we can't use it! EXECUTE 'SELECT (COUNT(*) = 0) FROM '|| TableId::regclass ||' LIMIT 1' INTO NotFound; RETURN NotFound; END; $$; 6DROP FUNCTION public._cm_table_is_empty(tableid oid); publicpostgresfalse%1255233156)_cm_trigger_cascade_delete_on_relations()FUNCTIONCREATE FUNCTION public._cm_trigger_cascade_delete_on_relations() RETURNS trigger LANGUAGE plpgsql AS $$ BEGIN RAISE DEBUG 'Trigger % on %', TG_NAME, TG_TABLE_NAME; IF (NEW."Status"='N') THEN UPDATE "Map" SET "Status"='N' WHERE "Status"='A' AND ( ("IdObj1" = OLD."Id" AND "IdClass1" = TG_RELID) OR ("IdObj2" = OLD."Id" AND "IdClass2" = TG_RELID) ); END IF; RETURN NEW; END; $$; @DROP FUNCTION public._cm_trigger_cascade_delete_on_relations(); publicpostgresfalse&1255233157%_cm_trigger_create_card_history_row()FUNCTIONCREATE FUNCTION public._cm_trigger_create_card_history_row() RETURNS trigger LANGUAGE plpgsql AS $_$ BEGIN -- Does not create the row on logic deletion IF (TG_OP='UPDATE') THEN OLD."Id" = _cm_new_card_id(); OLD."Status" = 'U'; -- PostgreSQL 8.4 -- EXECUTE 'INSERT INTO '||_cm_history_dbname(_cm_join_cmname(TG_TABLE_SCHEMA, TG_TABLE_NAME)) || -- ' ('||_cm_attribute_list_cs(TG_RELID)||',"CurrentId","EndDate")' || -- ' VALUES ($1.*, $2."Id", now())' USING OLD, NEW; -- PostgreSQL 8.3 EXECUTE 'INSERT INTO '||_cm_history_dbname(_cm_join_cmname(TG_TABLE_SCHEMA, TG_TABLE_NAME)) || ' ('||_cm_attribute_list_cs(TG_RELID)||',"CurrentId","EndDate")' || ' VALUES (' || ' (' || quote_literal(OLD) || '::' || TG_RELID::regclass || ').*, ' || ' (' || quote_literal(NEW) || '::' || TG_RELID::regclass || ')."Id", now())'; ELSIF (TG_OP='DELETE') THEN RAISE EXCEPTION 'CM_FORBIDDEN_OPERATION'; END IF; RETURN NEW; END; $_$; <DROP FUNCTION public._cm_trigger_create_card_history_row(); publicpostgresfalse'1255233158)_cm_trigger_create_relation_history_row()FUNCTIONCREATE FUNCTION public._cm_trigger_create_relation_history_row() RETURNS trigger LANGUAGE plpgsql AS $_$ BEGIN -- Does not create the row on logic deletion IF (TG_OP='UPDATE') THEN OLD."Status" = 'U'; OLD."EndDate" = now(); -- PostgreSQL 8.4 -- EXECUTE 'INSERT INTO '||_cm_history_dbname(_cm_join_cmname(TG_TABLE_SCHEMA, TG_TABLE_NAME)) || -- ' ('||_cm_attribute_list_cs(TG_RELID)||') VALUES ($1.*)' USING OLD; -- PostgreSQL 8.3 EXECUTE 'INSERT INTO '||_cm_history_dbname(_cm_join_cmname(TG_TABLE_SCHEMA, TG_TABLE_NAME)) || ' ('||_cm_attribute_list_cs(TG_RELID)||')' || ' VALUES (' || ' (' || quote_literal(OLD) || '::' || TG_RELID::regclass || ').*)'; ELSIF (TG_OP='DELETE') THEN RAISE EXCEPTION 'CM_FORBIDDEN_OPERATION'; END IF; RETURN NEW; END; $_$; @DROP FUNCTION public._cm_trigger_create_relation_history_row(); publicpostgresfalse(1255233159_cm_trigger_fk()FUNCTIONCREATE FUNCTION public._cm_trigger_fk() RETURNS trigger LANGUAGE plpgsql AS $_$ DECLARE SourceAttribute text := TG_ARGV[0]; TargetClassId oid := TG_ARGV[1]::regclass::oid; TriggerVariant text := TG_ARGV[2]; RefValue integer; ActiveCardsOnly boolean; BEGIN RAISE DEBUG 'Trigger % on %', TG_NAME, TG_TABLE_NAME; -- EXECUTE 'SELECT ($1).' || quote_ident(SourceAttribute) INTO RefValue USING NEW; -- pg84 EXECUTE 'SELECT (' || quote_literal(NEW) || '::' || TG_RELID::regclass || ').' || quote_ident(SourceAttribute) INTO RefValue; IF (TriggerVariant = 'simple') THEN ActiveCardsOnly := FALSE; ELSE ActiveCardsOnly := NEW."Status" <> 'A'; END IF; IF NOT _cm_check_id_exists(RefValue, TargetClassId, ActiveCardsOnly) THEN RETURN NULL; END IF; RETURN NEW; END; $_$; 'DROP FUNCTION public._cm_trigger_fk(); publicpostgresfalse)1255233160_cm_trigger_restrict()FUNCTIONxCREATE FUNCTION public._cm_trigger_restrict() RETURNS trigger LANGUAGE plpgsql AS $$ DECLARE TableId oid := TG_ARGV[0]::regclass::oid; AttributeName text := TG_ARGV[1]; BEGIN RAISE DEBUG 'Trigger % on %', TG_NAME, TG_TABLE_NAME; IF (TG_OP='UPDATE' AND NEW."Status"='N') THEN PERFORM _cm_restrict(OLD."Id", TableId, AttributeName); END IF; RETURN NEW; END; $$; -DROP FUNCTION public._cm_trigger_restrict(); publicpostgresfalse*1255233161&_cm_trigger_row_or_statement(smallint)FUNCTIONCREATE FUNCTION public._cm_trigger_row_or_statement(tgtype smallint) RETURNS text LANGUAGE sql IMMUTABLE AS $_$ SELECT CASE $1 & cast(1 as int2) WHEN 0 THEN 'STATEMENT' ELSE 'ROW' END; $_$; DDROP FUNCTION public._cm_trigger_row_or_statement(tgtype smallint); publicpostgresfalse+1255233162_cm_trigger_sanity_check()FUNCTIONCREATE FUNCTION public._cm_trigger_sanity_check() RETURNS trigger LANGUAGE plpgsql AS $$ BEGIN IF (TG_OP='UPDATE') THEN IF (NEW."Id" <> OLD."Id") THEN -- Id change RAISE EXCEPTION 'CM_FORBIDDEN_OPERATION'; END IF; IF (NEW."Status"='N' AND OLD."Status"='N') THEN -- Deletion of a deleted card RAISE EXCEPTION 'CM_FORBIDDEN_OPERATION'; END IF; ELSIF (TG_OP='INSERT') THEN IF (NEW."Status" IS NULL) THEN NEW."Status"='A'; ELSIF (NEW."Status"='N') THEN -- Creation of a deleted card RAISE EXCEPTION 'CM_FORBIDDEN_OPERATION'; END IF; NEW."Id" = _cm_new_card_id(); -- Class ID is needed because of the history tables BEGIN NEW."IdClass" = TG_RELID; EXCEPTION WHEN undefined_column THEN NEW."IdDomain" = TG_RELID; END; ELSE -- TG_OP='DELETE' RAISE EXCEPTION 'CM_FORBIDDEN_OPERATION'; END IF; -- 'U' is reserved for history tables only IF (position(NEW."Status" IN 'AND') = 0) THEN -- Invalid status RAISE EXCEPTION 'CM_FORBIDDEN_OPERATION'; END IF; NEW."BeginDate" = now(); RETURN NEW; END; $$; 1DROP FUNCTION public._cm_trigger_sanity_check(); publicpostgresfalse,1255233163!_cm_trigger_sanity_check_simple()FUNCTIONCREATE FUNCTION public._cm_trigger_sanity_check_simple() RETURNS trigger LANGUAGE plpgsql AS $$ BEGIN IF (TG_OP='UPDATE') THEN IF (NEW."Id" <> OLD."Id") THEN -- Id change RAISE EXCEPTION 'CM_FORBIDDEN_OPERATION'; END IF; ELSIF (TG_OP='DELETE') THEN -- RETURN NEW would return NULL forbidding the operation RETURN OLD; ELSE NEW."BeginDate" = now(); NEW."IdClass" = TG_RELID; END IF; RETURN NEW; END; $$; 8DROP FUNCTION public._cm_trigger_sanity_check_simple(); publicpostgresfalse-1255233164_cm_trigger_update_reference()FUNCTION+CREATE FUNCTION public._cm_trigger_update_reference() RETURNS trigger LANGUAGE plpgsql AS $$ DECLARE AttributeName text := TG_ARGV[0]; TableId oid := TG_ARGV[1]::regclass::oid; CardColumn text := TG_ARGV[2]; -- Domain column name for the card id RefColumn text := TG_ARGV[3]; -- Domain column name for the reference id OldCardId integer; NewCardId integer; OldRefValue integer; NewRefValue integer; BEGIN RAISE DEBUG 'Trigger % on %', TG_NAME, TG_TABLE_NAME; IF (NEW."Status"='A') THEN EXECUTE 'SELECT (' || quote_literal(NEW) || '::' || TG_RELID::regclass || ').' || quote_ident(RefColumn) INTO NewRefValue; ELSIF (NEW."Status"<>'N') THEN -- Ignore history rows RETURN NEW; END IF; EXECUTE 'SELECT (' || quote_literal(NEW) || '::' || TG_RELID::regclass || ').' || quote_ident(CardColumn) INTO NewCardId; IF (TG_OP='UPDATE') THEN EXECUTE 'SELECT (' || quote_literal(OLD) || '::' || TG_RELID::regclass || ').' || quote_ident(CardColumn) INTO OldCardId; IF (OldCardId <> NewCardId) THEN -- If the non-reference side changes... PERFORM _cm_update_reference(NEW."User", TableId, AttributeName, OldCardId, NULL); -- OldRefValue is kept null because it is like a new relation ELSE EXECUTE 'SELECT (' || quote_literal(OLD) || '::' || TG_RELID::regclass || ').' || quote_ident(RefColumn) INTO OldRefValue; END IF; END IF; IF ((NewRefValue IS NULL) OR (OldRefValue IS NULL) OR (OldRefValue <> NewRefValue)) THEN PERFORM _cm_update_reference(NEW."User", TableId, AttributeName, NewCardId, NewRefValue); END IF; RETURN NEW; END; $$; 5DROP FUNCTION public._cm_trigger_update_reference(); publicpostgresfalse.1255233165_cm_trigger_update_relation()FUNCTIONCREATE FUNCTION public._cm_trigger_update_relation() RETURNS trigger LANGUAGE plpgsql AS $_$ DECLARE AttributeName text := TG_ARGV[0]; DomainId oid := TG_ARGV[1]::regclass::oid; CardColumn text := TG_ARGV[2]; -- Domain column name for the card id RefColumn text := TG_ARGV[3]; -- Domain column name for the reference id OldRefValue integer; NewRefValue integer; BEGIN RAISE DEBUG 'Trigger % on %', TG_NAME, TG_TABLE_NAME; IF (TG_OP = 'UPDATE') THEN -- EXECUTE 'SELECT ($1).' || quote_ident(AttributeName) INTO OldRefValue USING OLD; -- pg84 EXECUTE 'SELECT (' || quote_literal(OLD) || '::' || TG_RELID::regclass || ').' || quote_ident(AttributeName) INTO OldRefValue; END IF; -- EXECUTE 'SELECT ($1).' || quote_ident(AttributeName) INTO NewRefValue USING NEW; -- pg84 EXECUTE 'SELECT (' || quote_literal(NEW) || '::' || TG_RELID::regclass || ').' || quote_ident(AttributeName) INTO NewRefValue; IF (NewRefValue IS NOT NULL) THEN IF (OldRefValue IS NOT NULL) THEN IF (OldRefValue <> NewRefValue) THEN PERFORM _cm_update_relation(NEW."User", DomainId, CardColumn, NEW."Id", RefColumn, NewRefValue); END IF; ELSE PERFORM _cm_insert_relation(NEW."User", DomainId, CardColumn, NEW."Id", RefColumn, NewRefValue, TG_RELID); END IF; ELSE IF (OldRefValue IS NOT NULL) THEN PERFORM _cm_delete_relation(NEW."User", DomainId, CardColumn, NEW."Id"); END IF; END IF; RETURN NEW; END; $_$; 4DROP FUNCTION public._cm_trigger_update_relation(); publicpostgresfalse/1255233166_cm_trigger_when(smallint)FUNCTIONCREATE FUNCTION public._cm_trigger_when(tgtype smallint) RETURNS text LANGUAGE sql IMMUTABLE AS $_$ SELECT CASE $1 & cast(2 as int2) WHEN 0 THEN 'AFTER' ELSE 'BEFORE' END || ' ' || CASE $1 & cast(28 as int2) WHEN 16 THEN 'UPDATE' WHEN 8 THEN 'DELETE' WHEN 4 THEN 'INSERT' WHEN 20 THEN 'INSERT OR UPDATE' WHEN 28 THEN 'INSERT OR UPDATE OR DELETE' WHEN 24 THEN 'UPDATE OR DELETE' WHEN 12 THEN 'INSERT OR DELETE' END; $_$; 8DROP FUNCTION public._cm_trigger_when(tgtype smallint); publicpostgresfalse01255233167_cm_unique_index_id(oid, text)FUNCTIONCREATE FUNCTION public._cm_unique_index_id(tableid oid, attributename text) RETURNS oid LANGUAGE sql STABLE AS $_$ SELECT ( quote_ident(_cm_cmschema($1)) ||'.'|| quote_ident(_cm_unique_index_name($1, $2)) )::regclass::oid; $_$; KDROP FUNCTION public._cm_unique_index_id(tableid oid, attributename text); publicpostgresfalse11255233168 _cm_unique_index_name(oid, text)FUNCTIONCREATE FUNCTION public._cm_unique_index_name(tableid oid, attributename text) RETURNS text LANGUAGE sql STABLE AS $_$ SELECT '_Unique_'|| _cm_cmtable($1) ||'_'|| $2; $_$; MDROP FUNCTION public._cm_unique_index_name(tableid oid, attributename text); publicpostgresfalse212552331697_cm_update_reference(text, oid, text, integer, integer)FUNCTIONCREATE FUNCTION public._cm_update_reference(username text, tableid oid, attributename text, cardid integer, referenceid integer) RETURNS void LANGUAGE plpgsql AS $$ BEGIN EXECUTE 'UPDATE ' || TableId::regclass || ' SET ' || quote_ident(AttributeName) || ' = ' || coalesce(ReferenceId::text, 'NULL') || ', "User" = ' || coalesce(quote_literal(UserName),'NULL') || ' WHERE "Status"=''A'' AND "Id" = ' || CardId::text || ' AND coalesce(' || quote_ident(AttributeName) || ', 0) <> ' || coalesce(ReferenceId, 0)::text; END; $$; DROP FUNCTION public._cm_update_reference(username text, tableid oid, attributename text, cardid integer, referenceid integer); publicpostgresfalse31255233170,_cm_update_reference_trigger_name(oid, text)FUNCTIONCREATE FUNCTION public._cm_update_reference_trigger_name(reftableid oid, refattribute text) RETURNS text LANGUAGE sql IMMUTABLE AS $_$ SELECT '_UpdRef_'|| _cm_cmtable($1) ||'_'|| $2; $_$; [DROP FUNCTION public._cm_update_reference_trigger_name(reftableid oid, refattribute text); publicpostgresfalse41255233171<_cm_update_relation(text, oid, text, integer, text, integer)FUNCTIONCREATE FUNCTION public._cm_update_relation(username text, domainid oid, cardidcolumn text, cardid integer, refidcolumn text, refid integer) RETURNS void LANGUAGE plpgsql AS $$ DECLARE RefClassUpdatePart text; BEGIN -- Needed to update IdClassX (if the domain attributres are IdClass1/2) RefClassUpdatePart := coalesce( ', ' || quote_ident('IdClass'||substring(RefIdColumn from E'^IdObj(\\d)+')) || '=' || _cm_dest_reference_classid(DomainId, RefIdColumn, RefId), '' ); -- coalesce(quote_literal(UserName),'NULL') -> quote_nullable(UserName) -- pg84 EXECUTE 'UPDATE ' || DomainId::regclass || ' SET ' || quote_ident(RefIdColumn) || ' = ' || RefId || ', "User" = ' || coalesce(quote_literal(UserName),'NULL') || RefClassUpdatePart || ' WHERE "Status"=''A'' AND ' || quote_ident(CardIdColumn) || ' = ' || CardId || ' AND ' || quote_ident(RefIdColumn) || ' <> ' || RefId; END; $$; DROP FUNCTION public._cm_update_relation(username text, domainid oid, cardidcolumn text, cardid integer, refidcolumn text, refid integer); publicpostgresfalse1255233172+_cm_update_relation_trigger_name(oid, text)FUNCTIONCREATE FUNCTION public._cm_update_relation_trigger_name(reftableid oid, refattribute text) RETURNS text LANGUAGE sql IMMUTABLE AS $_$ SELECT '_UpdRel_'|| _cm_cmtable($1) ||'_'|| $2; $_$; ZDROP FUNCTION public._cm_update_relation_trigger_name(reftableid oid, refattribute text); publicpostgresfalse1255233173_cm_zero_rownum_sequence()FUNCTION CREATE FUNCTION public._cm_zero_rownum_sequence() RETURNS void LANGUAGE plpgsql AS $$ DECLARE temp BIGINT; BEGIN SELECT INTO temp setval('rownum', 0, true); EXCEPTION WHEN undefined_table THEN CREATE TEMPORARY SEQUENCE rownum MINVALUE 0 START 1; END $$; 1DROP FUNCTION public._cm_zero_rownum_sequence(); publicpostgresfalse51255233174_cmf_class_description(oid)FUNCTIONCREATE FUNCTION public._cmf_class_description(cid oid) RETURNS character varying LANGUAGE sql STABLE AS $_$ SELECT _cm_read_comment(_cm_comment_for_table_id($1), 'DESCR'); $_$; 6DROP FUNCTION public._cmf_class_description(cid oid); publicpostgresfalse61255233175_cmf_is_displayable(oid)FUNCTIONCREATE FUNCTION public._cmf_is_displayable(cid oid) RETURNS boolean LANGUAGE sql STABLE AS $_$ SELECT _cm_read_comment(_cm_comment_for_table_id($1), 'MODE') IN ('write','read','baseclass'); $_$; 3DROP FUNCTION public._cmf_is_displayable(cid oid); publicpostgresfalse71255233176I_graph_get_related_classes(character varying, character varying, integer)FUNCTIONCREATE FUNCTION public._graph_get_related_classes("DomainName" character varying, "ClassName" character varying, "CardId" integer, OUT type character varying, OUT total integer) RETURNS SETOF record LANGUAGE plpgsql AS $_$ BEGIN RETURN QUERY SELECT case when _cm_cmtable("IdClass2")::varchar=$2 then _cm_cmtable("IdClass1")::varchar else _cm_cmtable("IdClass2")::varchar end "type", count(*)::integer as "total" FROM "Map" WHERE "Status" = 'A' and _cm_cmtable("IdDomain")::varchar=$1 and (("IdObj1"=$3 and _cm_cmtable("IdClass1")::varchar=$2) or ("IdObj2"=$3 and _cm_cmtable("IdClass2")::varchar=$2)) group by 1; END $_$; DROP FUNCTION public._graph_get_related_classes("DomainName" character varying, "ClassName" character varying, "CardId" integer, OUT type character varying, OUT total integer); publicpostgresfalse00FUNCTION _graph_get_related_classes("DomainName" character varying, "ClassName" character varying, "CardId" integer, OUT type character varying, OUT total integer)COMMENTCOMMENT ON FUNCTION public._graph_get_related_classes("DomainName" character varying, "ClassName" character varying, "CardId" integer, OUT type character varying, OUT total integer) IS 'TYPE: function'; publicpostgresfalse184781255233177%cm_attribute_exists(text, text, text)FUNCTION3CREATE FUNCTION public.cm_attribute_exists(schemaname text, tablename text, attributename text, OUT attribute_exists boolean) RETURNS boolean LANGUAGE plpgsql AS $$ DECLARE attribute_name varchar; BEGIN SELECT attname into attribute_name FROM pg_attribute WHERE attrelid = (SELECT oid FROM pg_class WHERE relname = tablename AND relnamespace = (SELECT oid FROM pg_namespace WHERE nspname=schemaname)) AND attname = attributename; IF(attribute_name is not null) THEN attribute_exists = true; ELSE attribute_exists = false; END IF; END; $$; }DROP FUNCTION public.cm_attribute_exists(schemaname text, tablename text, attributename text, OUT attribute_exists boolean); publicpostgresfalse00oFUNCTION cm_attribute_exists(schemaname text, tablename text, attributename text, OUT attribute_exists boolean)COMMENTCOMMENT ON FUNCTION public.cm_attribute_exists(schemaname text, tablename text, attributename text, OUT attribute_exists boolean) IS 'TYPE: function'; publicpostgresfalse184891255233178.cm_class(anyelement, timestamp with time zone)FUNCTIONCREATE FUNCTION public.cm_class(anyelement, timestamp with time zone) RETURNS SETOF anyelement LANGUAGE plpgsql AS $_$ DECLARE classname varchar; fieldList text; datetime timestamp; sqlstring varchar; subsqlstring varchar; BEGIN select into classname replace(replace(pg_typeof($1)::text, '_history', ''), '"', ''); execute 'SELECT array_to_string(array(SELECT quote_ident(name) FROM _cm3_attribute_list(''"' || classname || '"''::regclass::oid) AS name),'','')' into fieldList; datetime = case when $2 = $2::date then $2 + interval '23 hours 59 minutes 59 seconds' else $2 end; sqlstring = 'SELECT ' || fieldList || ' FROM "' || classname || '" where "BeginDate" <= ''' || datetime || '''::timestamp and "' || classname || '"."Status" = ''A'''; if not _cm3_class_is_superclass(('"'||classname||'"')::regclass) then sqlstring = sqlstring || ' UNION SELECT ' || replace(fieldList, '"Id",', '"CurrentId",') || ' FROM "' || classname || '_history" where "BeginDate" <= ''' || datetime || '''::timestamp and "EndDate" >= ''' || datetime || '''::timestamp'; else subsqlstring = 'SELECT (replace(_cm_subtables_and_itself(inhrelid)::regclass::varchar, ''"'', '''')) FROM pg_inherits WHERE inhparent = ''' || pg_typeof($1) || '''::regclass::oid'; for classname in execute subsqlstring loop if not _cm3_class_is_superclass(('"'||classname||'"')::regclass) then sqlstring = sqlstring || ' UNION SELECT ' || replace(fieldList, '"Id",', '"CurrentId",') || ' FROM "' || classname || '_history" where "BeginDate" <= ''' || datetime || '''::timestamp and "EndDate" >= ''' || datetime || '''::timestamp'; end if; end loop; end if; raise notice 'QUERY STAMPATA: %', sqlstring; return query execute sqlstring; END; $_$; EDROP FUNCTION public.cm_class(anyelement, timestamp with time zone); publicpostgresfalse:1255233179Hcm_class(anyelement, timestamp with time zone, timestamp with time zone)FUNCTIONK CREATE FUNCTION public.cm_class(anyelement, timestamp with time zone, timestamp with time zone) RETURNS SETOF anyelement LANGUAGE plpgsql AS $_$ DECLARE classname varchar; fieldList text; datetime1 timestamp; datetime2 timestamp; sqlstring varchar; subsqlstring varchar; BEGIN select into classname replace(replace(pg_typeof($1)::text, '_history', ''), '"', ''); execute 'SELECT array_to_string(array(SELECT quote_ident(name) FROM _cm3_attribute_list(''"' || classname || '"''::regclass::oid) AS name),'','')' into fieldList; datetime1 = case when $2 = $2::date then $2 + interval '23 hours 59 minutes 59 seconds' else $2 end; datetime2 = case when $3 = $3::date then $3 + interval '23 hours 59 minutes 59 seconds' else $3 end; sqlstring = 'SELECT ' || fieldList || ' FROM "' || classname || '" where "BeginDate" <= ''' || datetime2 || '''::timestamp and "' || classname || '"."Status" = ''A'''; if not _cm3_class_is_superclass(('"'||classname||'"')::regclass) then sqlstring = sqlstring || ' UNION SELECT ' || replace(fieldList, '"Id",', '"CurrentId",') || ' FROM "' || classname || '_history" where ("BeginDate" <= ''' || datetime2 || '''::timestamp and "EndDate" >= ''' || datetime1 || '''::timestamp)'; else subsqlstring = 'SELECT (replace(_cm_subtables_and_itself(inhrelid)::regclass::varchar, ''"'', '''')) FROM pg_inherits WHERE inhparent = ''' || pg_typeof($1) || '''::regclass::oid'; for classname in execute subsqlstring loop if not _cm3_class_is_superclass(('"'||classname||'"')::regclass) then sqlstring = sqlstring || ' UNION SELECT ' || replace(fieldList, '"Id",', '"CurrentId",') || ' FROM "' || classname || '_history" where "BeginDate" <= ''' || datetime2 || '''::timestamp and "EndDate" >= ''' || datetime1 || '''::timestamp'; end if; end loop; end if; sqlstring = sqlstring || ' ORDER BY "Id", "BeginDate" DESC '; --ordino per Id (CurrentId), select distinct sull'Id per eliminare duplicati. Secondo attributo per l'ordinamento? BeginDate più alto? -- sqlstring = sqlstring || 'order by "Id"'; -- replace(fieldList, '"Id",', '"CurrentId",') || ' FROM --> replace(fieldList, '"Id",', '"CurrentId" AS "Id",') || ' FROM -- select distinct on "Id" all'inizio --raise notice 'QUERY STAMPATA: %', sqlstring; return query execute sqlstring; END; $_$; _DROP FUNCTION public.cm_class(anyelement, timestamp with time zone, timestamp with time zone); publicpostgresfalse;1255233180Bcm_create_attribute(oid, text, text, text, boolean, boolean, text)FUNCTIONCREATE FUNCTION public.cm_create_attribute(tableid oid, attributename text, sqltype text, attributedefault text, attributenotnull boolean, attributeunique boolean, attributecomment text) RETURNS void LANGUAGE plpgsql AS $$ BEGIN PERFORM _cm_check_attribute_comment_and_type(AttributeComment, SQLType); IF _cm_is_geometry_type(SQLType) THEN PERFORM _cm_add_spherical_mercator(); PERFORM AddGeometryColumn(_cm_cmschema(TableId), _cm_cmtable(TableId), AttributeName, 900913, SQLType, 2); ELSE EXECUTE 'ALTER TABLE '|| TableId::regclass ||' ADD COLUMN '|| quote_ident(AttributeName) ||' '|| SQLType; END IF; PERFORM _cm_set_attribute_default(TableId, AttributeName, AttributeDefault, TRUE); -- set the comment recursively (needs to be performed before unique and notnull, because they depend on the comment) PERFORM _cm_set_attribute_comment(TableId, AttributeName, AttributeComment); PERFORM _cm_attribute_set_notnull(TableId, AttributeName, AttributeNotNull); PERFORM _cm_attribute_set_uniqueness(TableId, AttributeName, AttributeUnique); PERFORM _cm_add_fk_constraints(TableId, AttributeName); PERFORM _cm_add_reference_handling(TableId, AttributeName); END; $$; DROP FUNCTION public.cm_create_attribute(tableid oid, attributename text, sqltype text, attributedefault text, attributenotnull boolean, attributeunique boolean, attributecomment text); publicpostgresfalse<1255233181 cm_create_class(text, oid, text)FUNCTION CREATE FUNCTION public.cm_create_class(cmclass text, parentid oid, classcomment text) RETURNS integer LANGUAGE plpgsql AS $$ DECLARE IsSimpleClass boolean := _cm_is_simpleclass_comment(ClassComment); TableId oid; BEGIN IF (IsSimpleClass AND ParentId IS NOT NULL) OR (NOT _cm_is_any_class_comment(ClassComment)) THEN RAISE EXCEPTION 'CM_FORBIDDEN_OPERATION'; END IF; -- TODO: Check if the superclass is a superclass PERFORM _cm_create_schema_if_needed(CMClass); DECLARE DBClassName text := _cm_table_dbname_unsafe(CMClass); InheritancePart text; AttributesPart text; BEGIN IF ParentId IS NULL THEN AttributesPart := ' "Id" integer NOT NULL DEFAULT _cm_new_card_id(), '; InheritancePart := ''; ELSE AttributesPart := ''; InheritancePart := ' INHERITS ('|| ParentId::regclass ||')'; END IF; EXECUTE 'CREATE TABLE '|| DBClassName || '('|| AttributesPart || ' CONSTRAINT '|| quote_ident(_cm_classpk_name(CMClass)) ||' PRIMARY KEY ("Id")'|| ')' || InheritancePart; EXECUTE 'COMMENT ON TABLE '|| DBClassName ||' IS '|| quote_literal(ClassComment); EXECUTE 'COMMENT ON COLUMN '|| DBClassName ||'."Id" IS '|| quote_literal('MODE: reserved'); TableId := _cm_table_id(CMClass); END; PERFORM _cm_copy_superclass_attribute_comments(TableId, ParentId); PERFORM _cm_create_class_triggers(TableId); IF ParentId IS NULL THEN PERFORM cm_create_attribute(TableId, 'IdClass', 'regclass', NULL, TRUE, FALSE, 'MODE: reserved'); IF NOT IsSimpleClass THEN PERFORM cm_create_attribute(TableId, 'Code', 'varchar(100)', NULL, FALSE, FALSE, 'MODE: read|DESCR: Code|INDEX: 1|BASEDSP: true'); PERFORM cm_create_attribute(TableId, 'Description', 'varchar(250)', NULL, FALSE, FALSE, 'MODE: read|DESCR: Description|INDEX: 2|BASEDSP: true'); -- Status is the only attribute needed PERFORM cm_create_attribute(TableId, 'Status', 'character(1)', NULL, FALSE, FALSE, 'MODE: reserved'); END IF; PERFORM cm_create_attribute(TableId, 'User', 'varchar(100)', NULL, FALSE, FALSE, 'MODE: reserved'); IF IsSimpleClass THEN PERFORM cm_create_attribute(TableId, 'BeginDate', 'timestamp', 'now()', TRUE, FALSE, 'MODE: write|FIELDMODE: read|BASEDSP: true'); ELSE PERFORM cm_create_attribute(TableId, 'BeginDate', 'timestamp', 'now()', TRUE, FALSE, 'MODE: reserved'); PERFORM cm_create_attribute(TableId, 'Notes', 'text', NULL, FALSE, FALSE, 'MODE: read|DESCR: Notes|INDEX: 3'); END IF; ELSE PERFORM _cm_propagate_superclass_triggers(TableId); END IF; IF IsSimpleClass THEN PERFORM _cm_create_index(TableId, 'BeginDate'); ELSE PERFORM _cm_create_class_indexes(TableId); IF NOT _cm_is_superclass_comment(ClassComment) THEN PERFORM _cm_create_class_history(CMClass); END IF; END IF; RETURN TableId::integer; END; $$; UDROP FUNCTION public.cm_create_class(cmclass text, parentid oid, classcomment text); publicpostgresfalse=1255233182!cm_create_class(text, text, text)FUNCTIONCREATE FUNCTION public.cm_create_class(cmclass text, cmparentclass text, classcomment text) RETURNS integer LANGUAGE sql AS $_$ SELECT cm_create_class($1, _cm_table_id($2), $3); $_$; [DROP FUNCTION public.cm_create_class(cmclass text, cmparentclass text, classcomment text); publicpostgresfalse>1255233183Icm_create_class_attribute(text, text, text, text, boolean, boolean, text)FUNCTION7CREATE FUNCTION public.cm_create_class_attribute(cmclass text, attributename text, sqltype text, attributedefault text, attributenotnull boolean, attributeunique boolean, attributecomment text) RETURNS void LANGUAGE sql AS $_$ SELECT cm_create_attribute(_cm_table_id($1), $2, $3, $4, $5, $6, $7); $_$; DROP FUNCTION public.cm_create_class_attribute(cmclass text, attributename text, sqltype text, attributedefault text, attributenotnull boolean, attributeunique boolean, attributecomment text); publicpostgresfalse?1255233184cm_create_domain(text, text)FUNCTIONCREATE FUNCTION public.cm_create_domain(cmdomain text, domaincomment text) RETURNS integer LANGUAGE plpgsql AS $$ DECLARE DomainId oid; HistoryDBName text := _cm_history_dbname_unsafe(_cm_domain_cmname(CMDomain)); BEGIN -- TODO: Add Creation of Map (from its name) EXECUTE 'CREATE TABLE '|| _cm_domain_dbname_unsafe(CMDomain) || ' (CONSTRAINT '|| quote_ident(_cm_domainpk_name(CMDomain)) || ' PRIMARY KEY ("IdDomain", "IdClass1", "IdObj1", "IdClass2", "IdObj2", "BeginDate"))'|| ' INHERITS ("Map")'; DomainId := _cm_domain_id(CMDomain); EXECUTE 'COMMENT ON TABLE '|| DomainId::regclass ||' IS '|| quote_literal(DomainComment); PERFORM _cm_copy_superclass_attribute_comments(DomainId, '"Map"'::regclass); EXECUTE 'CREATE TABLE '|| HistoryDBName || ' ( CONSTRAINT '|| quote_ident(_cm_historypk_name(_cm_domain_cmname(CMDomain))) || ' PRIMARY KEY ("IdDomain","IdClass1", "IdObj1", "IdClass2", "IdObj2","EndDate"))'|| ' INHERITS ('|| DomainId::regclass ||')'; EXECUTE 'ALTER TABLE '|| HistoryDBName ||' ALTER COLUMN "EndDate" SET DEFAULT now()'; PERFORM _cm_create_domain_indexes(DomainId); PERFORM _cm_create_domain_triggers(DomainId); RETURN DomainId; END $$; JDROP FUNCTION public.cm_create_domain(cmdomain text, domaincomment text); publicpostgresfalse@1255233185Jcm_create_domain_attribute(text, text, text, text, boolean, boolean, text)FUNCTION9CREATE FUNCTION public.cm_create_domain_attribute(cmclass text, attributename text, sqltype text, attributedefault text, attributenotnull boolean, attributeunique boolean, attributecomment text) RETURNS void LANGUAGE sql AS $_$ SELECT cm_create_attribute(_cm_domain_id($1), $2, $3, $4, $5, $6, $7); $_$; DROP FUNCTION public.cm_create_domain_attribute(cmclass text, attributename text, sqltype text, attributedefault text, attributenotnull boolean, attributeunique boolean, attributecomment text); publicpostgresfalseA1255233186cm_delete_attribute(oid, text)FUNCTIONCREATE FUNCTION public.cm_delete_attribute(tableid oid, attributename text) RETURNS void LANGUAGE plpgsql AS $$ DECLARE GeoType text := _cm_get_geometry_type(TableId, AttributeName); BEGIN IF NOT _cm_attribute_is_local(TableId, AttributeName) THEN RAISE EXCEPTION 'CM_FORBIDDEN_OPERATION'; END IF; IF NOT _cm_attribute_is_empty(TableId, AttributeName) THEN RAISE EXCEPTION 'CM_CONTAINS_DATA'; END IF; PERFORM _cm_remove_attribute_triggers(TableId, AttributeName); IF GeoType IS NOT NULL THEN PERFORM DropGeometryColumn(_cm_cmschema(TableId), _cm_cmtable(TableId), AttributeName); ELSE EXECUTE 'ALTER TABLE '|| TableId::regclass ||' DROP COLUMN '|| quote_ident(AttributeName) ||' CASCADE'; END IF; END; $$; KDROP FUNCTION public.cm_delete_attribute(tableid oid, attributename text); publicpostgresfalseB1255233187"cm_delete_card(integer, oid, text)FUNCTION|CREATE FUNCTION public.cm_delete_card(cardid integer, tableid oid, username text) RETURNS void LANGUAGE plpgsql AS $$ DECLARE ClassComment text := _cm_comment_for_table_id(TableId); IsSimpleClass boolean := _cm_is_simpleclass_comment(ClassComment); BEGIN IF IsSimpleClass THEN RAISE DEBUG 'deleting a card from a simple class'; EXECUTE 'DELETE FROM ' || TableId::regclass || ' WHERE "Id" = ' || CardId; ELSE RAISE DEBUG 'deleting a card from a standard class'; EXECUTE 'UPDATE ' || TableId::regclass || ' SET "User" = ''' || coalesce(UserName,'') || ''', "Status" = ''N'' WHERE "Id" = ' || CardId; END IF; END; $$; QDROP FUNCTION public.cm_delete_card(cardid integer, tableid oid, username text); publicpostgresfalseC1255233188cm_delete_class(oid)FUNCTIONCREATE FUNCTION public.cm_delete_class(tableid oid) RETURNS void LANGUAGE plpgsql AS $$ BEGIN IF _cm_class_has_domains(TableId) THEN RAISE EXCEPTION 'CM_HAS_DOMAINS'; ELSEIF _cm_class_has_children(TableId) THEN RAISE EXCEPTION 'CM_HAS_CHILDREN'; ELSEIF NOT _cm_table_is_empty(TableId) THEN RAISE EXCEPTION 'CM_CONTAINS_DATA'; END IF; PERFORM _cm_delete_local_attributes(TableId); -- Cascade for the history table EXECUTE 'DROP TABLE '|| TableId::regclass ||' CASCADE'; END; $$; 3DROP FUNCTION public.cm_delete_class(tableid oid); publicpostgresfalseD1255233189cm_delete_class(text)FUNCTIONCREATE FUNCTION public.cm_delete_class(cmclass text) RETURNS void LANGUAGE sql AS $_$ SELECT cm_delete_class(_cm_table_id($1)); $_$; 4DROP FUNCTION public.cm_delete_class(cmclass text); publicpostgresfalseE1255233190%cm_delete_class_attribute(text, text)FUNCTIONCREATE FUNCTION public.cm_delete_class_attribute(cmclass text, attributename text) RETURNS void LANGUAGE sql AS $_$ SELECT cm_delete_attribute(_cm_table_id($1), $2); $_$; RDROP FUNCTION public.cm_delete_class_attribute(cmclass text, attributename text); publicpostgresfalseF1255233191cm_delete_domain(oid)FUNCTION5CREATE FUNCTION public.cm_delete_domain(domainid oid) RETURNS void LANGUAGE plpgsql AS $$ BEGIN IF NOT _cm_table_is_empty(DomainId) THEN RAISE EXCEPTION 'CM_CONTAINS_DATA'; END IF; PERFORM _cm_delete_local_attributes(DomainId); EXECUTE 'DROP TABLE '|| DomainId::regclass ||' CASCADE'; END $$; 5DROP FUNCTION public.cm_delete_domain(domainid oid); publicpostgresfalseG1255233192cm_delete_domain(text)FUNCTIONCREATE FUNCTION public.cm_delete_domain(cmdomain text) RETURNS void LANGUAGE sql AS $_$ SELECT cm_delete_domain(_cm_domain_id($1)); $_$; 6DROP FUNCTION public.cm_delete_domain(cmdomain text); publicpostgresfalseH1255233193&cm_delete_domain_attribute(text, text)FUNCTIONCREATE FUNCTION public.cm_delete_domain_attribute(cmclass text, attributename text) RETURNS void LANGUAGE sql AS $_$ SELECT cm_delete_attribute(_cm_domain_id($1), $2); $_$; SDROP FUNCTION public.cm_delete_domain_attribute(cmclass text, attributename text); publicpostgresfalseI1255233194Bcm_modify_attribute(oid, text, text, text, boolean, boolean, text)FUNCTIONCREATE FUNCTION public.cm_modify_attribute(tableid oid, attributename text, sqltype text, attributedefault text, attributenotnull boolean, attributeunique boolean, newcomment text) RETURNS void LANGUAGE plpgsql AS $$ DECLARE OldComment text := _cm_comment_for_attribute(TableId, AttributeName); BEGIN IF COALESCE(_cm_read_reference_domain_comment(OldComment), '') IS DISTINCT FROM COALESCE(_cm_read_reference_domain_comment(NewComment), '') OR _cm_read_reference_type_comment(OldComment) IS DISTINCT FROM _cm_read_reference_type_comment(NewComment) OR COALESCE(_cm_get_fk_target_comment(OldComment), '') IS DISTINCT FROM COALESCE(_cm_get_fk_target_comment(NewComment), '') THEN RAISE EXCEPTION 'CM_FORBIDDEN_OPERATION'; END IF; PERFORM _cm_check_attribute_comment_and_type(NewComment, SQLType); IF _cm_get_attribute_sqltype(TableId, AttributeName) <> trim(SQLType) THEN IF _cm_attribute_is_inherited(TableId, AttributeName) THEN RAISE NOTICE 'Not altering column type'; -- Fail silently --RAISE EXCEPTION 'CM_FORBIDDEN_OPERATION'; ELSE EXECUTE 'ALTER TABLE '|| TableId::regclass ||' ALTER COLUMN '|| quote_ident(AttributeName) ||' TYPE '|| SQLType; END IF; END IF; PERFORM _cm_attribute_set_uniqueness(TableId, AttributeName, AttributeUnique); PERFORM _cm_attribute_set_notnull(TableId, AttributeName, AttributeNotNull); PERFORM _cm_set_attribute_default(TableId, AttributeName, AttributeDefault, FALSE); PERFORM _cm_set_attribute_comment(TableId, AttributeName, NewComment); END; $$; DROP FUNCTION public.cm_modify_attribute(tableid oid, attributename text, sqltype text, attributedefault text, attributenotnull boolean, attributeunique boolean, newcomment text); publicpostgresfalseK1255233195Lcm_modify_attribute(oid, text, text, text, boolean, boolean, text[], text[])FUNCTION CREATE FUNCTION public.cm_modify_attribute(tableid oid, attributename text, sqltype text, attributedefault text, attributenotnull boolean, attributeunique boolean, commentparts text[], classes text[]) RETURNS void LANGUAGE plpgsql AS $$ DECLARE OldComment text := _cm_comment_for_attribute(TableId, AttributeName); -- creates full new comment string for consistency checks NewComment text := _cm_comment_add_parts(_cm_comment_set_parts(OldComment, commentparts), commentparts, true); subClassId oid; _classes text[] := COALESCE(classes, ARRAY[]::text[]); BEGIN IF COALESCE(_cm_read_reference_domain_comment(OldComment), '') IS DISTINCT FROM COALESCE(_cm_read_reference_domain_comment(NewComment), '') OR _cm_read_reference_type_comment(OldComment) IS DISTINCT FROM _cm_read_reference_type_comment(NewComment) OR COALESCE(_cm_get_fk_target_comment(OldComment), '') IS DISTINCT FROM COALESCE(_cm_get_fk_target_comment(NewComment), '') THEN RAISE EXCEPTION 'CM_FORBIDDEN_OPERATION'; END IF; PERFORM _cm_check_attribute_comment_and_type(NewComment, SQLType); IF _cm_get_attribute_sqltype(TableId, AttributeName) <> trim(SQLType) THEN IF _cm_attribute_is_inherited(TableId, AttributeName) THEN RAISE NOTICE 'Not altering column type'; -- Fail silently --RAISE EXCEPTION 'CM_FORBIDDEN_OPERATION'; ELSE EXECUTE 'ALTER TABLE '|| TableId::regclass ||' ALTER COLUMN '|| quote_ident(AttributeName) ||' TYPE '|| SQLType; END IF; END IF; PERFORM _cm_attribute_set_uniqueness(TableId, AttributeName, AttributeUnique); PERFORM _cm_attribute_set_notnull(TableId, AttributeName, AttributeNotNull); PERFORM _cm_set_attribute_default(TableId, AttributeName, AttributeDefault, FALSE); -- updates comment according to specified tables (empty means all) FOR subClassId IN SELECT _cm_subtables_and_itself(tableid) LOOP IF (COALESCE(array_length(_classes, 1),0) = 0) OR (_classes @> ARRAY[replace(subClassId::regclass::text, '"', '')]) THEN OldComment = _cm_comment_for_attribute(subClassId, AttributeName); NewComment = _cm_comment_add_parts(_cm_comment_set_parts(OldComment, commentparts), commentparts, true); EXECUTE 'COMMENT ON COLUMN '|| subClassId::regclass ||'.'|| quote_ident(AttributeName) ||' IS '|| quote_literal(NewComment); END IF; END LOOP; END; $$; DROP FUNCTION public.cm_modify_attribute(tableid oid, attributename text, sqltype text, attributedefault text, attributenotnull boolean, attributeunique boolean, commentparts text[], classes text[]); publicpostgresfalseL1255233196cm_modify_class(oid, text)FUNCTIONCREATE FUNCTION public.cm_modify_class(tableid oid, newcomment text) RETURNS void LANGUAGE plpgsql AS $$ DECLARE OldComment text := _cm_comment_for_table_id(TableId); BEGIN IF _cm_is_superclass_comment(OldComment) <> _cm_is_superclass_comment(NewComment) OR _cm_get_type_comment(OldComment) <> _cm_get_type_comment(NewComment) THEN RAISE EXCEPTION 'CM_FORBIDDEN_OPERATION'; END IF; EXECUTE 'COMMENT ON TABLE ' || TableId::regclass || ' IS ' || quote_literal(NewComment); END; $$; DDROP FUNCTION public.cm_modify_class(tableid oid, newcomment text); publicpostgresfalseM1255233197cm_modify_class(text, text)FUNCTIONCREATE FUNCTION public.cm_modify_class(cmclass text, newcomment text) RETURNS void LANGUAGE sql AS $_$ SELECT cm_modify_class(_cm_table_id($1), $2); $_$; EDROP FUNCTION public.cm_modify_class(cmclass text, newcomment text); publicpostgresfalseN1255233198Icm_modify_class_attribute(text, text, text, text, boolean, boolean, text)FUNCTION7CREATE FUNCTION public.cm_modify_class_attribute(cmclass text, attributename text, sqltype text, attributedefault text, attributenotnull boolean, attributeunique boolean, attributecomment text) RETURNS void LANGUAGE sql AS $_$ SELECT cm_modify_attribute(_cm_table_id($1), $2, $3, $4, $5, $6, $7); $_$; DROP FUNCTION public.cm_modify_class_attribute(cmclass text, attributename text, sqltype text, attributedefault text, attributenotnull boolean, attributeunique boolean, attributecomment text); publicpostgresfalseO1255233199cm_modify_domain(oid, text)FUNCTIONCREATE FUNCTION public.cm_modify_domain(domainid oid, newcomment text) RETURNS void LANGUAGE plpgsql AS $$ DECLARE OldComment text := _cm_comment_for_table_id(DomainId); BEGIN IF _cm_read_domain_cardinality(OldComment) <> _cm_read_domain_cardinality(NewComment) OR _cm_read_comment(OldComment, 'CLASS1') <> _cm_read_comment(NewComment, 'CLASS1') OR _cm_read_comment(OldComment, 'CLASS2') <> _cm_read_comment(NewComment, 'CLASS2') OR _cm_get_type_comment(OldComment) <> _cm_get_type_comment(NewComment) THEN RAISE EXCEPTION 'CM_FORBIDDEN_OPERATION'; END IF; -- Check that the cardinality does not change EXECUTE 'COMMENT ON TABLE '|| DomainId::regclass || ' IS '|| quote_literal(NewComment); END $$; FDROP FUNCTION public.cm_modify_domain(domainid oid, newcomment text); publicpostgresfalseP1255233200cm_modify_domain(text, text)FUNCTIONCREATE FUNCTION public.cm_modify_domain(cmdomain text, domaincomment text) RETURNS void LANGUAGE sql AS $_$ SELECT cm_modify_domain(_cm_domain_id($1), $2); $_$; JDROP FUNCTION public.cm_modify_domain(cmdomain text, domaincomment text); publicpostgresfalseQ1255233201Jcm_modify_domain_attribute(text, text, text, text, boolean, boolean, text)FUNCTION9CREATE FUNCTION public.cm_modify_domain_attribute(cmclass text, attributename text, sqltype text, attributedefault text, attributenotnull boolean, attributeunique boolean, attributecomment text) RETURNS void LANGUAGE sql AS $_$ SELECT cm_modify_attribute(_cm_domain_id($1), $2, $3, $4, $5, $6, $7); $_$; DROP FUNCTION public.cm_modify_domain_attribute(cmclass text, attributename text, sqltype text, attributedefault text, attributenotnull boolean, attributeunique boolean, attributecomment text); publicpostgresfalseR1255233202-cmf_active_cards_for_class(character varying)FUNCTIONCREATE FUNCTION public.cmf_active_cards_for_class("ClassName" character varying, OUT "Class" character varying, OUT "Number" integer) RETURNS SETOF record LANGUAGE plpgsql AS $_$ BEGIN RETURN QUERY EXECUTE 'SELECT _cmf_class_description("IdClass") AS "ClassDescription", COUNT(*)::integer AS "CardCount"' || ' FROM ' || quote_ident($1) || ' WHERE' || ' "Status" = ' || quote_literal('A') || ' AND _cmf_is_displayable("IdClass")' || ' AND "IdClass" not IN (SELECT _cm_subtables_and_itself(_cm_table_id(' || quote_literal('Activity') || ')))' ' GROUP BY "IdClass"' || ' ORDER BY "ClassDescription"'; END $_$; DROP FUNCTION public.cmf_active_cards_for_class("ClassName" character varying, OUT "Class" character varying, OUT "Number" integer); publicpostgresfalse00wFUNCTION cmf_active_cards_for_class("ClassName" character varying, OUT "Class" character varying, OUT "Number" integer)COMMENTCOMMENT ON FUNCTION public.cmf_active_cards_for_class("ClassName" character varying, OUT "Class" character varying, OUT "Number" integer) IS 'TYPE: function'; publicpostgresfalse1874S1255233203)cmf_count_active_cards(character varying)FUNCTION CREATE FUNCTION public.cmf_count_active_cards("ClassName" character varying, OUT "Count" integer) RETURNS integer LANGUAGE plpgsql AS $$ BEGIN EXECUTE 'SELECT count(*) FROM '|| quote_ident("ClassName") ||' WHERE "Status" like ''A''' INTO "Count"; END $$; aDROP FUNCTION public.cmf_count_active_cards("ClassName" character varying, OUT "Count" integer); publicpostgresfalse00SFUNCTION cmf_count_active_cards("ClassName" character varying, OUT "Count" integer)COMMENT{COMMENT ON FUNCTION public.cmf_count_active_cards("ClassName" character varying, OUT "Count" integer) IS 'TYPE: function'; publicpostgresfalse1875T1255233204&cmf_incidentmgt_average_closing_time()FUNCTIONCREATE FUNCTION public.cmf_incidentmgt_average_closing_time(OUT period character varying, OUT duration numeric) RETURNS SETOF record LANGUAGE plpgsql AS $$ BEGIN RETURN QUERY select to_char(now() - '1 month'::interval * i, 'YYYY-MM')::varchar, avg(("TTHDClassification"+"TTHDAnalysis"+"TTHDExecution"+"TTHDStartCM"+"TTHDSuspension"+"TTHDClosure"+"TTSPClassification"+"TTSPAnalysis"+"TTSPExecution"+"TTSPStartCM"+"TTSPSuspension"+"TTSPClosure")/3600000)::numeric(6,2) as total FROM generate_series(0,11) i left outer join ("IncidentMgt" join "LookUp" on "LookUp"."Id" = "IncidentMgt"."FlowStatus" and "LookUp"."Code" = 'closed.completed') on "IncidentMgt"."ClosureTimestamp" between date_trunc('month', now() - '1 month'::interval * i) and date_trunc('month', now() - '1 month'::interval * i) + '1 month'::interval - '1 sec'::interval and "IncidentMgt"."Status" = 'A' group by to_char(now() - '1 month'::interval * i, 'YYYY-MM') order by 1; END $$; oDROP FUNCTION public.cmf_incidentmgt_average_closing_time(OUT period character varying, OUT duration numeric); publicpostgresfalse00aFUNCTION cmf_incidentmgt_average_closing_time(OUT period character varying, OUT duration numeric)COMMENTCOMMENT ON FUNCTION public.cmf_incidentmgt_average_closing_time(OUT period character varying, OUT duration numeric) IS 'TYPE: function'; publicpostgresfalse1876U1255233205,cmf_incidentmgt_for_status(integer, integer)FUNCTION:CREATE FUNCTION public.cmf_incidentmgt_for_status(year integer, month integer, OUT status character varying, OUT number integer) RETURNS SETOF record LANGUAGE plpgsql AS $$ DECLARE today timestamp without time zone; BEGIN today = now(); RETURN QUERY select coalesce(l2."Description",'Not available') as status, count(*)::integer from "IncidentMgt" as imgt left join "LookUp" l1 on l1."Id" = imgt."FlowStatus" and l1."Status"='A' left join "LookUp" l2 on l2."Id" = imgt."ProcessStatus" and l2."Status"='A' where imgt."Status" = 'A' and l1."Code" in ('closed.completed','open.running') and case when year is not null then date_part('year', imgt."BeginDate")::varchar = year::varchar else date_part('year', imgt."BeginDate")::varchar = date_part('year', today)::varchar end and case when month is not null then date_part('month', imgt."BeginDate")::varchar = month::varchar else date_part('month', imgt."BeginDate")::varchar = date_part('month', today)::varchar end group by status order by 1; END $$; DROP FUNCTION public.cmf_incidentmgt_for_status(year integer, month integer, OUT status character varying, OUT number integer); publicpostgresfalse00rFUNCTION cmf_incidentmgt_for_status(year integer, month integer, OUT status character varying, OUT number integer)COMMENTCOMMENT ON FUNCTION public.cmf_incidentmgt_for_status(year integer, month integer, OUT status character varying, OUT number integer) IS 'TYPE: function'; publicpostgresfalse1877W1255233206cmf_warrantycheck()FUNCTIONCREATE FUNCTION public.cmf_warrantycheck(OUT "Asset type" character varying, OUT "Code" character varying, OUT "Description" character varying, OUT "Warranty expiration" character varying, OUT "Missing days" integer) RETURNS SETOF record LANGUAGE plpgsql AS $$ DECLARE WarrantyExpiringDays integer; BEGIN select into WarrantyExpiringDays "Parameter"."Value"::integer from "Parameter" where "Parameter"."Code" = 'CMDBuildViews-WarrantyExpiringDays' and "Status" = 'A'; return query select _cm3_class_features_get("Hardware"."IdClass", 'DESCR') as "AssetType", "Hardware"."Code", "Hardware"."Description", to_char("Hardware"."WarrantyEnd", 'DD/MM/YYYY')::character varying, (date_part('day', "Hardware"."WarrantyEnd" - now()) + 1)::integer from "Hardware" where "Hardware"."WarrantyEnd" is not null and date_part('day', "Hardware"."WarrantyEnd" - now()) + 1 between 0 and WarrantyExpiringDays and "Status" = 'A' order by 1,2,3,4; END $$; DROP FUNCTION public.cmf_warrantycheck(OUT "Asset type" character varying, OUT "Code" character varying, OUT "Description" character varying, OUT "Warranty expiration" character varying, OUT "Missing days" integer); publicpostgresfalse00FUNCTION cmf_warrantycheck(OUT "Asset type" character varying, OUT "Code" character varying, OUT "Description" character varying, OUT "Warranty expiration" character varying, OUT "Missing days" integer)COMMENTCOMMENT ON FUNCTION public.cmf_warrantycheck(OUT "Asset type" character varying, OUT "Code" character varying, OUT "Description" character varying, OUT "Warranty expiration" character varying, OUT "Missing days" integer) IS 'TYPE: function'; publicpostgresfalse1879X1255233207/cmwf_getRolesForUserExtended(character varying)FUNCTIONJCREATE FUNCTION public."cmwf_getRolesForUserExtended"(userid character varying, OUT gruppo bigint) RETURNS SETOF bigint LANGUAGE sql AS $_$ select r."Id" from "Role" r join "Map_UserRole" ur on ur."IdObj2"=r."Id" and ur."IdObj1"::varchar=$1 and ur."Status"='A' where r."Code" not in ('Guest','SuperUser') and r."Status"='A' union select r."Id" from "Role" r join "User" on "User"."Id"::varchar=$1 where r."Code" not in ('Guest','SuperUser') and r."Status"='A' and ("User"."Description" = 'admin' OR "User"."Description" = 'Administrator') union select 0; $_$; bDROP FUNCTION public."cmwf_getRolesForUserExtended"(userid character varying, OUT gruppo bigint); publicpostgresfalse00TFUNCTION "cmwf_getRolesForUserExtended"(userid character varying, OUT gruppo bigint)COMMENT|COMMENT ON FUNCTION public."cmwf_getRolesForUserExtended"(userid character varying, OUT gruppo bigint) IS 'TYPE: function'; publicpostgresfalse1880Y1255233208?cp_slacount(timestamp with time zone, timestamp with time zone)FUNCTION CREATE FUNCTION public.cp_slacount(start_date timestamp with time zone, end_date timestamp with time zone, OUT sla_result integer[]) RETURNS integer[] LANGUAGE plpgsql AS $$ DECLARE today timestamp with time zone; slaobj_resolution bigint = (select "Id" from "LookUp" where "Type"='SLA - Object' and "Code"='resolution' and "Status"='A'); slaobj_takecharge bigint = (select "Id" from "LookUp" where "Type"='SLA - Object' and "Code"='charge' and "Status"='A'); slaobj_nbd bigint = (select "Id" from "LookUp" where "Type"='SLA - ThresholdType' and "Code"='NBD' and "Status"='A'); slaobj_imtype bigint = (select "Id" from "LookUp" where "Type"='ITProcessClassification - Workflow' and "Code"='IM' and "Status"='A'); server_url varchar = (select "Value" from "Parameter" where "Code"='Server-URL' and "Status"='A'); BEGIN --RETURN QUERY select array[sum( CASE WHEN (subq.imstatus = 'New' and sla_type_charge = slaobj_nbd and today>=slalimit ) or (subq.imstatus = 'New' and sla_type_charge <> slaobj_nbd and slatime_charge>=totaltime) or (subq.imstatus <> 'New' and sla_type_resolution = slaobj_nbd and today>=slalimit ) or (subq.imstatus <> 'New' and sla_type_resolution <> slaobj_nbd and slatime_resolution>=totaltime ) THEN 1 else (case when sla_type_charge is null and sla_type_resolution is null then 1 else 0 end) end )::integer, sum( CASE WHEN (subq.imstatus = 'New' and sla_type_charge = slaobj_nbd and today slaobj_nbd and slatime_charge=slalimit ) and (subq.imstatus = 'New' and sla_type_charge <> slaobj_nbd and slatime_charge>=totaltime) and (case when sla_type_resolution = slaobj_nbd then today 'New' and (case when sla_type_resolution = slaobj_nbd then today= from_date AND "CreationTimestamp"::date <= to_date AND CASE WHEN (select * from public.cp_ticketssummary_filter(username, usergroup, multigroup)) NOT IN (select "Id" FROM "Role" where "Code" = 'SuperUser' AND "Status" = 'A') THEN "CurrentRole" IN (select * from public.cp_ticketssummary_filter(username, usergroup, multigroup)) ELSE true END AND "Status" = 'A'); inExecutionNumber = (select count("Id") FROM "ITProc" Where "ShortStatus" IN (select "Id" FROM "LookUp" where "Type" = 'ITProc - ShortStatus' AND "Code" IN ('EXE', 'StartCM', 'Analysis') AND "Status" = 'A') AND "FlowStatus" = (SELECT "Id" FROM "LookUp" WHERE "Type" = 'FlowStatus' AND "Code" = 'open.running' AND "Status" = 'A') AND "CreationTimestamp"::date >= from_date AND "CreationTimestamp"::date <= to_date AND CASE WHEN (select * from public.cp_ticketssummary_filter(username, usergroup, multigroup)) NOT IN (select "Id" FROM "Role" where "Code" = 'SuperUser' AND "Status" = 'A') THEN "CurrentRole" IN (select * from public.cp_ticketssummary_filter(username, usergroup, multigroup)) ELSE true END AND "Status" = 'A'); toCloseNumber = (select count("Id") FROM "ITProc" Where "ShortStatus" = (select "Id" FROM "LookUp" where "Type" = 'ITProc - ShortStatus' AND "Code" = 'CLO' AND "Status" = 'A') AND "FlowStatus" = (SELECT "Id" FROM "LookUp" WHERE "Type" = 'FlowStatus' AND "Code" = 'open.running' AND "Status" = 'A') AND "CreationTimestamp"::date >= from_date AND "CreationTimestamp"::date <= to_date AND CASE WHEN (select * from public.cp_ticketssummary_filter(username, usergroup, multigroup)) NOT IN (select "Id" FROM "Role" where "Code" = 'SuperUser' AND "Status" = 'A') THEN "CurrentRole" IN (select * from public.cp_ticketssummary_filter(username, usergroup, multigroup)) ELSE true END AND "Status" = 'A'); suspendedNumber = (select count("Id") FROM "ITProc" Where "ShortStatus" = (select "Id" FROM "LookUp" where "Type" = 'ITProc - ShortStatus' AND "Code" = 'SUSP' AND "Status" = 'A') AND "FlowStatus" = (SELECT "Id" FROM "LookUp" WHERE "Type" = 'FlowStatus' AND "Code" = 'open.running' AND "Status" = 'A') AND "CreationTimestamp"::date >= from_date AND "CreationTimestamp"::date <= to_date AND CASE WHEN (select * from public.cp_ticketssummary_filter(username, usergroup, multigroup)) NOT IN (select "Id" FROM "Role" where "Code" = 'SuperUser' AND "Status" = 'A') THEN "CurrentRole" IN (select * from public.cp_ticketssummary_filter(username, usergroup, multigroup)) ELSE true END AND "Status" = 'A'); approvalNumber = (select count("Id") FROM "ITProc" Where "ShortStatus" = (select "Id" FROM "LookUp" where "Type" = 'ITProc - ShortStatus' AND "Code" = 'APP' AND "Status" = 'A') AND "FlowStatus" = (SELECT "Id" FROM "LookUp" WHERE "Type" = 'FlowStatus' AND "Code" = 'open.running' AND "Status" = 'A') AND "CreationTimestamp"::date >= from_date AND "CreationTimestamp"::date <= to_date AND CASE WHEN (select * from public.cp_ticketssummary_filter(username, usergroup, multigroup)) NOT IN (select "Id" FROM "Role" where "Code" = 'SuperUser' AND "Status" = 'A') THEN "CurrentRole" IN (select * from public.cp_ticketssummary_filter(username, usergroup, multigroup)) ELSE true END AND "Status" = 'A'); RETURN QUERY SELECT unnest(ARRAY[takeChargeDescr, inExecutionDescr, toCloseDescr, suspendedDescr, approvalDescr]) ticket_type, unnest(ARRAY[takeChargeNumber, inExecutionNumber, toCloseNumber, suspendedNumber, approvalNumber]) tickets_number; END; $$; DROP FUNCTION public.cp_ticketsstatus_chart(username character varying, usergroup character varying, multigroup boolean, session_lang character varying, from_date date, to_date date, OUT ticket_type character varying, OUT tickets_number integer); publicpostgresfalse00FUNCTION cp_ticketsstatus_chart(username character varying, usergroup character varying, multigroup boolean, session_lang character varying, from_date date, to_date date, OUT ticket_type character varying, OUT tickets_number integer)COMMENTCOMMENT ON FUNCTION public.cp_ticketsstatus_chart(username character varying, usergroup character varying, multigroup boolean, session_lang character varying, from_date date, to_date date, OUT ticket_type character varying, OUT tickets_number integer) IS 'TYPE: function'; publicpostgresfalse1883\1255233212Ecp_ticketssummary_data(character varying, character varying, boolean)FUNCTIONCREATE FUNCTION public.cp_ticketssummary_data(username character varying, usergroup character varying, multigroup boolean, OUT operator_description character varying, OUT organizational_unit character varying, OUT open_tickets integer, OUT assigned_to_me_tickets integer, OUT assigned_to_group_tickets integer, OUT sla_tickets integer, OUT incident_tickets integer, OUT request_tickets integer, OUT problem_tickets integer) RETURNS record LANGUAGE plpgsql AS $$ DECLARE employee_description character varying = (SELECT emp."Description" FROM "InternalEmployee" emp JOIN "User" usr ON usr."Email" = emp."Email" AND usr."Username" = username AND usr."Status" = 'A' WHERE emp."Status" = 'A'); BEGIN IF employee_description is null THEN SELECT "Description" FROM "User" WHERE "Username" = username AND "Status" = 'A' INTO operator_description; ELSE SELECT employee_description INTO operator_description; END IF; -- organizational_unit SELECT ou."Name" FROM "OU" ou JOIN "InternalEmployee" emp ON emp."OU" = ou."Id" AND emp."Status" = 'A' JOIN "User" usr ON usr."Email" = emp."Email" AND usr."Username" = username AND usr."Status" = 'A' WHERE ou."Status" = 'A' INTO organizational_unit; -- open_tickets SELECT COUNT("Id") FROM "ITProc" WHERE "FlowStatus" = (SELECT "Id" from "LookUp" where "Type" = 'FlowStatus' AND "Code" = 'open.running' AND "Status" = 'A') AND CASE WHEN (select * from public.cp_ticketssummary_filter(username, usergroup, multigroup)) NOT IN (select "Id" FROM "Role" where "Code" = 'SuperUser' AND "Status" = 'A') THEN "CurrentRole" IN (select * from public.cp_ticketssummary_filter(username, usergroup, multigroup)) ELSE true END AND "Status" = 'A' INTO open_tickets; -- assigned_to_me_tickets SELECT COUNT("Id") FROM "ITProc" WHERE "SuggOperator" = (select "Id" from "User" WHere "Username" = username AND "Status" = 'A') AND "Status" = 'A' AND "FlowStatus" = (SELECT "Id" FROM "LookUp" WHERE "Type" = 'FlowStatus' AND "Code" = 'open.running' AND "Status" = 'A') INTO assigned_to_me_tickets; -- assigned_to_group_tickets SElect COUNT("Id") FROM "ITProc" WHERE "CurrentRole" IN (select * from public.cp_ticketssummary_filter(username, usergroup, multigroup)) AND "Status" = 'A' AND "FlowStatus" = (SELECT "Id" FROM "LookUp" WHERE "Type" = 'FlowStatus' AND "Code" = 'open.running' AND "Status" = 'A') INTO assigned_to_group_tickets; -- sla_tickets SELECT 2 INTO sla_tickets; -- incident_tickets SELECT COUNT("Id") FROM "ITProc" WHERE "IdClass" = '"IncidentMgt"'::regclass AND "FlowStatus" = (SELECT "Id" FROM "LookUp" WHERE "Type" = 'FlowStatus' AND "Code" = 'open.running' AND "Status" = 'A') AND CASE WHEN (select * from public.cp_ticketssummary_filter(username, usergroup, multigroup)) NOT IN (select "Id" FROM "Role" where "Code" = 'SuperUser' AND "Status" = 'A') THEN "CurrentRole" IN (select * from public.cp_ticketssummary_filter(username, usergroup, multigroup)) ELSE true END AND "Status" = 'A' INTO incident_tickets; -- request_tickets SELECT COUNT("Id") FROM "ITProc" WHERE "IdClass" = '"ReqFulfil"'::regclass AND "FlowStatus" = (SELECT "Id" FROM "LookUp" WHERE "Type" = 'FlowStatus' AND "Code" = 'open.running' AND "Status" = 'A') AND CASE WHEN (select * from public.cp_ticketssummary_filter(username, usergroup, multigroup)) NOT IN (select "Id" FROM "Role" where "Code" = 'SuperUser' AND "Status" = 'A') THEN "CurrentRole" IN (select * from public.cp_ticketssummary_filter(username, usergroup, multigroup)) ELSE true END AND "Status" = 'A' INTO request_tickets; -- problem_tickets SELECT COUNT("Id") FROM "ITProc" WHERE "IdClass" = '"ProblemMgt"'::regclass and "Status" = 'A' AND "FlowStatus" = (SELECT "Id" FROM "LookUp" WHERE "Type" = 'FlowStatus' AND "Code" = 'open.running' AND "Status" = 'A') AND CASE WHEN (select * from public.cp_ticketssummary_filter(username, usergroup, multigroup)) NOT IN (select "Id" FROM "Role" where "Code" = 'SuperUser' AND "Status" = 'A') THEN "CurrentRole" IN (select * from public.cp_ticketssummary_filter(username, usergroup, multigroup)) ELSE true END AND "Status" = 'A' INTO problem_tickets; END; $$; DROP FUNCTION public.cp_ticketssummary_data(username character varying, usergroup character varying, multigroup boolean, OUT operator_description character varying, OUT organizational_unit character varying, OUT open_tickets integer, OUT assigned_to_me_tickets integer, OUT assigned_to_group_tickets integer, OUT sla_tickets integer, OUT incident_tickets integer, OUT request_tickets integer, OUT problem_tickets integer); publicpostgresfalse00FUNCTION cp_ticketssummary_data(username character varying, usergroup character varying, multigroup boolean, OUT operator_description character varying, OUT organizational_unit character varying, OUT open_tickets integer, OUT assigned_to_me_tickets integer, OUT assigned_to_group_tickets integer, OUT sla_tickets integer, OUT incident_tickets integer, OUT request_tickets integer, OUT problem_tickets integer)COMMENTCOMMENT ON FUNCTION public.cp_ticketssummary_data(username character varying, usergroup character varying, multigroup boolean, OUT operator_description character varying, OUT organizational_unit character varying, OUT open_tickets integer, OUT assigned_to_me_tickets integer, OUT assigned_to_group_tickets integer, OUT sla_tickets integer, OUT incident_tickets integer, OUT request_tickets integer, OUT problem_tickets integer) IS 'TYPE: function'; publicpostgresfalse1884]1255233213Gcp_ticketssummary_filter(character varying, character varying, boolean)FUNCTIONCREATE FUNCTION public.cp_ticketssummary_filter(username character varying, usergroup character varying, multigroup boolean, OUT "UserRole" bigint) RETURNS SETOF bigint LANGUAGE plpgsql AS $$ BEGIN IF multigroup THEN RETURN QUERY SELECT map."IdObj2" FROM "Map_UserRole" map JOIN "User" usr ON usr."Id" = map."IdObj1" AND usr."Username" = username AND usr."Status" = 'A' WHERE map."Status" = 'A'; ELSE RETURN QUERY SELECT "Id" FROM "Role" WHERE "Code" = usergroup AND "Status" = 'A'; END IF; END; $$; DROP FUNCTION public.cp_ticketssummary_filter(username character varying, usergroup character varying, multigroup boolean, OUT "UserRole" bigint); publicpostgresfalse00FUNCTION cp_ticketssummary_filter(username character varying, usergroup character varying, multigroup boolean, OUT "UserRole" bigint)COMMENTCOMMENT ON FUNCTION public.cp_ticketssummary_filter(username character varying, usergroup character varying, multigroup boolean, OUT "UserRole" bigint) IS 'TYPE: function'; publicpostgresfalse1885^1255233214=dashboard_tickets_for_service_desk_category(integer, integer)FUNCTIONCREATE FUNCTION public.dashboard_tickets_for_service_desk_category("group (default: all)" integer, "category (default: all)" integer, OUT "Category" character varying, OUT "Counter" integer) RETURNS SETOF record LANGUAGE plpgsql AS $$ BEGIN RETURN QUERY select * from dashboard_tickets_for_service_desk_category_1('"ITProc"', "group (default: all)", "category (default: all)"); END; $$; DROP FUNCTION public.dashboard_tickets_for_service_desk_category("group (default: all)" integer, "category (default: all)" integer, OUT "Category" character varying, OUT "Counter" integer); publicpostgresfalse00FUNCTION dashboard_tickets_for_service_desk_category("group (default: all)" integer, "category (default: all)" integer, OUT "Category" character varying, OUT "Counter" integer)COMMENTCOMMENT ON FUNCTION public.dashboard_tickets_for_service_desk_category("group (default: all)" integer, "category (default: all)" integer, OUT "Category" character varying, OUT "Counter" integer) IS 'TYPE: function'; publicpostgresfalse1886_1255233215Rdashboard_tickets_for_service_desk_category_1(character varying, integer, integer)FUNCTIONCREATE FUNCTION public.dashboard_tickets_for_service_desk_category_1(class character varying, "group" integer, category integer, OUT outputcategory character varying, OUT counter integer) RETURNS SETOF record LANGUAGE plpgsql AS $$ DECLARE query varchar; BEGIN query= 'SELECT coalesce(s."Description"::varchar,''Category not defined'') as outputcategory, count(*)::integer as counter FROM ' || class || ' sd LEFT JOIN "Role" r on r."Id" = sd."CurrentRole" and r."Status" = ''A'' LEFT JOIN "LookUp" l1 on l1."Id" = sd."FlowStatus" and l1."Status" = ''A'' LEFT JOIN "LookUp" l2 on l2."Id" = sd."ProcessStatus" and l2."Status" = ''A'' LEFT JOIN "ITProcCategory" s on s."Id" = sd."Category" and s."Status" = ''A'' WHERE sd."Status" = ''A'' AND l1."Code" = ''open.running'' AND ( l2."Code" <> ''Closed'' OR l2."Code" IS NULL ) AND ' || CASE WHEN "group" is not null THEN 'sd."CurrentRole" = ' || "group" ELSE 'true' END || ' AND ' || CASE WHEN category is not null THEN 'sd."Category" = ' || category ELSE 'true' END ||' GROUP BY s."Description" ORDER BY count(*) desc LIMIT 10 ;'; -- raise notice '%', query; RETURN QUERY EXECUTE query; END; $$; DROP FUNCTION public.dashboard_tickets_for_service_desk_category_1(class character varying, "group" integer, category integer, OUT outputcategory character varying, OUT counter integer); publicpostgresfalse00FUNCTION dashboard_tickets_for_service_desk_category_1(class character varying, "group" integer, category integer, OUT outputcategory character varying, OUT counter integer)COMMENTCOMMENT ON FUNCTION public.dashboard_tickets_for_service_desk_category_1(class character varying, "group" integer, category integer, OUT outputcategory character varying, OUT counter integer) IS 'TYPE: function'; publicpostgresfalse1887`1255233216:dashboard_tickets_for_service_desk_group(integer, integer)FUNCTIONCREATE FUNCTION public.dashboard_tickets_for_service_desk_group("group (default: all)" integer, "status (default: all)" integer, OUT "Group" character varying, OUT "Counter" integer) RETURNS SETOF record LANGUAGE plpgsql AS $$ BEGIN RETURN QUERY select * from dashboard_tickets_for_service_desk_group_1('"ITProc"', "group (default: all)", "status (default: all)"); END; $$; DROP FUNCTION public.dashboard_tickets_for_service_desk_group("group (default: all)" integer, "status (default: all)" integer, OUT "Group" character varying, OUT "Counter" integer); publicpostgresfalse00FUNCTION dashboard_tickets_for_service_desk_group("group (default: all)" integer, "status (default: all)" integer, OUT "Group" character varying, OUT "Counter" integer)COMMENTCOMMENT ON FUNCTION public.dashboard_tickets_for_service_desk_group("group (default: all)" integer, "status (default: all)" integer, OUT "Group" character varying, OUT "Counter" integer) IS 'TYPE: function'; publicpostgresfalse1888a1255233217Odashboard_tickets_for_service_desk_group_1(character varying, integer, integer)FUNCTIONCREATE FUNCTION public.dashboard_tickets_for_service_desk_group_1(class character varying, "group" integer, status integer, OUT outputgroup character varying, OUT counter integer) RETURNS SETOF record LANGUAGE plpgsql AS $$ DECLARE selection varchar; stato_code varchar; stato_id INTEGER; BEGIN select into stato_code "Code" from "LookUp" where "Id" = status; -- raise notice 'codice dello stato %', stato_code; select into stato_id "Id" from "LookUp" where "Type" = 'ITProc - ProcessStatus' and "Code" = stato_code and "Status" = 'A'; -- raise notice 'id dello stato %', stato_id; selection = 'SELECT coalesce(r."Description"::varchar,''No group'') as outputgroup, count(*)::integer as counter FROM ' || class || ' sd LEFT JOIN "Role" r on r."Id" = sd."CurrentRole" and r."Status" = ''A'' LEFT JOIN "LookUp" l1 on l1."Id" = sd."FlowStatus" and l1."Status" = ''A'' LEFT JOIN "LookUp" l2 on l2."Id" = sd."ProcessStatus" and l2."Status" = ''A'' WHERE sd."Status" = ''A'' AND l1."Code" = ''open.running'' AND ( l2."Code" <> ''Closed'' OR l2."Code" IS NULL ) AND ' || CASE WHEN "group" is not null THEN 'sd."CurrentRole" = ' || "group" ELSE 'true' END || ' AND ' || CASE WHEN stato_code = 'A' THEN 'sd."ProcessStatus" IN ( select "Id" from "LookUp" where "Type" = ''ITProc - ProcessStatus'' and "Code" in (''"Assignment"'') and "Status" = ''A'' )' else case when stato_code is not null then 'sd."ProcessStatus" = ' || stato_id ELSE 'true' END END ||' GROUP BY r."Description" ORDER BY count(*) desc LIMIT 10;'; raise notice '%', selection; RETURN QUERY EXECUTE selection; END; $$; DROP FUNCTION public.dashboard_tickets_for_service_desk_group_1(class character varying, "group" integer, status integer, OUT outputgroup character varying, OUT counter integer); publicpostgresfalse00FUNCTION dashboard_tickets_for_service_desk_group_1(class character varying, "group" integer, status integer, OUT outputgroup character varying, OUT counter integer)COMMENTCOMMENT ON FUNCTION public.dashboard_tickets_for_service_desk_group_1(class character varying, "group" integer, status integer, OUT outputgroup character varying, OUT counter integer) IS 'TYPE: function'; publicpostgresfalse1889b12552332185dashboard_tickets_for_service_desk_processes(integer)FUNCTIONKCREATE FUNCTION public.dashboard_tickets_for_service_desk_processes("group (default: all)" integer, OUT "Process" character varying, OUT "Counter" integer) RETURNS SETOF record LANGUAGE plpgsql AS $$ BEGIN "group (default: all)" = case when ( "group (default: all)" = (select "Id" from "Role" where "Code" like 'SuperUser') ) then null else "group (default: all)" end; RETURN QUERY SELECT CASE WHEN sd."IdClass"::varchar = '"IncidentMgt"' THEN 'IM'::varchar WHEN sd."IdClass"::varchar = '"ReqFulfil"' THEN 'RF'::varchar ELSE 'ND'::varchar END, count(*)::integer FROM "ITProc" sd LEFT JOIN "Role" r on r."Id" = sd."CurrentRole" and r."Status" = 'A' LEFT JOIN "LookUp" l on l."Id" = sd."FlowStatus" and l."Status" = 'A' LEFT JOIN "LookUp" l2 on l2."Id" = sd."ProcessStatus" and l."Status" = 'A' WHERE sd."Status" = 'A' and l."Code" = 'open.running' and l2."Code" <> 'Closed' AND CASE WHEN "group (default: all)" is not null THEN sd."CurrentRole" = "group (default: all)" ELSE true END GROUP BY sd."IdClass" ORDER BY sd."IdClass"; END; $$; DROP FUNCTION public.dashboard_tickets_for_service_desk_processes("group (default: all)" integer, OUT "Process" character varying, OUT "Counter" integer); publicpostgresfalse00FUNCTION dashboard_tickets_for_service_desk_processes("group (default: all)" integer, OUT "Process" character varying, OUT "Counter" integer)COMMENTCOMMENT ON FUNCTION public.dashboard_tickets_for_service_desk_processes("group (default: all)" integer, OUT "Process" character varying, OUT "Counter" integer) IS 'TYPE: function'; publicpostgresfalse1890c12552332192dashboard_tickets_for_service_desk_status(integer)FUNCTIONCREATE FUNCTION public.dashboard_tickets_for_service_desk_status("group (default:all)" integer, OUT "Status" character varying, OUT "Counter" integer) RETURNS SETOF record LANGUAGE plpgsql AS $$ BEGIN "group (default:all)" = case when ( "group (default:all)" = (select "Id" from "Role" where "Code" like 'SuperUser') ) then null else "group (default:all)" end; RETURN QUERY select * from dashboard_tickets_for_service_desk_status_1('"ITProc"', "group (default:all)"); END; $$; DROP FUNCTION public.dashboard_tickets_for_service_desk_status("group (default:all)" integer, OUT "Status" character varying, OUT "Counter" integer); publicpostgresfalse00FUNCTION dashboard_tickets_for_service_desk_status("group (default:all)" integer, OUT "Status" character varying, OUT "Counter" integer)COMMENTCOMMENT ON FUNCTION public.dashboard_tickets_for_service_desk_status("group (default:all)" integer, OUT "Status" character varying, OUT "Counter" integer) IS 'TYPE: function'; publicpostgresfalse1891d1255233220Gdashboard_tickets_for_service_desk_status_1(character varying, integer)FUNCTIONCREATE FUNCTION public.dashboard_tickets_for_service_desk_status_1(class character varying, "group" integer, OUT status character varying, OUT flownumber integer) RETURNS SETOF record LANGUAGE plpgsql AS $$ DECLARE selection varchar; BEGIN selection = 'SELECT coalesce(l2."Description"::varchar,''Status not assigned'') as status, count(*)::integer as flownumber FROM ' || class || ' sd LEFT JOIN "Role" r on r."Id" = sd."CurrentRole" and r."Status" = ''A'' LEFT JOIN "LookUp" l1 on l1."Id" = sd."FlowStatus" and l1."Status" = ''A'' LEFT JOIN "LookUp" l2 on l2."Id" = sd."ProcessStatus" and l2."Status" = ''A'' WHERE sd."Status" = ''A'' AND l1."Code" = ''open.running'' AND ( l2."Code" <> ''Closed'' OR l2."Code" IS NULL) AND ' || CASE WHEN "group" is not null THEN 'sd."CurrentRole" = ' || "group" ELSE 'true' END || ' GROUP BY coalesce(l2."Description"::varchar,''Status not assigned'') ORDER BY count(*)::integer desc'; RETURN QUERY EXECUTE selection; -- raise notice '%', selection; END; $$; DROP FUNCTION public.dashboard_tickets_for_service_desk_status_1(class character varying, "group" integer, OUT status character varying, OUT flownumber integer); publicpostgresfalse00FUNCTION dashboard_tickets_for_service_desk_status_1(class character varying, "group" integer, OUT status character varying, OUT flownumber integer)COMMENTCOMMENT ON FUNCTION public.dashboard_tickets_for_service_desk_status_1(class character varying, "group" integer, OUT status character varying, OUT flownumber integer) IS 'TYPE: function'; publicpostgresfalse1892e1255233221@dashboard_tickets_for_service_desk_subcategory(integer, integer)FUNCTIONCREATE FUNCTION public.dashboard_tickets_for_service_desk_subcategory("group (default: all)" integer, "subcategory (default: all)" integer, OUT "Subcategory" character varying, OUT "Counter" integer) RETURNS SETOF record LANGUAGE plpgsql AS $$ BEGIN RETURN QUERY select * from dashboard_tickets_for_service_desk_subcategory_1('"ITProc"', "group (default: all)", "subcategory (default: all)"); END; $$; DROP FUNCTION public.dashboard_tickets_for_service_desk_subcategory("group (default: all)" integer, "subcategory (default: all)" integer, OUT "Subcategory" character varying, OUT "Counter" integer); publicpostgresfalse00FUNCTION dashboard_tickets_for_service_desk_subcategory("group (default: all)" integer, "subcategory (default: all)" integer, OUT "Subcategory" character varying, OUT "Counter" integer)COMMENTCOMMENT ON FUNCTION public.dashboard_tickets_for_service_desk_subcategory("group (default: all)" integer, "subcategory (default: all)" integer, OUT "Subcategory" character varying, OUT "Counter" integer) IS 'TYPE: function'; publicpostgresfalse1893g1255233222Udashboard_tickets_for_service_desk_subcategory_1(character varying, integer, integer)FUNCTIONCREATE FUNCTION public.dashboard_tickets_for_service_desk_subcategory_1(class character varying, "group" integer, subcategory integer, OUT outputsubcategory character varying, OUT counter integer) RETURNS SETOF record LANGUAGE plpgsql AS $$ DECLARE query varchar; BEGIN query= 'SELECT coalesce(s."Description"::varchar,''Subcategory not defined'') as outputsubcategory, count(*)::integer as counter FROM ' || class || ' sd LEFT JOIN "Role" r on r."Id" = sd."CurrentRole" and r."Status" = ''A'' LEFT JOIN "LookUp" l1 on l1."Id" = sd."FlowStatus" and l1."Status" = ''A'' LEFT JOIN "LookUp" l2 on l2."Id" = sd."ProcessStatus" and l2."Status" = ''A'' LEFT JOIN "ITProcSubcategory" s on s."Id" = sd."Subcategory" and s."Status" = ''A'' WHERE sd."Status" = ''A'' AND l1."Code" = ''open.running'' AND ( l2."Code" <> ''Closed'' OR l2."Code" IS NULL ) AND ' || CASE WHEN "group" is not null THEN 'sd."CurrentRole" = ' || "group" ELSE 'true' END || ' AND ' || CASE WHEN subcategory is not null THEN 'sd."Subcategory" = ' || subcategory ELSE 'true' END ||' GROUP BY s."Description" ORDER BY count(*) desc LIMIT 10 ;'; -- raise notice '%', query; RETURN QUERY EXECUTE query; END; $$; DROP FUNCTION public.dashboard_tickets_for_service_desk_subcategory_1(class character varying, "group" integer, subcategory integer, OUT outputsubcategory character varying, OUT counter integer); publicpostgresfalse00FUNCTION dashboard_tickets_for_service_desk_subcategory_1(class character varying, "group" integer, subcategory integer, OUT outputsubcategory character varying, OUT counter integer)COMMENTCOMMENT ON FUNCTION public.dashboard_tickets_for_service_desk_subcategory_1(class character varying, "group" integer, subcategory integer, OUT outputsubcategory character varying, OUT counter integer) IS 'TYPE: function'; publicpostgresfalse1895h1255233223dashboards_assetsage()FUNCTION)CREATE FUNCTION public.dashboards_assetsage(OUT hwcount integer, OUT age character varying) RETURNS SETOF record LANGUAGE plpgsql AS $$ BEGIN RETURN QUERY SELECT count(q1.hwid)::integer as hwage, q1.age::varchar as age FROM ( SELECT hw."Id" AS hwid, CASE WHEN date_part('year',age(now(), hw."AcceptanceDate")) = 0 THEN '<1 year' ELSE CASE WHEN date_part('year',age(now(), hw."AcceptanceDate")) > 0 AND date_part('year',age(now(), hw."AcceptanceDate")) < 3 THEN '1-2 years' ELSE CASE WHEN date_part('year',age(now(), hw."AcceptanceDate")) > 2 AND date_part('year',age(now(), hw."AcceptanceDate")) < 5 THEN '3-4 years' ELSE CASE WHEN date_part('year',age(now(), hw."AcceptanceDate")) > 4 AND date_part('year',age(now(), hw."AcceptanceDate")) < 6 THEN '4-5 years' ELSE CASE WHEN date_part('year',age(now(), hw."AcceptanceDate")) > 4 THEN '>5 years' END END END END END::varchar as age FROM "Hardware" hw LEFT OUTER JOIN "LookUp" l2 ON l2."Id"=hw."State" WHERE hw."Status"='A' AND hw."AcceptanceDate" is not null and l2."Code" <> 'Disposed' ) as q1 GROUP BY q1.age ORDER BY CASE WHEN q1.age = '<1 year' THEN 1 WHEN q1.age = '1-2 years' THEN 2 WHEN q1.age = '3-4 years' THEN 3 WHEN q1.age = '>5 years' THEN 4 END; END $$; [DROP FUNCTION public.dashboards_assetsage(OUT hwcount integer, OUT age character varying); publicpostgresfalse00MFUNCTION dashboards_assetsage(OUT hwcount integer, OUT age character varying)COMMENTuCOMMENT ON FUNCTION public.dashboards_assetsage(OUT hwcount integer, OUT age character varying) IS 'TYPE: function'; publicpostgresfalse1896i1255233224!dashboards_assetsbyavailability()FUNCTIONCREATE FUNCTION public.dashboards_assetsbyavailability(OUT availability character varying, OUT total integer) RETURNS SETOF record LANGUAGE plpgsql AS $$ BEGIN RETURN QUERY SELECT coalesce(l."Description"::text,'Not reported')::varchar as availability, count(*)::integer as total FROM "Hardware" ci LEFT JOIN "LookUp" l ON l."Id" = ci."Availability" WHERE ci."Status" = 'A' and ci."IdClass"::text not in ('"VirtualServer"') GROUP BY availability; END $$; mDROP FUNCTION public.dashboards_assetsbyavailability(OUT availability character varying, OUT total integer); publicpostgresfalse00_FUNCTION dashboards_assetsbyavailability(OUT availability character varying, OUT total integer)COMMENTCOMMENT ON FUNCTION public.dashboards_assetsbyavailability(OUT availability character varying, OUT total integer) IS 'TYPE: function'; publicpostgresfalse1897j1255233225dashboards_assetsbystate()FUNCTIONCREATE FUNCTION public.dashboards_assetsbystate(OUT state character varying, OUT total integer) RETURNS SETOF record LANGUAGE plpgsql AS $$ BEGIN RETURN QUERY SELECT coalesce(l."Description"::text,'Not reported')::varchar as state, count(*)::integer as total FROM "Hardware" ci LEFT JOIN "LookUp" l ON l."Id" = ci."State" WHERE ci."Status" = 'A' and ci."IdClass"::text not in ('"VirtualServer"') GROUP BY state; END $$; _DROP FUNCTION public.dashboards_assetsbystate(OUT state character varying, OUT total integer); publicpostgresfalse00QFUNCTION dashboards_assetsbystate(OUT state character varying, OUT total integer)COMMENTyCOMMENT ON FUNCTION public.dashboards_assetsbystate(OUT state character varying, OUT total integer) IS 'TYPE: function'; publicpostgresfalse1898k1255233226dashboards_assetsbytype()FUNCTIONCREATE FUNCTION public.dashboards_assetsbytype(OUT hwtype character varying, OUT total integer) RETURNS SETOF record LANGUAGE plpgsql AS $$ BEGIN RETURN QUERY SELECT (CASE WHEN (SELECT count(*) FROM "LookUp" WHERE "Code" ILIKE replace(ci."IdClass"::text,'"','')::varchar and "Type"='CIReportClass' and "Status"='A')>0 THEN (select "Description" from "LookUp" where "Code" ilike replace(ci."IdClass"::text,'"','')::varchar and "Type"='CIReportClass' and "Status"='A') ELSE (replace(ci."IdClass"::text,'"','')::varchar) END) AS hwtype, count(*)::integer as total FROM "Hardware" ci WHERE "Status" = 'A' and "IdClass"::text not in ('"VirtualServer"') GROUP BY hwtype ORDER BY hwtype; END $$; _DROP FUNCTION public.dashboards_assetsbytype(OUT hwtype character varying, OUT total integer); publicpostgresfalse00QFUNCTION dashboards_assetsbytype(OUT hwtype character varying, OUT total integer)COMMENTyCOMMENT ON FUNCTION public.dashboards_assetsbytype(OUT hwtype character varying, OUT total integer) IS 'TYPE: function'; publicpostgresfalse1899l1255233227$dashboards_im_average_closing_time()FUNCTION:CREATE FUNCTION public.dashboards_im_average_closing_time(OUT period character varying, OUT duration numeric) RETURNS SETOF record LANGUAGE plpgsql AS $$ BEGIN RETURN QUERY select to_char(now() - '1 month'::interval * i, 'YYYY-MM')::varchar, CASE WHEN avg(("TTHDClassification"::numeric(12,2)+"TTHDAnalysis"::numeric(12,2)+"TTHDExecution"::numeric(12,2)+"TTHDStartCM"::numeric(12,2)+"TTHDSuspension"::numeric(12,2)+"TTHDClosure"::numeric(12,2)+"TTSPClassification"::numeric(12,2)+"TTSPAnalysis"::numeric(12,2)+"TTSPExecution"::numeric(12,2)+"TTSPStartCM"::numeric(12,2)+"TTSPSuspension"::numeric(12,2)+"TTSPClosure"::numeric(12,2))/3600)::numeric(12,2) is null THEN 0 ELSE avg(("TTHDClassification"::numeric(12,2)+"TTHDAnalysis"::numeric(12,2)+"TTHDExecution"::numeric(12,2)+"TTHDStartCM"::numeric(12,2)+"TTHDSuspension"::numeric(12,2)+"TTHDClosure"::numeric(12,2)+"TTSPClassification"::numeric(12,2)+"TTSPAnalysis"::numeric(12,2)+"TTSPExecution"::numeric(12,2)+"TTSPStartCM"::numeric(12,2)+"TTSPSuspension"::numeric(12,2)+"TTSPClosure"::numeric(12,2))/3600)::numeric(12,2) END as total FROM generate_series(0,11) i left outer join ("IncidentMgt" join "LookUp" on "LookUp"."Id" = "IncidentMgt"."FlowStatus" and "LookUp"."Code" = 'closed.completed') on "IncidentMgt"."ClosureTimestamp" between date_trunc('month', now() - '1 month'::interval * i) and date_trunc('month', now() - '1 month'::interval * i) + '1 month'::interval - '1 sec'::interval and "IncidentMgt"."Status" = 'A' group by to_char(now() - '1 month'::interval * i, 'YYYY-MM') order by 1; END $$; mDROP FUNCTION public.dashboards_im_average_closing_time(OUT period character varying, OUT duration numeric); publicpostgresfalse00_FUNCTION dashboards_im_average_closing_time(OUT period character varying, OUT duration numeric)COMMENTCOMMENT ON FUNCTION public.dashboards_im_average_closing_time(OUT period character varying, OUT duration numeric) IS 'TYPE: function'; publicpostgresfalse1900m1255233228,dashboards_im_for_category(integer, integer)FUNCTION3CREATE FUNCTION public.dashboards_im_for_category("year (default:current)" integer, "month (default:current)" integer, OUT category character varying, OUT number integer) RETURNS SETOF record LANGUAGE plpgsql AS $$ DECLARE today timestamp without time zone; month_code integer; year_value integer; BEGIN today = now(); year_value = "year (default:current)"; select "Code" into month_code from "LookUp" where "LookUp"."Id" = "month (default:current)"; RETURN QUERY select coalesce(l2."Description",'Not available') as category, count(*)::integer from "IncidentMgt" as imgt left join "LookUp" l1 on l1."Id" = imgt."FlowStatus" and l1."Status"='A' left join "ITProcCategory" l2 on l2."Id" = imgt."Category" and l2."Status"='A' where imgt."Status" = 'A' and l1."Code" in ('open.running') and case when year_value is not null then date_part('year', imgt."BeginDate")::varchar = year_value::varchar else date_part('year', imgt."BeginDate")::varchar = date_part('year', today)::varchar end and case when month_code is not null then date_part('month', imgt."BeginDate")::varchar = month_code::varchar else date_part('month', imgt."BeginDate")::varchar = date_part('month', today)::varchar end and imgt."Status" = 'A' group by category order by 1; END $$; DROP FUNCTION public.dashboards_im_for_category("year (default:current)" integer, "month (default:current)" integer, OUT category character varying, OUT number integer); publicpostgresfalse00FUNCTION dashboards_im_for_category("year (default:current)" integer, "month (default:current)" integer, OUT category character varying, OUT number integer)COMMENTCOMMENT ON FUNCTION public.dashboards_im_for_category("year (default:current)" integer, "month (default:current)" integer, OUT category character varying, OUT number integer) IS 'TYPE: function'; publicpostgresfalse1901n1255233229*dashboards_im_for_status(integer, integer)FUNCTION.CREATE FUNCTION public.dashboards_im_for_status("year (default:current)" integer, "month (default:current)" integer, OUT status character varying, OUT number integer) RETURNS SETOF record LANGUAGE plpgsql AS $$ DECLARE today timestamp without time zone; month_code integer; year_value integer; BEGIN today = now(); year_value = "year (default:current)"; select "Code" into month_code from "LookUp" where "LookUp"."Id" = "month (default:current)"; RETURN QUERY select coalesce(l2."Description",'Not available') as status, count(*)::integer from "IncidentMgt" as imgt left join "LookUp" l1 on l1."Id" = imgt."FlowStatus" and l1."Status"='A' left join "LookUp" l2 on l2."Id" = imgt."ProcessStatus" and l2."Status"='A' where imgt."Status" = 'A' and l1."Code" in ('open.running') and case when year_value is not null then date_part('year', imgt."BeginDate")::varchar = year_value::varchar else date_part('year', imgt."BeginDate")::varchar = date_part('year', today)::varchar end and case when month_code is not null then date_part('month', imgt."BeginDate")::varchar = month_code::varchar else date_part('month', imgt."BeginDate")::varchar = date_part('month', today)::varchar end and imgt."Status" = 'A' group by status order by 1; END $$; DROP FUNCTION public.dashboards_im_for_status("year (default:current)" integer, "month (default:current)" integer, OUT status character varying, OUT number integer); publicpostgresfalse00FUNCTION dashboards_im_for_status("year (default:current)" integer, "month (default:current)" integer, OUT status character varying, OUT number integer)COMMENTCOMMENT ON FUNCTION public.dashboards_im_for_status("year (default:current)" integer, "month (default:current)" integer, OUT status character varying, OUT number integer) IS 'TYPE: function'; publicpostgresfalse1902o1255233230+dashboards_im_openclosed_for_month(integer)FUNCTIONYCREATE FUNCTION public.dashboards_im_openclosed_for_month("year (default: current)" integer, OUT month character varying, OUT open integer, OUT closed integer) RETURNS SETOF record LANGUAGE plpgsql AS $$ DECLARE today timestamp without time zone = now(); BEGIN RETURN QUERY select dashboards_int_to_month(i), q1.open, q2.closed from generate_series(1,12) i left join (select dashboards_int_to_month(i) as month1, sum(case when fs."Code" in ('open.running','closed.completed','open.not_running.suspended') then 1 else 0 end)::integer as open from generate_series(1,12) i left join ("IncidentMgt" im left join "LookUp" fs on fs."Id" = im."FlowStatus" and fs."Status"='A') on (case when "year (default: current)" is not null then date_part('year', im."CreationTimestamp")::varchar = "year (default: current)"::varchar else date_part('year', im."CreationTimestamp")::varchar = date_part('year', today)::varchar end) and (date_part('month', im."CreationTimestamp") = i) and im."Status" = 'A' and "CreationTimestamp" is not null and fs."Code" in ('open.running','closed.completed','open.not_running.suspended') group by i order by i ) as q1 on dashboards_int_to_month(i) = q1.month1 left join (select dashboards_int_to_month(i) as month2, sum(case when fs."Code" in ('open.running','closed.completed','open.not_running.suspended') then 1 else 0 end)::integer as closed from generate_series(1,12) i left join ("IncidentMgt" im left join "LookUp" fs on fs."Id" = im."FlowStatus" and fs."Status"='A') on (case when "year (default: current)" is not null then date_part('year', im."ClosureTimestamp")::varchar = "year (default: current)"::varchar else date_part('year', im."ClosureTimestamp")::varchar = date_part('year', today)::varchar end) and (date_part('month', im."ClosureTimestamp") = i) and im."Status" = 'A' and "ClosureTimestamp" is not null and fs."Code" in ('open.running','closed.completed','open.not_running.suspended') group by i order by i ) as q2 on dashboards_int_to_month(i) = q2.month2; END $$; DROP FUNCTION public.dashboards_im_openclosed_for_month("year (default: current)" integer, OUT month character varying, OUT open integer, OUT closed integer); publicpostgresfalse00FUNCTION dashboards_im_openclosed_for_month("year (default: current)" integer, OUT month character varying, OUT open integer, OUT closed integer)COMMENTCOMMENT ON FUNCTION public.dashboards_im_openclosed_for_month("year (default: current)" integer, OUT month character varying, OUT open integer, OUT closed integer) IS 'TYPE: function'; publicpostgresfalse1903p1255233231 dashboards_int_to_month(integer)FUNCTIONCREATE FUNCTION public.dashboards_int_to_month(mese integer, OUT mese_string character varying) RETURNS character varying LANGUAGE plpgsql AS $$ BEGIN CASE WHEN mese=1 THEN mese_string = 'January'; WHEN mese=2 THEN mese_string = 'February'; WHEN mese=3 THEN mese_string = 'March'; WHEN mese=4 THEN mese_string = 'April'; WHEN mese=5 THEN mese_string = 'May'; WHEN mese=6 THEN mese_string = 'June'; WHEN mese=7 THEN mese_string = 'July'; WHEN mese=8 THEN mese_string = 'August'; WHEN mese=9 THEN mese_string = 'September'; WHEN mese=10 THEN mese_string = 'October'; WHEN mese=11 THEN mese_string = 'November'; ELSE mese_string = 'December'; END CASE; END $$; _DROP FUNCTION public.dashboards_int_to_month(mese integer, OUT mese_string character varying); publicpostgresfalse00QFUNCTION dashboards_int_to_month(mese integer, OUT mese_string character varying)COMMENTyCOMMENT ON FUNCTION public.dashboards_int_to_month(mese integer, OUT mese_string character varying) IS 'TYPE: function'; publicpostgresfalse1904q1255233232+dashboards_reqfulfil_average_closing_time()FUNCTIONpCREATE FUNCTION public.dashboards_reqfulfil_average_closing_time(OUT period character varying, OUT duration numeric) RETURNS SETOF record LANGUAGE plpgsql AS $$ BEGIN RETURN QUERY select to_char(now() - '1 month'::interval * i, 'YYYY-MM')::varchar, CASE WHEN avg(("TTApproval"::numeric(12,2)+"TTAnalysis"::numeric(12,2)+"TTHDClassification"::numeric(12,2)+"TTHDClosure"::numeric(12,2)+"TTHDInfoMgt"::numeric(12,2)+"TTSPClassification"::numeric(12,2)+"TTSPClosure"::numeric(12,2)+"TTSPInfoMgt"::numeric(12,2)+"TTWorkorders"::numeric(12,2))/3600)::numeric(12,2) is null THEN 0 ELSE avg(("TTApproval"::numeric(12,2)+"TTAnalysis"::numeric(12,2)+"TTHDClassification"::numeric(12,2)+"TTHDClosure"::numeric(12,2)+"TTHDInfoMgt"::numeric(12,2)+"TTSPClassification"::numeric(12,2)+"TTSPClosure"::numeric(12,2)+"TTSPInfoMgt"::numeric(12,2)+"TTWorkorders"::numeric(12,2))/3600)::numeric(12,2) END as total FROM generate_series(0,11) i left outer join ("ReqFulfil" join "LookUp" on "LookUp"."Id" = "ReqFulfil"."FlowStatus" and "LookUp"."Code" = 'closed.completed') on "ReqFulfil"."ClosureTimestamp" between date_trunc('month', now() - '1 month'::interval * i) and date_trunc('month', now() - '1 month'::interval * i) + '1 month'::interval - '1 sec'::interval and "ReqFulfil"."Status" = 'A' group by to_char(now() - '1 month'::interval * i, 'YYYY-MM') order by 1; END $$; tDROP FUNCTION public.dashboards_reqfulfil_average_closing_time(OUT period character varying, OUT duration numeric); publicpostgresfalse00fFUNCTION dashboards_reqfulfil_average_closing_time(OUT period character varying, OUT duration numeric)COMMENTCOMMENT ON FUNCTION public.dashboards_reqfulfil_average_closing_time(OUT period character varying, OUT duration numeric) IS 'TYPE: function'; publicpostgresfalse1905r12552332333dashboards_reqfulfil_for_category(integer, integer)FUNCTIONSCREATE FUNCTION public.dashboards_reqfulfil_for_category("year (default:current)" integer, "month (default:current)" integer, OUT category character varying, OUT number integer) RETURNS SETOF record LANGUAGE plpgsql AS $$ DECLARE today timestamp without time zone; month_code integer; year_value integer; BEGIN today = now(); year_value = "year (default:current)"; select "Code" into month_code from "LookUp" where "LookUp"."Id" = "month (default:current)"; RETURN QUERY select coalesce(l2."Description",'Not available') as category, count(*)::integer from "ReqFulfil" as rff left join "LookUp" l1 on l1."Id" = rff."FlowStatus" and l1."Status"='A' left join "ITProcCategory" l2 on l2."Id" = rff."Category" and l2."Status"='A' where rff."Status" = 'A' and l1."Code" in ('open.running') and case when year_value is not null then date_part('year', rff."BeginDate")::varchar = year_value::varchar else date_part('year', rff."BeginDate")::varchar = date_part('year', today)::varchar end and case when month_code is not null then date_part('month', rff."BeginDate")::varchar = month_code::varchar else date_part('month', rff."BeginDate")::varchar = date_part('month', today)::varchar end and rff."Status" = 'A' and l1."Code" <> 'closed.completed' group by category order by 1; END $$; DROP FUNCTION public.dashboards_reqfulfil_for_category("year (default:current)" integer, "month (default:current)" integer, OUT category character varying, OUT number integer); publicpostgresfalse00FUNCTION dashboards_reqfulfil_for_category("year (default:current)" integer, "month (default:current)" integer, OUT category character varying, OUT number integer)COMMENTCOMMENT ON FUNCTION public.dashboards_reqfulfil_for_category("year (default:current)" integer, "month (default:current)" integer, OUT category character varying, OUT number integer) IS 'TYPE: function'; publicpostgresfalse1906s12552332341dashboards_reqfulfil_for_status(integer, integer)FUNCTION%CREATE FUNCTION public.dashboards_reqfulfil_for_status("year (default:current)" integer, "month (default:current)" integer, OUT status character varying, OUT number integer) RETURNS SETOF record LANGUAGE plpgsql AS $$ DECLARE today timestamp without time zone; month_code integer; year_value integer; BEGIN today = now(); year_value = "year (default:current)"; select "Code" into month_code from "LookUp" where "LookUp"."Id" = "month (default:current)"; RETURN QUERY select coalesce(l2."Description",'Not available') as status, count(*)::integer from "ReqFulfil" as rff left join "LookUp" l1 on l1."Id" = rff."FlowStatus" and l1."Status"='A' left join "LookUp" l2 on l2."Id" = rff."ProcessStatus" and l2."Status"='A' where rff."Status" = 'A' and l1."Code" in ('open.running') and case when year_value is not null then date_part('year', rff."BeginDate")::varchar = year_value::varchar else date_part('year', rff."BeginDate")::varchar = date_part('year', today)::varchar end and case when month_code is not null then date_part('month', rff."BeginDate")::varchar = month_code::varchar else date_part('month', rff."BeginDate")::varchar = date_part('month', today)::varchar end and rff."Status" = 'A' group by status order by 1; END $$; DROP FUNCTION public.dashboards_reqfulfil_for_status("year (default:current)" integer, "month (default:current)" integer, OUT status character varying, OUT number integer); publicpostgresfalse00FUNCTION dashboards_reqfulfil_for_status("year (default:current)" integer, "month (default:current)" integer, OUT status character varying, OUT number integer)COMMENTCOMMENT ON FUNCTION public.dashboards_reqfulfil_for_status("year (default:current)" integer, "month (default:current)" integer, OUT status character varying, OUT number integer) IS 'TYPE: function'; publicpostgresfalse1907f12552332352dashboards_reqfulfil_openclosed_for_month(integer)FUNCTIONRCREATE FUNCTION public.dashboards_reqfulfil_openclosed_for_month("year (default: current)" integer, OUT month character varying, OUT open integer, OUT closed integer) RETURNS SETOF record LANGUAGE plpgsql AS $$ DECLARE today timestamp without time zone = now(); BEGIN RETURN QUERY select dashboards_int_to_month(i), q1.open, q2.closed from generate_series(1,12) i left join (select dashboards_int_to_month(i) as month1, sum(case when fs."Code" in ('open.running','closed.completed','open.not_running.suspended') then 1 else 0 end)::integer as open from generate_series(1,12) i left join ("ReqFulfil" rff left join "LookUp" fs on fs."Id" = rff."FlowStatus" and fs."Status"='A') on (case when "year (default: current)" is not null then date_part('year', rff."CreationTimestamp")::varchar = "year (default: current)"::varchar else date_part('year', rff."CreationTimestamp")::varchar = date_part('year', today)::varchar end) and (date_part('month', rff."CreationTimestamp") = i) and rff."Status" = 'A' and "CreationTimestamp" is not null and fs."Code" in ('open.running','closed.completed','open.not_running.suspended') group by i order by i ) as q1 on dashboards_int_to_month(i) = q1.month1 left join (select dashboards_int_to_month(i) as month2, sum(case when date_part('month', rff."ClosureTimestamp") = i then 1 else 0 end)::integer as closed from generate_series(1,12) i left join ("ReqFulfil" rff left join "LookUp" fs on fs."Id" = rff."FlowStatus" and fs."Status"='A') on (case when "year (default: current)" is not null then date_part('year', rff."ClosureTimestamp")::varchar = "year (default: current)"::varchar else date_part('year', rff."ClosureTimestamp")::varchar = date_part('year', today)::varchar end) and (date_part('month', rff."ClosureTimestamp") = i) and rff."Status" = 'A' and "ClosureTimestamp" is not null and fs."Code" in ('open.running','closed.completed','open.not_running.suspended') group by i order by i ) as q2 on dashboards_int_to_month(i) = q2.month2; END $$; DROP FUNCTION public.dashboards_reqfulfil_openclosed_for_month("year (default: current)" integer, OUT month character varying, OUT open integer, OUT closed integer); publicpostgresfalse00FUNCTION dashboards_reqfulfil_openclosed_for_month("year (default: current)" integer, OUT month character varying, OUT open integer, OUT closed integer)COMMENTCOMMENT ON FUNCTION public.dashboards_reqfulfil_openclosed_for_month("year (default: current)" integer, OUT month character varying, OUT open integer, OUT closed integer) IS 'TYPE: function'; publicpostgresfalse1894u1255233236dashboards_sla(integer)FUNCTION CREATE FUNCTION public.dashboards_sla(status integer, OUT "Workflow" character varying, OUT "Intime processes" integer, OUT "Threshold 1 delay" integer, OUT "Threshold 2 delay" integer) RETURNS SETOF record LANGUAGE plpgsql AS $$ DECLARE today timestamp without time zone; statuscode varchar; BEGIN today = cast(now() AS timestamp without time zone); SELECT "Code" FROM "LookUp" WHERE "Id" = status INTO statuscode; IF statuscode = 'Closed' THEN RETURN QUERY SELECT 'Incident Management'::varchar AS "Workflow", sum( ( CASE WHEN ( subq.totaltime=subq.threshold1) THEN 1 ELSE 0 END ) )::integer AS "Threshold 1 delay", sum( ( CASE WHEN subq.totaltime>=subq.threshold2 THEN 1 ELSE 0 END ) )::integer AS "Threshold 2 delay" FROM ( SELECT i."Id" AS ident, ceil((select activitytime from wf_incidentmgt_getactivitytime(i."CreationTimestamp",i."ClosureTimestamp"))) AS totaltime, itc."Threshold1Delay" AS threshold1, itc."Threshold2Delay" AS threshold2 FROM "IncidentMgt" i JOIN "LookUp" fs ON fs."Id"=i."FlowStatus" AND fs."Status"='A' LEFT JOIN "ITProcClassification" itc ON itc."Category" = i."Category" AND i."Subcategory" = itc."Subcategory" AND itc."Status" = 'A' JOIN "LookUp" l ON l."Id"=itc."Workflow" AND l."Status"='A' WHERE i."Status"='A' AND ( fs."Code" = 'closed.completed' OR fs."Code" = 'open.not_running.suspended' ) AND l."Code" = 'IM' AND ( itc."Threshold1Delay" is not null OR itc."Threshold2Delay" is not null) ORDER BY i."Id" ) AS subq UNION SELECT 'Request fulfilment'::varchar AS "Workflow", sum( ( CASE WHEN ( subq.totaltime=subq.threshold1) THEN 1 ELSE 0 END ) )::integer AS "Threshold 1 delay", sum( ( CASE WHEN subq.totaltime>=subq.threshold2 THEN 1 ELSE 0 END ) )::integer AS "Threshold 2 delay" FROM ( SELECT i."Id" AS ident, ceil((select activitytime from wf_reqfulfil_getactivitytime(i."CreationTimestamp",i."ClosureTimestamp"))) AS totaltime, itc."Threshold1Delay" AS threshold1, itc."Threshold2Delay" AS threshold2 FROM "ReqFulfil" i JOIN "LookUp" fs ON fs."Id"=i."FlowStatus" AND fs."Status"='A' LEFT JOIN "ITProcClassification" itc ON itc."Category" = i."Category" AND i."Subcategory" = itc."Subcategory" AND itc."Status" = 'A' JOIN "LookUp" l ON l."Id"=itc."Workflow" AND l."Status"='A' WHERE i."Status"='A' AND ( fs."Code" = 'closed.completed' OR fs."Code" = 'open.not_running.suspended' ) AND l."Code" = 'RF' AND ( itc."Threshold1Delay" is not null OR itc."Threshold2Delay" is not null) ORDER BY i."Id" ) AS subq; ELSE RETURN QUERY SELECT 'Incident Management'::varchar AS "Workflow", sum( ( CASE WHEN ( subq.totaltime=subq.threshold1) THEN 1 ELSE 0 END ) )::integer AS "Threshold 1 delay", sum( ( CASE WHEN subq.totaltime>=subq.threshold2 THEN 1 ELSE 0 END ) )::integer AS "Threshold 2 delay" FROM ( SELECT i."Id" AS ident, ceil((select activitytime from wf_incidentmgt_getactivitytime(i."CreationTimestamp",today))) AS totaltime, itc."Threshold1Delay" AS threshold1, itc."Threshold2Delay" AS threshold2 FROM "IncidentMgt" i JOIN "LookUp" fs ON fs."Id"=i."FlowStatus" AND fs."Status"='A' LEFT JOIN "ITProcClassification" itc ON itc."Category" = i."Category" AND i."Subcategory" = itc."Subcategory" AND itc."Status" = 'A' JOIN "LookUp" l ON l."Id"=itc."Workflow" AND l."Status"='A' WHERE i."Status"='A' AND ( fs."Code" = 'open.running' ) AND l."Code" = 'IM' AND ( itc."Threshold1Delay" is not null OR itc."Threshold2Delay" is not null) ORDER BY i."Id" ) AS subq UNION SELECT 'Request fulfilment'::varchar AS process, sum( ( CASE WHEN ( subq.totaltime=subq.threshold1) THEN 1 ELSE 0 END ) )::integer AS "Threshold 1 delay", sum( ( CASE WHEN subq.totaltime>=subq.threshold2 THEN 1 ELSE 0 END ) )::integer AS "Threshold 2 delay" FROM ( SELECT i."Id" AS ident, ceil((select activitytime from wf_reqfulfil_getactivitytime(i."CreationTimestamp",today))) AS totaltime, itc."Threshold1Delay" AS threshold1, itc."Threshold2Delay" AS threshold2 FROM "ReqFulfil" i JOIN "LookUp" fs ON fs."Id"=i."FlowStatus" AND fs."Status"='A' LEFT JOIN "ITProcClassification" itc ON itc."Category" = i."Category" AND i."Subcategory" = itc."Subcategory" AND itc."Status" = 'A' JOIN "LookUp" l ON l."Id"=itc."Workflow" AND l."Status"='A' WHERE i."Status"='A' AND ( fs."Code" = 'open.running' ) AND l."Code" = 'RF' AND ( itc."Threshold1Delay" is not null OR itc."Threshold2Delay" is not null) ORDER BY i."Id" ) AS subq; END IF; END $$; DROP FUNCTION public.dashboards_sla(status integer, OUT "Workflow" character varying, OUT "Intime processes" integer, OUT "Threshold 1 delay" integer, OUT "Threshold 2 delay" integer); publicpostgresfalse00FUNCTION dashboards_sla(status integer, OUT "Workflow" character varying, OUT "Intime processes" integer, OUT "Threshold 1 delay" integer, OUT "Threshold 2 delay" integer)COMMENTCOMMENT ON FUNCTION public.dashboards_sla(status integer, OUT "Workflow" character varying, OUT "Intime processes" integer, OUT "Threshold 1 delay" integer, OUT "Threshold 2 delay" integer) IS 'TYPE: function'; publicpostgresfalse1909v1255233237db_assetsbyavailability()FUNCTIONCREATE FUNCTION public.db_assetsbyavailability(OUT availability character varying, OUT total integer) RETURNS SETOF record LANGUAGE plpgsql AS $$ BEGIN RETURN QUERY SELECT coalesce(l."Description"::text,'Not reported')::varchar as availability, count(*)::integer as total FROM "CI" ci LEFT JOIN "LookUp" l ON l."Id" = ci."Availability" WHERE ci."Status" = 'A' GROUP BY availability; END $$; eDROP FUNCTION public.db_assetsbyavailability(OUT availability character varying, OUT total integer); publicpostgresfalse00WFUNCTION db_assetsbyavailability(OUT availability character varying, OUT total integer)COMMENTCOMMENT ON FUNCTION public.db_assetsbyavailability(OUT availability character varying, OUT total integer) IS 'TYPE: function'; publicpostgresfalse1910w1255233238db_assetsbystate()FUNCTIONwCREATE FUNCTION public.db_assetsbystate(OUT state character varying, OUT total integer) RETURNS SETOF record LANGUAGE plpgsql AS $$ BEGIN RETURN QUERY SELECT coalesce(l."Description"::text,'Not reported')::varchar as state, count(*)::integer as total FROM "CI" ci LEFT JOIN "LookUp" l ON l."Id" = ci."State" WHERE ci."Status" = 'A' GROUP BY state; END $$; WDROP FUNCTION public.db_assetsbystate(OUT state character varying, OUT total integer); publicpostgresfalse00IFUNCTION db_assetsbystate(OUT state character varying, OUT total integer)COMMENTqCOMMENT ON FUNCTION public.db_assetsbystate(OUT state character varying, OUT total integer) IS 'TYPE: function'; publicpostgresfalse1911x1255233239db_assetsbytype()FUNCTIONCREATE FUNCTION public.db_assetsbytype(OUT hwtype character varying, OUT total integer) RETURNS SETOF record LANGUAGE plpgsql AS $$ BEGIN RETURN QUERY SELECT CASE WHEN "IdClass"::text ilike '"Storage"' THEN 'Storage'::varchar ELSE CASE WHEN "IdClass"::text ilike '"NetworkBox"' THEN 'NetworkBox'::varchar ELSE CASE WHEN "IdClass"::text ilike '"Rack"' THEN 'Rack'::varchar ELSE CASE WHEN "IdClass"::text ilike '"NetworkDevice"' THEN 'NetworkDevice'::varchar ELSE CASE WHEN "IdClass"::text ilike '"Monitor"' THEN 'Monitor'::varchar ELSE CASE WHEN "IdClass"::text ilike '"Printer"' THEN 'Printer'::varchar ELSE CASE WHEN "IdClass"::text ilike '"Desktop"' THEN 'Desktop'::varchar ELSE CASE WHEN "IdClass"::text ilike '"Mobile"' THEN 'Mobile'::varchar ELSE CASE WHEN "IdClass"::text ilike '"Notebook"' THEN 'Notebook'::varchar ELSE CASE WHEN "IdClass"::text ilike '"DesktopDevice"' THEN 'DesktopDevice'::varchar ELSE CASE WHEN "IdClass"::text ilike '"MobileDevice"' THEN 'MobileDevice'::varchar ELSE CASE WHEN "IdClass"::text ilike '"SIM"' THEN 'SIM'::varchar ELSE CASE WHEN "IdClass"::text ilike '"TelephoneExchange"' THEN 'TelephoneExchange'::varchar ELSE CASE WHEN "IdClass"::text ilike '"PhysicalServer"' THEN 'PhysicalServer'::varchar END END END END END END END END END END END END END END AS hwtype, count(*)::integer as total FROM "CI" WHERE "Status" = 'A' GROUP BY hwtype; END $$; WDROP FUNCTION public.db_assetsbytype(OUT hwtype character varying, OUT total integer); publicpostgresfalse00IFUNCTION db_assetsbytype(OUT hwtype character varying, OUT total integer)COMMENTqCOMMENT ON FUNCTION public.db_assetsbytype(OUT hwtype character varying, OUT total integer) IS 'TYPE: function'; publicpostgresfalse1912y12552332401itproc_classification_approver(character varying)FUNCTIONCREATE FUNCTION public.itproc_classification_approver(wf_id character varying, OUT roleid bigint) RETURNS SETOF bigint LANGUAGE plpgsql AS $$ DECLARE wf_code character varying; BEGIN --raise notice 'INPUT: wf_id: %' , wf_id; if (wf_id!='null' and wf_id!='') then select "Code" into wf_code from "LookUp" where "Id" = wf_id::bigint; if (wf_code ilike 'cm') then return query select "Id" from "Role" where "Status" = 'A'; end if; else return query select 0::bigint; end if; END; $$; aDROP FUNCTION public.itproc_classification_approver(wf_id character varying, OUT roleid bigint); publicpostgresfalsez1255233241portal_approval_filter(bigint)FUNCTIONCREATE FUNCTION public.portal_approval_filter(employee_id bigint, OUT id bigint) RETURNS SETOF bigint LANGUAGE plpgsql AS $$ begin return query select r."Id" from "ReqFulfil" r join "LookUp" fs on fs."Id" = r."FlowStatus" and fs."Status"='A' where r."Status" = 'A' and fs."Code" in ('open.running') and r."ApproverSuggEmpl" = employee_id and r."ProcessStatus" = ( select "Id" from "LookUp" where "Type" = 'ITProc - ProcessStatus' and "Code" = 'Approval' and "Status" = 'A' ); end; $$; PDROP FUNCTION public.portal_approval_filter(employee_id bigint, OUT id bigint); publicpostgresfalse{1255233242#portal_email_filter(bigint, bigint)FUNCTIONCREATE FUNCTION public.portal_email_filter(period_id bigint, employee_id bigint, OUT id bigint) RETURNS SETOF bigint LANGUAGE plpgsql AS $$ declare employee_email varchar; datesoil timestamp; periodcode varchar; begin select "Email" from "Employee" where "Id" = employee_id INTO employee_email; SELECT "Code" from "LookUp" where "Id" = period_id INTO periodcode; IF(period_id is not null) THEN EXECUTE 'SELECT current_timestamp - interval ''' || periodcode|| '''' INTO datesoil; return query select "Id" from "Email" where "BeginDate" > datesoil and ("ToAddresses" like '%'||employee_email||'%' or "CcAddresses" like '%'||employee_email||'%' or "BccAddresses" like '%'||employee_email||'%') and "Status" = 'A'; ELSE return query select "Id" from "Email" where ("ToAddresses" like '%'||employee_email||'%' or "CcAddresses" like '%'||employee_email||'%' or "BccAddresses" like '%'||employee_email||'%') and "Status" = 'A'; END IF; end; $$; _DROP FUNCTION public.portal_email_filter(period_id bigint, employee_id bigint, OUT id bigint); publicpostgresfalse00QFUNCTION portal_email_filter(period_id bigint, employee_id bigint, OUT id bigint)COMMENTyCOMMENT ON FUNCTION public.portal_email_filter(period_id bigint, employee_id bigint, OUT id bigint) IS 'TYPE: function'; publicpostgresfalse1915|12552332434portal_itemservice_filter(character varying, bigint)FUNCTIONCREATE FUNCTION public.portal_itemservice_filter(type character varying, employee_id bigint, OUT id bigint) RETURNS SETOF bigint LANGUAGE plpgsql AS $$ declare begin if(type ilike '%item%') then return query select "Id" from "Hardware" where "Status" = 'A' and "Assignee" = employee_id union select "Id" from "SWInstance" where "Status" = 'A' and "Assignee" = employee_id; elseif(type ilike '%service%') then return query select s."Id" from "Service" s left join "ServiceContract" sc on sc."Service" = s."Id" and sc."Status" = 'A' where s."Status" = 'A' and sc."Employee" = employee_id; end if; end; $$; kDROP FUNCTION public.portal_itemservice_filter(type character varying, employee_id bigint, OUT id bigint); publicpostgresfalse00]FUNCTION portal_itemservice_filter(type character varying, employee_id bigint, OUT id bigint)COMMENTCOMMENT ON FUNCTION public.portal_itemservice_filter(type character varying, employee_id bigint, OUT id bigint) IS 'TYPE: function'; publicpostgresfalse1916}1255233244portal_kb_filter(bigint)FUNCTIONCREATE FUNCTION public.portal_kb_filter(category_id bigint, OUT id bigint) RETURNS SETOF bigint LANGUAGE plpgsql AS $$ begin IF (category_id is not null) THEN return query select "Id" from "KnowledgeBase" where "Publish" and "Category" = category_id and "Status" = 'A'; ELSE return query select "Id" from "KnowledgeBase" where "Publish" and "Status" = 'A'; END IF; end; $$; JDROP FUNCTION public.portal_kb_filter(category_id bigint, OUT id bigint); publicpostgresfalse00<FUNCTION portal_kb_filter(category_id bigint, OUT id bigint)COMMENTdCOMMENT ON FUNCTION public.portal_kb_filter(category_id bigint, OUT id bigint) IS 'TYPE: function'; publicpostgresfalse1917~1255233245portal_news_filter(bigint)FUNCTIONCREATE FUNCTION public.portal_news_filter(period_id bigint, OUT id bigint) RETURNS SETOF bigint LANGUAGE plpgsql AS $$ declare periodcode varchar; datesoil timestamp; begin IF(period_id is not null) THEN SELECT "Code" from "LookUp" where "Id" = period_id INTO periodcode; EXECUTE 'SELECT current_timestamp - interval ''' || periodcode|| '''' INTO datesoil; END IF; IF(period_id is not null) THEN return query select "Id" from "News" n where n."Publish" and ( n."PublishFrom" < clock_timestamp() or n."PublishFrom" is null ) and ( n."PublishUntil" > clock_timestamp() or n."PublishUntil" is null ) and "Date" >= datesoil and "Status" = 'A'; ELSE return query select "Id" from "News" n where n."Publish" and ( n."PublishFrom" < clock_timestamp() or n."PublishFrom" is null ) and ( n."PublishUntil" > clock_timestamp() or n."PublishUntil" is null ) and "Status" = 'A'; END IF; end; $$; JDROP FUNCTION public.portal_news_filter(period_id bigint, OUT id bigint); publicpostgresfalse00<FUNCTION portal_news_filter(period_id bigint, OUT id bigint)COMMENTdCOMMENT ON FUNCTION public.portal_news_filter(period_id bigint, OUT id bigint) IS 'TYPE: function'; publicpostgresfalse19181255233246 portal_request_dynfields(bigint)FUNCTIONCREATE FUNCTION public.portal_request_dynfields(servicerequest_id bigint, OUT id bigint) RETURNS SETOF bigint LANGUAGE plpgsql AS $$ DECLARE BEGIN RETURN QUERY SELECT ff."Id" FROM "ServiceRequest" s LEFT JOIN "LookUp" fm ON s."FlowMode" = fm."Id" AND fm."Status" = 'A' AND fm."Code" = 'Dynamic' LEFT JOIN "RFWOForm" f ON s."FormName" = f."Code" AND f."Status" = 'A' JOIN "RFWOFormField" ff ON ff."Form" = f."Id" AND ff."Status" = 'A' WHERE s."Status" = 'A' AND s."Id" = servicerequest_id; END; $$; XDROP FUNCTION public.portal_request_dynfields(servicerequest_id bigint, OUT id bigint); publicpostgresfalse00JFUNCTION portal_request_dynfields(servicerequest_id bigint, OUT id bigint)COMMENTrCOMMENT ON FUNCTION public.portal_request_dynfields(servicerequest_id bigint, OUT id bigint) IS 'TYPE: function'; publicpostgresfalse191912552332478portal_request_filter(character varying, bigint, bigint)FUNCTION`CREATE FUNCTION public.portal_request_filter(classname character varying, employee_id bigint, status_id bigint, OUT id bigint) RETURNS SETOF bigint LANGUAGE plpgsql AS $$ declare query text; begin query = 'SELECT i."Id" FROM "ITProc" i '; query = query || 'JOIN "LookUp" fs ON fs."Id" = i."FlowStatus" '; query = query || ' WHERE i."Status" = ''A'' '; query = query || ' AND ( i."Requester" = ' || employee_id; IF ( status_id is not null) THEN query = query || ' AND i."FlowStatus" = ' || status_id; ELSE query = query || ' AND fs."Code" <> ''closed.aborted'' '; END IF; IF ( classname = 'ALL' ) THEN query = query || ' AND I."IdClass" in ( ''"IncidentMgt"''::regclass, ''"ReqFulfil"''::regclass));'; ELSE query = query || ' AND I."IdClass" = ''"' || classname || '"''::regclass);'; END IF; RETURN QUERY EXECUTE query; end; $$; ~DROP FUNCTION public.portal_request_filter(classname character varying, employee_id bigint, status_id bigint, OUT id bigint); publicpostgresfalse00pFUNCTION portal_request_filter(classname character varying, employee_id bigint, status_id bigint, OUT id bigint)COMMENTCOMMENT ON FUNCTION public.portal_request_filter(classname character varying, employee_id bigint, status_id bigint, OUT id bigint) IS 'TYPE: function'; publicpostgresfalse19201255233248'portal_servicecategories_filter(bigint)FUNCTIONb CREATE FUNCTION public.portal_servicecategories_filter(userid bigint, OUT servicesid bigint) RETURNS SETOF bigint LANGUAGE plpgsql AS $$ DECLARE active_state bigint := (select "Id" from "LookUp" where "Code" = 'Active' and "Type" = 'Service - State' and "Status" = 'A'); category_active_state bigint := (select "Id" from "LookUp" where "Code" = 'Active' and "Type" = 'ServiceCategory - State' and "Status" = 'A'); BEGIN RETURN QUERY SELECT DISTINCT sc."Id" FROM "ServiceCategory" sc JOIN "Service" s on s."Category" = sc."Id" and s."Status" = 'A' and s."ServiceState" = active_state AND s."ShowInCatalogue" JOIN "Map_GrantedEmplService" mapges on mapges."IdObj2" = s."Id" and mapges."Status" = 'A' WHERE sc."Status" = 'A' AND mapges."IdObj1" = userid AND sc."State"=category_active_state UNION SELECT DISTINCT sc."Id" FROM "ServiceCategory" sc JOIN "Service" s on s."Category" = sc."Id" and s."Status" = 'A' and s."ServiceState" = active_state AND s."ShowInCatalogue" JOIN "Map_GrantedOUService" mapgous on mapgous."IdObj2" = s."Id" and mapgous."Status" = 'A' JOIN "Map_OUEmployee" mapoue on mapoue."IdObj1" = mapgous."IdObj1" and mapoue."Status" = 'A' WHERE sc."Status" = 'A' AND mapoue."IdObj2" = userid AND sc."State"=category_active_state UNION SELECT DISTINCT sc."Id" FROM "ServiceCategory" sc JOIN "Service" s on s."Category" = sc."Id" and s."Status" = 'A' and s."ServiceState" = active_state AND s."ShowInCatalogue" WHERE sc."Status" = 'A' AND s."GrantForAll" AND sc."State"=category_active_state UNION SELECT DISTINCT sc."Id" FROM "ServiceCategory" sc JOIN "Service" s on s."Category" = sc."Id" and s."Status" = 'A' and s."ServiceState" = active_state AND s."ShowInCatalogue" JOIN "Map_GrantedEmplService" mapges on mapges."IdObj2" = s."Id" and mapges."Status" = 'A' WHERE sc."Status" = 'A' AND mapges."IdObj1" = userid AND sc."State"=category_active_state UNION SELECT DISTINCT sc."Id" FROM "ServiceCategory" sc JOIN "Service" s on s."Category" = sc."Id" and s."Status" = 'A' and s."ServiceState" = active_state AND s."ShowInCatalogue" JOIN "Map_GrantedOUService" mapgous on mapgous."IdObj2" = s."Id" and mapgous."Status" = 'A' JOIN "Map_OUEmployee" mapoue on mapoue."IdObj1" = mapgous."IdObj1" and mapoue."Status" = 'A' WHERE sc."Status" = 'A' AND mapoue."IdObj2" = userid AND sc."State"=category_active_state UNION SELECT DISTINCT sc."Parent" FROM "ServiceCategory" sc JOIN "Service" s on s."Category" = sc."Id" and s."Status" = 'A' and s."ServiceState" = active_state AND s."ShowInCatalogue" WHERE sc."Status" = 'A' AND s."GrantForAll" AND sc."State"=category_active_state; END; $$; \DROP FUNCTION public.portal_servicecategories_filter(userid bigint, OUT servicesid bigint); publicpostgresfalse00NFUNCTION portal_servicecategories_filter(userid bigint, OUT servicesid bigint)COMMENTvCOMMENT ON FUNCTION public.portal_servicecategories_filter(userid bigint, OUT servicesid bigint) IS 'TYPE: function'; publicpostgresfalse19211255233249&portal_services_filter(bigint, bigint)FUNCTIONCREATE FUNCTION public.portal_services_filter(userid bigint, categoryid bigint, OUT servicesid bigint) RETURNS SETOF bigint LANGUAGE plpgsql AS $$ DECLARE active_state bigint := (select "Id" from "LookUp" where "Code" = 'Active' and "Type" = 'Service - State' and "Status" = 'A'); BEGIN RETURN QUERY SELECT DISTINCT s."Id" FROM "Service" s JOIN "Map_GrantedEmplService" mapges on mapges."IdObj2" = s."Id" and mapges."Status" = 'A' WHERE s."Category" = categoryid and s."Status" = 'A' AND mapges."IdObj1" = userid AND s."ServiceState" = active_state AND s."ShowInCatalogue" UNION SELECT DISTINCT s."Id" FROM "Service" s JOIN "Map_GrantedOUService" mapgous on mapgous."IdObj2" = s."Id" and mapgous."Status" = 'A' JOIN "Map_OUEmployee" mapoue on mapoue."IdObj1" = mapgous."IdObj1" and mapoue."Status" = 'A' WHERE s."Category" = categoryid and s."Status" = 'A' AND mapoue."IdObj2" = userid AND s."ServiceState" = active_state AND s."ShowInCatalogue" UNION SELECT DISTINCT s."Id" FROM "Service" s WHERE s."Category" = categoryid and s."Status" = 'A' AND s."ServiceState" = active_state AND s."GrantForAll" AND s."ShowInCatalogue"; END; $$; fDROP FUNCTION public.portal_services_filter(userid bigint, categoryid bigint, OUT servicesid bigint); publicpostgresfalse00XFUNCTION portal_services_filter(userid bigint, categoryid bigint, OUT servicesid bigint)COMMENTCOMMENT ON FUNCTION public.portal_services_filter(userid bigint, categoryid bigint, OUT servicesid bigint) IS 'TYPE: function'; publicpostgresfalse19221255233250problem_code()FUNCTIONCREATE FUNCTION public.problem_code(OUT number character varying) RETURNS character varying LANGUAGE plpgsql AS $$ BEGIN number = 'PM'||lpad(nextval('problem_seq')::TEXT, 6, '0'); END; $$; ADROP FUNCTION public.problem_code(OUT number character varying); publicpostgresfalse003FUNCTION problem_code(OUT number character varying)COMMENT[COMMENT ON FUNCTION public.problem_code(OUT number character varying) IS 'TYPE: function'; publicpostgresfalse19231255233251rep_am_barcodeprint(bigint)FUNCTIONCREATE FUNCTION public.rep_am_barcodeprint(processid bigint, OUT hwcode character varying, OUT hwserialnumber character varying, OUT hwhostname character varying) RETURNS SETOF record LANGUAGE plpgsql AS $$ BEGIN RETURN QUERY select hw."Code" as hwcode, hw."SerialNumber" as hwserialnumber, hw."Hostname" as hwhostname from "Hardware" hw join "Map_AssetMgtCI" mapamci on mapamci."IdObj2"=hw."Id" and mapamci."Status"='A' WHERE hw."Status" = 'A' and mapamci."IdObj1"=processid; END $$; DROP FUNCTION public.rep_am_barcodeprint(processid bigint, OUT hwcode character varying, OUT hwserialnumber character varying, OUT hwhostname character varying); publicpostgresfalse1255233252rep_am_list(bigint, date, date)FUNCTIONCREATE FUNCTION public.rep_am_list(assettype bigint, startdate date, enddate date, OUT wfnumber character varying, OUT hwcode character varying, OUT hwtype character varying, OUT hwbuilding character varying, OUT hwfloor character varying, OUT hwroom character varying, OUT hwroomtype character varying, OUT hwassignee character varying, OUT hwavailability character varying, OUT hwmodel character varying, OUT hwstate character varying, OUT wfclosuredate timestamp with time zone, OUT wforiguser character varying, OUT wfdstuser character varying, OUT wftype character varying, OUT wfdststatus text, OUT wfdstroomtype character varying, OUT wfdestination character varying) RETURNS SETOF record LANGUAGE plpgsql AS $$ DECLARE assetclass text; BEGIN select coalesce('"'||l."Code"||'"','"Hardware"') from "LookUp" l where "Id" = assettype INTO assetclass; RETURN QUERY select assmgt."Number" as wfnumber, hw."Code" as hwcode, trim(both '"' from hw."IdClass"::text)::varchar as hwtype, coalesce(b."Description",'unknown building') as hwbuilding, coalesce(f."Code",'unknown floor') as hwfloor, coalesce(r."Description",'unknown room') as hwroom, coalesce(lr."Description"||': ','Location: ')::varchar as hwroomtype, coalesce (e."Description", 'Not assigned') as hwassignee, coalesce(l1."Description",'N/A') as hwavailability, coalesce(hw."Model",'N/A') as hwmodel, coalesce(l3."Description",'N/A') as hwstate, assmgt."ClosureTimestamp" as wfclosuredate, coalesce(e2."Description",'Not assigned') as wforiguser, coalesce(e3."Description",'Not assigned') as wfdstuser, lp6."Description" as wftype, CASE WHEN ( lp6."Code" = 'Replacement' AND l4."Description" = 'To warehouse') OR lp6."Code" = 'Withdrawal' OR lp6."Code" = 'TransferBtwWarehouses' THEN lp8."Description" ELSE CASE WHEN lp6."Code" = 'Acceptance' THEN 'Available' ELSE CASE WHEN lp6."Code" = 'Assignment' THEN 'In use' ELSE CASE WHEN lp6."Code" = 'Replacement' AND l4."Description" = 'From warehouse' THEN 'In use' ELSE CASE WHEN lp6."Code" = 'TransferBtwUsers' THEN 'In use' ELSE CASE WHEN lp6."Code" = 'MoveUser' THEN 'In use' ELSE CASE WHEN lp6."Code" = 'Disposal' THEN 'Disposed' END END END END END END END as wfdststatus, CASE WHEN lp6."Code" = 'Replacement' and l4."Code" = '-' THEN lr2."Description" ELSE CASE WHEN lp6."Code" = 'Replacement' and l4."Code" = '+' THEN lr4."Description" ELSE CASE WHEN lr2."Code" is not null THEN lr2."Description" ELSE lr4."Description" END END END as wfdstroomtype, CASE WHEN lp6."Code" = 'Replacement' and l4."Code" = '-' THEN r2."Description" ELSE CASE WHEN lp6."Code" = 'Replacement' and l4."Code" = '+' THEN r4."Code" ELSE CASE WHEN r2."Code" is not null THEN r2."Code" ELSE r4."Code" END END END as wfdestination from "Hardware" hw left outer join "Map_AssetMgtCI" mapamci on mapamci."IdObj2"=hw."Id" and mapamci."Status"='A' left outer join "AssetMgt" assmgt on assmgt."Id"=mapamci."IdObj1" and assmgt."Status"='A' left outer join "Building" b on b."Id"=hw."Building" and b."Status"='A' left outer join "Floor" f on f."Id"=hw."Floor" and f."Status"='A' left outer join "Room" r on r."Id"=hw."Room" and r."Status"='A' left outer join "Room" r2 on r2."Id"=assmgt."DstRoom" and r2."Status"='A' left outer join "Room" r4 on r4."Id"=assmgt."DstWrhouse" and r4."Status"='A' left outer join "Employee" e on e."Id"=hw."Assignee" and e."Status"='A' left outer join "Employee" e2 on e2."Id"=assmgt."DstUser" and e2."Status"='A' left outer join "Employee" e3 on e3."Id"=assmgt."OrigUser" and e3."Status"='A' left outer join "LookUp" lr on lr."Id"=r."Use" and lr."Status"='A' left outer join "LookUp" l1 on l1."Id"=hw."Availability" and l1."Status"='A' left outer join "LookUp" l3 on l3."Id"=hw."State" and l3."Status"='A' left outer join "LookUp" l4 on l4."Id"=mapamci."Direction" and l4."Status"='A' left outer join "LookUp" lr2 on lr2."Id"=r2."Use" and lr2."Status"='A' left outer join "LookUp" lr4 on lr4."Id"=r4."Use" and lr4."Status"='A' left outer join "LookUp" lp6 on lp6."Id"=assmgt."Type" and lp6."Status"='A' left outer join "LookUp" lp7 on lp7."Id"=assmgt."FlowStatus" and lp7."Status"='A' left outer join "LookUp" lp8 on lp8."Id"=assmgt."DstStatus" and lp8."Status"='A' WHERE hw."Status" = 'A' and lp7."Code" = 'closed.completed' and ( case when assetclass is not null then hw."IdClass" = assetclass::regclass else true end ) and ( case when startdate is not null then assmgt."ClosureTimestamp"::date >= startdate else true end ) and ( case when enddate is not null then assmgt."ClosureTimestamp"::date <= enddate else true end ) order by hw."Code", assmgt."ClosureTimestamp" asc; END $$; DROP FUNCTION public.rep_am_list(assettype bigint, startdate date, enddate date, OUT wfnumber character varying, OUT hwcode character varying, OUT hwtype character varying, OUT hwbuilding character varying, OUT hwfloor character varying, OUT hwroom character varying, OUT hwroomtype character varying, OUT hwassignee character varying, OUT hwavailability character varying, OUT hwmodel character varying, OUT hwstate character varying, OUT wfclosuredate timestamp with time zone, OUT wforiguser character varying, OUT wfdstuser character varying, OUT wftype character varying, OUT wfdststatus text, OUT wfdstroomtype character varying, OUT wfdestination character varying); publicpostgresfalseJ1255233253rep_barcodeprint(bigint)FUNCTIONCREATE FUNCTION public.rep_barcodeprint(hardware bigint, OUT hwcode character varying, OUT hwserialnumber character varying, OUT hwhostname character varying) RETURNS SETOF record LANGUAGE plpgsql AS $$ BEGIN RETURN QUERY SELECT hw."Code" AS hwcode, hw."SerialNumber" AS hwserialnumber, hw."Hostname" AS hwhostname FROM "Hardware" hw WHERE hw."Status" = 'A' AND hw."Id" = hardware; END $$; DROP FUNCTION public.rep_barcodeprint(hardware bigint, OUT hwcode character varying, OUT hwserialnumber character varying, OUT hwhostname character varying); publicpostgresfalseV1255233254 rep_connector_gettextstyle(text)FUNCTIONCREATE FUNCTION public.rep_connector_gettextstyle(INOUT field text) RETURNS text LANGUAGE sql AS $_$ select ''||$1||''; $_$; CDROP FUNCTION public.rep_connector_gettextstyle(INOUT field text); publicpostgresfalse1255233255(rep_im_avgclosingtime(character varying)FUNCTIONU CREATE FUNCTION public.rep_im_avgclosingtime(sorting character varying, OUT month character varying, OUT avg numeric) RETURNS SETOF record LANGUAGE plpgsql AS $$ BEGIN IF sorting = 'desc' THEN RETURN QUERY select to_char(now() - '1 month'::interval * i, 'YYYY-MM')::varchar as month, case when avg(("TTHDClassification"+"TTHDAnalysis"+"TTHDExecution"+"TTHDStartCM"+"TTHDSuspension"+"TTHDClosure"+"TTSPClassification"+"TTSPAnalysis"+"TTSPExecution"+"TTSPStartCM"+"TTSPSuspension"+"TTSPClosure")::numeric(12,2)/3600) is null then 0 else avg(("TTHDClassification"+"TTHDAnalysis"+"TTHDExecution"+"TTHDStartCM"+"TTHDSuspension"+"TTHDClosure"+"TTSPClassification"+"TTSPAnalysis"+"TTSPExecution"+"TTSPStartCM"+"TTSPSuspension"+"TTSPClosure")::numeric(12,2)/3600) END as avg FROM generate_series(0,11) i left outer join ("IncidentMgt" join "LookUp" on "LookUp"."Id" = "IncidentMgt"."FlowStatus" and "LookUp"."Code" = 'closed.completed') on "IncidentMgt"."ClosureTimestamp" between date_trunc('month', now() - '1 month'::interval * i) and date_trunc('month', now() - '1 month'::interval * i) + '1 month'::interval - '1 sec'::interval and "IncidentMgt"."Status" = 'A' group by to_char(now() - '1 month'::interval * i, 'YYYY-MM') order by 1 desc; ELSE RETURN QUERY select to_char(now() - '1 month'::interval * i, 'YYYY-MM')::varchar as month, case when avg(("TTHDClassification"+"TTHDAnalysis"+"TTHDExecution"+"TTHDStartCM"+"TTHDSuspension"+"TTHDClosure"+"TTSPClassification"+"TTSPAnalysis"+"TTSPExecution"+"TTSPStartCM"+"TTSPSuspension"+"TTSPClosure")::numeric(12,2)/3600) is null then 0 else avg(("TTHDClassification"+"TTHDAnalysis"+"TTHDExecution"+"TTHDStartCM"+"TTHDSuspension"+"TTHDClosure"+"TTSPClassification"+"TTSPAnalysis"+"TTSPExecution"+"TTSPStartCM"+"TTSPSuspension"+"TTSPClosure")::numeric(12,2)/3600) END as avg FROM generate_series(0,11) i left outer join ("IncidentMgt" join "LookUp" on "LookUp"."Id" = "IncidentMgt"."FlowStatus" and "LookUp"."Code" = 'closed.completed') on "IncidentMgt"."ClosureTimestamp" between date_trunc('month', now() - '1 month'::interval * i) and date_trunc('month', now() - '1 month'::interval * i) + '1 month'::interval - '1 sec'::interval and "IncidentMgt"."Status" = 'A' group by to_char(now() - '1 month'::interval * i, 'YYYY-MM') order by 1 asc; END if; END $$; uDROP FUNCTION public.rep_im_avgclosingtime(sorting character varying, OUT month character varying, OUT avg numeric); publicpostgresfalse1255233256Vrep_im_dailydistributionbytimeslot(timestamp with time zone, timestamp with time zone)FUNCTIONCREATE FUNCTION public.rep_im_dailydistributionbytimeslot(date1 timestamp with time zone, date2 timestamp with time zone, OUT hour text, OUT tot bigint) RETURNS SETOF record LANGUAGE plpgsql AS $$ BEGIN RETURN QUERY SELECT to_char(('00:00'::time + '1 hour'::interval * i ),'HH24:MI') || ' - ' || to_char(('00:00'::time + ('1 hour'::interval * (i+1)) - ('1 minute'::interval)),'HH24:MI') as hour, --to_char(('00:00'::time + '1 hour'::interval * i ),'HH24:MI') as hour, sum(case when im."CreationTimestamp"::time between ('00:00'::time + ('1 hour'::interval*i) ) and ('00:00'::time + ('1 hour'::interval * (i+1)) - '1 ms'::interval ) and im."Status" = 'A' then 1 else 0 end) as tot FROM generate_series(0,23) i LEFT OUTER JOIN "IncidentMgt" im ON im."CreationTimestamp"::time between ('00:00'::time + ('1 hour'::interval*i) ) and ('00:00'::time + ('1 hour'::interval * (i+1)) - '1 ms'::interval ) AND (case when date1 is not null then im."CreationTimestamp" >= date1 else true end) and (case when date2 is not null then im."CreationTimestamp" <= date2 else true end) where im."Status" = 'A' group by hour order by 1; END; $$; DROP FUNCTION public.rep_im_dailydistributionbytimeslot(date1 timestamp with time zone, date2 timestamp with time zone, OUT hour text, OUT tot bigint); publicpostgresfalse1255233257 rep_im_open()FUNCTIONCREATE FUNCTION public.rep_im_open(OUT currentactivity character varying, OUT requestname character varying, OUT creationdate date, OUT processstatus character varying, OUT priority character varying, OUT area character varying, OUT requester character varying, OUT expectedclosuredate character varying, OUT shortdescription text, OUT category character varying, OUT totaltime text) RETURNS SETOF record LANGUAGE plpgsql AS $$ BEGIN RETURN QUERY SELECT coalesce(im."Code",'Not available') as CurrentActivity, coalesce(im."Description",'Not available') as RequestName, im."CreationTimestamp"::Date as CreationDate, coalesce(l1."Description",'Not classified') as ProcessStatus, coalesce(l2."Description",'Not prioritized') as Priority, coalesce(l3."Description",'Not assigned') as Area, coalesce(e."Description",'Not available') as Requester, coalesce(im."ExpectedClosureDate"::varchar,'Not available') as ExpectedClosureDate, im."ShortDescr" as ShortDescription, coalesce(itpc."Description",'Not categorized') as Category, coalesce( extract('hour' from (ceil((select activitytime from wf_incidentmgt_getactivitytime(im."CreationTimestamp",cast(now() AS timestamp without time zone))))*INTERVAL '1 second'))::text, '') as totaltime FROM "IncidentMgt" im LEFT JOIN "LookUp" l1 on l1."Id" = im."ProcessStatus" LEFT JOIN "LookUp" l2 on l2."Id" = im."Priority" LEFT JOIN "LookUp" l3 on l3."Id" = im."Area" LEFT JOIN "LookUp" l4 on l4."Id" = im."FlowStatus" LEFT JOIN "Employee" e on e."Id" = im."Requester" LEFT JOIN "ITProcCategory" itpc on itpc."Id" = im."Category" WHERE im."Status" = 'A' AND l4."Code" = 'open.running' ORDER BY ProcessStatus, Priority; END $$; DROP FUNCTION public.rep_im_open(OUT currentactivity character varying, OUT requestname character varying, OUT creationdate date, OUT processstatus character varying, OUT priority character varying, OUT area character varying, OUT requester character varying, OUT expectedclosuredate character varying, OUT shortdescription text, OUT category character varying, OUT totaltime text); publicpostgresfalse1255233258rep_im_timetable(bigint)FUNCTION CREATE FUNCTION public.rep_im_timetable(idprocess bigint, OUT creationtimestamp text, OUT shortdescription text, OUT extendeddescription text, OUT number character varying, OUT requester character varying, OUT hdclassificationtime text, OUT hdanalysistime text, OUT hdexecutiontime text, OUT hdstartcmtime text, OUT hdsuspensiontime text, OUT hdclosuretime text, OUT spclassificationtime text, OUT spanalysistime text, OUT spexecutiontime text, OUT spstartcmtime text, OUT spsuspensiontime text, OUT spclosuretime text, OUT code character varying, OUT status character varying, OUT priority character varying, OUT urgency character varying, OUT impact character varying, OUT currentsteptime text) RETURNS SETOF record LANGUAGE plpgsql AS $$ BEGIN RETURN QUERY select --imgt."Id", to_char("CreationTimestamp",'DD/Mon/YYYY, HH24:MI:SS') as creationtimestamp, imgt."ShortDescr" as shortdescription, coalesce(imgt."ExtDescr",'Not available') as extendedescription, imgt."Number" as number, e."Description" as requester, to_char(("TTHDClassification"||' second')::interval,'HH24:MI:SS') as hdclassificationtime, to_char(("TTHDAnalysis"||' second')::interval,'HH24:MI:SS') as hdanalysistime, to_char(("TTHDExecution"||' second')::interval,'HH24:MI:SS') as hdexecutiontime, to_char(("TTHDStartCM"||' second')::interval,'HH24:MI:SS') as hdstartcmtime, to_char(("TTHDSuspension"||' second')::interval,'HH24:MI:SS') as hdsuspensiontime, to_char(("TTHDClosure"||' second')::interval,'HH24:MI:SS') as hdclosuretime, to_char(("TTSPClassification"||' second')::interval,'HH24:MI:SS') as spclassificationtime, to_char(("TTSPAnalysis"||' second')::interval,'HH24:MI:SS') as spanalysistime, to_char(("TTSPExecution"||' second')::interval,'HH24:MI:SS') as spexecutiontime, to_char(("TTSPStartCM"||' second')::interval,'HH24:MI:SS') as spstartcmtime, to_char(("TTSPSuspension"||' second')::interval,'HH24:MI:SS') as spsuspensiontime, to_char(("TTSPClosure"||' second')::interval,'HH24:MI:SS') as spclosuretime, imgt."Code" as code, coalesce(l1."Description",'Not available') as status, coalesce(l2."Description",'Not prioritized') as priority, coalesce(l3."Description",'Not available') as urgency, coalesce(l4."Description",'Not available') as impact, coalesce(to_char((select work_time from utils_wc_get_worktime(imgt."BeginDate",now(),cal."Id")),'HH24:MI:SS'),'00:00:00') as currentsteptime from "IncidentMgt" imgt left join "LookUp" l1 on l1."Id" = imgt."ProcessStatus" and l1."Status" = 'A' left join "LookUp" l2 on l2."Id" = imgt."Priority" and l2."Status" = 'A' left join "LookUp" l3 on l3."Id" = imgt."Urgency" and l3."Status" = 'A' left join "LookUp" l4 on l4."Id" = imgt."Impact" and l4."Status" = 'A' left join "Employee" e on e."Id" = imgt."Requester" and e."Status" = 'A' left join "ServiceContract" sc on sc."Id" = imgt."ServiceContract" and sc."Status" = 'A' left join "CalendarDef" cal on cal."Id" = sc."Calendar" and cal."Status" = 'A' WHERE imgt."Status" ='A' and imgt."Id" = IdProcess; END $$; DROP FUNCTION public.rep_im_timetable(idprocess bigint, OUT creationtimestamp text, OUT shortdescription text, OUT extendeddescription text, OUT number character varying, OUT requester character varying, OUT hdclassificationtime text, OUT hdanalysistime text, OUT hdexecutiontime text, OUT hdstartcmtime text, OUT hdsuspensiontime text, OUT hdclosuretime text, OUT spclassificationtime text, OUT spanalysistime text, OUT spexecutiontime text, OUT spstartcmtime text, OUT spsuspensiontime text, OUT spclosuretime text, OUT code character varying, OUT status character varying, OUT priority character varying, OUT urgency character varying, OUT impact character varying, OUT currentsteptime text); publicpostgresfalse1255233259rep_locationswithassets()FUNCTIONCREATE FUNCTION public.rep_locationswithassets(OUT hwid bigint, OUT hwdescription character varying, OUT hwmodel character varying, OUT hwtype text, OUT roomcode character varying, OUT roomdescription character varying, OUT floordescription character varying, OUT floorcode character varying, OUT buildingdescription character varying, OUT assigneedescription character varying, OUT hwbrand character varying, OUT hwstate character varying, OUT hwavailability character varying) RETURNS SETOF record LANGUAGE plpgsql AS $$ BEGIN RETURN QUERY SELECT hw."Id" AS hwid, hw."Description" AS hwdescription, coalesce(hw."Model",'Not defined') AS hwmodel, trim('"' from hw."IdClass"::text) as hwtype, coalesce(r."Code", 'Not defined') AS roomcode, coalesce(r."Description",'Not defined') AS roomdescription, coalesce(f."Description",'Not defined') AS floordescription, coalesce(f."Code",'Not defined') AS floorcode, coalesce(b."Description",'Not defined') AS buildingdescription, coalesce(e."Description",'Not defined') AS assigneedescription, coalesce(l1."Description",'Not defined') AS hwbrand, coalesce(l2."Description",'Not defined') AS hwstate, coalesce(l3."Description",'Not defined') AS hwavailability FROM "Hardware" hw LEFT OUTER JOIN "Building" b ON b."Id"=hw."Building" AND b."Status"='A' LEFT OUTER JOIN "Floor" f ON f."Id"=hw."Floor" AND f."Status"='A' LEFT OUTER JOIN "Room" r ON r."Id"=hw."Room" AND r."Status"='A' LEFT OUTER JOIN "Employee" e ON e."Id"=hw."Assignee" AND e."Status" = 'A' LEFT OUTER JOIN "LookUp" l1 ON l1."Id"=hw."Brand" LEFT OUTER JOIN "LookUp" l2 ON l2."Id"=hw."State" LEFT OUTER JOIN "LookUp" l3 ON l3."Id"=hw."Availability" WHERE hw."Status"='A' ORDER BY b."Description", f."Description", r."Description"; END $$; DROP FUNCTION public.rep_locationswithassets(OUT hwid bigint, OUT hwdescription character varying, OUT hwmodel character varying, OUT hwtype text, OUT roomcode character varying, OUT roomdescription character varying, OUT floordescription character varying, OUT floorcode character varying, OUT buildingdescription character varying, OUT assigneedescription character varying, OUT hwbrand character varying, OUT hwstate character varying, OUT hwavailability character varying); publicpostgresfalse1255233260rep_mtbf(bigint)FUNCTIONCREATE FUNCTION public.rep_mtbf(assetclassid bigint, OUT itemid bigint, OUT itemclass text, OUT itemdescription character varying, OUT itemcode character varying, OUT itemsn character varying, OUT itembrand character varying, OUT itemmodel character varying, OUT acceptancedate date, OUT numberoffails bigint, OUT totaldowntime text, OUT totalitemlife text, OUT mtbf text) RETURNS SETOF record LANGUAGE plpgsql AS $$ DECLARE assetclass text; BEGIN IF ( assetclassid is not null) THEN select coalesce('"'||l."Code"||'"','"Hardware"') from "LookUp" l where "Id" = assetclassid INTO assetclass; RETURN QUERY select q1.itemid, q1.itemclass, q1.itemdescription, q1.itemcode, q1.itemsn, q1.itembrand, q1.itemmodel, q1.acceptancedate, q1.numberoffails, CASE WHEN q1.totaldowntime = '0' THEN '1' ELSE q1.totaldowntime END, q1.totalitemlife, q1.mtbf from ( select i."Id" as itemid, trim(both '"' from i."IdClass"::text) as itemclass, i."Description" as itemdescription, i."Code" as itemcode, i."SerialNumber" as itemsn, lb."Description" as itembrand, i."Model" as itemmodel, coalesce(i."AcceptanceDate",i."DeliveryDate") as acceptancedate, count(mr."Id") as numberoffails, coalesce( extract( 'days' from (sum( (mr."ClosureTimestamp" - mr."CreationTimestamp") )) )::text,'0' ) as totaldowntime, coalesce( (max( mr."ClosureTimestamp" )-coalesce(i."AcceptanceDate",i."DeliveryDate") )::text,'0') as totalitemlife, coalesce( extract ( 'days' from ( ((max( mr."ClosureTimestamp" )-coalesce(i."AcceptanceDate",i."DeliveryDate") )-sum( (mr."ClosureTimestamp" - mr."CreationTimestamp") ) )/count(mr."Id") ) )::text, 'N/A' ) as mtbf from "CI" i left join "Map_ITProcCI" mapmri on mapmri."IdObj2" = i."Id" and mapmri."Status" = 'A' left join "IncidentMgt" mr on mr."Id" = mapmri."IdObj1" and mr."Status" = 'A' left join "LookUp" lb on lb."Id" = i."Brand" and lb."Status" = 'A' where i."Status" = 'A' and ( i."AcceptanceDate" is not null or i."DeliveryDate" is not null ) and mr."ClosureTimestamp" is not null and i."IdClass" = assetclass::regclass group by i."Id", lb."Description" ) as q1 where q1.numberoffails > 0 order by q1.itemclass asc, q1.itemsn asc, q1.itemcode asc, q1.itemdescription asc; ELSE RETURN QUERY select q1.itemid, q1.itemclass, q1.itemdescription, q1.itemcode, q1.itemsn, q1.itembrand, q1.itemmodel, q1.acceptancedate, q1.numberoffails, CASE WHEN q1.totaldowntime = '0' THEN '1' ELSE q1.totaldowntime END, q1.totalitemlife, q1.mtbf from ( select i."Id" as itemid, trim(both '"' from i."IdClass"::text) as itemclass, i."Description" as itemdescription, i."Code" as itemcode, i."SerialNumber" as itemsn, lb."Description" as itembrand, i."Model" as itemmodel, coalesce(i."AcceptanceDate",i."DeliveryDate") as acceptancedate, count(mr."Id") as numberoffails, coalesce( extract( 'days' from (sum( (mr."ClosureTimestamp" - mr."CreationTimestamp") )) )::text,'0' ) as totaldowntime, coalesce( (max( mr."ClosureTimestamp" )-coalesce(i."AcceptanceDate",i."DeliveryDate"))::text,'0') as totalitemlife, coalesce( extract ( 'days' from ( ((max( mr."ClosureTimestamp" )-coalesce(i."AcceptanceDate",i."DeliveryDate") )-sum( (mr."ClosureTimestamp" - mr."CreationTimestamp") ) )/count(mr."Id") ) )::text, 'N/A' ) as mtbf from "CI" i left join "Map_ITProcCI" mapmri on mapmri."IdObj2" = i."Id" and mapmri."Status" = 'A' left join "IncidentMgt" mr on mr."Id" = mapmri."IdObj1" and mr."Status" = 'A' left join "LookUp" lb on lb."Id" = i."Brand" and lb."Status" = 'A' where i."Status" = 'A' and ( i."AcceptanceDate" is not null or i."DeliveryDate" is not null ) and mr."ClosureTimestamp" is not null group by i."Id", lb."Description" ) as q1 where q1.numberoffails > 0 order by q1.itemclass asc, q1.itemsn asc, q1.itemcode asc, q1.itemdescription asc; END IF; END; $$; tDROP FUNCTION public.rep_mtbf(assetclassid bigint, OUT itemid bigint, OUT itemclass text, OUT itemdescription character varying, OUT itemcode character varying, OUT itemsn character varying, OUT itembrand character varying, OUT itemmodel character varying, OUT acceptancedate date, OUT numberoffails bigint, OUT totaldowntime text, OUT totalitemlife text, OUT mtbf text); publicpostgresfalse1255233261rep_racklayout()FUNCTION, CREATE FUNCTION public.rep_racklayout(OUT rack_code character varying, OUT rack_descr character varying, OUT tot_ru integer, OUT ru_id integer, OUT item_unit integer, OUT item_descr character varying, OUT item_type text, OUT item_type_f text, OUT item_type_r text, OUT item_type_w text, OUT item_descr_f character varying, OUT item_descr_r character varying, OUT item_descr_w character varying, OUT item_position character varying, OUT item_size integer, OUT item_last integer) RETURNS SETOF record LANGUAGE plpgsql AS $$ DECLARE max_id integer; rack_row "Rack"%ROWTYPE; max_size INTEGER; BEGIN SELECT max("TotalUnits") INTO max_size FROM "Rack" WHERE "Rack"."Status"='A' AND "Rack"."TotalUnits" IS NOT NULL; RAISE NOTICE 'Numero massimo di slot: %',max_size; RETURN QUERY SELECT rack."Code" as rack_code, rack."Description" as rack_descr, rack."TotalUnits" as tot_ru, serie.ru_id, -- item."RackUnit" AS item_unit, item."Description" AS item_descr, replace(item."IdClass"::text,'"','') as item_type, CASE WHEN (l1."Code" = 'Front' ) THEN btrim(item."IdClass"::text, '"') WHEN (l1."Code" <> 'Front' ) THEN '' END AS item_type_f, CASE WHEN (l1."Code" = 'Back') THEN btrim(item."IdClass"::text, '"') WHEN (l1."Code" <> 'Back' ) THEN '' END AS item_type_r, CASE WHEN (l1."Code" = 'Whole') THEN btrim(item."IdClass"::text, '"') WHEN (l1."Code" <> 'Whole' ) THEN '' END AS item_type_w, CASE WHEN (l1."Code" = 'Front' ) THEN item."Description" WHEN (l1."Code" <> 'Front' ) THEN '' END AS item_descr_f, CASE WHEN (l1."Code" = 'Back') THEN item."Description" WHEN (l1."Code" <> 'Back' ) THEN '' END AS item_descr_r, CASE WHEN (l1."Code" = 'Whole') THEN item."Description" WHEN (l1."Code" <> 'Whole' ) THEN '' END AS item_descr_w, l1."Description" as item_position, item."NumOfUnits" AS item_size, item."RackUnit" + item."NumOfUnits" -1 as item_last FROM "Rack" rack JOIN generate_series(1,max_size) AS serie(ru_id) ON serie.ru_id <= rack."TotalUnits" LEFT JOIN "ServerHW" item ON item."Rack" = rack."Id" AND item."RackUnit" <= serie.ru_id AND serie.ru_id= date1 else true end) and (case when date2 is not null then im."CreationTimestamp" <= date2 else true end) where im."Status" = 'A' group by hour order by 1; END; $$; DROP FUNCTION public.rep_rf_dailydistributionbytimeslot(date1 timestamp with time zone, date2 timestamp with time zone, OUT hour text, OUT tot bigint); publicpostgresfalse1255233264 rep_rf_open()FUNCTION?CREATE FUNCTION public.rep_rf_open(OUT currentactivity character varying, OUT requestname character varying, OUT creationdate date, OUT processstatus character varying, OUT priority character varying, OUT area character varying, OUT requester character varying, OUT expectedclosuredate character varying, OUT shortdescription text, OUT category character varying, OUT totaltime text) RETURNS SETOF record LANGUAGE plpgsql AS $$ BEGIN RETURN QUERY SELECT coalesce(rf."Code",'Not available') as CurrentActivity, coalesce(rf."Description",'Not available') as RequestName, rf."CreationTimestamp"::Date as CreationDate, coalesce(l1."Description",'Not classified') as ProcessStatus, coalesce(l2."Description",'Not prioritized') as Priority, coalesce(l3."Description",'Not assigned') as Area, coalesce(e."Description",'Not available') as Requester, coalesce(rf."ExpectedClosureDate"::varchar,'Not available') as ExpectedClosureDate, rf."ShortDescr" as ShortDescription, coalesce(itpc."Description",'Not categorized') as Category, -- coalesce( extract('day' from (now()-rf."CreationTimestamp") ) || ' days,' || extract('hour' from (now()-rf."CreationTimestamp") ) || ' hours', 'N/A') as TotalTime coalesce( extract('hour' from (ceil((select activitytime from wf_reqfulfil_getactivitytime(rf."CreationTimestamp",cast(now() AS timestamp without time zone))))*INTERVAL '1 second'))::text, '') as totaltime FROM "ReqFulfil" rf LEFT JOIN "LookUp" l1 on l1."Id" = rf."ProcessStatus" LEFT JOIN "LookUp" l2 on l2."Id" = rf."Priority" LEFT JOIN "LookUp" l3 on l3."Id" = rf."Area" LEFT JOIN "LookUp" l4 on l4."Id" = rf."FlowStatus" LEFT JOIN "Employee" e on e."Id" = rf."Requester" LEFT JOIN "ITProcCategory" itpc on itpc."Id" = rf."Category" WHERE rf."Status" = 'A' AND l4."Code" = 'open.running' ORDER BY ProcessStatus, Priority; END $$; DROP FUNCTION public.rep_rf_open(OUT currentactivity character varying, OUT requestname character varying, OUT creationdate date, OUT processstatus character varying, OUT priority character varying, OUT area character varying, OUT requester character varying, OUT expectedclosuredate character varying, OUT shortdescription text, OUT category character varying, OUT totaltime text); publicpostgresfalse1255233265rep_rf_timetable(bigint)FUNCTIONECREATE FUNCTION public.rep_rf_timetable(idprocess bigint, OUT creationtimestamp text, OUT shortdescription text, OUT extendeddescription text, OUT number character varying, OUT requester character varying, OUT approvaltime text, OUT analysistime text, OUT hdclassificationtime text, OUT hdclosuretime text, OUT hdinfomgttime text, OUT spclassificationtime text, OUT spclosuretime text, OUT spinfomgttime text, OUT ttworkorderstime text, OUT code character varying, OUT status character varying, OUT priority character varying, OUT urgency character varying, OUT impact character varying, OUT currentsteptime text) RETURNS SETOF record LANGUAGE plpgsql AS $$ BEGIN RETURN QUERY select to_char("CreationTimestamp",'DD/Mon/YYYY, HH24:MI:SS') as creationtimestamp, reqff."ShortDescr" as shortdescription, coalesce(reqff."ExtDescr",'Not available')::text as extendedescription, reqff."Number" as number, e."Description" as requester, to_char(("TTApproval"||' second')::interval,'HH24:MI:SS') as approvaltime, to_char(("TTAnalysis"||' second')::interval,'HH24:MI:SS') as analysistime, to_char(("TTHDClassification"||' second')::interval,'HH24:MI:SS') as hdclassificationtime, to_char(("TTHDClosure"||' second')::interval,'HH24:MI:SS') as hdclosuretime, to_char(("TTHDInfoMgt"||' second')::interval,'HH24:MI:SS') as hdinfomgttime, to_char(("TTSPClassification"||' second')::interval,'HH24:MI:SS') as spclassificationtime, to_char(("TTSPClosure"||' second')::interval,'HH24:MI:SS') as spclosuretime, to_char(("TTSPInfoMgt"||' second')::interval,'HH24:MI:SS') as spinfomgttime, to_char(("TTWorkorders"||' second')::interval,'HH24:MI:SS') as ttworkorderstime, reqff."Code" as code, coalesce(l1."Description",'Not available') as status, coalesce(l2."Description",'Not prioritized') as priority, coalesce(l3."Description",'Not available') as urgency, coalesce(l4."Description",'Not available') as impact, CASE WHEN l1."Code" = 'Classification' and reqff."STSPClassification" is null THEN coalesce(to_char((now()-"STHDClassification"),'HH24:MI:SS'),'00:00:00') ELSE CASE WHEN l1."Code" = 'Execution' and reqff."STSPInfoMgt" is null THEN coalesce(to_char((now()-"STHDInfoMgt"),'HH24:MI:SS'),'00:00:00') ELSE CASE WHEN l1."Code" = 'Analysis' and "STAnalysis" is not null THEN coalesce(to_char((now()-"STAnalysis"),'HH24:MI:SS'),'00:00:00') ELSE CASE WHEN l1."Code" = 'Approval' THEN coalesce(to_char((now()-"STApproval"),'HH24:MI:SS'),'00:00:00') ELSE CASE WHEN l1."Code" = 'Execution' and (reqff."STHDInfoMgt" is null and reqff."STSPInfoMgt" is null) THEN coalesce(to_char((now()-"STWorkorders"),'HH24:MI:SS'),'00:00:00') ELSE CASE WHEN l1."Code" = 'Closure' and reqff."STSPClosure" is null THEN coalesce(to_char((now()-"STHDClosure"),'HH24:MI:SS'),'00:00:00') ELSE CASE WHEN l1."Code" = 'Classification' and reqff."STHDClassification" is null THEN coalesce(to_char((now()-"STSPClassification"),'HH24:MI:SS'),'00:00:00') ELSE CASE WHEN l1."Code" = 'Execution' and reqff."STHDInfoMgt" is null THEN coalesce(to_char((now()-"STSPInfoMgt"),'HH24:MI:SS'),'00:00:00') ELSE CASE WHEN l1."Code" = 'Closure' and reqff."STHDClosure" is null THEN coalesce(to_char((now()-"STSPClosure"),'HH24:MI:SS'),'00:00:00') END END END END END END END END END as currentsteptime from "ReqFulfil" reqff left join "LookUp" l1 on l1."Id" = reqff."ProcessStatus" and l1."Status" = 'A' left join "LookUp" l2 on l2."Id" = reqff."Priority" and l2."Status" = 'A' left join "LookUp" l3 on l3."Id" = reqff."Urgency" and l3."Status" = 'A' left join "LookUp" l4 on l4."Id" = reqff."Impact" and l4."Status" = 'A' left join "Employee" e on e."Id" = reqff."Requester" and e."Status" = 'A' WHERE reqff."Status" ='A' and reqff."Id" = IdProcess; END $$; eDROP FUNCTION public.rep_rf_timetable(idprocess bigint, OUT creationtimestamp text, OUT shortdescription text, OUT extendeddescription text, OUT number character varying, OUT requester character varying, OUT approvaltime text, OUT analysistime text, OUT hdclassificationtime text, OUT hdclosuretime text, OUT hdinfomgttime text, OUT spclassificationtime text, OUT spclosuretime text, OUT spinfomgttime text, OUT ttworkorderstime text, OUT code character varying, OUT status character varying, OUT priority character varying, OUT urgency character varying, OUT impact character varying, OUT currentsteptime text); publicpostgresfalse212552576911rep_workplacesinventory(timestamp with time zone)FUNCTIONCREATE FUNCTION public.rep_workplacesinventory(_timestamp_date timestamp with time zone, OUT invdate timestamp with time zone, OUT class character varying, OUT code character varying, OUT description character varying, OUT serialnumber character varying, OUT partnumber character varying, OUT hostname character varying, OUT buildingdescription character varying, OUT floorlevel character varying, OUT roomcode character varying, OUT employeedescription character varying, OUT availability character varying, OUT brand character varying, OUT model character varying, OUT state character varying, OUT environment character varying, OUT supplierdescription character varying, OUT warrantyenddate date, OUT deliveryenddate date, OUT acceptancedate date, OUT disposaldate date, OUT orderrowcode character varying, OUT os character varying, OUT osversion character varying, OUT ram integer, OUT hdsize integer, OUT costprice numeric, OUT cpu character varying, OUT computer character varying, OUT link character varying) RETURNS SETOF record LANGUAGE plpgsql AS $_$ DECLARE _date date = coalesce(_timestamp_date, now())::date; BEGIN RETURN QUERY SELECT $1 as invdate, _cm3_class_comment_get("ClientHW"."IdClass", 'DESCR') as class, "ClientHW"."Code" as code, "ClientHW"."Description" as description, "ClientHW"."SerialNumber" as serialnumber, "ClientHW"."PartNumber" as partnumber, "ClientHW"."Hostname" as hostname, "Building"."Description" as buildingdescription, l5."Description" as floorlevel, "Room"."Code" as roomcode, "Employee"."Description" as employeedescription, l0."Description" as availability, l1."Description" as brand, "ClientHW"."Model" as model, l2."Description" as state, l3."Description" as environment, "Supplier"."Description" as supplierdescription, "ClientHW"."WarrantyEnd" as warrantyenddate, "ClientHW"."DeliveryDate" as deliverydate, "ClientHW"."AcceptanceDate" as acceptancedate, "ClientHW"."DisposalDate" as disposaldate, "PurchaseOrderRow"."Code" as orderrowcode, l4."Description" as os, "ClientHW"."OSVersion" as osversion, "ClientHW"."RAM" as ram, "ClientHW"."HDSize" as hdsize, "ClientHW"."CostPrice" as costprice, "ClientHW"."CPU" as cpu, case when "ClientHW"."IdClass" in ('"Monitor"', '"Printer"') then (select "Computer"."Description" from _cm3_card_list_at_date(NULL::"ClientPeripheral", _date) as "ClientPeripheral", _cm3_card_list_at_date(NULL::"Computer", _date) as "Computer" where "ClientPeripheral"."CurrentId" = "ClientHW"."CurrentId" and "Computer"."CurrentId" = "ClientPeripheral"."Computer") else null end as computer, ((select "Value" from "Parameter" where "Code" = 'Server-URL' and "Status" = 'A') || '#classes/' || _cm3_utils_regclass_to_name("ClientHW"."IdClass") || '/cards/Code~' || "ClientHW"."Code")::varchar from _cm3_card_list_at_date(NULL::"ClientHW", _date) as "ClientHW" left outer join _cm3_card_list_at_date(NULL::"Building", _date) as "Building" on "Building"."CurrentId" = "ClientHW"."Building" left outer join _cm3_card_list_at_date(NULL::"Floor", _date) as "Floor" on "Floor"."CurrentId" = "ClientHW"."Floor" left outer join _cm3_card_list_at_date(NULL::"Room", _date) as "Room" on "Room"."CurrentId" = "ClientHW"."Room" left outer join _cm3_card_list_at_date(NULL::"Employee", _date) as "Employee" on "Employee"."CurrentId" = "ClientHW"."Assignee" left outer join _cm3_card_list_at_date(NULL::"Supplier", _date) as "Supplier" on "Supplier"."CurrentId" = "ClientHW"."Supplier" left outer join _cm3_card_list_at_date(NULL::"PurchaseOrderRow", _date) as "PurchaseOrderRow" on "PurchaseOrderRow"."CurrentId" = "ClientHW"."OrderRow" left outer join "LookUp" as l0 on l0."Id" = "ClientHW"."Availability" and l0."Status" = 'A' left outer join "LookUp" as l1 on l1."Id" = "ClientHW"."Brand" and l1."Status" = 'A' left outer join "LookUp" as l2 on l2."Id" = "ClientHW"."State" and l2."Status" = 'A' left outer join "LookUp" as l3 on l3."Id" = "ClientHW"."Environment" and l3."Status" = 'A' left outer join "LookUp" as l4 on l4."Id" = "ClientHW"."OS" and l4."Status" = 'A' left outer join "LookUp" as l5 on l5."Id" = "Floor"."Level" and l5."Status" = 'A' order by 2,3; END $_$; DROP FUNCTION public.rep_workplacesinventory(_timestamp_date timestamp with time zone, OUT invdate timestamp with time zone, OUT class character varying, OUT code character varying, OUT description character varying, OUT serialnumber character varying, OUT partnumber character varying, OUT hostname character varying, OUT buildingdescription character varying, OUT floorlevel character varying, OUT roomcode character varying, OUT employeedescription character varying, OUT availability character varying, OUT brand character varying, OUT model character varying, OUT state character varying, OUT environment character varying, OUT supplierdescription character varying, OUT warrantyenddate date, OUT deliveryenddate date, OUT acceptancedate date, OUT disposaldate date, OUT orderrowcode character varying, OUT os character varying, OUT osversion character varying, OUT ram integer, OUT hdsize integer, OUT costprice numeric, OUT cpu character varying, OUT computer character varying, OUT link character varying); publicpostgresfalse1255233267$report_activetickets_process(bigint)FUNCTIONWCREATE FUNCTION public.report_activetickets_process(process bigint) RETURNS text LANGUAGE plpgsql AS $$ DECLARE description text; BEGIN SELECT CASE WHEN ("Code" = 'IM') THEN '"IncidentMgt"' WHEN ("Code" = 'RF') THEN '"ReqFulfil"' END INTO description FROM "LookUp" WHERE "Id" = process; RETURN description; END; $$; CDROP FUNCTION public.report_activetickets_process(process bigint); publicpostgresfalse1255233268Treport_activeticketsindate(bigint, bigint, bigint, bigint, timestamp with time zone)FUNCTION~CREATE FUNCTION public.report_activeticketsindate("group" bigint, process bigint, category bigint, subcategory bigint, date timestamp with time zone, OUT "Group" character varying, OUT "TicketNumber" character varying, OUT "Description" character varying, OUT "Requester" character varying, OUT "ProcessClass" text, OUT "ProcessCategory" character varying, OUT "ProcessSubcategory" character varying, OUT "StatusCode" character varying, OUT "StatusDescription" character varying, OUT "CreationDate" timestamp with time zone, OUT "LastModified" timestamp with time zone, OUT "TotalAssigned" double precision, OUT "TotalExecution" double precision, OUT "TotalSuspended" double precision, OUT "TotalToAnswer" double precision, OUT "TotalPermanence" double precision, OUT "TotalElaboration" double precision) RETURNS SETOF record LANGUAGE plpgsql AS $$ BEGIN "date" = coalesce("date", now()); --data = (data::date + interval '23 hours 59 minutes 59 seconds'); RETURN QUERY SELECT (SELECT "Role"."Description" FROM "Role" WHERE "Role"."Id" = "group") AS "Group", p."Number" AS "TicketNumber", p."Description" AS "Description", e."Description" AS "Requester", p."IdClass"::text AS "ProcessClass", coalesce (pc."Code") AS "ProcessCategory", coalesce (sc."Code") AS "ProcessSubcategory", l0."Code" AS "StatusCode", l0."Description" AS "StatusDescription", p."CreationTimestamp" AS "CreationDate", p."BeginDate" AS "LastModified", (nullif( report_activeticketsindate_code(p."IdClass"::varchar, report_activeticketsindate_activepid(p."IdClass"::varchar, p."Id"), "group", "date", 'Opening')+ report_activeticketsindate_code(p."IdClass"::varchar, report_activeticketsindate_activepid(p."IdClass"::varchar, p."Id"), "group", "date", 'Classification')+ report_activeticketsindate_code(p."IdClass"::varchar, report_activeticketsindate_activepid(p."IdClass"::varchar, p."Id"), "group", "date", 'Analysis')+ (CASE WHEN p."Status" = 'A' AND (l0."Code" = 'Opening' OR l0."Code" = 'Classification' OR l0."Code" = 'Analysis') THEN report_activeticketsindate_getactivitytime(LEAST(p."BeginDate", "date"), "date") ELSE 0 END ) ,0)) AS "TotalAssigned", (nullif( report_activeticketsindate_code(p."IdClass"::varchar, report_activeticketsindate_activepid(p."IdClass"::varchar, p."Id"), "group", "date", 'Execution')+ (CASE WHEN p."Status" = 'A' AND (l0."Code" = 'Execution') THEN report_activeticketsindate_getactivitytime(LEAST(p."BeginDate", "date"), "date") ELSE 0 END ) ,0)) AS "TotalExecution", (nullif( report_activeticketsindate_code(p."IdClass"::varchar, report_activeticketsindate_activepid(p."IdClass"::varchar, p."Id"), "group", "date", 'WaitForRelatedProcess')+ report_activeticketsindate_code(p."IdClass"::varchar, report_activeticketsindate_activepid(p."IdClass"::varchar, p."Id"), "group", "date", 'StartCM')+ report_activeticketsindate_code(p."IdClass"::varchar, report_activeticketsindate_activepid(p."IdClass"::varchar, p."Id"), "group", "date", 'Suspended')+ (CASE WHEN p."Status" = 'A' AND (l0."Code" = 'WaitForRelatedProcess' OR l0."Code" = 'StartCM' OR l0."Code" = 'Suspended') THEN report_activeticketsindate_getactivitytime(LEAST(p."BeginDate", "date"), "date") ELSE 0 END ) ,0)) AS "TotalSuspended", (nullif( report_activeticketsindate_code(p."IdClass"::varchar, report_activeticketsindate_activepid(p."IdClass"::varchar, p."Id"), "group", "date", 'Closure')+ (CASE WHEN p."Status" = 'A' AND (l0."Code" = 'Closure') THEN report_activeticketsindate_getactivitytime(LEAST(p."BeginDate", "date"), "date") ELSE 0 END ) ,0)) AS "TotalToAnswer", (nullif((report_activeticketsindate_perm(p."IdClass"::varchar, report_activeticketsindate_activepid(p."IdClass"::varchar, p."Id"), "group","date")) + (CASE WHEN p."Status" = 'A' THEN report_activeticketsindate_getactivitytime(LEAST(p."BeginDate", "date"), "date") ELSE 0 END), 0)) AS "TotalPermanence", (report_activeticketsindate_getactivitytime(report_activeticketsindate_opening(p."IdClass"::varchar, report_activeticketsindate_activepid(p."IdClass"::varchar, p."Id")), "date")) AS "TotalElaboration" FROM cm_class(null::"ITProc", "date") AS p LEFT OUTER JOIN "Employee" e ON e."Id" = p."Requester" AND e."Status" = 'A' -- requester LEFT OUTER JOIN "LookUp" l0 ON l0."Id" = p."ProcessStatus" AND l0."Status" = 'A' -- LookUp Type = ITProc - ProcessStatus LEFT OUTER JOIN "LookUp" l1 ON l1."Id" = p."FlowStatus" AND l1."Status" = 'A' -- LookUp Type = FlowStatus LEFT OUTER JOIN "Role" r on r."Id" = p."CurrentRole" AND r."Status" = 'A' LEFT OUTER JOIN "ITProcCategory" pc on pc."Id" = p."Category" AND pc."Status" = 'A' LEFT OUTER JOIN "ITProcSubcategory" sc on sc."Id" = p."Subcategory" AND sc."Status" = 'A' WHERE p."CurrentRole" = "group" AND (p."IdClass"::text = report_activetickets_process(process) OR process IS NULL) AND l0."Code" NOT IN ('Closed') AND l1."Code" IN ('open.running', 'open.not_running.suspended') AND (p."Category" = category OR category IS NULL) AND (p."Subcategory" = subcategory OR subcategory IS NULL) ORDER BY p."IdClass", pc."Code", sc."Code", substr(p."Number", 3, length(p."Number")-2)::integer; END; $$; $DROP FUNCTION public.report_activeticketsindate("group" bigint, process bigint, category bigint, subcategory bigint, date timestamp with time zone, OUT "Group" character varying, OUT "TicketNumber" character varying, OUT "Description" character varying, OUT "Requester" character varying, OUT "ProcessClass" text, OUT "ProcessCategory" character varying, OUT "ProcessSubcategory" character varying, OUT "StatusCode" character varying, OUT "StatusDescription" character varying, OUT "CreationDate" timestamp with time zone, OUT "LastModified" timestamp with time zone, OUT "TotalAssigned" double precision, OUT "TotalExecution" double precision, OUT "TotalSuspended" double precision, OUT "TotalToAnswer" double precision, OUT "TotalPermanence" double precision, OUT "TotalElaboration" double precision); publicpostgresfalse1255233269?report_activeticketsindate_activepid(character varying, bigint)FUNCTION%CREATE FUNCTION public.report_activeticketsindate_activepid(class character varying, processid bigint) RETURNS bigint LANGUAGE plpgsql AS $$ DECLARE query varchar; pid integer; BEGIN query = 'SELECT * FROM coalesce((SELECT c."Id" FROM ' || "class" || ' c WHERE c."Id" = ' || processid || ' AND c."Status" = ''A''), (SELECT h."CurrentId" AS "Id" FROM "' || substr("class", 2, (length("class")-2)) || '_history" h WHERE h."Id" = ' || processid || '));'; --raise notice '%', query; EXECUTE query INTO pid; RETURN pid; END; $$; fDROP FUNCTION public.report_activeticketsindate_activepid(class character varying, processid bigint); publicpostgresfalse1255233270oreport_activeticketsindate_code(character varying, bigint, bigint, timestamp with time zone, character varying)FUNCTION*CREATE FUNCTION public.report_activeticketsindate_code(class character varying, processid bigint, "group" bigint, querydate timestamp with time zone, code character varying) RETURNS double precision LANGUAGE plpgsql AS $$ DECLARE query varchar; sum double precision; BEGIN query = 'SELECT coalesce(sum(report_activeticketsindate_getactivitytime(h."BeginDate", LEAST(h."EndDate", ''' || querydate || '''))), 0) FROM "' || substr("class", 2, (length("class")-2)) || '_history" h JOIN "LookUp" l0 ON l0."Id" = h."ProcessStatus" AND l0."Status" = ''A'' WHERE h."CurrentId" = ' || processid || ' AND h."CurrentRole" = ' || "group" ||' AND h."BeginDate" <= ''' || querydate || ''' AND l0."Code" = ''' || code || ''';'; --raise notice 'xx %', query; EXECUTE query INTO sum; RETURN sum; END; $$; DROP FUNCTION public.report_activeticketsindate_code(class character varying, processid bigint, "group" bigint, querydate timestamp with time zone, code character varying); publicpostgresfalse1255233271^report_activeticketsindate_getactivitytime(timestamp with time zone, timestamp with time zone)FUNCTION CREATE FUNCTION public.report_activeticketsindate_getactivitytime(date1 timestamp with time zone, date2 timestamp with time zone, OUT activitytime double precision) RETURNS double precision LANGUAGE plpgsql AS $_$ DECLARE i integer; j integer; qt1 decimal; qt2 decimal; qt3 decimal; daytimetable text[]; dayworktime decimal[]; holidays character varying[]; timetable character varying[]; BEGIN holidays = array (select split_part("LookUp"."Code" || '|', '|', 1) from "LookUp" where "LookUp"."Type" = 'Holidays' and "LookUp"."Status" = 'A' group by "LookUp"."Code" order by "LookUp"."Code"); timetable = array (select split_part("LookUp"."Notes" || '|', '|', 1) from "LookUp" where "LookUp"."Type" = 'Working hours' and "LookUp"."Status" = 'A' group by "LookUp"."Notes", "LookUp"."Code" order by "LookUp"."Code"); if $1 is null or $2 is null then activitytime = 0; else for i in 1 .. 7 loop -- initialize array with working hours dayworktime[i] = 0; daytimetable = string_to_array(timetable[i], ','); if daytimetable is null then continue; end if; for j in 1 .. array_upper(daytimetable, 1) loop dayworktime[i] = dayworktime[i] + extract(epoch from ((split_part(daytimetable[j], '-', 2) || ':00')::time - (split_part(daytimetable[j], '-', 1) || ':00')::time)) /*/ 3600*/; end loop; end loop; -- raise notice '%', dayworktime; qt1 = 0.0; -- calculate working time for the first day if timetable[date_part('dow', $1) + 1] is not null and not substr(replace($2::date::varchar, '-', ''), 5, 4) = any (holidays) then daytimetable = string_to_array(timetable[date_part('dow', $1) + 1], ','); for i in 1 .. array_upper(daytimetable, 1) loop if split_part(daytimetable[i], '-', 1)::time > $1::time then qt1 = qt1 + extract(epoch from split_part(daytimetable[i], '-', 2)::time - split_part(daytimetable[i], '-', 1)::time) /*/ 3600*/; elsif split_part(daytimetable[i], '-', 2)::time > $1::time then qt1 = qt1 + extract(epoch from split_part(daytimetable[i], '-', 2)::time - $1::time) /*/ 3600*/; end if; end loop; end if; -- calculate working time for the other days --select now()+ s.a * interval '1 day' from generate_series(1, 5, 1) as s(a) select into qt2 sum(dayworktime[date_part('dow', $1::date + s.a * interval '1 day') + 1]) from generate_series(1, ($2::date - $1::date)-1,1) as s(a) where not substr(replace(($1::date + s.a * interval '1 day')::varchar, '-', ''), 5, 4) = any (holidays); -- raise notice 'qt2 = %', qt2; qt3 = 0.0; -- calculate working time for the last day if timetable[date_part('dow', $2) + 1] is not null and not substr(replace($2::date::varchar, '-', ''), 5, 4) = any (holidays) then daytimetable = string_to_array(timetable[date_part('dow', $2) + 1], ','); for i in 1 .. array_upper(daytimetable, 1) loop if $2::time > split_part(daytimetable[i], '-', 2)::time then qt3 = qt3 + extract(epoch from split_part(daytimetable[i], '-', 2)::time - split_part(daytimetable[i], '-', 1)::time) /*/ 3600*/; elsif $2::time > split_part(daytimetable[i], '-', 1)::time then qt3 = qt3 + extract(epoch from $2::time - split_part(daytimetable[i], '-', 1)::time) /*/ 3600*/; end if; end loop; end if; -- raise notice 'qt3 = %', qt3; -- raise notice 'date1=% date2=% qt1=% qt2=% qt3=% totale=%', $1, $2, qt1, qt2, qt3, case when $1::date = $2::date then qt1 + qt3 - dayworktime[date_part('dow', $1)] else qt1 + coalesce(qt2, 0) + qt3 end; if $1::date = $2::date then activitytime = case when qt1 + qt3 - dayworktime[date_part('dow', $1) + 1] < 0.0 then 0.0 else qt1 + qt3 - dayworktime[date_part('dow', $1) + 1] end; else activitytime = qt1 + coalesce(qt2, 0.0) + qt3; end if; end if; END; $_$; DROP FUNCTION public.report_activeticketsindate_getactivitytime(date1 timestamp with time zone, date2 timestamp with time zone, OUT activitytime double precision); publicpostgresfalse00FUNCTION report_activeticketsindate_getactivitytime(date1 timestamp with time zone, date2 timestamp with time zone, OUT activitytime double precision)COMMENTCOMMENT ON FUNCTION public.report_activeticketsindate_getactivitytime(date1 timestamp with time zone, date2 timestamp with time zone, OUT activitytime double precision) IS 'TYPE: function'; publicpostgresfalse19441255233272Hreport_activeticketsindate_lastsolved(character varying, bigint, bigint)FUNCTIONCREATE FUNCTION public.report_activeticketsindate_lastsolved(class character varying, processid bigint, "group" bigint) RETURNS timestamp with time zone LANGUAGE plpgsql AS $$ DECLARE query varchar; lastsolved timestamp with time zone; BEGIN query = 'SELECT subquery."BeginDate" FROM (SELECT p."BeginDate" FROM ' || "class" || ' p JOIN "LookUp" l0 ON l0."Id" = p."ProcessStatus" AND l0."Status" = ''A'' WHERE p."Id" = ' || processid || ' AND p."CurrentRole" = ' || "group" ||' AND l0."Code" = ''Closed'' AND p."Status" = ''A'' UNION SELECT h."BeginDate" FROM "' || substr("class", 2, (length("class")-2)) || '_history" h JOIN "LookUp" l0 ON l0."Id" = h."ProcessStatus" AND l0."Status" = ''A'' WHERE h."CurrentId" = ' || processid || ' AND h."CurrentRole" = ' || "group" ||' AND l0."Code" = ''Closed'') AS subquery ORDER BY subquery."BeginDate" DESC LIMIT 1;'; --raise notice '%', query; EXECUTE query INTO lastsolved; RETURN lastsolved; END; $$; wDROP FUNCTION public.report_activeticketsindate_lastsolved(class character varying, processid bigint, "group" bigint); publicpostgresfalse1255233273=report_activeticketsindate_opening(character varying, bigint)FUNCTIONCREATE FUNCTION public.report_activeticketsindate_opening(class character varying, processid bigint) RETURNS timestamp with time zone LANGUAGE plpgsql AS $$ DECLARE query varchar; openingdate timestamp with time zone; BEGIN query = 'SELECT subquery."BeginDate" FROM (SELECT p."BeginDate" FROM ' || "class" || ' p WHERE p."Id" = ' || processid || ' AND p."Status" = ''A'' UNION SELECT h."BeginDate" FROM "' || substr("class", 2, (length("class")-2)) || '_history" h WHERE h."CurrentId" = ' || processid || ') AS subquery ORDER BY subquery."BeginDate" ASC LIMIT 1;'; --raise notice '%', query; EXECUTE query INTO openingdate; RETURN openingdate; END; $$; dDROP FUNCTION public.report_activeticketsindate_opening(class character varying, processid bigint); publicpostgresfalse1255233274\report_activeticketsindate_perm(character varying, bigint, bigint, timestamp with time zone)FUNCTIONCREATE FUNCTION public.report_activeticketsindate_perm(class character varying, processid bigint, "group" bigint, querydate timestamp with time zone) RETURNS double precision LANGUAGE plpgsql AS $$ DECLARE query varchar; sum double precision; BEGIN query = 'SELECT coalesce(sum(report_activeticketsindate_getactivitytime(h."BeginDate", LEAST(h."EndDate", ''' || querydate || '''))), 0) FROM "' || substr("class", 2, (length("class")-2)) || '_history" h WHERE h."CurrentId" = ' || processid || ' AND h."CurrentRole" = ' || "group" ||' AND h."BeginDate" <= ''' || querydate || ''';'; --raise notice '%', query; EXECUTE query INTO sum; RETURN sum; END; $$; DROP FUNCTION public.report_activeticketsindate_perm(class character varying, processid bigint, "group" bigint, querydate timestamp with time zone); publicpostgresfalse1255233275rreport_activeticketsininterval(bigint, bigint, bigint, bigint, timestamp with time zone, timestamp with time zone)FUNCTION CREATE FUNCTION public.report_activeticketsininterval("group" bigint, process bigint, category bigint, subcategory bigint, date1 timestamp with time zone, date2 timestamp with time zone, OUT "Code" text, OUT "Group" character varying, OUT "ProcessClass" text, OUT "ProcessCategory" character varying, OUT "ProcessSubcategory" character varying, OUT "StatusCode" character varying, OUT "TotalAssigned" double precision, OUT "TotalWorking" double precision, OUT "TotalSuspended" double precision, OUT "TotalToAnswer" double precision, OUT "TotalPermanence" double precision, OUT "TotalElaboration" double precision) RETURNS SETOF record LANGUAGE plpgsql AS $$ BEGIN date1 = (date1::date + interval '23 hours 59 minutes 59 seconds'); date2 = (date2::date + interval '23 hours 59 minutes 59 seconds'); RETURN QUERY SELECT p."ProcessCode" AS "Code", r."Description" AS "Group", p."IdClass"::text AS "ProcessClass", coalesce (pc."Code") AS "ProcessCategory", coalesce (sc."Code") AS "ProcessSubcategory", l0."Code" AS "StatusCode", (nullif( (report_activeticketsininterval_code(p."IdClass"::varchar, report_activeticketsindate_activepid(p."IdClass"::varchar, p."Id"), "group", date1, date2, 'Opening', (CASE WHEN (l0."Code" IN ('Closed')) THEN report_activeticketsindate_lastsolved(p."IdClass"::varchar, p."Id", "group") ELSE date2 END))) + (report_activeticketsininterval_code(p."IdClass"::varchar, report_activeticketsindate_activepid(p."IdClass"::varchar, p."Id"), "group", date1, date2, 'Classification', (CASE WHEN (l0."Code" IN ('Closed')) THEN report_activeticketsindate_lastsolved(p."IdClass"::varchar, p."Id", "group") ELSE date2 END))) + (report_activeticketsininterval_code(p."IdClass"::varchar, report_activeticketsindate_activepid(p."IdClass"::varchar, p."Id"), "group", date1, date2, 'Analysis', (CASE WHEN (l0."Code" IN ('Closed')) THEN report_activeticketsindate_lastsolved(p."IdClass"::varchar, p."Id", "group") ELSE date2 END))) + (report_activeticketsininterval_code(p."IdClass"::varchar, report_activeticketsindate_activepid(p."IdClass"::varchar, p."Id"), "group", date1, date2, 'Opening')) + (report_activeticketsininterval_code(p."IdClass"::varchar, report_activeticketsindate_activepid(p."IdClass"::varchar, p."Id"), "group", date1, date2, 'Classification')) + (report_activeticketsininterval_code(p."IdClass"::varchar, report_activeticketsindate_activepid(p."IdClass"::varchar, p."Id"), "group", date1, date2, 'Analysis')) + (CASE WHEN p."Status" = 'A' AND (l0."Code" = 'Opening' OR l0."Code" = 'Classification' OR l0."Code" = 'Analysis') THEN report_activeticketsindate_getactivitytime(GREATEST(p."BeginDate", date1), date2) ELSE 0 END) , 0)) AS "TotalAssigned", (nullif( (report_activeticketsininterval_code(p."IdClass"::varchar, report_activeticketsindate_activepid(p."IdClass"::varchar, p."Id"), "group", date1, date2, 'Execution', (CASE WHEN (l0."Code" IN ('Closed')) THEN report_activeticketsindate_lastsolved(p."IdClass"::varchar, p."Id", "group") ELSE date2 END))) + (CASE WHEN p."Status" = 'A' AND l0."Code" = 'Execution' THEN report_activeticketsindate_getactivitytime(GREATEST(p."BeginDate", date1), date2) ELSE 0 END) , 0)) AS "TotalWorking", (nullif( (report_activeticketsininterval_code(p."IdClass"::varchar, report_activeticketsindate_activepid(p."IdClass"::varchar, p."Id"), "group", date1, date2, 'WaitForRelatedProcess', (CASE WHEN (l0."Code" IN ('Closed')) THEN report_activeticketsindate_lastsolved(p."IdClass"::varchar, p."Id", "group") ELSE date2 END))) + (report_activeticketsininterval_code(p."IdClass"::varchar, report_activeticketsindate_activepid(p."IdClass"::varchar, p."Id"), "group", date1, date2, 'StartCM', (CASE WHEN (l0."Code" IN ('Closed')) THEN report_activeticketsindate_lastsolved(p."IdClass"::varchar, p."Id", "group") ELSE date2 END))) + (report_activeticketsininterval_code(p."IdClass"::varchar, report_activeticketsindate_activepid(p."IdClass"::varchar, p."Id"), "group", date1, date2, 'Suspended', (CASE WHEN (l0."Code" IN ('Closed')) THEN report_activeticketsindate_lastsolved(p."IdClass"::varchar, p."Id", "group") ELSE date2 END))) + (CASE WHEN p."Status" = 'A' AND l0."Code" = 'WaitForRelatedProcess' THEN report_activeticketsindate_getactivitytime(GREATEST(p."BeginDate", date1), date2) ELSE 0 END) + (CASE WHEN p."Status" = 'A' AND l0."Code" = 'StartCM' THEN report_activeticketsindate_getactivitytime(GREATEST(p."BeginDate", date1), date2) ELSE 0 END) + (CASE WHEN p."Status" = 'A' AND l0."Code" = 'Suspended' THEN report_activeticketsindate_getactivitytime(GREATEST(p."BeginDate", date1), date2) ELSE 0 END) , 0)) AS "TotalSuspended", (nullif( (report_activeticketsininterval_code(p."IdClass"::varchar, report_activeticketsindate_activepid(p."IdClass"::varchar, p."Id"), "group", date1, date2, 'Closure', (CASE WHEN (l0."Code" IN ('Closed')) THEN report_activeticketsindate_lastsolved(p."IdClass"::varchar, p."Id", "group") ELSE date2 END))) + (CASE WHEN p."Status" = 'A' AND l0."Code" = 'Closure' THEN report_activeticketsindate_getactivitytime(GREATEST(p."BeginDate", date1), date2) ELSE 0 END) , 0)) AS "TotalToAnswer", (nullif( (report_activeticketsininterval_perm(p."IdClass"::varchar, report_activeticketsindate_activepid(p."IdClass"::varchar, p."Id"), "group", date1, date2, report_activeticketsindate_lastsolved(p."IdClass"::varchar, p."Id", "group"))) + (CASE WHEN ( p."Status" = 'A' AND l0."Code" NOT IN ('Closed')) THEN report_activeticketsindate_getactivitytime(GREATEST(p."BeginDate", date1), date2) ELSE 0 END) , 0)) AS "TotalPermanence", (null::double precision) AS "TotalElaboration" FROM (select distinct on ("Id") * from cm_class(null::"ITProc", date1, date2) order by "Id", "BeginDate" desc) AS p LEFT OUTER JOIN "Employee" e ON e."Id" = p."Requester" AND e."Status" = 'A' -- requester LEFT OUTER JOIN "LookUp" l0 ON l0."Id" = p."ProcessStatus" AND l0."Status" = 'A' -- LookUp Type = ITProc - ProcessStatus LEFT OUTER JOIN "LookUp" l1 ON l1."Id" = p."FlowStatus" AND l1."Status" = 'A' -- LookUp Type = FlowStatus LEFT OUTER JOIN "Role" r on r."Id" = p."CurrentRole" AND r."Status" = 'A' LEFT OUTER JOIN "ITProcCategory" pc on pc."Id" = p."Category" AND pc."Status" = 'A' LEFT OUTER JOIN "ITProcSubcategory" sc on sc."Id" = p."Subcategory" AND sc."Status" = 'A' WHERE p."CurrentRole" = "group" AND (p."IdClass"::text = report_activetickets_process(process) OR process IS NULL) AND (l1."Code" NOT IN ('closed.completed', 'closed.terminated', 'closed.aborted') OR (l1."Code" IN ('closed.completed', 'closed.terminated', 'closed.aborted') AND (p."Category" = category OR category IS NULL) AND (p."Subcategory" = subcategory OR subcategory IS NULL) AND p."BeginDate" >= date1)) ORDER BY p."IdClass", pc."Code", sc."Code", substr(p."Number", 3, length(p."Number")-2)::integer, p."ProcessCode", p."BeginDate" desc; END; $$; eDROP FUNCTION public.report_activeticketsininterval("group" bigint, process bigint, category bigint, subcategory bigint, date1 timestamp with time zone, date2 timestamp with time zone, OUT "Code" text, OUT "Group" character varying, OUT "ProcessClass" text, OUT "ProcessCategory" character varying, OUT "ProcessSubcategory" character varying, OUT "StatusCode" character varying, OUT "TotalAssigned" double precision, OUT "TotalWorking" double precision, OUT "TotalSuspended" double precision, OUT "TotalToAnswer" double precision, OUT "TotalPermanence" double precision, OUT "TotalElaboration" double precision); publicpostgresfalse1255233276report_activeticketsininterval_code(character varying, bigint, bigint, timestamp with time zone, timestamp with time zone, character varying)FUNCTIONCREATE FUNCTION public.report_activeticketsininterval_code(class character varying, processid bigint, "group" bigint, querydate1 timestamp with time zone, querydate2 timestamp with time zone, code character varying) RETURNS double precision LANGUAGE plpgsql AS $$ DECLARE query varchar; sum double precision; BEGIN query = 'SELECT coalesce(sum(report_activeticketsindate_getactivitytime(GREATEST(h."BeginDate", ''' || querydate1 || '''), LEAST(h."EndDate", ''' || querydate2 || '''))), 0) FROM "' || substr("class", 2, (length("class")-2)) || '_history" h JOIN "LookUp" l0 ON l0."Id" = h."ProcessStatus" AND l0."Status" = ''A'' WHERE h."CurrentId" = ' || processid || ' AND h."CurrentRole" = ' || "group" ||' AND h."BeginDate" <= ''' || querydate2 || ''' AND h."EndDate" >= ''' || querydate1 || ''' AND l0."Code" = ''' || code || ''';'; --raise notice '%', query; EXECUTE query INTO sum; RETURN sum; END; $$; DROP FUNCTION public.report_activeticketsininterval_code(class character varying, processid bigint, "group" bigint, querydate1 timestamp with time zone, querydate2 timestamp with time zone, code character varying); publicpostgresfalse1255233277report_activeticketsininterval_code(character varying, bigint, bigint, timestamp with time zone, timestamp with time zone, character varying, timestamp with time zone)FUNCTIONoCREATE FUNCTION public.report_activeticketsininterval_code(class character varying, processid bigint, "group" bigint, querydate1 timestamp with time zone, querydate2 timestamp with time zone, code character varying, lastsolved timestamp with time zone) RETURNS double precision LANGUAGE plpgsql AS $$ DECLARE query varchar; sum double precision; BEGIN if (lastsolved >= querydate1 and lastsolved <= querydate2) then querydate2 = lastsolved; end if; if (lastsolved < querydate1) then querydate1 = querydate2; end if; query = 'SELECT coalesce(sum(report_activeticketsindate_getactivitytime(GREATEST(h."BeginDate", ''' || querydate1 || '''), LEAST(h."EndDate", ''' || querydate2 || '''))), 0) FROM "' || substr("class", 2, (length("class")-2)) || '_history" h JOIN "LookUp" l0 ON l0."Id" = h."ProcessStatus" AND l0."Status" = ''A'' WHERE h."CurrentId" = ' || processid || ' AND h."CurrentRole" = ' || "group" ||' AND h."BeginDate" <= ''' || querydate2 || ''' AND h."EndDate" >= ''' || querydate1 || ''' AND l0."Code" = ''' || code || ''';'; --raise notice '%', query; EXECUTE query INTO sum; RETURN sum; END; $$; DROP FUNCTION public.report_activeticketsininterval_code(class character varying, processid bigint, "group" bigint, querydate1 timestamp with time zone, querydate2 timestamp with time zone, code character varying, lastsolved timestamp with time zone); publicpostgresfalse1255233278report_activeticketsininterval_perm(character varying, bigint, bigint, timestamp with time zone, timestamp with time zone, timestamp with time zone)FUNCTIONCREATE FUNCTION public.report_activeticketsininterval_perm(class character varying, processid bigint, "group" bigint, querydate1 timestamp with time zone, querydate2 timestamp with time zone, lastsolved timestamp with time zone) RETURNS double precision LANGUAGE plpgsql AS $$ DECLARE query varchar; sum double precision; BEGIN if (lastsolved >= querydate1 and lastsolved <= querydate2) then querydate2 = lastsolved; end if; if (lastsolved < querydate1) then querydate1 = querydate1; end if; query = 'SELECT coalesce(sum(report_activeticketsindate_getactivitytime(GREATEST(h."BeginDate", ''' || querydate1 || '''), LEAST(h."EndDate", ''' || querydate2 || '''))), 0) FROM "' || substr("class", 2, (length("class")-2)) || '_history" h WHERE h."CurrentId" = ' || processid || ' AND h."CurrentRole" = ' || "group" ||' AND h."BeginDate" <= ''' || querydate2 || ''' AND h."EndDate" >= ''' || querydate1 || ''';'; --raise notice '%', query; EXECUTE query INTO sum; RETURN sum; END; $$; DROP FUNCTION public.report_activeticketsininterval_perm(class character varying, processid bigint, "group" bigint, querydate1 timestamp with time zone, querydate2 timestamp with time zone, lastsolved timestamp with time zone); publicpostgresfalse1255233279*report_getRolesFromUser(character varying)FUNCTIONnCREATE FUNCTION public."report_getRolesFromUser"(userid character varying, OUT _group bigint) RETURNS SETOF bigint LANGUAGE plpgsql AS $$ BEGIN return query select r."Id" from "Role" r join "Map_UserRole" ur on ur."IdObj2"=r."Id" and ur."IdObj1"::varchar=userid and ur."Status"='A' where r."Code" not in ('Guest','SuperUser') and r."Status"='A' union select r."Id" from "Role" r join "User" on "User"."Id"::varchar=userid where r."Code" not in ('Guest','SuperUser') and r."Status"='A' and ("User"."Description" = 'admin' OR "User"."Description" = 'Administrator') union select 0::bigint; END; $$; ]DROP FUNCTION public."report_getRolesFromUser"(userid character varying, OUT _group bigint); publicpostgresfalse00OFUNCTION "report_getRolesFromUser"(userid character varying, OUT _group bigint)COMMENTwCOMMENT ON FUNCTION public."report_getRolesFromUser"(userid character varying, OUT _group bigint) IS 'TYPE: function'; publicpostgresfalse19311255233280Creport_tickets_in_classification(character varying, bigint, bigint)FUNCTIONICREATE FUNCTION public.report_tickets_in_classification(class character varying, groupp bigint, subcategory bigint, OUT outputservice character varying, OUT counter integer) RETURNS SETOF record LANGUAGE plpgsql AS $$ DECLARE query varchar; BEGIN groupp = case when ( groupp = (select "Id" from "Role" where "Code" like 'SuperUser' and "Status" = 'A') ) then null else groupp end; query= 'SELECT coalesce(c."Description"::varchar,''No category'') as outputservice, count(*)::integer as counter FROM ' || class || ' sd LEFT JOIN "Role" r on r."Id" = sd."CurrentRole" and r."Status" = ''A'' LEFT JOIN "LookUp" l1 on l1."Id" = sd."FlowStatus" and l1."Status" = ''A'' LEFT JOIN "LookUp" l2 on l2."Id" = sd."ProcessStatus" and l2."Status" = ''A'' LEFT JOIN "ITProcSubcategory" c on c."Id" = sd."Subcategory" and c."Status" = ''A'' WHERE sd."Status" = ''A'' AND l1."Code" = ''open.running'' AND ( l2."Code" <> ''Closed'' OR l2."Code" IS NULL ) AND ' || CASE WHEN groupp is not null THEN 'sd."CurrentRole" = ' || groupp ELSE 'true' END || ' AND ' || CASE WHEN subcategory is not null THEN 'sd."Subcategory" = ' || subcategory ELSE 'true' END ||' GROUP BY c."Description" ORDER BY count(*) desc LIMIT 10 ;'; -- raise notice '%', query; RETURN QUERY EXECUTE query; END; $$; DROP FUNCTION public.report_tickets_in_classification(class character varying, groupp bigint, subcategory bigint, OUT outputservice character varying, OUT counter integer); publicpostgresfalse00FUNCTION report_tickets_in_classification(class character varying, groupp bigint, subcategory bigint, OUT outputservice character varying, OUT counter integer)COMMENTCOMMENT ON FUNCTION public.report_tickets_in_classification(class character varying, groupp bigint, subcategory bigint, OUT outputservice character varying, OUT counter integer) IS 'TYPE: function'; publicpostgresfalse19511255233281:report_tickets_in_group(character varying, bigint, bigint)FUNCTIONCREATE FUNCTION public.report_tickets_in_group(class character varying, status bigint, groupp bigint, OUT outputgroup character varying, OUT counter integer) RETURNS SETOF record LANGUAGE plpgsql AS $$ DECLARE selection varchar; stato_code varchar; stato_id INTEGER; BEGIN groupp = case when ( groupp = (select "Id" from "Role" where "Code" like 'SuperUser' and "Status" = 'A') ) then null else groupp end; select into stato_code "Code" from "LookUp" where "Id" = status; -- raise notice 'codice dello stato %', stato_code; select into stato_id "Id" from "LookUp" where "Type" = 'ITProc - ProcessStatus' and "Code" = stato_code and "Status" = 'A'; -- raise notice 'id dello stato %', stato_id; selection = 'SELECT coalesce(r."Description"::varchar,''No Group'') as outputgroup, count(*)::integer as counter FROM ' || class || ' sd LEFT JOIN "Role" r on r."Id" = sd."CurrentRole" and r."Status" = ''A'' LEFT JOIN "LookUp" l1 on l1."Id" = sd."FlowStatus" and l1."Status" = ''A'' LEFT JOIN "LookUp" l2 on l2."Id" = sd."ProcessStatus" and l2."Status" = ''A'' WHERE sd."Status" = ''A'' AND l1."Code" = ''open.running'' AND ( l2."Code" <> ''Closed'' OR l2."Code" IS NULL ) AND ' || CASE WHEN groupp is not null THEN 'sd."CurrentRole" = ' || groupp ELSE 'true' END || ' AND ' || CASE WHEN stato_code = 'A' THEN 'sd."ProcessStatus" IN ( select "Id" from "LookUp" where "Type" = ''ITProc - ProcessStatus'' and "Code" in (''Assignment'') and "Status" = ''A'' )' else case when stato_code is not null then 'sd."ProcessStatus" = ' || stato_id ELSE 'true' END END ||' GROUP BY r."Description" ORDER BY count(*) desc LIMIT 10 ;'; -- raise notice '%', selection; RETURN QUERY EXECUTE selection; END; $$; DROP FUNCTION public.report_tickets_in_group(class character varying, status bigint, groupp bigint, OUT outputgroup character varying, OUT counter integer); publicpostgresfalse00FUNCTION report_tickets_in_group(class character varying, status bigint, groupp bigint, OUT outputgroup character varying, OUT counter integer)COMMENTCOMMENT ON FUNCTION public.report_tickets_in_group(class character varying, status bigint, groupp bigint, OUT outputgroup character varying, OUT counter integer) IS 'TYPE: function'; publicpostgresfalse195212552332823report_tickets_in_status(character varying, bigint)FUNCTIONCREATE FUNCTION public.report_tickets_in_status(class character varying, groupp bigint, OUT status character varying, OUT flownumber integer) RETURNS SETOF record LANGUAGE plpgsql AS $$ DECLARE selection varchar; BEGIN groupp = case when ( groupp = (select "Id" from "Role" where "Code" like 'SuperUser' and "Status" = 'A') ) then null else groupp end; selection = 'SELECT coalesce(l2."Description"::varchar,''No status'') as status, count(*)::integer as flownumber FROM ' || class || ' sd LEFT JOIN "Role" r on r."Id" = sd."CurrentRole" and r."Status" = ''A'' LEFT JOIN "LookUp" l1 on l1."Id" = sd."FlowStatus" and l1."Status" = ''A'' LEFT JOIN "LookUp" l2 on l2."Id" = sd."ProcessStatus" and l2."Status" = ''A'' WHERE sd."Status" = ''A'' and l1."Code" = ''open.running'' AND (l2."Code" <> ''Closed'' OR l2."Code" IS NULL) AND ' || CASE WHEN (groupp is not null) THEN 'sd."CurrentRole" = ' || groupp ELSE 'true' END || ' GROUP BY coalesce(l2."Description"::varchar,''No status'') ORDER BY count(*), coalesce(l2."Description"::varchar,''No status'');'; -- raise notice '%', selection; RETURN QUERY EXECUTE selection; END; $$; DROP FUNCTION public.report_tickets_in_status(class character varying, groupp bigint, OUT status character varying, OUT flownumber integer); publicpostgresfalse00FUNCTION report_tickets_in_status(class character varying, groupp bigint, OUT status character varying, OUT flownumber integer)COMMENTCOMMENT ON FUNCTION public.report_tickets_in_status(class character varying, groupp bigint, OUT status character varying, OUT flownumber integer) IS 'TYPE: function'; publicpostgresfalse19531255233283system_attribute_create(character varying, character varying, character varying, character varying, boolean, boolean, character varying, character varying, character varying, character varying, boolean)FUNCTIONCREATE FUNCTION public.system_attribute_create(cmclass character varying, attributename character varying, denormalizedsqltype character varying, attributedefault character varying, attributenotnull boolean, attributeunique boolean, attributecomment character varying, attributereference character varying, attributereferencedomain character varying, attributereferencetype character varying, attributereferenceisdirect boolean) RETURNS integer LANGUAGE plpgsql AS $$ DECLARE AttributeIndex integer; SQLType varchar; BEGIN -- redundant parameters sanity check IF COALESCE(AttributeReferenceDomain,'') <> COALESCE(_cm_read_reference_domain_comment(AttributeComment),'') OR (COALESCE(_cm_read_reference_domain_comment(AttributeComment),'') <> '' AND ( COALESCE(AttributeReferenceIsDirect,FALSE) <> COALESCE(_cm_read_comment(AttributeComment, 'REFERENCEDIRECT')::boolean,FALSE) OR COALESCE(AttributeReference,'') <> COALESCE(_cm_read_reference_target_comment(AttributeComment),'') OR COALESCE(AttributeReferenceType,'') <> COALESCE(_cm_read_comment(AttributeComment, 'REFERENCETYPE'),'') ) ) THEN RAISE EXCEPTION 'CM_FORBIDDEN_OPERATION'; END IF; IF DenormalizedSQLType ILIKE 'bpchar%' THEN SQLType := 'bpchar(1)'; ELSE SQLType := DenormalizedSQLType; END IF; PERFORM cm_create_class_attribute(CMClass, AttributeName, SQLType, AttributeDefault, AttributeNotNull, AttributeUnique, AttributeComment); SELECT CASE WHEN _cm_check_comment(AttributeComment,'MODE','reserved') THEN -1 ELSE COALESCE(_cm_read_comment(AttributeComment, 'INDEX'),'0')::integer END INTO AttributeIndex; RETURN AttributeIndex; END; $$; DROP FUNCTION public.system_attribute_create(cmclass character varying, attributename character varying, denormalizedsqltype character varying, attributedefault character varying, attributenotnull boolean, attributeunique boolean, attributecomment character varying, attributereference character varying, attributereferencedomain character varying, attributereferencetype character varying, attributereferenceisdirect boolean); publicpostgresfalse1255233284=system_attribute_delete(character varying, character varying)FUNCTIONCREATE FUNCTION public.system_attribute_delete(cmclass character varying, attributename character varying) RETURNS boolean LANGUAGE plpgsql AS $$ BEGIN PERFORM cm_delete_class_attribute(CMClass, AttributeName); RETURN TRUE; END; $$; jDROP FUNCTION public.system_attribute_delete(cmclass character varying, attributename character varying); publicpostgresfalse1255233285Msystem_attribute_modify(text, text, text, text, text, boolean, boolean, text)FUNCTIONCREATE FUNCTION public.system_attribute_modify(cmclass text, attributename text, attributenewname text, denormalizedsqltype text, attributedefault text, attributenotnull boolean, attributeunique boolean, attributecomment text) RETURNS boolean LANGUAGE plpgsql AS $$ DECLARE SQLType varchar; BEGIN IF (AttributeName <> AttributeNewName) THEN RAISE EXCEPTION 'CM_FORBIDDEN_OPERATION'; END IF; IF DenormalizedSQLType ILIKE 'bpchar%' THEN SQLType := 'bpchar(1)'; ELSE SQLType := DenormalizedSQLType; END IF; PERFORM cm_modify_class_attribute(CMClass, AttributeName, SQLType, AttributeDefault, AttributeNotNull, AttributeUnique, AttributeComment); RETURN TRUE; END; $$; DROP FUNCTION public.system_attribute_modify(cmclass text, attributename text, attributenewname text, denormalizedsqltype text, attributedefault text, attributenotnull boolean, attributeunique boolean, attributecomment text); publicpostgresfalse1255233286Usystem_class_create(character varying, character varying, boolean, character varying)FUNCTIONCREATE FUNCTION public.system_class_create(classname character varying, parentclass character varying, issuperclass boolean, classcomment character varying) RETURNS integer LANGUAGE plpgsql AS $$ BEGIN -- consistency checks for wrong signatures IF IsSuperClass <> _cm_is_superclass_comment(ClassComment) THEN RAISE EXCEPTION 'CM_FORBIDDEN_OPERATION'; END IF; RETURN cm_create_class(ClassName, ParentClass, ClassComment); END; $$; DROP FUNCTION public.system_class_create(classname character varying, parentclass character varying, issuperclass boolean, classcomment character varying); publicpostgresfalse1255233287&system_class_delete(character varying)FUNCTIONCREATE FUNCTION public.system_class_delete(cmclass character varying) RETURNS void LANGUAGE sql AS $_$ SELECT cm_delete_class($1); $_$; EDROP FUNCTION public.system_class_delete(cmclass character varying); publicpostgresfalse1255233288Ksystem_class_modify(integer, character varying, boolean, character varying)FUNCTIONCREATE FUNCTION public.system_class_modify(classid integer, newclassname character varying, newissuperclass boolean, newclasscomment character varying) RETURNS boolean LANGUAGE plpgsql AS $$ BEGIN IF _cm_cmtable(ClassId) <> NewClassName OR _cm_is_superclass_comment(NewClassComment) <> NewIsSuperClass THEN RAISE EXCEPTION 'CM_FORBIDDEN_OPERATION'; END IF; PERFORM cm_modify_class(ClassId::oid, NewClassComment); RETURN TRUE; END; $$; DROP FUNCTION public.system_class_modify(classid integer, newclassname character varying, newissuperclass boolean, newclasscomment character varying); publicpostgresfalse1255233289,system_domain_create(text, text, text, text)FUNCTIONCREATE FUNCTION public.system_domain_create(cmdomain text, domainclass1 text, domainclass2 text, domaincomment text) RETURNS integer LANGUAGE plpgsql AS $$ DECLARE TableName text := _cm_domain_cmname(CMDomain); HistoryTableName text := _cm_history_cmname(TableName); DomainId oid; BEGIN -- TODO: Check DomainClass1 and DomainClass2 RETURN cm_create_domain(CMDomain, DomainComment); END $$; tDROP FUNCTION public.system_domain_create(cmdomain text, domainclass1 text, domainclass2 text, domaincomment text); publicpostgresfalse1255233290system_domain_delete(text)FUNCTIONCREATE FUNCTION public.system_domain_delete(cmdomain text) RETURNS void LANGUAGE sql AS $_$ SELECT cm_delete_domain($1); $_$; :DROP FUNCTION public.system_domain_delete(cmdomain text); publicpostgresfalse12552332911system_domain_modify(oid, text, text, text, text)FUNCTIONXCREATE FUNCTION public.system_domain_modify(domainid oid, domainname text, domainclass1 text, domainclass2 text, newcomment text) RETURNS boolean LANGUAGE plpgsql AS $$ DECLARE OldComment text := _cm_comment_for_table_id(DomainId); BEGIN -- TODO: Check DomainName, DomainClass1 and DomainClass2 IF _cm_domain_id(DomainName) <> DomainId OR _cm_read_comment(NewComment, 'CLASS1') <> DomainClass1 OR _cm_read_comment(NewComment, 'CLASS2') <> DomainClass2 THEN RAISE EXCEPTION 'CM_FORBIDDEN_OPERATION'; END IF; PERFORM cm_modify_domain(DomainId, NewComment); RETURN TRUE; END; $$; DROP FUNCTION public.system_domain_modify(domainid oid, domainname text, domainclass1 text, domainclass2 text, newcomment text); publicpostgresfalse1255233292tt_brand_to_swcatalogue_descr()FUNCTIONCREATE FUNCTION public.tt_brand_to_swcatalogue_descr() RETURNS trigger LANGUAGE plpgsql AS $$ DECLARE softwares CURSOR FOR SELECT "Id" FROM "SWCatalogue" WHERE "Brand" = NEW."Id" AND "Status" = 'A'; BEGIN --RAISE NOTICE 'Trigger % on %', TG_NAME, TG_TABLE_NAME; FOR sw IN softwares LOOP UPDATE "SWCatalogue" SET "Description" = null WHERE "Id" = sw."Id"; END LOOP; RETURN null; END; $$; 6DROP FUNCTION public.tt_brand_to_swcatalogue_descr(); publicpostgresfalse1255233293tt_calendardef_data()FUNCTIONHCREATE FUNCTION public.tt_calendardef_data() RETURNS trigger LANGUAGE plpgsql AS $$ DECLARE default_calendar bigint = (SELECT "Id" FROM "CalendarDef" WHERE "Id" != NEW."Id" AND "Default" AND "Status" = 'A'); BEGIN --Autofills & checks IF default_calendar IS null THEN IF NEW."Status" = 'N' THEN RAISE EXCEPTION 'CM_CUSTOM_EXCEPTION: It is not possible to delete the default calendar'; ELSE NEW."Default" = true; END IF; ELSIF NEW."Default" = true THEN UPDATE "CalendarDef" SET "Default" = false WHERE "Id" = default_calendar; END IF; RETURN NEW; END; $$; ,DROP FUNCTION public.tt_calendardef_data(); publicpostgresfalse1255233294tt_clienthw_to_clientsw_descr()FUNCTIONCREATE FUNCTION public.tt_clienthw_to_clientsw_descr() RETURNS trigger LANGUAGE plpgsql AS $$ DECLARE clientsws CURSOR FOR SELECT "Id" FROM "GenericClientSW" WHERE "ComputerClient" = NEW."Id" AND "Status" = 'A'; BEGIN --RAISE NOTICE 'Trigger % on %', TG_NAME, TG_TABLE_NAME; UPDATE "GenericClientSW" SET "Code" = null WHERE "Hardware" = NEW."Id" AND "Status" = 'A'; RETURN null; END; $$; 6DROP FUNCTION public.tt_clienthw_to_clientsw_descr(); publicpostgresfalse1255233295tt_clientsw_descr()FUNCTION"CREATE FUNCTION public.tt_clientsw_descr() RETURNS trigger LANGUAGE plpgsql AS $$ DECLARE hostname VARCHAR; infrdescr VARCHAR; idci INTEGER; model VARCHAR; version VARCHAR; BEGIN --RAISE NOTICE 'Trigger % on %', TG_NAME, TG_TABLE_NAME; SELECT "Hostname" INTO hostname FROM "Hardware" WHERE "Id" = NEW."Hardware"; SELECT "IdObj1" into idci from "Map_HardwareSoftwareInstance" where "IdObj2" = NEW."Id" and "Status" = 'A'; SELECT * into infrdescr from _cm_get_value_infrastructure(idci); -- check if Product has value -- Minimum set of attributes: Product OR Model+Version IF NEW."Product" IS NOT NULL THEN select into model, version "Model","Version" from "SWCatalogue" where "Id"=NEW."Product"; END IF; if(NEW."Model") IS NULL THEN NEW."Model" = model; END IF; if(NEW."Version") IS NULL THEN NEW."Version" = version; END IF; IF NEW."Model" IS NULL OR NEW."Version" IS NULL THEN RAISE EXCEPTION 'CM_CUSTOM_EXCEPTION: one between Product and Version+Model is compulsory. Please correct the data and try again.'; END IF; NEW."Description" = concat_ws(coalesce(infrdescr,' ',hostname,hostname),' ',NEW."Model",' ',NEW."Version"); --NEW."Description" = coalesce(NEW."HardwareKey"|| ' ' || NEW."Code" || coalesce(' ' || NEW."Version",''), hostname || ' ' || NEW."Model" || coalesce(' ' || NEW."Version",'')); --NEW."Description" = coalesce(infrdescr|| ' ' || hostname || NEW."Model" || coalesce(' ' || NEW."Version",''), NEW."HardwareKey"|| ' ' || NEW."Model"|| NEW."Code" || coalesce(' ' || NEW."Version",''), hostname || ' ' || NEW."Model" || coalesce(' ' || NEW."Version",'')); --NEW."Code" = coalesce(infrdescr|| ' ' || hostname ||' '||NEW."Description", NEW."HardwareKey"|| ' ' || NEW."Description", hostname || ' ' ||NEW."Description", NEW."Description" ); RETURN NEW; END; $$; *DROP FUNCTION public.tt_clientsw_descr(); publicpostgresfalse1255233296tt_cluster_descr()FUNCTIONCREATE FUNCTION public.tt_cluster_descr() RETURNS trigger LANGUAGE plpgsql AS $$ BEGIN --RAISE NOTICE 'Trigger % on %', TG_NAME, TG_TABLE_NAME; NEW."Description" = concat_ws(' ', NEW."Name", '[' || NEW."Code" || ']'); RETURN NEW; END; $$; )DROP FUNCTION public.tt_cluster_descr(); publicpostgresfalse1255233297tt_company_descr()FUNCTIONCREATE FUNCTION public.tt_company_descr() RETURNS trigger LANGUAGE plpgsql AS $$ BEGIN --RAISE NOTICE 'Trigger % on %', TG_NAME, TG_TABLE_NAME; NEW."Description" = concat_ws(' ', NEW."CompanyTitle", '[' || NEW."Code" || ']'); RETURN NEW; END; $$; )DROP FUNCTION public.tt_company_descr(); publicpostgresfalse1255233298tt_device_descr()FUNCTIONYCREATE FUNCTION public.tt_device_descr() RETURNS trigger LANGUAGE plpgsql AS $$ DECLARE infrdescr character varying ; BEGIN --RAISE NOTICE 'Trigger % on %', TG_NAME, TG_TABLE_NAME; SELECT * into infrdescr from _cm_get_value_infrastructure(NEW."Id"); NEW."Description" = concat_ws(' ', infrdescr, NEW."Code"); RETURN NEW; END; $$; (DROP FUNCTION public.tt_device_descr(); publicpostgresfalse1255233299tt_employee_descr()FUNCTION CREATE FUNCTION public.tt_employee_descr() RETURNS trigger LANGUAGE plpgsql AS $$ BEGIN --RAISE NOTICE 'Trigger % on %', TG_NAME, TG_TABLE_NAME; NEW."Description" = concat_ws(' ', initcap(NEW."LastName"),initcap(NEW."FirstName")); RETURN NEW; END; $$; *DROP FUNCTION public.tt_employee_descr(); publicpostgresfalse1255233300tt_formparameter_index()FUNCTIONoCREATE FUNCTION public.tt_formparameter_index() RETURNS trigger LANGUAGE plpgsql AS $$ DECLARE maxindex integer; BEGIN --RAISE NOTICE 'Trigger % on %', TG_NAME, TG_TABLE_NAME; SELECT coalesce(max("Index"),0) INTO maxindex FROM "FormParameter" WHERE "Status" = 'A' AND "FormName" = NEW."FormName"; NEW."Index" = maxindex + 1; RETURN NEW; END; $$; /DROP FUNCTION public.tt_formparameter_index(); publicpostgresfalse1255233301tt_hardware_descr()FUNCTIONCREATE FUNCTION public.tt_hardware_descr() RETURNS trigger LANGUAGE plpgsql AS $$ DECLARE infrdescr character varying ; BEGIN --RAISE NOTICE 'Trigger % on %', TG_NAME, TG_TABLE_NAME; SELECT * into infrdescr from _cm_get_value_infrastructure(NEW."Id"); NEW."Description" = concat_ws(' ', infrdescr, NEW."Hostname"); IF NEW."Product" IS NOT NULL THEN SELECT INTO NEW."Brand",NEW."Model",NEW."PartNumber" m."Brand",m."Model",m."PartNumber" from "HWCatalogue" m WHERE m."Id"=NEW."Product"; END IF; RETURN NEW; END; $$; *DROP FUNCTION public.tt_hardware_descr(); publicpostgresfalset1255233302'tt_hardware_to_networkinterface_descr()FUNCTION-CREATE FUNCTION public.tt_hardware_to_networkinterface_descr() RETURNS trigger LANGUAGE plpgsql AS $$ BEGIN --RAISE NOTICE 'Trigger % on %', TG_NAME, TG_TABLE_NAME; UPDATE "NetworkInterface" SET "Description" = null WHERE "Hardware" = NEW."Id" AND "Status" = 'A'; RETURN null; END; $$; >DROP FUNCTION public.tt_hardware_to_networkinterface_descr(); publicpostgresfalse1255233303tt_hwcatalogue_descr()FUNCTIONZCREATE FUNCTION public.tt_hwcatalogue_descr() RETURNS trigger LANGUAGE plpgsql AS $$ DECLARE brand VARCHAR; BEGIN --RAISE NOTICE 'Trigger % on %', TG_NAME, TG_TABLE_NAME; SELECT "Code" INTO brand FROM "LookUp" WHERE "Id" = NEW."Brand" ; NEW."Description" = concat_ws(' ',brand,NEW."Model",NEW."PartNumber"); RETURN NEW; END; $$; -DROP FUNCTION public.tt_hwcatalogue_descr(); publicpostgresfalse1255233304tt_infrastructure_descr()FUNCTIONCREATE FUNCTION public.tt_infrastructure_descr() RETURNS trigger LANGUAGE plpgsql AS $$ DECLARE DESCRTYPE character varying; BEGIN select "Description" INTO DESCRTYPE from "LookUp" where "Id" = NEW."Type"; --RAISE NOTICE 'Trigger % on %', TG_NAME, TG_TABLE_NAME; NEW."Description" = coalesce(NEW."Description", NEW."Name" || ' ' ||DESCRTYPE); NEW."Code" = coalesce(NEW."Code", NEW."Name" || ' ' ||DESCRTYPE); RETURN NEW; END; $$; 0DROP FUNCTION public.tt_infrastructure_descr(); publicpostgresfalse1255233305tt_infrastructureci_descr()FUNCTIONCREATE FUNCTION public.tt_infrastructureci_descr() RETURNS trigger LANGUAGE plpgsql AS $$ DECLARE OLDDESCR character varying ; BEGIN --UPDATE "CI" SET "Description" = NULL where "Id" = NEW."IdObj2"; SELECT "Description" INTO OLDDESCR FROM "CI" WHERE "Id" = NEW."IdObj2" AND "Status" = 'A'; UPDATE "CI" SET "Description" = OLDDESCR where "Id" = NEW."IdObj2"; RETURN NEW; END; $$; 2DROP FUNCTION public.tt_infrastructureci_descr(); publicpostgresfalse1255233306tt_iprange_descr()FUNCTIONoCREATE FUNCTION public.tt_iprange_descr() RETURNS trigger LANGUAGE plpgsql AS $$ DECLARE network VARCHAR; BEGIN --RAISE NOTICE 'Trigger % on %', TG_NAME, TG_TABLE_NAME; SELECT "Name" INTO network FROM "Network" WHERE "Id" = NEW."Network"; NEW."Description" = concat_ws(' ', network, concat_ws('-',NEW."FirstIP",NEW."LastIP")); RETURN NEW; END; $$; )DROP FUNCTION public.tt_iprange_descr(); publicpostgresfalse1255233307tt_itproccategory_descr()FUNCTIONCREATE FUNCTION public.tt_itproccategory_descr() RETURNS trigger LANGUAGE plpgsql AS $$ BEGIN --RAISE NOTICE 'Trigger % on %', TG_NAME, TG_TABLE_NAME; NEW."Description" = NEW."Code"; RETURN NEW; END; $$; 0DROP FUNCTION public.tt_itproccategory_descr(); publicpostgresfalse1255233308(tt_itproccategory_to_subcategory_descr()FUNCTIONCREATE FUNCTION public.tt_itproccategory_to_subcategory_descr() RETURNS trigger LANGUAGE plpgsql AS $$ DECLARE subcategories CURSOR FOR SELECT "Id" FROM "ITProcSubcategory" WHERE "Category" = NEW."Id" AND "Status" = 'A'; BEGIN --RAISE NOTICE 'Trigger % on %', TG_NAME, TG_TABLE_NAME; FOR subcategory IN subcategories LOOP UPDATE "ITProcSubcategory" SET "Description" = null WHERE "Id" = subcategory."Id"; END LOOP; RETURN null; END; $$; ?DROP FUNCTION public.tt_itproccategory_to_subcategory_descr(); publicpostgresfalse1255233309tt_itprocclassification_descr()FUNCTIONCREATE FUNCTION public.tt_itprocclassification_descr() RETURNS trigger LANGUAGE plpgsql AS $$ DECLARE wf_type varchar = (select "Code" from "LookUp" where "Id" = NEW."Workflow"); subcat_descr varchar = (select "Description" from "ITProcSubcategory" where "Id" = NEW."Subcategory"); BEGIN --RAISE NOTICE 'Trigger % on %', TG_NAME, TG_TABLE_NAME; NEW."Description" = concat_ws(' - ', wf_type, subcat_descr); RETURN NEW; END; $$; 6DROP FUNCTION public.tt_itprocclassification_descr(); publicpostgresfalse1255233310tt_itprocsubcategory_descr()FUNCTIONdCREATE FUNCTION public.tt_itprocsubcategory_descr() RETURNS trigger LANGUAGE plpgsql AS $$ DECLARE category VARCHAR; BEGIN --RAISE NOTICE 'Trigger % on %', TG_NAME, TG_TABLE_NAME; SELECT "Code" INTO category FROM "ITProcCategory" WHERE "Id" = NEW."Category"; NEW."Description" = concat_ws(' ', category, NEW."Code"); RETURN NEW; END; $$; 3DROP FUNCTION public.tt_itprocsubcategory_descr(); publicpostgresfalse1255233311)tt_itprocsubcategory_to_classific_descr()FUNCTIONLCREATE FUNCTION public.tt_itprocsubcategory_to_classific_descr() RETURNS trigger LANGUAGE plpgsql AS $$ BEGIN --RAISE NOTICE 'Trigger % on %', TG_NAME, TG_TABLE_NAME; UPDATE "ITProcClassification" SET "Description" = null, "User" = NEW."User" WHERE "Subcategory" = NEW."Id" and "Status" = 'A'; RETURN null; END; $$; @DROP FUNCTION public.tt_itprocsubcategory_to_classific_descr(); publicpostgresfalse1255233312 tt_kb_descr()FUNCTIONCREATE FUNCTION public.tt_kb_descr() RETURNS trigger LANGUAGE plpgsql AS $$ BEGIN --RAISE NOTICE 'Trigger % on %', TG_NAME, TG_TABLE_NAME; NEW."Description" = NEW."Code"; RETURN NEW; END; $$; $DROP FUNCTION public.tt_kb_descr(); publicpostgresfalse1255233313tt_level_to_floor_descr()FUNCTIONCREATE FUNCTION public.tt_level_to_floor_descr() RETURNS trigger LANGUAGE plpgsql AS $$ DECLARE floors CURSOR FOR SELECT "Id" FROM "Floor" WHERE "Level" = NEW."Id" AND "Status" = 'A'; BEGIN --RAISE NOTICE 'Trigger % on %', TG_NAME, TG_TABLE_NAME; FOR floor IN floors LOOP UPDATE "Floor" SET "Description" = null WHERE "Id" = floor."Id"; END LOOP; RETURN null; END; $$; 0DROP FUNCTION public.tt_level_to_floor_descr(); publicpostgresfalse1255233314tt_monitor_descr()FUNCTIONCREATE FUNCTION public.tt_monitor_descr() RETURNS trigger LANGUAGE plpgsql AS $$ DECLARE infrdescr character varying ; BEGIN --RAISE NOTICE 'Trigger % on %', TG_NAME, TG_TABLE_NAME; SELECT * into infrdescr from _cm_get_value_infrastructure(NEW."Id"); --NEW."Description" = coalesce(NEW."Hostname",'') || coalesce(' [' || NEW."Code" || '] ', ''); NEW."Description" = concat_ws(' ', infrdescr, NEW."Hostname",' [' || NEW."Code" || '] '); RETURN NEW; END; $$; )DROP FUNCTION public.tt_monitor_descr(); publicpostgresfalse1255233315!tt_netinterf_to_virtualip_descr()FUNCTIONCREATE FUNCTION public.tt_netinterf_to_virtualip_descr() RETURNS trigger LANGUAGE plpgsql AS $$ DECLARE virtualips CURSOR FOR SELECT "Id" FROM "VirtualIP" WHERE "NetworkInterface" = NEW."Id" AND "Status" = 'A'; BEGIN --RAISE NOTICE 'Trigger % on %', TG_NAME, TG_TABLE_NAME; FOR virtualip IN virtualips LOOP UPDATE "VirtualIP" SET "Description" = null WHERE "Id" = virtualip."Id"; END LOOP; RETURN null; END; $$; 8DROP FUNCTION public.tt_netinterf_to_virtualip_descr(); publicpostgresfalse1255233316tt_network_descr()FUNCTIONCREATE FUNCTION public.tt_network_descr() RETURNS trigger LANGUAGE plpgsql AS $$ BEGIN --RAISE NOTICE 'Trigger % on %', TG_NAME, TG_TABLE_NAME; NEW."Description" = NEW."Name"; RETURN NEW; END; $$; )DROP FUNCTION public.tt_network_descr(); publicpostgresfalse1255233317tt_network_to_iprange_descr()FUNCTIONCREATE FUNCTION public.tt_network_to_iprange_descr() RETURNS trigger LANGUAGE plpgsql AS $$ BEGIN --RAISE NOTICE 'Trigger % on %', TG_NAME, TG_TABLE_NAME; UPDATE "IPRange" SET "Description" = null WHERE "Network" = NEW."Id" AND "Status" = 'A'; RETURN null; END; $$; 4DROP FUNCTION public.tt_network_to_iprange_descr(); publicpostgresfalse1255233318tt_networkinterface_descr()FUNCTION}CREATE FUNCTION public.tt_networkinterface_descr() RETURNS trigger LANGUAGE plpgsql AS $$ DECLARE hostname VARCHAR; BEGIN --RAISE NOTICE 'Trigger % on %', TG_NAME, TG_TABLE_NAME; SELECT "Hostname" INTO hostname FROM "Hardware" WHERE "Id" = NEW."Hardware"; NEW."Code" = NEW."Name"; NEW."Description" = concat_ws(' ', hostname, NEW."Code"); RETURN NEW; END; $$; 2DROP FUNCTION public.tt_networkinterface_descr(); publicpostgresfalse1255233319 tt_no_data()FUNCTIONCREATE FUNCTION public.tt_no_data() RETURNS trigger LANGUAGE plpgsql AS $$ BEGIN RAISE EXCEPTION 'This class cannot contain any data'; NEW = null; END; $$; #DROP FUNCTION public.tt_no_data(); publicpostgresfalse1255233320tt_order_to_orderrow_code()FUNCTIONCREATE FUNCTION public.tt_order_to_orderrow_code() RETURNS trigger LANGUAGE plpgsql AS $$ BEGIN --RAISE NOTICE 'Trigger % on %', TG_NAME, TG_TABLE_NAME; UPDATE "PurchaseOrderRow" SET "Code" = null WHERE "Order" = NEW."Id" and "Status" = 'A'; RETURN null; END; $$; 2DROP FUNCTION public.tt_order_to_orderrow_code(); publicpostgresfalse1255233321tt_orderrow_code()FUNCTIONCREATE FUNCTION public.tt_orderrow_code() RETURNS trigger LANGUAGE plpgsql AS $$ DECLARE orderCode varchar; max_code integer; BEGIN --RAISE NOTICE 'Trigger % on %', TG_NAME, TG_TABLE_NAME; SELECT "Code" INTO orderCode FROM "PurchaseOrder" WHERE "Id" = NEW."Order"; IF(TG_OP = 'INSERT') THEN SELECT coalesce(MAX("Position")::integer,0) into max_code FROM "PurchaseOrderRow" WHERE "Order" = NEW."Order" AND "Status"='A'; NEW."Position" = lpad((max_code + 1)::text, 2, '0'); NEW."Code" = coalesce(orderCode || '-' , '') || NEW."Position"; ELSE NEW."Code" = coalesce(orderCode || '-' , '') || NEW."Position"; END IF; RETURN NEW; END; $$; )DROP FUNCTION public.tt_orderrow_code(); publicpostgresfalse1255233322 tt_ou_descr()FUNCTIONWCREATE FUNCTION public.tt_ou_descr() RETURNS trigger LANGUAGE plpgsql AS $$ BEGIN --RAISE NOTICE 'Trigger % on %', TG_NAME, TG_TABLE_NAME; NEW."Description" = coalesce((select "Description" from "CorporateGroup" where "Id" = NEW."Company" and "Status" = 'A') || ' - ', '') || coalesce(NEW."Name", ''); RETURN NEW; END; $$; $DROP FUNCTION public.tt_ou_descr(); publicpostgresfalse1255233323tt_printer_descr()FUNCTIONCREATE FUNCTION public.tt_printer_descr() RETURNS trigger LANGUAGE plpgsql AS $$ DECLARE infrdescr character varying ; BEGIN --RAISE NOTICE 'Trigger % on %', TG_NAME, TG_TABLE_NAME; SELECT * into infrdescr from _cm_get_value_infrastructure(NEW."Id"); --NEW."Description" = coalesce(NEW."Hostname",'') || coalesce(' [' || NEW."Code" || '] ', ''); NEW."Description" = concat_ws(' ', infrdescr, NEW."Hostname",' [' || NEW."Code" || '] '); RETURN NEW; END; $$; )DROP FUNCTION public.tt_printer_descr(); publicpostgresfalse1255233324tt_problem_code()FUNCTION4CREATE FUNCTION public.tt_problem_code() RETURNS trigger LANGUAGE plpgsql AS $$ DECLARE newcode text; BEGIN --RAISE NOTICE 'Trigger % on %', TG_NAME, TG_TABLE_NAME; SELECT number INTO newcode FROM problem_code(); NEW."Code" = newcode; NEW."Number" = newcode; RETURN NEW; END; $$; (DROP FUNCTION public.tt_problem_code(); publicpostgresfalse1255233325tt_reqfulfil_nextrole()FUNCTIONCREATE FUNCTION public.tt_reqfulfil_nextrole() RETURNS trigger LANGUAGE plpgsql AS $$ BEGIN NEW."NextRole" = COALESCE(NEW."HDNextRole", NEW."SRClassificNextRole", NEW."SRApprNextRole", NEW."SRWORevNextRole", NEW."SPNextRole"); NEW."SuggOperator" = COALESCE(NEW."HDSuggOperator", NEW."SRClassificSuggOp", NEW."SRApprSuggOp", NEW."SRWORevSuggOp", NEW."SPSuggOperator"); RETURN NEW; END; $$; .DROP FUNCTION public.tt_reqfulfil_nextrole(); publicpostgresfalse1255233326tt_server_to_serversw_descr()FUNCTIONCREATE FUNCTION public.tt_server_to_serversw_descr() RETURNS trigger LANGUAGE plpgsql AS $$ BEGIN --RAISE NOTICE 'Trigger % on %', TG_NAME, TG_TABLE_NAME; UPDATE "ServerSW" SET "Code" = null WHERE "Hardware" = NEW."Id" AND "Status" = 'A'; RETURN null; END; $$; 4DROP FUNCTION public.tt_server_to_serversw_descr(); publicpostgresfalse1255233327tt_serversw_descr()FUNCTIONCREATE FUNCTION public.tt_serversw_descr() RETURNS trigger LANGUAGE plpgsql AS $$ DECLARE hostname VARCHAR; infrdescr character varying ; idci integer; BEGIN --RAISE NOTICE 'Trigger % on %', TG_NAME, TG_TABLE_NAME; SELECT "Hostname" INTO hostname FROM "Hardware" WHERE "Id" = NEW."Hardware"; SELECT "IdObj1" into idci from "Map_HardwareSoftwareInstance" where "IdObj2" = NEW."Id" and "Status" = 'A'; SELECT * into infrdescr from _cm_get_value_infrastructure(idci); NEW."Code" = coalesce(infrdescr|| ' ' || hostname ||' '||NEW."Description", NEW."HardwareKey"|| ' ' || NEW."Description", hostname || ' ' ||NEW."Description", NEW."Description" ); RETURN NEW; END; $$; *DROP FUNCTION public.tt_serversw_descr(); publicpostgresfalse1255233328tt_service_descr()FUNCTIONCREATE FUNCTION public.tt_service_descr() RETURNS trigger LANGUAGE plpgsql AS $$ BEGIN --RAISE NOTICE 'Trigger % on %', TG_NAME, TG_TABLE_NAME; NEW."Description" = concat_ws(' ', NEW."Code",NEW."Name"); RETURN NEW; END; $$; )DROP FUNCTION public.tt_service_descr(); publicpostgresfalse1255233329tt_servicecategory_code()FUNCTIONUCREATE FUNCTION public.tt_servicecategory_code() RETURNS trigger LANGUAGE plpgsql AS $$ DECLARE parent VARCHAR; BEGIN --RAISE NOTICE 'Trigger % on %', TG_NAME, TG_TABLE_NAME; SELECT "Code" INTO parent FROM "ServiceCategory" WHERE "Id" = NEW."Parent"; NEW."Code" = concat_ws(' ', parent, NEW."Index"); RETURN NEW; END; $$; 0DROP FUNCTION public.tt_servicecategory_code(); publicpostgresfalse1255233330%tt_servicecategory_to_children_code()FUNCTION!CREATE FUNCTION public.tt_servicecategory_to_children_code() RETURNS trigger LANGUAGE plpgsql AS $$ BEGIN --RAISE NOTICE 'Trigger % on %', TG_NAME, TG_TABLE_NAME; UPDATE "ServiceCategory" SET "Code" = null WHERE "Parent" = NEW."Id" AND "Status" = 'A'; RETURN null; END; $$; <DROP FUNCTION public.tt_servicecategory_to_children_code(); publicpostgresfalse1255233331 tt_servicecontract_description()FUNCTIONMCREATE FUNCTION public.tt_servicecontract_description() RETURNS trigger LANGUAGE plpgsql AS $$ DECLARE servicedescr VARCHAR := (SELECT "Description" FROM "Service" WHERE "Id" = NEW."Service"); requesterdescr VARCHAR := (SELECT "Description" FROM "Employee" WHERE "Id" = NEW."Employee"); startdatedescr VARCHAR := to_char(NEW."StartDate",'DD/MM/YYYY'); expirationdatedescr VARCHAR := to_char(NEW."ExpirationDate",'DD/MM/YYYY'); BEGIN NEW."Description" = concat_ws(' - ', servicedescr, requesterdescr, concat_ws(' / ',startdatedescr,expirationdatedescr)); RETURN NEW; END; $$; 7DROP FUNCTION public.tt_servicecontract_description(); publicpostgresfalse1255233332tt_servicerequest_check()FUNCTIONCREATE FUNCTION public.tt_servicerequest_check() RETURNS trigger LANGUAGE plpgsql AS $$ DECLARE no_approval INTEGER = (select "Id" from "LookUp" where "Code" = 'None' and "Type" = 'Approval - Type' and "Status" = 'A'); it_approval INTEGER = (select "Id" from "LookUp" where "Code" = 'IT' and "Type" = 'Approval - Type' and "Status" = 'A'); ou_approval INTEGER = (select "Id" from "LookUp" where "Code" = 'OU' and "Type" = 'Approval - Type' and "Status" = 'A'); manager_approval INTEGER = (select "Id" from "LookUp" where "Code" = 'manager' and "Type" = 'Approval - Type' and "Status" = 'A'); BEGIN --RAISE NOTICE 'Trigger % on %', TG_NAME, TG_TABLE_NAME; IF(NEW."ApprovalType" = no_approval AND (NEW."ApproverRole" IS NOT NULL OR NEW."ApproverOU" IS NOT NULL)) THEN RAISE EXCEPTION 'CM_CUSTOM_EXCEPTION: If approval is not required, "Approver role" and "Approver OU" must be blank'; ELSEIF(NEW."ApprovalType" = it_approval AND NEW."ApproverRole" IS NULL) THEN RAISE EXCEPTION 'CM_CUSTOM_EXCEPTION: If approval is required by an IT group, "Approver role" is mandatory'; ELSEIF(NEW."ApprovalType" = it_approval AND NEW."ApproverOU" IS NOT NULL) THEN RAISE EXCEPTION 'CM_CUSTOM_EXCEPTION: If approval is required by an IT group, "Approver OU" must be blank'; ELSEIF(NEW."ApprovalType" = ou_approval AND NEW."ApproverOU" IS NULL) THEN RAISE EXCEPTION 'CM_CUSTOM_EXCEPTION: If approval is required by an IT group, "Approver OU" is mandatory'; ELSEIF(NEW."ApprovalType" = ou_approval AND NEW."ApproverRole" IS NOT NULL) THEN RAISE EXCEPTION 'CM_CUSTOM_EXCEPTION: If approval is required by an IT group, "Approver role" must be blank'; ELSEIF(NEW."ApprovalType" = manager_approval AND (NEW."ApproverRole" IS NOT NULL OR NEW."ApproverOU" IS NOT NULL)) THEN RAISE EXCEPTION 'CM_CUSTOM_EXCEPTION: If approval is required by the requester''s unit manager, "Approver role" and "Approver OU" must be blank'; END IF; RETURN NEW; END; $$; 0DROP FUNCTION public.tt_servicerequest_check(); publicpostgresfalse1255233333tt_servicerequest_descr()FUNCTIONCREATE FUNCTION public.tt_servicerequest_descr() RETURNS trigger LANGUAGE plpgsql AS $$ BEGIN --RAISE NOTICE 'Trigger % on %', TG_NAME, TG_TABLE_NAME; NEW."Description" = concat_ws(NEW."Code", NEW."Name"); RETURN NEW; END; $$; 0DROP FUNCTION public.tt_servicerequest_descr(); publicpostgresfalse1255233334tt_site_data()FUNCTIONCREATE FUNCTION public.tt_site_data() RETURNS trigger LANGUAGE plpgsql AS $$ BEGIN NEW."Description" = concat_ws(' - ', NEW."Code", NEW."Name"); RETURN NEW; END; $$; %DROP FUNCTION public.tt_site_data(); publicpostgresfalse1255233335$tt_supplier_to_purchaseorder_descr()FUNCTION(CREATE FUNCTION public.tt_supplier_to_purchaseorder_descr() RETURNS trigger LANGUAGE plpgsql AS $$ BEGIN --RAISE NOTICE 'Trigger % on %', TG_NAME, TG_TABLE_NAME; UPDATE "PurchaseOrder" SET "Description" = null WHERE "Supplier" = NEW."Id" AND "Status" = 'A'; RETURN null; END; $$; ;DROP FUNCTION public.tt_supplier_to_purchaseorder_descr(); publicpostgresfalse1255233336tt_suppliercontract_descr()FUNCTIONCREATE FUNCTION public.tt_suppliercontract_descr() RETURNS trigger LANGUAGE plpgsql AS $$ DECLARE companytitle VARCHAR; BEGIN --RAISE NOTICE 'Trigger % on %', TG_NAME, TG_TABLE_NAME; SELECT "CompanyTitle" INTO companytitle FROM "Supplier" WHERE "Id" = NEW."Supplier"; NEW."Description" = concat_ws(' ', companytitle,NEW."Code",NEW."SigningDate"); RETURN NEW; END; $$; 2DROP FUNCTION public.tt_suppliercontract_descr(); publicpostgresfalse1255233337tt_supplieremployee_descr()FUNCTIONCREATE FUNCTION public.tt_supplieremployee_descr() RETURNS trigger LANGUAGE plpgsql AS $$ DECLARE companytitle VARCHAR; BEGIN --RAISE NOTICE 'Trigger % on %', TG_NAME, TG_TABLE_NAME; SELECT "CompanyTitle" INTO companytitle FROM "Supplier" WHERE "Id" = NEW."Company"; NEW."Description" = concat_ws(' ', companytitle, initcap(NEW."LastName"), initcap(NEW."FirstName")); RETURN NEW; END; $$; 2DROP FUNCTION public.tt_supplieremployee_descr(); publicpostgresfalse1255233338tt_swcatalogue_descr()FUNCTIONWCREATE FUNCTION public.tt_swcatalogue_descr() RETURNS trigger LANGUAGE plpgsql AS $$ DECLARE brand VARCHAR; BEGIN --RAISE NOTICE 'Trigger % on %', TG_NAME, TG_TABLE_NAME; SELECT "Code" INTO brand FROM "LookUp" WHERE "Id" = NEW."Brand" ; NEW."Description" = concat_ws(' ',brand,NEW."Model",NEW."Version"); RETURN NEW; END; $$; -DROP FUNCTION public.tt_swcatalogue_descr(); publicpostgresfalse1255233339tt_swlicense_descr()FUNCTIONoCREATE FUNCTION public.tt_swlicense_descr() RETURNS trigger LANGUAGE plpgsql AS $$ DECLARE infrdescr character varying ; BEGIN --RAISE NOTICE 'Trigger % on %', TG_NAME, TG_TABLE_NAME; SELECT * into infrdescr from _cm_get_value_infrastructure(NEW."Id"); NEW."Description" = concat_ws(' ', infrdescr, NEW."Code", NEW."SerialNumber"); RETURN NEW; END; $$; +DROP FUNCTION public.tt_swlicense_descr(); publicpostgresfalse1255233340tt_virtualip_descr()FUNCTIONCREATE FUNCTION public.tt_virtualip_descr() RETURNS trigger LANGUAGE plpgsql AS $$ DECLARE netinterf VARCHAR; BEGIN --RAISE NOTICE 'Trigger % on %', TG_NAME, TG_TABLE_NAME; NEW."Code" = NEW."IPAddress"; SELECT "Description" INTO netinterf FROM "NetworkInterface" WHERE "Id" = NEW."NetworkInterface"; NEW."Description" = concat_ws(netinterf, NEW."Code"); RETURN NEW; END; $$; +DROP FUNCTION public.tt_virtualip_descr(); publicpostgresfalse1255233341tt_virtualserver_instancetype()FUNCTIONCREATE FUNCTION public.tt_virtualserver_instancetype() RETURNS trigger LANGUAGE plpgsql AS $$ DECLARE infrdescr character varying ; BEGIN --RAISE NOTICE 'Trigger % on %', TG_NAME, TG_TABLE_NAME; SELECT * into infrdescr from _cm_get_value_infrastructure(NEW."Id"); IF NEW."InstanceType" IS NOT NULL THEN SELECT INTO NEW."RAM",NEW."TotalCPUs" i."RAM",i."VCPU" from "InstanceType" i WHERE i."Id"=NEW."InstanceType"; END IF; RETURN NEW; END; $$; 6DROP FUNCTION public.tt_virtualserver_instancetype(); publicpostgresfalse1255233342tt_workingcalendar_data()FUNCTIONUCREATE FUNCTION public.tt_workingcalendar_data() RETURNS trigger LANGUAGE plpgsql AS $$ DECLARE date_dlm varchar = '-'; year_pattern varchar = 'YYYY'; occurrence_type varchar = (SELECT "Code" FROM "LookUp" WHERE "Id" = NEW."OccurrenceType"); working_time varchar = (SELECT "Code" FROM "LookUp" WHERE "Id" = NEW."WorkingTime"); BEGIN --Autofills IF occurrence_type = 'DayOfWeek' THEN NEW."Description" = (SELECT "Description" FROM "LookUp" WHERE "Id" = NEW."DayOfWeek"); END IF; IF working_time IN ('Never', 'Always') THEN NEW."TimeSlots" = (SELECT upper("Code") FROM "LookUp" WHERE "Id" = NEW."WorkingTime"); END IF; IF occurrence_type = 'CalendarDate' AND split_part(NEW."CalendarDate", date_dlm, 1) != year_pattern THEN NEW."Priority" = (SELECT "Id" FROM "LookUp" WHERE "Type" = 'WorkingCalendar - Priority' AND "Code" = '1' AND "Status" = 'A'); ELSIF occurrence_type = 'CalendarDate' AND split_part(NEW."CalendarDate", date_dlm, 1) = year_pattern THEN NEW."Priority" = (SELECT "Id" FROM "LookUp" WHERE "Type" = 'WorkingCalendar - Priority' AND "Code" = '2' AND "Status" = 'A'); ELSIF occurrence_type = 'DayOfWeek' THEN NEW."Priority" = (SELECT "Id" FROM "LookUp" WHERE "Type" = 'WorkingCalendar - Priority' AND "Code" = '3' AND "Status" = 'A'); END IF; --Checks IF occurrence_type IS null THEN RAISE EXCEPTION 'CM_CUSTOM_EXCEPTION: The "Occurrence type" field is mandatory'; END IF; IF occurrence_type = 'CalendarDate' AND NEW."CalendarDate" IS null THEN RAISE EXCEPTION 'CM_CUSTOM_EXCEPTION: The "Calendar date" field is mandatory'; END IF; IF occurrence_type = 'DayOfWeek' AND NEW."DayOfWeek" IS null THEN RAISE EXCEPTION 'CM_CUSTOM_EXCEPTION: The "Day of week" field is mandatory'; END IF; IF working_time IS null THEN RAISE EXCEPTION 'CM_CUSTOM_EXCEPTION: The "Working time" field is mandatory'; END IF; IF NEW."TimeSlots" IS null THEN RAISE EXCEPTION 'CM_CUSTOM_EXCEPTION: The "Time slots" field is mandatory'; END IF; IF NEW."Description" IS null THEN RAISE EXCEPTION 'CM_CUSTOM_EXCEPTION: The "Description" field is mandatory'; END IF; RETURN NEW; END; $$; 0DROP FUNCTION public.tt_workingcalendar_data(); publicpostgresfalse1255233343tt_wotmpl_descr()FUNCTIONCREATE FUNCTION public.tt_wotmpl_descr() RETURNS trigger LANGUAGE plpgsql AS $$ BEGIN --RAISE NOTICE 'Trigger % on %', TG_NAME, TG_TABLE_NAME; NEW."Description" = NEW."ActivityName"; RETURN NEW; END; $$; (DROP FUNCTION public.tt_wotmpl_descr(); publicpostgresfalse1255233344tt_wotmpl_setclass()FUNCTIONCREATE FUNCTION public.tt_wotmpl_setclass() RETURNS trigger LANGUAGE plpgsql AS $$ BEGIN --RAISE NOTICE 'Trigger % on %', TG_NAME, TG_TABLE_NAME; NEW."TargetClass" = trim('"' from NEW."IdClass"::varchar); RETURN NEW; END; $$; +DROP FUNCTION public.tt_wotmpl_setclass(); publicpostgresfalse1255233345Rutils_wc_closest_workingrange(timestamp with time zone, bigint, character varying)FUNCTIONCREATE FUNCTION public.utils_wc_closest_workingrange(reference_ts timestamp with time zone, calendar_def bigint DEFAULT 0, direction character varying DEFAULT 'forward'::character varying, OUT working_range tstzrange) RETURNS tstzrange LANGUAGE plpgsql STRICT AS $$ DECLARE max_days_iteration integer = 366; BEGIN --By using the STRICT language option the function is not executed when there are null arguments and a null result is assumed automatically calendar_def = coalesce(nullif(calendar_def, 0), (SELECT "Id" FROM "CalendarDef" WHERE "Default" AND "Status" = 'A')); RAISE DEBUG 'providing the closest available working range from the reference timestamp "%" in calendar "%" by searching "%"',reference_ts,calendar_def,direction; FOR d IN 1..max_days_iteration LOOP RAISE DEBUG 'checking day "%/%" with the reference timestamp "%"',d,max_days_iteration,reference_ts; CASE direction WHEN 'forward' THEN --Check foreward if there are available working ranges fot the current timestamp FOR working_range IN ( --Get highest priority working ranges with pattern '[%s,%s)' (not specified since default) for forward search SELECT sq.working_range FROM utils_wc_date_workingranges(reference_ts, (SELECT time_slots FROM utils_wc_date_timeslots(reference_ts, calendar_def))) sq WHERE NOT isempty(sq.working_range) ORDER BY lower(sq.working_range) ASC, upper(sq.working_range) ASC ) LOOP IF reference_ts < lower(working_range) THEN RAISE DEBUG 'provided the working range "%" since the reference timestamp "%" in calendar "%" is before it',working_range,reference_ts,calendar_def; RETURN; ELSIF reference_ts <@ working_range THEN working_range = format('[%s,%s)', reference_ts, upper(working_range)); RAISE DEBUG 'provided the working range "%" since the reference timestamp "%" in calendar "%" is within it',working_range,reference_ts,calendar_def; RETURN; ELSE RAISE DEBUG 'check the next working range since the reference timestamp "%" in calendar "%" is after "%"',reference_ts,calendar_def,working_range; END IF; END LOOP; reference_ts = date_trunc('day', reference_ts) + '1 day'::interval; WHEN 'backward' THEN --Check backward if there are available working ranges fot the current timestamp FOR working_range IN ( --Get highest priority working ranges with pattern '(%s,%s]' for backward search SELECT sq.working_range FROM utils_wc_date_workingranges(reference_ts, (SELECT time_slots FROM utils_wc_date_timeslots(reference_ts, calendar_def)), '(%s,%s]') sq WHERE NOT isempty(sq.working_range) ORDER BY upper(sq.working_range) DESC, lower(sq.working_range) DESC ) LOOP IF reference_ts > upper(working_range) THEN RAISE DEBUG 'provided the working range "%" since the reference timestamp "%" in calendar "%" is after it',working_range,reference_ts,calendar_def; RETURN; ELSIF reference_ts <@ working_range THEN working_range = format('(%s,%s]', lower(working_range), reference_ts); RAISE DEBUG 'provided the working range "%" since the reference timestamp "%" in calendar "%" is within it',working_range,reference_ts,calendar_def; RETURN; ELSE RAISE DEBUG 'check the previous working range since the reference timestamp "%" in calendar "%" is before "%"',reference_ts,calendar_def,working_range; END IF; END LOOP; reference_ts = date_trunc('day', reference_ts) - '1 millisecond'::interval; ELSE RAISE EXCEPTION 'CM_CUSTOM_EXCEPTION: Search direction "%" not handled',direction; END CASE; END LOOP; working_range = 'empty'; RAISE DEBUG 'provided the working range "%" because the maximum iterations number was exceeded',working_range; RETURN; END; $$; DROP FUNCTION public.utils_wc_closest_workingrange(reference_ts timestamp with time zone, calendar_def bigint, direction character varying, OUT working_range tstzrange); publicpostgresfalse12552333469utils_wc_date_timeslots(timestamp with time zone, bigint)FUNCTIONzCREATE FUNCTION public.utils_wc_date_timeslots(reference_ts timestamp with time zone, calendar_def bigint DEFAULT 0, OUT time_slots character varying) RETURNS character varying LANGUAGE plpgsql STRICT AS $$ DECLARE year_pattern varchar = 'YYYY'; BEGIN --By using the STRICT language option the function is not executed when there are null arguments and a null result is assumed automatically calendar_def = coalesce(nullif(calendar_def, 0), (SELECT "Id" FROM "CalendarDef" WHERE "Default" AND "Status" = 'A')); RAISE DEBUG 'retrieving the time slots from the highest priority WorkingCalendar entry for the reference timestamp "%" in calendar "%"',reference_ts,calendar_def; SELECT wc."TimeSlots" FROM "WorkingCalendar" wc LEFT JOIN "LookUp" priority ON priority."Id" = wc."Priority" WHERE ( (REPLACE(wc."CalendarDate", year_pattern, date_part('year', reference_ts)::varchar))::date = reference_ts::date --specific or recurrent day OR EXTRACT(DOW FROM reference_ts) = (SELECT "Notes"::integer FROM "LookUp" WHERE "Id" = wc."DayOfWeek") --corresponding weekday ) AND wc."CalendarDef" = calendar_def AND wc."Status" = 'A' ORDER BY priority."Code"::integer ASC LIMIT 1 INTO time_slots; RAISE DEBUG 'retrieved the time slots "%" from the highest priority WorkingCalendar entry for the reference timestamp "%" in calendar "%"',time_slots,reference_ts,calendar_def; RETURN; END; $$; DROP FUNCTION public.utils_wc_date_timeslots(reference_ts timestamp with time zone, calendar_def bigint, OUT time_slots character varying); publicpostgresfalse1255233347[utils_wc_date_workingranges(timestamp with time zone, character varying, character varying)FUNCTIONCREATE FUNCTION public.utils_wc_date_workingranges(reference_ts timestamp with time zone, time_slots character varying, pattern character varying DEFAULT '[%s,%s)'::character varying, OUT working_range tstzrange) RETURNS SETOF tstzrange LANGUAGE plpgsql STRICT AS $$ DECLARE slot_dlm varchar = ','; time_dlm varchar = '-'; working_ranges tstzrange[]; BEGIN --By using the STRICT language option the function is not executed when there are null arguments and a null result is assumed automatically RAISE DEBUG 'creating the working ranges for the reference timestamp "%" and the time slots "%" using the pattern "%"',reference_ts,time_slots,pattern; CASE time_slots WHEN 'NEVER' THEN working_ranges = '{empty}'; WHEN 'ALWAYS' THEN CASE pattern WHEN '(%s,%s]' THEN --Used for backward search working_ranges = array_agg(format(pattern, date_trunc('day', reference_ts) - '1 day'::interval, date_trunc('day', reference_ts))); ELSE --Used for forward search working_ranges = array_agg(format(pattern, date_trunc('day', reference_ts), date_trunc('day', reference_ts) + '1 day'::interval)); END CASE; ELSE WITH working AS ( SELECT split_part(slot, time_dlm, 1) time_start, split_part(slot, time_dlm, 2) time_stop FROM (SELECT unnest(string_to_array(time_slots, slot_dlm)) slot) sq ORDER BY 1, 2 ) SELECT array_agg(format(pattern, reference_ts::date || ' ' || working.time_start, reference_ts::date || ' ' || working.time_stop)) FROM working INTO working_ranges; END CASE; RAISE DEBUG 'created the working ranges "%" for the reference timestamp "%" and the time slots "%" using the pattern "%"',working_ranges,reference_ts,time_slots,pattern; RETURN QUERY SELECT unnest(working_ranges); END; $$; DROP FUNCTION public.utils_wc_date_workingranges(reference_ts timestamp with time zone, time_slots character varying, pattern character varying, OUT working_range tstzrange); publicpostgresfalse1255233348Eutils_wc_get_workboundary(timestamp with time zone, interval, bigint)FUNCTION CREATE FUNCTION public.utils_wc_get_workboundary(reference_ts timestamp with time zone, work_time interval, calendar_def bigint DEFAULT 0, OUT working_ts timestamp with time zone) RETURNS timestamp with time zone LANGUAGE plpgsql STRICT AS $$ DECLARE working_range tstzrange; leftover interval = work_time; BEGIN --By using the STRICT language option the function is not executed when there are null arguments and a null result is assumed automatically calendar_def = coalesce(nullif(calendar_def, 0), (SELECT "Id" FROM "CalendarDef" WHERE "Default" AND "Status" = 'A')); RAISE DEBUG 'computing the work boundary timestamp at a work time "%" from the reference timestamp "%" in calendar "%"',work_time,reference_ts,calendar_def; IF work_time >= '0'::interval THEN --For positive intervals search 'forward' (not specified since default) working_range = (SELECT sq.working_range FROM utils_wc_closest_workingrange(reference_ts, calendar_def) sq); WHILE leftover > upper(working_range) - lower(working_range) LOOP RAISE DEBUG 'continue since leftover "%" is greater than working range "%" interval "%"',leftover,working_range,upper(working_range)-lower(working_range); leftover = leftover - (upper(working_range) - lower(working_range)); working_range = (SELECT sq.working_range FROM utils_wc_closest_workingrange(upper(working_range), calendar_def) sq); END LOOP; working_ts = lower(working_range) + leftover; ELSE --For negative intervals search 'backward' working_range = (SELECT sq.working_range FROM utils_wc_closest_workingrange(reference_ts, calendar_def, 'backward') sq); WHILE -leftover > upper(working_range) - lower(working_range) LOOP RAISE DEBUG 'continue since |leftover| "%" is greater than working range "%" interval "%"',leftover,working_range,upper(working_range)-lower(working_range); leftover = leftover + (upper(working_range) - lower(working_range)); working_range = (SELECT sq.working_range FROM utils_wc_closest_workingrange(lower(working_range), calendar_def, 'backward') sq); END LOOP; working_ts = upper(working_range) + leftover; END IF; RAISE DEBUG 'computed the work boundary timestamp "%" at a work time "%" from the reference timestamp "%" in calendar "%"',working_ts,work_time,reference_ts,calendar_def; RETURN; END; $$; DROP FUNCTION public.utils_wc_get_workboundary(reference_ts timestamp with time zone, work_time interval, calendar_def bigint, OUT working_ts timestamp with time zone); publicpostgresfalse1255233349Qutils_wc_get_worktime(timestamp with time zone, timestamp with time zone, bigint)FUNCTIONCREATE FUNCTION public.utils_wc_get_worktime(initial_ts timestamp with time zone, final_ts timestamp with time zone, calendar_def bigint DEFAULT 0, OUT work_time interval) RETURNS interval LANGUAGE plpgsql STRICT AS $$ DECLARE working_range tstzrange; lower_ts timestamptz = least(initial_ts, final_ts); upper_ts timestamptz = greatest(initial_ts, final_ts); stop_ts timestamptz = (SELECT upper(sq.working_range) FROM utils_wc_closest_workingrange(upper_ts, calendar_def, 'backward') sq); BEGIN --By using the STRICT language option the function is not executed when there are null arguments and a null result is assumed automatically calendar_def = coalesce(nullif(calendar_def, 0), (SELECT "Id" FROM "CalendarDef" WHERE "Default" AND "Status" = 'A')); RAISE DEBUG 'computing the work time elapsed between the initial "%" and final "%" timestamps in calendar "%"',initial_ts,final_ts,calendar_def; work_time = '0'; working_range = (SELECT sq.working_range FROM utils_wc_closest_workingrange(lower_ts, calendar_def) sq); WHILE upper(working_range) < stop_ts LOOP RAISE DEBUG 'continue since final working timestamp "%" greater than working range "%" upper bound (work time "%")',stop_ts,working_range,work_time; work_time = work_time + (upper(working_range) - lower(working_range)); working_range = (SELECT sq.working_range FROM utils_wc_closest_workingrange(upper(working_range), calendar_def) sq); END LOOP; work_time = work_time + (stop_ts - lower(working_range)); IF initial_ts > final_ts THEN work_time = -work_time; END IF; RAISE DEBUG 'computed the work time "%" elapsed between the initial "%" and final "%" timestamps in calendar "%"',work_time,initial_ts,final_ts,calendar_def; RETURN; END; $$; DROP FUNCTION public.utils_wc_get_worktime(initial_ts timestamp with time zone, final_ts timestamp with time zone, calendar_def bigint, OUT work_time interval); publicpostgresfalse1255233350view_imoutofsla()FUNCTIONCREATE FUNCTION public.view_imoutofsla(OUT "Number" character varying, OUT "Creation date" text, OUT "Subject" text, OUT "Area" character varying, OUT "Requester" character varying, OUT "Contract" character varying, OUT "Priority" character varying, OUT "Subcategory" character varying, OUT "SLA name" character varying, OUT "Link" text) RETURNS SETOF record LANGUAGE plpgsql AS $$ DECLARE today timestamp with time zone; slaobj_resolution bigint = (select "Id" from "LookUp" where "Type"='SLA - Object' and "Code"='resolution' and "Status"='A'); slaobj_takecharge bigint = (select "Id" from "LookUp" where "Type"='SLA - Object' and "Code"='charge' and "Status"='A'); slaobj_nbd bigint = (select "Id" from "LookUp" where "Type"='SLA - ThresholdType' and "Code"='NBD' and "Status"='A'); slaobj_imtype bigint = (select "Id" from "LookUp" where "Type"='ITProcessClassification - Workflow' and "Code"='IM' and "Status"='A'); server_url varchar = (select "Value" from "Parameter" where "Code"='Server-URL' and "Status"='A'); BEGIN RETURN QUERY select "Ticket number", to_char(subq."Creation date",'dd/mm/YYYY HH24:MM:ss'), subq."Subject", subq."Area", subq."Requester", subq."Contract", subq."Priority", subq."Subcategory", --(CASE WHEN subq.imstatus = 'New' and slatime_charge slaobj_nbd and slatime_chargeOpen ticket'::text as "Link" from (SELECT i."Id" AS im_id, i."Number" as "Ticket number", i."Id" as ident, i."CreationTimestamp" as "Creation date", a."Description" as "Area", e."Description" as "Requester", coalesce(sc."Description",dsc."Description") as "Contract", p."Description" as "Priority", subc."Description" as "Subcategory", i."ShortDescr" as "Subject", cal."Id" AS calendar, a."Area" as area, coalesce(sc."Id",dsc."Id") as contract, imstatus."Description" as imstatus, sla_resolution."Description" as sla_resolution, sla_charge."Description" sla_charge, (select limit_date from wf_sla_getlimit(sla_charge."Id",cal."Id",i."CreationTimestamp")) slalimit, (select totalseconds from wf_sla_getseconds(sla_charge."Id")) slatime_charge, (select totalseconds from wf_sla_getseconds(sla_resolution."Id")) slatime_resolution, sla_charge."ThresholdType" as sla_type_charge, sla_resolution."ThresholdType" as sla_type_resolution, ceil( i."TTHDAnalysis" + i."TTHDClassification" + i."TTHDClosure" + i."TTHDExecution" + i."TTHDStartCM" + i."TTHDSuspension" + i."TTSPAnalysis" + i."TTSPClassification" + i."TTSPClosure" + i."TTSPStartCM" + i."TTSPSuspension" + extract(epoch from(select work_time from utils_wc_get_worktime(i."BeginDate",now(),cal."Id")))) AS totaltime, coalesce(e."Email",u."Email") AS recipient1, m."Email" AS recipient2, r."Code" AS groupcode FROM "IncidentMgt" i JOIN "LookUp" fs ON fs."Id"=i."FlowStatus" AND (fs."Code" IN ('open.running','open.not_running.suspended')) AND fs."Status"='A' LEFT OUTER JOIN "ServiceContract" sc ON i."ServiceContract" = sc."Id" LEFT OUTER JOIN "ITProcArea" a ON a."Area"=i."Area" and a."Status"='A' LEFT OUTER JOIN "ITProcSubcategory" subc ON subc."Id"=i."Subcategory" and subc."Status"='A' LEFT OUTER JOIN "LookUp" p ON p."Id"=i."Priority" and p."Status"='A' LEFT OUTER JOIN "ServiceContract" dsc ON dsc."Area"=a."Id" and dsc."Status"='A' LEFT OUTER JOIN "CalendarDef" cal ON coalesce(sc."Calendar",dsc."Calendar") = cal."Id" LEFT OUTER JOIN "User" u ON u."Id"=i."CurrentUser" AND u."Status"='A' LEFT OUTER JOIN "Employee" e ON e."Code"=u."Username" AND e."Status"='A' LEFT OUTER JOIN "OU" ou ON ou."Id"=e."OU" AND ou."Status"='A' LEFT OUTER JOIN "Employee" m ON m."Id"=ou."Manager" AND m."Status"='A' LEFT OUTER JOIN "Role" r ON r."Id"=i."CurrentRole" AND r."Status"='A' LEFT OUTER JOIN "SLA" sla_charge ON sla_charge."Id" = ( select "IdObj1" from "Map_SLAServiceContract" m join "SLA" s1 on s1."Id"= "IdObj1" and s1."Object"=slaobj_takecharge and "IdObj2" = coalesce(sc."Id",dsc."Id") and m."Status"='A' and s1."Workflow"=slaobj_imtype and (i."Category"=s1."Category" or s1."Category" is null) and (i."Subcategory"=s1."Subcategory" or s1."Subcategory" is null) and (i."Priority"=s1."Priority" or s1."Priority" is null) order by s1."Priority" limit 1 ) LEFT OUTER JOIN "SLA" sla_resolution ON sla_resolution."Id" = ( select "IdObj1" from "Map_SLAServiceContract" m join "SLA" s1 on s1."Id"= "IdObj1" and s1."Object"=slaobj_resolution and "IdObj2" = coalesce(sc."Id",dsc."Id") and m."Status"='A' and s1."Workflow"=slaobj_imtype and (i."Category"=s1."Category" or s1."Category" is null) and (i."Subcategory"=s1."Subcategory" or s1."Subcategory" is null) and (i."Priority"=s1."Priority" or s1."Priority" is null) order by s1."Priority" limit 1 ) LEFT OUTER JOIN "LookUp" imstatus ON imstatus."Id" = i."ProcessStatus" WHERE i."Status"='A' AND (i."AllowDelay" is null or i."AllowDelay"=false) ) AS subq WHERE ( (case when imstatus = 'New' then ((case when sla_type_charge = slaobj_nbd then today coalesce(row."DeliveredQuantity",0) AND NOT coalesce(row."EarlyClosure",false) ORDER BY row."CMDBClass", row."Brand", row."Model", row."Code", row."Description"; END; $$; ?DROP FUNCTION public.wf_assetmgt_orderrows(orderid bigint, OUT "Brand" bigint, OUT "Model" character varying, OUT "Code" character varying, OUT "Description" character varying, OUT "CMDBClass" bigint, OUT "Quantity" integer, OUT "DeliveredQuantity" integer, OUT "DeliveryQuantity" integer, OUT "EarlyClosure" boolean); publicpostgresfalse 001FUNCTION wf_assetmgt_orderrows(orderid bigint, OUT "Brand" bigint, OUT "Model" character varying, OUT "Code" character varying, OUT "Description" character varying, OUT "CMDBClass" bigint, OUT "Quantity" integer, OUT "DeliveredQuantity" integer, OUT "DeliveryQuantity" integer, OUT "EarlyClosure" boolean)COMMENTYCOMMENT ON FUNCTION public.wf_assetmgt_orderrows(orderid bigint, OUT "Brand" bigint, OUT "Model" character varying, OUT "Code" character varying, OUT "Description" character varying, OUT "CMDBClass" bigint, OUT "Quantity" integer, OUT "DeliveredQuantity" integer, OUT "DeliveryQuantity" integer, OUT "EarlyClosure" boolean) IS 'TYPE: function'; publicpostgresfalse20271255233358?wf_changemgt_cm01_email_to_requester(bigint, character varying)FUNCTIONCREATE FUNCTION public.wf_changemgt_cm01_email_to_requester(processid bigint, number character varying, OUT toaddress character varying, OUT fromaddress character varying, OUT subject character varying, OUT body text) RETURNS record LANGUAGE plpgsql AS $$ DECLARE shortDescr varchar; extDescr varchar; requesterDescr varchar; channelDescr varchar; BEGIN SELECT "Email" INTO toaddress FROM "Employee" e JOIN "ChangeMgt" cm ON cm."Requester" = e."Id" AND cm."Id" = processid AND cm."Status" = 'A' WHERE e."Status" = 'A'; SELECT "Address" INTO fromaddress FROM "_EmailAccount" WHERE "Code" IN (select _cm3_system_config_get('org.cmdbuild.email.accountDefault')) AND "Status" = 'A'; SELECT 'Change management n.' || number || ' - Registered' INTO subject; SELECT cm."ShortDescr", cm."ExtDescr", r."Description", a."Description" INTO shortDescr, extDescr, requesterDescr, channelDescr FROM "ChangeMgt" AS cm LEFT JOIN "LookUp" a ON cm."Channel" = a."Id" LEFT JOIN "Employee" r ON cm."Requester" = r."Id" WHERE cm."Id" = processid; SELECT '

The request ' || number || ' has been registered.

Request data:

  • Number and summary: ' || number || '- ' || shortDescr || '
  • ' || coalesce('
  • Service request: ' || channelDescr || '
  • ', '') || coalesce('
  • Description: ' || extDescr || '
  • ', '') || coalesce('
  • Requester: ' || requesterDescr || '
  • ', '') || '

 

This message was generated automatically by CMDBuild - Ready2Use, please don''t change subject in case of reply.
For more information and to contribute to the fulfilment of this request, please login into the system.

' INTO body; END; $$; DROP FUNCTION public.wf_changemgt_cm01_email_to_requester(processid bigint, number character varying, OUT toaddress character varying, OUT fromaddress character varying, OUT subject character varying, OUT body text); publicpostgresfalse 00FUNCTION wf_changemgt_cm01_email_to_requester(processid bigint, number character varying, OUT toaddress character varying, OUT fromaddress character varying, OUT subject character varying, OUT body text)COMMENTCOMMENT ON FUNCTION public.wf_changemgt_cm01_email_to_requester(processid bigint, number character varying, OUT toaddress character varying, OUT fromaddress character varying, OUT subject character varying, OUT body text) IS 'TYPE: function'; publicpostgresfalse20281255233359/wf_changemgt_load_workorders(character varying)FUNCTION CREATE FUNCTION public.wf_changemgt_load_workorders(cmnumber character varying, OUT "Code" character varying, OUT "Description" character varying, OUT "ActivityName" character varying, OUT "ActivityDescription" character varying, OUT "ExpectedTime" numeric, OUT "ExecutorRole" bigint, OUT "State" bigint, OUT "PrecWO" integer) RETURNS SETOF record LANGUAGE plpgsql AS $$ BEGIN RETURN QUERY SELECT wo."Code", wo."Description", wo."ActivityName", wo."ActivityDescription", wo."ExpectedTime", wo."ExecutorRole", wo."State", (select "IdObj2" from "Map_ITProcClassificCMWOTmpl" as precwo where "Order"::varchar = map."PrecWO" and precwo."Status" = 'A' and precwo."IdObj1" = classific."Id") as "PrecWO" FROM "ChangeMgtWOTmpl" wo JOIN "Map_ITProcClassificCMWOTmpl" map ON wo."Id" = map."IdObj2" AND map."Status" = 'A' JOIN "ITProcClassification" classific ON classific."Id" = map."IdObj1" AND map."Status" = 'A' JOIN "ChangeMgt" cm ON cm."Category" = classific."Category" AND cm."Subcategory" = classific."Subcategory" AND cm."Number" = cmnumber AND cm."Status" = 'A' JOIN "LookUp" state ON wo."State" = state."Id" AND state."Code" = 'Active' WHERE wo."Status" = 'A' ORDER BY map."Order"; END; $$; FDROP FUNCTION public.wf_changemgt_load_workorders(cmnumber character varying, OUT "Code" character varying, OUT "Description" character varying, OUT "ActivityName" character varying, OUT "ActivityDescription" character varying, OUT "ExpectedTime" numeric, OUT "ExecutorRole" bigint, OUT "State" bigint, OUT "PrecWO" integer); publicpostgresfalse 008FUNCTION wf_changemgt_load_workorders(cmnumber character varying, OUT "Code" character varying, OUT "Description" character varying, OUT "ActivityName" character varying, OUT "ActivityDescription" character varying, OUT "ExpectedTime" numeric, OUT "ExecutorRole" bigint, OUT "State" bigint, OUT "PrecWO" integer)COMMENT`COMMENT ON FUNCTION public.wf_changemgt_load_workorders(cmnumber character varying, OUT "Code" character varying, OUT "Description" character varying, OUT "ActivityName" character varying, OUT "ActivityDescription" character varying, OUT "ExpectedTime" numeric, OUT "ExecutorRole" bigint, OUT "State" bigint, OUT "PrecWO" integer) IS 'TYPE: function'; publicpostgresfalse20291255233360wf_changemgt_load_wos(bigint)FUNCTIONgCREATE FUNCTION public.wf_changemgt_load_wos(procid bigint, OUT "Number" integer, OUT "PrecWO" character varying, OUT "ActivityName" character varying, OUT "ActivityDescription" character varying, OUT "ExecutorRole" bigint, OUT "ExpectedTime" numeric, OUT "FormName" character varying, OUT "Condition" text, OUT "PreScript" text, OUT "PostScript" text) RETURNS SETOF record LANGUAGE plpgsql AS $$ DECLARE cm_workflow_type bigint := (select "Id" from "LookUp" where "Type" = 'ITProcessClassification - Workflow' and "Code" = 'CM' and "Status" = 'A'); active_tmpl bigint := (select "Id" from "LookUp" where "Type" = 'WorkorderTmpl - State' and "Code" = 'Active' and "Status" = 'A'); BEGIN RETURN QUERY SELECT map."Order", map."PrecWO", tmpl."ActivityName", tmpl."ActivityDescription", tmpl."ExecutorRole", tmpl."ExpectedTime", tmpl."FormName", tmpl."Condition", tmpl."PreScript", tmpl."PostScript" FROM "ChangeMgtWOTmpl" tmpl JOIN "Map_ITProcClassificCMWOTmpl" map ON tmpl."Id" = map."IdObj2" AND map."Status" = 'A' JOIN "ITProcClassification" classific ON classific."Id" = map."IdObj1" AND classific."Status" = 'A' JOIN "ChangeMgt" cm ON cm."Subcategory" = classific."Subcategory" AND classific."Workflow" = cm_workflow_type AND cm."Id" = procid WHERE tmpl."Status" = 'A' AND tmpl."State" = active_tmpl ORDER BY map."Order"; END; $$; `DROP FUNCTION public.wf_changemgt_load_wos(procid bigint, OUT "Number" integer, OUT "PrecWO" character varying, OUT "ActivityName" character varying, OUT "ActivityDescription" character varying, OUT "ExecutorRole" bigint, OUT "ExpectedTime" numeric, OUT "FormName" character varying, OUT "Condition" text, OUT "PreScript" text, OUT "PostScript" text); publicpostgresfalse00RFUNCTION wf_changemgt_load_wos(procid bigint, OUT "Number" integer, OUT "PrecWO" character varying, OUT "ActivityName" character varying, OUT "ActivityDescription" character varying, OUT "ExecutorRole" bigint, OUT "ExpectedTime" numeric, OUT "FormName" character varying, OUT "Condition" text, OUT "PreScript" text, OUT "PostScript" text)COMMENTzCOMMENT ON FUNCTION public.wf_changemgt_load_wos(procid bigint, OUT "Number" integer, OUT "PrecWO" character varying, OUT "ActivityName" character varying, OUT "ActivityDescription" character varying, OUT "ExecutorRole" bigint, OUT "ExpectedTime" numeric, OUT "FormName" character varying, OUT "Condition" text, OUT "PreScript" text, OUT "PostScript" text) IS 'TYPE: function'; publicpostgresfalse20301255233361wf_changemgt_nextrole(character varying, character varying, character varying, character varying, character varying, character varying)FUNCTIONCREATE FUNCTION public.wf_changemgt_nextrole(procnum character varying, category character varying, subcategory character varying, action character varying, wftype character varying, currentuser character varying, OUT roleid bigint) RETURNS SETOF bigint LANGUAGE plpgsql AS $$ DECLARE categoryId bigint; subcategoryId bigint; actionId bigint; currentUserId bigint; assignedRoleId bigint; approverRoleId bigint; mustbecurrent boolean; isValid boolean; isAdministrator character varying; toApprove boolean; BEGIN --raise notice 'INPUT: procnum %, category: %, subcategory: %, action: %, currentuser: %', procnum, category, subcategory, action, currentuser; select into assignedRoleId wf_getassignedrole(procnum); if (category!='null' and category!='') then select into categoryId c."Id" from "ITProcCategory" c where (c."Id"::varchar=category or c."Description"=category) and c."Status"='A'; end if; if (subcategory!='null' and subcategory!='') then select into subcategoryId sc."Id" from "ITProcSubcategory" sc where (sc."Id"::varchar=subcategory or sc."Description"=subcategory) and sc."Status"='A'; end if; if(action = 'open') then -- show all specialists related to current classification return query select c."SPRole" from "ITProcClassification" c join "LookUp" l1 on c."Workflow"=l1."Id" and l1."Status"='A' and l1."Code"=wftype join "ITProcCategory" p on p."Id"=c."Category" and p."Status"='A' join "ITProcSubcategory" sp on sp."Id"=c."Subcategory" and sp."Status"='A' where c."Status"='A' and c."Active" and c."Category"=categoryId and c."Subcategory"=subcategoryId; else if (action!='null' and action!='') then select into actionId, mustbecurrent a."Id" , case when ( (a."Code" in ('SPAnalysis', 'Closure') and a."Type"='ChangeMgt - SPClassification Action') ) then true else false end from "LookUp" a where (a."Id"::varchar=action or a."Description"=action) and a."Status"='A'; end if; end if; if (currentuser!='null' and currentuser!='') then select into currentUserId u."Id" from "User" u where (u."Id"::varchar=currentuser or u."Description"=currentuser) and u."Status"='A'; end if; --raise notice 'categoryId:%, subcategoryId: %, actionId: %, mustbecurrent: %, assignedRoleId: %', categoryId, subcategoryId, actionId, mustbecurrent,assignedRoleId; if(mustbecurrent) then select into isAdministrator "Type" from "Role" where "Id"=assignedRoleId; -- has the currentRole a valid classification for the selected category and subcategory? select count(*)>0 into isValid from "ITProcClassification" c join "LookUp" l1 on c."Workflow"=l1."Id" and l1."Status"='A' and l1."Code"=wftype join "ITProcCategory" p on p."Id"=c."Category" and p."Status"='A' join "ITProcSubcategory" sp on sp."Id"=c."Subcategory" and sp."Status"='A' where c."Status"='A' and c."Active" and c."SPRole"=assignedRoleId and actionId in (select a."Id" from "LookUp" a where a."Type"='ChangeMgt - SPClassification Action') and c."Category"=categoryId and c."Subcategory"=subcategoryId; select c."ApproverRole" into approverRoleId from "ITProcClassification" c join "LookUp" l1 on c."Workflow"=l1."Id" and l1."Status"='A' and l1."Code"=wftype join "ITProcCategory" p on p."Id"=c."Category" and p."Status"='A' join "ITProcSubcategory" sp on sp."Id"=c."Subcategory" and sp."Status"='A' where c."Status"='A' and c."Active" and c."Category"=categoryId and c."Subcategory"=subcategoryId and actionId in (select a."Id" from "LookUp" a where a."Type"='ChangeMgt - SPClassification Action' and "Code" = 'SPAnalysis'); toApprove = coalesce(approverRoleId,-1) > 0; if(isValid or isAdministrator = 'admin') then if(toApprove) then return query select approverRoleId; else return query select assignedRoleId; end if; else return query select 0::bigint; end if; else return query select c."SPRole" from "ITProcClassification" c join "LookUp" l1 on c."Workflow"=l1."Id" and l1."Status"='A' and l1."Code"=wftype join "ITProcCategory" p on p."Id"=c."Category" and p."Status"='A' join "ITProcSubcategory" sp on sp."Id"=c."Subcategory" and sp."Status"='A' left join "LookUp" asp on asp."Type"='ChangeMgt - SPClassification Action' and asp."Id"=actionId where c."Status"='A' and asp."Code" in ('EscalationSP') and c."SPRole" <> assignedRoleId and c."Category"=categoryId and c."Subcategory"=subcategoryId and c."Active"; end if; --raise notice ' roleid:%',roleid; END; $$; DROP FUNCTION public.wf_changemgt_nextrole(procnum character varying, category character varying, subcategory character varying, action character varying, wftype character varying, currentuser character varying, OUT roleid bigint); publicpostgresfalse1255233362wf_changemgt_number()FUNCTIONCREATE FUNCTION public.wf_changemgt_number(OUT number character varying) RETURNS character varying LANGUAGE plpgsql AS $$ BEGIN number = lpad(nextval('changemgt_seq')::text,6,'0'); END; $$; HDROP FUNCTION public.wf_changemgt_number(OUT number character varying); publicpostgresfalse00:FUNCTION wf_changemgt_number(OUT number character varying)COMMENTbCOMMENT ON FUNCTION public.wf_changemgt_number(OUT number character varying) IS 'TYPE: function'; publicpostgresfalse20321255233363dwf_changemgt_prepare_email(bigint, character varying, character varying, integer, character varying)FUNCTIONCREATE FUNCTION public.wf_changemgt_prepare_email(process_id bigint, proc_number character varying, template_name character varying, workorder integer, email_status character varying, OUT emailid bigint) RETURNS bigint LANGUAGE plpgsql AS $$ DECLARE from_address VARCHAR; to_addresses VARCHAR; cc_addresses VARCHAR; bcc_addresses VARCHAR; subject VARCHAR; body VARCHAR; language_config VARCHAR; proc_shortdescr VARCHAR; proc_extdescr VARCHAR; chn_descr VARCHAR; requester_descr VARCHAR; requester_email VARCHAR; url_page_server VARCHAR; url_page_portal VARCHAR; wo_name VARCHAR; wo_descr VARCHAR; wo_time VARCHAR; wo_recipient VARCHAR; BEGIN IF (SELECT "Template" FROM "_Templates" WHERE "Name" = 'Email-Lang') IN ('en', 'it') THEN language_config = (SELECT "Template" FROM "_Templates" WHERE "Name" = 'Email-Lang'); ELSIF COALESCE(_cm3_system_config_get('org.cmdbuild.core.language'), '') IN ('en', 'it') THEN language_config = _cm3_system_config_get('org.cmdbuild.core.language'); ELSE language_config = 'en'; END IF; --Retrieve email account and email template fields SELECT COALESCE(et."From", ''), COALESCE(et."To", ''), COALESCE(et."CC", ''), COALESCE(et."BCC", ''), COALESCE(et."Subject", ''), COALESCE(et."Body", '') INTO from_address, to_addresses, cc_addresses, bcc_addresses, subject, body FROM "_EmailTemplate" et LEFT JOIN "_EmailAccount" ea ON ea."Id" = et."Account" AND ea."Status" = 'A' WHERE et."Code" = template_name AND et."Status" = 'A'; -- retrieve cm data SELECT proc."ShortDescr", proc."ExtDescr", chn."Description", requester."Description", requester."Email" INTO proc_shortdescr, proc_extdescr, chn_descr, requester_descr, requester_email FROM "ChangeMgt" proc LEFT JOIN "Employee" requester ON proc."Requester" = requester."Id" LEFT JOIN "LookUp" chn ON proc."Channel" = chn."Id" WHERE proc."Id" = process_id; url_page_server = (select "Value" FROM "Parameter" WHERE "Code" = 'Server-URL' and "Status"='A') || '#processes/ChangeMgt/instances/' || process_id; url_page_portal = (select "Value" FROM "Parameter" WHERE "Code" = 'Portal-URL' and "Status"='A') || '#page=my-requests&selected-item=' || process_id || '/'; -- mapping of fields into the template SELECT INTO to_addresses REPLACE(to_addresses, '{server:Requester.Email}', COALESCE(requester_email, '')); SELECT INTO subject REPLACE(subject, '{server:Number}', COALESCE(proc_number, '')); SELECT INTO body REPLACE(body, '{server:Number}', COALESCE(proc_number, '')); SELECT INTO body REPLACE(body, '{server:ShortDescr}', COALESCE(proc_shortdescr, '')); SELECT INTO body REPLACE(body, '{server:Channel.Description}', COALESCE(chn_descr, '')); SELECT INTO body REPLACE(body, '{server:Requester.Description}', COALESCE(requester_descr, '')); SELECT INTO body REPLACE(body, '{server:ExtDescr}', COALESCE(proc_extdescr, '')); SELECT INTO body REPLACE(body, '{server:Parameter.Server-Url}', COALESCE(url_page_server, '')); SELECT INTO body REPLACE(body, '{server:Parameter.Portal-Url}', COALESCE(url_page_portal, '')); IF workorder is not null THEN EXECUTE format('select "ActivityName'||workorder||'","ActivityDescription'||workorder||'","ExpectedTime'||workorder||'"::varchar,g."Email" from "ReqFulfil" rf JOIN "Role" g ON g."Id"=rf."WORole'||workorder||'" where rf."Id"='||process_id) INTO wo_name,wo_descr,wo_time,wo_recipient ; SELECT INTO body REPLACE(body, '{server:ActivityName}', COALESCE(wo_name, '')); SELECT INTO body REPLACE(body, '{server:ActivityDescription}', COALESCE(wo_descr, '')); SELECT INTO body REPLACE(body, '{server:ExpectedTime}', COALESCE(wo_time, '')); SELECT INTO to_addresses REPLACE(to_addresses, '{server:ToAddress}', COALESCE(wo_recipient, '')); END IF; -- create an outgoing e-mail linked to the process --Generate email IF EXISTS (SELECT "Code" FROM "_EmailTemplate" WHERE "Code" = template_name AND "Status" = 'A') THEN INSERT INTO "Email" ("EmailStatus","FromAddress","ToAddresses","CcAddresses", "BccAddresses", "Subject","Content","Card","Delay","KeepSynchronization","PromptSynchronization") SELECT coalesce(nullif(email_status, ''), 'outgoing'), from_address, to_addresses, cc_addresses, bcc_addresses, subject, body, process_id, 0, false, false RETURNING "Id" INTO emailid; END IF; END; $$; DROP FUNCTION public.wf_changemgt_prepare_email(process_id bigint, proc_number character varying, template_name character varying, workorder integer, email_status character varying, OUT emailid bigint); publicpostgresfalse00FUNCTION wf_changemgt_prepare_email(process_id bigint, proc_number character varying, template_name character varying, workorder integer, email_status character varying, OUT emailid bigint)COMMENTCOMMENT ON FUNCTION public.wf_changemgt_prepare_email(process_id bigint, proc_number character varying, template_name character varying, workorder integer, email_status character varying, OUT emailid bigint) IS 'TYPE: function'; publicpostgresfalse20331255233364?wf_changemgt_suggoperator(character varying, character varying)FUNCTIONCREATE FUNCTION public.wf_changemgt_suggoperator(nextrole character varying, currentrole character varying, OUT userid bigint) RETURNS SETOF bigint LANGUAGE plpgsql AS $$ DECLARE nextroleId bigint; currentRoleId bigint; mustbecurrent boolean; BEGIN --raise notice 'INPUT: nextrole: %, currentrole: %' , nextrole, currentrole; if (nextrole!='null' and nextrole!='') then mustbecurrent = false; select into nextroleId r."Id" from "Role" r where (r."Id"::varchar=nextrole or r."Description"=nextrole) and r."Status"='A'; else mustbecurrent = true; end if; if (currentrole!='null' and currentrole!='') then select into currentRoleId r."Id" from "Role" r where (r."Id"::varchar=currentrole or r."Description"=currentrole) and r."Status"='A'; end if; --raise notice ' nextroleId:%, currentRoleId: %, mustbecurrent: %', nextroleId, currentRoleId, mustbecurrent; if(mustbecurrent) then return query select u."Id" from "User" u join "Map_UserRole" map on map."IdObj1" = u."Id" and map."Status" = 'A' and map."IdObj2" = currentRoleId where u."Status" = 'A' and not coalesce(u."Service", false); else return query select u."Id" from "User" u join "Map_UserRole" map on map."IdObj1" = u."Id" and map."Status" = 'A' and map."IdObj2" = nextroleId where u."Status" = 'A' and not coalesce(u."Service", false); end if; END; $$; ~DROP FUNCTION public.wf_changemgt_suggoperator(nextrole character varying, currentrole character varying, OUT userid bigint); publicpostgresfalse00pFUNCTION wf_changemgt_suggoperator(nextrole character varying, currentrole character varying, OUT userid bigint)COMMENTCOMMENT ON FUNCTION public.wf_changemgt_suggoperator(nextrole character varying, currentrole character varying, OUT userid bigint) IS 'TYPE: function'; publicpostgresfalse20341255233365 wf_cmworkord_checkiflast(bigint)FUNCTIONCREATE FUNCTION public.wf_cmworkord_checkiflast(procid bigint, OUT islast boolean) RETURNS boolean LANGUAGE plpgsql AS $$ BEGIN IF EXISTS ( SELECT s."Id" FROM "CMWorkOrd" s JOIN "CMWorkOrd" myself ON myself."Parent" = s."Parent" AND myself."Id" = procid WHERE s."Status" = 'A' AND s."Id"<> procid AND s."FlowStatus" IN (SELECT "Id" FROM "LookUp" WHERE "Code" ILIKE 'open.%' AND "Status" = 'A' AND "Type" = 'FlowStatus') ) THEN isLast = false; ELSE isLast = true; END IF; END; $$; RDROP FUNCTION public.wf_cmworkord_checkiflast(procid bigint, OUT islast boolean); publicpostgresfalse00DFUNCTION wf_cmworkord_checkiflast(procid bigint, OUT islast boolean)COMMENTlCOMMENT ON FUNCTION public.wf_cmworkord_checkiflast(procid bigint, OUT islast boolean) IS 'TYPE: function'; publicpostgresfalse20351255233366wf_cmworkord_isactive(bigint)FUNCTIONCREATE FUNCTION public.wf_cmworkord_isactive(procid bigint, OUT isactive boolean) RETURNS boolean LANGUAGE plpgsql AS $$ DECLARE flowstatus bigint; processStatus bigint; running bigint := (SELECT "Id" FROM "LookUp" WHERE "Code" ILIKE 'open%running' AND "Type" = 'FlowStatus' AND "Status" = 'A'); closed bigint := (SELECT "Id" FROM "LookUp" WHERE "Code" ILIKE 'closed' AND "Type" = 'ITProc - ProcessStatus' AND "Status" = 'A'); BEGIN SELECT "FlowStatus","ProcessStatus" INTO flowstatus, processStatus FROM "CMWorkOrd" WHERE "Id" = procid; isactive = (flowstatus = running AND coalesce(processStatus,0) <> closed); END; $$; QDROP FUNCTION public.wf_cmworkord_isactive(procid bigint, OUT isactive boolean); publicpostgresfalse00CFUNCTION wf_cmworkord_isactive(procid bigint, OUT isactive boolean)COMMENTkCOMMENT ON FUNCTION public.wf_cmworkord_isactive(procid bigint, OUT isactive boolean) IS 'TYPE: function'; publicpostgresfalse20361255233367 wf_cmworkord_parent_data(bigint)FUNCTIONCREATE FUNCTION public.wf_cmworkord_parent_data(parentid bigint, OUT "Number" character varying, OUT "CreationTimestamp" text, OUT "ShortDescr" text, OUT "ExtDescr" text, OUT "Register" text) RETURNS SETOF record LANGUAGE plpgsql AS $$ BEGIN RETURN QUERY SELECT cm."Number", to_char(cm."CreationTimestamp", 'DD/MM/YYYY HH:mm:SS'), cm."ShortDescr", cm."ExtDescr", cm."Register" FROM "ChangeMgt" cm WHERE cm."Id" = parentid; END; $$; DROP FUNCTION public.wf_cmworkord_parent_data(parentid bigint, OUT "Number" character varying, OUT "CreationTimestamp" text, OUT "ShortDescr" text, OUT "ExtDescr" text, OUT "Register" text); publicpostgresfalse00FUNCTION wf_cmworkord_parent_data(parentid bigint, OUT "Number" character varying, OUT "CreationTimestamp" text, OUT "ShortDescr" text, OUT "ExtDescr" text, OUT "Register" text)COMMENTCOMMENT ON FUNCTION public.wf_cmworkord_parent_data(parentid bigint, OUT "Number" character varying, OUT "CreationTimestamp" text, OUT "ShortDescr" text, OUT "ExtDescr" text, OUT "Register" text) IS 'TYPE: FUNCTION'; publicpostgresfalse20371255233368Xwf_cmworkord_store_form(bigint, character varying, character varying, character varying)FUNCTIONCREATE FUNCTION public.wf_cmworkord_store_form(procid bigint, username character varying, formname character varying, data character varying, OUT formvalues text) RETURNS text LANGUAGE plpgsql AS $$ DECLARE token character varying; keyvalue character varying[]; key character varying; value character varying; rf_formvalue_id integer; parameter_type character varying; metadata character varying; name character varying; classname character varying; query character varying; BEGIN formvalues = '
    '; FOREACH token IN ARRAY regexp_split_to_array(data, ',') LOOP keyvalue = regexp_split_to_array(token, '='); key = keyvalue[1]; value = keyvalue[2]; -- RAISE NOTICE 'token: %', token; -- RAISE NOTICE 'key: %', key; -- RAISE NOTICE 'value: %', value; SELECT "Id" INTO rf_formvalue_id FROM "CMWorkOrdFormValue" WHERE "Process"=procid AND "FormParameter" = key; SELECT "Type", "Metadata", "Description" INTO parameter_type, metadata, name FROM "CMWOFormField" WHERE FormName = formname AND "Name" = key AND "Status" = 'A'; -- RAISE NOTICE 'formname: % - key: % - parameter_type: % - metadata: %',formname,key,parameter_type, metadata; IF parameter_type ILIKE '%reference%' THEN classname = regexp_replace(unnest(regexp_matches(metadata, '(targetClass#:# [^\|]*)')),'targetClass#:# ', ''); -- RAISE NOTICE 'fech description of card % from class %',value,classname; query = 'SELECT "Description" FROM "' || classname || '" WHERE "Id" = ' ||value::INTEGER || 'AND "Status" = ''A'''; EXECUTE query INTO value; ELSEIF parameter_type ILIKE '%lookup%' THEN SELECT "Description" INTO value FROM "LookUp" WHERE "Id" = value::INTEGER AND "Status" = 'A'; END IF; -- RAISE NOTICE 'value: %',value; formvalues = concat_ws('', formvalues, '
  • ' || name || ': ' || value); IF rf_formvalue_id IS NULL THEN INSERT INTO "CMWorkOrdFormValue"("User", "Process", "FormParameter", "Value") SELECT username, procid, key, value; ELSE UPDATE "CMWorkOrdFormValue" SET "Value"=value WHERE "Id"=rf_formvalue_id; END IF; END LOOP; IF(trim(formvalues) = '
      ') THEN formvalues = null; END IF; formvalues = formvalues || '
    '; END; $$; DROP FUNCTION public.wf_cmworkord_store_form(procid bigint, username character varying, formname character varying, data character varying, OUT formvalues text); publicpostgresfalse00FUNCTION wf_cmworkord_store_form(procid bigint, username character varying, formname character varying, data character varying, OUT formvalues text)COMMENTCOMMENT ON FUNCTION public.wf_cmworkord_store_form(procid bigint, username character varying, formname character varying, data character varying, OUT formvalues text) IS 'TYPE: function'; publicpostgresfalse20161255233369&wf_disconnect_networkinterface(bigint)FUNCTIONCREATE FUNCTION public.wf_disconnect_networkinterface(origin_hw_id bigint, OUT success boolean) RETURNS boolean LANGUAGE plpgsql AS $_$ BEGIN UPDATE "Map_DstPortNetworkInterface" SET "Status"='N' WHERE "Map_DstPortNetworkInterface"."Id" in ( select "Map_DstPortNetworkInterface"."Id" from "Hardware" left outer join "NetworkInterface" on "Hardware"."Id"="NetworkInterface"."Hardware" left outer join "Map_DstPortNetworkInterface" on "NetworkInterface"."Id"="Map_DstPortNetworkInterface"."IdObj1" or "NetworkInterface"."Id"="Map_DstPortNetworkInterface"."IdObj2" where "Hardware"."Status"='A' and "NetworkInterface"."Status"='A' and "Map_DstPortNetworkInterface"."Status"='A' and "Hardware"."Id" = $1 ); success = true; END $_$; _DROP FUNCTION public.wf_disconnect_networkinterface(origin_hw_id bigint, OUT success boolean); publicpostgresfalse00QFUNCTION wf_disconnect_networkinterface(origin_hw_id bigint, OUT success boolean)COMMENTyCOMMENT ON FUNCTION public.wf_disconnect_networkinterface(origin_hw_id bigint, OUT success boolean) IS 'TYPE: function'; publicpostgresfalse20241255233370wf_dynchild_isactive(bigint)FUNCTIONCREATE FUNCTION public.wf_dynchild_isactive(procid bigint, OUT isactive boolean) RETURNS boolean LANGUAGE plpgsql AS $$ DECLARE flowstatus bigint; processStatus bigint; running bigint := (SELECT "Id" FROM "LookUp" WHERE "Code" ILIKE 'open%running' AND "Type" = 'FlowStatus' AND "Status" = 'A'); closed bigint := (SELECT "Id" FROM "LookUp" WHERE "Code" ILIKE 'closed' AND "Type" = 'ITProc - ProcessStatus' AND "Status" = 'A'); BEGIN SELECT "FlowStatus","ProcessStatus" INTO flowstatus, processStatus FROM "DynChild" WHERE "Id" = procid; isactive = (flowstatus = running AND coalesce(processStatus,0) <> closed); END; $$; PDROP FUNCTION public.wf_dynchild_isactive(procid bigint, OUT isactive boolean); publicpostgresfalse00BFUNCTION wf_dynchild_isactive(procid bigint, OUT isactive boolean)COMMENTjCOMMENT ON FUNCTION public.wf_dynchild_isactive(procid bigint, OUT isactive boolean) IS 'TYPE: function'; publicpostgresfalse20381255233371|wf_emailmgt_linkemail(character varying, character varying, character varying, character varying, character varying, bigint)FUNCTIONCREATE FUNCTION public.wf_emailmgt_linkemail(fromaddress character varying, toaddresses character varying, ccaddresses character varying, subject character varying, body character varying, cardid bigint, OUT result boolean) RETURNS boolean LANGUAGE plpgsql AS $$ BEGIN -- create an outgoing e-mail linked to the process insert into "Email" ("IdClass","Status","User","EmailStatus","FromAddress","ToAddresses","CcAddresses","Subject","Content","Account","Card","Delay","KeepSynchronization","PromptSynchronization") select '"Email"'::regclass,'A','system','received',fromAddress,toAddresses,ccAddresses,subject,body,'default',cardid,0,false,false; result = TRUE; END; $$; DROP FUNCTION public.wf_emailmgt_linkemail(fromaddress character varying, toaddresses character varying, ccaddresses character varying, subject character varying, body character varying, cardid bigint, OUT result boolean); publicpostgresfalse00FUNCTION wf_emailmgt_linkemail(fromaddress character varying, toaddresses character varying, ccaddresses character varying, subject character varying, body character varying, cardid bigint, OUT result boolean)COMMENTCOMMENT ON FUNCTION public.wf_emailmgt_linkemail(fromaddress character varying, toaddresses character varying, ccaddresses character varying, subject character varying, body character varying, cardid bigint, OUT result boolean) IS 'TYPE: function'; publicpostgresfalse203912552333720wf_emailmgt_sendnotify(bigint, text, text, text)FUNCTIONCREATE FUNCTION public.wf_emailmgt_sendnotify(cardid bigint, origfromaddress text, origsubject text, origbody text, OUT result boolean) RETURNS boolean LANGUAGE plpgsql AS $$ DECLARE n text; fromaddress text; toAddresses text; ccaddresses text; subject text; body text; BEGIN select i."Number", r."Email" into n, toAddresses from "IncidentMgt" i left join "Role" r on r."Id"=i."CurrentRole" where i."Id"=cardid; select "Subject", "Body", "From", "CC" into subject, body, fromaddress, ccaddresses from "_EmailTemplate" where "Status"='A' and "Code" = 'IM-EmailReceivedNotification'; subject = replace(subject,'{card:Number}',n); body = replace(body,'{email:from}',origFromAddress); body = replace(body,'{email:subject}',origSubject); body = replace(body,'{email:content}',origBody); -- create an outgoing e-mail linked to the process insert into "Email" ("IdClass","Status","User","EmailStatus","FromAddress","ToAddresses","CcAddresses","Subject","Content","Account","Delay","KeepSynchronization","PromptSynchronization") select '"Email"'::regclass,'A','system','outgoing',fromAddress,toAddresses,ccAddresses,subject,body,'default',0,false,false; result = TRUE; END; $$; DROP FUNCTION public.wf_emailmgt_sendnotify(cardid bigint, origfromaddress text, origsubject text, origbody text, OUT result boolean); publicpostgresfalse00yFUNCTION wf_emailmgt_sendnotify(cardid bigint, origfromaddress text, origsubject text, origbody text, OUT result boolean)COMMENTCOMMENT ON FUNCTION public.wf_emailmgt_sendnotify(cardid bigint, origfromaddress text, origsubject text, origbody text, OUT result boolean) IS 'TYPE: function'; publicpostgresfalse20401255233373#wf_get_ids_networkinterface(bigint)FUNCTIONyCREATE FUNCTION public.wf_get_ids_networkinterface(idinterface bigint, OUT ids character varying) RETURNS character varying LANGUAGE sql STRICT AS $_$ select concat("IdObj2") from ( select distinct "Map_DstPortNetworkInterface"."IdObj2" from "Map_DstPortNetworkInterface" where "Map_DstPortNetworkInterface"."IdObj1"= $1 and "Map_DstPortNetworkInterface"."Status"='A') as r2 union select concat("IdObj1") from ( select distinct "Map_DstPortNetworkInterface"."IdObj1" from "Map_DstPortNetworkInterface" where "Map_DstPortNetworkInterface"."IdObj2"= $1 and "Map_DstPortNetworkInterface"."Status"='A') as r1 $_$; aDROP FUNCTION public.wf_get_ids_networkinterface(idinterface bigint, OUT ids character varying); publicpostgresfalse00SFUNCTION wf_get_ids_networkinterface(idinterface bigint, OUT ids character varying)COMMENT{COMMENT ON FUNCTION public.wf_get_ids_networkinterface(idinterface bigint, OUT ids character varying) IS 'TYPE: function'; publicpostgresfalse20411255233374%wf_getassignedrole(character varying)FUNCTIONCREATE FUNCTION public.wf_getassignedrole(procnum character varying, OUT gruppo bigint) RETURNS bigint LANGUAGE sql AS $_$ select max("Id") -- the function must return just ONE row from( select r."Id" from "ITProc" p join "Role" r on r."Code"=p."NextExecutor"[1] and r."Status"='A' where p."Number"=$1 and p."Status"='A' union select 0::bigint --the union avoids void returns ) q; $_$; WDROP FUNCTION public.wf_getassignedrole(procnum character varying, OUT gruppo bigint); publicpostgresfalse00IFUNCTION wf_getassignedrole(procnum character varying, OUT gruppo bigint)COMMENTqCOMMENT ON FUNCTION public.wf_getassignedrole(procnum character varying, OUT gruppo bigint) IS 'TYPE: function'; publicpostgresfalse20421255233375-wf_incidentmgt_checkdelays(character varying)FUNCTIONCREATE FUNCTION public.wf_incidentmgt_checkdelays(processtype character varying, OUT processeslist character varying, OUT delayslist character varying, OUT typeslist character varying, OUT recipientslist character varying, OUT grouplist character varying) RETURNS record LANGUAGE plpgsql AS $$ DECLARE singleticket record; singleuser record; diff integer; today timestamp with time zone; groupemaillist character varying; BEGIN diff=0; processeslist = ''; delayslist=''; typeslist=''; recipientslist=''; grouplist=''; today = now(); --raise notice '%', today; FOR singleticket IN SELECT subq.ident AS ident, (CASE WHEN totaltime>threshold2 THEN totaltime-threshold2 else totaltime-threshold1 END) AS totaltime, (CASE WHEN totaltime>threshold2 THEN 'Threshold2' else 'Threshold1' END) AS type, (CASE WHEN totaltime>threshold2 THEN subq.recipient2 else subq.recipient1 END) AS recipient, subq.groupcode AS groupcode FROM ( SELECT i."Id" AS ident, ceil( i."TTHDAnalysis" + i."TTHDClassification" + i."TTHDClosure" + i."TTHDExecution" + i."TTHDStartCM" + i."TTHDSuspension" + i."TTSPAnalysis" + i."TTSPClassification" + i."TTSPClosure" + i."TTSPStartCM" + i."TTSPSuspension" + (select activitytime from wf_incidentmgt_getactivitytime(i."BeginDate",today))) AS totaltime, c."Threshold1Delay" AS threshold1, c."Threshold2Delay" AS threshold2, e."Email" AS recipient1, m."Email" AS recipient2, r."Code" AS groupcode FROM "IncidentMgt" i JOIN "LookUp" fs ON fs."Id"=i."FlowStatus" AND (fs."Code" IN ('open.running','open.not_running.suspended')) AND fs."Status"='A' JOIN "ITProcClassification" c ON i."Category" = c."Category" AND i."Subcategory" = c."Subcategory" AND c."Status"='A' JOIN "LookUp" l ON l."Id"=c."Workflow" AND l."Status"='A' JOIN "LookUp" l1 ON l1."Id"=c."Notify1Delay" AND l1."Status"='A' JOIN "LookUp" l2 ON l2."Id"=c."Notify2Delay" AND l2."Status"='A' LEFT OUTER JOIN "User" u ON u."Id"=i."CurrentUser" AND u."Status"='A' LEFT OUTER JOIN "Employee" e ON e."Code"=u."Username" AND e."Status"='A' LEFT OUTER JOIN "OU" ou ON ou."Id"=e."OU" AND ou."Status"='A' LEFT OUTER JOIN "Employee" m ON m."Id"=ou."Manager" AND m."Status"='A' LEFT OUTER JOIN "Role" r ON r."Id"=i."CurrentRole" AND r."Status"='A' WHERE i."Status"='A' AND l."Code" = processtype AND (i."AllowDelay" is null or i."AllowDelay"=false) ) AS subq WHERE ( subq.totaltime> subq.threshold1 or subq.totaltime> subq.threshold2 ) LOOP IF processeslist<>'' THEN processeslist = processeslist || ',' || singleticket.ident; else processeslist = processeslist || singleticket.ident; END IF; IF delayslist<>'' THEN delayslist = delayslist || ',' || singleticket.totaltime; else delayslist = delayslist || singleticket.totaltime; END IF; IF typeslist<>'' THEN typeslist = typeslist || ',' || singleticket.type; else typeslist = typeslist || singleticket.type; END IF; IF recipientslist<>'' THEN recipientslist = recipientslist || ',' || singleticket.recipient; else recipientslist = recipientslist || singleticket.recipient; END IF; groupemaillist = ''; FOR singleuser IN SELECT coalesce(employee."Email",usr."Email",'') AS email FROM "User" usr LEFT OUTER JOIN "Map_UserRole" mur ON mur."IdObj1" = usr."Id" AND mur."Status"='A' LEFT OUTER JOIN "Role" role ON role."Id" = mur."IdObj2" AND role."Status"='A' LEFT OUTER JOIN "Employee" employee ON employee."Code"=usr."Username" AND employee."Status"='A' WHERE role."Code"=singleticket.groupcode AND role."Status"='A' LOOP IF singleuser.email <> '' THEN IF groupemaillist<>'' THEN groupemaillist = groupemaillist || ',' || singleuser.email; ELSE groupemaillist = groupemaillist || singleuser.email; END IF; END IF; END LOOP; IF grouplist<>'' THEN grouplist = grouplist || ';' || groupemaillist; else grouplist = grouplist || groupemaillist; END IF; END LOOP; END; $$; DROP FUNCTION public.wf_incidentmgt_checkdelays(processtype character varying, OUT processeslist character varying, OUT delayslist character varying, OUT typeslist character varying, OUT recipientslist character varying, OUT grouplist character varying); publicpostgresfalse00FUNCTION wf_incidentmgt_checkdelays(processtype character varying, OUT processeslist character varying, OUT delayslist character varying, OUT typeslist character varying, OUT recipientslist character varying, OUT grouplist character varying)COMMENTCOMMENT ON FUNCTION public.wf_incidentmgt_checkdelays(processtype character varying, OUT processeslist character varying, OUT delayslist character varying, OUT typeslist character varying, OUT recipientslist character varying, OUT grouplist character varying) IS 'TYPE: function'; publicpostgresfalse20431255233376*wf_incidentmgt_checksla(character varying)FUNCTIONCREATE FUNCTION public.wf_incidentmgt_checksla(processtype character varying, OUT processeslist character varying, OUT delayslist character varying, OUT typeslist character varying, OUT recipientslist character varying, OUT grouplist character varying) RETURNS record LANGUAGE plpgsql AS $$ DECLARE singleticket record; singleuser record; diff integer; today timestamp with time zone; groupemaillist character varying; slaobj_resolution bigint = (select "Id" from "LookUp" where "Type"='SLA - Object' and "Code"='resolution' and "Status"='A'); slaobj_takecharge bigint = (select "Id" from "LookUp" where "Type"='SLA - Object' and "Code"='charge' and "Status"='A'); slaobj_nbd bigint = (select "Id" from "LookUp" where "Type"='SLA - ThresholdType' and "Code"='NBD' and "Status"='A'); slaobj_imtype bigint = (select "Id" from "LookUp" where "Type"='ITProcessClassification - Workflow' and "Code"='IM' and "Status"='A'); BEGIN diff=0; processeslist = ''; delayslist=''; typeslist=''; recipientslist=''; grouplist=''; today = now(); FOR singleticket IN SELECT subq.ident AS ident, subq.slalimit, subq.sla_type_charge, totaltime, (CASE WHEN (subq.imstatus = 'New' and sla_type_charge = slaobj_nbd and today slaobj_nbd and slatime_charge'' THEN processeslist = processeslist || ',' || singleticket.ident; else processeslist = processeslist || singleticket.ident; END IF; IF delayslist<>'' THEN delayslist = delayslist || ',' || singleticket.totaltime; else delayslist = delayslist || singleticket.totaltime; END IF; IF typeslist<>'' THEN typeslist = typeslist || ',' || singleticket.type; else typeslist = typeslist || singleticket.type; END IF; IF recipientslist<>'' THEN recipientslist = recipientslist || ',' || singleticket.recipient; else recipientslist = recipientslist || singleticket.recipient; END IF; groupemaillist = ''; FOR singleuser IN SELECT coalesce(employee."Email",usr."Email",'') AS email FROM "User" usr LEFT OUTER JOIN "Map_UserRole" mur ON mur."IdObj1" = usr."Id" AND mur."Status"='A' LEFT OUTER JOIN "Role" role ON role."Id" = mur."IdObj2" AND role."Status"='A' LEFT OUTER JOIN "Employee" employee ON employee."Code"=usr."Username" AND employee."Status"='A' WHERE role."Code"=singleticket.groupcode AND role."Status"='A' LOOP IF singleuser.email <> '' THEN IF groupemaillist<>'' THEN groupemaillist = groupemaillist || ',' || singleuser.email; ELSE groupemaillist = groupemaillist || singleuser.email; END IF; END IF; END LOOP; IF grouplist<>'' THEN grouplist = grouplist || ';' || groupemaillist; else grouplist = grouplist || groupemaillist; END IF; END LOOP; END; $$; DROP FUNCTION public.wf_incidentmgt_checksla(processtype character varying, OUT processeslist character varying, OUT delayslist character varying, OUT typeslist character varying, OUT recipientslist character varying, OUT grouplist character varying); publicpostgresfalse00FUNCTION wf_incidentmgt_checksla(processtype character varying, OUT processeslist character varying, OUT delayslist character varying, OUT typeslist character varying, OUT recipientslist character varying, OUT grouplist character varying)COMMENTCOMMENT ON FUNCTION public.wf_incidentmgt_checksla(processtype character varying, OUT processeslist character varying, OUT delayslist character varying, OUT typeslist character varying, OUT recipientslist character varying, OUT grouplist character varying) IS 'TYPE: function'; publicpostgresfalse20441255233378wf_incidentmgt_delaynotificationmail(bigint, integer, character varying, character varying, character varying, character varying)FUNCTIONCREATE FUNCTION public.wf_incidentmgt_delaynotificationmail(processid bigint, delay integer, mailtype character varying, notificationtype character varying, to_recipients character varying, cc_recipients character varying, OUT fromaddress character varying, OUT toaddress character varying, OUT ccaddress character varying, OUT bccaddress character varying, OUT subject character varying, OUT content character varying, OUT contenttype character varying) RETURNS record LANGUAGE plpgsql AS $$ DECLARE im_number varchar; im_start timestamp; im_start_string varchar; im_operator varchar; im_operator_email varchar; im_group_code varchar; link varchar; hours integer; minutes integer; seconds integer; today timestamp with time zone; mailmap map[]; singleuser record; BEGIN SELECT INTO fromaddress, toaddress, ccaddress, bccaddress, subject, content coalesce(t."From",(select "Address" from "_EmailAccount" where "Id"=t."Account" and "_EmailAccount"."Status"='A'),''), coalesce(t."To",''), coalesce(t."CC",''), coalesce(t."BCC",''), coalesce(t."Subject",''), coalesce(t."Body",'') from "_EmailTemplate" t WHERE "Status"='A' and "Code"=mailtype; contenttype = 'text/html; charset=utf-8'; SELECT INTO im_number, im_operator, im_start, im_operator_email, im_group_code coalesce(im."Number",''), coalesce(u."Description",''), coalesce(im."CreationTimestamp",null), coalesce(e."Email",''), coalesce(g."Code",'') FROM "IncidentMgt" im LEFT OUTER JOIN "User" u ON u."Id" = im."CurrentUser" AND u."Status"='A' LEFT OUTER JOIN "InternalEmployee" e ON e."Code" = u."Username" AND e."Status"='A' LEFT OUTER JOIN "Role" g ON g."Id" = im."CurrentRole" AND g."Status"='A' WHERE im."Status"='A' AND im."Id"=processid; IF delay IS NOT null THEN hours = ceil(delay/3600); minutes = ceil((delay-hours*3600)/60); seconds = (delay-hours*3600-minutes*60); END IF; im_start_string=''; IF im_start is not null THEN im_start_string = to_char(im_start, 'dd/mm/YYYY HH:MI:SS'); END IF; IF to_recipients is null THEN to_recipients = ''; to_recipients = im_operator_email; END IF; IF cc_recipients is null THEN cc_recipients = ''; FOR singleuser IN SELECT coalesce(employee."Email",usr."Email",'') AS email FROM "User" usr LEFT OUTER JOIN "Map_UserRole" mur ON mur."IdObj1" = usr."Id" AND mur."Status"='A' LEFT OUTER JOIN "Role" role ON role."Id" = mur."IdObj2" AND role."Status"='A' LEFT OUTER JOIN "Employee" employee ON employee."Code"=usr."Username" AND employee."Status"='A' WHERE role."Code"=im_group_code AND role."Status"='A' LOOP IF singleuser.email <> '' THEN IF cc_recipients<>'' THEN cc_recipients = cc_recipients || ',' || singleuser.email; ELSE cc_recipients = cc_recipients || singleuser.email; END IF; END IF; END LOOP; END IF; select into link "Value" from "Parameter" where "Code"='Server-URL' and "Status"='A'; link = link || '#processes/IncidentMgt/instances/'||processid||'/'; mailmap = null; mailmap = array(SELECT ('{server:Number}',im_number)::map); mailmap = mailmap || array(SELECT ('{server:Operator.Description}',im_operator)::map); mailmap = mailmap || array(SELECT ('{server:CreationTimestamp}',im_start_string)::map); mailmap = mailmap || array(SELECT ('{js:DelayHours}',''||hours)::map); mailmap = mailmap || array(SELECT ('{js:DelayMinutes}',''||minutes)::map); mailmap = mailmap || array(SELECT ('{js:DelaySeconds}',''||seconds)::map); mailmap = mailmap || array(SELECT ('{ToAddress}',to_recipients)::map); mailmap = mailmap || array(SELECT ('{CcAddress}',cc_recipients)::map); mailmap = mailmap || array(SELECT ('{Link}',link)::map); toaddress = wf_mailparser(toaddress,mailmap); ccaddress = wf_mailparser(ccaddress,mailmap); bccaddress = wf_mailparser(bccaddress,mailmap); subject = wf_mailparser(subject,mailmap); content = wf_mailparser(content,mailmap); END; $$; DROP FUNCTION public.wf_incidentmgt_delaynotificationmail(processid bigint, delay integer, mailtype character varying, notificationtype character varying, to_recipients character varying, cc_recipients character varying, OUT fromaddress character varying, OUT toaddress character varying, OUT ccaddress character varying, OUT bccaddress character varying, OUT subject character varying, OUT content character varying, OUT contenttype character varying); publicpostgresfalse00FUNCTION wf_incidentmgt_delaynotificationmail(processid bigint, delay integer, mailtype character varying, notificationtype character varying, to_recipients character varying, cc_recipients character varying, OUT fromaddress character varying, OUT toaddress character varying, OUT ccaddress character varying, OUT bccaddress character varying, OUT subject character varying, OUT content character varying, OUT contenttype character varying)COMMENTCOMMENT ON FUNCTION public.wf_incidentmgt_delaynotificationmail(processid bigint, delay integer, mailtype character varying, notificationtype character varying, to_recipients character varying, cc_recipients character varying, OUT fromaddress character varying, OUT toaddress character varying, OUT ccaddress character varying, OUT bccaddress character varying, OUT subject character varying, OUT content character varying, OUT contenttype character varying) IS 'TYPE: function'; publicpostgresfalse20471255233379Rwf_incidentmgt_getactivitytime(timestamp with time zone, timestamp with time zone)FUNCTIONCREATE FUNCTION public.wf_incidentmgt_getactivitytime(date1 timestamp with time zone, date2 timestamp with time zone, OUT activitytime double precision) RETURNS double precision LANGUAGE plpgsql AS $_$ DECLARE i integer; j integer; qt1 decimal; qt2 decimal; qt3 decimal; daytimetable text[]; dayworktime decimal[]; holidays character varying[]; timetable character varying[]; BEGIN holidays = array (select split_part("LookUp"."Code" || '|', '|', 1) from "LookUp" where "LookUp"."Type" = 'Holidays' and "LookUp"."Status" = 'A' group by "LookUp"."Code" order by "LookUp"."Code"); timetable = array (select split_part("LookUp"."Notes" || '|', '|', 1) from "LookUp" where "LookUp"."Type" = 'Working hours' and "LookUp"."Status" = 'A' group by "LookUp"."Notes", "LookUp"."Code" order by "LookUp"."Code"); if $1 is null or $2 is null then activitytime = 0; else for i in 1 .. 7 loop -- initialize array with working hours dayworktime[i] = 0; daytimetable = string_to_array(timetable[i], ','); if daytimetable is null then continue; end if; for j in 1 .. array_upper(daytimetable, 1) loop dayworktime[i] = dayworktime[i] + extract(epoch from ((split_part(daytimetable[j], '-', 2) || ':00')::time - (split_part(daytimetable[j], '-', 1) || ':00')::time)) /*/ 3600*/; end loop; end loop; -- raise notice '%', dayworktime; qt1 = 0.0; -- calculate working time for the first day if timetable[date_part('dow', $1) + 1] is not null and not substr(replace($2::date::varchar, '-', ''), 5, 4) = any (holidays) then daytimetable = string_to_array(timetable[date_part('dow', $1) + 1], ','); for i in 1 .. array_upper(daytimetable, 1) loop if split_part(daytimetable[i], '-', 1)::time > $1::time then qt1 = qt1 + extract(epoch from split_part(daytimetable[i], '-', 2)::time - split_part(daytimetable[i], '-', 1)::time) /*/ 3600*/; elsif split_part(daytimetable[i], '-', 2)::time > $1::time then qt1 = qt1 + extract(epoch from split_part(daytimetable[i], '-', 2)::time - $1::time) /*/ 3600*/; end if; end loop; end if; -- calculate working time for the other days --select now()+ s.a * interval '1 day' from generate_series(1, 5, 1) as s(a) select into qt2 sum(dayworktime[date_part('dow', $1::date + s.a * interval '1 day') + 1]) from generate_series(1, ($2::date - $1::date)-1,1) as s(a) where not substr(replace(($1::date + s.a * interval '1 day')::varchar, '-', ''), 5, 4) = any (holidays); -- raise notice 'qt2 = %', qt2; qt3 = 0.0; -- calculate working time for the last day if timetable[date_part('dow', $2) + 1] is not null and not substr(replace($2::date::varchar, '-', ''), 5, 4) = any (holidays) then daytimetable = string_to_array(timetable[date_part('dow', $2) + 1], ','); for i in 1 .. array_upper(daytimetable, 1) loop if $2::time > split_part(daytimetable[i], '-', 2)::time then qt3 = qt3 + extract(epoch from split_part(daytimetable[i], '-', 2)::time - split_part(daytimetable[i], '-', 1)::time) /*/ 3600*/; elsif $2::time > split_part(daytimetable[i], '-', 1)::time then qt3 = qt3 + extract(epoch from $2::time - split_part(daytimetable[i], '-', 1)::time) /*/ 3600*/; end if; end loop; end if; -- raise notice 'qt3 = %', qt3; -- raise notice 'date1=% date2=% qt1=% qt2=% qt3=% totale=%', $1, $2, qt1, qt2, qt3, case when $1::date = $2::date then qt1 + qt3 - dayworktime[date_part('dow', $1)] else qt1 + coalesce(qt2, 0) + qt3 end; if $1::date = $2::date then activitytime = case when qt1 + qt3 - dayworktime[date_part('dow', $1) + 1] < 0.0 then 0.0 else qt1 + qt3 - dayworktime[date_part('dow', $1) + 1] end; else activitytime = qt1 + coalesce(qt2, 0.0) + qt3; end if; end if; END; $_$; DROP FUNCTION public.wf_incidentmgt_getactivitytime(date1 timestamp with time zone, date2 timestamp with time zone, OUT activitytime double precision); publicpostgresfalse00FUNCTION wf_incidentmgt_getactivitytime(date1 timestamp with time zone, date2 timestamp with time zone, OUT activitytime double precision)COMMENTCOMMENT ON FUNCTION public.wf_incidentmgt_getactivitytime(date1 timestamp with time zone, date2 timestamp with time zone, OUT activitytime double precision) IS 'TYPE: function'; publicpostgresfalse20481255233380&wf_incidentmgt_getcisrequester(bigint)FUNCTIONCREATE FUNCTION public.wf_incidentmgt_getcisrequester(requester bigint, OUT id bigint) RETURNS SETOF bigint LANGUAGE sql AS $_$ select "Id" from "CI" where "Assignee"=$1 and "Status"='A' and "IdClass" NOT IN ('"Service"'::regclass); $_$; VDROP FUNCTION public.wf_incidentmgt_getcisrequester(requester bigint, OUT id bigint); publicpostgresfalse 00HFUNCTION wf_incidentmgt_getcisrequester(requester bigint, OUT id bigint)COMMENTpCOMMENT ON FUNCTION public.wf_incidentmgt_getcisrequester(requester bigint, OUT id bigint) IS 'TYPE: function'; publicpostgresfalse20491255233381*wf_incidentmgt_getgeneratedprocess(bigint)FUNCTIONCREATE FUNCTION public.wf_incidentmgt_getgeneratedprocess(processid bigint, OUT id bigint) RETURNS SETOF bigint LANGUAGE sql AS $_$ select "IdObj2" from "Map_GeneratedITProc" where "IdObj1"=$1 and "Status"='A'; $_$; ZDROP FUNCTION public.wf_incidentmgt_getgeneratedprocess(processid bigint, OUT id bigint); publicpostgresfalse!00LFUNCTION wf_incidentmgt_getgeneratedprocess(processid bigint, OUT id bigint)COMMENTtCOMMENT ON FUNCTION public.wf_incidentmgt_getgeneratedprocess(processid bigint, OUT id bigint) IS 'TYPE: function'; publicpostgresfalse20501255233382*wf_incidentmgt_getservicerequester(bigint)FUNCTION-CREATE FUNCTION public.wf_incidentmgt_getservicerequester(requester bigint, OUT id bigint) RETURNS SETOF bigint LANGUAGE sql AS $_$ select "Service" from "ServiceContract" sc left join "LookUp" l on l."Id"=sc."State" and l."Code"='Active' where sc."Employee"=$1 and sc."Status"='A'; $_$; ZDROP FUNCTION public.wf_incidentmgt_getservicerequester(requester bigint, OUT id bigint); publicpostgresfalse"00LFUNCTION wf_incidentmgt_getservicerequester(requester bigint, OUT id bigint)COMMENTtCOMMENT ON FUNCTION public.wf_incidentmgt_getservicerequester(requester bigint, OUT id bigint) IS 'TYPE: function'; publicpostgresfalse20511255233383@wf_incidentmgt_im01_email_to_helpdesk(character varying, bigint)FUNCTION6CREATE FUNCTION public.wf_incidentmgt_im01_email_to_helpdesk(number character varying, process bigint, OUT toaddress character varying, OUT fromaddress character varying, OUT subject character varying, OUT body text) RETURNS record LANGUAGE plpgsql AS $$ DECLARE shortDescr varchar; areaDescr varchar; extDescr varchar; requesterDescr varchar; hdDescr varchar; url varchar; BEGIN SELECT "Email", r."Description" INTO toaddress, hdDescr FROM "Role" r JOIN "IncidentMgt" im ON im."Id" = process AND im."Status" = 'A' JOIN "LookUp" la ON im."Area" = la."Id" and la."Status"='A' JOIN "ITProcArea" a on la."Id"=a."Area" and a."Role"=r."Id" and a."Status"='A' WHERE r."Status" = 'A'; SELECT "Address" INTO fromaddress FROM "_EmailAccount" WHERE "Code" IN (select _cm3_system_config_get('org.cmdbuild.email.accountDefault')) AND "Status" = 'A'; SELECT 'Incident management n.' || number || ' - Registered' INTO subject; SELECT im."ShortDescr", a."Description", im."ExtDescr", r."Description" INTO shortDescr, areaDescr, extDescr, requesterDescr FROM "IncidentMgt" AS im JOIN "LookUp" a ON im."Area" = a."Id" JOIN "Employee" r ON im."Requester" = r."Id" WHERE im."Id" = process; SELECT "Value" INTO url FROM "Parameter" WHERE "Status" = 'A' AND "Code" = 'Server-URL'; url = url || '#processes/IncidentMgt/instances/' || process || '/'; SELECT coalesce('

    The request ' || number || ' has been registered and assigned to ' || hdDescr || '.

    Request data:

    • Number and summary: ' || number || '- ' || shortDescr || '
    • ' || coalesce('
    • Area : ' || areaDescr || '
    • ', '') || coalesce('
    • Description: ' || extDescr || '
    • ', '') || coalesce('
    • Requester: ' || requesterDescr || '
    • ', '') || '

     

    This message was generated automatically by CMDBuild - Ready2Use, please don''t reply.
    For more information and to contribute to the fulfilment of this request, please click here.

    ','') INTO body; END; $$; DROP FUNCTION public.wf_incidentmgt_im01_email_to_helpdesk(number character varying, process bigint, OUT toaddress character varying, OUT fromaddress character varying, OUT subject character varying, OUT body text); publicpostgresfalse#00FUNCTION wf_incidentmgt_im01_email_to_helpdesk(number character varying, process bigint, OUT toaddress character varying, OUT fromaddress character varying, OUT subject character varying, OUT body text)COMMENTCOMMENT ON FUNCTION public.wf_incidentmgt_im01_email_to_helpdesk(number character varying, process bigint, OUT toaddress character varying, OUT fromaddress character varying, OUT subject character varying, OUT body text) IS 'TYPE: function'; publicpostgresfalse20521255233384Awf_incidentmgt_im01_email_to_requester(character varying, bigint)FUNCTIONCREATE FUNCTION public.wf_incidentmgt_im01_email_to_requester(number character varying, process bigint, OUT toaddress character varying, OUT fromaddress character varying, OUT subject character varying, OUT body text) RETURNS record LANGUAGE plpgsql AS $$ DECLARE shortDescr varchar; areaDescr varchar; extDescr varchar; requesterDescr varchar; url varchar; BEGIN SELECT "Email" INTO toaddress FROM "Employee" e JOIN "IncidentMgt" im ON im."Requester" = e."Id" AND im."Id" = process AND im."Status" = 'A' WHERE e."Status" = 'A'; SELECT "Address" INTO fromaddress FROM "_EmailAccount" WHERE "Code" IN (select _cm3_system_config_get('org.cmdbuild.email.accountDefault')) AND "Status" = 'A'; SELECT 'Incident management n.' || number || ' - Registered' INTO subject; SELECT im."ShortDescr", a."Description", im."ExtDescr", e."Description" INTO shortDescr, areaDescr, extDescr, requesterDescr FROM "IncidentMgt" AS im LEFT JOIN "LookUp" a ON im."Area" = a."Id" JOIN "Employee" e ON im."Requester" = e."Id" WHERE im."Id" = process; SELECT "Value" INTO url FROM "Parameter" WHERE "Status" = 'A' AND "Code" = 'Portal-URL'; url = url || '#page=my-requests&selected-item=' || process; SELECT '

    The request ' || number || ' has been registered.

    Request data:

    • Number and summary: ' || number || '- ' || shortDescr || '
    • ' || coalesce('
    • Area : ' || areaDescr || '
    • ', '') || coalesce('
    • Description: ' || extDescr || '
    • ', '') || coalesce('
    • Requester: ' || requesterDescr || '
    • ', '') || '

     

    This message was generated automatically by CMDBuild - Ready2Use, please don''t change the subject in case of reply.
    For more information and to contribute to the fulfilment of this request, please click here.

    ' INTO body; END; $$; DROP FUNCTION public.wf_incidentmgt_im01_email_to_requester(number character varying, process bigint, OUT toaddress character varying, OUT fromaddress character varying, OUT subject character varying, OUT body text); publicpostgresfalse$00FUNCTION wf_incidentmgt_im01_email_to_requester(number character varying, process bigint, OUT toaddress character varying, OUT fromaddress character varying, OUT subject character varying, OUT body text)COMMENTCOMMENT ON FUNCTION public.wf_incidentmgt_im01_email_to_requester(number character varying, process bigint, OUT toaddress character varying, OUT fromaddress character varying, OUT subject character varying, OUT body text) IS 'TYPE: function'; publicpostgresfalse2056 1255233385wf_incidentmgt_nextrole(character varying, character varying, character varying, character varying, character varying, character varying)FUNCTION\CREATE FUNCTION public.wf_incidentmgt_nextrole(procnum character varying, category character varying, subcategory character varying, action character varying, wftype character varying, currentuser character varying, OUT roleid bigint) RETURNS SETOF bigint LANGUAGE plpgsql AS $$ DECLARE categoryId bigint; subcategoryId bigint; actionId bigint; currentUserId bigint; assignedRoleId bigint; mustbecurrent boolean; isValid boolean; isAdministrator character varying; BEGIN --raise log 'INPUT: procnum %, category: %, subcategory: %, action: %, currentuser: %', procnum, category, subcategory, action, currentuser; select into assignedRoleId wf_getassignedrole(procnum); if (category!='null' and category!='') then select into categoryId c."Id" from "ITProcCategory" c where (c."Id"::varchar=category or c."Description"=category) and c."Status"='A'; end if; if (subcategory!='null' and subcategory!='') then select into subcategoryId sc."Id" from "ITProcSubcategory" sc where (sc."Id"::varchar=subcategory or sc."Description"=subcategory) and sc."Status"='A'; end if; if (action!='null' and action!='') then select into actionId, mustbecurrent a."Id" , case when ( (a."Code" in ('HDAnalysis', 'HDExecution', 'Closure', 'StartCM', 'StartRF') and a."Type"='IncidentMgt - HDClassification Action') or (a."Code" in ('SPAnalysis', 'SPExecution', 'Closure') and a."Type"='IncidentMgt - SPClassification Action') ) then true else false end from "LookUp" a where (a."Id"::varchar=action or a."Description"=action) and a."Status"='A'; end if; if (currentuser!='null' and currentuser!='') then select into currentUserId u."Id" from "User" u where (u."Id"::varchar=currentuser or u."Description"=currentuser) and u."Status"='A'; end if; --raise log ' categoryId:%, subcategoryId: %, actionId: %, mustbecurrent: %, currentrole: %', categoryId, subcategoryId, actionId, mustbecurrent,assignedRoleId; if(mustbecurrent) then select into isAdministrator "Type" from "Role" where "Id"=assignedRoleId; -- has the currentUser a role that has a valid classification for the selected category and subcategory? select into isValid count(*)>0 from "ITProcClassification" c join "LookUp" l1 on c."Workflow"=l1."Id" and l1."Status"='A' and l1."Code"=wftype join "ITProcCategory" p on p."Id"=c."Category" and p."Status"='A' join "ITProcSubcategory" sp on sp."Id"=c."Subcategory" and sp."Status"='A' where c."Status"='A' and c."Active" and ( (c."HDRole" = assignedRoleId and actionId in (select a."Id" from "LookUp" a where a."Type"='IncidentMgt - HDClassification Action')) or (c."SPRole" = assignedRoleId and actionId in (select a."Id" from "LookUp" a where a."Type"='IncidentMgt - SPClassification Action')) ) and c."Category"=categoryId and c."Subcategory"=subcategoryId; if(isValid or isAdministrator='admin') then return query select assignedRoleId; else return query select 0::bigint; end if; else return query select c."HDRole" from "ITProcClassification" c join "LookUp" l1 on c."Workflow"=l1."Id" and l1."Status"='A' and l1."Code"=wftype join "ITProcCategory" p on p."Id"=c."Category" and p."Status"='A' join "ITProcSubcategory" sp on sp."Id"=c."Subcategory" and sp."Status"='A' left join "LookUp" ahd on ahd."Type"='IncidentMgt - HDClassification Action' and ahd."Id"=actionId left join "LookUp" asp on asp."Type"='IncidentMgt - SPClassification Action' and asp."Id"=actionId where c."Status"='A' and c."Active" and ( ahd."Code" in ('EscalationHD') or asp."Code" in ('DescalationHD') ) and c."HDRole"<>assignedRoleId and c."Category"=categoryId and c."Subcategory"=subcategoryId union select c."SPRole" from "ITProcClassification" c join "LookUp" l1 on c."Workflow"=l1."Id" and l1."Status"='A' and l1."Code"=wftype join "ITProcCategory" p on p."Id"=c."Category" and p."Status"='A' join "ITProcSubcategory" sp on sp."Id"=c."Subcategory" and sp."Status"='A' left join "LookUp" ahd on ahd."Type"='IncidentMgt - HDClassification Action' and ahd."Id"=actionId left join "LookUp" asp on asp."Type"='IncidentMgt - SPClassification Action' and asp."Id"=actionId where c."Status"='A'and c."Active" and ( asp."Code" in ('EscalationSP') or ahd."Code" in ('EscalationSP') ) and c."SPRole"<>assignedRoleId and c."Category"=categoryId and c."Subcategory"=subcategoryId; end if; --raise log ' roleid:%',roleid; END; $$; DROP FUNCTION public.wf_incidentmgt_nextrole(procnum character varying, category character varying, subcategory character varying, action character varying, wftype character varying, currentuser character varying, OUT roleid bigint); publicpostgresfalse%00FUNCTION wf_incidentmgt_nextrole(procnum character varying, category character varying, subcategory character varying, action character varying, wftype character varying, currentuser character varying, OUT roleid bigint)COMMENTCOMMENT ON FUNCTION public.wf_incidentmgt_nextrole(procnum character varying, category character varying, subcategory character varying, action character varying, wftype character varying, currentuser character varying, OUT roleid bigint) IS 'TYPE: function'; publicpostgresfalse2057 1255233386wf_incidentmgt_number()FUNCTIONCREATE FUNCTION public.wf_incidentmgt_number(OUT number character varying) RETURNS character varying LANGUAGE plpgsql AS $$ BEGIN number = lpad(nextval('incidentmgt_seq')::text,6,'0'); END; $$; JDROP FUNCTION public.wf_incidentmgt_number(OUT number character varying); publicpostgresfalse&00<FUNCTION wf_incidentmgt_number(OUT number character varying)COMMENTdCOMMENT ON FUNCTION public.wf_incidentmgt_number(OUT number character varying) IS 'TYPE: function'; publicpostgresfalse2058 1255233387]wf_incidentmgt_prepare_email(bigint, character varying, character varying, character varying)FUNCTIONhCREATE FUNCTION public.wf_incidentmgt_prepare_email(process_id bigint, proc_number character varying, template_name character varying, email_status character varying, OUT emailid bigint) RETURNS bigint LANGUAGE plpgsql AS $$ DECLARE from_address VARCHAR; to_addresses VARCHAR; cc_addresses VARCHAR; bcc_addresses VARCHAR; subject VARCHAR; body VARCHAR; language_config VARCHAR; proc_shortdescr VARCHAR; proc_extdescr VARCHAR; reqtype_code VARCHAR; area_descr VARCHAR; ser_descr VARCHAR; sercat_descr VARCHAR; priority_descr VARCHAR; requester_descr VARCHAR; requester_email VARCHAR; helpdesk_descr VARCHAR; helpdesk_email VARCHAR; url_page_server VARCHAR; url_page_portal VARCHAR; BEGIN IF (SELECT "Template" FROM "_Templates" WHERE "Name" = 'Email-Lang') IN ('en', 'it') THEN language_config = (SELECT "Template" FROM "_Templates" WHERE "Name" = 'Email-Lang'); ELSIF coalesce(_cm3_system_config_get('org.cmdbuild.core.language'), '') IN ('en', 'it') THEN language_config = _cm3_system_config_get('org.cmdbuild.core.language'); ELSE language_config = 'en'; END IF; --Retrieve email account and email template fields SELECT COALESCE(et."From", ''), COALESCE(et."To", ''), COALESCE(et."CC", ''), COALESCE(et."BCC", ''), COALESCE(et."Subject", ''), COALESCE(et."Body", '') INTO from_address, to_addresses, cc_addresses, bcc_addresses, subject, body FROM "_EmailTemplate" et LEFT JOIN "_EmailAccount" ea ON ea."Id" = et."Account" AND ea."Status" = 'A' WHERE et."Code" = template_name AND et."Status" = 'A'; -- retrieve im data SELECT proc."ShortDescr", proc."ExtDescr", area."Description", requester."Description", requester."Email", hd."Description", hd."Email" INTO proc_shortdescr, proc_extdescr, area_descr, requester_descr, requester_email, helpdesk_descr, helpdesk_email FROM "IncidentMgt" proc LEFT JOIN "Employee" requester ON proc."Requester" = requester."Id" LEFT JOIN "LookUp" area ON proc."Area" = area."Id" LEFT JOIN "ITProcArea" itparea ON itparea."Area"=area."Id" LEFT JOIN "Role" hd ON hd."Id"=itparea."Role" WHERE proc."Id" = process_id; url_page_server = (select "Value" FROM "Parameter" WHERE "Code" = 'Server-URL' and "Status"='A') || '#processes/IncidentMgt/instances/' || process_id; url_page_portal = (select "Value" FROM "Parameter" WHERE "Code" = 'Portal-URL' and "Status"='A') || '#page=my-requests&selected-item=' || process_id || '/'; -- mapping of fields into the template SELECT INTO to_addresses REPLACE(to_addresses, '{server:Helpdesk.Email}', COALESCE(helpdesk_email, '')); SELECT INTO to_addresses REPLACE(to_addresses, '{server:Requester.Email}', COALESCE(requester_email, '')); SELECT INTO subject REPLACE(subject, '{server:Number}', COALESCE(proc_number, '')); SELECT INTO body REPLACE(body, '{server:Number}', COALESCE(proc_number, '')); SELECT INTO body REPLACE(body, '{server:ShortDescr}', COALESCE(proc_shortdescr, '')); SELECT INTO body REPLACE(body, '{server:Area.Description}', COALESCE(area_descr, '')); SELECT INTO body REPLACE(body, '{server:Requester.Description}', COALESCE(requester_descr, '')); SELECT INTO body REPLACE(body, '{server:ExtDescr}', COALESCE(proc_extdescr, '')); SELECT INTO body REPLACE(body, '{server:Parameter.Server-Url}', COALESCE(url_page_server, '')); SELECT INTO body REPLACE(body, '{server:Parameter.Portal-Url}', COALESCE(url_page_portal, '')); -- create an outgoing e-mail linked to the process --Generate email IF EXISTS (SELECT "Code" FROM "_EmailTemplate" WHERE "Code" = template_name AND "Status" = 'A') THEN INSERT INTO "Email" ("EmailStatus","FromAddress","ToAddresses","CcAddresses", "BccAddresses", "Subject","Content","Card","Delay","KeepSynchronization","PromptSynchronization") SELECT coalesce(nullif(email_status, ''), 'outgoing'), from_address, to_addresses, cc_addresses, bcc_addresses, subject, body, process_id, 0, false, false RETURNING "Id" INTO emailid; END IF; END; $$; DROP FUNCTION public.wf_incidentmgt_prepare_email(process_id bigint, proc_number character varying, template_name character varying, email_status character varying, OUT emailid bigint); publicpostgresfalse'00FUNCTION wf_incidentmgt_prepare_email(process_id bigint, proc_number character varying, template_name character varying, email_status character varying, OUT emailid bigint)COMMENTCOMMENT ON FUNCTION public.wf_incidentmgt_prepare_email(process_id bigint, proc_number character varying, template_name character varying, email_status character varying, OUT emailid bigint) IS 'TYPE: function'; publicpostgresfalse2059 1255233388,wf_incidentmgt_servicecontractfilter(bigint)FUNCTIONSCREATE FUNCTION public.wf_incidentmgt_servicecontractfilter(idemployee bigint, OUT itprocsubcategory bigint) RETURNS SETOF bigint LANGUAGE plpgsql AS $$ BEGIN RETURN QUERY select "IdObj2" from "Map_CompanyServiceContract" where "IdObj1" = (select "Company" from "Employee" where "Id" = idemployee and "Status" = 'A'); END; $$; lDROP FUNCTION public.wf_incidentmgt_servicecontractfilter(idemployee bigint, OUT itprocsubcategory bigint); publicpostgresfalse(00^FUNCTION wf_incidentmgt_servicecontractfilter(idemployee bigint, OUT itprocsubcategory bigint)COMMENTCOMMENT ON FUNCTION public.wf_incidentmgt_servicecontractfilter(idemployee bigint, OUT itprocsubcategory bigint) IS 'TYPE: function'; publicpostgresfalse2060 1255233389Awf_incidentmgt_suggoperator(character varying, character varying)FUNCTIONCREATE FUNCTION public.wf_incidentmgt_suggoperator(nextrole character varying, procnum character varying, OUT userid bigint) RETURNS SETOF bigint LANGUAGE plpgsql AS $$ DECLARE nextroleId bigint; assignedRoleId bigint; mustbecurrent boolean; BEGIN --raise notice 'INPUT: nextrole: %' , nextrole; select into assignedRoleId wf_getassignedrole(procnum); if (nextrole!='null' and nextrole!='') then mustbecurrent = false; select into nextroleId r."Id" from "Role" r where (r."Id"::varchar=nextrole or r."Description"=nextrole) and r."Status"='A'; else mustbecurrent = true; end if; --raise notice ' nextroleId:%, assignedRoleId: %, mustbecurrent: %', nextroleId, assignedRoleId, mustbecurrent; if(mustbecurrent) then return query select u."Id" from "User" u join "Map_UserRole" map on map."IdObj1" = u."Id" and map."Status" = 'A' and map."IdObj2" = assignedRoleId where u."Status" = 'A' and not coalesce(u."Service", false); else return query select u."Id" from "User" u join "Map_UserRole" map on map."IdObj1" = u."Id" and map."Status" = 'A' and map."IdObj2" = nextroleId where u."Status" = 'A' and not coalesce(u."Service", false); end if; END; $$; |DROP FUNCTION public.wf_incidentmgt_suggoperator(nextrole character varying, procnum character varying, OUT userid bigint); publicpostgresfalse)00nFUNCTION wf_incidentmgt_suggoperator(nextrole character varying, procnum character varying, OUT userid bigint)COMMENTCOMMENT ON FUNCTION public.wf_incidentmgt_suggoperator(nextrole character varying, procnum character varying, OUT userid bigint) IS 'TYPE: function'; publicpostgresfalse20611255233390wf_ipaddressmgt_grid(bigint)FUNCTIONCREATE FUNCTION public.wf_ipaddressmgt_grid(hardwareid bigint, OUT "IdInterface" bigint, OUT "IdVirtualIP" bigint, OUT "InterfaceName" character varying, OUT "InterfaceType" bigint, OUT "IPAddress" character varying, OUT "VirtualIP" boolean) RETURNS SETOF record LANGUAGE plpgsql AS $$ BEGIN RETURN QUERY SELECT * FROM ( SELECT ni."Id" AS "IdInterface", '-1' AS "IdVirtualIP", ni."Name" AS "InterfaceName", ni."Type" AS "InterfaceType", host(ni."IPAddress")::varchar AS "IPAddress", false AS "VirtualIP" FROM "NetworkInterface" ni WHERE ni."Status" = 'A' AND ni."Hardware" = hardwareid UNION SELECT ni."Id" AS "IdInterface", ip."Id" AS "IdVirtualIP", ni."Name" AS "InterfaceName", ni."Type" AS "InterfaceType", host(ip."IPAddress")::varchar AS "IPAddress", true AS "VirtualIP" FROM "NetworkInterface" ni JOIN "VirtualIP" ip ON ip."NetworkInterface"=ni."Id" AND ip."Status"='A' WHERE ni."Status" = 'A' AND ni."Hardware" = hardwareid ) AS main order by "InterfaceName","VirtualIP"; END; $$; DROP FUNCTION public.wf_ipaddressmgt_grid(hardwareid bigint, OUT "IdInterface" bigint, OUT "IdVirtualIP" bigint, OUT "InterfaceName" character varying, OUT "InterfaceType" bigint, OUT "IPAddress" character varying, OUT "VirtualIP" boolean); publicpostgresfalse*00FUNCTION wf_ipaddressmgt_grid(hardwareid bigint, OUT "IdInterface" bigint, OUT "IdVirtualIP" bigint, OUT "InterfaceName" character varying, OUT "InterfaceType" bigint, OUT "IPAddress" character varying, OUT "VirtualIP" boolean)COMMENT COMMENT ON FUNCTION public.wf_ipaddressmgt_grid(hardwareid bigint, OUT "IdInterface" bigint, OUT "IdVirtualIP" bigint, OUT "InterfaceName" character varying, OUT "InterfaceType" bigint, OUT "IPAddress" character varying, OUT "VirtualIP" boolean) IS 'TYPE: function'; publicpostgresfalse20451255233391wf_ipaddressmgt_number()FUNCTIONCREATE FUNCTION public.wf_ipaddressmgt_number(OUT number character varying) RETURNS character varying LANGUAGE plpgsql AS $$ BEGIN number = lpad(nextval('ipaddressmgt_seq')::text,6,'0'); END; $$; KDROP FUNCTION public.wf_ipaddressmgt_number(OUT number character varying); publicpostgresfalse+00=FUNCTION wf_ipaddressmgt_number(OUT number character varying)COMMENTeCOMMENT ON FUNCTION public.wf_ipaddressmgt_number(OUT number character varying) IS 'TYPE: function'; publicpostgresfalse20461255233392Uwf_itproc_getactivitytime(timestamp with time zone, timestamp with time zone, bigint)FUNCTION\CREATE FUNCTION public.wf_itproc_getactivitytime(date1 timestamp with time zone, date2 timestamp with time zone, calendar_id bigint, OUT activitytime double precision) RETURNS double precision LANGUAGE plpgsql AS $$ BEGIN activitytime = extract(epoch from (select work_time from utils_wc_get_worktime(date1,date2,calendar_id))); END; $$; DROP FUNCTION public.wf_itproc_getactivitytime(date1 timestamp with time zone, date2 timestamp with time zone, calendar_id bigint, OUT activitytime double precision); publicpostgresfalse,00FUNCTION wf_itproc_getactivitytime(date1 timestamp with time zone, date2 timestamp with time zone, calendar_id bigint, OUT activitytime double precision)COMMENTCOMMENT ON FUNCTION public.wf_itproc_getactivitytime(date1 timestamp with time zone, date2 timestamp with time zone, calendar_id bigint, OUT activitytime double precision) IS 'TYPE: function'; publicpostgresfalse20531255233393wf_itproc_isactive(bigint)FUNCTIONCREATE FUNCTION public.wf_itproc_isactive(procid bigint, OUT isactive boolean) RETURNS boolean LANGUAGE plpgsql AS $$ DECLARE flowstatus bigint; BEGIN SELECT "FlowStatus" INTO flowstatus FROM "ITProc" WHERE "Id" = procid; isactive = coalesce((flowstatus IN (SELECT "Id" FROM "LookUp" WHERE "Code" ILIKE 'open.%' AND "Type" = 'FlowStatus' AND "Status" = 'A')),false); END; $$; NDROP FUNCTION public.wf_itproc_isactive(procid bigint, OUT isactive boolean); publicpostgresfalse-00@FUNCTION wf_itproc_isactive(procid bigint, OUT isactive boolean)COMMENThCOMMENT ON FUNCTION public.wf_itproc_isactive(procid bigint, OUT isactive boolean) IS 'TYPE: function'; publicpostgresfalse20541255233394wf_itproc_send_email(bigint, character varying, character varying, character varying, character varying, character varying, character varying)FUNCTIONtCREATE FUNCTION public.wf_itproc_send_email(processid bigint, fromaddress character varying, toaddress character varying, ccaddress character varying, bccaddress character varying, subject character varying, body character varying, OUT sentemailid bigint) RETURNS bigint LANGUAGE plpgsql AS $$ DECLARE emailid bigint; BEGIN INSERT INTO "Email" ("Card","FromAddress","ToAddresses","CcAddresses","BccAddresses","Subject","Content", "EmailStatus","User") VALUES(processid, fromaddress, toaddress, ccaddress, bccaddress, subject, body, 'outgoing','system') RETURNING "Id" INTO emailid; sentemailid=emailid; END; $$; DROP FUNCTION public.wf_itproc_send_email(processid bigint, fromaddress character varying, toaddress character varying, ccaddress character varying, bccaddress character varying, subject character varying, body character varying, OUT sentemailid bigint); publicpostgresfalse.00FUNCTION wf_itproc_send_email(processid bigint, fromaddress character varying, toaddress character varying, ccaddress character varying, bccaddress character varying, subject character varying, body character varying, OUT sentemailid bigint)COMMENTCOMMENT ON FUNCTION public.wf_itproc_send_email(processid bigint, fromaddress character varying, toaddress character varying, ccaddress character varying, bccaddress character varying, subject character varying, body character varying, OUT sentemailid bigint) IS 'TYPE: function'; publicpostgresfalse20551255233395.wf_mailparser(character varying, public.map[])FUNCTION&CREATE FUNCTION public.wf_mailparser(INOUT txt character varying, vars public.map[]) RETURNS character varying LANGUAGE plpgsql AS $$ DECLARE map_row map; BEGIN for map_row in (select * from unnest(vars)) loop select into txt replace(txt, map_row.k, map_row.v); end loop; END; $$; TDROP FUNCTION public.wf_mailparser(INOUT txt character varying, vars public.map[]); publicpostgresfalse25451255233396Cwf_pm_classification_nextrole(character varying, character varying)FUNCTIONCREATE FUNCTION public.wf_pm_classification_nextrole(category character varying, subcategory character varying, OUT roleid bigint) RETURNS SETOF bigint LANGUAGE plpgsql AS $$ DECLARE idcategory BIGINT; idsubcategory BIGINT; wftype BIGINT; BEGIN SELECT "Id" INTO idcategory FROM "ITProcCategory" WHERE "Id"::text = category; SELECT "Id" INTO idsubcategory FROM "ITProcSubcategory" WHERE "Id"::text = subcategory; SELECT "Id" INTO wftype FROM "LookUp" WHERE "Type" = 'ITProcessClassification - Workflow' AND "Status" = 'A' AND "Code" = 'PM'; -- RAISE NOTICE 'INPUT: CategoryId: % - SubcategoryId: %', CategoryId, SubcategoryId; return query SELECT sr."HDRole" FROM "ITProcClassification" sr WHERE sr."Workflow"=wftype AND sr."Category"=idcategory AND sr."Subcategory"=idsubcategory AND sr."Status"='A' union SELECT sr."SPRole" FROM "ITProcClassification" sr WHERE sr."Workflow"=wftype AND sr."Category"=idcategory AND sr."Subcategory"=idsubcategory AND sr."Status"='A'; END; $$; DROP FUNCTION public.wf_pm_classification_nextrole(category character varying, subcategory character varying, OUT roleid bigint); publicpostgresfalse/00tFUNCTION wf_pm_classification_nextrole(category character varying, subcategory character varying, OUT roleid bigint)COMMENTCOMMENT ON FUNCTION public.wf_pm_classification_nextrole(category character varying, subcategory character varying, OUT roleid bigint) IS 'TYPE: function'; publicpostgresfalse20631255233397.wf_problemmgt_count_workorders(bigint, bigint)FUNCTIONKCREATE FUNCTION public.wf_problemmgt_count_workorders(category bigint, subcategory bigint, OUT result bigint) RETURNS SETOF bigint LANGUAGE plpgsql ROWS 1 AS $_$ BEGIN RETURN QUERY SELECT count(pmtmpl."Id") FROM "ProblemMgtWOTmpl" pmtmpl LEFT JOIN "Map_ITProcClassPMWOTmpl" mappmtmpl ON mappmtmpl."IdObj2"=pmtmpl."Id" AND mappmtmpl."Status"='A' LEFT JOIN "ITProcClassification" itprocclassific ON itprocclassific."Category"=$1 AND itprocclassific."Subcategory"=$2 AND itprocclassific."Workflow"=(SELECT "Id" FROM "LookUp" WHERE "Code"='PM' AND "Type"='ITProcessClassification - Workflow' AND "Status"='A') AND itprocclassific."Active"=TRUE AND itprocclassific."Status"='A' WHERE pmtmpl."Status"='A' AND pmtmpl."State"=(SELECT "Id" FROM "LookUp" WHERE "Code"='Active' AND "Type"='WorkorderTmpl - State'); END $_$; mDROP FUNCTION public.wf_problemmgt_count_workorders(category bigint, subcategory bigint, OUT result bigint); publicpostgresfalse000_FUNCTION wf_problemmgt_count_workorders(category bigint, subcategory bigint, OUT result bigint)COMMENTCOMMENT ON FUNCTION public.wf_problemmgt_count_workorders(category bigint, subcategory bigint, OUT result bigint) IS 'TYPE: function'; publicpostgresfalse206412552333983wf_problemmgt_get_workorder(bigint, bigint, bigint)FUNCTION]CREATE FUNCTION public.wf_problemmgt_get_workorder(category bigint, subcategory bigint, poswo bigint, OUT activitydescr character varying, OUT exptime character varying, OUT nextextrole character varying) RETURNS SETOF record LANGUAGE plpgsql ROWS 1 AS $_$ BEGIN RETURN QUERY SELECT (COALESCE(pmtmpl."ActivityName" || E'\n', '') || COALESCE(pmtmpl."ActivityDescription", ''))::VARCHAR, pmtmpl."ExpectedTime"::VARCHAR, pmtmpl."ExecutorRole"::VARCHAR FROM "ProblemMgtWOTmpl" pmtmpl LEFT JOIN "Map_ITProcClassPMWOTmpl" mappmtmpl ON mappmtmpl."IdObj2"=pmtmpl."Id" AND mappmtmpl."Status"='A' LEFT JOIN "ITProcClassification" itprocclassific ON itprocclassific."Category"=$1 AND itprocclassific."Subcategory"=$2 AND itprocclassific."Workflow"=(SELECT "Id" FROM "LookUp" WHERE "Code"='PM' AND "Type"='ITProcessClassification - Workflow' AND "Status"='A') AND itprocclassific."Active"=TRUE AND itprocclassific."Status"='A' WHERE pmtmpl."Status"='A' AND pmtmpl."State"=(SELECT "Id" FROM "LookUp" WHERE "Code"='Active' AND "Type"='WorkorderTmpl - State') AND mappmtmpl."Order"=$3; END; $_$; DROP FUNCTION public.wf_problemmgt_get_workorder(category bigint, subcategory bigint, poswo bigint, OUT activitydescr character varying, OUT exptime character varying, OUT nextextrole character varying); publicpostgresfalse100FUNCTION wf_problemmgt_get_workorder(category bigint, subcategory bigint, poswo bigint, OUT activitydescr character varying, OUT exptime character varying, OUT nextextrole character varying)COMMENTCOMMENT ON FUNCTION public.wf_problemmgt_get_workorder(category bigint, subcategory bigint, poswo bigint, OUT activitydescr character varying, OUT exptime character varying, OUT nextextrole character varying) IS 'TYPE: function'; publicpostgresfalse20651255233399-wf_problemmgt_load_workorders(bigint, bigint)FUNCTIONCREATE FUNCTION public.wf_problemmgt_load_workorders(category bigint, subcategory bigint, OUT id bigint) RETURNS SETOF bigint LANGUAGE sql AS $_$ SELECT pmtmpl."Id" FROM "ProblemMgtWOTmpl" pmtmpl LEFT JOIN "Map_ITProcClassPMWOTmpl" mappmtmpl ON mappmtmpl."IdObj2"=pmtmpl."Id" AND mappmtmpl."Status"='A' LEFT JOIN "ITProcClassification" itprocclassific ON itprocclassific."Category"=$1 AND itprocclassific."Subcategory"=$2 AND itprocclassific."Workflow"=(SELECT "Id" FROM "LookUp" WHERE "Code"='PM' AND "Type"='ITProcessClassification - Workflow' AND "Status"='A') AND itprocclassific."Active"=TRUE AND itprocclassific."Status"='A' WHERE pmtmpl."Status"='A' AND pmtmpl."State"=(SELECT "Id" FROM "LookUp" WHERE "Code"='Active' AND "Type"='WorkorderTmpl - State'); $_$; hDROP FUNCTION public.wf_problemmgt_load_workorders(category bigint, subcategory bigint, OUT id bigint); publicpostgresfalse200ZFUNCTION wf_problemmgt_load_workorders(category bigint, subcategory bigint, OUT id bigint)COMMENTCOMMENT ON FUNCTION public.wf_problemmgt_load_workorders(category bigint, subcategory bigint, OUT id bigint) IS 'TYPE: function'; publicpostgresfalse20661255233400Iwf_problemmgt_prepare_email(bigint, character varying, character varying)FUNCTION,CREATE FUNCTION public.wf_problemmgt_prepare_email(process_id bigint, mailtype character varying, email_status character varying, OUT emailid bigint) RETURNS bigint LANGUAGE plpgsql AS $$ DECLARE from_address VARCHAR; to_addresses VARCHAR; cc_addresses VARCHAR; bcc_addresses VARCHAR; subject VARCHAR; body VARCHAR; template_name VARCHAR; toaddressemail VARCHAR; ccaddressemail VARCHAR; bccaddressemail VARCHAR; proc_number VARCHAR; nextroleanalyst VARCHAR; nextrolespecialist VARCHAR; classificnotes VARCHAR; category VARCHAR; subcategory VARCHAR; proc_shortdescr VARCHAR; wo VARCHAR; analysis VARCHAR; diagnosis VARCHAR; cm_shortdescr VARCHAR; cm_urgency VARCHAR; url_page_server VARCHAR; url_page_portal VARCHAR; BEGIN -- calculate name template template_name = mailtype; IF LEFT(template_name, 28) = 'PM04-Assignment-ToSpecialist' THEN template_name = 'PM04-Assignment-ToSpecialist'; ELSEIF LEFT(template_name, 21) = 'PM04-Submit-ToAnalyst' THEN template_name = 'PM04-Submit-ToAnalyst'; END IF; -- extract fields of email --Retrieve email account and email template fields SELECT COALESCE(et."From", ''), COALESCE(et."To", ''), COALESCE(et."CC", ''), COALESCE(et."BCC", ''), COALESCE(et."Subject", ''), COALESCE(et."Body", '') INTO from_address, to_addresses, cc_addresses, bcc_addresses, subject, body FROM "_EmailTemplate" et LEFT JOIN "_EmailAccount" ea ON ea."Id" = et."Account" AND ea."Status" = 'A' WHERE et."Code" = template_name AND et."Status" = 'A'; -- retrieve pm data IF template_name='PM02-Classification-ToAnalyst' THEN SELECT coalesce(nra."Notes", nra."Email", ''), pm."Number", nra."Description", pm."ClassificNotes", cat."Description", scat."Description", pm."ShortDescr" INTO toaddressemail, proc_number, nextroleanalyst, classificnotes, category, subcategory, proc_shortdescr FROM "ProblemMgt" pm LEFT JOIN "Role" nra ON nra."Id"=pm."NextRoleAnalyst" AND nra."Status"='A' LEFT JOIN "ITProcCategory" cat ON cat."Id"=pm."Category" AND cat."Status"='A' LEFT JOIN "ITProcSubcategory" scat ON scat."Id"=pm."Subcategory" AND scat."Status"='A' WHERE pm."Status"='A' AND pm."Id"=process_id; ELSEIF template_name='PM04-Assignment-ToSpecialist' THEN SELECT coalesce(nrs."Notes", nrs."Email", ''), pm."Number", nrs."Description", pm."ClassificNotes", cat."Description", scat."Description", pm."ShortDescr", CASE WHEN mailtype = 'PM04-Assignment-ToSpecialist-01' THEN pm."WODescr01" WHEN mailtype = 'PM04-Assignment-ToSpecialist-02' THEN pm."WODescr02" WHEN mailtype = 'PM04-Assignment-ToSpecialist-03' THEN pm."WODescr03" WHEN mailtype = 'PM04-Assignment-ToSpecialist-04' THEN pm."WODescr04" WHEN mailtype = 'PM04-Assignment-ToSpecialist-05' THEN pm."WODescr05" WHEN mailtype = 'PM04-Assignment-ToSpecialist-06' THEN pm."WODescr06" WHEN mailtype = 'PM04-Assignment-ToSpecialist-07' THEN pm."WODescr07" WHEN mailtype = 'PM04-Assignment-ToSpecialist-08' THEN pm."WODescr08" WHEN mailtype = 'PM04-Assignment-ToSpecialist-09' THEN pm."WODescr09" WHEN mailtype = 'PM04-Assignment-ToSpecialist-10' THEN pm."WODescr10" END INTO toaddressemail, proc_number, nextrolespecialist, classificnotes, category, subcategory, proc_shortdescr, wo FROM "ProblemMgt" pm LEFT JOIN "Role" nrs ON CASE WHEN mailtype = 'PM04-Assignment-ToSpecialist-01' THEN nrs."Id"=pm."WORole1" WHEN mailtype = 'PM04-Assignment-ToSpecialist-02' THEN nrs."Id"=pm."WORole2" WHEN mailtype = 'PM04-Assignment-ToSpecialist-03' THEN nrs."Id"=pm."WORole3" WHEN mailtype = 'PM04-Assignment-ToSpecialist-04' THEN nrs."Id"=pm."WORole4" WHEN mailtype = 'PM04-Assignment-ToSpecialist-05' THEN nrs."Id"=pm."WORole5" WHEN mailtype = 'PM04-Assignment-ToSpecialist-06' THEN nrs."Id"=pm."WORole6" WHEN mailtype = 'PM04-Assignment-ToSpecialist-07' THEN nrs."Id"=pm."WORole7" WHEN mailtype = 'PM04-Assignment-ToSpecialist-08' THEN nrs."Id"=pm."WORole8" WHEN mailtype = 'PM04-Assignment-ToSpecialist-09' THEN nrs."Id"=pm."WORole9" WHEN mailtype = 'PM04-Assignment-ToSpecialist-10' THEN nrs."Id"=pm."WORole10" END AND nrs."Status"='A' LEFT JOIN "ITProcCategory" cat ON cat."Id"=pm."Category" AND cat."Status"='A' LEFT JOIN "ITProcSubcategory" scat ON scat."Id"=pm."Subcategory" AND scat."Status"='A' WHERE pm."Status"='A' AND pm."Id"=process_id; ELSEIF template_name='PM04-Submit-ToAnalyst' THEN SELECT coalesce(nra."Notes", nra."Email", ''), pm."Number", nrs."Description", pm."ClassificNotes", cat."Description", scat."Description", pm."ShortDescr", CASE WHEN mailtype = 'PM04-Submit-ToAnalyst-01' THEN pm."WODescr01" WHEN mailtype = 'PM04-Submit-ToAnalyst-02' THEN pm."WODescr02" WHEN mailtype = 'PM04-Submit-ToAnalyst-03' THEN pm."WODescr03" WHEN mailtype = 'PM04-Submit-ToAnalyst-04' THEN pm."WODescr04" WHEN mailtype = 'PM04-Submit-ToAnalyst-05' THEN pm."WODescr05" WHEN mailtype = 'PM04-Submit-ToAnalyst-06' THEN pm."WODescr06" WHEN mailtype = 'PM04-Submit-ToAnalyst-07' THEN pm."WODescr07" WHEN mailtype = 'PM04-Submit-ToAnalyst-08' THEN pm."WODescr08" WHEN mailtype = 'PM04-Submit-ToAnalyst-09' THEN pm."WODescr09" WHEN mailtype = 'PM04-Submit-ToAnalyst-10' THEN pm."WODescr10" END, CASE WHEN mailtype = 'PM04-Submit-ToAnalyst-01' THEN pm."Analysis01" WHEN mailtype = 'PM04-Submit-ToAnalyst-02' THEN pm."Analysis02" WHEN mailtype = 'PM04-Submit-ToAnalyst-03' THEN pm."Analysis03" WHEN mailtype = 'PM04-Submit-ToAnalyst-04' THEN pm."Analysis04" WHEN mailtype = 'PM04-Submit-ToAnalyst-05' THEN pm."Analysis05" WHEN mailtype = 'PM04-Submit-ToAnalyst-06' THEN pm."Analysis06" WHEN mailtype = 'PM04-Submit-ToAnalyst-07' THEN pm."Analysis07" WHEN mailtype = 'PM04-Submit-ToAnalyst-08' THEN pm."Analysis08" WHEN mailtype = 'PM04-Submit-ToAnalyst-09' THEN pm."Analysis09" WHEN mailtype = 'PM04-Submit-ToAnalyst-10' THEN pm."Analysis10" END, CASE WHEN mailtype = 'PM04-Submit-ToAnalyst-01' THEN pm."Diagnosis01" WHEN mailtype = 'PM04-Submit-ToAnalyst-02' THEN pm."Diagnosis02" WHEN mailtype = 'PM04-Submit-ToAnalyst-03' THEN pm."Diagnosis03" WHEN mailtype = 'PM04-Submit-ToAnalyst-04' THEN pm."Diagnosis04" WHEN mailtype = 'PM04-Submit-ToAnalyst-05' THEN pm."Diagnosis05" WHEN mailtype = 'PM04-Submit-ToAnalyst-06' THEN pm."Diagnosis06" WHEN mailtype = 'PM04-Submit-ToAnalyst-07' THEN pm."Diagnosis07" WHEN mailtype = 'PM04-Submit-ToAnalyst-08' THEN pm."Diagnosis08" WHEN mailtype = 'PM04-Submit-ToAnalyst-09' THEN pm."Diagnosis09" WHEN mailtype = 'PM04-Submit-ToAnalyst-10' THEN pm."Diagnosis10" END INTO toaddressemail, proc_number, nextrolespecialist, classificnotes, category, subcategory, proc_shortdescr, wo, analysis, diagnosis FROM "ProblemMgt" pm LEFT JOIN "Role" nra ON nra."Id"=pm."NextRoleAnalyst" AND nra."Status"='A' LEFT JOIN "Role" nrs ON CASE WHEN mailtype = 'PM04-Submit-ToAnalyst-01' THEN nrs."Id"=pm."WORole1" WHEN mailtype = 'PM04-Submit-ToAnalyst-02' THEN nrs."Id"=pm."WORole2" WHEN mailtype = 'PM04-Submit-ToAnalyst-03' THEN nrs."Id"=pm."WORole3" WHEN mailtype = 'PM04-Submit-ToAnalyst-04' THEN nrs."Id"=pm."WORole4" WHEN mailtype = 'PM04-Submit-ToAnalyst-05' THEN nrs."Id"=pm."WORole5" WHEN mailtype = 'PM04-Submit-ToAnalyst-06' THEN nrs."Id"=pm."WORole6" WHEN mailtype = 'PM04-Submit-ToAnalyst-07' THEN nrs."Id"=pm."WORole7" WHEN mailtype = 'PM04-Submit-ToAnalyst-08' THEN nrs."Id"=pm."WORole8" WHEN mailtype = 'PM04-Submit-ToAnalyst-09' THEN nrs."Id"=pm."WORole9" WHEN mailtype = 'PM04-Submit-ToAnalyst-10' THEN nrs."Id"=pm."WORole10" END AND nrs."Status"='A' LEFT JOIN "ITProcCategory" cat ON cat."Id"=pm."Category" AND cat."Status"='A' LEFT JOIN "ITProcSubcategory" scat ON scat."Id"=pm."Subcategory" AND scat."Status"='A' WHERE pm."Status"='A' AND pm."Id"=process_id; ELSEIF template_name='PM05-Submit-ToManager' THEN SELECT coalesce(su."Notes", su."Email", ''), pm."Number", pm."ClassificNotes", cat."Description", scat."Description", pm."ShortDescr", pm."AnalystDiagnosis" INTO toaddressemail, proc_number, classificnotes, category, subcategory, proc_shortdescr, diagnosis FROM "ProblemMgt" pm LEFT JOIN "User" su ON su."Id"=pm."StartUser" AND su."Status"='A' LEFT JOIN "Role" nra ON nra."Id"=pm."NextRoleAnalyst" AND nra."Status"='A' LEFT JOIN "ITProcCategory" cat ON cat."Id"=pm."Category" AND cat."Status"='A' LEFT JOIN "ITProcSubcategory" scat ON scat."Id"=pm."Subcategory" AND scat."Status"='A' WHERE pm."Status"='A' AND pm."Id"=process_id; ELSEIF template_name='PM09-Return-FromChange' THEN SELECT coalesce(su."Notes", su."Email", ''), pm."Number", pm."ShortDescr", pm."AnalystDiagnosis" INTO toaddressemail, proc_number, proc_shortdescr, cm_shortdescr FROM "ProblemMgt" pm LEFT JOIN "User" su ON su."Id"=pm."StartUser" AND su."Status"='A' WHERE pm."Status"='A' AND pm."Id"=process_id; END IF; url_page_server = (select "Value" FROM "Parameter" WHERE "Code" = 'Server-URL' and "Status"='A') || '#processes/ProblemMgt/instances/' || process_id; url_page_portal = (select "Value" FROM "Parameter" WHERE "Code" = 'Portal-URL' and "Status"='A') || '#page=my-requests&selected-item=' || process_id || '/'; -- mapping of fields into the template SELECT INTO to_addresses REPLACE(to_addresses, '{server:ToAddress}', COALESCE(toaddressemail, '')); SELECT INTO subject REPLACE(subject, '{server:Number}', COALESCE(proc_number, '')); SELECT INTO body REPLACE(body, '{server:Number}', COALESCE(proc_number, '')); SELECT INTO body REPLACE(body, '{server:ShortDescr}', COALESCE(proc_shortdescr, '')); SELECT INTO body REPLACE(body, '{server:NextRoleAnalyst}', COALESCE(nextroleanalyst, '')); SELECT INTO body REPLACE(body, '{server:NextRoleSpecialist}', COALESCE(nextrolespecialist, '')); SELECT INTO body REPLACE(body, '{server:ClassificNotes}', COALESCE(classificnotes, '')); SELECT INTO body REPLACE(body, '{server:Category}', COALESCE(category, '')); SELECT INTO body REPLACE(body, '{server:Subcategory}', COALESCE(subcategory, '')); SELECT INTO body REPLACE(body, '{server:WO}', COALESCE(wo, '')); SELECT INTO body REPLACE(body, '{server:Analysis}', COALESCE(analysis, '')); SELECT INTO body REPLACE(body, '{server:Diagnosis}', COALESCE(diagnosis, '')); SELECT INTO body REPLACE(body, '{server:CMShortDescr}', COALESCE(cm_shortdescr, '')); SELECT INTO body REPLACE(body, '{server:Parameter.Server-Url}', COALESCE(url_page_server, '')); SELECT INTO body REPLACE(body, '{server:Parameter.Portal-Url}', COALESCE(url_page_portal, '')); -- create an outgoing e-mail linked to the process --Generate email IF EXISTS (SELECT "Code" FROM "_EmailTemplate" WHERE "Code" = template_name AND "Status" = 'A') THEN INSERT INTO "Email" ("EmailStatus","FromAddress","ToAddresses","CcAddresses", "BccAddresses", "Subject","Content","Card","Delay","KeepSynchronization","PromptSynchronization") SELECT coalesce(nullif(email_status, ''), 'outgoing'), from_address, to_addresses, cc_addresses, bcc_addresses, subject, body, process_id, 0, false, false RETURNING "Id" INTO emailid; END IF; END; $$; DROP FUNCTION public.wf_problemmgt_prepare_email(process_id bigint, mailtype character varying, email_status character varying, OUT emailid bigint); publicpostgresfalse300FUNCTION wf_problemmgt_prepare_email(process_id bigint, mailtype character varying, email_status character varying, OUT emailid bigint)COMMENTCOMMENT ON FUNCTION public.wf_problemmgt_prepare_email(process_id bigint, mailtype character varying, email_status character varying, OUT emailid bigint) IS 'TYPE: function'; publicpostgresfalse206712552334025wf_reqfulfil_approver_suggemployee(character varying)FUNCTIONCREATE FUNCTION public.wf_reqfulfil_approver_suggemployee(number character varying, OUT employeeid bigint) RETURNS SETOF bigint LANGUAGE plpgsql AS $$ DECLARE nextouId bigint; BEGIN --raise notice 'INPUT: number: %' , number; select ou."Id" into nextouId from "ReqFulfil" rf join "ServiceRequest" sr on sr."Id" = rf."ServiceReq" and sr."Status" = 'A' join "OU" ou on sr."ApproverOU" = ou."Id" and ou."Status" = 'A' where rf."Number" = number and rf."Status" = 'A'; if(nextouId is null) then select e."OU" into nextouId from "ReqFulfil" rf join "Employee" e on e."Id" = rf."Requester" and e."Status" = 'A' where rf."Number" = number and rf."Status" = 'A'; end if; --raise notice 'INPUT: nextouId: %' , nextouId; if(nextouId is not null) then return query select e."Id" from "Employee" e join "Map_ManagerOU" map on map."IdObj1" = e."Id" and map."Status" = 'A' and map."IdObj2" = nextouId where e."Status" = 'A' union select e."Id" from "Employee" e join "Map_AdditionalManagerOU" map on map."IdObj1" = e."Id" and map."Status" = 'A' and map."IdObj2" = nextouId where e."Status" = 'A'; else end if; END; $$; jDROP FUNCTION public.wf_reqfulfil_approver_suggemployee(number character varying, OUT employeeid bigint); publicpostgresfalse400\FUNCTION wf_reqfulfil_approver_suggemployee(number character varying, OUT employeeid bigint)COMMENTCOMMENT ON FUNCTION public.wf_reqfulfil_approver_suggemployee(number character varying, OUT employeeid bigint) IS 'TYPE: function'; publicpostgresfalse206812552334035wf_reqfulfil_approver_suggoperator(character varying)FUNCTIONCREATE FUNCTION public.wf_reqfulfil_approver_suggoperator(number character varying, OUT userid bigint) RETURNS SETOF bigint LANGUAGE plpgsql AS $$ DECLARE nextroleId bigint; BEGIN --raise notice 'INPUT: number: %' , number; select r."Id" into nextroleId from "ReqFulfil" rf join "ServiceRequest" sr on sr."Id" = rf."ServiceReq" and sr."Status" = 'A' join "Role" r on sr."ApproverRole" = r."Id" and r."Status" = 'A' where rf."Number" = number and rf."Status" = 'A'; return query select u."Id" from "User" u join "Map_UserRole" map on map."IdObj1" = u."Id" and map."Status" = 'A' and map."IdObj2" = nextroleId where u."Status" = 'A' and not coalesce(u."Service", false); END; $$; fDROP FUNCTION public.wf_reqfulfil_approver_suggoperator(number character varying, OUT userid bigint); publicpostgresfalse500XFUNCTION wf_reqfulfil_approver_suggoperator(number character varying, OUT userid bigint)COMMENTCOMMENT ON FUNCTION public.wf_reqfulfil_approver_suggoperator(number character varying, OUT userid bigint) IS 'TYPE: function'; publicpostgresfalse20691255233404Pwf_reqfulfil_getactivitytime(timestamp with time zone, timestamp with time zone)FUNCTIONCREATE FUNCTION public.wf_reqfulfil_getactivitytime(date1 timestamp with time zone, date2 timestamp with time zone, OUT activitytime double precision) RETURNS double precision LANGUAGE plpgsql AS $_$ DECLARE i integer; j integer; qt1 decimal; qt2 decimal; qt3 decimal; daytimetable text[]; dayworktime decimal[]; holidays character varying[]; timetable character varying[]; BEGIN holidays = array (select split_part("LookUp"."Code" || '|', '|', 1) from "LookUp" where "LookUp"."Type" = 'Holidays' and "LookUp"."Status" = 'A' group by "LookUp"."Code" order by "LookUp"."Code"); timetable = array (select split_part("LookUp"."Notes" || '|', '|', 1) from "LookUp" where "LookUp"."Type" = 'Working hours' and "LookUp"."Status" = 'A' group by "LookUp"."Notes", "LookUp"."Code" order by "LookUp"."Code"); if $1 is null or $2 is null then activitytime = 0; else for i in 1 .. 7 loop -- initialize array with working hours dayworktime[i] = 0; daytimetable = string_to_array(timetable[i], ','); if daytimetable is null then continue; end if; for j in 1 .. array_upper(daytimetable, 1) loop dayworktime[i] = dayworktime[i] + extract(epoch from ((split_part(daytimetable[j], '-', 2) || ':00')::time - (split_part(daytimetable[j], '-', 1) || ':00')::time)) /*/ 3600*/; end loop; end loop; -- raise notice '%', dayworktime; qt1 = 0.0; -- calculate working time for the first day if timetable[date_part('dow', $1) + 1] is not null and not substr(replace($2::date::varchar, '-', ''), 5, 4) = any (holidays) then daytimetable = string_to_array(timetable[date_part('dow', $1) + 1], ','); for i in 1 .. array_upper(daytimetable, 1) loop if split_part(daytimetable[i], '-', 1)::time > $1::time then qt1 = qt1 + extract(epoch from split_part(daytimetable[i], '-', 2)::time - split_part(daytimetable[i], '-', 1)::time) /*/ 3600*/; elsif split_part(daytimetable[i], '-', 2)::time > $1::time then qt1 = qt1 + extract(epoch from split_part(daytimetable[i], '-', 2)::time - $1::time) /*/ 3600*/; end if; end loop; end if; -- calculate working time for the other days --select now()+ s.a * interval '1 day' from generate_series(1, 5, 1) as s(a) select into qt2 sum(dayworktime[date_part('dow', $1::date + s.a * interval '1 day') + 1]) from generate_series(1, ($2::date - $1::date)-1,1) as s(a) where not substr(replace(($1::date + s.a * interval '1 day')::varchar, '-', ''), 5, 4) = any (holidays); -- raise notice 'qt2 = %', qt2; qt3 = 0.0; -- calculate working time for the last day if timetable[date_part('dow', $2) + 1] is not null and not substr(replace($2::date::varchar, '-', ''), 5, 4) = any (holidays) then daytimetable = string_to_array(timetable[date_part('dow', $2) + 1], ','); for i in 1 .. array_upper(daytimetable, 1) loop if $2::time > split_part(daytimetable[i], '-', 2)::time then qt3 = qt3 + extract(epoch from split_part(daytimetable[i], '-', 2)::time - split_part(daytimetable[i], '-', 1)::time) /*/ 3600*/; elsif $2::time > split_part(daytimetable[i], '-', 1)::time then qt3 = qt3 + extract(epoch from $2::time - split_part(daytimetable[i], '-', 1)::time) /*/ 3600*/; end if; end loop; end if; -- raise notice 'qt3 = %', qt3; -- raise notice 'date1=% date2=% qt1=% qt2=% qt3=% totale=%', $1, $2, qt1, qt2, qt3, case when $1::date = $2::date then qt1 + qt3 - dayworktime[date_part('dow', $1)] else qt1 + coalesce(qt2, 0) + qt3 end; if $1::date = $2::date then activitytime = case when qt1 + qt3 - dayworktime[date_part('dow', $1) + 1] < 0.0 then 0.0 else qt1 + qt3 - dayworktime[date_part('dow', $1) + 1] end; else activitytime = qt1 + coalesce(qt2, 0.0) + qt3; end if; end if; END; $_$; DROP FUNCTION public.wf_reqfulfil_getactivitytime(date1 timestamp with time zone, date2 timestamp with time zone, OUT activitytime double precision); publicpostgresfalse600FUNCTION wf_reqfulfil_getactivitytime(date1 timestamp with time zone, date2 timestamp with time zone, OUT activitytime double precision)COMMENTCOMMENT ON FUNCTION public.wf_reqfulfil_getactivitytime(date1 timestamp with time zone, date2 timestamp with time zone, OUT activitytime double precision) IS 'TYPE: function'; publicpostgresfalse20711255233405wf_reqfulfil_load_wos(bigint)FUNCTIONCREATE FUNCTION public.wf_reqfulfil_load_wos(procid bigint, OUT "Number" integer, OUT "PrecWO" character varying, OUT "ActivityName" character varying, OUT "ActivityDescription" character varying, OUT "ExecutorRole" bigint, OUT "ExpectedTime" numeric, OUT "FormName" character varying, OUT "Condition" text, OUT "PreScript" text, OUT "PostScript" text) RETURNS SETOF record LANGUAGE plpgsql AS $$ BEGIN RETURN QUERY SELECT map."Order", map."PrecWO", tmpl."ActivityName", tmpl."ActivityDescription", tmpl."ExecutorRole", tmpl."ExpectedTime", tmpl."FormName", tmpl."Condition", tmpl."PreScript", tmpl."PostScript" FROM "ReqFulfilWOTmpl" tmpl JOIN "Map_ServiceRequestWOTmpl" map ON tmpl."Id" = map."IdObj2" AND map."Status" = 'A' JOIN "ReqFulfil" rf ON rf."ServiceReq" = map."IdObj1" AND rf."Id" = procid WHERE tmpl."Status" = 'A' ORDER BY map."Order"; END; $$; `DROP FUNCTION public.wf_reqfulfil_load_wos(procid bigint, OUT "Number" integer, OUT "PrecWO" character varying, OUT "ActivityName" character varying, OUT "ActivityDescription" character varying, OUT "ExecutorRole" bigint, OUT "ExpectedTime" numeric, OUT "FormName" character varying, OUT "Condition" text, OUT "PreScript" text, OUT "PostScript" text); publicpostgresfalse700RFUNCTION wf_reqfulfil_load_wos(procid bigint, OUT "Number" integer, OUT "PrecWO" character varying, OUT "ActivityName" character varying, OUT "ActivityDescription" character varying, OUT "ExecutorRole" bigint, OUT "ExpectedTime" numeric, OUT "FormName" character varying, OUT "Condition" text, OUT "PreScript" text, OUT "PostScript" text)COMMENTzCOMMENT ON FUNCTION public.wf_reqfulfil_load_wos(procid bigint, OUT "Number" integer, OUT "PrecWO" character varying, OUT "ActivityName" character varying, OUT "ActivityDescription" character varying, OUT "ExecutorRole" bigint, OUT "ExpectedTime" numeric, OUT "FormName" character varying, OUT "Condition" text, OUT "PreScript" text, OUT "PostScript" text) IS 'TYPE: function'; publicpostgresfalse20721255233406wf_reqfulfil_nextrole(character varying, character varying, character varying, character varying, character varying, character varying)FUNCTIONCREATE FUNCTION public.wf_reqfulfil_nextrole(procnum character varying, category character varying, subcategory character varying, action character varying, wftype character varying, currentuser character varying, OUT roleid bigint) RETURNS SETOF bigint LANGUAGE plpgsql AS $$ DECLARE categoryId bigint; subcategoryId bigint; actionId bigint; currentUserId bigint; assignedRoleId bigint; mustbecurrent boolean; isValid boolean; isAdministrator character varying; BEGIN --raise log 'INPUT: procnum %, category: %, subcategory: %, action: %, currentuser: %', procnum, category, subcategory, action, currentuser; select into assignedRoleId wf_getassignedrole(procnum); if (category!='null' and category!='') then select into categoryId c."Id" from "ITProcCategory" c where (c."Id"::varchar=category or c."Description"=category) and c."Status"='A'; end if; if (subcategory!='null' and subcategory!='') then select into subcategoryId sc."Id" from "ITProcSubcategory" sc where (sc."Id"::varchar=subcategory or sc."Description"=subcategory) and sc."Status"='A'; end if; if (action!='null' and action!='') then select into actionId, mustbecurrent a."Id" , case when ( (a."Code" in ('ManageStdReq', 'ManageReqInfo', 'Closure', 'StartCM', 'StartIM') and a."Type"='ReqFulfil - HDClassific Action') or (a."Code" in ('ManageReqInfo') and a."Type"='ReqFulfil - SPClassific Action') ) then true else false end from "LookUp" a where (a."Id"::varchar=action or a."Description"=action) and a."Status"='A'; end if; if (currentuser!='null' and currentuser!='') then select into currentUserId u."Id" from "User" u where (u."Id"::varchar=currentuser or u."Description"=currentuser) and u."Status"='A'; end if; --raise log ' categoryId:%, subcategoryId: %, actionId: %, mustbecurrent: %, currentrole: %', categoryId, subcategoryId, actionId, mustbecurrent,assignedRoleId; if(mustbecurrent) then select into isAdministrator "Type" from "Role" where "Id"=assignedRoleId; -- has the currentUser a role that has a valid classification for the selected category and subcategory? select into isValid count(*)>0 from "ITProcClassification" c join "LookUp" l1 on c."Workflow"=l1."Id" and l1."Status"='A' and l1."Code"=wftype join "ITProcCategory" p on p."Id"=c."Category" and p."Status"='A' join "ITProcSubcategory" sp on sp."Id"=c."Subcategory" and sp."Status"='A' where c."Status"='A' and c."Active" and ( (c."HDRole" = assignedRoleId and actionId in (select a."Id" from "LookUp" a where a."Type"='ReqFulfil - HDClassific Action')) or (c."SPRole" = assignedRoleId and actionId in (select a."Id" from "LookUp" a where a."Type"='ReqFulfil - SPClassific Action')) ) and c."Category"=categoryId and c."Subcategory"=subcategoryId; if(isValid or isAdministrator='admin') then return query select assignedRoleId; else return query select 0::bigint; end if; else return query select c."HDRole" from "ITProcClassification" c join "LookUp" l1 on c."Workflow"=l1."Id" and l1."Status"='A' and l1."Code"=wftype join "ITProcCategory" p on p."Id"=c."Category" and p."Status"='A' join "ITProcSubcategory" sp on sp."Id"=c."Subcategory" and sp."Status"='A' left join "LookUp" ahd on ahd."Type"='ReqFulfil - HDClassific Action' and ahd."Id"=actionId left join "LookUp" asp on asp."Type"='ReqFulfil - SPClassific Action' and asp."Id"=actionId where c."Status"='A' and c."Active" and ( ahd."Code" in ('EscalationHD') or asp."Code" in ('DeEscalationHD') ) and c."HDRole"<>assignedRoleId and c."Category"=categoryId and c."Subcategory"=subcategoryId union select c."SPRole" from "ITProcClassification" c join "LookUp" l1 on c."Workflow"=l1."Id" and l1."Status"='A' and l1."Code"=wftype join "ITProcCategory" p on p."Id"=c."Category" and p."Status"='A' join "ITProcSubcategory" sp on sp."Id"=c."Subcategory" and sp."Status"='A' left join "LookUp" ahd on ahd."Type"='ReqFulfil - HDClassific Action' and ahd."Id"=actionId left join "LookUp" asp on asp."Type"='ReqFulfil - SPClassific Action' and asp."Id"=actionId where c."Status"='A'and c."Active" and ( asp."Code" in ('EscalationSP') or ahd."Code" in ('EscalationSP') ) and c."SPRole"<>assignedRoleId and c."Category"=categoryId and c."Subcategory"=subcategoryId; end if; --raise log ' roleid:%',roleid; END; $$; DROP FUNCTION public.wf_reqfulfil_nextrole(procnum character varying, category character varying, subcategory character varying, action character varying, wftype character varying, currentuser character varying, OUT roleid bigint); publicpostgresfalse1255233407wf_reqfulfil_number()FUNCTIONCREATE FUNCTION public.wf_reqfulfil_number(OUT number character varying) RETURNS character varying LANGUAGE plpgsql AS $$ BEGIN number = lpad(nextval('reqfulfil_seq')::text,6,'0'); END; $$; HDROP FUNCTION public.wf_reqfulfil_number(OUT number character varying); publicpostgresfalse800:FUNCTION wf_reqfulfil_number(OUT number character varying)COMMENTbCOMMENT ON FUNCTION public.wf_reqfulfil_number(OUT number character varying) IS 'TYPE: function'; publicpostgresfalse20741255233408dwf_reqfulfil_prepare_email(bigint, character varying, character varying, integer, character varying)FUNCTIONCREATE FUNCTION public.wf_reqfulfil_prepare_email(process_id bigint, proc_number character varying, template_name character varying, workorder integer, email_status character varying, OUT emailid bigint) RETURNS bigint LANGUAGE plpgsql AS $$ DECLARE from_address VARCHAR; to_addresses VARCHAR; cc_addresses VARCHAR; bcc_addresses VARCHAR; subject VARCHAR; body VARCHAR; language_config VARCHAR; proc_shortdescr VARCHAR; proc_extdescr VARCHAR; reqtype_code VARCHAR; area_descr VARCHAR; ser_descr VARCHAR; sercat_descr VARCHAR; priority_descr VARCHAR; urgency_descr VARCHAR; requester_descr VARCHAR; requester_email VARCHAR; helpdesk_descr VARCHAR; helpdesk_email VARCHAR; url_page_server VARCHAR; url_page_portal VARCHAR; wo_name VARCHAR; wo_descr VARCHAR; wo_time VARCHAR; wo_recipient VARCHAR; BEGIN IF (SELECT "Template" FROM "_Templates" WHERE "Name" = 'Email-Lang') IN ('en', 'it') THEN language_config = (SELECT "Template" FROM "_Templates" WHERE "Name" = 'Email-Lang'); ELSIF coalesce(_cm3_system_config_get('org.cmdbuild.core.language'), '') IN ('en', 'it') THEN language_config = _cm3_system_config_get('org.cmdbuild.core.language'); ELSE language_config = 'en'; END IF; --Retrieve email account and email template fields SELECT COALESCE(et."From", ''), COALESCE(et."To", ''), COALESCE(et."CC", ''), COALESCE(et."BCC", ''), COALESCE(et."Subject", ''), COALESCE(et."Body", '') INTO from_address, to_addresses, cc_addresses, bcc_addresses, subject, body FROM "_EmailTemplate" et LEFT JOIN "_EmailAccount" ea ON ea."Id" = et."Account" AND ea."Status" = 'A' WHERE et."Code" = template_name AND et."Status" = 'A'; --retrieve rf reqtype SELECT reqtype."Code" INTO reqtype_code FROM "ReqFulfil" proc LEFT JOIN "LookUp" reqtype ON reqtype."Id" = proc."RequestType" WHERE proc."Id" = process_id; -- retrieve rf data IF reqtype_code = 'Information' THEN SELECT proc."ShortDescr", proc."ExtDescr", area."Description", ser."Description", sercat."Description", LOWER(COALESCE(tr_urgency."Value", urgency."Description")), requester."Description", requester."Email", hd."Description", hd."Email" INTO proc_shortdescr, proc_extdescr, area_descr, ser_descr, sercat_descr, urgency_descr, requester_descr, requester_email, helpdesk_descr, helpdesk_email FROM "ReqFulfil" proc LEFT JOIN "Employee" requester ON proc."Requester" = requester."Id" LEFT JOIN "LookUp" area ON proc."Area" = area."Id" LEFT JOIN "Service" ser ON ser."Id"=proc."Service" LEFT JOIN "ServiceCategory" sercat ON sercat."Id"=ser."Category" LEFT JOIN "ITProcArea" itparea ON itparea."Area"=area."Id" LEFT JOIN "LookUp" urgency ON proc."Urgency" = urgency."Id" LEFT JOIN "Role" hd ON hd."Id"=itparea."Role" LEFT JOIN "_Translation" tr_urgency ON tr_urgency."Code" = format('lookup.%s.%s.description', urgency."Type", urgency."Code") AND tr_urgency."Lang" = language_config AND tr_urgency."Status" = 'A' WHERE proc."Id" = process_id; ELSIF reqtype_code = 'Service' THEN SELECT proc."ShortDescr", proc."ExtDescr", ser."Description", sercat."Description", LOWER(COALESCE(tr_urgency."Value", urgency."Description")), requester."Description", requester."Email", hd."Description", hd."Email" INTO proc_shortdescr, proc_extdescr, ser_descr, sercat_descr, urgency_descr, requester_descr, requester_email, helpdesk_descr, helpdesk_email FROM "ReqFulfil" proc LEFT JOIN "Employee" requester ON proc."Requester" = requester."Id" LEFT JOIN "LookUp" area ON proc."Area" = area."Id" LEFT JOIN "Service" ser ON ser."Id"=proc."Service" LEFT JOIN "ServiceCategory" sercat ON sercat."Id"=ser."Category" LEFT JOIN "LookUp" urgency ON proc."Urgency" = urgency."Id" LEFT JOIN "Role" hd ON hd."Id"=sercat."HDRole" LEFT JOIN "_Translation" tr_urgency ON tr_urgency."Code" = format('lookup.%s.%s.description', urgency."Type", urgency."Code") AND tr_urgency."Lang" = language_config AND tr_urgency."Status" = 'A' WHERE proc."Id" = process_id; END IF; url_page_server = (select "Value" FROM "Parameter" WHERE "Code" = 'Server-URL' and "Status"='A') || '#processes/ReqFulfil/instances/' || process_id; url_page_portal = (select "Value" FROM "Parameter" WHERE "Code" = 'Portal-URL' and "Status"='A') || '#page=my-requests&selected-item=' || process_id || '/'; -- mapping of fields into the template SELECT INTO to_addresses REPLACE(to_addresses, '{server:Helpdesk.Email}', COALESCE(helpdesk_email, '')); SELECT INTO to_addresses REPLACE(to_addresses, '{server:Requester.Email}', COALESCE(requester_email, '')); SELECT INTO subject REPLACE(subject, '{server:Number}', COALESCE(proc_number, '')); SELECT INTO body REPLACE(body, '{server:Number}', COALESCE(proc_number, '')); SELECT INTO body REPLACE(body, '{server:ShortDescr}', COALESCE(proc_shortdescr, '')); SELECT INTO body REPLACE(body, '{server:Area.Description}', COALESCE(area_descr, '')); SELECT INTO body REPLACE(body, '{server:Service.Description}', COALESCE(ser_descr, '')); SELECT INTO body REPLACE(body, '{server:ServiceReq.Description}', COALESCE(sercat_descr, '')); SELECT INTO body REPLACE(body, '{server:Requester.Description}', COALESCE(requester_descr, '')); SELECT INTO body REPLACE(body, '{server:ExtDescr}', COALESCE(proc_extdescr, '')); SELECT INTO body REPLACE(body, '{server:Urgency.Description}', COALESCE(urgency_descr, '')); SELECT INTO body REPLACE(body, '{server:Parameter.Server-Url}', COALESCE(url_page_server, '')); SELECT INTO body REPLACE(body, '{server:Parameter.Portal-Url}', COALESCE(url_page_portal, '')); IF workorder is not null THEN EXECUTE format('select "ActivityName'||workorder||'","ActivityDescription'||workorder||'","ExpectedTime'||workorder||'"::varchar,g."Email" from "ReqFulfil" rf JOIN "Role" g ON g."Id"=rf."WORole'||workorder||'" where rf."Id"='||process_id) INTO wo_name,wo_descr,wo_time,wo_recipient ; SELECT INTO body REPLACE(body, '{server:ActivityName}', COALESCE(wo_name, '')); SELECT INTO body REPLACE(body, '{server:ActivityDescription}', COALESCE(wo_descr, '')); SELECT INTO body REPLACE(body, '{server:ExpectedTime}', COALESCE(wo_time, '')); SELECT INTO to_addresses REPLACE(to_addresses, '{server:ToAddress}', COALESCE(wo_recipient, '')); END IF; --RAISE NOTICE 'workorder %',wo_descr; --RAISE NOTICE 'to: %, subject: %, body: %',to_addresses,subject,body; -- create an outgoing e-mail linked to the process --Generate email IF EXISTS (SELECT "Code" FROM "_EmailTemplate" WHERE "Code" = template_name AND "Status" = 'A') THEN INSERT INTO "Email" ("EmailStatus","FromAddress","ToAddresses","CcAddresses", "BccAddresses", "Subject","Content","Card","Delay","KeepSynchronization","PromptSynchronization") SELECT coalesce(nullif(email_status, ''), 'outgoing'), from_address, to_addresses, cc_addresses, bcc_addresses, subject, body, process_id, 0, false, false RETURNING "Id" INTO emailid; END IF; END; $$; DROP FUNCTION public.wf_reqfulfil_prepare_email(process_id bigint, proc_number character varying, template_name character varying, workorder integer, email_status character varying, OUT emailid bigint); publicpostgresfalse900FUNCTION wf_reqfulfil_prepare_email(process_id bigint, proc_number character varying, template_name character varying, workorder integer, email_status character varying, OUT emailid bigint)COMMENTCOMMENT ON FUNCTION public.wf_reqfulfil_prepare_email(process_id bigint, proc_number character varying, template_name character varying, workorder integer, email_status character varying, OUT emailid bigint) IS 'TYPE: function'; publicpostgresfalse20751255233410Fwf_reqfulfil_rf01_email_to_helpdesk(bigint, character varying, bigint)FUNCTION CREATE FUNCTION public.wf_reqfulfil_rf01_email_to_helpdesk(processid bigint, number character varying, helpdeskid bigint, OUT toaddress character varying, OUT fromaddress character varying, OUT subject character varying, OUT body text) RETURNS record LANGUAGE plpgsql AS $$ DECLARE shortDescr varchar; serviceDescr varchar; serviceReqDescr varchar; areaDescr varchar; extDescr varchar; requesterDescr varchar; urgencyDescr varchar; hdDescr varchar; url varchar; BEGIN SELECT r."Email", r."Description" INTO toaddress, hdDescr FROM "Role" r WHERE r."Id" = helpdeskid; SELECT "Address" INTO fromaddress FROM "_EmailAccount" WHERE "Code" IN (select _cm3_system_config_get('org.cmdbuild.email.accountDefault')) AND "Status" = 'A'; SELECT 'Request Fulfilment n.' || number || ' - Registered' INTO subject; SELECT rf."ShortDescr", s."Description", sr."Description", a."Description", rf."ExtDescr", r."Description", u."Description" INTO shortDescr, serviceDescr, serviceReqDescr, areaDescr, extDescr, requesterDescr, urgencyDescr FROM "ReqFulfil" AS rf LEFT JOIN "LookUp" a ON rf."Area" = a."Id" LEFT JOIN "Service" s ON rf."Service" = s."Id" LEFT JOIN "ServiceRequest" sr ON rf."ServiceReq" = sr."Id" LEFT JOIN "Employee" r ON rf."Requester" = r."Id" LEFT JOIN "LookUp" u ON rf."Urgency" = u."Id" WHERE rf."Id" = processid; SELECT "Value" INTO url FROM "Parameter" WHERE "Status" = 'A' AND "Code" = 'Server-URL'; url = url || '#processes/ReqFulfil/instances/' || processid || '/'; SELECT '

    The request ' || number || ' has been registered and assigned to ' || hdDescr || '.

    ' '

    Request data:

    • Number and summary: ' || number || '- ' || shortDescr || '
    • ' || coalesce('
    • Area : ' || areaDescr || '
    • ', '') || coalesce('
    • Service : ' || serviceDescr || '
    • ', '') || coalesce('
    • Service request: ' || serviceReqDescr || '
    • ', '') || coalesce('
    • Description: ' || extDescr || '
    • ', '') || coalesce('
    • Requester: ' || requesterDescr || '
    • ', '') || coalesce('
    • Urgency: ' || urgencyDescr || '
    • ', '') || '

     

    This message was generated automatically by CMDBuild - Ready2Use
    For more information and to contribute to the fulfilment of this request, please click here.

    ' INTO body; END; $$; DROP FUNCTION public.wf_reqfulfil_rf01_email_to_helpdesk(processid bigint, number character varying, helpdeskid bigint, OUT toaddress character varying, OUT fromaddress character varying, OUT subject character varying, OUT body text); publicpostgresfalse:00FUNCTION wf_reqfulfil_rf01_email_to_helpdesk(processid bigint, number character varying, helpdeskid bigint, OUT toaddress character varying, OUT fromaddress character varying, OUT subject character varying, OUT body text)COMMENTCOMMENT ON FUNCTION public.wf_reqfulfil_rf01_email_to_helpdesk(processid bigint, number character varying, helpdeskid bigint, OUT toaddress character varying, OUT fromaddress character varying, OUT subject character varying, OUT body text) IS 'TYPE: function'; publicpostgresfalse20761255233411?wf_reqfulfil_rf01_email_to_requester(bigint, character varying)FUNCTIONO CREATE FUNCTION public.wf_reqfulfil_rf01_email_to_requester(processid bigint, number character varying, OUT toaddress character varying, OUT fromaddress character varying, OUT subject character varying, OUT body text) RETURNS record LANGUAGE plpgsql AS $$ DECLARE shortDescr varchar; serviceDescr varchar; serviceReqDescr varchar; areaDescr varchar; extDescr varchar; requesterDescr varchar; urgencyDescr varchar; url varchar; BEGIN SELECT "Email" INTO toaddress FROM "Employee" e JOIN "ReqFulfil" rf ON rf."Requester" = e."Id" AND rf."Id" = processid AND rf."Status" = 'A' WHERE e."Status" = 'A'; SELECT "Address" INTO fromaddress FROM "_EmailAccount" WHERE "Code" IN (select _cm3_system_config_get('org.cmdbuild.email.accountDefault')) AND "Status" = 'A'; SELECT 'Request Fulfilment n.' || number || ' - Registered' INTO subject; SELECT rf."ShortDescr", s."Description", sr."Description", a."Description", rf."ExtDescr", r."Description" INTO shortDescr, serviceDescr, serviceReqDescr, areaDescr, extDescr, requesterDescr FROM "ReqFulfil" AS rf LEFT JOIN "LookUp" a ON rf."Area" = a."Id" LEFT JOIN "Service" s ON rf."Service" = s."Id" LEFT JOIN "ServiceRequest" sr ON rf."ServiceReq" = sr."Id" LEFT JOIN "Employee" r ON rf."Requester" = r."Id" WHERE rf."Id" = processid; SELECT "Value" INTO url FROM "Parameter" WHERE "Status" = 'A' AND "Code" = 'Portal-URL'; url = url || '#page=my-requests&selected-item=' || processid; SELECT '

    The request ' || number || ' has been registered.

    Request data:

    • Number and summary: ' || number || '- ' || shortDescr || '
    • ' || coalesce('
    • Area : ' || areaDescr || '
    • ', '') || coalesce('
    • Service : ' || serviceDescr || '
    • ', '') || coalesce('
    • Service request: ' || serviceReqDescr || '
    • ', '') || coalesce('
    • Description: ' || extDescr || '
    • ', '') || coalesce('
    • Requester: ' || requesterDescr || '
    • ', '') || coalesce('
    • Urgency: ' || urgencyDescr || '
    • ', '') || '

     

    This message was generated automatically by CMDBuild - Ready2Use, please don''t change the subject in case of reply.
    For more information and to contribute to the fulfilment of this request, please click here.

    ' INTO body; END; $$; DROP FUNCTION public.wf_reqfulfil_rf01_email_to_requester(processid bigint, number character varying, OUT toaddress character varying, OUT fromaddress character varying, OUT subject character varying, OUT body text); publicpostgresfalse;00FUNCTION wf_reqfulfil_rf01_email_to_requester(processid bigint, number character varying, OUT toaddress character varying, OUT fromaddress character varying, OUT subject character varying, OUT body text)COMMENTCOMMENT ON FUNCTION public.wf_reqfulfil_rf01_email_to_requester(processid bigint, number character varying, OUT toaddress character varying, OUT fromaddress character varying, OUT subject character varying, OUT body text) IS 'TYPE: function'; publicpostgresfalse20771255233412pwf_reqfulfil_rf05_email_portal_approval(bigint, character varying, character varying, character varying, bigint)FUNCTIONCREATE FUNCTION public.wf_reqfulfil_rf05_email_portal_approval(processid bigint, templatename character varying, approvalnotes character varying, approvalaction character varying, helpdeskid bigint, OUT toaddress character varying, OUT fromaddress character varying, OUT subject character varying, OUT body text) RETURNS record LANGUAGE plpgsql AS $$ DECLARE hdEmail varchar; hdDescr varchar; worEmail varchar; worDescr varchar; accountid bigint; rf_shortdescr varchar; rf_number varchar; rf_service varchar; rf_servicereq varchar; rf_extdescr varchar; rf_requester varchar; rf_urgency varchar; rf_lasthelpdesk bigint; url varchar; mailmap map[]; BEGIN -- get template data SELECT coalesce(t."To",''), coalesce(t."Subject",''), coalesce(t."Body",''), t."Account" INTO toaddress, subject, body, accountid FROM "_EmailTemplate" t WHERE "Status"='A' AND "Code"=templatename; -- get wo reviewer group data SELECT coalesce(r."Email",''), coalesce(r."Description",'') INTO worEmail, worDescr FROM "Role" r WHERE r."Id" = helpdeskid; -- get from address SELECT "Address" INTO fromaddress FROM "_EmailAccount" WHERE "Id"=accountid AND "Status" = 'A'; -- get process data SELECT rf."ShortDescr", rf."Number", s."Description", sr."Description", rf."ExtDescr", r."Description", u."Description", rf."LastHelpdesk" INTO rf_shortdescr, rf_number, rf_service, rf_servicereq, rf_extdescr, rf_requester, rf_urgency, rf_lasthelpdesk FROM "ReqFulfil" AS rf LEFT JOIN "Service" s ON rf."Service" = s."Id" LEFT JOIN "ServiceRequest" sr ON rf."ServiceReq" = sr."Id" LEFT JOIN "Employee" r ON rf."Requester" = r."Id" LEFT JOIN "LookUp" u ON rf."Urgency" = u."Id" WHERE rf."Id" = processid; -- get hd group data SELECT coalesce(r."Email",''), coalesce(r."Description",'') INTO hdEmail, hdDescr FROM "Role" r WHERE r."Id" = rf_lasthelpdesk; -- get url data SELECT "Value" INTO url FROM "Parameter" WHERE "Status" = 'A' AND "Code" = 'Server-URL'; url = url || '#processes/ReqFulfil/instances/' || processid || '/'; -- mail parser mailmap = null; mailmap = array(SELECT ('{server:Number}',rf_number)::map); mailmap = mailmap || array(SELECT ('{cql:queryRichiedente.Description}',rf_requester)::map); mailmap = mailmap || array(SELECT ('{client:ApprovalNotes}',coalesce(approvalnotes,''))::map); mailmap = mailmap || array(SELECT ('{server:Urgency.Description}',coalesce(rf_urgency,''))::map); mailmap = mailmap || array(SELECT ('{server:Requester.Description}',coalesce(rf_requester,''))::map); mailmap = mailmap || array(SELECT ('{server:ExtDescr}', coalesce(rf_extdescr,''))::map); mailmap = mailmap || array(SELECT ('{server:ServiceReq.Description}',coalesce(rf_servicereq,''))::map); mailmap = mailmap || array(SELECT ('{server:Service.Description}',coalesce(rf_service,''))::map); mailmap = mailmap || array(SELECT ('{server:ShortDescr}',coalesce(rf_shortdescr,''))::map); mailmap = mailmap || array(SELECT ('{js:RF05-PortalApproval-ToHelpdesk-url}',coalesce(url,''))::map); mailmap = mailmap || array(SELECT ('{js:RF05-PortalApproval-ToWOReviewer-url}',coalesce(url,''))::map); mailmap = mailmap || array(SELECT ('{js:RF05-PortalApproval-ToHelpdesk-outcome}',coalesce((case when approvalaction ilike 'approve' then 'approved' else 'rejected' end),''))::map); mailmap = mailmap || array(SELECT ('{cql:RF05-PortalApproval-ToHelpdesk-dstRole.Email}',coalesce(hdEmail,''))::map); mailmap = mailmap || array(SELECT ('{cql:RF05-PortalApproval-ToWOReviewer-dstRole.Email}',coalesce(worEmail,''))::map); toaddress = wf_mailparser(toaddress,mailmap); --ccaddress = wf_mailparser(ccaddress,mailmap); --bccaddress = wf_mailparser(bccaddress,mailmap); subject = wf_mailparser(subject,mailmap); body = wf_mailparser(body,mailmap); END; $$; 8DROP FUNCTION public.wf_reqfulfil_rf05_email_portal_approval(processid bigint, templatename character varying, approvalnotes character varying, approvalaction character varying, helpdeskid bigint, OUT toaddress character varying, OUT fromaddress character varying, OUT subject character varying, OUT body text); publicpostgresfalse<00*FUNCTION wf_reqfulfil_rf05_email_portal_approval(processid bigint, templatename character varying, approvalnotes character varying, approvalaction character varying, helpdeskid bigint, OUT toaddress character varying, OUT fromaddress character varying, OUT subject character varying, OUT body text)COMMENTRCOMMENT ON FUNCTION public.wf_reqfulfil_rf05_email_portal_approval(processid bigint, templatename character varying, approvalnotes character varying, approvalaction character varying, helpdeskid bigint, OUT toaddress character varying, OUT fromaddress character varying, OUT subject character varying, OUT body text) IS 'TYPE: function'; publicpostgresfalse20781255233413Uwf_reqfulfil_srappr_nextrole(character varying, character varying, character varying)FUNCTIONCREATE FUNCTION public.wf_reqfulfil_srappr_nextrole(action character varying, servicereq character varying, currentrole character varying, OUT roleid bigint) RETURNS SETOF bigint LANGUAGE plpgsql AS $$ DECLARE servicereqId bigint; actionId bigint; currentRoleId bigint; mustbecurrent boolean; isValid boolean; approvalType character varying; BEGIN --raise notice 'INPUT: servicereq: %, action: %, currentrole: %' , servicereq, action, currentrole; if (servicereq !='null' and servicereq !='') then select into servicereqId sr."Id" from "ServiceRequest" sr where (sr."Id"::varchar=servicereq or sr."Description"=servicereq) and sr."Status"='A'; select into approvalType l."Code" from "ServiceRequest" sr join "LookUp" l on sr."ApprovalType" = l."Id" where sr."Id" = servicereqId; end if; if (action!='null' and action!='') then select into actionId a."Id" from "LookUp" a where (a."Id"::varchar=action or a."Description"=action) and a."Status"='A'; end if; if (currentrole != 'null' and currentrole != '') then select into currentRoleId r."Id" from "Role" r where (r."Id"::varchar=currentrole or r."Description"=currentrole) and r."Status"='A'; end if; --raise notice 'servicereqId:%, approvalType:%, actionId: %, currentrole: %', servicereqId, approvalType, actionid, currentRoleId; --raise notice 'is action null? % ' ,(actionId is null); if(actionid is null) then return query select 0::bigint; -- action not filled yet, leave the field blank elseif (actionid = (select "Id" from "LookUp" where "Type" = 'ReqFulfil - Approval Action' and "Code" ilike '%approve%')) then return query select coalesce("WOReviewer", currentRoleId) from "ServiceRequest" where "Id" = servicereqId; elseif (actionid = (select "Id" from "LookUp" where "Type" = 'ReqFulfil - Approval Action' and "Code" ilike '%reject%')) then return query select currentRoleId; else return query select 0::bigint; end if; END; $$; DROP FUNCTION public.wf_reqfulfil_srappr_nextrole(action character varying, servicereq character varying, currentrole character varying, OUT roleid bigint); publicpostgresfalse=00FUNCTION wf_reqfulfil_srappr_nextrole(action character varying, servicereq character varying, currentrole character varying, OUT roleid bigint)COMMENTCOMMENT ON FUNCTION public.wf_reqfulfil_srappr_nextrole(action character varying, servicereq character varying, currentrole character varying, OUT roleid bigint) IS 'TYPE: function'; publicpostgresfalse2079 12552334141wf_reqfulfil_srapproval_suggop(character varying)FUNCTIONCREATE FUNCTION public.wf_reqfulfil_srapproval_suggop(nextrole character varying, OUT userid bigint) RETURNS SETOF bigint LANGUAGE plpgsql AS $$ DECLARE nextroleId bigint; isguest boolean; BEGIN --raise notice 'INPUT: nextrole: %' , nextrole; if (nextrole !='null' and nextrole !='') then select r."Id", (r."Code" ilike 'guest') into nextroleId, isguest from "Role" r where (r."Id"::varchar=nextrole or r."Description"=nextrole) and r."Status"='A'; end if; --raise notice 'nextroleId:%', nextroleId; if(nextroleId is null or isguest) then return query select 0::bigint; -- action not filled yet, leave the field blank else return query select u."Id" from "User" u join "Map_UserRole" map on map."IdObj1" = u."Id" and map."Status" = 'A' where map."IdObj2" = nextroleId and u."Status" = 'A' and not coalesce(u."Service", false); end if; END; $$; dDROP FUNCTION public.wf_reqfulfil_srapproval_suggop(nextrole character varying, OUT userid bigint); publicpostgresfalse>00VFUNCTION wf_reqfulfil_srapproval_suggop(nextrole character varying, OUT userid bigint)COMMENT~COMMENT ON FUNCTION public.wf_reqfulfil_srapproval_suggop(nextrole character varying, OUT userid bigint) IS 'TYPE: function'; publicpostgresfalse2080!1255233415Zwf_reqfulfil_srclassific_nextrole(character varying, character varying, character varying)FUNCTION CREATE FUNCTION public.wf_reqfulfil_srclassific_nextrole(action character varying, servicereq character varying, currentrole character varying, OUT roleid bigint) RETURNS SETOF bigint LANGUAGE plpgsql AS $$ DECLARE servicereqId bigint; actionId bigint; currentRoleId bigint; mustbecurrent boolean; isValid boolean; isAdministrator character varying; approvalType character varying; BEGIN --raise notice 'INPUT: servicereq: %, action: %, currentrole: %' , servicereq, action, currentrole; if (servicereq !='null' and servicereq !='') then select into servicereqId sr."Id" from "ServiceRequest" sr where (sr."Id"::varchar=servicereq or sr."Description"=servicereq) and sr."Status"='A'; select into approvalType l."Code" from "ServiceRequest" sr join "LookUp" l on sr."ApprovalType" = l."Id" where sr."Id" = servicereqId; end if; if (action!='null' and action!='') then select into actionId, mustbecurrent a."Id" , (case when (a."Code" in ('Closure', 'StartCM', 'StartIM') and a."Type"='ReqFulfil - SRClassific Action') then true else false end) from "LookUp" a where (a."Id"::varchar=action or a."Description"=action) and a."Status"='A'; end if; if (currentrole != 'null' and currentrole != '') then select into currentRoleId r."Id" from "Role" r where (r."Id"::varchar=currentrole or r."Description"=currentrole) and r."Status"='A'; end if; --raise notice 'servicereqId:%, approvalType:%, actionId: %, mustbecurrent: %, currentrole: %', servicereqId, approvalType, actionid, mustbecurrent,currentRoleId; --raise notice 'is action null? % ' ,(actionId is null); if(actionid is null) then return query select 0::bigint; -- action not filled yet, leave the field blank ELSEIF mustbecurrent then select into isAdministrator "Type" from "Role" where "Id"=currentRoleId; -- the current helpdesk cannot be invalid for current service req isValid = true; --raise notice 'isValid:%, isAdministrator:%',isValid,isAdministrator; if(isValid or isAdministrator = 'admin') then return query select currentRoleId; else return query select 0::bigint; end if; ELSE IF (approvalType ilike '%IT%') then return query select "ApproverRole" from "ServiceRequest" where "Id" = servicereqId; elseif (approvalType ilike '%OU%' OR approvalType ilike '%manager%') then return query select "Id" from "Role" where "Code" ilike 'Guest' and "Status" = 'A'; elseif (approvalType ilike '%none%') then return query select coalesce("WOReviewer", currentRoleId) from "ServiceRequest" where "Id" = servicereqId; end if; end if; END; $$; DROP FUNCTION public.wf_reqfulfil_srclassific_nextrole(action character varying, servicereq character varying, currentrole character varying, OUT roleid bigint); publicpostgresfalse?00FUNCTION wf_reqfulfil_srclassific_nextrole(action character varying, servicereq character varying, currentrole character varying, OUT roleid bigint)COMMENTCOMMENT ON FUNCTION public.wf_reqfulfil_srclassific_nextrole(action character varying, servicereq character varying, currentrole character varying, OUT roleid bigint) IS 'TYPE: function'; publicpostgresfalse2081"12552334162wf_reqfulfil_srclassific_suggop(character varying)FUNCTIONCREATE FUNCTION public.wf_reqfulfil_srclassific_suggop(nextrole character varying, OUT userid bigint) RETURNS SETOF bigint LANGUAGE plpgsql AS $$ DECLARE nextroleId bigint; isguest boolean; BEGIN --raise notice 'INPUT: nextrole: %' , nextrole; if (nextrole !='null' and nextrole !='') then select r."Id", (r."Code" ilike 'guest') into nextroleId, isguest from "Role" r where (r."Id"::varchar=nextrole or r."Description"=nextrole) and r."Status"='A'; end if; --raise notice 'nextroleId:%', nextroleId; -- nextroleId is null: action not filled yet, leave the field blank -- is guest: don't want to see the guest user as operator, leave the field blank if(nextroleId is null or isguest) then return query select 0::bigint; else return query select u."Id" from "User" u join "Map_UserRole" map on map."IdObj1" = u."Id" and map."Status" = 'A' where map."IdObj2" = nextroleId and u."Status" = 'A' and not coalesce(u."Service", false); end if; END; $$; eDROP FUNCTION public.wf_reqfulfil_srclassific_suggop(nextrole character varying, OUT userid bigint); publicpostgresfalse@00WFUNCTION wf_reqfulfil_srclassific_suggop(nextrole character varying, OUT userid bigint)COMMENTCOMMENT ON FUNCTION public.wf_reqfulfil_srclassific_suggop(nextrole character varying, OUT userid bigint) IS 'TYPE: function'; publicpostgresfalse2082#12552334173wf_reqfulfil_srworevision_suggop(character varying)FUNCTIONCREATE FUNCTION public.wf_reqfulfil_srworevision_suggop(lasthelpdesk character varying, OUT userid bigint) RETURNS SETOF bigint LANGUAGE plpgsql AS $$ DECLARE lastHelpdeskId bigint; BEGIN --raise notice 'INPUT: lasthelpdesk: %' , lasthelpdesk; if (lasthelpdesk !='null' and lasthelpdesk !='') then select r."Id" into lastHelpdeskId from "Role" r where (r."Id"::varchar=lasthelpdesk or r."Description"=lasthelpdesk) and r."Status"='A'; end if; return query select u."Id" from "User" u join "Map_UserRole" map on map."IdObj1" = u."Id" and map."Status" = 'A' where map."IdObj2" = lastHelpdeskId and u."Status" = 'A' and not coalesce(u."Service", false); END; $$; jDROP FUNCTION public.wf_reqfulfil_srworevision_suggop(lasthelpdesk character varying, OUT userid bigint); publicpostgresfalseA00\FUNCTION wf_reqfulfil_srworevision_suggop(lasthelpdesk character varying, OUT userid bigint)COMMENTCOMMENT ON FUNCTION public.wf_reqfulfil_srworevision_suggop(lasthelpdesk character varying, OUT userid bigint) IS 'TYPE: function'; publicpostgresfalse2083$1255233418Xwf_reqfulfil_store_form(bigint, character varying, character varying, character varying)FUNCTIONCREATE FUNCTION public.wf_reqfulfil_store_form(procid bigint, username character varying, formname character varying, data character varying, OUT formvalues text) RETURNS text LANGUAGE plpgsql AS $$ DECLARE token character varying; keyvalue character varying[]; key character varying; value character varying; rf_formvalue_id integer; parameter_type character varying; metadata character varying; name character varying; classname character varying; query character varying; BEGIN formvalues = '
      '; FOREACH token IN ARRAY regexp_split_to_array(data, ',') LOOP keyvalue = regexp_split_to_array(token, '='); key = keyvalue[1]; value = keyvalue[2]; -- RAISE NOTICE 'token: %', token; -- RAISE NOTICE 'key: %', key; -- RAISE NOTICE 'value: %', value; SELECT "Id" INTO rf_formvalue_id FROM "RFFormValue" WHERE "Process"=procid AND "FormParameter" = key; SELECT "Type", "Metadata", "Description" INTO parameter_type, metadata, name FROM "RFWOFormField" WHERE FormName = formname AND "Name" = key AND "Status" = 'A'; -- RAISE NOTICE 'formname: % - key: % - parameter_type: % - metadata: %',formname,key,parameter_type, metadata; IF parameter_type ILIKE '%reference%' THEN classname = regexp_replace(unnest(regexp_matches(metadata, '(targetClass#:# [^\|]*)')),'targetClass#:# ', ''); -- RAISE NOTICE 'fech description of card % from class %',value,classname; query = 'SELECT "Description" FROM "' || classname || '" WHERE "Id" = ' ||value::INTEGER || 'AND "Status" = ''A'''; EXECUTE query INTO value; ELSEIF parameter_type ILIKE '%lookup%' THEN SELECT "Description" INTO value FROM "LookUp" WHERE "Id" = value::INTEGER AND "Status" = 'A'; END IF; -- RAISE NOTICE 'value: %',value; formvalues = concat_ws('', formvalues, '
    • ' || name || ': ' || value || '
    • '); IF rf_formvalue_id IS NULL THEN INSERT INTO "RFFormValue"("User", "Process", "FormParameter", "Value") SELECT username, procid, key, value; ELSE UPDATE "RFFormValue" SET "Value"=value WHERE "Id"=rf_formvalue_id; END IF; END LOOP; IF(trim(formvalues) = '
        ') THEN formvalues = null; END IF; formvalues = formvalues || '
      '; END; $$; DROP FUNCTION public.wf_reqfulfil_store_form(procid bigint, username character varying, formname character varying, data character varying, OUT formvalues text); publicpostgresfalseB00FUNCTION wf_reqfulfil_store_form(procid bigint, username character varying, formname character varying, data character varying, OUT formvalues text)COMMENTCOMMENT ON FUNCTION public.wf_reqfulfil_store_form(procid bigint, username character varying, formname character varying, data character varying, OUT formvalues text) IS 'TYPE: function'; publicpostgresfalse2084%1255233419?wf_reqfulfil_suggoperator(character varying, character varying)FUNCTIONCREATE FUNCTION public.wf_reqfulfil_suggoperator(nextrole character varying, currentrole character varying, OUT userid bigint) RETURNS SETOF bigint LANGUAGE plpgsql AS $$ DECLARE nextroleId bigint; currentRoleId bigint; mustbecurrent boolean; BEGIN --raise notice 'INPUT: nextrole: %, currentrole: %' , nextrole, currentrole; if (nextrole!='null' and nextrole!='') then mustbecurrent = false; select into nextroleId r."Id" from "Role" r where (r."Id"::varchar=nextrole or r."Description"=nextrole) and r."Status"='A'; else mustbecurrent = true; end if; if (currentrole!='null' and currentrole!='') then select into currentRoleId r."Id" from "Role" r where (r."Id"::varchar=currentrole or r."Description"=currentrole) and r."Status"='A'; end if; --raise notice ' nextroleId:%, currentRoleId: %, mustbecurrent: %', nextroleId, currentRoleId, mustbecurrent; if(mustbecurrent) then return query select u."Id" from "User" u join "Map_UserRole" map on map."IdObj1" = u."Id" and map."Status" = 'A' and map."IdObj2" = currentRoleId where u."Status" = 'A' and not coalesce(u."Service", false); else return query select u."Id" from "User" u join "Map_UserRole" map on map."IdObj1" = u."Id" and map."Status" = 'A' and map."IdObj2" = nextroleId where u."Status" = 'A' and not coalesce(u."Service", false); end if; END; $$; ~DROP FUNCTION public.wf_reqfulfil_suggoperator(nextrole character varying, currentrole character varying, OUT userid bigint); publicpostgresfalseC00pFUNCTION wf_reqfulfil_suggoperator(nextrole character varying, currentrole character varying, OUT userid bigint)COMMENTCOMMENT ON FUNCTION public.wf_reqfulfil_suggoperator(nextrole character varying, currentrole character varying, OUT userid bigint) IS 'TYPE: function'; publicpostgresfalse2085&1255233420@wf_reqfulfil_valid_service(character varying, character varying)FUNCTIONqCREATE FUNCTION public.wf_reqfulfil_valid_service(currentuser character varying, assignedrole character varying, OUT serviceid bigint) RETURNS SETOF bigint LANGUAGE plpgsql AS $$ DECLARE currentuserId bigint; assignedRoleId bigint; isMultiGroup boolean; isAdministrator boolean; BEGIN --raise notice 'INPUT: currentuser: %, assignedrole: %' , currentuser, assignedrole; if (currentuser != 'null' and currentuser != '') then select into currentuserId u."Id" from "User" u where u."Id"::varchar=currentuser and u."Status"='A'; end if; if (assignedrole != 'null' and assignedrole != '') then select into assignedRoleId r."Id" from "Role" r where r."Id"::varchar=assignedrole and r."Status"='A'; end if; --raise notice 'currentuserId: %, assignedRoleId: %', currentuserId, assignedRoleId; select exists( select * from "Map_UserRole" map join "Role" r on r."Id" = map."IdObj2" where "IdObj1" = currentuserId and map."Status" = 'A' and "DefaultGroup") into isMultiGroup; if (isMultiGroup) then select exists ( select * from "Map_UserRole" map join "Role" r on r."Id" = map."IdObj2" and r."Status" = 'A' where "IdObj1" = currentuserId and map."Status" = 'A' and "Type"='admin') into isAdministrator; if (isAdministrator) then return query select "Id" from "Service" where "Status" = 'A'; else return query select s."Id" from "Service" s join "ServiceCategory" c on s."Category" = c."Id" where c."HDRole" in (select "IdObj2" from "Map_UserRole" where "IdObj1" = currentuserId and "Status" = 'A') and s."Status" = 'A'; end if; else select "Type"='admin' into isAdministrator from "Role" where "Id" = assignedRoleId; if (isAdministrator) then return query select "Id" from "Service" where "Status" = 'A'; else return query select s."Id" from "Service" s join "ServiceCategory" c on s."Category" = c."Id" where c."HDRole" = assignedRoleId and s."Status" = 'A'; end if; end if; END; $$; DROP FUNCTION public.wf_reqfulfil_valid_service(currentuser character varying, assignedrole character varying, OUT serviceid bigint); publicpostgresfalseD00xFUNCTION wf_reqfulfil_valid_service(currentuser character varying, assignedrole character varying, OUT serviceid bigint)COMMENTCOMMENT ON FUNCTION public.wf_reqfulfil_valid_service(currentuser character varying, assignedrole character varying, OUT serviceid bigint) IS 'TYPE: function'; publicpostgresfalse2086'1255233421 wf_rfworkord_checkiflast(bigint)FUNCTIONCREATE FUNCTION public.wf_rfworkord_checkiflast(procid bigint, OUT islast boolean) RETURNS boolean LANGUAGE plpgsql AS $$ BEGIN IF EXISTS ( SELECT s."Id" FROM "RFWorkOrd" s JOIN "RFWorkOrd" myself ON myself."Parent" = s."Parent" AND myself."Id" = procid WHERE s."Status" = 'A' AND s."Id"<> procid AND s."FlowStatus" IN (SELECT "Id" FROM "LookUp" WHERE "Code" ILIKE 'open.%' AND "Status" = 'A' AND "Type" = 'FlowStatus') ) THEN isLast = false; ELSE isLast = TRUE; END IF; END; $$; RDROP FUNCTION public.wf_rfworkord_checkiflast(procid bigint, OUT islast boolean); publicpostgresfalseE00DFUNCTION wf_rfworkord_checkiflast(procid bigint, OUT islast boolean)COMMENTlCOMMENT ON FUNCTION public.wf_rfworkord_checkiflast(procid bigint, OUT islast boolean) IS 'TYPE: function'; publicpostgresfalse2087(1255233422 wf_rfworkord_parent_data(bigint)FUNCTIONCREATE FUNCTION public.wf_rfworkord_parent_data(parentid bigint, OUT "Number" character varying, OUT "CreationTimestamp" text, OUT "ShortDescr" text, OUT "ExtDescr" text, OUT "Register" text, OUT "FormOutput" text) RETURNS SETOF record LANGUAGE plpgsql AS $$ BEGIN RETURN QUERY SELECT rf."Number", to_char(rf."CreationTimestamp", 'DD/MM/YYYY HH:mm:SS'), rf."ShortDescr", rf."ExtDescr", rf."Register", rf."FormOutput" FROM "ReqFulfil" rf WHERE rf."Id" = parentid; END; $$; DROP FUNCTION public.wf_rfworkord_parent_data(parentid bigint, OUT "Number" character varying, OUT "CreationTimestamp" text, OUT "ShortDescr" text, OUT "ExtDescr" text, OUT "Register" text, OUT "FormOutput" text); publicpostgresfalseF00FUNCTION wf_rfworkord_parent_data(parentid bigint, OUT "Number" character varying, OUT "CreationTimestamp" text, OUT "ShortDescr" text, OUT "ExtDescr" text, OUT "Register" text, OUT "FormOutput" text)COMMENTCOMMENT ON FUNCTION public.wf_rfworkord_parent_data(parentid bigint, OUT "Number" character varying, OUT "CreationTimestamp" text, OUT "ShortDescr" text, OUT "ExtDescr" text, OUT "Register" text, OUT "FormOutput" text) IS 'TYPE: FUNCTION'; publicpostgresfalse2088)1255233423Xwf_rfworkord_store_form(bigint, character varying, character varying, character varying)FUNCTIONCREATE FUNCTION public.wf_rfworkord_store_form(procid bigint, username character varying, formname character varying, data character varying, OUT formvalues text) RETURNS text LANGUAGE plpgsql AS $$ DECLARE token character varying; keyvalue character varying[]; key character varying; value character varying; rf_formvalue_id integer; parameter_type character varying; metadata character varying; name character varying; classname character varying; query character varying; BEGIN formvalues = '
        '; FOREACH token IN ARRAY regexp_split_to_array(data, ',') LOOP keyvalue = regexp_split_to_array(token, '='); key = keyvalue[1]; value = keyvalue[2]; -- RAISE NOTICE 'token: %', token; -- RAISE NOTICE 'key: %', key; -- RAISE NOTICE 'value: %', value; SELECT "Id" INTO rf_formvalue_id FROM "RFWorkOrdFormValue" WHERE "Process"=procid AND "FormParameter" = key; SELECT "Type", "Metadata", "Description" INTO parameter_type, metadata, name FROM "RFWOFormField" WHERE FormName = formname AND "Name" = key AND "Status" = 'A'; -- RAISE NOTICE 'formname: % - key: % - parameter_type: % - metadata: %',formname,key,parameter_type, metadata; IF parameter_type ILIKE '%reference%' THEN classname = regexp_replace(unnest(regexp_matches(metadata, '(targetClass#:# [^\|]*)')),'targetClass#:# ', ''); -- RAISE NOTICE 'fech description of card % from class %',value,classname; query = 'SELECT "Description" FROM "' || classname || '" WHERE "Id" = ' ||value::INTEGER || 'AND "Status" = ''A'''; EXECUTE query INTO value; ELSEIF parameter_type ILIKE '%lookup%' THEN SELECT "Description" INTO value FROM "LookUp" WHERE "Id" = value::INTEGER AND "Status" = 'A'; END IF; -- RAISE NOTICE 'value: %',value; formvalues = concat_ws('', formvalues, '
      • ' || name || ': ' || value); IF rf_formvalue_id IS NULL THEN INSERT INTO "RFWorkOrdFormValue"("User", "Process", "FormParameter", "Value") SELECT username, procid, key, value; ELSE UPDATE "RFWorkOrdFormValue" SET "Value"=value WHERE "Id"=rf_formvalue_id; END IF; END LOOP; IF(trim(formvalues) = '
          ') THEN formvalues = null; END IF; formvalues = formvalues || '
        '; END; $$; DROP FUNCTION public.wf_rfworkord_store_form(procid bigint, username character varying, formname character varying, data character varying, OUT formvalues text); publicpostgresfalseG00FUNCTION wf_rfworkord_store_form(procid bigint, username character varying, formname character varying, data character varying, OUT formvalues text)COMMENTCOMMENT ON FUNCTION public.wf_rfworkord_store_form(procid bigint, username character varying, formname character varying, data character varying, OUT formvalues text) IS 'TYPE: function'; publicpostgresfalse2089*1255233424wf_sendmail(bigint)FUNCTIONCREATE FUNCTION public.wf_sendmail(emailid bigint, OUT success boolean) RETURNS boolean LANGUAGE plpgsql AS $$ DECLARE outgoing bigint; BEGIN UPDATE "Email" set "EmailStatus"='outgoing' WHERE "Id"=emailid AND "Status"='A'; success = true; END; $$; GDROP FUNCTION public.wf_sendmail(emailid bigint, OUT success boolean); publicpostgresfalseH009FUNCTION wf_sendmail(emailid bigint, OUT success boolean)COMMENTaCOMMENT ON FUNCTION public.wf_sendmail(emailid bigint, OUT success boolean) IS 'TYPE: function'; publicpostgresfalse2090+12552334259wf_sla_getlimit(bigint, bigint, timestamp with time zone)FUNCTIONCREATE FUNCTION public.wf_sla_getlimit(slaid bigint, calendar bigint, start_date timestamp with time zone, OUT limit_date timestamp with time zone) RETURNS timestamp with time zone LANGUAGE plpgsql AS $$ DECLARE slatype varchar; slavalue integer; temp_range tstzrange; BEGIN select into slatype,slavalue type."Code",s."Threshold" from "SLA" s join "LookUp" type on type."Id"=s."ThresholdType" where s."Id"=slaid; RAISE NOTICE 'type is % val is %',slatype,slavalue; select into temp_range working_range from utils_wc_closest_workingrange((start_date + '1 day'::interval),calendar,'forward'); raise notice 'range is %',temp_range; limit_date = date_trunc('day', upper(temp_range) + '1 day'::interval) - '1 millisecond'::interval; select into temp_range working_range from utils_wc_closest_workingrange(limit_date,calendar,'backward'); raise notice 'range is %',temp_range; limit_date = upper(temp_range); END; $$; DROP FUNCTION public.wf_sla_getlimit(slaid bigint, calendar bigint, start_date timestamp with time zone, OUT limit_date timestamp with time zone); publicpostgresfalse1255233426wf_sla_getseconds(bigint)FUNCTIONICREATE FUNCTION public.wf_sla_getseconds(slaid bigint, OUT totalseconds double precision) RETURNS double precision LANGUAGE plpgsql AS $$ DECLARE slatype varchar; slavalue integer; BEGIN select into slatype,slavalue type."Code",s."Threshold" from "SLA" s join "LookUp" type on type."Id"=s."ThresholdType" where s."Id"=slaid; RAISE NOTICE 'type is % val is %',slatype,slavalue; --totalseconds 0.0; CASE slatype WHEN 'HH' THEN totalseconds = slavalue * 3600; WHEN 'MM' THEN totalseconds = slavalue * 60; ELSE totalseconds = slavalue; END CASE; END; $$; YDROP FUNCTION public.wf_sla_getseconds(slaid bigint, OUT totalseconds double precision); publicpostgresfalse,1255233427)wf_wiringmgt_if_filter(character varying)FUNCTIONCREATE FUNCTION public.wf_wiringmgt_if_filter(ifin_id character varying, OUT ifout_id bigint) RETURNS SETOF bigint LANGUAGE plpgsql AS $$ DECLARE classname varchar; ifin_id_integer bigint; BEGIN if (ifin_id!='null' and ifin_id!='') then ifin_id_integer = ifin_id::integer; IF ifin_id_integer <> -1 THEN RETURN QUERY SELECT "IdObj1" FROM "Map_DstPortNetworkInterface" where "IdObj2" = ifin_id::integer AND "IdObj1" <> ifin_id::integer AND "Status" = 'A' union select "IdObj2" FROM "Map_DstPortNetworkInterface" where "IdObj1" = ifin_id::integer AND "IdObj2" <> ifin_id::integer AND "Status" = 'A'; ELSE RETURN QUERY EXECUTE 'SELECT 0::bigint'; END IF; else RETURN QUERY SELECT -1; end if; END; $$; ]DROP FUNCTION public.wf_wiringmgt_if_filter(ifin_id character varying, OUT ifout_id bigint); publicpostgresfalseI00OFUNCTION wf_wiringmgt_if_filter(ifin_id character varying, OUT ifout_id bigint)COMMENTwCOMMENT ON FUNCTION public.wf_wiringmgt_if_filter(ifin_id character varying, OUT ifout_id bigint) IS 'TYPE: function'; publicpostgresfalse2092-12552334289wf_wiringmgt_map_networkinterface(bigint, bigint, bigint)FUNCTIONCREATE FUNCTION public.wf_wiringmgt_map_networkinterface(originter bigint, destinter bigint, colour bigint, OUT success boolean) RETURNS boolean LANGUAGE plpgsql AS $$ BEGIN insert into "Map_DstPortNetworkInterface" ("IdClass1", "IdObj1", "IdClass2", "IdObj2", "CableColour") values('"NetworkInterface"'::regclass, destinter, '"NetworkInterface"'::regclass, originter, colour); success = true; END $$; DROP FUNCTION public.wf_wiringmgt_map_networkinterface(originter bigint, destinter bigint, colour bigint, OUT success boolean); publicpostgresfalseJ00rFUNCTION wf_wiringmgt_map_networkinterface(originter bigint, destinter bigint, colour bigint, OUT success boolean)COMMENTCOMMENT ON FUNCTION public.wf_wiringmgt_map_networkinterface(originter bigint, destinter bigint, colour bigint, OUT success boolean) IS 'TYPE: function'; publicpostgresfalse2093.1255233429wf_wiringmgt_number()FUNCTIONCREATE FUNCTION public.wf_wiringmgt_number(OUT number character varying) RETURNS character varying LANGUAGE plpgsql AS $$ BEGIN number = lpad(nextval('wiring_seq')::text,6,'0'); END; $$; HDROP FUNCTION public.wf_wiringmgt_number(OUT number character varying); publicpostgresfalseK00:FUNCTION wf_wiringmgt_number(OUT number character varying)COMMENTbCOMMENT ON FUNCTION public.wf_wiringmgt_number(OUT number character varying) IS 'TYPE: function'; publicpostgresfalse2094 1255233430_cm_string_agg(anyelement) AGGREGATECREATE AGGREGATE public._cm_string_agg(anyelement) ( SFUNC = array_append, STYPE = anyarray, INITCOND = '{}', FINALFUNC = public._cm_string_agg ); 2DROP AGGREGATE public._cm_string_agg(anyelement); publicpostgresfalse18221259271651 _FunctionTABLE CREATE TABLE public."_Function" ( "Id" bigint NOT NULL, "IdClass" regclass DEFAULT 'public."_Function"'::regclass NOT NULL, "User" character varying DEFAULT 'system'::character varying NOT NULL, "BeginDate" timestamp with time zone DEFAULT now() NOT NULL, "IdTenant" bigint, "Code" character varying NOT NULL, "Description" character varying, "Notes" character varying, "Category" character varying, "Hash" character varying, "Revision" character varying, "Content" text ); DROP TABLE public."_Function"; publicpostgresfalseL00TABLE "_Function"COMMENTCCOMMENT ON TABLE public."_Function" IS 'TYPE: special|VERSION: 1'; publicpostgresfalse2201259271649_Function_Id_seqSEQUENCE{CREATE SEQUENCE public."_Function_Id_seq" START WITH 1 INCREMENT BY 1 NO MINVALUE NO MAXVALUE CACHE 1; )DROP SEQUENCE public."_Function_Id_seq"; publicpostgresfalse220M00_Function_Id_seqSEQUENCE OWNED BYKALTER SEQUENCE public."_Function_Id_seq" OWNED BY public."_Function"."Id"; publicpostgresfalse2191259271637_PatchTABLECREATE TABLE public."_Patch" ( "Id" bigint NOT NULL, "IdClass" regclass DEFAULT 'public."_Patch"'::regclass NOT NULL, "User" character varying DEFAULT 'system'::character varying NOT NULL, "BeginDate" timestamp with time zone DEFAULT now() NOT NULL, "IdTenant" bigint, "Code" character varying NOT NULL, "Description" character varying, "Notes" character varying, "Category" character varying, "Hash" character varying, "Content" text ); DROP TABLE public."_Patch"; publicpostgresfalseN00TABLE "_Patch"COMMENT@COMMENT ON TABLE public."_Patch" IS 'TYPE: special|VERSION: 1'; publicpostgresfalse2181259271635 _Patch_Id_seqSEQUENCExCREATE SEQUENCE public."_Patch_Id_seq" START WITH 1 INCREMENT BY 1 NO MINVALUE NO MAXVALUE CACHE 1; &DROP SEQUENCE public."_Patch_Id_seq"; publicpostgresfalse218O00 _Patch_Id_seqSEQUENCE OWNED BYEALTER SEQUENCE public."_Patch_Id_seq" OWNED BY public."_Patch"."Id"; publicpostgresfalse2171259271627_SysLockTABLEJCREATE TABLE public."_SysLock" ( "Code" character varying NOT NULL ); DROP TABLE public."_SysLock"; publicpostgresfalse1259237998 assetmgt_seqSEQUENCEyCREATE SEQUENCE public.assetmgt_seq START WITH 1 INCREMENT BY 1 NO MINVALUE MAXVALUE 999999 CACHE 1; #DROP SEQUENCE public.assetmgt_seq; publicpostgresfalse1259238000 changemgt_seqSEQUENCEzCREATE SEQUENCE public.changemgt_seq START WITH 1 INCREMENT BY 1 NO MINVALUE MAXVALUE 999999 CACHE 1; $DROP SEQUENCE public.changemgt_seq; publicpostgresfalse1259238002 class_seqSEQUENCErCREATE SEQUENCE public.class_seq START WITH 1 INCREMENT BY 1 NO MINVALUE NO MAXVALUE CACHE 1; DROP SEQUENCE public.class_seq; publicpostgresfalseP00SEQUENCE class_seqCOMMENTLCOMMENT ON SEQUENCE public.class_seq IS 'Sequence for autoincrement class'; publicpostgresfalse2101259238004incidentmgt_seqSEQUENCE|CREATE SEQUENCE public.incidentmgt_seq START WITH 1 INCREMENT BY 1 NO MINVALUE MAXVALUE 999999 CACHE 1; &DROP SEQUENCE public.incidentmgt_seq; publicpostgresfalse1259238006ipaddressmgt_seqSEQUENCE}CREATE SEQUENCE public.ipaddressmgt_seq START WITH 1 INCREMENT BY 1 NO MINVALUE MAXVALUE 999999 CACHE 1; 'DROP SEQUENCE public.ipaddressmgt_seq; publicpostgresfalse1259238008 problem_seqSEQUENCExCREATE SEQUENCE public.problem_seq START WITH 1 INCREMENT BY 1 NO MINVALUE MAXVALUE 999999 CACHE 1; "DROP SEQUENCE public.problem_seq; publicpostgresfalse1259238010 reqfulfil_seqSEQUENCEzCREATE SEQUENCE public.reqfulfil_seq START WITH 1 INCREMENT BY 1 NO MINVALUE MAXVALUE 999999 CACHE 1; $DROP SEQUENCE public.reqfulfil_seq; publicpostgresfalse1259238051 wiring_seqSEQUENCEwCREATE SEQUENCE public.wiring_seq START WITH 1 INCREMENT BY 1 NO MINVALUE MAXVALUE 999999 CACHE 1; !DROP SEQUENCE public.wiring_seq; publicpostgresfalse12604271654 _Function IdDEFAULTrALTER TABLE ONLY public."_Function" ALTER COLUMN "Id" SET DEFAULT nextval('public."_Function_Id_seq"'::regclass); ?ALTER TABLE public."_Function" ALTER COLUMN "Id" DROP DEFAULT; publicpostgresfalse220219220-2604271640 _Patch IdDEFAULTlALTER TABLE ONLY public."_Patch" ALTER COLUMN "Id" SET DEFAULT nextval('public."_Patch_Id_seq"'::regclass); <ALTER TABLE public."_Patch" ALTER COLUMN "Id" DROP DEFAULT; publicpostgresfalse217218218+0230271spatial_ref_sys TABLE DATAUCOPY gis.spatial_ref_sys (srid, auth_name, auth_srid, srtext, proj4text) FROM stdin; gispostgresfalse193 0271651 _Function TABLE DATACOPY public."_Function" ("Id", "IdClass", "User", "BeginDate", "IdTenant", "Code", "Description", "Notes", "Category", "Hash", "Revision", "Content") FROM stdin; publicpostgresfalse220 0271637_Patch TABLE DATACOPY public."_Patch" ("Id", "IdClass", "User", "BeginDate", "IdTenant", "Code", "Description", "Notes", "Category", "Hash", "Content") FROM stdin; publicpostgresfalse218 0271627_SysLock TABLE DATA,COPY public."_SysLock" ("Code") FROM stdin; publicpostgresfalse216 Q00_Function_Id_seq SEQUENCE SETASELECT pg_catalog.setval('public."_Function_Id_seq"', 1, false); publicpostgresfalse219R00 _Patch_Id_seq SEQUENCE SET>SELECT pg_catalog.setval('public."_Patch_Id_seq"', 1, false); publicpostgresfalse217S00 assetmgt_seq SEQUENCE SET;SELECT pg_catalog.setval('public.assetmgt_seq', 1, false); publicpostgresfalse208T00 changemgt_seq SEQUENCE SET<SELECT pg_catalog.setval('public.changemgt_seq', 1, false); publicpostgresfalse209U00 class_seq SEQUENCE SET;SELECT pg_catalog.setval('public.class_seq', 56561, true); publicpostgresfalse210V00incidentmgt_seq SEQUENCE SET>SELECT pg_catalog.setval('public.incidentmgt_seq', 1, false); publicpostgresfalse211W00ipaddressmgt_seq SEQUENCE SET?SELECT pg_catalog.setval('public.ipaddressmgt_seq', 1, false); publicpostgresfalse212X00 problem_seq SEQUENCE SET:SELECT pg_catalog.setval('public.problem_seq', 1, false); publicpostgresfalse213Y00 reqfulfil_seq SEQUENCE SET<SELECT pg_catalog.setval('public.reqfulfil_seq', 1, false); publicpostgresfalse214Z00 wiring_seq SEQUENCE SET9SELECT pg_catalog.setval('public.wiring_seq', 1, false); publicpostgresfalse215<2606271661_Function _Function_Code_key CONSTRAINT]ALTER TABLE ONLY public."_Function" ADD CONSTRAINT "_Function_Code_key" UNIQUE ("Code"); JALTER TABLE ONLY public."_Function" DROP CONSTRAINT "_Function_Code_key"; publicpostgresfalse220:2606271647_Patch _Patch_Code_key CONSTRAINTWALTER TABLE ONLY public."_Patch" ADD CONSTRAINT "_Patch_Code_key" UNIQUE ("Code"); DALTER TABLE ONLY public."_Patch" DROP CONSTRAINT "_Patch_Code_key"; publicpostgresfalse21882606271634_SysLock _SysLock_pkey CONSTRAINT\ALTER TABLE ONLY public."_SysLock" ADD CONSTRAINT "_SysLock_pkey" PRIMARY KEY ("Code"); DALTER TABLE ONLY public."_SysLock" DROP CONSTRAINT "_SysLock_pkey"; publicpostgresfalse216+ x x x x