1 /*
2 * PostgreSQL definitions for managed Large Objects.
3 *
4 * contrib/lo/lo.c
5 *
6 */
7
8 #include "postgres.h"
9
10 #include "commands/trigger.h"
11 #include "executor/spi.h"
12 #include "libpq/be-fsstubs.h"
13 #include "utils/rel.h"
14
15 PG_MODULE_MAGIC;
16
17 #define atooid(x) ((Oid) strtoul((x), NULL, 10))
18
19
20 /*
21 * This is the trigger that protects us from orphaned large objects
22 */
23 PG_FUNCTION_INFO_V1(lo_manage);
24
25 Datum
lo_manage(PG_FUNCTION_ARGS)26 lo_manage(PG_FUNCTION_ARGS)
27 {
28 TriggerData *trigdata = (TriggerData *) fcinfo->context;
29 int attnum; /* attribute number to monitor */
30 char **args; /* Args containing attr name */
31 TupleDesc tupdesc; /* Tuple Descriptor */
32 HeapTuple rettuple; /* Tuple to be returned */
33 bool isdelete; /* are we deleting? */
34 HeapTuple newtuple; /* The new value for tuple */
35 HeapTuple trigtuple; /* The original value of tuple */
36
37 if (!CALLED_AS_TRIGGER(fcinfo)) /* internal error */
38 elog(ERROR, "lo_manage: not fired by trigger manager");
39
40 if (!TRIGGER_FIRED_FOR_ROW(trigdata->tg_event)) /* internal error */
41 elog(ERROR, "%s: must be fired for row",
42 trigdata->tg_trigger->tgname);
43
44 /*
45 * Fetch some values from trigdata
46 */
47 newtuple = trigdata->tg_newtuple;
48 trigtuple = trigdata->tg_trigtuple;
49 tupdesc = trigdata->tg_relation->rd_att;
50 args = trigdata->tg_trigger->tgargs;
51
52 if (args == NULL) /* internal error */
53 elog(ERROR, "%s: no column name provided in the trigger definition",
54 trigdata->tg_trigger->tgname);
55
56 /* tuple to return to Executor */
57 if (TRIGGER_FIRED_BY_UPDATE(trigdata->tg_event))
58 rettuple = newtuple;
59 else
60 rettuple = trigtuple;
61
62 /* Are we deleting the row? */
63 isdelete = TRIGGER_FIRED_BY_DELETE(trigdata->tg_event);
64
65 /* Get the column we're interested in */
66 attnum = SPI_fnumber(tupdesc, args[0]);
67
68 if (attnum <= 0)
69 elog(ERROR, "%s: column \"%s\" does not exist",
70 trigdata->tg_trigger->tgname, args[0]);
71
72 /*
73 * Handle updates
74 *
75 * Here, if the value of the monitored attribute changes, then the large
76 * object associated with the original value is unlinked.
77 */
78 if (newtuple != NULL)
79 {
80 char *orig = SPI_getvalue(trigtuple, tupdesc, attnum);
81 char *newv = SPI_getvalue(newtuple, tupdesc, attnum);
82
83 if (orig != NULL && (newv == NULL || strcmp(orig, newv) != 0))
84 DirectFunctionCall1(lo_unlink,
85 ObjectIdGetDatum(atooid(orig)));
86
87 if (newv)
88 pfree(newv);
89 if (orig)
90 pfree(orig);
91 }
92
93 /*
94 * Handle deleting of rows
95 *
96 * Here, we unlink the large object associated with the managed attribute
97 */
98 if (isdelete)
99 {
100 char *orig = SPI_getvalue(trigtuple, tupdesc, attnum);
101
102 if (orig != NULL)
103 {
104 DirectFunctionCall1(lo_unlink,
105 ObjectIdGetDatum(atooid(orig)));
106
107 pfree(orig);
108 }
109 }
110
111 return PointerGetDatum(rettuple);
112 }
113