3 ** The author disclaims copyright to this source code. In place of
4 ** a legal notice, here is a blessing:
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.
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
;
60 Trigger
*pTrig
= (Trigger
*)sqliteHashData(p
);
61 if( pTrig
->pTabSchema
==pTab
->pSchema
63 && 0==sqlite3StrICmp(pTrig
->table
, pTab
->zName
)
64 && (pTrig
->pTabSchema
!=pTmpSchema
|| pTrig
->bReturning
)
68 }else if( pTrig
->op
==TK_RETURNING
){
69 #ifndef SQLITE_OMIT_VIRTUALTABLE
70 assert( pParse
->db
->pVtabCtx
==0 );
72 assert( pParse
->bReturning
);
73 assert( &(pParse
->u1
.pReturning
->retTrig
) == pTrig
);
74 pTrig
->table
= pTab
->zName
;
75 pTrig
->pTabSchema
= pTab
->pSchema
;
79 p
= sqliteHashNext(p
);
84 printf("Triggers for %s:", pTab
->zName
);
85 for(pX
=pList
; pX
; pX
=pX
->pNext
){
86 printf(" %s", pX
->zName
);
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 */
125 assert( op
==TK_INSERT
|| op
==TK_UPDATE
|| op
==TK_DELETE
);
126 assert( op
>0 && op
<0xff );
128 /* If TEMP was specified, then the trigger name may not be qualified. */
130 sqlite3ErrorMsg(pParse
, "temporary trigger may not have qualified name");
131 goto trigger_cleanup
;
136 /* Figure out the db that the trigger will be created in */
137 iDb
= sqlite3TwoPartName(pParse
, pName1
, pName2
, &pName
);
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 ....
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
){
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
);
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
;
187 /* Check that the trigger name is not reserved and that no trigger of the
188 ** specified name exists */
189 zName
= sqlite3NameFromToken(db
, pName
);
191 assert( db
->mallocFailed
);
192 goto trigger_cleanup
;
194 if( sqlite3CheckObjectName(pParse
, zName
, "trigger", pTab
->zName
) ){
195 goto trigger_cleanup
;
197 assert( sqlite3SchemaMutexHeld(db
, iDb
, 0) );
198 if( !IN_RENAME_OBJECT
){
199 if( sqlite3HashFind(&(db
->aDb
[iDb
].pSchema
->trigHash
),zName
) ){
201 sqlite3ErrorMsg(pParse
, "trigger %T already exists", pName
);
203 assert( !db
->init
.busy
);
204 sqlite3CodeVerifySchema(pParse
, iDb
);
205 VVA_ONLY( pParse
->ifNotExists
= 1; )
207 goto trigger_cleanup
;
211 /* Do not create a trigger on a system table */
212 if( sqlite3StrNICmp(pTab
->zName
, "sqlite_", 7)==0 ){
213 sqlite3ErrorMsg(pParse
, "cannot create trigger on system table");
214 goto trigger_cleanup
;
217 /* INSTEAD of triggers are only for views and views only support INSTEAD
220 if( IsView(pTab
) && tr_tm
!=TK_INSTEAD
){
221 sqlite3ErrorMsg(pParse
, "cannot create %s trigger on view: %S",
222 (tr_tm
== TK_BEFORE
)?"BEFORE":"AFTER", pTableName
->a
);
223 goto trigger_orphan_error
;
225 if( !IsView(pTab
) && tr_tm
==TK_INSTEAD
){
226 sqlite3ErrorMsg(pParse
, "cannot create INSTEAD OF"
227 " trigger on table: %S", pTableName
->a
);
228 goto trigger_orphan_error
;
231 #ifndef SQLITE_OMIT_AUTHORIZATION
232 if( !IN_RENAME_OBJECT
){
233 int iTabDb
= sqlite3SchemaToIndex(db
, pTab
->pSchema
);
234 int code
= SQLITE_CREATE_TRIGGER
;
235 const char *zDb
= db
->aDb
[iTabDb
].zDbSName
;
236 const char *zDbTrig
= isTemp
? db
->aDb
[1].zDbSName
: zDb
;
237 if( iTabDb
==1 || isTemp
) code
= SQLITE_CREATE_TEMP_TRIGGER
;
238 if( sqlite3AuthCheck(pParse
, code
, zName
, pTab
->zName
, zDbTrig
) ){
239 goto trigger_cleanup
;
241 if( sqlite3AuthCheck(pParse
, SQLITE_INSERT
, SCHEMA_TABLE(iTabDb
),0,zDb
)){
242 goto trigger_cleanup
;
247 /* INSTEAD OF triggers can only appear on views and BEFORE triggers
248 ** cannot appear on views. So we might as well translate every
249 ** INSTEAD OF trigger into a BEFORE trigger. It simplifies code
252 if (tr_tm
== TK_INSTEAD
){
256 /* Build the Trigger object */
257 pTrigger
= (Trigger
*)sqlite3DbMallocZero(db
, sizeof(Trigger
));
258 if( pTrigger
==0 ) goto trigger_cleanup
;
259 pTrigger
->zName
= zName
;
261 pTrigger
->table
= sqlite3DbStrDup(db
, pTableName
->a
[0].zName
);
262 pTrigger
->pSchema
= db
->aDb
[iDb
].pSchema
;
263 pTrigger
->pTabSchema
= pTab
->pSchema
;
264 pTrigger
->op
= (u8
)op
;
265 pTrigger
->tr_tm
= tr_tm
==TK_BEFORE
? TRIGGER_BEFORE
: TRIGGER_AFTER
;
266 if( IN_RENAME_OBJECT
){
267 sqlite3RenameTokenRemap(pParse
, pTrigger
->table
, pTableName
->a
[0].zName
);
268 pTrigger
->pWhen
= pWhen
;
271 pTrigger
->pWhen
= sqlite3ExprDup(db
, pWhen
, EXPRDUP_REDUCE
);
273 pTrigger
->pColumns
= pColumns
;
275 assert( pParse
->pNewTrigger
==0 );
276 pParse
->pNewTrigger
= pTrigger
;
279 sqlite3DbFree(db
, zName
);
280 sqlite3SrcListDelete(db
, pTableName
);
281 sqlite3IdListDelete(db
, pColumns
);
282 sqlite3ExprDelete(db
, pWhen
);
283 if( !pParse
->pNewTrigger
){
284 sqlite3DeleteTrigger(db
, pTrigger
);
286 assert( pParse
->pNewTrigger
==pTrigger
);
290 trigger_orphan_error
:
291 if( db
->init
.iDb
==1 ){
293 ** Normally, whenever a table is dropped, all associated triggers are
294 ** dropped too. But if a TEMP trigger is created on a non-TEMP table
295 ** and the table is dropped by a different database connection, the
296 ** trigger is not visible to the database connection that does the
297 ** drop so the trigger cannot be dropped. This results in an
298 ** "orphaned trigger" - a trigger whose associated table is missing.
300 ** 2020-11-05 see also https://sqlite.org/forum/forumpost/157dc791df
302 db
->init
.orphanTrigger
= 1;
304 goto trigger_cleanup
;
308 ** This routine is called after all of the trigger actions have been parsed
309 ** in order to complete the process of building the trigger.
311 void sqlite3FinishTrigger(
312 Parse
*pParse
, /* Parser context */
313 TriggerStep
*pStepList
, /* The triggered program */
314 Token
*pAll
/* Token that describes the complete CREATE TRIGGER */
316 Trigger
*pTrig
= pParse
->pNewTrigger
; /* Trigger being finished */
317 char *zName
; /* Name of trigger */
318 sqlite3
*db
= pParse
->db
; /* The database */
319 DbFixer sFix
; /* Fixer object */
320 int iDb
; /* Database containing the trigger */
321 Token nameToken
; /* Trigger name for error reporting */
323 pParse
->pNewTrigger
= 0;
324 if( NEVER(pParse
->nErr
) || !pTrig
) goto triggerfinish_cleanup
;
325 zName
= pTrig
->zName
;
326 iDb
= sqlite3SchemaToIndex(pParse
->db
, pTrig
->pSchema
);
327 pTrig
->step_list
= pStepList
;
329 pStepList
->pTrig
= pTrig
;
330 pStepList
= pStepList
->pNext
;
332 sqlite3TokenInit(&nameToken
, pTrig
->zName
);
333 sqlite3FixInit(&sFix
, pParse
, iDb
, "trigger", &nameToken
);
334 if( sqlite3FixTriggerStep(&sFix
, pTrig
->step_list
)
335 || sqlite3FixExpr(&sFix
, pTrig
->pWhen
)
337 goto triggerfinish_cleanup
;
340 #ifndef SQLITE_OMIT_ALTERTABLE
341 if( IN_RENAME_OBJECT
){
342 assert( !db
->init
.busy
);
343 pParse
->pNewTrigger
= pTrig
;
348 /* if we are not initializing,
349 ** build the sqlite_schema entry
351 if( !db
->init
.busy
){
355 /* If this is a new CREATE TABLE statement, and if shadow tables
356 ** are read-only, and the trigger makes a change to a shadow table,
357 ** then raise an error - do not allow the trigger to be created. */
358 if( sqlite3ReadOnlyShadowTables(db
) ){
360 for(pStep
=pTrig
->step_list
; pStep
; pStep
=pStep
->pNext
){
361 if( pStep
->zTarget
!=0
362 && sqlite3ShadowTableName(db
, pStep
->zTarget
)
364 sqlite3ErrorMsg(pParse
,
365 "trigger \"%s\" may not write to shadow table \"%s\"",
366 pTrig
->zName
, pStep
->zTarget
);
367 goto triggerfinish_cleanup
;
372 /* Make an entry in the sqlite_schema table */
373 v
= sqlite3GetVdbe(pParse
);
374 if( v
==0 ) goto triggerfinish_cleanup
;
375 sqlite3BeginWriteOperation(pParse
, 0, iDb
);
376 z
= sqlite3DbStrNDup(db
, (char*)pAll
->z
, pAll
->n
);
378 sqlite3NestedParse(pParse
,
379 "INSERT INTO %Q." LEGACY_SCHEMA_TABLE
380 " VALUES('trigger',%Q,%Q,0,'CREATE TRIGGER %q')",
381 db
->aDb
[iDb
].zDbSName
, zName
,
383 sqlite3DbFree(db
, z
);
384 sqlite3ChangeCookie(pParse
, iDb
);
385 sqlite3VdbeAddParseSchemaOp(v
, iDb
,
386 sqlite3MPrintf(db
, "type='trigger' AND name='%q'", zName
), 0);
390 Trigger
*pLink
= pTrig
;
391 Hash
*pHash
= &db
->aDb
[iDb
].pSchema
->trigHash
;
392 assert( sqlite3SchemaMutexHeld(db
, iDb
, 0) );
394 pTrig
= sqlite3HashInsert(pHash
, zName
, pTrig
);
397 }else if( pLink
->pSchema
==pLink
->pTabSchema
){
399 pTab
= sqlite3HashFind(&pLink
->pTabSchema
->tblHash
, pLink
->table
);
401 pLink
->pNext
= pTab
->pTrigger
;
402 pTab
->pTrigger
= pLink
;
406 triggerfinish_cleanup
:
407 sqlite3DeleteTrigger(db
, pTrig
);
408 assert( IN_RENAME_OBJECT
|| !pParse
->pNewTrigger
);
409 sqlite3DeleteTriggerStep(db
, pStepList
);
413 ** Duplicate a range of text from an SQL statement, then convert all
414 ** whitespace characters into ordinary space characters.
416 static char *triggerSpanDup(sqlite3
*db
, const char *zStart
, const char *zEnd
){
417 char *z
= sqlite3DbSpanDup(db
, zStart
, zEnd
);
419 if( z
) for(i
=0; z
[i
]; i
++) if( sqlite3Isspace(z
[i
]) ) z
[i
] = ' ';
424 ** Turn a SELECT statement (that the pSelect parameter points to) into
425 ** a trigger step. Return a pointer to a TriggerStep structure.
427 ** The parser calls this routine when it finds a SELECT statement in
428 ** body of a TRIGGER.
430 TriggerStep
*sqlite3TriggerSelectStep(
431 sqlite3
*db
, /* Database connection */
432 Select
*pSelect
, /* The SELECT statement */
433 const char *zStart
, /* Start of SQL text */
434 const char *zEnd
/* End of SQL text */
436 TriggerStep
*pTriggerStep
= sqlite3DbMallocZero(db
, sizeof(TriggerStep
));
437 if( pTriggerStep
==0 ) {
438 sqlite3SelectDelete(db
, pSelect
);
441 pTriggerStep
->op
= TK_SELECT
;
442 pTriggerStep
->pSelect
= pSelect
;
443 pTriggerStep
->orconf
= OE_Default
;
444 pTriggerStep
->zSpan
= triggerSpanDup(db
, zStart
, zEnd
);
449 ** Allocate space to hold a new trigger step. The allocated space
450 ** holds both the TriggerStep object and the TriggerStep.target.z string.
452 ** If an OOM error occurs, NULL is returned and db->mallocFailed is set.
454 static TriggerStep
*triggerStepAllocate(
455 Parse
*pParse
, /* Parser context */
456 u8 op
, /* Trigger opcode */
457 Token
*pName
, /* The target name */
458 const char *zStart
, /* Start of SQL text */
459 const char *zEnd
/* End of SQL text */
461 sqlite3
*db
= pParse
->db
;
462 TriggerStep
*pTriggerStep
;
464 if( pParse
->nErr
) return 0;
465 pTriggerStep
= sqlite3DbMallocZero(db
, sizeof(TriggerStep
) + pName
->n
+ 1);
467 char *z
= (char*)&pTriggerStep
[1];
468 memcpy(z
, pName
->z
, pName
->n
);
470 pTriggerStep
->zTarget
= z
;
471 pTriggerStep
->op
= op
;
472 pTriggerStep
->zSpan
= triggerSpanDup(db
, zStart
, zEnd
);
473 if( IN_RENAME_OBJECT
){
474 sqlite3RenameTokenMap(pParse
, pTriggerStep
->zTarget
, pName
);
481 ** Build a trigger step out of an INSERT statement. Return a pointer
482 ** to the new trigger step.
484 ** The parser calls this routine when it sees an INSERT inside the
485 ** body of a trigger.
487 TriggerStep
*sqlite3TriggerInsertStep(
488 Parse
*pParse
, /* Parser */
489 Token
*pTableName
, /* Name of the table into which we insert */
490 IdList
*pColumn
, /* List of columns in pTableName to insert into */
491 Select
*pSelect
, /* A SELECT statement that supplies values */
492 u8 orconf
, /* The conflict algorithm (OE_Abort, OE_Replace, etc.) */
493 Upsert
*pUpsert
, /* ON CONFLICT clauses for upsert */
494 const char *zStart
, /* Start of SQL text */
495 const char *zEnd
/* End of SQL text */
497 sqlite3
*db
= pParse
->db
;
498 TriggerStep
*pTriggerStep
;
500 assert(pSelect
!= 0 || db
->mallocFailed
);
502 pTriggerStep
= triggerStepAllocate(pParse
, TK_INSERT
, pTableName
,zStart
,zEnd
);
504 if( IN_RENAME_OBJECT
){
505 pTriggerStep
->pSelect
= pSelect
;
508 pTriggerStep
->pSelect
= sqlite3SelectDup(db
, pSelect
, EXPRDUP_REDUCE
);
510 pTriggerStep
->pIdList
= pColumn
;
511 pTriggerStep
->pUpsert
= pUpsert
;
512 pTriggerStep
->orconf
= orconf
;
514 sqlite3HasExplicitNulls(pParse
, pUpsert
->pUpsertTarget
);
518 sqlite3IdListDelete(db
, pColumn
);
520 sqlite3UpsertDelete(db
, pUpsert
);
522 sqlite3SelectDelete(db
, pSelect
);
528 ** Construct a trigger step that implements an UPDATE statement and return
529 ** a pointer to that trigger step. The parser calls this routine when it
530 ** sees an UPDATE statement inside the body of a CREATE TRIGGER.
532 TriggerStep
*sqlite3TriggerUpdateStep(
533 Parse
*pParse
, /* Parser */
534 Token
*pTableName
, /* Name of the table to be updated */
535 SrcList
*pFrom
, /* FROM clause for an UPDATE-FROM, or NULL */
536 ExprList
*pEList
, /* The SET clause: list of column and new values */
537 Expr
*pWhere
, /* The WHERE clause */
538 u8 orconf
, /* The conflict algorithm. (OE_Abort, OE_Ignore, etc) */
539 const char *zStart
, /* Start of SQL text */
540 const char *zEnd
/* End of SQL text */
542 sqlite3
*db
= pParse
->db
;
543 TriggerStep
*pTriggerStep
;
545 pTriggerStep
= triggerStepAllocate(pParse
, TK_UPDATE
, pTableName
,zStart
,zEnd
);
547 if( IN_RENAME_OBJECT
){
548 pTriggerStep
->pExprList
= pEList
;
549 pTriggerStep
->pWhere
= pWhere
;
550 pTriggerStep
->pFrom
= pFrom
;
555 pTriggerStep
->pExprList
= sqlite3ExprListDup(db
, pEList
, EXPRDUP_REDUCE
);
556 pTriggerStep
->pWhere
= sqlite3ExprDup(db
, pWhere
, EXPRDUP_REDUCE
);
557 pTriggerStep
->pFrom
= sqlite3SrcListDup(db
, pFrom
, EXPRDUP_REDUCE
);
559 pTriggerStep
->orconf
= orconf
;
561 sqlite3ExprListDelete(db
, pEList
);
562 sqlite3ExprDelete(db
, pWhere
);
563 sqlite3SrcListDelete(db
, pFrom
);
568 ** Construct a trigger step that implements a DELETE statement and return
569 ** a pointer to that trigger step. The parser calls this routine when it
570 ** sees a DELETE statement inside the body of a CREATE TRIGGER.
572 TriggerStep
*sqlite3TriggerDeleteStep(
573 Parse
*pParse
, /* Parser */
574 Token
*pTableName
, /* The table from which rows are deleted */
575 Expr
*pWhere
, /* The WHERE clause */
576 const char *zStart
, /* Start of SQL text */
577 const char *zEnd
/* End of SQL text */
579 sqlite3
*db
= pParse
->db
;
580 TriggerStep
*pTriggerStep
;
582 pTriggerStep
= triggerStepAllocate(pParse
, TK_DELETE
, pTableName
,zStart
,zEnd
);
584 if( IN_RENAME_OBJECT
){
585 pTriggerStep
->pWhere
= pWhere
;
588 pTriggerStep
->pWhere
= sqlite3ExprDup(db
, pWhere
, EXPRDUP_REDUCE
);
590 pTriggerStep
->orconf
= OE_Default
;
592 sqlite3ExprDelete(db
, pWhere
);
597 ** Recursively delete a Trigger structure
599 void sqlite3DeleteTrigger(sqlite3
*db
, Trigger
*pTrigger
){
600 if( pTrigger
==0 || pTrigger
->bReturning
) return;
601 sqlite3DeleteTriggerStep(db
, pTrigger
->step_list
);
602 sqlite3DbFree(db
, pTrigger
->zName
);
603 sqlite3DbFree(db
, pTrigger
->table
);
604 sqlite3ExprDelete(db
, pTrigger
->pWhen
);
605 sqlite3IdListDelete(db
, pTrigger
->pColumns
);
606 sqlite3DbFree(db
, pTrigger
);
610 ** This function is called to drop a trigger from the database schema.
612 ** This may be called directly from the parser and therefore identifies
613 ** the trigger by name. The sqlite3DropTriggerPtr() routine does the
614 ** same job as this routine except it takes a pointer to the trigger
615 ** instead of the trigger name.
617 void sqlite3DropTrigger(Parse
*pParse
, SrcList
*pName
, int noErr
){
618 Trigger
*pTrigger
= 0;
622 sqlite3
*db
= pParse
->db
;
624 if( db
->mallocFailed
) goto drop_trigger_cleanup
;
625 if( SQLITE_OK
!=sqlite3ReadSchema(pParse
) ){
626 goto drop_trigger_cleanup
;
629 assert( pName
->nSrc
==1 );
630 zDb
= pName
->a
[0].zDatabase
;
631 zName
= pName
->a
[0].zName
;
632 assert( zDb
!=0 || sqlite3BtreeHoldsAllMutexes(db
) );
633 for(i
=OMIT_TEMPDB
; i
<db
->nDb
; i
++){
634 int j
= (i
<2) ? i
^1 : i
; /* Search TEMP before MAIN */
635 if( zDb
&& sqlite3DbIsNamed(db
, j
, zDb
)==0 ) continue;
636 assert( sqlite3SchemaMutexHeld(db
, j
, 0) );
637 pTrigger
= sqlite3HashFind(&(db
->aDb
[j
].pSchema
->trigHash
), zName
);
638 if( pTrigger
) break;
642 sqlite3ErrorMsg(pParse
, "no such trigger: %S", pName
->a
);
644 sqlite3CodeVerifyNamedSchema(pParse
, zDb
);
646 pParse
->checkSchema
= 1;
647 goto drop_trigger_cleanup
;
649 sqlite3DropTriggerPtr(pParse
, pTrigger
);
651 drop_trigger_cleanup
:
652 sqlite3SrcListDelete(db
, pName
);
656 ** Return a pointer to the Table structure for the table that a trigger
659 static Table
*tableOfTrigger(Trigger
*pTrigger
){
660 return sqlite3HashFind(&pTrigger
->pTabSchema
->tblHash
, pTrigger
->table
);
665 ** Drop a trigger given a pointer to that trigger.
667 void sqlite3DropTriggerPtr(Parse
*pParse
, Trigger
*pTrigger
){
670 sqlite3
*db
= pParse
->db
;
673 iDb
= sqlite3SchemaToIndex(pParse
->db
, pTrigger
->pSchema
);
674 assert( iDb
>=0 && iDb
<db
->nDb
);
675 pTable
= tableOfTrigger(pTrigger
);
676 assert( (pTable
&& pTable
->pSchema
==pTrigger
->pSchema
) || iDb
==1 );
677 #ifndef SQLITE_OMIT_AUTHORIZATION
679 int code
= SQLITE_DROP_TRIGGER
;
680 const char *zDb
= db
->aDb
[iDb
].zDbSName
;
681 const char *zTab
= SCHEMA_TABLE(iDb
);
682 if( iDb
==1 ) code
= SQLITE_DROP_TEMP_TRIGGER
;
683 if( sqlite3AuthCheck(pParse
, code
, pTrigger
->zName
, pTable
->zName
, zDb
) ||
684 sqlite3AuthCheck(pParse
, SQLITE_DELETE
, zTab
, 0, zDb
) ){
690 /* Generate code to destroy the database record of the trigger.
692 if( (v
= sqlite3GetVdbe(pParse
))!=0 ){
693 sqlite3NestedParse(pParse
,
694 "DELETE FROM %Q." LEGACY_SCHEMA_TABLE
" WHERE name=%Q AND type='trigger'",
695 db
->aDb
[iDb
].zDbSName
, pTrigger
->zName
697 sqlite3ChangeCookie(pParse
, iDb
);
698 sqlite3VdbeAddOp4(v
, OP_DropTrigger
, iDb
, 0, 0, pTrigger
->zName
, 0);
703 ** Remove a trigger from the hash tables of the sqlite* pointer.
705 void sqlite3UnlinkAndDeleteTrigger(sqlite3
*db
, int iDb
, const char *zName
){
709 assert( sqlite3SchemaMutexHeld(db
, iDb
, 0) );
710 pHash
= &(db
->aDb
[iDb
].pSchema
->trigHash
);
711 pTrigger
= sqlite3HashInsert(pHash
, zName
, 0);
712 if( ALWAYS(pTrigger
) ){
713 if( pTrigger
->pSchema
==pTrigger
->pTabSchema
){
714 Table
*pTab
= tableOfTrigger(pTrigger
);
717 for(pp
=&pTab
->pTrigger
; *pp
; pp
=&((*pp
)->pNext
)){
725 sqlite3DeleteTrigger(db
, pTrigger
);
726 db
->mDbFlags
|= DBFLAG_SchemaChange
;
731 ** pEList is the SET clause of an UPDATE statement. Each entry
732 ** in pEList is of the format <id>=<expr>. If any of the entries
733 ** in pEList have an <id> which matches an identifier in pIdList,
734 ** then return TRUE. If pIdList==NULL, then it is considered a
735 ** wildcard that matches anything. Likewise if pEList==NULL then
736 ** it matches anything so always return true. Return false only
737 ** if there is no match.
739 static int checkColumnOverlap(IdList
*pIdList
, ExprList
*pEList
){
741 if( pIdList
==0 || NEVER(pEList
==0) ) return 1;
742 for(e
=0; e
<pEList
->nExpr
; e
++){
743 if( sqlite3IdListIndex(pIdList
, pEList
->a
[e
].zEName
)>=0 ) return 1;
749 ** Return true if any TEMP triggers exist
751 static int tempTriggersExist(sqlite3
*db
){
752 if( NEVER(db
->aDb
[1].pSchema
==0) ) return 0;
753 if( sqliteHashFirst(&db
->aDb
[1].pSchema
->trigHash
)==0 ) return 0;
758 ** Return a list of all triggers on table pTab if there exists at least
759 ** one trigger that must be fired when an operation of type 'op' is
760 ** performed on the table, and, if that operation is an UPDATE, if at
761 ** least one of the columns in pChanges is being modified.
763 static SQLITE_NOINLINE Trigger
*triggersReallyExist(
764 Parse
*pParse
, /* Parse context */
765 Table
*pTab
, /* The table the contains the triggers */
766 int op
, /* one of TK_DELETE, TK_INSERT, TK_UPDATE */
767 ExprList
*pChanges
, /* Columns that change in an UPDATE statement */
768 int *pMask
/* OUT: Mask of TRIGGER_BEFORE|TRIGGER_AFTER */
774 pList
= sqlite3TriggerList(pParse
, pTab
);
775 assert( pList
==0 || IsVirtual(pTab
)==0
776 || (pList
->bReturning
&& pList
->pNext
==0) );
779 if( (pParse
->db
->flags
& SQLITE_EnableTrigger
)==0
782 /* The SQLITE_DBCONFIG_ENABLE_TRIGGER setting is off. That means that
783 ** only TEMP triggers are allowed. Truncate the pList so that it
784 ** includes only TEMP triggers */
785 if( pList
==pTab
->pTrigger
){
787 goto exit_triggers_exist
;
789 while( ALWAYS(p
->pNext
) && p
->pNext
!=pTab
->pTrigger
) p
= p
->pNext
;
794 if( p
->op
==op
&& checkColumnOverlap(p
->pColumns
, pChanges
) ){
796 }else if( p
->op
==TK_RETURNING
){
797 /* The first time a RETURNING trigger is seen, the "op" value tells
798 ** us what time of trigger it should be. */
799 assert( sqlite3IsToplevel(pParse
) );
801 if( IsVirtual(pTab
) ){
803 sqlite3ErrorMsg(pParse
,
804 "%s RETURNING is not available on virtual tables",
805 op
==TK_DELETE
? "DELETE" : "UPDATE");
807 p
->tr_tm
= TRIGGER_BEFORE
;
809 p
->tr_tm
= TRIGGER_AFTER
;
812 }else if( p
->bReturning
&& p
->op
==TK_INSERT
&& op
==TK_UPDATE
813 && sqlite3IsToplevel(pParse
) ){
814 /* Also fire a RETURNING trigger for an UPSERT */
824 return (mask
? pList
: 0);
826 Trigger
*sqlite3TriggersExist(
827 Parse
*pParse
, /* Parse context */
828 Table
*pTab
, /* The table the contains the triggers */
829 int op
, /* one of TK_DELETE, TK_INSERT, TK_UPDATE */
830 ExprList
*pChanges
, /* Columns that change in an UPDATE statement */
831 int *pMask
/* OUT: Mask of TRIGGER_BEFORE|TRIGGER_AFTER */
834 if( (pTab
->pTrigger
==0 && !tempTriggersExist(pParse
->db
))
835 || pParse
->disableTriggers
837 if( pMask
) *pMask
= 0;
840 return triggersReallyExist(pParse
,pTab
,op
,pChanges
,pMask
);
844 ** Convert the pStep->zTarget string into a SrcList and return a pointer
847 ** This routine adds a specific database name, if needed, to the target when
848 ** forming the SrcList. This prevents a trigger in one database from
849 ** referring to a target in another database. An exception is when the
850 ** trigger is in TEMP in which case it can refer to any other database it
853 SrcList
*sqlite3TriggerStepSrc(
854 Parse
*pParse
, /* The parsing context */
855 TriggerStep
*pStep
/* The trigger containing the target token */
857 sqlite3
*db
= pParse
->db
;
858 SrcList
*pSrc
; /* SrcList to be returned */
859 char *zName
= sqlite3DbStrDup(db
, pStep
->zTarget
);
860 pSrc
= sqlite3SrcListAppend(pParse
, 0, 0, 0);
861 assert( pSrc
==0 || pSrc
->nSrc
==1 );
862 assert( zName
|| pSrc
==0 );
864 Schema
*pSchema
= pStep
->pTrig
->pSchema
;
865 pSrc
->a
[0].zName
= zName
;
866 if( pSchema
!=db
->aDb
[1].pSchema
){
867 pSrc
->a
[0].pSchema
= pSchema
;
870 SrcList
*pDup
= sqlite3SrcListDup(db
, pStep
->pFrom
, 0);
871 if( pDup
&& pDup
->nSrc
>1 && !IN_RENAME_OBJECT
){
874 pSubquery
= sqlite3SelectNew(pParse
,0,pDup
,0,0,0,0,SF_NestedFrom
,0);
877 pDup
= sqlite3SrcListAppendFromTerm(pParse
,0,0,0,&as
,pSubquery
,0);
879 pSrc
= sqlite3SrcListAppendList(pParse
, pSrc
, pDup
);
882 sqlite3DbFree(db
, zName
);
888 ** Return true if the pExpr term from the RETURNING clause argument
889 ** list is of the form "*". Raise an error if the terms if of the
892 static int isAsteriskTerm(
893 Parse
*pParse
, /* Parsing context */
894 Expr
*pTerm
/* A term in the RETURNING clause */
897 if( pTerm
->op
==TK_ASTERISK
) return 1;
898 if( pTerm
->op
!=TK_DOT
) return 0;
899 assert( pTerm
->pRight
!=0 );
900 assert( pTerm
->pLeft
!=0 );
901 if( pTerm
->pRight
->op
!=TK_ASTERISK
) return 0;
902 sqlite3ErrorMsg(pParse
, "RETURNING may not use \"TABLE.*\" wildcards");
906 /* The input list pList is the list of result set terms from a RETURNING
907 ** clause. The table that we are returning from is pTab.
909 ** This routine makes a copy of the pList, and at the same time expands
910 ** any "*" wildcards to be the complete set of columns from pTab.
912 static ExprList
*sqlite3ExpandReturning(
913 Parse
*pParse
, /* Parsing context */
914 ExprList
*pList
, /* The arguments to RETURNING */
915 Table
*pTab
/* The table being updated */
918 sqlite3
*db
= pParse
->db
;
921 for(i
=0; i
<pList
->nExpr
; i
++){
922 Expr
*pOldExpr
= pList
->a
[i
].pExpr
;
923 if( NEVER(pOldExpr
==0) ) continue;
924 if( isAsteriskTerm(pParse
, pOldExpr
) ){
926 for(jj
=0; jj
<pTab
->nCol
; jj
++){
928 if( IsHiddenColumn(pTab
->aCol
+jj
) ) continue;
929 pNewExpr
= sqlite3Expr(db
, TK_ID
, pTab
->aCol
[jj
].zCnName
);
930 pNew
= sqlite3ExprListAppend(pParse
, pNew
, pNewExpr
);
931 if( !db
->mallocFailed
){
932 struct ExprList_item
*pItem
= &pNew
->a
[pNew
->nExpr
-1];
933 pItem
->zEName
= sqlite3DbStrDup(db
, pTab
->aCol
[jj
].zCnName
);
934 pItem
->fg
.eEName
= ENAME_NAME
;
938 Expr
*pNewExpr
= sqlite3ExprDup(db
, pOldExpr
, 0);
939 pNew
= sqlite3ExprListAppend(pParse
, pNew
, pNewExpr
);
940 if( !db
->mallocFailed
&& ALWAYS(pList
->a
[i
].zEName
!=0) ){
941 struct ExprList_item
*pItem
= &pNew
->a
[pNew
->nExpr
-1];
942 pItem
->zEName
= sqlite3DbStrDup(db
, pList
->a
[i
].zEName
);
943 pItem
->fg
.eEName
= pList
->a
[i
].fg
.eEName
;
951 ** Generate code for the RETURNING trigger. Unlike other triggers
952 ** that invoke a subprogram in the bytecode, the code for RETURNING
953 ** is generated in-line.
955 static void codeReturningTrigger(
956 Parse
*pParse
, /* Parse context */
957 Trigger
*pTrigger
, /* The trigger step that defines the RETURNING */
958 Table
*pTab
, /* The table to code triggers from */
959 int regIn
/* The first in an array of registers */
961 Vdbe
*v
= pParse
->pVdbe
;
962 sqlite3
*db
= pParse
->db
;
964 Returning
*pReturning
;
969 assert( pParse
->bReturning
);
970 assert( db
->pParse
==pParse
);
971 pReturning
= pParse
->u1
.pReturning
;
972 assert( pTrigger
== &(pReturning
->retTrig
) );
973 memset(&sSelect
, 0, sizeof(sSelect
));
974 memset(&sFrom
, 0, sizeof(sFrom
));
975 sSelect
.pEList
= sqlite3ExprListDup(db
, pReturning
->pReturnEL
, 0);
976 sSelect
.pSrc
= &sFrom
;
978 sFrom
.a
[0].pTab
= pTab
;
979 sFrom
.a
[0].iCursor
= -1;
980 sqlite3SelectPrep(pParse
, &sSelect
, 0);
981 if( pParse
->nErr
==0 ){
982 assert( db
->mallocFailed
==0 );
983 sqlite3GenerateColumnNames(pParse
, &sSelect
);
985 sqlite3ExprListDelete(db
, sSelect
.pEList
);
986 pNew
= sqlite3ExpandReturning(pParse
, pReturning
->pReturnEL
, pTab
);
987 if( pParse
->nErr
==0 ){
989 memset(&sNC
, 0, sizeof(sNC
));
990 if( pReturning
->nRetCol
==0 ){
991 pReturning
->nRetCol
= pNew
->nExpr
;
992 pReturning
->iRetCur
= pParse
->nTab
++;
995 sNC
.uNC
.iBaseReg
= regIn
;
996 sNC
.ncFlags
= NC_UBaseReg
;
997 pParse
->eTriggerOp
= pTrigger
->op
;
998 pParse
->pTriggerTab
= pTab
;
999 if( sqlite3ResolveExprListNames(&sNC
, pNew
)==SQLITE_OK
1000 && ALWAYS(!db
->mallocFailed
)
1003 int nCol
= pNew
->nExpr
;
1004 int reg
= pParse
->nMem
+1;
1005 pParse
->nMem
+= nCol
+2;
1006 pReturning
->iRetReg
= reg
;
1007 for(i
=0; i
<nCol
; i
++){
1008 Expr
*pCol
= pNew
->a
[i
].pExpr
;
1009 assert( pCol
!=0 ); /* Due to !db->mallocFailed ~9 lines above */
1010 sqlite3ExprCodeFactorable(pParse
, pCol
, reg
+i
);
1011 if( sqlite3ExprAffinity(pCol
)==SQLITE_AFF_REAL
){
1012 sqlite3VdbeAddOp1(v
, OP_RealAffinity
, reg
+i
);
1015 sqlite3VdbeAddOp3(v
, OP_MakeRecord
, reg
, i
, reg
+i
);
1016 sqlite3VdbeAddOp2(v
, OP_NewRowid
, pReturning
->iRetCur
, reg
+i
+1);
1017 sqlite3VdbeAddOp3(v
, OP_Insert
, pReturning
->iRetCur
, reg
+i
, reg
+i
+1);
1020 sqlite3ExprListDelete(db
, pNew
);
1021 pParse
->eTriggerOp
= 0;
1022 pParse
->pTriggerTab
= 0;
1028 ** Generate VDBE code for the statements inside the body of a single
1031 static int codeTriggerProgram(
1032 Parse
*pParse
, /* The parser context */
1033 TriggerStep
*pStepList
, /* List of statements inside the trigger body */
1034 int orconf
/* Conflict algorithm. (OE_Abort, etc) */
1037 Vdbe
*v
= pParse
->pVdbe
;
1038 sqlite3
*db
= pParse
->db
;
1040 assert( pParse
->pTriggerTab
&& pParse
->pToplevel
);
1041 assert( pStepList
);
1043 for(pStep
=pStepList
; pStep
; pStep
=pStep
->pNext
){
1044 /* Figure out the ON CONFLICT policy that will be used for this step
1045 ** of the trigger program. If the statement that caused this trigger
1046 ** to fire had an explicit ON CONFLICT, then use it. Otherwise, use
1047 ** the ON CONFLICT policy that was specified as part of the trigger
1048 ** step statement. Example:
1050 ** CREATE TRIGGER AFTER INSERT ON t1 BEGIN;
1051 ** INSERT OR REPLACE INTO t2 VALUES(new.a, new.b);
1054 ** INSERT INTO t1 ... ; -- insert into t2 uses REPLACE policy
1055 ** INSERT OR IGNORE INTO t1 ... ; -- insert into t2 uses IGNORE policy
1057 pParse
->eOrconf
= (orconf
==OE_Default
)?pStep
->orconf
:(u8
)orconf
;
1058 assert( pParse
->okConstFactor
==0 );
1060 #ifndef SQLITE_OMIT_TRACE
1062 sqlite3VdbeAddOp4(v
, OP_Trace
, 0x7fffffff, 1, 0,
1063 sqlite3MPrintf(db
, "-- %s", pStep
->zSpan
),
1068 switch( pStep
->op
){
1070 sqlite3Update(pParse
,
1071 sqlite3TriggerStepSrc(pParse
, pStep
),
1072 sqlite3ExprListDup(db
, pStep
->pExprList
, 0),
1073 sqlite3ExprDup(db
, pStep
->pWhere
, 0),
1074 pParse
->eOrconf
, 0, 0, 0
1076 sqlite3VdbeAddOp0(v
, OP_ResetCount
);
1080 sqlite3Insert(pParse
,
1081 sqlite3TriggerStepSrc(pParse
, pStep
),
1082 sqlite3SelectDup(db
, pStep
->pSelect
, 0),
1083 sqlite3IdListDup(db
, pStep
->pIdList
),
1085 sqlite3UpsertDup(db
, pStep
->pUpsert
)
1087 sqlite3VdbeAddOp0(v
, OP_ResetCount
);
1091 sqlite3DeleteFrom(pParse
,
1092 sqlite3TriggerStepSrc(pParse
, pStep
),
1093 sqlite3ExprDup(db
, pStep
->pWhere
, 0), 0, 0
1095 sqlite3VdbeAddOp0(v
, OP_ResetCount
);
1098 default: assert( pStep
->op
==TK_SELECT
); {
1100 Select
*pSelect
= sqlite3SelectDup(db
, pStep
->pSelect
, 0);
1101 sqlite3SelectDestInit(&sDest
, SRT_Discard
, 0);
1102 sqlite3Select(pParse
, pSelect
, &sDest
);
1103 sqlite3SelectDelete(db
, pSelect
);
1112 #ifdef SQLITE_ENABLE_EXPLAIN_COMMENTS
1114 ** This function is used to add VdbeComment() annotations to a VDBE
1115 ** program. It is not used in production code, only for debugging.
1117 static const char *onErrorText(int onError
){
1119 case OE_Abort
: return "abort";
1120 case OE_Rollback
: return "rollback";
1121 case OE_Fail
: return "fail";
1122 case OE_Replace
: return "replace";
1123 case OE_Ignore
: return "ignore";
1124 case OE_Default
: return "default";
1131 ** Parse context structure pFrom has just been used to create a sub-vdbe
1132 ** (trigger program). If an error has occurred, transfer error information
1133 ** from pFrom to pTo.
1135 static void transferParseError(Parse
*pTo
, Parse
*pFrom
){
1136 assert( pFrom
->zErrMsg
==0 || pFrom
->nErr
);
1137 assert( pTo
->zErrMsg
==0 || pTo
->nErr
);
1139 pTo
->zErrMsg
= pFrom
->zErrMsg
;
1140 pTo
->nErr
= pFrom
->nErr
;
1141 pTo
->rc
= pFrom
->rc
;
1143 sqlite3DbFree(pFrom
->db
, pFrom
->zErrMsg
);
1148 ** Create and populate a new TriggerPrg object with a sub-program
1149 ** implementing trigger pTrigger with ON CONFLICT policy orconf.
1151 static TriggerPrg
*codeRowTrigger(
1152 Parse
*pParse
, /* Current parse context */
1153 Trigger
*pTrigger
, /* Trigger to code */
1154 Table
*pTab
, /* The table pTrigger is attached to */
1155 int orconf
/* ON CONFLICT policy to code trigger program with */
1157 Parse
*pTop
= sqlite3ParseToplevel(pParse
);
1158 sqlite3
*db
= pParse
->db
; /* Database handle */
1159 TriggerPrg
*pPrg
; /* Value to return */
1160 Expr
*pWhen
= 0; /* Duplicate of trigger WHEN expression */
1161 Vdbe
*v
; /* Temporary VM */
1162 NameContext sNC
; /* Name context for sub-vdbe */
1163 SubProgram
*pProgram
= 0; /* Sub-vdbe for trigger program */
1164 int iEndTrigger
= 0; /* Label to jump to if WHEN is false */
1165 Parse sSubParse
; /* Parse context for sub-vdbe */
1167 assert( pTrigger
->zName
==0 || pTab
==tableOfTrigger(pTrigger
) );
1168 assert( pTop
->pVdbe
);
1170 /* Allocate the TriggerPrg and SubProgram objects. To ensure that they
1171 ** are freed if an error occurs, link them into the Parse.pTriggerPrg
1172 ** list of the top-level Parse object sooner rather than later. */
1173 pPrg
= sqlite3DbMallocZero(db
, sizeof(TriggerPrg
));
1174 if( !pPrg
) return 0;
1175 pPrg
->pNext
= pTop
->pTriggerPrg
;
1176 pTop
->pTriggerPrg
= pPrg
;
1177 pPrg
->pProgram
= pProgram
= sqlite3DbMallocZero(db
, sizeof(SubProgram
));
1178 if( !pProgram
) return 0;
1179 sqlite3VdbeLinkSubProgram(pTop
->pVdbe
, pProgram
);
1180 pPrg
->pTrigger
= pTrigger
;
1181 pPrg
->orconf
= orconf
;
1182 pPrg
->aColmask
[0] = 0xffffffff;
1183 pPrg
->aColmask
[1] = 0xffffffff;
1185 /* Allocate and populate a new Parse context to use for coding the
1186 ** trigger sub-program. */
1187 sqlite3ParseObjectInit(&sSubParse
, db
);
1188 memset(&sNC
, 0, sizeof(sNC
));
1189 sNC
.pParse
= &sSubParse
;
1190 sSubParse
.pTriggerTab
= pTab
;
1191 sSubParse
.pToplevel
= pTop
;
1192 sSubParse
.zAuthContext
= pTrigger
->zName
;
1193 sSubParse
.eTriggerOp
= pTrigger
->op
;
1194 sSubParse
.nQueryLoop
= pParse
->nQueryLoop
;
1195 sSubParse
.prepFlags
= pParse
->prepFlags
;
1197 v
= sqlite3GetVdbe(&sSubParse
);
1199 VdbeComment((v
, "Start: %s.%s (%s %s%s%s ON %s)",
1200 pTrigger
->zName
, onErrorText(orconf
),
1201 (pTrigger
->tr_tm
==TRIGGER_BEFORE
? "BEFORE" : "AFTER"),
1202 (pTrigger
->op
==TK_UPDATE
? "UPDATE" : ""),
1203 (pTrigger
->op
==TK_INSERT
? "INSERT" : ""),
1204 (pTrigger
->op
==TK_DELETE
? "DELETE" : ""),
1207 #ifndef SQLITE_OMIT_TRACE
1208 if( pTrigger
->zName
){
1209 sqlite3VdbeChangeP4(v
, -1,
1210 sqlite3MPrintf(db
, "-- TRIGGER %s", pTrigger
->zName
), P4_DYNAMIC
1215 /* If one was specified, code the WHEN clause. If it evaluates to false
1216 ** (or NULL) the sub-vdbe is immediately halted by jumping to the
1217 ** OP_Halt inserted at the end of the program. */
1218 if( pTrigger
->pWhen
){
1219 pWhen
= sqlite3ExprDup(db
, pTrigger
->pWhen
, 0);
1220 if( db
->mallocFailed
==0
1221 && SQLITE_OK
==sqlite3ResolveExprNames(&sNC
, pWhen
)
1223 iEndTrigger
= sqlite3VdbeMakeLabel(&sSubParse
);
1224 sqlite3ExprIfFalse(&sSubParse
, pWhen
, iEndTrigger
, SQLITE_JUMPIFNULL
);
1226 sqlite3ExprDelete(db
, pWhen
);
1229 /* Code the trigger program into the sub-vdbe. */
1230 codeTriggerProgram(&sSubParse
, pTrigger
->step_list
, orconf
);
1232 /* Insert an OP_Halt at the end of the sub-program. */
1234 sqlite3VdbeResolveLabel(v
, iEndTrigger
);
1236 sqlite3VdbeAddOp0(v
, OP_Halt
);
1237 VdbeComment((v
, "End: %s.%s", pTrigger
->zName
, onErrorText(orconf
)));
1238 transferParseError(pParse
, &sSubParse
);
1240 if( pParse
->nErr
==0 ){
1241 assert( db
->mallocFailed
==0 );
1242 pProgram
->aOp
= sqlite3VdbeTakeOpArray(v
, &pProgram
->nOp
, &pTop
->nMaxArg
);
1244 pProgram
->nMem
= sSubParse
.nMem
;
1245 pProgram
->nCsr
= sSubParse
.nTab
;
1246 pProgram
->token
= (void *)pTrigger
;
1247 pPrg
->aColmask
[0] = sSubParse
.oldmask
;
1248 pPrg
->aColmask
[1] = sSubParse
.newmask
;
1249 sqlite3VdbeDelete(v
);
1251 transferParseError(pParse
, &sSubParse
);
1254 assert( !sSubParse
.pTriggerPrg
&& !sSubParse
.nMaxArg
);
1255 sqlite3ParseObjectReset(&sSubParse
);
1260 ** Return a pointer to a TriggerPrg object containing the sub-program for
1261 ** trigger pTrigger with default ON CONFLICT algorithm orconf. If no such
1262 ** TriggerPrg object exists, a new object is allocated and populated before
1265 static TriggerPrg
*getRowTrigger(
1266 Parse
*pParse
, /* Current parse context */
1267 Trigger
*pTrigger
, /* Trigger to code */
1268 Table
*pTab
, /* The table trigger pTrigger is attached to */
1269 int orconf
/* ON CONFLICT algorithm. */
1271 Parse
*pRoot
= sqlite3ParseToplevel(pParse
);
1274 assert( pTrigger
->zName
==0 || pTab
==tableOfTrigger(pTrigger
) );
1276 /* It may be that this trigger has already been coded (or is in the
1277 ** process of being coded). If this is the case, then an entry with
1278 ** a matching TriggerPrg.pTrigger field will be present somewhere
1279 ** in the Parse.pTriggerPrg list. Search for such an entry. */
1280 for(pPrg
=pRoot
->pTriggerPrg
;
1281 pPrg
&& (pPrg
->pTrigger
!=pTrigger
|| pPrg
->orconf
!=orconf
);
1285 /* If an existing TriggerPrg could not be located, create a new one. */
1287 pPrg
= codeRowTrigger(pParse
, pTrigger
, pTab
, orconf
);
1288 pParse
->db
->errByteOffset
= -1;
1295 ** Generate code for the trigger program associated with trigger p on
1296 ** table pTab. The reg, orconf and ignoreJump parameters passed to this
1297 ** function are the same as those described in the header function for
1298 ** sqlite3CodeRowTrigger()
1300 void sqlite3CodeRowTriggerDirect(
1301 Parse
*pParse
, /* Parse context */
1302 Trigger
*p
, /* Trigger to code */
1303 Table
*pTab
, /* The table to code triggers from */
1304 int reg
, /* Reg array containing OLD.* and NEW.* values */
1305 int orconf
, /* ON CONFLICT policy */
1306 int ignoreJump
/* Instruction to jump to for RAISE(IGNORE) */
1308 Vdbe
*v
= sqlite3GetVdbe(pParse
); /* Main VM */
1310 pPrg
= getRowTrigger(pParse
, p
, pTab
, orconf
);
1311 assert( pPrg
|| pParse
->nErr
);
1313 /* Code the OP_Program opcode in the parent VDBE. P4 of the OP_Program
1314 ** is a pointer to the sub-vdbe containing the trigger program. */
1316 int bRecursive
= (p
->zName
&& 0==(pParse
->db
->flags
&SQLITE_RecTriggers
));
1318 sqlite3VdbeAddOp4(v
, OP_Program
, reg
, ignoreJump
, ++pParse
->nMem
,
1319 (const char *)pPrg
->pProgram
, P4_SUBPROGRAM
);
1321 (v
, "Call: %s.%s", (p
->zName
?p
->zName
:"fkey"), onErrorText(orconf
)));
1323 /* Set the P5 operand of the OP_Program instruction to non-zero if
1324 ** recursive invocation of this trigger program is disallowed. Recursive
1325 ** invocation is disallowed if (a) the sub-program is really a trigger,
1326 ** not a foreign key action, and (b) the flag to enable recursive triggers
1328 sqlite3VdbeChangeP5(v
, (u8
)bRecursive
);
1333 ** This is called to code the required FOR EACH ROW triggers for an operation
1334 ** on table pTab. The operation to code triggers for (INSERT, UPDATE or DELETE)
1335 ** is given by the op parameter. The tr_tm parameter determines whether the
1336 ** BEFORE or AFTER triggers are coded. If the operation is an UPDATE, then
1337 ** parameter pChanges is passed the list of columns being modified.
1339 ** If there are no triggers that fire at the specified time for the specified
1340 ** operation on pTab, this function is a no-op.
1342 ** The reg argument is the address of the first in an array of registers
1343 ** that contain the values substituted for the new.* and old.* references
1344 ** in the trigger program. If N is the number of columns in table pTab
1345 ** (a copy of pTab->nCol), then registers are populated as follows:
1347 ** Register Contains
1348 ** ------------------------------------------------------
1350 ** reg+1 OLD.* value of left-most column of pTab
1352 ** reg+N OLD.* value of right-most column of pTab
1353 ** reg+N+1 NEW.rowid
1354 ** reg+N+2 NEW.* value of left-most column of pTab
1356 ** reg+N+N+1 NEW.* value of right-most column of pTab
1358 ** For ON DELETE triggers, the registers containing the NEW.* values will
1359 ** never be accessed by the trigger program, so they are not allocated or
1360 ** populated by the caller (there is no data to populate them with anyway).
1361 ** Similarly, for ON INSERT triggers the values stored in the OLD.* registers
1362 ** are never accessed, and so are not allocated by the caller. So, for an
1363 ** ON INSERT trigger, the value passed to this function as parameter reg
1364 ** is not a readable register, although registers (reg+N) through
1367 ** Parameter orconf is the default conflict resolution algorithm for the
1368 ** trigger program to use (REPLACE, IGNORE etc.). Parameter ignoreJump
1369 ** is the instruction that control should jump to if a trigger program
1370 ** raises an IGNORE exception.
1372 void sqlite3CodeRowTrigger(
1373 Parse
*pParse
, /* Parse context */
1374 Trigger
*pTrigger
, /* List of triggers on table pTab */
1375 int op
, /* One of TK_UPDATE, TK_INSERT, TK_DELETE */
1376 ExprList
*pChanges
, /* Changes list for any UPDATE OF triggers */
1377 int tr_tm
, /* One of TRIGGER_BEFORE, TRIGGER_AFTER */
1378 Table
*pTab
, /* The table to code triggers from */
1379 int reg
, /* The first in an array of registers (see above) */
1380 int orconf
, /* ON CONFLICT policy */
1381 int ignoreJump
/* Instruction to jump to for RAISE(IGNORE) */
1383 Trigger
*p
; /* Used to iterate through pTrigger list */
1385 assert( op
==TK_UPDATE
|| op
==TK_INSERT
|| op
==TK_DELETE
);
1386 assert( tr_tm
==TRIGGER_BEFORE
|| tr_tm
==TRIGGER_AFTER
);
1387 assert( (op
==TK_UPDATE
)==(pChanges
!=0) );
1389 for(p
=pTrigger
; p
; p
=p
->pNext
){
1391 /* Sanity checking: The schema for the trigger and for the table are
1392 ** always defined. The trigger must be in the same schema as the table
1393 ** or else it must be a TEMP trigger. */
1394 assert( p
->pSchema
!=0 );
1395 assert( p
->pTabSchema
!=0 );
1396 assert( p
->pSchema
==p
->pTabSchema
1397 || p
->pSchema
==pParse
->db
->aDb
[1].pSchema
);
1399 /* Determine whether we should code this trigger. One of two choices:
1400 ** 1. The trigger is an exact match to the current DML statement
1401 ** 2. This is a RETURNING trigger for INSERT but we are currently
1402 ** doing the UPDATE part of an UPSERT.
1404 if( (p
->op
==op
|| (p
->bReturning
&& p
->op
==TK_INSERT
&& op
==TK_UPDATE
))
1406 && checkColumnOverlap(p
->pColumns
, pChanges
)
1408 if( !p
->bReturning
){
1409 sqlite3CodeRowTriggerDirect(pParse
, p
, pTab
, reg
, orconf
, ignoreJump
);
1410 }else if( sqlite3IsToplevel(pParse
) ){
1411 codeReturningTrigger(pParse
, p
, pTab
, reg
);
1418 ** Triggers may access values stored in the old.* or new.* pseudo-table.
1419 ** This function returns a 32-bit bitmask indicating which columns of the
1420 ** old.* or new.* tables actually are used by triggers. This information
1421 ** may be used by the caller, for example, to avoid having to load the entire
1422 ** old.* record into memory when executing an UPDATE or DELETE command.
1424 ** Bit 0 of the returned mask is set if the left-most column of the
1425 ** table may be accessed using an [old|new].<col> reference. Bit 1 is set if
1426 ** the second leftmost column value is required, and so on. If there
1427 ** are more than 32 columns in the table, and at least one of the columns
1428 ** with an index greater than 32 may be accessed, 0xffffffff is returned.
1430 ** It is not possible to determine if the old.rowid or new.rowid column is
1431 ** accessed by triggers. The caller must always assume that it is.
1433 ** Parameter isNew must be either 1 or 0. If it is 0, then the mask returned
1434 ** applies to the old.* table. If 1, the new.* table.
1436 ** Parameter tr_tm must be a mask with one or both of the TRIGGER_BEFORE
1437 ** and TRIGGER_AFTER bits set. Values accessed by BEFORE triggers are only
1438 ** included in the returned mask if the TRIGGER_BEFORE bit is set in the
1439 ** tr_tm parameter. Similarly, values accessed by AFTER triggers are only
1440 ** included in the returned mask if the TRIGGER_AFTER bit is set in tr_tm.
1442 u32
sqlite3TriggerColmask(
1443 Parse
*pParse
, /* Parse context */
1444 Trigger
*pTrigger
, /* List of triggers on table pTab */
1445 ExprList
*pChanges
, /* Changes list for any UPDATE OF triggers */
1446 int isNew
, /* 1 for new.* ref mask, 0 for old.* ref mask */
1447 int tr_tm
, /* Mask of TRIGGER_BEFORE|TRIGGER_AFTER */
1448 Table
*pTab
, /* The table to code triggers from */
1449 int orconf
/* Default ON CONFLICT policy for trigger steps */
1451 const int op
= pChanges
? TK_UPDATE
: TK_DELETE
;
1455 assert( isNew
==1 || isNew
==0 );
1459 for(p
=pTrigger
; p
; p
=p
->pNext
){
1462 && checkColumnOverlap(p
->pColumns
,pChanges
)
1464 if( p
->bReturning
){
1468 pPrg
= getRowTrigger(pParse
, p
, pTab
, orconf
);
1470 mask
|= pPrg
->aColmask
[isNew
];
1479 #endif /* !defined(SQLITE_OMIT_TRIGGER) */