xref: /sqlite-3.40.0/src/insert.c (revision bbb5e4e0)
1cce7d176Sdrh /*
2b19a2bc6Sdrh ** 2001 September 15
3cce7d176Sdrh **
4b19a2bc6Sdrh ** The author disclaims copyright to this source code.  In place of
5b19a2bc6Sdrh ** a legal notice, here is a blessing:
6cce7d176Sdrh **
7b19a2bc6Sdrh **    May you do good and not evil.
8b19a2bc6Sdrh **    May you find forgiveness for yourself and forgive others.
9b19a2bc6Sdrh **    May you share freely, never taking more than you give.
10cce7d176Sdrh **
11cce7d176Sdrh *************************************************************************
12cce7d176Sdrh ** This file contains C code routines that are called by the parser
13b19a2bc6Sdrh ** to handle INSERT statements in SQLite.
14cce7d176Sdrh **
15*bbb5e4e0Sdrh ** $Id: insert.c,v 1.261 2009/04/30 00:11:10 drh Exp $
16cce7d176Sdrh */
17cce7d176Sdrh #include "sqliteInt.h"
18cce7d176Sdrh 
19cce7d176Sdrh /*
20*bbb5e4e0Sdrh ** Generate code that will open a table for reading.
21*bbb5e4e0Sdrh */
22*bbb5e4e0Sdrh void sqlite3OpenTable(
23*bbb5e4e0Sdrh   Parse *p,       /* Generate code into this VDBE */
24*bbb5e4e0Sdrh   int iCur,       /* The cursor number of the table */
25*bbb5e4e0Sdrh   int iDb,        /* The database index in sqlite3.aDb[] */
26*bbb5e4e0Sdrh   Table *pTab,    /* The table to be opened */
27*bbb5e4e0Sdrh   int opcode      /* OP_OpenRead or OP_OpenWrite */
28*bbb5e4e0Sdrh ){
29*bbb5e4e0Sdrh   Vdbe *v;
30*bbb5e4e0Sdrh   if( IsVirtual(pTab) ) return;
31*bbb5e4e0Sdrh   v = sqlite3GetVdbe(p);
32*bbb5e4e0Sdrh   assert( opcode==OP_OpenWrite || opcode==OP_OpenRead );
33*bbb5e4e0Sdrh   sqlite3TableLock(p, iDb, pTab->tnum, (opcode==OP_OpenWrite)?1:0, pTab->zName);
34*bbb5e4e0Sdrh   sqlite3VdbeAddOp3(v, opcode, iCur, pTab->tnum, iDb);
35*bbb5e4e0Sdrh   sqlite3VdbeChangeP4(v, -1, SQLITE_INT_TO_PTR(pTab->nCol), P4_INT32);
36*bbb5e4e0Sdrh   VdbeComment((v, "%s", pTab->zName));
37*bbb5e4e0Sdrh }
38*bbb5e4e0Sdrh 
39*bbb5e4e0Sdrh /*
4066a5167bSdrh ** Set P4 of the most recently inserted opcode to a column affinity
41a37cdde0Sdanielk1977 ** string for index pIdx. A column affinity string has one character
423d1bfeaaSdanielk1977 ** for each column in the table, according to the affinity of the column:
433d1bfeaaSdanielk1977 **
443d1bfeaaSdanielk1977 **  Character      Column affinity
453d1bfeaaSdanielk1977 **  ------------------------------
463eda040bSdrh **  'a'            TEXT
473eda040bSdrh **  'b'            NONE
483eda040bSdrh **  'c'            NUMERIC
493eda040bSdrh **  'd'            INTEGER
503eda040bSdrh **  'e'            REAL
512d401ab8Sdrh **
522d401ab8Sdrh ** An extra 'b' is appended to the end of the string to cover the
532d401ab8Sdrh ** rowid that appears as the last column in every index.
543d1bfeaaSdanielk1977 */
55a37cdde0Sdanielk1977 void sqlite3IndexAffinityStr(Vdbe *v, Index *pIdx){
56a37cdde0Sdanielk1977   if( !pIdx->zColAff ){
57e014a838Sdanielk1977     /* The first time a column affinity string for a particular index is
58a37cdde0Sdanielk1977     ** required, it is allocated and populated here. It is then stored as
59e014a838Sdanielk1977     ** a member of the Index structure for subsequent use.
60a37cdde0Sdanielk1977     **
61a37cdde0Sdanielk1977     ** The column affinity string will eventually be deleted by
62e014a838Sdanielk1977     ** sqliteDeleteIndex() when the Index structure itself is cleaned
63a37cdde0Sdanielk1977     ** up.
64a37cdde0Sdanielk1977     */
65a37cdde0Sdanielk1977     int n;
66a37cdde0Sdanielk1977     Table *pTab = pIdx->pTable;
67abb6fcabSdrh     sqlite3 *db = sqlite3VdbeDb(v);
68633e6d57Sdrh     pIdx->zColAff = (char *)sqlite3Malloc(pIdx->nColumn+2);
69a37cdde0Sdanielk1977     if( !pIdx->zColAff ){
70633e6d57Sdrh       db->mallocFailed = 1;
71a37cdde0Sdanielk1977       return;
72a37cdde0Sdanielk1977     }
73a37cdde0Sdanielk1977     for(n=0; n<pIdx->nColumn; n++){
74a37cdde0Sdanielk1977       pIdx->zColAff[n] = pTab->aCol[pIdx->aiColumn[n]].affinity;
75a37cdde0Sdanielk1977     }
762d401ab8Sdrh     pIdx->zColAff[n++] = SQLITE_AFF_NONE;
772d401ab8Sdrh     pIdx->zColAff[n] = 0;
78a37cdde0Sdanielk1977   }
793d1bfeaaSdanielk1977 
8066a5167bSdrh   sqlite3VdbeChangeP4(v, -1, pIdx->zColAff, 0);
81a37cdde0Sdanielk1977 }
82a37cdde0Sdanielk1977 
83a37cdde0Sdanielk1977 /*
8466a5167bSdrh ** Set P4 of the most recently inserted opcode to a column affinity
85a37cdde0Sdanielk1977 ** string for table pTab. A column affinity string has one character
86a37cdde0Sdanielk1977 ** for each column indexed by the index, according to the affinity of the
87a37cdde0Sdanielk1977 ** column:
88a37cdde0Sdanielk1977 **
89a37cdde0Sdanielk1977 **  Character      Column affinity
90a37cdde0Sdanielk1977 **  ------------------------------
913eda040bSdrh **  'a'            TEXT
923eda040bSdrh **  'b'            NONE
933eda040bSdrh **  'c'            NUMERIC
943eda040bSdrh **  'd'            INTEGER
953eda040bSdrh **  'e'            REAL
96a37cdde0Sdanielk1977 */
97a37cdde0Sdanielk1977 void sqlite3TableAffinityStr(Vdbe *v, Table *pTab){
983d1bfeaaSdanielk1977   /* The first time a column affinity string for a particular table
993d1bfeaaSdanielk1977   ** is required, it is allocated and populated here. It is then
1003d1bfeaaSdanielk1977   ** stored as a member of the Table structure for subsequent use.
1013d1bfeaaSdanielk1977   **
1023d1bfeaaSdanielk1977   ** The column affinity string will eventually be deleted by
1033d1bfeaaSdanielk1977   ** sqlite3DeleteTable() when the Table structure itself is cleaned up.
1043d1bfeaaSdanielk1977   */
1053d1bfeaaSdanielk1977   if( !pTab->zColAff ){
1063d1bfeaaSdanielk1977     char *zColAff;
1073d1bfeaaSdanielk1977     int i;
108abb6fcabSdrh     sqlite3 *db = sqlite3VdbeDb(v);
1093d1bfeaaSdanielk1977 
110633e6d57Sdrh     zColAff = (char *)sqlite3Malloc(pTab->nCol+1);
1113d1bfeaaSdanielk1977     if( !zColAff ){
112633e6d57Sdrh       db->mallocFailed = 1;
113a37cdde0Sdanielk1977       return;
1143d1bfeaaSdanielk1977     }
1153d1bfeaaSdanielk1977 
1163d1bfeaaSdanielk1977     for(i=0; i<pTab->nCol; i++){
117a37cdde0Sdanielk1977       zColAff[i] = pTab->aCol[i].affinity;
1183d1bfeaaSdanielk1977     }
1193d1bfeaaSdanielk1977     zColAff[pTab->nCol] = '\0';
1203d1bfeaaSdanielk1977 
1213d1bfeaaSdanielk1977     pTab->zColAff = zColAff;
1223d1bfeaaSdanielk1977   }
1233d1bfeaaSdanielk1977 
12466a5167bSdrh   sqlite3VdbeChangeP4(v, -1, pTab->zColAff, 0);
1253d1bfeaaSdanielk1977 }
1263d1bfeaaSdanielk1977 
1274d88778bSdanielk1977 /*
12848d1178aSdrh ** Return non-zero if the table pTab in database iDb or any of its indices
12948d1178aSdrh ** have been opened at any point in the VDBE program beginning at location
13048d1178aSdrh ** iStartAddr throught the end of the program.  This is used to see if
13148d1178aSdrh ** a statement of the form  "INSERT INTO <iDb, pTab> SELECT ..." can
13248d1178aSdrh ** run without using temporary table for the results of the SELECT.
1334d88778bSdanielk1977 */
13448d1178aSdrh static int readsTable(Vdbe *v, int iStartAddr, int iDb, Table *pTab){
1354d88778bSdanielk1977   int i;
13648d1178aSdrh   int iEnd = sqlite3VdbeCurrentAddr(v);
13748d1178aSdrh   for(i=iStartAddr; i<iEnd; i++){
13848d1178aSdrh     VdbeOp *pOp = sqlite3VdbeGetOp(v, i);
139ef0bea92Sdrh     assert( pOp!=0 );
140207872a4Sdanielk1977     if( pOp->opcode==OP_OpenRead && pOp->p3==iDb ){
14148d1178aSdrh       Index *pIndex;
142207872a4Sdanielk1977       int tnum = pOp->p2;
14348d1178aSdrh       if( tnum==pTab->tnum ){
14448d1178aSdrh         return 1;
14548d1178aSdrh       }
14648d1178aSdrh       for(pIndex=pTab->pIndex; pIndex; pIndex=pIndex->pNext){
14748d1178aSdrh         if( tnum==pIndex->tnum ){
14848d1178aSdrh           return 1;
14948d1178aSdrh         }
15048d1178aSdrh       }
15148d1178aSdrh     }
152543165efSdrh #ifndef SQLITE_OMIT_VIRTUALTABLE
1532dca4ac1Sdanielk1977     if( pOp->opcode==OP_VOpen && pOp->p4.pVtab==pTab->pVtab ){
1542dca4ac1Sdanielk1977       assert( pOp->p4.pVtab!=0 );
15566a5167bSdrh       assert( pOp->p4type==P4_VTAB );
15648d1178aSdrh       return 1;
1574d88778bSdanielk1977     }
158543165efSdrh #endif
1594d88778bSdanielk1977   }
1604d88778bSdanielk1977   return 0;
1614d88778bSdanielk1977 }
1623d1bfeaaSdanielk1977 
1639d9cf229Sdrh #ifndef SQLITE_OMIT_AUTOINCREMENT
1649d9cf229Sdrh /*
1659d9cf229Sdrh ** Write out code to initialize the autoincrement logic.  This code
1669d9cf229Sdrh ** looks up the current autoincrement value in the sqlite_sequence
1676a288a33Sdrh ** table and stores that value in a register.  Code generated by
1686a288a33Sdrh ** autoIncStep() will keep that register holding the largest
1699d9cf229Sdrh ** rowid value.  Code generated by autoIncEnd() will write the new
1709d9cf229Sdrh ** largest value of the counter back into the sqlite_sequence table.
1719d9cf229Sdrh **
1729d9cf229Sdrh ** This routine returns the index of the mem[] cell that contains
1739d9cf229Sdrh ** the maximum rowid counter.
1749d9cf229Sdrh **
1756a288a33Sdrh ** Three consecutive registers are allocated by this routine.  The
1766a288a33Sdrh ** first two hold the name of the target table and the maximum rowid
1776a288a33Sdrh ** inserted into the target table, respectively.
1786a288a33Sdrh ** The third holds the rowid in sqlite_sequence where we will
1796a288a33Sdrh ** write back the revised maximum rowid.  This routine returns the
1806a288a33Sdrh ** index of the second of these three registers.
1819d9cf229Sdrh */
1829d9cf229Sdrh static int autoIncBegin(
1839d9cf229Sdrh   Parse *pParse,      /* Parsing context */
1849d9cf229Sdrh   int iDb,            /* Index of the database holding pTab */
1859d9cf229Sdrh   Table *pTab         /* The table we are writing to */
1869d9cf229Sdrh ){
1876a288a33Sdrh   int memId = 0;      /* Register holding maximum rowid */
1887d10d5a6Sdrh   if( pTab->tabFlags & TF_Autoincrement ){
1899d9cf229Sdrh     Vdbe *v = pParse->pVdbe;
1909d9cf229Sdrh     Db *pDb = &pParse->db->aDb[iDb];
1916ab3a2ecSdanielk1977     int iCur = pParse->nTab++;
1926a288a33Sdrh     int addr;               /* Address of the top of the loop */
1939d9cf229Sdrh     assert( v );
1946a288a33Sdrh     pParse->nMem++;         /* Holds name of table */
1956a288a33Sdrh     memId = ++pParse->nMem;
1966a288a33Sdrh     pParse->nMem++;
1979d9cf229Sdrh     sqlite3OpenTable(pParse, iCur, iDb, pDb->pSchema->pSeqTab, OP_OpenRead);
1986a288a33Sdrh     addr = sqlite3VdbeCurrentAddr(v);
1991db639ceSdrh     sqlite3VdbeAddOp4(v, OP_String8, 0, memId-1, 0, pTab->zName, 0);
200c9ded4c6Sdrh     sqlite3VdbeAddOp2(v, OP_Rewind, iCur, addr+9);
2011db639ceSdrh     sqlite3VdbeAddOp3(v, OP_Column, iCur, 0, memId);
2021db639ceSdrh     sqlite3VdbeAddOp3(v, OP_Ne, memId-1, addr+7, memId);
20335573356Sdrh     sqlite3VdbeChangeP5(v, SQLITE_JUMPIFNULL);
2046a288a33Sdrh     sqlite3VdbeAddOp2(v, OP_Rowid, iCur, memId+1);
2056a288a33Sdrh     sqlite3VdbeAddOp3(v, OP_Column, iCur, 1, memId);
206c9ded4c6Sdrh     sqlite3VdbeAddOp2(v, OP_Goto, 0, addr+9);
2071db639ceSdrh     sqlite3VdbeAddOp2(v, OP_Next, iCur, addr+2);
208c9ded4c6Sdrh     sqlite3VdbeAddOp2(v, OP_Integer, 0, memId);
20966a5167bSdrh     sqlite3VdbeAddOp2(v, OP_Close, iCur, 0);
2109d9cf229Sdrh   }
2119d9cf229Sdrh   return memId;
2129d9cf229Sdrh }
2139d9cf229Sdrh 
2149d9cf229Sdrh /*
2159d9cf229Sdrh ** Update the maximum rowid for an autoincrement calculation.
2169d9cf229Sdrh **
2179d9cf229Sdrh ** This routine should be called when the top of the stack holds a
2189d9cf229Sdrh ** new rowid that is about to be inserted.  If that new rowid is
2199d9cf229Sdrh ** larger than the maximum rowid in the memId memory cell, then the
2209d9cf229Sdrh ** memory cell is updated.  The stack is unchanged.
2219d9cf229Sdrh */
2226a288a33Sdrh static void autoIncStep(Parse *pParse, int memId, int regRowid){
2239d9cf229Sdrh   if( memId>0 ){
2246a288a33Sdrh     sqlite3VdbeAddOp2(pParse->pVdbe, OP_MemMax, memId, regRowid);
2259d9cf229Sdrh   }
2269d9cf229Sdrh }
2279d9cf229Sdrh 
2289d9cf229Sdrh /*
2299d9cf229Sdrh ** After doing one or more inserts, the maximum rowid is stored
2306a288a33Sdrh ** in reg[memId].  Generate code to write this value back into the
2319d9cf229Sdrh ** the sqlite_sequence table.
2329d9cf229Sdrh */
2339d9cf229Sdrh static void autoIncEnd(
2349d9cf229Sdrh   Parse *pParse,     /* The parsing context */
2359d9cf229Sdrh   int iDb,           /* Index of the database holding pTab */
2369d9cf229Sdrh   Table *pTab,       /* Table we are inserting into */
2379d9cf229Sdrh   int memId          /* Memory cell holding the maximum rowid */
2389d9cf229Sdrh ){
2397d10d5a6Sdrh   if( pTab->tabFlags & TF_Autoincrement ){
2406ab3a2ecSdanielk1977     int iCur = pParse->nTab++;
2419d9cf229Sdrh     Vdbe *v = pParse->pVdbe;
2429d9cf229Sdrh     Db *pDb = &pParse->db->aDb[iDb];
2436a288a33Sdrh     int j1;
244a7a8e14bSdanielk1977     int iRec = ++pParse->nMem;    /* Memory cell used for record */
2456a288a33Sdrh 
2469d9cf229Sdrh     assert( v );
2479d9cf229Sdrh     sqlite3OpenTable(pParse, iCur, iDb, pDb->pSchema->pSeqTab, OP_OpenWrite);
2486a288a33Sdrh     j1 = sqlite3VdbeAddOp1(v, OP_NotNull, memId+1);
2496a288a33Sdrh     sqlite3VdbeAddOp2(v, OP_NewRowid, iCur, memId+1);
2506a288a33Sdrh     sqlite3VdbeJumpHere(v, j1);
251a7a8e14bSdanielk1977     sqlite3VdbeAddOp3(v, OP_MakeRecord, memId-1, 2, iRec);
252a7a8e14bSdanielk1977     sqlite3VdbeAddOp3(v, OP_Insert, iCur, iRec, memId+1);
25335573356Sdrh     sqlite3VdbeChangeP5(v, OPFLAG_APPEND);
2546a288a33Sdrh     sqlite3VdbeAddOp1(v, OP_Close, iCur);
2559d9cf229Sdrh   }
2569d9cf229Sdrh }
2579d9cf229Sdrh #else
2589d9cf229Sdrh /*
2599d9cf229Sdrh ** If SQLITE_OMIT_AUTOINCREMENT is defined, then the three routines
2609d9cf229Sdrh ** above are all no-ops
2619d9cf229Sdrh */
2629d9cf229Sdrh # define autoIncBegin(A,B,C) (0)
263287fb61cSdanielk1977 # define autoIncStep(A,B,C)
2649d9cf229Sdrh # define autoIncEnd(A,B,C,D)
2659d9cf229Sdrh #endif /* SQLITE_OMIT_AUTOINCREMENT */
2669d9cf229Sdrh 
2679d9cf229Sdrh 
2689d9cf229Sdrh /* Forward declaration */
2699d9cf229Sdrh static int xferOptimization(
2709d9cf229Sdrh   Parse *pParse,        /* Parser context */
2719d9cf229Sdrh   Table *pDest,         /* The table we are inserting into */
2729d9cf229Sdrh   Select *pSelect,      /* A SELECT statement to use as the data source */
2739d9cf229Sdrh   int onError,          /* How to handle constraint errors */
2749d9cf229Sdrh   int iDbDest           /* The database of pDest */
2759d9cf229Sdrh );
2769d9cf229Sdrh 
2773d1bfeaaSdanielk1977 /*
2781ccde15dSdrh ** This routine is call to handle SQL of the following forms:
279cce7d176Sdrh **
280cce7d176Sdrh **    insert into TABLE (IDLIST) values(EXPRLIST)
2811ccde15dSdrh **    insert into TABLE (IDLIST) select
282cce7d176Sdrh **
2831ccde15dSdrh ** The IDLIST following the table name is always optional.  If omitted,
2841ccde15dSdrh ** then a list of all columns for the table is substituted.  The IDLIST
285967e8b73Sdrh ** appears in the pColumn parameter.  pColumn is NULL if IDLIST is omitted.
2861ccde15dSdrh **
2871ccde15dSdrh ** The pList parameter holds EXPRLIST in the first form of the INSERT
2881ccde15dSdrh ** statement above, and pSelect is NULL.  For the second form, pList is
2891ccde15dSdrh ** NULL and pSelect is a pointer to the select statement used to generate
2901ccde15dSdrh ** data for the insert.
291142e30dfSdrh **
2929d9cf229Sdrh ** The code generated follows one of four templates.  For a simple
293142e30dfSdrh ** select with data coming from a VALUES clause, the code executes
294e00ee6ebSdrh ** once straight down through.  Pseudo-code follows (we call this
295e00ee6ebSdrh ** the "1st template"):
296142e30dfSdrh **
297142e30dfSdrh **         open write cursor to <table> and its indices
298142e30dfSdrh **         puts VALUES clause expressions onto the stack
299142e30dfSdrh **         write the resulting record into <table>
300142e30dfSdrh **         cleanup
301142e30dfSdrh **
3029d9cf229Sdrh ** The three remaining templates assume the statement is of the form
303142e30dfSdrh **
304142e30dfSdrh **   INSERT INTO <table> SELECT ...
305142e30dfSdrh **
3069d9cf229Sdrh ** If the SELECT clause is of the restricted form "SELECT * FROM <table2>" -
3079d9cf229Sdrh ** in other words if the SELECT pulls all columns from a single table
3089d9cf229Sdrh ** and there is no WHERE or LIMIT or GROUP BY or ORDER BY clauses, and
3099d9cf229Sdrh ** if <table2> and <table1> are distinct tables but have identical
3109d9cf229Sdrh ** schemas, including all the same indices, then a special optimization
3119d9cf229Sdrh ** is invoked that copies raw records from <table2> over to <table1>.
3129d9cf229Sdrh ** See the xferOptimization() function for the implementation of this
313e00ee6ebSdrh ** template.  This is the 2nd template.
3149d9cf229Sdrh **
3159d9cf229Sdrh **         open a write cursor to <table>
3169d9cf229Sdrh **         open read cursor on <table2>
3179d9cf229Sdrh **         transfer all records in <table2> over to <table>
3189d9cf229Sdrh **         close cursors
3199d9cf229Sdrh **         foreach index on <table>
3209d9cf229Sdrh **           open a write cursor on the <table> index
3219d9cf229Sdrh **           open a read cursor on the corresponding <table2> index
3229d9cf229Sdrh **           transfer all records from the read to the write cursors
3239d9cf229Sdrh **           close cursors
3249d9cf229Sdrh **         end foreach
3259d9cf229Sdrh **
326e00ee6ebSdrh ** The 3rd template is for when the second template does not apply
3279d9cf229Sdrh ** and the SELECT clause does not read from <table> at any time.
3289d9cf229Sdrh ** The generated code follows this template:
329142e30dfSdrh **
330e00ee6ebSdrh **         EOF <- 0
331e00ee6ebSdrh **         X <- A
332142e30dfSdrh **         goto B
333142e30dfSdrh **      A: setup for the SELECT
3349d9cf229Sdrh **         loop over the rows in the SELECT
335e00ee6ebSdrh **           load values into registers R..R+n
336e00ee6ebSdrh **           yield X
337142e30dfSdrh **         end loop
338142e30dfSdrh **         cleanup after the SELECT
339e00ee6ebSdrh **         EOF <- 1
340e00ee6ebSdrh **         yield X
341142e30dfSdrh **         goto A
342e00ee6ebSdrh **      B: open write cursor to <table> and its indices
343e00ee6ebSdrh **      C: yield X
344e00ee6ebSdrh **         if EOF goto D
345e00ee6ebSdrh **         insert the select result into <table> from R..R+n
346e00ee6ebSdrh **         goto C
347142e30dfSdrh **      D: cleanup
348142e30dfSdrh **
349e00ee6ebSdrh ** The 4th template is used if the insert statement takes its
350142e30dfSdrh ** values from a SELECT but the data is being inserted into a table
351142e30dfSdrh ** that is also read as part of the SELECT.  In the third form,
352142e30dfSdrh ** we have to use a intermediate table to store the results of
353142e30dfSdrh ** the select.  The template is like this:
354142e30dfSdrh **
355e00ee6ebSdrh **         EOF <- 0
356e00ee6ebSdrh **         X <- A
357142e30dfSdrh **         goto B
358142e30dfSdrh **      A: setup for the SELECT
359142e30dfSdrh **         loop over the tables in the SELECT
360e00ee6ebSdrh **           load value into register R..R+n
361e00ee6ebSdrh **           yield X
362142e30dfSdrh **         end loop
363142e30dfSdrh **         cleanup after the SELECT
364e00ee6ebSdrh **         EOF <- 1
365e00ee6ebSdrh **         yield X
366e00ee6ebSdrh **         halt-error
367e00ee6ebSdrh **      B: open temp table
368e00ee6ebSdrh **      L: yield X
369e00ee6ebSdrh **         if EOF goto M
370e00ee6ebSdrh **         insert row from R..R+n into temp table
371e00ee6ebSdrh **         goto L
372e00ee6ebSdrh **      M: open write cursor to <table> and its indices
373e00ee6ebSdrh **         rewind temp table
374e00ee6ebSdrh **      C: loop over rows of intermediate table
375142e30dfSdrh **           transfer values form intermediate table into <table>
376e00ee6ebSdrh **         end loop
377e00ee6ebSdrh **      D: cleanup
378cce7d176Sdrh */
3794adee20fSdanielk1977 void sqlite3Insert(
380cce7d176Sdrh   Parse *pParse,        /* Parser context */
381113088ecSdrh   SrcList *pTabList,    /* Name of table into which we are inserting */
382cce7d176Sdrh   ExprList *pList,      /* List of values to be inserted */
3835974a30fSdrh   Select *pSelect,      /* A SELECT statement to use as the data source */
3849cfcf5d4Sdrh   IdList *pColumn,      /* Column names corresponding to IDLIST. */
3859cfcf5d4Sdrh   int onError           /* How to handle constraint errors */
386cce7d176Sdrh ){
3876a288a33Sdrh   sqlite3 *db;          /* The main database structure */
3886a288a33Sdrh   Table *pTab;          /* The table to insert into.  aka TABLE */
389113088ecSdrh   char *zTab;           /* Name of the table into which we are inserting */
390e22a334bSdrh   const char *zDb;      /* Name of the database holding this table */
3915974a30fSdrh   int i, j, idx;        /* Loop counters */
3925974a30fSdrh   Vdbe *v;              /* Generate code into this virtual machine */
3935974a30fSdrh   Index *pIdx;          /* For looping over indices of the table */
394967e8b73Sdrh   int nColumn;          /* Number of columns in the data */
3956a288a33Sdrh   int nHidden = 0;      /* Number of hidden columns if TABLE is virtual */
39604adf416Sdrh   int baseCur = 0;      /* VDBE Cursor number for pTab */
3974a32431cSdrh   int keyColumn = -1;   /* Column that is the INTEGER PRIMARY KEY */
3980ca3e24bSdrh   int endOfLoop;        /* Label for the end of the insertion loop */
3994d88778bSdanielk1977   int useTempTable = 0; /* Store SELECT results in intermediate table */
400cfe9a69fSdanielk1977   int srcTab = 0;       /* Data comes from this temporary cursor if >=0 */
401e00ee6ebSdrh   int addrInsTop = 0;   /* Jump to label "D" */
402e00ee6ebSdrh   int addrCont = 0;     /* Top of insert loop. Label "C" in templates 3 and 4 */
403e00ee6ebSdrh   int addrSelect = 0;   /* Address of coroutine that implements the SELECT */
4042eb95377Sdrh   SelectDest dest;      /* Destination for SELECT on rhs of INSERT */
4056a288a33Sdrh   int newIdx = -1;      /* Cursor for the NEW pseudo-table */
4066a288a33Sdrh   int iDb;              /* Index of database holding TABLE */
4072958a4e6Sdrh   Db *pDb;              /* The database containing table being inserted into */
408e4d90813Sdrh   int appendFlag = 0;   /* True if the insert is likely to be an append */
409cce7d176Sdrh 
4106a288a33Sdrh   /* Register allocations */
4111bd10f8aSdrh   int regFromSelect = 0;/* Base register for data coming from SELECT */
4126a288a33Sdrh   int regAutoinc = 0;   /* Register holding the AUTOINCREMENT counter */
4136a288a33Sdrh   int regRowCount = 0;  /* Memory cell used for the row counter */
4146a288a33Sdrh   int regIns;           /* Block of regs holding rowid+data being inserted */
4156a288a33Sdrh   int regRowid;         /* registers holding insert rowid */
4166a288a33Sdrh   int regData;          /* register holding first column to insert */
4176a288a33Sdrh   int regRecord;        /* Holds the assemblied row record */
4181bd10f8aSdrh   int regEof = 0;       /* Register recording end of SELECT data */
419aa9b8963Sdrh   int *aRegIdx = 0;     /* One register allocated to each index */
4206a288a33Sdrh 
421034ca14fSdanielk1977 
422798da52cSdrh #ifndef SQLITE_OMIT_TRIGGER
423798da52cSdrh   int isView;                 /* True if attempting to insert into a view */
4242f886d1dSdanielk1977   Trigger *pTrigger;          /* List of triggers on pTab, if required */
4252f886d1dSdanielk1977   int tmask;                  /* Mask of trigger times */
426798da52cSdrh #endif
427c3f9bad2Sdanielk1977 
42817435752Sdrh   db = pParse->db;
4291bd10f8aSdrh   memset(&dest, 0, sizeof(dest));
43017435752Sdrh   if( pParse->nErr || db->mallocFailed ){
4316f7adc8aSdrh     goto insert_cleanup;
4326f7adc8aSdrh   }
433daffd0e5Sdrh 
4341ccde15dSdrh   /* Locate the table into which we will be inserting new information.
4351ccde15dSdrh   */
436113088ecSdrh   assert( pTabList->nSrc==1 );
437113088ecSdrh   zTab = pTabList->a[0].zName;
438daffd0e5Sdrh   if( zTab==0 ) goto insert_cleanup;
4394adee20fSdanielk1977   pTab = sqlite3SrcListLookup(pParse, pTabList);
440c3f9bad2Sdanielk1977   if( pTab==0 ){
441c3f9bad2Sdanielk1977     goto insert_cleanup;
442c3f9bad2Sdanielk1977   }
443da184236Sdanielk1977   iDb = sqlite3SchemaToIndex(db, pTab->pSchema);
444da184236Sdanielk1977   assert( iDb<db->nDb );
445da184236Sdanielk1977   pDb = &db->aDb[iDb];
4462958a4e6Sdrh   zDb = pDb->zName;
4474adee20fSdanielk1977   if( sqlite3AuthCheck(pParse, SQLITE_INSERT, pTab->zName, 0, zDb) ){
4481962bda7Sdrh     goto insert_cleanup;
4491962bda7Sdrh   }
450c3f9bad2Sdanielk1977 
451b7f9164eSdrh   /* Figure out if we have any triggers and if the table being
452b7f9164eSdrh   ** inserted into is a view
453b7f9164eSdrh   */
454b7f9164eSdrh #ifndef SQLITE_OMIT_TRIGGER
4552f886d1dSdanielk1977   pTrigger = sqlite3TriggersExist(pParse, pTab, TK_INSERT, 0, &tmask);
456b7f9164eSdrh   isView = pTab->pSelect!=0;
457b7f9164eSdrh #else
4582f886d1dSdanielk1977 # define pTrigger 0
4592f886d1dSdanielk1977 # define tmask 0
460b7f9164eSdrh # define isView 0
461b7f9164eSdrh #endif
462b7f9164eSdrh #ifdef SQLITE_OMIT_VIEW
463b7f9164eSdrh # undef isView
464b7f9164eSdrh # define isView 0
465b7f9164eSdrh #endif
4662f886d1dSdanielk1977   assert( (pTrigger && tmask) || (pTrigger==0 && tmask==0) );
467b7f9164eSdrh 
468c3f9bad2Sdanielk1977   /* Ensure that:
469c3f9bad2Sdanielk1977   *  (a) the table is not read-only,
470c3f9bad2Sdanielk1977   *  (b) that if it is a view then ON INSERT triggers exist
471c3f9bad2Sdanielk1977   */
4722f886d1dSdanielk1977   if( sqlite3IsReadOnly(pParse, pTab, tmask) ){
473c3f9bad2Sdanielk1977     goto insert_cleanup;
474c3f9bad2Sdanielk1977   }
47543617e9aSdrh   assert( pTab!=0 );
4761ccde15dSdrh 
477f573c99bSdrh   /* If pTab is really a view, make sure it has been initialized.
478b3d24bf8Sdanielk1977   ** ViewGetColumnNames() is a no-op if pTab is not a view (or virtual
479b3d24bf8Sdanielk1977   ** module table).
480f573c99bSdrh   */
481b3d24bf8Sdanielk1977   if( sqlite3ViewGetColumnNames(pParse, pTab) ){
482f573c99bSdrh     goto insert_cleanup;
483f573c99bSdrh   }
484f573c99bSdrh 
4851ccde15dSdrh   /* Allocate a VDBE
4861ccde15dSdrh   */
4874adee20fSdanielk1977   v = sqlite3GetVdbe(pParse);
4885974a30fSdrh   if( v==0 ) goto insert_cleanup;
4894794f735Sdrh   if( pParse->nested==0 ) sqlite3VdbeCountChanges(v);
4902f886d1dSdanielk1977   sqlite3BeginWriteOperation(pParse, pSelect || pTrigger, iDb);
4911ccde15dSdrh 
492c3f9bad2Sdanielk1977   /* if there are row triggers, allocate a temp table for new.* references. */
4932f886d1dSdanielk1977   if( pTrigger ){
494c3f9bad2Sdanielk1977     newIdx = pParse->nTab++;
495f29ce559Sdanielk1977   }
496c3f9bad2Sdanielk1977 
4979d9cf229Sdrh #ifndef SQLITE_OMIT_XFER_OPT
4989d9cf229Sdrh   /* If the statement is of the form
4999d9cf229Sdrh   **
5009d9cf229Sdrh   **       INSERT INTO <table1> SELECT * FROM <table2>;
5019d9cf229Sdrh   **
5029d9cf229Sdrh   ** Then special optimizations can be applied that make the transfer
5039d9cf229Sdrh   ** very fast and which reduce fragmentation of indices.
504e00ee6ebSdrh   **
505e00ee6ebSdrh   ** This is the 2nd template.
5069d9cf229Sdrh   */
5079d9cf229Sdrh   if( pColumn==0 && xferOptimization(pParse, pTab, pSelect, onError, iDb) ){
5082f886d1dSdanielk1977     assert( !pTrigger );
5099d9cf229Sdrh     assert( pList==0 );
5109d9cf229Sdrh     goto insert_cleanup;
5119d9cf229Sdrh   }
5129d9cf229Sdrh #endif /* SQLITE_OMIT_XFER_OPT */
5139d9cf229Sdrh 
5142958a4e6Sdrh   /* If this is an AUTOINCREMENT table, look up the sequence number in the
5156a288a33Sdrh   ** sqlite_sequence table and store it in memory cell regAutoinc.
5162958a4e6Sdrh   */
5176a288a33Sdrh   regAutoinc = autoIncBegin(pParse, iDb, pTab);
5182958a4e6Sdrh 
5191ccde15dSdrh   /* Figure out how many columns of data are supplied.  If the data
520e00ee6ebSdrh   ** is coming from a SELECT statement, then generate a co-routine that
521e00ee6ebSdrh   ** produces a single row of the SELECT on each invocation.  The
522e00ee6ebSdrh   ** co-routine is the common header to the 3rd and 4th templates.
5231ccde15dSdrh   */
5245974a30fSdrh   if( pSelect ){
525142e30dfSdrh     /* Data is coming from a SELECT.  Generate code to implement that SELECT
526e00ee6ebSdrh     ** as a co-routine.  The code is common to both the 3rd and 4th
527e00ee6ebSdrh     ** templates:
528e00ee6ebSdrh     **
529e00ee6ebSdrh     **         EOF <- 0
530e00ee6ebSdrh     **         X <- A
531e00ee6ebSdrh     **         goto B
532e00ee6ebSdrh     **      A: setup for the SELECT
533e00ee6ebSdrh     **         loop over the tables in the SELECT
534e00ee6ebSdrh     **           load value into register R..R+n
535e00ee6ebSdrh     **           yield X
536e00ee6ebSdrh     **         end loop
537e00ee6ebSdrh     **         cleanup after the SELECT
538e00ee6ebSdrh     **         EOF <- 1
539e00ee6ebSdrh     **         yield X
540e00ee6ebSdrh     **         halt-error
541e00ee6ebSdrh     **
542e00ee6ebSdrh     ** On each invocation of the co-routine, it puts a single row of the
543e00ee6ebSdrh     ** SELECT result into registers dest.iMem...dest.iMem+dest.nMem-1.
544e00ee6ebSdrh     ** (These output registers are allocated by sqlite3Select().)  When
545e00ee6ebSdrh     ** the SELECT completes, it sets the EOF flag stored in regEof.
546142e30dfSdrh     */
547e00ee6ebSdrh     int rc, j1;
5481013c932Sdrh 
549e00ee6ebSdrh     regEof = ++pParse->nMem;
550e00ee6ebSdrh     sqlite3VdbeAddOp2(v, OP_Integer, 0, regEof);      /* EOF <- 0 */
551e00ee6ebSdrh     VdbeComment((v, "SELECT eof flag"));
55292b01d53Sdrh     sqlite3SelectDestInit(&dest, SRT_Coroutine, ++pParse->nMem);
553e00ee6ebSdrh     addrSelect = sqlite3VdbeCurrentAddr(v)+2;
55492b01d53Sdrh     sqlite3VdbeAddOp2(v, OP_Integer, addrSelect-1, dest.iParm);
555e00ee6ebSdrh     j1 = sqlite3VdbeAddOp2(v, OP_Goto, 0, 0);
556e00ee6ebSdrh     VdbeComment((v, "Jump over SELECT coroutine"));
557b3bce662Sdanielk1977 
558b3bce662Sdanielk1977     /* Resolve the expressions in the SELECT statement and execute it. */
5597d10d5a6Sdrh     rc = sqlite3Select(pParse, pSelect, &dest);
56017435752Sdrh     if( rc || pParse->nErr || db->mallocFailed ){
5616f7adc8aSdrh       goto insert_cleanup;
5626f7adc8aSdrh     }
563e00ee6ebSdrh     sqlite3VdbeAddOp2(v, OP_Integer, 1, regEof);         /* EOF <- 1 */
56492b01d53Sdrh     sqlite3VdbeAddOp1(v, OP_Yield, dest.iParm);   /* yield X */
565e00ee6ebSdrh     sqlite3VdbeAddOp2(v, OP_Halt, SQLITE_INTERNAL, OE_Abort);
566e00ee6ebSdrh     VdbeComment((v, "End of SELECT coroutine"));
567e00ee6ebSdrh     sqlite3VdbeJumpHere(v, j1);                          /* label B: */
568b3bce662Sdanielk1977 
5696a288a33Sdrh     regFromSelect = dest.iMem;
5705974a30fSdrh     assert( pSelect->pEList );
571967e8b73Sdrh     nColumn = pSelect->pEList->nExpr;
572e00ee6ebSdrh     assert( dest.nMem==nColumn );
573142e30dfSdrh 
574142e30dfSdrh     /* Set useTempTable to TRUE if the result of the SELECT statement
575e00ee6ebSdrh     ** should be written into a temporary table (template 4).  Set to
576e00ee6ebSdrh     ** FALSE if each* row of the SELECT can be written directly into
577e00ee6ebSdrh     ** the destination table (template 3).
578048c530cSdrh     **
579048c530cSdrh     ** A temp table must be used if the table being updated is also one
580048c530cSdrh     ** of the tables being read by the SELECT statement.  Also use a
581048c530cSdrh     ** temp table in the case of row triggers.
582142e30dfSdrh     */
5832f886d1dSdanielk1977     if( pTrigger || readsTable(v, addrSelect, iDb, pTab) ){
584048c530cSdrh       useTempTable = 1;
585048c530cSdrh     }
586142e30dfSdrh 
587142e30dfSdrh     if( useTempTable ){
588e00ee6ebSdrh       /* Invoke the coroutine to extract information from the SELECT
589e00ee6ebSdrh       ** and add it to a transient table srcTab.  The code generated
590e00ee6ebSdrh       ** here is from the 4th template:
591e00ee6ebSdrh       **
592e00ee6ebSdrh       **      B: open temp table
593e00ee6ebSdrh       **      L: yield X
594e00ee6ebSdrh       **         if EOF goto M
595e00ee6ebSdrh       **         insert row from R..R+n into temp table
596e00ee6ebSdrh       **         goto L
597e00ee6ebSdrh       **      M: ...
598142e30dfSdrh       */
599e00ee6ebSdrh       int regRec;          /* Register to hold packed record */
600dc5ea5c7Sdrh       int regTempRowid;    /* Register to hold temp table ROWID */
601e00ee6ebSdrh       int addrTop;         /* Label "L" */
602e00ee6ebSdrh       int addrIf;          /* Address of jump to M */
603b7654111Sdrh 
604142e30dfSdrh       srcTab = pParse->nTab++;
605b7654111Sdrh       regRec = sqlite3GetTempReg(pParse);
606dc5ea5c7Sdrh       regTempRowid = sqlite3GetTempReg(pParse);
607e00ee6ebSdrh       sqlite3VdbeAddOp2(v, OP_OpenEphemeral, srcTab, nColumn);
60892b01d53Sdrh       addrTop = sqlite3VdbeAddOp1(v, OP_Yield, dest.iParm);
609e00ee6ebSdrh       addrIf = sqlite3VdbeAddOp1(v, OP_If, regEof);
6101db639ceSdrh       sqlite3VdbeAddOp3(v, OP_MakeRecord, regFromSelect, nColumn, regRec);
611dc5ea5c7Sdrh       sqlite3VdbeAddOp2(v, OP_NewRowid, srcTab, regTempRowid);
612dc5ea5c7Sdrh       sqlite3VdbeAddOp3(v, OP_Insert, srcTab, regRec, regTempRowid);
613e00ee6ebSdrh       sqlite3VdbeAddOp2(v, OP_Goto, 0, addrTop);
614e00ee6ebSdrh       sqlite3VdbeJumpHere(v, addrIf);
615b7654111Sdrh       sqlite3ReleaseTempReg(pParse, regRec);
616dc5ea5c7Sdrh       sqlite3ReleaseTempReg(pParse, regTempRowid);
617142e30dfSdrh     }
618142e30dfSdrh   }else{
619142e30dfSdrh     /* This is the case if the data for the INSERT is coming from a VALUES
620142e30dfSdrh     ** clause
621142e30dfSdrh     */
622b3bce662Sdanielk1977     NameContext sNC;
623b3bce662Sdanielk1977     memset(&sNC, 0, sizeof(sNC));
624b3bce662Sdanielk1977     sNC.pParse = pParse;
6255974a30fSdrh     srcTab = -1;
62648d1178aSdrh     assert( useTempTable==0 );
627147d0cccSdrh     nColumn = pList ? pList->nExpr : 0;
628e64e7b20Sdrh     for(i=0; i<nColumn; i++){
6297d10d5a6Sdrh       if( sqlite3ResolveExprNames(&sNC, pList->a[i].pExpr) ){
630b04a5d87Sdrh         goto insert_cleanup;
631b04a5d87Sdrh       }
632e64e7b20Sdrh     }
6335974a30fSdrh   }
6341ccde15dSdrh 
6351ccde15dSdrh   /* Make sure the number of columns in the source data matches the number
6361ccde15dSdrh   ** of columns to be inserted into the table.
6371ccde15dSdrh   */
638034ca14fSdanielk1977   if( IsVirtual(pTab) ){
639034ca14fSdanielk1977     for(i=0; i<pTab->nCol; i++){
640034ca14fSdanielk1977       nHidden += (IsHiddenColumn(&pTab->aCol[i]) ? 1 : 0);
641034ca14fSdanielk1977     }
642034ca14fSdanielk1977   }
643034ca14fSdanielk1977   if( pColumn==0 && nColumn && nColumn!=(pTab->nCol-nHidden) ){
6444adee20fSdanielk1977     sqlite3ErrorMsg(pParse,
645da93d238Sdrh        "table %S has %d columns but %d values were supplied",
646da93d238Sdrh        pTabList, 0, pTab->nCol, nColumn);
647cce7d176Sdrh     goto insert_cleanup;
648cce7d176Sdrh   }
649967e8b73Sdrh   if( pColumn!=0 && nColumn!=pColumn->nId ){
6504adee20fSdanielk1977     sqlite3ErrorMsg(pParse, "%d values for %d columns", nColumn, pColumn->nId);
651cce7d176Sdrh     goto insert_cleanup;
652cce7d176Sdrh   }
6531ccde15dSdrh 
6541ccde15dSdrh   /* If the INSERT statement included an IDLIST term, then make sure
6551ccde15dSdrh   ** all elements of the IDLIST really are columns of the table and
6561ccde15dSdrh   ** remember the column indices.
657c8392586Sdrh   **
658c8392586Sdrh   ** If the table has an INTEGER PRIMARY KEY column and that column
659c8392586Sdrh   ** is named in the IDLIST, then record in the keyColumn variable
660c8392586Sdrh   ** the index into IDLIST of the primary key column.  keyColumn is
661c8392586Sdrh   ** the index of the primary key as it appears in IDLIST, not as
662c8392586Sdrh   ** is appears in the original table.  (The index of the primary
663c8392586Sdrh   ** key in the original table is pTab->iPKey.)
6641ccde15dSdrh   */
665967e8b73Sdrh   if( pColumn ){
666967e8b73Sdrh     for(i=0; i<pColumn->nId; i++){
667967e8b73Sdrh       pColumn->a[i].idx = -1;
668cce7d176Sdrh     }
669967e8b73Sdrh     for(i=0; i<pColumn->nId; i++){
670cce7d176Sdrh       for(j=0; j<pTab->nCol; j++){
6714adee20fSdanielk1977         if( sqlite3StrICmp(pColumn->a[i].zName, pTab->aCol[j].zName)==0 ){
672967e8b73Sdrh           pColumn->a[i].idx = j;
6734a32431cSdrh           if( j==pTab->iPKey ){
6749aa028daSdrh             keyColumn = i;
6754a32431cSdrh           }
676cce7d176Sdrh           break;
677cce7d176Sdrh         }
678cce7d176Sdrh       }
679cce7d176Sdrh       if( j>=pTab->nCol ){
6804adee20fSdanielk1977         if( sqlite3IsRowid(pColumn->a[i].zName) ){
681a0217ba7Sdrh           keyColumn = i;
682a0217ba7Sdrh         }else{
6834adee20fSdanielk1977           sqlite3ErrorMsg(pParse, "table %S has no column named %s",
684da93d238Sdrh               pTabList, 0, pColumn->a[i].zName);
685cce7d176Sdrh           pParse->nErr++;
686cce7d176Sdrh           goto insert_cleanup;
687cce7d176Sdrh         }
688cce7d176Sdrh       }
689cce7d176Sdrh     }
690a0217ba7Sdrh   }
6911ccde15dSdrh 
692aacc543eSdrh   /* If there is no IDLIST term but the table has an integer primary
693c8392586Sdrh   ** key, the set the keyColumn variable to the primary key column index
694c8392586Sdrh   ** in the original table definition.
6954a32431cSdrh   */
696147d0cccSdrh   if( pColumn==0 && nColumn>0 ){
6974a32431cSdrh     keyColumn = pTab->iPKey;
6984a32431cSdrh   }
6994a32431cSdrh 
700142e30dfSdrh   /* Open the temp table for FOR EACH ROW triggers
701142e30dfSdrh   */
7022f886d1dSdanielk1977   if( pTrigger ){
703d336e222Sdanielk1977     sqlite3VdbeAddOp3(v, OP_OpenPseudo, newIdx, 0, pTab->nCol);
704f29ce559Sdanielk1977   }
705c3f9bad2Sdanielk1977 
706c3f9bad2Sdanielk1977   /* Initialize the count of rows to be inserted
7071ccde15dSdrh   */
708142e30dfSdrh   if( db->flags & SQLITE_CountRows ){
7096a288a33Sdrh     regRowCount = ++pParse->nMem;
7106a288a33Sdrh     sqlite3VdbeAddOp2(v, OP_Integer, 0, regRowCount);
711c3f9bad2Sdanielk1977   }
712c3f9bad2Sdanielk1977 
713e448dc4aSdanielk1977   /* If this is not a view, open the table and and all indices */
714e448dc4aSdanielk1977   if( !isView ){
715aa9b8963Sdrh     int nIdx;
716aa9b8963Sdrh 
71704adf416Sdrh     baseCur = pParse->nTab;
71804adf416Sdrh     nIdx = sqlite3OpenTableAndIndices(pParse, pTab, baseCur, OP_OpenWrite);
7195c070538Sdrh     aRegIdx = sqlite3DbMallocRaw(db, sizeof(int)*(nIdx+1));
720aa9b8963Sdrh     if( aRegIdx==0 ){
721aa9b8963Sdrh       goto insert_cleanup;
722aa9b8963Sdrh     }
723aa9b8963Sdrh     for(i=0; i<nIdx; i++){
724aa9b8963Sdrh       aRegIdx[i] = ++pParse->nMem;
725aa9b8963Sdrh     }
726feeb1394Sdrh   }
727feeb1394Sdrh 
728e00ee6ebSdrh   /* This is the top of the main insertion loop */
729142e30dfSdrh   if( useTempTable ){
730e00ee6ebSdrh     /* This block codes the top of loop only.  The complete loop is the
731e00ee6ebSdrh     ** following pseudocode (template 4):
732e00ee6ebSdrh     **
733e00ee6ebSdrh     **         rewind temp table
734e00ee6ebSdrh     **      C: loop over rows of intermediate table
735e00ee6ebSdrh     **           transfer values form intermediate table into <table>
736e00ee6ebSdrh     **         end loop
737e00ee6ebSdrh     **      D: ...
738e00ee6ebSdrh     */
739e00ee6ebSdrh     addrInsTop = sqlite3VdbeAddOp1(v, OP_Rewind, srcTab);
740e00ee6ebSdrh     addrCont = sqlite3VdbeCurrentAddr(v);
741142e30dfSdrh   }else if( pSelect ){
742e00ee6ebSdrh     /* This block codes the top of loop only.  The complete loop is the
743e00ee6ebSdrh     ** following pseudocode (template 3):
744e00ee6ebSdrh     **
745e00ee6ebSdrh     **      C: yield X
746e00ee6ebSdrh     **         if EOF goto D
747e00ee6ebSdrh     **         insert the select result into <table> from R..R+n
748e00ee6ebSdrh     **         goto C
749e00ee6ebSdrh     **      D: ...
750e00ee6ebSdrh     */
75192b01d53Sdrh     addrCont = sqlite3VdbeAddOp1(v, OP_Yield, dest.iParm);
752e00ee6ebSdrh     addrInsTop = sqlite3VdbeAddOp1(v, OP_If, regEof);
753bed8690fSdrh   }
7541ccde15dSdrh 
7556a288a33Sdrh   /* Allocate registers for holding the rowid of the new row,
7566a288a33Sdrh   ** the content of the new row, and the assemblied row record.
7576a288a33Sdrh   */
7586a288a33Sdrh   regRecord = ++pParse->nMem;
7596a288a33Sdrh   regRowid = regIns = pParse->nMem+1;
7606a288a33Sdrh   pParse->nMem += pTab->nCol + 1;
7616a288a33Sdrh   if( IsVirtual(pTab) ){
7626a288a33Sdrh     regRowid++;
7636a288a33Sdrh     pParse->nMem++;
7646a288a33Sdrh   }
7656a288a33Sdrh   regData = regRowid+1;
7666a288a33Sdrh 
7675cf590c1Sdrh   /* Run the BEFORE and INSTEAD OF triggers, if there are any
76870ce3f0cSdrh   */
7694adee20fSdanielk1977   endOfLoop = sqlite3VdbeMakeLabel(v);
7702f886d1dSdanielk1977   if( tmask & TRIGGER_BEFORE ){
771dc5ea5c7Sdrh     int regTrigRowid;
7722d401ab8Sdrh     int regCols;
7732d401ab8Sdrh     int regRec;
774c3f9bad2Sdanielk1977 
77570ce3f0cSdrh     /* build the NEW.* reference row.  Note that if there is an INTEGER
77670ce3f0cSdrh     ** PRIMARY KEY into which a NULL is being inserted, that NULL will be
77770ce3f0cSdrh     ** translated into a unique ID for the row.  But on a BEFORE trigger,
77870ce3f0cSdrh     ** we do not know what the unique ID will be (because the insert has
77970ce3f0cSdrh     ** not happened yet) so we substitute a rowid of -1
78070ce3f0cSdrh     */
781dc5ea5c7Sdrh     regTrigRowid = sqlite3GetTempReg(pParse);
78270ce3f0cSdrh     if( keyColumn<0 ){
783dc5ea5c7Sdrh       sqlite3VdbeAddOp2(v, OP_Integer, -1, regTrigRowid);
78470ce3f0cSdrh     }else if( useTempTable ){
785dc5ea5c7Sdrh       sqlite3VdbeAddOp3(v, OP_Column, srcTab, keyColumn, regTrigRowid);
78670ce3f0cSdrh     }else{
7876a288a33Sdrh       int j1;
788d6fe961eSdrh       assert( pSelect==0 );  /* Otherwise useTempTable is true */
789dc5ea5c7Sdrh       sqlite3ExprCode(pParse, pList->a[keyColumn].pExpr, regTrigRowid);
790dc5ea5c7Sdrh       j1 = sqlite3VdbeAddOp1(v, OP_NotNull, regTrigRowid);
791dc5ea5c7Sdrh       sqlite3VdbeAddOp2(v, OP_Integer, -1, regTrigRowid);
7926a288a33Sdrh       sqlite3VdbeJumpHere(v, j1);
793dc5ea5c7Sdrh       sqlite3VdbeAddOp1(v, OP_MustBeInt, regTrigRowid);
79470ce3f0cSdrh     }
79570ce3f0cSdrh 
796034ca14fSdanielk1977     /* Cannot have triggers on a virtual table. If it were possible,
797034ca14fSdanielk1977     ** this block would have to account for hidden column.
798034ca14fSdanielk1977     */
799034ca14fSdanielk1977     assert(!IsVirtual(pTab));
800034ca14fSdanielk1977 
80170ce3f0cSdrh     /* Create the new column data
80270ce3f0cSdrh     */
8032d401ab8Sdrh     regCols = sqlite3GetTempRange(pParse, pTab->nCol);
804c3f9bad2Sdanielk1977     for(i=0; i<pTab->nCol; i++){
805c3f9bad2Sdanielk1977       if( pColumn==0 ){
806c3f9bad2Sdanielk1977         j = i;
807c3f9bad2Sdanielk1977       }else{
808c3f9bad2Sdanielk1977         for(j=0; j<pColumn->nId; j++){
809c3f9bad2Sdanielk1977           if( pColumn->a[j].idx==i ) break;
810c3f9bad2Sdanielk1977         }
811c3f9bad2Sdanielk1977       }
812c3f9bad2Sdanielk1977       if( pColumn && j>=pColumn->nId ){
8132d401ab8Sdrh         sqlite3ExprCode(pParse, pTab->aCol[i].pDflt, regCols+i);
814142e30dfSdrh       }else if( useTempTable ){
8152d401ab8Sdrh         sqlite3VdbeAddOp3(v, OP_Column, srcTab, j, regCols+i);
816c3f9bad2Sdanielk1977       }else{
817d6fe961eSdrh         assert( pSelect==0 ); /* Otherwise useTempTable is true */
8182d401ab8Sdrh         sqlite3ExprCodeAndCache(pParse, pList->a[j].pExpr, regCols+i);
819c3f9bad2Sdanielk1977       }
820c3f9bad2Sdanielk1977     }
8212d401ab8Sdrh     regRec = sqlite3GetTempReg(pParse);
8221db639ceSdrh     sqlite3VdbeAddOp3(v, OP_MakeRecord, regCols, pTab->nCol, regRec);
823a37cdde0Sdanielk1977 
824a37cdde0Sdanielk1977     /* If this is an INSERT on a view with an INSTEAD OF INSERT trigger,
825a37cdde0Sdanielk1977     ** do not attempt any conversions before assembling the record.
826a37cdde0Sdanielk1977     ** If this is a real table, attempt conversions as required by the
827a37cdde0Sdanielk1977     ** table column affinities.
828a37cdde0Sdanielk1977     */
829a37cdde0Sdanielk1977     if( !isView ){
830a37cdde0Sdanielk1977       sqlite3TableAffinityStr(v, pTab);
831a37cdde0Sdanielk1977     }
832dc5ea5c7Sdrh     sqlite3VdbeAddOp3(v, OP_Insert, newIdx, regRec, regTrigRowid);
8332d401ab8Sdrh     sqlite3ReleaseTempReg(pParse, regRec);
834dc5ea5c7Sdrh     sqlite3ReleaseTempReg(pParse, regTrigRowid);
8352d401ab8Sdrh     sqlite3ReleaseTempRange(pParse, regCols, pTab->nCol);
836c3f9bad2Sdanielk1977 
8375cf590c1Sdrh     /* Fire BEFORE or INSTEAD OF triggers */
8382f886d1dSdanielk1977     if( sqlite3CodeRowTrigger(pParse, pTrigger, TK_INSERT, 0, TRIGGER_BEFORE,
8392f886d1dSdanielk1977         pTab, newIdx, -1, onError, endOfLoop, 0, 0) ){
840f29ce559Sdanielk1977       goto insert_cleanup;
841f29ce559Sdanielk1977     }
84270ce3f0cSdrh   }
843c3f9bad2Sdanielk1977 
8444a32431cSdrh   /* Push the record number for the new entry onto the stack.  The
845f0863fe5Sdrh   ** record number is a randomly generate integer created by NewRowid
8464a32431cSdrh   ** except when the table has an INTEGER PRIMARY KEY column, in which
847b419a926Sdrh   ** case the record number is the same as that column.
8481ccde15dSdrh   */
8495cf590c1Sdrh   if( !isView ){
8504cbdda9eSdrh     if( IsVirtual(pTab) ){
8514cbdda9eSdrh       /* The row that the VUpdate opcode will delete: none */
8526a288a33Sdrh       sqlite3VdbeAddOp2(v, OP_Null, 0, regIns);
8534cbdda9eSdrh     }
8544a32431cSdrh     if( keyColumn>=0 ){
855142e30dfSdrh       if( useTempTable ){
8566a288a33Sdrh         sqlite3VdbeAddOp3(v, OP_Column, srcTab, keyColumn, regRowid);
857142e30dfSdrh       }else if( pSelect ){
858b7654111Sdrh         sqlite3VdbeAddOp2(v, OP_SCopy, regFromSelect+keyColumn, regRowid);
8594a32431cSdrh       }else{
860e4d90813Sdrh         VdbeOp *pOp;
8611db639ceSdrh         sqlite3ExprCode(pParse, pList->a[keyColumn].pExpr, regRowid);
862e4d90813Sdrh         pOp = sqlite3VdbeGetOp(v, sqlite3VdbeCurrentAddr(v) - 1);
863bb50e7adSdanielk1977         if( pOp && pOp->opcode==OP_Null && !IsVirtual(pTab) ){
864e4d90813Sdrh           appendFlag = 1;
865e4d90813Sdrh           pOp->opcode = OP_NewRowid;
86604adf416Sdrh           pOp->p1 = baseCur;
8676a288a33Sdrh           pOp->p2 = regRowid;
8686a288a33Sdrh           pOp->p3 = regAutoinc;
869e4d90813Sdrh         }
87027a32783Sdrh       }
871f0863fe5Sdrh       /* If the PRIMARY KEY expression is NULL, then use OP_NewRowid
872e1e68f49Sdrh       ** to generate a unique primary key value.
873e1e68f49Sdrh       */
874e4d90813Sdrh       if( !appendFlag ){
8751db639ceSdrh         int j1;
876bb50e7adSdanielk1977         if( !IsVirtual(pTab) ){
8771db639ceSdrh           j1 = sqlite3VdbeAddOp1(v, OP_NotNull, regRowid);
87804adf416Sdrh           sqlite3VdbeAddOp3(v, OP_NewRowid, baseCur, regRowid, regAutoinc);
8791db639ceSdrh           sqlite3VdbeJumpHere(v, j1);
880bb50e7adSdanielk1977         }else{
881bb50e7adSdanielk1977           j1 = sqlite3VdbeCurrentAddr(v);
882bb50e7adSdanielk1977           sqlite3VdbeAddOp2(v, OP_IsNull, regRowid, j1+2);
883bb50e7adSdanielk1977         }
8843c84ddffSdrh         sqlite3VdbeAddOp1(v, OP_MustBeInt, regRowid);
885e4d90813Sdrh       }
8864cbdda9eSdrh     }else if( IsVirtual(pTab) ){
8876a288a33Sdrh       sqlite3VdbeAddOp2(v, OP_Null, 0, regRowid);
8884a32431cSdrh     }else{
88904adf416Sdrh       sqlite3VdbeAddOp3(v, OP_NewRowid, baseCur, regRowid, regAutoinc);
890e4d90813Sdrh       appendFlag = 1;
8914a32431cSdrh     }
8926a288a33Sdrh     autoIncStep(pParse, regAutoinc, regRowid);
8934a32431cSdrh 
894aacc543eSdrh     /* Push onto the stack, data for all columns of the new entry, beginning
8954a32431cSdrh     ** with the first column.
8964a32431cSdrh     */
897034ca14fSdanielk1977     nHidden = 0;
898cce7d176Sdrh     for(i=0; i<pTab->nCol; i++){
8996a288a33Sdrh       int iRegStore = regRowid+1+i;
9004a32431cSdrh       if( i==pTab->iPKey ){
9014a32431cSdrh         /* The value of the INTEGER PRIMARY KEY column is always a NULL.
902aacc543eSdrh         ** Whenever this column is read, the record number will be substituted
903aacc543eSdrh         ** in its place.  So will fill this column with a NULL to avoid
904aacc543eSdrh         ** taking up data space with information that will never be used. */
9054c583128Sdrh         sqlite3VdbeAddOp2(v, OP_Null, 0, iRegStore);
9064a32431cSdrh         continue;
9074a32431cSdrh       }
908967e8b73Sdrh       if( pColumn==0 ){
909034ca14fSdanielk1977         if( IsHiddenColumn(&pTab->aCol[i]) ){
910034ca14fSdanielk1977           assert( IsVirtual(pTab) );
911034ca14fSdanielk1977           j = -1;
912034ca14fSdanielk1977           nHidden++;
913034ca14fSdanielk1977         }else{
914034ca14fSdanielk1977           j = i - nHidden;
915034ca14fSdanielk1977         }
916cce7d176Sdrh       }else{
917967e8b73Sdrh         for(j=0; j<pColumn->nId; j++){
918967e8b73Sdrh           if( pColumn->a[j].idx==i ) break;
919cce7d176Sdrh         }
920cce7d176Sdrh       }
921034ca14fSdanielk1977       if( j<0 || nColumn==0 || (pColumn && j>=pColumn->nId) ){
922287fb61cSdanielk1977         sqlite3ExprCode(pParse, pTab->aCol[i].pDflt, iRegStore);
923142e30dfSdrh       }else if( useTempTable ){
924287fb61cSdanielk1977         sqlite3VdbeAddOp3(v, OP_Column, srcTab, j, iRegStore);
925142e30dfSdrh       }else if( pSelect ){
926b7654111Sdrh         sqlite3VdbeAddOp2(v, OP_SCopy, regFromSelect+j, iRegStore);
927cce7d176Sdrh       }else{
928287fb61cSdanielk1977         sqlite3ExprCode(pParse, pList->a[j].pExpr, iRegStore);
929cce7d176Sdrh       }
930cce7d176Sdrh     }
9311ccde15dSdrh 
9320ca3e24bSdrh     /* Generate code to check constraints and generate index keys and
9330ca3e24bSdrh     ** do the insertion.
9344a32431cSdrh     */
9354cbdda9eSdrh #ifndef SQLITE_OMIT_VIRTUALTABLE
9364cbdda9eSdrh     if( IsVirtual(pTab) ){
9374f3dd150Sdrh       sqlite3VtabMakeWritable(pParse, pTab);
9386a288a33Sdrh       sqlite3VdbeAddOp4(v, OP_VUpdate, 1, pTab->nCol+2, regIns,
93966a5167bSdrh                      (const char*)pTab->pVtab, P4_VTAB);
9404cbdda9eSdrh     }else
9414cbdda9eSdrh #endif
9424cbdda9eSdrh     {
94304adf416Sdrh       sqlite3GenerateConstraintChecks(
94404adf416Sdrh           pParse,
94504adf416Sdrh           pTab,
94604adf416Sdrh           baseCur,
94704adf416Sdrh           regIns,
94804adf416Sdrh           aRegIdx,
94904adf416Sdrh           keyColumn>=0,
95004adf416Sdrh           0,
95104adf416Sdrh           onError,
95204adf416Sdrh           endOfLoop
95304adf416Sdrh       );
95404adf416Sdrh       sqlite3CompleteInsertion(
95504adf416Sdrh           pParse,
95604adf416Sdrh           pTab,
95704adf416Sdrh           baseCur,
95804adf416Sdrh           regIns,
95904adf416Sdrh           aRegIdx,
96004adf416Sdrh           0,
9612f886d1dSdanielk1977           (tmask&TRIGGER_AFTER) ? newIdx : -1,
96204adf416Sdrh           appendFlag
96304adf416Sdrh        );
9645cf590c1Sdrh     }
9654cbdda9eSdrh   }
9661bee3d7bSdrh 
967feeb1394Sdrh   /* Update the count of rows that are inserted
9681bee3d7bSdrh   */
969142e30dfSdrh   if( (db->flags & SQLITE_CountRows)!=0 ){
9706a288a33Sdrh     sqlite3VdbeAddOp2(v, OP_AddImm, regRowCount, 1);
9711bee3d7bSdrh   }
972c3f9bad2Sdanielk1977 
9732f886d1dSdanielk1977   if( pTrigger ){
974c3f9bad2Sdanielk1977     /* Code AFTER triggers */
9752f886d1dSdanielk1977     if( sqlite3CodeRowTrigger(pParse, pTrigger, TK_INSERT, 0, TRIGGER_AFTER,
9762f886d1dSdanielk1977           pTab, newIdx, -1, onError, endOfLoop, 0, 0) ){
977f29ce559Sdanielk1977       goto insert_cleanup;
978f29ce559Sdanielk1977     }
979c3f9bad2Sdanielk1977   }
9801bee3d7bSdrh 
981e00ee6ebSdrh   /* The bottom of the main insertion loop, if the data source
982e00ee6ebSdrh   ** is a SELECT statement.
9831ccde15dSdrh   */
9844adee20fSdanielk1977   sqlite3VdbeResolveLabel(v, endOfLoop);
985142e30dfSdrh   if( useTempTable ){
986e00ee6ebSdrh     sqlite3VdbeAddOp2(v, OP_Next, srcTab, addrCont);
987e00ee6ebSdrh     sqlite3VdbeJumpHere(v, addrInsTop);
9882eb95377Sdrh     sqlite3VdbeAddOp1(v, OP_Close, srcTab);
989142e30dfSdrh   }else if( pSelect ){
990e00ee6ebSdrh     sqlite3VdbeAddOp2(v, OP_Goto, 0, addrCont);
991e00ee6ebSdrh     sqlite3VdbeJumpHere(v, addrInsTop);
9926b56344dSdrh   }
993c3f9bad2Sdanielk1977 
994e448dc4aSdanielk1977   if( !IsVirtual(pTab) && !isView ){
995c3f9bad2Sdanielk1977     /* Close all tables opened */
9962eb95377Sdrh     sqlite3VdbeAddOp1(v, OP_Close, baseCur);
9976b56344dSdrh     for(idx=1, pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext, idx++){
9982eb95377Sdrh       sqlite3VdbeAddOp1(v, OP_Close, idx+baseCur);
999cce7d176Sdrh     }
1000c3f9bad2Sdanielk1977   }
1001c3f9bad2Sdanielk1977 
1002f3388144Sdrh   /* Update the sqlite_sequence table by storing the content of the
10036a288a33Sdrh   ** counter value in memory regAutoinc back into the sqlite_sequence
1004f3388144Sdrh   ** table.
10052958a4e6Sdrh   */
10066a288a33Sdrh   autoIncEnd(pParse, iDb, pTab, regAutoinc);
10072958a4e6Sdrh 
10081bee3d7bSdrh   /*
1009e7de6f25Sdanielk1977   ** Return the number of rows inserted. If this routine is
1010e7de6f25Sdanielk1977   ** generating code because of a call to sqlite3NestedParse(), do not
1011e7de6f25Sdanielk1977   ** invoke the callback function.
10121bee3d7bSdrh   */
1013cc6bd383Sdanielk1977   if( db->flags & SQLITE_CountRows && pParse->nested==0 && !pParse->trigStack ){
10146a288a33Sdrh     sqlite3VdbeAddOp2(v, OP_ResultRow, regRowCount, 1);
101522322fd4Sdanielk1977     sqlite3VdbeSetNumCols(v, 1);
101610fb749bSdanielk1977     sqlite3VdbeSetColName(v, 0, COLNAME_NAME, "rows inserted", SQLITE_STATIC);
10171bee3d7bSdrh   }
1018cce7d176Sdrh 
1019cce7d176Sdrh insert_cleanup:
1020633e6d57Sdrh   sqlite3SrcListDelete(db, pTabList);
1021633e6d57Sdrh   sqlite3ExprListDelete(db, pList);
1022633e6d57Sdrh   sqlite3SelectDelete(db, pSelect);
1023633e6d57Sdrh   sqlite3IdListDelete(db, pColumn);
1024633e6d57Sdrh   sqlite3DbFree(db, aRegIdx);
1025cce7d176Sdrh }
10269cfcf5d4Sdrh 
10279cfcf5d4Sdrh /*
10286a288a33Sdrh ** Generate code to do constraint checks prior to an INSERT or an UPDATE.
10299cfcf5d4Sdrh **
103004adf416Sdrh ** The input is a range of consecutive registers as follows:
10310ca3e24bSdrh **
1032f0863fe5Sdrh **    1.  The rowid of the row to be updated before the update.  This
1033b419a926Sdrh **        value is omitted unless we are doing an UPDATE that involves a
1034a05a722fSdrh **        change to the record number or writing to a virtual table.
10350ca3e24bSdrh **
1036f0863fe5Sdrh **    2.  The rowid of the row after the update.
10370ca3e24bSdrh **
10380ca3e24bSdrh **    3.  The data in the first column of the entry after the update.
10390ca3e24bSdrh **
10400ca3e24bSdrh **    i.  Data from middle columns...
10410ca3e24bSdrh **
10420ca3e24bSdrh **    N.  The data in the last column of the entry after the update.
10430ca3e24bSdrh **
104404adf416Sdrh ** The regRowid parameter is the index of the register containing (2).
104504adf416Sdrh **
1046f0863fe5Sdrh ** The old rowid shown as entry (1) above is omitted unless both isUpdate
1047f0863fe5Sdrh ** and rowidChng are 1.  isUpdate is true for UPDATEs and false for
1048a05a722fSdrh ** INSERTs.  RowidChng means that the new rowid is explicitly specified by
1049a05a722fSdrh ** the update or insert statement.  If rowidChng is false, it means that
1050a05a722fSdrh ** the rowid is computed automatically in an insert or that the rowid value
1051a05a722fSdrh ** is not modified by the update.
10520ca3e24bSdrh **
1053aa9b8963Sdrh ** The code generated by this routine store new index entries into
1054aa9b8963Sdrh ** registers identified by aRegIdx[].  No index entry is created for
1055aa9b8963Sdrh ** indices where aRegIdx[i]==0.  The order of indices in aRegIdx[] is
1056aa9b8963Sdrh ** the same as the order of indices on the linked list of indices
1057aa9b8963Sdrh ** attached to the table.
10589cfcf5d4Sdrh **
10599cfcf5d4Sdrh ** This routine also generates code to check constraints.  NOT NULL,
10609cfcf5d4Sdrh ** CHECK, and UNIQUE constraints are all checked.  If a constraint fails,
10611c92853dSdrh ** then the appropriate action is performed.  There are five possible
10621c92853dSdrh ** actions: ROLLBACK, ABORT, FAIL, REPLACE, and IGNORE.
10639cfcf5d4Sdrh **
10649cfcf5d4Sdrh **  Constraint type  Action       What Happens
10659cfcf5d4Sdrh **  ---------------  ----------   ----------------------------------------
10661c92853dSdrh **  any              ROLLBACK     The current transaction is rolled back and
106724b03fd0Sdanielk1977 **                                sqlite3_exec() returns immediately with a
10689cfcf5d4Sdrh **                                return code of SQLITE_CONSTRAINT.
10699cfcf5d4Sdrh **
10701c92853dSdrh **  any              ABORT        Back out changes from the current command
10711c92853dSdrh **                                only (do not do a complete rollback) then
107224b03fd0Sdanielk1977 **                                cause sqlite3_exec() to return immediately
10731c92853dSdrh **                                with SQLITE_CONSTRAINT.
10741c92853dSdrh **
10751c92853dSdrh **  any              FAIL         Sqlite_exec() returns immediately with a
10761c92853dSdrh **                                return code of SQLITE_CONSTRAINT.  The
10771c92853dSdrh **                                transaction is not rolled back and any
10781c92853dSdrh **                                prior changes are retained.
10791c92853dSdrh **
10809cfcf5d4Sdrh **  any              IGNORE       The record number and data is popped from
10819cfcf5d4Sdrh **                                the stack and there is an immediate jump
10829cfcf5d4Sdrh **                                to label ignoreDest.
10839cfcf5d4Sdrh **
10849cfcf5d4Sdrh **  NOT NULL         REPLACE      The NULL value is replace by the default
10859cfcf5d4Sdrh **                                value for that column.  If the default value
10869cfcf5d4Sdrh **                                is NULL, the action is the same as ABORT.
10879cfcf5d4Sdrh **
10889cfcf5d4Sdrh **  UNIQUE           REPLACE      The other row that conflicts with the row
10899cfcf5d4Sdrh **                                being inserted is removed.
10909cfcf5d4Sdrh **
10919cfcf5d4Sdrh **  CHECK            REPLACE      Illegal.  The results in an exception.
10929cfcf5d4Sdrh **
10931c92853dSdrh ** Which action to take is determined by the overrideError parameter.
10941c92853dSdrh ** Or if overrideError==OE_Default, then the pParse->onError parameter
10951c92853dSdrh ** is used.  Or if pParse->onError==OE_Default then the onError value
10961c92853dSdrh ** for the constraint is used.
10979cfcf5d4Sdrh **
1098aaab5725Sdrh ** The calling routine must open a read/write cursor for pTab with
109904adf416Sdrh ** cursor number "baseCur".  All indices of pTab must also have open
110004adf416Sdrh ** read/write cursors with cursor number baseCur+i for the i-th cursor.
11019cfcf5d4Sdrh ** Except, if there is no possibility of a REPLACE action then
1102aa9b8963Sdrh ** cursors do not need to be open for indices where aRegIdx[i]==0.
11039cfcf5d4Sdrh */
11044adee20fSdanielk1977 void sqlite3GenerateConstraintChecks(
11059cfcf5d4Sdrh   Parse *pParse,      /* The parser context */
11069cfcf5d4Sdrh   Table *pTab,        /* the table into which we are inserting */
110704adf416Sdrh   int baseCur,        /* Index of a read/write cursor pointing at pTab */
110804adf416Sdrh   int regRowid,       /* Index of the range of input registers */
1109aa9b8963Sdrh   int *aRegIdx,       /* Register used by each index.  0 for unused indices */
1110a05a722fSdrh   int rowidChng,      /* True if the rowid might collide with existing entry */
1111b419a926Sdrh   int isUpdate,       /* True for UPDATE, False for INSERT */
11129cfcf5d4Sdrh   int overrideError,  /* Override onError to this if not OE_Default */
1113b419a926Sdrh   int ignoreDest      /* Jump to this label on an OE_Ignore resolution */
11149cfcf5d4Sdrh ){
11159cfcf5d4Sdrh   int i;
11169cfcf5d4Sdrh   Vdbe *v;
11179cfcf5d4Sdrh   int nCol;
11189cfcf5d4Sdrh   int onError;
11191bd10f8aSdrh   int j1;             /* Addresss of jump instruction */
11201bd10f8aSdrh   int j2 = 0, j3;     /* Addresses of jump instructions */
112104adf416Sdrh   int regData;        /* Register containing first data column */
11220ca3e24bSdrh   int iCur;
11230ca3e24bSdrh   Index *pIdx;
11240ca3e24bSdrh   int seenReplace = 0;
1125f0863fe5Sdrh   int hasTwoRowids = (isUpdate && rowidChng);
11269cfcf5d4Sdrh 
11274adee20fSdanielk1977   v = sqlite3GetVdbe(pParse);
11289cfcf5d4Sdrh   assert( v!=0 );
1129417be79cSdrh   assert( pTab->pSelect==0 );  /* This table is not a VIEW */
11309cfcf5d4Sdrh   nCol = pTab->nCol;
1131aa9b8963Sdrh   regData = regRowid + 1;
1132aa9b8963Sdrh 
113304adf416Sdrh 
11349cfcf5d4Sdrh   /* Test all NOT NULL constraints.
11359cfcf5d4Sdrh   */
11369cfcf5d4Sdrh   for(i=0; i<nCol; i++){
11370ca3e24bSdrh     if( i==pTab->iPKey ){
11380ca3e24bSdrh       continue;
11390ca3e24bSdrh     }
11409cfcf5d4Sdrh     onError = pTab->aCol[i].notNull;
11410ca3e24bSdrh     if( onError==OE_None ) continue;
11429cfcf5d4Sdrh     if( overrideError!=OE_Default ){
11439cfcf5d4Sdrh       onError = overrideError;
1144a996e477Sdrh     }else if( onError==OE_Default ){
1145a996e477Sdrh       onError = OE_Abort;
11469cfcf5d4Sdrh     }
11477977a17fSdanielk1977     if( onError==OE_Replace && pTab->aCol[i].pDflt==0 ){
11489cfcf5d4Sdrh       onError = OE_Abort;
11499cfcf5d4Sdrh     }
1150b84f96f8Sdanielk1977     assert( onError==OE_Rollback || onError==OE_Abort || onError==OE_Fail
1151b84f96f8Sdanielk1977         || onError==OE_Ignore || onError==OE_Replace );
11529cfcf5d4Sdrh     switch( onError ){
11531c92853dSdrh       case OE_Rollback:
11541c92853dSdrh       case OE_Abort:
11551c92853dSdrh       case OE_Fail: {
1156f089aa45Sdrh         char *zMsg;
11575053a79bSdrh         j1 = sqlite3VdbeAddOp3(v, OP_HaltIfNull,
11585053a79bSdrh                                   SQLITE_CONSTRAINT, onError, regData+i);
1159f089aa45Sdrh         zMsg = sqlite3MPrintf(pParse->db, "%s.%s may not be NULL",
1160f089aa45Sdrh                               pTab->zName, pTab->aCol[i].zName);
116166a5167bSdrh         sqlite3VdbeChangeP4(v, -1, zMsg, P4_DYNAMIC);
11629cfcf5d4Sdrh         break;
11639cfcf5d4Sdrh       }
11649cfcf5d4Sdrh       case OE_Ignore: {
11655053a79bSdrh         sqlite3VdbeAddOp2(v, OP_IsNull, regData+i, ignoreDest);
11669cfcf5d4Sdrh         break;
11679cfcf5d4Sdrh       }
11689cfcf5d4Sdrh       case OE_Replace: {
11695053a79bSdrh         j1 = sqlite3VdbeAddOp1(v, OP_NotNull, regData+i);
117004adf416Sdrh         sqlite3ExprCode(pParse, pTab->aCol[i].pDflt, regData+i);
11715053a79bSdrh         sqlite3VdbeJumpHere(v, j1);
11729cfcf5d4Sdrh         break;
11739cfcf5d4Sdrh       }
11749cfcf5d4Sdrh     }
11759cfcf5d4Sdrh   }
11769cfcf5d4Sdrh 
11779cfcf5d4Sdrh   /* Test all CHECK constraints
11789cfcf5d4Sdrh   */
1179ffe07b2dSdrh #ifndef SQLITE_OMIT_CHECK
11800cd2d4c9Sdrh   if( pTab->pCheck && (pParse->db->flags & SQLITE_IgnoreChecks)==0 ){
1181ffe07b2dSdrh     int allOk = sqlite3VdbeMakeLabel(v);
1182aa9b8963Sdrh     pParse->ckBase = regData;
118335573356Sdrh     sqlite3ExprIfTrue(pParse, pTab->pCheck, allOk, SQLITE_JUMPIFNULL);
1184aa01c7e2Sdrh     onError = overrideError!=OE_Default ? overrideError : OE_Abort;
11852e06c67cSdrh     if( onError==OE_Ignore ){
118666a5167bSdrh       sqlite3VdbeAddOp2(v, OP_Goto, 0, ignoreDest);
1187aa01c7e2Sdrh     }else{
118866a5167bSdrh       sqlite3VdbeAddOp2(v, OP_Halt, SQLITE_CONSTRAINT, onError);
1189aa01c7e2Sdrh     }
1190ffe07b2dSdrh     sqlite3VdbeResolveLabel(v, allOk);
1191ffe07b2dSdrh   }
1192ffe07b2dSdrh #endif /* !defined(SQLITE_OMIT_CHECK) */
11939cfcf5d4Sdrh 
11940bd1f4eaSdrh   /* If we have an INTEGER PRIMARY KEY, make sure the primary key
11950bd1f4eaSdrh   ** of the new record does not previously exist.  Except, if this
11960bd1f4eaSdrh   ** is an UPDATE and the primary key is not changing, that is OK.
11979cfcf5d4Sdrh   */
1198f0863fe5Sdrh   if( rowidChng ){
11990ca3e24bSdrh     onError = pTab->keyConf;
12000ca3e24bSdrh     if( overrideError!=OE_Default ){
12010ca3e24bSdrh       onError = overrideError;
1202a996e477Sdrh     }else if( onError==OE_Default ){
1203a996e477Sdrh       onError = OE_Abort;
12040ca3e24bSdrh     }
1205a0217ba7Sdrh 
120660a713c6Sdrh     if( onError!=OE_Replace || pTab->pIndex ){
120779b0c956Sdrh       if( isUpdate ){
1208892d3179Sdrh         j2 = sqlite3VdbeAddOp3(v, OP_Eq, regRowid, 0, regRowid-1);
120979b0c956Sdrh       }
121004adf416Sdrh       j3 = sqlite3VdbeAddOp3(v, OP_NotExists, baseCur, 0, regRowid);
12110ca3e24bSdrh       switch( onError ){
1212a0217ba7Sdrh         default: {
1213a0217ba7Sdrh           onError = OE_Abort;
1214a0217ba7Sdrh           /* Fall thru into the next case */
1215a0217ba7Sdrh         }
12161c92853dSdrh         case OE_Rollback:
12171c92853dSdrh         case OE_Abort:
12181c92853dSdrh         case OE_Fail: {
121966a5167bSdrh           sqlite3VdbeAddOp4(v, OP_Halt, SQLITE_CONSTRAINT, onError, 0,
122066a5167bSdrh                            "PRIMARY KEY must be unique", P4_STATIC);
12210ca3e24bSdrh           break;
12220ca3e24bSdrh         }
12235383ae5cSdrh         case OE_Replace: {
12242d401ab8Sdrh           sqlite3GenerateRowIndexDelete(pParse, pTab, baseCur, 0);
12255383ae5cSdrh           seenReplace = 1;
12265383ae5cSdrh           break;
12275383ae5cSdrh         }
12280ca3e24bSdrh         case OE_Ignore: {
12295383ae5cSdrh           assert( seenReplace==0 );
123066a5167bSdrh           sqlite3VdbeAddOp2(v, OP_Goto, 0, ignoreDest);
12310ca3e24bSdrh           break;
12320ca3e24bSdrh         }
12330ca3e24bSdrh       }
1234aa9b8963Sdrh       sqlite3VdbeJumpHere(v, j3);
1235f5905aa7Sdrh       if( isUpdate ){
1236aa9b8963Sdrh         sqlite3VdbeJumpHere(v, j2);
1237a05a722fSdrh       }
12380ca3e24bSdrh     }
12390ca3e24bSdrh   }
12400bd1f4eaSdrh 
12410bd1f4eaSdrh   /* Test all UNIQUE constraints by creating entries for each UNIQUE
12420bd1f4eaSdrh   ** index and making sure that duplicate entries do not already exist.
12430bd1f4eaSdrh   ** Add the new records to the indices as we go.
12440bd1f4eaSdrh   */
1245b2fe7d8cSdrh   for(iCur=0, pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext, iCur++){
12462d401ab8Sdrh     int regIdx;
12472d401ab8Sdrh     int regR;
12482d401ab8Sdrh 
1249aa9b8963Sdrh     if( aRegIdx[iCur]==0 ) continue;  /* Skip unused indices */
1250b2fe7d8cSdrh 
1251b2fe7d8cSdrh     /* Create a key for accessing the index entry */
12522d401ab8Sdrh     regIdx = sqlite3GetTempRange(pParse, pIdx->nColumn+1);
12539cfcf5d4Sdrh     for(i=0; i<pIdx->nColumn; i++){
12549cfcf5d4Sdrh       int idx = pIdx->aiColumn[i];
12559cfcf5d4Sdrh       if( idx==pTab->iPKey ){
12562d401ab8Sdrh         sqlite3VdbeAddOp2(v, OP_SCopy, regRowid, regIdx+i);
12579cfcf5d4Sdrh       }else{
12582d401ab8Sdrh         sqlite3VdbeAddOp2(v, OP_SCopy, regData+idx, regIdx+i);
12599cfcf5d4Sdrh       }
12609cfcf5d4Sdrh     }
12612d401ab8Sdrh     sqlite3VdbeAddOp2(v, OP_SCopy, regRowid, regIdx+i);
12621db639ceSdrh     sqlite3VdbeAddOp3(v, OP_MakeRecord, regIdx, pIdx->nColumn+1, aRegIdx[iCur]);
1263a37cdde0Sdanielk1977     sqlite3IndexAffinityStr(v, pIdx);
1264da250ea5Sdrh     sqlite3ExprCacheAffinityChange(pParse, regIdx, pIdx->nColumn+1);
12652d401ab8Sdrh     sqlite3ReleaseTempRange(pParse, regIdx, pIdx->nColumn+1);
1266b2fe7d8cSdrh 
1267b2fe7d8cSdrh     /* Find out what action to take in case there is an indexing conflict */
12689cfcf5d4Sdrh     onError = pIdx->onError;
1269b2fe7d8cSdrh     if( onError==OE_None ) continue;  /* pIdx is not a UNIQUE index */
12709cfcf5d4Sdrh     if( overrideError!=OE_Default ){
12719cfcf5d4Sdrh       onError = overrideError;
1272a996e477Sdrh     }else if( onError==OE_Default ){
1273a996e477Sdrh       onError = OE_Abort;
12749cfcf5d4Sdrh     }
12755383ae5cSdrh     if( seenReplace ){
12765383ae5cSdrh       if( onError==OE_Ignore ) onError = OE_Replace;
12775383ae5cSdrh       else if( onError==OE_Fail ) onError = OE_Abort;
12785383ae5cSdrh     }
12795383ae5cSdrh 
1280b2fe7d8cSdrh 
1281b2fe7d8cSdrh     /* Check to see if the new index entry will be unique */
12822d401ab8Sdrh     j2 = sqlite3VdbeAddOp3(v, OP_IsNull, regIdx, 0, pIdx->nColumn);
12832d401ab8Sdrh     regR = sqlite3GetTempReg(pParse);
12842d401ab8Sdrh     sqlite3VdbeAddOp2(v, OP_SCopy, regRowid-hasTwoRowids, regR);
12852d401ab8Sdrh     j3 = sqlite3VdbeAddOp4(v, OP_IsUnique, baseCur+iCur+1, 0,
12861fc4129dSshane                            regR, SQLITE_INT_TO_PTR(aRegIdx[iCur]),
1287a9e852b6Smlcreech                            P4_INT32);
1288b2fe7d8cSdrh 
1289b2fe7d8cSdrh     /* Generate code that executes if the new index entry is not unique */
1290b84f96f8Sdanielk1977     assert( onError==OE_Rollback || onError==OE_Abort || onError==OE_Fail
1291b84f96f8Sdanielk1977         || onError==OE_Ignore || onError==OE_Replace );
12929cfcf5d4Sdrh     switch( onError ){
12931c92853dSdrh       case OE_Rollback:
12941c92853dSdrh       case OE_Abort:
12951c92853dSdrh       case OE_Fail: {
129637ed48edSdrh         int j, n1, n2;
129737ed48edSdrh         char zErrMsg[200];
129800e13613Sdanielk1977         sqlite3_snprintf(ArraySize(zErrMsg), zErrMsg,
12995bb3eb9bSdrh                          pIdx->nColumn>1 ? "columns " : "column ");
1300ea678832Sdrh         n1 = sqlite3Strlen30(zErrMsg);
130100e13613Sdanielk1977         for(j=0; j<pIdx->nColumn && n1<ArraySize(zErrMsg)-30; j++){
130237ed48edSdrh           char *zCol = pTab->aCol[pIdx->aiColumn[j]].zName;
1303ea678832Sdrh           n2 = sqlite3Strlen30(zCol);
130437ed48edSdrh           if( j>0 ){
130500e13613Sdanielk1977             sqlite3_snprintf(ArraySize(zErrMsg)-n1, &zErrMsg[n1], ", ");
130637ed48edSdrh             n1 += 2;
130737ed48edSdrh           }
130800e13613Sdanielk1977           if( n1+n2>ArraySize(zErrMsg)-30 ){
130900e13613Sdanielk1977             sqlite3_snprintf(ArraySize(zErrMsg)-n1, &zErrMsg[n1], "...");
131037ed48edSdrh             n1 += 3;
131137ed48edSdrh             break;
131237ed48edSdrh           }else{
131300e13613Sdanielk1977             sqlite3_snprintf(ArraySize(zErrMsg)-n1, &zErrMsg[n1], "%s", zCol);
131437ed48edSdrh             n1 += n2;
131537ed48edSdrh           }
131637ed48edSdrh         }
131700e13613Sdanielk1977         sqlite3_snprintf(ArraySize(zErrMsg)-n1, &zErrMsg[n1],
131837ed48edSdrh             pIdx->nColumn>1 ? " are not unique" : " is not unique");
131966a5167bSdrh         sqlite3VdbeAddOp4(v, OP_Halt, SQLITE_CONSTRAINT, onError, 0, zErrMsg,0);
13209cfcf5d4Sdrh         break;
13219cfcf5d4Sdrh       }
13229cfcf5d4Sdrh       case OE_Ignore: {
13230ca3e24bSdrh         assert( seenReplace==0 );
132466a5167bSdrh         sqlite3VdbeAddOp2(v, OP_Goto, 0, ignoreDest);
13259cfcf5d4Sdrh         break;
13269cfcf5d4Sdrh       }
13279cfcf5d4Sdrh       case OE_Replace: {
13282d401ab8Sdrh         sqlite3GenerateRowDelete(pParse, pTab, baseCur, regR, 0);
13290ca3e24bSdrh         seenReplace = 1;
13309cfcf5d4Sdrh         break;
13319cfcf5d4Sdrh       }
13329cfcf5d4Sdrh     }
1333aa9b8963Sdrh     sqlite3VdbeJumpHere(v, j2);
13342d401ab8Sdrh     sqlite3VdbeJumpHere(v, j3);
13352d401ab8Sdrh     sqlite3ReleaseTempReg(pParse, regR);
13369cfcf5d4Sdrh   }
13379cfcf5d4Sdrh }
13380ca3e24bSdrh 
13390ca3e24bSdrh /*
13400ca3e24bSdrh ** This routine generates code to finish the INSERT or UPDATE operation
13414adee20fSdanielk1977 ** that was started by a prior call to sqlite3GenerateConstraintChecks.
134204adf416Sdrh ** A consecutive range of registers starting at regRowid contains the
134304adf416Sdrh ** rowid and the content to be inserted.
13440ca3e24bSdrh **
1345b419a926Sdrh ** The arguments to this routine should be the same as the first six
13464adee20fSdanielk1977 ** arguments to sqlite3GenerateConstraintChecks.
13470ca3e24bSdrh */
13484adee20fSdanielk1977 void sqlite3CompleteInsertion(
13490ca3e24bSdrh   Parse *pParse,      /* The parser context */
13500ca3e24bSdrh   Table *pTab,        /* the table into which we are inserting */
135104adf416Sdrh   int baseCur,        /* Index of a read/write cursor pointing at pTab */
135204adf416Sdrh   int regRowid,       /* Range of content */
1353aa9b8963Sdrh   int *aRegIdx,       /* Register used by each index.  0 for unused indices */
135470ce3f0cSdrh   int isUpdate,       /* True for UPDATE, False for INSERT */
1355e4d90813Sdrh   int newIdx,         /* Index of NEW table for triggers.  -1 if none */
1356e4d90813Sdrh   int appendBias      /* True if this is likely to be an append */
13570ca3e24bSdrh ){
13580ca3e24bSdrh   int i;
13590ca3e24bSdrh   Vdbe *v;
13600ca3e24bSdrh   int nIdx;
13610ca3e24bSdrh   Index *pIdx;
13621bd10f8aSdrh   u8 pik_flags;
136304adf416Sdrh   int regData;
1364b7654111Sdrh   int regRec;
13650ca3e24bSdrh 
13664adee20fSdanielk1977   v = sqlite3GetVdbe(pParse);
13670ca3e24bSdrh   assert( v!=0 );
1368417be79cSdrh   assert( pTab->pSelect==0 );  /* This table is not a VIEW */
13690ca3e24bSdrh   for(nIdx=0, pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext, nIdx++){}
13700ca3e24bSdrh   for(i=nIdx-1; i>=0; i--){
1371aa9b8963Sdrh     if( aRegIdx[i]==0 ) continue;
137204adf416Sdrh     sqlite3VdbeAddOp2(v, OP_IdxInsert, baseCur+i+1, aRegIdx[i]);
13730ca3e24bSdrh   }
137404adf416Sdrh   regData = regRowid + 1;
1375b7654111Sdrh   regRec = sqlite3GetTempReg(pParse);
13761db639ceSdrh   sqlite3VdbeAddOp3(v, OP_MakeRecord, regData, pTab->nCol, regRec);
1377a37cdde0Sdanielk1977   sqlite3TableAffinityStr(v, pTab);
1378da250ea5Sdrh   sqlite3ExprCacheAffinityChange(pParse, regData, pTab->nCol);
1379b84f96f8Sdanielk1977 #ifndef SQLITE_OMIT_TRIGGER
138070ce3f0cSdrh   if( newIdx>=0 ){
1381b7654111Sdrh     sqlite3VdbeAddOp3(v, OP_Insert, newIdx, regRec, regRowid);
138270ce3f0cSdrh   }
1383b84f96f8Sdanielk1977 #endif
13844794f735Sdrh   if( pParse->nested ){
13854794f735Sdrh     pik_flags = 0;
13864794f735Sdrh   }else{
138794eb6a14Sdanielk1977     pik_flags = OPFLAG_NCHANGE;
138894eb6a14Sdanielk1977     pik_flags |= (isUpdate?OPFLAG_ISUPDATE:OPFLAG_LASTROWID);
13894794f735Sdrh   }
1390e4d90813Sdrh   if( appendBias ){
1391e4d90813Sdrh     pik_flags |= OPFLAG_APPEND;
1392e4d90813Sdrh   }
1393b7654111Sdrh   sqlite3VdbeAddOp3(v, OP_Insert, baseCur, regRec, regRowid);
139494eb6a14Sdanielk1977   if( !pParse->nested ){
139566a5167bSdrh     sqlite3VdbeChangeP4(v, -1, pTab->zName, P4_STATIC);
139694eb6a14Sdanielk1977   }
1397b7654111Sdrh   sqlite3VdbeChangeP5(v, pik_flags);
13980ca3e24bSdrh }
1399cd44690aSdrh 
1400cd44690aSdrh /*
1401290c1948Sdrh ** Generate code that will open cursors for a table and for all
140204adf416Sdrh ** indices of that table.  The "baseCur" parameter is the cursor number used
1403cd44690aSdrh ** for the table.  Indices are opened on subsequent cursors.
1404aa9b8963Sdrh **
1405aa9b8963Sdrh ** Return the number of indices on the table.
1406cd44690aSdrh */
1407aa9b8963Sdrh int sqlite3OpenTableAndIndices(
1408290c1948Sdrh   Parse *pParse,   /* Parsing context */
1409290c1948Sdrh   Table *pTab,     /* Table to be opened */
141004adf416Sdrh   int baseCur,     /* Cursor number assigned to the table */
1411290c1948Sdrh   int op           /* OP_OpenRead or OP_OpenWrite */
1412290c1948Sdrh ){
1413cd44690aSdrh   int i;
14144cbdda9eSdrh   int iDb;
1415cd44690aSdrh   Index *pIdx;
14164cbdda9eSdrh   Vdbe *v;
14174cbdda9eSdrh 
1418aa9b8963Sdrh   if( IsVirtual(pTab) ) return 0;
14194cbdda9eSdrh   iDb = sqlite3SchemaToIndex(pParse->db, pTab->pSchema);
14204cbdda9eSdrh   v = sqlite3GetVdbe(pParse);
1421cd44690aSdrh   assert( v!=0 );
142204adf416Sdrh   sqlite3OpenTable(pParse, baseCur, iDb, pTab, op);
1423cd44690aSdrh   for(i=1, pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext, i++){
1424b3bf556eSdanielk1977     KeyInfo *pKey = sqlite3IndexKeyinfo(pParse, pIdx);
1425da184236Sdanielk1977     assert( pIdx->pSchema==pTab->pSchema );
142604adf416Sdrh     sqlite3VdbeAddOp4(v, op, i+baseCur, pIdx->tnum, iDb,
142766a5167bSdrh                       (char*)pKey, P4_KEYINFO_HANDOFF);
1428207872a4Sdanielk1977     VdbeComment((v, "%s", pIdx->zName));
1429cd44690aSdrh   }
143004adf416Sdrh   if( pParse->nTab<=baseCur+i ){
143104adf416Sdrh     pParse->nTab = baseCur+i;
1432290c1948Sdrh   }
1433aa9b8963Sdrh   return i-1;
1434cd44690aSdrh }
14359d9cf229Sdrh 
143691c58e23Sdrh 
143791c58e23Sdrh #ifdef SQLITE_TEST
143891c58e23Sdrh /*
143991c58e23Sdrh ** The following global variable is incremented whenever the
144091c58e23Sdrh ** transfer optimization is used.  This is used for testing
144191c58e23Sdrh ** purposes only - to make sure the transfer optimization really
144291c58e23Sdrh ** is happening when it is suppose to.
144391c58e23Sdrh */
144491c58e23Sdrh int sqlite3_xferopt_count;
144591c58e23Sdrh #endif /* SQLITE_TEST */
144691c58e23Sdrh 
144791c58e23Sdrh 
14489d9cf229Sdrh #ifndef SQLITE_OMIT_XFER_OPT
14499d9cf229Sdrh /*
14509d9cf229Sdrh ** Check to collation names to see if they are compatible.
14519d9cf229Sdrh */
14529d9cf229Sdrh static int xferCompatibleCollation(const char *z1, const char *z2){
14539d9cf229Sdrh   if( z1==0 ){
14549d9cf229Sdrh     return z2==0;
14559d9cf229Sdrh   }
14569d9cf229Sdrh   if( z2==0 ){
14579d9cf229Sdrh     return 0;
14589d9cf229Sdrh   }
14599d9cf229Sdrh   return sqlite3StrICmp(z1, z2)==0;
14609d9cf229Sdrh }
14619d9cf229Sdrh 
14629d9cf229Sdrh 
14639d9cf229Sdrh /*
14649d9cf229Sdrh ** Check to see if index pSrc is compatible as a source of data
14659d9cf229Sdrh ** for index pDest in an insert transfer optimization.  The rules
14669d9cf229Sdrh ** for a compatible index:
14679d9cf229Sdrh **
14689d9cf229Sdrh **    *   The index is over the same set of columns
14699d9cf229Sdrh **    *   The same DESC and ASC markings occurs on all columns
14709d9cf229Sdrh **    *   The same onError processing (OE_Abort, OE_Ignore, etc)
14719d9cf229Sdrh **    *   The same collating sequence on each column
14729d9cf229Sdrh */
14739d9cf229Sdrh static int xferCompatibleIndex(Index *pDest, Index *pSrc){
14749d9cf229Sdrh   int i;
14759d9cf229Sdrh   assert( pDest && pSrc );
14769d9cf229Sdrh   assert( pDest->pTable!=pSrc->pTable );
14779d9cf229Sdrh   if( pDest->nColumn!=pSrc->nColumn ){
14789d9cf229Sdrh     return 0;   /* Different number of columns */
14799d9cf229Sdrh   }
14809d9cf229Sdrh   if( pDest->onError!=pSrc->onError ){
14819d9cf229Sdrh     return 0;   /* Different conflict resolution strategies */
14829d9cf229Sdrh   }
14839d9cf229Sdrh   for(i=0; i<pSrc->nColumn; i++){
14849d9cf229Sdrh     if( pSrc->aiColumn[i]!=pDest->aiColumn[i] ){
14859d9cf229Sdrh       return 0;   /* Different columns indexed */
14869d9cf229Sdrh     }
14879d9cf229Sdrh     if( pSrc->aSortOrder[i]!=pDest->aSortOrder[i] ){
14889d9cf229Sdrh       return 0;   /* Different sort orders */
14899d9cf229Sdrh     }
14909d9cf229Sdrh     if( pSrc->azColl[i]!=pDest->azColl[i] ){
149160a713c6Sdrh       return 0;   /* Different collating sequences */
14929d9cf229Sdrh     }
14939d9cf229Sdrh   }
14949d9cf229Sdrh 
14959d9cf229Sdrh   /* If no test above fails then the indices must be compatible */
14969d9cf229Sdrh   return 1;
14979d9cf229Sdrh }
14989d9cf229Sdrh 
14999d9cf229Sdrh /*
15009d9cf229Sdrh ** Attempt the transfer optimization on INSERTs of the form
15019d9cf229Sdrh **
15029d9cf229Sdrh **     INSERT INTO tab1 SELECT * FROM tab2;
15039d9cf229Sdrh **
15049d9cf229Sdrh ** This optimization is only attempted if
15059d9cf229Sdrh **
15069d9cf229Sdrh **    (1)  tab1 and tab2 have identical schemas including all the
15078103b7d2Sdrh **         same indices and constraints
15089d9cf229Sdrh **
15099d9cf229Sdrh **    (2)  tab1 and tab2 are different tables
15109d9cf229Sdrh **
15119d9cf229Sdrh **    (3)  There must be no triggers on tab1
15129d9cf229Sdrh **
15139d9cf229Sdrh **    (4)  The result set of the SELECT statement is "*"
15149d9cf229Sdrh **
15159d9cf229Sdrh **    (5)  The SELECT statement has no WHERE, HAVING, ORDER BY, GROUP BY,
15169d9cf229Sdrh **         or LIMIT clause.
15179d9cf229Sdrh **
15189d9cf229Sdrh **    (6)  The SELECT statement is a simple (not a compound) select that
15199d9cf229Sdrh **         contains only tab2 in its FROM clause
15209d9cf229Sdrh **
15219d9cf229Sdrh ** This method for implementing the INSERT transfers raw records from
15229d9cf229Sdrh ** tab2 over to tab1.  The columns are not decoded.  Raw records from
15239d9cf229Sdrh ** the indices of tab2 are transfered to tab1 as well.  In so doing,
15249d9cf229Sdrh ** the resulting tab1 has much less fragmentation.
15259d9cf229Sdrh **
15269d9cf229Sdrh ** This routine returns TRUE if the optimization is attempted.  If any
15279d9cf229Sdrh ** of the conditions above fail so that the optimization should not
15289d9cf229Sdrh ** be attempted, then this routine returns FALSE.
15299d9cf229Sdrh */
15309d9cf229Sdrh static int xferOptimization(
15319d9cf229Sdrh   Parse *pParse,        /* Parser context */
15329d9cf229Sdrh   Table *pDest,         /* The table we are inserting into */
15339d9cf229Sdrh   Select *pSelect,      /* A SELECT statement to use as the data source */
15349d9cf229Sdrh   int onError,          /* How to handle constraint errors */
15359d9cf229Sdrh   int iDbDest           /* The database of pDest */
15369d9cf229Sdrh ){
15379d9cf229Sdrh   ExprList *pEList;                /* The result set of the SELECT */
15389d9cf229Sdrh   Table *pSrc;                     /* The table in the FROM clause of SELECT */
15399d9cf229Sdrh   Index *pSrcIdx, *pDestIdx;       /* Source and destination indices */
15409d9cf229Sdrh   struct SrcList_item *pItem;      /* An element of pSelect->pSrc */
15419d9cf229Sdrh   int i;                           /* Loop counter */
15429d9cf229Sdrh   int iDbSrc;                      /* The database of pSrc */
15439d9cf229Sdrh   int iSrc, iDest;                 /* Cursors from source and destination */
15449d9cf229Sdrh   int addr1, addr2;                /* Loop addresses */
15459d9cf229Sdrh   int emptyDestTest;               /* Address of test for empty pDest */
15469d9cf229Sdrh   int emptySrcTest;                /* Address of test for empty pSrc */
15479d9cf229Sdrh   Vdbe *v;                         /* The VDBE we are building */
15489d9cf229Sdrh   KeyInfo *pKey;                   /* Key information for an index */
15496a288a33Sdrh   int regAutoinc;                  /* Memory register used by AUTOINC */
1550f33c9fadSdrh   int destHasUniqueIdx = 0;        /* True if pDest has a UNIQUE index */
1551b7654111Sdrh   int regData, regRowid;           /* Registers holding data and rowid */
15529d9cf229Sdrh 
15539d9cf229Sdrh   if( pSelect==0 ){
15549d9cf229Sdrh     return 0;   /* Must be of the form  INSERT INTO ... SELECT ... */
15559d9cf229Sdrh   }
15562f886d1dSdanielk1977   if( sqlite3TriggerList(pParse, pDest) ){
15579d9cf229Sdrh     return 0;   /* tab1 must not have triggers */
15589d9cf229Sdrh   }
15599d9cf229Sdrh #ifndef SQLITE_OMIT_VIRTUALTABLE
15607d10d5a6Sdrh   if( pDest->tabFlags & TF_Virtual ){
15619d9cf229Sdrh     return 0;   /* tab1 must not be a virtual table */
15629d9cf229Sdrh   }
15639d9cf229Sdrh #endif
15649d9cf229Sdrh   if( onError==OE_Default ){
15659d9cf229Sdrh     onError = OE_Abort;
15669d9cf229Sdrh   }
15679d9cf229Sdrh   if( onError!=OE_Abort && onError!=OE_Rollback ){
15689d9cf229Sdrh     return 0;   /* Cannot do OR REPLACE or OR IGNORE or OR FAIL */
15699d9cf229Sdrh   }
15705ce240a6Sdanielk1977   assert(pSelect->pSrc);   /* allocated even if there is no FROM clause */
15719d9cf229Sdrh   if( pSelect->pSrc->nSrc!=1 ){
15729d9cf229Sdrh     return 0;   /* FROM clause must have exactly one term */
15739d9cf229Sdrh   }
15749d9cf229Sdrh   if( pSelect->pSrc->a[0].pSelect ){
15759d9cf229Sdrh     return 0;   /* FROM clause cannot contain a subquery */
15769d9cf229Sdrh   }
15779d9cf229Sdrh   if( pSelect->pWhere ){
15789d9cf229Sdrh     return 0;   /* SELECT may not have a WHERE clause */
15799d9cf229Sdrh   }
15809d9cf229Sdrh   if( pSelect->pOrderBy ){
15819d9cf229Sdrh     return 0;   /* SELECT may not have an ORDER BY clause */
15829d9cf229Sdrh   }
15838103b7d2Sdrh   /* Do not need to test for a HAVING clause.  If HAVING is present but
15848103b7d2Sdrh   ** there is no ORDER BY, we will get an error. */
15859d9cf229Sdrh   if( pSelect->pGroupBy ){
15869d9cf229Sdrh     return 0;   /* SELECT may not have a GROUP BY clause */
15879d9cf229Sdrh   }
15889d9cf229Sdrh   if( pSelect->pLimit ){
15899d9cf229Sdrh     return 0;   /* SELECT may not have a LIMIT clause */
15909d9cf229Sdrh   }
15918103b7d2Sdrh   assert( pSelect->pOffset==0 );  /* Must be so if pLimit==0 */
15929d9cf229Sdrh   if( pSelect->pPrior ){
15939d9cf229Sdrh     return 0;   /* SELECT may not be a compound query */
15949d9cf229Sdrh   }
15957d10d5a6Sdrh   if( pSelect->selFlags & SF_Distinct ){
15969d9cf229Sdrh     return 0;   /* SELECT may not be DISTINCT */
15979d9cf229Sdrh   }
15989d9cf229Sdrh   pEList = pSelect->pEList;
15999d9cf229Sdrh   assert( pEList!=0 );
16009d9cf229Sdrh   if( pEList->nExpr!=1 ){
16019d9cf229Sdrh     return 0;   /* The result set must have exactly one column */
16029d9cf229Sdrh   }
16039d9cf229Sdrh   assert( pEList->a[0].pExpr );
16049d9cf229Sdrh   if( pEList->a[0].pExpr->op!=TK_ALL ){
16059d9cf229Sdrh     return 0;   /* The result set must be the special operator "*" */
16069d9cf229Sdrh   }
16079d9cf229Sdrh 
16089d9cf229Sdrh   /* At this point we have established that the statement is of the
16099d9cf229Sdrh   ** correct syntactic form to participate in this optimization.  Now
16109d9cf229Sdrh   ** we have to check the semantics.
16119d9cf229Sdrh   */
16129d9cf229Sdrh   pItem = pSelect->pSrc->a;
1613ca424114Sdrh   pSrc = sqlite3LocateTable(pParse, 0, pItem->zName, pItem->zDatabase);
16149d9cf229Sdrh   if( pSrc==0 ){
16159d9cf229Sdrh     return 0;   /* FROM clause does not contain a real table */
16169d9cf229Sdrh   }
16179d9cf229Sdrh   if( pSrc==pDest ){
16189d9cf229Sdrh     return 0;   /* tab1 and tab2 may not be the same table */
16199d9cf229Sdrh   }
16209d9cf229Sdrh #ifndef SQLITE_OMIT_VIRTUALTABLE
16217d10d5a6Sdrh   if( pSrc->tabFlags & TF_Virtual ){
16229d9cf229Sdrh     return 0;   /* tab2 must not be a virtual table */
16239d9cf229Sdrh   }
16249d9cf229Sdrh #endif
16259d9cf229Sdrh   if( pSrc->pSelect ){
16269d9cf229Sdrh     return 0;   /* tab2 may not be a view */
16279d9cf229Sdrh   }
16289d9cf229Sdrh   if( pDest->nCol!=pSrc->nCol ){
16299d9cf229Sdrh     return 0;   /* Number of columns must be the same in tab1 and tab2 */
16309d9cf229Sdrh   }
16319d9cf229Sdrh   if( pDest->iPKey!=pSrc->iPKey ){
16329d9cf229Sdrh     return 0;   /* Both tables must have the same INTEGER PRIMARY KEY */
16339d9cf229Sdrh   }
16349d9cf229Sdrh   for(i=0; i<pDest->nCol; i++){
16359d9cf229Sdrh     if( pDest->aCol[i].affinity!=pSrc->aCol[i].affinity ){
16369d9cf229Sdrh       return 0;    /* Affinity must be the same on all columns */
16379d9cf229Sdrh     }
16389d9cf229Sdrh     if( !xferCompatibleCollation(pDest->aCol[i].zColl, pSrc->aCol[i].zColl) ){
16399d9cf229Sdrh       return 0;    /* Collating sequence must be the same on all columns */
16409d9cf229Sdrh     }
16419d9cf229Sdrh     if( pDest->aCol[i].notNull && !pSrc->aCol[i].notNull ){
16429d9cf229Sdrh       return 0;    /* tab2 must be NOT NULL if tab1 is */
16439d9cf229Sdrh     }
16449d9cf229Sdrh   }
16459d9cf229Sdrh   for(pDestIdx=pDest->pIndex; pDestIdx; pDestIdx=pDestIdx->pNext){
1646f33c9fadSdrh     if( pDestIdx->onError!=OE_None ){
1647f33c9fadSdrh       destHasUniqueIdx = 1;
1648f33c9fadSdrh     }
16499d9cf229Sdrh     for(pSrcIdx=pSrc->pIndex; pSrcIdx; pSrcIdx=pSrcIdx->pNext){
16509d9cf229Sdrh       if( xferCompatibleIndex(pDestIdx, pSrcIdx) ) break;
16519d9cf229Sdrh     }
16529d9cf229Sdrh     if( pSrcIdx==0 ){
16539d9cf229Sdrh       return 0;    /* pDestIdx has no corresponding index in pSrc */
16549d9cf229Sdrh     }
16559d9cf229Sdrh   }
16567fc2f41bSdrh #ifndef SQLITE_OMIT_CHECK
1657fb658dedSdrh   if( pDest->pCheck && !sqlite3ExprCompare(pSrc->pCheck, pDest->pCheck) ){
16588103b7d2Sdrh     return 0;   /* Tables have different CHECK constraints.  Ticket #2252 */
16598103b7d2Sdrh   }
16607fc2f41bSdrh #endif
16619d9cf229Sdrh 
16629d9cf229Sdrh   /* If we get this far, it means either:
16639d9cf229Sdrh   **
16649d9cf229Sdrh   **    *   We can always do the transfer if the table contains an
16659d9cf229Sdrh   **        an integer primary key
16669d9cf229Sdrh   **
16679d9cf229Sdrh   **    *   We can conditionally do the transfer if the destination
16689d9cf229Sdrh   **        table is empty.
16699d9cf229Sdrh   */
1670dd73521bSdrh #ifdef SQLITE_TEST
1671dd73521bSdrh   sqlite3_xferopt_count++;
1672dd73521bSdrh #endif
16739d9cf229Sdrh   iDbSrc = sqlite3SchemaToIndex(pParse->db, pSrc->pSchema);
16749d9cf229Sdrh   v = sqlite3GetVdbe(pParse);
1675f53e9b5aSdrh   sqlite3CodeVerifySchema(pParse, iDbSrc);
16769d9cf229Sdrh   iSrc = pParse->nTab++;
16779d9cf229Sdrh   iDest = pParse->nTab++;
16786a288a33Sdrh   regAutoinc = autoIncBegin(pParse, iDbDest, pDest);
16799d9cf229Sdrh   sqlite3OpenTable(pParse, iDest, iDbDest, pDest, OP_OpenWrite);
1680f33c9fadSdrh   if( (pDest->iPKey<0 && pDest->pIndex!=0) || destHasUniqueIdx ){
1681bd36ba69Sdrh     /* If tables do not have an INTEGER PRIMARY KEY and there
1682bd36ba69Sdrh     ** are indices to be copied and the destination is not empty,
1683bd36ba69Sdrh     ** we have to disallow the transfer optimization because the
1684bd36ba69Sdrh     ** the rowids might change which will mess up indexing.
1685f33c9fadSdrh     **
1686f33c9fadSdrh     ** Or if the destination has a UNIQUE index and is not empty,
1687f33c9fadSdrh     ** we also disallow the transfer optimization because we cannot
1688f33c9fadSdrh     ** insure that all entries in the union of DEST and SRC will be
1689f33c9fadSdrh     ** unique.
16909d9cf229Sdrh     */
169166a5167bSdrh     addr1 = sqlite3VdbeAddOp2(v, OP_Rewind, iDest, 0);
169266a5167bSdrh     emptyDestTest = sqlite3VdbeAddOp2(v, OP_Goto, 0, 0);
16939d9cf229Sdrh     sqlite3VdbeJumpHere(v, addr1);
16949d9cf229Sdrh   }else{
16959d9cf229Sdrh     emptyDestTest = 0;
16969d9cf229Sdrh   }
16979d9cf229Sdrh   sqlite3OpenTable(pParse, iSrc, iDbSrc, pSrc, OP_OpenRead);
169866a5167bSdrh   emptySrcTest = sqlite3VdbeAddOp2(v, OP_Rewind, iSrc, 0);
1699b7654111Sdrh   regData = sqlite3GetTempReg(pParse);
1700b7654111Sdrh   regRowid = sqlite3GetTempReg(pParse);
170142242dedSdrh   if( pDest->iPKey>=0 ){
1702b7654111Sdrh     addr1 = sqlite3VdbeAddOp2(v, OP_Rowid, iSrc, regRowid);
1703b7654111Sdrh     addr2 = sqlite3VdbeAddOp3(v, OP_NotExists, iDest, 0, regRowid);
170466a5167bSdrh     sqlite3VdbeAddOp4(v, OP_Halt, SQLITE_CONSTRAINT, onError, 0,
170566a5167bSdrh                       "PRIMARY KEY must be unique", P4_STATIC);
17069d9cf229Sdrh     sqlite3VdbeJumpHere(v, addr2);
1707b7654111Sdrh     autoIncStep(pParse, regAutoinc, regRowid);
1708bd36ba69Sdrh   }else if( pDest->pIndex==0 ){
1709b7654111Sdrh     addr1 = sqlite3VdbeAddOp2(v, OP_NewRowid, iDest, regRowid);
171095bad4c7Sdrh   }else{
1711b7654111Sdrh     addr1 = sqlite3VdbeAddOp2(v, OP_Rowid, iSrc, regRowid);
17127d10d5a6Sdrh     assert( (pDest->tabFlags & TF_Autoincrement)==0 );
171395bad4c7Sdrh   }
1714b7654111Sdrh   sqlite3VdbeAddOp2(v, OP_RowData, iSrc, regData);
1715b7654111Sdrh   sqlite3VdbeAddOp3(v, OP_Insert, iDest, regData, regRowid);
1716b7654111Sdrh   sqlite3VdbeChangeP5(v, OPFLAG_NCHANGE|OPFLAG_LASTROWID|OPFLAG_APPEND);
17171f4aa337Sdanielk1977   sqlite3VdbeChangeP4(v, -1, pDest->zName, 0);
171866a5167bSdrh   sqlite3VdbeAddOp2(v, OP_Next, iSrc, addr1);
17196a288a33Sdrh   autoIncEnd(pParse, iDbDest, pDest, regAutoinc);
17209d9cf229Sdrh   for(pDestIdx=pDest->pIndex; pDestIdx; pDestIdx=pDestIdx->pNext){
17219d9cf229Sdrh     for(pSrcIdx=pSrc->pIndex; pSrcIdx; pSrcIdx=pSrcIdx->pNext){
17229d9cf229Sdrh       if( xferCompatibleIndex(pDestIdx, pSrcIdx) ) break;
17239d9cf229Sdrh     }
17249d9cf229Sdrh     assert( pSrcIdx );
172566a5167bSdrh     sqlite3VdbeAddOp2(v, OP_Close, iSrc, 0);
172666a5167bSdrh     sqlite3VdbeAddOp2(v, OP_Close, iDest, 0);
17279d9cf229Sdrh     pKey = sqlite3IndexKeyinfo(pParse, pSrcIdx);
1728207872a4Sdanielk1977     sqlite3VdbeAddOp4(v, OP_OpenRead, iSrc, pSrcIdx->tnum, iDbSrc,
1729207872a4Sdanielk1977                       (char*)pKey, P4_KEYINFO_HANDOFF);
1730d4e70ebdSdrh     VdbeComment((v, "%s", pSrcIdx->zName));
17319d9cf229Sdrh     pKey = sqlite3IndexKeyinfo(pParse, pDestIdx);
1732207872a4Sdanielk1977     sqlite3VdbeAddOp4(v, OP_OpenWrite, iDest, pDestIdx->tnum, iDbDest,
173366a5167bSdrh                       (char*)pKey, P4_KEYINFO_HANDOFF);
1734207872a4Sdanielk1977     VdbeComment((v, "%s", pDestIdx->zName));
173566a5167bSdrh     addr1 = sqlite3VdbeAddOp2(v, OP_Rewind, iSrc, 0);
1736b7654111Sdrh     sqlite3VdbeAddOp2(v, OP_RowKey, iSrc, regData);
1737b7654111Sdrh     sqlite3VdbeAddOp3(v, OP_IdxInsert, iDest, regData, 1);
173866a5167bSdrh     sqlite3VdbeAddOp2(v, OP_Next, iSrc, addr1+1);
17399d9cf229Sdrh     sqlite3VdbeJumpHere(v, addr1);
17409d9cf229Sdrh   }
17419d9cf229Sdrh   sqlite3VdbeJumpHere(v, emptySrcTest);
1742b7654111Sdrh   sqlite3ReleaseTempReg(pParse, regRowid);
1743b7654111Sdrh   sqlite3ReleaseTempReg(pParse, regData);
174466a5167bSdrh   sqlite3VdbeAddOp2(v, OP_Close, iSrc, 0);
174566a5167bSdrh   sqlite3VdbeAddOp2(v, OP_Close, iDest, 0);
17469d9cf229Sdrh   if( emptyDestTest ){
174766a5167bSdrh     sqlite3VdbeAddOp2(v, OP_Halt, SQLITE_OK, 0);
17489d9cf229Sdrh     sqlite3VdbeJumpHere(v, emptyDestTest);
174966a5167bSdrh     sqlite3VdbeAddOp2(v, OP_Close, iDest, 0);
17509d9cf229Sdrh     return 0;
17519d9cf229Sdrh   }else{
17529d9cf229Sdrh     return 1;
17539d9cf229Sdrh   }
17549d9cf229Sdrh }
17559d9cf229Sdrh #endif /* SQLITE_OMIT_XFER_OPT */
1756f39d9588Sdrh 
1757f39d9588Sdrh /* Make sure "isView" gets undefined in case this file becomes part of
1758f39d9588Sdrh ** the amalgamation - so that subsequent files do not see isView as a
1759f39d9588Sdrh ** macro. */
1760f39d9588Sdrh #undef isView
1761