tuple concurrently updated when creating functions in postgresql / PL/pgSQL
<p>When initializing my process, it runs the PL/pgSQL statement below creating two functions. However, every time I create multiple processes simultaneously as part of an end-to-end test, parallel execution of this statement leads to a <code>tuple concurrently updated</code> error that I can't seem to get around. Any help would be much appreciated.</p>

<pre><code>CREATE OR REPLACE FUNCTION
  count_rows(schema text, tablename text) returns integer
  AS
  $body$
  DECLARE
    result integer;
    query varchar;
  BEGIN
    query := 'SELECT count(1) FROM "' || schema || '"."' || tablename || '"';
    execute query into result;
    return result;
  END;
  $body$
  LANGUAGE plpgsql;

CREATE OR REPLACE FUNCTION
  delete_if_empty(schema text, tablename text) RETURNS INTEGER
  AS
  $$
  DECLARE
    result integer;
    query varchar;
  BEGIN
    query := 'SELECT COUNT(*) FROM "' || schema || '"."' || tablename || '"';
    execute query into result;
    IF result = 0 THEN
      EXECUTE 'DROP TABLE "' || schema || '"."' || tablename || '" CASCADE;';
      EXECUTE 'NOTIFY "' || schema || '", ''DESTROY_TABLE:' || tablename || ''';';
      RETURN 1;
    END IF;
    RETURN 0;
  END;
  $$
  LANGUAGE plpgsql;

  SELECT version()
</code></pre>