4 ** The author disclaims copyright to this source code. In place of
5 ** a legal notice, here is a blessing:
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.
11 *************************************************************************
12 ** This file contains C code routines that used to generate VDBE code
13 ** that implements the ALTER TABLE command.
15 #include "sqliteInt.h"
18 ** The code in this file only exists if we are not omitting the
19 ** ALTER TABLE logic from the build.
21 #ifndef SQLITE_OMIT_ALTERTABLE
24 ** Parameter zName is the name of a table that is about to be altered
25 ** (either with ALTER TABLE ... RENAME TO or ALTER TABLE ... ADD COLUMN).
26 ** If the table is a system table, this function leaves an error message
27 ** in pParse->zErr (system tables may not be altered) and returns non-zero.
29 ** Or, if zName is not a system table, zero is returned.
31 static int isAlterableTable(Parse
*pParse
, Table
*pTab
){
32 if( 0==sqlite3StrNICmp(pTab
->zName
, "sqlite_", 7)
33 #ifndef SQLITE_OMIT_VIRTUALTABLE
34 || (pTab
->tabFlags
& TF_Eponymous
)!=0
35 || ( (pTab
->tabFlags
& TF_Shadow
)!=0
36 && sqlite3ReadOnlyShadowTables(pParse
->db
)
40 sqlite3ErrorMsg(pParse
, "table %s may not be altered", pTab
->zName
);
47 ** Generate code to verify that the schemas of database zDb and, if
48 ** bTemp is not true, database "temp", can still be parsed. This is
49 ** called at the end of the generation of an ALTER TABLE ... RENAME ...
50 ** statement to ensure that the operation has not rendered any schema
53 static void renameTestSchema(
54 Parse
*pParse
, /* Parse context */
55 const char *zDb
, /* Name of db to verify schema of */
56 int bTemp
, /* True if this is the temp db */
57 const char *zWhen
, /* "when" part of error message */
58 int bNoDQS
/* Do not allow DQS in the schema */
60 pParse
->colNamesSet
= 1;
61 sqlite3NestedParse(pParse
,
63 "FROM \"%w\"." LEGACY_SCHEMA_TABLE
" "
64 "WHERE name NOT LIKE 'sqliteX_%%' ESCAPE 'X'"
65 " AND sql NOT LIKE 'create virtual%%'"
66 " AND sqlite_rename_test(%Q, sql, type, name, %d, %Q, %d)=NULL ",
68 zDb
, bTemp
, zWhen
, bNoDQS
72 sqlite3NestedParse(pParse
,
74 "FROM temp." LEGACY_SCHEMA_TABLE
" "
75 "WHERE name NOT LIKE 'sqliteX_%%' ESCAPE 'X'"
76 " AND sql NOT LIKE 'create virtual%%'"
77 " AND sqlite_rename_test(%Q, sql, type, name, 1, %Q, %d)=NULL ",
84 ** Generate VM code to replace any double-quoted strings (but not double-quoted
85 ** identifiers) within the "sql" column of the sqlite_schema table in
86 ** database zDb with their single-quoted equivalents. If argument bTemp is
87 ** not true, similarly update all SQL statements in the sqlite_schema table
90 static void renameFixQuotes(Parse
*pParse
, const char *zDb
, int bTemp
){
91 sqlite3NestedParse(pParse
,
92 "UPDATE \"%w\"." LEGACY_SCHEMA_TABLE
93 " SET sql = sqlite_rename_quotefix(%Q, sql)"
94 "WHERE name NOT LIKE 'sqliteX_%%' ESCAPE 'X'"
95 " AND sql NOT LIKE 'create virtual%%'" , zDb
, zDb
98 sqlite3NestedParse(pParse
,
99 "UPDATE temp." LEGACY_SCHEMA_TABLE
100 " SET sql = sqlite_rename_quotefix('temp', sql)"
101 "WHERE name NOT LIKE 'sqliteX_%%' ESCAPE 'X'"
102 " AND sql NOT LIKE 'create virtual%%'"
108 ** Generate code to reload the schema for database iDb. And, if iDb!=1, for
109 ** the temp database as well.
111 static void renameReloadSchema(Parse
*pParse
, int iDb
, u16 p5
){
112 Vdbe
*v
= pParse
->pVdbe
;
114 sqlite3ChangeCookie(pParse
, iDb
);
115 sqlite3VdbeAddParseSchemaOp(pParse
->pVdbe
, iDb
, 0, p5
);
116 if( iDb
!=1 ) sqlite3VdbeAddParseSchemaOp(pParse
->pVdbe
, 1, 0, p5
);
121 ** Generate code to implement the "ALTER TABLE xxx RENAME TO yyy"
124 void sqlite3AlterRenameTable(
125 Parse
*pParse
, /* Parser context. */
126 SrcList
*pSrc
, /* The table to rename. */
127 Token
*pName
/* The new table name. */
129 int iDb
; /* Database that contains the table */
130 char *zDb
; /* Name of database iDb */
131 Table
*pTab
; /* Table being renamed */
132 char *zName
= 0; /* NULL-terminated version of pName */
133 sqlite3
*db
= pParse
->db
; /* Database connection */
134 int nTabName
; /* Number of UTF-8 characters in zTabName */
135 const char *zTabName
; /* Original name of the table */
137 VTable
*pVTab
= 0; /* Non-zero if this is a v-tab with an xRename() */
139 if( NEVER(db
->mallocFailed
) ) goto exit_rename_table
;
140 assert( pSrc
->nSrc
==1 );
141 assert( sqlite3BtreeHoldsAllMutexes(pParse
->db
) );
143 pTab
= sqlite3LocateTableItem(pParse
, 0, &pSrc
->a
[0]);
144 if( !pTab
) goto exit_rename_table
;
145 iDb
= sqlite3SchemaToIndex(pParse
->db
, pTab
->pSchema
);
146 zDb
= db
->aDb
[iDb
].zDbSName
;
148 /* Get a NULL terminated version of the new table name. */
149 zName
= sqlite3NameFromToken(db
, pName
);
150 if( !zName
) goto exit_rename_table
;
152 /* Check that a table or index named 'zName' does not already exist
153 ** in database iDb. If so, this is an error.
155 if( sqlite3FindTable(db
, zName
, zDb
)
156 || sqlite3FindIndex(db
, zName
, zDb
)
157 || sqlite3IsShadowTableOf(db
, pTab
, zName
)
159 sqlite3ErrorMsg(pParse
,
160 "there is already another table or index with this name: %s", zName
);
161 goto exit_rename_table
;
164 /* Make sure it is not a system table being altered, or a reserved name
165 ** that the table is being renamed to.
167 if( SQLITE_OK
!=isAlterableTable(pParse
, pTab
) ){
168 goto exit_rename_table
;
170 if( SQLITE_OK
!=sqlite3CheckObjectName(pParse
,zName
,"table",zName
) ){
171 goto exit_rename_table
;
174 #ifndef SQLITE_OMIT_VIEW
176 sqlite3ErrorMsg(pParse
, "view %s may not be altered", pTab
->zName
);
177 goto exit_rename_table
;
181 #ifndef SQLITE_OMIT_AUTHORIZATION
182 /* Invoke the authorization callback. */
183 if( sqlite3AuthCheck(pParse
, SQLITE_ALTER_TABLE
, zDb
, pTab
->zName
, 0) ){
184 goto exit_rename_table
;
188 #ifndef SQLITE_OMIT_VIRTUALTABLE
189 if( sqlite3ViewGetColumnNames(pParse
, pTab
) ){
190 goto exit_rename_table
;
192 if( IsVirtual(pTab
) ){
193 pVTab
= sqlite3GetVTable(db
, pTab
);
194 if( pVTab
->pVtab
->pModule
->xRename
==0 ){
200 /* Begin a transaction for database iDb. Then modify the schema cookie
201 ** (since the ALTER TABLE modifies the schema). Call sqlite3MayAbort(),
202 ** as the scalar functions (e.g. sqlite_rename_table()) invoked by the
203 ** nested SQL may raise an exception. */
204 v
= sqlite3GetVdbe(pParse
);
206 goto exit_rename_table
;
208 sqlite3MayAbort(pParse
);
210 /* figure out how many UTF-8 characters are in zName */
211 zTabName
= pTab
->zName
;
212 nTabName
= sqlite3Utf8CharLen(zTabName
, -1);
214 /* Rewrite all CREATE TABLE, INDEX, TRIGGER or VIEW statements in
215 ** the schema to use the new table name. */
216 sqlite3NestedParse(pParse
,
217 "UPDATE \"%w\"." LEGACY_SCHEMA_TABLE
" SET "
218 "sql = sqlite_rename_table(%Q, type, name, sql, %Q, %Q, %d) "
219 "WHERE (type!='index' OR tbl_name=%Q COLLATE nocase)"
220 "AND name NOT LIKE 'sqliteX_%%' ESCAPE 'X'"
221 , zDb
, zDb
, zTabName
, zName
, (iDb
==1), zTabName
224 /* Update the tbl_name and name columns of the sqlite_schema table
226 sqlite3NestedParse(pParse
,
227 "UPDATE %Q." LEGACY_SCHEMA_TABLE
" SET "
230 "WHEN type='table' THEN %Q "
231 "WHEN name LIKE 'sqliteX_autoindex%%' ESCAPE 'X' "
232 " AND type='index' THEN "
233 "'sqlite_autoindex_' || %Q || substr(name,%d+18) "
235 "WHERE tbl_name=%Q COLLATE nocase AND "
236 "(type='table' OR type='index' OR type='trigger');",
242 #ifndef SQLITE_OMIT_AUTOINCREMENT
243 /* If the sqlite_sequence table exists in this database, then update
244 ** it with the new table name.
246 if( sqlite3FindTable(db
, "sqlite_sequence", zDb
) ){
247 sqlite3NestedParse(pParse
,
248 "UPDATE \"%w\".sqlite_sequence set name = %Q WHERE name = %Q",
249 zDb
, zName
, pTab
->zName
);
253 /* If the table being renamed is not itself part of the temp database,
254 ** edit view and trigger definitions within the temp database
257 sqlite3NestedParse(pParse
,
258 "UPDATE sqlite_temp_schema SET "
259 "sql = sqlite_rename_table(%Q, type, name, sql, %Q, %Q, 1), "
261 "CASE WHEN tbl_name=%Q COLLATE nocase AND "
262 " sqlite_rename_test(%Q, sql, type, name, 1, 'after rename', 0) "
263 "THEN %Q ELSE tbl_name END "
264 "WHERE type IN ('view', 'trigger')"
265 , zDb
, zTabName
, zName
, zTabName
, zDb
, zName
);
268 /* If this is a virtual table, invoke the xRename() function if
269 ** one is defined. The xRename() callback will modify the names
270 ** of any resources used by the v-table implementation (including other
271 ** SQLite tables) that are identified by the name of the virtual table.
273 #ifndef SQLITE_OMIT_VIRTUALTABLE
275 int i
= ++pParse
->nMem
;
276 sqlite3VdbeLoadString(v
, i
, zName
);
277 sqlite3VdbeAddOp4(v
, OP_VRename
, i
, 0, 0,(const char*)pVTab
, P4_VTAB
);
281 renameReloadSchema(pParse
, iDb
, INITFLAG_AlterRename
);
282 renameTestSchema(pParse
, zDb
, iDb
==1, "after rename", 0);
285 sqlite3SrcListDelete(db
, pSrc
);
286 sqlite3DbFree(db
, zName
);
290 ** Write code that will raise an error if the table described by
291 ** zDb and zTab is not empty.
293 static void sqlite3ErrorIfNotEmpty(
294 Parse
*pParse
, /* Parsing context */
295 const char *zDb
, /* Schema holding the table */
296 const char *zTab
, /* Table to check for empty */
297 const char *zErr
/* Error message text */
299 sqlite3NestedParse(pParse
,
300 "SELECT raise(ABORT,%Q) FROM \"%w\".\"%w\"",
306 ** This function is called after an "ALTER TABLE ... ADD" statement
307 ** has been parsed. Argument pColDef contains the text of the new
308 ** column definition.
310 ** The Table structure pParse->pNewTable was extended to include
311 ** the new column during parsing.
313 void sqlite3AlterFinishAddColumn(Parse
*pParse
, Token
*pColDef
){
314 Table
*pNew
; /* Copy of pParse->pNewTable */
315 Table
*pTab
; /* Table being altered */
316 int iDb
; /* Database number */
317 const char *zDb
; /* Database name */
318 const char *zTab
; /* Table name */
319 char *zCol
; /* Null-terminated column definition */
320 Column
*pCol
; /* The new column */
321 Expr
*pDflt
; /* Default value for the new column */
322 sqlite3
*db
; /* The database connection; */
323 Vdbe
*v
; /* The prepared statement under construction */
324 int r1
; /* Temporary registers */
327 assert( db
->pParse
==pParse
);
328 if( pParse
->nErr
) return;
329 assert( db
->mallocFailed
==0 );
330 pNew
= pParse
->pNewTable
;
333 assert( sqlite3BtreeHoldsAllMutexes(db
) );
334 iDb
= sqlite3SchemaToIndex(db
, pNew
->pSchema
);
335 zDb
= db
->aDb
[iDb
].zDbSName
;
336 zTab
= &pNew
->zName
[16]; /* Skip the "sqlite_altertab_" prefix on the name */
337 pCol
= &pNew
->aCol
[pNew
->nCol
-1];
338 pDflt
= sqlite3ColumnExpr(pNew
, pCol
);
339 pTab
= sqlite3FindTable(db
, zTab
, zDb
);
342 #ifndef SQLITE_OMIT_AUTHORIZATION
343 /* Invoke the authorization callback. */
344 if( sqlite3AuthCheck(pParse
, SQLITE_ALTER_TABLE
, zDb
, pTab
->zName
, 0) ){
350 /* Check that the new column is not specified as PRIMARY KEY or UNIQUE.
351 ** If there is a NOT NULL constraint, then the default value for the
352 ** column must not be NULL.
354 if( pCol
->colFlags
& COLFLAG_PRIMKEY
){
355 sqlite3ErrorMsg(pParse
, "Cannot add a PRIMARY KEY column");
359 sqlite3ErrorMsg(pParse
,
360 "Cannot add a UNIQUE column");
363 if( (pCol
->colFlags
& COLFLAG_GENERATED
)==0 ){
364 /* If the default value for the new column was specified with a
365 ** literal NULL, then set pDflt to 0. This simplifies checking
366 ** for an SQL NULL default below.
368 assert( pDflt
==0 || pDflt
->op
==TK_SPAN
);
369 if( pDflt
&& pDflt
->pLeft
->op
==TK_NULL
){
372 assert( IsOrdinaryTable(pNew
) );
373 if( (db
->flags
&SQLITE_ForeignKeys
) && pNew
->u
.tab
.pFKey
&& pDflt
){
374 sqlite3ErrorIfNotEmpty(pParse
, zDb
, zTab
,
375 "Cannot add a REFERENCES column with non-NULL default value");
377 if( pCol
->notNull
&& !pDflt
){
378 sqlite3ErrorIfNotEmpty(pParse
, zDb
, zTab
,
379 "Cannot add a NOT NULL column with default value NULL");
383 /* Ensure the default expression is something that sqlite3ValueFromExpr()
384 ** can handle (i.e. not CURRENT_TIME etc.)
387 sqlite3_value
*pVal
= 0;
389 rc
= sqlite3ValueFromExpr(db
, pDflt
, SQLITE_UTF8
, SQLITE_AFF_BLOB
, &pVal
);
390 assert( rc
==SQLITE_OK
|| rc
==SQLITE_NOMEM
);
392 assert( db
->mallocFailed
== 1 );
396 sqlite3ErrorIfNotEmpty(pParse
, zDb
, zTab
,
397 "Cannot add a column with non-constant default");
399 sqlite3ValueFree(pVal
);
401 }else if( pCol
->colFlags
& COLFLAG_STORED
){
402 sqlite3ErrorIfNotEmpty(pParse
, zDb
, zTab
, "cannot add a STORED column");
406 /* Modify the CREATE TABLE statement. */
407 zCol
= sqlite3DbStrNDup(db
, (char*)pColDef
->z
, pColDef
->n
);
409 char *zEnd
= &zCol
[pColDef
->n
-1];
410 while( zEnd
>zCol
&& (*zEnd
==';' || sqlite3Isspace(*zEnd
)) ){
413 /* substr() operations on characters, but addColOffset is in bytes. So we
414 ** have to use printf() to translate between these units: */
415 assert( IsOrdinaryTable(pTab
) );
416 assert( IsOrdinaryTable(pNew
) );
417 sqlite3NestedParse(pParse
,
418 "UPDATE \"%w\"." LEGACY_SCHEMA_TABLE
" SET "
419 "sql = printf('%%.%ds, ',sql) || %Q"
420 " || substr(sql,1+length(printf('%%.%ds',sql))) "
421 "WHERE type = 'table' AND name = %Q",
422 zDb
, pNew
->u
.tab
.addColOffset
, zCol
, pNew
->u
.tab
.addColOffset
,
425 sqlite3DbFree(db
, zCol
);
428 v
= sqlite3GetVdbe(pParse
);
430 /* Make sure the schema version is at least 3. But do not upgrade
431 ** from less than 3 to 4, as that will corrupt any preexisting DESC
434 r1
= sqlite3GetTempReg(pParse
);
435 sqlite3VdbeAddOp3(v
, OP_ReadCookie
, iDb
, r1
, BTREE_FILE_FORMAT
);
436 sqlite3VdbeUsesBtree(v
, iDb
);
437 sqlite3VdbeAddOp2(v
, OP_AddImm
, r1
, -2);
438 sqlite3VdbeAddOp2(v
, OP_IfPos
, r1
, sqlite3VdbeCurrentAddr(v
)+2);
440 sqlite3VdbeAddOp3(v
, OP_SetCookie
, iDb
, BTREE_FILE_FORMAT
, 3);
441 sqlite3ReleaseTempReg(pParse
, r1
);
443 /* Reload the table definition */
444 renameReloadSchema(pParse
, iDb
, INITFLAG_AlterAdd
);
446 /* Verify that constraints are still satisfied */
448 || (pCol
->notNull
&& (pCol
->colFlags
& COLFLAG_GENERATED
)!=0)
449 || (pTab
->tabFlags
& TF_Strict
)!=0
451 sqlite3NestedParse(pParse
,
452 "SELECT CASE WHEN quick_check GLOB 'CHECK*'"
453 " THEN raise(ABORT,'CHECK constraint failed')"
454 " WHEN quick_check GLOB 'non-* value in*'"
455 " THEN raise(ABORT,'type mismatch on DEFAULT')"
456 " ELSE raise(ABORT,'NOT NULL constraint failed')"
458 " FROM pragma_quick_check(%Q,%Q)"
459 " WHERE quick_check GLOB 'CHECK*'"
460 " OR quick_check GLOB 'NULL*'"
461 " OR quick_check GLOB 'non-* value in*'",
469 ** This function is called by the parser after the table-name in
470 ** an "ALTER TABLE <table-name> ADD" statement is parsed. Argument
471 ** pSrc is the full-name of the table being altered.
473 ** This routine makes a (partial) copy of the Table structure
474 ** for the table being altered and sets Parse.pNewTable to point
475 ** to it. Routines called by the parser as the column definition
476 ** is parsed (i.e. sqlite3AddColumn()) add the new Column data to
477 ** the copy. The copy of the Table structure is deleted by tokenize.c
478 ** after parsing is finished.
480 ** Routine sqlite3AlterFinishAddColumn() will be called to complete
481 ** coding the "ALTER TABLE ... ADD" statement.
483 void sqlite3AlterBeginAddColumn(Parse
*pParse
, SrcList
*pSrc
){
489 sqlite3
*db
= pParse
->db
;
491 /* Look up the table being altered. */
492 assert( pParse
->pNewTable
==0 );
493 assert( sqlite3BtreeHoldsAllMutexes(db
) );
494 if( db
->mallocFailed
) goto exit_begin_add_column
;
495 pTab
= sqlite3LocateTableItem(pParse
, 0, &pSrc
->a
[0]);
496 if( !pTab
) goto exit_begin_add_column
;
498 #ifndef SQLITE_OMIT_VIRTUALTABLE
499 if( IsVirtual(pTab
) ){
500 sqlite3ErrorMsg(pParse
, "virtual tables may not be altered");
501 goto exit_begin_add_column
;
505 /* Make sure this is not an attempt to ALTER a view. */
507 sqlite3ErrorMsg(pParse
, "Cannot add a column to a view");
508 goto exit_begin_add_column
;
510 if( SQLITE_OK
!=isAlterableTable(pParse
, pTab
) ){
511 goto exit_begin_add_column
;
514 sqlite3MayAbort(pParse
);
515 assert( IsOrdinaryTable(pTab
) );
516 assert( pTab
->u
.tab
.addColOffset
>0 );
517 iDb
= sqlite3SchemaToIndex(db
, pTab
->pSchema
);
519 /* Put a copy of the Table struct in Parse.pNewTable for the
520 ** sqlite3AddColumn() function and friends to modify. But modify
521 ** the name by adding an "sqlite_altertab_" prefix. By adding this
522 ** prefix, we insure that the name will not collide with an existing
523 ** table because user table are not allowed to have the "sqlite_"
524 ** prefix on their name.
526 pNew
= (Table
*)sqlite3DbMallocZero(db
, sizeof(Table
));
527 if( !pNew
) goto exit_begin_add_column
;
528 pParse
->pNewTable
= pNew
;
530 pNew
->nCol
= pTab
->nCol
;
531 assert( pNew
->nCol
>0 );
532 nAlloc
= (((pNew
->nCol
-1)/8)*8)+8;
533 assert( nAlloc
>=pNew
->nCol
&& nAlloc
%8==0 && nAlloc
-pNew
->nCol
<8 );
534 pNew
->aCol
= (Column
*)sqlite3DbMallocZero(db
, sizeof(Column
)*nAlloc
);
535 pNew
->zName
= sqlite3MPrintf(db
, "sqlite_altertab_%s", pTab
->zName
);
536 if( !pNew
->aCol
|| !pNew
->zName
){
537 assert( db
->mallocFailed
);
538 goto exit_begin_add_column
;
540 memcpy(pNew
->aCol
, pTab
->aCol
, sizeof(Column
)*pNew
->nCol
);
541 for(i
=0; i
<pNew
->nCol
; i
++){
542 Column
*pCol
= &pNew
->aCol
[i
];
543 pCol
->zCnName
= sqlite3DbStrDup(db
, pCol
->zCnName
);
544 pCol
->hName
= sqlite3StrIHash(pCol
->zCnName
);
546 assert( IsOrdinaryTable(pNew
) );
547 pNew
->u
.tab
.pDfltList
= sqlite3ExprListDup(db
, pTab
->u
.tab
.pDfltList
, 0);
548 pNew
->pSchema
= db
->aDb
[iDb
].pSchema
;
549 pNew
->u
.tab
.addColOffset
= pTab
->u
.tab
.addColOffset
;
550 assert( pNew
->nTabRef
==1 );
552 exit_begin_add_column
:
553 sqlite3SrcListDelete(db
, pSrc
);
558 ** Parameter pTab is the subject of an ALTER TABLE ... RENAME COLUMN
559 ** command. This function checks if the table is a view or virtual
560 ** table (columns of views or virtual tables may not be renamed). If so,
561 ** it loads an error message into pParse and returns non-zero.
563 ** Or, if pTab is not a view or virtual table, zero is returned.
565 #if !defined(SQLITE_OMIT_VIEW) || !defined(SQLITE_OMIT_VIRTUALTABLE)
566 static int isRealTable(Parse
*pParse
, Table
*pTab
, int bDrop
){
567 const char *zType
= 0;
568 #ifndef SQLITE_OMIT_VIEW
573 #ifndef SQLITE_OMIT_VIRTUALTABLE
574 if( IsVirtual(pTab
) ){
575 zType
= "virtual table";
579 sqlite3ErrorMsg(pParse
, "cannot %s %s \"%s\"",
580 (bDrop
? "drop column from" : "rename columns of"),
587 #else /* !defined(SQLITE_OMIT_VIEW) || !defined(SQLITE_OMIT_VIRTUALTABLE) */
588 # define isRealTable(x,y,z) (0)
592 ** Handles the following parser reduction:
594 ** cmd ::= ALTER TABLE pSrc RENAME COLUMN pOld TO pNew
596 void sqlite3AlterRenameColumn(
597 Parse
*pParse
, /* Parsing context */
598 SrcList
*pSrc
, /* Table being altered. pSrc->nSrc==1 */
599 Token
*pOld
, /* Name of column being changed */
600 Token
*pNew
/* New column name */
602 sqlite3
*db
= pParse
->db
; /* Database connection */
603 Table
*pTab
; /* Table being updated */
604 int iCol
; /* Index of column being renamed */
605 char *zOld
= 0; /* Old column name */
606 char *zNew
= 0; /* New column name */
607 const char *zDb
; /* Name of schema containing the table */
608 int iSchema
; /* Index of the schema */
609 int bQuote
; /* True to quote the new name */
611 /* Locate the table to be altered */
612 pTab
= sqlite3LocateTableItem(pParse
, 0, &pSrc
->a
[0]);
613 if( !pTab
) goto exit_rename_column
;
615 /* Cannot alter a system table */
616 if( SQLITE_OK
!=isAlterableTable(pParse
, pTab
) ) goto exit_rename_column
;
617 if( SQLITE_OK
!=isRealTable(pParse
, pTab
, 0) ) goto exit_rename_column
;
619 /* Which schema holds the table to be altered */
620 iSchema
= sqlite3SchemaToIndex(db
, pTab
->pSchema
);
621 assert( iSchema
>=0 );
622 zDb
= db
->aDb
[iSchema
].zDbSName
;
624 #ifndef SQLITE_OMIT_AUTHORIZATION
625 /* Invoke the authorization callback. */
626 if( sqlite3AuthCheck(pParse
, SQLITE_ALTER_TABLE
, zDb
, pTab
->zName
, 0) ){
627 goto exit_rename_column
;
631 /* Make sure the old name really is a column name in the table to be
632 ** altered. Set iCol to be the index of the column being renamed */
633 zOld
= sqlite3NameFromToken(db
, pOld
);
634 if( !zOld
) goto exit_rename_column
;
635 for(iCol
=0; iCol
<pTab
->nCol
; iCol
++){
636 if( 0==sqlite3StrICmp(pTab
->aCol
[iCol
].zCnName
, zOld
) ) break;
638 if( iCol
==pTab
->nCol
){
639 sqlite3ErrorMsg(pParse
, "no such column: \"%T\"", pOld
);
640 goto exit_rename_column
;
643 /* Ensure the schema contains no double-quoted strings */
644 renameTestSchema(pParse
, zDb
, iSchema
==1, "", 0);
645 renameFixQuotes(pParse
, zDb
, iSchema
==1);
647 /* Do the rename operation using a recursive UPDATE statement that
648 ** uses the sqlite_rename_column() SQL function to compute the new
649 ** CREATE statement text for the sqlite_schema table.
651 sqlite3MayAbort(pParse
);
652 zNew
= sqlite3NameFromToken(db
, pNew
);
653 if( !zNew
) goto exit_rename_column
;
655 bQuote
= sqlite3Isquote(pNew
->z
[0]);
656 sqlite3NestedParse(pParse
,
657 "UPDATE \"%w\"." LEGACY_SCHEMA_TABLE
" SET "
658 "sql = sqlite_rename_column(sql, type, name, %Q, %Q, %d, %Q, %d, %d) "
659 "WHERE name NOT LIKE 'sqliteX_%%' ESCAPE 'X' "
660 " AND (type != 'index' OR tbl_name = %Q)",
662 zDb
, pTab
->zName
, iCol
, zNew
, bQuote
, iSchema
==1,
666 sqlite3NestedParse(pParse
,
667 "UPDATE temp." LEGACY_SCHEMA_TABLE
" SET "
668 "sql = sqlite_rename_column(sql, type, name, %Q, %Q, %d, %Q, %d, 1) "
669 "WHERE type IN ('trigger', 'view')",
670 zDb
, pTab
->zName
, iCol
, zNew
, bQuote
673 /* Drop and reload the database schema. */
674 renameReloadSchema(pParse
, iSchema
, INITFLAG_AlterRename
);
675 renameTestSchema(pParse
, zDb
, iSchema
==1, "after rename", 1);
678 sqlite3SrcListDelete(db
, pSrc
);
679 sqlite3DbFree(db
, zOld
);
680 sqlite3DbFree(db
, zNew
);
685 ** Each RenameToken object maps an element of the parse tree into
686 ** the token that generated that element. The parse tree element
689 ** * A pointer to an Expr that represents an ID
690 ** * The name of a table column in Column.zName
692 ** A list of RenameToken objects can be constructed during parsing.
693 ** Each new object is created by sqlite3RenameTokenMap().
694 ** As the parse tree is transformed, the sqlite3RenameTokenRemap()
695 ** routine is used to keep the mapping current.
697 ** After the parse finishes, renameTokenFind() routine can be used
698 ** to look up the actual token value that created some element in
702 const void *p
; /* Parse tree element created by token t */
703 Token t
; /* The token that created parse tree element p */
704 RenameToken
*pNext
; /* Next is a list of all RenameToken objects */
708 ** The context of an ALTER TABLE RENAME COLUMN operation that gets passed
709 ** down into the Walker.
711 typedef struct RenameCtx RenameCtx
;
713 RenameToken
*pList
; /* List of tokens to overwrite */
714 int nList
; /* Number of tokens in pList */
715 int iCol
; /* Index of column being renamed */
716 Table
*pTab
; /* Table being ALTERed */
717 const char *zOld
; /* Old column name */
722 ** This function is only for debugging. It performs two tasks:
724 ** 1. Checks that pointer pPtr does not already appear in the
725 ** rename-token list.
727 ** 2. Dereferences each pointer in the rename-token list.
729 ** The second is most effective when debugging under valgrind or
730 ** address-sanitizer or similar. If any of these pointers no longer
731 ** point to valid objects, an exception is raised by the memory-checking
734 ** The point of this is to prevent comparisons of invalid pointer values.
735 ** Even though this always seems to work, it is undefined according to the
736 ** C standard. Example of undefined comparison:
741 ** Technically, as x no longer points into a valid object or to the byte
742 ** following a valid object, it may not be used in comparison operations.
744 static void renameTokenCheckAll(Parse
*pParse
, const void *pPtr
){
745 assert( pParse
==pParse
->db
->pParse
);
746 assert( pParse
->db
->mallocFailed
==0 || pParse
->nErr
!=0 );
747 if( pParse
->nErr
==0 ){
748 const RenameToken
*p
;
750 for(p
=pParse
->pRename
; p
; p
=p
->pNext
){
752 assert( p
->p
!=pPtr
);
753 i
+= *(u8
*)(p
->p
) | 1;
760 # define renameTokenCheckAll(x,y)
764 ** Remember that the parser tree element pPtr was created using
767 ** In other words, construct a new RenameToken object and add it
768 ** to the list of RenameToken objects currently being built up
769 ** in pParse->pRename.
771 ** The pPtr argument is returned so that this routine can be used
772 ** with tail recursion in tokenExpr() routine, for a small performance
775 const void *sqlite3RenameTokenMap(
781 assert( pPtr
|| pParse
->db
->mallocFailed
);
782 renameTokenCheckAll(pParse
, pPtr
);
783 if( ALWAYS(pParse
->eParseMode
!=PARSE_MODE_UNMAP
) ){
784 pNew
= sqlite3DbMallocZero(pParse
->db
, sizeof(RenameToken
));
788 pNew
->pNext
= pParse
->pRename
;
789 pParse
->pRename
= pNew
;
797 ** It is assumed that there is already a RenameToken object associated
798 ** with parse tree element pFrom. This function remaps the associated token
799 ** to parse tree element pTo.
801 void sqlite3RenameTokenRemap(Parse
*pParse
, const void *pTo
, const void *pFrom
){
803 renameTokenCheckAll(pParse
, pTo
);
804 for(p
=pParse
->pRename
; p
; p
=p
->pNext
){
813 ** Walker callback used by sqlite3RenameExprUnmap().
815 static int renameUnmapExprCb(Walker
*pWalker
, Expr
*pExpr
){
816 Parse
*pParse
= pWalker
->pParse
;
817 sqlite3RenameTokenRemap(pParse
, 0, (const void*)pExpr
);
818 if( ExprUseYTab(pExpr
) ){
819 sqlite3RenameTokenRemap(pParse
, 0, (const void*)&pExpr
->y
.pTab
);
825 ** Iterate through the Select objects that are part of WITH clauses attached
826 ** to select statement pSelect.
828 static void renameWalkWith(Walker
*pWalker
, Select
*pSelect
){
829 With
*pWith
= pSelect
->pWith
;
831 Parse
*pParse
= pWalker
->pParse
;
834 assert( pWith
->nCte
>0 );
835 if( (pWith
->a
[0].pSelect
->selFlags
& SF_Expanded
)==0 ){
836 /* Push a copy of the With object onto the with-stack. We use a copy
837 ** here as the original will be expanded and resolved (flags SF_Expanded
838 ** and SF_Resolved) below. And the parser code that uses the with-stack
839 ** fails if the Select objects on it have already been expanded and
841 pCopy
= sqlite3WithDup(pParse
->db
, pWith
);
842 pCopy
= sqlite3WithPush(pParse
, pCopy
, 1);
844 for(i
=0; i
<pWith
->nCte
; i
++){
845 Select
*p
= pWith
->a
[i
].pSelect
;
847 memset(&sNC
, 0, sizeof(sNC
));
849 if( pCopy
) sqlite3SelectPrep(sNC
.pParse
, p
, &sNC
);
850 if( sNC
.pParse
->db
->mallocFailed
) return;
851 sqlite3WalkSelect(pWalker
, p
);
852 sqlite3RenameExprlistUnmap(pParse
, pWith
->a
[i
].pCols
);
854 if( pCopy
&& pParse
->pWith
==pCopy
){
855 pParse
->pWith
= pCopy
->pOuter
;
861 ** Unmap all tokens in the IdList object passed as the second argument.
863 static void unmapColumnIdlistNames(
865 const IdList
*pIdList
868 assert( pIdList
!=0 );
869 for(ii
=0; ii
<pIdList
->nId
; ii
++){
870 sqlite3RenameTokenRemap(pParse
, 0, (const void*)pIdList
->a
[ii
].zName
);
875 ** Walker callback used by sqlite3RenameExprUnmap().
877 static int renameUnmapSelectCb(Walker
*pWalker
, Select
*p
){
878 Parse
*pParse
= pWalker
->pParse
;
880 if( pParse
->nErr
) return WRC_Abort
;
881 testcase( p
->selFlags
& SF_View
);
882 testcase( p
->selFlags
& SF_CopyCte
);
883 if( p
->selFlags
& (SF_View
|SF_CopyCte
) ){
886 if( ALWAYS(p
->pEList
) ){
887 ExprList
*pList
= p
->pEList
;
888 for(i
=0; i
<pList
->nExpr
; i
++){
889 if( pList
->a
[i
].zEName
&& pList
->a
[i
].fg
.eEName
==ENAME_NAME
){
890 sqlite3RenameTokenRemap(pParse
, 0, (void*)pList
->a
[i
].zEName
);
894 if( ALWAYS(p
->pSrc
) ){ /* Every Select as a SrcList, even if it is empty */
895 SrcList
*pSrc
= p
->pSrc
;
896 for(i
=0; i
<pSrc
->nSrc
; i
++){
897 sqlite3RenameTokenRemap(pParse
, 0, (void*)pSrc
->a
[i
].zName
);
898 if( pSrc
->a
[i
].fg
.isUsing
==0 ){
899 sqlite3WalkExpr(pWalker
, pSrc
->a
[i
].u3
.pOn
);
901 unmapColumnIdlistNames(pParse
, pSrc
->a
[i
].u3
.pUsing
);
906 renameWalkWith(pWalker
, p
);
911 ** Remove all nodes that are part of expression pExpr from the rename list.
913 void sqlite3RenameExprUnmap(Parse
*pParse
, Expr
*pExpr
){
914 u8 eMode
= pParse
->eParseMode
;
916 memset(&sWalker
, 0, sizeof(Walker
));
917 sWalker
.pParse
= pParse
;
918 sWalker
.xExprCallback
= renameUnmapExprCb
;
919 sWalker
.xSelectCallback
= renameUnmapSelectCb
;
920 pParse
->eParseMode
= PARSE_MODE_UNMAP
;
921 sqlite3WalkExpr(&sWalker
, pExpr
);
922 pParse
->eParseMode
= eMode
;
926 ** Remove all nodes that are part of expression-list pEList from the
929 void sqlite3RenameExprlistUnmap(Parse
*pParse
, ExprList
*pEList
){
933 memset(&sWalker
, 0, sizeof(Walker
));
934 sWalker
.pParse
= pParse
;
935 sWalker
.xExprCallback
= renameUnmapExprCb
;
936 sqlite3WalkExprList(&sWalker
, pEList
);
937 for(i
=0; i
<pEList
->nExpr
; i
++){
938 if( ALWAYS(pEList
->a
[i
].fg
.eEName
==ENAME_NAME
) ){
939 sqlite3RenameTokenRemap(pParse
, 0, (void*)pEList
->a
[i
].zEName
);
946 ** Free the list of RenameToken objects given in the second argument
948 static void renameTokenFree(sqlite3
*db
, RenameToken
*pToken
){
951 for(p
=pToken
; p
; p
=pNext
){
953 sqlite3DbFree(db
, p
);
958 ** Search the Parse object passed as the first argument for a RenameToken
959 ** object associated with parse tree element pPtr. If found, return a pointer
960 ** to it. Otherwise, return NULL.
962 ** If the second argument passed to this function is not NULL and a matching
963 ** RenameToken object is found, remove it from the Parse object and add it to
964 ** the list maintained by the RenameCtx object.
966 static RenameToken
*renameTokenFind(
968 struct RenameCtx
*pCtx
,
972 if( NEVER(pPtr
==0) ){
975 for(pp
=&pParse
->pRename
; (*pp
); pp
=&(*pp
)->pNext
){
976 if( (*pp
)->p
==pPtr
){
977 RenameToken
*pToken
= *pp
;
980 pToken
->pNext
= pCtx
->pList
;
981 pCtx
->pList
= pToken
;
991 ** This is a Walker select callback. It does nothing. It is only required
992 ** because without a dummy callback, sqlite3WalkExpr() and similar do not
993 ** descend into sub-select statements.
995 static int renameColumnSelectCb(Walker
*pWalker
, Select
*p
){
996 if( p
->selFlags
& (SF_View
|SF_CopyCte
) ){
997 testcase( p
->selFlags
& SF_View
);
998 testcase( p
->selFlags
& SF_CopyCte
);
1001 renameWalkWith(pWalker
, p
);
1002 return WRC_Continue
;
1006 ** This is a Walker expression callback.
1008 ** For every TK_COLUMN node in the expression tree, search to see
1009 ** if the column being references is the column being renamed by an
1010 ** ALTER TABLE statement. If it is, then attach its associated
1011 ** RenameToken object to the list of RenameToken objects being
1012 ** constructed in RenameCtx object at pWalker->u.pRename.
1014 static int renameColumnExprCb(Walker
*pWalker
, Expr
*pExpr
){
1015 RenameCtx
*p
= pWalker
->u
.pRename
;
1016 if( pExpr
->op
==TK_TRIGGER
1017 && pExpr
->iColumn
==p
->iCol
1018 && pWalker
->pParse
->pTriggerTab
==p
->pTab
1020 renameTokenFind(pWalker
->pParse
, p
, (void*)pExpr
);
1021 }else if( pExpr
->op
==TK_COLUMN
1022 && pExpr
->iColumn
==p
->iCol
1023 && ALWAYS(ExprUseYTab(pExpr
))
1024 && p
->pTab
==pExpr
->y
.pTab
1026 renameTokenFind(pWalker
->pParse
, p
, (void*)pExpr
);
1028 return WRC_Continue
;
1032 ** The RenameCtx contains a list of tokens that reference a column that
1033 ** is being renamed by an ALTER TABLE statement. Return the "last"
1034 ** RenameToken in the RenameCtx and remove that RenameToken from the
1035 ** RenameContext. "Last" means the last RenameToken encountered when
1036 ** the input SQL is parsed from left to right. Repeated calls to this routine
1037 ** return all column name tokens in the order that they are encountered
1038 ** in the SQL statement.
1040 static RenameToken
*renameColumnTokenNext(RenameCtx
*pCtx
){
1041 RenameToken
*pBest
= pCtx
->pList
;
1042 RenameToken
*pToken
;
1045 for(pToken
=pBest
->pNext
; pToken
; pToken
=pToken
->pNext
){
1046 if( pToken
->t
.z
>pBest
->t
.z
) pBest
= pToken
;
1048 for(pp
=&pCtx
->pList
; *pp
!=pBest
; pp
=&(*pp
)->pNext
);
1055 ** An error occurred while parsing or otherwise processing a database
1056 ** object (either pParse->pNewTable, pNewIndex or pNewTrigger) as part of an
1057 ** ALTER TABLE RENAME COLUMN program. The error message emitted by the
1058 ** sub-routine is currently stored in pParse->zErrMsg. This function
1059 ** adds context to the error message and then stores it in pCtx.
1061 static void renameColumnParseError(
1062 sqlite3_context
*pCtx
,
1064 sqlite3_value
*pType
,
1065 sqlite3_value
*pObject
,
1068 const char *zT
= (const char*)sqlite3_value_text(pType
);
1069 const char *zN
= (const char*)sqlite3_value_text(pObject
);
1072 zErr
= sqlite3MPrintf(pParse
->db
, "error in %s %s%s%s: %s",
1073 zT
, zN
, (zWhen
[0] ? " " : ""), zWhen
,
1076 sqlite3_result_error(pCtx
, zErr
, -1);
1077 sqlite3DbFree(pParse
->db
, zErr
);
1081 ** For each name in the the expression-list pEList (i.e. each
1082 ** pEList->a[i].zName) that matches the string in zOld, extract the
1083 ** corresponding rename-token from Parse object pParse and add it
1084 ** to the RenameCtx pCtx.
1086 static void renameColumnElistNames(
1089 const ExprList
*pEList
,
1094 for(i
=0; i
<pEList
->nExpr
; i
++){
1095 const char *zName
= pEList
->a
[i
].zEName
;
1096 if( ALWAYS(pEList
->a
[i
].fg
.eEName
==ENAME_NAME
)
1098 && 0==sqlite3_stricmp(zName
, zOld
)
1100 renameTokenFind(pParse
, pCtx
, (const void*)zName
);
1107 ** For each name in the the id-list pIdList (i.e. each pIdList->a[i].zName)
1108 ** that matches the string in zOld, extract the corresponding rename-token
1109 ** from Parse object pParse and add it to the RenameCtx pCtx.
1111 static void renameColumnIdlistNames(
1114 const IdList
*pIdList
,
1119 for(i
=0; i
<pIdList
->nId
; i
++){
1120 const char *zName
= pIdList
->a
[i
].zName
;
1121 if( 0==sqlite3_stricmp(zName
, zOld
) ){
1122 renameTokenFind(pParse
, pCtx
, (const void*)zName
);
1130 ** Parse the SQL statement zSql using Parse object (*p). The Parse object
1131 ** is initialized by this function before it is used.
1133 static int renameParseSql(
1134 Parse
*p
, /* Memory to use for Parse object */
1135 const char *zDb
, /* Name of schema SQL belongs to */
1136 sqlite3
*db
, /* Database handle */
1137 const char *zSql
, /* SQL to parse */
1138 int bTemp
/* True if SQL is from temp schema */
1142 sqlite3ParseObjectInit(p
, db
);
1144 return SQLITE_NOMEM
;
1146 if( sqlite3StrNICmp(zSql
,"CREATE ",7)!=0 ){
1147 return SQLITE_CORRUPT_BKPT
;
1149 db
->init
.iDb
= bTemp
? 1 : sqlite3FindDbName(db
, zDb
);
1150 p
->eParseMode
= PARSE_MODE_RENAME
;
1153 rc
= sqlite3RunParser(p
, zSql
);
1154 if( db
->mallocFailed
) rc
= SQLITE_NOMEM
;
1156 && NEVER(p
->pNewTable
==0 && p
->pNewIndex
==0 && p
->pNewTrigger
==0)
1158 rc
= SQLITE_CORRUPT_BKPT
;
1162 /* Ensure that all mappings in the Parse.pRename list really do map to
1163 ** a part of the input string. */
1164 if( rc
==SQLITE_OK
){
1165 int nSql
= sqlite3Strlen30(zSql
);
1166 RenameToken
*pToken
;
1167 for(pToken
=p
->pRename
; pToken
; pToken
=pToken
->pNext
){
1168 assert( pToken
->t
.z
>=zSql
&& &pToken
->t
.z
[pToken
->t
.n
]<=&zSql
[nSql
] );
1178 ** This function edits SQL statement zSql, replacing each token identified
1179 ** by the linked list pRename with the text of zNew. If argument bQuote is
1180 ** true, then zNew is always quoted first. If no error occurs, the result
1181 ** is loaded into context object pCtx as the result.
1183 ** Or, if an error occurs (i.e. an OOM condition), an error is left in
1184 ** pCtx and an SQLite error code returned.
1186 static int renameEditSql(
1187 sqlite3_context
*pCtx
, /* Return result here */
1188 RenameCtx
*pRename
, /* Rename context */
1189 const char *zSql
, /* SQL statement to edit */
1190 const char *zNew
, /* New token text */
1191 int bQuote
/* True to always quote token */
1193 i64 nNew
= sqlite3Strlen30(zNew
);
1194 i64 nSql
= sqlite3Strlen30(zSql
);
1195 sqlite3
*db
= sqlite3_context_db_handle(pCtx
);
1204 /* Set zQuot to point to a buffer containing a quoted copy of the
1205 ** identifier zNew. If the corresponding identifier in the original
1206 ** ALTER TABLE statement was quoted (bQuote==1), then set zNew to
1207 ** point to zQuot so that all substitutions are made using the
1208 ** quoted version of the new column name. */
1209 zQuot
= sqlite3MPrintf(db
, "\"%w\" ", zNew
);
1211 return SQLITE_NOMEM
;
1213 nQuot
= sqlite3Strlen30(zQuot
)-1;
1216 assert( nQuot
>=nNew
);
1217 zOut
= sqlite3DbMallocZero(db
, nSql
+ pRename
->nList
*nQuot
+ 1);
1219 zOut
= (char*)sqlite3DbMallocZero(db
, (nSql
*2+1) * 3);
1221 zBuf1
= &zOut
[nSql
*2+1];
1222 zBuf2
= &zOut
[nSql
*4+2];
1226 /* At this point pRename->pList contains a list of RenameToken objects
1227 ** corresponding to all tokens in the input SQL that must be replaced
1228 ** with the new column name, or with single-quoted versions of themselves.
1229 ** All that remains is to construct and return the edited SQL string. */
1232 memcpy(zOut
, zSql
, nSql
);
1233 while( pRename
->pList
){
1234 int iOff
; /* Offset of token to replace in zOut */
1236 const char *zReplace
;
1237 RenameToken
*pBest
= renameColumnTokenNext(pRename
);
1240 if( bQuote
==0 && sqlite3IsIdChar(*pBest
->t
.z
) ){
1246 if( pBest
->t
.z
[pBest
->t
.n
]=='"' ) nReplace
++;
1249 /* Dequote the double-quoted token. Then requote it again, this time
1250 ** using single quotes. If the character immediately following the
1251 ** original token within the input SQL was a single quote ('), then
1252 ** add another space after the new, single-quoted version of the
1253 ** token. This is so that (SELECT "string"'alias') maps to
1254 ** (SELECT 'string' 'alias'), and not (SELECT 'string''alias'). */
1255 memcpy(zBuf1
, pBest
->t
.z
, pBest
->t
.n
);
1256 zBuf1
[pBest
->t
.n
] = 0;
1257 sqlite3Dequote(zBuf1
);
1258 sqlite3_snprintf(nSql
*2, zBuf2
, "%Q%s", zBuf1
,
1259 pBest
->t
.z
[pBest
->t
.n
]=='\'' ? " " : ""
1262 nReplace
= sqlite3Strlen30(zReplace
);
1265 iOff
= pBest
->t
.z
- zSql
;
1266 if( pBest
->t
.n
!=nReplace
){
1267 memmove(&zOut
[iOff
+ nReplace
], &zOut
[iOff
+ pBest
->t
.n
],
1268 nOut
- (iOff
+ pBest
->t
.n
)
1270 nOut
+= nReplace
- pBest
->t
.n
;
1273 memcpy(&zOut
[iOff
], zReplace
, nReplace
);
1274 sqlite3DbFree(db
, pBest
);
1277 sqlite3_result_text(pCtx
, zOut
, -1, SQLITE_TRANSIENT
);
1278 sqlite3DbFree(db
, zOut
);
1283 sqlite3_free(zQuot
);
1288 ** Set all pEList->a[].fg.eEName fields in the expression-list to val.
1290 static void renameSetENames(ExprList
*pEList
, int val
){
1293 for(i
=0; i
<pEList
->nExpr
; i
++){
1294 assert( val
==ENAME_NAME
|| pEList
->a
[i
].fg
.eEName
==ENAME_NAME
);
1295 pEList
->a
[i
].fg
.eEName
= val
;
1301 ** Resolve all symbols in the trigger at pParse->pNewTrigger, assuming
1302 ** it was read from the schema of database zDb. Return SQLITE_OK if
1303 ** successful. Otherwise, return an SQLite error code and leave an error
1304 ** message in the Parse object.
1306 static int renameResolveTrigger(Parse
*pParse
){
1307 sqlite3
*db
= pParse
->db
;
1308 Trigger
*pNew
= pParse
->pNewTrigger
;
1313 memset(&sNC
, 0, sizeof(sNC
));
1314 sNC
.pParse
= pParse
;
1315 assert( pNew
->pTabSchema
);
1316 pParse
->pTriggerTab
= sqlite3FindTable(db
, pNew
->table
,
1317 db
->aDb
[sqlite3SchemaToIndex(db
, pNew
->pTabSchema
)].zDbSName
1319 pParse
->eTriggerOp
= pNew
->op
;
1320 /* ALWAYS() because if the table of the trigger does not exist, the
1321 ** error would have been hit before this point */
1322 if( ALWAYS(pParse
->pTriggerTab
) ){
1323 rc
= sqlite3ViewGetColumnNames(pParse
, pParse
->pTriggerTab
);
1326 /* Resolve symbols in WHEN clause */
1327 if( rc
==SQLITE_OK
&& pNew
->pWhen
){
1328 rc
= sqlite3ResolveExprNames(&sNC
, pNew
->pWhen
);
1331 for(pStep
=pNew
->step_list
; rc
==SQLITE_OK
&& pStep
; pStep
=pStep
->pNext
){
1332 if( pStep
->pSelect
){
1333 sqlite3SelectPrep(pParse
, pStep
->pSelect
, &sNC
);
1334 if( pParse
->nErr
) rc
= pParse
->rc
;
1336 if( rc
==SQLITE_OK
&& pStep
->zTarget
){
1337 SrcList
*pSrc
= sqlite3TriggerStepSrc(pParse
, pStep
);
1339 Select
*pSel
= sqlite3SelectNew(
1340 pParse
, pStep
->pExprList
, pSrc
, 0, 0, 0, 0, 0, 0
1343 pStep
->pExprList
= 0;
1347 /* pStep->pExprList contains an expression-list used for an UPDATE
1348 ** statement. So the a[].zEName values are the RHS of the
1349 ** "<col> = <expr>" clauses of the UPDATE statement. So, before
1350 ** running SelectPrep(), change all the eEName values in
1351 ** pStep->pExprList to ENAME_SPAN (from their current value of
1352 ** ENAME_NAME). This is to prevent any ids in ON() clauses that are
1353 ** part of pSrc from being incorrectly resolved against the
1354 ** a[].zEName values as if they were column aliases. */
1355 renameSetENames(pStep
->pExprList
, ENAME_SPAN
);
1356 sqlite3SelectPrep(pParse
, pSel
, 0);
1357 renameSetENames(pStep
->pExprList
, ENAME_NAME
);
1358 rc
= pParse
->nErr
? SQLITE_ERROR
: SQLITE_OK
;
1359 assert( pStep
->pExprList
==0 || pStep
->pExprList
==pSel
->pEList
);
1360 assert( pSrc
==pSel
->pSrc
);
1361 if( pStep
->pExprList
) pSel
->pEList
= 0;
1363 sqlite3SelectDelete(db
, pSel
);
1367 for(i
=0; i
<pStep
->pFrom
->nSrc
&& rc
==SQLITE_OK
; i
++){
1368 SrcItem
*p
= &pStep
->pFrom
->a
[i
];
1370 sqlite3SelectPrep(pParse
, p
->pSelect
, 0);
1375 if( db
->mallocFailed
){
1378 sNC
.pSrcList
= pSrc
;
1379 if( rc
==SQLITE_OK
&& pStep
->pWhere
){
1380 rc
= sqlite3ResolveExprNames(&sNC
, pStep
->pWhere
);
1382 if( rc
==SQLITE_OK
){
1383 rc
= sqlite3ResolveExprListNames(&sNC
, pStep
->pExprList
);
1385 assert( !pStep
->pUpsert
|| (!pStep
->pWhere
&& !pStep
->pExprList
) );
1386 if( pStep
->pUpsert
&& rc
==SQLITE_OK
){
1387 Upsert
*pUpsert
= pStep
->pUpsert
;
1388 pUpsert
->pUpsertSrc
= pSrc
;
1389 sNC
.uNC
.pUpsert
= pUpsert
;
1390 sNC
.ncFlags
= NC_UUpsert
;
1391 rc
= sqlite3ResolveExprListNames(&sNC
, pUpsert
->pUpsertTarget
);
1392 if( rc
==SQLITE_OK
){
1393 ExprList
*pUpsertSet
= pUpsert
->pUpsertSet
;
1394 rc
= sqlite3ResolveExprListNames(&sNC
, pUpsertSet
);
1396 if( rc
==SQLITE_OK
){
1397 rc
= sqlite3ResolveExprNames(&sNC
, pUpsert
->pUpsertWhere
);
1399 if( rc
==SQLITE_OK
){
1400 rc
= sqlite3ResolveExprNames(&sNC
, pUpsert
->pUpsertTargetWhere
);
1405 sqlite3SrcListDelete(db
, pSrc
);
1415 ** Invoke sqlite3WalkExpr() or sqlite3WalkSelect() on all Select or Expr
1416 ** objects that are part of the trigger passed as the second argument.
1418 static void renameWalkTrigger(Walker
*pWalker
, Trigger
*pTrigger
){
1421 /* Find tokens to edit in WHEN clause */
1422 sqlite3WalkExpr(pWalker
, pTrigger
->pWhen
);
1424 /* Find tokens to edit in trigger steps */
1425 for(pStep
=pTrigger
->step_list
; pStep
; pStep
=pStep
->pNext
){
1426 sqlite3WalkSelect(pWalker
, pStep
->pSelect
);
1427 sqlite3WalkExpr(pWalker
, pStep
->pWhere
);
1428 sqlite3WalkExprList(pWalker
, pStep
->pExprList
);
1429 if( pStep
->pUpsert
){
1430 Upsert
*pUpsert
= pStep
->pUpsert
;
1431 sqlite3WalkExprList(pWalker
, pUpsert
->pUpsertTarget
);
1432 sqlite3WalkExprList(pWalker
, pUpsert
->pUpsertSet
);
1433 sqlite3WalkExpr(pWalker
, pUpsert
->pUpsertWhere
);
1434 sqlite3WalkExpr(pWalker
, pUpsert
->pUpsertTargetWhere
);
1438 for(i
=0; i
<pStep
->pFrom
->nSrc
; i
++){
1439 sqlite3WalkSelect(pWalker
, pStep
->pFrom
->a
[i
].pSelect
);
1446 ** Free the contents of Parse object (*pParse). Do not free the memory
1447 ** occupied by the Parse object itself.
1449 static void renameParseCleanup(Parse
*pParse
){
1450 sqlite3
*db
= pParse
->db
;
1452 if( pParse
->pVdbe
){
1453 sqlite3VdbeFinalize(pParse
->pVdbe
);
1455 sqlite3DeleteTable(db
, pParse
->pNewTable
);
1456 while( (pIdx
= pParse
->pNewIndex
)!=0 ){
1457 pParse
->pNewIndex
= pIdx
->pNext
;
1458 sqlite3FreeIndex(db
, pIdx
);
1460 sqlite3DeleteTrigger(db
, pParse
->pNewTrigger
);
1461 sqlite3DbFree(db
, pParse
->zErrMsg
);
1462 renameTokenFree(db
, pParse
->pRename
);
1463 sqlite3ParseObjectReset(pParse
);
1469 ** sqlite_rename_column(SQL,TYPE,OBJ,DB,TABLE,COL,NEWNAME,QUOTE,TEMP)
1471 ** 0. zSql: SQL statement to rewrite
1472 ** 1. type: Type of object ("table", "view" etc.)
1473 ** 2. object: Name of object
1474 ** 3. Database: Database name (e.g. "main")
1475 ** 4. Table: Table name
1476 ** 5. iCol: Index of column to rename
1477 ** 6. zNew: New column name
1478 ** 7. bQuote: Non-zero if the new column name should be quoted.
1479 ** 8. bTemp: True if zSql comes from temp schema
1481 ** Do a column rename operation on the CREATE statement given in zSql.
1482 ** The iCol-th column (left-most is 0) of table zTable is renamed from zCol
1483 ** into zNew. The name should be quoted if bQuote is true.
1485 ** This function is used internally by the ALTER TABLE RENAME COLUMN command.
1486 ** It is only accessible to SQL created using sqlite3NestedParse(). It is
1487 ** not reachable from ordinary SQL passed into sqlite3_prepare() unless the
1488 ** SQLITE_TESTCTRL_INTERNAL_FUNCTIONS test setting is enabled.
1490 static void renameColumnFunc(
1491 sqlite3_context
*context
,
1493 sqlite3_value
**argv
1495 sqlite3
*db
= sqlite3_context_db_handle(context
);
1497 const char *zSql
= (const char*)sqlite3_value_text(argv
[0]);
1498 const char *zDb
= (const char*)sqlite3_value_text(argv
[3]);
1499 const char *zTable
= (const char*)sqlite3_value_text(argv
[4]);
1500 int iCol
= sqlite3_value_int(argv
[5]);
1501 const char *zNew
= (const char*)sqlite3_value_text(argv
[6]);
1502 int bQuote
= sqlite3_value_int(argv
[7]);
1503 int bTemp
= sqlite3_value_int(argv
[8]);
1511 #ifndef SQLITE_OMIT_AUTHORIZATION
1512 sqlite3_xauth xAuth
= db
->xAuth
;
1515 UNUSED_PARAMETER(NotUsed
);
1516 if( zSql
==0 ) return;
1517 if( zTable
==0 ) return;
1518 if( zNew
==0 ) return;
1519 if( iCol
<0 ) return;
1520 sqlite3BtreeEnterAll(db
);
1521 pTab
= sqlite3FindTable(db
, zTable
, zDb
);
1522 if( pTab
==0 || iCol
>=pTab
->nCol
){
1523 sqlite3BtreeLeaveAll(db
);
1526 zOld
= pTab
->aCol
[iCol
].zCnName
;
1527 memset(&sCtx
, 0, sizeof(sCtx
));
1528 sCtx
.iCol
= ((iCol
==pTab
->iPKey
) ? -1 : iCol
);
1530 #ifndef SQLITE_OMIT_AUTHORIZATION
1533 rc
= renameParseSql(&sParse
, zDb
, db
, zSql
, bTemp
);
1535 /* Find tokens that need to be replaced. */
1536 memset(&sWalker
, 0, sizeof(Walker
));
1537 sWalker
.pParse
= &sParse
;
1538 sWalker
.xExprCallback
= renameColumnExprCb
;
1539 sWalker
.xSelectCallback
= renameColumnSelectCb
;
1540 sWalker
.u
.pRename
= &sCtx
;
1543 if( rc
!=SQLITE_OK
) goto renameColumnFunc_done
;
1544 if( sParse
.pNewTable
){
1545 if( IsView(sParse
.pNewTable
) ){
1546 Select
*pSelect
= sParse
.pNewTable
->u
.view
.pSelect
;
1547 pSelect
->selFlags
&= ~SF_View
;
1548 sParse
.rc
= SQLITE_OK
;
1549 sqlite3SelectPrep(&sParse
, pSelect
, 0);
1550 rc
= (db
->mallocFailed
? SQLITE_NOMEM
: sParse
.rc
);
1551 if( rc
==SQLITE_OK
){
1552 sqlite3WalkSelect(&sWalker
, pSelect
);
1554 if( rc
!=SQLITE_OK
) goto renameColumnFunc_done
;
1555 }else if( IsOrdinaryTable(sParse
.pNewTable
) ){
1556 /* A regular table */
1557 int bFKOnly
= sqlite3_stricmp(zTable
, sParse
.pNewTable
->zName
);
1559 sCtx
.pTab
= sParse
.pNewTable
;
1561 if( iCol
<sParse
.pNewTable
->nCol
){
1563 &sParse
, &sCtx
, (void*)sParse
.pNewTable
->aCol
[iCol
].zCnName
1567 renameTokenFind(&sParse
, &sCtx
, (void*)&sParse
.pNewTable
->iPKey
);
1569 sqlite3WalkExprList(&sWalker
, sParse
.pNewTable
->pCheck
);
1570 for(pIdx
=sParse
.pNewTable
->pIndex
; pIdx
; pIdx
=pIdx
->pNext
){
1571 sqlite3WalkExprList(&sWalker
, pIdx
->aColExpr
);
1573 for(pIdx
=sParse
.pNewIndex
; pIdx
; pIdx
=pIdx
->pNext
){
1574 sqlite3WalkExprList(&sWalker
, pIdx
->aColExpr
);
1576 #ifndef SQLITE_OMIT_GENERATED_COLUMNS
1577 for(i
=0; i
<sParse
.pNewTable
->nCol
; i
++){
1578 Expr
*pExpr
= sqlite3ColumnExpr(sParse
.pNewTable
,
1579 &sParse
.pNewTable
->aCol
[i
]);
1580 sqlite3WalkExpr(&sWalker
, pExpr
);
1585 assert( IsOrdinaryTable(sParse
.pNewTable
) );
1586 for(pFKey
=sParse
.pNewTable
->u
.tab
.pFKey
; pFKey
; pFKey
=pFKey
->pNextFrom
){
1587 for(i
=0; i
<pFKey
->nCol
; i
++){
1588 if( bFKOnly
==0 && pFKey
->aCol
[i
].iFrom
==iCol
){
1589 renameTokenFind(&sParse
, &sCtx
, (void*)&pFKey
->aCol
[i
]);
1591 if( 0==sqlite3_stricmp(pFKey
->zTo
, zTable
)
1592 && 0==sqlite3_stricmp(pFKey
->aCol
[i
].zCol
, zOld
)
1594 renameTokenFind(&sParse
, &sCtx
, (void*)pFKey
->aCol
[i
].zCol
);
1599 }else if( sParse
.pNewIndex
){
1600 sqlite3WalkExprList(&sWalker
, sParse
.pNewIndex
->aColExpr
);
1601 sqlite3WalkExpr(&sWalker
, sParse
.pNewIndex
->pPartIdxWhere
);
1605 rc
= renameResolveTrigger(&sParse
);
1606 if( rc
!=SQLITE_OK
) goto renameColumnFunc_done
;
1608 for(pStep
=sParse
.pNewTrigger
->step_list
; pStep
; pStep
=pStep
->pNext
){
1609 if( pStep
->zTarget
){
1610 Table
*pTarget
= sqlite3LocateTable(&sParse
, 0, pStep
->zTarget
, zDb
);
1611 if( pTarget
==pTab
){
1612 if( pStep
->pUpsert
){
1613 ExprList
*pUpsertSet
= pStep
->pUpsert
->pUpsertSet
;
1614 renameColumnElistNames(&sParse
, &sCtx
, pUpsertSet
, zOld
);
1616 renameColumnIdlistNames(&sParse
, &sCtx
, pStep
->pIdList
, zOld
);
1617 renameColumnElistNames(&sParse
, &sCtx
, pStep
->pExprList
, zOld
);
1623 /* Find tokens to edit in UPDATE OF clause */
1624 if( sParse
.pTriggerTab
==pTab
){
1625 renameColumnIdlistNames(&sParse
, &sCtx
,sParse
.pNewTrigger
->pColumns
,zOld
);
1628 /* Find tokens to edit in various expressions and selects */
1629 renameWalkTrigger(&sWalker
, sParse
.pNewTrigger
);
1632 assert( rc
==SQLITE_OK
);
1633 rc
= renameEditSql(context
, &sCtx
, zSql
, zNew
, bQuote
);
1635 renameColumnFunc_done
:
1636 if( rc
!=SQLITE_OK
){
1637 if( rc
==SQLITE_ERROR
&& sqlite3WritableSchema(db
) ){
1638 sqlite3_result_value(context
, argv
[0]);
1639 }else if( sParse
.zErrMsg
){
1640 renameColumnParseError(context
, "", argv
[1], argv
[2], &sParse
);
1642 sqlite3_result_error_code(context
, rc
);
1646 renameParseCleanup(&sParse
);
1647 renameTokenFree(db
, sCtx
.pList
);
1648 #ifndef SQLITE_OMIT_AUTHORIZATION
1651 sqlite3BtreeLeaveAll(db
);
1655 ** Walker expression callback used by "RENAME TABLE".
1657 static int renameTableExprCb(Walker
*pWalker
, Expr
*pExpr
){
1658 RenameCtx
*p
= pWalker
->u
.pRename
;
1659 if( pExpr
->op
==TK_COLUMN
1660 && ALWAYS(ExprUseYTab(pExpr
))
1661 && p
->pTab
==pExpr
->y
.pTab
1663 renameTokenFind(pWalker
->pParse
, p
, (void*)&pExpr
->y
.pTab
);
1665 return WRC_Continue
;
1669 ** Walker select callback used by "RENAME TABLE".
1671 static int renameTableSelectCb(Walker
*pWalker
, Select
*pSelect
){
1673 RenameCtx
*p
= pWalker
->u
.pRename
;
1674 SrcList
*pSrc
= pSelect
->pSrc
;
1675 if( pSelect
->selFlags
& (SF_View
|SF_CopyCte
) ){
1676 testcase( pSelect
->selFlags
& SF_View
);
1677 testcase( pSelect
->selFlags
& SF_CopyCte
);
1680 if( NEVER(pSrc
==0) ){
1681 assert( pWalker
->pParse
->db
->mallocFailed
);
1684 for(i
=0; i
<pSrc
->nSrc
; i
++){
1685 SrcItem
*pItem
= &pSrc
->a
[i
];
1686 if( pItem
->pTab
==p
->pTab
){
1687 renameTokenFind(pWalker
->pParse
, p
, pItem
->zName
);
1690 renameWalkWith(pWalker
, pSelect
);
1692 return WRC_Continue
;
1697 ** This C function implements an SQL user function that is used by SQL code
1698 ** generated by the ALTER TABLE ... RENAME command to modify the definition
1699 ** of any foreign key constraints that use the table being renamed as the
1700 ** parent table. It is passed three arguments:
1702 ** 0: The database containing the table being renamed.
1703 ** 1. type: Type of object ("table", "view" etc.)
1704 ** 2. object: Name of object
1705 ** 3: The complete text of the schema statement being modified,
1706 ** 4: The old name of the table being renamed, and
1707 ** 5: The new name of the table being renamed.
1708 ** 6: True if the schema statement comes from the temp db.
1710 ** It returns the new schema statement. For example:
1712 ** sqlite_rename_table('main', 'CREATE TABLE t1(a REFERENCES t2)','t2','t3',0)
1713 ** -> 'CREATE TABLE t1(a REFERENCES t3)'
1715 static void renameTableFunc(
1716 sqlite3_context
*context
,
1718 sqlite3_value
**argv
1720 sqlite3
*db
= sqlite3_context_db_handle(context
);
1721 const char *zDb
= (const char*)sqlite3_value_text(argv
[0]);
1722 const char *zInput
= (const char*)sqlite3_value_text(argv
[3]);
1723 const char *zOld
= (const char*)sqlite3_value_text(argv
[4]);
1724 const char *zNew
= (const char*)sqlite3_value_text(argv
[5]);
1725 int bTemp
= sqlite3_value_int(argv
[6]);
1726 UNUSED_PARAMETER(NotUsed
);
1728 if( zInput
&& zOld
&& zNew
){
1735 #ifndef SQLITE_OMIT_AUTHORIZATION
1736 sqlite3_xauth xAuth
= db
->xAuth
;
1740 sqlite3BtreeEnterAll(db
);
1742 memset(&sCtx
, 0, sizeof(RenameCtx
));
1743 sCtx
.pTab
= sqlite3FindTable(db
, zOld
, zDb
);
1744 memset(&sWalker
, 0, sizeof(Walker
));
1745 sWalker
.pParse
= &sParse
;
1746 sWalker
.xExprCallback
= renameTableExprCb
;
1747 sWalker
.xSelectCallback
= renameTableSelectCb
;
1748 sWalker
.u
.pRename
= &sCtx
;
1750 rc
= renameParseSql(&sParse
, zDb
, db
, zInput
, bTemp
);
1752 if( rc
==SQLITE_OK
){
1753 int isLegacy
= (db
->flags
& SQLITE_LegacyAlter
);
1754 if( sParse
.pNewTable
){
1755 Table
*pTab
= sParse
.pNewTable
;
1759 Select
*pSelect
= pTab
->u
.view
.pSelect
;
1761 memset(&sNC
, 0, sizeof(sNC
));
1762 sNC
.pParse
= &sParse
;
1764 assert( pSelect
->selFlags
& SF_View
);
1765 pSelect
->selFlags
&= ~SF_View
;
1766 sqlite3SelectPrep(&sParse
, pTab
->u
.view
.pSelect
, &sNC
);
1770 sqlite3WalkSelect(&sWalker
, pTab
->u
.view
.pSelect
);
1774 /* Modify any FK definitions to point to the new table. */
1775 #ifndef SQLITE_OMIT_FOREIGN_KEY
1776 if( (isLegacy
==0 || (db
->flags
& SQLITE_ForeignKeys
))
1780 assert( IsOrdinaryTable(pTab
) );
1781 for(pFKey
=pTab
->u
.tab
.pFKey
; pFKey
; pFKey
=pFKey
->pNextFrom
){
1782 if( sqlite3_stricmp(pFKey
->zTo
, zOld
)==0 ){
1783 renameTokenFind(&sParse
, &sCtx
, (void*)pFKey
->zTo
);
1789 /* If this is the table being altered, fix any table refs in CHECK
1790 ** expressions. Also update the name that appears right after the
1791 ** "CREATE [VIRTUAL] TABLE" bit. */
1792 if( sqlite3_stricmp(zOld
, pTab
->zName
)==0 ){
1795 sqlite3WalkExprList(&sWalker
, pTab
->pCheck
);
1797 renameTokenFind(&sParse
, &sCtx
, pTab
->zName
);
1802 else if( sParse
.pNewIndex
){
1803 renameTokenFind(&sParse
, &sCtx
, sParse
.pNewIndex
->zName
);
1805 sqlite3WalkExpr(&sWalker
, sParse
.pNewIndex
->pPartIdxWhere
);
1809 #ifndef SQLITE_OMIT_TRIGGER
1811 Trigger
*pTrigger
= sParse
.pNewTrigger
;
1813 if( 0==sqlite3_stricmp(sParse
.pNewTrigger
->table
, zOld
)
1814 && sCtx
.pTab
->pSchema
==pTrigger
->pTabSchema
1816 renameTokenFind(&sParse
, &sCtx
, sParse
.pNewTrigger
->table
);
1820 rc
= renameResolveTrigger(&sParse
);
1821 if( rc
==SQLITE_OK
){
1822 renameWalkTrigger(&sWalker
, pTrigger
);
1823 for(pStep
=pTrigger
->step_list
; pStep
; pStep
=pStep
->pNext
){
1824 if( pStep
->zTarget
&& 0==sqlite3_stricmp(pStep
->zTarget
, zOld
) ){
1825 renameTokenFind(&sParse
, &sCtx
, pStep
->zTarget
);
1829 for(i
=0; i
<pStep
->pFrom
->nSrc
; i
++){
1830 SrcItem
*pItem
= &pStep
->pFrom
->a
[i
];
1831 if( 0==sqlite3_stricmp(pItem
->zName
, zOld
) ){
1832 renameTokenFind(&sParse
, &sCtx
, pItem
->zName
);
1843 if( rc
==SQLITE_OK
){
1844 rc
= renameEditSql(context
, &sCtx
, zInput
, zNew
, bQuote
);
1846 if( rc
!=SQLITE_OK
){
1847 if( rc
==SQLITE_ERROR
&& sqlite3WritableSchema(db
) ){
1848 sqlite3_result_value(context
, argv
[3]);
1849 }else if( sParse
.zErrMsg
){
1850 renameColumnParseError(context
, "", argv
[1], argv
[2], &sParse
);
1852 sqlite3_result_error_code(context
, rc
);
1856 renameParseCleanup(&sParse
);
1857 renameTokenFree(db
, sCtx
.pList
);
1858 sqlite3BtreeLeaveAll(db
);
1859 #ifndef SQLITE_OMIT_AUTHORIZATION
1867 static int renameQuotefixExprCb(Walker
*pWalker
, Expr
*pExpr
){
1868 if( pExpr
->op
==TK_STRING
&& (pExpr
->flags
& EP_DblQuoted
) ){
1869 renameTokenFind(pWalker
->pParse
, pWalker
->u
.pRename
, (const void*)pExpr
);
1871 return WRC_Continue
;
1874 /* SQL function: sqlite_rename_quotefix(DB,SQL)
1876 ** Rewrite the DDL statement "SQL" so that any string literals that use
1877 ** double-quotes use single quotes instead.
1879 ** Two arguments must be passed:
1881 ** 0: Database name ("main", "temp" etc.).
1882 ** 1: SQL statement to edit.
1884 ** The returned value is the modified SQL statement. For example, given
1885 ** the database schema:
1887 ** CREATE TABLE t1(a, b, c);
1889 ** SELECT sqlite_rename_quotefix('main',
1890 ** 'CREATE VIEW v1 AS SELECT "a", "string" FROM t1'
1893 ** returns the string:
1895 ** CREATE VIEW v1 AS SELECT "a", 'string' FROM t1
1897 ** If there is a error in the input SQL, then raise an error, except
1898 ** if PRAGMA writable_schema=ON, then just return the input string
1899 ** unmodified following an error.
1901 static void renameQuotefixFunc(
1902 sqlite3_context
*context
,
1904 sqlite3_value
**argv
1906 sqlite3
*db
= sqlite3_context_db_handle(context
);
1907 char const *zDb
= (const char*)sqlite3_value_text(argv
[0]);
1908 char const *zInput
= (const char*)sqlite3_value_text(argv
[1]);
1910 #ifndef SQLITE_OMIT_AUTHORIZATION
1911 sqlite3_xauth xAuth
= db
->xAuth
;
1915 sqlite3BtreeEnterAll(db
);
1917 UNUSED_PARAMETER(NotUsed
);
1918 if( zDb
&& zInput
){
1921 rc
= renameParseSql(&sParse
, zDb
, db
, zInput
, 0);
1923 if( rc
==SQLITE_OK
){
1927 /* Walker to find tokens that need to be replaced. */
1928 memset(&sCtx
, 0, sizeof(RenameCtx
));
1929 memset(&sWalker
, 0, sizeof(Walker
));
1930 sWalker
.pParse
= &sParse
;
1931 sWalker
.xExprCallback
= renameQuotefixExprCb
;
1932 sWalker
.xSelectCallback
= renameColumnSelectCb
;
1933 sWalker
.u
.pRename
= &sCtx
;
1935 if( sParse
.pNewTable
){
1936 if( IsView(sParse
.pNewTable
) ){
1937 Select
*pSelect
= sParse
.pNewTable
->u
.view
.pSelect
;
1938 pSelect
->selFlags
&= ~SF_View
;
1939 sParse
.rc
= SQLITE_OK
;
1940 sqlite3SelectPrep(&sParse
, pSelect
, 0);
1941 rc
= (db
->mallocFailed
? SQLITE_NOMEM
: sParse
.rc
);
1942 if( rc
==SQLITE_OK
){
1943 sqlite3WalkSelect(&sWalker
, pSelect
);
1947 sqlite3WalkExprList(&sWalker
, sParse
.pNewTable
->pCheck
);
1948 #ifndef SQLITE_OMIT_GENERATED_COLUMNS
1949 for(i
=0; i
<sParse
.pNewTable
->nCol
; i
++){
1950 sqlite3WalkExpr(&sWalker
,
1951 sqlite3ColumnExpr(sParse
.pNewTable
,
1952 &sParse
.pNewTable
->aCol
[i
]));
1954 #endif /* SQLITE_OMIT_GENERATED_COLUMNS */
1956 }else if( sParse
.pNewIndex
){
1957 sqlite3WalkExprList(&sWalker
, sParse
.pNewIndex
->aColExpr
);
1958 sqlite3WalkExpr(&sWalker
, sParse
.pNewIndex
->pPartIdxWhere
);
1960 #ifndef SQLITE_OMIT_TRIGGER
1961 rc
= renameResolveTrigger(&sParse
);
1962 if( rc
==SQLITE_OK
){
1963 renameWalkTrigger(&sWalker
, sParse
.pNewTrigger
);
1965 #endif /* SQLITE_OMIT_TRIGGER */
1968 if( rc
==SQLITE_OK
){
1969 rc
= renameEditSql(context
, &sCtx
, zInput
, 0, 0);
1971 renameTokenFree(db
, sCtx
.pList
);
1973 if( rc
!=SQLITE_OK
){
1974 if( sqlite3WritableSchema(db
) && rc
==SQLITE_ERROR
){
1975 sqlite3_result_value(context
, argv
[1]);
1977 sqlite3_result_error_code(context
, rc
);
1980 renameParseCleanup(&sParse
);
1983 #ifndef SQLITE_OMIT_AUTHORIZATION
1987 sqlite3BtreeLeaveAll(db
);
1990 /* Function: sqlite_rename_test(DB,SQL,TYPE,NAME,ISTEMP,WHEN,DQS)
1992 ** An SQL user function that checks that there are no parse or symbol
1993 ** resolution problems in a CREATE TRIGGER|TABLE|VIEW|INDEX statement.
1994 ** After an ALTER TABLE .. RENAME operation is performed and the schema
1995 ** reloaded, this function is called on each SQL statement in the schema
1996 ** to ensure that it is still usable.
1998 ** 0: Database name ("main", "temp" etc.).
1999 ** 1: SQL statement.
2000 ** 2: Object type ("view", "table", "trigger" or "index").
2002 ** 4: True if object is from temp schema.
2003 ** 5: "when" part of error message.
2004 ** 6: True to disable the DQS quirk when parsing SQL.
2006 ** The return value is computed as follows:
2008 ** A. If an error is seen and not in PRAGMA writable_schema=ON mode,
2009 ** then raise the error.
2010 ** B. Else if a trigger is created and the the table that the trigger is
2011 ** attached to is in database zDb, then return 1.
2012 ** C. Otherwise return NULL.
2014 static void renameTableTest(
2015 sqlite3_context
*context
,
2017 sqlite3_value
**argv
2019 sqlite3
*db
= sqlite3_context_db_handle(context
);
2020 char const *zDb
= (const char*)sqlite3_value_text(argv
[0]);
2021 char const *zInput
= (const char*)sqlite3_value_text(argv
[1]);
2022 int bTemp
= sqlite3_value_int(argv
[4]);
2023 int isLegacy
= (db
->flags
& SQLITE_LegacyAlter
);
2024 char const *zWhen
= (const char*)sqlite3_value_text(argv
[5]);
2025 int bNoDQS
= sqlite3_value_int(argv
[6]);
2027 #ifndef SQLITE_OMIT_AUTHORIZATION
2028 sqlite3_xauth xAuth
= db
->xAuth
;
2032 UNUSED_PARAMETER(NotUsed
);
2034 if( zDb
&& zInput
){
2037 int flags
= db
->flags
;
2038 if( bNoDQS
) db
->flags
&= ~(SQLITE_DqsDML
|SQLITE_DqsDDL
);
2039 rc
= renameParseSql(&sParse
, zDb
, db
, zInput
, bTemp
);
2040 db
->flags
|= (flags
& (SQLITE_DqsDML
|SQLITE_DqsDDL
));
2041 if( rc
==SQLITE_OK
){
2042 if( isLegacy
==0 && sParse
.pNewTable
&& IsView(sParse
.pNewTable
) ){
2044 memset(&sNC
, 0, sizeof(sNC
));
2045 sNC
.pParse
= &sParse
;
2046 sqlite3SelectPrep(&sParse
, sParse
.pNewTable
->u
.view
.pSelect
, &sNC
);
2047 if( sParse
.nErr
) rc
= sParse
.rc
;
2050 else if( sParse
.pNewTrigger
){
2052 rc
= renameResolveTrigger(&sParse
);
2054 if( rc
==SQLITE_OK
){
2055 int i1
= sqlite3SchemaToIndex(db
, sParse
.pNewTrigger
->pTabSchema
);
2056 int i2
= sqlite3FindDbName(db
, zDb
);
2058 /* Handle output case B */
2059 sqlite3_result_int(context
, 1);
2065 if( rc
!=SQLITE_OK
&& zWhen
&& !sqlite3WritableSchema(db
) ){
2067 renameColumnParseError(context
, zWhen
, argv
[2], argv
[3],&sParse
);
2069 renameParseCleanup(&sParse
);
2072 #ifndef SQLITE_OMIT_AUTHORIZATION
2078 ** The implementation of internal UDF sqlite_drop_column().
2082 ** argv[0]: An integer - the index of the schema containing the table
2083 ** argv[1]: CREATE TABLE statement to modify.
2084 ** argv[2]: An integer - the index of the column to remove.
2086 ** The value returned is a string containing the CREATE TABLE statement
2087 ** with column argv[2] removed.
2089 static void dropColumnFunc(
2090 sqlite3_context
*context
,
2092 sqlite3_value
**argv
2094 sqlite3
*db
= sqlite3_context_db_handle(context
);
2095 int iSchema
= sqlite3_value_int(argv
[0]);
2096 const char *zSql
= (const char*)sqlite3_value_text(argv
[1]);
2097 int iCol
= sqlite3_value_int(argv
[2]);
2098 const char *zDb
= db
->aDb
[iSchema
].zDbSName
;
2106 #ifndef SQLITE_OMIT_AUTHORIZATION
2107 sqlite3_xauth xAuth
= db
->xAuth
;
2111 UNUSED_PARAMETER(NotUsed
);
2112 rc
= renameParseSql(&sParse
, zDb
, db
, zSql
, iSchema
==1);
2113 if( rc
!=SQLITE_OK
) goto drop_column_done
;
2114 pTab
= sParse
.pNewTable
;
2115 if( pTab
==0 || pTab
->nCol
==1 || iCol
>=pTab
->nCol
){
2116 /* This can happen if the sqlite_schema table is corrupt */
2117 rc
= SQLITE_CORRUPT_BKPT
;
2118 goto drop_column_done
;
2121 pCol
= renameTokenFind(&sParse
, 0, (void*)pTab
->aCol
[iCol
].zCnName
);
2122 if( iCol
<pTab
->nCol
-1 ){
2124 pEnd
= renameTokenFind(&sParse
, 0, (void*)pTab
->aCol
[iCol
+1].zCnName
);
2125 zEnd
= (const char*)pEnd
->t
.z
;
2127 assert( IsOrdinaryTable(pTab
) );
2128 zEnd
= (const char*)&zSql
[pTab
->u
.tab
.addColOffset
];
2129 while( ALWAYS(pCol
->t
.z
[0]!=0) && pCol
->t
.z
[0]!=',' ) pCol
->t
.z
--;
2132 zNew
= sqlite3MPrintf(db
, "%.*s%s", pCol
->t
.z
-zSql
, zSql
, zEnd
);
2133 sqlite3_result_text(context
, zNew
, -1, SQLITE_TRANSIENT
);
2137 renameParseCleanup(&sParse
);
2138 #ifndef SQLITE_OMIT_AUTHORIZATION
2141 if( rc
!=SQLITE_OK
){
2142 sqlite3_result_error_code(context
, rc
);
2147 ** This function is called by the parser upon parsing an
2149 ** ALTER TABLE pSrc DROP COLUMN pName
2151 ** statement. Argument pSrc contains the possibly qualified name of the
2152 ** table being edited, and token pName the name of the column to drop.
2154 void sqlite3AlterDropColumn(Parse
*pParse
, SrcList
*pSrc
, const Token
*pName
){
2155 sqlite3
*db
= pParse
->db
; /* Database handle */
2156 Table
*pTab
; /* Table to modify */
2157 int iDb
; /* Index of db containing pTab in aDb[] */
2158 const char *zDb
; /* Database containing pTab ("main" etc.) */
2159 char *zCol
= 0; /* Name of column to drop */
2160 int iCol
; /* Index of column zCol in pTab->aCol[] */
2162 /* Look up the table being altered. */
2163 assert( pParse
->pNewTable
==0 );
2164 assert( sqlite3BtreeHoldsAllMutexes(db
) );
2165 if( NEVER(db
->mallocFailed
) ) goto exit_drop_column
;
2166 pTab
= sqlite3LocateTableItem(pParse
, 0, &pSrc
->a
[0]);
2167 if( !pTab
) goto exit_drop_column
;
2169 /* Make sure this is not an attempt to ALTER a view, virtual table or
2171 if( SQLITE_OK
!=isAlterableTable(pParse
, pTab
) ) goto exit_drop_column
;
2172 if( SQLITE_OK
!=isRealTable(pParse
, pTab
, 1) ) goto exit_drop_column
;
2174 /* Find the index of the column being dropped. */
2175 zCol
= sqlite3NameFromToken(db
, pName
);
2177 assert( db
->mallocFailed
);
2178 goto exit_drop_column
;
2180 iCol
= sqlite3ColumnIndex(pTab
, zCol
);
2182 sqlite3ErrorMsg(pParse
, "no such column: \"%T\"", pName
);
2183 goto exit_drop_column
;
2186 /* Do not allow the user to drop a PRIMARY KEY column or a column
2187 ** constrained by a UNIQUE constraint. */
2188 if( pTab
->aCol
[iCol
].colFlags
& (COLFLAG_PRIMKEY
|COLFLAG_UNIQUE
) ){
2189 sqlite3ErrorMsg(pParse
, "cannot drop %s column: \"%s\"",
2190 (pTab
->aCol
[iCol
].colFlags
&COLFLAG_PRIMKEY
) ? "PRIMARY KEY" : "UNIQUE",
2193 goto exit_drop_column
;
2196 /* Do not allow the number of columns to go to zero */
2197 if( pTab
->nCol
<=1 ){
2198 sqlite3ErrorMsg(pParse
, "cannot drop column \"%s\": no other columns exist",zCol
);
2199 goto exit_drop_column
;
2202 /* Edit the sqlite_schema table */
2203 iDb
= sqlite3SchemaToIndex(db
, pTab
->pSchema
);
2205 zDb
= db
->aDb
[iDb
].zDbSName
;
2206 #ifndef SQLITE_OMIT_AUTHORIZATION
2207 /* Invoke the authorization callback. */
2208 if( sqlite3AuthCheck(pParse
, SQLITE_ALTER_TABLE
, zDb
, pTab
->zName
, zCol
) ){
2209 goto exit_drop_column
;
2212 renameTestSchema(pParse
, zDb
, iDb
==1, "", 0);
2213 renameFixQuotes(pParse
, zDb
, iDb
==1);
2214 sqlite3NestedParse(pParse
,
2215 "UPDATE \"%w\"." LEGACY_SCHEMA_TABLE
" SET "
2216 "sql = sqlite_drop_column(%d, sql, %d) "
2217 "WHERE (type=='table' AND tbl_name=%Q COLLATE nocase)"
2218 , zDb
, iDb
, iCol
, pTab
->zName
2221 /* Drop and reload the database schema. */
2222 renameReloadSchema(pParse
, iDb
, INITFLAG_AlterDrop
);
2223 renameTestSchema(pParse
, zDb
, iDb
==1, "after drop column", 1);
2225 /* Edit rows of table on disk */
2226 if( pParse
->nErr
==0 && (pTab
->aCol
[iCol
].colFlags
& COLFLAG_VIRTUAL
)==0 ){
2232 int nField
= 0; /* Number of non-virtual columns after drop */
2234 Vdbe
*v
= sqlite3GetVdbe(pParse
);
2235 iCur
= pParse
->nTab
++;
2236 sqlite3OpenTable(pParse
, iCur
, iDb
, pTab
, OP_OpenWrite
);
2237 addr
= sqlite3VdbeAddOp1(v
, OP_Rewind
, iCur
); VdbeCoverage(v
);
2238 reg
= ++pParse
->nMem
;
2239 if( HasRowid(pTab
) ){
2240 sqlite3VdbeAddOp2(v
, OP_Rowid
, iCur
, reg
);
2241 pParse
->nMem
+= pTab
->nCol
;
2243 pPk
= sqlite3PrimaryKeyIndex(pTab
);
2244 pParse
->nMem
+= pPk
->nColumn
;
2245 for(i
=0; i
<pPk
->nKeyCol
; i
++){
2246 sqlite3VdbeAddOp3(v
, OP_Column
, iCur
, i
, reg
+i
+1);
2248 nField
= pPk
->nKeyCol
;
2250 regRec
= ++pParse
->nMem
;
2251 for(i
=0; i
<pTab
->nCol
; i
++){
2252 if( i
!=iCol
&& (pTab
->aCol
[i
].colFlags
& COLFLAG_VIRTUAL
)==0 ){
2255 int iPos
= sqlite3TableColumnToIndex(pPk
, i
);
2256 int iColPos
= sqlite3TableColumnToIndex(pPk
, iCol
);
2257 if( iPos
<pPk
->nKeyCol
) continue;
2258 regOut
= reg
+1+iPos
-(iPos
>iColPos
);
2260 regOut
= reg
+1+nField
;
2262 if( i
==pTab
->iPKey
){
2263 sqlite3VdbeAddOp2(v
, OP_Null
, 0, regOut
);
2265 sqlite3ExprCodeGetColumnOfTable(v
, pTab
, iCur
, i
, regOut
);
2271 /* dbsqlfuzz 5f09e7bcc78b4954d06bf9f2400d7715f48d1fef */
2273 sqlite3VdbeAddOp2(v
, OP_Null
, 0, reg
+1);
2276 sqlite3VdbeAddOp3(v
, OP_MakeRecord
, reg
+1, nField
, regRec
);
2278 sqlite3VdbeAddOp4Int(v
, OP_IdxInsert
, iCur
, regRec
, reg
+1, pPk
->nKeyCol
);
2280 sqlite3VdbeAddOp3(v
, OP_Insert
, iCur
, regRec
, reg
);
2282 sqlite3VdbeChangeP5(v
, OPFLAG_SAVEPOSITION
);
2284 sqlite3VdbeAddOp2(v
, OP_Next
, iCur
, addr
+1); VdbeCoverage(v
);
2285 sqlite3VdbeJumpHere(v
, addr
);
2289 sqlite3DbFree(db
, zCol
);
2290 sqlite3SrcListDelete(db
, pSrc
);
2294 ** Register built-in functions used to help implement ALTER TABLE
2296 void sqlite3AlterFunctions(void){
2297 static FuncDef aAlterTableFuncs
[] = {
2298 INTERNAL_FUNCTION(sqlite_rename_column
, 9, renameColumnFunc
),
2299 INTERNAL_FUNCTION(sqlite_rename_table
, 7, renameTableFunc
),
2300 INTERNAL_FUNCTION(sqlite_rename_test
, 7, renameTableTest
),
2301 INTERNAL_FUNCTION(sqlite_drop_column
, 3, dropColumnFunc
),
2302 INTERNAL_FUNCTION(sqlite_rename_quotefix
,2, renameQuotefixFunc
),
2304 sqlite3InsertBuiltinFuncs(aAlterTableFuncs
, ArraySize(aAlterTableFuncs
));
2306 #endif /* SQLITE_ALTER_TABLE */