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\"." DFLT_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." DFLT_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\"." DFLT_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." DFLT_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() */
138 u32 savedDbFlags
; /* Saved value of db->mDbFlags */
140 savedDbFlags
= db
->mDbFlags
;
141 if( NEVER(db
->mallocFailed
) ) goto exit_rename_table
;
142 assert( pSrc
->nSrc
==1 );
143 assert( sqlite3BtreeHoldsAllMutexes(pParse
->db
) );
145 pTab
= sqlite3LocateTableItem(pParse
, 0, &pSrc
->a
[0]);
146 if( !pTab
) goto exit_rename_table
;
147 iDb
= sqlite3SchemaToIndex(pParse
->db
, pTab
->pSchema
);
148 zDb
= db
->aDb
[iDb
].zDbSName
;
149 db
->mDbFlags
|= DBFLAG_PreferBuiltin
;
151 /* Get a NULL terminated version of the new table name. */
152 zName
= sqlite3NameFromToken(db
, pName
);
153 if( !zName
) goto exit_rename_table
;
155 /* Check that a table or index named 'zName' does not already exist
156 ** in database iDb. If so, this is an error.
158 if( sqlite3FindTable(db
, zName
, zDb
)
159 || sqlite3FindIndex(db
, zName
, zDb
)
160 || sqlite3IsShadowTableOf(db
, pTab
, zName
)
162 sqlite3ErrorMsg(pParse
,
163 "there is already another table or index with this name: %s", zName
);
164 goto exit_rename_table
;
167 /* Make sure it is not a system table being altered, or a reserved name
168 ** that the table is being renamed to.
170 if( SQLITE_OK
!=isAlterableTable(pParse
, pTab
) ){
171 goto exit_rename_table
;
173 if( SQLITE_OK
!=sqlite3CheckObjectName(pParse
,zName
,"table",zName
) ){
174 goto exit_rename_table
;
177 #ifndef SQLITE_OMIT_VIEW
179 sqlite3ErrorMsg(pParse
, "view %s may not be altered", pTab
->zName
);
180 goto exit_rename_table
;
184 #ifndef SQLITE_OMIT_AUTHORIZATION
185 /* Invoke the authorization callback. */
186 if( sqlite3AuthCheck(pParse
, SQLITE_ALTER_TABLE
, zDb
, pTab
->zName
, 0) ){
187 goto exit_rename_table
;
191 #ifndef SQLITE_OMIT_VIRTUALTABLE
192 if( sqlite3ViewGetColumnNames(pParse
, pTab
) ){
193 goto exit_rename_table
;
195 if( IsVirtual(pTab
) ){
196 pVTab
= sqlite3GetVTable(db
, pTab
);
197 if( pVTab
->pVtab
->pModule
->xRename
==0 ){
203 /* Begin a transaction for database iDb. Then modify the schema cookie
204 ** (since the ALTER TABLE modifies the schema). Call sqlite3MayAbort(),
205 ** as the scalar functions (e.g. sqlite_rename_table()) invoked by the
206 ** nested SQL may raise an exception. */
207 v
= sqlite3GetVdbe(pParse
);
209 goto exit_rename_table
;
211 sqlite3MayAbort(pParse
);
213 /* figure out how many UTF-8 characters are in zName */
214 zTabName
= pTab
->zName
;
215 nTabName
= sqlite3Utf8CharLen(zTabName
, -1);
217 /* Rewrite all CREATE TABLE, INDEX, TRIGGER or VIEW statements in
218 ** the schema to use the new table name. */
219 sqlite3NestedParse(pParse
,
220 "UPDATE \"%w\"." DFLT_SCHEMA_TABLE
" SET "
221 "sql = sqlite_rename_table(%Q, type, name, sql, %Q, %Q, %d) "
222 "WHERE (type!='index' OR tbl_name=%Q COLLATE nocase)"
223 "AND name NOT LIKE 'sqliteX_%%' ESCAPE 'X'"
224 , zDb
, zDb
, zTabName
, zName
, (iDb
==1), zTabName
227 /* Update the tbl_name and name columns of the sqlite_schema table
229 sqlite3NestedParse(pParse
,
230 "UPDATE %Q." DFLT_SCHEMA_TABLE
" SET "
233 "WHEN type='table' THEN %Q "
234 "WHEN name LIKE 'sqliteX_autoindex%%' ESCAPE 'X' "
235 " AND type='index' THEN "
236 "'sqlite_autoindex_' || %Q || substr(name,%d+18) "
238 "WHERE tbl_name=%Q COLLATE nocase AND "
239 "(type='table' OR type='index' OR type='trigger');",
245 #ifndef SQLITE_OMIT_AUTOINCREMENT
246 /* If the sqlite_sequence table exists in this database, then update
247 ** it with the new table name.
249 if( sqlite3FindTable(db
, "sqlite_sequence", zDb
) ){
250 sqlite3NestedParse(pParse
,
251 "UPDATE \"%w\".sqlite_sequence set name = %Q WHERE name = %Q",
252 zDb
, zName
, pTab
->zName
);
256 /* If the table being renamed is not itself part of the temp database,
257 ** edit view and trigger definitions within the temp database
260 sqlite3NestedParse(pParse
,
261 "UPDATE sqlite_temp_schema SET "
262 "sql = sqlite_rename_table(%Q, type, name, sql, %Q, %Q, 1), "
264 "CASE WHEN tbl_name=%Q COLLATE nocase AND "
265 " sqlite_rename_test(%Q, sql, type, name, 1, 'after rename', 0) "
266 "THEN %Q ELSE tbl_name END "
267 "WHERE type IN ('view', 'trigger')"
268 , zDb
, zTabName
, zName
, zTabName
, zDb
, zName
);
271 /* If this is a virtual table, invoke the xRename() function if
272 ** one is defined. The xRename() callback will modify the names
273 ** of any resources used by the v-table implementation (including other
274 ** SQLite tables) that are identified by the name of the virtual table.
276 #ifndef SQLITE_OMIT_VIRTUALTABLE
278 int i
= ++pParse
->nMem
;
279 sqlite3VdbeLoadString(v
, i
, zName
);
280 sqlite3VdbeAddOp4(v
, OP_VRename
, i
, 0, 0,(const char*)pVTab
, P4_VTAB
);
284 renameReloadSchema(pParse
, iDb
, INITFLAG_AlterRename
);
285 renameTestSchema(pParse
, zDb
, iDb
==1, "after rename", 0);
288 sqlite3SrcListDelete(db
, pSrc
);
289 sqlite3DbFree(db
, zName
);
290 db
->mDbFlags
= savedDbFlags
;
294 ** Write code that will raise an error if the table described by
295 ** zDb and zTab is not empty.
297 static void sqlite3ErrorIfNotEmpty(
298 Parse
*pParse
, /* Parsing context */
299 const char *zDb
, /* Schema holding the table */
300 const char *zTab
, /* Table to check for empty */
301 const char *zErr
/* Error message text */
303 sqlite3NestedParse(pParse
,
304 "SELECT raise(ABORT,%Q) FROM \"%w\".\"%w\"",
310 ** This function is called after an "ALTER TABLE ... ADD" statement
311 ** has been parsed. Argument pColDef contains the text of the new
312 ** column definition.
314 ** The Table structure pParse->pNewTable was extended to include
315 ** the new column during parsing.
317 void sqlite3AlterFinishAddColumn(Parse
*pParse
, Token
*pColDef
){
318 Table
*pNew
; /* Copy of pParse->pNewTable */
319 Table
*pTab
; /* Table being altered */
320 int iDb
; /* Database number */
321 const char *zDb
; /* Database name */
322 const char *zTab
; /* Table name */
323 char *zCol
; /* Null-terminated column definition */
324 Column
*pCol
; /* The new column */
325 Expr
*pDflt
; /* Default value for the new column */
326 sqlite3
*db
; /* The database connection; */
327 Vdbe
*v
; /* The prepared statement under construction */
328 int r1
; /* Temporary registers */
331 if( pParse
->nErr
|| db
->mallocFailed
) return;
332 pNew
= pParse
->pNewTable
;
335 assert( sqlite3BtreeHoldsAllMutexes(db
) );
336 iDb
= sqlite3SchemaToIndex(db
, pNew
->pSchema
);
337 zDb
= db
->aDb
[iDb
].zDbSName
;
338 zTab
= &pNew
->zName
[16]; /* Skip the "sqlite_altertab_" prefix on the name */
339 pCol
= &pNew
->aCol
[pNew
->nCol
-1];
341 pTab
= sqlite3FindTable(db
, zTab
, zDb
);
344 #ifndef SQLITE_OMIT_AUTHORIZATION
345 /* Invoke the authorization callback. */
346 if( sqlite3AuthCheck(pParse
, SQLITE_ALTER_TABLE
, zDb
, pTab
->zName
, 0) ){
352 /* Check that the new column is not specified as PRIMARY KEY or UNIQUE.
353 ** If there is a NOT NULL constraint, then the default value for the
354 ** column must not be NULL.
356 if( pCol
->colFlags
& COLFLAG_PRIMKEY
){
357 sqlite3ErrorMsg(pParse
, "Cannot add a PRIMARY KEY column");
361 sqlite3ErrorMsg(pParse
,
362 "Cannot add a UNIQUE column");
365 if( (pCol
->colFlags
& COLFLAG_GENERATED
)==0 ){
366 /* If the default value for the new column was specified with a
367 ** literal NULL, then set pDflt to 0. This simplifies checking
368 ** for an SQL NULL default below.
370 assert( pDflt
==0 || pDflt
->op
==TK_SPAN
);
371 if( pDflt
&& pDflt
->pLeft
->op
==TK_NULL
){
374 if( (db
->flags
&SQLITE_ForeignKeys
) && pNew
->pFKey
&& pDflt
){
375 sqlite3ErrorIfNotEmpty(pParse
, zDb
, zTab
,
376 "Cannot add a REFERENCES column with non-NULL default value");
378 if( pCol
->notNull
&& !pDflt
){
379 sqlite3ErrorIfNotEmpty(pParse
, zDb
, zTab
,
380 "Cannot add a NOT NULL column with default value NULL");
384 /* Ensure the default expression is something that sqlite3ValueFromExpr()
385 ** can handle (i.e. not CURRENT_TIME etc.)
388 sqlite3_value
*pVal
= 0;
390 rc
= sqlite3ValueFromExpr(db
, pDflt
, SQLITE_UTF8
, SQLITE_AFF_BLOB
, &pVal
);
391 assert( rc
==SQLITE_OK
|| rc
==SQLITE_NOMEM
);
393 assert( db
->mallocFailed
== 1 );
397 sqlite3ErrorIfNotEmpty(pParse
, zDb
, zTab
,
398 "Cannot add a column with non-constant default");
400 sqlite3ValueFree(pVal
);
402 }else if( pCol
->colFlags
& COLFLAG_STORED
){
403 sqlite3ErrorIfNotEmpty(pParse
, zDb
, zTab
, "cannot add a STORED column");
407 /* Modify the CREATE TABLE statement. */
408 zCol
= sqlite3DbStrNDup(db
, (char*)pColDef
->z
, pColDef
->n
);
410 char *zEnd
= &zCol
[pColDef
->n
-1];
411 u32 savedDbFlags
= db
->mDbFlags
;
412 while( zEnd
>zCol
&& (*zEnd
==';' || sqlite3Isspace(*zEnd
)) ){
415 db
->mDbFlags
|= DBFLAG_PreferBuiltin
;
416 /* substr() operations on characters, but addColOffset is in bytes. So we
417 ** have to use printf() to translate between these units: */
418 sqlite3NestedParse(pParse
,
419 "UPDATE \"%w\"." DFLT_SCHEMA_TABLE
" SET "
420 "sql = printf('%%.%ds, ',sql) || %Q"
421 " || substr(sql,1+length(printf('%%.%ds',sql))) "
422 "WHERE type = 'table' AND name = %Q",
423 zDb
, pNew
->addColOffset
, zCol
, pNew
->addColOffset
,
426 sqlite3DbFree(db
, zCol
);
427 db
->mDbFlags
= savedDbFlags
;
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 v
= sqlite3GetVdbe(pParse
);
436 r1
= sqlite3GetTempReg(pParse
);
437 sqlite3VdbeAddOp3(v
, OP_ReadCookie
, iDb
, r1
, BTREE_FILE_FORMAT
);
438 sqlite3VdbeUsesBtree(v
, iDb
);
439 sqlite3VdbeAddOp2(v
, OP_AddImm
, r1
, -2);
440 sqlite3VdbeAddOp2(v
, OP_IfPos
, r1
, sqlite3VdbeCurrentAddr(v
)+2);
442 sqlite3VdbeAddOp3(v
, OP_SetCookie
, iDb
, BTREE_FILE_FORMAT
, 3);
443 sqlite3ReleaseTempReg(pParse
, r1
);
446 /* Reload the table definition */
447 renameReloadSchema(pParse
, iDb
, INITFLAG_AlterRename
);
451 ** This function is called by the parser after the table-name in
452 ** an "ALTER TABLE <table-name> ADD" statement is parsed. Argument
453 ** pSrc is the full-name of the table being altered.
455 ** This routine makes a (partial) copy of the Table structure
456 ** for the table being altered and sets Parse.pNewTable to point
457 ** to it. Routines called by the parser as the column definition
458 ** is parsed (i.e. sqlite3AddColumn()) add the new Column data to
459 ** the copy. The copy of the Table structure is deleted by tokenize.c
460 ** after parsing is finished.
462 ** Routine sqlite3AlterFinishAddColumn() will be called to complete
463 ** coding the "ALTER TABLE ... ADD" statement.
465 void sqlite3AlterBeginAddColumn(Parse
*pParse
, SrcList
*pSrc
){
471 sqlite3
*db
= pParse
->db
;
473 /* Look up the table being altered. */
474 assert( pParse
->pNewTable
==0 );
475 assert( sqlite3BtreeHoldsAllMutexes(db
) );
476 if( db
->mallocFailed
) goto exit_begin_add_column
;
477 pTab
= sqlite3LocateTableItem(pParse
, 0, &pSrc
->a
[0]);
478 if( !pTab
) goto exit_begin_add_column
;
480 #ifndef SQLITE_OMIT_VIRTUALTABLE
481 if( IsVirtual(pTab
) ){
482 sqlite3ErrorMsg(pParse
, "virtual tables may not be altered");
483 goto exit_begin_add_column
;
487 /* Make sure this is not an attempt to ALTER a view. */
489 sqlite3ErrorMsg(pParse
, "Cannot add a column to a view");
490 goto exit_begin_add_column
;
492 if( SQLITE_OK
!=isAlterableTable(pParse
, pTab
) ){
493 goto exit_begin_add_column
;
496 sqlite3MayAbort(pParse
);
497 assert( pTab
->addColOffset
>0 );
498 iDb
= sqlite3SchemaToIndex(db
, pTab
->pSchema
);
500 /* Put a copy of the Table struct in Parse.pNewTable for the
501 ** sqlite3AddColumn() function and friends to modify. But modify
502 ** the name by adding an "sqlite_altertab_" prefix. By adding this
503 ** prefix, we insure that the name will not collide with an existing
504 ** table because user table are not allowed to have the "sqlite_"
505 ** prefix on their name.
507 pNew
= (Table
*)sqlite3DbMallocZero(db
, sizeof(Table
));
508 if( !pNew
) goto exit_begin_add_column
;
509 pParse
->pNewTable
= pNew
;
511 pNew
->nCol
= pTab
->nCol
;
512 assert( pNew
->nCol
>0 );
513 nAlloc
= (((pNew
->nCol
-1)/8)*8)+8;
514 assert( nAlloc
>=pNew
->nCol
&& nAlloc
%8==0 && nAlloc
-pNew
->nCol
<8 );
515 pNew
->aCol
= (Column
*)sqlite3DbMallocZero(db
, sizeof(Column
)*nAlloc
);
516 pNew
->zName
= sqlite3MPrintf(db
, "sqlite_altertab_%s", pTab
->zName
);
517 if( !pNew
->aCol
|| !pNew
->zName
){
518 assert( db
->mallocFailed
);
519 goto exit_begin_add_column
;
521 memcpy(pNew
->aCol
, pTab
->aCol
, sizeof(Column
)*pNew
->nCol
);
522 for(i
=0; i
<pNew
->nCol
; i
++){
523 Column
*pCol
= &pNew
->aCol
[i
];
524 pCol
->zName
= sqlite3DbStrDup(db
, pCol
->zName
);
525 pCol
->hName
= sqlite3StrIHash(pCol
->zName
);
529 pNew
->pSchema
= db
->aDb
[iDb
].pSchema
;
530 pNew
->addColOffset
= pTab
->addColOffset
;
533 exit_begin_add_column
:
534 sqlite3SrcListDelete(db
, pSrc
);
539 ** Parameter pTab is the subject of an ALTER TABLE ... RENAME COLUMN
540 ** command. This function checks if the table is a view or virtual
541 ** table (columns of views or virtual tables may not be renamed). If so,
542 ** it loads an error message into pParse and returns non-zero.
544 ** Or, if pTab is not a view or virtual table, zero is returned.
546 #if !defined(SQLITE_OMIT_VIEW) || !defined(SQLITE_OMIT_VIRTUALTABLE)
547 static int isRealTable(Parse
*pParse
, Table
*pTab
, int bDrop
){
548 const char *zType
= 0;
549 #ifndef SQLITE_OMIT_VIEW
554 #ifndef SQLITE_OMIT_VIRTUALTABLE
555 if( IsVirtual(pTab
) ){
556 zType
= "virtual table";
560 sqlite3ErrorMsg(pParse
, "cannot %s %s \"%s\"",
561 (bDrop
? "drop column from" : "rename columns of"),
568 #else /* !defined(SQLITE_OMIT_VIEW) || !defined(SQLITE_OMIT_VIRTUALTABLE) */
569 # define isRealTable(x,y,z) (0)
573 ** Handles the following parser reduction:
575 ** cmd ::= ALTER TABLE pSrc RENAME COLUMN pOld TO pNew
577 void sqlite3AlterRenameColumn(
578 Parse
*pParse
, /* Parsing context */
579 SrcList
*pSrc
, /* Table being altered. pSrc->nSrc==1 */
580 Token
*pOld
, /* Name of column being changed */
581 Token
*pNew
/* New column name */
583 sqlite3
*db
= pParse
->db
; /* Database connection */
584 Table
*pTab
; /* Table being updated */
585 int iCol
; /* Index of column being renamed */
586 char *zOld
= 0; /* Old column name */
587 char *zNew
= 0; /* New column name */
588 const char *zDb
; /* Name of schema containing the table */
589 int iSchema
; /* Index of the schema */
590 int bQuote
; /* True to quote the new name */
592 /* Locate the table to be altered */
593 pTab
= sqlite3LocateTableItem(pParse
, 0, &pSrc
->a
[0]);
594 if( !pTab
) goto exit_rename_column
;
596 /* Cannot alter a system table */
597 if( SQLITE_OK
!=isAlterableTable(pParse
, pTab
) ) goto exit_rename_column
;
598 if( SQLITE_OK
!=isRealTable(pParse
, pTab
, 0) ) goto exit_rename_column
;
600 /* Which schema holds the table to be altered */
601 iSchema
= sqlite3SchemaToIndex(db
, pTab
->pSchema
);
602 assert( iSchema
>=0 );
603 zDb
= db
->aDb
[iSchema
].zDbSName
;
605 #ifndef SQLITE_OMIT_AUTHORIZATION
606 /* Invoke the authorization callback. */
607 if( sqlite3AuthCheck(pParse
, SQLITE_ALTER_TABLE
, zDb
, pTab
->zName
, 0) ){
608 goto exit_rename_column
;
612 /* Make sure the old name really is a column name in the table to be
613 ** altered. Set iCol to be the index of the column being renamed */
614 zOld
= sqlite3NameFromToken(db
, pOld
);
615 if( !zOld
) goto exit_rename_column
;
616 for(iCol
=0; iCol
<pTab
->nCol
; iCol
++){
617 if( 0==sqlite3StrICmp(pTab
->aCol
[iCol
].zName
, zOld
) ) break;
619 if( iCol
==pTab
->nCol
){
620 sqlite3ErrorMsg(pParse
, "no such column: \"%s\"", zOld
);
621 goto exit_rename_column
;
624 /* Ensure the schema contains no double-quoted strings */
625 renameTestSchema(pParse
, zDb
, iSchema
==1, "", 0);
626 renameFixQuotes(pParse
, zDb
, iSchema
==1);
628 /* Do the rename operation using a recursive UPDATE statement that
629 ** uses the sqlite_rename_column() SQL function to compute the new
630 ** CREATE statement text for the sqlite_schema table.
632 sqlite3MayAbort(pParse
);
633 zNew
= sqlite3NameFromToken(db
, pNew
);
634 if( !zNew
) goto exit_rename_column
;
636 bQuote
= sqlite3Isquote(pNew
->z
[0]);
637 sqlite3NestedParse(pParse
,
638 "UPDATE \"%w\"." DFLT_SCHEMA_TABLE
" SET "
639 "sql = sqlite_rename_column(sql, type, name, %Q, %Q, %d, %Q, %d, %d) "
640 "WHERE name NOT LIKE 'sqliteX_%%' ESCAPE 'X' "
641 " AND (type != 'index' OR tbl_name = %Q)"
642 " AND sql NOT LIKE 'create virtual%%'",
644 zDb
, pTab
->zName
, iCol
, zNew
, bQuote
, iSchema
==1,
648 sqlite3NestedParse(pParse
,
649 "UPDATE temp." DFLT_SCHEMA_TABLE
" SET "
650 "sql = sqlite_rename_column(sql, type, name, %Q, %Q, %d, %Q, %d, 1) "
651 "WHERE type IN ('trigger', 'view')",
652 zDb
, pTab
->zName
, iCol
, zNew
, bQuote
655 /* Drop and reload the database schema. */
656 renameReloadSchema(pParse
, iSchema
, INITFLAG_AlterRename
);
657 renameTestSchema(pParse
, zDb
, iSchema
==1, "after rename", 1);
660 sqlite3SrcListDelete(db
, pSrc
);
661 sqlite3DbFree(db
, zOld
);
662 sqlite3DbFree(db
, zNew
);
667 ** Each RenameToken object maps an element of the parse tree into
668 ** the token that generated that element. The parse tree element
671 ** * A pointer to an Expr that represents an ID
672 ** * The name of a table column in Column.zName
674 ** A list of RenameToken objects can be constructed during parsing.
675 ** Each new object is created by sqlite3RenameTokenMap().
676 ** As the parse tree is transformed, the sqlite3RenameTokenRemap()
677 ** routine is used to keep the mapping current.
679 ** After the parse finishes, renameTokenFind() routine can be used
680 ** to look up the actual token value that created some element in
684 void *p
; /* Parse tree element created by token t */
685 Token t
; /* The token that created parse tree element p */
686 RenameToken
*pNext
; /* Next is a list of all RenameToken objects */
690 ** The context of an ALTER TABLE RENAME COLUMN operation that gets passed
691 ** down into the Walker.
693 typedef struct RenameCtx RenameCtx
;
695 RenameToken
*pList
; /* List of tokens to overwrite */
696 int nList
; /* Number of tokens in pList */
697 int iCol
; /* Index of column being renamed */
698 Table
*pTab
; /* Table being ALTERed */
699 const char *zOld
; /* Old column name */
704 ** This function is only for debugging. It performs two tasks:
706 ** 1. Checks that pointer pPtr does not already appear in the
707 ** rename-token list.
709 ** 2. Dereferences each pointer in the rename-token list.
711 ** The second is most effective when debugging under valgrind or
712 ** address-sanitizer or similar. If any of these pointers no longer
713 ** point to valid objects, an exception is raised by the memory-checking
716 ** The point of this is to prevent comparisons of invalid pointer values.
717 ** Even though this always seems to work, it is undefined according to the
718 ** C standard. Example of undefined comparison:
723 ** Technically, as x no longer points into a valid object or to the byte
724 ** following a valid object, it may not be used in comparison operations.
726 static void renameTokenCheckAll(Parse
*pParse
, void *pPtr
){
727 if( pParse
->nErr
==0 && pParse
->db
->mallocFailed
==0 ){
730 for(p
=pParse
->pRename
; p
; p
=p
->pNext
){
732 assert( p
->p
!=pPtr
);
739 # define renameTokenCheckAll(x,y)
743 ** Remember that the parser tree element pPtr was created using
746 ** In other words, construct a new RenameToken object and add it
747 ** to the list of RenameToken objects currently being built up
748 ** in pParse->pRename.
750 ** The pPtr argument is returned so that this routine can be used
751 ** with tail recursion in tokenExpr() routine, for a small performance
754 void *sqlite3RenameTokenMap(Parse
*pParse
, void *pPtr
, Token
*pToken
){
756 assert( pPtr
|| pParse
->db
->mallocFailed
);
757 renameTokenCheckAll(pParse
, pPtr
);
758 if( ALWAYS(pParse
->eParseMode
!=PARSE_MODE_UNMAP
) ){
759 pNew
= sqlite3DbMallocZero(pParse
->db
, sizeof(RenameToken
));
763 pNew
->pNext
= pParse
->pRename
;
764 pParse
->pRename
= pNew
;
772 ** It is assumed that there is already a RenameToken object associated
773 ** with parse tree element pFrom. This function remaps the associated token
774 ** to parse tree element pTo.
776 void sqlite3RenameTokenRemap(Parse
*pParse
, void *pTo
, void *pFrom
){
778 renameTokenCheckAll(pParse
, pTo
);
779 for(p
=pParse
->pRename
; p
; p
=p
->pNext
){
788 ** Walker callback used by sqlite3RenameExprUnmap().
790 static int renameUnmapExprCb(Walker
*pWalker
, Expr
*pExpr
){
791 Parse
*pParse
= pWalker
->pParse
;
792 sqlite3RenameTokenRemap(pParse
, 0, (void*)pExpr
);
797 ** Iterate through the Select objects that are part of WITH clauses attached
798 ** to select statement pSelect.
800 static void renameWalkWith(Walker
*pWalker
, Select
*pSelect
){
801 With
*pWith
= pSelect
->pWith
;
803 Parse
*pParse
= pWalker
->pParse
;
806 assert( pWith
->nCte
>0 );
807 if( (pWith
->a
[0].pSelect
->selFlags
& SF_Expanded
)==0 ){
808 /* Push a copy of the With object onto the with-stack. We use a copy
809 ** here as the original will be expanded and resolved (flags SF_Expanded
810 ** and SF_Resolved) below. And the parser code that uses the with-stack
811 ** fails if the Select objects on it have already been expanded and
813 pCopy
= sqlite3WithDup(pParse
->db
, pWith
);
814 pCopy
= sqlite3WithPush(pParse
, pCopy
, 1);
816 for(i
=0; i
<pWith
->nCte
; i
++){
817 Select
*p
= pWith
->a
[i
].pSelect
;
819 memset(&sNC
, 0, sizeof(sNC
));
821 if( pCopy
) sqlite3SelectPrep(sNC
.pParse
, p
, &sNC
);
822 sqlite3WalkSelect(pWalker
, p
);
823 sqlite3RenameExprlistUnmap(pParse
, pWith
->a
[i
].pCols
);
825 if( pCopy
&& pParse
->pWith
==pCopy
){
826 pParse
->pWith
= pCopy
->pOuter
;
832 ** Unmap all tokens in the IdList object passed as the second argument.
834 static void unmapColumnIdlistNames(
840 for(ii
=0; ii
<pIdList
->nId
; ii
++){
841 sqlite3RenameTokenRemap(pParse
, 0, (void*)pIdList
->a
[ii
].zName
);
847 ** Walker callback used by sqlite3RenameExprUnmap().
849 static int renameUnmapSelectCb(Walker
*pWalker
, Select
*p
){
850 Parse
*pParse
= pWalker
->pParse
;
852 if( pParse
->nErr
) return WRC_Abort
;
853 if( p
->selFlags
& (SF_View
|SF_CopyCte
) ){
854 testcase( p
->selFlags
& SF_View
);
855 testcase( p
->selFlags
& SF_CopyCte
);
858 if( ALWAYS(p
->pEList
) ){
859 ExprList
*pList
= p
->pEList
;
860 for(i
=0; i
<pList
->nExpr
; i
++){
861 if( pList
->a
[i
].zEName
&& pList
->a
[i
].eEName
==ENAME_NAME
){
862 sqlite3RenameTokenRemap(pParse
, 0, (void*)pList
->a
[i
].zEName
);
866 if( ALWAYS(p
->pSrc
) ){ /* Every Select as a SrcList, even if it is empty */
867 SrcList
*pSrc
= p
->pSrc
;
868 for(i
=0; i
<pSrc
->nSrc
; i
++){
869 sqlite3RenameTokenRemap(pParse
, 0, (void*)pSrc
->a
[i
].zName
);
870 if( sqlite3WalkExpr(pWalker
, pSrc
->a
[i
].pOn
) ) return WRC_Abort
;
871 unmapColumnIdlistNames(pParse
, pSrc
->a
[i
].pUsing
);
875 renameWalkWith(pWalker
, p
);
880 ** Remove all nodes that are part of expression pExpr from the rename list.
882 void sqlite3RenameExprUnmap(Parse
*pParse
, Expr
*pExpr
){
883 u8 eMode
= pParse
->eParseMode
;
885 memset(&sWalker
, 0, sizeof(Walker
));
886 sWalker
.pParse
= pParse
;
887 sWalker
.xExprCallback
= renameUnmapExprCb
;
888 sWalker
.xSelectCallback
= renameUnmapSelectCb
;
889 pParse
->eParseMode
= PARSE_MODE_UNMAP
;
890 sqlite3WalkExpr(&sWalker
, pExpr
);
891 pParse
->eParseMode
= eMode
;
895 ** Remove all nodes that are part of expression-list pEList from the
898 void sqlite3RenameExprlistUnmap(Parse
*pParse
, ExprList
*pEList
){
902 memset(&sWalker
, 0, sizeof(Walker
));
903 sWalker
.pParse
= pParse
;
904 sWalker
.xExprCallback
= renameUnmapExprCb
;
905 sqlite3WalkExprList(&sWalker
, pEList
);
906 for(i
=0; i
<pEList
->nExpr
; i
++){
907 if( ALWAYS(pEList
->a
[i
].eEName
==ENAME_NAME
) ){
908 sqlite3RenameTokenRemap(pParse
, 0, (void*)pEList
->a
[i
].zEName
);
915 ** Free the list of RenameToken objects given in the second argument
917 static void renameTokenFree(sqlite3
*db
, RenameToken
*pToken
){
920 for(p
=pToken
; p
; p
=pNext
){
922 sqlite3DbFree(db
, p
);
927 ** Search the Parse object passed as the first argument for a RenameToken
928 ** object associated with parse tree element pPtr. If found, return a pointer
929 ** to it. Otherwise, return NULL.
931 ** If the second argument passed to this function is not NULL and a matching
932 ** RenameToken object is found, remove it from the Parse object and add it to
933 ** the list maintained by the RenameCtx object.
935 static RenameToken
*renameTokenFind(
937 struct RenameCtx
*pCtx
,
941 if( NEVER(pPtr
==0) ){
944 for(pp
=&pParse
->pRename
; (*pp
); pp
=&(*pp
)->pNext
){
945 if( (*pp
)->p
==pPtr
){
946 RenameToken
*pToken
= *pp
;
949 pToken
->pNext
= pCtx
->pList
;
950 pCtx
->pList
= pToken
;
960 ** This is a Walker select callback. It does nothing. It is only required
961 ** because without a dummy callback, sqlite3WalkExpr() and similar do not
962 ** descend into sub-select statements.
964 static int renameColumnSelectCb(Walker
*pWalker
, Select
*p
){
965 if( p
->selFlags
& (SF_View
|SF_CopyCte
) ){
966 testcase( p
->selFlags
& SF_View
);
967 testcase( p
->selFlags
& SF_CopyCte
);
970 renameWalkWith(pWalker
, p
);
975 ** This is a Walker expression callback.
977 ** For every TK_COLUMN node in the expression tree, search to see
978 ** if the column being references is the column being renamed by an
979 ** ALTER TABLE statement. If it is, then attach its associated
980 ** RenameToken object to the list of RenameToken objects being
981 ** constructed in RenameCtx object at pWalker->u.pRename.
983 static int renameColumnExprCb(Walker
*pWalker
, Expr
*pExpr
){
984 RenameCtx
*p
= pWalker
->u
.pRename
;
985 if( pExpr
->op
==TK_TRIGGER
986 && pExpr
->iColumn
==p
->iCol
987 && pWalker
->pParse
->pTriggerTab
==p
->pTab
989 renameTokenFind(pWalker
->pParse
, p
, (void*)pExpr
);
990 }else if( pExpr
->op
==TK_COLUMN
991 && pExpr
->iColumn
==p
->iCol
992 && p
->pTab
==pExpr
->y
.pTab
994 renameTokenFind(pWalker
->pParse
, p
, (void*)pExpr
);
1000 ** The RenameCtx contains a list of tokens that reference a column that
1001 ** is being renamed by an ALTER TABLE statement. Return the "last"
1002 ** RenameToken in the RenameCtx and remove that RenameToken from the
1003 ** RenameContext. "Last" means the last RenameToken encountered when
1004 ** the input SQL is parsed from left to right. Repeated calls to this routine
1005 ** return all column name tokens in the order that they are encountered
1006 ** in the SQL statement.
1008 static RenameToken
*renameColumnTokenNext(RenameCtx
*pCtx
){
1009 RenameToken
*pBest
= pCtx
->pList
;
1010 RenameToken
*pToken
;
1013 for(pToken
=pBest
->pNext
; pToken
; pToken
=pToken
->pNext
){
1014 if( pToken
->t
.z
>pBest
->t
.z
) pBest
= pToken
;
1016 for(pp
=&pCtx
->pList
; *pp
!=pBest
; pp
=&(*pp
)->pNext
);
1023 ** An error occured while parsing or otherwise processing a database
1024 ** object (either pParse->pNewTable, pNewIndex or pNewTrigger) as part of an
1025 ** ALTER TABLE RENAME COLUMN program. The error message emitted by the
1026 ** sub-routine is currently stored in pParse->zErrMsg. This function
1027 ** adds context to the error message and then stores it in pCtx.
1029 static void renameColumnParseError(
1030 sqlite3_context
*pCtx
,
1032 sqlite3_value
*pType
,
1033 sqlite3_value
*pObject
,
1036 const char *zT
= (const char*)sqlite3_value_text(pType
);
1037 const char *zN
= (const char*)sqlite3_value_text(pObject
);
1040 zErr
= sqlite3_mprintf("error in %s %s%s%s: %s",
1041 zT
, zN
, (zWhen
[0] ? " " : ""), zWhen
,
1044 sqlite3_result_error(pCtx
, zErr
, -1);
1049 ** For each name in the the expression-list pEList (i.e. each
1050 ** pEList->a[i].zName) that matches the string in zOld, extract the
1051 ** corresponding rename-token from Parse object pParse and add it
1052 ** to the RenameCtx pCtx.
1054 static void renameColumnElistNames(
1062 for(i
=0; i
<pEList
->nExpr
; i
++){
1063 char *zName
= pEList
->a
[i
].zEName
;
1064 if( ALWAYS(pEList
->a
[i
].eEName
==ENAME_NAME
)
1066 && 0==sqlite3_stricmp(zName
, zOld
)
1068 renameTokenFind(pParse
, pCtx
, (void*)zName
);
1075 ** For each name in the the id-list pIdList (i.e. each pIdList->a[i].zName)
1076 ** that matches the string in zOld, extract the corresponding rename-token
1077 ** from Parse object pParse and add it to the RenameCtx pCtx.
1079 static void renameColumnIdlistNames(
1087 for(i
=0; i
<pIdList
->nId
; i
++){
1088 char *zName
= pIdList
->a
[i
].zName
;
1089 if( 0==sqlite3_stricmp(zName
, zOld
) ){
1090 renameTokenFind(pParse
, pCtx
, (void*)zName
);
1098 ** Parse the SQL statement zSql using Parse object (*p). The Parse object
1099 ** is initialized by this function before it is used.
1101 static int renameParseSql(
1102 Parse
*p
, /* Memory to use for Parse object */
1103 const char *zDb
, /* Name of schema SQL belongs to */
1104 sqlite3
*db
, /* Database handle */
1105 const char *zSql
, /* SQL to parse */
1106 int bTemp
/* True if SQL is from temp schema */
1111 db
->init
.iDb
= bTemp
? 1 : sqlite3FindDbName(db
, zDb
);
1113 /* Parse the SQL statement passed as the first argument. If no error
1114 ** occurs and the parse does not result in a new table, index or
1115 ** trigger object, the database must be corrupt. */
1116 memset(p
, 0, sizeof(Parse
));
1117 p
->eParseMode
= PARSE_MODE_RENAME
;
1120 rc
= zSql
? sqlite3RunParser(p
, zSql
, &zErr
) : SQLITE_NOMEM
;
1121 assert( p
->zErrMsg
==0 );
1122 assert( rc
!=SQLITE_OK
|| zErr
==0 );
1124 if( db
->mallocFailed
) rc
= SQLITE_NOMEM
;
1126 && p
->pNewTable
==0 && p
->pNewIndex
==0 && p
->pNewTrigger
==0
1128 rc
= SQLITE_CORRUPT_BKPT
;
1132 /* Ensure that all mappings in the Parse.pRename list really do map to
1133 ** a part of the input string. */
1134 if( rc
==SQLITE_OK
){
1135 int nSql
= sqlite3Strlen30(zSql
);
1136 RenameToken
*pToken
;
1137 for(pToken
=p
->pRename
; pToken
; pToken
=pToken
->pNext
){
1138 assert( pToken
->t
.z
>=zSql
&& &pToken
->t
.z
[pToken
->t
.n
]<=&zSql
[nSql
] );
1148 ** This function edits SQL statement zSql, replacing each token identified
1149 ** by the linked list pRename with the text of zNew. If argument bQuote is
1150 ** true, then zNew is always quoted first. If no error occurs, the result
1151 ** is loaded into context object pCtx as the result.
1153 ** Or, if an error occurs (i.e. an OOM condition), an error is left in
1154 ** pCtx and an SQLite error code returned.
1156 static int renameEditSql(
1157 sqlite3_context
*pCtx
, /* Return result here */
1158 RenameCtx
*pRename
, /* Rename context */
1159 const char *zSql
, /* SQL statement to edit */
1160 const char *zNew
, /* New token text */
1161 int bQuote
/* True to always quote token */
1163 i64 nNew
= sqlite3Strlen30(zNew
);
1164 i64 nSql
= sqlite3Strlen30(zSql
);
1165 sqlite3
*db
= sqlite3_context_db_handle(pCtx
);
1174 /* Set zQuot to point to a buffer containing a quoted copy of the
1175 ** identifier zNew. If the corresponding identifier in the original
1176 ** ALTER TABLE statement was quoted (bQuote==1), then set zNew to
1177 ** point to zQuot so that all substitutions are made using the
1178 ** quoted version of the new column name. */
1179 zQuot
= sqlite3MPrintf(db
, "\"%w\" ", zNew
);
1181 return SQLITE_NOMEM
;
1183 nQuot
= sqlite3Strlen30(zQuot
)-1;
1186 assert( nQuot
>=nNew
);
1187 zOut
= sqlite3DbMallocZero(db
, nSql
+ pRename
->nList
*nQuot
+ 1);
1189 zOut
= (char*)sqlite3DbMallocZero(db
, (nSql
*2+1) * 3);
1191 zBuf1
= &zOut
[nSql
*2+1];
1192 zBuf2
= &zOut
[nSql
*4+2];
1196 /* At this point pRename->pList contains a list of RenameToken objects
1197 ** corresponding to all tokens in the input SQL that must be replaced
1198 ** with the new column name, or with single-quoted versions of themselves.
1199 ** All that remains is to construct and return the edited SQL string. */
1202 memcpy(zOut
, zSql
, nSql
);
1203 while( pRename
->pList
){
1204 int iOff
; /* Offset of token to replace in zOut */
1206 const char *zReplace
;
1207 RenameToken
*pBest
= renameColumnTokenNext(pRename
);
1210 if( bQuote
==0 && sqlite3IsIdChar(*pBest
->t
.z
) ){
1216 if( pBest
->t
.z
[pBest
->t
.n
]=='"' ) nReplace
++;
1219 /* Dequote the double-quoted token. Then requote it again, this time
1220 ** using single quotes. If the character immediately following the
1221 ** original token within the input SQL was a single quote ('), then
1222 ** add another space after the new, single-quoted version of the
1223 ** token. This is so that (SELECT "string"'alias') maps to
1224 ** (SELECT 'string' 'alias'), and not (SELECT 'string''alias'). */
1225 memcpy(zBuf1
, pBest
->t
.z
, pBest
->t
.n
);
1226 zBuf1
[pBest
->t
.n
] = 0;
1227 sqlite3Dequote(zBuf1
);
1228 sqlite3_snprintf(nSql
*2, zBuf2
, "%Q%s", zBuf1
,
1229 pBest
->t
.z
[pBest
->t
.n
]=='\'' ? " " : ""
1232 nReplace
= sqlite3Strlen30(zReplace
);
1235 iOff
= pBest
->t
.z
- zSql
;
1236 if( pBest
->t
.n
!=nReplace
){
1237 memmove(&zOut
[iOff
+ nReplace
], &zOut
[iOff
+ pBest
->t
.n
],
1238 nOut
- (iOff
+ pBest
->t
.n
)
1240 nOut
+= nReplace
- pBest
->t
.n
;
1243 memcpy(&zOut
[iOff
], zReplace
, nReplace
);
1244 sqlite3DbFree(db
, pBest
);
1247 sqlite3_result_text(pCtx
, zOut
, -1, SQLITE_TRANSIENT
);
1248 sqlite3DbFree(db
, zOut
);
1253 sqlite3_free(zQuot
);
1258 ** Resolve all symbols in the trigger at pParse->pNewTrigger, assuming
1259 ** it was read from the schema of database zDb. Return SQLITE_OK if
1260 ** successful. Otherwise, return an SQLite error code and leave an error
1261 ** message in the Parse object.
1263 static int renameResolveTrigger(Parse
*pParse
){
1264 sqlite3
*db
= pParse
->db
;
1265 Trigger
*pNew
= pParse
->pNewTrigger
;
1270 memset(&sNC
, 0, sizeof(sNC
));
1271 sNC
.pParse
= pParse
;
1272 assert( pNew
->pTabSchema
);
1273 pParse
->pTriggerTab
= sqlite3FindTable(db
, pNew
->table
,
1274 db
->aDb
[sqlite3SchemaToIndex(db
, pNew
->pTabSchema
)].zDbSName
1276 pParse
->eTriggerOp
= pNew
->op
;
1277 /* ALWAYS() because if the table of the trigger does not exist, the
1278 ** error would have been hit before this point */
1279 if( ALWAYS(pParse
->pTriggerTab
) ){
1280 rc
= sqlite3ViewGetColumnNames(pParse
, pParse
->pTriggerTab
);
1283 /* Resolve symbols in WHEN clause */
1284 if( rc
==SQLITE_OK
&& pNew
->pWhen
){
1285 rc
= sqlite3ResolveExprNames(&sNC
, pNew
->pWhen
);
1288 for(pStep
=pNew
->step_list
; rc
==SQLITE_OK
&& pStep
; pStep
=pStep
->pNext
){
1289 if( pStep
->pSelect
){
1290 sqlite3SelectPrep(pParse
, pStep
->pSelect
, &sNC
);
1291 if( pParse
->nErr
) rc
= pParse
->rc
;
1293 if( rc
==SQLITE_OK
&& pStep
->zTarget
){
1294 SrcList
*pSrc
= sqlite3TriggerStepSrc(pParse
, pStep
);
1297 for(i
=0; i
<pSrc
->nSrc
&& rc
==SQLITE_OK
; i
++){
1298 SrcItem
*p
= &pSrc
->a
[i
];
1299 p
->iCursor
= pParse
->nTab
++;
1301 sqlite3SelectPrep(pParse
, p
->pSelect
, 0);
1302 sqlite3ExpandSubquery(pParse
, p
);
1304 assert( pStep
->pFrom
->a
[i
-1].pSelect
);
1305 sqlite3SelectPrep(pParse
, pStep
->pFrom
->a
[i
-1].pSelect
, 0);
1307 p
->pTab
= sqlite3LocateTableItem(pParse
, 0, p
);
1312 rc
= sqlite3ViewGetColumnNames(pParse
, p
->pTab
);
1316 sNC
.pSrcList
= pSrc
;
1317 if( rc
==SQLITE_OK
&& pStep
->pWhere
){
1318 rc
= sqlite3ResolveExprNames(&sNC
, pStep
->pWhere
);
1320 if( rc
==SQLITE_OK
){
1321 rc
= sqlite3ResolveExprListNames(&sNC
, pStep
->pExprList
);
1323 assert( !pStep
->pUpsert
|| (!pStep
->pWhere
&& !pStep
->pExprList
) );
1324 if( pStep
->pUpsert
&& rc
==SQLITE_OK
){
1325 Upsert
*pUpsert
= pStep
->pUpsert
;
1326 pUpsert
->pUpsertSrc
= pSrc
;
1327 sNC
.uNC
.pUpsert
= pUpsert
;
1328 sNC
.ncFlags
= NC_UUpsert
;
1329 rc
= sqlite3ResolveExprListNames(&sNC
, pUpsert
->pUpsertTarget
);
1330 if( rc
==SQLITE_OK
){
1331 ExprList
*pUpsertSet
= pUpsert
->pUpsertSet
;
1332 rc
= sqlite3ResolveExprListNames(&sNC
, pUpsertSet
);
1334 if( rc
==SQLITE_OK
){
1335 rc
= sqlite3ResolveExprNames(&sNC
, pUpsert
->pUpsertWhere
);
1337 if( rc
==SQLITE_OK
){
1338 rc
= sqlite3ResolveExprNames(&sNC
, pUpsert
->pUpsertTargetWhere
);
1343 sqlite3SrcListDelete(db
, pSrc
);
1353 ** Invoke sqlite3WalkExpr() or sqlite3WalkSelect() on all Select or Expr
1354 ** objects that are part of the trigger passed as the second argument.
1356 static void renameWalkTrigger(Walker
*pWalker
, Trigger
*pTrigger
){
1359 /* Find tokens to edit in WHEN clause */
1360 sqlite3WalkExpr(pWalker
, pTrigger
->pWhen
);
1362 /* Find tokens to edit in trigger steps */
1363 for(pStep
=pTrigger
->step_list
; pStep
; pStep
=pStep
->pNext
){
1364 sqlite3WalkSelect(pWalker
, pStep
->pSelect
);
1365 sqlite3WalkExpr(pWalker
, pStep
->pWhere
);
1366 sqlite3WalkExprList(pWalker
, pStep
->pExprList
);
1367 if( pStep
->pUpsert
){
1368 Upsert
*pUpsert
= pStep
->pUpsert
;
1369 sqlite3WalkExprList(pWalker
, pUpsert
->pUpsertTarget
);
1370 sqlite3WalkExprList(pWalker
, pUpsert
->pUpsertSet
);
1371 sqlite3WalkExpr(pWalker
, pUpsert
->pUpsertWhere
);
1372 sqlite3WalkExpr(pWalker
, pUpsert
->pUpsertTargetWhere
);
1376 for(i
=0; i
<pStep
->pFrom
->nSrc
; i
++){
1377 sqlite3WalkSelect(pWalker
, pStep
->pFrom
->a
[i
].pSelect
);
1384 ** Free the contents of Parse object (*pParse). Do not free the memory
1385 ** occupied by the Parse object itself.
1387 static void renameParseCleanup(Parse
*pParse
){
1388 sqlite3
*db
= pParse
->db
;
1390 if( pParse
->pVdbe
){
1391 sqlite3VdbeFinalize(pParse
->pVdbe
);
1393 sqlite3DeleteTable(db
, pParse
->pNewTable
);
1394 while( (pIdx
= pParse
->pNewIndex
)!=0 ){
1395 pParse
->pNewIndex
= pIdx
->pNext
;
1396 sqlite3FreeIndex(db
, pIdx
);
1398 sqlite3DeleteTrigger(db
, pParse
->pNewTrigger
);
1399 sqlite3DbFree(db
, pParse
->zErrMsg
);
1400 renameTokenFree(db
, pParse
->pRename
);
1401 sqlite3ParserReset(pParse
);
1407 ** sqlite_rename_column(zSql, iCol, bQuote, zNew, zTable, zOld)
1409 ** 0. zSql: SQL statement to rewrite
1410 ** 1. type: Type of object ("table", "view" etc.)
1411 ** 2. object: Name of object
1412 ** 3. Database: Database name (e.g. "main")
1413 ** 4. Table: Table name
1414 ** 5. iCol: Index of column to rename
1415 ** 6. zNew: New column name
1416 ** 7. bQuote: Non-zero if the new column name should be quoted.
1417 ** 8. bTemp: True if zSql comes from temp schema
1419 ** Do a column rename operation on the CREATE statement given in zSql.
1420 ** The iCol-th column (left-most is 0) of table zTable is renamed from zCol
1421 ** into zNew. The name should be quoted if bQuote is true.
1423 ** This function is used internally by the ALTER TABLE RENAME COLUMN command.
1424 ** It is only accessible to SQL created using sqlite3NestedParse(). It is
1425 ** not reachable from ordinary SQL passed into sqlite3_prepare().
1427 static void renameColumnFunc(
1428 sqlite3_context
*context
,
1430 sqlite3_value
**argv
1432 sqlite3
*db
= sqlite3_context_db_handle(context
);
1434 const char *zSql
= (const char*)sqlite3_value_text(argv
[0]);
1435 const char *zDb
= (const char*)sqlite3_value_text(argv
[3]);
1436 const char *zTable
= (const char*)sqlite3_value_text(argv
[4]);
1437 int iCol
= sqlite3_value_int(argv
[5]);
1438 const char *zNew
= (const char*)sqlite3_value_text(argv
[6]);
1439 int bQuote
= sqlite3_value_int(argv
[7]);
1440 int bTemp
= sqlite3_value_int(argv
[8]);
1448 #ifndef SQLITE_OMIT_AUTHORIZATION
1449 sqlite3_xauth xAuth
= db
->xAuth
;
1452 UNUSED_PARAMETER(NotUsed
);
1453 if( zSql
==0 ) return;
1454 if( zTable
==0 ) return;
1455 if( zNew
==0 ) return;
1456 if( iCol
<0 ) return;
1457 sqlite3BtreeEnterAll(db
);
1458 pTab
= sqlite3FindTable(db
, zTable
, zDb
);
1459 if( pTab
==0 || iCol
>=pTab
->nCol
){
1460 sqlite3BtreeLeaveAll(db
);
1463 zOld
= pTab
->aCol
[iCol
].zName
;
1464 memset(&sCtx
, 0, sizeof(sCtx
));
1465 sCtx
.iCol
= ((iCol
==pTab
->iPKey
) ? -1 : iCol
);
1467 #ifndef SQLITE_OMIT_AUTHORIZATION
1470 rc
= renameParseSql(&sParse
, zDb
, db
, zSql
, bTemp
);
1472 /* Find tokens that need to be replaced. */
1473 memset(&sWalker
, 0, sizeof(Walker
));
1474 sWalker
.pParse
= &sParse
;
1475 sWalker
.xExprCallback
= renameColumnExprCb
;
1476 sWalker
.xSelectCallback
= renameColumnSelectCb
;
1477 sWalker
.u
.pRename
= &sCtx
;
1480 if( rc
!=SQLITE_OK
) goto renameColumnFunc_done
;
1481 if( sParse
.pNewTable
){
1482 Select
*pSelect
= sParse
.pNewTable
->pSelect
;
1484 pSelect
->selFlags
&= ~SF_View
;
1485 sParse
.rc
= SQLITE_OK
;
1486 sqlite3SelectPrep(&sParse
, pSelect
, 0);
1487 rc
= (db
->mallocFailed
? SQLITE_NOMEM
: sParse
.rc
);
1488 if( rc
==SQLITE_OK
){
1489 sqlite3WalkSelect(&sWalker
, pSelect
);
1491 if( rc
!=SQLITE_OK
) goto renameColumnFunc_done
;
1493 /* A regular table */
1494 int bFKOnly
= sqlite3_stricmp(zTable
, sParse
.pNewTable
->zName
);
1496 assert( sParse
.pNewTable
->pSelect
==0 );
1497 sCtx
.pTab
= sParse
.pNewTable
;
1499 if( iCol
<sParse
.pNewTable
->nCol
){
1501 &sParse
, &sCtx
, (void*)sParse
.pNewTable
->aCol
[iCol
].zName
1505 renameTokenFind(&sParse
, &sCtx
, (void*)&sParse
.pNewTable
->iPKey
);
1507 sqlite3WalkExprList(&sWalker
, sParse
.pNewTable
->pCheck
);
1508 for(pIdx
=sParse
.pNewTable
->pIndex
; pIdx
; pIdx
=pIdx
->pNext
){
1509 sqlite3WalkExprList(&sWalker
, pIdx
->aColExpr
);
1511 for(pIdx
=sParse
.pNewIndex
; pIdx
; pIdx
=pIdx
->pNext
){
1512 sqlite3WalkExprList(&sWalker
, pIdx
->aColExpr
);
1514 #ifndef SQLITE_OMIT_GENERATED_COLUMNS
1515 for(i
=0; i
<sParse
.pNewTable
->nCol
; i
++){
1516 sqlite3WalkExpr(&sWalker
, sParse
.pNewTable
->aCol
[i
].pDflt
);
1521 for(pFKey
=sParse
.pNewTable
->pFKey
; pFKey
; pFKey
=pFKey
->pNextFrom
){
1522 for(i
=0; i
<pFKey
->nCol
; i
++){
1523 if( bFKOnly
==0 && pFKey
->aCol
[i
].iFrom
==iCol
){
1524 renameTokenFind(&sParse
, &sCtx
, (void*)&pFKey
->aCol
[i
]);
1526 if( 0==sqlite3_stricmp(pFKey
->zTo
, zTable
)
1527 && 0==sqlite3_stricmp(pFKey
->aCol
[i
].zCol
, zOld
)
1529 renameTokenFind(&sParse
, &sCtx
, (void*)pFKey
->aCol
[i
].zCol
);
1534 }else if( sParse
.pNewIndex
){
1535 sqlite3WalkExprList(&sWalker
, sParse
.pNewIndex
->aColExpr
);
1536 sqlite3WalkExpr(&sWalker
, sParse
.pNewIndex
->pPartIdxWhere
);
1540 rc
= renameResolveTrigger(&sParse
);
1541 if( rc
!=SQLITE_OK
) goto renameColumnFunc_done
;
1543 for(pStep
=sParse
.pNewTrigger
->step_list
; pStep
; pStep
=pStep
->pNext
){
1544 if( pStep
->zTarget
){
1545 Table
*pTarget
= sqlite3LocateTable(&sParse
, 0, pStep
->zTarget
, zDb
);
1546 if( pTarget
==pTab
){
1547 if( pStep
->pUpsert
){
1548 ExprList
*pUpsertSet
= pStep
->pUpsert
->pUpsertSet
;
1549 renameColumnElistNames(&sParse
, &sCtx
, pUpsertSet
, zOld
);
1551 renameColumnIdlistNames(&sParse
, &sCtx
, pStep
->pIdList
, zOld
);
1552 renameColumnElistNames(&sParse
, &sCtx
, pStep
->pExprList
, zOld
);
1558 /* Find tokens to edit in UPDATE OF clause */
1559 if( sParse
.pTriggerTab
==pTab
){
1560 renameColumnIdlistNames(&sParse
, &sCtx
,sParse
.pNewTrigger
->pColumns
,zOld
);
1563 /* Find tokens to edit in various expressions and selects */
1564 renameWalkTrigger(&sWalker
, sParse
.pNewTrigger
);
1567 assert( rc
==SQLITE_OK
);
1568 rc
= renameEditSql(context
, &sCtx
, zSql
, zNew
, bQuote
);
1570 renameColumnFunc_done
:
1571 if( rc
!=SQLITE_OK
){
1572 if( sParse
.zErrMsg
){
1573 renameColumnParseError(context
, "", argv
[1], argv
[2], &sParse
);
1575 sqlite3_result_error_code(context
, rc
);
1579 renameParseCleanup(&sParse
);
1580 renameTokenFree(db
, sCtx
.pList
);
1581 #ifndef SQLITE_OMIT_AUTHORIZATION
1584 sqlite3BtreeLeaveAll(db
);
1588 ** Walker expression callback used by "RENAME TABLE".
1590 static int renameTableExprCb(Walker
*pWalker
, Expr
*pExpr
){
1591 RenameCtx
*p
= pWalker
->u
.pRename
;
1592 if( pExpr
->op
==TK_COLUMN
&& p
->pTab
==pExpr
->y
.pTab
){
1593 renameTokenFind(pWalker
->pParse
, p
, (void*)&pExpr
->y
.pTab
);
1595 return WRC_Continue
;
1599 ** Walker select callback used by "RENAME TABLE".
1601 static int renameTableSelectCb(Walker
*pWalker
, Select
*pSelect
){
1603 RenameCtx
*p
= pWalker
->u
.pRename
;
1604 SrcList
*pSrc
= pSelect
->pSrc
;
1605 if( pSelect
->selFlags
& (SF_View
|SF_CopyCte
) ){
1606 testcase( pSelect
->selFlags
& SF_View
);
1607 testcase( pSelect
->selFlags
& SF_CopyCte
);
1610 if( NEVER(pSrc
==0) ){
1611 assert( pWalker
->pParse
->db
->mallocFailed
);
1614 for(i
=0; i
<pSrc
->nSrc
; i
++){
1615 SrcItem
*pItem
= &pSrc
->a
[i
];
1616 if( pItem
->pTab
==p
->pTab
){
1617 renameTokenFind(pWalker
->pParse
, p
, pItem
->zName
);
1620 renameWalkWith(pWalker
, pSelect
);
1622 return WRC_Continue
;
1627 ** This C function implements an SQL user function that is used by SQL code
1628 ** generated by the ALTER TABLE ... RENAME command to modify the definition
1629 ** of any foreign key constraints that use the table being renamed as the
1630 ** parent table. It is passed three arguments:
1632 ** 0: The database containing the table being renamed.
1633 ** 1. type: Type of object ("table", "view" etc.)
1634 ** 2. object: Name of object
1635 ** 3: The complete text of the schema statement being modified,
1636 ** 4: The old name of the table being renamed, and
1637 ** 5: The new name of the table being renamed.
1638 ** 6: True if the schema statement comes from the temp db.
1640 ** It returns the new schema statement. For example:
1642 ** sqlite_rename_table('main', 'CREATE TABLE t1(a REFERENCES t2)','t2','t3',0)
1643 ** -> 'CREATE TABLE t1(a REFERENCES t3)'
1645 static void renameTableFunc(
1646 sqlite3_context
*context
,
1648 sqlite3_value
**argv
1650 sqlite3
*db
= sqlite3_context_db_handle(context
);
1651 const char *zDb
= (const char*)sqlite3_value_text(argv
[0]);
1652 const char *zInput
= (const char*)sqlite3_value_text(argv
[3]);
1653 const char *zOld
= (const char*)sqlite3_value_text(argv
[4]);
1654 const char *zNew
= (const char*)sqlite3_value_text(argv
[5]);
1655 int bTemp
= sqlite3_value_int(argv
[6]);
1656 UNUSED_PARAMETER(NotUsed
);
1658 if( zInput
&& zOld
&& zNew
){
1665 #ifndef SQLITE_OMIT_AUTHORIZATION
1666 sqlite3_xauth xAuth
= db
->xAuth
;
1670 sqlite3BtreeEnterAll(db
);
1672 memset(&sCtx
, 0, sizeof(RenameCtx
));
1673 sCtx
.pTab
= sqlite3FindTable(db
, zOld
, zDb
);
1674 memset(&sWalker
, 0, sizeof(Walker
));
1675 sWalker
.pParse
= &sParse
;
1676 sWalker
.xExprCallback
= renameTableExprCb
;
1677 sWalker
.xSelectCallback
= renameTableSelectCb
;
1678 sWalker
.u
.pRename
= &sCtx
;
1680 rc
= renameParseSql(&sParse
, zDb
, db
, zInput
, bTemp
);
1682 if( rc
==SQLITE_OK
){
1683 int isLegacy
= (db
->flags
& SQLITE_LegacyAlter
);
1684 if( sParse
.pNewTable
){
1685 Table
*pTab
= sParse
.pNewTable
;
1687 if( pTab
->pSelect
){
1689 Select
*pSelect
= pTab
->pSelect
;
1691 memset(&sNC
, 0, sizeof(sNC
));
1692 sNC
.pParse
= &sParse
;
1694 assert( pSelect
->selFlags
& SF_View
);
1695 pSelect
->selFlags
&= ~SF_View
;
1696 sqlite3SelectPrep(&sParse
, pTab
->pSelect
, &sNC
);
1700 sqlite3WalkSelect(&sWalker
, pTab
->pSelect
);
1704 /* Modify any FK definitions to point to the new table. */
1705 #ifndef SQLITE_OMIT_FOREIGN_KEY
1706 if( isLegacy
==0 || (db
->flags
& SQLITE_ForeignKeys
) ){
1708 for(pFKey
=pTab
->pFKey
; pFKey
; pFKey
=pFKey
->pNextFrom
){
1709 if( sqlite3_stricmp(pFKey
->zTo
, zOld
)==0 ){
1710 renameTokenFind(&sParse
, &sCtx
, (void*)pFKey
->zTo
);
1716 /* If this is the table being altered, fix any table refs in CHECK
1717 ** expressions. Also update the name that appears right after the
1718 ** "CREATE [VIRTUAL] TABLE" bit. */
1719 if( sqlite3_stricmp(zOld
, pTab
->zName
)==0 ){
1722 sqlite3WalkExprList(&sWalker
, pTab
->pCheck
);
1724 renameTokenFind(&sParse
, &sCtx
, pTab
->zName
);
1729 else if( sParse
.pNewIndex
){
1730 renameTokenFind(&sParse
, &sCtx
, sParse
.pNewIndex
->zName
);
1732 sqlite3WalkExpr(&sWalker
, sParse
.pNewIndex
->pPartIdxWhere
);
1736 #ifndef SQLITE_OMIT_TRIGGER
1738 Trigger
*pTrigger
= sParse
.pNewTrigger
;
1740 if( 0==sqlite3_stricmp(sParse
.pNewTrigger
->table
, zOld
)
1741 && sCtx
.pTab
->pSchema
==pTrigger
->pTabSchema
1743 renameTokenFind(&sParse
, &sCtx
, sParse
.pNewTrigger
->table
);
1747 rc
= renameResolveTrigger(&sParse
);
1748 if( rc
==SQLITE_OK
){
1749 renameWalkTrigger(&sWalker
, pTrigger
);
1750 for(pStep
=pTrigger
->step_list
; pStep
; pStep
=pStep
->pNext
){
1751 if( pStep
->zTarget
&& 0==sqlite3_stricmp(pStep
->zTarget
, zOld
) ){
1752 renameTokenFind(&sParse
, &sCtx
, pStep
->zTarget
);
1761 if( rc
==SQLITE_OK
){
1762 rc
= renameEditSql(context
, &sCtx
, zInput
, zNew
, bQuote
);
1764 if( rc
!=SQLITE_OK
){
1765 if( sParse
.zErrMsg
){
1766 renameColumnParseError(context
, "", argv
[1], argv
[2], &sParse
);
1768 sqlite3_result_error_code(context
, rc
);
1772 renameParseCleanup(&sParse
);
1773 renameTokenFree(db
, sCtx
.pList
);
1774 sqlite3BtreeLeaveAll(db
);
1775 #ifndef SQLITE_OMIT_AUTHORIZATION
1783 static int renameQuotefixExprCb(Walker
*pWalker
, Expr
*pExpr
){
1784 if( pExpr
->op
==TK_STRING
&& (pExpr
->flags
& EP_DblQuoted
) ){
1785 renameTokenFind(pWalker
->pParse
, pWalker
->u
.pRename
, (void*)pExpr
);
1787 return WRC_Continue
;
1791 ** The implementation of an SQL scalar function that rewrites DDL statements
1792 ** so that any string literals that use double-quotes are modified so that
1793 ** they use single quotes.
1795 ** Two arguments must be passed:
1797 ** 0: Database name ("main", "temp" etc.).
1798 ** 1: SQL statement to edit.
1800 ** The returned value is the modified SQL statement. For example, given
1801 ** the database schema:
1803 ** CREATE TABLE t1(a, b, c);
1805 ** SELECT sqlite_rename_quotefix('main',
1806 ** 'CREATE VIEW v1 AS SELECT "a", "string" FROM t1'
1809 ** returns the string:
1811 ** CREATE VIEW v1 AS SELECT "a", 'string' FROM t1
1813 static void renameQuotefixFunc(
1814 sqlite3_context
*context
,
1816 sqlite3_value
**argv
1818 sqlite3
*db
= sqlite3_context_db_handle(context
);
1819 char const *zDb
= (const char*)sqlite3_value_text(argv
[0]);
1820 char const *zInput
= (const char*)sqlite3_value_text(argv
[1]);
1822 #ifndef SQLITE_OMIT_AUTHORIZATION
1823 sqlite3_xauth xAuth
= db
->xAuth
;
1827 sqlite3BtreeEnterAll(db
);
1829 UNUSED_PARAMETER(NotUsed
);
1830 if( zDb
&& zInput
){
1833 rc
= renameParseSql(&sParse
, zDb
, db
, zInput
, 0);
1835 if( rc
==SQLITE_OK
){
1839 /* Walker to find tokens that need to be replaced. */
1840 memset(&sCtx
, 0, sizeof(RenameCtx
));
1841 memset(&sWalker
, 0, sizeof(Walker
));
1842 sWalker
.pParse
= &sParse
;
1843 sWalker
.xExprCallback
= renameQuotefixExprCb
;
1844 sWalker
.xSelectCallback
= renameColumnSelectCb
;
1845 sWalker
.u
.pRename
= &sCtx
;
1847 if( sParse
.pNewTable
){
1848 Select
*pSelect
= sParse
.pNewTable
->pSelect
;
1850 pSelect
->selFlags
&= ~SF_View
;
1851 sParse
.rc
= SQLITE_OK
;
1852 sqlite3SelectPrep(&sParse
, pSelect
, 0);
1853 rc
= (db
->mallocFailed
? SQLITE_NOMEM
: sParse
.rc
);
1854 if( rc
==SQLITE_OK
){
1855 sqlite3WalkSelect(&sWalker
, pSelect
);
1859 sqlite3WalkExprList(&sWalker
, sParse
.pNewTable
->pCheck
);
1860 #ifndef SQLITE_OMIT_GENERATED_COLUMNS
1861 for(i
=0; i
<sParse
.pNewTable
->nCol
; i
++){
1862 sqlite3WalkExpr(&sWalker
, sParse
.pNewTable
->aCol
[i
].pDflt
);
1864 #endif /* SQLITE_OMIT_GENERATED_COLUMNS */
1866 }else if( sParse
.pNewIndex
){
1867 sqlite3WalkExprList(&sWalker
, sParse
.pNewIndex
->aColExpr
);
1868 sqlite3WalkExpr(&sWalker
, sParse
.pNewIndex
->pPartIdxWhere
);
1870 #ifndef SQLITE_OMIT_TRIGGER
1871 rc
= renameResolveTrigger(&sParse
);
1872 if( rc
==SQLITE_OK
){
1873 renameWalkTrigger(&sWalker
, sParse
.pNewTrigger
);
1875 #endif /* SQLITE_OMIT_TRIGGER */
1878 if( rc
==SQLITE_OK
){
1879 rc
= renameEditSql(context
, &sCtx
, zInput
, 0, 0);
1881 renameTokenFree(db
, sCtx
.pList
);
1883 if( rc
!=SQLITE_OK
){
1884 sqlite3_result_error_code(context
, rc
);
1886 renameParseCleanup(&sParse
);
1889 #ifndef SQLITE_OMIT_AUTHORIZATION
1893 sqlite3BtreeLeaveAll(db
);
1897 ** An SQL user function that checks that there are no parse or symbol
1898 ** resolution problems in a CREATE TRIGGER|TABLE|VIEW|INDEX statement.
1899 ** After an ALTER TABLE .. RENAME operation is performed and the schema
1900 ** reloaded, this function is called on each SQL statement in the schema
1901 ** to ensure that it is still usable.
1903 ** 0: Database name ("main", "temp" etc.).
1904 ** 1: SQL statement.
1905 ** 2: Object type ("view", "table", "trigger" or "index").
1907 ** 4: True if object is from temp schema.
1908 ** 5: "when" part of error message.
1909 ** 6: True to disable the DQS quirk when parsing SQL.
1911 ** Unless it finds an error, this function normally returns NULL. However, it
1912 ** returns integer value 1 if:
1914 ** * the SQL argument creates a trigger, and
1915 ** * the table that the trigger is attached to is in database zDb.
1917 static void renameTableTest(
1918 sqlite3_context
*context
,
1920 sqlite3_value
**argv
1922 sqlite3
*db
= sqlite3_context_db_handle(context
);
1923 char const *zDb
= (const char*)sqlite3_value_text(argv
[0]);
1924 char const *zInput
= (const char*)sqlite3_value_text(argv
[1]);
1925 int bTemp
= sqlite3_value_int(argv
[4]);
1926 int isLegacy
= (db
->flags
& SQLITE_LegacyAlter
);
1927 char const *zWhen
= (const char*)sqlite3_value_text(argv
[5]);
1928 int bNoDQS
= sqlite3_value_int(argv
[6]);
1930 #ifndef SQLITE_OMIT_AUTHORIZATION
1931 sqlite3_xauth xAuth
= db
->xAuth
;
1935 UNUSED_PARAMETER(NotUsed
);
1937 if( zDb
&& zInput
){
1940 int flags
= db
->flags
;
1941 if( bNoDQS
) db
->flags
&= ~(SQLITE_DqsDML
|SQLITE_DqsDDL
);
1942 rc
= renameParseSql(&sParse
, zDb
, db
, zInput
, bTemp
);
1943 db
->flags
|= (flags
& (SQLITE_DqsDML
|SQLITE_DqsDDL
));
1944 if( rc
==SQLITE_OK
){
1945 if( isLegacy
==0 && sParse
.pNewTable
&& sParse
.pNewTable
->pSelect
){
1947 memset(&sNC
, 0, sizeof(sNC
));
1948 sNC
.pParse
= &sParse
;
1949 sqlite3SelectPrep(&sParse
, sParse
.pNewTable
->pSelect
, &sNC
);
1950 if( sParse
.nErr
) rc
= sParse
.rc
;
1953 else if( sParse
.pNewTrigger
){
1955 rc
= renameResolveTrigger(&sParse
);
1957 if( rc
==SQLITE_OK
){
1958 int i1
= sqlite3SchemaToIndex(db
, sParse
.pNewTrigger
->pTabSchema
);
1959 int i2
= sqlite3FindDbName(db
, zDb
);
1960 if( i1
==i2
) sqlite3_result_int(context
, 1);
1965 if( rc
!=SQLITE_OK
&& zWhen
){
1966 renameColumnParseError(context
, zWhen
, argv
[2], argv
[3],&sParse
);
1968 renameParseCleanup(&sParse
);
1971 #ifndef SQLITE_OMIT_AUTHORIZATION
1977 ** The implementation of internal UDF sqlite_drop_column().
1981 ** argv[0]: An integer - the index of the schema containing the table
1982 ** argv[1]: CREATE TABLE statement to modify.
1983 ** argv[2]: An integer - the index of the column to remove.
1985 ** The value returned is a string containing the CREATE TABLE statement
1986 ** with column argv[2] removed.
1988 static void dropColumnFunc(
1989 sqlite3_context
*context
,
1991 sqlite3_value
**argv
1993 sqlite3
*db
= sqlite3_context_db_handle(context
);
1994 int iSchema
= sqlite3_value_int(argv
[0]);
1995 const char *zSql
= (const char*)sqlite3_value_text(argv
[1]);
1996 int iCol
= sqlite3_value_int(argv
[2]);
1997 const char *zDb
= db
->aDb
[iSchema
].zDbSName
;
2005 #ifndef SQLITE_OMIT_AUTHORIZATION
2006 sqlite3_xauth xAuth
= db
->xAuth
;
2010 UNUSED_PARAMETER(NotUsed
);
2011 rc
= renameParseSql(&sParse
, zDb
, db
, zSql
, iSchema
==1);
2012 if( rc
!=SQLITE_OK
) goto drop_column_done
;
2013 pTab
= sParse
.pNewTable
;
2014 if( pTab
==0 || pTab
->nCol
==1 || iCol
>=pTab
->nCol
){
2015 /* This can happen if the sqlite_schema table is corrupt */
2016 rc
= SQLITE_CORRUPT_BKPT
;
2017 goto drop_column_done
;
2020 pCol
= renameTokenFind(&sParse
, 0, (void*)pTab
->aCol
[iCol
].zName
);
2021 if( iCol
<pTab
->nCol
-1 ){
2023 pEnd
= renameTokenFind(&sParse
, 0, (void*)pTab
->aCol
[iCol
+1].zName
);
2024 zEnd
= (const char*)pEnd
->t
.z
;
2026 zEnd
= (const char*)&zSql
[pTab
->addColOffset
];
2027 while( ALWAYS(pCol
->t
.z
[0]!=0) && pCol
->t
.z
[0]!=',' ) pCol
->t
.z
--;
2030 zNew
= sqlite3MPrintf(db
, "%.*s%s", pCol
->t
.z
-zSql
, zSql
, zEnd
);
2031 sqlite3_result_text(context
, zNew
, -1, SQLITE_TRANSIENT
);
2035 renameParseCleanup(&sParse
);
2036 #ifndef SQLITE_OMIT_AUTHORIZATION
2039 if( rc
!=SQLITE_OK
){
2040 sqlite3_result_error_code(context
, rc
);
2045 ** This function is called by the parser upon parsing an
2047 ** ALTER TABLE pSrc DROP COLUMN pName
2049 ** statement. Argument pSrc contains the possibly qualified name of the
2050 ** table being edited, and token pName the name of the column to drop.
2052 void sqlite3AlterDropColumn(Parse
*pParse
, SrcList
*pSrc
, Token
*pName
){
2053 sqlite3
*db
= pParse
->db
; /* Database handle */
2054 Table
*pTab
; /* Table to modify */
2055 int iDb
; /* Index of db containing pTab in aDb[] */
2056 const char *zDb
; /* Database containing pTab ("main" etc.) */
2057 char *zCol
= 0; /* Name of column to drop */
2058 int iCol
; /* Index of column zCol in pTab->aCol[] */
2060 /* Look up the table being altered. */
2061 assert( pParse
->pNewTable
==0 );
2062 assert( sqlite3BtreeHoldsAllMutexes(db
) );
2063 if( NEVER(db
->mallocFailed
) ) goto exit_drop_column
;
2064 pTab
= sqlite3LocateTableItem(pParse
, 0, &pSrc
->a
[0]);
2065 if( !pTab
) goto exit_drop_column
;
2067 /* Make sure this is not an attempt to ALTER a view, virtual table or
2069 if( SQLITE_OK
!=isAlterableTable(pParse
, pTab
) ) goto exit_drop_column
;
2070 if( SQLITE_OK
!=isRealTable(pParse
, pTab
, 1) ) goto exit_drop_column
;
2072 /* Find the index of the column being dropped. */
2073 zCol
= sqlite3NameFromToken(db
, pName
);
2075 assert( db
->mallocFailed
);
2076 goto exit_drop_column
;
2078 iCol
= sqlite3ColumnIndex(pTab
, zCol
);
2080 sqlite3ErrorMsg(pParse
, "no such column: \"%s\"", zCol
);
2081 goto exit_drop_column
;
2084 /* Do not allow the user to drop a PRIMARY KEY column or a column
2085 ** constrained by a UNIQUE constraint. */
2086 if( pTab
->aCol
[iCol
].colFlags
& (COLFLAG_PRIMKEY
|COLFLAG_UNIQUE
) ){
2087 sqlite3ErrorMsg(pParse
, "cannot drop %s column: \"%s\"",
2088 (pTab
->aCol
[iCol
].colFlags
&COLFLAG_PRIMKEY
) ? "PRIMARY KEY" : "UNIQUE",
2091 goto exit_drop_column
;
2094 /* Do not allow the number of columns to go to zero */
2095 if( pTab
->nCol
<=1 ){
2096 sqlite3ErrorMsg(pParse
, "cannot drop column \"%s\": no other columns exist",zCol
);
2097 goto exit_drop_column
;
2100 /* Edit the sqlite_schema table */
2101 iDb
= sqlite3SchemaToIndex(db
, pTab
->pSchema
);
2103 zDb
= db
->aDb
[iDb
].zDbSName
;
2104 renameTestSchema(pParse
, zDb
, iDb
==1, "", 0);
2105 renameFixQuotes(pParse
, zDb
, iDb
==1);
2106 sqlite3NestedParse(pParse
,
2107 "UPDATE \"%w\"." DFLT_SCHEMA_TABLE
" SET "
2108 "sql = sqlite_drop_column(%d, sql, %d) "
2109 "WHERE (type=='table' AND tbl_name=%Q COLLATE nocase)"
2110 , zDb
, iDb
, iCol
, pTab
->zName
2113 /* Drop and reload the database schema. */
2114 renameReloadSchema(pParse
, iDb
, INITFLAG_AlterDrop
);
2115 renameTestSchema(pParse
, zDb
, iDb
==1, "after drop column", 1);
2117 /* Edit rows of table on disk */
2118 if( pParse
->nErr
==0 && (pTab
->aCol
[iCol
].colFlags
& COLFLAG_VIRTUAL
)==0 ){
2124 int nField
= 0; /* Number of non-virtual columns after drop */
2126 Vdbe
*v
= sqlite3GetVdbe(pParse
);
2127 iCur
= pParse
->nTab
++;
2128 sqlite3OpenTable(pParse
, iCur
, iDb
, pTab
, OP_OpenWrite
);
2129 addr
= sqlite3VdbeAddOp1(v
, OP_Rewind
, iCur
); VdbeCoverage(v
);
2130 reg
= ++pParse
->nMem
;
2131 if( HasRowid(pTab
) ){
2132 sqlite3VdbeAddOp2(v
, OP_Rowid
, iCur
, reg
);
2133 pParse
->nMem
+= pTab
->nCol
;
2135 pPk
= sqlite3PrimaryKeyIndex(pTab
);
2136 pParse
->nMem
+= pPk
->nColumn
;
2137 for(i
=0; i
<pPk
->nKeyCol
; i
++){
2138 sqlite3VdbeAddOp3(v
, OP_Column
, iCur
, i
, reg
+i
+1);
2140 nField
= pPk
->nKeyCol
;
2142 regRec
= ++pParse
->nMem
;
2143 for(i
=0; i
<pTab
->nCol
; i
++){
2144 if( i
!=iCol
&& (pTab
->aCol
[i
].colFlags
& COLFLAG_VIRTUAL
)==0 ){
2147 int iPos
= sqlite3TableColumnToIndex(pPk
, i
);
2148 int iColPos
= sqlite3TableColumnToIndex(pPk
, iCol
);
2149 if( iPos
<pPk
->nKeyCol
) continue;
2150 regOut
= reg
+1+iPos
-(iPos
>iColPos
);
2152 regOut
= reg
+1+nField
;
2154 if( i
==pTab
->iPKey
){
2155 sqlite3VdbeAddOp2(v
, OP_Null
, 0, regOut
);
2157 sqlite3ExprCodeGetColumnOfTable(v
, pTab
, iCur
, i
, regOut
);
2162 sqlite3VdbeAddOp3(v
, OP_MakeRecord
, reg
+1, nField
, regRec
);
2164 sqlite3VdbeAddOp4Int(v
, OP_IdxInsert
, iCur
, regRec
, reg
+1, pPk
->nKeyCol
);
2166 sqlite3VdbeAddOp3(v
, OP_Insert
, iCur
, regRec
, reg
);
2168 sqlite3VdbeChangeP5(v
, OPFLAG_SAVEPOSITION
);
2170 sqlite3VdbeAddOp2(v
, OP_Next
, iCur
, addr
+1); VdbeCoverage(v
);
2171 sqlite3VdbeJumpHere(v
, addr
);
2175 sqlite3DbFree(db
, zCol
);
2176 sqlite3SrcListDelete(db
, pSrc
);
2180 ** Register built-in functions used to help implement ALTER TABLE
2182 void sqlite3AlterFunctions(void){
2183 static FuncDef aAlterTableFuncs
[] = {
2184 INTERNAL_FUNCTION(sqlite_rename_column
, 9, renameColumnFunc
),
2185 INTERNAL_FUNCTION(sqlite_rename_table
, 7, renameTableFunc
),
2186 INTERNAL_FUNCTION(sqlite_rename_test
, 7, renameTableTest
),
2187 INTERNAL_FUNCTION(sqlite_drop_column
, 3, dropColumnFunc
),
2188 INTERNAL_FUNCTION(sqlite_rename_quotefix
,2, renameQuotefixFunc
),
2190 sqlite3InsertBuiltinFuncs(aAlterTableFuncs
, ArraySize(aAlterTableFuncs
));
2192 #endif /* SQLITE_ALTER_TABLE */