delete.c 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472
  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. ** $Id: delete.c,v 1.134 2007/12/12 17:42:53 danielk1977 Exp $
  16. */
  17. #include "sqliteInt.h"
  18. /*
  19. ** Look up every table that is named in pSrc. If any table is not found,
  20. ** add an error message to pParse->zErrMsg and return NULL. If all tables
  21. ** are found, return a pointer to the last table.
  22. */
  23. Table *sqlite3SrcListLookup(Parse *pParse, SrcList *pSrc){
  24. Table *pTab = 0;
  25. int i;
  26. struct SrcList_item *pItem;
  27. for(i=0, pItem=pSrc->a; i<pSrc->nSrc; i++, pItem++){
  28. pTab = sqlite3LocateTable(pParse, pItem->zName, pItem->zDatabase);
  29. sqlite3DeleteTable(pItem->pTab);
  30. pItem->pTab = pTab;
  31. if( pTab ){
  32. pTab->nRef++;
  33. }
  34. }
  35. return pTab;
  36. }
  37. /*
  38. ** Check to make sure the given table is writable. If it is not
  39. ** writable, generate an error message and return 1. If it is
  40. ** writable return 0;
  41. */
  42. int sqlite3IsReadOnly(Parse *pParse, Table *pTab, int viewOk){
  43. if( (pTab->readOnly && (pParse->db->flags & SQLITE_WriteSchema)==0
  44. && pParse->nested==0)
  45. #ifndef SQLITE_OMIT_VIRTUALTABLE
  46. || (pTab->pMod && pTab->pMod->pModule->xUpdate==0)
  47. #endif
  48. ){
  49. sqlite3ErrorMsg(pParse, "table %s may not be modified", pTab->zName);
  50. return 1;
  51. }
  52. #ifndef SQLITE_OMIT_VIEW
  53. if( !viewOk && pTab->pSelect ){
  54. sqlite3ErrorMsg(pParse,"cannot modify %s because it is a view",pTab->zName);
  55. return 1;
  56. }
  57. #endif
  58. return 0;
  59. }
  60. /*
  61. ** Generate code that will open a table for reading.
  62. */
  63. void sqlite3OpenTable(
  64. Parse *p, /* Generate code into this VDBE */
  65. int iCur, /* The cursor number of the table */
  66. int iDb, /* The database index in sqlite3.aDb[] */
  67. Table *pTab, /* The table to be opened */
  68. int opcode /* OP_OpenRead or OP_OpenWrite */
  69. ){
  70. Vdbe *v;
  71. if( IsVirtual(pTab) ) return;
  72. v = sqlite3GetVdbe(p);
  73. assert( opcode==OP_OpenWrite || opcode==OP_OpenRead );
  74. sqlite3TableLock(p, iDb, pTab->tnum, (opcode==OP_OpenWrite), pTab->zName);
  75. sqlite3VdbeAddOp(v, OP_Integer, iDb, 0);
  76. VdbeComment((v, "# %s", pTab->zName));
  77. sqlite3VdbeAddOp(v, opcode, iCur, pTab->tnum);
  78. sqlite3VdbeAddOp(v, OP_SetNumColumns, iCur, pTab->nCol);
  79. }
  80. /*
  81. ** Generate code for a DELETE FROM statement.
  82. **
  83. ** DELETE FROM table_wxyz WHERE a<5 AND b NOT NULL;
  84. ** \________/ \________________/
  85. ** pTabList pWhere
  86. */
  87. void sqlite3DeleteFrom(
  88. Parse *pParse, /* The parser context */
  89. SrcList *pTabList, /* The table from which we should delete things */
  90. Expr *pWhere /* The WHERE clause. May be null */
  91. ){
  92. Vdbe *v; /* The virtual database engine */
  93. Table *pTab; /* The table from which records will be deleted */
  94. const char *zDb; /* Name of database holding pTab */
  95. int end, addr = 0; /* A couple addresses of generated code */
  96. int i; /* Loop counter */
  97. WhereInfo *pWInfo; /* Information about the WHERE clause */
  98. Index *pIdx; /* For looping over indices of the table */
  99. int iCur; /* VDBE Cursor number for pTab */
  100. sqlite3 *db; /* Main database structure */
  101. AuthContext sContext; /* Authorization context */
  102. int oldIdx = -1; /* Cursor for the OLD table of AFTER triggers */
  103. NameContext sNC; /* Name context to resolve expressions in */
  104. int iDb; /* Database number */
  105. int memCnt = 0; /* Memory cell used for change counting */
  106. #ifndef SQLITE_OMIT_TRIGGER
  107. int isView; /* True if attempting to delete from a view */
  108. int triggers_exist = 0; /* True if any triggers exist */
  109. #endif
  110. sContext.pParse = 0;
  111. db = pParse->db;
  112. if( pParse->nErr || db->mallocFailed ){
  113. goto delete_from_cleanup;
  114. }
  115. assert( pTabList->nSrc==1 );
  116. /* Locate the table which we want to delete. This table has to be
  117. ** put in an SrcList structure because some of the subroutines we
  118. ** will be calling are designed to work with multiple tables and expect
  119. ** an SrcList* parameter instead of just a Table* parameter.
  120. */
  121. pTab = sqlite3SrcListLookup(pParse, pTabList);
  122. if( pTab==0 ) goto delete_from_cleanup;
  123. /* Figure out if we have any triggers and if the table being
  124. ** deleted from is a view
  125. */
  126. #ifndef SQLITE_OMIT_TRIGGER
  127. triggers_exist = sqlite3TriggersExist(pParse, pTab, TK_DELETE, 0);
  128. isView = pTab->pSelect!=0;
  129. #else
  130. # define triggers_exist 0
  131. # define isView 0
  132. #endif
  133. #ifdef SQLITE_OMIT_VIEW
  134. # undef isView
  135. # define isView 0
  136. #endif
  137. if( sqlite3IsReadOnly(pParse, pTab, triggers_exist) ){
  138. goto delete_from_cleanup;
  139. }
  140. iDb = sqlite3SchemaToIndex(db, pTab->pSchema);
  141. assert( iDb<db->nDb );
  142. zDb = db->aDb[iDb].zName;
  143. if( sqlite3AuthCheck(pParse, SQLITE_DELETE, pTab->zName, 0, zDb) ){
  144. goto delete_from_cleanup;
  145. }
  146. /* If pTab is really a view, make sure it has been initialized.
  147. */
  148. if( sqlite3ViewGetColumnNames(pParse, pTab) ){
  149. goto delete_from_cleanup;
  150. }
  151. /* Allocate a cursor used to store the old.* data for a trigger.
  152. */
  153. if( triggers_exist ){
  154. oldIdx = pParse->nTab++;
  155. }
  156. /* Resolve the column names in the WHERE clause.
  157. */
  158. assert( pTabList->nSrc==1 );
  159. iCur = pTabList->a[0].iCursor = pParse->nTab++;
  160. memset(&sNC, 0, sizeof(sNC));
  161. sNC.pParse = pParse;
  162. sNC.pSrcList = pTabList;
  163. if( sqlite3ExprResolveNames(&sNC, pWhere) ){
  164. goto delete_from_cleanup;
  165. }
  166. /* Start the view context
  167. */
  168. if( isView ){
  169. sqlite3AuthContextPush(pParse, &sContext, pTab->zName);
  170. }
  171. /* Begin generating code.
  172. */
  173. v = sqlite3GetVdbe(pParse);
  174. if( v==0 ){
  175. goto delete_from_cleanup;
  176. }
  177. if( pParse->nested==0 ) sqlite3VdbeCountChanges(v);
  178. sqlite3BeginWriteOperation(pParse, triggers_exist, iDb);
  179. /* If we are trying to delete from a view, realize that view into
  180. ** a ephemeral table.
  181. */
  182. if( isView ){
  183. Select *pView = sqlite3SelectDup(db, pTab->pSelect);
  184. sqlite3Select(pParse, pView, SRT_EphemTab, iCur, 0, 0, 0, 0);
  185. sqlite3SelectDelete(pView);
  186. }
  187. /* Initialize the counter of the number of rows deleted, if
  188. ** we are counting rows.
  189. */
  190. if( db->flags & SQLITE_CountRows ){
  191. memCnt = pParse->nMem++;
  192. sqlite3VdbeAddOp(v, OP_MemInt, 0, memCnt);
  193. }
  194. /* Special case: A DELETE without a WHERE clause deletes everything.
  195. ** It is easier just to erase the whole table. Note, however, that
  196. ** this means that the row change count will be incorrect.
  197. */
  198. if( pWhere==0 && !triggers_exist && !IsVirtual(pTab) ){
  199. if( db->flags & SQLITE_CountRows ){
  200. /* If counting rows deleted, just count the total number of
  201. ** entries in the table. */
  202. int addr2;
  203. if( !isView ){
  204. sqlite3OpenTable(pParse, iCur, iDb, pTab, OP_OpenRead);
  205. }
  206. sqlite3VdbeAddOp(v, OP_Rewind, iCur, sqlite3VdbeCurrentAddr(v)+2);
  207. addr2 = sqlite3VdbeAddOp(v, OP_MemIncr, 1, memCnt);
  208. sqlite3VdbeAddOp(v, OP_Next, iCur, addr2);
  209. sqlite3VdbeAddOp(v, OP_Close, iCur, 0);
  210. }
  211. if( !isView ){
  212. sqlite3VdbeAddOp(v, OP_Clear, pTab->tnum, iDb);
  213. if( !pParse->nested ){
  214. sqlite3VdbeChangeP3(v, -1, pTab->zName, P3_STATIC);
  215. }
  216. for(pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext){
  217. assert( pIdx->pSchema==pTab->pSchema );
  218. sqlite3VdbeAddOp(v, OP_Clear, pIdx->tnum, iDb);
  219. }
  220. }
  221. }
  222. /* The usual case: There is a WHERE clause so we have to scan through
  223. ** the table and pick which records to delete.
  224. */
  225. else{
  226. /* Begin the database scan
  227. */
  228. pWInfo = sqlite3WhereBegin(pParse, pTabList, pWhere, 0);
  229. if( pWInfo==0 ) goto delete_from_cleanup;
  230. /* Remember the rowid of every item to be deleted.
  231. */
  232. sqlite3VdbeAddOp(v, IsVirtual(pTab) ? OP_VRowid : OP_Rowid, iCur, 0);
  233. sqlite3VdbeAddOp(v, OP_FifoWrite, 0, 0);
  234. if( db->flags & SQLITE_CountRows ){
  235. sqlite3VdbeAddOp(v, OP_MemIncr, 1, memCnt);
  236. }
  237. /* End the database scan loop.
  238. */
  239. sqlite3WhereEnd(pWInfo);
  240. /* Open the pseudo-table used to store OLD if there are triggers.
  241. */
  242. if( triggers_exist ){
  243. sqlite3VdbeAddOp(v, OP_OpenPseudo, oldIdx, 0);
  244. sqlite3VdbeAddOp(v, OP_SetNumColumns, oldIdx, pTab->nCol);
  245. }
  246. /* Delete every item whose key was written to the list during the
  247. ** database scan. We have to delete items after the scan is complete
  248. ** because deleting an item can change the scan order.
  249. */
  250. end = sqlite3VdbeMakeLabel(v);
  251. /* This is the beginning of the delete loop when there are
  252. ** row triggers.
  253. */
  254. if( triggers_exist ){
  255. int mem1 = pParse->nMem++;
  256. addr = sqlite3VdbeAddOp(v, OP_FifoRead, 0, end);
  257. sqlite3VdbeAddOp(v, OP_StackDepth, -1, 0);
  258. sqlite3VdbeAddOp(v, OP_MemStore, mem1, 0);
  259. if( !isView ){
  260. sqlite3OpenTable(pParse, iCur, iDb, pTab, OP_OpenRead);
  261. }
  262. sqlite3VdbeAddOp(v, OP_NotExists, iCur, addr);
  263. sqlite3VdbeAddOp(v, OP_Rowid, iCur, 0);
  264. sqlite3VdbeAddOp(v, OP_RowData, iCur, 0);
  265. sqlite3VdbeAddOp(v, OP_Insert, oldIdx, 0);
  266. if( !isView ){
  267. sqlite3VdbeAddOp(v, OP_Close, iCur, 0);
  268. }
  269. (void)sqlite3CodeRowTrigger(pParse, TK_DELETE, 0, TRIGGER_BEFORE, pTab,
  270. -1, oldIdx, (pParse->trigStack)?pParse->trigStack->orconf:OE_Default,
  271. addr);
  272. if( !isView ){
  273. sqlite3VdbeAddOp(v, OP_MemLoad, mem1, 0);
  274. }
  275. }
  276. if( !isView ){
  277. /* Open cursors for the table we are deleting from and all its
  278. ** indices. If there are row triggers, this happens inside the
  279. ** OP_FifoRead loop because the cursor have to all be closed
  280. ** before the trigger fires. If there are no row triggers, the
  281. ** cursors are opened only once on the outside the loop.
  282. */
  283. sqlite3OpenTableAndIndices(pParse, pTab, iCur, OP_OpenWrite);
  284. /* This is the beginning of the delete loop when there are no
  285. ** row triggers */
  286. if( !triggers_exist ){
  287. addr = sqlite3VdbeAddOp(v, OP_FifoRead, 0, end);
  288. sqlite3VdbeAddOp(v, OP_StackDepth, -1, 0);
  289. }
  290. /* Delete the row */
  291. #ifndef SQLITE_OMIT_VIRTUALTABLE
  292. if( IsVirtual(pTab) ){
  293. pParse->pVirtualLock = pTab;
  294. sqlite3VdbeOp3(v, OP_VUpdate, 0, 1, (const char*)pTab->pVtab, P3_VTAB);
  295. }else
  296. #endif
  297. {
  298. sqlite3GenerateRowDelete(db, v, pTab, iCur, pParse->nested==0);
  299. }
  300. }
  301. /* If there are row triggers, close all cursors then invoke
  302. ** the AFTER triggers
  303. */
  304. if( triggers_exist ){
  305. if( !isView ){
  306. for(i=1, pIdx=pTab->pIndex; pIdx; i++, pIdx=pIdx->pNext){
  307. sqlite3VdbeAddOp(v, OP_Close, iCur + i, pIdx->tnum);
  308. }
  309. sqlite3VdbeAddOp(v, OP_Close, iCur, 0);
  310. }
  311. (void)sqlite3CodeRowTrigger(pParse, TK_DELETE, 0, TRIGGER_AFTER, pTab, -1,
  312. oldIdx, (pParse->trigStack)?pParse->trigStack->orconf:OE_Default,
  313. addr);
  314. }
  315. /* End of the delete loop */
  316. sqlite3VdbeAddOp(v, OP_Goto, 0, addr);
  317. sqlite3VdbeResolveLabel(v, end);
  318. /* Close the cursors after the loop if there are no row triggers */
  319. if( !triggers_exist && !IsVirtual(pTab) ){
  320. for(i=1, pIdx=pTab->pIndex; pIdx; i++, pIdx=pIdx->pNext){
  321. sqlite3VdbeAddOp(v, OP_Close, iCur + i, pIdx->tnum);
  322. }
  323. sqlite3VdbeAddOp(v, OP_Close, iCur, 0);
  324. }
  325. }
  326. /*
  327. ** Return the number of rows that were deleted. If this routine is
  328. ** generating code because of a call to sqlite3NestedParse(), do not
  329. ** invoke the callback function.
  330. */
  331. if( db->flags & SQLITE_CountRows && pParse->nested==0 && !pParse->trigStack ){
  332. sqlite3VdbeAddOp(v, OP_MemLoad, memCnt, 0);
  333. sqlite3VdbeAddOp(v, OP_Callback, 1, 0);
  334. sqlite3VdbeSetNumCols(v, 1);
  335. sqlite3VdbeSetColName(v, 0, COLNAME_NAME, "rows deleted", P3_STATIC);
  336. }
  337. delete_from_cleanup:
  338. sqlite3AuthContextPop(&sContext);
  339. sqlite3SrcListDelete(pTabList);
  340. sqlite3ExprDelete(pWhere);
  341. return;
  342. }
  343. /*
  344. ** This routine generates VDBE code that causes a single row of a
  345. ** single table to be deleted.
  346. **
  347. ** The VDBE must be in a particular state when this routine is called.
  348. ** These are the requirements:
  349. **
  350. ** 1. A read/write cursor pointing to pTab, the table containing the row
  351. ** to be deleted, must be opened as cursor number "base".
  352. **
  353. ** 2. Read/write cursors for all indices of pTab must be open as
  354. ** cursor number base+i for the i-th index.
  355. **
  356. ** 3. The record number of the row to be deleted must be on the top
  357. ** of the stack.
  358. **
  359. ** This routine pops the top of the stack to remove the record number
  360. ** and then generates code to remove both the table record and all index
  361. ** entries that point to that record.
  362. */
  363. void sqlite3GenerateRowDelete(
  364. sqlite3 *db, /* The database containing the index */
  365. Vdbe *v, /* Generate code into this VDBE */
  366. Table *pTab, /* Table containing the row to be deleted */
  367. int iCur, /* Cursor number for the table */
  368. int count /* Increment the row change counter */
  369. ){
  370. int addr;
  371. addr = sqlite3VdbeAddOp(v, OP_NotExists, iCur, 0);
  372. sqlite3GenerateRowIndexDelete(v, pTab, iCur, 0);
  373. sqlite3VdbeAddOp(v, OP_Delete, iCur, (count?OPFLAG_NCHANGE:0));
  374. if( count ){
  375. sqlite3VdbeChangeP3(v, -1, pTab->zName, P3_STATIC);
  376. }
  377. sqlite3VdbeJumpHere(v, addr);
  378. }
  379. /*
  380. ** This routine generates VDBE code that causes the deletion of all
  381. ** index entries associated with a single row of a single table.
  382. **
  383. ** The VDBE must be in a particular state when this routine is called.
  384. ** These are the requirements:
  385. **
  386. ** 1. A read/write cursor pointing to pTab, the table containing the row
  387. ** to be deleted, must be opened as cursor number "iCur".
  388. **
  389. ** 2. Read/write cursors for all indices of pTab must be open as
  390. ** cursor number iCur+i for the i-th index.
  391. **
  392. ** 3. The "iCur" cursor must be pointing to the row that is to be
  393. ** deleted.
  394. */
  395. void sqlite3GenerateRowIndexDelete(
  396. Vdbe *v, /* Generate code into this VDBE */
  397. Table *pTab, /* Table containing the row to be deleted */
  398. int iCur, /* Cursor number for the table */
  399. char *aIdxUsed /* Only delete if aIdxUsed!=0 && aIdxUsed[i]!=0 */
  400. ){
  401. int i;
  402. Index *pIdx;
  403. for(i=1, pIdx=pTab->pIndex; pIdx; i++, pIdx=pIdx->pNext){
  404. if( aIdxUsed!=0 && aIdxUsed[i-1]==0 ) continue;
  405. sqlite3GenerateIndexKey(v, pIdx, iCur);
  406. sqlite3VdbeAddOp(v, OP_IdxDelete, iCur+i, 0);
  407. }
  408. }
  409. /*
  410. ** Generate code that will assemble an index key and put it on the top
  411. ** of the tack. The key with be for index pIdx which is an index on pTab.
  412. ** iCur is the index of a cursor open on the pTab table and pointing to
  413. ** the entry that needs indexing.
  414. */
  415. void sqlite3GenerateIndexKey(
  416. Vdbe *v, /* Generate code into this VDBE */
  417. Index *pIdx, /* The index for which to generate a key */
  418. int iCur /* Cursor number for the pIdx->pTable table */
  419. ){
  420. int j;
  421. Table *pTab = pIdx->pTable;
  422. sqlite3VdbeAddOp(v, OP_Rowid, iCur, 0);
  423. for(j=0; j<pIdx->nColumn; j++){
  424. int idx = pIdx->aiColumn[j];
  425. if( idx==pTab->iPKey ){
  426. sqlite3VdbeAddOp(v, OP_Dup, j, 0);
  427. }else{
  428. sqlite3VdbeAddOp(v, OP_Column, iCur, idx);
  429. sqlite3ColumnDefault(v, pTab, idx);
  430. }
  431. }
  432. sqlite3VdbeAddOp(v, OP_MakeIdxRec, pIdx->nColumn, 0);
  433. sqlite3IndexAffinityStr(v, pIdx);
  434. }