delete.c 24 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674
  1. /*
  2. ** 2001 September 15
  3. **
  4. ** The author disclaims copyright to this source code. In place of
  5. ** a legal notice, here is a blessing:
  6. **
  7. ** May you do good and not evil.
  8. ** May you find forgiveness for yourself and forgive others.
  9. ** May you share freely, never taking more than you give.
  10. **
  11. *************************************************************************
  12. ** This file contains C code routines that are called by the parser
  13. ** in order to generate code for DELETE FROM statements.
  14. */
  15. #include "sqliteInt.h"
  16. /*
  17. ** While a SrcList can in general represent multiple tables and subqueries
  18. ** (as in the FROM clause of a SELECT statement) in this case it contains
  19. ** the name of a single table, as one might find in an INSERT, DELETE,
  20. ** or UPDATE statement. Look up that table in the symbol table and
  21. ** return a pointer. Set an error message and return NULL if the table
  22. ** name is not found or if any other error occurs.
  23. **
  24. ** The following fields are initialized appropriate in pSrc:
  25. **
  26. ** pSrc->a[0].pTab Pointer to the Table object
  27. ** pSrc->a[0].pIndex Pointer to the INDEXED BY index, if there is one
  28. **
  29. */
  30. Table *sqlite3SrcListLookup(Parse *pParse, SrcList *pSrc){
  31. struct SrcList_item *pItem = pSrc->a;
  32. Table *pTab;
  33. assert( pItem && pSrc->nSrc==1 );
  34. pTab = sqlite3LocateTableItem(pParse, 0, pItem);
  35. sqlite3DeleteTable(pParse->db, pItem->pTab);
  36. pItem->pTab = pTab;
  37. if( pTab ){
  38. pTab->nRef++;
  39. }
  40. if( sqlite3IndexedByLookup(pParse, pItem) ){
  41. pTab = 0;
  42. }
  43. return pTab;
  44. }
  45. /*
  46. ** Check to make sure the given table is writable. If it is not
  47. ** writable, generate an error message and return 1. If it is
  48. ** writable return 0;
  49. */
  50. int sqlite3IsReadOnly(Parse *pParse, Table *pTab, int viewOk){
  51. /* A table is not writable under the following circumstances:
  52. **
  53. ** 1) It is a virtual table and no implementation of the xUpdate method
  54. ** has been provided, or
  55. ** 2) It is a system table (i.e. sqlite_master), this call is not
  56. ** part of a nested parse and writable_schema pragma has not
  57. ** been specified.
  58. **
  59. ** In either case leave an error message in pParse and return non-zero.
  60. */
  61. if( ( IsVirtual(pTab)
  62. && sqlite3GetVTable(pParse->db, pTab)->pMod->pModule->xUpdate==0 )
  63. || ( (pTab->tabFlags & TF_Readonly)!=0
  64. && (pParse->db->flags & SQLITE_WriteSchema)==0
  65. && pParse->nested==0 )
  66. ){
  67. sqlite3ErrorMsg(pParse, "table %s may not be modified", pTab->zName);
  68. return 1;
  69. }
  70. #ifndef SQLITE_OMIT_VIEW
  71. if( !viewOk && pTab->pSelect ){
  72. sqlite3ErrorMsg(pParse,"cannot modify %s because it is a view",pTab->zName);
  73. return 1;
  74. }
  75. #endif
  76. return 0;
  77. }
  78. #if !defined(SQLITE_OMIT_VIEW) && !defined(SQLITE_OMIT_TRIGGER)
  79. /*
  80. ** Evaluate a view and store its result in an ephemeral table. The
  81. ** pWhere argument is an optional WHERE clause that restricts the
  82. ** set of rows in the view that are to be added to the ephemeral table.
  83. */
  84. void sqlite3MaterializeView(
  85. Parse *pParse, /* Parsing context */
  86. Table *pView, /* View definition */
  87. Expr *pWhere, /* Optional WHERE clause to be added */
  88. int iCur /* Cursor number for ephemerial table */
  89. ){
  90. SelectDest dest;
  91. Select *pSel;
  92. SrcList *pFrom;
  93. sqlite3 *db = pParse->db;
  94. int iDb = sqlite3SchemaToIndex(db, pView->pSchema);
  95. pWhere = sqlite3ExprDup(db, pWhere, 0);
  96. pFrom = sqlite3SrcListAppend(db, 0, 0, 0);
  97. if( pFrom ){
  98. assert( pFrom->nSrc==1 );
  99. pFrom->a[0].zName = sqlite3DbStrDup(db, pView->zName);
  100. pFrom->a[0].zDatabase = sqlite3DbStrDup(db, db->aDb[iDb].zName);
  101. assert( pFrom->a[0].pOn==0 );
  102. assert( pFrom->a[0].pUsing==0 );
  103. }
  104. pSel = sqlite3SelectNew(pParse, 0, pFrom, pWhere, 0, 0, 0, 0, 0, 0);
  105. if( pSel ) pSel->selFlags |= SF_Materialize;
  106. sqlite3SelectDestInit(&dest, SRT_EphemTab, iCur);
  107. sqlite3Select(pParse, pSel, &dest);
  108. sqlite3SelectDelete(db, pSel);
  109. }
  110. #endif /* !defined(SQLITE_OMIT_VIEW) && !defined(SQLITE_OMIT_TRIGGER) */
  111. #if defined(SQLITE_ENABLE_UPDATE_DELETE_LIMIT) && !defined(SQLITE_OMIT_SUBQUERY)
  112. /*
  113. ** Generate an expression tree to implement the WHERE, ORDER BY,
  114. ** and LIMIT/OFFSET portion of DELETE and UPDATE statements.
  115. **
  116. ** DELETE FROM table_wxyz WHERE a<5 ORDER BY a LIMIT 1;
  117. ** \__________________________/
  118. ** pLimitWhere (pInClause)
  119. */
  120. Expr *sqlite3LimitWhere(
  121. Parse *pParse, /* The parser context */
  122. SrcList *pSrc, /* the FROM clause -- which tables to scan */
  123. Expr *pWhere, /* The WHERE clause. May be null */
  124. ExprList *pOrderBy, /* The ORDER BY clause. May be null */
  125. Expr *pLimit, /* The LIMIT clause. May be null */
  126. Expr *pOffset, /* The OFFSET clause. May be null */
  127. char *zStmtType /* Either DELETE or UPDATE. For error messages. */
  128. ){
  129. Expr *pWhereRowid = NULL; /* WHERE rowid .. */
  130. Expr *pInClause = NULL; /* WHERE rowid IN ( select ) */
  131. Expr *pSelectRowid = NULL; /* SELECT rowid ... */
  132. ExprList *pEList = NULL; /* Expression list contaning only pSelectRowid */
  133. SrcList *pSelectSrc = NULL; /* SELECT rowid FROM x ... (dup of pSrc) */
  134. Select *pSelect = NULL; /* Complete SELECT tree */
  135. /* Check that there isn't an ORDER BY without a LIMIT clause.
  136. */
  137. if( pOrderBy && (pLimit == 0) ) {
  138. sqlite3ErrorMsg(pParse, "ORDER BY without LIMIT on %s", zStmtType);
  139. goto limit_where_cleanup_2;
  140. }
  141. /* We only need to generate a select expression if there
  142. ** is a limit/offset term to enforce.
  143. */
  144. if( pLimit == 0 ) {
  145. /* if pLimit is null, pOffset will always be null as well. */
  146. assert( pOffset == 0 );
  147. return pWhere;
  148. }
  149. /* Generate a select expression tree to enforce the limit/offset
  150. ** term for the DELETE or UPDATE statement. For example:
  151. ** DELETE FROM table_a WHERE col1=1 ORDER BY col2 LIMIT 1 OFFSET 1
  152. ** becomes:
  153. ** DELETE FROM table_a WHERE rowid IN (
  154. ** SELECT rowid FROM table_a WHERE col1=1 ORDER BY col2 LIMIT 1 OFFSET 1
  155. ** );
  156. */
  157. pSelectRowid = sqlite3PExpr(pParse, TK_ROW, 0, 0, 0);
  158. if( pSelectRowid == 0 ) goto limit_where_cleanup_2;
  159. pEList = sqlite3ExprListAppend(pParse, 0, pSelectRowid);
  160. if( pEList == 0 ) goto limit_where_cleanup_2;
  161. /* duplicate the FROM clause as it is needed by both the DELETE/UPDATE tree
  162. ** and the SELECT subtree. */
  163. pSelectSrc = sqlite3SrcListDup(pParse->db, pSrc, 0);
  164. if( pSelectSrc == 0 ) {
  165. sqlite3ExprListDelete(pParse->db, pEList);
  166. goto limit_where_cleanup_2;
  167. }
  168. /* generate the SELECT expression tree. */
  169. pSelect = sqlite3SelectNew(pParse,pEList,pSelectSrc,pWhere,0,0,
  170. pOrderBy,0,pLimit,pOffset);
  171. if( pSelect == 0 ) return 0;
  172. /* now generate the new WHERE rowid IN clause for the DELETE/UDPATE */
  173. pWhereRowid = sqlite3PExpr(pParse, TK_ROW, 0, 0, 0);
  174. if( pWhereRowid == 0 ) goto limit_where_cleanup_1;
  175. pInClause = sqlite3PExpr(pParse, TK_IN, pWhereRowid, 0, 0);
  176. if( pInClause == 0 ) goto limit_where_cleanup_1;
  177. pInClause->x.pSelect = pSelect;
  178. pInClause->flags |= EP_xIsSelect;
  179. sqlite3ExprSetHeight(pParse, pInClause);
  180. return pInClause;
  181. /* something went wrong. clean up anything allocated. */
  182. limit_where_cleanup_1:
  183. sqlite3SelectDelete(pParse->db, pSelect);
  184. return 0;
  185. limit_where_cleanup_2:
  186. sqlite3ExprDelete(pParse->db, pWhere);
  187. sqlite3ExprListDelete(pParse->db, pOrderBy);
  188. sqlite3ExprDelete(pParse->db, pLimit);
  189. sqlite3ExprDelete(pParse->db, pOffset);
  190. return 0;
  191. }
  192. #endif /* defined(SQLITE_ENABLE_UPDATE_DELETE_LIMIT) && !defined(SQLITE_OMIT_SUBQUERY) */
  193. /*
  194. ** Generate code for a DELETE FROM statement.
  195. **
  196. ** DELETE FROM table_wxyz WHERE a<5 AND b NOT NULL;
  197. ** \________/ \________________/
  198. ** pTabList pWhere
  199. */
  200. void sqlite3DeleteFrom(
  201. Parse *pParse, /* The parser context */
  202. SrcList *pTabList, /* The table from which we should delete things */
  203. Expr *pWhere /* The WHERE clause. May be null */
  204. ){
  205. Vdbe *v; /* The virtual database engine */
  206. Table *pTab; /* The table from which records will be deleted */
  207. const char *zDb; /* Name of database holding pTab */
  208. int end, addr = 0; /* A couple addresses of generated code */
  209. int i; /* Loop counter */
  210. WhereInfo *pWInfo; /* Information about the WHERE clause */
  211. Index *pIdx; /* For looping over indices of the table */
  212. int iCur; /* VDBE Cursor number for pTab */
  213. sqlite3 *db; /* Main database structure */
  214. AuthContext sContext; /* Authorization context */
  215. NameContext sNC; /* Name context to resolve expressions in */
  216. int iDb; /* Database number */
  217. int memCnt = -1; /* Memory cell used for change counting */
  218. int rcauth; /* Value returned by authorization callback */
  219. #ifndef SQLITE_OMIT_TRIGGER
  220. int isView; /* True if attempting to delete from a view */
  221. Trigger *pTrigger; /* List of table triggers, if required */
  222. #endif
  223. memset(&sContext, 0, sizeof(sContext));
  224. db = pParse->db;
  225. if( pParse->nErr || db->mallocFailed ){
  226. goto delete_from_cleanup;
  227. }
  228. assert( pTabList->nSrc==1 );
  229. /* Locate the table which we want to delete. This table has to be
  230. ** put in an SrcList structure because some of the subroutines we
  231. ** will be calling are designed to work with multiple tables and expect
  232. ** an SrcList* parameter instead of just a Table* parameter.
  233. */
  234. pTab = sqlite3SrcListLookup(pParse, pTabList);
  235. if( pTab==0 ) goto delete_from_cleanup;
  236. /* Figure out if we have any triggers and if the table being
  237. ** deleted from is a view
  238. */
  239. #ifndef SQLITE_OMIT_TRIGGER
  240. pTrigger = sqlite3TriggersExist(pParse, pTab, TK_DELETE, 0, 0);
  241. isView = pTab->pSelect!=0;
  242. #else
  243. # define pTrigger 0
  244. # define isView 0
  245. #endif
  246. #ifdef SQLITE_OMIT_VIEW
  247. # undef isView
  248. # define isView 0
  249. #endif
  250. /* If pTab is really a view, make sure it has been initialized.
  251. */
  252. if( sqlite3ViewGetColumnNames(pParse, pTab) ){
  253. goto delete_from_cleanup;
  254. }
  255. if( sqlite3IsReadOnly(pParse, pTab, (pTrigger?1:0)) ){
  256. goto delete_from_cleanup;
  257. }
  258. iDb = sqlite3SchemaToIndex(db, pTab->pSchema);
  259. assert( iDb<db->nDb );
  260. zDb = db->aDb[iDb].zName;
  261. rcauth = sqlite3AuthCheck(pParse, SQLITE_DELETE, pTab->zName, 0, zDb);
  262. assert( rcauth==SQLITE_OK || rcauth==SQLITE_DENY || rcauth==SQLITE_IGNORE );
  263. if( rcauth==SQLITE_DENY ){
  264. goto delete_from_cleanup;
  265. }
  266. assert(!isView || pTrigger);
  267. /* Assign cursor number to the table and all its indices.
  268. */
  269. assert( pTabList->nSrc==1 );
  270. iCur = pTabList->a[0].iCursor = pParse->nTab++;
  271. for(pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext){
  272. pParse->nTab++;
  273. }
  274. /* Start the view context
  275. */
  276. if( isView ){
  277. sqlite3AuthContextPush(pParse, &sContext, pTab->zName);
  278. }
  279. /* Begin generating code.
  280. */
  281. v = sqlite3GetVdbe(pParse);
  282. if( v==0 ){
  283. goto delete_from_cleanup;
  284. }
  285. if( pParse->nested==0 ) sqlite3VdbeCountChanges(v);
  286. sqlite3BeginWriteOperation(pParse, 1, iDb);
  287. /* If we are trying to delete from a view, realize that view into
  288. ** a ephemeral table.
  289. */
  290. #if !defined(SQLITE_OMIT_VIEW) && !defined(SQLITE_OMIT_TRIGGER)
  291. if( isView ){
  292. sqlite3MaterializeView(pParse, pTab, pWhere, iCur);
  293. }
  294. #endif
  295. /* Resolve the column names in the WHERE clause.
  296. */
  297. memset(&sNC, 0, sizeof(sNC));
  298. sNC.pParse = pParse;
  299. sNC.pSrcList = pTabList;
  300. if( sqlite3ResolveExprNames(&sNC, pWhere) ){
  301. goto delete_from_cleanup;
  302. }
  303. /* Initialize the counter of the number of rows deleted, if
  304. ** we are counting rows.
  305. */
  306. if( db->flags & SQLITE_CountRows ){
  307. memCnt = ++pParse->nMem;
  308. sqlite3VdbeAddOp2(v, OP_Integer, 0, memCnt);
  309. }
  310. #ifndef SQLITE_OMIT_TRUNCATE_OPTIMIZATION
  311. /* Special case: A DELETE without a WHERE clause deletes everything.
  312. ** It is easier just to erase the whole table. Prior to version 3.6.5,
  313. ** this optimization caused the row change count (the value returned by
  314. ** API function sqlite3_count_changes) to be set incorrectly. */
  315. if( rcauth==SQLITE_OK && pWhere==0 && !pTrigger && !IsVirtual(pTab)
  316. && 0==sqlite3FkRequired(pParse, pTab, 0, 0)
  317. ){
  318. assert( !isView );
  319. sqlite3TableLock(pParse, iDb, pTab->tnum, 1, pTab->zName);
  320. sqlite3VdbeAddOp4(v, OP_Clear, pTab->tnum, iDb, memCnt,
  321. pTab->zName, P4_STATIC);
  322. for(pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext){
  323. assert( pIdx->pSchema==pTab->pSchema );
  324. sqlite3VdbeAddOp2(v, OP_Clear, pIdx->tnum, iDb);
  325. }
  326. }else
  327. #endif /* SQLITE_OMIT_TRUNCATE_OPTIMIZATION */
  328. /* The usual case: There is a WHERE clause so we have to scan through
  329. ** the table and pick which records to delete.
  330. */
  331. {
  332. int iRowSet = ++pParse->nMem; /* Register for rowset of rows to delete */
  333. int iRowid = ++pParse->nMem; /* Used for storing rowid values. */
  334. int regRowid; /* Actual register containing rowids */
  335. /* Collect rowids of every row to be deleted.
  336. */
  337. sqlite3VdbeAddOp2(v, OP_Null, 0, iRowSet);
  338. pWInfo = sqlite3WhereBegin(
  339. pParse, pTabList, pWhere, 0, 0, WHERE_DUPLICATES_OK, 0
  340. );
  341. if( pWInfo==0 ) goto delete_from_cleanup;
  342. regRowid = sqlite3ExprCodeGetColumn(pParse, pTab, -1, iCur, iRowid, 0);
  343. sqlite3VdbeAddOp2(v, OP_RowSetAdd, iRowSet, regRowid);
  344. if( db->flags & SQLITE_CountRows ){
  345. sqlite3VdbeAddOp2(v, OP_AddImm, memCnt, 1);
  346. }
  347. sqlite3WhereEnd(pWInfo);
  348. /* Delete every item whose key was written to the list during the
  349. ** database scan. We have to delete items after the scan is complete
  350. ** because deleting an item can change the scan order. */
  351. end = sqlite3VdbeMakeLabel(v);
  352. /* Unless this is a view, open cursors for the table we are
  353. ** deleting from and all its indices. If this is a view, then the
  354. ** only effect this statement has is to fire the INSTEAD OF
  355. ** triggers. */
  356. if( !isView ){
  357. sqlite3OpenTableAndIndices(pParse, pTab, iCur, OP_OpenWrite);
  358. }
  359. addr = sqlite3VdbeAddOp3(v, OP_RowSetRead, iRowSet, end, iRowid);
  360. /* Delete the row */
  361. #ifndef SQLITE_OMIT_VIRTUALTABLE
  362. if( IsVirtual(pTab) ){
  363. const char *pVTab = (const char *)sqlite3GetVTable(db, pTab);
  364. sqlite3VtabMakeWritable(pParse, pTab);
  365. sqlite3VdbeAddOp4(v, OP_VUpdate, 0, 1, iRowid, pVTab, P4_VTAB);
  366. sqlite3VdbeChangeP5(v, OE_Abort);
  367. sqlite3MayAbort(pParse);
  368. }else
  369. #endif
  370. {
  371. int count = (pParse->nested==0); /* True to count changes */
  372. sqlite3GenerateRowDelete(pParse, pTab, iCur, iRowid, count, pTrigger, OE_Default);
  373. }
  374. /* End of the delete loop */
  375. sqlite3VdbeAddOp2(v, OP_Goto, 0, addr);
  376. sqlite3VdbeResolveLabel(v, end);
  377. /* Close the cursors open on the table and its indexes. */
  378. if( !isView && !IsVirtual(pTab) ){
  379. for(i=1, pIdx=pTab->pIndex; pIdx; i++, pIdx=pIdx->pNext){
  380. sqlite3VdbeAddOp2(v, OP_Close, iCur + i, pIdx->tnum);
  381. }
  382. sqlite3VdbeAddOp1(v, OP_Close, iCur);
  383. }
  384. }
  385. /* Update the sqlite_sequence table by storing the content of the
  386. ** maximum rowid counter values recorded while inserting into
  387. ** autoincrement tables.
  388. */
  389. if( pParse->nested==0 && pParse->pTriggerTab==0 ){
  390. sqlite3AutoincrementEnd(pParse);
  391. }
  392. /* Return the number of rows that were deleted. If this routine is
  393. ** generating code because of a call to sqlite3NestedParse(), do not
  394. ** invoke the callback function.
  395. */
  396. if( (db->flags&SQLITE_CountRows) && !pParse->nested && !pParse->pTriggerTab ){
  397. sqlite3VdbeAddOp2(v, OP_ResultRow, memCnt, 1);
  398. sqlite3VdbeSetNumCols(v, 1);
  399. sqlite3VdbeSetColName(v, 0, COLNAME_NAME, "rows deleted", SQLITE_STATIC);
  400. }
  401. delete_from_cleanup:
  402. sqlite3AuthContextPop(&sContext);
  403. sqlite3SrcListDelete(db, pTabList);
  404. sqlite3ExprDelete(db, pWhere);
  405. return;
  406. }
  407. /* Make sure "isView" and other macros defined above are undefined. Otherwise
  408. ** thely may interfere with compilation of other functions in this file
  409. ** (or in another file, if this file becomes part of the amalgamation). */
  410. #ifdef isView
  411. #undef isView
  412. #endif
  413. #ifdef pTrigger
  414. #undef pTrigger
  415. #endif
  416. /*
  417. ** This routine generates VDBE code that causes a single row of a
  418. ** single table to be deleted.
  419. **
  420. ** The VDBE must be in a particular state when this routine is called.
  421. ** These are the requirements:
  422. **
  423. ** 1. A read/write cursor pointing to pTab, the table containing the row
  424. ** to be deleted, must be opened as cursor number $iCur.
  425. **
  426. ** 2. Read/write cursors for all indices of pTab must be open as
  427. ** cursor number base+i for the i-th index.
  428. **
  429. ** 3. The record number of the row to be deleted must be stored in
  430. ** memory cell iRowid.
  431. **
  432. ** This routine generates code to remove both the table record and all
  433. ** index entries that point to that record.
  434. */
  435. void sqlite3GenerateRowDelete(
  436. Parse *pParse, /* Parsing context */
  437. Table *pTab, /* Table containing the row to be deleted */
  438. int iCur, /* Cursor number for the table */
  439. int iRowid, /* Memory cell that contains the rowid to delete */
  440. int count, /* If non-zero, increment the row change counter */
  441. Trigger *pTrigger, /* List of triggers to (potentially) fire */
  442. int onconf /* Default ON CONFLICT policy for triggers */
  443. ){
  444. Vdbe *v = pParse->pVdbe; /* Vdbe */
  445. int iOld = 0; /* First register in OLD.* array */
  446. int iLabel; /* Label resolved to end of generated code */
  447. /* Vdbe is guaranteed to have been allocated by this stage. */
  448. assert( v );
  449. /* Seek cursor iCur to the row to delete. If this row no longer exists
  450. ** (this can happen if a trigger program has already deleted it), do
  451. ** not attempt to delete it or fire any DELETE triggers. */
  452. iLabel = sqlite3VdbeMakeLabel(v);
  453. sqlite3VdbeAddOp3(v, OP_NotExists, iCur, iLabel, iRowid);
  454. /* If there are any triggers to fire, allocate a range of registers to
  455. ** use for the old.* references in the triggers. */
  456. if( sqlite3FkRequired(pParse, pTab, 0, 0) || pTrigger ){
  457. u32 mask; /* Mask of OLD.* columns in use */
  458. int iCol; /* Iterator used while populating OLD.* */
  459. /* TODO: Could use temporary registers here. Also could attempt to
  460. ** avoid copying the contents of the rowid register. */
  461. mask = sqlite3TriggerColmask(
  462. pParse, pTrigger, 0, 0, TRIGGER_BEFORE|TRIGGER_AFTER, pTab, onconf
  463. );
  464. mask |= sqlite3FkOldmask(pParse, pTab);
  465. iOld = pParse->nMem+1;
  466. pParse->nMem += (1 + pTab->nCol);
  467. /* Populate the OLD.* pseudo-table register array. These values will be
  468. ** used by any BEFORE and AFTER triggers that exist. */
  469. sqlite3VdbeAddOp2(v, OP_Copy, iRowid, iOld);
  470. for(iCol=0; iCol<pTab->nCol; iCol++){
  471. if( mask==0xffffffff || mask&(1<<iCol) ){
  472. sqlite3ExprCodeGetColumnOfTable(v, pTab, iCur, iCol, iOld+iCol+1);
  473. }
  474. }
  475. /* Invoke BEFORE DELETE trigger programs. */
  476. sqlite3CodeRowTrigger(pParse, pTrigger,
  477. TK_DELETE, 0, TRIGGER_BEFORE, pTab, iOld, onconf, iLabel
  478. );
  479. /* Seek the cursor to the row to be deleted again. It may be that
  480. ** the BEFORE triggers coded above have already removed the row
  481. ** being deleted. Do not attempt to delete the row a second time, and
  482. ** do not fire AFTER triggers. */
  483. sqlite3VdbeAddOp3(v, OP_NotExists, iCur, iLabel, iRowid);
  484. /* Do FK processing. This call checks that any FK constraints that
  485. ** refer to this table (i.e. constraints attached to other tables)
  486. ** are not violated by deleting this row. */
  487. sqlite3FkCheck(pParse, pTab, iOld, 0, 0, 0);
  488. }
  489. /* Delete the index and table entries. Skip this step if pTab is really
  490. ** a view (in which case the only effect of the DELETE statement is to
  491. ** fire the INSTEAD OF triggers). */
  492. if( pTab->pSelect==0 ){
  493. sqlite3GenerateRowIndexDelete(pParse, pTab, iCur, 0);
  494. sqlite3VdbeAddOp2(v, OP_Delete, iCur, (count?OPFLAG_NCHANGE:0));
  495. if( count ){
  496. sqlite3VdbeChangeP4(v, -1, pTab->zName, P4_TRANSIENT);
  497. }
  498. }
  499. /* Do any ON CASCADE, SET NULL or SET DEFAULT operations required to
  500. ** handle rows (possibly in other tables) that refer via a foreign key
  501. ** to the row just deleted. */
  502. sqlite3FkActions(pParse, pTab, 0, iOld, 0, 0);
  503. /* Invoke AFTER DELETE trigger programs. */
  504. sqlite3CodeRowTrigger(pParse, pTrigger,
  505. TK_DELETE, 0, TRIGGER_AFTER, pTab, iOld, onconf, iLabel
  506. );
  507. /* Jump here if the row had already been deleted before any BEFORE
  508. ** trigger programs were invoked. Or if a trigger program throws a
  509. ** RAISE(IGNORE) exception. */
  510. sqlite3VdbeResolveLabel(v, iLabel);
  511. }
  512. /*
  513. ** This routine generates VDBE code that causes the deletion of all
  514. ** index entries associated with a single row of a single table.
  515. **
  516. ** The VDBE must be in a particular state when this routine is called.
  517. ** These are the requirements:
  518. **
  519. ** 1. A read/write cursor pointing to pTab, the table containing the row
  520. ** to be deleted, must be opened as cursor number "iCur".
  521. **
  522. ** 2. Read/write cursors for all indices of pTab must be open as
  523. ** cursor number iCur+i for the i-th index.
  524. **
  525. ** 3. The "iCur" cursor must be pointing to the row that is to be
  526. ** deleted.
  527. */
  528. void sqlite3GenerateRowIndexDelete(
  529. Parse *pParse, /* Parsing and code generating context */
  530. Table *pTab, /* Table containing the row to be deleted */
  531. int iCur, /* Cursor number for the table */
  532. int *aRegIdx /* Only delete if aRegIdx!=0 && aRegIdx[i]>0 */
  533. ){
  534. int i;
  535. Index *pIdx;
  536. int r1;
  537. int iPartIdxLabel;
  538. Vdbe *v = pParse->pVdbe;
  539. for(i=1, pIdx=pTab->pIndex; pIdx; i++, pIdx=pIdx->pNext){
  540. if( aRegIdx!=0 && aRegIdx[i-1]==0 ) continue;
  541. r1 = sqlite3GenerateIndexKey(pParse, pIdx, iCur, 0, 0, &iPartIdxLabel);
  542. sqlite3VdbeAddOp3(v, OP_IdxDelete, iCur+i, r1, pIdx->nColumn+1);
  543. sqlite3VdbeResolveLabel(v, iPartIdxLabel);
  544. }
  545. }
  546. /*
  547. ** Generate code that will assemble an index key and put it in register
  548. ** regOut. The key with be for index pIdx which is an index on pTab.
  549. ** iCur is the index of a cursor open on the pTab table and pointing to
  550. ** the entry that needs indexing.
  551. **
  552. ** Return a register number which is the first in a block of
  553. ** registers that holds the elements of the index key. The
  554. ** block of registers has already been deallocated by the time
  555. ** this routine returns.
  556. **
  557. ** If *piPartIdxLabel is not NULL, fill it in with a label and jump
  558. ** to that label if pIdx is a partial index that should be skipped.
  559. ** A partial index should be skipped if its WHERE clause evaluates
  560. ** to false or null. If pIdx is not a partial index, *piPartIdxLabel
  561. ** will be set to zero which is an empty label that is ignored by
  562. ** sqlite3VdbeResolveLabel().
  563. */
  564. int sqlite3GenerateIndexKey(
  565. Parse *pParse, /* Parsing context */
  566. Index *pIdx, /* The index for which to generate a key */
  567. int iCur, /* Cursor number for the pIdx->pTable table */
  568. int regOut, /* Write the new index key to this register */
  569. int doMakeRec, /* Run the OP_MakeRecord instruction if true */
  570. int *piPartIdxLabel /* OUT: Jump to this label to skip partial index */
  571. ){
  572. Vdbe *v = pParse->pVdbe;
  573. int j;
  574. Table *pTab = pIdx->pTable;
  575. int regBase;
  576. int nCol;
  577. if( piPartIdxLabel ){
  578. if( pIdx->pPartIdxWhere ){
  579. *piPartIdxLabel = sqlite3VdbeMakeLabel(v);
  580. pParse->iPartIdxTab = iCur;
  581. sqlite3ExprIfFalse(pParse, pIdx->pPartIdxWhere, *piPartIdxLabel,
  582. SQLITE_JUMPIFNULL);
  583. }else{
  584. *piPartIdxLabel = 0;
  585. }
  586. }
  587. nCol = pIdx->nColumn;
  588. regBase = sqlite3GetTempRange(pParse, nCol+1);
  589. sqlite3VdbeAddOp2(v, OP_Rowid, iCur, regBase+nCol);
  590. for(j=0; j<nCol; j++){
  591. int idx = pIdx->aiColumn[j];
  592. if( idx==pTab->iPKey ){
  593. sqlite3VdbeAddOp2(v, OP_SCopy, regBase+nCol, regBase+j);
  594. }else{
  595. sqlite3VdbeAddOp3(v, OP_Column, iCur, idx, regBase+j);
  596. sqlite3ColumnDefault(v, pTab, idx, -1);
  597. }
  598. }
  599. if( doMakeRec ){
  600. const char *zAff;
  601. if( pTab->pSelect
  602. || OptimizationDisabled(pParse->db, SQLITE_IdxRealAsInt)
  603. ){
  604. zAff = 0;
  605. }else{
  606. zAff = sqlite3IndexAffinityStr(v, pIdx);
  607. }
  608. sqlite3VdbeAddOp3(v, OP_MakeRecord, regBase, nCol+1, regOut);
  609. sqlite3VdbeChangeP4(v, -1, zAff, P4_TRANSIENT);
  610. }
  611. sqlite3ReleaseTempRange(pParse, regBase, nCol+1);
  612. return regBase;
  613. }