BEGIN;
CREATE FUNCTION f() RETURNS boolean AS '
DECLARE
  x RECORD;
BEGIN
  SELECT INTO x * FROM pg_class WHERE relkind=\'r\' AND relname=\'alien_descriptive_item\';
  IF NOT FOUND THEN
    SELECT INTO x * FROM pg_class WHERE relkind=\'r\' AND relname=\'alien_service_item\';
    IF NOT FOUND THEN
      CREATE TABLE alien_descriptive_item (
        amount numeric(12,4),
        description text,
        id bigserial NOT NULL,
        entry bigint,
        account_plan bigint,
        alien_item bigint,
        PRIMARY KEY (id)
      );
      CREATE INDEX alien_descriptive_item_alien_item_idx ON alien_descriptive_item(alien_item);
    ELSE
      ALTER TABLE alien_service_item RENAME TO alien_descriptive_item;
    END IF;
  ELSE
    SELECT INTO x * FROM pg_class WHERE relkind=\'r\' AND relname=\'alien_service_item\';
    IF FOUND THEN
      RAISE EXCEPTION \'Existen alien_service_item y alien_descriptive_item!\';
    END IF;
  END IF;
  RETURN true;
END;
' LANGUAGE 'plpgsql';
SELECT f();
DROP FUNCTION f();
COMMIT;
