xref: /sqlite-3.40.0/src/insert.c (revision c6b52df3)
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*c6b52df3Sdrh ** $Id: insert.c,v 1.31 2002/01/04 03:09:30 drh Exp $
16cce7d176Sdrh */
17cce7d176Sdrh #include "sqliteInt.h"
18cce7d176Sdrh 
19cce7d176Sdrh /*
201ccde15dSdrh ** This routine is call to handle SQL of the following forms:
21cce7d176Sdrh **
22cce7d176Sdrh **    insert into TABLE (IDLIST) values(EXPRLIST)
231ccde15dSdrh **    insert into TABLE (IDLIST) select
24cce7d176Sdrh **
251ccde15dSdrh ** The IDLIST following the table name is always optional.  If omitted,
261ccde15dSdrh ** then a list of all columns for the table is substituted.  The IDLIST
27967e8b73Sdrh ** appears in the pColumn parameter.  pColumn is NULL if IDLIST is omitted.
281ccde15dSdrh **
291ccde15dSdrh ** The pList parameter holds EXPRLIST in the first form of the INSERT
301ccde15dSdrh ** statement above, and pSelect is NULL.  For the second form, pList is
311ccde15dSdrh ** NULL and pSelect is a pointer to the select statement used to generate
321ccde15dSdrh ** data for the insert.
33cce7d176Sdrh */
34cce7d176Sdrh void sqliteInsert(
35cce7d176Sdrh   Parse *pParse,        /* Parser context */
36cce7d176Sdrh   Token *pTableName,    /* Name of table into which we are inserting */
37cce7d176Sdrh   ExprList *pList,      /* List of values to be inserted */
385974a30fSdrh   Select *pSelect,      /* A SELECT statement to use as the data source */
39967e8b73Sdrh   IdList *pColumn       /* Column names corresponding to IDLIST. */
40cce7d176Sdrh ){
415974a30fSdrh   Table *pTab;          /* The table to insert into */
425974a30fSdrh   char *zTab;           /* Name of the table into which we are inserting */
435974a30fSdrh   int i, j, idx;        /* Loop counters */
445974a30fSdrh   Vdbe *v;              /* Generate code into this virtual machine */
455974a30fSdrh   Index *pIdx;          /* For looping over indices of the table */
465974a30fSdrh   int srcTab;           /* Date comes from this temporary cursor if >=0 */
47967e8b73Sdrh   int nColumn;          /* Number of columns in the data */
485974a30fSdrh   int base;             /* First available cursor */
495974a30fSdrh   int iCont, iBreak;    /* Beginning and end of the loop over srcTab */
50ecdc7530Sdrh   sqlite *db;           /* The main database structure */
51f57b3399Sdrh   int openOp;           /* Opcode used to open cursors */
524a32431cSdrh   int keyColumn = -1;   /* Column that is the INTEGER PRIMARY KEY */
53cce7d176Sdrh 
54daffd0e5Sdrh   if( pParse->nErr || sqlite_malloc_failed ) goto insert_cleanup;
55ecdc7530Sdrh   db = pParse->db;
56daffd0e5Sdrh 
571ccde15dSdrh   /* Locate the table into which we will be inserting new information.
581ccde15dSdrh   */
59cce7d176Sdrh   zTab = sqliteTableNameFromToken(pTableName);
60daffd0e5Sdrh   if( zTab==0 ) goto insert_cleanup;
61ecdc7530Sdrh   pTab = sqliteFindTable(db, zTab);
62cce7d176Sdrh   sqliteFree(zTab);
63cce7d176Sdrh   if( pTab==0 ){
64cce7d176Sdrh     sqliteSetNString(&pParse->zErrMsg, "no such table: ", 0,
65cce7d176Sdrh         pTableName->z, pTableName->n, 0);
66cce7d176Sdrh     pParse->nErr++;
67cce7d176Sdrh     goto insert_cleanup;
68cce7d176Sdrh   }
69cce7d176Sdrh   if( pTab->readOnly ){
70cce7d176Sdrh     sqliteSetString(&pParse->zErrMsg, "table ", pTab->zName,
71cce7d176Sdrh         " may not be modified", 0);
72cce7d176Sdrh     pParse->nErr++;
73cce7d176Sdrh     goto insert_cleanup;
74cce7d176Sdrh   }
751ccde15dSdrh 
761ccde15dSdrh   /* Allocate a VDBE
771ccde15dSdrh   */
78d8bc7086Sdrh   v = sqliteGetVdbe(pParse);
795974a30fSdrh   if( v==0 ) goto insert_cleanup;
80ecdc7530Sdrh   if( (db->flags & SQLITE_InTrans)==0 ){
8199fcd718Sdrh     sqliteVdbeAddOp(v, OP_Transaction, 0, 0);
8299fcd718Sdrh     sqliteVdbeAddOp(v, OP_VerifyCookie, db->schema_cookie, 0);
83ecdc7530Sdrh     pParse->schemaVerified = 1;
845e00f6c7Sdrh   }
851ccde15dSdrh 
861ccde15dSdrh   /* Figure out how many columns of data are supplied.  If the data
87*c6b52df3Sdrh   ** is coming from a SELECT statement, then this step has to generate
881ccde15dSdrh   ** all the code to implement the SELECT statement and leave the data
891ccde15dSdrh   ** in a temporary table.  If data is coming from an expression list,
901ccde15dSdrh   ** then we just have to count the number of expressions.
911ccde15dSdrh   */
925974a30fSdrh   if( pSelect ){
935974a30fSdrh     int rc;
945974a30fSdrh     srcTab = pParse->nTab++;
9599fcd718Sdrh     sqliteVdbeAddOp(v, OP_OpenTemp, srcTab, 0);
965974a30fSdrh     rc = sqliteSelect(pParse, pSelect, SRT_Table, srcTab);
97daffd0e5Sdrh     if( rc || pParse->nErr || sqlite_malloc_failed ) goto insert_cleanup;
985974a30fSdrh     assert( pSelect->pEList );
99967e8b73Sdrh     nColumn = pSelect->pEList->nExpr;
1005974a30fSdrh   }else{
101daffd0e5Sdrh     assert( pList!=0 );
1025974a30fSdrh     srcTab = -1;
1035974a30fSdrh     assert( pList );
104967e8b73Sdrh     nColumn = pList->nExpr;
1055974a30fSdrh   }
1061ccde15dSdrh 
1071ccde15dSdrh   /* Make sure the number of columns in the source data matches the number
1081ccde15dSdrh   ** of columns to be inserted into the table.
1091ccde15dSdrh   */
110967e8b73Sdrh   if( pColumn==0 && nColumn!=pTab->nCol ){
111cce7d176Sdrh     char zNum1[30];
112cce7d176Sdrh     char zNum2[30];
113967e8b73Sdrh     sprintf(zNum1,"%d", nColumn);
114cce7d176Sdrh     sprintf(zNum2,"%d", pTab->nCol);
115cce7d176Sdrh     sqliteSetString(&pParse->zErrMsg, "table ", pTab->zName,
116cce7d176Sdrh        " has ", zNum2, " columns but ",
117cce7d176Sdrh        zNum1, " values were supplied", 0);
118cce7d176Sdrh     pParse->nErr++;
119cce7d176Sdrh     goto insert_cleanup;
120cce7d176Sdrh   }
121967e8b73Sdrh   if( pColumn!=0 && nColumn!=pColumn->nId ){
122cce7d176Sdrh     char zNum1[30];
123cce7d176Sdrh     char zNum2[30];
124967e8b73Sdrh     sprintf(zNum1,"%d", nColumn);
125967e8b73Sdrh     sprintf(zNum2,"%d", pColumn->nId);
126cce7d176Sdrh     sqliteSetString(&pParse->zErrMsg, zNum1, " values for ",
127cce7d176Sdrh        zNum2, " columns", 0);
128cce7d176Sdrh     pParse->nErr++;
129cce7d176Sdrh     goto insert_cleanup;
130cce7d176Sdrh   }
1311ccde15dSdrh 
1321ccde15dSdrh   /* If the INSERT statement included an IDLIST term, then make sure
1331ccde15dSdrh   ** all elements of the IDLIST really are columns of the table and
1341ccde15dSdrh   ** remember the column indices.
135c8392586Sdrh   **
136c8392586Sdrh   ** If the table has an INTEGER PRIMARY KEY column and that column
137c8392586Sdrh   ** is named in the IDLIST, then record in the keyColumn variable
138c8392586Sdrh   ** the index into IDLIST of the primary key column.  keyColumn is
139c8392586Sdrh   ** the index of the primary key as it appears in IDLIST, not as
140c8392586Sdrh   ** is appears in the original table.  (The index of the primary
141c8392586Sdrh   ** key in the original table is pTab->iPKey.)
1421ccde15dSdrh   */
143967e8b73Sdrh   if( pColumn ){
144967e8b73Sdrh     for(i=0; i<pColumn->nId; i++){
145967e8b73Sdrh       pColumn->a[i].idx = -1;
146cce7d176Sdrh     }
147967e8b73Sdrh     for(i=0; i<pColumn->nId; i++){
148cce7d176Sdrh       for(j=0; j<pTab->nCol; j++){
149967e8b73Sdrh         if( sqliteStrICmp(pColumn->a[i].zName, pTab->aCol[j].zName)==0 ){
150967e8b73Sdrh           pColumn->a[i].idx = j;
1514a32431cSdrh           if( j==pTab->iPKey ){
1529aa028daSdrh             keyColumn = i;
1534a32431cSdrh           }
154cce7d176Sdrh           break;
155cce7d176Sdrh         }
156cce7d176Sdrh       }
157cce7d176Sdrh       if( j>=pTab->nCol ){
158cce7d176Sdrh         sqliteSetString(&pParse->zErrMsg, "table ", pTab->zName,
159967e8b73Sdrh            " has no column named ", pColumn->a[i].zName, 0);
160cce7d176Sdrh         pParse->nErr++;
161cce7d176Sdrh         goto insert_cleanup;
162cce7d176Sdrh       }
163cce7d176Sdrh     }
164cce7d176Sdrh   }
1651ccde15dSdrh 
1664a32431cSdrh   /* If there is not IDLIST term but the table has an integer primary
167c8392586Sdrh   ** key, the set the keyColumn variable to the primary key column index
168c8392586Sdrh   ** in the original table definition.
1694a32431cSdrh   */
1704a32431cSdrh   if( pColumn==0 ){
1714a32431cSdrh     keyColumn = pTab->iPKey;
1724a32431cSdrh   }
1734a32431cSdrh 
1741ccde15dSdrh   /* Open cursors into the table that is received the new data and
1751ccde15dSdrh   ** all indices of that table.
1761ccde15dSdrh   */
1775974a30fSdrh   base = pParse->nTab;
178f57b3399Sdrh   openOp = pTab->isTemp ? OP_OpenWrAux : OP_OpenWrite;
17999fcd718Sdrh   sqliteVdbeAddOp(v, openOp, base, pTab->tnum);
18099fcd718Sdrh   sqliteVdbeChangeP3(v, -1, pTab->zName, P3_STATIC);
181bed8690fSdrh   for(idx=1, pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext, idx++){
18299fcd718Sdrh     sqliteVdbeAddOp(v, openOp, idx+base, pIdx->tnum);
18399fcd718Sdrh     sqliteVdbeChangeP3(v, -1, pIdx->zName, P3_STATIC);
1845974a30fSdrh   }
1851ccde15dSdrh 
1861ccde15dSdrh   /* If the data source is a SELECT statement, then we have to create
1871ccde15dSdrh   ** a loop because there might be multiple rows of data.  If the data
1881ccde15dSdrh   ** source is an expression list, then exactly one row will be inserted
1891ccde15dSdrh   ** and the loop is not used.
1901ccde15dSdrh   */
1915974a30fSdrh   if( srcTab>=0 ){
1921bee3d7bSdrh     if( db->flags & SQLITE_CountRows ){
1931bee3d7bSdrh       sqliteVdbeAddOp(v, OP_Integer, 0, 0);  /* Initialize the row count */
1941bee3d7bSdrh     }
1955974a30fSdrh     iBreak = sqliteVdbeMakeLabel(v);
1966b56344dSdrh     sqliteVdbeAddOp(v, OP_Rewind, srcTab, iBreak);
1976b56344dSdrh     iCont = sqliteVdbeCurrentAddr(v);
198bed8690fSdrh   }
1991ccde15dSdrh 
2004a32431cSdrh   /* Push the record number for the new entry onto the stack.  The
2014a32431cSdrh   ** record number is a randomly generate integer created by NewRecno
2024a32431cSdrh   ** except when the table has an INTEGER PRIMARY KEY column, in which
2034a32431cSdrh   ** case the record number is the same as that column.
2041ccde15dSdrh   */
2054a32431cSdrh   if( keyColumn>=0 ){
2064a32431cSdrh     if( srcTab>=0 ){
2074a32431cSdrh       sqliteVdbeAddOp(v, OP_Column, srcTab, keyColumn);
2084a32431cSdrh     }else{
2094a32431cSdrh       sqliteExprCode(pParse, pList->a[keyColumn].pExpr);
2104a32431cSdrh     }
2118aff1015Sdrh     sqliteVdbeAddOp(v, OP_MustBeInt, 0, 0);
2124a32431cSdrh   }else{
21399fcd718Sdrh     sqliteVdbeAddOp(v, OP_NewRecno, base, 0);
2144a32431cSdrh   }
2154a32431cSdrh 
216c8392586Sdrh   /* If there are indices, we'll need the new record number again, so make
2174a32431cSdrh   ** a copy.
2184a32431cSdrh   */
219cce7d176Sdrh   if( pTab->pIndex ){
22099fcd718Sdrh     sqliteVdbeAddOp(v, OP_Dup, 0, 0);
221cce7d176Sdrh   }
2224a32431cSdrh 
2234a32431cSdrh   /* Push onto the stack data for all columns of the new entry, beginning
2244a32431cSdrh   ** with the first column.
2254a32431cSdrh   */
226cce7d176Sdrh   for(i=0; i<pTab->nCol; i++){
2274a32431cSdrh     if( i==pTab->iPKey ){
2284a32431cSdrh       /* The value of the INTEGER PRIMARY KEY column is always a NULL.
2294a32431cSdrh       ** Whenever this column is used, the record number will be substituted
230c8392586Sdrh       ** in its place, so there is no point in it taking up space in
2314a32431cSdrh       ** the data record. */
2324a32431cSdrh       sqliteVdbeAddOp(v, OP_String, 0, 0);
2334a32431cSdrh       continue;
2344a32431cSdrh     }
235967e8b73Sdrh     if( pColumn==0 ){
236cce7d176Sdrh       j = i;
237cce7d176Sdrh     }else{
238967e8b73Sdrh       for(j=0; j<pColumn->nId; j++){
239967e8b73Sdrh         if( pColumn->a[j].idx==i ) break;
240cce7d176Sdrh       }
241cce7d176Sdrh     }
242967e8b73Sdrh     if( pColumn && j>=pColumn->nId ){
24399fcd718Sdrh       sqliteVdbeAddOp(v, OP_String, 0, 0);
24499fcd718Sdrh       sqliteVdbeChangeP3(v, -1, pTab->aCol[i].zDflt, P3_STATIC);
2455974a30fSdrh     }else if( srcTab>=0 ){
24699fcd718Sdrh       sqliteVdbeAddOp(v, OP_Column, srcTab, i);
247cce7d176Sdrh     }else{
248cce7d176Sdrh       sqliteExprCode(pParse, pList->a[j].pExpr);
249cce7d176Sdrh     }
250cce7d176Sdrh   }
2511ccde15dSdrh 
2524a32431cSdrh   /* Create the new record and put it into the database.
2534a32431cSdrh   */
2544a32431cSdrh   sqliteVdbeAddOp(v, OP_MakeRecord, pTab->nCol, 0);
2554a32431cSdrh   sqliteVdbeAddOp(v, OP_Put, base, keyColumn>=0);
2561bee3d7bSdrh 
2571ccde15dSdrh   /* Create appropriate entries for the new data row in all indices
2581ccde15dSdrh   ** of the table.
2591ccde15dSdrh   */
260bed8690fSdrh   for(idx=1, pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext, idx++){
261cce7d176Sdrh     if( pIdx->pNext ){
26299fcd718Sdrh       sqliteVdbeAddOp(v, OP_Dup, 0, 0);
263cce7d176Sdrh     }
264967e8b73Sdrh     for(i=0; i<pIdx->nColumn; i++){
265967e8b73Sdrh       int idx = pIdx->aiColumn[i];
2664a32431cSdrh       if( idx==pTab->iPKey ){
2674a32431cSdrh         /* Copy the record number in place of the INTEGER PRIMARY KEY column */
2684a32431cSdrh         sqliteVdbeAddOp(v, OP_Dup, i, 0);
2694a32431cSdrh         continue;
2704a32431cSdrh       }
271967e8b73Sdrh       if( pColumn==0 ){
272cce7d176Sdrh         j = idx;
273cce7d176Sdrh       }else{
274967e8b73Sdrh         for(j=0; j<pColumn->nId; j++){
275967e8b73Sdrh           if( pColumn->a[j].idx==idx ) break;
276cce7d176Sdrh         }
277cce7d176Sdrh       }
278967e8b73Sdrh       if( pColumn && j>=pColumn->nId ){
27999fcd718Sdrh         sqliteVdbeAddOp(v, OP_String, 0, 0);
28099fcd718Sdrh         sqliteVdbeChangeP3(v, -1, pTab->aCol[idx].zDflt, P3_STATIC);
2815974a30fSdrh       }else if( srcTab>=0 ){
28299fcd718Sdrh         sqliteVdbeAddOp(v, OP_Column, srcTab, idx);
283cce7d176Sdrh       }else{
284cce7d176Sdrh         sqliteExprCode(pParse, pList->a[j].pExpr);
285cce7d176Sdrh       }
286cce7d176Sdrh     }
28799fcd718Sdrh     sqliteVdbeAddOp(v, OP_MakeIdxKey, pIdx->nColumn, 0);
2888721ce4aSdrh     sqliteVdbeAddOp(v, OP_IdxPut, idx+base, pIdx->isUnique);
289cce7d176Sdrh   }
2901ccde15dSdrh 
2911bee3d7bSdrh 
2921bee3d7bSdrh   /* If inserting from a SELECT, keep a count of the number of
2931bee3d7bSdrh   ** rows inserted.
2941bee3d7bSdrh   */
2951bee3d7bSdrh   if( srcTab>=0 && (db->flags & SQLITE_CountRows)!=0 ){
2961bee3d7bSdrh     sqliteVdbeAddOp(v, OP_AddImm, 1, 0);
2971bee3d7bSdrh   }
2981bee3d7bSdrh 
2991ccde15dSdrh   /* The bottom of the loop, if the data source is a SELECT statement
3001ccde15dSdrh   */
3015974a30fSdrh   if( srcTab>=0 ){
3026b56344dSdrh     sqliteVdbeAddOp(v, OP_Next, srcTab, iCont);
30399fcd718Sdrh     sqliteVdbeResolveLabel(v, iBreak);
3046b56344dSdrh     sqliteVdbeAddOp(v, OP_Close, srcTab, 0);
3056b56344dSdrh   }
3066b56344dSdrh   sqliteVdbeAddOp(v, OP_Close, base, 0);
3076b56344dSdrh   for(idx=1, pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext, idx++){
3086b56344dSdrh     sqliteVdbeAddOp(v, OP_Close, idx+base, 0);
309cce7d176Sdrh   }
310ecdc7530Sdrh   if( (db->flags & SQLITE_InTrans)==0 ){
31199fcd718Sdrh     sqliteVdbeAddOp(v, OP_Commit, 0, 0);
3125e00f6c7Sdrh   }
3135e00f6c7Sdrh 
3141bee3d7bSdrh   /*
3151bee3d7bSdrh   ** Return the number of rows inserted.
3161bee3d7bSdrh   */
3171bee3d7bSdrh   if( db->flags & SQLITE_CountRows ){
3181bee3d7bSdrh     sqliteVdbeAddOp(v, OP_ColumnCount, 1, 0);
3191bee3d7bSdrh     sqliteVdbeAddOp(v, OP_ColumnName, 0, 0);
3201bee3d7bSdrh     sqliteVdbeChangeP3(v, -1, "rows inserted", P3_STATIC);
3211bee3d7bSdrh     if( srcTab<0 ){
3221bee3d7bSdrh       sqliteVdbeAddOp(v, OP_Integer, 1, 0);
3231bee3d7bSdrh     }
3241bee3d7bSdrh     sqliteVdbeAddOp(v, OP_Callback, 1, 0);
3251bee3d7bSdrh   }
326cce7d176Sdrh 
327cce7d176Sdrh insert_cleanup:
3285974a30fSdrh   if( pList ) sqliteExprListDelete(pList);
3295974a30fSdrh   if( pSelect ) sqliteSelectDelete(pSelect);
330967e8b73Sdrh   sqliteIdListDelete(pColumn);
331cce7d176Sdrh }
332