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