trigger.c 40 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135
  1. /*
  2. **
  3. ** The author disclaims copyright to this source code. In place of
  4. ** a legal notice, here is a blessing:
  5. **
  6. ** May you do good and not evil.
  7. ** May you find forgiveness for yourself and forgive others.
  8. ** May you share freely, never taking more than you give.
  9. **
  10. *************************************************************************
  11. ** This file contains the implementation for TRIGGERs
  12. */
  13. #include "sqliteInt.h"
  14. #ifndef SQLITE_OMIT_TRIGGER
  15. /*
  16. ** Delete a linked list of TriggerStep structures.
  17. */
  18. void sqlite3DeleteTriggerStep(sqlite3 *db, TriggerStep *pTriggerStep){
  19. while( pTriggerStep ){
  20. TriggerStep * pTmp = pTriggerStep;
  21. pTriggerStep = pTriggerStep->pNext;
  22. sqlite3ExprDelete(db, pTmp->pWhere);
  23. sqlite3ExprListDelete(db, pTmp->pExprList);
  24. sqlite3SelectDelete(db, pTmp->pSelect);
  25. sqlite3IdListDelete(db, pTmp->pIdList);
  26. sqlite3DbFree(db, pTmp);
  27. }
  28. }
  29. /*
  30. ** Given table pTab, return a list of all the triggers attached to
  31. ** the table. The list is connected by Trigger.pNext pointers.
  32. **
  33. ** All of the triggers on pTab that are in the same database as pTab
  34. ** are already attached to pTab->pTrigger. But there might be additional
  35. ** triggers on pTab in the TEMP schema. This routine prepends all
  36. ** TEMP triggers on pTab to the beginning of the pTab->pTrigger list
  37. ** and returns the combined list.
  38. **
  39. ** To state it another way: This routine returns a list of all triggers
  40. ** that fire off of pTab. The list will include any TEMP triggers on
  41. ** pTab as well as the triggers lised in pTab->pTrigger.
  42. */
  43. Trigger *sqlite3TriggerList(Parse *pParse, Table *pTab){
  44. Schema * const pTmpSchema = pParse->db->aDb[1].pSchema;
  45. Trigger *pList = 0; /* List of triggers to return */
  46. if( pParse->disableTriggers ){
  47. return 0;
  48. }
  49. if( pTmpSchema!=pTab->pSchema ){
  50. HashElem *p;
  51. assert( sqlite3SchemaMutexHeld(pParse->db, 0, pTmpSchema) );
  52. for(p=sqliteHashFirst(&pTmpSchema->trigHash); p; p=sqliteHashNext(p)){
  53. Trigger *pTrig = (Trigger *)sqliteHashData(p);
  54. if( pTrig->pTabSchema==pTab->pSchema
  55. && 0==sqlite3StrICmp(pTrig->table, pTab->zName)
  56. ){
  57. pTrig->pNext = (pList ? pList : pTab->pTrigger);
  58. pList = pTrig;
  59. }
  60. }
  61. }
  62. return (pList ? pList : pTab->pTrigger);
  63. }
  64. /*
  65. ** This is called by the parser when it sees a CREATE TRIGGER statement
  66. ** up to the point of the BEGIN before the trigger actions. A Trigger
  67. ** structure is generated based on the information available and stored
  68. ** in pParse->pNewTrigger. After the trigger actions have been parsed, the
  69. ** sqlite3FinishTrigger() function is called to complete the trigger
  70. ** construction process.
  71. */
  72. void sqlite3BeginTrigger(
  73. Parse *pParse, /* The parse context of the CREATE TRIGGER statement */
  74. Token *pName1, /* The name of the trigger */
  75. Token *pName2, /* The name of the trigger */
  76. int tr_tm, /* One of TK_BEFORE, TK_AFTER, TK_INSTEAD */
  77. int op, /* One of TK_INSERT, TK_UPDATE, TK_DELETE */
  78. IdList *pColumns, /* column list if this is an UPDATE OF trigger */
  79. SrcList *pTableName,/* The name of the table/view the trigger applies to */
  80. Expr *pWhen, /* WHEN clause */
  81. int isTemp, /* True if the TEMPORARY keyword is present */
  82. int noErr /* Suppress errors if the trigger already exists */
  83. ){
  84. Trigger *pTrigger = 0; /* The new trigger */
  85. Table *pTab; /* Table that the trigger fires off of */
  86. char *zName = 0; /* Name of the trigger */
  87. sqlite3 *db = pParse->db; /* The database connection */
  88. int iDb; /* The database to store the trigger in */
  89. Token *pName; /* The unqualified db name */
  90. DbFixer sFix; /* State vector for the DB fixer */
  91. int iTabDb; /* Index of the database holding pTab */
  92. assert( pName1!=0 ); /* pName1->z might be NULL, but not pName1 itself */
  93. assert( pName2!=0 );
  94. assert( op==TK_INSERT || op==TK_UPDATE || op==TK_DELETE );
  95. assert( op>0 && op<0xff );
  96. if( isTemp ){
  97. /* If TEMP was specified, then the trigger name may not be qualified. */
  98. if( pName2->n>0 ){
  99. sqlite3ErrorMsg(pParse, "temporary trigger may not have qualified name");
  100. goto trigger_cleanup;
  101. }
  102. iDb = 1;
  103. pName = pName1;
  104. }else{
  105. /* Figure out the db that the trigger will be created in */
  106. iDb = sqlite3TwoPartName(pParse, pName1, pName2, &pName);
  107. if( iDb<0 ){
  108. goto trigger_cleanup;
  109. }
  110. }
  111. if( !pTableName || db->mallocFailed ){
  112. goto trigger_cleanup;
  113. }
  114. /* A long-standing parser bug is that this syntax was allowed:
  115. **
  116. ** CREATE TRIGGER attached.demo AFTER INSERT ON attached.tab ....
  117. ** ^^^^^^^^
  118. **
  119. ** To maintain backwards compatibility, ignore the database
  120. ** name on pTableName if we are reparsing our of SQLITE_MASTER.
  121. */
  122. if( db->init.busy && iDb!=1 ){
  123. sqlite3DbFree(db, pTableName->a[0].zDatabase);
  124. pTableName->a[0].zDatabase = 0;
  125. }
  126. /* If the trigger name was unqualified, and the table is a temp table,
  127. ** then set iDb to 1 to create the trigger in the temporary database.
  128. ** If sqlite3SrcListLookup() returns 0, indicating the table does not
  129. ** exist, the error is caught by the block below.
  130. */
  131. pTab = sqlite3SrcListLookup(pParse, pTableName);
  132. if( db->init.busy==0 && pName2->n==0 && pTab
  133. && pTab->pSchema==db->aDb[1].pSchema ){
  134. iDb = 1;
  135. }
  136. /* Ensure the table name matches database name and that the table exists */
  137. if( db->mallocFailed ) goto trigger_cleanup;
  138. assert( pTableName->nSrc==1 );
  139. sqlite3FixInit(&sFix, pParse, iDb, "trigger", pName);
  140. if( sqlite3FixSrcList(&sFix, pTableName) ){
  141. goto trigger_cleanup;
  142. }
  143. pTab = sqlite3SrcListLookup(pParse, pTableName);
  144. if( !pTab ){
  145. /* The table does not exist. */
  146. if( db->init.iDb==1 ){
  147. /* Ticket #3810.
  148. ** Normally, whenever a table is dropped, all associated triggers are
  149. ** dropped too. But if a TEMP trigger is created on a non-TEMP table
  150. ** and the table is dropped by a different database connection, the
  151. ** trigger is not visible to the database connection that does the
  152. ** drop so the trigger cannot be dropped. This results in an
  153. ** "orphaned trigger" - a trigger whose associated table is missing.
  154. */
  155. db->init.orphanTrigger = 1;
  156. }
  157. goto trigger_cleanup;
  158. }
  159. if( IsVirtual(pTab) ){
  160. sqlite3ErrorMsg(pParse, "cannot create triggers on virtual tables");
  161. goto trigger_cleanup;
  162. }
  163. /* Check that the trigger name is not reserved and that no trigger of the
  164. ** specified name exists */
  165. zName = sqlite3NameFromToken(db, pName);
  166. if( !zName || SQLITE_OK!=sqlite3CheckObjectName(pParse, zName) ){
  167. goto trigger_cleanup;
  168. }
  169. assert( sqlite3SchemaMutexHeld(db, iDb, 0) );
  170. if( sqlite3HashFind(&(db->aDb[iDb].pSchema->trigHash),
  171. zName, sqlite3Strlen30(zName)) ){
  172. if( !noErr ){
  173. sqlite3ErrorMsg(pParse, "trigger %T already exists", pName);
  174. }else{
  175. assert( !db->init.busy );
  176. sqlite3CodeVerifySchema(pParse, iDb);
  177. }
  178. goto trigger_cleanup;
  179. }
  180. /* Do not create a trigger on a system table */
  181. if( sqlite3StrNICmp(pTab->zName, "sqlite_", 7)==0 ){
  182. sqlite3ErrorMsg(pParse, "cannot create trigger on system table");
  183. pParse->nErr++;
  184. goto trigger_cleanup;
  185. }
  186. /* INSTEAD of triggers are only for views and views only support INSTEAD
  187. ** of triggers.
  188. */
  189. if( pTab->pSelect && tr_tm!=TK_INSTEAD ){
  190. sqlite3ErrorMsg(pParse, "cannot create %s trigger on view: %S",
  191. (tr_tm == TK_BEFORE)?"BEFORE":"AFTER", pTableName, 0);
  192. goto trigger_cleanup;
  193. }
  194. if( !pTab->pSelect && tr_tm==TK_INSTEAD ){
  195. sqlite3ErrorMsg(pParse, "cannot create INSTEAD OF"
  196. " trigger on table: %S", pTableName, 0);
  197. goto trigger_cleanup;
  198. }
  199. iTabDb = sqlite3SchemaToIndex(db, pTab->pSchema);
  200. #ifndef SQLITE_OMIT_AUTHORIZATION
  201. {
  202. int code = SQLITE_CREATE_TRIGGER;
  203. const char *zDb = db->aDb[iTabDb].zName;
  204. const char *zDbTrig = isTemp ? db->aDb[1].zName : zDb;
  205. if( iTabDb==1 || isTemp ) code = SQLITE_CREATE_TEMP_TRIGGER;
  206. if( sqlite3AuthCheck(pParse, code, zName, pTab->zName, zDbTrig) ){
  207. goto trigger_cleanup;
  208. }
  209. if( sqlite3AuthCheck(pParse, SQLITE_INSERT, SCHEMA_TABLE(iTabDb),0,zDb)){
  210. goto trigger_cleanup;
  211. }
  212. }
  213. #endif
  214. /* INSTEAD OF triggers can only appear on views and BEFORE triggers
  215. ** cannot appear on views. So we might as well translate every
  216. ** INSTEAD OF trigger into a BEFORE trigger. It simplifies code
  217. ** elsewhere.
  218. */
  219. if (tr_tm == TK_INSTEAD){
  220. tr_tm = TK_BEFORE;
  221. }
  222. /* Build the Trigger object */
  223. pTrigger = (Trigger*)sqlite3DbMallocZero(db, sizeof(Trigger));
  224. if( pTrigger==0 ) goto trigger_cleanup;
  225. pTrigger->zName = zName;
  226. zName = 0;
  227. pTrigger->table = sqlite3DbStrDup(db, pTableName->a[0].zName);
  228. pTrigger->pSchema = db->aDb[iDb].pSchema;
  229. pTrigger->pTabSchema = pTab->pSchema;
  230. pTrigger->op = (u8)op;
  231. pTrigger->tr_tm = tr_tm==TK_BEFORE ? TRIGGER_BEFORE : TRIGGER_AFTER;
  232. pTrigger->pWhen = sqlite3ExprDup(db, pWhen, EXPRDUP_REDUCE);
  233. pTrigger->pColumns = sqlite3IdListDup(db, pColumns);
  234. assert( pParse->pNewTrigger==0 );
  235. pParse->pNewTrigger = pTrigger;
  236. trigger_cleanup:
  237. sqlite3DbFree(db, zName);
  238. sqlite3SrcListDelete(db, pTableName);
  239. sqlite3IdListDelete(db, pColumns);
  240. sqlite3ExprDelete(db, pWhen);
  241. if( !pParse->pNewTrigger ){
  242. sqlite3DeleteTrigger(db, pTrigger);
  243. }else{
  244. assert( pParse->pNewTrigger==pTrigger );
  245. }
  246. }
  247. /*
  248. ** This routine is called after all of the trigger actions have been parsed
  249. ** in order to complete the process of building the trigger.
  250. */
  251. void sqlite3FinishTrigger(
  252. Parse *pParse, /* Parser context */
  253. TriggerStep *pStepList, /* The triggered program */
  254. Token *pAll /* Token that describes the complete CREATE TRIGGER */
  255. ){
  256. Trigger *pTrig = pParse->pNewTrigger; /* Trigger being finished */
  257. char *zName; /* Name of trigger */
  258. sqlite3 *db = pParse->db; /* The database */
  259. DbFixer sFix; /* Fixer object */
  260. int iDb; /* Database containing the trigger */
  261. Token nameToken; /* Trigger name for error reporting */
  262. pParse->pNewTrigger = 0;
  263. if( NEVER(pParse->nErr) || !pTrig ) goto triggerfinish_cleanup;
  264. zName = pTrig->zName;
  265. iDb = sqlite3SchemaToIndex(pParse->db, pTrig->pSchema);
  266. pTrig->step_list = pStepList;
  267. while( pStepList ){
  268. pStepList->pTrig = pTrig;
  269. pStepList = pStepList->pNext;
  270. }
  271. nameToken.z = pTrig->zName;
  272. nameToken.n = sqlite3Strlen30(nameToken.z);
  273. sqlite3FixInit(&sFix, pParse, iDb, "trigger", &nameToken);
  274. if( sqlite3FixTriggerStep(&sFix, pTrig->step_list)
  275. || sqlite3FixExpr(&sFix, pTrig->pWhen)
  276. ){
  277. goto triggerfinish_cleanup;
  278. }
  279. /* if we are not initializing,
  280. ** build the sqlite_master entry
  281. */
  282. if( !db->init.busy ){
  283. Vdbe *v;
  284. char *z;
  285. /* Make an entry in the sqlite_master table */
  286. v = sqlite3GetVdbe(pParse);
  287. if( v==0 ) goto triggerfinish_cleanup;
  288. sqlite3BeginWriteOperation(pParse, 0, iDb);
  289. z = sqlite3DbStrNDup(db, (char*)pAll->z, pAll->n);
  290. sqlite3NestedParse(pParse,
  291. "INSERT INTO %Q.%s VALUES('trigger',%Q,%Q,0,'CREATE TRIGGER %q')",
  292. db->aDb[iDb].zName, SCHEMA_TABLE(iDb), zName,
  293. pTrig->table, z);
  294. sqlite3DbFree(db, z);
  295. sqlite3ChangeCookie(pParse, iDb);
  296. sqlite3VdbeAddParseSchemaOp(v, iDb,
  297. sqlite3MPrintf(db, "type='trigger' AND name='%q'", zName));
  298. }
  299. if( db->init.busy ){
  300. Trigger *pLink = pTrig;
  301. Hash *pHash = &db->aDb[iDb].pSchema->trigHash;
  302. assert( sqlite3SchemaMutexHeld(db, iDb, 0) );
  303. pTrig = sqlite3HashInsert(pHash, zName, sqlite3Strlen30(zName), pTrig);
  304. if( pTrig ){
  305. db->mallocFailed = 1;
  306. }else if( pLink->pSchema==pLink->pTabSchema ){
  307. Table *pTab;
  308. int n = sqlite3Strlen30(pLink->table);
  309. pTab = sqlite3HashFind(&pLink->pTabSchema->tblHash, pLink->table, n);
  310. assert( pTab!=0 );
  311. pLink->pNext = pTab->pTrigger;
  312. pTab->pTrigger = pLink;
  313. }
  314. }
  315. triggerfinish_cleanup:
  316. sqlite3DeleteTrigger(db, pTrig);
  317. assert( !pParse->pNewTrigger );
  318. sqlite3DeleteTriggerStep(db, pStepList);
  319. }
  320. /*
  321. ** Turn a SELECT statement (that the pSelect parameter points to) into
  322. ** a trigger step. Return a pointer to a TriggerStep structure.
  323. **
  324. ** The parser calls this routine when it finds a SELECT statement in
  325. ** body of a TRIGGER.
  326. */
  327. TriggerStep *sqlite3TriggerSelectStep(sqlite3 *db, Select *pSelect){
  328. TriggerStep *pTriggerStep = sqlite3DbMallocZero(db, sizeof(TriggerStep));
  329. if( pTriggerStep==0 ) {
  330. sqlite3SelectDelete(db, pSelect);
  331. return 0;
  332. }
  333. pTriggerStep->op = TK_SELECT;
  334. pTriggerStep->pSelect = pSelect;
  335. pTriggerStep->orconf = OE_Default;
  336. return pTriggerStep;
  337. }
  338. /*
  339. ** Allocate space to hold a new trigger step. The allocated space
  340. ** holds both the TriggerStep object and the TriggerStep.target.z string.
  341. **
  342. ** If an OOM error occurs, NULL is returned and db->mallocFailed is set.
  343. */
  344. static TriggerStep *triggerStepAllocate(
  345. sqlite3 *db, /* Database connection */
  346. u8 op, /* Trigger opcode */
  347. Token *pName /* The target name */
  348. ){
  349. TriggerStep *pTriggerStep;
  350. pTriggerStep = sqlite3DbMallocZero(db, sizeof(TriggerStep) + pName->n);
  351. if( pTriggerStep ){
  352. char *z = (char*)&pTriggerStep[1];
  353. memcpy(z, pName->z, pName->n);
  354. pTriggerStep->target.z = z;
  355. pTriggerStep->target.n = pName->n;
  356. pTriggerStep->op = op;
  357. }
  358. return pTriggerStep;
  359. }
  360. /*
  361. ** Build a trigger step out of an INSERT statement. Return a pointer
  362. ** to the new trigger step.
  363. **
  364. ** The parser calls this routine when it sees an INSERT inside the
  365. ** body of a trigger.
  366. */
  367. TriggerStep *sqlite3TriggerInsertStep(
  368. sqlite3 *db, /* The database connection */
  369. Token *pTableName, /* Name of the table into which we insert */
  370. IdList *pColumn, /* List of columns in pTableName to insert into */
  371. ExprList *pEList, /* The VALUE clause: a list of values to be inserted */
  372. Select *pSelect, /* A SELECT statement that supplies values */
  373. u8 orconf /* The conflict algorithm (OE_Abort, OE_Replace, etc.) */
  374. ){
  375. TriggerStep *pTriggerStep;
  376. assert(pEList == 0 || pSelect == 0);
  377. assert(pEList != 0 || pSelect != 0 || db->mallocFailed);
  378. pTriggerStep = triggerStepAllocate(db, TK_INSERT, pTableName);
  379. if( pTriggerStep ){
  380. pTriggerStep->pSelect = sqlite3SelectDup(db, pSelect, EXPRDUP_REDUCE);
  381. pTriggerStep->pIdList = pColumn;
  382. pTriggerStep->pExprList = sqlite3ExprListDup(db, pEList, EXPRDUP_REDUCE);
  383. pTriggerStep->orconf = orconf;
  384. }else{
  385. sqlite3IdListDelete(db, pColumn);
  386. }
  387. sqlite3ExprListDelete(db, pEList);
  388. sqlite3SelectDelete(db, pSelect);
  389. return pTriggerStep;
  390. }
  391. /*
  392. ** Construct a trigger step that implements an UPDATE statement and return
  393. ** a pointer to that trigger step. The parser calls this routine when it
  394. ** sees an UPDATE statement inside the body of a CREATE TRIGGER.
  395. */
  396. TriggerStep *sqlite3TriggerUpdateStep(
  397. sqlite3 *db, /* The database connection */
  398. Token *pTableName, /* Name of the table to be updated */
  399. ExprList *pEList, /* The SET clause: list of column and new values */
  400. Expr *pWhere, /* The WHERE clause */
  401. u8 orconf /* The conflict algorithm. (OE_Abort, OE_Ignore, etc) */
  402. ){
  403. TriggerStep *pTriggerStep;
  404. pTriggerStep = triggerStepAllocate(db, TK_UPDATE, pTableName);
  405. if( pTriggerStep ){
  406. pTriggerStep->pExprList = sqlite3ExprListDup(db, pEList, EXPRDUP_REDUCE);
  407. pTriggerStep->pWhere = sqlite3ExprDup(db, pWhere, EXPRDUP_REDUCE);
  408. pTriggerStep->orconf = orconf;
  409. }
  410. sqlite3ExprListDelete(db, pEList);
  411. sqlite3ExprDelete(db, pWhere);
  412. return pTriggerStep;
  413. }
  414. /*
  415. ** Construct a trigger step that implements a DELETE statement and return
  416. ** a pointer to that trigger step. The parser calls this routine when it
  417. ** sees a DELETE statement inside the body of a CREATE TRIGGER.
  418. */
  419. TriggerStep *sqlite3TriggerDeleteStep(
  420. sqlite3 *db, /* Database connection */
  421. Token *pTableName, /* The table from which rows are deleted */
  422. Expr *pWhere /* The WHERE clause */
  423. ){
  424. TriggerStep *pTriggerStep;
  425. pTriggerStep = triggerStepAllocate(db, TK_DELETE, pTableName);
  426. if( pTriggerStep ){
  427. pTriggerStep->pWhere = sqlite3ExprDup(db, pWhere, EXPRDUP_REDUCE);
  428. pTriggerStep->orconf = OE_Default;
  429. }
  430. sqlite3ExprDelete(db, pWhere);
  431. return pTriggerStep;
  432. }
  433. /*
  434. ** Recursively delete a Trigger structure
  435. */
  436. void sqlite3DeleteTrigger(sqlite3 *db, Trigger *pTrigger){
  437. if( pTrigger==0 ) return;
  438. sqlite3DeleteTriggerStep(db, pTrigger->step_list);
  439. sqlite3DbFree(db, pTrigger->zName);
  440. sqlite3DbFree(db, pTrigger->table);
  441. sqlite3ExprDelete(db, pTrigger->pWhen);
  442. sqlite3IdListDelete(db, pTrigger->pColumns);
  443. sqlite3DbFree(db, pTrigger);
  444. }
  445. /*
  446. ** This function is called to drop a trigger from the database schema.
  447. **
  448. ** This may be called directly from the parser and therefore identifies
  449. ** the trigger by name. The sqlite3DropTriggerPtr() routine does the
  450. ** same job as this routine except it takes a pointer to the trigger
  451. ** instead of the trigger name.
  452. **/
  453. void sqlite3DropTrigger(Parse *pParse, SrcList *pName, int noErr){
  454. Trigger *pTrigger = 0;
  455. int i;
  456. const char *zDb;
  457. const char *zName;
  458. int nName;
  459. sqlite3 *db = pParse->db;
  460. if( db->mallocFailed ) goto drop_trigger_cleanup;
  461. if( SQLITE_OK!=sqlite3ReadSchema(pParse) ){
  462. goto drop_trigger_cleanup;
  463. }
  464. assert( pName->nSrc==1 );
  465. zDb = pName->a[0].zDatabase;
  466. zName = pName->a[0].zName;
  467. nName = sqlite3Strlen30(zName);
  468. assert( zDb!=0 || sqlite3BtreeHoldsAllMutexes(db) );
  469. for(i=OMIT_TEMPDB; i<db->nDb; i++){
  470. int j = (i<2) ? i^1 : i; /* Search TEMP before MAIN */
  471. if( zDb && sqlite3StrICmp(db->aDb[j].zName, zDb) ) continue;
  472. assert( sqlite3SchemaMutexHeld(db, j, 0) );
  473. pTrigger = sqlite3HashFind(&(db->aDb[j].pSchema->trigHash), zName, nName);
  474. if( pTrigger ) break;
  475. }
  476. if( !pTrigger ){
  477. if( !noErr ){
  478. sqlite3ErrorMsg(pParse, "no such trigger: %S", pName, 0);
  479. }else{
  480. sqlite3CodeVerifyNamedSchema(pParse, zDb);
  481. }
  482. pParse->checkSchema = 1;
  483. goto drop_trigger_cleanup;
  484. }
  485. sqlite3DropTriggerPtr(pParse, pTrigger);
  486. drop_trigger_cleanup:
  487. sqlite3SrcListDelete(db, pName);
  488. }
  489. /*
  490. ** Return a pointer to the Table structure for the table that a trigger
  491. ** is set on.
  492. */
  493. static Table *tableOfTrigger(Trigger *pTrigger){
  494. int n = sqlite3Strlen30(pTrigger->table);
  495. return sqlite3HashFind(&pTrigger->pTabSchema->tblHash, pTrigger->table, n);
  496. }
  497. /*
  498. ** Drop a trigger given a pointer to that trigger.
  499. */
  500. void sqlite3DropTriggerPtr(Parse *pParse, Trigger *pTrigger){
  501. Table *pTable;
  502. Vdbe *v;
  503. sqlite3 *db = pParse->db;
  504. int iDb;
  505. iDb = sqlite3SchemaToIndex(pParse->db, pTrigger->pSchema);
  506. assert( iDb>=0 && iDb<db->nDb );
  507. pTable = tableOfTrigger(pTrigger);
  508. assert( pTable );
  509. assert( pTable->pSchema==pTrigger->pSchema || iDb==1 );
  510. #ifndef SQLITE_OMIT_AUTHORIZATION
  511. {
  512. int code = SQLITE_DROP_TRIGGER;
  513. const char *zDb = db->aDb[iDb].zName;
  514. const char *zTab = SCHEMA_TABLE(iDb);
  515. if( iDb==1 ) code = SQLITE_DROP_TEMP_TRIGGER;
  516. if( sqlite3AuthCheck(pParse, code, pTrigger->zName, pTable->zName, zDb) ||
  517. sqlite3AuthCheck(pParse, SQLITE_DELETE, zTab, 0, zDb) ){
  518. return;
  519. }
  520. }
  521. #endif
  522. /* Generate code to destroy the database record of the trigger.
  523. */
  524. assert( pTable!=0 );
  525. if( (v = sqlite3GetVdbe(pParse))!=0 ){
  526. int base;
  527. static const VdbeOpList dropTrigger[] = {
  528. { OP_Rewind, 0, ADDR(9), 0},
  529. { OP_String8, 0, 1, 0}, /* 1 */
  530. { OP_Column, 0, 1, 2},
  531. { OP_Ne, 2, ADDR(8), 1},
  532. { OP_String8, 0, 1, 0}, /* 4: "trigger" */
  533. { OP_Column, 0, 0, 2},
  534. { OP_Ne, 2, ADDR(8), 1},
  535. { OP_Delete, 0, 0, 0},
  536. { OP_Next, 0, ADDR(1), 0}, /* 8 */
  537. };
  538. sqlite3BeginWriteOperation(pParse, 0, iDb);
  539. sqlite3OpenMasterTable(pParse, iDb);
  540. base = sqlite3VdbeAddOpList(v, ArraySize(dropTrigger), dropTrigger);
  541. sqlite3VdbeChangeP4(v, base+1, pTrigger->zName, P4_TRANSIENT);
  542. sqlite3VdbeChangeP4(v, base+4, "trigger", P4_STATIC);
  543. sqlite3ChangeCookie(pParse, iDb);
  544. sqlite3VdbeAddOp2(v, OP_Close, 0, 0);
  545. sqlite3VdbeAddOp4(v, OP_DropTrigger, iDb, 0, 0, pTrigger->zName, 0);
  546. if( pParse->nMem<3 ){
  547. pParse->nMem = 3;
  548. }
  549. }
  550. }
  551. /*
  552. ** Remove a trigger from the hash tables of the sqlite* pointer.
  553. */
  554. void sqlite3UnlinkAndDeleteTrigger(sqlite3 *db, int iDb, const char *zName){
  555. Trigger *pTrigger;
  556. Hash *pHash;
  557. assert( sqlite3SchemaMutexHeld(db, iDb, 0) );
  558. pHash = &(db->aDb[iDb].pSchema->trigHash);
  559. pTrigger = sqlite3HashInsert(pHash, zName, sqlite3Strlen30(zName), 0);
  560. if( ALWAYS(pTrigger) ){
  561. if( pTrigger->pSchema==pTrigger->pTabSchema ){
  562. Table *pTab = tableOfTrigger(pTrigger);
  563. Trigger **pp;
  564. for(pp=&pTab->pTrigger; *pp!=pTrigger; pp=&((*pp)->pNext));
  565. *pp = (*pp)->pNext;
  566. }
  567. sqlite3DeleteTrigger(db, pTrigger);
  568. db->flags |= SQLITE_InternChanges;
  569. }
  570. }
  571. /*
  572. ** pEList is the SET clause of an UPDATE statement. Each entry
  573. ** in pEList is of the format <id>=<expr>. If any of the entries
  574. ** in pEList have an <id> which matches an identifier in pIdList,
  575. ** then return TRUE. If pIdList==NULL, then it is considered a
  576. ** wildcard that matches anything. Likewise if pEList==NULL then
  577. ** it matches anything so always return true. Return false only
  578. ** if there is no match.
  579. */
  580. static int checkColumnOverlap(IdList *pIdList, ExprList *pEList){
  581. int e;
  582. if( pIdList==0 || NEVER(pEList==0) ) return 1;
  583. for(e=0; e<pEList->nExpr; e++){
  584. if( sqlite3IdListIndex(pIdList, pEList->a[e].zName)>=0 ) return 1;
  585. }
  586. return 0;
  587. }
  588. /*
  589. ** Return a list of all triggers on table pTab if there exists at least
  590. ** one trigger that must be fired when an operation of type 'op' is
  591. ** performed on the table, and, if that operation is an UPDATE, if at
  592. ** least one of the columns in pChanges is being modified.
  593. */
  594. Trigger *sqlite3TriggersExist(
  595. Parse *pParse, /* Parse context */
  596. Table *pTab, /* The table the contains the triggers */
  597. int op, /* one of TK_DELETE, TK_INSERT, TK_UPDATE */
  598. ExprList *pChanges, /* Columns that change in an UPDATE statement */
  599. int *pMask /* OUT: Mask of TRIGGER_BEFORE|TRIGGER_AFTER */
  600. ){
  601. int mask = 0;
  602. Trigger *pList = 0;
  603. Trigger *p;
  604. if( (pParse->db->flags & SQLITE_EnableTrigger)!=0 ){
  605. pList = sqlite3TriggerList(pParse, pTab);
  606. }
  607. assert( pList==0 || IsVirtual(pTab)==0 );
  608. for(p=pList; p; p=p->pNext){
  609. if( p->op==op && checkColumnOverlap(p->pColumns, pChanges) ){
  610. mask |= p->tr_tm;
  611. }
  612. }
  613. if( pMask ){
  614. *pMask = mask;
  615. }
  616. return (mask ? pList : 0);
  617. }
  618. /*
  619. ** Convert the pStep->target token into a SrcList and return a pointer
  620. ** to that SrcList.
  621. **
  622. ** This routine adds a specific database name, if needed, to the target when
  623. ** forming the SrcList. This prevents a trigger in one database from
  624. ** referring to a target in another database. An exception is when the
  625. ** trigger is in TEMP in which case it can refer to any other database it
  626. ** wants.
  627. */
  628. static SrcList *targetSrcList(
  629. Parse *pParse, /* The parsing context */
  630. TriggerStep *pStep /* The trigger containing the target token */
  631. ){
  632. int iDb; /* Index of the database to use */
  633. SrcList *pSrc; /* SrcList to be returned */
  634. pSrc = sqlite3SrcListAppend(pParse->db, 0, &pStep->target, 0);
  635. if( pSrc ){
  636. assert( pSrc->nSrc>0 );
  637. assert( pSrc->a!=0 );
  638. iDb = sqlite3SchemaToIndex(pParse->db, pStep->pTrig->pSchema);
  639. if( iDb==0 || iDb>=2 ){
  640. sqlite3 *db = pParse->db;
  641. assert( iDb<pParse->db->nDb );
  642. pSrc->a[pSrc->nSrc-1].zDatabase = sqlite3DbStrDup(db, db->aDb[iDb].zName);
  643. }
  644. }
  645. return pSrc;
  646. }
  647. /*
  648. ** Generate VDBE code for the statements inside the body of a single
  649. ** trigger.
  650. */
  651. static int codeTriggerProgram(
  652. Parse *pParse, /* The parser context */
  653. TriggerStep *pStepList, /* List of statements inside the trigger body */
  654. int orconf /* Conflict algorithm. (OE_Abort, etc) */
  655. ){
  656. TriggerStep *pStep;
  657. Vdbe *v = pParse->pVdbe;
  658. sqlite3 *db = pParse->db;
  659. assert( pParse->pTriggerTab && pParse->pToplevel );
  660. assert( pStepList );
  661. assert( v!=0 );
  662. for(pStep=pStepList; pStep; pStep=pStep->pNext){
  663. /* Figure out the ON CONFLICT policy that will be used for this step
  664. ** of the trigger program. If the statement that caused this trigger
  665. ** to fire had an explicit ON CONFLICT, then use it. Otherwise, use
  666. ** the ON CONFLICT policy that was specified as part of the trigger
  667. ** step statement. Example:
  668. **
  669. ** CREATE TRIGGER AFTER INSERT ON t1 BEGIN;
  670. ** INSERT OR REPLACE INTO t2 VALUES(new.a, new.b);
  671. ** END;
  672. **
  673. ** INSERT INTO t1 ... ; -- insert into t2 uses REPLACE policy
  674. ** INSERT OR IGNORE INTO t1 ... ; -- insert into t2 uses IGNORE policy
  675. */
  676. pParse->eOrconf = (orconf==OE_Default)?pStep->orconf:(u8)orconf;
  677. /* Clear the cookieGoto flag. When coding triggers, the cookieGoto
  678. ** variable is used as a flag to indicate to sqlite3ExprCodeConstants()
  679. ** that it is not safe to refactor constants (this happens after the
  680. ** start of the first loop in the SQL statement is coded - at that
  681. ** point code may be conditionally executed, so it is no longer safe to
  682. ** initialize constant register values). */
  683. assert( pParse->cookieGoto==0 || pParse->cookieGoto==-1 );
  684. pParse->cookieGoto = 0;
  685. switch( pStep->op ){
  686. case TK_UPDATE: {
  687. sqlite3Update(pParse,
  688. targetSrcList(pParse, pStep),
  689. sqlite3ExprListDup(db, pStep->pExprList, 0),
  690. sqlite3ExprDup(db, pStep->pWhere, 0),
  691. pParse->eOrconf
  692. );
  693. break;
  694. }
  695. case TK_INSERT: {
  696. sqlite3Insert(pParse,
  697. targetSrcList(pParse, pStep),
  698. sqlite3ExprListDup(db, pStep->pExprList, 0),
  699. sqlite3SelectDup(db, pStep->pSelect, 0),
  700. sqlite3IdListDup(db, pStep->pIdList),
  701. pParse->eOrconf
  702. );
  703. break;
  704. }
  705. case TK_DELETE: {
  706. sqlite3DeleteFrom(pParse,
  707. targetSrcList(pParse, pStep),
  708. sqlite3ExprDup(db, pStep->pWhere, 0)
  709. );
  710. break;
  711. }
  712. default: assert( pStep->op==TK_SELECT ); {
  713. SelectDest sDest;
  714. Select *pSelect = sqlite3SelectDup(db, pStep->pSelect, 0);
  715. sqlite3SelectDestInit(&sDest, SRT_Discard, 0);
  716. sqlite3Select(pParse, pSelect, &sDest);
  717. sqlite3SelectDelete(db, pSelect);
  718. break;
  719. }
  720. }
  721. if( pStep->op!=TK_SELECT ){
  722. sqlite3VdbeAddOp0(v, OP_ResetCount);
  723. }
  724. }
  725. return 0;
  726. }
  727. #ifdef SQLITE_DEBUG
  728. /*
  729. ** This function is used to add VdbeComment() annotations to a VDBE
  730. ** program. It is not used in production code, only for debugging.
  731. */
  732. static const char *onErrorText(int onError){
  733. switch( onError ){
  734. case OE_Abort: return "abort";
  735. case OE_Rollback: return "rollback";
  736. case OE_Fail: return "fail";
  737. case OE_Replace: return "replace";
  738. case OE_Ignore: return "ignore";
  739. case OE_Default: return "default";
  740. }
  741. return "n/a";
  742. }
  743. #endif
  744. /*
  745. ** Parse context structure pFrom has just been used to create a sub-vdbe
  746. ** (trigger program). If an error has occurred, transfer error information
  747. ** from pFrom to pTo.
  748. */
  749. static void transferParseError(Parse *pTo, Parse *pFrom){
  750. assert( pFrom->zErrMsg==0 || pFrom->nErr );
  751. assert( pTo->zErrMsg==0 || pTo->nErr );
  752. if( pTo->nErr==0 ){
  753. pTo->zErrMsg = pFrom->zErrMsg;
  754. pTo->nErr = pFrom->nErr;
  755. }else{
  756. sqlite3DbFree(pFrom->db, pFrom->zErrMsg);
  757. }
  758. }
  759. /*
  760. ** Create and populate a new TriggerPrg object with a sub-program
  761. ** implementing trigger pTrigger with ON CONFLICT policy orconf.
  762. */
  763. static TriggerPrg *codeRowTrigger(
  764. Parse *pParse, /* Current parse context */
  765. Trigger *pTrigger, /* Trigger to code */
  766. Table *pTab, /* The table pTrigger is attached to */
  767. int orconf /* ON CONFLICT policy to code trigger program with */
  768. ){
  769. Parse *pTop = sqlite3ParseToplevel(pParse);
  770. sqlite3 *db = pParse->db; /* Database handle */
  771. TriggerPrg *pPrg; /* Value to return */
  772. Expr *pWhen = 0; /* Duplicate of trigger WHEN expression */
  773. Vdbe *v; /* Temporary VM */
  774. NameContext sNC; /* Name context for sub-vdbe */
  775. SubProgram *pProgram = 0; /* Sub-vdbe for trigger program */
  776. Parse *pSubParse; /* Parse context for sub-vdbe */
  777. int iEndTrigger = 0; /* Label to jump to if WHEN is false */
  778. assert( pTrigger->zName==0 || pTab==tableOfTrigger(pTrigger) );
  779. assert( pTop->pVdbe );
  780. /* Allocate the TriggerPrg and SubProgram objects. To ensure that they
  781. ** are freed if an error occurs, link them into the Parse.pTriggerPrg
  782. ** list of the top-level Parse object sooner rather than later. */
  783. pPrg = sqlite3DbMallocZero(db, sizeof(TriggerPrg));
  784. if( !pPrg ) return 0;
  785. pPrg->pNext = pTop->pTriggerPrg;
  786. pTop->pTriggerPrg = pPrg;
  787. pPrg->pProgram = pProgram = sqlite3DbMallocZero(db, sizeof(SubProgram));
  788. if( !pProgram ) return 0;
  789. sqlite3VdbeLinkSubProgram(pTop->pVdbe, pProgram);
  790. pPrg->pTrigger = pTrigger;
  791. pPrg->orconf = orconf;
  792. pPrg->aColmask[0] = 0xffffffff;
  793. pPrg->aColmask[1] = 0xffffffff;
  794. /* Allocate and populate a new Parse context to use for coding the
  795. ** trigger sub-program. */
  796. pSubParse = sqlite3StackAllocZero(db, sizeof(Parse));
  797. if( !pSubParse ) return 0;
  798. memset(&sNC, 0, sizeof(sNC));
  799. sNC.pParse = pSubParse;
  800. pSubParse->db = db;
  801. pSubParse->pTriggerTab = pTab;
  802. pSubParse->pToplevel = pTop;
  803. pSubParse->zAuthContext = pTrigger->zName;
  804. pSubParse->eTriggerOp = pTrigger->op;
  805. pSubParse->nQueryLoop = pParse->nQueryLoop;
  806. v = sqlite3GetVdbe(pSubParse);
  807. if( v ){
  808. VdbeComment((v, "Start: %s.%s (%s %s%s%s ON %s)",
  809. pTrigger->zName, onErrorText(orconf),
  810. (pTrigger->tr_tm==TRIGGER_BEFORE ? "BEFORE" : "AFTER"),
  811. (pTrigger->op==TK_UPDATE ? "UPDATE" : ""),
  812. (pTrigger->op==TK_INSERT ? "INSERT" : ""),
  813. (pTrigger->op==TK_DELETE ? "DELETE" : ""),
  814. pTab->zName
  815. ));
  816. #ifndef SQLITE_OMIT_TRACE
  817. sqlite3VdbeChangeP4(v, -1,
  818. sqlite3MPrintf(db, "-- TRIGGER %s", pTrigger->zName), P4_DYNAMIC
  819. );
  820. #endif
  821. /* If one was specified, code the WHEN clause. If it evaluates to false
  822. ** (or NULL) the sub-vdbe is immediately halted by jumping to the
  823. ** OP_Halt inserted at the end of the program. */
  824. if( pTrigger->pWhen ){
  825. pWhen = sqlite3ExprDup(db, pTrigger->pWhen, 0);
  826. if( SQLITE_OK==sqlite3ResolveExprNames(&sNC, pWhen)
  827. && db->mallocFailed==0
  828. ){
  829. iEndTrigger = sqlite3VdbeMakeLabel(v);
  830. sqlite3ExprIfFalse(pSubParse, pWhen, iEndTrigger, SQLITE_JUMPIFNULL);
  831. }
  832. sqlite3ExprDelete(db, pWhen);
  833. }
  834. /* Code the trigger program into the sub-vdbe. */
  835. codeTriggerProgram(pSubParse, pTrigger->step_list, orconf);
  836. /* Insert an OP_Halt at the end of the sub-program. */
  837. if( iEndTrigger ){
  838. sqlite3VdbeResolveLabel(v, iEndTrigger);
  839. }
  840. sqlite3VdbeAddOp0(v, OP_Halt);
  841. VdbeComment((v, "End: %s.%s", pTrigger->zName, onErrorText(orconf)));
  842. transferParseError(pParse, pSubParse);
  843. if( db->mallocFailed==0 ){
  844. pProgram->aOp = sqlite3VdbeTakeOpArray(v, &pProgram->nOp, &pTop->nMaxArg);
  845. }
  846. pProgram->nMem = pSubParse->nMem;
  847. pProgram->nCsr = pSubParse->nTab;
  848. pProgram->nOnce = pSubParse->nOnce;
  849. pProgram->token = (void *)pTrigger;
  850. pPrg->aColmask[0] = pSubParse->oldmask;
  851. pPrg->aColmask[1] = pSubParse->newmask;
  852. sqlite3VdbeDelete(v);
  853. }
  854. assert( !pSubParse->pAinc && !pSubParse->pZombieTab );
  855. assert( !pSubParse->pTriggerPrg && !pSubParse->nMaxArg );
  856. sqlite3StackFree(db, pSubParse);
  857. return pPrg;
  858. }
  859. /*
  860. ** Return a pointer to a TriggerPrg object containing the sub-program for
  861. ** trigger pTrigger with default ON CONFLICT algorithm orconf. If no such
  862. ** TriggerPrg object exists, a new object is allocated and populated before
  863. ** being returned.
  864. */
  865. static TriggerPrg *getRowTrigger(
  866. Parse *pParse, /* Current parse context */
  867. Trigger *pTrigger, /* Trigger to code */
  868. Table *pTab, /* The table trigger pTrigger is attached to */
  869. int orconf /* ON CONFLICT algorithm. */
  870. ){
  871. Parse *pRoot = sqlite3ParseToplevel(pParse);
  872. TriggerPrg *pPrg;
  873. assert( pTrigger->zName==0 || pTab==tableOfTrigger(pTrigger) );
  874. /* It may be that this trigger has already been coded (or is in the
  875. ** process of being coded). If this is the case, then an entry with
  876. ** a matching TriggerPrg.pTrigger field will be present somewhere
  877. ** in the Parse.pTriggerPrg list. Search for such an entry. */
  878. for(pPrg=pRoot->pTriggerPrg;
  879. pPrg && (pPrg->pTrigger!=pTrigger || pPrg->orconf!=orconf);
  880. pPrg=pPrg->pNext
  881. );
  882. /* If an existing TriggerPrg could not be located, create a new one. */
  883. if( !pPrg ){
  884. pPrg = codeRowTrigger(pParse, pTrigger, pTab, orconf);
  885. }
  886. return pPrg;
  887. }
  888. /*
  889. ** Generate code for the trigger program associated with trigger p on
  890. ** table pTab. The reg, orconf and ignoreJump parameters passed to this
  891. ** function are the same as those described in the header function for
  892. ** sqlite3CodeRowTrigger()
  893. */
  894. void sqlite3CodeRowTriggerDirect(
  895. Parse *pParse, /* Parse context */
  896. Trigger *p, /* Trigger to code */
  897. Table *pTab, /* The table to code triggers from */
  898. int reg, /* Reg array containing OLD.* and NEW.* values */
  899. int orconf, /* ON CONFLICT policy */
  900. int ignoreJump /* Instruction to jump to for RAISE(IGNORE) */
  901. ){
  902. Vdbe *v = sqlite3GetVdbe(pParse); /* Main VM */
  903. TriggerPrg *pPrg;
  904. pPrg = getRowTrigger(pParse, p, pTab, orconf);
  905. assert( pPrg || pParse->nErr || pParse->db->mallocFailed );
  906. /* Code the OP_Program opcode in the parent VDBE. P4 of the OP_Program
  907. ** is a pointer to the sub-vdbe containing the trigger program. */
  908. if( pPrg ){
  909. int bRecursive = (p->zName && 0==(pParse->db->flags&SQLITE_RecTriggers));
  910. sqlite3VdbeAddOp3(v, OP_Program, reg, ignoreJump, ++pParse->nMem);
  911. sqlite3VdbeChangeP4(v, -1, (const char *)pPrg->pProgram, P4_SUBPROGRAM);
  912. VdbeComment(
  913. (v, "Call: %s.%s", (p->zName?p->zName:"fkey"), onErrorText(orconf)));
  914. /* Set the P5 operand of the OP_Program instruction to non-zero if
  915. ** recursive invocation of this trigger program is disallowed. Recursive
  916. ** invocation is disallowed if (a) the sub-program is really a trigger,
  917. ** not a foreign key action, and (b) the flag to enable recursive triggers
  918. ** is clear. */
  919. sqlite3VdbeChangeP5(v, (u8)bRecursive);
  920. }
  921. }
  922. /*
  923. ** This is called to code the required FOR EACH ROW triggers for an operation
  924. ** on table pTab. The operation to code triggers for (INSERT, UPDATE or DELETE)
  925. ** is given by the op parameter. The tr_tm parameter determines whether the
  926. ** BEFORE or AFTER triggers are coded. If the operation is an UPDATE, then
  927. ** parameter pChanges is passed the list of columns being modified.
  928. **
  929. ** If there are no triggers that fire at the specified time for the specified
  930. ** operation on pTab, this function is a no-op.
  931. **
  932. ** The reg argument is the address of the first in an array of registers
  933. ** that contain the values substituted for the new.* and old.* references
  934. ** in the trigger program. If N is the number of columns in table pTab
  935. ** (a copy of pTab->nCol), then registers are populated as follows:
  936. **
  937. ** Register Contains
  938. ** ------------------------------------------------------
  939. ** reg+0 OLD.rowid
  940. ** reg+1 OLD.* value of left-most column of pTab
  941. ** ... ...
  942. ** reg+N OLD.* value of right-most column of pTab
  943. ** reg+N+1 NEW.rowid
  944. ** reg+N+2 OLD.* value of left-most column of pTab
  945. ** ... ...
  946. ** reg+N+N+1 NEW.* value of right-most column of pTab
  947. **
  948. ** For ON DELETE triggers, the registers containing the NEW.* values will
  949. ** never be accessed by the trigger program, so they are not allocated or
  950. ** populated by the caller (there is no data to populate them with anyway).
  951. ** Similarly, for ON INSERT triggers the values stored in the OLD.* registers
  952. ** are never accessed, and so are not allocated by the caller. So, for an
  953. ** ON INSERT trigger, the value passed to this function as parameter reg
  954. ** is not a readable register, although registers (reg+N) through
  955. ** (reg+N+N+1) are.
  956. **
  957. ** Parameter orconf is the default conflict resolution algorithm for the
  958. ** trigger program to use (REPLACE, IGNORE etc.). Parameter ignoreJump
  959. ** is the instruction that control should jump to if a trigger program
  960. ** raises an IGNORE exception.
  961. */
  962. void sqlite3CodeRowTrigger(
  963. Parse *pParse, /* Parse context */
  964. Trigger *pTrigger, /* List of triggers on table pTab */
  965. int op, /* One of TK_UPDATE, TK_INSERT, TK_DELETE */
  966. ExprList *pChanges, /* Changes list for any UPDATE OF triggers */
  967. int tr_tm, /* One of TRIGGER_BEFORE, TRIGGER_AFTER */
  968. Table *pTab, /* The table to code triggers from */
  969. int reg, /* The first in an array of registers (see above) */
  970. int orconf, /* ON CONFLICT policy */
  971. int ignoreJump /* Instruction to jump to for RAISE(IGNORE) */
  972. ){
  973. Trigger *p; /* Used to iterate through pTrigger list */
  974. assert( op==TK_UPDATE || op==TK_INSERT || op==TK_DELETE );
  975. assert( tr_tm==TRIGGER_BEFORE || tr_tm==TRIGGER_AFTER );
  976. assert( (op==TK_UPDATE)==(pChanges!=0) );
  977. for(p=pTrigger; p; p=p->pNext){
  978. /* Sanity checking: The schema for the trigger and for the table are
  979. ** always defined. The trigger must be in the same schema as the table
  980. ** or else it must be a TEMP trigger. */
  981. assert( p->pSchema!=0 );
  982. assert( p->pTabSchema!=0 );
  983. assert( p->pSchema==p->pTabSchema
  984. || p->pSchema==pParse->db->aDb[1].pSchema );
  985. /* Determine whether we should code this trigger */
  986. if( p->op==op
  987. && p->tr_tm==tr_tm
  988. && checkColumnOverlap(p->pColumns, pChanges)
  989. ){
  990. sqlite3CodeRowTriggerDirect(pParse, p, pTab, reg, orconf, ignoreJump);
  991. }
  992. }
  993. }
  994. /*
  995. ** Triggers may access values stored in the old.* or new.* pseudo-table.
  996. ** This function returns a 32-bit bitmask indicating which columns of the
  997. ** old.* or new.* tables actually are used by triggers. This information
  998. ** may be used by the caller, for example, to avoid having to load the entire
  999. ** old.* record into memory when executing an UPDATE or DELETE command.
  1000. **
  1001. ** Bit 0 of the returned mask is set if the left-most column of the
  1002. ** table may be accessed using an [old|new].<col> reference. Bit 1 is set if
  1003. ** the second leftmost column value is required, and so on. If there
  1004. ** are more than 32 columns in the table, and at least one of the columns
  1005. ** with an index greater than 32 may be accessed, 0xffffffff is returned.
  1006. **
  1007. ** It is not possible to determine if the old.rowid or new.rowid column is
  1008. ** accessed by triggers. The caller must always assume that it is.
  1009. **
  1010. ** Parameter isNew must be either 1 or 0. If it is 0, then the mask returned
  1011. ** applies to the old.* table. If 1, the new.* table.
  1012. **
  1013. ** Parameter tr_tm must be a mask with one or both of the TRIGGER_BEFORE
  1014. ** and TRIGGER_AFTER bits set. Values accessed by BEFORE triggers are only
  1015. ** included in the returned mask if the TRIGGER_BEFORE bit is set in the
  1016. ** tr_tm parameter. Similarly, values accessed by AFTER triggers are only
  1017. ** included in the returned mask if the TRIGGER_AFTER bit is set in tr_tm.
  1018. */
  1019. u32 sqlite3TriggerColmask(
  1020. Parse *pParse, /* Parse context */
  1021. Trigger *pTrigger, /* List of triggers on table pTab */
  1022. ExprList *pChanges, /* Changes list for any UPDATE OF triggers */
  1023. int isNew, /* 1 for new.* ref mask, 0 for old.* ref mask */
  1024. int tr_tm, /* Mask of TRIGGER_BEFORE|TRIGGER_AFTER */
  1025. Table *pTab, /* The table to code triggers from */
  1026. int orconf /* Default ON CONFLICT policy for trigger steps */
  1027. ){
  1028. const int op = pChanges ? TK_UPDATE : TK_DELETE;
  1029. u32 mask = 0;
  1030. Trigger *p;
  1031. assert( isNew==1 || isNew==0 );
  1032. for(p=pTrigger; p; p=p->pNext){
  1033. if( p->op==op && (tr_tm&p->tr_tm)
  1034. && checkColumnOverlap(p->pColumns,pChanges)
  1035. ){
  1036. TriggerPrg *pPrg;
  1037. pPrg = getRowTrigger(pParse, p, pTab, orconf);
  1038. if( pPrg ){
  1039. mask |= pPrg->aColmask[isNew];
  1040. }
  1041. }
  1042. }
  1043. return mask;
  1044. }
  1045. #endif /* !defined(SQLITE_OMIT_TRIGGER) */