xref: /sqlite-3.40.0/src/alter.c (revision a408adc5)
1 /*
2 ** 2005 February 15
3 **
4 ** The author disclaims copyright to this source code.  In place of
5 ** a legal notice, here is a blessing:
6 **
7 **    May you do good and not evil.
8 **    May you find forgiveness for yourself and forgive others.
9 **    May you share freely, never taking more than you give.
10 **
11 *************************************************************************
12 ** This file contains C code routines that used to generate VDBE code
13 ** that implements the ALTER TABLE command.
14 **
15 ** $Id: alter.c,v 1.25 2007/05/15 14:34:32 drh Exp $
16 */
17 #include "sqliteInt.h"
18 #include <ctype.h>
19 
20 /*
21 ** The code in this file only exists if we are not omitting the
22 ** ALTER TABLE logic from the build.
23 */
24 #ifndef SQLITE_OMIT_ALTERTABLE
25 
26 
27 /*
28 ** This function is used by SQL generated to implement the
29 ** ALTER TABLE command. The first argument is the text of a CREATE TABLE or
30 ** CREATE INDEX command. The second is a table name. The table name in
31 ** the CREATE TABLE or CREATE INDEX statement is replaced with the third
32 ** argument and the result returned. Examples:
33 **
34 ** sqlite_rename_table('CREATE TABLE abc(a, b, c)', 'def')
35 **     -> 'CREATE TABLE def(a, b, c)'
36 **
37 ** sqlite_rename_table('CREATE INDEX i ON abc(a)', 'def')
38 **     -> 'CREATE INDEX i ON def(a, b, c)'
39 */
40 static void renameTableFunc(
41   sqlite3_context *context,
42   int argc,
43   sqlite3_value **argv
44 ){
45   unsigned char const *zSql = sqlite3_value_text(argv[0]);
46   unsigned char const *zTableName = sqlite3_value_text(argv[1]);
47 
48   int token;
49   Token tname;
50   unsigned char const *zCsr = zSql;
51   int len = 0;
52   char *zRet;
53 
54   /* The principle used to locate the table name in the CREATE TABLE
55   ** statement is that the table name is the first token that is immediatedly
56   ** followed by a left parenthesis - TK_LP.
57   */
58   if( zSql ){
59     do {
60       if( !*zCsr ){
61         /* Ran out of input before finding an opening bracket. Return NULL. */
62         return;
63       }
64 
65       /* Store the token that zCsr points to in tname. */
66       tname.z = zCsr;
67       tname.n = len;
68 
69       /* Advance zCsr to the next token. Store that token type in 'token',
70       ** and it's length in 'len' (to be used next iteration of this loop).
71       */
72       do {
73         zCsr += len;
74         len = sqlite3GetToken(zCsr, &token);
75       } while( token==TK_SPACE );
76       assert( len>0 );
77     } while( token!=TK_LP );
78 
79     zRet = sqlite3MPrintf("%.*s%Q%s", tname.z - zSql, zSql,
80        zTableName, tname.z+tname.n);
81     sqlite3_result_text(context, zRet, -1, sqlite3FreeX);
82   }
83 }
84 
85 #ifndef SQLITE_OMIT_TRIGGER
86 /* This function is used by SQL generated to implement the
87 ** ALTER TABLE command. The first argument is the text of a CREATE TRIGGER
88 ** statement. The second is a table name. The table name in the CREATE
89 ** TRIGGER statement is replaced with the third argument and the result
90 ** returned. This is analagous to renameTableFunc() above, except for CREATE
91 ** TRIGGER, not CREATE INDEX and CREATE TABLE.
92 */
93 static void renameTriggerFunc(
94   sqlite3_context *context,
95   int argc,
96   sqlite3_value **argv
97 ){
98   unsigned char const *zSql = sqlite3_value_text(argv[0]);
99   unsigned char const *zTableName = sqlite3_value_text(argv[1]);
100 
101   int token;
102   Token tname;
103   int dist = 3;
104   unsigned char const *zCsr = zSql;
105   int len = 0;
106   char *zRet;
107 
108   /* The principle used to locate the table name in the CREATE TRIGGER
109   ** statement is that the table name is the first token that is immediatedly
110   ** preceded by either TK_ON or TK_DOT and immediatedly followed by one
111   ** of TK_WHEN, TK_BEGIN or TK_FOR.
112   */
113   if( zSql ){
114     do {
115 
116       if( !*zCsr ){
117         /* Ran out of input before finding the table name. Return NULL. */
118         return;
119       }
120 
121       /* Store the token that zCsr points to in tname. */
122       tname.z = zCsr;
123       tname.n = len;
124 
125       /* Advance zCsr to the next token. Store that token type in 'token',
126       ** and it's length in 'len' (to be used next iteration of this loop).
127       */
128       do {
129         zCsr += len;
130         len = sqlite3GetToken(zCsr, &token);
131       }while( token==TK_SPACE );
132       assert( len>0 );
133 
134       /* Variable 'dist' stores the number of tokens read since the most
135       ** recent TK_DOT or TK_ON. This means that when a WHEN, FOR or BEGIN
136       ** token is read and 'dist' equals 2, the condition stated above
137       ** to be met.
138       **
139       ** Note that ON cannot be a database, table or column name, so
140       ** there is no need to worry about syntax like
141       ** "CREATE TRIGGER ... ON ON.ON BEGIN ..." etc.
142       */
143       dist++;
144       if( token==TK_DOT || token==TK_ON ){
145         dist = 0;
146       }
147     } while( dist!=2 || (token!=TK_WHEN && token!=TK_FOR && token!=TK_BEGIN) );
148 
149     /* Variable tname now contains the token that is the old table-name
150     ** in the CREATE TRIGGER statement.
151     */
152     zRet = sqlite3MPrintf("%.*s%Q%s", tname.z - zSql, zSql,
153        zTableName, tname.z+tname.n);
154     sqlite3_result_text(context, zRet, -1, sqlite3FreeX);
155   }
156 }
157 #endif   /* !SQLITE_OMIT_TRIGGER */
158 
159 /*
160 ** Register built-in functions used to help implement ALTER TABLE
161 */
162 void sqlite3AlterFunctions(sqlite3 *db){
163   static const struct {
164      char *zName;
165      signed char nArg;
166      void (*xFunc)(sqlite3_context*,int,sqlite3_value **);
167   } aFuncs[] = {
168     { "sqlite_rename_table",    2, renameTableFunc},
169 #ifndef SQLITE_OMIT_TRIGGER
170     { "sqlite_rename_trigger",  2, renameTriggerFunc},
171 #endif
172   };
173   int i;
174 
175   for(i=0; i<sizeof(aFuncs)/sizeof(aFuncs[0]); i++){
176     sqlite3CreateFunc(db, aFuncs[i].zName, aFuncs[i].nArg,
177         SQLITE_UTF8, 0, aFuncs[i].xFunc, 0, 0);
178   }
179 }
180 
181 /*
182 ** Generate the text of a WHERE expression which can be used to select all
183 ** temporary triggers on table pTab from the sqlite_temp_master table. If
184 ** table pTab has no temporary triggers, or is itself stored in the
185 ** temporary database, NULL is returned.
186 */
187 static char *whereTempTriggers(Parse *pParse, Table *pTab){
188   Trigger *pTrig;
189   char *zWhere = 0;
190   char *tmp = 0;
191   const Schema *pTempSchema = pParse->db->aDb[1].pSchema; /* Temp db schema */
192 
193   /* If the table is not located in the temp-db (in which case NULL is
194   ** returned, loop through the tables list of triggers. For each trigger
195   ** that is not part of the temp-db schema, add a clause to the WHERE
196   ** expression being built up in zWhere.
197   */
198   if( pTab->pSchema!=pTempSchema ){
199     for( pTrig=pTab->pTrigger; pTrig; pTrig=pTrig->pNext ){
200       if( pTrig->pSchema==pTempSchema ){
201         if( !zWhere ){
202           zWhere = sqlite3MPrintf("name=%Q", pTrig->name);
203         }else{
204           tmp = zWhere;
205           zWhere = sqlite3MPrintf("%s OR name=%Q", zWhere, pTrig->name);
206           sqliteFree(tmp);
207         }
208       }
209     }
210   }
211   return zWhere;
212 }
213 
214 /*
215 ** Generate code to drop and reload the internal representation of table
216 ** pTab from the database, including triggers and temporary triggers.
217 ** Argument zName is the name of the table in the database schema at
218 ** the time the generated code is executed. This can be different from
219 ** pTab->zName if this function is being called to code part of an
220 ** "ALTER TABLE RENAME TO" statement.
221 */
222 static void reloadTableSchema(Parse *pParse, Table *pTab, const char *zName){
223   Vdbe *v;
224   char *zWhere;
225   int iDb;                   /* Index of database containing pTab */
226 #ifndef SQLITE_OMIT_TRIGGER
227   Trigger *pTrig;
228 #endif
229 
230   v = sqlite3GetVdbe(pParse);
231   if( !v ) return;
232   iDb = sqlite3SchemaToIndex(pParse->db, pTab->pSchema);
233   assert( iDb>=0 );
234 
235 #ifndef SQLITE_OMIT_TRIGGER
236   /* Drop any table triggers from the internal schema. */
237   for(pTrig=pTab->pTrigger; pTrig; pTrig=pTrig->pNext){
238     int iTrigDb = sqlite3SchemaToIndex(pParse->db, pTrig->pSchema);
239     assert( iTrigDb==iDb || iTrigDb==1 );
240     sqlite3VdbeOp3(v, OP_DropTrigger, iTrigDb, 0, pTrig->name, 0);
241   }
242 #endif
243 
244   /* Drop the table and index from the internal schema */
245   sqlite3VdbeOp3(v, OP_DropTable, iDb, 0, pTab->zName, 0);
246 
247   /* Reload the table, index and permanent trigger schemas. */
248   zWhere = sqlite3MPrintf("tbl_name=%Q", zName);
249   if( !zWhere ) return;
250   sqlite3VdbeOp3(v, OP_ParseSchema, iDb, 0, zWhere, P3_DYNAMIC);
251 
252 #ifndef SQLITE_OMIT_TRIGGER
253   /* Now, if the table is not stored in the temp database, reload any temp
254   ** triggers. Don't use IN(...) in case SQLITE_OMIT_SUBQUERY is defined.
255   */
256   if( (zWhere=whereTempTriggers(pParse, pTab))!=0 ){
257     sqlite3VdbeOp3(v, OP_ParseSchema, 1, 0, zWhere, P3_DYNAMIC);
258   }
259 #endif
260 }
261 
262 /*
263 ** Generate code to implement the "ALTER TABLE xxx RENAME TO yyy"
264 ** command.
265 */
266 void sqlite3AlterRenameTable(
267   Parse *pParse,            /* Parser context. */
268   SrcList *pSrc,            /* The table to rename. */
269   Token *pName              /* The new table name. */
270 ){
271   int iDb;                  /* Database that contains the table */
272   char *zDb;                /* Name of database iDb */
273   Table *pTab;              /* Table being renamed */
274   char *zName = 0;          /* NULL-terminated version of pName */
275   sqlite3 *db = pParse->db; /* Database connection */
276   int nTabName;             /* Number of UTF-8 characters in zTabName */
277   const char *zTabName;     /* Original name of the table */
278   Vdbe *v;
279 #ifndef SQLITE_OMIT_TRIGGER
280   char *zWhere = 0;         /* Where clause to locate temp triggers */
281 #endif
282 
283   if( sqlite3MallocFailed() ) goto exit_rename_table;
284   assert( pSrc->nSrc==1 );
285 
286   pTab = sqlite3LocateTable(pParse, pSrc->a[0].zName, pSrc->a[0].zDatabase);
287   if( !pTab ) goto exit_rename_table;
288 #ifndef SQLITE_OMIT_VIRTUALTABLE
289   if( IsVirtual(pTab) ){
290     sqlite3ErrorMsg(pParse, "virtual tables may not be altered");
291     goto exit_rename_table;
292   }
293 #endif
294   iDb = sqlite3SchemaToIndex(pParse->db, pTab->pSchema);
295   zDb = db->aDb[iDb].zName;
296 
297   /* Get a NULL terminated version of the new table name. */
298   zName = sqlite3NameFromToken(pName);
299   if( !zName ) goto exit_rename_table;
300 
301   /* Check that a table or index named 'zName' does not already exist
302   ** in database iDb. If so, this is an error.
303   */
304   if( sqlite3FindTable(db, zName, zDb) || sqlite3FindIndex(db, zName, zDb) ){
305     sqlite3ErrorMsg(pParse,
306         "there is already another table or index with this name: %s", zName);
307     goto exit_rename_table;
308   }
309 
310   /* Make sure it is not a system table being altered, or a reserved name
311   ** that the table is being renamed to.
312   */
313   if( strlen(pTab->zName)>6 && 0==sqlite3StrNICmp(pTab->zName, "sqlite_", 7) ){
314     sqlite3ErrorMsg(pParse, "table %s may not be altered", pTab->zName);
315     goto exit_rename_table;
316   }
317   if( SQLITE_OK!=sqlite3CheckObjectName(pParse, zName) ){
318     goto exit_rename_table;
319   }
320 
321 #ifndef SQLITE_OMIT_AUTHORIZATION
322   /* Invoke the authorization callback. */
323   if( sqlite3AuthCheck(pParse, SQLITE_ALTER_TABLE, zDb, pTab->zName, 0) ){
324     goto exit_rename_table;
325   }
326 #endif
327 
328   /* Begin a transaction and code the VerifyCookie for database iDb.
329   ** Then modify the schema cookie (since the ALTER TABLE modifies the
330   ** schema).
331   */
332   v = sqlite3GetVdbe(pParse);
333   if( v==0 ){
334     goto exit_rename_table;
335   }
336   sqlite3BeginWriteOperation(pParse, 0, iDb);
337   sqlite3ChangeCookie(db, v, iDb);
338 
339   /* figure out how many UTF-8 characters are in zName */
340   zTabName = pTab->zName;
341   nTabName = sqlite3Utf8CharLen(zTabName, -1);
342 
343   /* Modify the sqlite_master table to use the new table name. */
344   sqlite3NestedParse(pParse,
345       "UPDATE %Q.%s SET "
346 #ifdef SQLITE_OMIT_TRIGGER
347           "sql = sqlite_rename_table(sql, %Q), "
348 #else
349           "sql = CASE "
350             "WHEN type = 'trigger' THEN sqlite_rename_trigger(sql, %Q)"
351             "ELSE sqlite_rename_table(sql, %Q) END, "
352 #endif
353           "tbl_name = %Q, "
354           "name = CASE "
355             "WHEN type='table' THEN %Q "
356             "WHEN name LIKE 'sqlite_autoindex%%' AND type='index' THEN "
357              "'sqlite_autoindex_' || %Q || substr(name,%d+18,10) "
358             "ELSE name END "
359       "WHERE tbl_name=%Q AND "
360           "(type='table' OR type='index' OR type='trigger');",
361       zDb, SCHEMA_TABLE(iDb), zName, zName, zName,
362 #ifndef SQLITE_OMIT_TRIGGER
363       zName,
364 #endif
365       zName, nTabName, zTabName
366   );
367 
368 #ifndef SQLITE_OMIT_AUTOINCREMENT
369   /* If the sqlite_sequence table exists in this database, then update
370   ** it with the new table name.
371   */
372   if( sqlite3FindTable(db, "sqlite_sequence", zDb) ){
373     sqlite3NestedParse(pParse,
374         "UPDATE %Q.sqlite_sequence set name = %Q WHERE name = %Q",
375         zDb, zName, pTab->zName);
376   }
377 #endif
378 
379 #ifndef SQLITE_OMIT_TRIGGER
380   /* If there are TEMP triggers on this table, modify the sqlite_temp_master
381   ** table. Don't do this if the table being ALTERed is itself located in
382   ** the temp database.
383   */
384   if( (zWhere=whereTempTriggers(pParse, pTab))!=0 ){
385     sqlite3NestedParse(pParse,
386         "UPDATE sqlite_temp_master SET "
387             "sql = sqlite_rename_trigger(sql, %Q), "
388             "tbl_name = %Q "
389             "WHERE %s;", zName, zName, zWhere);
390     sqliteFree(zWhere);
391   }
392 #endif
393 
394   /* Drop and reload the internal table schema. */
395   reloadTableSchema(pParse, pTab, zName);
396 
397 exit_rename_table:
398   sqlite3SrcListDelete(pSrc);
399   sqliteFree(zName);
400 }
401 
402 
403 /*
404 ** This function is called after an "ALTER TABLE ... ADD" statement
405 ** has been parsed. Argument pColDef contains the text of the new
406 ** column definition.
407 **
408 ** The Table structure pParse->pNewTable was extended to include
409 ** the new column during parsing.
410 */
411 void sqlite3AlterFinishAddColumn(Parse *pParse, Token *pColDef){
412   Table *pNew;              /* Copy of pParse->pNewTable */
413   Table *pTab;              /* Table being altered */
414   int iDb;                  /* Database number */
415   const char *zDb;          /* Database name */
416   const char *zTab;         /* Table name */
417   char *zCol;               /* Null-terminated column definition */
418   Column *pCol;             /* The new column */
419   Expr *pDflt;              /* Default value for the new column */
420 
421   if( pParse->nErr ) return;
422   pNew = pParse->pNewTable;
423   assert( pNew );
424 
425   iDb = sqlite3SchemaToIndex(pParse->db, pNew->pSchema);
426   zDb = pParse->db->aDb[iDb].zName;
427   zTab = pNew->zName;
428   pCol = &pNew->aCol[pNew->nCol-1];
429   pDflt = pCol->pDflt;
430   pTab = sqlite3FindTable(pParse->db, zTab, zDb);
431   assert( pTab );
432 
433 #ifndef SQLITE_OMIT_AUTHORIZATION
434   /* Invoke the authorization callback. */
435   if( sqlite3AuthCheck(pParse, SQLITE_ALTER_TABLE, zDb, pTab->zName, 0) ){
436     return;
437   }
438 #endif
439 
440   /* If the default value for the new column was specified with a
441   ** literal NULL, then set pDflt to 0. This simplifies checking
442   ** for an SQL NULL default below.
443   */
444   if( pDflt && pDflt->op==TK_NULL ){
445     pDflt = 0;
446   }
447 
448   /* Check that the new column is not specified as PRIMARY KEY or UNIQUE.
449   ** If there is a NOT NULL constraint, then the default value for the
450   ** column must not be NULL.
451   */
452   if( pCol->isPrimKey ){
453     sqlite3ErrorMsg(pParse, "Cannot add a PRIMARY KEY column");
454     return;
455   }
456   if( pNew->pIndex ){
457     sqlite3ErrorMsg(pParse, "Cannot add a UNIQUE column");
458     return;
459   }
460   if( pCol->notNull && !pDflt ){
461     sqlite3ErrorMsg(pParse,
462         "Cannot add a NOT NULL column with default value NULL");
463     return;
464   }
465 
466   /* Ensure the default expression is something that sqlite3ValueFromExpr()
467   ** can handle (i.e. not CURRENT_TIME etc.)
468   */
469   if( pDflt ){
470     sqlite3_value *pVal;
471     if( sqlite3ValueFromExpr(pDflt, SQLITE_UTF8, SQLITE_AFF_NONE, &pVal) ){
472       /* malloc() has failed */
473       return;
474     }
475     if( !pVal ){
476       sqlite3ErrorMsg(pParse, "Cannot add a column with non-constant default");
477       return;
478     }
479     sqlite3ValueFree(pVal);
480   }
481 
482   /* Modify the CREATE TABLE statement. */
483   zCol = sqliteStrNDup((char*)pColDef->z, pColDef->n);
484   if( zCol ){
485     char *zEnd = &zCol[pColDef->n-1];
486     while( (zEnd>zCol && *zEnd==';') || isspace(*(unsigned char *)zEnd) ){
487       *zEnd-- = '\0';
488     }
489     sqlite3NestedParse(pParse,
490         "UPDATE %Q.%s SET "
491           "sql = substr(sql,1,%d) || ', ' || %Q || substr(sql,%d,length(sql)) "
492         "WHERE type = 'table' AND name = %Q",
493       zDb, SCHEMA_TABLE(iDb), pNew->addColOffset, zCol, pNew->addColOffset+1,
494       zTab
495     );
496     sqliteFree(zCol);
497   }
498 
499   /* If the default value of the new column is NULL, then set the file
500   ** format to 2. If the default value of the new column is not NULL,
501   ** the file format becomes 3.
502   */
503   sqlite3MinimumFileFormat(pParse, iDb, pDflt ? 3 : 2);
504 
505   /* Reload the schema of the modified table. */
506   reloadTableSchema(pParse, pTab, pTab->zName);
507 }
508 
509 /*
510 ** This function is called by the parser after the table-name in
511 ** an "ALTER TABLE <table-name> ADD" statement is parsed. Argument
512 ** pSrc is the full-name of the table being altered.
513 **
514 ** This routine makes a (partial) copy of the Table structure
515 ** for the table being altered and sets Parse.pNewTable to point
516 ** to it. Routines called by the parser as the column definition
517 ** is parsed (i.e. sqlite3AddColumn()) add the new Column data to
518 ** the copy. The copy of the Table structure is deleted by tokenize.c
519 ** after parsing is finished.
520 **
521 ** Routine sqlite3AlterFinishAddColumn() will be called to complete
522 ** coding the "ALTER TABLE ... ADD" statement.
523 */
524 void sqlite3AlterBeginAddColumn(Parse *pParse, SrcList *pSrc){
525   Table *pNew;
526   Table *pTab;
527   Vdbe *v;
528   int iDb;
529   int i;
530   int nAlloc;
531 
532   /* Look up the table being altered. */
533   assert( pParse->pNewTable==0 );
534   if( sqlite3MallocFailed() ) goto exit_begin_add_column;
535   pTab = sqlite3LocateTable(pParse, pSrc->a[0].zName, pSrc->a[0].zDatabase);
536   if( !pTab ) goto exit_begin_add_column;
537 
538 #ifndef SQLITE_OMIT_VIRTUALTABLE
539   if( IsVirtual(pTab) ){
540     sqlite3ErrorMsg(pParse, "virtual tables may not be altered");
541     goto exit_begin_add_column;
542   }
543 #endif
544 
545   /* Make sure this is not an attempt to ALTER a view. */
546   if( pTab->pSelect ){
547     sqlite3ErrorMsg(pParse, "Cannot add a column to a view");
548     goto exit_begin_add_column;
549   }
550 
551   assert( pTab->addColOffset>0 );
552   iDb = sqlite3SchemaToIndex(pParse->db, pTab->pSchema);
553 
554   /* Put a copy of the Table struct in Parse.pNewTable for the
555   ** sqlite3AddColumn() function and friends to modify.
556   */
557   pNew = (Table *)sqliteMalloc(sizeof(Table));
558   if( !pNew ) goto exit_begin_add_column;
559   pParse->pNewTable = pNew;
560   pNew->nRef = 1;
561   pNew->nCol = pTab->nCol;
562   assert( pNew->nCol>0 );
563   nAlloc = (((pNew->nCol-1)/8)*8)+8;
564   assert( nAlloc>=pNew->nCol && nAlloc%8==0 && nAlloc-pNew->nCol<8 );
565   pNew->aCol = (Column *)sqliteMalloc(sizeof(Column)*nAlloc);
566   pNew->zName = sqliteStrDup(pTab->zName);
567   if( !pNew->aCol || !pNew->zName ){
568     goto exit_begin_add_column;
569   }
570   memcpy(pNew->aCol, pTab->aCol, sizeof(Column)*pNew->nCol);
571   for(i=0; i<pNew->nCol; i++){
572     Column *pCol = &pNew->aCol[i];
573     pCol->zName = sqliteStrDup(pCol->zName);
574     pCol->zColl = 0;
575     pCol->zType = 0;
576     pCol->pDflt = 0;
577   }
578   pNew->pSchema = pParse->db->aDb[iDb].pSchema;
579   pNew->addColOffset = pTab->addColOffset;
580   pNew->nRef = 1;
581 
582   /* Begin a transaction and increment the schema cookie.  */
583   sqlite3BeginWriteOperation(pParse, 0, iDb);
584   v = sqlite3GetVdbe(pParse);
585   if( !v ) goto exit_begin_add_column;
586   sqlite3ChangeCookie(pParse->db, v, iDb);
587 
588 exit_begin_add_column:
589   sqlite3SrcListDelete(pSrc);
590   return;
591 }
592 #endif  /* SQLITE_ALTER_TABLE */
593