Fix a typo in a comment in a test case. No changes to code.
[sqlite.git] / src / trigger.c
blob98e8da58c1fc56670d7ba498588a744d45a3c4f2
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 ** This file contains the implementation for TRIGGERs
13 #include "sqliteInt.h"
15 #ifndef SQLITE_OMIT_TRIGGER
17 ** Delete a linked list of TriggerStep structures.
19 void sqlite3DeleteTriggerStep(sqlite3 *db, TriggerStep *pTriggerStep){
20 while( pTriggerStep ){
21 TriggerStep * pTmp = pTriggerStep;
22 pTriggerStep = pTriggerStep->pNext;
24 sqlite3ExprDelete(db, pTmp->pWhere);
25 sqlite3ExprListDelete(db, pTmp->pExprList);
26 sqlite3SelectDelete(db, pTmp->pSelect);
27 sqlite3IdListDelete(db, pTmp->pIdList);
28 sqlite3UpsertDelete(db, pTmp->pUpsert);
29 sqlite3SrcListDelete(db, pTmp->pFrom);
30 sqlite3DbFree(db, pTmp->zSpan);
32 sqlite3DbFree(db, pTmp);
37 ** Given table pTab, return a list of all the triggers attached to
38 ** the table. The list is connected by Trigger.pNext pointers.
40 ** All of the triggers on pTab that are in the same database as pTab
41 ** are already attached to pTab->pTrigger. But there might be additional
42 ** triggers on pTab in the TEMP schema. This routine prepends all
43 ** TEMP triggers on pTab to the beginning of the pTab->pTrigger list
44 ** and returns the combined list.
46 ** To state it another way: This routine returns a list of all triggers
47 ** that fire off of pTab. The list will include any TEMP triggers on
48 ** pTab as well as the triggers lised in pTab->pTrigger.
50 Trigger *sqlite3TriggerList(Parse *pParse, Table *pTab){
51 Schema *pTmpSchema; /* Schema of the pTab table */
52 Trigger *pList; /* List of triggers to return */
53 HashElem *p; /* Loop variable for TEMP triggers */
55 assert( pParse->disableTriggers==0 );
56 pTmpSchema = pParse->db->aDb[1].pSchema;
57 p = sqliteHashFirst(&pTmpSchema->trigHash);
58 pList = pTab->pTrigger;
59 while( p ){
60 Trigger *pTrig = (Trigger *)sqliteHashData(p);
61 if( pTrig->pTabSchema==pTab->pSchema
62 && pTrig->table
63 && 0==sqlite3StrICmp(pTrig->table, pTab->zName)
64 && (pTrig->pTabSchema!=pTmpSchema || pTrig->bReturning)
66 pTrig->pNext = pList;
67 pList = pTrig;
68 }else if( pTrig->op==TK_RETURNING ){
69 #ifndef SQLITE_OMIT_VIRTUALTABLE
70 assert( pParse->db->pVtabCtx==0 );
71 #endif
72 assert( pParse->bReturning );
73 assert( &(pParse->u1.pReturning->retTrig) == pTrig );
74 pTrig->table = pTab->zName;
75 pTrig->pTabSchema = pTab->pSchema;
76 pTrig->pNext = pList;
77 pList = pTrig;
79 p = sqliteHashNext(p);
81 #if 0
82 if( pList ){
83 Trigger *pX;
84 printf("Triggers for %s:", pTab->zName);
85 for(pX=pList; pX; pX=pX->pNext){
86 printf(" %s", pX->zName);
88 printf("\n");
89 fflush(stdout);
91 #endif
92 return pList;
96 ** This is called by the parser when it sees a CREATE TRIGGER statement
97 ** up to the point of the BEGIN before the trigger actions. A Trigger
98 ** structure is generated based on the information available and stored
99 ** in pParse->pNewTrigger. After the trigger actions have been parsed, the
100 ** sqlite3FinishTrigger() function is called to complete the trigger
101 ** construction process.
103 void sqlite3BeginTrigger(
104 Parse *pParse, /* The parse context of the CREATE TRIGGER statement */
105 Token *pName1, /* The name of the trigger */
106 Token *pName2, /* The name of the trigger */
107 int tr_tm, /* One of TK_BEFORE, TK_AFTER, TK_INSTEAD */
108 int op, /* One of TK_INSERT, TK_UPDATE, TK_DELETE */
109 IdList *pColumns, /* column list if this is an UPDATE OF trigger */
110 SrcList *pTableName,/* The name of the table/view the trigger applies to */
111 Expr *pWhen, /* WHEN clause */
112 int isTemp, /* True if the TEMPORARY keyword is present */
113 int noErr /* Suppress errors if the trigger already exists */
115 Trigger *pTrigger = 0; /* The new trigger */
116 Table *pTab; /* Table that the trigger fires off of */
117 char *zName = 0; /* Name of the trigger */
118 sqlite3 *db = pParse->db; /* The database connection */
119 int iDb; /* The database to store the trigger in */
120 Token *pName; /* The unqualified db name */
121 DbFixer sFix; /* State vector for the DB fixer */
123 assert( pName1!=0 ); /* pName1->z might be NULL, but not pName1 itself */
124 assert( pName2!=0 );
125 assert( op==TK_INSERT || op==TK_UPDATE || op==TK_DELETE );
126 assert( op>0 && op<0xff );
127 if( isTemp ){
128 /* If TEMP was specified, then the trigger name may not be qualified. */
129 if( pName2->n>0 ){
130 sqlite3ErrorMsg(pParse, "temporary trigger may not have qualified name");
131 goto trigger_cleanup;
133 iDb = 1;
134 pName = pName1;
135 }else{
136 /* Figure out the db that the trigger will be created in */
137 iDb = sqlite3TwoPartName(pParse, pName1, pName2, &pName);
138 if( iDb<0 ){
139 goto trigger_cleanup;
142 if( !pTableName || db->mallocFailed ){
143 goto trigger_cleanup;
146 /* A long-standing parser bug is that this syntax was allowed:
148 ** CREATE TRIGGER attached.demo AFTER INSERT ON attached.tab ....
149 ** ^^^^^^^^
151 ** To maintain backwards compatibility, ignore the database
152 ** name on pTableName if we are reparsing out of the schema table
154 if( db->init.busy && iDb!=1 ){
155 sqlite3DbFree(db, pTableName->a[0].zDatabase);
156 pTableName->a[0].zDatabase = 0;
159 /* If the trigger name was unqualified, and the table is a temp table,
160 ** then set iDb to 1 to create the trigger in the temporary database.
161 ** If sqlite3SrcListLookup() returns 0, indicating the table does not
162 ** exist, the error is caught by the block below.
164 pTab = sqlite3SrcListLookup(pParse, pTableName);
165 if( db->init.busy==0 && pName2->n==0 && pTab
166 && pTab->pSchema==db->aDb[1].pSchema ){
167 iDb = 1;
170 /* Ensure the table name matches database name and that the table exists */
171 if( db->mallocFailed ) goto trigger_cleanup;
172 assert( pTableName->nSrc==1 );
173 sqlite3FixInit(&sFix, pParse, iDb, "trigger", pName);
174 if( sqlite3FixSrcList(&sFix, pTableName) ){
175 goto trigger_cleanup;
177 pTab = sqlite3SrcListLookup(pParse, pTableName);
178 if( !pTab ){
179 /* The table does not exist. */
180 goto trigger_orphan_error;
182 if( IsVirtual(pTab) ){
183 sqlite3ErrorMsg(pParse, "cannot create triggers on virtual tables");
184 goto trigger_orphan_error;
186 if( (pTab->tabFlags & TF_Shadow)!=0 && sqlite3ReadOnlyShadowTables(db) ){
187 sqlite3ErrorMsg(pParse, "cannot create triggers on shadow tables");
188 goto trigger_orphan_error;
191 /* Check that the trigger name is not reserved and that no trigger of the
192 ** specified name exists */
193 zName = sqlite3NameFromToken(db, pName);
194 if( zName==0 ){
195 assert( db->mallocFailed );
196 goto trigger_cleanup;
198 if( sqlite3CheckObjectName(pParse, zName, "trigger", pTab->zName) ){
199 goto trigger_cleanup;
201 assert( sqlite3SchemaMutexHeld(db, iDb, 0) );
202 if( !IN_RENAME_OBJECT ){
203 if( sqlite3HashFind(&(db->aDb[iDb].pSchema->trigHash),zName) ){
204 if( !noErr ){
205 sqlite3ErrorMsg(pParse, "trigger %T already exists", pName);
206 }else{
207 assert( !db->init.busy );
208 sqlite3CodeVerifySchema(pParse, iDb);
209 VVA_ONLY( pParse->ifNotExists = 1; )
211 goto trigger_cleanup;
215 /* Do not create a trigger on a system table */
216 if( sqlite3StrNICmp(pTab->zName, "sqlite_", 7)==0 ){
217 sqlite3ErrorMsg(pParse, "cannot create trigger on system table");
218 goto trigger_cleanup;
221 /* INSTEAD of triggers are only for views and views only support INSTEAD
222 ** of triggers.
224 if( IsView(pTab) && tr_tm!=TK_INSTEAD ){
225 sqlite3ErrorMsg(pParse, "cannot create %s trigger on view: %S",
226 (tr_tm == TK_BEFORE)?"BEFORE":"AFTER", pTableName->a);
227 goto trigger_orphan_error;
229 if( !IsView(pTab) && tr_tm==TK_INSTEAD ){
230 sqlite3ErrorMsg(pParse, "cannot create INSTEAD OF"
231 " trigger on table: %S", pTableName->a);
232 goto trigger_orphan_error;
235 #ifndef SQLITE_OMIT_AUTHORIZATION
236 if( !IN_RENAME_OBJECT ){
237 int iTabDb = sqlite3SchemaToIndex(db, pTab->pSchema);
238 int code = SQLITE_CREATE_TRIGGER;
239 const char *zDb = db->aDb[iTabDb].zDbSName;
240 const char *zDbTrig = isTemp ? db->aDb[1].zDbSName : zDb;
241 if( iTabDb==1 || isTemp ) code = SQLITE_CREATE_TEMP_TRIGGER;
242 if( sqlite3AuthCheck(pParse, code, zName, pTab->zName, zDbTrig) ){
243 goto trigger_cleanup;
245 if( sqlite3AuthCheck(pParse, SQLITE_INSERT, SCHEMA_TABLE(iTabDb),0,zDb)){
246 goto trigger_cleanup;
249 #endif
251 /* INSTEAD OF triggers can only appear on views and BEFORE triggers
252 ** cannot appear on views. So we might as well translate every
253 ** INSTEAD OF trigger into a BEFORE trigger. It simplifies code
254 ** elsewhere.
256 if (tr_tm == TK_INSTEAD){
257 tr_tm = TK_BEFORE;
260 /* Build the Trigger object */
261 pTrigger = (Trigger*)sqlite3DbMallocZero(db, sizeof(Trigger));
262 if( pTrigger==0 ) goto trigger_cleanup;
263 pTrigger->zName = zName;
264 zName = 0;
265 pTrigger->table = sqlite3DbStrDup(db, pTableName->a[0].zName);
266 pTrigger->pSchema = db->aDb[iDb].pSchema;
267 pTrigger->pTabSchema = pTab->pSchema;
268 pTrigger->op = (u8)op;
269 pTrigger->tr_tm = tr_tm==TK_BEFORE ? TRIGGER_BEFORE : TRIGGER_AFTER;
270 if( IN_RENAME_OBJECT ){
271 sqlite3RenameTokenRemap(pParse, pTrigger->table, pTableName->a[0].zName);
272 pTrigger->pWhen = pWhen;
273 pWhen = 0;
274 }else{
275 pTrigger->pWhen = sqlite3ExprDup(db, pWhen, EXPRDUP_REDUCE);
277 pTrigger->pColumns = pColumns;
278 pColumns = 0;
279 assert( pParse->pNewTrigger==0 );
280 pParse->pNewTrigger = pTrigger;
282 trigger_cleanup:
283 sqlite3DbFree(db, zName);
284 sqlite3SrcListDelete(db, pTableName);
285 sqlite3IdListDelete(db, pColumns);
286 sqlite3ExprDelete(db, pWhen);
287 if( !pParse->pNewTrigger ){
288 sqlite3DeleteTrigger(db, pTrigger);
289 }else{
290 assert( pParse->pNewTrigger==pTrigger );
292 return;
294 trigger_orphan_error:
295 if( db->init.iDb==1 ){
296 /* Ticket #3810.
297 ** Normally, whenever a table is dropped, all associated triggers are
298 ** dropped too. But if a TEMP trigger is created on a non-TEMP table
299 ** and the table is dropped by a different database connection, the
300 ** trigger is not visible to the database connection that does the
301 ** drop so the trigger cannot be dropped. This results in an
302 ** "orphaned trigger" - a trigger whose associated table is missing.
304 ** 2020-11-05 see also https://sqlite.org/forum/forumpost/157dc791df
306 db->init.orphanTrigger = 1;
308 goto trigger_cleanup;
312 ** This routine is called after all of the trigger actions have been parsed
313 ** in order to complete the process of building the trigger.
315 void sqlite3FinishTrigger(
316 Parse *pParse, /* Parser context */
317 TriggerStep *pStepList, /* The triggered program */
318 Token *pAll /* Token that describes the complete CREATE TRIGGER */
320 Trigger *pTrig = pParse->pNewTrigger; /* Trigger being finished */
321 char *zName; /* Name of trigger */
322 sqlite3 *db = pParse->db; /* The database */
323 DbFixer sFix; /* Fixer object */
324 int iDb; /* Database containing the trigger */
325 Token nameToken; /* Trigger name for error reporting */
327 pParse->pNewTrigger = 0;
328 if( NEVER(pParse->nErr) || !pTrig ) goto triggerfinish_cleanup;
329 zName = pTrig->zName;
330 iDb = sqlite3SchemaToIndex(pParse->db, pTrig->pSchema);
331 pTrig->step_list = pStepList;
332 while( pStepList ){
333 pStepList->pTrig = pTrig;
334 pStepList = pStepList->pNext;
336 sqlite3TokenInit(&nameToken, pTrig->zName);
337 sqlite3FixInit(&sFix, pParse, iDb, "trigger", &nameToken);
338 if( sqlite3FixTriggerStep(&sFix, pTrig->step_list)
339 || sqlite3FixExpr(&sFix, pTrig->pWhen)
341 goto triggerfinish_cleanup;
344 #ifndef SQLITE_OMIT_ALTERTABLE
345 if( IN_RENAME_OBJECT ){
346 assert( !db->init.busy );
347 pParse->pNewTrigger = pTrig;
348 pTrig = 0;
349 }else
350 #endif
352 /* if we are not initializing,
353 ** build the sqlite_schema entry
355 if( !db->init.busy ){
356 Vdbe *v;
357 char *z;
359 /* If this is a new CREATE TABLE statement, and if shadow tables
360 ** are read-only, and the trigger makes a change to a shadow table,
361 ** then raise an error - do not allow the trigger to be created. */
362 if( sqlite3ReadOnlyShadowTables(db) ){
363 TriggerStep *pStep;
364 for(pStep=pTrig->step_list; pStep; pStep=pStep->pNext){
365 if( pStep->zTarget!=0
366 && sqlite3ShadowTableName(db, pStep->zTarget)
368 sqlite3ErrorMsg(pParse,
369 "trigger \"%s\" may not write to shadow table \"%s\"",
370 pTrig->zName, pStep->zTarget);
371 goto triggerfinish_cleanup;
376 /* Make an entry in the sqlite_schema table */
377 v = sqlite3GetVdbe(pParse);
378 if( v==0 ) goto triggerfinish_cleanup;
379 sqlite3BeginWriteOperation(pParse, 0, iDb);
380 z = sqlite3DbStrNDup(db, (char*)pAll->z, pAll->n);
381 testcase( z==0 );
382 sqlite3NestedParse(pParse,
383 "INSERT INTO %Q." LEGACY_SCHEMA_TABLE
384 " VALUES('trigger',%Q,%Q,0,'CREATE TRIGGER %q')",
385 db->aDb[iDb].zDbSName, zName,
386 pTrig->table, z);
387 sqlite3DbFree(db, z);
388 sqlite3ChangeCookie(pParse, iDb);
389 sqlite3VdbeAddParseSchemaOp(v, iDb,
390 sqlite3MPrintf(db, "type='trigger' AND name='%q'", zName), 0);
393 if( db->init.busy ){
394 Trigger *pLink = pTrig;
395 Hash *pHash = &db->aDb[iDb].pSchema->trigHash;
396 assert( sqlite3SchemaMutexHeld(db, iDb, 0) );
397 assert( pLink!=0 );
398 pTrig = sqlite3HashInsert(pHash, zName, pTrig);
399 if( pTrig ){
400 sqlite3OomFault(db);
401 }else if( pLink->pSchema==pLink->pTabSchema ){
402 Table *pTab;
403 pTab = sqlite3HashFind(&pLink->pTabSchema->tblHash, pLink->table);
404 assert( pTab!=0 );
405 pLink->pNext = pTab->pTrigger;
406 pTab->pTrigger = pLink;
410 triggerfinish_cleanup:
411 sqlite3DeleteTrigger(db, pTrig);
412 assert( IN_RENAME_OBJECT || !pParse->pNewTrigger );
413 sqlite3DeleteTriggerStep(db, pStepList);
417 ** Duplicate a range of text from an SQL statement, then convert all
418 ** whitespace characters into ordinary space characters.
420 static char *triggerSpanDup(sqlite3 *db, const char *zStart, const char *zEnd){
421 char *z = sqlite3DbSpanDup(db, zStart, zEnd);
422 int i;
423 if( z ) for(i=0; z[i]; i++) if( sqlite3Isspace(z[i]) ) z[i] = ' ';
424 return z;
428 ** Turn a SELECT statement (that the pSelect parameter points to) into
429 ** a trigger step. Return a pointer to a TriggerStep structure.
431 ** The parser calls this routine when it finds a SELECT statement in
432 ** body of a TRIGGER.
434 TriggerStep *sqlite3TriggerSelectStep(
435 sqlite3 *db, /* Database connection */
436 Select *pSelect, /* The SELECT statement */
437 const char *zStart, /* Start of SQL text */
438 const char *zEnd /* End of SQL text */
440 TriggerStep *pTriggerStep = sqlite3DbMallocZero(db, sizeof(TriggerStep));
441 if( pTriggerStep==0 ) {
442 sqlite3SelectDelete(db, pSelect);
443 return 0;
445 pTriggerStep->op = TK_SELECT;
446 pTriggerStep->pSelect = pSelect;
447 pTriggerStep->orconf = OE_Default;
448 pTriggerStep->zSpan = triggerSpanDup(db, zStart, zEnd);
449 return pTriggerStep;
453 ** Allocate space to hold a new trigger step. The allocated space
454 ** holds both the TriggerStep object and the TriggerStep.target.z string.
456 ** If an OOM error occurs, NULL is returned and db->mallocFailed is set.
458 static TriggerStep *triggerStepAllocate(
459 Parse *pParse, /* Parser context */
460 u8 op, /* Trigger opcode */
461 Token *pName, /* The target name */
462 const char *zStart, /* Start of SQL text */
463 const char *zEnd /* End of SQL text */
465 sqlite3 *db = pParse->db;
466 TriggerStep *pTriggerStep;
468 if( pParse->nErr ) return 0;
469 pTriggerStep = sqlite3DbMallocZero(db, sizeof(TriggerStep) + pName->n + 1);
470 if( pTriggerStep ){
471 char *z = (char*)&pTriggerStep[1];
472 memcpy(z, pName->z, pName->n);
473 sqlite3Dequote(z);
474 pTriggerStep->zTarget = z;
475 pTriggerStep->op = op;
476 pTriggerStep->zSpan = triggerSpanDup(db, zStart, zEnd);
477 if( IN_RENAME_OBJECT ){
478 sqlite3RenameTokenMap(pParse, pTriggerStep->zTarget, pName);
481 return pTriggerStep;
485 ** Build a trigger step out of an INSERT statement. Return a pointer
486 ** to the new trigger step.
488 ** The parser calls this routine when it sees an INSERT inside the
489 ** body of a trigger.
491 TriggerStep *sqlite3TriggerInsertStep(
492 Parse *pParse, /* Parser */
493 Token *pTableName, /* Name of the table into which we insert */
494 IdList *pColumn, /* List of columns in pTableName to insert into */
495 Select *pSelect, /* A SELECT statement that supplies values */
496 u8 orconf, /* The conflict algorithm (OE_Abort, OE_Replace, etc.) */
497 Upsert *pUpsert, /* ON CONFLICT clauses for upsert */
498 const char *zStart, /* Start of SQL text */
499 const char *zEnd /* End of SQL text */
501 sqlite3 *db = pParse->db;
502 TriggerStep *pTriggerStep;
504 assert(pSelect != 0 || db->mallocFailed);
506 pTriggerStep = triggerStepAllocate(pParse, TK_INSERT, pTableName,zStart,zEnd);
507 if( pTriggerStep ){
508 if( IN_RENAME_OBJECT ){
509 pTriggerStep->pSelect = pSelect;
510 pSelect = 0;
511 }else{
512 pTriggerStep->pSelect = sqlite3SelectDup(db, pSelect, EXPRDUP_REDUCE);
514 pTriggerStep->pIdList = pColumn;
515 pTriggerStep->pUpsert = pUpsert;
516 pTriggerStep->orconf = orconf;
517 if( pUpsert ){
518 sqlite3HasExplicitNulls(pParse, pUpsert->pUpsertTarget);
520 }else{
521 testcase( pColumn );
522 sqlite3IdListDelete(db, pColumn);
523 testcase( pUpsert );
524 sqlite3UpsertDelete(db, pUpsert);
526 sqlite3SelectDelete(db, pSelect);
528 return pTriggerStep;
532 ** Construct a trigger step that implements an UPDATE statement and return
533 ** a pointer to that trigger step. The parser calls this routine when it
534 ** sees an UPDATE statement inside the body of a CREATE TRIGGER.
536 TriggerStep *sqlite3TriggerUpdateStep(
537 Parse *pParse, /* Parser */
538 Token *pTableName, /* Name of the table to be updated */
539 SrcList *pFrom, /* FROM clause for an UPDATE-FROM, or NULL */
540 ExprList *pEList, /* The SET clause: list of column and new values */
541 Expr *pWhere, /* The WHERE clause */
542 u8 orconf, /* The conflict algorithm. (OE_Abort, OE_Ignore, etc) */
543 const char *zStart, /* Start of SQL text */
544 const char *zEnd /* End of SQL text */
546 sqlite3 *db = pParse->db;
547 TriggerStep *pTriggerStep;
549 pTriggerStep = triggerStepAllocate(pParse, TK_UPDATE, pTableName,zStart,zEnd);
550 if( pTriggerStep ){
551 if( IN_RENAME_OBJECT ){
552 pTriggerStep->pExprList = pEList;
553 pTriggerStep->pWhere = pWhere;
554 pTriggerStep->pFrom = pFrom;
555 pEList = 0;
556 pWhere = 0;
557 pFrom = 0;
558 }else{
559 pTriggerStep->pExprList = sqlite3ExprListDup(db, pEList, EXPRDUP_REDUCE);
560 pTriggerStep->pWhere = sqlite3ExprDup(db, pWhere, EXPRDUP_REDUCE);
561 pTriggerStep->pFrom = sqlite3SrcListDup(db, pFrom, EXPRDUP_REDUCE);
563 pTriggerStep->orconf = orconf;
565 sqlite3ExprListDelete(db, pEList);
566 sqlite3ExprDelete(db, pWhere);
567 sqlite3SrcListDelete(db, pFrom);
568 return pTriggerStep;
572 ** Construct a trigger step that implements a DELETE statement and return
573 ** a pointer to that trigger step. The parser calls this routine when it
574 ** sees a DELETE statement inside the body of a CREATE TRIGGER.
576 TriggerStep *sqlite3TriggerDeleteStep(
577 Parse *pParse, /* Parser */
578 Token *pTableName, /* The table from which rows are deleted */
579 Expr *pWhere, /* The WHERE clause */
580 const char *zStart, /* Start of SQL text */
581 const char *zEnd /* End of SQL text */
583 sqlite3 *db = pParse->db;
584 TriggerStep *pTriggerStep;
586 pTriggerStep = triggerStepAllocate(pParse, TK_DELETE, pTableName,zStart,zEnd);
587 if( pTriggerStep ){
588 if( IN_RENAME_OBJECT ){
589 pTriggerStep->pWhere = pWhere;
590 pWhere = 0;
591 }else{
592 pTriggerStep->pWhere = sqlite3ExprDup(db, pWhere, EXPRDUP_REDUCE);
594 pTriggerStep->orconf = OE_Default;
596 sqlite3ExprDelete(db, pWhere);
597 return pTriggerStep;
601 ** Recursively delete a Trigger structure
603 void sqlite3DeleteTrigger(sqlite3 *db, Trigger *pTrigger){
604 if( pTrigger==0 || pTrigger->bReturning ) return;
605 sqlite3DeleteTriggerStep(db, pTrigger->step_list);
606 sqlite3DbFree(db, pTrigger->zName);
607 sqlite3DbFree(db, pTrigger->table);
608 sqlite3ExprDelete(db, pTrigger->pWhen);
609 sqlite3IdListDelete(db, pTrigger->pColumns);
610 sqlite3DbFree(db, pTrigger);
614 ** This function is called to drop a trigger from the database schema.
616 ** This may be called directly from the parser and therefore identifies
617 ** the trigger by name. The sqlite3DropTriggerPtr() routine does the
618 ** same job as this routine except it takes a pointer to the trigger
619 ** instead of the trigger name.
621 void sqlite3DropTrigger(Parse *pParse, SrcList *pName, int noErr){
622 Trigger *pTrigger = 0;
623 int i;
624 const char *zDb;
625 const char *zName;
626 sqlite3 *db = pParse->db;
628 if( db->mallocFailed ) goto drop_trigger_cleanup;
629 if( SQLITE_OK!=sqlite3ReadSchema(pParse) ){
630 goto drop_trigger_cleanup;
633 assert( pName->nSrc==1 );
634 zDb = pName->a[0].zDatabase;
635 zName = pName->a[0].zName;
636 assert( zDb!=0 || sqlite3BtreeHoldsAllMutexes(db) );
637 for(i=OMIT_TEMPDB; i<db->nDb; i++){
638 int j = (i<2) ? i^1 : i; /* Search TEMP before MAIN */
639 if( zDb && sqlite3DbIsNamed(db, j, zDb)==0 ) continue;
640 assert( sqlite3SchemaMutexHeld(db, j, 0) );
641 pTrigger = sqlite3HashFind(&(db->aDb[j].pSchema->trigHash), zName);
642 if( pTrigger ) break;
644 if( !pTrigger ){
645 if( !noErr ){
646 sqlite3ErrorMsg(pParse, "no such trigger: %S", pName->a);
647 }else{
648 sqlite3CodeVerifyNamedSchema(pParse, zDb);
650 pParse->checkSchema = 1;
651 goto drop_trigger_cleanup;
653 sqlite3DropTriggerPtr(pParse, pTrigger);
655 drop_trigger_cleanup:
656 sqlite3SrcListDelete(db, pName);
660 ** Return a pointer to the Table structure for the table that a trigger
661 ** is set on.
663 static Table *tableOfTrigger(Trigger *pTrigger){
664 return sqlite3HashFind(&pTrigger->pTabSchema->tblHash, pTrigger->table);
669 ** Drop a trigger given a pointer to that trigger.
671 void sqlite3DropTriggerPtr(Parse *pParse, Trigger *pTrigger){
672 Table *pTable;
673 Vdbe *v;
674 sqlite3 *db = pParse->db;
675 int iDb;
677 iDb = sqlite3SchemaToIndex(pParse->db, pTrigger->pSchema);
678 assert( iDb>=0 && iDb<db->nDb );
679 pTable = tableOfTrigger(pTrigger);
680 assert( (pTable && pTable->pSchema==pTrigger->pSchema) || iDb==1 );
681 #ifndef SQLITE_OMIT_AUTHORIZATION
682 if( pTable ){
683 int code = SQLITE_DROP_TRIGGER;
684 const char *zDb = db->aDb[iDb].zDbSName;
685 const char *zTab = SCHEMA_TABLE(iDb);
686 if( iDb==1 ) code = SQLITE_DROP_TEMP_TRIGGER;
687 if( sqlite3AuthCheck(pParse, code, pTrigger->zName, pTable->zName, zDb) ||
688 sqlite3AuthCheck(pParse, SQLITE_DELETE, zTab, 0, zDb) ){
689 return;
692 #endif
694 /* Generate code to destroy the database record of the trigger.
696 if( (v = sqlite3GetVdbe(pParse))!=0 ){
697 sqlite3NestedParse(pParse,
698 "DELETE FROM %Q." LEGACY_SCHEMA_TABLE " WHERE name=%Q AND type='trigger'",
699 db->aDb[iDb].zDbSName, pTrigger->zName
701 sqlite3ChangeCookie(pParse, iDb);
702 sqlite3VdbeAddOp4(v, OP_DropTrigger, iDb, 0, 0, pTrigger->zName, 0);
707 ** Remove a trigger from the hash tables of the sqlite* pointer.
709 void sqlite3UnlinkAndDeleteTrigger(sqlite3 *db, int iDb, const char *zName){
710 Trigger *pTrigger;
711 Hash *pHash;
713 assert( sqlite3SchemaMutexHeld(db, iDb, 0) );
714 pHash = &(db->aDb[iDb].pSchema->trigHash);
715 pTrigger = sqlite3HashInsert(pHash, zName, 0);
716 if( ALWAYS(pTrigger) ){
717 if( pTrigger->pSchema==pTrigger->pTabSchema ){
718 Table *pTab = tableOfTrigger(pTrigger);
719 if( pTab ){
720 Trigger **pp;
721 for(pp=&pTab->pTrigger; *pp; pp=&((*pp)->pNext)){
722 if( *pp==pTrigger ){
723 *pp = (*pp)->pNext;
724 break;
729 sqlite3DeleteTrigger(db, pTrigger);
730 db->mDbFlags |= DBFLAG_SchemaChange;
735 ** pEList is the SET clause of an UPDATE statement. Each entry
736 ** in pEList is of the format <id>=<expr>. If any of the entries
737 ** in pEList have an <id> which matches an identifier in pIdList,
738 ** then return TRUE. If pIdList==NULL, then it is considered a
739 ** wildcard that matches anything. Likewise if pEList==NULL then
740 ** it matches anything so always return true. Return false only
741 ** if there is no match.
743 static int checkColumnOverlap(IdList *pIdList, ExprList *pEList){
744 int e;
745 if( pIdList==0 || NEVER(pEList==0) ) return 1;
746 for(e=0; e<pEList->nExpr; e++){
747 if( sqlite3IdListIndex(pIdList, pEList->a[e].zEName)>=0 ) return 1;
749 return 0;
753 ** Return true if any TEMP triggers exist
755 static int tempTriggersExist(sqlite3 *db){
756 if( NEVER(db->aDb[1].pSchema==0) ) return 0;
757 if( sqliteHashFirst(&db->aDb[1].pSchema->trigHash)==0 ) return 0;
758 return 1;
762 ** Return a list of all triggers on table pTab if there exists at least
763 ** one trigger that must be fired when an operation of type 'op' is
764 ** performed on the table, and, if that operation is an UPDATE, if at
765 ** least one of the columns in pChanges is being modified.
767 static SQLITE_NOINLINE Trigger *triggersReallyExist(
768 Parse *pParse, /* Parse context */
769 Table *pTab, /* The table the contains the triggers */
770 int op, /* one of TK_DELETE, TK_INSERT, TK_UPDATE */
771 ExprList *pChanges, /* Columns that change in an UPDATE statement */
772 int *pMask /* OUT: Mask of TRIGGER_BEFORE|TRIGGER_AFTER */
774 int mask = 0;
775 Trigger *pList = 0;
776 Trigger *p;
778 pList = sqlite3TriggerList(pParse, pTab);
779 assert( pList==0 || IsVirtual(pTab)==0
780 || (pList->bReturning && pList->pNext==0) );
781 if( pList!=0 ){
782 p = pList;
783 if( (pParse->db->flags & SQLITE_EnableTrigger)==0
784 && pTab->pTrigger!=0
786 /* The SQLITE_DBCONFIG_ENABLE_TRIGGER setting is off. That means that
787 ** only TEMP triggers are allowed. Truncate the pList so that it
788 ** includes only TEMP triggers */
789 if( pList==pTab->pTrigger ){
790 pList = 0;
791 goto exit_triggers_exist;
793 while( ALWAYS(p->pNext) && p->pNext!=pTab->pTrigger ) p = p->pNext;
794 p->pNext = 0;
795 p = pList;
798 if( p->op==op && checkColumnOverlap(p->pColumns, pChanges) ){
799 mask |= p->tr_tm;
800 }else if( p->op==TK_RETURNING ){
801 /* The first time a RETURNING trigger is seen, the "op" value tells
802 ** us what time of trigger it should be. */
803 assert( sqlite3IsToplevel(pParse) );
804 p->op = op;
805 if( IsVirtual(pTab) ){
806 if( op!=TK_INSERT ){
807 sqlite3ErrorMsg(pParse,
808 "%s RETURNING is not available on virtual tables",
809 op==TK_DELETE ? "DELETE" : "UPDATE");
811 p->tr_tm = TRIGGER_BEFORE;
812 }else{
813 p->tr_tm = TRIGGER_AFTER;
815 mask |= p->tr_tm;
816 }else if( p->bReturning && p->op==TK_INSERT && op==TK_UPDATE
817 && sqlite3IsToplevel(pParse) ){
818 /* Also fire a RETURNING trigger for an UPSERT */
819 mask |= p->tr_tm;
821 p = p->pNext;
822 }while( p );
824 exit_triggers_exist:
825 if( pMask ){
826 *pMask = mask;
828 return (mask ? pList : 0);
830 Trigger *sqlite3TriggersExist(
831 Parse *pParse, /* Parse context */
832 Table *pTab, /* The table the contains the triggers */
833 int op, /* one of TK_DELETE, TK_INSERT, TK_UPDATE */
834 ExprList *pChanges, /* Columns that change in an UPDATE statement */
835 int *pMask /* OUT: Mask of TRIGGER_BEFORE|TRIGGER_AFTER */
837 assert( pTab!=0 );
838 if( (pTab->pTrigger==0 && !tempTriggersExist(pParse->db))
839 || pParse->disableTriggers
841 if( pMask ) *pMask = 0;
842 return 0;
844 return triggersReallyExist(pParse,pTab,op,pChanges,pMask);
848 ** Convert the pStep->zTarget string into a SrcList and return a pointer
849 ** to that SrcList.
851 ** This routine adds a specific database name, if needed, to the target when
852 ** forming the SrcList. This prevents a trigger in one database from
853 ** referring to a target in another database. An exception is when the
854 ** trigger is in TEMP in which case it can refer to any other database it
855 ** wants.
857 SrcList *sqlite3TriggerStepSrc(
858 Parse *pParse, /* The parsing context */
859 TriggerStep *pStep /* The trigger containing the target token */
861 sqlite3 *db = pParse->db;
862 SrcList *pSrc; /* SrcList to be returned */
863 char *zName = sqlite3DbStrDup(db, pStep->zTarget);
864 pSrc = sqlite3SrcListAppend(pParse, 0, 0, 0);
865 assert( pSrc==0 || pSrc->nSrc==1 );
866 assert( zName || pSrc==0 );
867 if( pSrc ){
868 Schema *pSchema = pStep->pTrig->pSchema;
869 pSrc->a[0].zName = zName;
870 if( pSchema!=db->aDb[1].pSchema ){
871 pSrc->a[0].pSchema = pSchema;
873 if( pStep->pFrom ){
874 SrcList *pDup = sqlite3SrcListDup(db, pStep->pFrom, 0);
875 if( pDup && pDup->nSrc>1 && !IN_RENAME_OBJECT ){
876 Select *pSubquery;
877 Token as;
878 pSubquery = sqlite3SelectNew(pParse,0,pDup,0,0,0,0,SF_NestedFrom,0);
879 as.n = 0;
880 as.z = 0;
881 pDup = sqlite3SrcListAppendFromTerm(pParse,0,0,0,&as,pSubquery,0);
883 pSrc = sqlite3SrcListAppendList(pParse, pSrc, pDup);
885 }else{
886 sqlite3DbFree(db, zName);
888 return pSrc;
892 ** Return true if the pExpr term from the RETURNING clause argument
893 ** list is of the form "*". Raise an error if the terms if of the
894 ** form "table.*".
896 static int isAsteriskTerm(
897 Parse *pParse, /* Parsing context */
898 Expr *pTerm /* A term in the RETURNING clause */
900 assert( pTerm!=0 );
901 if( pTerm->op==TK_ASTERISK ) return 1;
902 if( pTerm->op!=TK_DOT ) return 0;
903 assert( pTerm->pRight!=0 );
904 assert( pTerm->pLeft!=0 );
905 if( pTerm->pRight->op!=TK_ASTERISK ) return 0;
906 sqlite3ErrorMsg(pParse, "RETURNING may not use \"TABLE.*\" wildcards");
907 return 1;
910 /* The input list pList is the list of result set terms from a RETURNING
911 ** clause. The table that we are returning from is pTab.
913 ** This routine makes a copy of the pList, and at the same time expands
914 ** any "*" wildcards to be the complete set of columns from pTab.
916 static ExprList *sqlite3ExpandReturning(
917 Parse *pParse, /* Parsing context */
918 ExprList *pList, /* The arguments to RETURNING */
919 Table *pTab /* The table being updated */
921 ExprList *pNew = 0;
922 sqlite3 *db = pParse->db;
923 int i;
925 for(i=0; i<pList->nExpr; i++){
926 Expr *pOldExpr = pList->a[i].pExpr;
927 if( NEVER(pOldExpr==0) ) continue;
928 if( isAsteriskTerm(pParse, pOldExpr) ){
929 int jj;
930 for(jj=0; jj<pTab->nCol; jj++){
931 Expr *pNewExpr;
932 if( IsHiddenColumn(pTab->aCol+jj) ) continue;
933 pNewExpr = sqlite3Expr(db, TK_ID, pTab->aCol[jj].zCnName);
934 pNew = sqlite3ExprListAppend(pParse, pNew, pNewExpr);
935 if( !db->mallocFailed ){
936 struct ExprList_item *pItem = &pNew->a[pNew->nExpr-1];
937 pItem->zEName = sqlite3DbStrDup(db, pTab->aCol[jj].zCnName);
938 pItem->fg.eEName = ENAME_NAME;
941 }else{
942 Expr *pNewExpr = sqlite3ExprDup(db, pOldExpr, 0);
943 pNew = sqlite3ExprListAppend(pParse, pNew, pNewExpr);
944 if( !db->mallocFailed && ALWAYS(pList->a[i].zEName!=0) ){
945 struct ExprList_item *pItem = &pNew->a[pNew->nExpr-1];
946 pItem->zEName = sqlite3DbStrDup(db, pList->a[i].zEName);
947 pItem->fg.eEName = pList->a[i].fg.eEName;
951 return pNew;
954 /* If the Expr node is a subquery or an EXISTS operator or an IN operator that
955 ** uses a subquery, and if the subquery is SF_Correlated, then mark the
956 ** expression as EP_VarSelect.
958 static int sqlite3ReturningSubqueryVarSelect(Walker *NotUsed, Expr *pExpr){
959 UNUSED_PARAMETER(NotUsed);
960 if( ExprUseXSelect(pExpr)
961 && (pExpr->x.pSelect->selFlags & SF_Correlated)!=0
963 testcase( ExprHasProperty(pExpr, EP_VarSelect) );
964 ExprSetProperty(pExpr, EP_VarSelect);
966 return WRC_Continue;
971 ** If the SELECT references the table pWalker->u.pTab, then do two things:
973 ** (1) Mark the SELECT as as SF_Correlated.
974 ** (2) Set pWalker->eCode to non-zero so that the caller will know
975 ** that (1) has happened.
977 static int sqlite3ReturningSubqueryCorrelated(Walker *pWalker, Select *pSelect){
978 int i;
979 SrcList *pSrc;
980 assert( pSelect!=0 );
981 pSrc = pSelect->pSrc;
982 assert( pSrc!=0 );
983 for(i=0; i<pSrc->nSrc; i++){
984 if( pSrc->a[i].pTab==pWalker->u.pTab ){
985 testcase( pSelect->selFlags & SF_Correlated );
986 pSelect->selFlags |= SF_Correlated;
987 pWalker->eCode = 1;
988 break;
991 return WRC_Continue;
995 ** Scan the expression list that is the argument to RETURNING looking
996 ** for subqueries that depend on the table which is being modified in the
997 ** statement that is hosting the RETURNING clause (pTab). Mark all such
998 ** subqueries as SF_Correlated. If the subqueries are part of an
999 ** expression, mark the expression as EP_VarSelect.
1001 ** https://sqlite.org/forum/forumpost/2c83569ce8945d39
1003 static void sqlite3ProcessReturningSubqueries(
1004 ExprList *pEList,
1005 Table *pTab
1007 Walker w;
1008 memset(&w, 0, sizeof(w));
1009 w.xExprCallback = sqlite3ExprWalkNoop;
1010 w.xSelectCallback = sqlite3ReturningSubqueryCorrelated;
1011 w.u.pTab = pTab;
1012 sqlite3WalkExprList(&w, pEList);
1013 if( w.eCode ){
1014 w.xExprCallback = sqlite3ReturningSubqueryVarSelect;
1015 w.xSelectCallback = sqlite3SelectWalkNoop;
1016 sqlite3WalkExprList(&w, pEList);
1021 ** Generate code for the RETURNING trigger. Unlike other triggers
1022 ** that invoke a subprogram in the bytecode, the code for RETURNING
1023 ** is generated in-line.
1025 static void codeReturningTrigger(
1026 Parse *pParse, /* Parse context */
1027 Trigger *pTrigger, /* The trigger step that defines the RETURNING */
1028 Table *pTab, /* The table to code triggers from */
1029 int regIn /* The first in an array of registers */
1031 Vdbe *v = pParse->pVdbe;
1032 sqlite3 *db = pParse->db;
1033 ExprList *pNew;
1034 Returning *pReturning;
1035 Select sSelect;
1036 SrcList sFrom;
1038 assert( v!=0 );
1039 if( !pParse->bReturning ){
1040 /* This RETURNING trigger must be for a different statement as
1041 ** this statement lacks a RETURNING clause. */
1042 return;
1044 assert( db->pParse==pParse );
1045 pReturning = pParse->u1.pReturning;
1046 if( pTrigger != &(pReturning->retTrig) ){
1047 /* This RETURNING trigger is for a different statement */
1048 return;
1050 memset(&sSelect, 0, sizeof(sSelect));
1051 memset(&sFrom, 0, sizeof(sFrom));
1052 sSelect.pEList = sqlite3ExprListDup(db, pReturning->pReturnEL, 0);
1053 sSelect.pSrc = &sFrom;
1054 sFrom.nSrc = 1;
1055 sFrom.a[0].pTab = pTab;
1056 sFrom.a[0].zName = pTab->zName; /* tag-20240424-1 */
1057 sFrom.a[0].iCursor = -1;
1058 sqlite3SelectPrep(pParse, &sSelect, 0);
1059 if( pParse->nErr==0 ){
1060 assert( db->mallocFailed==0 );
1061 sqlite3GenerateColumnNames(pParse, &sSelect);
1063 sqlite3ExprListDelete(db, sSelect.pEList);
1064 pNew = sqlite3ExpandReturning(pParse, pReturning->pReturnEL, pTab);
1065 if( pParse->nErr==0 ){
1066 NameContext sNC;
1067 memset(&sNC, 0, sizeof(sNC));
1068 if( pReturning->nRetCol==0 ){
1069 pReturning->nRetCol = pNew->nExpr;
1070 pReturning->iRetCur = pParse->nTab++;
1072 sNC.pParse = pParse;
1073 sNC.uNC.iBaseReg = regIn;
1074 sNC.ncFlags = NC_UBaseReg;
1075 pParse->eTriggerOp = pTrigger->op;
1076 pParse->pTriggerTab = pTab;
1077 if( sqlite3ResolveExprListNames(&sNC, pNew)==SQLITE_OK
1078 && ALWAYS(!db->mallocFailed)
1080 int i;
1081 int nCol = pNew->nExpr;
1082 int reg = pParse->nMem+1;
1083 sqlite3ProcessReturningSubqueries(pNew, pTab);
1084 pParse->nMem += nCol+2;
1085 pReturning->iRetReg = reg;
1086 for(i=0; i<nCol; i++){
1087 Expr *pCol = pNew->a[i].pExpr;
1088 assert( pCol!=0 ); /* Due to !db->mallocFailed ~9 lines above */
1089 sqlite3ExprCodeFactorable(pParse, pCol, reg+i);
1090 if( sqlite3ExprAffinity(pCol)==SQLITE_AFF_REAL ){
1091 sqlite3VdbeAddOp1(v, OP_RealAffinity, reg+i);
1094 sqlite3VdbeAddOp3(v, OP_MakeRecord, reg, i, reg+i);
1095 sqlite3VdbeAddOp2(v, OP_NewRowid, pReturning->iRetCur, reg+i+1);
1096 sqlite3VdbeAddOp3(v, OP_Insert, pReturning->iRetCur, reg+i, reg+i+1);
1099 sqlite3ExprListDelete(db, pNew);
1100 pParse->eTriggerOp = 0;
1101 pParse->pTriggerTab = 0;
1107 ** Generate VDBE code for the statements inside the body of a single
1108 ** trigger.
1110 static int codeTriggerProgram(
1111 Parse *pParse, /* The parser context */
1112 TriggerStep *pStepList, /* List of statements inside the trigger body */
1113 int orconf /* Conflict algorithm. (OE_Abort, etc) */
1115 TriggerStep *pStep;
1116 Vdbe *v = pParse->pVdbe;
1117 sqlite3 *db = pParse->db;
1119 assert( pParse->pTriggerTab && pParse->pToplevel );
1120 assert( pStepList );
1121 assert( v!=0 );
1122 for(pStep=pStepList; pStep; pStep=pStep->pNext){
1123 /* Figure out the ON CONFLICT policy that will be used for this step
1124 ** of the trigger program. If the statement that caused this trigger
1125 ** to fire had an explicit ON CONFLICT, then use it. Otherwise, use
1126 ** the ON CONFLICT policy that was specified as part of the trigger
1127 ** step statement. Example:
1129 ** CREATE TRIGGER AFTER INSERT ON t1 BEGIN;
1130 ** INSERT OR REPLACE INTO t2 VALUES(new.a, new.b);
1131 ** END;
1133 ** INSERT INTO t1 ... ; -- insert into t2 uses REPLACE policy
1134 ** INSERT OR IGNORE INTO t1 ... ; -- insert into t2 uses IGNORE policy
1136 pParse->eOrconf = (orconf==OE_Default)?pStep->orconf:(u8)orconf;
1137 assert( pParse->okConstFactor==0 );
1139 #ifndef SQLITE_OMIT_TRACE
1140 if( pStep->zSpan ){
1141 sqlite3VdbeAddOp4(v, OP_Trace, 0x7fffffff, 1, 0,
1142 sqlite3MPrintf(db, "-- %s", pStep->zSpan),
1143 P4_DYNAMIC);
1145 #endif
1147 switch( pStep->op ){
1148 case TK_UPDATE: {
1149 sqlite3Update(pParse,
1150 sqlite3TriggerStepSrc(pParse, pStep),
1151 sqlite3ExprListDup(db, pStep->pExprList, 0),
1152 sqlite3ExprDup(db, pStep->pWhere, 0),
1153 pParse->eOrconf, 0, 0, 0
1155 sqlite3VdbeAddOp0(v, OP_ResetCount);
1156 break;
1158 case TK_INSERT: {
1159 sqlite3Insert(pParse,
1160 sqlite3TriggerStepSrc(pParse, pStep),
1161 sqlite3SelectDup(db, pStep->pSelect, 0),
1162 sqlite3IdListDup(db, pStep->pIdList),
1163 pParse->eOrconf,
1164 sqlite3UpsertDup(db, pStep->pUpsert)
1166 sqlite3VdbeAddOp0(v, OP_ResetCount);
1167 break;
1169 case TK_DELETE: {
1170 sqlite3DeleteFrom(pParse,
1171 sqlite3TriggerStepSrc(pParse, pStep),
1172 sqlite3ExprDup(db, pStep->pWhere, 0), 0, 0
1174 sqlite3VdbeAddOp0(v, OP_ResetCount);
1175 break;
1177 default: assert( pStep->op==TK_SELECT ); {
1178 SelectDest sDest;
1179 Select *pSelect = sqlite3SelectDup(db, pStep->pSelect, 0);
1180 sqlite3SelectDestInit(&sDest, SRT_Discard, 0);
1181 sqlite3Select(pParse, pSelect, &sDest);
1182 sqlite3SelectDelete(db, pSelect);
1183 break;
1188 return 0;
1191 #ifdef SQLITE_ENABLE_EXPLAIN_COMMENTS
1193 ** This function is used to add VdbeComment() annotations to a VDBE
1194 ** program. It is not used in production code, only for debugging.
1196 static const char *onErrorText(int onError){
1197 switch( onError ){
1198 case OE_Abort: return "abort";
1199 case OE_Rollback: return "rollback";
1200 case OE_Fail: return "fail";
1201 case OE_Replace: return "replace";
1202 case OE_Ignore: return "ignore";
1203 case OE_Default: return "default";
1205 return "n/a";
1207 #endif
1210 ** Parse context structure pFrom has just been used to create a sub-vdbe
1211 ** (trigger program). If an error has occurred, transfer error information
1212 ** from pFrom to pTo.
1214 static void transferParseError(Parse *pTo, Parse *pFrom){
1215 assert( pFrom->zErrMsg==0 || pFrom->nErr );
1216 assert( pTo->zErrMsg==0 || pTo->nErr );
1217 if( pTo->nErr==0 ){
1218 pTo->zErrMsg = pFrom->zErrMsg;
1219 pTo->nErr = pFrom->nErr;
1220 pTo->rc = pFrom->rc;
1221 }else{
1222 sqlite3DbFree(pFrom->db, pFrom->zErrMsg);
1227 ** Create and populate a new TriggerPrg object with a sub-program
1228 ** implementing trigger pTrigger with ON CONFLICT policy orconf.
1230 static TriggerPrg *codeRowTrigger(
1231 Parse *pParse, /* Current parse context */
1232 Trigger *pTrigger, /* Trigger to code */
1233 Table *pTab, /* The table pTrigger is attached to */
1234 int orconf /* ON CONFLICT policy to code trigger program with */
1236 Parse *pTop = sqlite3ParseToplevel(pParse);
1237 sqlite3 *db = pParse->db; /* Database handle */
1238 TriggerPrg *pPrg; /* Value to return */
1239 Expr *pWhen = 0; /* Duplicate of trigger WHEN expression */
1240 Vdbe *v; /* Temporary VM */
1241 NameContext sNC; /* Name context for sub-vdbe */
1242 SubProgram *pProgram = 0; /* Sub-vdbe for trigger program */
1243 int iEndTrigger = 0; /* Label to jump to if WHEN is false */
1244 Parse sSubParse; /* Parse context for sub-vdbe */
1246 assert( pTrigger->zName==0 || pTab==tableOfTrigger(pTrigger) );
1247 assert( pTop->pVdbe );
1249 /* Allocate the TriggerPrg and SubProgram objects. To ensure that they
1250 ** are freed if an error occurs, link them into the Parse.pTriggerPrg
1251 ** list of the top-level Parse object sooner rather than later. */
1252 pPrg = sqlite3DbMallocZero(db, sizeof(TriggerPrg));
1253 if( !pPrg ) return 0;
1254 pPrg->pNext = pTop->pTriggerPrg;
1255 pTop->pTriggerPrg = pPrg;
1256 pPrg->pProgram = pProgram = sqlite3DbMallocZero(db, sizeof(SubProgram));
1257 if( !pProgram ) return 0;
1258 sqlite3VdbeLinkSubProgram(pTop->pVdbe, pProgram);
1259 pPrg->pTrigger = pTrigger;
1260 pPrg->orconf = orconf;
1261 pPrg->aColmask[0] = 0xffffffff;
1262 pPrg->aColmask[1] = 0xffffffff;
1264 /* Allocate and populate a new Parse context to use for coding the
1265 ** trigger sub-program. */
1266 sqlite3ParseObjectInit(&sSubParse, db);
1267 memset(&sNC, 0, sizeof(sNC));
1268 sNC.pParse = &sSubParse;
1269 sSubParse.pTriggerTab = pTab;
1270 sSubParse.pToplevel = pTop;
1271 sSubParse.zAuthContext = pTrigger->zName;
1272 sSubParse.eTriggerOp = pTrigger->op;
1273 sSubParse.nQueryLoop = pParse->nQueryLoop;
1274 sSubParse.prepFlags = pParse->prepFlags;
1276 v = sqlite3GetVdbe(&sSubParse);
1277 if( v ){
1278 VdbeComment((v, "Start: %s.%s (%s %s%s%s ON %s)",
1279 pTrigger->zName, onErrorText(orconf),
1280 (pTrigger->tr_tm==TRIGGER_BEFORE ? "BEFORE" : "AFTER"),
1281 (pTrigger->op==TK_UPDATE ? "UPDATE" : ""),
1282 (pTrigger->op==TK_INSERT ? "INSERT" : ""),
1283 (pTrigger->op==TK_DELETE ? "DELETE" : ""),
1284 pTab->zName
1286 #ifndef SQLITE_OMIT_TRACE
1287 if( pTrigger->zName ){
1288 sqlite3VdbeChangeP4(v, -1,
1289 sqlite3MPrintf(db, "-- TRIGGER %s", pTrigger->zName), P4_DYNAMIC
1292 #endif
1294 /* If one was specified, code the WHEN clause. If it evaluates to false
1295 ** (or NULL) the sub-vdbe is immediately halted by jumping to the
1296 ** OP_Halt inserted at the end of the program. */
1297 if( pTrigger->pWhen ){
1298 pWhen = sqlite3ExprDup(db, pTrigger->pWhen, 0);
1299 if( db->mallocFailed==0
1300 && SQLITE_OK==sqlite3ResolveExprNames(&sNC, pWhen)
1302 iEndTrigger = sqlite3VdbeMakeLabel(&sSubParse);
1303 sqlite3ExprIfFalse(&sSubParse, pWhen, iEndTrigger, SQLITE_JUMPIFNULL);
1305 sqlite3ExprDelete(db, pWhen);
1308 /* Code the trigger program into the sub-vdbe. */
1309 codeTriggerProgram(&sSubParse, pTrigger->step_list, orconf);
1311 /* Insert an OP_Halt at the end of the sub-program. */
1312 if( iEndTrigger ){
1313 sqlite3VdbeResolveLabel(v, iEndTrigger);
1315 sqlite3VdbeAddOp0(v, OP_Halt);
1316 VdbeComment((v, "End: %s.%s", pTrigger->zName, onErrorText(orconf)));
1317 transferParseError(pParse, &sSubParse);
1319 if( pParse->nErr==0 ){
1320 assert( db->mallocFailed==0 );
1321 pProgram->aOp = sqlite3VdbeTakeOpArray(v, &pProgram->nOp, &pTop->nMaxArg);
1323 pProgram->nMem = sSubParse.nMem;
1324 pProgram->nCsr = sSubParse.nTab;
1325 pProgram->token = (void *)pTrigger;
1326 pPrg->aColmask[0] = sSubParse.oldmask;
1327 pPrg->aColmask[1] = sSubParse.newmask;
1328 sqlite3VdbeDelete(v);
1329 }else{
1330 transferParseError(pParse, &sSubParse);
1333 assert( !sSubParse.pTriggerPrg && !sSubParse.nMaxArg );
1334 sqlite3ParseObjectReset(&sSubParse);
1335 return pPrg;
1339 ** Return a pointer to a TriggerPrg object containing the sub-program for
1340 ** trigger pTrigger with default ON CONFLICT algorithm orconf. If no such
1341 ** TriggerPrg object exists, a new object is allocated and populated before
1342 ** being returned.
1344 static TriggerPrg *getRowTrigger(
1345 Parse *pParse, /* Current parse context */
1346 Trigger *pTrigger, /* Trigger to code */
1347 Table *pTab, /* The table trigger pTrigger is attached to */
1348 int orconf /* ON CONFLICT algorithm. */
1350 Parse *pRoot = sqlite3ParseToplevel(pParse);
1351 TriggerPrg *pPrg;
1353 assert( pTrigger->zName==0 || pTab==tableOfTrigger(pTrigger) );
1355 /* It may be that this trigger has already been coded (or is in the
1356 ** process of being coded). If this is the case, then an entry with
1357 ** a matching TriggerPrg.pTrigger field will be present somewhere
1358 ** in the Parse.pTriggerPrg list. Search for such an entry. */
1359 for(pPrg=pRoot->pTriggerPrg;
1360 pPrg && (pPrg->pTrigger!=pTrigger || pPrg->orconf!=orconf);
1361 pPrg=pPrg->pNext
1364 /* If an existing TriggerPrg could not be located, create a new one. */
1365 if( !pPrg ){
1366 pPrg = codeRowTrigger(pParse, pTrigger, pTab, orconf);
1367 pParse->db->errByteOffset = -1;
1370 return pPrg;
1374 ** Generate code for the trigger program associated with trigger p on
1375 ** table pTab. The reg, orconf and ignoreJump parameters passed to this
1376 ** function are the same as those described in the header function for
1377 ** sqlite3CodeRowTrigger()
1379 void sqlite3CodeRowTriggerDirect(
1380 Parse *pParse, /* Parse context */
1381 Trigger *p, /* Trigger to code */
1382 Table *pTab, /* The table to code triggers from */
1383 int reg, /* Reg array containing OLD.* and NEW.* values */
1384 int orconf, /* ON CONFLICT policy */
1385 int ignoreJump /* Instruction to jump to for RAISE(IGNORE) */
1387 Vdbe *v = sqlite3GetVdbe(pParse); /* Main VM */
1388 TriggerPrg *pPrg;
1389 pPrg = getRowTrigger(pParse, p, pTab, orconf);
1390 assert( pPrg || pParse->nErr );
1392 /* Code the OP_Program opcode in the parent VDBE. P4 of the OP_Program
1393 ** is a pointer to the sub-vdbe containing the trigger program. */
1394 if( pPrg ){
1395 int bRecursive = (p->zName && 0==(pParse->db->flags&SQLITE_RecTriggers));
1397 sqlite3VdbeAddOp4(v, OP_Program, reg, ignoreJump, ++pParse->nMem,
1398 (const char *)pPrg->pProgram, P4_SUBPROGRAM);
1399 VdbeComment(
1400 (v, "Call: %s.%s", (p->zName?p->zName:"fkey"), onErrorText(orconf)));
1402 /* Set the P5 operand of the OP_Program instruction to non-zero if
1403 ** recursive invocation of this trigger program is disallowed. Recursive
1404 ** invocation is disallowed if (a) the sub-program is really a trigger,
1405 ** not a foreign key action, and (b) the flag to enable recursive triggers
1406 ** is clear. */
1407 sqlite3VdbeChangeP5(v, (u8)bRecursive);
1412 ** This is called to code the required FOR EACH ROW triggers for an operation
1413 ** on table pTab. The operation to code triggers for (INSERT, UPDATE or DELETE)
1414 ** is given by the op parameter. The tr_tm parameter determines whether the
1415 ** BEFORE or AFTER triggers are coded. If the operation is an UPDATE, then
1416 ** parameter pChanges is passed the list of columns being modified.
1418 ** If there are no triggers that fire at the specified time for the specified
1419 ** operation on pTab, this function is a no-op.
1421 ** The reg argument is the address of the first in an array of registers
1422 ** that contain the values substituted for the new.* and old.* references
1423 ** in the trigger program. If N is the number of columns in table pTab
1424 ** (a copy of pTab->nCol), then registers are populated as follows:
1426 ** Register Contains
1427 ** ------------------------------------------------------
1428 ** reg+0 OLD.rowid
1429 ** reg+1 OLD.* value of left-most column of pTab
1430 ** ... ...
1431 ** reg+N OLD.* value of right-most column of pTab
1432 ** reg+N+1 NEW.rowid
1433 ** reg+N+2 NEW.* value of left-most column of pTab
1434 ** ... ...
1435 ** reg+N+N+1 NEW.* value of right-most column of pTab
1437 ** For ON DELETE triggers, the registers containing the NEW.* values will
1438 ** never be accessed by the trigger program, so they are not allocated or
1439 ** populated by the caller (there is no data to populate them with anyway).
1440 ** Similarly, for ON INSERT triggers the values stored in the OLD.* registers
1441 ** are never accessed, and so are not allocated by the caller. So, for an
1442 ** ON INSERT trigger, the value passed to this function as parameter reg
1443 ** is not a readable register, although registers (reg+N) through
1444 ** (reg+N+N+1) are.
1446 ** Parameter orconf is the default conflict resolution algorithm for the
1447 ** trigger program to use (REPLACE, IGNORE etc.). Parameter ignoreJump
1448 ** is the instruction that control should jump to if a trigger program
1449 ** raises an IGNORE exception.
1451 void sqlite3CodeRowTrigger(
1452 Parse *pParse, /* Parse context */
1453 Trigger *pTrigger, /* List of triggers on table pTab */
1454 int op, /* One of TK_UPDATE, TK_INSERT, TK_DELETE */
1455 ExprList *pChanges, /* Changes list for any UPDATE OF triggers */
1456 int tr_tm, /* One of TRIGGER_BEFORE, TRIGGER_AFTER */
1457 Table *pTab, /* The table to code triggers from */
1458 int reg, /* The first in an array of registers (see above) */
1459 int orconf, /* ON CONFLICT policy */
1460 int ignoreJump /* Instruction to jump to for RAISE(IGNORE) */
1462 Trigger *p; /* Used to iterate through pTrigger list */
1464 assert( op==TK_UPDATE || op==TK_INSERT || op==TK_DELETE );
1465 assert( tr_tm==TRIGGER_BEFORE || tr_tm==TRIGGER_AFTER );
1466 assert( (op==TK_UPDATE)==(pChanges!=0) );
1468 for(p=pTrigger; p; p=p->pNext){
1470 /* Sanity checking: The schema for the trigger and for the table are
1471 ** always defined. The trigger must be in the same schema as the table
1472 ** or else it must be a TEMP trigger. */
1473 assert( p->pSchema!=0 );
1474 assert( p->pTabSchema!=0 );
1475 assert( p->pSchema==p->pTabSchema
1476 || p->pSchema==pParse->db->aDb[1].pSchema );
1478 /* Determine whether we should code this trigger. One of two choices:
1479 ** 1. The trigger is an exact match to the current DML statement
1480 ** 2. This is a RETURNING trigger for INSERT but we are currently
1481 ** doing the UPDATE part of an UPSERT.
1483 if( (p->op==op || (p->bReturning && p->op==TK_INSERT && op==TK_UPDATE))
1484 && p->tr_tm==tr_tm
1485 && checkColumnOverlap(p->pColumns, pChanges)
1487 if( !p->bReturning ){
1488 sqlite3CodeRowTriggerDirect(pParse, p, pTab, reg, orconf, ignoreJump);
1489 }else if( sqlite3IsToplevel(pParse) ){
1490 codeReturningTrigger(pParse, p, pTab, reg);
1497 ** Triggers may access values stored in the old.* or new.* pseudo-table.
1498 ** This function returns a 32-bit bitmask indicating which columns of the
1499 ** old.* or new.* tables actually are used by triggers. This information
1500 ** may be used by the caller, for example, to avoid having to load the entire
1501 ** old.* record into memory when executing an UPDATE or DELETE command.
1503 ** Bit 0 of the returned mask is set if the left-most column of the
1504 ** table may be accessed using an [old|new].<col> reference. Bit 1 is set if
1505 ** the second leftmost column value is required, and so on. If there
1506 ** are more than 32 columns in the table, and at least one of the columns
1507 ** with an index greater than 32 may be accessed, 0xffffffff is returned.
1509 ** It is not possible to determine if the old.rowid or new.rowid column is
1510 ** accessed by triggers. The caller must always assume that it is.
1512 ** Parameter isNew must be either 1 or 0. If it is 0, then the mask returned
1513 ** applies to the old.* table. If 1, the new.* table.
1515 ** Parameter tr_tm must be a mask with one or both of the TRIGGER_BEFORE
1516 ** and TRIGGER_AFTER bits set. Values accessed by BEFORE triggers are only
1517 ** included in the returned mask if the TRIGGER_BEFORE bit is set in the
1518 ** tr_tm parameter. Similarly, values accessed by AFTER triggers are only
1519 ** included in the returned mask if the TRIGGER_AFTER bit is set in tr_tm.
1521 u32 sqlite3TriggerColmask(
1522 Parse *pParse, /* Parse context */
1523 Trigger *pTrigger, /* List of triggers on table pTab */
1524 ExprList *pChanges, /* Changes list for any UPDATE OF triggers */
1525 int isNew, /* 1 for new.* ref mask, 0 for old.* ref mask */
1526 int tr_tm, /* Mask of TRIGGER_BEFORE|TRIGGER_AFTER */
1527 Table *pTab, /* The table to code triggers from */
1528 int orconf /* Default ON CONFLICT policy for trigger steps */
1530 const int op = pChanges ? TK_UPDATE : TK_DELETE;
1531 u32 mask = 0;
1532 Trigger *p;
1534 assert( isNew==1 || isNew==0 );
1535 if( IsView(pTab) ){
1536 return 0xffffffff;
1538 for(p=pTrigger; p; p=p->pNext){
1539 if( p->op==op
1540 && (tr_tm&p->tr_tm)
1541 && checkColumnOverlap(p->pColumns,pChanges)
1543 if( p->bReturning ){
1544 mask = 0xffffffff;
1545 }else{
1546 TriggerPrg *pPrg;
1547 pPrg = getRowTrigger(pParse, p, pTab, orconf);
1548 if( pPrg ){
1549 mask |= pPrg->aColmask[isNew];
1555 return mask;
1558 #endif /* !defined(SQLITE_OMIT_TRIGGER) */