|
| 1 | +CREATE OR REPLACE FUNCTION build_attribute_index(subgraph_id text, index_name text, index_type text, index_operator text, jsonb_index boolean, attribute_name text, entity_name text) |
| 2 | + RETURNS void |
| 3 | + LANGUAGE plpgsql |
| 4 | +AS $function$ |
| 5 | +DECLARE |
| 6 | + jsonb_operator TEXT := '->>'; |
| 7 | +BEGIN |
| 8 | + IF jsonb_index THEN |
| 9 | + jsonb_operator := '->'; |
| 10 | + END IF; |
| 11 | + EXECUTE 'CREATE INDEX ' || index_name |
| 12 | + || ' ON entities USING ' |
| 13 | + || index_type |
| 14 | + || '((data -> ' |
| 15 | + || quote_literal(attribute_name) |
| 16 | + || ' ' |
| 17 | + || jsonb_operator |
| 18 | + || '''data'')' |
| 19 | + || index_operator |
| 20 | + || ') where subgraph=' |
| 21 | + || quote_literal(subgraph_id) |
| 22 | + || ' and entity=' |
| 23 | + || quote_literal(entity_name); |
| 24 | + RETURN ; |
| 25 | +EXCEPTION |
| 26 | + WHEN duplicate_table THEN |
| 27 | + -- do nothing if index already exists |
| 28 | +END; |
| 29 | +$function$ |
| 30 | +; |
| 31 | + |
| 32 | +CREATE OR REPLACE FUNCTION public.revert_block(block_to_revert_hash character varying, subgraph_id character varying) |
| 33 | + RETURNS void |
| 34 | + LANGUAGE plpgsql |
| 35 | +AS $function$ |
| 36 | +declare |
| 37 | + history record; |
| 38 | +begin |
| 39 | + -- Revert all relevant events |
| 40 | + for history in |
| 41 | + -- Get all history entries associated with the given block. Note |
| 42 | + -- that the view imposes the correct order |
| 43 | + select |
| 44 | + h.entity, |
| 45 | + h.entity_id, |
| 46 | + h.data_before, |
| 47 | + h.op_id |
| 48 | + from entity_history_with_source h |
| 49 | + where h.source = block_to_revert_hash |
| 50 | + and h.subgraph = subgraph_id |
| 51 | + loop |
| 52 | + case |
| 53 | + -- insert case |
| 54 | + when history.op_id = 0 then |
| 55 | + -- Delete inserted row |
| 56 | + begin |
| 57 | + perform set_config('vars.current_event_source', |
| 58 | + 'REVERSION', false); |
| 59 | + delete from entities |
| 60 | + where subgraph = subgraph_id |
| 61 | + and entity = history.entity |
| 62 | + and id = history.entity_id; |
| 63 | + -- Row was already updated |
| 64 | + exception when no_data_found then |
| 65 | + -- do nothing, the entity was gone already |
| 66 | + end; |
| 67 | + -- update or delete case |
| 68 | + when history.op_id IN (1,2) then |
| 69 | + -- Insert deleted row if not exists |
| 70 | + -- If row exists perform update |
| 71 | + begin |
| 72 | + insert into entities |
| 73 | + (id, subgraph, entity, data, event_source) |
| 74 | + values (history.entity_id, |
| 75 | + subgraph_id, |
| 76 | + history.entity, |
| 77 | + history.data_before, |
| 78 | + 'REVERSION') |
| 79 | + on conflict (id, subgraph, entity) |
| 80 | + do update |
| 81 | + set data = history.data_before, |
| 82 | + event_source = 'REVERSION'; |
| 83 | + end; |
| 84 | + end case; |
| 85 | + end loop; |
| 86 | +end; |
| 87 | +$function$ |
| 88 | +; |
0 commit comments