SELECT COUNT(*) as cnt FROM spec_events WHERE supplement_id = SELECT COALESCE(MAX(seq), 0) as m FROM spec_events WHERE contract_id = FOR UPDATE SELECT name_hash, name, price, qty, sum, date_start FROM spec_current WHERE contract_id = INSERT INTO spec_events (contract_id, supplement_id, seq, action, target_hash, comment, status) VALUES ( , , , 'DELETE', , 'full_replace', 'applied' ) DELETE FROM spec_current WHERE contract_id = INSERT INTO spec_events (contract_id, supplement_id, seq, action, new_values, comment, status) VALUES ( , , , 'ADD', ::jsonb, , 'applied' ) RETURNING id INSERT INTO spec_current (contract_id, name_hash, name, price, qty, sum, date_start, last_event_id) VALUES ( , md5(lower(trim()) || coalesce(, '')), , , , , , ) SELECT price, qty, sum, date_start FROM spec_current WHERE contract_id = AND name_hash = INSERT INTO spec_events (contract_id, supplement_id, seq, action, target_hash, new_values, comment, status) VALUES ( , , , 'UPDATE', , ::jsonb, , 'applied' ) RETURNING id UPDATE spec_current SET price = , qty = , sum = , date_start = , last_event_id = , updated_at = now() WHERE contract_id = AND name_hash = INSERT INTO spec_events (contract_id, supplement_id, seq, action, target_hash, comment, status) VALUES ( , , , 'DELETE', , , 'applied' ) DELETE FROM spec_current WHERE contract_id = AND name_hash = INSERT INTO spec_events (contract_id, supplement_id, seq, action, new_values, comment, status) VALUES ( , , , 'UNRESOLVED', ::jsonb, , 'pending' ) #serializeJSON(result)#