diff --git a/packages/fuel-indexer-database/postgres/migrations/20230913134030_add_ensure_block_height_consecutive_function.down.sql b/packages/fuel-indexer-database/postgres/migrations/20230913134030_add_ensure_block_height_consecutive_function.down.sql new file mode 100644 index 000000000..8bf41d0b3 --- /dev/null +++ b/packages/fuel-indexer-database/postgres/migrations/20230913134030_add_ensure_block_height_consecutive_function.down.sql @@ -0,0 +1 @@ +DROP FUNCTION IF EXISTS ensure_block_height_consecutive; \ No newline at end of file diff --git a/packages/fuel-indexer-database/postgres/migrations/20230913134030_add_ensure_block_height_consecutive_function.up.sql b/packages/fuel-indexer-database/postgres/migrations/20230913134030_add_ensure_block_height_consecutive_function.up.sql new file mode 100644 index 000000000..96af4be7b --- /dev/null +++ b/packages/fuel-indexer-database/postgres/migrations/20230913134030_add_ensure_block_height_consecutive_function.up.sql @@ -0,0 +1,14 @@ +CREATE OR REPLACE FUNCTION ensure_block_height_consecutive() +RETURNS TRIGGER AS $$ +DECLARE + block_height integer; +BEGIN + EXECUTE format('SELECT MAX(block_height) FROM %I.%I', TG_TABLE_SCHEMA, TG_TABLE_NAME) INTO block_height; + + IF NEW.block_height IS NOT NULL AND block_height IS NOT NULL AND NEW.block_height != block_height + 1 THEN + RAISE EXCEPTION '%.%: attempted to insert value with block_height = % while last indexed block_height = %. block_height values must be consecutive.', TG_TABLE_SCHEMA, TG_TABLE_NAME, NEW.block_height, block_height; + END IF; + + RETURN NEW; +END; +$$ LANGUAGE plpgsql; \ No newline at end of file diff --git a/packages/fuel-indexer-schema/src/db/tables.rs b/packages/fuel-indexer-schema/src/db/tables.rs index b43cbe186..cccba114a 100644 --- a/packages/fuel-indexer-schema/src/db/tables.rs +++ b/packages/fuel-indexer-schema/src/db/tables.rs @@ -183,6 +183,15 @@ impl IndexerSchema { statements.extend(constraint_stmnts); + statements.push(format!( + "CREATE TRIGGER trigger_ensure_block_height_consecutive + BEFORE INSERT OR UPDATE ON {namespace}_{identifier}.indexmetadataentity + FOR EACH ROW + EXECUTE FUNCTION ensure_block_height_consecutive();", + namespace = self.namespace, + identifier = self.identifier + )); + for stmnt in statements.iter() { queries::execute_query(conn, stmnt.to_owned()).await?; }