BEGIN;
DELETE FROM _own_pos_document_data WHERE _end_t IS NOT NULL OR document_type NOT IN (3,4,6,7,8,9,12,13,14,15,16,20,21,30,31,32);
DELETE FROM own_pos_document WHERE id NOT IN (SELECT DISTINCT _table FROM _own_pos_document_data ORDER BY _table);

CREATE FUNCTION f() RETURNS boolean AS '
DECLARE
  i RECORD;
BEGIN
  FOR i IN SELECT entity FROM _entity_types_data WHERE entity_type=15 LOOP
    FOR j IN 30..32 LOOP
      EXECUTE \'INSERT INTO own_pos_document (id) VALUES (nextval(\\\'own_pos_document_id_seq\\\')); INSERT INTO _own_pos_document_data (_table, print_command, document_type, own_pos, number) VALUES (currval(\\\'own_pos_document_id_seq\\\'), \\\'xless\\\', \'|| j ||\', \' || i.entity || \', 1);\n\';
    END LOOP;
   END LOOP;
   RETURN true;
END;' LANGUAGE 'plpgsql';
SELECT f();
DROP FUNCTION f();

COMMIT;

