postgresql/contrib/spi/timetravel.c

554 lines
14 KiB
C
Raw Normal View History

/*
2010-09-20 22:08:53 +02:00
* contrib/spi/timetravel.c
*
*
* timetravel.c -- function to get time travel feature
* using general triggers.
*
* Modified by BÖJTHE Zoltán, Hungary, mailto:urdesobt@axelero.hu
*/
#include "postgres.h"
#include <ctype.h>
#include "access/htup_details.h"
#include "catalog/pg_type.h"
#include "commands/trigger.h"
#include "executor/spi.h"
#include "miscadmin.h"
#include "utils/builtins.h"
#include "utils/nabstime.h"
#include "utils/rel.h"
PG_MODULE_MAGIC;
/* AbsoluteTime currabstime(void); */
typedef struct
{
char *ident;
SPIPlanPtr splan;
} EPlan;
static EPlan *Plans = NULL; /* for UPDATE/DELETE */
static int nPlans = 0;
typedef struct _TTOffList
{
2003-08-04 02:43:34 +02:00
struct _TTOffList *next;
char name[FLEXIBLE_ARRAY_MEMBER];
} TTOffList;
static TTOffList *TTOff = NULL;
2003-08-04 02:43:34 +02:00
static int findTTStatus(char *name);
static EPlan *find_plan(char *ident, EPlan **eplan, int *nplans);
/*
* timetravel () --
* 1. IF an update affects tuple with stop_date eq INFINITY
* then form (and return) new tuple with start_date eq current date
* and stop_date eq INFINITY [ and update_user eq current user ]
* and all other column values as in new tuple, and insert tuple
* with old data and stop_date eq current date
* ELSE - skip updating of tuple.
* 2. IF a delete affects tuple with stop_date eq INFINITY
* then insert the same tuple with stop_date eq current date
* [ and delete_user eq current user ]
* ELSE - skip deletion of tuple.
* 3. On INSERT, if start_date is NULL then current date will be
* inserted, if stop_date is NULL then INFINITY will be inserted.
* [ and insert_user eq current user, update_user and delete_user
* eq NULL ]
*
* In CREATE TRIGGER you are to specify start_date and stop_date column
* names:
* EXECUTE PROCEDURE
* timetravel ('date_on', 'date_off' [,'insert_user', 'update_user', 'delete_user' ] ).
*/
#define MaxAttrNum 5
#define MinAttrNum 2
#define a_time_on 0
#define a_time_off 1
#define a_ins_user 2
#define a_upd_user 3
#define a_del_user 4
PG_FUNCTION_INFO_V1(timetravel);
2003-08-04 02:43:34 +02:00
Datum /* have to return HeapTuple to Executor */
timetravel(PG_FUNCTION_ARGS)
{
2003-08-04 02:43:34 +02:00
TriggerData *trigdata = (TriggerData *) fcinfo->context;
Trigger *trigger; /* to get trigger name */
int argc;
char **args; /* arguments */
Phase 2 of pgindent updates. Change pg_bsd_indent to follow upstream rules for placement of comments to the right of code, and remove pgindent hack that caused comments following #endif to not obey the general rule. Commit e3860ffa4dd0dad0dd9eea4be9cc1412373a8c89 wasn't actually using the published version of pg_bsd_indent, but a hacked-up version that tried to minimize the amount of movement of comments to the right of code. The situation of interest is where such a comment has to be moved to the right of its default placement at column 33 because there's code there. BSD indent has always moved right in units of tab stops in such cases --- but in the previous incarnation, indent was working in 8-space tab stops, while now it knows we use 4-space tabs. So the net result is that in about half the cases, such comments are placed one tab stop left of before. This is better all around: it leaves more room on the line for comment text, and it means that in such cases the comment uniformly starts at the next 4-space tab stop after the code, rather than sometimes one and sometimes two tabs after. Also, ensure that comments following #endif are indented the same as comments following other preprocessor commands such as #else. That inconsistency turns out to have been self-inflicted damage from a poorly-thought-through post-indent "fixup" in pgindent. This patch is much less interesting than the first round of indent changes, but also bulkier, so I thought it best to separate the effects. Discussion: https://postgr.es/m/E1dAmxK-0006EE-1r@gemulon.postgresql.org Discussion: https://postgr.es/m/30527.1495162840@sss.pgh.pa.us
2017-06-21 21:18:54 +02:00
int attnum[MaxAttrNum]; /* fnumbers of start/stop columns */
Datum oldtimeon,
2003-08-04 02:43:34 +02:00
oldtimeoff;
Datum newtimeon,
2003-08-04 02:43:34 +02:00
newtimeoff,
newuser,
nulltext;
Datum *cvals; /* column values */
char *cnulls; /* column nulls */
char *relname; /* triggered relation name */
Relation rel; /* triggered relation */
HeapTuple trigtuple;
HeapTuple newtuple = NULL;
HeapTuple rettuple;
TupleDesc tupdesc; /* tuple description */
2003-08-04 02:43:34 +02:00
int natts; /* # of attributes */
EPlan *plan; /* prepared plan */
char ident[2 * NAMEDATALEN];
bool isnull; /* to know is some column NULL or not */
bool isinsert = false;
2003-08-04 02:43:34 +02:00
int ret;
int i;
/*
* Some checks first...
*/
/* Called by trigger manager ? */
2003-08-04 02:43:34 +02:00
if (!CALLED_AS_TRIGGER(fcinfo))
elog(ERROR, "timetravel: not fired by trigger manager");
/* Should be called for ROW trigger */
if (!TRIGGER_FIRED_FOR_ROW(trigdata->tg_event))
elog(ERROR, "timetravel: must be fired for row");
/* Should be called BEFORE */
if (!TRIGGER_FIRED_BEFORE(trigdata->tg_event))
elog(ERROR, "timetravel: must be fired before event");
/* INSERT ? */
2003-08-04 02:43:34 +02:00
if (TRIGGER_FIRED_BY_INSERT(trigdata->tg_event))
isinsert = true;
2003-08-04 02:43:34 +02:00
if (TRIGGER_FIRED_BY_UPDATE(trigdata->tg_event))
newtuple = trigdata->tg_newtuple;
trigtuple = trigdata->tg_trigtuple;
rel = trigdata->tg_relation;
relname = SPI_getrelname(rel);
/* check if TT is OFF for this relation */
2003-08-04 02:43:34 +02:00
if (0 == findTTStatus(relname))
{
/* OFF - nothing to do */
pfree(relname);
return PointerGetDatum((newtuple != NULL) ? newtuple : trigtuple);
}
trigger = trigdata->tg_trigger;
argc = trigger->tgnargs;
2003-08-04 02:43:34 +02:00
if (argc != MinAttrNum && argc != MaxAttrNum)
elog(ERROR, "timetravel (%s): invalid (!= %d or %d) number of arguments %d",
relname, MinAttrNum, MaxAttrNum, trigger->tgnargs);
args = trigger->tgargs;
tupdesc = rel->rd_att;
natts = tupdesc->natts;
2003-08-04 02:43:34 +02:00
for (i = 0; i < MinAttrNum; i++)
{
attnum[i] = SPI_fnumber(tupdesc, args[i]);
if (attnum[i] <= 0)
elog(ERROR, "timetravel (%s): there is no attribute %s", relname, args[i]);
2003-08-04 02:43:34 +02:00
if (SPI_gettypeid(tupdesc, attnum[i]) != ABSTIMEOID)
elog(ERROR, "timetravel (%s): attribute %s must be of abstime type",
relname, args[i]);
}
2003-08-04 02:43:34 +02:00
for (; i < argc; i++)
{
attnum[i] = SPI_fnumber(tupdesc, args[i]);
if (attnum[i] <= 0)
elog(ERROR, "timetravel (%s): there is no attribute %s", relname, args[i]);
2003-08-04 02:43:34 +02:00
if (SPI_gettypeid(tupdesc, attnum[i]) != TEXTOID)
elog(ERROR, "timetravel (%s): attribute %s must be of text type",
relname, args[i]);
}
/* create fields containing name */
newuser = CStringGetTextDatum(GetUserNameFromId(GetUserId(), false));
2003-08-04 02:43:34 +02:00
nulltext = (Datum) NULL;
2003-08-04 02:43:34 +02:00
if (isinsert)
{ /* INSERT */
int chnattrs = 0;
int chattrs[MaxAttrNum];
Datum newvals[MaxAttrNum];
bool newnulls[MaxAttrNum];
oldtimeon = SPI_getbinval(trigtuple, tupdesc, attnum[a_time_on], &isnull);
2003-08-04 02:43:34 +02:00
if (isnull)
{
newvals[chnattrs] = GetCurrentAbsoluteTime();
newnulls[chnattrs] = false;
chattrs[chnattrs] = attnum[a_time_on];
chnattrs++;
}
oldtimeoff = SPI_getbinval(trigtuple, tupdesc, attnum[a_time_off], &isnull);
2003-08-04 02:43:34 +02:00
if (isnull)
{
2003-08-04 02:43:34 +02:00
if ((chnattrs == 0 && DatumGetInt32(oldtimeon) >= NOEND_ABSTIME) ||
(chnattrs > 0 && DatumGetInt32(newvals[a_time_on]) >= NOEND_ABSTIME))
elog(ERROR, "timetravel (%s): %s is infinity", relname, args[a_time_on]);
newvals[chnattrs] = NOEND_ABSTIME;
newnulls[chnattrs] = false;
chattrs[chnattrs] = attnum[a_time_off];
chnattrs++;
}
else
{
2003-08-04 02:43:34 +02:00
if ((chnattrs == 0 && DatumGetInt32(oldtimeon) > DatumGetInt32(oldtimeoff)) ||
(chnattrs > 0 && DatumGetInt32(newvals[a_time_on]) > DatumGetInt32(oldtimeoff)))
elog(ERROR, "timetravel (%s): %s gt %s", relname, args[a_time_on], args[a_time_off]);
}
pfree(relname);
2003-08-04 02:43:34 +02:00
if (chnattrs <= 0)
return PointerGetDatum(trigtuple);
2003-08-04 02:43:34 +02:00
if (argc == MaxAttrNum)
{
/* clear update_user value */
newvals[chnattrs] = nulltext;
newnulls[chnattrs] = true;
chattrs[chnattrs] = attnum[a_upd_user];
chnattrs++;
/* clear delete_user value */
newvals[chnattrs] = nulltext;
newnulls[chnattrs] = true;
chattrs[chnattrs] = attnum[a_del_user];
chnattrs++;
/* set insert_user value */
newvals[chnattrs] = newuser;
newnulls[chnattrs] = false;
chattrs[chnattrs] = attnum[a_ins_user];
chnattrs++;
}
rettuple = heap_modify_tuple_by_cols(trigtuple, tupdesc,
chnattrs, chattrs,
newvals, newnulls);
return PointerGetDatum(rettuple);
/* end of INSERT */
}
/* UPDATE/DELETE: */
oldtimeon = SPI_getbinval(trigtuple, tupdesc, attnum[a_time_on], &isnull);
2003-08-04 02:43:34 +02:00
if (isnull)
elog(ERROR, "timetravel (%s): %s must be NOT NULL", relname, args[a_time_on]);
oldtimeoff = SPI_getbinval(trigtuple, tupdesc, attnum[a_time_off], &isnull);
2003-08-04 02:43:34 +02:00
if (isnull)
elog(ERROR, "timetravel (%s): %s must be NOT NULL", relname, args[a_time_off]);
/*
2005-10-15 04:49:52 +02:00
* If DELETE/UPDATE of tuple with stop_date neq INFINITY then say upper
* Executor to skip operation for this tuple
*/
2003-08-04 02:43:34 +02:00
if (newtuple != NULL)
{ /* UPDATE */
newtimeon = SPI_getbinval(newtuple, tupdesc, attnum[a_time_on], &isnull);
2003-08-04 02:43:34 +02:00
if (isnull)
elog(ERROR, "timetravel (%s): %s must be NOT NULL", relname, args[a_time_on]);
newtimeoff = SPI_getbinval(newtuple, tupdesc, attnum[a_time_off], &isnull);
2003-08-04 02:43:34 +02:00
if (isnull)
elog(ERROR, "timetravel (%s): %s must be NOT NULL", relname, args[a_time_off]);
2003-08-04 02:43:34 +02:00
if (oldtimeon != newtimeon || oldtimeoff != newtimeoff)
elog(ERROR, "timetravel (%s): you cannot change %s and/or %s columns (use set_timetravel)",
relname, args[a_time_on], args[a_time_off]);
}
2003-08-04 02:43:34 +02:00
if (oldtimeoff != NOEND_ABSTIME)
2005-10-15 04:49:52 +02:00
{ /* current record is a deleted/updated record */
pfree(relname);
return PointerGetDatum(NULL);
}
newtimeoff = GetCurrentAbsoluteTime();
/* Connect to SPI manager */
2003-08-04 02:43:34 +02:00
if ((ret = SPI_connect()) < 0)
elog(ERROR, "timetravel (%s): SPI_connect returned %d", relname, ret);
/* Fetch tuple values and nulls */
cvals = (Datum *) palloc(natts * sizeof(Datum));
cnulls = (char *) palloc(natts * sizeof(char));
2003-08-04 02:43:34 +02:00
for (i = 0; i < natts; i++)
{
cvals[i] = SPI_getbinval(trigtuple, tupdesc, i + 1, &isnull);
cnulls[i] = (isnull) ? 'n' : ' ';
}
/* change date column(s) */
2005-10-15 04:49:52 +02:00
cvals[attnum[a_time_off] - 1] = newtimeoff; /* stop_date eq current date */
cnulls[attnum[a_time_off] - 1] = ' ';
2003-08-04 02:43:34 +02:00
if (!newtuple)
{ /* DELETE */
if (argc == MaxAttrNum)
{
2003-08-04 02:43:34 +02:00
cvals[attnum[a_del_user] - 1] = newuser; /* set delete user */
cnulls[attnum[a_del_user] - 1] = ' ';
}
}
/*
2005-10-15 04:49:52 +02:00
* Construct ident string as TriggerName $ TriggeredRelationId and try to
* find prepared execution plan.
*/
snprintf(ident, sizeof(ident), "%s$%u", trigger->tgname, rel->rd_id);
plan = find_plan(ident, &Plans, &nPlans);
/* if there is no plan ... */
2003-08-04 02:43:34 +02:00
if (plan->splan == NULL)
{
SPIPlanPtr pplan;
2003-08-04 02:43:34 +02:00
Oid *ctypes;
char sql[8192];
2004-08-29 07:07:03 +02:00
char separ = ' ';
/* allocate ctypes for preparation */
ctypes = (Oid *) palloc(natts * sizeof(Oid));
/*
* Construct query: INSERT INTO _relation_ VALUES ($1, ...)
*/
snprintf(sql, sizeof(sql), "INSERT INTO %s VALUES (", relname);
2003-08-04 02:43:34 +02:00
for (i = 1; i <= natts; i++)
{
ctypes[i - 1] = SPI_gettypeid(tupdesc, i);
if (!(TupleDescAttr(tupdesc, i - 1)->attisdropped)) /* skip dropped columns */
{
2004-08-29 07:07:03 +02:00
snprintf(sql + strlen(sql), sizeof(sql) - strlen(sql), "%c$%d", separ, i);
separ = ',';
}
}
snprintf(sql + strlen(sql), sizeof(sql) - strlen(sql), ")");
2003-07-27 18:32:34 +02:00
elog(DEBUG4, "timetravel (%s) update: sql: %s", relname, sql);
/* Prepare plan for query */
pplan = SPI_prepare(sql, natts, ctypes);
2003-08-04 02:43:34 +02:00
if (pplan == NULL)
elog(ERROR, "timetravel (%s): SPI_prepare returned %s", relname, SPI_result_code_string(SPI_result));
/*
2005-10-15 04:49:52 +02:00
* Remember that SPI_prepare places plan in current memory context -
* so, we have to save plan in Top memory context for later use.
*/
if (SPI_keepplan(pplan))
elog(ERROR, "timetravel (%s): SPI_keepplan failed", relname);
plan->splan = pplan;
}
/*
* Ok, execute prepared plan.
*/
ret = SPI_execp(plan->splan, cvals, cnulls, 0);
2003-08-04 02:43:34 +02:00
if (ret < 0)
elog(ERROR, "timetravel (%s): SPI_execp returned %d", relname, ret);
/* Tuple to return to upper Executor ... */
2003-08-04 02:43:34 +02:00
if (newtuple)
{ /* UPDATE */
int chnattrs = 0;
int chattrs[MaxAttrNum];
Datum newvals[MaxAttrNum];
char newnulls[MaxAttrNum];
newvals[chnattrs] = newtimeoff;
newnulls[chnattrs] = ' ';
chattrs[chnattrs] = attnum[a_time_on];
chnattrs++;
newvals[chnattrs] = NOEND_ABSTIME;
newnulls[chnattrs] = ' ';
chattrs[chnattrs] = attnum[a_time_off];
chnattrs++;
2003-08-04 02:43:34 +02:00
if (argc == MaxAttrNum)
{
/* set update_user value */
newvals[chnattrs] = newuser;
newnulls[chnattrs] = ' ';
chattrs[chnattrs] = attnum[a_upd_user];
chnattrs++;
/* clear delete_user value */
newvals[chnattrs] = nulltext;
newnulls[chnattrs] = 'n';
chattrs[chnattrs] = attnum[a_del_user];
chnattrs++;
/* set insert_user value */
newvals[chnattrs] = nulltext;
newnulls[chnattrs] = 'n';
chattrs[chnattrs] = attnum[a_ins_user];
chnattrs++;
}
/*
* Use SPI_modifytuple() here because we are inside SPI environment
* but rettuple must be allocated in caller's context.
*/
rettuple = SPI_modifytuple(rel, newtuple, chnattrs, chattrs, newvals, newnulls);
}
2003-08-04 02:43:34 +02:00
else
/* DELETE case */
rettuple = trigtuple;
SPI_finish(); /* don't forget say Bye to SPI mgr */
pfree(relname);
return PointerGetDatum(rettuple);
}
/*
* set_timetravel (relname, on) --
* turn timetravel for specified relation ON/OFF
*/
PG_FUNCTION_INFO_V1(set_timetravel);
Datum
set_timetravel(PG_FUNCTION_ARGS)
{
2003-08-04 02:43:34 +02:00
Name relname = PG_GETARG_NAME(0);
int32 on = PG_GETARG_INT32(1);
char *rname;
char *d;
char *s;
int32 ret;
TTOffList *prev,
2003-08-04 02:43:34 +02:00
*pp;
prev = NULL;
for (pp = TTOff; pp; prev = pp, pp = pp->next)
{
2003-08-04 02:43:34 +02:00
if (namestrcmp(relname, pp->name) == 0)
break;
}
2003-08-04 02:43:34 +02:00
if (pp)
{
/* OFF currently */
2003-08-04 02:43:34 +02:00
if (on != 0)
{
/* turn ON */
if (prev)
prev->next = pp->next;
else
TTOff = pp->next;
free(pp);
}
ret = 0;
}
else
{
/* ON currently */
2003-08-04 02:43:34 +02:00
if (on == 0)
{
/* turn OFF */
s = rname = DatumGetCString(DirectFunctionCall1(nameout, NameGetDatum(relname)));
2003-08-04 02:43:34 +02:00
if (s)
{
2017-06-21 20:39:04 +02:00
pp = malloc(offsetof(TTOffList, name) + strlen(rname) + 1);
2003-08-04 02:43:34 +02:00
if (pp)
{
pp->next = NULL;
d = pp->name;
while (*s)
2003-08-04 02:43:34 +02:00
*d++ = tolower((unsigned char) *s++);
*d = '\0';
if (prev)
prev->next = pp;
else
TTOff = pp;
}
pfree(rname);
}
}
ret = 1;
}
PG_RETURN_INT32(ret);
}
/*
* get_timetravel (relname) --
2003-08-04 02:43:34 +02:00
* get timetravel status for specified relation (ON/OFF)
*/
PG_FUNCTION_INFO_V1(get_timetravel);
Datum
get_timetravel(PG_FUNCTION_ARGS)
{
Name relname = PG_GETARG_NAME(0);
2003-08-04 02:43:34 +02:00
TTOffList *pp;
for (pp = TTOff; pp; pp = pp->next)
{
2003-08-04 02:43:34 +02:00
if (namestrcmp(relname, pp->name) == 0)
PG_RETURN_INT32(0);
}
PG_RETURN_INT32(1);
}
static int
findTTStatus(char *name)
{
2003-08-04 02:43:34 +02:00
TTOffList *pp;
for (pp = TTOff; pp; pp = pp->next)
if (pg_strcasecmp(name, pp->name) == 0)
return 0;
return 1;
}
/*
AbsoluteTime
currabstime()
{
return GetCurrentAbsoluteTime();
}
*/
static EPlan *
find_plan(char *ident, EPlan **eplan, int *nplans)
{
2003-08-04 02:43:34 +02:00
EPlan *newp;
int i;
2003-08-04 02:43:34 +02:00
if (*nplans > 0)
{
2003-08-04 02:43:34 +02:00
for (i = 0; i < *nplans; i++)
{
2003-08-04 02:43:34 +02:00
if (strcmp((*eplan)[i].ident, ident) == 0)
break;
}
2003-08-04 02:43:34 +02:00
if (i != *nplans)
return (*eplan + i);
*eplan = (EPlan *) realloc(*eplan, (i + 1) * sizeof(EPlan));
newp = *eplan + i;
}
else
{
newp = *eplan = (EPlan *) malloc(sizeof(EPlan));
(*nplans) = i = 0;
}
newp->ident = strdup(ident);
newp->splan = NULL;
(*nplans)++;
return newp;
}