De foutmelding is
Je hebt twee EXECUTE
commando's:
_query := 'CREATE TABLE public.'
|| quote_ident(_table_name) || ' ( ) INHERITS (public.evidence)';
EXECUTE _query;
...
EXECUTE 'INSERT INTO public.'
|| quote_ident(_table_name) || ' VALUES ($1.*)' USING NEW;
Het enige deel dat NULL
. kan zijn is table_name
.
De enige kans voor table_name
om NULL
te worden is hier:
SELECT raised_local_time FROM notifications WHERE id=_notification_id
INTO _raised_local_time;
Dus de oorzaak moet een van de twee redenen zijn :
-
NEW.notification_id
isNULL
. -
Er is geen rij in
notifications
voor de opgegevenNEW.notification_id
.
Probeer deze aangepaste triggerfunctie voor foutopsporing :
CREATE OR REPLACE FUNCTION partition_evidence_by_month()
RETURNS trigger AS
$func$
DECLARE
_table_name text;
BEGIN
SELECT 'evidence-' || to_char(raised_local_time, 'YYYY-MM')
FROM public.notifications -- schema-qualify to be sure
WHERE id = NEW.notification_id
INTO _table_name;
IF _table_name IS NULL THEN
RAISE EXCEPTION '_table_name is NULL. Should not occur!';
END IF;
IF NOT EXISTS ( -- create table if it does not exist
SELECT 1
FROM pg_catalog.pg_class c
JOIN pg_catalog.pg_namespace n ON n.oid = c.relnamespace
WHERE c.relkind = 'r'
AND c.relname = _table_name
AND n.nspname = 'public') THEN
EXECUTE 'CREATE TABLE public.'
|| quote_ident(_table_name) || ' ( ) INHERITS (public.evidence)';
END IF;
EXECUTE 'INSERT INTO public.'
|| quote_ident(_table_name) || ' VALUES $1' -- Use NEW row directly
USING NEW; -- write data to the partition table
RETURN NULL;
END
$func$ LANGUAGE plpgsql;
-
Verwijder ongebruikte variabelen en vereenvoudig de code. (Dit is duidelijk een vereenvoudigd voorbeeld.)
-
U hebt onder andere
date_trunc()
. niet nodig helemaal niet. Voer eenvoudig de originele tijdstempel in naarto_char()
. -
Geen zin in het gebruik van
varchar(n)
. Gebruik gewoontext
ofvarchar
. -
Vermijd te veel opdrachten waar onnodig - relatief duur in PL/pgSQL.
-
-
Voeg een
RAISE
toe om mijn hypothese te controleren.
Als je de foutmelding krijgt, is het de volgende stap om onderscheid te maken tussen de twee mogelijke oorzaken. Zou triviaal moeten zijn ...