/ Check-in [b1d72cb5]
Login

Many hyperlinks are disabled.
Use anonymous login to enable hyperlinks.

Overview
Comment:Stylistic changes to src/trigger.c (partial fix to ticket #39). Also more comments. (CVS 570)
Downloads: Tarball | ZIP archive | SQL archive
Timelines: family | ancestors | descendants | both | trunk
Files: files | file ages | folders
SHA1:b1d72cb5847a9f5f08e40b36ad117b5493232ea7
User & Date: danielk1977 2002-05-17 00:05:59
Context
2002-05-19
23:43
Style fixes to triggers code in various *.c files (partial fix to ticket #39) (CVS 571) check-in: 8a4195c7 user: danielk1977 tags: trunk
2002-05-17
00:05
Stylistic changes to src/trigger.c (partial fix to ticket #39). Also more comments. (CVS 570) check-in: b1d72cb5 user: danielk1977 tags: trunk
2002-05-16
00:13
Fix for ticket #42: Added comments to structs Trigger, TriggerStep and TriggerStack. (CVS 569) check-in: 9ec8a2b1 user: danielk1977 tags: trunk
Changes
Hide Diffs Unified Diffs Ignore Whitespace Patch

Changes to src/trigger.c.

1
2









3
4
5
6
7


8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
...
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
...
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162

163
164




165
166
167
168


169
170
171
172
173
174
175
176
177
178
179
180
181




182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208



209
210
211
212
213

214
215
216


217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235








236
237
238
239
240
241
242
243
244
245
246
247

248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
...
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
...
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360

361

362
363



364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381

382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427

428
429
430
431
432
















433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
...
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
...
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
...
507
508
509
510
511
512
513
514




515
516
517
518










519
520
521
522
523
524
525
...
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578

579
580
581
582
583
584
585
...
598
599
600
601
602
603
604
605
606
607
608
609


610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
/*
** All copyright on this work is disclaimed by the author.









*/
#include "sqliteInt.h"

/*
** This is called by the parser when it sees a CREATE TRIGGER statement


*/
void sqliteCreateTrigger(
  Parse *pParse,      /* The parse context of the CREATE TRIGGER statement */
  Token *nm,          /* The name of the trigger */
  int tr_tm,          /* One of TK_BEFORE, TK_AFTER */
  int op,             /* One of TK_INSERT, TK_UPDATE, TK_DELETE */
  IdList *cols,       /* column list if this is an UPDATE OF trigger */
  Token *tbl,         /* The name of the table/view the trigger applies to */
  int foreach,        /* One of TK_ROW or TK_STATEMENT */
  Expr *pWhen,        /* WHEN clause */
  TriggerStep *steps, /* The triggered program */
  char const *cc,     /* The string data to make persistent */
  int len
){
  Trigger *nt;
  Table   *tab;
  int offset;
  TriggerStep *ss;

  /* Check that: 
  ** 1. the trigger name does not already exist.
  ** 2. the table (or view) does exist.
  */
  {
    char *tmp_str = sqliteStrNDup(nm->z, nm->n);
    if( sqliteHashFind(&(pParse->db->trigHash), tmp_str, nm->n + 1) ){
      sqliteSetNString(&pParse->zErrMsg, "trigger ", -1,
          nm->z, nm->n, " already exists", -1, 0);
      sqliteFree(tmp_str);
      pParse->nErr++;
      goto trigger_cleanup;
    }
    sqliteFree(tmp_str);
  }
  {
    char *tmp_str = sqliteStrNDup(tbl->z, tbl->n);
    tab = sqliteFindTable(pParse->db, tmp_str);
    sqliteFree(tmp_str);
    if( !tab ){
      sqliteSetNString(&pParse->zErrMsg, "no such table: ", -1,
          tbl->z, tbl->n, 0);
      pParse->nErr++;
      goto trigger_cleanup;
    }
  }

  /* Build the Trigger object */
  nt = (Trigger*)sqliteMalloc(sizeof(Trigger));
  nt->name = sqliteStrNDup(nm->z, nm->n);
  nt->table = sqliteStrNDup(tbl->z, tbl->n);
  nt->op = op;
  nt->tr_tm = tr_tm;
  nt->pWhen = pWhen;
  nt->pColumns = cols;
  nt->foreach = foreach;
  nt->step_list = steps;
  nt->isCommit = 0;

  nt->strings = sqliteStrNDup(cc, len);
  offset = (int)(nt->strings - cc);

  sqliteExprMoveStrings(nt->pWhen, offset);

  ss = nt->step_list;
  while (ss) {
    sqliteSelectMoveStrings(ss->pSelect, offset);
    if (ss->target.z) ss->target.z += offset;
................................................................................
    sqliteVdbeAddOp(pParse->pVdbe, OP_SetCookie, 0, 0);

    sqliteVdbeAddOp(pParse->pVdbe,        OP_Close,     0, 0);

    sqliteEndWriteOperation(pParse);
  }

  if (!pParse->explain) {
    /* Stick it in the hash-table */
    sqliteHashInsert(&(pParse->db->trigHash), nt->name, nm->n + 1, nt);

    /* Attach it to the table object */
    nt->pNext = tab->pTrigger;
    tab->pTrigger = nt;
    return;
  } else {
    sqliteFree(nt->strings);
................................................................................
    sqliteFree(nt->name);
    sqliteFree(nt->table);
    sqliteFree(nt);
  }

trigger_cleanup:

  sqliteIdListDelete(cols);
  sqliteExprDelete(pWhen);
  {
    TriggerStep * pp;
    TriggerStep * nn;

    pp = steps;
    while (pp) {
      nn = pp->pNext;
      sqliteExprDelete(pp->pWhere);
      sqliteExprListDelete(pp->pExprList);
      sqliteSelectDelete(pp->pSelect);
      sqliteIdListDelete(pp->pIdList);
      sqliteFree(pp);
      pp = nn;
    }
  }
}

  TriggerStep * 
sqliteTriggerSelectStep(Select * s)
{
  TriggerStep * tt = sqliteMalloc(sizeof(TriggerStep));

  tt->op = TK_SELECT;
  tt->pSelect = s;
  tt->orconf = OE_Default;

  return tt;
}

TriggerStep * 

sqliteTriggerInsertStep(Token * tbl, IdList * col, ExprList * val, Select * s, int orconf)
{




  TriggerStep * tt = sqliteMalloc(sizeof(TriggerStep));

  assert(val == 0 || s == 0);
  assert(val != 0 || s != 0);



  tt->op = TK_INSERT;
  tt->pSelect = s;
  tt->target  = *tbl;
  tt->pIdList = col;
  tt->pExprList = val;
  tt->orconf = orconf;

  return tt;
}

TriggerStep * 
sqliteTriggerUpdateStep(Token * tbl, ExprList * val, Expr * w, int orconf)




{
  TriggerStep * tt = sqliteMalloc(sizeof(TriggerStep));

  tt->op = TK_UPDATE;
  tt->target  = *tbl;
  tt->pExprList = val;
  tt->pWhere = w;
  tt->orconf = orconf;

  return tt;
}

TriggerStep * 
sqliteTriggerDeleteStep(Token * tbl, Expr * w)
{
  TriggerStep * tt = sqliteMalloc(sizeof(TriggerStep));

  tt->op = TK_DELETE;
  tt->target  = *tbl;
  tt->pWhere = w;
  tt->orconf = OE_Default;

  return tt;
}


/* This does a recursive delete of the trigger structure */



void sqliteDeleteTrigger(Trigger * tt)
{
  TriggerStep * ts, * tc;
  ts = tt->step_list;


  while (ts) {
    tc = ts;
    ts = ts->pNext;



    sqliteExprDelete(tc->pWhere);
    sqliteExprListDelete(tc->pExprList);
    sqliteSelectDelete(tc->pSelect);
    sqliteIdListDelete(tc->pIdList);

    sqliteFree(tc);
  }

  sqliteFree(tt->name);
  sqliteFree(tt->table);
  sqliteExprDelete(tt->pWhen);
  sqliteIdListDelete(tt->pColumns);
  sqliteFree(tt->strings);
  sqliteFree(tt);
}

/*
 * "nested" is true if this is begin called as the result of a DROP TABLE








 */
void sqliteDropTrigger(Parse *pParse, Token * trigname, int nested)
{
  char * tmp_name;
  Trigger * trig;
  Table   * tbl;

  tmp_name = sqliteStrNDup(trigname->z, trigname->n);

  /* ensure that the trigger being dropped exists */
  trig = sqliteHashFind(&(pParse->db->trigHash), tmp_name, trigname->n + 1); 
  if (!trig) {

    sqliteSetNString(&pParse->zErrMsg, "no such trigger: ", -1,
        tmp_name, -1, 0);
    sqliteFree(tmp_name);
    return;
  }

  /*
   * If this is not an "explain", do the following:
   * 1. Remove the trigger from its associated table structure
   * 2. Move the trigger from the trigHash hash to trigDrop
   */
  if (!pParse->explain) {
    /* 1 */
    tbl = sqliteFindTable(pParse->db, trig->table);
    assert(tbl);
    if (tbl->pTrigger == trig) 
      tbl->pTrigger = trig->pNext;
    else {
      Trigger * cc = tbl->pTrigger;
      while (cc) {
        if (cc->pNext == trig) {
          cc->pNext = cc->pNext->pNext;
          break;
        }
        cc = cc->pNext;
      }
      assert(cc);
    }

    /* 2 */
    sqliteHashInsert(&(pParse->db->trigHash), tmp_name, 
        trigname->n + 1, NULL);
    sqliteHashInsert(&(pParse->db->trigDrop), trig->name, 
        trigname->n + 1, trig);
  }

  /* Unless this is a trigger on a TEMP TABLE, generate code to destroy the
   * database record of the trigger */
  if (!tbl->isTemp) {
    int base;
    static VdbeOp dropTrigger[] = {
      { OP_OpenWrite,  0, 2,        MASTER_NAME},
      { OP_Rewind,     0, ADDR(9),  0},
      { OP_String,     0, 0,        0}, /* 2 */
      { OP_MemStore,   1, 1,        0},
      { OP_MemLoad,    1, 0,        0}, /* 4 */
................................................................................
    };

    if( !nested ){
      sqliteBeginWriteOperation(pParse);
    }
    base = sqliteVdbeAddOpList(pParse->pVdbe, 
        ArraySize(dropTrigger), dropTrigger);
    sqliteVdbeChangeP3(pParse->pVdbe, base+2, tmp_name, 0);
    if( !nested ){
      sqliteChangeCookie(pParse->db);
    }
    sqliteVdbeChangeP1(pParse->pVdbe, base+9, pParse->db->next_cookie);
    if( !nested ){
      sqliteEndWriteOperation(pParse);
    }
  }

  sqliteFree(tmp_name);
}

static int checkColumnOverLap(IdList * ii, ExprList * ee)
{
  int i, e;
  if (!ii) return 1;
  if (!ee) return 1;

  for (i = 0; i < ii->nId; i++) 
    for (e = 0; e < ee->nExpr; e++) 
      if (!sqliteStrICmp(ii->a[i].zName, ee->a[e].zName))
        return 1;

  return 0; 
}

/* A global variable that is TRUE if we should always set up temp tables for
 * for triggers, even if there are no triggers to code. This is used to test 
................................................................................

/*
 * Returns true if a trigger matching op, tr_tm and foreach that is NOT already
 * on the Parse objects trigger-stack (to prevent recursive trigger firing) is
 * found in the list specified as pTrigger.
 */
int sqliteTriggersExist(
    Parse * pParse, 
    Trigger * pTrigger,
    int op,                 /* one of TK_DELETE, TK_INSERT, TK_UPDATE */
    int tr_tm,              /* one of TK_BEFORE, TK_AFTER */
    int foreach,            /* one of TK_ROW or TK_STATEMENT */
    ExprList * pChanges)
{
  Trigger * tt;

  if (always_code_trigger_setup) return 1;



  tt = pTrigger;
  while (tt) {



    if (tt->op == op && tt->tr_tm == tr_tm && tt->foreach == foreach &&
        checkColumnOverLap(tt->pColumns, pChanges)) {
      TriggerStack * ss;
      ss = pParse->trigStack;
      while (ss && ss->pTrigger != pTrigger) ss = ss->pNext;
      if (!ss) return 1;
    }
    tt = tt->pNext;
  }

  return 0;
}

static int codeTriggerProgram(
        Parse *pParse,
        TriggerStep * program,
        int onError)
{

    TriggerStep * step = program;
    int orconf;

    while (step) {
        int saveNTab = pParse->nTab;
        orconf = (onError == OE_Default)?step->orconf:onError;
        pParse->trigStack->orconf = orconf;
        switch(step->op) {
            case TK_SELECT: {
                int tmp_tbl = pParse->nTab++;
                sqliteVdbeAddOp(pParse->pVdbe, OP_OpenTemp, tmp_tbl, 0);
                sqliteVdbeAddOp(pParse->pVdbe, OP_KeyAsData, tmp_tbl, 1);
                sqliteSelect(pParse, step->pSelect, 
                        SRT_Union, tmp_tbl, 0, 0, 0);
                sqliteVdbeAddOp(pParse->pVdbe, OP_Close, tmp_tbl, 0);
                pParse->nTab--;
                break;
                            }
            case TK_UPDATE: {
                sqliteVdbeAddOp(pParse->pVdbe, OP_PushList, 0, 0);
                sqliteUpdate(pParse, &step->target, 
                        sqliteExprListDup(step->pExprList), 
                        sqliteExprDup(step->pWhere), orconf);
                sqliteVdbeAddOp(pParse->pVdbe, OP_PopList, 0, 0);
                break;
                            }
            case TK_INSERT: {
                sqliteInsert(pParse, &step->target, 
                        sqliteExprListDup(step->pExprList), 
                        sqliteSelectDup(step->pSelect), 
                        sqliteIdListDup(step->pIdList), orconf);
                break;
                            }
            case TK_DELETE: {
                sqliteVdbeAddOp(pParse->pVdbe, OP_PushList, 0, 0);
                sqliteDeleteFrom(pParse, &step->target, 
                        sqliteExprDup(step->pWhere)
                        );
                sqliteVdbeAddOp(pParse->pVdbe, OP_PopList, 0, 0);
                break;
                            }
            default:
                            assert(0);
        } 
        pParse->nTab = saveNTab;
        step = step->pNext;

    }

    return 0;
}

















int sqliteCodeRowTrigger(
        Parse * pParse,  /* Parse context */
        int op,          /* One of TK_UPDATE, TK_INSERT, TK_DELETE */
        ExprList * changes, /* Changes list for any UPDATE OF triggers */
        int tr_tm,       /* One of TK_BEFORE, TK_AFTER */
        Table * tbl,     /* The table to code triggers from */
        int newTable,    /* The indice of the "new" row to access */
        int oldTable,    /* The indice of the "old" row to access */
        int onError)     /* ON CONFLICT policy */
{
  Trigger * pTrigger;
  TriggerStack * pTriggerStack;


  assert(op == TK_UPDATE || op == TK_INSERT || op == TK_DELETE);
  assert(tr_tm == TK_BEFORE || tr_tm == TK_AFTER);

  assert(newTable != -1 || oldTable != -1);

  pTrigger = tbl->pTrigger;
  while (pTrigger) {
    int fire_this = 0;

    /* determine whether we should code this trigger */
    if (pTrigger->op == op && pTrigger->tr_tm == tr_tm && 
        pTrigger->foreach == TK_ROW) {
      fire_this = 1;
      pTriggerStack = pParse->trigStack;
      while (pTriggerStack) {
        if (pTriggerStack->pTrigger == pTrigger) fire_this = 0;
        pTriggerStack = pTriggerStack->pNext;
      }
      if (op == TK_UPDATE && pTrigger->pColumns &&
          !checkColumnOverLap(pTrigger->pColumns, changes))
        fire_this = 0;
    }

    if (fire_this) {
      int endTrigger;
      IdList dummyTablist;
      Expr * whenExpr;
................................................................................

      dummyTablist.nId = 0;
      dummyTablist.a = 0;

      /* Push an entry on to the trigger stack */
      pTriggerStack = sqliteMalloc(sizeof(TriggerStack));
      pTriggerStack->pTrigger = pTrigger;
      pTriggerStack->newIdx = newTable;
      pTriggerStack->oldIdx = oldTable;
      pTriggerStack->pTab = tbl;
      pTriggerStack->pNext = pParse->trigStack;
      pParse->trigStack = pTriggerStack;

      /* code the WHEN clause */
      endTrigger = sqliteVdbeMakeLabel(pParse->pVdbe);
      whenExpr = sqliteExprDup(pTrigger->pWhen);
      if (sqliteExprResolveIds(pParse, 0, &dummyTablist, 0, whenExpr)) {
................................................................................
        sqliteFree(pTriggerStack);
        sqliteExprDelete(whenExpr);
        return 1;
      }
      sqliteExprIfFalse(pParse, whenExpr, endTrigger);
      sqliteExprDelete(whenExpr);

      codeTriggerProgram(pParse, pTrigger->step_list, onError); 

      /* Pop the entry off the trigger stack */
      pParse->trigStack = pParse->trigStack->pNext;
      sqliteFree(pTriggerStack);

      sqliteVdbeResolveLabel(pParse->pVdbe, endTrigger);
    }
................................................................................
    pTrigger = pTrigger->pNext;
  }

  return 0;
}

/*
 * Handle UPDATE and DELETE triggers on views




 */
void sqliteViewTriggers(Parse *pParse, Table *pTab, 
    Expr * pWhere, int onError, ExprList * pChanges)
{










  int oldIdx = -1;
  int newIdx = -1;
  int *aXRef = 0;   
  Vdbe *v;
  int endOfLoop;
  int startOfLoop;
  Select theSelect;
................................................................................
  v = sqliteGetVdbe(pParse);
  assert(v);
  sqliteBeginMultiWriteOperation(pParse);

  /* Allocate temp tables */
  oldIdx = pParse->nTab++;
  sqliteVdbeAddOp(v, OP_OpenTemp, oldIdx, 0);
  if (pChanges) {
    newIdx = pParse->nTab++;
    sqliteVdbeAddOp(v, OP_OpenTemp, newIdx, 0);
  }

  /* Snapshot the view */
  if (sqliteSelect(pParse, &theSelect, SRT_Table, oldIdx, 0, 0, 0)) {
    goto trigger_cleanup;
  }

  /* loop thru the view snapshot, executing triggers for each row */
  endOfLoop = sqliteVdbeMakeLabel(v);
  sqliteVdbeAddOp(v, OP_Rewind, oldIdx, endOfLoop);

  /* Loop thru the view snapshot, executing triggers for each row */
  startOfLoop = sqliteVdbeCurrentAddr(v);

  /* Build the updated row if required */
  if (pChanges) {
    int ii, jj;

    aXRef = sqliteMalloc( sizeof(int) * pTab->nCol );
    if( aXRef==0 ) goto trigger_cleanup;
    for (ii = 0; ii < pTab->nCol; ii++)
      aXRef[ii] = -1;


    for(ii=0; ii<pChanges->nExpr; ii++){
      int jj;
      if( sqliteExprResolveIds(pParse, oldIdx, theSelect.pSrc , 0, 
            pChanges->a[ii].pExpr) )
        goto trigger_cleanup;

................................................................................
        pParse->nErr++;
        goto trigger_cleanup;
      }
    }

    sqliteVdbeAddOp(v, OP_Integer, 13, 0);

    for (ii = 0; ii < pTab->nCol; ii++)
      if( aXRef[ii] < 0 ) 
        sqliteVdbeAddOp(v, OP_Column, oldIdx, ii);
      else
        sqliteExprCode(pParse, pChanges->a[aXRef[ii]].pExpr);



    sqliteVdbeAddOp(v, OP_MakeRecord, pTab->nCol, 0);
    sqliteVdbeAddOp(v, OP_PutIntKey, newIdx, 0);
    sqliteVdbeAddOp(v, OP_Rewind, newIdx, 0);

    sqliteCodeRowTrigger(pParse, TK_UPDATE, pChanges, TK_BEFORE, 
        pTab, newIdx, oldIdx, onError);
    sqliteCodeRowTrigger(pParse, TK_UPDATE, pChanges, TK_AFTER, 
        pTab, newIdx, oldIdx, onError);
  } else {
    sqliteCodeRowTrigger(pParse, TK_DELETE, 0, TK_BEFORE, pTab, -1, oldIdx, 
        onError);
    sqliteCodeRowTrigger(pParse, TK_DELETE, 0, TK_AFTER, pTab, -1, oldIdx, 
        onError);
  }

  sqliteVdbeAddOp(v, OP_Next, oldIdx, startOfLoop);

  sqliteVdbeResolveLabel(v, endOfLoop);
  sqliteEndWriteOperation(pParse);


|
>
>
>
>
>
>
>
>
>




|
>
>



|


|
|


|
|
|











|
|

|







|




|







|
|



|

|


|
|







 







|

|







 







|





|












<
|

|

|
|
|

|


|
>
|
<
>
>
>
>
|

<
<
>
>

|
|
|
|
|
|

|


|
<
>
>
>
>

|

|
|
|
|
|

|


<
|

|

|
|
|
|

|


<
<
>
>
>
|

|
<

>
|
<
<
>
>

|
|
|
|

|


|
|
|
|
|
|



|
>
>
>
>
>
>
>
>

|

|
|
|

|


|
<
>

|
|








|

|
|
|
|
|
|
|
|









|
|
|
|




|







 







|









|


|


|
|

|
|
|







 







|
|
|
|
|
|

|

|
>
|
>
|
<
>
>
>
|
|





|






|
|
|
<
>
|
|

|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
<
|
|
|
|
|
|
|
<
>
|

|


>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>

|
|
|
|
|
|
|
|




<



|

|













|







 







|
|
|







 







|







 







|
>
>
>
>

|
<
<
>
>
>
>
>
>
>
>
>
>







 







|





|











|




|

>







 







|
|

|

>
>






|

|


|

|







1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
...
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
...
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160

161
162
163
164
165
166
167
168
169
170
171
172
173
174

175
176
177
178
179
180


181
182
183
184
185
186
187
188
189
190
191
192
193
194

195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210

211
212
213
214
215
216
217
218
219
220
221
222


223
224
225
226
227
228

229
230
231


232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271

272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
...
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
...
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389

390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409

410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447

448
449
450
451
452
453
454

455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489

490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
...
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
...
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
...
550
551
552
553
554
555
556
557
558
559
560
561
562
563


564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
...
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
...
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
/*
**
** The author disclaims copyright to this source code.  In place of
** a legal notice, here is a blessing:
**
**    May you do good and not evil.
**    May you find forgiveness for yourself and forgive others.
**    May you share freely, never taking more than you give.
**
*************************************************************************
*
*/
#include "sqliteInt.h"

/*
** This is called by the parser when it sees a CREATE TRIGGER statement. See
** comments surrounding struct Trigger in sqliteInt.h for a description of 
** how triggers are stored.
*/
void sqliteCreateTrigger(
  Parse *pParse,      /* The parse context of the CREATE TRIGGER statement */
  Token *pName,       /* The name of the trigger */
  int tr_tm,          /* One of TK_BEFORE, TK_AFTER */
  int op,             /* One of TK_INSERT, TK_UPDATE, TK_DELETE */
  IdList *pColumns,   /* column list if this is an UPDATE OF trigger */
  Token *pTableName,  /* The name of the table/view the trigger applies to */
  int foreach,        /* One of TK_ROW or TK_STATEMENT */
  Expr *pWhen,        /* WHEN clause */
  TriggerStep *pStepList, /* The triggered program */
  char const *zData,  /* The string data to make persistent */
  int zDataLen
){
  Trigger *nt;
  Table   *tab;
  int offset;
  TriggerStep *ss;

  /* Check that: 
  ** 1. the trigger name does not already exist.
  ** 2. the table (or view) does exist.
  */
  {
    char *tmp_str = sqliteStrNDup(pName->z, pName->n);
    if( sqliteHashFind(&(pParse->db->trigHash), tmp_str, pName->n + 1) ){
      sqliteSetNString(&pParse->zErrMsg, "trigger ", -1,
          pName->z, pName->n, " already exists", -1, 0);
      sqliteFree(tmp_str);
      pParse->nErr++;
      goto trigger_cleanup;
    }
    sqliteFree(tmp_str);
  }
  {
    char *tmp_str = sqliteStrNDup(pTableName->z, pTableName->n);
    tab = sqliteFindTable(pParse->db, tmp_str);
    sqliteFree(tmp_str);
    if( !tab ){
      sqliteSetNString(&pParse->zErrMsg, "no such table: ", -1,
          pTableName->z, pTableName->n, 0);
      pParse->nErr++;
      goto trigger_cleanup;
    }
  }

  /* Build the Trigger object */
  nt = (Trigger*)sqliteMalloc(sizeof(Trigger));
  nt->name = sqliteStrNDup(pName->z, pName->n);
  nt->table = sqliteStrNDup(pTableName->z, pTableName->n);
  nt->op = op;
  nt->tr_tm = tr_tm;
  nt->pWhen = pWhen;
  nt->pColumns = pColumns;
  nt->foreach = foreach;
  nt->step_list = pStepList;
  nt->isCommit = 0;

  nt->strings = sqliteStrNDup(zData, zDataLen);
  offset = (int)(nt->strings - zData);

  sqliteExprMoveStrings(nt->pWhen, offset);

  ss = nt->step_list;
  while (ss) {
    sqliteSelectMoveStrings(ss->pSelect, offset);
    if (ss->target.z) ss->target.z += offset;
................................................................................
    sqliteVdbeAddOp(pParse->pVdbe, OP_SetCookie, 0, 0);

    sqliteVdbeAddOp(pParse->pVdbe,        OP_Close,     0, 0);

    sqliteEndWriteOperation(pParse);
  }

  if( !pParse->explain ){
    /* Stick it in the hash-table */
    sqliteHashInsert(&(pParse->db->trigHash), nt->name, pName->n + 1, nt);

    /* Attach it to the table object */
    nt->pNext = tab->pTrigger;
    tab->pTrigger = nt;
    return;
  } else {
    sqliteFree(nt->strings);
................................................................................
    sqliteFree(nt->name);
    sqliteFree(nt->table);
    sqliteFree(nt);
  }

trigger_cleanup:

  sqliteIdListDelete(pColumns);
  sqliteExprDelete(pWhen);
  {
    TriggerStep * pp;
    TriggerStep * nn;

    pp = pStepList;
    while (pp) {
      nn = pp->pNext;
      sqliteExprDelete(pp->pWhere);
      sqliteExprListDelete(pp->pExprList);
      sqliteSelectDelete(pp->pSelect);
      sqliteIdListDelete(pp->pIdList);
      sqliteFree(pp);
      pp = nn;
    }
  }
}


TriggerStep *sqliteTriggerSelectStep(Select * pSelect)
{
  TriggerStep *pTriggerStep = sqliteMalloc(sizeof(TriggerStep));

  pTriggerStep->op = TK_SELECT;
  pTriggerStep->pSelect = pSelect;
  pTriggerStep->orconf = OE_Default;

  return pTriggerStep;
}

TriggerStep *sqliteTriggerInsertStep(
  Token *pTableName,
  IdList *pColumn,

  ExprList *pEList,
  Select *pSelect,
  int orconf
){
  TriggerStep *pTriggerStep = sqliteMalloc(sizeof(TriggerStep));



  assert(pEList == 0 || pSelect == 0);
  assert(pEList != 0 || pSelect != 0);

  pTriggerStep->op = TK_INSERT;
  pTriggerStep->pSelect = pSelect;
  pTriggerStep->target  = *pTableName;
  pTriggerStep->pIdList = pColumn;
  pTriggerStep->pExprList = pEList;
  pTriggerStep->orconf = orconf;

  return pTriggerStep;
}

TriggerStep *sqliteTriggerUpdateStep(

  Token *pTableName, 
  ExprList *pEList, 
  Expr *pWhere, 
  int orconf)
{
  TriggerStep *pTriggerStep = sqliteMalloc(sizeof(TriggerStep));

  pTriggerStep->op = TK_UPDATE;
  pTriggerStep->target  = *pTableName;
  pTriggerStep->pExprList = pEList;
  pTriggerStep->pWhere = pWhere;
  pTriggerStep->orconf = orconf;

  return pTriggerStep;
}


TriggerStep *sqliteTriggerDeleteStep(Token *pTableName, Expr *pWhere)
{
  TriggerStep * pTriggerStep = sqliteMalloc(sizeof(TriggerStep));

  pTriggerStep->op = TK_DELETE;
  pTriggerStep->target  = *pTableName;
  pTriggerStep->pWhere = pWhere;
  pTriggerStep->orconf = OE_Default;

  return pTriggerStep;
}



/* 
** Recursively delete a Trigger structure
*/
void sqliteDeleteTrigger(Trigger *pTrigger)
{
  TriggerStep *pTriggerStep;


  pTriggerStep = pTrigger->step_list;
  while (pTriggerStep) {


    TriggerStep * pTmp = pTriggerStep;
    pTriggerStep = pTriggerStep->pNext;

    sqliteExprDelete(pTmp->pWhere);
    sqliteExprListDelete(pTmp->pExprList);
    sqliteSelectDelete(pTmp->pSelect);
    sqliteIdListDelete(pTmp->pIdList);

    sqliteFree(pTmp);
  }

  sqliteFree(pTrigger->name);
  sqliteFree(pTrigger->table);
  sqliteExprDelete(pTrigger->pWhen);
  sqliteIdListDelete(pTrigger->pColumns);
  sqliteFree(pTrigger->strings);
  sqliteFree(pTrigger);
}

/*
 * This function is called to drop a trigger from the database schema. 
 *
 * This may be called directly from the parser, or from within 
 * sqliteDropTable(). In the latter case the "nested" argument is true.
 *
 * Note that this function does not delete the trigger entirely. Instead it
 * removes it from the internal schema and places it in the trigDrop hash 
 * table. This is so that the trigger can be restored into the database schema
 * if the transaction is rolled back.
 */
void sqliteDropTrigger(Parse *pParse, Token *pName, int nested)
{
  char *zName;
  Trigger *pTrigger;
  Table   *pTable;

  zName = sqliteStrNDup(pName->z, pName->n);

  /* ensure that the trigger being dropped exists */
  pTrigger = sqliteHashFind(&(pParse->db->trigHash), zName, pName->n + 1); 

  if( !pTrigger ){
    sqliteSetNString(&pParse->zErrMsg, "no such trigger: ", -1,
        zName, -1, 0);
    sqliteFree(zName);
    return;
  }

  /*
   * If this is not an "explain", do the following:
   * 1. Remove the trigger from its associated table structure
   * 2. Move the trigger from the trigHash hash to trigDrop
   */
  if( !pParse->explain ){
    /* 1 */
    pTable = sqliteFindTable(pParse->db, pTrigger->table);
    assert(pTable);
    if( pTable->pTrigger == pTrigger ){
      pTable->pTrigger = pTrigger->pNext;
    } else {
      Trigger *cc = pTable->pTrigger;
      while( cc ){ 
        if( cc->pNext == pTrigger ){
          cc->pNext = cc->pNext->pNext;
          break;
        }
        cc = cc->pNext;
      }
      assert(cc);
    }

    /* 2 */
    sqliteHashInsert(&(pParse->db->trigHash), zName, 
        pName->n + 1, NULL);
    sqliteHashInsert(&(pParse->db->trigDrop), pTrigger->name, 
        pName->n + 1, pTrigger);
  }

  /* Unless this is a trigger on a TEMP TABLE, generate code to destroy the
   * database record of the trigger */
  if( !pTable->isTemp ){
    int base;
    static VdbeOp dropTrigger[] = {
      { OP_OpenWrite,  0, 2,        MASTER_NAME},
      { OP_Rewind,     0, ADDR(9),  0},
      { OP_String,     0, 0,        0}, /* 2 */
      { OP_MemStore,   1, 1,        0},
      { OP_MemLoad,    1, 0,        0}, /* 4 */
................................................................................
    };

    if( !nested ){
      sqliteBeginWriteOperation(pParse);
    }
    base = sqliteVdbeAddOpList(pParse->pVdbe, 
        ArraySize(dropTrigger), dropTrigger);
    sqliteVdbeChangeP3(pParse->pVdbe, base+2, zName, 0);
    if( !nested ){
      sqliteChangeCookie(pParse->db);
    }
    sqliteVdbeChangeP1(pParse->pVdbe, base+9, pParse->db->next_cookie);
    if( !nested ){
      sqliteEndWriteOperation(pParse);
    }
  }

  sqliteFree(zName);
}

static int checkColumnOverLap(IdList * pIdList, ExprList * pEList)
{
  int i, e;
  if (!pIdList) return 1;
  if (!pEList) return 1;

  for (i = 0; i < pIdList->nId; i++) 
    for (e = 0; e < pEList->nExpr; e++) 
      if (!sqliteStrICmp(pIdList->a[i].zName, pEList->a[e].zName))
        return 1;

  return 0; 
}

/* A global variable that is TRUE if we should always set up temp tables for
 * for triggers, even if there are no triggers to code. This is used to test 
................................................................................

/*
 * Returns true if a trigger matching op, tr_tm and foreach that is NOT already
 * on the Parse objects trigger-stack (to prevent recursive trigger firing) is
 * found in the list specified as pTrigger.
 */
int sqliteTriggersExist(
  Parse *pParse, 
  Trigger *pTrigger,
  int op,                 /* one of TK_DELETE, TK_INSERT, TK_UPDATE */
  int tr_tm,              /* one of TK_BEFORE, TK_AFTER */
  int foreach,            /* one of TK_ROW or TK_STATEMENT */
  ExprList *pChanges)
{
  Trigger * pTriggerCursor;

  if( always_code_trigger_setup ){
    return 1;
  }

  pTriggerCursor = pTrigger;

  while( pTriggerCursor ){
    if( pTriggerCursor->op == op && 
	pTriggerCursor->tr_tm == tr_tm && 
	pTriggerCursor->foreach == foreach &&
	checkColumnOverLap(pTriggerCursor->pColumns, pChanges) ){
      TriggerStack * ss;
      ss = pParse->trigStack;
      while (ss && ss->pTrigger != pTrigger) ss = ss->pNext;
      if (!ss) return 1;
    }
    pTriggerCursor = pTriggerCursor->pNext;
  }

  return 0;
}

static int codeTriggerProgram(
  Parse *pParse, 
  TriggerStep *pStepList, 
  int orconfin

){
  TriggerStep * pTriggerStep = pStepList;
  int orconf;

  while( pTriggerStep ){
    int saveNTab = pParse->nTab;
    orconf = (orconfin == OE_Default)?pTriggerStep->orconf:orconfin;
    pParse->trigStack->orconf = orconf;
    switch( pTriggerStep->op ){
      case TK_SELECT: {
        int tmp_tbl = pParse->nTab++;
	sqliteVdbeAddOp(pParse->pVdbe, OP_OpenTemp, tmp_tbl, 0);
	sqliteVdbeAddOp(pParse->pVdbe, OP_KeyAsData, tmp_tbl, 1);
	sqliteSelect(pParse, pTriggerStep->pSelect, SRT_Union, 
	    tmp_tbl, 0, 0, 0);
	sqliteVdbeAddOp(pParse->pVdbe, OP_Close, tmp_tbl, 0);
	pParse->nTab--;
	break;
      }
      case TK_UPDATE: {
        sqliteVdbeAddOp(pParse->pVdbe, OP_PushList, 0, 0);
        sqliteUpdate(pParse, &pTriggerStep->target, 
        sqliteExprListDup(pTriggerStep->pExprList), 
        sqliteExprDup(pTriggerStep->pWhere), orconf);
        sqliteVdbeAddOp(pParse->pVdbe, OP_PopList, 0, 0);
        break;
      }
      case TK_INSERT: {
        sqliteInsert(pParse, &pTriggerStep->target, 
        sqliteExprListDup(pTriggerStep->pExprList), 
        sqliteSelectDup(pTriggerStep->pSelect), 
        sqliteIdListDup(pTriggerStep->pIdList), orconf);
        break;
      }
      case TK_DELETE: {
        sqliteVdbeAddOp(pParse->pVdbe, OP_PushList, 0, 0);
        sqliteDeleteFrom(pParse, &pTriggerStep->target, 
	    sqliteExprDup(pTriggerStep->pWhere));

        sqliteVdbeAddOp(pParse->pVdbe, OP_PopList, 0, 0);
        break;
      }
      default:
        assert(0);
    } 
    pParse->nTab = saveNTab;

    pTriggerStep = pTriggerStep->pNext;
  }

  return 0;
}

/*
** This is called to code FOR EACH ROW triggers.
**
** When the code that this function generates is executed, the following 
** must be true:
** 1. NO vdbe cursors must be open.
** 2. If the triggers being coded are ON INSERT or ON UPDATE triggers, then
**    a temporary vdbe cursor (index newIdx) must be open and pointing at
**    a row containing values to be substituted for new.* expressions in the
**    trigger program(s).
** 3. If the triggers being coded are ON DELETE or ON UPDATE triggers, then
**    a temporary vdbe cursor (index oldIdx) must be open and pointing at
**    a row containing values to be substituted for old.* expressions in the
**    trigger program(s).
**
*/
int sqliteCodeRowTrigger(
  Parse *pParse,       /* Parse context */
  int op,              /* One of TK_UPDATE, TK_INSERT, TK_DELETE */
  ExprList *pChanges,  /* Changes list for any UPDATE OF triggers */
  int tr_tm,           /* One of TK_BEFORE, TK_AFTER */
  Table *pTab,         /* The table to code triggers from */
  int newIdx,          /* The indice of the "new" row to access */
  int oldIdx,          /* The indice of the "old" row to access */
  int orconf)          /* ON CONFLICT policy */
{
  Trigger * pTrigger;
  TriggerStack * pTriggerStack;


  assert(op == TK_UPDATE || op == TK_INSERT || op == TK_DELETE);
  assert(tr_tm == TK_BEFORE || tr_tm == TK_AFTER);

  assert(newIdx != -1 || oldIdx != -1);

  pTrigger = pTab->pTrigger;
  while (pTrigger) {
    int fire_this = 0;

    /* determine whether we should code this trigger */
    if (pTrigger->op == op && pTrigger->tr_tm == tr_tm && 
        pTrigger->foreach == TK_ROW) {
      fire_this = 1;
      pTriggerStack = pParse->trigStack;
      while (pTriggerStack) {
        if (pTriggerStack->pTrigger == pTrigger) fire_this = 0;
        pTriggerStack = pTriggerStack->pNext;
      }
      if (op == TK_UPDATE && pTrigger->pColumns &&
          !checkColumnOverLap(pTrigger->pColumns, pChanges))
        fire_this = 0;
    }

    if (fire_this) {
      int endTrigger;
      IdList dummyTablist;
      Expr * whenExpr;
................................................................................

      dummyTablist.nId = 0;
      dummyTablist.a = 0;

      /* Push an entry on to the trigger stack */
      pTriggerStack = sqliteMalloc(sizeof(TriggerStack));
      pTriggerStack->pTrigger = pTrigger;
      pTriggerStack->newIdx = newIdx;
      pTriggerStack->oldIdx = oldIdx;
      pTriggerStack->pTab = pTab;
      pTriggerStack->pNext = pParse->trigStack;
      pParse->trigStack = pTriggerStack;

      /* code the WHEN clause */
      endTrigger = sqliteVdbeMakeLabel(pParse->pVdbe);
      whenExpr = sqliteExprDup(pTrigger->pWhen);
      if (sqliteExprResolveIds(pParse, 0, &dummyTablist, 0, whenExpr)) {
................................................................................
        sqliteFree(pTriggerStack);
        sqliteExprDelete(whenExpr);
        return 1;
      }
      sqliteExprIfFalse(pParse, whenExpr, endTrigger);
      sqliteExprDelete(whenExpr);

      codeTriggerProgram(pParse, pTrigger->step_list, orconf); 

      /* Pop the entry off the trigger stack */
      pParse->trigStack = pParse->trigStack->pNext;
      sqliteFree(pTriggerStack);

      sqliteVdbeResolveLabel(pParse->pVdbe, endTrigger);
    }
................................................................................
    pTrigger = pTrigger->pNext;
  }

  return 0;
}

/*
 * This function is called to code ON UPDATE and ON DELETE triggers on 
 * views. 
 *
 * This function deletes the data pointed at by the pWhere and pChanges
 * arguments before it completes.
 */
void sqliteViewTriggers(


  Parse *pParse, 
  Table *pTab,         /* The view to code triggers on */
  Expr *pWhere,        /* The WHERE clause of the statement causing triggers*/
  int orconf,          /* The ON CONFLICT policy specified as part of the
			  statement causing these triggers */
  ExprList *pChanges   /* If this is an statement causing triggers to fire
			  is an UPDATE, then this list holds the columns
			  to update and the expressions to update them to.
			  See comments for sqliteUpdate(). */
){
  int oldIdx = -1;
  int newIdx = -1;
  int *aXRef = 0;   
  Vdbe *v;
  int endOfLoop;
  int startOfLoop;
  Select theSelect;
................................................................................
  v = sqliteGetVdbe(pParse);
  assert(v);
  sqliteBeginMultiWriteOperation(pParse);

  /* Allocate temp tables */
  oldIdx = pParse->nTab++;
  sqliteVdbeAddOp(v, OP_OpenTemp, oldIdx, 0);
  if( pChanges ){
    newIdx = pParse->nTab++;
    sqliteVdbeAddOp(v, OP_OpenTemp, newIdx, 0);
  }

  /* Snapshot the view */
  if( sqliteSelect(pParse, &theSelect, SRT_Table, oldIdx, 0, 0, 0) ){
    goto trigger_cleanup;
  }

  /* loop thru the view snapshot, executing triggers for each row */
  endOfLoop = sqliteVdbeMakeLabel(v);
  sqliteVdbeAddOp(v, OP_Rewind, oldIdx, endOfLoop);

  /* Loop thru the view snapshot, executing triggers for each row */
  startOfLoop = sqliteVdbeCurrentAddr(v);

  /* Build the updated row if required */
  if( pChanges ){
    int ii, jj;

    aXRef = sqliteMalloc( sizeof(int) * pTab->nCol );
    if( aXRef==0 ) goto trigger_cleanup;
    for(ii = 0; ii < pTab->nCol; ii++){
      aXRef[ii] = -1;
    }

    for(ii=0; ii<pChanges->nExpr; ii++){
      int jj;
      if( sqliteExprResolveIds(pParse, oldIdx, theSelect.pSrc , 0, 
            pChanges->a[ii].pExpr) )
        goto trigger_cleanup;

................................................................................
        pParse->nErr++;
        goto trigger_cleanup;
      }
    }

    sqliteVdbeAddOp(v, OP_Integer, 13, 0);

    for(ii = 0; ii<pTab->nCol; ii++){
      if( aXRef[ii] < 0 ){ 
        sqliteVdbeAddOp(v, OP_Column, oldIdx, ii);
      } else {
        sqliteExprCode(pParse, pChanges->a[aXRef[ii]].pExpr);
      }
    }

    sqliteVdbeAddOp(v, OP_MakeRecord, pTab->nCol, 0);
    sqliteVdbeAddOp(v, OP_PutIntKey, newIdx, 0);
    sqliteVdbeAddOp(v, OP_Rewind, newIdx, 0);

    sqliteCodeRowTrigger(pParse, TK_UPDATE, pChanges, TK_BEFORE, 
        pTab, newIdx, oldIdx, orconf);
    sqliteCodeRowTrigger(pParse, TK_UPDATE, pChanges, TK_AFTER, 
        pTab, newIdx, oldIdx, orconf);
  } else {
    sqliteCodeRowTrigger(pParse, TK_DELETE, 0, TK_BEFORE, pTab, -1, oldIdx, 
        orconf);
    sqliteCodeRowTrigger(pParse, TK_DELETE, 0, TK_AFTER, pTab, -1, oldIdx, 
        orconf);
  }

  sqliteVdbeAddOp(v, OP_Next, oldIdx, startOfLoop);

  sqliteVdbeResolveLabel(v, endOfLoop);
  sqliteEndWriteOperation(pParse);