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