aboutsummaryrefslogtreecommitdiffstatshomepage
path: root/libraries/sqlite/win32/trigger.c
diff options
context:
space:
mode:
Diffstat (limited to 'libraries/sqlite/win32/trigger.c')
-rwxr-xr-xlibraries/sqlite/win32/trigger.c839
1 files changed, 839 insertions, 0 deletions
diff --git a/libraries/sqlite/win32/trigger.c b/libraries/sqlite/win32/trigger.c
new file mode 100755
index 0000000..252dd7b
--- /dev/null
+++ b/libraries/sqlite/win32/trigger.c
@@ -0,0 +1,839 @@
1/*
2**
3** The author disclaims copyright to this source code. In place of
4** a legal notice, here is a blessing:
5**
6** May you do good and not evil.
7** May you find forgiveness for yourself and forgive others.
8** May you share freely, never taking more than you give.
9**
10*************************************************************************
11*
12*/
13#include "sqliteInt.h"
14
15#ifndef SQLITE_OMIT_TRIGGER
16/*
17** Delete a linked list of TriggerStep structures.
18*/
19void sqlite3DeleteTriggerStep(TriggerStep *pTriggerStep){
20 while( pTriggerStep ){
21 TriggerStep * pTmp = pTriggerStep;
22 pTriggerStep = pTriggerStep->pNext;
23
24 if( pTmp->target.dyn ) sqlite3_free((char*)pTmp->target.z);
25 sqlite3ExprDelete(pTmp->pWhere);
26 sqlite3ExprListDelete(pTmp->pExprList);
27 sqlite3SelectDelete(pTmp->pSelect);
28 sqlite3IdListDelete(pTmp->pIdList);
29
30 sqlite3_free(pTmp);
31 }
32}
33
34/*
35** This is called by the parser when it sees a CREATE TRIGGER statement
36** up to the point of the BEGIN before the trigger actions. A Trigger
37** structure is generated based on the information available and stored
38** in pParse->pNewTrigger. After the trigger actions have been parsed, the
39** sqlite3FinishTrigger() function is called to complete the trigger
40** construction process.
41*/
42void sqlite3BeginTrigger(
43 Parse *pParse, /* The parse context of the CREATE TRIGGER statement */
44 Token *pName1, /* The name of the trigger */
45 Token *pName2, /* The name of the trigger */
46 int tr_tm, /* One of TK_BEFORE, TK_AFTER, TK_INSTEAD */
47 int op, /* One of TK_INSERT, TK_UPDATE, TK_DELETE */
48 IdList *pColumns, /* column list if this is an UPDATE OF trigger */
49 SrcList *pTableName,/* The name of the table/view the trigger applies to */
50 Expr *pWhen, /* WHEN clause */
51 int isTemp, /* True if the TEMPORARY keyword is present */
52 int noErr /* Suppress errors if the trigger already exists */
53){
54 Trigger *pTrigger = 0;
55 Table *pTab;
56 char *zName = 0; /* Name of the trigger */
57 sqlite3 *db = pParse->db;
58 int iDb; /* The database to store the trigger in */
59 Token *pName; /* The unqualified db name */
60 DbFixer sFix;
61 int iTabDb;
62
63 assert( pName1!=0 ); /* pName1->z might be NULL, but not pName1 itself */
64 assert( pName2!=0 );
65 if( isTemp ){
66 /* If TEMP was specified, then the trigger name may not be qualified. */
67 if( pName2->n>0 ){
68 sqlite3ErrorMsg(pParse, "temporary trigger may not have qualified name");
69 goto trigger_cleanup;
70 }
71 iDb = 1;
72 pName = pName1;
73 }else{
74 /* Figure out the db that the the trigger will be created in */
75 iDb = sqlite3TwoPartName(pParse, pName1, pName2, &pName);
76 if( iDb<0 ){
77 goto trigger_cleanup;
78 }
79 }
80
81 /* If the trigger name was unqualified, and the table is a temp table,
82 ** then set iDb to 1 to create the trigger in the temporary database.
83 ** If sqlite3SrcListLookup() returns 0, indicating the table does not
84 ** exist, the error is caught by the block below.
85 */
86 if( !pTableName || db->mallocFailed ){
87 goto trigger_cleanup;
88 }
89 pTab = sqlite3SrcListLookup(pParse, pTableName);
90 if( pName2->n==0 && pTab && pTab->pSchema==db->aDb[1].pSchema ){
91 iDb = 1;
92 }
93
94 /* Ensure the table name matches database name and that the table exists */
95 if( db->mallocFailed ) goto trigger_cleanup;
96 assert( pTableName->nSrc==1 );
97 if( sqlite3FixInit(&sFix, pParse, iDb, "trigger", pName) &&
98 sqlite3FixSrcList(&sFix, pTableName) ){
99 goto trigger_cleanup;
100 }
101 pTab = sqlite3SrcListLookup(pParse, pTableName);
102 if( !pTab ){
103 /* The table does not exist. */
104 goto trigger_cleanup;
105 }
106 if( IsVirtual(pTab) ){
107 sqlite3ErrorMsg(pParse, "cannot create triggers on virtual tables");
108 goto trigger_cleanup;
109 }
110
111 /* Check that the trigger name is not reserved and that no trigger of the
112 ** specified name exists */
113 zName = sqlite3NameFromToken(db, pName);
114 if( !zName || SQLITE_OK!=sqlite3CheckObjectName(pParse, zName) ){
115 goto trigger_cleanup;
116 }
117 if( sqlite3HashFind(&(db->aDb[iDb].pSchema->trigHash), zName,strlen(zName)) ){
118 if( !noErr ){
119 sqlite3ErrorMsg(pParse, "trigger %T already exists", pName);
120 }
121 goto trigger_cleanup;
122 }
123
124 /* Do not create a trigger on a system table */
125 if( sqlite3StrNICmp(pTab->zName, "sqlite_", 7)==0 ){
126 sqlite3ErrorMsg(pParse, "cannot create trigger on system table");
127 pParse->nErr++;
128 goto trigger_cleanup;
129 }
130
131 /* INSTEAD of triggers are only for views and views only support INSTEAD
132 ** of triggers.
133 */
134 if( pTab->pSelect && tr_tm!=TK_INSTEAD ){
135 sqlite3ErrorMsg(pParse, "cannot create %s trigger on view: %S",
136 (tr_tm == TK_BEFORE)?"BEFORE":"AFTER", pTableName, 0);
137 goto trigger_cleanup;
138 }
139 if( !pTab->pSelect && tr_tm==TK_INSTEAD ){
140 sqlite3ErrorMsg(pParse, "cannot create INSTEAD OF"
141 " trigger on table: %S", pTableName, 0);
142 goto trigger_cleanup;
143 }
144 iTabDb = sqlite3SchemaToIndex(db, pTab->pSchema);
145
146#ifndef SQLITE_OMIT_AUTHORIZATION
147 {
148 int code = SQLITE_CREATE_TRIGGER;
149 const char *zDb = db->aDb[iTabDb].zName;
150 const char *zDbTrig = isTemp ? db->aDb[1].zName : zDb;
151 if( iTabDb==1 || isTemp ) code = SQLITE_CREATE_TEMP_TRIGGER;
152 if( sqlite3AuthCheck(pParse, code, zName, pTab->zName, zDbTrig) ){
153 goto trigger_cleanup;
154 }
155 if( sqlite3AuthCheck(pParse, SQLITE_INSERT, SCHEMA_TABLE(iTabDb),0,zDb)){
156 goto trigger_cleanup;
157 }
158 }
159#endif
160
161 /* INSTEAD OF triggers can only appear on views and BEFORE triggers
162 ** cannot appear on views. So we might as well translate every
163 ** INSTEAD OF trigger into a BEFORE trigger. It simplifies code
164 ** elsewhere.
165 */
166 if (tr_tm == TK_INSTEAD){
167 tr_tm = TK_BEFORE;
168 }
169
170 /* Build the Trigger object */
171 pTrigger = (Trigger*)sqlite3DbMallocZero(db, sizeof(Trigger));
172 if( pTrigger==0 ) goto trigger_cleanup;
173 pTrigger->name = zName;
174 zName = 0;
175 pTrigger->table = sqlite3DbStrDup(db, pTableName->a[0].zName);
176 pTrigger->pSchema = db->aDb[iDb].pSchema;
177 pTrigger->pTabSchema = pTab->pSchema;
178 pTrigger->op = op;
179 pTrigger->tr_tm = tr_tm==TK_BEFORE ? TRIGGER_BEFORE : TRIGGER_AFTER;
180 pTrigger->pWhen = sqlite3ExprDup(db, pWhen);
181 pTrigger->pColumns = sqlite3IdListDup(db, pColumns);
182 sqlite3TokenCopy(db, &pTrigger->nameToken,pName);
183 assert( pParse->pNewTrigger==0 );
184 pParse->pNewTrigger = pTrigger;
185
186trigger_cleanup:
187 sqlite3_free(zName);
188 sqlite3SrcListDelete(pTableName);
189 sqlite3IdListDelete(pColumns);
190 sqlite3ExprDelete(pWhen);
191 if( !pParse->pNewTrigger ){
192 sqlite3DeleteTrigger(pTrigger);
193 }else{
194 assert( pParse->pNewTrigger==pTrigger );
195 }
196}
197
198/*
199** This routine is called after all of the trigger actions have been parsed
200** in order to complete the process of building the trigger.
201*/
202void sqlite3FinishTrigger(
203 Parse *pParse, /* Parser context */
204 TriggerStep *pStepList, /* The triggered program */
205 Token *pAll /* Token that describes the complete CREATE TRIGGER */
206){
207 Trigger *pTrig = 0; /* The trigger whose construction is finishing up */
208 sqlite3 *db = pParse->db; /* The database */
209 DbFixer sFix;
210 int iDb; /* Database containing the trigger */
211
212 pTrig = pParse->pNewTrigger;
213 pParse->pNewTrigger = 0;
214 if( pParse->nErr || !pTrig ) goto triggerfinish_cleanup;
215 iDb = sqlite3SchemaToIndex(pParse->db, pTrig->pSchema);
216 pTrig->step_list = pStepList;
217 while( pStepList ){
218 pStepList->pTrig = pTrig;
219 pStepList = pStepList->pNext;
220 }
221 if( sqlite3FixInit(&sFix, pParse, iDb, "trigger", &pTrig->nameToken)
222 && sqlite3FixTriggerStep(&sFix, pTrig->step_list) ){
223 goto triggerfinish_cleanup;
224 }
225
226 /* if we are not initializing, and this trigger is not on a TEMP table,
227 ** build the sqlite_master entry
228 */
229 if( !db->init.busy ){
230 static const VdbeOpList insertTrig[] = {
231 { OP_NewRowid, 0, 0, 0 },
232 { OP_String8, 0, 0, "trigger" },
233 { OP_String8, 0, 0, 0 }, /* 2: trigger name */
234 { OP_String8, 0, 0, 0 }, /* 3: table name */
235 { OP_Integer, 0, 0, 0 },
236 { OP_String8, 0, 0, "CREATE TRIGGER "},
237 { OP_String8, 0, 0, 0 }, /* 6: SQL */
238 { OP_Concat, 0, 0, 0 },
239 { OP_MakeRecord, 5, 0, "aaada" },
240 { OP_Insert, 0, 0, 0 },
241 };
242 int addr;
243 Vdbe *v;
244
245 /* Make an entry in the sqlite_master table */
246 v = sqlite3GetVdbe(pParse);
247 if( v==0 ) goto triggerfinish_cleanup;
248 sqlite3BeginWriteOperation(pParse, 0, iDb);
249 sqlite3OpenMasterTable(pParse, iDb);
250 addr = sqlite3VdbeAddOpList(v, ArraySize(insertTrig), insertTrig);
251 sqlite3VdbeChangeP3(v, addr+2, pTrig->name, 0);
252 sqlite3VdbeChangeP3(v, addr+3, pTrig->table, 0);
253 sqlite3VdbeChangeP3(v, addr+6, (char*)pAll->z, pAll->n);
254 sqlite3ChangeCookie(db, v, iDb);
255 sqlite3VdbeAddOp(v, OP_Close, 0, 0);
256 sqlite3VdbeOp3(v, OP_ParseSchema, iDb, 0, sqlite3MPrintf(
257 db, "type='trigger' AND name='%q'", pTrig->name), P3_DYNAMIC
258 );
259 }
260
261 if( db->init.busy ){
262 int n;
263 Table *pTab;
264 Trigger *pDel;
265 pDel = sqlite3HashInsert(&db->aDb[iDb].pSchema->trigHash,
266 pTrig->name, strlen(pTrig->name), pTrig);
267 if( pDel ){
268 assert( pDel==pTrig );
269 db->mallocFailed = 1;
270 goto triggerfinish_cleanup;
271 }
272 n = strlen(pTrig->table) + 1;
273 pTab = sqlite3HashFind(&pTrig->pTabSchema->tblHash, pTrig->table, n);
274 assert( pTab!=0 );
275 pTrig->pNext = pTab->pTrigger;
276 pTab->pTrigger = pTrig;
277 pTrig = 0;
278 }
279
280triggerfinish_cleanup:
281 sqlite3DeleteTrigger(pTrig);
282 assert( !pParse->pNewTrigger );
283 sqlite3DeleteTriggerStep(pStepList);
284}
285
286/*
287** Make a copy of all components of the given trigger step. This has
288** the effect of copying all Expr.token.z values into memory obtained
289** from sqlite3_malloc(). As initially created, the Expr.token.z values
290** all point to the input string that was fed to the parser. But that
291** string is ephemeral - it will go away as soon as the sqlite3_exec()
292** call that started the parser exits. This routine makes a persistent
293** copy of all the Expr.token.z strings so that the TriggerStep structure
294** will be valid even after the sqlite3_exec() call returns.
295*/
296static void sqlitePersistTriggerStep(sqlite3 *db, TriggerStep *p){
297 if( p->target.z ){
298 p->target.z = (u8*)sqlite3DbStrNDup(db, (char*)p->target.z, p->target.n);
299 p->target.dyn = 1;
300 }
301 if( p->pSelect ){
302 Select *pNew = sqlite3SelectDup(db, p->pSelect);
303 sqlite3SelectDelete(p->pSelect);
304 p->pSelect = pNew;
305 }
306 if( p->pWhere ){
307 Expr *pNew = sqlite3ExprDup(db, p->pWhere);
308 sqlite3ExprDelete(p->pWhere);
309 p->pWhere = pNew;
310 }
311 if( p->pExprList ){
312 ExprList *pNew = sqlite3ExprListDup(db, p->pExprList);
313 sqlite3ExprListDelete(p->pExprList);
314 p->pExprList = pNew;
315 }
316 if( p->pIdList ){
317 IdList *pNew = sqlite3IdListDup(db, p->pIdList);
318 sqlite3IdListDelete(p->pIdList);
319 p->pIdList = pNew;
320 }
321}
322
323/*
324** Turn a SELECT statement (that the pSelect parameter points to) into
325** a trigger step. Return a pointer to a TriggerStep structure.
326**
327** The parser calls this routine when it finds a SELECT statement in
328** body of a TRIGGER.
329*/
330TriggerStep *sqlite3TriggerSelectStep(sqlite3 *db, Select *pSelect){
331 TriggerStep *pTriggerStep = sqlite3DbMallocZero(db, sizeof(TriggerStep));
332 if( pTriggerStep==0 ) {
333 sqlite3SelectDelete(pSelect);
334 return 0;
335 }
336
337 pTriggerStep->op = TK_SELECT;
338 pTriggerStep->pSelect = pSelect;
339 pTriggerStep->orconf = OE_Default;
340 sqlitePersistTriggerStep(db, pTriggerStep);
341
342 return pTriggerStep;
343}
344
345/*
346** Build a trigger step out of an INSERT statement. Return a pointer
347** to the new trigger step.
348**
349** The parser calls this routine when it sees an INSERT inside the
350** body of a trigger.
351*/
352TriggerStep *sqlite3TriggerInsertStep(
353 sqlite3 *db, /* The database connection */
354 Token *pTableName, /* Name of the table into which we insert */
355 IdList *pColumn, /* List of columns in pTableName to insert into */
356 ExprList *pEList, /* The VALUE clause: a list of values to be inserted */
357 Select *pSelect, /* A SELECT statement that supplies values */
358 int orconf /* The conflict algorithm (OE_Abort, OE_Replace, etc.) */
359){
360 TriggerStep *pTriggerStep;
361
362 assert(pEList == 0 || pSelect == 0);
363 assert(pEList != 0 || pSelect != 0 || db->mallocFailed);
364
365 pTriggerStep = sqlite3DbMallocZero(db, sizeof(TriggerStep));
366 if( pTriggerStep ){
367 pTriggerStep->op = TK_INSERT;
368 pTriggerStep->pSelect = pSelect;
369 pTriggerStep->target = *pTableName;
370 pTriggerStep->pIdList = pColumn;
371 pTriggerStep->pExprList = pEList;
372 pTriggerStep->orconf = orconf;
373 sqlitePersistTriggerStep(db, pTriggerStep);
374 }else{
375 sqlite3IdListDelete(pColumn);
376 sqlite3ExprListDelete(pEList);
377 sqlite3SelectDelete(pSelect);
378 }
379
380 return pTriggerStep;
381}
382
383/*
384** Construct a trigger step that implements an UPDATE statement and return
385** a pointer to that trigger step. The parser calls this routine when it
386** sees an UPDATE statement inside the body of a CREATE TRIGGER.
387*/
388TriggerStep *sqlite3TriggerUpdateStep(
389 sqlite3 *db, /* The database connection */
390 Token *pTableName, /* Name of the table to be updated */
391 ExprList *pEList, /* The SET clause: list of column and new values */
392 Expr *pWhere, /* The WHERE clause */
393 int orconf /* The conflict algorithm. (OE_Abort, OE_Ignore, etc) */
394){
395 TriggerStep *pTriggerStep = sqlite3DbMallocZero(db, sizeof(TriggerStep));
396 if( pTriggerStep==0 ){
397 sqlite3ExprListDelete(pEList);
398 sqlite3ExprDelete(pWhere);
399 return 0;
400 }
401
402 pTriggerStep->op = TK_UPDATE;
403 pTriggerStep->target = *pTableName;
404 pTriggerStep->pExprList = pEList;
405 pTriggerStep->pWhere = pWhere;
406 pTriggerStep->orconf = orconf;
407 sqlitePersistTriggerStep(db, pTriggerStep);
408
409 return pTriggerStep;
410}
411
412/*
413** Construct a trigger step that implements a DELETE statement and return
414** a pointer to that trigger step. The parser calls this routine when it
415** sees a DELETE statement inside the body of a CREATE TRIGGER.
416*/
417TriggerStep *sqlite3TriggerDeleteStep(
418 sqlite3 *db, /* Database connection */
419 Token *pTableName, /* The table from which rows are deleted */
420 Expr *pWhere /* The WHERE clause */
421){
422 TriggerStep *pTriggerStep = sqlite3DbMallocZero(db, sizeof(TriggerStep));
423 if( pTriggerStep==0 ){
424 sqlite3ExprDelete(pWhere);
425 return 0;
426 }
427
428 pTriggerStep->op = TK_DELETE;
429 pTriggerStep->target = *pTableName;
430 pTriggerStep->pWhere = pWhere;
431 pTriggerStep->orconf = OE_Default;
432 sqlitePersistTriggerStep(db, pTriggerStep);
433
434 return pTriggerStep;
435}
436
437/*
438** Recursively delete a Trigger structure
439*/
440void sqlite3DeleteTrigger(Trigger *pTrigger){
441 if( pTrigger==0 ) return;
442 sqlite3DeleteTriggerStep(pTrigger->step_list);
443 sqlite3_free(pTrigger->name);
444 sqlite3_free(pTrigger->table);
445 sqlite3ExprDelete(pTrigger->pWhen);
446 sqlite3IdListDelete(pTrigger->pColumns);
447 if( pTrigger->nameToken.dyn ) sqlite3_free((char*)pTrigger->nameToken.z);
448 sqlite3_free(pTrigger);
449}
450
451/*
452** This function is called to drop a trigger from the database schema.
453**
454** This may be called directly from the parser and therefore identifies
455** the trigger by name. The sqlite3DropTriggerPtr() routine does the
456** same job as this routine except it takes a pointer to the trigger
457** instead of the trigger name.
458**/
459void sqlite3DropTrigger(Parse *pParse, SrcList *pName, int noErr){
460 Trigger *pTrigger = 0;
461 int i;
462 const char *zDb;
463 const char *zName;
464 int nName;
465 sqlite3 *db = pParse->db;
466
467 if( db->mallocFailed ) goto drop_trigger_cleanup;
468 if( SQLITE_OK!=sqlite3ReadSchema(pParse) ){
469 goto drop_trigger_cleanup;
470 }
471
472 assert( pName->nSrc==1 );
473 zDb = pName->a[0].zDatabase;
474 zName = pName->a[0].zName;
475 nName = strlen(zName);
476 for(i=OMIT_TEMPDB; i<db->nDb; i++){
477 int j = (i<2) ? i^1 : i; /* Search TEMP before MAIN */
478 if( zDb && sqlite3StrICmp(db->aDb[j].zName, zDb) ) continue;
479 pTrigger = sqlite3HashFind(&(db->aDb[j].pSchema->trigHash), zName, nName);
480 if( pTrigger ) break;
481 }
482 if( !pTrigger ){
483 if( !noErr ){
484 sqlite3ErrorMsg(pParse, "no such trigger: %S", pName, 0);
485 }
486 goto drop_trigger_cleanup;
487 }
488 sqlite3DropTriggerPtr(pParse, pTrigger);
489
490drop_trigger_cleanup:
491 sqlite3SrcListDelete(pName);
492}
493
494/*
495** Return a pointer to the Table structure for the table that a trigger
496** is set on.
497*/
498static Table *tableOfTrigger(Trigger *pTrigger){
499 int n = strlen(pTrigger->table) + 1;
500 return sqlite3HashFind(&pTrigger->pTabSchema->tblHash, pTrigger->table, n);
501}
502
503
504/*
505** Drop a trigger given a pointer to that trigger.
506*/
507void sqlite3DropTriggerPtr(Parse *pParse, Trigger *pTrigger){
508 Table *pTable;
509 Vdbe *v;
510 sqlite3 *db = pParse->db;
511 int iDb;
512
513 iDb = sqlite3SchemaToIndex(pParse->db, pTrigger->pSchema);
514 assert( iDb>=0 && iDb<db->nDb );
515 pTable = tableOfTrigger(pTrigger);
516 assert( pTable );
517 assert( pTable->pSchema==pTrigger->pSchema || iDb==1 );
518#ifndef SQLITE_OMIT_AUTHORIZATION
519 {
520 int code = SQLITE_DROP_TRIGGER;
521 const char *zDb = db->aDb[iDb].zName;
522 const char *zTab = SCHEMA_TABLE(iDb);
523 if( iDb==1 ) code = SQLITE_DROP_TEMP_TRIGGER;
524 if( sqlite3AuthCheck(pParse, code, pTrigger->name, pTable->zName, zDb) ||
525 sqlite3AuthCheck(pParse, SQLITE_DELETE, zTab, 0, zDb) ){
526 return;
527 }
528 }
529#endif
530
531 /* Generate code to destroy the database record of the trigger.
532 */
533 assert( pTable!=0 );
534 if( (v = sqlite3GetVdbe(pParse))!=0 ){
535 int base;
536 static const VdbeOpList dropTrigger[] = {
537 { OP_Rewind, 0, ADDR(9), 0},
538 { OP_String8, 0, 0, 0}, /* 1 */
539 { OP_Column, 0, 1, 0},
540 { OP_Ne, 0, ADDR(8), 0},
541 { OP_String8, 0, 0, "trigger"},
542 { OP_Column, 0, 0, 0},
543 { OP_Ne, 0, ADDR(8), 0},
544 { OP_Delete, 0, 0, 0},
545 { OP_Next, 0, ADDR(1), 0}, /* 8 */
546 };
547
548 sqlite3BeginWriteOperation(pParse, 0, iDb);
549 sqlite3OpenMasterTable(pParse, iDb);
550 base = sqlite3VdbeAddOpList(v, ArraySize(dropTrigger), dropTrigger);
551 sqlite3VdbeChangeP3(v, base+1, pTrigger->name, 0);
552 sqlite3ChangeCookie(db, v, iDb);
553 sqlite3VdbeAddOp(v, OP_Close, 0, 0);
554 sqlite3VdbeOp3(v, OP_DropTrigger, iDb, 0, pTrigger->name, 0);
555 }
556}
557
558/*
559** Remove a trigger from the hash tables of the sqlite* pointer.
560*/
561void sqlite3UnlinkAndDeleteTrigger(sqlite3 *db, int iDb, const char *zName){
562 Trigger *pTrigger;
563 int nName = strlen(zName);
564 pTrigger = sqlite3HashInsert(&(db->aDb[iDb].pSchema->trigHash),
565 zName, nName, 0);
566 if( pTrigger ){
567 Table *pTable = tableOfTrigger(pTrigger);
568 assert( pTable!=0 );
569 if( pTable->pTrigger == pTrigger ){
570 pTable->pTrigger = pTrigger->pNext;
571 }else{
572 Trigger *cc = pTable->pTrigger;
573 while( cc ){
574 if( cc->pNext == pTrigger ){
575 cc->pNext = cc->pNext->pNext;
576 break;
577 }
578 cc = cc->pNext;
579 }
580 assert(cc);
581 }
582 sqlite3DeleteTrigger(pTrigger);
583 db->flags |= SQLITE_InternChanges;
584 }
585}
586
587/*
588** pEList is the SET clause of an UPDATE statement. Each entry
589** in pEList is of the format <id>=<expr>. If any of the entries
590** in pEList have an <id> which matches an identifier in pIdList,
591** then return TRUE. If pIdList==NULL, then it is considered a
592** wildcard that matches anything. Likewise if pEList==NULL then
593** it matches anything so always return true. Return false only
594** if there is no match.
595*/
596static int checkColumnOverLap(IdList *pIdList, ExprList *pEList){
597 int e;
598 if( !pIdList || !pEList ) return 1;
599 for(e=0; e<pEList->nExpr; e++){
600 if( sqlite3IdListIndex(pIdList, pEList->a[e].zName)>=0 ) return 1;
601 }
602 return 0;
603}
604
605/*
606** Return a bit vector to indicate what kind of triggers exist for operation
607** "op" on table pTab. If pChanges is not NULL then it is a list of columns
608** that are being updated. Triggers only match if the ON clause of the
609** trigger definition overlaps the set of columns being updated.
610**
611** The returned bit vector is some combination of TRIGGER_BEFORE and
612** TRIGGER_AFTER.
613*/
614int sqlite3TriggersExist(
615 Parse *pParse, /* Used to check for recursive triggers */
616 Table *pTab, /* The table the contains the triggers */
617 int op, /* one of TK_DELETE, TK_INSERT, TK_UPDATE */
618 ExprList *pChanges /* Columns that change in an UPDATE statement */
619){
620 Trigger *pTrigger;
621 int mask = 0;
622
623 pTrigger = IsVirtual(pTab) ? 0 : pTab->pTrigger;
624 while( pTrigger ){
625 if( pTrigger->op==op && checkColumnOverLap(pTrigger->pColumns, pChanges) ){
626 mask |= pTrigger->tr_tm;
627 }
628 pTrigger = pTrigger->pNext;
629 }
630 return mask;
631}
632
633/*
634** Convert the pStep->target token into a SrcList and return a pointer
635** to that SrcList.
636**
637** This routine adds a specific database name, if needed, to the target when
638** forming the SrcList. This prevents a trigger in one database from
639** referring to a target in another database. An exception is when the
640** trigger is in TEMP in which case it can refer to any other database it
641** wants.
642*/
643static SrcList *targetSrcList(
644 Parse *pParse, /* The parsing context */
645 TriggerStep *pStep /* The trigger containing the target token */
646){
647 Token sDb; /* Dummy database name token */
648 int iDb; /* Index of the database to use */
649 SrcList *pSrc; /* SrcList to be returned */
650
651 iDb = sqlite3SchemaToIndex(pParse->db, pStep->pTrig->pSchema);
652 if( iDb==0 || iDb>=2 ){
653 assert( iDb<pParse->db->nDb );
654 sDb.z = (u8*)pParse->db->aDb[iDb].zName;
655 sDb.n = strlen((char*)sDb.z);
656 pSrc = sqlite3SrcListAppend(pParse->db, 0, &sDb, &pStep->target);
657 } else {
658 pSrc = sqlite3SrcListAppend(pParse->db, 0, &pStep->target, 0);
659 }
660 return pSrc;
661}
662
663/*
664** Generate VDBE code for zero or more statements inside the body of a
665** trigger.
666*/
667static int codeTriggerProgram(
668 Parse *pParse, /* The parser context */
669 TriggerStep *pStepList, /* List of statements inside the trigger body */
670 int orconfin /* Conflict algorithm. (OE_Abort, etc) */
671){
672 TriggerStep * pTriggerStep = pStepList;
673 int orconf;
674 Vdbe *v = pParse->pVdbe;
675 sqlite3 *db = pParse->db;
676
677 assert( pTriggerStep!=0 );
678 assert( v!=0 );
679 sqlite3VdbeAddOp(v, OP_ContextPush, 0, 0);
680 VdbeComment((v, "# begin trigger %s", pStepList->pTrig->name));
681 while( pTriggerStep ){
682 orconf = (orconfin == OE_Default)?pTriggerStep->orconf:orconfin;
683 pParse->trigStack->orconf = orconf;
684 switch( pTriggerStep->op ){
685 case TK_SELECT: {
686 Select *ss = sqlite3SelectDup(db, pTriggerStep->pSelect);
687 if( ss ){
688 sqlite3SelectResolve(pParse, ss, 0);
689 sqlite3Select(pParse, ss, SRT_Discard, 0, 0, 0, 0, 0);
690 sqlite3SelectDelete(ss);
691 }
692 break;
693 }
694 case TK_UPDATE: {
695 SrcList *pSrc;
696 pSrc = targetSrcList(pParse, pTriggerStep);
697 sqlite3VdbeAddOp(v, OP_ResetCount, 0, 0);
698 sqlite3Update(pParse, pSrc,
699 sqlite3ExprListDup(db, pTriggerStep->pExprList),
700 sqlite3ExprDup(db, pTriggerStep->pWhere), orconf);
701 sqlite3VdbeAddOp(v, OP_ResetCount, 1, 0);
702 break;
703 }
704 case TK_INSERT: {
705 SrcList *pSrc;
706 pSrc = targetSrcList(pParse, pTriggerStep);
707 sqlite3VdbeAddOp(v, OP_ResetCount, 0, 0);
708 sqlite3Insert(pParse, pSrc,
709 sqlite3ExprListDup(db, pTriggerStep->pExprList),
710 sqlite3SelectDup(db, pTriggerStep->pSelect),
711 sqlite3IdListDup(db, pTriggerStep->pIdList), orconf);
712 sqlite3VdbeAddOp(v, OP_ResetCount, 1, 0);
713 break;
714 }
715 case TK_DELETE: {
716 SrcList *pSrc;
717 sqlite3VdbeAddOp(v, OP_ResetCount, 0, 0);
718 pSrc = targetSrcList(pParse, pTriggerStep);
719 sqlite3DeleteFrom(pParse, pSrc,
720 sqlite3ExprDup(db, pTriggerStep->pWhere));
721 sqlite3VdbeAddOp(v, OP_ResetCount, 1, 0);
722 break;
723 }
724 default:
725 assert(0);
726 }
727 pTriggerStep = pTriggerStep->pNext;
728 }
729 sqlite3VdbeAddOp(v, OP_ContextPop, 0, 0);
730 VdbeComment((v, "# end trigger %s", pStepList->pTrig->name));
731
732 return 0;
733}
734
735/*
736** This is called to code FOR EACH ROW triggers.
737**
738** When the code that this function generates is executed, the following
739** must be true:
740**
741** 1. No cursors may be open in the main database. (But newIdx and oldIdx
742** can be indices of cursors in temporary tables. See below.)
743**
744** 2. If the triggers being coded are ON INSERT or ON UPDATE triggers, then
745** a temporary vdbe cursor (index newIdx) must be open and pointing at
746** a row containing values to be substituted for new.* expressions in the
747** trigger program(s).
748**
749** 3. If the triggers being coded are ON DELETE or ON UPDATE triggers, then
750** a temporary vdbe cursor (index oldIdx) must be open and pointing at
751** a row containing values to be substituted for old.* expressions in the
752** trigger program(s).
753**
754*/
755int sqlite3CodeRowTrigger(
756 Parse *pParse, /* Parse context */
757 int op, /* One of TK_UPDATE, TK_INSERT, TK_DELETE */
758 ExprList *pChanges, /* Changes list for any UPDATE OF triggers */
759 int tr_tm, /* One of TRIGGER_BEFORE, TRIGGER_AFTER */
760 Table *pTab, /* The table to code triggers from */
761 int newIdx, /* The indice of the "new" row to access */
762 int oldIdx, /* The indice of the "old" row to access */
763 int orconf, /* ON CONFLICT policy */
764 int ignoreJump /* Instruction to jump to for RAISE(IGNORE) */
765){
766 Trigger *p;
767 TriggerStack trigStackEntry;
768
769 assert(op == TK_UPDATE || op == TK_INSERT || op == TK_DELETE);
770 assert(tr_tm == TRIGGER_BEFORE || tr_tm == TRIGGER_AFTER );
771
772 assert(newIdx != -1 || oldIdx != -1);
773
774 for(p=pTab->pTrigger; p; p=p->pNext){
775 int fire_this = 0;
776
777 /* Determine whether we should code this trigger */
778 if(
779 p->op==op &&
780 p->tr_tm==tr_tm &&
781 (p->pSchema==p->pTabSchema || p->pSchema==pParse->db->aDb[1].pSchema) &&
782 (op!=TK_UPDATE||!p->pColumns||checkColumnOverLap(p->pColumns,pChanges))
783 ){
784 TriggerStack *pS; /* Pointer to trigger-stack entry */
785 for(pS=pParse->trigStack; pS && p!=pS->pTrigger; pS=pS->pNext){}
786 if( !pS ){
787 fire_this = 1;
788 }
789#if 0 /* Give no warning for recursive triggers. Just do not do them */
790 else{
791 sqlite3ErrorMsg(pParse, "recursive triggers not supported (%s)",
792 p->name);
793 return SQLITE_ERROR;
794 }
795#endif
796 }
797
798 if( fire_this ){
799 int endTrigger;
800 Expr * whenExpr;
801 AuthContext sContext;
802 NameContext sNC;
803
804 memset(&sNC, 0, sizeof(sNC));
805 sNC.pParse = pParse;
806
807 /* Push an entry on to the trigger stack */
808 trigStackEntry.pTrigger = p;
809 trigStackEntry.newIdx = newIdx;
810 trigStackEntry.oldIdx = oldIdx;
811 trigStackEntry.pTab = pTab;
812 trigStackEntry.pNext = pParse->trigStack;
813 trigStackEntry.ignoreJump = ignoreJump;
814 pParse->trigStack = &trigStackEntry;
815 sqlite3AuthContextPush(pParse, &sContext, p->name);
816
817 /* code the WHEN clause */
818 endTrigger = sqlite3VdbeMakeLabel(pParse->pVdbe);
819 whenExpr = sqlite3ExprDup(pParse->db, p->pWhen);
820 if( sqlite3ExprResolveNames(&sNC, whenExpr) ){
821 pParse->trigStack = trigStackEntry.pNext;
822 sqlite3ExprDelete(whenExpr);
823 return 1;
824 }
825 sqlite3ExprIfFalse(pParse, whenExpr, endTrigger, 1);
826 sqlite3ExprDelete(whenExpr);
827
828 codeTriggerProgram(pParse, p->step_list, orconf);
829
830 /* Pop the entry off the trigger stack */
831 pParse->trigStack = trigStackEntry.pNext;
832 sqlite3AuthContextPop(&sContext);
833
834 sqlite3VdbeResolveLabel(pParse->pVdbe, endTrigger);
835 }
836 }
837 return 0;
838}
839#endif /* !defined(SQLITE_OMIT_TRIGGER) */