64bit fixes
[AROS-Contrib.git] / sqlite3 / delete.c
blob15eb8f4e8d373e7f13d2b5b047e7226a3db30162
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.
11 *************************************************************************
12 ** This file contains C code routines that are called by the parser
13 ** in order to generate code for DELETE FROM statements.
15 ** $Id$
17 #include "sqliteInt.h"
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.
24 Table *sqlite3SrcListLookup(Parse *pParse, SrcList *pSrc){
25 Table *pTab = 0;
26 int i;
27 struct SrcList_item *pItem;
28 for(i=0, pItem=pSrc->a; i<pSrc->nSrc; i++, pItem++){
29 pTab = sqlite3LocateTable(pParse, pItem->zName, pItem->zDatabase);
30 sqlite3DeleteTable(pParse->db, pItem->pTab);
31 pItem->pTab = pTab;
32 if( pTab ){
33 pTab->nRef++;
36 return pTab;
40 ** Check to make sure the given table is writable. If it is not
41 ** writable, generate an error message and return 1. If it is
42 ** writable return 0;
44 int sqlite3IsReadOnly(Parse *pParse, Table *pTab, int viewOk){
45 if( pTab->readOnly && (pParse->db->flags & SQLITE_WriteSchema)==0
46 && pParse->nested==0 ){
47 sqlite3ErrorMsg(pParse, "table %s may not be modified", pTab->zName);
48 return 1;
50 #ifndef SQLITE_OMIT_VIEW
51 if( !viewOk && pTab->pSelect ){
52 sqlite3ErrorMsg(pParse,"cannot modify %s because it is a view",pTab->zName);
53 return 1;
55 #endif
56 return 0;
60 ** Generate code that will open a table for reading.
62 void sqlite3OpenTableForReading(
63 Vdbe *v, /* Generate code into this VDBE */
64 int iCur, /* The cursor number of the table */
65 Table *pTab /* The table to be opened */
67 sqlite3VdbeAddOp(v, OP_Integer, pTab->iDb, 0);
68 sqlite3VdbeAddOp(v, OP_OpenRead, iCur, pTab->tnum);
69 VdbeComment((v, "# %s", pTab->zName));
70 sqlite3VdbeAddOp(v, OP_SetNumColumns, iCur, pTab->nCol);
75 ** Generate code for a DELETE FROM statement.
77 ** DELETE FROM table_wxyz WHERE a<5 AND b NOT NULL;
78 ** \________/ \________________/
79 ** pTabList pWhere
81 void sqlite3DeleteFrom(
82 Parse *pParse, /* The parser context */
83 SrcList *pTabList, /* The table from which we should delete things */
84 Expr *pWhere /* The WHERE clause. May be null */
86 Vdbe *v; /* The virtual database engine */
87 Table *pTab; /* The table from which records will be deleted */
88 const char *zDb; /* Name of database holding pTab */
89 int end, addr = 0; /* A couple addresses of generated code */
90 int i; /* Loop counter */
91 WhereInfo *pWInfo; /* Information about the WHERE clause */
92 Index *pIdx; /* For looping over indices of the table */
93 int iCur; /* VDBE Cursor number for pTab */
94 sqlite3 *db; /* Main database structure */
95 AuthContext sContext; /* Authorization context */
96 int oldIdx = -1; /* Cursor for the OLD table of AFTER triggers */
97 NameContext sNC; /* Name context to resolve expressions in */
99 #ifndef SQLITE_OMIT_TRIGGER
100 int isView; /* True if attempting to delete from a view */
101 int triggers_exist = 0; /* True if any triggers exist */
102 #endif
104 sContext.pParse = 0;
105 if( pParse->nErr || sqlite3_malloc_failed ){
106 goto delete_from_cleanup;
108 db = pParse->db;
109 assert( pTabList->nSrc==1 );
111 /* Locate the table which we want to delete. This table has to be
112 ** put in an SrcList structure because some of the subroutines we
113 ** will be calling are designed to work with multiple tables and expect
114 ** an SrcList* parameter instead of just a Table* parameter.
116 pTab = sqlite3SrcListLookup(pParse, pTabList);
117 if( pTab==0 ) goto delete_from_cleanup;
119 /* Figure out if we have any triggers and if the table being
120 ** deleted from is a view
122 #ifndef SQLITE_OMIT_TRIGGER
123 triggers_exist = sqlite3TriggersExist(pParse, pTab, TK_DELETE, 0);
124 isView = pTab->pSelect!=0;
125 #else
126 # define triggers_exist 0
127 # define isView 0
128 #endif
129 #ifdef SQLITE_OMIT_VIEW
130 # undef isView
131 # define isView 0
132 #endif
134 if( sqlite3IsReadOnly(pParse, pTab, triggers_exist) ){
135 goto delete_from_cleanup;
137 assert( pTab->iDb<db->nDb );
138 zDb = db->aDb[pTab->iDb].zName;
139 if( sqlite3AuthCheck(pParse, SQLITE_DELETE, pTab->zName, 0, zDb) ){
140 goto delete_from_cleanup;
143 /* If pTab is really a view, make sure it has been initialized.
145 if( isView && sqlite3ViewGetColumnNames(pParse, pTab) ){
146 goto delete_from_cleanup;
149 /* Allocate a cursor used to store the old.* data for a trigger.
151 if( triggers_exist ){
152 oldIdx = pParse->nTab++;
155 /* Resolve the column names in the WHERE clause.
157 assert( pTabList->nSrc==1 );
158 iCur = pTabList->a[0].iCursor = pParse->nTab++;
159 memset(&sNC, 0, sizeof(sNC));
160 sNC.pParse = pParse;
161 sNC.pSrcList = pTabList;
162 if( sqlite3ExprResolveNames(&sNC, pWhere) ){
163 goto delete_from_cleanup;
166 /* Start the view context
168 if( isView ){
169 sqlite3AuthContextPush(pParse, &sContext, pTab->zName);
172 /* Begin generating code.
174 v = sqlite3GetVdbe(pParse);
175 if( v==0 ){
176 goto delete_from_cleanup;
178 if( pParse->nested==0 ) sqlite3VdbeCountChanges(v);
179 sqlite3BeginWriteOperation(pParse, triggers_exist, pTab->iDb);
181 /* If we are trying to delete from a view, construct that view into
182 ** a temporary table.
184 if( isView ){
185 Select *pView = sqlite3SelectDup(pTab->pSelect);
186 sqlite3Select(pParse, pView, SRT_TempTable, iCur, 0, 0, 0, 0);
187 sqlite3SelectDelete(pView);
190 /* Initialize the counter of the number of rows deleted, if
191 ** we are counting rows.
193 if( db->flags & SQLITE_CountRows ){
194 sqlite3VdbeAddOp(v, OP_Integer, 0, 0);
197 /* Special case: A DELETE without a WHERE clause deletes everything.
198 ** It is easier just to erase the whole table. Note, however, that
199 ** this means that the row change count will be incorrect.
201 if( pWhere==0 && !triggers_exist ){
202 if( db->flags & SQLITE_CountRows ){
203 /* If counting rows deleted, just count the total number of
204 ** entries in the table. */
205 int endOfLoop = sqlite3VdbeMakeLabel(v);
206 int addr;
207 if( !isView ){
208 sqlite3OpenTableForReading(v, iCur, pTab);
210 sqlite3VdbeAddOp(v, OP_Rewind, iCur, sqlite3VdbeCurrentAddr(v)+2);
211 addr = sqlite3VdbeAddOp(v, OP_AddImm, 1, 0);
212 sqlite3VdbeAddOp(v, OP_Next, iCur, addr);
213 sqlite3VdbeResolveLabel(v, endOfLoop);
214 sqlite3VdbeAddOp(v, OP_Close, iCur, 0);
216 if( !isView ){
217 sqlite3VdbeAddOp(v, OP_Clear, pTab->tnum, pTab->iDb);
218 for(pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext){
219 sqlite3VdbeAddOp(v, OP_Clear, pIdx->tnum, pIdx->iDb);
224 /* The usual case: There is a WHERE clause so we have to scan through
225 ** the table and pick which records to delete.
227 else{
228 /* Ensure all required collation sequences are available. */
229 for(pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext){
230 if( sqlite3CheckIndexCollSeq(pParse, pIdx) ){
231 goto delete_from_cleanup;
235 /* Begin the database scan
237 pWInfo = sqlite3WhereBegin(pParse, pTabList, pWhere, 0);
238 if( pWInfo==0 ) goto delete_from_cleanup;
240 /* Remember the rowid of every item to be deleted.
242 sqlite3VdbeAddOp(v, OP_Rowid, iCur, 0);
243 sqlite3VdbeAddOp(v, OP_ListWrite, 0, 0);
244 if( db->flags & SQLITE_CountRows ){
245 sqlite3VdbeAddOp(v, OP_AddImm, 1, 0);
248 /* End the database scan loop.
250 sqlite3WhereEnd(pWInfo);
252 /* Open the pseudo-table used to store OLD if there are triggers.
254 if( triggers_exist ){
255 sqlite3VdbeAddOp(v, OP_OpenPseudo, oldIdx, 0);
256 sqlite3VdbeAddOp(v, OP_SetNumColumns, oldIdx, pTab->nCol);
259 /* Delete every item whose key was written to the list during the
260 ** database scan. We have to delete items after the scan is complete
261 ** because deleting an item can change the scan order.
263 sqlite3VdbeAddOp(v, OP_ListRewind, 0, 0);
264 end = sqlite3VdbeMakeLabel(v);
266 /* This is the beginning of the delete loop when there are
267 ** row triggers.
269 if( triggers_exist ){
270 addr = sqlite3VdbeAddOp(v, OP_ListRead, 0, end);
271 if( !isView ){
272 sqlite3VdbeAddOp(v, OP_Dup, 0, 0);
273 sqlite3OpenTableForReading(v, iCur, pTab);
275 sqlite3VdbeAddOp(v, OP_MoveGe, iCur, 0);
276 sqlite3VdbeAddOp(v, OP_Rowid, iCur, 0);
277 sqlite3VdbeAddOp(v, OP_RowData, iCur, 0);
278 sqlite3VdbeAddOp(v, OP_Insert, oldIdx, 0);
279 if( !isView ){
280 sqlite3VdbeAddOp(v, OP_Close, iCur, 0);
283 (void)sqlite3CodeRowTrigger(pParse, TK_DELETE, 0, TRIGGER_BEFORE, pTab,
284 -1, oldIdx, (pParse->trigStack)?pParse->trigStack->orconf:OE_Default,
285 addr);
288 if( !isView ){
289 /* Open cursors for the table we are deleting from and all its
290 ** indices. If there are row triggers, this happens inside the
291 ** OP_ListRead loop because the cursor have to all be closed
292 ** before the trigger fires. If there are no row triggers, the
293 ** cursors are opened only once on the outside the loop.
295 sqlite3OpenTableAndIndices(pParse, pTab, iCur, OP_OpenWrite);
297 /* This is the beginning of the delete loop when there are no
298 ** row triggers */
299 if( !triggers_exist ){
300 addr = sqlite3VdbeAddOp(v, OP_ListRead, 0, end);
303 /* Delete the row */
304 sqlite3GenerateRowDelete(db, v, pTab, iCur, pParse->nested==0);
307 /* If there are row triggers, close all cursors then invoke
308 ** the AFTER triggers
310 if( triggers_exist ){
311 if( !isView ){
312 for(i=1, pIdx=pTab->pIndex; pIdx; i++, pIdx=pIdx->pNext){
313 sqlite3VdbeAddOp(v, OP_Close, iCur + i, pIdx->tnum);
315 sqlite3VdbeAddOp(v, OP_Close, iCur, 0);
317 (void)sqlite3CodeRowTrigger(pParse, TK_DELETE, 0, TRIGGER_AFTER, pTab, -1,
318 oldIdx, (pParse->trigStack)?pParse->trigStack->orconf:OE_Default,
319 addr);
322 /* End of the delete loop */
323 sqlite3VdbeAddOp(v, OP_Goto, 0, addr);
324 sqlite3VdbeResolveLabel(v, end);
325 sqlite3VdbeAddOp(v, OP_ListReset, 0, 0);
327 /* Close the cursors after the loop if there are no row triggers */
328 if( !triggers_exist ){
329 for(i=1, pIdx=pTab->pIndex; pIdx; i++, pIdx=pIdx->pNext){
330 sqlite3VdbeAddOp(v, OP_Close, iCur + i, pIdx->tnum);
332 sqlite3VdbeAddOp(v, OP_Close, iCur, 0);
337 ** Return the number of rows that were deleted. If this routine is
338 ** generating code because of a call to sqlite3NestedParse(), do not
339 ** invoke the callback function.
341 if( db->flags & SQLITE_CountRows && pParse->nested==0 && !pParse->trigStack ){
342 sqlite3VdbeAddOp(v, OP_Callback, 1, 0);
343 sqlite3VdbeSetNumCols(v, 1);
344 sqlite3VdbeSetColName(v, 0, "rows deleted", P3_STATIC);
347 delete_from_cleanup:
348 sqlite3AuthContextPop(&sContext);
349 sqlite3SrcListDelete(pTabList);
350 sqlite3ExprDelete(pWhere);
351 return;
355 ** This routine generates VDBE code that causes a single row of a
356 ** single table to be deleted.
358 ** The VDBE must be in a particular state when this routine is called.
359 ** These are the requirements:
361 ** 1. A read/write cursor pointing to pTab, the table containing the row
362 ** to be deleted, must be opened as cursor number "base".
364 ** 2. Read/write cursors for all indices of pTab must be open as
365 ** cursor number base+i for the i-th index.
367 ** 3. The record number of the row to be deleted must be on the top
368 ** of the stack.
370 ** This routine pops the top of the stack to remove the record number
371 ** and then generates code to remove both the table record and all index
372 ** entries that point to that record.
374 void sqlite3GenerateRowDelete(
375 sqlite3 *db, /* The database containing the index */
376 Vdbe *v, /* Generate code into this VDBE */
377 Table *pTab, /* Table containing the row to be deleted */
378 int iCur, /* Cursor number for the table */
379 int count /* Increment the row change counter */
381 int addr;
382 addr = sqlite3VdbeAddOp(v, OP_NotExists, iCur, 0);
383 sqlite3GenerateRowIndexDelete(db, v, pTab, iCur, 0);
384 sqlite3VdbeAddOp(v, OP_Delete, iCur, (count?OPFLAG_NCHANGE:0));
385 sqlite3VdbeChangeP2(v, addr, sqlite3VdbeCurrentAddr(v));
389 ** This routine generates VDBE code that causes the deletion of all
390 ** index entries associated with a single row of a single table.
392 ** The VDBE must be in a particular state when this routine is called.
393 ** These are the requirements:
395 ** 1. A read/write cursor pointing to pTab, the table containing the row
396 ** to be deleted, must be opened as cursor number "iCur".
398 ** 2. Read/write cursors for all indices of pTab must be open as
399 ** cursor number iCur+i for the i-th index.
401 ** 3. The "iCur" cursor must be pointing to the row that is to be
402 ** deleted.
404 void sqlite3GenerateRowIndexDelete(
405 sqlite3 *db, /* The database containing the index */
406 Vdbe *v, /* Generate code into this VDBE */
407 Table *pTab, /* Table containing the row to be deleted */
408 int iCur, /* Cursor number for the table */
409 char *aIdxUsed /* Only delete if aIdxUsed!=0 && aIdxUsed[i]!=0 */
411 int i;
412 Index *pIdx;
414 for(i=1, pIdx=pTab->pIndex; pIdx; i++, pIdx=pIdx->pNext){
415 if( aIdxUsed!=0 && aIdxUsed[i-1]==0 ) continue;
416 sqlite3GenerateIndexKey(v, pIdx, iCur);
417 sqlite3VdbeAddOp(v, OP_IdxDelete, iCur+i, 0);
422 ** Generate code that will assemble an index key and put it on the top
423 ** of the tack. The key with be for index pIdx which is an index on pTab.
424 ** iCur is the index of a cursor open on the pTab table and pointing to
425 ** the entry that needs indexing.
427 void sqlite3GenerateIndexKey(
428 Vdbe *v, /* Generate code into this VDBE */
429 Index *pIdx, /* The index for which to generate a key */
430 int iCur /* Cursor number for the pIdx->pTable table */
432 int j;
433 Table *pTab = pIdx->pTable;
435 sqlite3VdbeAddOp(v, OP_Rowid, iCur, 0);
436 for(j=0; j<pIdx->nColumn; j++){
437 int idx = pIdx->aiColumn[j];
438 if( idx==pTab->iPKey ){
439 sqlite3VdbeAddOp(v, OP_Dup, j, 0);
440 }else{
441 sqlite3VdbeAddOp(v, OP_Column, iCur, idx);
442 sqlite3ColumnDefault(v, pTab, idx);
445 sqlite3VdbeAddOp(v, OP_MakeRecord, pIdx->nColumn, (1<<24));
446 sqlite3IndexAffinityStr(v, pIdx);