Skip to content

Instantly share code, notes, and snippets.

@pypt
Created July 8, 2016 01:33
Show Gist options
  • Save pypt/9951c6526a614f0eec2fdbc87c19da53 to your computer and use it in GitHub Desktop.
Save pypt/9951c6526a614f0eec2fdbc87c19da53 to your computer and use it in GitHub Desktop.
Deadlocking query
WITH new_sentences (disable_triggers, language, media_id, publish_date, sentence, sentence_number, stories_id) AS (VALUES
-- New sentences to potentially insert
(FALSE, 'ro', 40536, '2013-04-17 17:38:37'::timestamp, 'Primaria nu vrea ca iesenii sa scape de taxa de timbru', 0, 110124077),
(FALSE, 'ro', 40536, '2013-04-17 17:38:37'::timestamp, 'Un consilier PP-DD a venit cu o solutie la drumurile pe care iesenii le fac pentru a plati taxele.', 1, 110124077),
(FALSE, 'ro', 40536, '2013-04-17 17:38:37'::timestamp, 'Avocatul Anca Preda a initiat un proiect de hotarare prin care oamenii pot achita taxa de timbru prin posta.', 2, 110124077),
(FALSE, 'ro', 40536, '2013-04-17 17:38:37'::timestamp, 'Tot ceea ce au de facut reprezentantii primariei este sa incheie un contract cu posta, fara sa plateasca vreun comision.”Nu ar fi niciun efort din partea primariei.', 3, 110124077),
(FALSE, 'ro', 40536, '2013-04-17 17:38:37'::timestamp, 'Nu se cere niciun commision.', 4, 110124077),
(FALSE, 'ro', 40536, '2013-04-17 17:38:37'::timestamp, 'Trebuie incheiat un contract cu posta, doar atat”, a precizat Anca Preda, consilier local PP-DD.', 5, 110124077)
),
duplicate_sentences AS (
-- Either a list of duplicate sentences already found in the table
-- or an empty list if deduplication is disabled
UPDATE story_sentences
SET is_dup = 't',
disable_triggers = 't'
FROM new_sentences
WHERE half_md5(story_sentences.sentence) = half_md5(new_sentences.sentence)
AND week_start_date( story_sentences.publish_date::date )
= week_start_date( new_sentences.publish_date::date )
AND story_sentences.media_id = new_sentences.media_id
RETURNING story_sentences.sentence
)
INSERT INTO story_sentences (disable_triggers, language, media_id, publish_date, sentence, sentence_number, stories_id)
SELECT disable_triggers, language, media_id, publish_date, sentence, sentence_number, stories_id
FROM new_sentences
WHERE sentence NOT IN (
-- Skip the ones for which we've just set is_dup = 't'
SELECT sentence
FROM duplicate_sentences
)
RETURNING story_sentences.sentence
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment