update.c 24 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675
  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 UPDATE statements.
  14. */
  15. #include "sqliteInt.h"
  16. #ifndef SQLITE_OMIT_VIRTUALTABLE
  17. /* Forward declaration */
  18. static void updateVirtualTable(
  19. Parse *pParse, /* The parsing context */
  20. SrcList *pSrc, /* The virtual table to be modified */
  21. Table *pTab, /* The virtual table */
  22. ExprList *pChanges, /* The columns to change in the UPDATE statement */
  23. Expr *pRowidExpr, /* Expression used to recompute the rowid */
  24. int *aXRef, /* Mapping from columns of pTab to entries in pChanges */
  25. Expr *pWhere, /* WHERE clause of the UPDATE statement */
  26. int onError /* ON CONFLICT strategy */
  27. );
  28. #endif /* SQLITE_OMIT_VIRTUALTABLE */
  29. /*
  30. ** The most recently coded instruction was an OP_Column to retrieve the
  31. ** i-th column of table pTab. This routine sets the P4 parameter of the
  32. ** OP_Column to the default value, if any.
  33. **
  34. ** The default value of a column is specified by a DEFAULT clause in the
  35. ** column definition. This was either supplied by the user when the table
  36. ** was created, or added later to the table definition by an ALTER TABLE
  37. ** command. If the latter, then the row-records in the table btree on disk
  38. ** may not contain a value for the column and the default value, taken
  39. ** from the P4 parameter of the OP_Column instruction, is returned instead.
  40. ** If the former, then all row-records are guaranteed to include a value
  41. ** for the column and the P4 value is not required.
  42. **
  43. ** Column definitions created by an ALTER TABLE command may only have
  44. ** literal default values specified: a number, null or a string. (If a more
  45. ** complicated default expression value was provided, it is evaluated
  46. ** when the ALTER TABLE is executed and one of the literal values written
  47. ** into the sqlite_master table.)
  48. **
  49. ** Therefore, the P4 parameter is only required if the default value for
  50. ** the column is a literal number, string or null. The sqlite3ValueFromExpr()
  51. ** function is capable of transforming these types of expressions into
  52. ** sqlite3_value objects.
  53. **
  54. ** If parameter iReg is not negative, code an OP_RealAffinity instruction
  55. ** on register iReg. This is used when an equivalent integer value is
  56. ** stored in place of an 8-byte floating point value in order to save
  57. ** space.
  58. */
  59. void sqlite3ColumnDefault(Vdbe *v, Table *pTab, int i, int iReg){
  60. assert( pTab!=0 );
  61. if( !pTab->pSelect ){
  62. sqlite3_value *pValue = 0;
  63. u8 enc = ENC(sqlite3VdbeDb(v));
  64. Column *pCol = &pTab->aCol[i];
  65. VdbeComment((v, "%s.%s", pTab->zName, pCol->zName));
  66. assert( i<pTab->nCol );
  67. sqlite3ValueFromExpr(sqlite3VdbeDb(v), pCol->pDflt, enc,
  68. pCol->affinity, &pValue);
  69. if( pValue ){
  70. sqlite3VdbeChangeP4(v, -1, (const char *)pValue, P4_MEM);
  71. }
  72. #ifndef SQLITE_OMIT_FLOATING_POINT
  73. if( iReg>=0 && pTab->aCol[i].affinity==SQLITE_AFF_REAL ){
  74. sqlite3VdbeAddOp1(v, OP_RealAffinity, iReg);
  75. }
  76. #endif
  77. }
  78. }
  79. /*
  80. ** Process an UPDATE statement.
  81. **
  82. ** UPDATE OR IGNORE table_wxyz SET a=b, c=d WHERE e<5 AND f NOT NULL;
  83. ** \_______/ \________/ \______/ \________________/
  84. * onError pTabList pChanges pWhere
  85. */
  86. void sqlite3Update(
  87. Parse *pParse, /* The parser context */
  88. SrcList *pTabList, /* The table in which we should change things */
  89. ExprList *pChanges, /* Things to be changed */
  90. Expr *pWhere, /* The WHERE clause. May be null */
  91. int onError /* How to handle constraint errors */
  92. ){
  93. int i, j; /* Loop counters */
  94. Table *pTab; /* The table to be updated */
  95. int addr = 0; /* VDBE instruction address of the start of the loop */
  96. WhereInfo *pWInfo; /* Information about the WHERE clause */
  97. Vdbe *v; /* The virtual database engine */
  98. Index *pIdx; /* For looping over indices */
  99. int nIdx; /* Number of indices that need updating */
  100. int iCur; /* VDBE Cursor number of pTab */
  101. sqlite3 *db; /* The database structure */
  102. int *aRegIdx = 0; /* One register assigned to each index to be updated */
  103. int *aXRef = 0; /* aXRef[i] is the index in pChanges->a[] of the
  104. ** an expression for the i-th column of the table.
  105. ** aXRef[i]==-1 if the i-th column is not changed. */
  106. int chngRowid; /* True if the record number is being changed */
  107. Expr *pRowidExpr = 0; /* Expression defining the new record number */
  108. int openAll = 0; /* True if all indices need to be opened */
  109. AuthContext sContext; /* The authorization context */
  110. NameContext sNC; /* The name-context to resolve expressions in */
  111. int iDb; /* Database containing the table being updated */
  112. int okOnePass; /* True for one-pass algorithm without the FIFO */
  113. int hasFK; /* True if foreign key processing is required */
  114. #ifndef SQLITE_OMIT_TRIGGER
  115. int isView; /* True when updating a view (INSTEAD OF trigger) */
  116. Trigger *pTrigger; /* List of triggers on pTab, if required */
  117. int tmask; /* Mask of TRIGGER_BEFORE|TRIGGER_AFTER */
  118. #endif
  119. int newmask; /* Mask of NEW.* columns accessed by BEFORE triggers */
  120. /* Register Allocations */
  121. int regRowCount = 0; /* A count of rows changed */
  122. int regOldRowid; /* The old rowid */
  123. int regNewRowid; /* The new rowid */
  124. int regNew; /* Content of the NEW.* table in triggers */
  125. int regOld = 0; /* Content of OLD.* table in triggers */
  126. int regRowSet = 0; /* Rowset of rows to be updated */
  127. memset(&sContext, 0, sizeof(sContext));
  128. db = pParse->db;
  129. if( pParse->nErr || db->mallocFailed ){
  130. goto update_cleanup;
  131. }
  132. assert( pTabList->nSrc==1 );
  133. /* Locate the table which we want to update.
  134. */
  135. pTab = sqlite3SrcListLookup(pParse, pTabList);
  136. if( pTab==0 ) goto update_cleanup;
  137. iDb = sqlite3SchemaToIndex(pParse->db, pTab->pSchema);
  138. /* Figure out if we have any triggers and if the table being
  139. ** updated is a view.
  140. */
  141. #ifndef SQLITE_OMIT_TRIGGER
  142. pTrigger = sqlite3TriggersExist(pParse, pTab, TK_UPDATE, pChanges, &tmask);
  143. isView = pTab->pSelect!=0;
  144. assert( pTrigger || tmask==0 );
  145. #else
  146. # define pTrigger 0
  147. # define isView 0
  148. # define tmask 0
  149. #endif
  150. #ifdef SQLITE_OMIT_VIEW
  151. # undef isView
  152. # define isView 0
  153. #endif
  154. if( sqlite3ViewGetColumnNames(pParse, pTab) ){
  155. goto update_cleanup;
  156. }
  157. if( sqlite3IsReadOnly(pParse, pTab, tmask) ){
  158. goto update_cleanup;
  159. }
  160. aXRef = sqlite3DbMallocRaw(db, sizeof(int) * pTab->nCol );
  161. if( aXRef==0 ) goto update_cleanup;
  162. for(i=0; i<pTab->nCol; i++) aXRef[i] = -1;
  163. /* Allocate a cursors for the main database table and for all indices.
  164. ** The index cursors might not be used, but if they are used they
  165. ** need to occur right after the database cursor. So go ahead and
  166. ** allocate enough space, just in case.
  167. */
  168. pTabList->a[0].iCursor = iCur = pParse->nTab++;
  169. for(pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext){
  170. pParse->nTab++;
  171. }
  172. /* Initialize the name-context */
  173. memset(&sNC, 0, sizeof(sNC));
  174. sNC.pParse = pParse;
  175. sNC.pSrcList = pTabList;
  176. /* Resolve the column names in all the expressions of the
  177. ** of the UPDATE statement. Also find the column index
  178. ** for each column to be updated in the pChanges array. For each
  179. ** column to be updated, make sure we have authorization to change
  180. ** that column.
  181. */
  182. chngRowid = 0;
  183. for(i=0; i<pChanges->nExpr; i++){
  184. if( sqlite3ResolveExprNames(&sNC, pChanges->a[i].pExpr) ){
  185. goto update_cleanup;
  186. }
  187. for(j=0; j<pTab->nCol; j++){
  188. if( sqlite3StrICmp(pTab->aCol[j].zName, pChanges->a[i].zName)==0 ){
  189. if( j==pTab->iPKey ){
  190. chngRowid = 1;
  191. pRowidExpr = pChanges->a[i].pExpr;
  192. }
  193. aXRef[j] = i;
  194. break;
  195. }
  196. }
  197. if( j>=pTab->nCol ){
  198. if( sqlite3IsRowid(pChanges->a[i].zName) ){
  199. j = -1;
  200. chngRowid = 1;
  201. pRowidExpr = pChanges->a[i].pExpr;
  202. }else{
  203. sqlite3ErrorMsg(pParse, "no such column: %s", pChanges->a[i].zName);
  204. pParse->checkSchema = 1;
  205. goto update_cleanup;
  206. }
  207. }
  208. #ifndef SQLITE_OMIT_AUTHORIZATION
  209. {
  210. int rc;
  211. rc = sqlite3AuthCheck(pParse, SQLITE_UPDATE, pTab->zName,
  212. j<0 ? "ROWID" : pTab->aCol[j].zName,
  213. db->aDb[iDb].zName);
  214. if( rc==SQLITE_DENY ){
  215. goto update_cleanup;
  216. }else if( rc==SQLITE_IGNORE ){
  217. aXRef[j] = -1;
  218. }
  219. }
  220. #endif
  221. }
  222. hasFK = sqlite3FkRequired(pParse, pTab, aXRef, chngRowid);
  223. /* Allocate memory for the array aRegIdx[]. There is one entry in the
  224. ** array for each index associated with table being updated. Fill in
  225. ** the value with a register number for indices that are to be used
  226. ** and with zero for unused indices.
  227. */
  228. for(nIdx=0, pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext, nIdx++){}
  229. if( nIdx>0 ){
  230. aRegIdx = sqlite3DbMallocRaw(db, sizeof(Index*) * nIdx );
  231. if( aRegIdx==0 ) goto update_cleanup;
  232. }
  233. for(j=0, pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext, j++){
  234. int reg;
  235. if( hasFK || chngRowid || pIdx->pPartIdxWhere ){
  236. reg = ++pParse->nMem;
  237. }else{
  238. reg = 0;
  239. for(i=0; i<pIdx->nColumn; i++){
  240. if( aXRef[pIdx->aiColumn[i]]>=0 ){
  241. reg = ++pParse->nMem;
  242. break;
  243. }
  244. }
  245. }
  246. aRegIdx[j] = reg;
  247. }
  248. /* Begin generating code. */
  249. v = sqlite3GetVdbe(pParse);
  250. if( v==0 ) goto update_cleanup;
  251. if( pParse->nested==0 ) sqlite3VdbeCountChanges(v);
  252. sqlite3BeginWriteOperation(pParse, 1, iDb);
  253. #ifndef SQLITE_OMIT_VIRTUALTABLE
  254. /* Virtual tables must be handled separately */
  255. if( IsVirtual(pTab) ){
  256. updateVirtualTable(pParse, pTabList, pTab, pChanges, pRowidExpr, aXRef,
  257. pWhere, onError);
  258. pWhere = 0;
  259. pTabList = 0;
  260. goto update_cleanup;
  261. }
  262. #endif
  263. /* Allocate required registers. */
  264. regRowSet = ++pParse->nMem;
  265. regOldRowid = regNewRowid = ++pParse->nMem;
  266. if( pTrigger || hasFK ){
  267. regOld = pParse->nMem + 1;
  268. pParse->nMem += pTab->nCol;
  269. }
  270. if( chngRowid || pTrigger || hasFK ){
  271. regNewRowid = ++pParse->nMem;
  272. }
  273. regNew = pParse->nMem + 1;
  274. pParse->nMem += pTab->nCol;
  275. /* Start the view context. */
  276. if( isView ){
  277. sqlite3AuthContextPush(pParse, &sContext, pTab->zName);
  278. }
  279. /* If we are trying to update a view, realize that view into
  280. ** a ephemeral table.
  281. */
  282. #if !defined(SQLITE_OMIT_VIEW) && !defined(SQLITE_OMIT_TRIGGER)
  283. if( isView ){
  284. sqlite3MaterializeView(pParse, pTab, pWhere, iCur);
  285. }
  286. #endif
  287. /* Resolve the column names in all the expressions in the
  288. ** WHERE clause.
  289. */
  290. if( sqlite3ResolveExprNames(&sNC, pWhere) ){
  291. goto update_cleanup;
  292. }
  293. /* Begin the database scan
  294. */
  295. sqlite3VdbeAddOp3(v, OP_Null, 0, regRowSet, regOldRowid);
  296. pWInfo = sqlite3WhereBegin(
  297. pParse, pTabList, pWhere, 0, 0, WHERE_ONEPASS_DESIRED, 0
  298. );
  299. if( pWInfo==0 ) goto update_cleanup;
  300. okOnePass = sqlite3WhereOkOnePass(pWInfo);
  301. /* Remember the rowid of every item to be updated.
  302. */
  303. sqlite3VdbeAddOp2(v, OP_Rowid, iCur, regOldRowid);
  304. if( !okOnePass ){
  305. sqlite3VdbeAddOp2(v, OP_RowSetAdd, regRowSet, regOldRowid);
  306. }
  307. /* End the database scan loop.
  308. */
  309. sqlite3WhereEnd(pWInfo);
  310. /* Initialize the count of updated rows
  311. */
  312. if( (db->flags & SQLITE_CountRows) && !pParse->pTriggerTab ){
  313. regRowCount = ++pParse->nMem;
  314. sqlite3VdbeAddOp2(v, OP_Integer, 0, regRowCount);
  315. }
  316. if( !isView ){
  317. /*
  318. ** Open every index that needs updating. Note that if any
  319. ** index could potentially invoke a REPLACE conflict resolution
  320. ** action, then we need to open all indices because we might need
  321. ** to be deleting some records.
  322. */
  323. if( !okOnePass ) sqlite3OpenTable(pParse, iCur, iDb, pTab, OP_OpenWrite);
  324. if( onError==OE_Replace ){
  325. openAll = 1;
  326. }else{
  327. openAll = 0;
  328. for(pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext){
  329. if( pIdx->onError==OE_Replace ){
  330. openAll = 1;
  331. break;
  332. }
  333. }
  334. }
  335. for(i=0, pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext, i++){
  336. assert( aRegIdx );
  337. if( openAll || aRegIdx[i]>0 ){
  338. KeyInfo *pKey = sqlite3IndexKeyinfo(pParse, pIdx);
  339. sqlite3VdbeAddOp4(v, OP_OpenWrite, iCur+i+1, pIdx->tnum, iDb,
  340. (char*)pKey, P4_KEYINFO_HANDOFF);
  341. assert( pParse->nTab>iCur+i+1 );
  342. }
  343. }
  344. }
  345. /* Top of the update loop */
  346. if( okOnePass ){
  347. int a1 = sqlite3VdbeAddOp1(v, OP_NotNull, regOldRowid);
  348. addr = sqlite3VdbeAddOp0(v, OP_Goto);
  349. sqlite3VdbeJumpHere(v, a1);
  350. }else{
  351. addr = sqlite3VdbeAddOp3(v, OP_RowSetRead, regRowSet, 0, regOldRowid);
  352. }
  353. /* Make cursor iCur point to the record that is being updated. If
  354. ** this record does not exist for some reason (deleted by a trigger,
  355. ** for example, then jump to the next iteration of the RowSet loop. */
  356. sqlite3VdbeAddOp3(v, OP_NotExists, iCur, addr, regOldRowid);
  357. /* If the record number will change, set register regNewRowid to
  358. ** contain the new value. If the record number is not being modified,
  359. ** then regNewRowid is the same register as regOldRowid, which is
  360. ** already populated. */
  361. assert( chngRowid || pTrigger || hasFK || regOldRowid==regNewRowid );
  362. if( chngRowid ){
  363. sqlite3ExprCode(pParse, pRowidExpr, regNewRowid);
  364. sqlite3VdbeAddOp1(v, OP_MustBeInt, regNewRowid);
  365. }
  366. /* If there are triggers on this table, populate an array of registers
  367. ** with the required old.* column data. */
  368. if( hasFK || pTrigger ){
  369. u32 oldmask = (hasFK ? sqlite3FkOldmask(pParse, pTab) : 0);
  370. oldmask |= sqlite3TriggerColmask(pParse,
  371. pTrigger, pChanges, 0, TRIGGER_BEFORE|TRIGGER_AFTER, pTab, onError
  372. );
  373. for(i=0; i<pTab->nCol; i++){
  374. if( aXRef[i]<0 || oldmask==0xffffffff || (i<32 && (oldmask & (1<<i))) ){
  375. sqlite3ExprCodeGetColumnOfTable(v, pTab, iCur, i, regOld+i);
  376. }else{
  377. sqlite3VdbeAddOp2(v, OP_Null, 0, regOld+i);
  378. }
  379. }
  380. if( chngRowid==0 ){
  381. sqlite3VdbeAddOp2(v, OP_Copy, regOldRowid, regNewRowid);
  382. }
  383. }
  384. /* Populate the array of registers beginning at regNew with the new
  385. ** row data. This array is used to check constaints, create the new
  386. ** table and index records, and as the values for any new.* references
  387. ** made by triggers.
  388. **
  389. ** If there are one or more BEFORE triggers, then do not populate the
  390. ** registers associated with columns that are (a) not modified by
  391. ** this UPDATE statement and (b) not accessed by new.* references. The
  392. ** values for registers not modified by the UPDATE must be reloaded from
  393. ** the database after the BEFORE triggers are fired anyway (as the trigger
  394. ** may have modified them). So not loading those that are not going to
  395. ** be used eliminates some redundant opcodes.
  396. */
  397. newmask = sqlite3TriggerColmask(
  398. pParse, pTrigger, pChanges, 1, TRIGGER_BEFORE, pTab, onError
  399. );
  400. sqlite3VdbeAddOp3(v, OP_Null, 0, regNew, regNew+pTab->nCol-1);
  401. for(i=0; i<pTab->nCol; i++){
  402. if( i==pTab->iPKey ){
  403. /*sqlite3VdbeAddOp2(v, OP_Null, 0, regNew+i);*/
  404. }else{
  405. j = aXRef[i];
  406. if( j>=0 ){
  407. sqlite3ExprCode(pParse, pChanges->a[j].pExpr, regNew+i);
  408. }else if( 0==(tmask&TRIGGER_BEFORE) || i>31 || (newmask&(1<<i)) ){
  409. /* This branch loads the value of a column that will not be changed
  410. ** into a register. This is done if there are no BEFORE triggers, or
  411. ** if there are one or more BEFORE triggers that use this value via
  412. ** a new.* reference in a trigger program.
  413. */
  414. testcase( i==31 );
  415. testcase( i==32 );
  416. sqlite3VdbeAddOp3(v, OP_Column, iCur, i, regNew+i);
  417. sqlite3ColumnDefault(v, pTab, i, regNew+i);
  418. }
  419. }
  420. }
  421. /* Fire any BEFORE UPDATE triggers. This happens before constraints are
  422. ** verified. One could argue that this is wrong.
  423. */
  424. if( tmask&TRIGGER_BEFORE ){
  425. sqlite3VdbeAddOp2(v, OP_Affinity, regNew, pTab->nCol);
  426. sqlite3TableAffinityStr(v, pTab);
  427. sqlite3CodeRowTrigger(pParse, pTrigger, TK_UPDATE, pChanges,
  428. TRIGGER_BEFORE, pTab, regOldRowid, onError, addr);
  429. /* The row-trigger may have deleted the row being updated. In this
  430. ** case, jump to the next row. No updates or AFTER triggers are
  431. ** required. This behavior - what happens when the row being updated
  432. ** is deleted or renamed by a BEFORE trigger - is left undefined in the
  433. ** documentation.
  434. */
  435. sqlite3VdbeAddOp3(v, OP_NotExists, iCur, addr, regOldRowid);
  436. /* If it did not delete it, the row-trigger may still have modified
  437. ** some of the columns of the row being updated. Load the values for
  438. ** all columns not modified by the update statement into their
  439. ** registers in case this has happened.
  440. */
  441. for(i=0; i<pTab->nCol; i++){
  442. if( aXRef[i]<0 && i!=pTab->iPKey ){
  443. sqlite3VdbeAddOp3(v, OP_Column, iCur, i, regNew+i);
  444. sqlite3ColumnDefault(v, pTab, i, regNew+i);
  445. }
  446. }
  447. }
  448. if( !isView ){
  449. int j1; /* Address of jump instruction */
  450. /* Do constraint checks. */
  451. sqlite3GenerateConstraintChecks(pParse, pTab, iCur, regNewRowid,
  452. aRegIdx, (chngRowid?regOldRowid:0), 1, onError, addr, 0);
  453. /* Do FK constraint checks. */
  454. if( hasFK ){
  455. sqlite3FkCheck(pParse, pTab, regOldRowid, 0, aXRef, chngRowid);
  456. }
  457. /* Delete the index entries associated with the current record. */
  458. j1 = sqlite3VdbeAddOp3(v, OP_NotExists, iCur, 0, regOldRowid);
  459. sqlite3GenerateRowIndexDelete(pParse, pTab, iCur, aRegIdx);
  460. /* If changing the record number, delete the old record. */
  461. if( hasFK || chngRowid ){
  462. sqlite3VdbeAddOp2(v, OP_Delete, iCur, 0);
  463. }
  464. sqlite3VdbeJumpHere(v, j1);
  465. if( hasFK ){
  466. sqlite3FkCheck(pParse, pTab, 0, regNewRowid, aXRef, chngRowid);
  467. }
  468. /* Insert the new index entries and the new record. */
  469. sqlite3CompleteInsertion(pParse, pTab, iCur, regNewRowid, aRegIdx, 1, 0, 0);
  470. /* Do any ON CASCADE, SET NULL or SET DEFAULT operations required to
  471. ** handle rows (possibly in other tables) that refer via a foreign key
  472. ** to the row just updated. */
  473. if( hasFK ){
  474. sqlite3FkActions(pParse, pTab, pChanges, regOldRowid, aXRef, chngRowid);
  475. }
  476. }
  477. /* Increment the row counter
  478. */
  479. if( (db->flags & SQLITE_CountRows) && !pParse->pTriggerTab){
  480. sqlite3VdbeAddOp2(v, OP_AddImm, regRowCount, 1);
  481. }
  482. sqlite3CodeRowTrigger(pParse, pTrigger, TK_UPDATE, pChanges,
  483. TRIGGER_AFTER, pTab, regOldRowid, onError, addr);
  484. /* Repeat the above with the next record to be updated, until
  485. ** all record selected by the WHERE clause have been updated.
  486. */
  487. sqlite3VdbeAddOp2(v, OP_Goto, 0, addr);
  488. sqlite3VdbeJumpHere(v, addr);
  489. /* Close all tables */
  490. for(i=0, pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext, i++){
  491. assert( aRegIdx );
  492. if( openAll || aRegIdx[i]>0 ){
  493. sqlite3VdbeAddOp2(v, OP_Close, iCur+i+1, 0);
  494. }
  495. }
  496. sqlite3VdbeAddOp2(v, OP_Close, iCur, 0);
  497. /* Update the sqlite_sequence table by storing the content of the
  498. ** maximum rowid counter values recorded while inserting into
  499. ** autoincrement tables.
  500. */
  501. if( pParse->nested==0 && pParse->pTriggerTab==0 ){
  502. sqlite3AutoincrementEnd(pParse);
  503. }
  504. /*
  505. ** Return the number of rows that were changed. If this routine is
  506. ** generating code because of a call to sqlite3NestedParse(), do not
  507. ** invoke the callback function.
  508. */
  509. if( (db->flags&SQLITE_CountRows) && !pParse->pTriggerTab && !pParse->nested ){
  510. sqlite3VdbeAddOp2(v, OP_ResultRow, regRowCount, 1);
  511. sqlite3VdbeSetNumCols(v, 1);
  512. sqlite3VdbeSetColName(v, 0, COLNAME_NAME, "rows updated", SQLITE_STATIC);
  513. }
  514. update_cleanup:
  515. sqlite3AuthContextPop(&sContext);
  516. sqlite3DbFree(db, aRegIdx);
  517. sqlite3DbFree(db, aXRef);
  518. sqlite3SrcListDelete(db, pTabList);
  519. sqlite3ExprListDelete(db, pChanges);
  520. sqlite3ExprDelete(db, pWhere);
  521. return;
  522. }
  523. /* Make sure "isView" and other macros defined above are undefined. Otherwise
  524. ** thely may interfere with compilation of other functions in this file
  525. ** (or in another file, if this file becomes part of the amalgamation). */
  526. #ifdef isView
  527. #undef isView
  528. #endif
  529. #ifdef pTrigger
  530. #undef pTrigger
  531. #endif
  532. #ifndef SQLITE_OMIT_VIRTUALTABLE
  533. /*
  534. ** Generate code for an UPDATE of a virtual table.
  535. **
  536. ** The strategy is that we create an ephemerial table that contains
  537. ** for each row to be changed:
  538. **
  539. ** (A) The original rowid of that row.
  540. ** (B) The revised rowid for the row. (note1)
  541. ** (C) The content of every column in the row.
  542. **
  543. ** Then we loop over this ephemeral table and for each row in
  544. ** the ephermeral table call VUpdate.
  545. **
  546. ** When finished, drop the ephemeral table.
  547. **
  548. ** (note1) Actually, if we know in advance that (A) is always the same
  549. ** as (B) we only store (A), then duplicate (A) when pulling
  550. ** it out of the ephemeral table before calling VUpdate.
  551. */
  552. static void updateVirtualTable(
  553. Parse *pParse, /* The parsing context */
  554. SrcList *pSrc, /* The virtual table to be modified */
  555. Table *pTab, /* The virtual table */
  556. ExprList *pChanges, /* The columns to change in the UPDATE statement */
  557. Expr *pRowid, /* Expression used to recompute the rowid */
  558. int *aXRef, /* Mapping from columns of pTab to entries in pChanges */
  559. Expr *pWhere, /* WHERE clause of the UPDATE statement */
  560. int onError /* ON CONFLICT strategy */
  561. ){
  562. Vdbe *v = pParse->pVdbe; /* Virtual machine under construction */
  563. ExprList *pEList = 0; /* The result set of the SELECT statement */
  564. Select *pSelect = 0; /* The SELECT statement */
  565. Expr *pExpr; /* Temporary expression */
  566. int ephemTab; /* Table holding the result of the SELECT */
  567. int i; /* Loop counter */
  568. int addr; /* Address of top of loop */
  569. int iReg; /* First register in set passed to OP_VUpdate */
  570. sqlite3 *db = pParse->db; /* Database connection */
  571. const char *pVTab = (const char*)sqlite3GetVTable(db, pTab);
  572. SelectDest dest;
  573. /* Construct the SELECT statement that will find the new values for
  574. ** all updated rows.
  575. */
  576. pEList = sqlite3ExprListAppend(pParse, 0, sqlite3Expr(db, TK_ID, "_rowid_"));
  577. if( pRowid ){
  578. pEList = sqlite3ExprListAppend(pParse, pEList,
  579. sqlite3ExprDup(db, pRowid, 0));
  580. }
  581. assert( pTab->iPKey<0 );
  582. for(i=0; i<pTab->nCol; i++){
  583. if( aXRef[i]>=0 ){
  584. pExpr = sqlite3ExprDup(db, pChanges->a[aXRef[i]].pExpr, 0);
  585. }else{
  586. pExpr = sqlite3Expr(db, TK_ID, pTab->aCol[i].zName);
  587. }
  588. pEList = sqlite3ExprListAppend(pParse, pEList, pExpr);
  589. }
  590. pSelect = sqlite3SelectNew(pParse, pEList, pSrc, pWhere, 0, 0, 0, 0, 0, 0);
  591. /* Create the ephemeral table into which the update results will
  592. ** be stored.
  593. */
  594. assert( v );
  595. ephemTab = pParse->nTab++;
  596. sqlite3VdbeAddOp2(v, OP_OpenEphemeral, ephemTab, pTab->nCol+1+(pRowid!=0));
  597. sqlite3VdbeChangeP5(v, BTREE_UNORDERED);
  598. /* fill the ephemeral table
  599. */
  600. sqlite3SelectDestInit(&dest, SRT_Table, ephemTab);
  601. sqlite3Select(pParse, pSelect, &dest);
  602. /* Generate code to scan the ephemeral table and call VUpdate. */
  603. iReg = ++pParse->nMem;
  604. pParse->nMem += pTab->nCol+1;
  605. addr = sqlite3VdbeAddOp2(v, OP_Rewind, ephemTab, 0);
  606. sqlite3VdbeAddOp3(v, OP_Column, ephemTab, 0, iReg);
  607. sqlite3VdbeAddOp3(v, OP_Column, ephemTab, (pRowid?1:0), iReg+1);
  608. for(i=0; i<pTab->nCol; i++){
  609. sqlite3VdbeAddOp3(v, OP_Column, ephemTab, i+1+(pRowid!=0), iReg+2+i);
  610. }
  611. sqlite3VtabMakeWritable(pParse, pTab);
  612. sqlite3VdbeAddOp4(v, OP_VUpdate, 0, pTab->nCol+2, iReg, pVTab, P4_VTAB);
  613. sqlite3VdbeChangeP5(v, onError==OE_Default ? OE_Abort : onError);
  614. sqlite3MayAbort(pParse);
  615. sqlite3VdbeAddOp2(v, OP_Next, ephemTab, addr+1);
  616. sqlite3VdbeJumpHere(v, addr);
  617. sqlite3VdbeAddOp2(v, OP_Close, ephemTab, 0);
  618. /* Cleanup */
  619. sqlite3SelectDelete(db, pSelect);
  620. }
  621. #endif /* SQLITE_OMIT_VIRTUALTABLE */