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 if( pParse
->disableTriggers
){
58 pTmpSchema
= pParse
->db
->aDb
[1].pSchema
;
59 p
= sqliteHashFirst(&pTmpSchema
->trigHash
);
60 pList
= pTab
->pTrigger
;
62 Trigger
*pTrig
= (Trigger
*)sqliteHashData(p
);
63 if( pTrig
->pTabSchema
==pTab
->pSchema
65 && 0==sqlite3StrICmp(pTrig
->table
, pTab
->zName
)
66 && pTrig
->pTabSchema
!=pTmpSchema
70 }else if( pTrig
->op
==TK_RETURNING
71 #ifndef SQLITE_OMIT_VIRTUALTABLE
72 && pParse
->db
->pVtabCtx
==0
75 assert( pParse
->bReturning
);
76 assert( &(pParse
->u1
.pReturning
->retTrig
) == pTrig
);
77 pTrig
->table
= pTab
->zName
;
78 pTrig
->pTabSchema
= pTab
->pSchema
;
82 p
= sqliteHashNext(p
);
87 printf("Triggers for %s:", pTab
->zName
);
88 for(pX
=pList
; pX
; pX
=pX
->pNext
){
89 printf(" %s", pX
->zName
);
99 ** This is called by the parser when it sees a CREATE TRIGGER statement
100 ** up to the point of the BEGIN before the trigger actions. A Trigger
101 ** structure is generated based on the information available and stored
102 ** in pParse->pNewTrigger. After the trigger actions have been parsed, the
103 ** sqlite3FinishTrigger() function is called to complete the trigger
104 ** construction process.
106 void sqlite3BeginTrigger(
107 Parse
*pParse
, /* The parse context of the CREATE TRIGGER statement */
108 Token
*pName1
, /* The name of the trigger */
109 Token
*pName2
, /* The name of the trigger */
110 int tr_tm
, /* One of TK_BEFORE, TK_AFTER, TK_INSTEAD */
111 int op
, /* One of TK_INSERT, TK_UPDATE, TK_DELETE */
112 IdList
*pColumns
, /* column list if this is an UPDATE OF trigger */
113 SrcList
*pTableName
,/* The name of the table/view the trigger applies to */
114 Expr
*pWhen
, /* WHEN clause */
115 int isTemp
, /* True if the TEMPORARY keyword is present */
116 int noErr
/* Suppress errors if the trigger already exists */
118 Trigger
*pTrigger
= 0; /* The new trigger */
119 Table
*pTab
; /* Table that the trigger fires off of */
120 char *zName
= 0; /* Name of the trigger */
121 sqlite3
*db
= pParse
->db
; /* The database connection */
122 int iDb
; /* The database to store the trigger in */
123 Token
*pName
; /* The unqualified db name */
124 DbFixer sFix
; /* State vector for the DB fixer */
126 assert( pName1
!=0 ); /* pName1->z might be NULL, but not pName1 itself */
128 assert( op
==TK_INSERT
|| op
==TK_UPDATE
|| op
==TK_DELETE
);
129 assert( op
>0 && op
<0xff );
131 /* If TEMP was specified, then the trigger name may not be qualified. */
133 sqlite3ErrorMsg(pParse
, "temporary trigger may not have qualified name");
134 goto trigger_cleanup
;
139 /* Figure out the db that the trigger will be created in */
140 iDb
= sqlite3TwoPartName(pParse
, pName1
, pName2
, &pName
);
142 goto trigger_cleanup
;
145 if( !pTableName
|| db
->mallocFailed
){
146 goto trigger_cleanup
;
149 /* A long-standing parser bug is that this syntax was allowed:
151 ** CREATE TRIGGER attached.demo AFTER INSERT ON attached.tab ....
154 ** To maintain backwards compatibility, ignore the database
155 ** name on pTableName if we are reparsing out of the schema table
157 if( db
->init
.busy
&& iDb
!=1 ){
158 sqlite3DbFree(db
, pTableName
->a
[0].zDatabase
);
159 pTableName
->a
[0].zDatabase
= 0;
162 /* If the trigger name was unqualified, and the table is a temp table,
163 ** then set iDb to 1 to create the trigger in the temporary database.
164 ** If sqlite3SrcListLookup() returns 0, indicating the table does not
165 ** exist, the error is caught by the block below.
167 pTab
= sqlite3SrcListLookup(pParse
, pTableName
);
168 if( db
->init
.busy
==0 && pName2
->n
==0 && pTab
169 && pTab
->pSchema
==db
->aDb
[1].pSchema
){
173 /* Ensure the table name matches database name and that the table exists */
174 if( db
->mallocFailed
) goto trigger_cleanup
;
175 assert( pTableName
->nSrc
==1 );
176 sqlite3FixInit(&sFix
, pParse
, iDb
, "trigger", pName
);
177 if( sqlite3FixSrcList(&sFix
, pTableName
) ){
178 goto trigger_cleanup
;
180 pTab
= sqlite3SrcListLookup(pParse
, pTableName
);
182 /* The table does not exist. */
183 goto trigger_orphan_error
;
185 if( IsVirtual(pTab
) ){
186 sqlite3ErrorMsg(pParse
, "cannot create triggers on virtual tables");
187 goto trigger_orphan_error
;
190 /* Check that the trigger name is not reserved and that no trigger of the
191 ** specified name exists */
192 zName
= sqlite3NameFromToken(db
, pName
);
194 assert( db
->mallocFailed
);
195 goto trigger_cleanup
;
197 if( sqlite3CheckObjectName(pParse
, zName
, "trigger", pTab
->zName
) ){
198 goto trigger_cleanup
;
200 assert( sqlite3SchemaMutexHeld(db
, iDb
, 0) );
201 if( !IN_RENAME_OBJECT
){
202 if( sqlite3HashFind(&(db
->aDb
[iDb
].pSchema
->trigHash
),zName
) ){
204 sqlite3ErrorMsg(pParse
, "trigger %T already exists", pName
);
206 assert( !db
->init
.busy
);
207 sqlite3CodeVerifySchema(pParse
, iDb
);
209 goto trigger_cleanup
;
213 /* Do not create a trigger on a system table */
214 if( sqlite3StrNICmp(pTab
->zName
, "sqlite_", 7)==0 ){
215 sqlite3ErrorMsg(pParse
, "cannot create trigger on system table");
216 goto trigger_cleanup
;
219 /* INSTEAD of triggers are only for views and views only support INSTEAD
222 if( IsView(pTab
) && tr_tm
!=TK_INSTEAD
){
223 sqlite3ErrorMsg(pParse
, "cannot create %s trigger on view: %S",
224 (tr_tm
== TK_BEFORE
)?"BEFORE":"AFTER", pTableName
->a
);
225 goto trigger_orphan_error
;
227 if( !IsView(pTab
) && tr_tm
==TK_INSTEAD
){
228 sqlite3ErrorMsg(pParse
, "cannot create INSTEAD OF"
229 " trigger on table: %S", pTableName
->a
);
230 goto trigger_orphan_error
;
233 #ifndef SQLITE_OMIT_AUTHORIZATION
234 if( !IN_RENAME_OBJECT
){
235 int iTabDb
= sqlite3SchemaToIndex(db
, pTab
->pSchema
);
236 int code
= SQLITE_CREATE_TRIGGER
;
237 const char *zDb
= db
->aDb
[iTabDb
].zDbSName
;
238 const char *zDbTrig
= isTemp
? db
->aDb
[1].zDbSName
: zDb
;
239 if( iTabDb
==1 || isTemp
) code
= SQLITE_CREATE_TEMP_TRIGGER
;
240 if( sqlite3AuthCheck(pParse
, code
, zName
, pTab
->zName
, zDbTrig
) ){
241 goto trigger_cleanup
;
243 if( sqlite3AuthCheck(pParse
, SQLITE_INSERT
, SCHEMA_TABLE(iTabDb
),0,zDb
)){
244 goto trigger_cleanup
;
249 /* INSTEAD OF triggers can only appear on views and BEFORE triggers
250 ** cannot appear on views. So we might as well translate every
251 ** INSTEAD OF trigger into a BEFORE trigger. It simplifies code
254 if (tr_tm
== TK_INSTEAD
){
258 /* Build the Trigger object */
259 pTrigger
= (Trigger
*)sqlite3DbMallocZero(db
, sizeof(Trigger
));
260 if( pTrigger
==0 ) goto trigger_cleanup
;
261 pTrigger
->zName
= zName
;
263 pTrigger
->table
= sqlite3DbStrDup(db
, pTableName
->a
[0].zName
);
264 pTrigger
->pSchema
= db
->aDb
[iDb
].pSchema
;
265 pTrigger
->pTabSchema
= pTab
->pSchema
;
266 pTrigger
->op
= (u8
)op
;
267 pTrigger
->tr_tm
= tr_tm
==TK_BEFORE
? TRIGGER_BEFORE
: TRIGGER_AFTER
;
268 if( IN_RENAME_OBJECT
){
269 sqlite3RenameTokenRemap(pParse
, pTrigger
->table
, pTableName
->a
[0].zName
);
270 pTrigger
->pWhen
= pWhen
;
273 pTrigger
->pWhen
= sqlite3ExprDup(db
, pWhen
, EXPRDUP_REDUCE
);
275 pTrigger
->pColumns
= pColumns
;
277 assert( pParse
->pNewTrigger
==0 );
278 pParse
->pNewTrigger
= pTrigger
;
281 sqlite3DbFree(db
, zName
);
282 sqlite3SrcListDelete(db
, pTableName
);
283 sqlite3IdListDelete(db
, pColumns
);
284 sqlite3ExprDelete(db
, pWhen
);
285 if( !pParse
->pNewTrigger
){
286 sqlite3DeleteTrigger(db
, pTrigger
);
288 assert( pParse
->pNewTrigger
==pTrigger
);
292 trigger_orphan_error
:
293 if( db
->init
.iDb
==1 ){
295 ** Normally, whenever a table is dropped, all associated triggers are
296 ** dropped too. But if a TEMP trigger is created on a non-TEMP table
297 ** and the table is dropped by a different database connection, the
298 ** trigger is not visible to the database connection that does the
299 ** drop so the trigger cannot be dropped. This results in an
300 ** "orphaned trigger" - a trigger whose associated table is missing.
302 ** 2020-11-05 see also https://sqlite.org/forum/forumpost/157dc791df
304 db
->init
.orphanTrigger
= 1;
306 goto trigger_cleanup
;
310 ** This routine is called after all of the trigger actions have been parsed
311 ** in order to complete the process of building the trigger.
313 void sqlite3FinishTrigger(
314 Parse
*pParse
, /* Parser context */
315 TriggerStep
*pStepList
, /* The triggered program */
316 Token
*pAll
/* Token that describes the complete CREATE TRIGGER */
318 Trigger
*pTrig
= pParse
->pNewTrigger
; /* Trigger being finished */
319 char *zName
; /* Name of trigger */
320 sqlite3
*db
= pParse
->db
; /* The database */
321 DbFixer sFix
; /* Fixer object */
322 int iDb
; /* Database containing the trigger */
323 Token nameToken
; /* Trigger name for error reporting */
325 pParse
->pNewTrigger
= 0;
326 if( NEVER(pParse
->nErr
) || !pTrig
) goto triggerfinish_cleanup
;
327 zName
= pTrig
->zName
;
328 iDb
= sqlite3SchemaToIndex(pParse
->db
, pTrig
->pSchema
);
329 pTrig
->step_list
= pStepList
;
331 pStepList
->pTrig
= pTrig
;
332 pStepList
= pStepList
->pNext
;
334 sqlite3TokenInit(&nameToken
, pTrig
->zName
);
335 sqlite3FixInit(&sFix
, pParse
, iDb
, "trigger", &nameToken
);
336 if( sqlite3FixTriggerStep(&sFix
, pTrig
->step_list
)
337 || sqlite3FixExpr(&sFix
, pTrig
->pWhen
)
339 goto triggerfinish_cleanup
;
342 #ifndef SQLITE_OMIT_ALTERTABLE
343 if( IN_RENAME_OBJECT
){
344 assert( !db
->init
.busy
);
345 pParse
->pNewTrigger
= pTrig
;
350 /* if we are not initializing,
351 ** build the sqlite_schema entry
353 if( !db
->init
.busy
){
357 /* Make an entry in the sqlite_schema table */
358 v
= sqlite3GetVdbe(pParse
);
359 if( v
==0 ) goto triggerfinish_cleanup
;
360 sqlite3BeginWriteOperation(pParse
, 0, iDb
);
361 z
= sqlite3DbStrNDup(db
, (char*)pAll
->z
, pAll
->n
);
363 sqlite3NestedParse(pParse
,
364 "INSERT INTO %Q." LEGACY_SCHEMA_TABLE
365 " VALUES('trigger',%Q,%Q,0,'CREATE TRIGGER %q')",
366 db
->aDb
[iDb
].zDbSName
, zName
,
368 sqlite3DbFree(db
, z
);
369 sqlite3ChangeCookie(pParse
, iDb
);
370 sqlite3VdbeAddParseSchemaOp(v
, iDb
,
371 sqlite3MPrintf(db
, "type='trigger' AND name='%q'", zName
), 0);
375 Trigger
*pLink
= pTrig
;
376 Hash
*pHash
= &db
->aDb
[iDb
].pSchema
->trigHash
;
377 assert( sqlite3SchemaMutexHeld(db
, iDb
, 0) );
379 pTrig
= sqlite3HashInsert(pHash
, zName
, pTrig
);
382 }else if( pLink
->pSchema
==pLink
->pTabSchema
){
384 pTab
= sqlite3HashFind(&pLink
->pTabSchema
->tblHash
, pLink
->table
);
386 pLink
->pNext
= pTab
->pTrigger
;
387 pTab
->pTrigger
= pLink
;
391 triggerfinish_cleanup
:
392 sqlite3DeleteTrigger(db
, pTrig
);
393 assert( IN_RENAME_OBJECT
|| !pParse
->pNewTrigger
);
394 sqlite3DeleteTriggerStep(db
, pStepList
);
398 ** Duplicate a range of text from an SQL statement, then convert all
399 ** whitespace characters into ordinary space characters.
401 static char *triggerSpanDup(sqlite3
*db
, const char *zStart
, const char *zEnd
){
402 char *z
= sqlite3DbSpanDup(db
, zStart
, zEnd
);
404 if( z
) for(i
=0; z
[i
]; i
++) if( sqlite3Isspace(z
[i
]) ) z
[i
] = ' ';
409 ** Turn a SELECT statement (that the pSelect parameter points to) into
410 ** a trigger step. Return a pointer to a TriggerStep structure.
412 ** The parser calls this routine when it finds a SELECT statement in
413 ** body of a TRIGGER.
415 TriggerStep
*sqlite3TriggerSelectStep(
416 sqlite3
*db
, /* Database connection */
417 Select
*pSelect
, /* The SELECT statement */
418 const char *zStart
, /* Start of SQL text */
419 const char *zEnd
/* End of SQL text */
421 TriggerStep
*pTriggerStep
= sqlite3DbMallocZero(db
, sizeof(TriggerStep
));
422 if( pTriggerStep
==0 ) {
423 sqlite3SelectDelete(db
, pSelect
);
426 pTriggerStep
->op
= TK_SELECT
;
427 pTriggerStep
->pSelect
= pSelect
;
428 pTriggerStep
->orconf
= OE_Default
;
429 pTriggerStep
->zSpan
= triggerSpanDup(db
, zStart
, zEnd
);
434 ** Allocate space to hold a new trigger step. The allocated space
435 ** holds both the TriggerStep object and the TriggerStep.target.z string.
437 ** If an OOM error occurs, NULL is returned and db->mallocFailed is set.
439 static TriggerStep
*triggerStepAllocate(
440 Parse
*pParse
, /* Parser context */
441 u8 op
, /* Trigger opcode */
442 Token
*pName
, /* The target name */
443 const char *zStart
, /* Start of SQL text */
444 const char *zEnd
/* End of SQL text */
446 sqlite3
*db
= pParse
->db
;
447 TriggerStep
*pTriggerStep
;
449 if( pParse
->nErr
) return 0;
450 pTriggerStep
= sqlite3DbMallocZero(db
, sizeof(TriggerStep
) + pName
->n
+ 1);
452 char *z
= (char*)&pTriggerStep
[1];
453 memcpy(z
, pName
->z
, pName
->n
);
455 pTriggerStep
->zTarget
= z
;
456 pTriggerStep
->op
= op
;
457 pTriggerStep
->zSpan
= triggerSpanDup(db
, zStart
, zEnd
);
458 if( IN_RENAME_OBJECT
){
459 sqlite3RenameTokenMap(pParse
, pTriggerStep
->zTarget
, pName
);
466 ** Build a trigger step out of an INSERT statement. Return a pointer
467 ** to the new trigger step.
469 ** The parser calls this routine when it sees an INSERT inside the
470 ** body of a trigger.
472 TriggerStep
*sqlite3TriggerInsertStep(
473 Parse
*pParse
, /* Parser */
474 Token
*pTableName
, /* Name of the table into which we insert */
475 IdList
*pColumn
, /* List of columns in pTableName to insert into */
476 Select
*pSelect
, /* A SELECT statement that supplies values */
477 u8 orconf
, /* The conflict algorithm (OE_Abort, OE_Replace, etc.) */
478 Upsert
*pUpsert
, /* ON CONFLICT clauses for upsert */
479 const char *zStart
, /* Start of SQL text */
480 const char *zEnd
/* End of SQL text */
482 sqlite3
*db
= pParse
->db
;
483 TriggerStep
*pTriggerStep
;
485 assert(pSelect
!= 0 || db
->mallocFailed
);
487 pTriggerStep
= triggerStepAllocate(pParse
, TK_INSERT
, pTableName
,zStart
,zEnd
);
489 if( IN_RENAME_OBJECT
){
490 pTriggerStep
->pSelect
= pSelect
;
493 pTriggerStep
->pSelect
= sqlite3SelectDup(db
, pSelect
, EXPRDUP_REDUCE
);
495 pTriggerStep
->pIdList
= pColumn
;
496 pTriggerStep
->pUpsert
= pUpsert
;
497 pTriggerStep
->orconf
= orconf
;
499 sqlite3HasExplicitNulls(pParse
, pUpsert
->pUpsertTarget
);
503 sqlite3IdListDelete(db
, pColumn
);
505 sqlite3UpsertDelete(db
, pUpsert
);
507 sqlite3SelectDelete(db
, pSelect
);
513 ** Construct a trigger step that implements an UPDATE statement and return
514 ** a pointer to that trigger step. The parser calls this routine when it
515 ** sees an UPDATE statement inside the body of a CREATE TRIGGER.
517 TriggerStep
*sqlite3TriggerUpdateStep(
518 Parse
*pParse
, /* Parser */
519 Token
*pTableName
, /* Name of the table to be updated */
521 ExprList
*pEList
, /* The SET clause: list of column and new values */
522 Expr
*pWhere
, /* The WHERE clause */
523 u8 orconf
, /* The conflict algorithm. (OE_Abort, OE_Ignore, etc) */
524 const char *zStart
, /* Start of SQL text */
525 const char *zEnd
/* End of SQL text */
527 sqlite3
*db
= pParse
->db
;
528 TriggerStep
*pTriggerStep
;
530 pTriggerStep
= triggerStepAllocate(pParse
, TK_UPDATE
, pTableName
,zStart
,zEnd
);
532 if( IN_RENAME_OBJECT
){
533 pTriggerStep
->pExprList
= pEList
;
534 pTriggerStep
->pWhere
= pWhere
;
535 pTriggerStep
->pFrom
= pFrom
;
540 pTriggerStep
->pExprList
= sqlite3ExprListDup(db
, pEList
, EXPRDUP_REDUCE
);
541 pTriggerStep
->pWhere
= sqlite3ExprDup(db
, pWhere
, EXPRDUP_REDUCE
);
542 pTriggerStep
->pFrom
= sqlite3SrcListDup(db
, pFrom
, EXPRDUP_REDUCE
);
544 pTriggerStep
->orconf
= orconf
;
546 sqlite3ExprListDelete(db
, pEList
);
547 sqlite3ExprDelete(db
, pWhere
);
548 sqlite3SrcListDelete(db
, pFrom
);
553 ** Construct a trigger step that implements a DELETE statement and return
554 ** a pointer to that trigger step. The parser calls this routine when it
555 ** sees a DELETE statement inside the body of a CREATE TRIGGER.
557 TriggerStep
*sqlite3TriggerDeleteStep(
558 Parse
*pParse
, /* Parser */
559 Token
*pTableName
, /* The table from which rows are deleted */
560 Expr
*pWhere
, /* The WHERE clause */
561 const char *zStart
, /* Start of SQL text */
562 const char *zEnd
/* End of SQL text */
564 sqlite3
*db
= pParse
->db
;
565 TriggerStep
*pTriggerStep
;
567 pTriggerStep
= triggerStepAllocate(pParse
, TK_DELETE
, pTableName
,zStart
,zEnd
);
569 if( IN_RENAME_OBJECT
){
570 pTriggerStep
->pWhere
= pWhere
;
573 pTriggerStep
->pWhere
= sqlite3ExprDup(db
, pWhere
, EXPRDUP_REDUCE
);
575 pTriggerStep
->orconf
= OE_Default
;
577 sqlite3ExprDelete(db
, pWhere
);
582 ** Recursively delete a Trigger structure
584 void sqlite3DeleteTrigger(sqlite3
*db
, Trigger
*pTrigger
){
585 if( pTrigger
==0 || pTrigger
->bReturning
) return;
586 sqlite3DeleteTriggerStep(db
, pTrigger
->step_list
);
587 sqlite3DbFree(db
, pTrigger
->zName
);
588 sqlite3DbFree(db
, pTrigger
->table
);
589 sqlite3ExprDelete(db
, pTrigger
->pWhen
);
590 sqlite3IdListDelete(db
, pTrigger
->pColumns
);
591 sqlite3DbFree(db
, pTrigger
);
595 ** This function is called to drop a trigger from the database schema.
597 ** This may be called directly from the parser and therefore identifies
598 ** the trigger by name. The sqlite3DropTriggerPtr() routine does the
599 ** same job as this routine except it takes a pointer to the trigger
600 ** instead of the trigger name.
602 void sqlite3DropTrigger(Parse
*pParse
, SrcList
*pName
, int noErr
){
603 Trigger
*pTrigger
= 0;
607 sqlite3
*db
= pParse
->db
;
609 if( db
->mallocFailed
) goto drop_trigger_cleanup
;
610 if( SQLITE_OK
!=sqlite3ReadSchema(pParse
) ){
611 goto drop_trigger_cleanup
;
614 assert( pName
->nSrc
==1 );
615 zDb
= pName
->a
[0].zDatabase
;
616 zName
= pName
->a
[0].zName
;
617 assert( zDb
!=0 || sqlite3BtreeHoldsAllMutexes(db
) );
618 for(i
=OMIT_TEMPDB
; i
<db
->nDb
; i
++){
619 int j
= (i
<2) ? i
^1 : i
; /* Search TEMP before MAIN */
620 if( zDb
&& sqlite3DbIsNamed(db
, j
, zDb
)==0 ) continue;
621 assert( sqlite3SchemaMutexHeld(db
, j
, 0) );
622 pTrigger
= sqlite3HashFind(&(db
->aDb
[j
].pSchema
->trigHash
), zName
);
623 if( pTrigger
) break;
627 sqlite3ErrorMsg(pParse
, "no such trigger: %S", pName
->a
);
629 sqlite3CodeVerifyNamedSchema(pParse
, zDb
);
631 pParse
->checkSchema
= 1;
632 goto drop_trigger_cleanup
;
634 sqlite3DropTriggerPtr(pParse
, pTrigger
);
636 drop_trigger_cleanup
:
637 sqlite3SrcListDelete(db
, pName
);
641 ** Return a pointer to the Table structure for the table that a trigger
644 static Table
*tableOfTrigger(Trigger
*pTrigger
){
645 return sqlite3HashFind(&pTrigger
->pTabSchema
->tblHash
, pTrigger
->table
);
650 ** Drop a trigger given a pointer to that trigger.
652 void sqlite3DropTriggerPtr(Parse
*pParse
, Trigger
*pTrigger
){
655 sqlite3
*db
= pParse
->db
;
658 iDb
= sqlite3SchemaToIndex(pParse
->db
, pTrigger
->pSchema
);
659 assert( iDb
>=0 && iDb
<db
->nDb
);
660 pTable
= tableOfTrigger(pTrigger
);
661 assert( (pTable
&& pTable
->pSchema
==pTrigger
->pSchema
) || iDb
==1 );
662 #ifndef SQLITE_OMIT_AUTHORIZATION
664 int code
= SQLITE_DROP_TRIGGER
;
665 const char *zDb
= db
->aDb
[iDb
].zDbSName
;
666 const char *zTab
= SCHEMA_TABLE(iDb
);
667 if( iDb
==1 ) code
= SQLITE_DROP_TEMP_TRIGGER
;
668 if( sqlite3AuthCheck(pParse
, code
, pTrigger
->zName
, pTable
->zName
, zDb
) ||
669 sqlite3AuthCheck(pParse
, SQLITE_DELETE
, zTab
, 0, zDb
) ){
675 /* Generate code to destroy the database record of the trigger.
677 if( (v
= sqlite3GetVdbe(pParse
))!=0 ){
678 sqlite3NestedParse(pParse
,
679 "DELETE FROM %Q." LEGACY_SCHEMA_TABLE
" WHERE name=%Q AND type='trigger'",
680 db
->aDb
[iDb
].zDbSName
, pTrigger
->zName
682 sqlite3ChangeCookie(pParse
, iDb
);
683 sqlite3VdbeAddOp4(v
, OP_DropTrigger
, iDb
, 0, 0, pTrigger
->zName
, 0);
688 ** Remove a trigger from the hash tables of the sqlite* pointer.
690 void sqlite3UnlinkAndDeleteTrigger(sqlite3
*db
, int iDb
, const char *zName
){
694 assert( sqlite3SchemaMutexHeld(db
, iDb
, 0) );
695 pHash
= &(db
->aDb
[iDb
].pSchema
->trigHash
);
696 pTrigger
= sqlite3HashInsert(pHash
, zName
, 0);
697 if( ALWAYS(pTrigger
) ){
698 if( pTrigger
->pSchema
==pTrigger
->pTabSchema
){
699 Table
*pTab
= tableOfTrigger(pTrigger
);
702 for(pp
=&pTab
->pTrigger
; *pp
; pp
=&((*pp
)->pNext
)){
710 sqlite3DeleteTrigger(db
, pTrigger
);
711 db
->mDbFlags
|= DBFLAG_SchemaChange
;
716 ** pEList is the SET clause of an UPDATE statement. Each entry
717 ** in pEList is of the format <id>=<expr>. If any of the entries
718 ** in pEList have an <id> which matches an identifier in pIdList,
719 ** then return TRUE. If pIdList==NULL, then it is considered a
720 ** wildcard that matches anything. Likewise if pEList==NULL then
721 ** it matches anything so always return true. Return false only
722 ** if there is no match.
724 static int checkColumnOverlap(IdList
*pIdList
, ExprList
*pEList
){
726 if( pIdList
==0 || NEVER(pEList
==0) ) return 1;
727 for(e
=0; e
<pEList
->nExpr
; e
++){
728 if( sqlite3IdListIndex(pIdList
, pEList
->a
[e
].zEName
)>=0 ) return 1;
734 ** Return a list of all triggers on table pTab if there exists at least
735 ** one trigger that must be fired when an operation of type 'op' is
736 ** performed on the table, and, if that operation is an UPDATE, if at
737 ** least one of the columns in pChanges is being modified.
739 Trigger
*sqlite3TriggersExist(
740 Parse
*pParse
, /* Parse context */
741 Table
*pTab
, /* The table the contains the triggers */
742 int op
, /* one of TK_DELETE, TK_INSERT, TK_UPDATE */
743 ExprList
*pChanges
, /* Columns that change in an UPDATE statement */
744 int *pMask
/* OUT: Mask of TRIGGER_BEFORE|TRIGGER_AFTER */
750 pList
= sqlite3TriggerList(pParse
, pTab
);
751 assert( pList
==0 || IsVirtual(pTab
)==0
752 || (pList
->bReturning
&& pList
->pNext
==0) );
755 if( (pParse
->db
->flags
& SQLITE_EnableTrigger
)==0
758 /* The SQLITE_DBCONFIG_ENABLE_TRIGGER setting is off. That means that
759 ** only TEMP triggers are allowed. Truncate the pList so that it
760 ** includes only TEMP triggers */
761 if( pList
==pTab
->pTrigger
){
763 goto exit_triggers_exist
;
765 while( ALWAYS(p
->pNext
) && p
->pNext
!=pTab
->pTrigger
) p
= p
->pNext
;
770 if( p
->op
==op
&& checkColumnOverlap(p
->pColumns
, pChanges
) ){
772 }else if( p
->op
==TK_RETURNING
){
773 /* The first time a RETURNING trigger is seen, the "op" value tells
774 ** us what time of trigger it should be. */
775 assert( sqlite3IsToplevel(pParse
) );
777 if( IsVirtual(pTab
) ){
779 sqlite3ErrorMsg(pParse
,
780 "%s RETURNING is not available on virtual tables",
781 op
==TK_DELETE
? "DELETE" : "UPDATE");
783 p
->tr_tm
= TRIGGER_BEFORE
;
785 p
->tr_tm
= TRIGGER_AFTER
;
788 }else if( p
->bReturning
&& p
->op
==TK_INSERT
&& op
==TK_UPDATE
789 && sqlite3IsToplevel(pParse
) ){
790 /* Also fire a RETURNING trigger for an UPSERT */
800 return (mask
? pList
: 0);
804 ** Convert the pStep->zTarget string into a SrcList and return a pointer
807 ** This routine adds a specific database name, if needed, to the target when
808 ** forming the SrcList. This prevents a trigger in one database from
809 ** referring to a target in another database. An exception is when the
810 ** trigger is in TEMP in which case it can refer to any other database it
813 SrcList
*sqlite3TriggerStepSrc(
814 Parse
*pParse
, /* The parsing context */
815 TriggerStep
*pStep
/* The trigger containing the target token */
817 sqlite3
*db
= pParse
->db
;
818 SrcList
*pSrc
; /* SrcList to be returned */
819 char *zName
= sqlite3DbStrDup(db
, pStep
->zTarget
);
820 pSrc
= sqlite3SrcListAppend(pParse
, 0, 0, 0);
821 assert( pSrc
==0 || pSrc
->nSrc
==1 );
822 assert( zName
|| pSrc
==0 );
824 Schema
*pSchema
= pStep
->pTrig
->pSchema
;
825 pSrc
->a
[0].zName
= zName
;
826 if( pSchema
!=db
->aDb
[1].pSchema
){
827 pSrc
->a
[0].pSchema
= pSchema
;
830 SrcList
*pDup
= sqlite3SrcListDup(db
, pStep
->pFrom
, 0);
831 pSrc
= sqlite3SrcListAppendList(pParse
, pSrc
, pDup
);
834 sqlite3DbFree(db
, zName
);
840 ** Return true if the pExpr term from the RETURNING clause argument
841 ** list is of the form "*". Raise an error if the terms if of the
844 static int isAsteriskTerm(
845 Parse
*pParse
, /* Parsing context */
846 Expr
*pTerm
/* A term in the RETURNING clause */
849 if( pTerm
->op
==TK_ASTERISK
) return 1;
850 if( pTerm
->op
!=TK_DOT
) return 0;
851 assert( pTerm
->pRight
!=0 );
852 assert( pTerm
->pLeft
!=0 );
853 if( pTerm
->pRight
->op
!=TK_ASTERISK
) return 0;
854 sqlite3ErrorMsg(pParse
, "RETURNING may not use \"TABLE.*\" wildcards");
858 /* The input list pList is the list of result set terms from a RETURNING
859 ** clause. The table that we are returning from is pTab.
861 ** This routine makes a copy of the pList, and at the same time expands
862 ** any "*" wildcards to be the complete set of columns from pTab.
864 static ExprList
*sqlite3ExpandReturning(
865 Parse
*pParse
, /* Parsing context */
866 ExprList
*pList
, /* The arguments to RETURNING */
867 Table
*pTab
/* The table being updated */
870 sqlite3
*db
= pParse
->db
;
873 for(i
=0; i
<pList
->nExpr
; i
++){
874 Expr
*pOldExpr
= pList
->a
[i
].pExpr
;
875 if( NEVER(pOldExpr
==0) ) continue;
876 if( isAsteriskTerm(pParse
, pOldExpr
) ){
878 for(jj
=0; jj
<pTab
->nCol
; jj
++){
880 if( IsHiddenColumn(pTab
->aCol
+jj
) ) continue;
881 pNewExpr
= sqlite3Expr(db
, TK_ID
, pTab
->aCol
[jj
].zCnName
);
882 pNew
= sqlite3ExprListAppend(pParse
, pNew
, pNewExpr
);
883 if( !db
->mallocFailed
){
884 struct ExprList_item
*pItem
= &pNew
->a
[pNew
->nExpr
-1];
885 pItem
->zEName
= sqlite3DbStrDup(db
, pTab
->aCol
[jj
].zCnName
);
886 pItem
->eEName
= ENAME_NAME
;
890 Expr
*pNewExpr
= sqlite3ExprDup(db
, pOldExpr
, 0);
891 pNew
= sqlite3ExprListAppend(pParse
, pNew
, pNewExpr
);
892 if( !db
->mallocFailed
&& ALWAYS(pList
->a
[i
].zEName
!=0) ){
893 struct ExprList_item
*pItem
= &pNew
->a
[pNew
->nExpr
-1];
894 pItem
->zEName
= sqlite3DbStrDup(db
, pList
->a
[i
].zEName
);
895 pItem
->eEName
= pList
->a
[i
].eEName
;
903 ** Generate code for the RETURNING trigger. Unlike other triggers
904 ** that invoke a subprogram in the bytecode, the code for RETURNING
905 ** is generated in-line.
907 static void codeReturningTrigger(
908 Parse
*pParse
, /* Parse context */
909 Trigger
*pTrigger
, /* The trigger step that defines the RETURNING */
910 Table
*pTab
, /* The table to code triggers from */
911 int regIn
/* The first in an array of registers */
913 Vdbe
*v
= pParse
->pVdbe
;
914 sqlite3
*db
= pParse
->db
;
916 Returning
*pReturning
;
921 assert( pParse
->bReturning
);
922 assert( db
->pParse
==pParse
);
923 pReturning
= pParse
->u1
.pReturning
;
924 assert( pTrigger
== &(pReturning
->retTrig
) );
925 memset(&sSelect
, 0, sizeof(sSelect
));
926 memset(&sFrom
, 0, sizeof(sFrom
));
927 sSelect
.pEList
= sqlite3ExprListDup(db
, pReturning
->pReturnEL
, 0);
928 sSelect
.pSrc
= &sFrom
;
930 sFrom
.a
[0].pTab
= pTab
;
931 sFrom
.a
[0].iCursor
= -1;
932 sqlite3SelectPrep(pParse
, &sSelect
, 0);
933 if( pParse
->nErr
==0 ){
934 assert( db
->mallocFailed
==0 );
935 sqlite3GenerateColumnNames(pParse
, &sSelect
);
937 sqlite3ExprListDelete(db
, sSelect
.pEList
);
938 pNew
= sqlite3ExpandReturning(pParse
, pReturning
->pReturnEL
, pTab
);
939 if( !db
->mallocFailed
){
941 memset(&sNC
, 0, sizeof(sNC
));
942 if( pReturning
->nRetCol
==0 ){
943 pReturning
->nRetCol
= pNew
->nExpr
;
944 pReturning
->iRetCur
= pParse
->nTab
++;
947 sNC
.uNC
.iBaseReg
= regIn
;
948 sNC
.ncFlags
= NC_UBaseReg
;
949 pParse
->eTriggerOp
= pTrigger
->op
;
950 pParse
->pTriggerTab
= pTab
;
951 if( sqlite3ResolveExprListNames(&sNC
, pNew
)==SQLITE_OK
952 && ALWAYS(!db
->mallocFailed
)
955 int nCol
= pNew
->nExpr
;
956 int reg
= pParse
->nMem
+1;
957 pParse
->nMem
+= nCol
+2;
958 pReturning
->iRetReg
= reg
;
959 for(i
=0; i
<nCol
; i
++){
960 Expr
*pCol
= pNew
->a
[i
].pExpr
;
961 assert( pCol
!=0 ); /* Due to !db->mallocFailed ~9 lines above */
962 sqlite3ExprCodeFactorable(pParse
, pCol
, reg
+i
);
963 if( sqlite3ExprAffinity(pCol
)==SQLITE_AFF_REAL
){
964 sqlite3VdbeAddOp1(v
, OP_RealAffinity
, reg
+i
);
967 sqlite3VdbeAddOp3(v
, OP_MakeRecord
, reg
, i
, reg
+i
);
968 sqlite3VdbeAddOp2(v
, OP_NewRowid
, pReturning
->iRetCur
, reg
+i
+1);
969 sqlite3VdbeAddOp3(v
, OP_Insert
, pReturning
->iRetCur
, reg
+i
, reg
+i
+1);
972 sqlite3ExprListDelete(db
, pNew
);
973 pParse
->eTriggerOp
= 0;
974 pParse
->pTriggerTab
= 0;
980 ** Generate VDBE code for the statements inside the body of a single
983 static int codeTriggerProgram(
984 Parse
*pParse
, /* The parser context */
985 TriggerStep
*pStepList
, /* List of statements inside the trigger body */
986 int orconf
/* Conflict algorithm. (OE_Abort, etc) */
989 Vdbe
*v
= pParse
->pVdbe
;
990 sqlite3
*db
= pParse
->db
;
992 assert( pParse
->pTriggerTab
&& pParse
->pToplevel
);
995 for(pStep
=pStepList
; pStep
; pStep
=pStep
->pNext
){
996 /* Figure out the ON CONFLICT policy that will be used for this step
997 ** of the trigger program. If the statement that caused this trigger
998 ** to fire had an explicit ON CONFLICT, then use it. Otherwise, use
999 ** the ON CONFLICT policy that was specified as part of the trigger
1000 ** step statement. Example:
1002 ** CREATE TRIGGER AFTER INSERT ON t1 BEGIN;
1003 ** INSERT OR REPLACE INTO t2 VALUES(new.a, new.b);
1006 ** INSERT INTO t1 ... ; -- insert into t2 uses REPLACE policy
1007 ** INSERT OR IGNORE INTO t1 ... ; -- insert into t2 uses IGNORE policy
1009 pParse
->eOrconf
= (orconf
==OE_Default
)?pStep
->orconf
:(u8
)orconf
;
1010 assert( pParse
->okConstFactor
==0 );
1012 #ifndef SQLITE_OMIT_TRACE
1014 sqlite3VdbeAddOp4(v
, OP_Trace
, 0x7fffffff, 1, 0,
1015 sqlite3MPrintf(db
, "-- %s", pStep
->zSpan
),
1020 switch( pStep
->op
){
1022 sqlite3Update(pParse
,
1023 sqlite3TriggerStepSrc(pParse
, pStep
),
1024 sqlite3ExprListDup(db
, pStep
->pExprList
, 0),
1025 sqlite3ExprDup(db
, pStep
->pWhere
, 0),
1026 pParse
->eOrconf
, 0, 0, 0
1028 sqlite3VdbeAddOp0(v
, OP_ResetCount
);
1032 sqlite3Insert(pParse
,
1033 sqlite3TriggerStepSrc(pParse
, pStep
),
1034 sqlite3SelectDup(db
, pStep
->pSelect
, 0),
1035 sqlite3IdListDup(db
, pStep
->pIdList
),
1037 sqlite3UpsertDup(db
, pStep
->pUpsert
)
1039 sqlite3VdbeAddOp0(v
, OP_ResetCount
);
1043 sqlite3DeleteFrom(pParse
,
1044 sqlite3TriggerStepSrc(pParse
, pStep
),
1045 sqlite3ExprDup(db
, pStep
->pWhere
, 0), 0, 0
1047 sqlite3VdbeAddOp0(v
, OP_ResetCount
);
1050 default: assert( pStep
->op
==TK_SELECT
); {
1052 Select
*pSelect
= sqlite3SelectDup(db
, pStep
->pSelect
, 0);
1053 sqlite3SelectDestInit(&sDest
, SRT_Discard
, 0);
1054 sqlite3Select(pParse
, pSelect
, &sDest
);
1055 sqlite3SelectDelete(db
, pSelect
);
1064 #ifdef SQLITE_ENABLE_EXPLAIN_COMMENTS
1066 ** This function is used to add VdbeComment() annotations to a VDBE
1067 ** program. It is not used in production code, only for debugging.
1069 static const char *onErrorText(int onError
){
1071 case OE_Abort
: return "abort";
1072 case OE_Rollback
: return "rollback";
1073 case OE_Fail
: return "fail";
1074 case OE_Replace
: return "replace";
1075 case OE_Ignore
: return "ignore";
1076 case OE_Default
: return "default";
1083 ** Parse context structure pFrom has just been used to create a sub-vdbe
1084 ** (trigger program). If an error has occurred, transfer error information
1085 ** from pFrom to pTo.
1087 static void transferParseError(Parse
*pTo
, Parse
*pFrom
){
1088 assert( pFrom
->zErrMsg
==0 || pFrom
->nErr
);
1089 assert( pTo
->zErrMsg
==0 || pTo
->nErr
);
1091 pTo
->zErrMsg
= pFrom
->zErrMsg
;
1092 pTo
->nErr
= pFrom
->nErr
;
1093 pTo
->rc
= pFrom
->rc
;
1095 sqlite3DbFree(pFrom
->db
, pFrom
->zErrMsg
);
1100 ** Create and populate a new TriggerPrg object with a sub-program
1101 ** implementing trigger pTrigger with ON CONFLICT policy orconf.
1103 static TriggerPrg
*codeRowTrigger(
1104 Parse
*pParse
, /* Current parse context */
1105 Trigger
*pTrigger
, /* Trigger to code */
1106 Table
*pTab
, /* The table pTrigger is attached to */
1107 int orconf
/* ON CONFLICT policy to code trigger program with */
1109 Parse
*pTop
= sqlite3ParseToplevel(pParse
);
1110 sqlite3
*db
= pParse
->db
; /* Database handle */
1111 TriggerPrg
*pPrg
; /* Value to return */
1112 Expr
*pWhen
= 0; /* Duplicate of trigger WHEN expression */
1113 Vdbe
*v
; /* Temporary VM */
1114 NameContext sNC
; /* Name context for sub-vdbe */
1115 SubProgram
*pProgram
= 0; /* Sub-vdbe for trigger program */
1116 int iEndTrigger
= 0; /* Label to jump to if WHEN is false */
1117 Parse sSubParse
; /* Parse context for sub-vdbe */
1119 assert( pTrigger
->zName
==0 || pTab
==tableOfTrigger(pTrigger
) );
1120 assert( pTop
->pVdbe
);
1122 /* Allocate the TriggerPrg and SubProgram objects. To ensure that they
1123 ** are freed if an error occurs, link them into the Parse.pTriggerPrg
1124 ** list of the top-level Parse object sooner rather than later. */
1125 pPrg
= sqlite3DbMallocZero(db
, sizeof(TriggerPrg
));
1126 if( !pPrg
) return 0;
1127 pPrg
->pNext
= pTop
->pTriggerPrg
;
1128 pTop
->pTriggerPrg
= pPrg
;
1129 pPrg
->pProgram
= pProgram
= sqlite3DbMallocZero(db
, sizeof(SubProgram
));
1130 if( !pProgram
) return 0;
1131 sqlite3VdbeLinkSubProgram(pTop
->pVdbe
, pProgram
);
1132 pPrg
->pTrigger
= pTrigger
;
1133 pPrg
->orconf
= orconf
;
1134 pPrg
->aColmask
[0] = 0xffffffff;
1135 pPrg
->aColmask
[1] = 0xffffffff;
1137 /* Allocate and populate a new Parse context to use for coding the
1138 ** trigger sub-program. */
1139 sqlite3ParseObjectInit(&sSubParse
, db
);
1140 memset(&sNC
, 0, sizeof(sNC
));
1141 sNC
.pParse
= &sSubParse
;
1142 sSubParse
.pTriggerTab
= pTab
;
1143 sSubParse
.pToplevel
= pTop
;
1144 sSubParse
.zAuthContext
= pTrigger
->zName
;
1145 sSubParse
.eTriggerOp
= pTrigger
->op
;
1146 sSubParse
.nQueryLoop
= pParse
->nQueryLoop
;
1147 sSubParse
.disableVtab
= pParse
->disableVtab
;
1149 v
= sqlite3GetVdbe(&sSubParse
);
1151 VdbeComment((v
, "Start: %s.%s (%s %s%s%s ON %s)",
1152 pTrigger
->zName
, onErrorText(orconf
),
1153 (pTrigger
->tr_tm
==TRIGGER_BEFORE
? "BEFORE" : "AFTER"),
1154 (pTrigger
->op
==TK_UPDATE
? "UPDATE" : ""),
1155 (pTrigger
->op
==TK_INSERT
? "INSERT" : ""),
1156 (pTrigger
->op
==TK_DELETE
? "DELETE" : ""),
1159 #ifndef SQLITE_OMIT_TRACE
1160 if( pTrigger
->zName
){
1161 sqlite3VdbeChangeP4(v
, -1,
1162 sqlite3MPrintf(db
, "-- TRIGGER %s", pTrigger
->zName
), P4_DYNAMIC
1167 /* If one was specified, code the WHEN clause. If it evaluates to false
1168 ** (or NULL) the sub-vdbe is immediately halted by jumping to the
1169 ** OP_Halt inserted at the end of the program. */
1170 if( pTrigger
->pWhen
){
1171 pWhen
= sqlite3ExprDup(db
, pTrigger
->pWhen
, 0);
1172 if( db
->mallocFailed
==0
1173 && SQLITE_OK
==sqlite3ResolveExprNames(&sNC
, pWhen
)
1175 iEndTrigger
= sqlite3VdbeMakeLabel(&sSubParse
);
1176 sqlite3ExprIfFalse(&sSubParse
, pWhen
, iEndTrigger
, SQLITE_JUMPIFNULL
);
1178 sqlite3ExprDelete(db
, pWhen
);
1181 /* Code the trigger program into the sub-vdbe. */
1182 codeTriggerProgram(&sSubParse
, pTrigger
->step_list
, orconf
);
1184 /* Insert an OP_Halt at the end of the sub-program. */
1186 sqlite3VdbeResolveLabel(v
, iEndTrigger
);
1188 sqlite3VdbeAddOp0(v
, OP_Halt
);
1189 VdbeComment((v
, "End: %s.%s", pTrigger
->zName
, onErrorText(orconf
)));
1190 transferParseError(pParse
, &sSubParse
);
1192 if( pParse
->nErr
==0 ){
1193 assert( db
->mallocFailed
==0 );
1194 pProgram
->aOp
= sqlite3VdbeTakeOpArray(v
, &pProgram
->nOp
, &pTop
->nMaxArg
);
1196 pProgram
->nMem
= sSubParse
.nMem
;
1197 pProgram
->nCsr
= sSubParse
.nTab
;
1198 pProgram
->token
= (void *)pTrigger
;
1199 pPrg
->aColmask
[0] = sSubParse
.oldmask
;
1200 pPrg
->aColmask
[1] = sSubParse
.newmask
;
1201 sqlite3VdbeDelete(v
);
1203 transferParseError(pParse
, &sSubParse
);
1206 assert( !sSubParse
.pTriggerPrg
&& !sSubParse
.nMaxArg
);
1207 sqlite3ParseObjectReset(&sSubParse
);
1212 ** Return a pointer to a TriggerPrg object containing the sub-program for
1213 ** trigger pTrigger with default ON CONFLICT algorithm orconf. If no such
1214 ** TriggerPrg object exists, a new object is allocated and populated before
1217 static TriggerPrg
*getRowTrigger(
1218 Parse
*pParse
, /* Current parse context */
1219 Trigger
*pTrigger
, /* Trigger to code */
1220 Table
*pTab
, /* The table trigger pTrigger is attached to */
1221 int orconf
/* ON CONFLICT algorithm. */
1223 Parse
*pRoot
= sqlite3ParseToplevel(pParse
);
1226 assert( pTrigger
->zName
==0 || pTab
==tableOfTrigger(pTrigger
) );
1228 /* It may be that this trigger has already been coded (or is in the
1229 ** process of being coded). If this is the case, then an entry with
1230 ** a matching TriggerPrg.pTrigger field will be present somewhere
1231 ** in the Parse.pTriggerPrg list. Search for such an entry. */
1232 for(pPrg
=pRoot
->pTriggerPrg
;
1233 pPrg
&& (pPrg
->pTrigger
!=pTrigger
|| pPrg
->orconf
!=orconf
);
1237 /* If an existing TriggerPrg could not be located, create a new one. */
1239 pPrg
= codeRowTrigger(pParse
, pTrigger
, pTab
, orconf
);
1240 pParse
->db
->errByteOffset
= -1;
1247 ** Generate code for the trigger program associated with trigger p on
1248 ** table pTab. The reg, orconf and ignoreJump parameters passed to this
1249 ** function are the same as those described in the header function for
1250 ** sqlite3CodeRowTrigger()
1252 void sqlite3CodeRowTriggerDirect(
1253 Parse
*pParse
, /* Parse context */
1254 Trigger
*p
, /* Trigger to code */
1255 Table
*pTab
, /* The table to code triggers from */
1256 int reg
, /* Reg array containing OLD.* and NEW.* values */
1257 int orconf
, /* ON CONFLICT policy */
1258 int ignoreJump
/* Instruction to jump to for RAISE(IGNORE) */
1260 Vdbe
*v
= sqlite3GetVdbe(pParse
); /* Main VM */
1262 pPrg
= getRowTrigger(pParse
, p
, pTab
, orconf
);
1263 assert( pPrg
|| pParse
->nErr
);
1265 /* Code the OP_Program opcode in the parent VDBE. P4 of the OP_Program
1266 ** is a pointer to the sub-vdbe containing the trigger program. */
1268 int bRecursive
= (p
->zName
&& 0==(pParse
->db
->flags
&SQLITE_RecTriggers
));
1270 sqlite3VdbeAddOp4(v
, OP_Program
, reg
, ignoreJump
, ++pParse
->nMem
,
1271 (const char *)pPrg
->pProgram
, P4_SUBPROGRAM
);
1273 (v
, "Call: %s.%s", (p
->zName
?p
->zName
:"fkey"), onErrorText(orconf
)));
1275 /* Set the P5 operand of the OP_Program instruction to non-zero if
1276 ** recursive invocation of this trigger program is disallowed. Recursive
1277 ** invocation is disallowed if (a) the sub-program is really a trigger,
1278 ** not a foreign key action, and (b) the flag to enable recursive triggers
1280 sqlite3VdbeChangeP5(v
, (u8
)bRecursive
);
1285 ** This is called to code the required FOR EACH ROW triggers for an operation
1286 ** on table pTab. The operation to code triggers for (INSERT, UPDATE or DELETE)
1287 ** is given by the op parameter. The tr_tm parameter determines whether the
1288 ** BEFORE or AFTER triggers are coded. If the operation is an UPDATE, then
1289 ** parameter pChanges is passed the list of columns being modified.
1291 ** If there are no triggers that fire at the specified time for the specified
1292 ** operation on pTab, this function is a no-op.
1294 ** The reg argument is the address of the first in an array of registers
1295 ** that contain the values substituted for the new.* and old.* references
1296 ** in the trigger program. If N is the number of columns in table pTab
1297 ** (a copy of pTab->nCol), then registers are populated as follows:
1299 ** Register Contains
1300 ** ------------------------------------------------------
1302 ** reg+1 OLD.* value of left-most column of pTab
1304 ** reg+N OLD.* value of right-most column of pTab
1305 ** reg+N+1 NEW.rowid
1306 ** reg+N+2 NEW.* value of left-most column of pTab
1308 ** reg+N+N+1 NEW.* value of right-most column of pTab
1310 ** For ON DELETE triggers, the registers containing the NEW.* values will
1311 ** never be accessed by the trigger program, so they are not allocated or
1312 ** populated by the caller (there is no data to populate them with anyway).
1313 ** Similarly, for ON INSERT triggers the values stored in the OLD.* registers
1314 ** are never accessed, and so are not allocated by the caller. So, for an
1315 ** ON INSERT trigger, the value passed to this function as parameter reg
1316 ** is not a readable register, although registers (reg+N) through
1319 ** Parameter orconf is the default conflict resolution algorithm for the
1320 ** trigger program to use (REPLACE, IGNORE etc.). Parameter ignoreJump
1321 ** is the instruction that control should jump to if a trigger program
1322 ** raises an IGNORE exception.
1324 void sqlite3CodeRowTrigger(
1325 Parse
*pParse
, /* Parse context */
1326 Trigger
*pTrigger
, /* List of triggers on table pTab */
1327 int op
, /* One of TK_UPDATE, TK_INSERT, TK_DELETE */
1328 ExprList
*pChanges
, /* Changes list for any UPDATE OF triggers */
1329 int tr_tm
, /* One of TRIGGER_BEFORE, TRIGGER_AFTER */
1330 Table
*pTab
, /* The table to code triggers from */
1331 int reg
, /* The first in an array of registers (see above) */
1332 int orconf
, /* ON CONFLICT policy */
1333 int ignoreJump
/* Instruction to jump to for RAISE(IGNORE) */
1335 Trigger
*p
; /* Used to iterate through pTrigger list */
1337 assert( op
==TK_UPDATE
|| op
==TK_INSERT
|| op
==TK_DELETE
);
1338 assert( tr_tm
==TRIGGER_BEFORE
|| tr_tm
==TRIGGER_AFTER
);
1339 assert( (op
==TK_UPDATE
)==(pChanges
!=0) );
1341 for(p
=pTrigger
; p
; p
=p
->pNext
){
1343 /* Sanity checking: The schema for the trigger and for the table are
1344 ** always defined. The trigger must be in the same schema as the table
1345 ** or else it must be a TEMP trigger. */
1346 assert( p
->pSchema
!=0 );
1347 assert( p
->pTabSchema
!=0 );
1348 assert( p
->pSchema
==p
->pTabSchema
1349 || p
->pSchema
==pParse
->db
->aDb
[1].pSchema
);
1351 /* Determine whether we should code this trigger. One of two choices:
1352 ** 1. The trigger is an exact match to the current DML statement
1353 ** 2. This is a RETURNING trigger for INSERT but we are currently
1354 ** doing the UPDATE part of an UPSERT.
1356 if( (p
->op
==op
|| (p
->bReturning
&& p
->op
==TK_INSERT
&& op
==TK_UPDATE
))
1358 && checkColumnOverlap(p
->pColumns
, pChanges
)
1360 if( !p
->bReturning
){
1361 sqlite3CodeRowTriggerDirect(pParse
, p
, pTab
, reg
, orconf
, ignoreJump
);
1362 }else if( sqlite3IsToplevel(pParse
) ){
1363 codeReturningTrigger(pParse
, p
, pTab
, reg
);
1370 ** Triggers may access values stored in the old.* or new.* pseudo-table.
1371 ** This function returns a 32-bit bitmask indicating which columns of the
1372 ** old.* or new.* tables actually are used by triggers. This information
1373 ** may be used by the caller, for example, to avoid having to load the entire
1374 ** old.* record into memory when executing an UPDATE or DELETE command.
1376 ** Bit 0 of the returned mask is set if the left-most column of the
1377 ** table may be accessed using an [old|new].<col> reference. Bit 1 is set if
1378 ** the second leftmost column value is required, and so on. If there
1379 ** are more than 32 columns in the table, and at least one of the columns
1380 ** with an index greater than 32 may be accessed, 0xffffffff is returned.
1382 ** It is not possible to determine if the old.rowid or new.rowid column is
1383 ** accessed by triggers. The caller must always assume that it is.
1385 ** Parameter isNew must be either 1 or 0. If it is 0, then the mask returned
1386 ** applies to the old.* table. If 1, the new.* table.
1388 ** Parameter tr_tm must be a mask with one or both of the TRIGGER_BEFORE
1389 ** and TRIGGER_AFTER bits set. Values accessed by BEFORE triggers are only
1390 ** included in the returned mask if the TRIGGER_BEFORE bit is set in the
1391 ** tr_tm parameter. Similarly, values accessed by AFTER triggers are only
1392 ** included in the returned mask if the TRIGGER_AFTER bit is set in tr_tm.
1394 u32
sqlite3TriggerColmask(
1395 Parse
*pParse
, /* Parse context */
1396 Trigger
*pTrigger
, /* List of triggers on table pTab */
1397 ExprList
*pChanges
, /* Changes list for any UPDATE OF triggers */
1398 int isNew
, /* 1 for new.* ref mask, 0 for old.* ref mask */
1399 int tr_tm
, /* Mask of TRIGGER_BEFORE|TRIGGER_AFTER */
1400 Table
*pTab
, /* The table to code triggers from */
1401 int orconf
/* Default ON CONFLICT policy for trigger steps */
1403 const int op
= pChanges
? TK_UPDATE
: TK_DELETE
;
1407 assert( isNew
==1 || isNew
==0 );
1408 for(p
=pTrigger
; p
; p
=p
->pNext
){
1411 && checkColumnOverlap(p
->pColumns
,pChanges
)
1413 if( p
->bReturning
){
1417 pPrg
= getRowTrigger(pParse
, p
, pTab
, orconf
);
1419 mask
|= pPrg
->aColmask
[isNew
];
1428 #endif /* !defined(SQLITE_OMIT_TRIGGER) */