   );
   CREATE INDEX ve_open_idx ON _ermrest_history.visible_entities (table_rid, entity_rid, lower(during)) WHERE upper(during) IS NULL;
   CREATE INDEX ve_resolve_idx ON _ermrest_history.visible_entities (entity_rid, during);
+
+  -- logic to perform one-time conversion associated with creation of visible_entities on existing catalogs
+  CREATE FUNCTION _ermrest.htable_to_visible_entities(trid text, sname text, tname text, htname text) RETURNS void AS $$
+  DECLARE
+    record record;
+    prev_record record;
+    prev_record_rid text;
+    prev_born timestamptz;
+  BEGIN
+    -- we can assume the visible_entities table contains NO records for this table yet
+    prev_born := NULL;
+    FOR record IN
+      EXECUTE 'SELECT * FROM _ermrest_history.' || quote_ident(htname) || ' h ORDER BY "RID", during'
+    LOOP
+      IF prev_born IS NOT NULL THEN
+        IF record."RID" = prev_record."RID" AND (prev_record.during -|- record.during OR prev_record.during && record.during) THEN
+          -- this is a continuation of previous interval
+          record.during := prev_record.during + record.during; -- tolerate imprecise history ranges
+          prev_record := record;
+          CONTINUE;
+        ELSE
+          -- last record is final part of previous interval
+	  INSERT INTO _ermrest_history.visible_entities (entity_rid, table_rid, during)
+	  VALUES (prev_record."RID", trid, tstzrange(prev_born, upper(prev_record.during), '[)'));
+	END IF;
+      END IF;
+      -- this begins the first (or next interval if previous was flushed above)
+      prev_record := record;
+      prev_born := lower(record.during);
+    END LOOP;
+    IF prev_born IS NOT NULL THEN
+      -- flush final interval of iteration
+      INSERT INTO _ermrest_history.visible_entities (entity_rid, table_rid, during)
+      VALUES (prev_record."RID", trid, tstzrange(prev_born, upper(prev_record.during), '[)'));
+    END IF;
+  END;
+  $$ LANGUAGE plpgsql;
 END IF;
 
 IF (SELECT True FROM information_schema.tables WHERE table_schema = '_ermrest' AND table_name = 'known_columns') IS NULL THEN


-- 
-- Copyright 2012-2017 University of Southern California
-- 
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.

    || ' FOR EACH ROW EXECUTE PROCEDURE _ermrest.maintain_row();';
END LOOP;

-- disable one-time conversion that MAY have been done above
CREATE OR REPLACE FUNCTION _ermrest.htable_to_visible_entities(trid text, sname text, tname text, htname text) RETURNS void AS $$
BEGIN
  -- do nothing during normal operations...
  RETURN;
END;
$$ LANGUAGE plpgsql;

RAISE NOTICE 'Completed idempotent creation of standard ERMrest schema.';

END ermrest_schema;
