Back to index

lightning-sunbird  0.9+nobinonly
trigger.c
Go to the documentation of this file.
00001 /*
00002 **
00003 ** The author disclaims copyright to this source code.  In place of
00004 ** a legal notice, here is a blessing:
00005 **
00006 **    May you do good and not evil.
00007 **    May you find forgiveness for yourself and forgive others.
00008 **    May you share freely, never taking more than you give.
00009 **
00010 *************************************************************************
00011 *
00012 */
00013 #include "sqliteInt.h"
00014 
00015 #ifndef SQLITE_OMIT_TRIGGER
00016 /*
00017 ** Delete a linked list of TriggerStep structures.
00018 */
00019 void sqlite3DeleteTriggerStep(TriggerStep *pTriggerStep){
00020   while( pTriggerStep ){
00021     TriggerStep * pTmp = pTriggerStep;
00022     pTriggerStep = pTriggerStep->pNext;
00023 
00024     if( pTmp->target.dyn ) sqliteFree((char*)pTmp->target.z);
00025     sqlite3ExprDelete(pTmp->pWhere);
00026     sqlite3ExprListDelete(pTmp->pExprList);
00027     sqlite3SelectDelete(pTmp->pSelect);
00028     sqlite3IdListDelete(pTmp->pIdList);
00029 
00030     sqliteFree(pTmp);
00031   }
00032 }
00033 
00034 /*
00035 ** This is called by the parser when it sees a CREATE TRIGGER statement
00036 ** up to the point of the BEGIN before the trigger actions.  A Trigger
00037 ** structure is generated based on the information available and stored
00038 ** in pParse->pNewTrigger.  After the trigger actions have been parsed, the
00039 ** sqlite3FinishTrigger() function is called to complete the trigger
00040 ** construction process.
00041 */
00042 void sqlite3BeginTrigger(
00043   Parse *pParse,      /* The parse context of the CREATE TRIGGER statement */
00044   Token *pName1,      /* The name of the trigger */
00045   Token *pName2,      /* The name of the trigger */
00046   int tr_tm,          /* One of TK_BEFORE, TK_AFTER, TK_INSTEAD */
00047   int op,             /* One of TK_INSERT, TK_UPDATE, TK_DELETE */
00048   IdList *pColumns,   /* column list if this is an UPDATE OF trigger */
00049   SrcList *pTableName,/* The name of the table/view the trigger applies to */
00050   int foreach,        /* One of TK_ROW or TK_STATEMENT */
00051   Expr *pWhen,        /* WHEN clause */
00052   int isTemp          /* True if the TEMPORARY keyword is present */
00053 ){
00054   Trigger *pTrigger = 0;
00055   Table *pTab;
00056   char *zName = 0;        /* Name of the trigger */
00057   sqlite3 *db = pParse->db;
00058   int iDb;                /* The database to store the trigger in */
00059   Token *pName;           /* The unqualified db name */
00060   DbFixer sFix;
00061   int iTabDb;
00062 
00063   assert( pName1!=0 );   /* pName1->z might be NULL, but not pName1 itself */
00064   assert( pName2!=0 );
00065   if( isTemp ){
00066     /* If TEMP was specified, then the trigger name may not be qualified. */
00067     if( pName2->n>0 ){
00068       sqlite3ErrorMsg(pParse, "temporary trigger may not have qualified name");
00069       goto trigger_cleanup;
00070     }
00071     iDb = 1;
00072     pName = pName1;
00073   }else{
00074     /* Figure out the db that the the trigger will be created in */
00075     iDb = sqlite3TwoPartName(pParse, pName1, pName2, &pName);
00076     if( iDb<0 ){
00077       goto trigger_cleanup;
00078     }
00079   }
00080 
00081   /* If the trigger name was unqualified, and the table is a temp table,
00082   ** then set iDb to 1 to create the trigger in the temporary database.
00083   ** If sqlite3SrcListLookup() returns 0, indicating the table does not
00084   ** exist, the error is caught by the block below.
00085   */
00086   if( !pTableName || sqlite3MallocFailed() ){
00087     goto trigger_cleanup;
00088   }
00089   pTab = sqlite3SrcListLookup(pParse, pTableName);
00090   if( pName2->n==0 && pTab && pTab->pSchema==db->aDb[1].pSchema ){
00091     iDb = 1;
00092   }
00093 
00094   /* Ensure the table name matches database name and that the table exists */
00095   if( sqlite3MallocFailed() ) goto trigger_cleanup;
00096   assert( pTableName->nSrc==1 );
00097   if( sqlite3FixInit(&sFix, pParse, iDb, "trigger", pName) && 
00098       sqlite3FixSrcList(&sFix, pTableName) ){
00099     goto trigger_cleanup;
00100   }
00101   pTab = sqlite3SrcListLookup(pParse, pTableName);
00102   if( !pTab ){
00103     /* The table does not exist. */
00104     goto trigger_cleanup;
00105   }
00106 
00107   /* Check that the trigger name is not reserved and that no trigger of the
00108   ** specified name exists */
00109   zName = sqlite3NameFromToken(pName);
00110   if( !zName || SQLITE_OK!=sqlite3CheckObjectName(pParse, zName) ){
00111     goto trigger_cleanup;
00112   }
00113   if( sqlite3HashFind(&(db->aDb[iDb].pSchema->trigHash), zName,strlen(zName)) ){
00114     sqlite3ErrorMsg(pParse, "trigger %T already exists", pName);
00115     goto trigger_cleanup;
00116   }
00117 
00118   /* Do not create a trigger on a system table */
00119   if( sqlite3StrNICmp(pTab->zName, "sqlite_", 7)==0 ){
00120     sqlite3ErrorMsg(pParse, "cannot create trigger on system table");
00121     pParse->nErr++;
00122     goto trigger_cleanup;
00123   }
00124 
00125   /* INSTEAD of triggers are only for views and views only support INSTEAD
00126   ** of triggers.
00127   */
00128   if( pTab->pSelect && tr_tm!=TK_INSTEAD ){
00129     sqlite3ErrorMsg(pParse, "cannot create %s trigger on view: %S", 
00130         (tr_tm == TK_BEFORE)?"BEFORE":"AFTER", pTableName, 0);
00131     goto trigger_cleanup;
00132   }
00133   if( !pTab->pSelect && tr_tm==TK_INSTEAD ){
00134     sqlite3ErrorMsg(pParse, "cannot create INSTEAD OF"
00135         " trigger on table: %S", pTableName, 0);
00136     goto trigger_cleanup;
00137   }
00138   iTabDb = sqlite3SchemaToIndex(db, pTab->pSchema);
00139 
00140 #ifndef SQLITE_OMIT_AUTHORIZATION
00141   {
00142     int code = SQLITE_CREATE_TRIGGER;
00143     const char *zDb = db->aDb[iTabDb].zName;
00144     const char *zDbTrig = isTemp ? db->aDb[1].zName : zDb;
00145     if( iTabDb==1 || isTemp ) code = SQLITE_CREATE_TEMP_TRIGGER;
00146     if( sqlite3AuthCheck(pParse, code, zName, pTab->zName, zDbTrig) ){
00147       goto trigger_cleanup;
00148     }
00149     if( sqlite3AuthCheck(pParse, SQLITE_INSERT, SCHEMA_TABLE(iTabDb),0,zDb)){
00150       goto trigger_cleanup;
00151     }
00152   }
00153 #endif
00154 
00155   /* INSTEAD OF triggers can only appear on views and BEFORE triggers
00156   ** cannot appear on views.  So we might as well translate every
00157   ** INSTEAD OF trigger into a BEFORE trigger.  It simplifies code
00158   ** elsewhere.
00159   */
00160   if (tr_tm == TK_INSTEAD){
00161     tr_tm = TK_BEFORE;
00162   }
00163 
00164   /* Build the Trigger object */
00165   pTrigger = (Trigger*)sqliteMalloc(sizeof(Trigger));
00166   if( pTrigger==0 ) goto trigger_cleanup;
00167   pTrigger->name = zName;
00168   zName = 0;
00169   pTrigger->table = sqliteStrDup(pTableName->a[0].zName);
00170   pTrigger->pSchema = db->aDb[iDb].pSchema;
00171   pTrigger->pTabSchema = pTab->pSchema;
00172   pTrigger->op = op;
00173   pTrigger->tr_tm = tr_tm==TK_BEFORE ? TRIGGER_BEFORE : TRIGGER_AFTER;
00174   pTrigger->pWhen = sqlite3ExprDup(pWhen);
00175   pTrigger->pColumns = sqlite3IdListDup(pColumns);
00176   pTrigger->foreach = foreach;
00177   sqlite3TokenCopy(&pTrigger->nameToken,pName);
00178   assert( pParse->pNewTrigger==0 );
00179   pParse->pNewTrigger = pTrigger;
00180 
00181 trigger_cleanup:
00182   sqliteFree(zName);
00183   sqlite3SrcListDelete(pTableName);
00184   sqlite3IdListDelete(pColumns);
00185   sqlite3ExprDelete(pWhen);
00186   if( !pParse->pNewTrigger ){
00187     sqlite3DeleteTrigger(pTrigger);
00188   }else{
00189     assert( pParse->pNewTrigger==pTrigger );
00190   }
00191 }
00192 
00193 /*
00194 ** This routine is called after all of the trigger actions have been parsed
00195 ** in order to complete the process of building the trigger.
00196 */
00197 void sqlite3FinishTrigger(
00198   Parse *pParse,          /* Parser context */
00199   TriggerStep *pStepList, /* The triggered program */
00200   Token *pAll             /* Token that describes the complete CREATE TRIGGER */
00201 ){
00202   Trigger *pTrig = 0;     /* The trigger whose construction is finishing up */
00203   sqlite3 *db = pParse->db;  /* The database */
00204   DbFixer sFix;
00205   int iDb;                   /* Database containing the trigger */
00206 
00207   pTrig = pParse->pNewTrigger;
00208   pParse->pNewTrigger = 0;
00209   if( pParse->nErr || !pTrig ) goto triggerfinish_cleanup;
00210   iDb = sqlite3SchemaToIndex(pParse->db, pTrig->pSchema);
00211   pTrig->step_list = pStepList;
00212   while( pStepList ){
00213     pStepList->pTrig = pTrig;
00214     pStepList = pStepList->pNext;
00215   }
00216   if( sqlite3FixInit(&sFix, pParse, iDb, "trigger", &pTrig->nameToken) 
00217           && sqlite3FixTriggerStep(&sFix, pTrig->step_list) ){
00218     goto triggerfinish_cleanup;
00219   }
00220 
00221   /* if we are not initializing, and this trigger is not on a TEMP table, 
00222   ** build the sqlite_master entry
00223   */
00224   if( !db->init.busy ){
00225     static const VdbeOpList insertTrig[] = {
00226       { OP_NewRowid,   0, 0,  0          },
00227       { OP_String8,    0, 0,  "trigger"  },
00228       { OP_String8,    0, 0,  0          },  /* 2: trigger name */
00229       { OP_String8,    0, 0,  0          },  /* 3: table name */
00230       { OP_Integer,    0, 0,  0          },
00231       { OP_String8,    0, 0,  "CREATE TRIGGER "},
00232       { OP_String8,    0, 0,  0          },  /* 6: SQL */
00233       { OP_Concat,     0, 0,  0          }, 
00234       { OP_MakeRecord, 5, 0,  "aaada"    },
00235       { OP_Insert,     0, 0,  0          },
00236     };
00237     int addr;
00238     Vdbe *v;
00239 
00240     /* Make an entry in the sqlite_master table */
00241     v = sqlite3GetVdbe(pParse);
00242     if( v==0 ) goto triggerfinish_cleanup;
00243     sqlite3BeginWriteOperation(pParse, 0, iDb);
00244     sqlite3OpenMasterTable(pParse, iDb);
00245     addr = sqlite3VdbeAddOpList(v, ArraySize(insertTrig), insertTrig);
00246     sqlite3VdbeChangeP3(v, addr+2, pTrig->name, 0); 
00247     sqlite3VdbeChangeP3(v, addr+3, pTrig->table, 0); 
00248     sqlite3VdbeChangeP3(v, addr+6, (char*)pAll->z, pAll->n);
00249     sqlite3ChangeCookie(db, v, iDb);
00250     sqlite3VdbeAddOp(v, OP_Close, 0, 0);
00251     sqlite3VdbeOp3(v, OP_ParseSchema, iDb, 0, 
00252        sqlite3MPrintf("type='trigger' AND name='%q'", pTrig->name), P3_DYNAMIC);
00253   }
00254 
00255   if( db->init.busy ){
00256     int n;
00257     Table *pTab;
00258     Trigger *pDel;
00259     pDel = sqlite3HashInsert(&db->aDb[iDb].pSchema->trigHash, 
00260                      pTrig->name, strlen(pTrig->name), pTrig);
00261     if( pDel ){
00262       assert( sqlite3MallocFailed() && pDel==pTrig );
00263       goto triggerfinish_cleanup;
00264     }
00265     n = strlen(pTrig->table) + 1;
00266     pTab = sqlite3HashFind(&pTrig->pTabSchema->tblHash, pTrig->table, n);
00267     assert( pTab!=0 );
00268     pTrig->pNext = pTab->pTrigger;
00269     pTab->pTrigger = pTrig;
00270     pTrig = 0;
00271   }
00272 
00273 triggerfinish_cleanup:
00274   sqlite3DeleteTrigger(pTrig);
00275   assert( !pParse->pNewTrigger );
00276   sqlite3DeleteTriggerStep(pStepList);
00277 }
00278 
00279 /*
00280 ** Make a copy of all components of the given trigger step.  This has
00281 ** the effect of copying all Expr.token.z values into memory obtained
00282 ** from sqliteMalloc().  As initially created, the Expr.token.z values
00283 ** all point to the input string that was fed to the parser.  But that
00284 ** string is ephemeral - it will go away as soon as the sqlite3_exec()
00285 ** call that started the parser exits.  This routine makes a persistent
00286 ** copy of all the Expr.token.z strings so that the TriggerStep structure
00287 ** will be valid even after the sqlite3_exec() call returns.
00288 */
00289 static void sqlitePersistTriggerStep(TriggerStep *p){
00290   if( p->target.z ){
00291     p->target.z = (u8*)sqliteStrNDup((char*)p->target.z, p->target.n);
00292     p->target.dyn = 1;
00293   }
00294   if( p->pSelect ){
00295     Select *pNew = sqlite3SelectDup(p->pSelect);
00296     sqlite3SelectDelete(p->pSelect);
00297     p->pSelect = pNew;
00298   }
00299   if( p->pWhere ){
00300     Expr *pNew = sqlite3ExprDup(p->pWhere);
00301     sqlite3ExprDelete(p->pWhere);
00302     p->pWhere = pNew;
00303   }
00304   if( p->pExprList ){
00305     ExprList *pNew = sqlite3ExprListDup(p->pExprList);
00306     sqlite3ExprListDelete(p->pExprList);
00307     p->pExprList = pNew;
00308   }
00309   if( p->pIdList ){
00310     IdList *pNew = sqlite3IdListDup(p->pIdList);
00311     sqlite3IdListDelete(p->pIdList);
00312     p->pIdList = pNew;
00313   }
00314 }
00315 
00316 /*
00317 ** Turn a SELECT statement (that the pSelect parameter points to) into
00318 ** a trigger step.  Return a pointer to a TriggerStep structure.
00319 **
00320 ** The parser calls this routine when it finds a SELECT statement in
00321 ** body of a TRIGGER.  
00322 */
00323 TriggerStep *sqlite3TriggerSelectStep(Select *pSelect){
00324   TriggerStep *pTriggerStep = sqliteMalloc(sizeof(TriggerStep));
00325   if( pTriggerStep==0 ) {
00326     sqlite3SelectDelete(pSelect);
00327     return 0;
00328   }
00329 
00330   pTriggerStep->op = TK_SELECT;
00331   pTriggerStep->pSelect = pSelect;
00332   pTriggerStep->orconf = OE_Default;
00333   sqlitePersistTriggerStep(pTriggerStep);
00334 
00335   return pTriggerStep;
00336 }
00337 
00338 /*
00339 ** Build a trigger step out of an INSERT statement.  Return a pointer
00340 ** to the new trigger step.
00341 **
00342 ** The parser calls this routine when it sees an INSERT inside the
00343 ** body of a trigger.
00344 */
00345 TriggerStep *sqlite3TriggerInsertStep(
00346   Token *pTableName,  /* Name of the table into which we insert */
00347   IdList *pColumn,    /* List of columns in pTableName to insert into */
00348   ExprList *pEList,   /* The VALUE clause: a list of values to be inserted */
00349   Select *pSelect,    /* A SELECT statement that supplies values */
00350   int orconf          /* The conflict algorithm (OE_Abort, OE_Replace, etc.) */
00351 ){
00352   TriggerStep *pTriggerStep = sqliteMalloc(sizeof(TriggerStep));
00353 
00354   assert(pEList == 0 || pSelect == 0);
00355   assert(pEList != 0 || pSelect != 0);
00356 
00357   if( pTriggerStep ){
00358     pTriggerStep->op = TK_INSERT;
00359     pTriggerStep->pSelect = pSelect;
00360     pTriggerStep->target  = *pTableName;
00361     pTriggerStep->pIdList = pColumn;
00362     pTriggerStep->pExprList = pEList;
00363     pTriggerStep->orconf = orconf;
00364     sqlitePersistTriggerStep(pTriggerStep);
00365   }else{
00366     sqlite3IdListDelete(pColumn);
00367     sqlite3ExprListDelete(pEList);
00368     sqlite3SelectDup(pSelect);
00369   }
00370 
00371   return pTriggerStep;
00372 }
00373 
00374 /*
00375 ** Construct a trigger step that implements an UPDATE statement and return
00376 ** a pointer to that trigger step.  The parser calls this routine when it
00377 ** sees an UPDATE statement inside the body of a CREATE TRIGGER.
00378 */
00379 TriggerStep *sqlite3TriggerUpdateStep(
00380   Token *pTableName,   /* Name of the table to be updated */
00381   ExprList *pEList,    /* The SET clause: list of column and new values */
00382   Expr *pWhere,        /* The WHERE clause */
00383   int orconf           /* The conflict algorithm. (OE_Abort, OE_Ignore, etc) */
00384 ){
00385   TriggerStep *pTriggerStep = sqliteMalloc(sizeof(TriggerStep));
00386   if( pTriggerStep==0 ) return 0;
00387 
00388   pTriggerStep->op = TK_UPDATE;
00389   pTriggerStep->target  = *pTableName;
00390   pTriggerStep->pExprList = pEList;
00391   pTriggerStep->pWhere = pWhere;
00392   pTriggerStep->orconf = orconf;
00393   sqlitePersistTriggerStep(pTriggerStep);
00394 
00395   return pTriggerStep;
00396 }
00397 
00398 /*
00399 ** Construct a trigger step that implements a DELETE statement and return
00400 ** a pointer to that trigger step.  The parser calls this routine when it
00401 ** sees a DELETE statement inside the body of a CREATE TRIGGER.
00402 */
00403 TriggerStep *sqlite3TriggerDeleteStep(Token *pTableName, Expr *pWhere){
00404   TriggerStep *pTriggerStep = sqliteMalloc(sizeof(TriggerStep));
00405   if( pTriggerStep==0 ) return 0;
00406 
00407   pTriggerStep->op = TK_DELETE;
00408   pTriggerStep->target  = *pTableName;
00409   pTriggerStep->pWhere = pWhere;
00410   pTriggerStep->orconf = OE_Default;
00411   sqlitePersistTriggerStep(pTriggerStep);
00412 
00413   return pTriggerStep;
00414 }
00415 
00416 /* 
00417 ** Recursively delete a Trigger structure
00418 */
00419 void sqlite3DeleteTrigger(Trigger *pTrigger){
00420   if( pTrigger==0 ) return;
00421   sqlite3DeleteTriggerStep(pTrigger->step_list);
00422   sqliteFree(pTrigger->name);
00423   sqliteFree(pTrigger->table);
00424   sqlite3ExprDelete(pTrigger->pWhen);
00425   sqlite3IdListDelete(pTrigger->pColumns);
00426   if( pTrigger->nameToken.dyn ) sqliteFree((char*)pTrigger->nameToken.z);
00427   sqliteFree(pTrigger);
00428 }
00429 
00430 /*
00431 ** This function is called to drop a trigger from the database schema. 
00432 **
00433 ** This may be called directly from the parser and therefore identifies
00434 ** the trigger by name.  The sqlite3DropTriggerPtr() routine does the
00435 ** same job as this routine except it takes a pointer to the trigger
00436 ** instead of the trigger name.
00437 **/
00438 void sqlite3DropTrigger(Parse *pParse, SrcList *pName){
00439   Trigger *pTrigger = 0;
00440   int i;
00441   const char *zDb;
00442   const char *zName;
00443   int nName;
00444   sqlite3 *db = pParse->db;
00445 
00446   if( sqlite3MallocFailed() ) goto drop_trigger_cleanup;
00447   if( SQLITE_OK!=sqlite3ReadSchema(pParse) ){
00448     goto drop_trigger_cleanup;
00449   }
00450 
00451   assert( pName->nSrc==1 );
00452   zDb = pName->a[0].zDatabase;
00453   zName = pName->a[0].zName;
00454   nName = strlen(zName);
00455   for(i=OMIT_TEMPDB; i<db->nDb; i++){
00456     int j = (i<2) ? i^1 : i;  /* Search TEMP before MAIN */
00457     if( zDb && sqlite3StrICmp(db->aDb[j].zName, zDb) ) continue;
00458     pTrigger = sqlite3HashFind(&(db->aDb[j].pSchema->trigHash), zName, nName);
00459     if( pTrigger ) break;
00460   }
00461   if( !pTrigger ){
00462     sqlite3ErrorMsg(pParse, "no such trigger: %S", pName, 0);
00463     goto drop_trigger_cleanup;
00464   }
00465   sqlite3DropTriggerPtr(pParse, pTrigger);
00466 
00467 drop_trigger_cleanup:
00468   sqlite3SrcListDelete(pName);
00469 }
00470 
00471 /*
00472 ** Return a pointer to the Table structure for the table that a trigger
00473 ** is set on.
00474 */
00475 static Table *tableOfTrigger(Trigger *pTrigger){
00476   int n = strlen(pTrigger->table) + 1;
00477   return sqlite3HashFind(&pTrigger->pTabSchema->tblHash, pTrigger->table, n);
00478 }
00479 
00480 
00481 /*
00482 ** Drop a trigger given a pointer to that trigger. 
00483 */
00484 void sqlite3DropTriggerPtr(Parse *pParse, Trigger *pTrigger){
00485   Table   *pTable;
00486   Vdbe *v;
00487   sqlite3 *db = pParse->db;
00488   int iDb;
00489 
00490   iDb = sqlite3SchemaToIndex(pParse->db, pTrigger->pSchema);
00491   assert( iDb>=0 && iDb<db->nDb );
00492   pTable = tableOfTrigger(pTrigger);
00493   assert( pTable );
00494   assert( pTable->pSchema==pTrigger->pSchema || iDb==1 );
00495 #ifndef SQLITE_OMIT_AUTHORIZATION
00496   {
00497     int code = SQLITE_DROP_TRIGGER;
00498     const char *zDb = db->aDb[iDb].zName;
00499     const char *zTab = SCHEMA_TABLE(iDb);
00500     if( iDb==1 ) code = SQLITE_DROP_TEMP_TRIGGER;
00501     if( sqlite3AuthCheck(pParse, code, pTrigger->name, pTable->zName, zDb) ||
00502       sqlite3AuthCheck(pParse, SQLITE_DELETE, zTab, 0, zDb) ){
00503       return;
00504     }
00505   }
00506 #endif
00507 
00508   /* Generate code to destroy the database record of the trigger.
00509   */
00510   assert( pTable!=0 );
00511   if( (v = sqlite3GetVdbe(pParse))!=0 ){
00512     int base;
00513     static const VdbeOpList dropTrigger[] = {
00514       { OP_Rewind,     0, ADDR(9),  0},
00515       { OP_String8,    0, 0,        0}, /* 1 */
00516       { OP_Column,     0, 1,        0},
00517       { OP_Ne,         0, ADDR(8),  0},
00518       { OP_String8,    0, 0,        "trigger"},
00519       { OP_Column,     0, 0,        0},
00520       { OP_Ne,         0, ADDR(8),  0},
00521       { OP_Delete,     0, 0,        0},
00522       { OP_Next,       0, ADDR(1),  0}, /* 8 */
00523     };
00524 
00525     sqlite3BeginWriteOperation(pParse, 0, iDb);
00526     sqlite3OpenMasterTable(pParse, iDb);
00527     base = sqlite3VdbeAddOpList(v,  ArraySize(dropTrigger), dropTrigger);
00528     sqlite3VdbeChangeP3(v, base+1, pTrigger->name, 0);
00529     sqlite3ChangeCookie(db, v, iDb);
00530     sqlite3VdbeAddOp(v, OP_Close, 0, 0);
00531     sqlite3VdbeOp3(v, OP_DropTrigger, iDb, 0, pTrigger->name, 0);
00532   }
00533 }
00534 
00535 /*
00536 ** Remove a trigger from the hash tables of the sqlite* pointer.
00537 */
00538 void sqlite3UnlinkAndDeleteTrigger(sqlite3 *db, int iDb, const char *zName){
00539   Trigger *pTrigger;
00540   int nName = strlen(zName);
00541   pTrigger = sqlite3HashInsert(&(db->aDb[iDb].pSchema->trigHash),
00542                                zName, nName, 0);
00543   if( pTrigger ){
00544     Table *pTable = tableOfTrigger(pTrigger);
00545     assert( pTable!=0 );
00546     if( pTable->pTrigger == pTrigger ){
00547       pTable->pTrigger = pTrigger->pNext;
00548     }else{
00549       Trigger *cc = pTable->pTrigger;
00550       while( cc ){ 
00551         if( cc->pNext == pTrigger ){
00552           cc->pNext = cc->pNext->pNext;
00553           break;
00554         }
00555         cc = cc->pNext;
00556       }
00557       assert(cc);
00558     }
00559     sqlite3DeleteTrigger(pTrigger);
00560     db->flags |= SQLITE_InternChanges;
00561   }
00562 }
00563 
00564 /*
00565 ** pEList is the SET clause of an UPDATE statement.  Each entry
00566 ** in pEList is of the format <id>=<expr>.  If any of the entries
00567 ** in pEList have an <id> which matches an identifier in pIdList,
00568 ** then return TRUE.  If pIdList==NULL, then it is considered a
00569 ** wildcard that matches anything.  Likewise if pEList==NULL then
00570 ** it matches anything so always return true.  Return false only
00571 ** if there is no match.
00572 */
00573 static int checkColumnOverLap(IdList *pIdList, ExprList *pEList){
00574   int e;
00575   if( !pIdList || !pEList ) return 1;
00576   for(e=0; e<pEList->nExpr; e++){
00577     if( sqlite3IdListIndex(pIdList, pEList->a[e].zName)>=0 ) return 1;
00578   }
00579   return 0; 
00580 }
00581 
00582 /*
00583 ** Return a bit vector to indicate what kind of triggers exist for operation
00584 ** "op" on table pTab.  If pChanges is not NULL then it is a list of columns
00585 ** that are being updated.  Triggers only match if the ON clause of the
00586 ** trigger definition overlaps the set of columns being updated.
00587 **
00588 ** The returned bit vector is some combination of TRIGGER_BEFORE and
00589 ** TRIGGER_AFTER.
00590 */
00591 int sqlite3TriggersExist(
00592   Parse *pParse,          /* Used to check for recursive triggers */
00593   Table *pTab,            /* The table the contains the triggers */
00594   int op,                 /* one of TK_DELETE, TK_INSERT, TK_UPDATE */
00595   ExprList *pChanges      /* Columns that change in an UPDATE statement */
00596 ){
00597   Trigger *pTrigger = pTab->pTrigger;
00598   int mask = 0;
00599 
00600   while( pTrigger ){
00601     if( pTrigger->op==op && checkColumnOverLap(pTrigger->pColumns, pChanges) ){
00602       mask |= pTrigger->tr_tm;
00603     }
00604     pTrigger = pTrigger->pNext;
00605   }
00606   return mask;
00607 }
00608 
00609 /*
00610 ** Convert the pStep->target token into a SrcList and return a pointer
00611 ** to that SrcList.
00612 **
00613 ** This routine adds a specific database name, if needed, to the target when
00614 ** forming the SrcList.  This prevents a trigger in one database from
00615 ** referring to a target in another database.  An exception is when the
00616 ** trigger is in TEMP in which case it can refer to any other database it
00617 ** wants.
00618 */
00619 static SrcList *targetSrcList(
00620   Parse *pParse,       /* The parsing context */
00621   TriggerStep *pStep   /* The trigger containing the target token */
00622 ){
00623   Token sDb;           /* Dummy database name token */
00624   int iDb;             /* Index of the database to use */
00625   SrcList *pSrc;       /* SrcList to be returned */
00626 
00627   iDb = sqlite3SchemaToIndex(pParse->db, pStep->pTrig->pSchema);
00628   if( iDb==0 || iDb>=2 ){
00629     assert( iDb<pParse->db->nDb );
00630     sDb.z = (u8*)pParse->db->aDb[iDb].zName;
00631     sDb.n = strlen((char*)sDb.z);
00632     pSrc = sqlite3SrcListAppend(0, &sDb, &pStep->target);
00633   } else {
00634     pSrc = sqlite3SrcListAppend(0, &pStep->target, 0);
00635   }
00636   return pSrc;
00637 }
00638 
00639 /*
00640 ** Generate VDBE code for zero or more statements inside the body of a
00641 ** trigger.  
00642 */
00643 static int codeTriggerProgram(
00644   Parse *pParse,            /* The parser context */
00645   TriggerStep *pStepList,   /* List of statements inside the trigger body */
00646   int orconfin              /* Conflict algorithm. (OE_Abort, etc) */  
00647 ){
00648   TriggerStep * pTriggerStep = pStepList;
00649   int orconf;
00650   Vdbe *v = pParse->pVdbe;
00651 
00652   assert( pTriggerStep!=0 );
00653   assert( v!=0 );
00654   sqlite3VdbeAddOp(v, OP_ContextPush, 0, 0);
00655   VdbeComment((v, "# begin trigger %s", pStepList->pTrig->name));
00656   while( pTriggerStep ){
00657     orconf = (orconfin == OE_Default)?pTriggerStep->orconf:orconfin;
00658     pParse->trigStack->orconf = orconf;
00659     switch( pTriggerStep->op ){
00660       case TK_SELECT: {
00661        Select * ss = sqlite3SelectDup(pTriggerStep->pSelect);           
00662        assert(ss);
00663        assert(ss->pSrc);
00664         sqlite3SelectResolve(pParse, ss, 0);
00665        sqlite3Select(pParse, ss, SRT_Discard, 0, 0, 0, 0, 0);
00666        sqlite3SelectDelete(ss);
00667        break;
00668       }
00669       case TK_UPDATE: {
00670         SrcList *pSrc;
00671         pSrc = targetSrcList(pParse, pTriggerStep);
00672         sqlite3VdbeAddOp(v, OP_ResetCount, 0, 0);
00673         sqlite3Update(pParse, pSrc,
00674               sqlite3ExprListDup(pTriggerStep->pExprList), 
00675               sqlite3ExprDup(pTriggerStep->pWhere), orconf);
00676         sqlite3VdbeAddOp(v, OP_ResetCount, 1, 0);
00677         break;
00678       }
00679       case TK_INSERT: {
00680         SrcList *pSrc;
00681         pSrc = targetSrcList(pParse, pTriggerStep);
00682         sqlite3VdbeAddOp(v, OP_ResetCount, 0, 0);
00683         sqlite3Insert(pParse, pSrc,
00684           sqlite3ExprListDup(pTriggerStep->pExprList), 
00685           sqlite3SelectDup(pTriggerStep->pSelect), 
00686           sqlite3IdListDup(pTriggerStep->pIdList), orconf);
00687         sqlite3VdbeAddOp(v, OP_ResetCount, 1, 0);
00688         break;
00689       }
00690       case TK_DELETE: {
00691         SrcList *pSrc;
00692         sqlite3VdbeAddOp(v, OP_ResetCount, 0, 0);
00693         pSrc = targetSrcList(pParse, pTriggerStep);
00694         sqlite3DeleteFrom(pParse, pSrc, sqlite3ExprDup(pTriggerStep->pWhere));
00695         sqlite3VdbeAddOp(v, OP_ResetCount, 1, 0);
00696         break;
00697       }
00698       default:
00699         assert(0);
00700     } 
00701     pTriggerStep = pTriggerStep->pNext;
00702   }
00703   sqlite3VdbeAddOp(v, OP_ContextPop, 0, 0);
00704   VdbeComment((v, "# end trigger %s", pStepList->pTrig->name));
00705 
00706   return 0;
00707 }
00708 
00709 /*
00710 ** This is called to code FOR EACH ROW triggers.
00711 **
00712 ** When the code that this function generates is executed, the following 
00713 ** must be true:
00714 **
00715 ** 1. No cursors may be open in the main database.  (But newIdx and oldIdx
00716 **    can be indices of cursors in temporary tables.  See below.)
00717 **
00718 ** 2. If the triggers being coded are ON INSERT or ON UPDATE triggers, then
00719 **    a temporary vdbe cursor (index newIdx) must be open and pointing at
00720 **    a row containing values to be substituted for new.* expressions in the
00721 **    trigger program(s).
00722 **
00723 ** 3. If the triggers being coded are ON DELETE or ON UPDATE triggers, then
00724 **    a temporary vdbe cursor (index oldIdx) must be open and pointing at
00725 **    a row containing values to be substituted for old.* expressions in the
00726 **    trigger program(s).
00727 **
00728 */
00729 int sqlite3CodeRowTrigger(
00730   Parse *pParse,       /* Parse context */
00731   int op,              /* One of TK_UPDATE, TK_INSERT, TK_DELETE */
00732   ExprList *pChanges,  /* Changes list for any UPDATE OF triggers */
00733   int tr_tm,           /* One of TRIGGER_BEFORE, TRIGGER_AFTER */
00734   Table *pTab,         /* The table to code triggers from */
00735   int newIdx,          /* The indice of the "new" row to access */
00736   int oldIdx,          /* The indice of the "old" row to access */
00737   int orconf,          /* ON CONFLICT policy */
00738   int ignoreJump       /* Instruction to jump to for RAISE(IGNORE) */
00739 ){
00740   Trigger *p;
00741   TriggerStack trigStackEntry;
00742 
00743   assert(op == TK_UPDATE || op == TK_INSERT || op == TK_DELETE);
00744   assert(tr_tm == TRIGGER_BEFORE || tr_tm == TRIGGER_AFTER );
00745 
00746   assert(newIdx != -1 || oldIdx != -1);
00747 
00748   for(p=pTab->pTrigger; p; p=p->pNext){
00749     int fire_this = 0;
00750 
00751     /* Determine whether we should code this trigger */
00752     if( 
00753       p->op==op && 
00754       p->tr_tm==tr_tm && 
00755       (p->pSchema==p->pTabSchema || p->pSchema==pParse->db->aDb[1].pSchema) &&
00756       (op!=TK_UPDATE||!p->pColumns||checkColumnOverLap(p->pColumns,pChanges))
00757     ){
00758       TriggerStack *pS;      /* Pointer to trigger-stack entry */
00759       for(pS=pParse->trigStack; pS && p!=pS->pTrigger; pS=pS->pNext){}
00760       if( !pS ){
00761         fire_this = 1;
00762       }
00763 #if 0    /* Give no warning for recursive triggers.  Just do not do them */
00764       else{
00765         sqlite3ErrorMsg(pParse, "recursive triggers not supported (%s)",
00766             p->name);
00767         return SQLITE_ERROR;
00768       }
00769 #endif
00770     }
00771  
00772     if( fire_this ){
00773       int endTrigger;
00774       Expr * whenExpr;
00775       AuthContext sContext;
00776       NameContext sNC;
00777 
00778       memset(&sNC, 0, sizeof(sNC));
00779       sNC.pParse = pParse;
00780 
00781       /* Push an entry on to the trigger stack */
00782       trigStackEntry.pTrigger = p;
00783       trigStackEntry.newIdx = newIdx;
00784       trigStackEntry.oldIdx = oldIdx;
00785       trigStackEntry.pTab = pTab;
00786       trigStackEntry.pNext = pParse->trigStack;
00787       trigStackEntry.ignoreJump = ignoreJump;
00788       pParse->trigStack = &trigStackEntry;
00789       sqlite3AuthContextPush(pParse, &sContext, p->name);
00790 
00791       /* code the WHEN clause */
00792       endTrigger = sqlite3VdbeMakeLabel(pParse->pVdbe);
00793       whenExpr = sqlite3ExprDup(p->pWhen);
00794       if( sqlite3ExprResolveNames(&sNC, whenExpr) ){
00795         pParse->trigStack = trigStackEntry.pNext;
00796         sqlite3ExprDelete(whenExpr);
00797         return 1;
00798       }
00799       sqlite3ExprIfFalse(pParse, whenExpr, endTrigger, 1);
00800       sqlite3ExprDelete(whenExpr);
00801 
00802       codeTriggerProgram(pParse, p->step_list, orconf); 
00803 
00804       /* Pop the entry off the trigger stack */
00805       pParse->trigStack = trigStackEntry.pNext;
00806       sqlite3AuthContextPop(&sContext);
00807 
00808       sqlite3VdbeResolveLabel(pParse->pVdbe, endTrigger);
00809     }
00810   }
00811   return 0;
00812 }
00813 #endif /* !defined(SQLITE_OMIT_TRIGGER) */