get_or_create_issue2.sql 1.7 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152
  1. with issue_id as (
  2. INSERT INTO issues_issue (project_id) VALUES (1)
  3. WHERE NOT EXISTS (SELECT id from issues_issue where )
  4. SELECT issues_issue.id
  5. FROM issues_issue
  6. INNER JOIN issues_issuehash on issues_issuehash.issue_id = issues_issue.id
  7. WHERE issues_issuehash.value = 'acbd18db-4cc2-f85c-edef-654fccc4a4d8'::uuid
  8. )
  9. INSERT INTO issues_issuehash (value, issue_id, project_id)
  10. VALUES ('acbd18db-4cc2-f85c-edef-654fccc4a4d8'::uuid, 1, 1)
  11. INSERT INTO issues_issuehash ()
  12. CREATE OR REPLACE FUNCTION get_or_create_issue(_project_id INT, _issue_hash UUID, _level int, _title varchar) RETURNS RECORD AS $$
  13. DECLARE
  14. ret RECORD;
  15. BEGIN
  16. LOOP
  17. SELECT issues_issue.id, issues_issue.status, False as created_issue
  18. FROM issues_issue
  19. INNER JOIN issues_issuehash ON issues_issuehash.issue_id = issues_issue.id
  20. WHERE issues_issuehash.value = _issue_hash AND issues_issuehash.project_id = _project_id
  21. INTO ret;
  22. EXIT WHEN FOUND;
  23. INSERT INTO issues_issue (created, project_id, has_seen, is_public, level, metadata, title, type, status, count, last_seen, tags)
  24. SELECT now(), _project_id, False, False, _level, '{}'::jsonb, _title, 1, 1, 0, now(), '{}'::jsonb
  25. WHERE NOT EXISTS (
  26. SELECT 1 FROM issues_issuehash WHERE issues_issuehash.value = _issue_hash AND issues_issuehash.project_id = _project_id
  27. )
  28. RETURNING issues_issue.id, issues_issue.status, True as created_issue
  29. INTO ret;
  30. EXIT WHEN FOUND;
  31. END LOOP;
  32. if ret.created_issue = True THEN
  33. INSERT INTO issues_issuehash (issue_id, project_id, value)
  34. VALUES (ret.id, _project_id, _issue_hash)
  35. ON CONFLICT DO NOTHING;
  36. END IF;
  37. return ret;
  38. END;
  39. $$ LANGUAGE plpgsql;;