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