insert.c 56 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627
  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 INSERT statements in SQLite.
  14. **
  15. ** $Id: insert.c,v 1.197 2007/12/14 16:11:09 drh Exp $
  16. */
  17. #include "sqliteInt.h"
  18. /*
  19. ** Set P3 of the most recently inserted opcode to a column affinity
  20. ** string for index pIdx. A column affinity string has one character
  21. ** for each column in the table, according to the affinity of the column:
  22. **
  23. ** Character Column affinity
  24. ** ------------------------------
  25. ** 'a' TEXT
  26. ** 'b' NONE
  27. ** 'c' NUMERIC
  28. ** 'd' INTEGER
  29. ** 'e' REAL
  30. */
  31. void sqlite3IndexAffinityStr(Vdbe *v, Index *pIdx){
  32. if( !pIdx->zColAff ){
  33. /* The first time a column affinity string for a particular index is
  34. ** required, it is allocated and populated here. It is then stored as
  35. ** a member of the Index structure for subsequent use.
  36. **
  37. ** The column affinity string will eventually be deleted by
  38. ** sqliteDeleteIndex() when the Index structure itself is cleaned
  39. ** up.
  40. */
  41. int n;
  42. Table *pTab = pIdx->pTable;
  43. sqlite3 *db = sqlite3VdbeDb(v);
  44. pIdx->zColAff = (char *)sqlite3DbMallocZero(db, pIdx->nColumn+1);
  45. if( !pIdx->zColAff ){
  46. return;
  47. }
  48. for(n=0; n<pIdx->nColumn; n++){
  49. pIdx->zColAff[n] = pTab->aCol[pIdx->aiColumn[n]].affinity;
  50. }
  51. pIdx->zColAff[pIdx->nColumn] = '\0';
  52. }
  53. sqlite3VdbeChangeP3(v, -1, pIdx->zColAff, 0);
  54. }
  55. /*
  56. ** Set P3 of the most recently inserted opcode to a column affinity
  57. ** string for table pTab. A column affinity string has one character
  58. ** for each column indexed by the index, according to the affinity of the
  59. ** column:
  60. **
  61. ** Character Column affinity
  62. ** ------------------------------
  63. ** 'a' TEXT
  64. ** 'b' NONE
  65. ** 'c' NUMERIC
  66. ** 'd' INTEGER
  67. ** 'e' REAL
  68. */
  69. void sqlite3TableAffinityStr(Vdbe *v, Table *pTab){
  70. /* The first time a column affinity string for a particular table
  71. ** is required, it is allocated and populated here. It is then
  72. ** stored as a member of the Table structure for subsequent use.
  73. **
  74. ** The column affinity string will eventually be deleted by
  75. ** sqlite3DeleteTable() when the Table structure itself is cleaned up.
  76. */
  77. if( !pTab->zColAff ){
  78. char *zColAff;
  79. int i;
  80. sqlite3 *db = sqlite3VdbeDb(v);
  81. zColAff = (char *)sqlite3DbMallocZero(db, pTab->nCol+1);
  82. if( !zColAff ){
  83. return;
  84. }
  85. for(i=0; i<pTab->nCol; i++){
  86. zColAff[i] = pTab->aCol[i].affinity;
  87. }
  88. zColAff[pTab->nCol] = '\0';
  89. pTab->zColAff = zColAff;
  90. }
  91. sqlite3VdbeChangeP3(v, -1, pTab->zColAff, 0);
  92. }
  93. /*
  94. ** Return non-zero if the table pTab in database iDb or any of its indices
  95. ** have been opened at any point in the VDBE program beginning at location
  96. ** iStartAddr throught the end of the program. This is used to see if
  97. ** a statement of the form "INSERT INTO <iDb, pTab> SELECT ..." can
  98. ** run without using temporary table for the results of the SELECT.
  99. */
  100. static int readsTable(Vdbe *v, int iStartAddr, int iDb, Table *pTab){
  101. int i;
  102. int iEnd = sqlite3VdbeCurrentAddr(v);
  103. for(i=iStartAddr; i<iEnd; i++){
  104. VdbeOp *pOp = sqlite3VdbeGetOp(v, i);
  105. assert( pOp!=0 );
  106. if( pOp->opcode==OP_OpenRead ){
  107. VdbeOp *pPrior = &pOp[-1];
  108. int tnum = pOp->p2;
  109. assert( i>iStartAddr );
  110. assert( pPrior->opcode==OP_Integer );
  111. if( pPrior->p1==iDb ){
  112. Index *pIndex;
  113. if( tnum==pTab->tnum ){
  114. return 1;
  115. }
  116. for(pIndex=pTab->pIndex; pIndex; pIndex=pIndex->pNext){
  117. if( tnum==pIndex->tnum ){
  118. return 1;
  119. }
  120. }
  121. }
  122. }
  123. #ifndef SQLITE_OMIT_VIRTUALTABLE
  124. if( pOp->opcode==OP_VOpen && pOp->p3==(const char*)pTab->pVtab ){
  125. assert( pOp->p3!=0 );
  126. assert( pOp->p3type==P3_VTAB );
  127. return 1;
  128. }
  129. #endif
  130. }
  131. return 0;
  132. }
  133. #ifndef SQLITE_OMIT_AUTOINCREMENT
  134. /*
  135. ** Write out code to initialize the autoincrement logic. This code
  136. ** looks up the current autoincrement value in the sqlite_sequence
  137. ** table and stores that value in a memory cell. Code generated by
  138. ** autoIncStep() will keep that memory cell holding the largest
  139. ** rowid value. Code generated by autoIncEnd() will write the new
  140. ** largest value of the counter back into the sqlite_sequence table.
  141. **
  142. ** This routine returns the index of the mem[] cell that contains
  143. ** the maximum rowid counter.
  144. **
  145. ** Two memory cells are allocated. The next memory cell after the
  146. ** one returned holds the rowid in sqlite_sequence where we will
  147. ** write back the revised maximum rowid.
  148. */
  149. static int autoIncBegin(
  150. Parse *pParse, /* Parsing context */
  151. int iDb, /* Index of the database holding pTab */
  152. Table *pTab /* The table we are writing to */
  153. ){
  154. int memId = 0;
  155. if( pTab->autoInc ){
  156. Vdbe *v = pParse->pVdbe;
  157. Db *pDb = &pParse->db->aDb[iDb];
  158. int iCur = pParse->nTab;
  159. int addr;
  160. assert( v );
  161. addr = sqlite3VdbeCurrentAddr(v);
  162. memId = pParse->nMem+1;
  163. pParse->nMem += 2;
  164. sqlite3OpenTable(pParse, iCur, iDb, pDb->pSchema->pSeqTab, OP_OpenRead);
  165. sqlite3VdbeAddOp(v, OP_Rewind, iCur, addr+13);
  166. sqlite3VdbeAddOp(v, OP_Column, iCur, 0);
  167. sqlite3VdbeOp3(v, OP_String8, 0, 0, pTab->zName, 0);
  168. sqlite3VdbeAddOp(v, OP_Ne, 0x100, addr+12);
  169. sqlite3VdbeAddOp(v, OP_Rowid, iCur, 0);
  170. sqlite3VdbeAddOp(v, OP_MemStore, memId-1, 1);
  171. sqlite3VdbeAddOp(v, OP_Column, iCur, 1);
  172. sqlite3VdbeAddOp(v, OP_MemStore, memId, 1);
  173. sqlite3VdbeAddOp(v, OP_Goto, 0, addr+13);
  174. sqlite3VdbeAddOp(v, OP_Next, iCur, addr+4);
  175. sqlite3VdbeAddOp(v, OP_Close, iCur, 0);
  176. }
  177. return memId;
  178. }
  179. /*
  180. ** Update the maximum rowid for an autoincrement calculation.
  181. **
  182. ** This routine should be called when the top of the stack holds a
  183. ** new rowid that is about to be inserted. If that new rowid is
  184. ** larger than the maximum rowid in the memId memory cell, then the
  185. ** memory cell is updated. The stack is unchanged.
  186. */
  187. static void autoIncStep(Parse *pParse, int memId){
  188. if( memId>0 ){
  189. sqlite3VdbeAddOp(pParse->pVdbe, OP_MemMax, memId, 0);
  190. }
  191. }
  192. /*
  193. ** After doing one or more inserts, the maximum rowid is stored
  194. ** in mem[memId]. Generate code to write this value back into the
  195. ** the sqlite_sequence table.
  196. */
  197. static void autoIncEnd(
  198. Parse *pParse, /* The parsing context */
  199. int iDb, /* Index of the database holding pTab */
  200. Table *pTab, /* Table we are inserting into */
  201. int memId /* Memory cell holding the maximum rowid */
  202. ){
  203. if( pTab->autoInc ){
  204. int iCur = pParse->nTab;
  205. Vdbe *v = pParse->pVdbe;
  206. Db *pDb = &pParse->db->aDb[iDb];
  207. int addr;
  208. assert( v );
  209. addr = sqlite3VdbeCurrentAddr(v);
  210. sqlite3OpenTable(pParse, iCur, iDb, pDb->pSchema->pSeqTab, OP_OpenWrite);
  211. sqlite3VdbeAddOp(v, OP_MemLoad, memId-1, 0);
  212. sqlite3VdbeAddOp(v, OP_NotNull, -1, addr+7);
  213. sqlite3VdbeAddOp(v, OP_Pop, 1, 0);
  214. sqlite3VdbeAddOp(v, OP_NewRowid, iCur, 0);
  215. sqlite3VdbeOp3(v, OP_String8, 0, 0, pTab->zName, 0);
  216. sqlite3VdbeAddOp(v, OP_MemLoad, memId, 0);
  217. sqlite3VdbeAddOp(v, OP_MakeRecord, 2, 0);
  218. sqlite3VdbeAddOp(v, OP_Insert, iCur, OPFLAG_APPEND);
  219. sqlite3VdbeAddOp(v, OP_Close, iCur, 0);
  220. }
  221. }
  222. #else
  223. /*
  224. ** If SQLITE_OMIT_AUTOINCREMENT is defined, then the three routines
  225. ** above are all no-ops
  226. */
  227. # define autoIncBegin(A,B,C) (0)
  228. # define autoIncStep(A,B)
  229. # define autoIncEnd(A,B,C,D)
  230. #endif /* SQLITE_OMIT_AUTOINCREMENT */
  231. /* Forward declaration */
  232. static int xferOptimization(
  233. Parse *pParse, /* Parser context */
  234. Table *pDest, /* The table we are inserting into */
  235. Select *pSelect, /* A SELECT statement to use as the data source */
  236. int onError, /* How to handle constraint errors */
  237. int iDbDest /* The database of pDest */
  238. );
  239. /*
  240. ** This routine is call to handle SQL of the following forms:
  241. **
  242. ** insert into TABLE (IDLIST) values(EXPRLIST)
  243. ** insert into TABLE (IDLIST) select
  244. **
  245. ** The IDLIST following the table name is always optional. If omitted,
  246. ** then a list of all columns for the table is substituted. The IDLIST
  247. ** appears in the pColumn parameter. pColumn is NULL if IDLIST is omitted.
  248. **
  249. ** The pList parameter holds EXPRLIST in the first form of the INSERT
  250. ** statement above, and pSelect is NULL. For the second form, pList is
  251. ** NULL and pSelect is a pointer to the select statement used to generate
  252. ** data for the insert.
  253. **
  254. ** The code generated follows one of four templates. For a simple
  255. ** select with data coming from a VALUES clause, the code executes
  256. ** once straight down through. The template looks like this:
  257. **
  258. ** open write cursor to <table> and its indices
  259. ** puts VALUES clause expressions onto the stack
  260. ** write the resulting record into <table>
  261. ** cleanup
  262. **
  263. ** The three remaining templates assume the statement is of the form
  264. **
  265. ** INSERT INTO <table> SELECT ...
  266. **
  267. ** If the SELECT clause is of the restricted form "SELECT * FROM <table2>" -
  268. ** in other words if the SELECT pulls all columns from a single table
  269. ** and there is no WHERE or LIMIT or GROUP BY or ORDER BY clauses, and
  270. ** if <table2> and <table1> are distinct tables but have identical
  271. ** schemas, including all the same indices, then a special optimization
  272. ** is invoked that copies raw records from <table2> over to <table1>.
  273. ** See the xferOptimization() function for the implementation of this
  274. ** template. This is the second template.
  275. **
  276. ** open a write cursor to <table>
  277. ** open read cursor on <table2>
  278. ** transfer all records in <table2> over to <table>
  279. ** close cursors
  280. ** foreach index on <table>
  281. ** open a write cursor on the <table> index
  282. ** open a read cursor on the corresponding <table2> index
  283. ** transfer all records from the read to the write cursors
  284. ** close cursors
  285. ** end foreach
  286. **
  287. ** The third template is for when the second template does not apply
  288. ** and the SELECT clause does not read from <table> at any time.
  289. ** The generated code follows this template:
  290. **
  291. ** goto B
  292. ** A: setup for the SELECT
  293. ** loop over the rows in the SELECT
  294. ** gosub C
  295. ** end loop
  296. ** cleanup after the SELECT
  297. ** goto D
  298. ** B: open write cursor to <table> and its indices
  299. ** goto A
  300. ** C: insert the select result into <table>
  301. ** return
  302. ** D: cleanup
  303. **
  304. ** The fourth template is used if the insert statement takes its
  305. ** values from a SELECT but the data is being inserted into a table
  306. ** that is also read as part of the SELECT. In the third form,
  307. ** we have to use a intermediate table to store the results of
  308. ** the select. The template is like this:
  309. **
  310. ** goto B
  311. ** A: setup for the SELECT
  312. ** loop over the tables in the SELECT
  313. ** gosub C
  314. ** end loop
  315. ** cleanup after the SELECT
  316. ** goto D
  317. ** C: insert the select result into the intermediate table
  318. ** return
  319. ** B: open a cursor to an intermediate table
  320. ** goto A
  321. ** D: open write cursor to <table> and its indices
  322. ** loop over the intermediate table
  323. ** transfer values form intermediate table into <table>
  324. ** end the loop
  325. ** cleanup
  326. */
  327. void sqlite3Insert(
  328. Parse *pParse, /* Parser context */
  329. SrcList *pTabList, /* Name of table into which we are inserting */
  330. ExprList *pList, /* List of values to be inserted */
  331. Select *pSelect, /* A SELECT statement to use as the data source */
  332. IdList *pColumn, /* Column names corresponding to IDLIST. */
  333. int onError /* How to handle constraint errors */
  334. ){
  335. Table *pTab; /* The table to insert into */
  336. char *zTab; /* Name of the table into which we are inserting */
  337. const char *zDb; /* Name of the database holding this table */
  338. int i, j, idx; /* Loop counters */
  339. Vdbe *v; /* Generate code into this virtual machine */
  340. Index *pIdx; /* For looping over indices of the table */
  341. int nColumn; /* Number of columns in the data */
  342. int base = 0; /* VDBE Cursor number for pTab */
  343. int iCont=0,iBreak=0; /* Beginning and end of the loop over srcTab */
  344. sqlite3 *db; /* The main database structure */
  345. int keyColumn = -1; /* Column that is the INTEGER PRIMARY KEY */
  346. int endOfLoop; /* Label for the end of the insertion loop */
  347. int useTempTable = 0; /* Store SELECT results in intermediate table */
  348. int srcTab = 0; /* Data comes from this temporary cursor if >=0 */
  349. int iSelectLoop = 0; /* Address of code that implements the SELECT */
  350. int iCleanup = 0; /* Address of the cleanup code */
  351. int iInsertBlock = 0; /* Address of the subroutine used to insert data */
  352. int iCntMem = 0; /* Memory cell used for the row counter */
  353. int newIdx = -1; /* Cursor for the NEW table */
  354. Db *pDb; /* The database containing table being inserted into */
  355. int counterMem = 0; /* Memory cell holding AUTOINCREMENT counter */
  356. int appendFlag = 0; /* True if the insert is likely to be an append */
  357. int iDb;
  358. int nHidden = 0;
  359. #ifndef SQLITE_OMIT_TRIGGER
  360. int isView; /* True if attempting to insert into a view */
  361. int triggers_exist = 0; /* True if there are FOR EACH ROW triggers */
  362. #endif
  363. db = pParse->db;
  364. if( pParse->nErr || db->mallocFailed ){
  365. goto insert_cleanup;
  366. }
  367. /* Locate the table into which we will be inserting new information.
  368. */
  369. assert( pTabList->nSrc==1 );
  370. zTab = pTabList->a[0].zName;
  371. if( zTab==0 ) goto insert_cleanup;
  372. pTab = sqlite3SrcListLookup(pParse, pTabList);
  373. if( pTab==0 ){
  374. goto insert_cleanup;
  375. }
  376. iDb = sqlite3SchemaToIndex(db, pTab->pSchema);
  377. assert( iDb<db->nDb );
  378. pDb = &db->aDb[iDb];
  379. zDb = pDb->zName;
  380. if( sqlite3AuthCheck(pParse, SQLITE_INSERT, pTab->zName, 0, zDb) ){
  381. goto insert_cleanup;
  382. }
  383. /* Figure out if we have any triggers and if the table being
  384. ** inserted into is a view
  385. */
  386. #ifndef SQLITE_OMIT_TRIGGER
  387. triggers_exist = sqlite3TriggersExist(pParse, pTab, TK_INSERT, 0);
  388. isView = pTab->pSelect!=0;
  389. #else
  390. # define triggers_exist 0
  391. # define isView 0
  392. #endif
  393. #ifdef SQLITE_OMIT_VIEW
  394. # undef isView
  395. # define isView 0
  396. #endif
  397. /* Ensure that:
  398. * (a) the table is not read-only,
  399. * (b) that if it is a view then ON INSERT triggers exist
  400. */
  401. if( sqlite3IsReadOnly(pParse, pTab, triggers_exist) ){
  402. goto insert_cleanup;
  403. }
  404. assert( pTab!=0 );
  405. /* If pTab is really a view, make sure it has been initialized.
  406. ** ViewGetColumnNames() is a no-op if pTab is not a view (or virtual
  407. ** module table).
  408. */
  409. if( sqlite3ViewGetColumnNames(pParse, pTab) ){
  410. goto insert_cleanup;
  411. }
  412. /* Allocate a VDBE
  413. */
  414. v = sqlite3GetVdbe(pParse);
  415. if( v==0 ) goto insert_cleanup;
  416. if( pParse->nested==0 ) sqlite3VdbeCountChanges(v);
  417. sqlite3BeginWriteOperation(pParse, pSelect || triggers_exist, iDb);
  418. /* if there are row triggers, allocate a temp table for new.* references. */
  419. if( triggers_exist ){
  420. newIdx = pParse->nTab++;
  421. }
  422. #ifndef SQLITE_OMIT_XFER_OPT
  423. /* If the statement is of the form
  424. **
  425. ** INSERT INTO <table1> SELECT * FROM <table2>;
  426. **
  427. ** Then special optimizations can be applied that make the transfer
  428. ** very fast and which reduce fragmentation of indices.
  429. */
  430. if( pColumn==0 && xferOptimization(pParse, pTab, pSelect, onError, iDb) ){
  431. assert( !triggers_exist );
  432. assert( pList==0 );
  433. goto insert_cleanup;
  434. }
  435. #endif /* SQLITE_OMIT_XFER_OPT */
  436. /* If this is an AUTOINCREMENT table, look up the sequence number in the
  437. ** sqlite_sequence table and store it in memory cell counterMem. Also
  438. ** remember the rowid of the sqlite_sequence table entry in memory cell
  439. ** counterRowid.
  440. */
  441. counterMem = autoIncBegin(pParse, iDb, pTab);
  442. /* Figure out how many columns of data are supplied. If the data
  443. ** is coming from a SELECT statement, then this step also generates
  444. ** all the code to implement the SELECT statement and invoke a subroutine
  445. ** to process each row of the result. (Template 2.) If the SELECT
  446. ** statement uses the the table that is being inserted into, then the
  447. ** subroutine is also coded here. That subroutine stores the SELECT
  448. ** results in a temporary table. (Template 3.)
  449. */
  450. if( pSelect ){
  451. /* Data is coming from a SELECT. Generate code to implement that SELECT
  452. */
  453. int rc, iInitCode;
  454. iInitCode = sqlite3VdbeAddOp(v, OP_Goto, 0, 0);
  455. iSelectLoop = sqlite3VdbeCurrentAddr(v);
  456. iInsertBlock = sqlite3VdbeMakeLabel(v);
  457. /* Resolve the expressions in the SELECT statement and execute it. */
  458. rc = sqlite3Select(pParse, pSelect, SRT_Subroutine, iInsertBlock,0,0,0,0);
  459. if( rc || pParse->nErr || db->mallocFailed ){
  460. goto insert_cleanup;
  461. }
  462. iCleanup = sqlite3VdbeMakeLabel(v);
  463. sqlite3VdbeAddOp(v, OP_Goto, 0, iCleanup);
  464. assert( pSelect->pEList );
  465. nColumn = pSelect->pEList->nExpr;
  466. /* Set useTempTable to TRUE if the result of the SELECT statement
  467. ** should be written into a temporary table. Set to FALSE if each
  468. ** row of the SELECT can be written directly into the result table.
  469. **
  470. ** A temp table must be used if the table being updated is also one
  471. ** of the tables being read by the SELECT statement. Also use a
  472. ** temp table in the case of row triggers.
  473. */
  474. if( triggers_exist || readsTable(v, iSelectLoop, iDb, pTab) ){
  475. useTempTable = 1;
  476. }
  477. if( useTempTable ){
  478. /* Generate the subroutine that SELECT calls to process each row of
  479. ** the result. Store the result in a temporary table
  480. */
  481. srcTab = pParse->nTab++;
  482. sqlite3VdbeResolveLabel(v, iInsertBlock);
  483. sqlite3VdbeAddOp(v, OP_StackDepth, -1, 0);
  484. sqlite3VdbeAddOp(v, OP_MakeRecord, nColumn, 0);
  485. sqlite3VdbeAddOp(v, OP_NewRowid, srcTab, 0);
  486. sqlite3VdbeAddOp(v, OP_Pull, 1, 0);
  487. sqlite3VdbeAddOp(v, OP_Insert, srcTab, OPFLAG_APPEND);
  488. sqlite3VdbeAddOp(v, OP_Return, 0, 0);
  489. /* The following code runs first because the GOTO at the very top
  490. ** of the program jumps to it. Create the temporary table, then jump
  491. ** back up and execute the SELECT code above.
  492. */
  493. sqlite3VdbeJumpHere(v, iInitCode);
  494. sqlite3VdbeAddOp(v, OP_OpenEphemeral, srcTab, 0);
  495. sqlite3VdbeAddOp(v, OP_SetNumColumns, srcTab, nColumn);
  496. sqlite3VdbeAddOp(v, OP_Goto, 0, iSelectLoop);
  497. sqlite3VdbeResolveLabel(v, iCleanup);
  498. }else{
  499. sqlite3VdbeJumpHere(v, iInitCode);
  500. }
  501. }else{
  502. /* This is the case if the data for the INSERT is coming from a VALUES
  503. ** clause
  504. */
  505. NameContext sNC;
  506. memset(&sNC, 0, sizeof(sNC));
  507. sNC.pParse = pParse;
  508. srcTab = -1;
  509. assert( useTempTable==0 );
  510. nColumn = pList ? pList->nExpr : 0;
  511. for(i=0; i<nColumn; i++){
  512. if( sqlite3ExprResolveNames(&sNC, pList->a[i].pExpr) ){
  513. goto insert_cleanup;
  514. }
  515. }
  516. }
  517. /* Make sure the number of columns in the source data matches the number
  518. ** of columns to be inserted into the table.
  519. */
  520. if( IsVirtual(pTab) ){
  521. for(i=0; i<pTab->nCol; i++){
  522. nHidden += (IsHiddenColumn(&pTab->aCol[i]) ? 1 : 0);
  523. }
  524. }
  525. if( pColumn==0 && nColumn && nColumn!=(pTab->nCol-nHidden) ){
  526. sqlite3ErrorMsg(pParse,
  527. "table %S has %d columns but %d values were supplied",
  528. pTabList, 0, pTab->nCol, nColumn);
  529. goto insert_cleanup;
  530. }
  531. if( pColumn!=0 && nColumn!=pColumn->nId ){
  532. sqlite3ErrorMsg(pParse, "%d values for %d columns", nColumn, pColumn->nId);
  533. goto insert_cleanup;
  534. }
  535. /* If the INSERT statement included an IDLIST term, then make sure
  536. ** all elements of the IDLIST really are columns of the table and
  537. ** remember the column indices.
  538. **
  539. ** If the table has an INTEGER PRIMARY KEY column and that column
  540. ** is named in the IDLIST, then record in the keyColumn variable
  541. ** the index into IDLIST of the primary key column. keyColumn is
  542. ** the index of the primary key as it appears in IDLIST, not as
  543. ** is appears in the original table. (The index of the primary
  544. ** key in the original table is pTab->iPKey.)
  545. */
  546. if( pColumn ){
  547. for(i=0; i<pColumn->nId; i++){
  548. pColumn->a[i].idx = -1;
  549. }
  550. for(i=0; i<pColumn->nId; i++){
  551. for(j=0; j<pTab->nCol; j++){
  552. if( sqlite3StrICmp(pColumn->a[i].zName, pTab->aCol[j].zName)==0 ){
  553. pColumn->a[i].idx = j;
  554. if( j==pTab->iPKey ){
  555. keyColumn = i;
  556. }
  557. break;
  558. }
  559. }
  560. if( j>=pTab->nCol ){
  561. if( sqlite3IsRowid(pColumn->a[i].zName) ){
  562. keyColumn = i;
  563. }else{
  564. sqlite3ErrorMsg(pParse, "table %S has no column named %s",
  565. pTabList, 0, pColumn->a[i].zName);
  566. pParse->nErr++;
  567. goto insert_cleanup;
  568. }
  569. }
  570. }
  571. }
  572. /* If there is no IDLIST term but the table has an integer primary
  573. ** key, the set the keyColumn variable to the primary key column index
  574. ** in the original table definition.
  575. */
  576. if( pColumn==0 && nColumn>0 ){
  577. keyColumn = pTab->iPKey;
  578. }
  579. /* Open the temp table for FOR EACH ROW triggers
  580. */
  581. if( triggers_exist ){
  582. sqlite3VdbeAddOp(v, OP_OpenPseudo, newIdx, 0);
  583. sqlite3VdbeAddOp(v, OP_SetNumColumns, newIdx, pTab->nCol);
  584. }
  585. /* Initialize the count of rows to be inserted
  586. */
  587. if( db->flags & SQLITE_CountRows ){
  588. iCntMem = pParse->nMem++;
  589. sqlite3VdbeAddOp(v, OP_MemInt, 0, iCntMem);
  590. }
  591. /* Open tables and indices if there are no row triggers */
  592. if( !triggers_exist ){
  593. base = pParse->nTab;
  594. sqlite3OpenTableAndIndices(pParse, pTab, base, OP_OpenWrite);
  595. }
  596. /* If the data source is a temporary table, then we have to create
  597. ** a loop because there might be multiple rows of data. If the data
  598. ** source is a subroutine call from the SELECT statement, then we need
  599. ** to launch the SELECT statement processing.
  600. */
  601. if( useTempTable ){
  602. iBreak = sqlite3VdbeMakeLabel(v);
  603. sqlite3VdbeAddOp(v, OP_Rewind, srcTab, iBreak);
  604. iCont = sqlite3VdbeCurrentAddr(v);
  605. }else if( pSelect ){
  606. sqlite3VdbeAddOp(v, OP_Goto, 0, iSelectLoop);
  607. sqlite3VdbeResolveLabel(v, iInsertBlock);
  608. sqlite3VdbeAddOp(v, OP_StackDepth, -1, 0);
  609. }
  610. /* Run the BEFORE and INSTEAD OF triggers, if there are any
  611. */
  612. endOfLoop = sqlite3VdbeMakeLabel(v);
  613. if( triggers_exist & TRIGGER_BEFORE ){
  614. /* build the NEW.* reference row. Note that if there is an INTEGER
  615. ** PRIMARY KEY into which a NULL is being inserted, that NULL will be
  616. ** translated into a unique ID for the row. But on a BEFORE trigger,
  617. ** we do not know what the unique ID will be (because the insert has
  618. ** not happened yet) so we substitute a rowid of -1
  619. */
  620. if( keyColumn<0 ){
  621. sqlite3VdbeAddOp(v, OP_Integer, -1, 0);
  622. }else if( useTempTable ){
  623. sqlite3VdbeAddOp(v, OP_Column, srcTab, keyColumn);
  624. }else{
  625. assert( pSelect==0 ); /* Otherwise useTempTable is true */
  626. sqlite3ExprCode(pParse, pList->a[keyColumn].pExpr);
  627. sqlite3VdbeAddOp(v, OP_NotNull, -1, sqlite3VdbeCurrentAddr(v)+3);
  628. sqlite3VdbeAddOp(v, OP_Pop, 1, 0);
  629. sqlite3VdbeAddOp(v, OP_Integer, -1, 0);
  630. sqlite3VdbeAddOp(v, OP_MustBeInt, 0, 0);
  631. }
  632. /* Cannot have triggers on a virtual table. If it were possible,
  633. ** this block would have to account for hidden column.
  634. */
  635. assert(!IsVirtual(pTab));
  636. /* Create the new column data
  637. */
  638. for(i=0; i<pTab->nCol; i++){
  639. if( pColumn==0 ){
  640. j = i;
  641. }else{
  642. for(j=0; j<pColumn->nId; j++){
  643. if( pColumn->a[j].idx==i ) break;
  644. }
  645. }
  646. if( pColumn && j>=pColumn->nId ){
  647. sqlite3ExprCode(pParse, pTab->aCol[i].pDflt);
  648. }else if( useTempTable ){
  649. sqlite3VdbeAddOp(v, OP_Column, srcTab, j);
  650. }else{
  651. assert( pSelect==0 ); /* Otherwise useTempTable is true */
  652. sqlite3ExprCodeAndCache(pParse, pList->a[j].pExpr);
  653. }
  654. }
  655. sqlite3VdbeAddOp(v, OP_MakeRecord, pTab->nCol, 0);
  656. /* If this is an INSERT on a view with an INSTEAD OF INSERT trigger,
  657. ** do not attempt any conversions before assembling the record.
  658. ** If this is a real table, attempt conversions as required by the
  659. ** table column affinities.
  660. */
  661. if( !isView ){
  662. sqlite3TableAffinityStr(v, pTab);
  663. }
  664. sqlite3VdbeAddOp(v, OP_Insert, newIdx, 0);
  665. /* Fire BEFORE or INSTEAD OF triggers */
  666. if( sqlite3CodeRowTrigger(pParse, TK_INSERT, 0, TRIGGER_BEFORE, pTab,
  667. newIdx, -1, onError, endOfLoop) ){
  668. goto insert_cleanup;
  669. }
  670. }
  671. /* If any triggers exists, the opening of tables and indices is deferred
  672. ** until now.
  673. */
  674. if( triggers_exist && !isView ){
  675. base = pParse->nTab;
  676. sqlite3OpenTableAndIndices(pParse, pTab, base, OP_OpenWrite);
  677. }
  678. /* Push the record number for the new entry onto the stack. The
  679. ** record number is a randomly generate integer created by NewRowid
  680. ** except when the table has an INTEGER PRIMARY KEY column, in which
  681. ** case the record number is the same as that column.
  682. */
  683. if( !isView ){
  684. if( IsVirtual(pTab) ){
  685. /* The row that the VUpdate opcode will delete: none */
  686. sqlite3VdbeAddOp(v, OP_Null, 0, 0);
  687. }
  688. if( keyColumn>=0 ){
  689. if( useTempTable ){
  690. sqlite3VdbeAddOp(v, OP_Column, srcTab, keyColumn);
  691. }else if( pSelect ){
  692. sqlite3VdbeAddOp(v, OP_Dup, nColumn - keyColumn - 1, 1);
  693. }else{
  694. VdbeOp *pOp;
  695. sqlite3ExprCode(pParse, pList->a[keyColumn].pExpr);
  696. pOp = sqlite3VdbeGetOp(v, sqlite3VdbeCurrentAddr(v) - 1);
  697. if( pOp && pOp->opcode==OP_Null ){
  698. appendFlag = 1;
  699. pOp->opcode = OP_NewRowid;
  700. pOp->p1 = base;
  701. pOp->p2 = counterMem;
  702. }
  703. }
  704. /* If the PRIMARY KEY expression is NULL, then use OP_NewRowid
  705. ** to generate a unique primary key value.
  706. */
  707. if( !appendFlag ){
  708. sqlite3VdbeAddOp(v, OP_NotNull, -1, sqlite3VdbeCurrentAddr(v)+3);
  709. sqlite3VdbeAddOp(v, OP_Pop, 1, 0);
  710. sqlite3VdbeAddOp(v, OP_NewRowid, base, counterMem);
  711. sqlite3VdbeAddOp(v, OP_MustBeInt, 0, 0);
  712. }
  713. }else if( IsVirtual(pTab) ){
  714. sqlite3VdbeAddOp(v, OP_Null, 0, 0);
  715. }else{
  716. sqlite3VdbeAddOp(v, OP_NewRowid, base, counterMem);
  717. appendFlag = 1;
  718. }
  719. autoIncStep(pParse, counterMem);
  720. /* Push onto the stack, data for all columns of the new entry, beginning
  721. ** with the first column.
  722. */
  723. nHidden = 0;
  724. for(i=0; i<pTab->nCol; i++){
  725. if( i==pTab->iPKey ){
  726. /* The value of the INTEGER PRIMARY KEY column is always a NULL.
  727. ** Whenever this column is read, the record number will be substituted
  728. ** in its place. So will fill this column with a NULL to avoid
  729. ** taking up data space with information that will never be used. */
  730. sqlite3VdbeAddOp(v, OP_Null, 0, 0);
  731. continue;
  732. }
  733. if( pColumn==0 ){
  734. if( IsHiddenColumn(&pTab->aCol[i]) ){
  735. assert( IsVirtual(pTab) );
  736. j = -1;
  737. nHidden++;
  738. }else{
  739. j = i - nHidden;
  740. }
  741. }else{
  742. for(j=0; j<pColumn->nId; j++){
  743. if( pColumn->a[j].idx==i ) break;
  744. }
  745. }
  746. if( j<0 || nColumn==0 || (pColumn && j>=pColumn->nId) ){
  747. sqlite3ExprCode(pParse, pTab->aCol[i].pDflt);
  748. }else if( useTempTable ){
  749. sqlite3VdbeAddOp(v, OP_Column, srcTab, j);
  750. }else if( pSelect ){
  751. sqlite3VdbeAddOp(v, OP_Dup, i+nColumn-j+IsVirtual(pTab), 1);
  752. }else{
  753. sqlite3ExprCode(pParse, pList->a[j].pExpr);
  754. }
  755. }
  756. /* Generate code to check constraints and generate index keys and
  757. ** do the insertion.
  758. */
  759. #ifndef SQLITE_OMIT_VIRTUALTABLE
  760. if( IsVirtual(pTab) ){
  761. pParse->pVirtualLock = pTab;
  762. sqlite3VdbeOp3(v, OP_VUpdate, 1, pTab->nCol+2,
  763. (const char*)pTab->pVtab, P3_VTAB);
  764. }else
  765. #endif
  766. {
  767. sqlite3GenerateConstraintChecks(pParse, pTab, base, 0, keyColumn>=0,
  768. 0, onError, endOfLoop);
  769. sqlite3CompleteInsertion(pParse, pTab, base, 0,0,0,
  770. (triggers_exist & TRIGGER_AFTER)!=0 ? newIdx : -1,
  771. appendFlag);
  772. }
  773. }
  774. /* Update the count of rows that are inserted
  775. */
  776. if( (db->flags & SQLITE_CountRows)!=0 ){
  777. sqlite3VdbeAddOp(v, OP_MemIncr, 1, iCntMem);
  778. }
  779. if( triggers_exist ){
  780. /* Close all tables opened */
  781. if( !isView ){
  782. sqlite3VdbeAddOp(v, OP_Close, base, 0);
  783. for(idx=1, pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext, idx++){
  784. sqlite3VdbeAddOp(v, OP_Close, idx+base, 0);
  785. }
  786. }
  787. /* Code AFTER triggers */
  788. if( sqlite3CodeRowTrigger(pParse, TK_INSERT, 0, TRIGGER_AFTER, pTab,
  789. newIdx, -1, onError, endOfLoop) ){
  790. goto insert_cleanup;
  791. }
  792. }
  793. /* The bottom of the loop, if the data source is a SELECT statement
  794. */
  795. sqlite3VdbeResolveLabel(v, endOfLoop);
  796. if( useTempTable ){
  797. sqlite3VdbeAddOp(v, OP_Next, srcTab, iCont);
  798. sqlite3VdbeResolveLabel(v, iBreak);
  799. sqlite3VdbeAddOp(v, OP_Close, srcTab, 0);
  800. }else if( pSelect ){
  801. sqlite3VdbeAddOp(v, OP_Pop, nColumn, 0);
  802. sqlite3VdbeAddOp(v, OP_Return, 0, 0);
  803. sqlite3VdbeResolveLabel(v, iCleanup);
  804. }
  805. if( !triggers_exist && !IsVirtual(pTab) ){
  806. /* Close all tables opened */
  807. sqlite3VdbeAddOp(v, OP_Close, base, 0);
  808. for(idx=1, pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext, idx++){
  809. sqlite3VdbeAddOp(v, OP_Close, idx+base, 0);
  810. }
  811. }
  812. /* Update the sqlite_sequence table by storing the content of the
  813. ** counter value in memory counterMem back into the sqlite_sequence
  814. ** table.
  815. */
  816. autoIncEnd(pParse, iDb, pTab, counterMem);
  817. /*
  818. ** Return the number of rows inserted. If this routine is
  819. ** generating code because of a call to sqlite3NestedParse(), do not
  820. ** invoke the callback function.
  821. */
  822. if( db->flags & SQLITE_CountRows && pParse->nested==0 && !pParse->trigStack ){
  823. sqlite3VdbeAddOp(v, OP_MemLoad, iCntMem, 0);
  824. sqlite3VdbeAddOp(v, OP_Callback, 1, 0);
  825. sqlite3VdbeSetNumCols(v, 1);
  826. sqlite3VdbeSetColName(v, 0, COLNAME_NAME, "rows inserted", P3_STATIC);
  827. }
  828. insert_cleanup:
  829. sqlite3SrcListDelete(pTabList);
  830. sqlite3ExprListDelete(pList);
  831. sqlite3SelectDelete(pSelect);
  832. sqlite3IdListDelete(pColumn);
  833. }
  834. /*
  835. ** Generate code to do a constraint check prior to an INSERT or an UPDATE.
  836. **
  837. ** When this routine is called, the stack contains (from bottom to top)
  838. ** the following values:
  839. **
  840. ** 1. The rowid of the row to be updated before the update. This
  841. ** value is omitted unless we are doing an UPDATE that involves a
  842. ** change to the record number.
  843. **
  844. ** 2. The rowid of the row after the update.
  845. **
  846. ** 3. The data in the first column of the entry after the update.
  847. **
  848. ** i. Data from middle columns...
  849. **
  850. ** N. The data in the last column of the entry after the update.
  851. **
  852. ** The old rowid shown as entry (1) above is omitted unless both isUpdate
  853. ** and rowidChng are 1. isUpdate is true for UPDATEs and false for
  854. ** INSERTs and rowidChng is true if the record number is being changed.
  855. **
  856. ** The code generated by this routine pushes additional entries onto
  857. ** the stack which are the keys for new index entries for the new record.
  858. ** The order of index keys is the same as the order of the indices on
  859. ** the pTable->pIndex list. A key is only created for index i if
  860. ** aIdxUsed!=0 and aIdxUsed[i]!=0.
  861. **
  862. ** This routine also generates code to check constraints. NOT NULL,
  863. ** CHECK, and UNIQUE constraints are all checked. If a constraint fails,
  864. ** then the appropriate action is performed. There are five possible
  865. ** actions: ROLLBACK, ABORT, FAIL, REPLACE, and IGNORE.
  866. **
  867. ** Constraint type Action What Happens
  868. ** --------------- ---------- ----------------------------------------
  869. ** any ROLLBACK The current transaction is rolled back and
  870. ** sqlite3_exec() returns immediately with a
  871. ** return code of SQLITE_CONSTRAINT.
  872. **
  873. ** any ABORT Back out changes from the current command
  874. ** only (do not do a complete rollback) then
  875. ** cause sqlite3_exec() to return immediately
  876. ** with SQLITE_CONSTRAINT.
  877. **
  878. ** any FAIL Sqlite_exec() returns immediately with a
  879. ** return code of SQLITE_CONSTRAINT. The
  880. ** transaction is not rolled back and any
  881. ** prior changes are retained.
  882. **
  883. ** any IGNORE The record number and data is popped from
  884. ** the stack and there is an immediate jump
  885. ** to label ignoreDest.
  886. **
  887. ** NOT NULL REPLACE The NULL value is replace by the default
  888. ** value for that column. If the default value
  889. ** is NULL, the action is the same as ABORT.
  890. **
  891. ** UNIQUE REPLACE The other row that conflicts with the row
  892. ** being inserted is removed.
  893. **
  894. ** CHECK REPLACE Illegal. The results in an exception.
  895. **
  896. ** Which action to take is determined by the overrideError parameter.
  897. ** Or if overrideError==OE_Default, then the pParse->onError parameter
  898. ** is used. Or if pParse->onError==OE_Default then the onError value
  899. ** for the constraint is used.
  900. **
  901. ** The calling routine must open a read/write cursor for pTab with
  902. ** cursor number "base". All indices of pTab must also have open
  903. ** read/write cursors with cursor number base+i for the i-th cursor.
  904. ** Except, if there is no possibility of a REPLACE action then
  905. ** cursors do not need to be open for indices where aIdxUsed[i]==0.
  906. **
  907. ** If the isUpdate flag is true, it means that the "base" cursor is
  908. ** initially pointing to an entry that is being updated. The isUpdate
  909. ** flag causes extra code to be generated so that the "base" cursor
  910. ** is still pointing at the same entry after the routine returns.
  911. ** Without the isUpdate flag, the "base" cursor might be moved.
  912. */
  913. void sqlite3GenerateConstraintChecks(
  914. Parse *pParse, /* The parser context */
  915. Table *pTab, /* the table into which we are inserting */
  916. int base, /* Index of a read/write cursor pointing at pTab */
  917. char *aIdxUsed, /* Which indices are used. NULL means all are used */
  918. int rowidChng, /* True if the record number will change */
  919. int isUpdate, /* True for UPDATE, False for INSERT */
  920. int overrideError, /* Override onError to this if not OE_Default */
  921. int ignoreDest /* Jump to this label on an OE_Ignore resolution */
  922. ){
  923. int i;
  924. Vdbe *v;
  925. int nCol;
  926. int onError;
  927. int addr;
  928. int extra;
  929. int iCur;
  930. Index *pIdx;
  931. int seenReplace = 0;
  932. int jumpInst1=0, jumpInst2;
  933. int hasTwoRowids = (isUpdate && rowidChng);
  934. v = sqlite3GetVdbe(pParse);
  935. assert( v!=0 );
  936. assert( pTab->pSelect==0 ); /* This table is not a VIEW */
  937. nCol = pTab->nCol;
  938. /* Test all NOT NULL constraints.
  939. */
  940. for(i=0; i<nCol; i++){
  941. if( i==pTab->iPKey ){
  942. continue;
  943. }
  944. onError = pTab->aCol[i].notNull;
  945. if( onError==OE_None ) continue;
  946. if( overrideError!=OE_Default ){
  947. onError = overrideError;
  948. }else if( onError==OE_Default ){
  949. onError = OE_Abort;
  950. }
  951. if( onError==OE_Replace && pTab->aCol[i].pDflt==0 ){
  952. onError = OE_Abort;
  953. }
  954. sqlite3VdbeAddOp(v, OP_Dup, nCol-1-i, 1);
  955. addr = sqlite3VdbeAddOp(v, OP_NotNull, 1, 0);
  956. assert( onError==OE_Rollback || onError==OE_Abort || onError==OE_Fail
  957. || onError==OE_Ignore || onError==OE_Replace );
  958. switch( onError ){
  959. case OE_Rollback:
  960. case OE_Abort:
  961. case OE_Fail: {
  962. char *zMsg = 0;
  963. sqlite3VdbeAddOp(v, OP_Halt, SQLITE_CONSTRAINT, onError);
  964. sqlite3SetString(&zMsg, pTab->zName, ".", pTab->aCol[i].zName,
  965. " may not be NULL", (char*)0);
  966. sqlite3VdbeChangeP3(v, -1, zMsg, P3_DYNAMIC);
  967. break;
  968. }
  969. case OE_Ignore: {
  970. sqlite3VdbeAddOp(v, OP_Pop, nCol+1+hasTwoRowids, 0);
  971. sqlite3VdbeAddOp(v, OP_Goto, 0, ignoreDest);
  972. break;
  973. }
  974. case OE_Replace: {
  975. sqlite3ExprCode(pParse, pTab->aCol[i].pDflt);
  976. sqlite3VdbeAddOp(v, OP_Push, nCol-i, 0);
  977. break;
  978. }
  979. }
  980. sqlite3VdbeJumpHere(v, addr);
  981. }
  982. /* Test all CHECK constraints
  983. */
  984. #ifndef SQLITE_OMIT_CHECK
  985. if( pTab->pCheck && (pParse->db->flags & SQLITE_IgnoreChecks)==0 ){
  986. int allOk = sqlite3VdbeMakeLabel(v);
  987. assert( pParse->ckOffset==0 );
  988. pParse->ckOffset = nCol;
  989. sqlite3ExprIfTrue(pParse, pTab->pCheck, allOk, 1);
  990. assert( pParse->ckOffset==nCol );
  991. pParse->ckOffset = 0;
  992. onError = overrideError!=OE_Default ? overrideError : OE_Abort;
  993. if( onError==OE_Ignore ){
  994. sqlite3VdbeAddOp(v, OP_Pop, nCol+1+hasTwoRowids, 0);
  995. sqlite3VdbeAddOp(v, OP_Goto, 0, ignoreDest);
  996. }else{
  997. sqlite3VdbeAddOp(v, OP_Halt, SQLITE_CONSTRAINT, onError);
  998. }
  999. sqlite3VdbeResolveLabel(v, allOk);
  1000. }
  1001. #endif /* !defined(SQLITE_OMIT_CHECK) */
  1002. /* If we have an INTEGER PRIMARY KEY, make sure the primary key
  1003. ** of the new record does not previously exist. Except, if this
  1004. ** is an UPDATE and the primary key is not changing, that is OK.
  1005. */
  1006. if( rowidChng ){
  1007. onError = pTab->keyConf;
  1008. if( overrideError!=OE_Default ){
  1009. onError = overrideError;
  1010. }else if( onError==OE_Default ){
  1011. onError = OE_Abort;
  1012. }
  1013. if( isUpdate ){
  1014. sqlite3VdbeAddOp(v, OP_Dup, nCol+1, 1);
  1015. sqlite3VdbeAddOp(v, OP_Dup, nCol+1, 1);
  1016. jumpInst1 = sqlite3VdbeAddOp(v, OP_Eq, 0, 0);
  1017. }
  1018. sqlite3VdbeAddOp(v, OP_Dup, nCol, 1);
  1019. jumpInst2 = sqlite3VdbeAddOp(v, OP_NotExists, base, 0);
  1020. switch( onError ){
  1021. default: {
  1022. onError = OE_Abort;
  1023. /* Fall thru into the next case */
  1024. }
  1025. case OE_Rollback:
  1026. case OE_Abort:
  1027. case OE_Fail: {
  1028. sqlite3VdbeOp3(v, OP_Halt, SQLITE_CONSTRAINT, onError,
  1029. "PRIMARY KEY must be unique", P3_STATIC);
  1030. break;
  1031. }
  1032. case OE_Replace: {
  1033. sqlite3GenerateRowIndexDelete(v, pTab, base, 0);
  1034. if( isUpdate ){
  1035. sqlite3VdbeAddOp(v, OP_Dup, nCol+hasTwoRowids, 1);
  1036. sqlite3VdbeAddOp(v, OP_MoveGe, base, 0);
  1037. }
  1038. seenReplace = 1;
  1039. break;
  1040. }
  1041. case OE_Ignore: {
  1042. assert( seenReplace==0 );
  1043. sqlite3VdbeAddOp(v, OP_Pop, nCol+1+hasTwoRowids, 0);
  1044. sqlite3VdbeAddOp(v, OP_Goto, 0, ignoreDest);
  1045. break;
  1046. }
  1047. }
  1048. sqlite3VdbeJumpHere(v, jumpInst2);
  1049. if( isUpdate ){
  1050. sqlite3VdbeJumpHere(v, jumpInst1);
  1051. sqlite3VdbeAddOp(v, OP_Dup, nCol+1, 1);
  1052. sqlite3VdbeAddOp(v, OP_MoveGe, base, 0);
  1053. }
  1054. }
  1055. /* Test all UNIQUE constraints by creating entries for each UNIQUE
  1056. ** index and making sure that duplicate entries do not already exist.
  1057. ** Add the new records to the indices as we go.
  1058. */
  1059. extra = -1;
  1060. for(iCur=0, pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext, iCur++){
  1061. if( aIdxUsed && aIdxUsed[iCur]==0 ) continue; /* Skip unused indices */
  1062. extra++;
  1063. /* Create a key for accessing the index entry */
  1064. sqlite3VdbeAddOp(v, OP_Dup, nCol+extra, 1);
  1065. for(i=0; i<pIdx->nColumn; i++){
  1066. int idx = pIdx->aiColumn[i];
  1067. if( idx==pTab->iPKey ){
  1068. sqlite3VdbeAddOp(v, OP_Dup, i+extra+nCol+1, 1);
  1069. }else{
  1070. sqlite3VdbeAddOp(v, OP_Dup, i+extra+nCol-idx, 1);
  1071. }
  1072. }
  1073. jumpInst1 = sqlite3VdbeAddOp(v, OP_MakeIdxRec, pIdx->nColumn, 0);
  1074. sqlite3IndexAffinityStr(v, pIdx);
  1075. /* Find out what action to take in case there is an indexing conflict */
  1076. onError = pIdx->onError;
  1077. if( onError==OE_None ) continue; /* pIdx is not a UNIQUE index */
  1078. if( overrideError!=OE_Default ){
  1079. onError = overrideError;
  1080. }else if( onError==OE_Default ){
  1081. onError = OE_Abort;
  1082. }
  1083. if( seenReplace ){
  1084. if( onError==OE_Ignore ) onError = OE_Replace;
  1085. else if( onError==OE_Fail ) onError = OE_Abort;
  1086. }
  1087. /* Check to see if the new index entry will be unique */
  1088. sqlite3VdbeAddOp(v, OP_Dup, extra+nCol+1+hasTwoRowids, 1);
  1089. jumpInst2 = sqlite3VdbeAddOp(v, OP_IsUnique, base+iCur+1, 0);
  1090. /* Generate code that executes if the new index entry is not unique */
  1091. assert( onError==OE_Rollback || onError==OE_Abort || onError==OE_Fail
  1092. || onError==OE_Ignore || onError==OE_Replace );
  1093. switch( onError ){
  1094. case OE_Rollback:
  1095. case OE_Abort:
  1096. case OE_Fail: {
  1097. int j, n1, n2;
  1098. char zErrMsg[200];
  1099. sqlite3_snprintf(sizeof(zErrMsg), zErrMsg,
  1100. pIdx->nColumn>1 ? "columns " : "column ");
  1101. n1 = strlen(zErrMsg);
  1102. for(j=0; j<pIdx->nColumn && n1<sizeof(zErrMsg)-30; j++){
  1103. char *zCol = pTab->aCol[pIdx->aiColumn[j]].zName;
  1104. n2 = strlen(zCol);
  1105. if( j>0 ){
  1106. sqlite3_snprintf(sizeof(zErrMsg)-n1, &zErrMsg[n1], ", ");
  1107. n1 += 2;
  1108. }
  1109. if( n1+n2>sizeof(zErrMsg)-30 ){
  1110. sqlite3_snprintf(sizeof(zErrMsg)-n1, &zErrMsg[n1], "...");
  1111. n1 += 3;
  1112. break;
  1113. }else{
  1114. sqlite3_snprintf(sizeof(zErrMsg)-n1, &zErrMsg[n1], "%s", zCol);
  1115. n1 += n2;
  1116. }
  1117. }
  1118. sqlite3_snprintf(sizeof(zErrMsg)-n1, &zErrMsg[n1],
  1119. pIdx->nColumn>1 ? " are not unique" : " is not unique");
  1120. sqlite3VdbeOp3(v, OP_Halt, SQLITE_CONSTRAINT, onError, zErrMsg, 0);
  1121. break;
  1122. }
  1123. case OE_Ignore: {
  1124. assert( seenReplace==0 );
  1125. sqlite3VdbeAddOp(v, OP_Pop, nCol+extra+3+hasTwoRowids, 0);
  1126. sqlite3VdbeAddOp(v, OP_Goto, 0, ignoreDest);
  1127. break;
  1128. }
  1129. case OE_Replace: {
  1130. sqlite3GenerateRowDelete(pParse->db, v, pTab, base, 0);
  1131. if( isUpdate ){
  1132. sqlite3VdbeAddOp(v, OP_Dup, nCol+extra+1+hasTwoRowids, 1);
  1133. sqlite3VdbeAddOp(v, OP_MoveGe, base, 0);
  1134. }
  1135. seenReplace = 1;
  1136. break;
  1137. }
  1138. }
  1139. #if NULL_DISTINCT_FOR_UNIQUE
  1140. sqlite3VdbeJumpHere(v, jumpInst1);
  1141. #endif
  1142. sqlite3VdbeJumpHere(v, jumpInst2);
  1143. }
  1144. }
  1145. /*
  1146. ** This routine generates code to finish the INSERT or UPDATE operation
  1147. ** that was started by a prior call to sqlite3GenerateConstraintChecks.
  1148. ** The stack must contain keys for all active indices followed by data
  1149. ** and the rowid for the new entry. This routine creates the new
  1150. ** entries in all indices and in the main table.
  1151. **
  1152. ** The arguments to this routine should be the same as the first six
  1153. ** arguments to sqlite3GenerateConstraintChecks.
  1154. */
  1155. void sqlite3CompleteInsertion(
  1156. Parse *pParse, /* The parser context */
  1157. Table *pTab, /* the table into which we are inserting */
  1158. int base, /* Index of a read/write cursor pointing at pTab */
  1159. char *aIdxUsed, /* Which indices are used. NULL means all are used */
  1160. int rowidChng, /* True if the record number will change */
  1161. int isUpdate, /* True for UPDATE, False for INSERT */
  1162. int newIdx, /* Index of NEW table for triggers. -1 if none */
  1163. int appendBias /* True if this is likely to be an append */
  1164. ){
  1165. int i;
  1166. Vdbe *v;
  1167. int nIdx;
  1168. Index *pIdx;
  1169. int pik_flags;
  1170. v = sqlite3GetVdbe(pParse);
  1171. assert( v!=0 );
  1172. assert( pTab->pSelect==0 ); /* This table is not a VIEW */
  1173. for(nIdx=0, pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext, nIdx++){}
  1174. for(i=nIdx-1; i>=0; i--){
  1175. if( aIdxUsed && aIdxUsed[i]==0 ) continue;
  1176. sqlite3VdbeAddOp(v, OP_IdxInsert, base+i+1, 0);
  1177. }
  1178. sqlite3VdbeAddOp(v, OP_MakeRecord, pTab->nCol, 0);
  1179. sqlite3TableAffinityStr(v, pTab);
  1180. #ifndef SQLITE_OMIT_TRIGGER
  1181. if( newIdx>=0 ){
  1182. sqlite3VdbeAddOp(v, OP_Dup, 1, 0);
  1183. sqlite3VdbeAddOp(v, OP_Dup, 1, 0);
  1184. sqlite3VdbeAddOp(v, OP_Insert, newIdx, 0);
  1185. }
  1186. #endif
  1187. if( pParse->nested ){
  1188. pik_flags = 0;
  1189. }else{
  1190. pik_flags = OPFLAG_NCHANGE;
  1191. pik_flags |= (isUpdate?OPFLAG_ISUPDATE:OPFLAG_LASTROWID);
  1192. }
  1193. if( appendBias ){
  1194. pik_flags |= OPFLAG_APPEND;
  1195. }
  1196. sqlite3VdbeAddOp(v, OP_Insert, base, pik_flags);
  1197. if( !pParse->nested ){
  1198. sqlite3VdbeChangeP3(v, -1, pTab->zName, P3_STATIC);
  1199. }
  1200. if( isUpdate && rowidChng ){
  1201. sqlite3VdbeAddOp(v, OP_Pop, 1, 0);
  1202. }
  1203. }
  1204. /*
  1205. ** Generate code that will open cursors for a table and for all
  1206. ** indices of that table. The "base" parameter is the cursor number used
  1207. ** for the table. Indices are opened on subsequent cursors.
  1208. */
  1209. void sqlite3OpenTableAndIndices(
  1210. Parse *pParse, /* Parsing context */
  1211. Table *pTab, /* Table to be opened */
  1212. int base, /* Cursor number assigned to the table */
  1213. int op /* OP_OpenRead or OP_OpenWrite */
  1214. ){
  1215. int i;
  1216. int iDb;
  1217. Index *pIdx;
  1218. Vdbe *v;
  1219. if( IsVirtual(pTab) ) return;
  1220. iDb = sqlite3SchemaToIndex(pParse->db, pTab->pSchema);
  1221. v = sqlite3GetVdbe(pParse);
  1222. assert( v!=0 );
  1223. sqlite3OpenTable(pParse, base, iDb, pTab, op);
  1224. for(i=1, pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext, i++){
  1225. KeyInfo *pKey = sqlite3IndexKeyinfo(pParse, pIdx);
  1226. assert( pIdx->pSchema==pTab->pSchema );
  1227. sqlite3VdbeAddOp(v, OP_Integer, iDb, 0);
  1228. VdbeComment((v, "# %s", pIdx->zName));
  1229. sqlite3VdbeOp3(v, op, i+base, pIdx->tnum, (char*)pKey, P3_KEYINFO_HANDOFF);
  1230. }
  1231. if( pParse->nTab<=base+i ){
  1232. pParse->nTab = base+i;
  1233. }
  1234. }
  1235. #ifdef SQLITE_TEST
  1236. /*
  1237. ** The following global variable is incremented whenever the
  1238. ** transfer optimization is used. This is used for testing
  1239. ** purposes only - to make sure the transfer optimization really
  1240. ** is happening when it is suppose to.
  1241. */
  1242. int sqlite3_xferopt_count;
  1243. #endif /* SQLITE_TEST */
  1244. #ifndef SQLITE_OMIT_XFER_OPT
  1245. /*
  1246. ** Check to collation names to see if they are compatible.
  1247. */
  1248. static int xferCompatibleCollation(const char *z1, const char *z2){
  1249. if( z1==0 ){
  1250. return z2==0;
  1251. }
  1252. if( z2==0 ){
  1253. return 0;
  1254. }
  1255. return sqlite3StrICmp(z1, z2)==0;
  1256. }
  1257. /*
  1258. ** Check to see if index pSrc is compatible as a source of data
  1259. ** for index pDest in an insert transfer optimization. The rules
  1260. ** for a compatible index:
  1261. **
  1262. ** * The index is over the same set of columns
  1263. ** * The same DESC and ASC markings occurs on all columns
  1264. ** * The same onError processing (OE_Abort, OE_Ignore, etc)
  1265. ** * The same collating sequence on each column
  1266. */
  1267. static int xferCompatibleIndex(Index *pDest, Index *pSrc){
  1268. int i;
  1269. assert( pDest && pSrc );
  1270. assert( pDest->pTable!=pSrc->pTable );
  1271. if( pDest->nColumn!=pSrc->nColumn ){
  1272. return 0; /* Different number of columns */
  1273. }
  1274. if( pDest->onError!=pSrc->onError ){
  1275. return 0; /* Different conflict resolution strategies */
  1276. }
  1277. for(i=0; i<pSrc->nColumn; i++){
  1278. if( pSrc->aiColumn[i]!=pDest->aiColumn[i] ){
  1279. return 0; /* Different columns indexed */
  1280. }
  1281. if( pSrc->aSortOrder[i]!=pDest->aSortOrder[i] ){
  1282. return 0; /* Different sort orders */
  1283. }
  1284. if( pSrc->azColl[i]!=pDest->azColl[i] ){
  1285. return 0; /* Different sort orders */
  1286. }
  1287. }
  1288. /* If no test above fails then the indices must be compatible */
  1289. return 1;
  1290. }
  1291. /*
  1292. ** Attempt the transfer optimization on INSERTs of the form
  1293. **
  1294. ** INSERT INTO tab1 SELECT * FROM tab2;
  1295. **
  1296. ** This optimization is only attempted if
  1297. **
  1298. ** (1) tab1 and tab2 have identical schemas including all the
  1299. ** same indices and constraints
  1300. **
  1301. ** (2) tab1 and tab2 are different tables
  1302. **
  1303. ** (3) There must be no triggers on tab1
  1304. **
  1305. ** (4) The result set of the SELECT statement is "*"
  1306. **
  1307. ** (5) The SELECT statement has no WHERE, HAVING, ORDER BY, GROUP BY,
  1308. ** or LIMIT clause.
  1309. **
  1310. ** (6) The SELECT statement is a simple (not a compound) select that
  1311. ** contains only tab2 in its FROM clause
  1312. **
  1313. ** This method for implementing the INSERT transfers raw records from
  1314. ** tab2 over to tab1. The columns are not decoded. Raw records from
  1315. ** the indices of tab2 are transfered to tab1 as well. In so doing,
  1316. ** the resulting tab1 has much less fragmentation.
  1317. **
  1318. ** This routine returns TRUE if the optimization is attempted. If any
  1319. ** of the conditions above fail so that the optimization should not
  1320. ** be attempted, then this routine returns FALSE.
  1321. */
  1322. static int xferOptimization(
  1323. Parse *pParse, /* Parser context */
  1324. Table *pDest, /* The table we are inserting into */
  1325. Select *pSelect, /* A SELECT statement to use as the data source */
  1326. int onError, /* How to handle constraint errors */
  1327. int iDbDest /* The database of pDest */
  1328. ){
  1329. ExprList *pEList; /* The result set of the SELECT */
  1330. Table *pSrc; /* The table in the FROM clause of SELECT */
  1331. Index *pSrcIdx, *pDestIdx; /* Source and destination indices */
  1332. struct SrcList_item *pItem; /* An element of pSelect->pSrc */
  1333. int i; /* Loop counter */
  1334. int iDbSrc; /* The database of pSrc */
  1335. int iSrc, iDest; /* Cursors from source and destination */
  1336. int addr1, addr2; /* Loop addresses */
  1337. int emptyDestTest; /* Address of test for empty pDest */
  1338. int emptySrcTest; /* Address of test for empty pSrc */
  1339. Vdbe *v; /* The VDBE we are building */
  1340. KeyInfo *pKey; /* Key information for an index */
  1341. int counterMem; /* Memory register used by AUTOINC */
  1342. int destHasUniqueIdx = 0; /* True if pDest has a UNIQUE index */
  1343. if( pSelect==0 ){
  1344. return 0; /* Must be of the form INSERT INTO ... SELECT ... */
  1345. }
  1346. if( pDest->pTrigger ){
  1347. return 0; /* tab1 must not have triggers */
  1348. }
  1349. #ifndef SQLITE_OMIT_VIRTUALTABLE
  1350. if( pDest->isVirtual ){
  1351. return 0; /* tab1 must not be a virtual table */
  1352. }
  1353. #endif
  1354. if( onError==OE_Default ){
  1355. onError = OE_Abort;
  1356. }
  1357. if( onError!=OE_Abort && onError!=OE_Rollback ){
  1358. return 0; /* Cannot do OR REPLACE or OR IGNORE or OR FAIL */
  1359. }
  1360. assert(pSelect->pSrc); /* allocated even if there is no FROM clause */
  1361. if( pSelect->pSrc->nSrc!=1 ){
  1362. return 0; /* FROM clause must have exactly one term */
  1363. }
  1364. if( pSelect->pSrc->a[0].pSelect ){
  1365. return 0; /* FROM clause cannot contain a subquery */
  1366. }
  1367. if( pSelect->pWhere ){
  1368. return 0; /* SELECT may not have a WHERE clause */
  1369. }
  1370. if( pSelect->pOrderBy ){
  1371. return 0; /* SELECT may not have an ORDER BY clause */
  1372. }
  1373. /* Do not need to test for a HAVING clause. If HAVING is present but
  1374. ** there is no ORDER BY, we will get an error. */
  1375. if( pSelect->pGroupBy ){
  1376. return 0; /* SELECT may not have a GROUP BY clause */
  1377. }
  1378. if( pSelect->pLimit ){
  1379. return 0; /* SELECT may not have a LIMIT clause */
  1380. }
  1381. assert( pSelect->pOffset==0 ); /* Must be so if pLimit==0 */
  1382. if( pSelect->pPrior ){
  1383. return 0; /* SELECT may not be a compound query */
  1384. }
  1385. if( pSelect->isDistinct ){
  1386. return 0; /* SELECT may not be DISTINCT */
  1387. }
  1388. pEList = pSelect->pEList;
  1389. assert( pEList!=0 );
  1390. if( pEList->nExpr!=1 ){
  1391. return 0; /* The result set must have exactly one column */
  1392. }
  1393. assert( pEList->a[0].pExpr );
  1394. if( pEList->a[0].pExpr->op!=TK_ALL ){
  1395. return 0; /* The result set must be the special operator "*" */
  1396. }
  1397. /* At this point we have established that the statement is of the
  1398. ** correct syntactic form to participate in this optimization. Now
  1399. ** we have to check the semantics.
  1400. */
  1401. pItem = pSelect->pSrc->a;
  1402. pSrc = sqlite3LocateTable(pParse, pItem->zName, pItem->zDatabase);
  1403. if( pSrc==0 ){
  1404. return 0; /* FROM clause does not contain a real table */
  1405. }
  1406. if( pSrc==pDest ){
  1407. return 0; /* tab1 and tab2 may not be the same table */
  1408. }
  1409. #ifndef SQLITE_OMIT_VIRTUALTABLE
  1410. if( pSrc->isVirtual ){
  1411. return 0; /* tab2 must not be a virtual table */
  1412. }
  1413. #endif
  1414. if( pSrc->pSelect ){
  1415. return 0; /* tab2 may not be a view */
  1416. }
  1417. if( pDest->nCol!=pSrc->nCol ){
  1418. return 0; /* Number of columns must be the same in tab1 and tab2 */
  1419. }
  1420. if( pDest->iPKey!=pSrc->iPKey ){
  1421. return 0; /* Both tables must have the same INTEGER PRIMARY KEY */
  1422. }
  1423. for(i=0; i<pDest->nCol; i++){
  1424. if( pDest->aCol[i].affinity!=pSrc->aCol[i].affinity ){
  1425. return 0; /* Affinity must be the same on all columns */
  1426. }
  1427. if( !xferCompatibleCollation(pDest->aCol[i].zColl, pSrc->aCol[i].zColl) ){
  1428. return 0; /* Collating sequence must be the same on all columns */
  1429. }
  1430. if( pDest->aCol[i].notNull && !pSrc->aCol[i].notNull ){
  1431. return 0; /* tab2 must be NOT NULL if tab1 is */
  1432. }
  1433. }
  1434. for(pDestIdx=pDest->pIndex; pDestIdx; pDestIdx=pDestIdx->pNext){
  1435. if( pDestIdx->onError!=OE_None ){
  1436. destHasUniqueIdx = 1;
  1437. }
  1438. for(pSrcIdx=pSrc->pIndex; pSrcIdx; pSrcIdx=pSrcIdx->pNext){
  1439. if( xferCompatibleIndex(pDestIdx, pSrcIdx) ) break;
  1440. }
  1441. if( pSrcIdx==0 ){
  1442. return 0; /* pDestIdx has no corresponding index in pSrc */
  1443. }
  1444. }
  1445. #ifndef SQLITE_OMIT_CHECK
  1446. if( pDest->pCheck && !sqlite3ExprCompare(pSrc->pCheck, pDest->pCheck) ){
  1447. return 0; /* Tables have different CHECK constraints. Ticket #2252 */
  1448. }
  1449. #endif
  1450. /* If we get this far, it means either:
  1451. **
  1452. ** * We can always do the transfer if the table contains an
  1453. ** an integer primary key
  1454. **
  1455. ** * We can conditionally do the transfer if the destination
  1456. ** table is empty.
  1457. */
  1458. #ifdef SQLITE_TEST
  1459. sqlite3_xferopt_count++;
  1460. #endif
  1461. iDbSrc = sqlite3SchemaToIndex(pParse->db, pSrc->pSchema);
  1462. v = sqlite3GetVdbe(pParse);
  1463. sqlite3CodeVerifySchema(pParse, iDbSrc);
  1464. iSrc = pParse->nTab++;
  1465. iDest = pParse->nTab++;
  1466. counterMem = autoIncBegin(pParse, iDbDest, pDest);
  1467. sqlite3OpenTable(pParse, iDest, iDbDest, pDest, OP_OpenWrite);
  1468. if( (pDest->iPKey<0 && pDest->pIndex!=0) || destHasUniqueIdx ){
  1469. /* If tables do not have an INTEGER PRIMARY KEY and there
  1470. ** are indices to be copied and the destination is not empty,
  1471. ** we have to disallow the transfer optimization because the
  1472. ** the rowids might change which will mess up indexing.
  1473. **
  1474. ** Or if the destination has a UNIQUE index and is not empty,
  1475. ** we also disallow the transfer optimization because we cannot
  1476. ** insure that all entries in the union of DEST and SRC will be
  1477. ** unique.
  1478. */
  1479. addr1 = sqlite3VdbeAddOp(v, OP_Rewind, iDest, 0);
  1480. emptyDestTest = sqlite3VdbeAddOp(v, OP_Goto, 0, 0);
  1481. sqlite3VdbeJumpHere(v, addr1);
  1482. }else{
  1483. emptyDestTest = 0;
  1484. }
  1485. sqlite3OpenTable(pParse, iSrc, iDbSrc, pSrc, OP_OpenRead);
  1486. emptySrcTest = sqlite3VdbeAddOp(v, OP_Rewind, iSrc, 0);
  1487. if( pDest->iPKey>=0 ){
  1488. addr1 = sqlite3VdbeAddOp(v, OP_Rowid, iSrc, 0);
  1489. sqlite3VdbeAddOp(v, OP_Dup, 0, 0);
  1490. addr2 = sqlite3VdbeAddOp(v, OP_NotExists, iDest, 0);
  1491. sqlite3VdbeOp3(v, OP_Halt, SQLITE_CONSTRAINT, onError,
  1492. "PRIMARY KEY must be unique", P3_STATIC);
  1493. sqlite3VdbeJumpHere(v, addr2);
  1494. autoIncStep(pParse, counterMem);
  1495. }else if( pDest->pIndex==0 ){
  1496. addr1 = sqlite3VdbeAddOp(v, OP_NewRowid, iDest, 0);
  1497. }else{
  1498. addr1 = sqlite3VdbeAddOp(v, OP_Rowid, iSrc, 0);
  1499. assert( pDest->autoInc==0 );
  1500. }
  1501. sqlite3VdbeAddOp(v, OP_RowData, iSrc, 0);
  1502. sqlite3VdbeOp3(v, OP_Insert, iDest,
  1503. OPFLAG_NCHANGE|OPFLAG_LASTROWID|OPFLAG_APPEND,
  1504. pDest->zName, 0);
  1505. sqlite3VdbeAddOp(v, OP_Next, iSrc, addr1);
  1506. autoIncEnd(pParse, iDbDest, pDest, counterMem);
  1507. for(pDestIdx=pDest->pIndex; pDestIdx; pDestIdx=pDestIdx->pNext){
  1508. for(pSrcIdx=pSrc->pIndex; pSrcIdx; pSrcIdx=pSrcIdx->pNext){
  1509. if( xferCompatibleIndex(pDestIdx, pSrcIdx) ) break;
  1510. }
  1511. assert( pSrcIdx );
  1512. sqlite3VdbeAddOp(v, OP_Close, iSrc, 0);
  1513. sqlite3VdbeAddOp(v, OP_Close, iDest, 0);
  1514. sqlite3VdbeAddOp(v, OP_Integer, iDbSrc, 0);
  1515. pKey = sqlite3IndexKeyinfo(pParse, pSrcIdx);
  1516. VdbeComment((v, "# %s", pSrcIdx->zName));
  1517. sqlite3VdbeOp3(v, OP_OpenRead, iSrc, pSrcIdx->tnum,
  1518. (char*)pKey, P3_KEYINFO_HANDOFF);
  1519. sqlite3VdbeAddOp(v, OP_Integer, iDbDest, 0);
  1520. pKey = sqlite3IndexKeyinfo(pParse, pDestIdx);
  1521. VdbeComment((v, "# %s", pDestIdx->zName));
  1522. sqlite3VdbeOp3(v, OP_OpenWrite, iDest, pDestIdx->tnum,
  1523. (char*)pKey, P3_KEYINFO_HANDOFF);
  1524. addr1 = sqlite3VdbeAddOp(v, OP_Rewind, iSrc, 0);
  1525. sqlite3VdbeAddOp(v, OP_RowKey, iSrc, 0);
  1526. sqlite3VdbeAddOp(v, OP_IdxInsert, iDest, 1);
  1527. sqlite3VdbeAddOp(v, OP_Next, iSrc, addr1+1);
  1528. sqlite3VdbeJumpHere(v, addr1);
  1529. }
  1530. sqlite3VdbeJumpHere(v, emptySrcTest);
  1531. sqlite3VdbeAddOp(v, OP_Close, iSrc, 0);
  1532. sqlite3VdbeAddOp(v, OP_Close, iDest, 0);
  1533. if( emptyDestTest ){
  1534. sqlite3VdbeAddOp(v, OP_Halt, SQLITE_OK, 0);
  1535. sqlite3VdbeJumpHere(v, emptyDestTest);
  1536. sqlite3VdbeAddOp(v, OP_Close, iDest, 0);
  1537. return 0;
  1538. }else{
  1539. return 1;
  1540. }
  1541. }
  1542. #endif /* SQLITE_OMIT_XFER_OPT */