trigger.c 28 KB

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