alter.c 27 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826
  1. /*
  2. ** 2005 February 15
  3. **
  4. ** The author disclaims copyright to this source code. In place of
  5. ** a legal notice, here is a blessing:
  6. **
  7. ** May you do good and not evil.
  8. ** May you find forgiveness for yourself and forgive others.
  9. ** May you share freely, never taking more than you give.
  10. **
  11. *************************************************************************
  12. ** This file contains C code routines that used to generate VDBE code
  13. ** that implements the ALTER TABLE command.
  14. */
  15. #include "sqliteInt.h"
  16. /*
  17. ** The code in this file only exists if we are not omitting the
  18. ** ALTER TABLE logic from the build.
  19. */
  20. #ifndef SQLITE_OMIT_ALTERTABLE
  21. /*
  22. ** This function is used by SQL generated to implement the
  23. ** ALTER TABLE command. The first argument is the text of a CREATE TABLE or
  24. ** CREATE INDEX command. The second is a table name. The table name in
  25. ** the CREATE TABLE or CREATE INDEX statement is replaced with the third
  26. ** argument and the result returned. Examples:
  27. **
  28. ** sqlite_rename_table('CREATE TABLE abc(a, b, c)', 'def')
  29. ** -> 'CREATE TABLE def(a, b, c)'
  30. **
  31. ** sqlite_rename_table('CREATE INDEX i ON abc(a)', 'def')
  32. ** -> 'CREATE INDEX i ON def(a, b, c)'
  33. */
  34. static void renameTableFunc(
  35. sqlite3_context *context,
  36. int NotUsed,
  37. sqlite3_value **argv
  38. ){
  39. unsigned char const *zSql = sqlite3_value_text(argv[0]);
  40. unsigned char const *zTableName = sqlite3_value_text(argv[1]);
  41. int token;
  42. Token tname;
  43. unsigned char const *zCsr = zSql;
  44. int len = 0;
  45. char *zRet;
  46. sqlite3 *db = sqlite3_context_db_handle(context);
  47. UNUSED_PARAMETER(NotUsed);
  48. /* The principle used to locate the table name in the CREATE TABLE
  49. ** statement is that the table name is the first non-space token that
  50. ** is immediately followed by a TK_LP or TK_USING token.
  51. */
  52. if( zSql ){
  53. do {
  54. if( !*zCsr ){
  55. /* Ran out of input before finding an opening bracket. Return NULL. */
  56. return;
  57. }
  58. /* Store the token that zCsr points to in tname. */
  59. tname.z = (char*)zCsr;
  60. tname.n = len;
  61. /* Advance zCsr to the next token. Store that token type in 'token',
  62. ** and its length in 'len' (to be used next iteration of this loop).
  63. */
  64. do {
  65. zCsr += len;
  66. len = sqlite3GetToken(zCsr, &token);
  67. } while( token==TK_SPACE );
  68. assert( len>0 );
  69. } while( token!=TK_LP && token!=TK_USING );
  70. zRet = sqlite3MPrintf(db, "%.*s\"%w\"%s", ((u8*)tname.z) - zSql, zSql,
  71. zTableName, tname.z+tname.n);
  72. sqlite3_result_text(context, zRet, -1, SQLITE_DYNAMIC);
  73. }
  74. }
  75. /*
  76. ** This C function implements an SQL user function that is used by SQL code
  77. ** generated by the ALTER TABLE ... RENAME command to modify the definition
  78. ** of any foreign key constraints that use the table being renamed as the
  79. ** parent table. It is passed three arguments:
  80. **
  81. ** 1) The complete text of the CREATE TABLE statement being modified,
  82. ** 2) The old name of the table being renamed, and
  83. ** 3) The new name of the table being renamed.
  84. **
  85. ** It returns the new CREATE TABLE statement. For example:
  86. **
  87. ** sqlite_rename_parent('CREATE TABLE t1(a REFERENCES t2)', 't2', 't3')
  88. ** -> 'CREATE TABLE t1(a REFERENCES t3)'
  89. */
  90. #ifndef SQLITE_OMIT_FOREIGN_KEY
  91. static void renameParentFunc(
  92. sqlite3_context *context,
  93. int NotUsed,
  94. sqlite3_value **argv
  95. ){
  96. sqlite3 *db = sqlite3_context_db_handle(context);
  97. char *zOutput = 0;
  98. char *zResult;
  99. unsigned char const *zInput = sqlite3_value_text(argv[0]);
  100. unsigned char const *zOld = sqlite3_value_text(argv[1]);
  101. unsigned char const *zNew = sqlite3_value_text(argv[2]);
  102. unsigned const char *z; /* Pointer to token */
  103. int n; /* Length of token z */
  104. int token; /* Type of token */
  105. UNUSED_PARAMETER(NotUsed);
  106. for(z=zInput; *z; z=z+n){
  107. n = sqlite3GetToken(z, &token);
  108. if( token==TK_REFERENCES ){
  109. char *zParent;
  110. do {
  111. z += n;
  112. n = sqlite3GetToken(z, &token);
  113. }while( token==TK_SPACE );
  114. zParent = sqlite3DbStrNDup(db, (const char *)z, n);
  115. if( zParent==0 ) break;
  116. sqlite3Dequote(zParent);
  117. if( 0==sqlite3StrICmp((const char *)zOld, zParent) ){
  118. char *zOut = sqlite3MPrintf(db, "%s%.*s\"%w\"",
  119. (zOutput?zOutput:""), z-zInput, zInput, (const char *)zNew
  120. );
  121. sqlite3DbFree(db, zOutput);
  122. zOutput = zOut;
  123. zInput = &z[n];
  124. }
  125. sqlite3DbFree(db, zParent);
  126. }
  127. }
  128. zResult = sqlite3MPrintf(db, "%s%s", (zOutput?zOutput:""), zInput),
  129. sqlite3_result_text(context, zResult, -1, SQLITE_DYNAMIC);
  130. sqlite3DbFree(db, zOutput);
  131. }
  132. #endif
  133. #ifndef SQLITE_OMIT_TRIGGER
  134. /* This function is used by SQL generated to implement the
  135. ** ALTER TABLE command. The first argument is the text of a CREATE TRIGGER
  136. ** statement. The second is a table name. The table name in the CREATE
  137. ** TRIGGER statement is replaced with the third argument and the result
  138. ** returned. This is analagous to renameTableFunc() above, except for CREATE
  139. ** TRIGGER, not CREATE INDEX and CREATE TABLE.
  140. */
  141. static void renameTriggerFunc(
  142. sqlite3_context *context,
  143. int NotUsed,
  144. sqlite3_value **argv
  145. ){
  146. unsigned char const *zSql = sqlite3_value_text(argv[0]);
  147. unsigned char const *zTableName = sqlite3_value_text(argv[1]);
  148. int token;
  149. Token tname;
  150. int dist = 3;
  151. unsigned char const *zCsr = zSql;
  152. int len = 0;
  153. char *zRet;
  154. sqlite3 *db = sqlite3_context_db_handle(context);
  155. UNUSED_PARAMETER(NotUsed);
  156. /* The principle used to locate the table name in the CREATE TRIGGER
  157. ** statement is that the table name is the first token that is immediatedly
  158. ** preceded by either TK_ON or TK_DOT and immediatedly followed by one
  159. ** of TK_WHEN, TK_BEGIN or TK_FOR.
  160. */
  161. if( zSql ){
  162. do {
  163. if( !*zCsr ){
  164. /* Ran out of input before finding the table name. Return NULL. */
  165. return;
  166. }
  167. /* Store the token that zCsr points to in tname. */
  168. tname.z = (char*)zCsr;
  169. tname.n = len;
  170. /* Advance zCsr to the next token. Store that token type in 'token',
  171. ** and its length in 'len' (to be used next iteration of this loop).
  172. */
  173. do {
  174. zCsr += len;
  175. len = sqlite3GetToken(zCsr, &token);
  176. }while( token==TK_SPACE );
  177. assert( len>0 );
  178. /* Variable 'dist' stores the number of tokens read since the most
  179. ** recent TK_DOT or TK_ON. This means that when a WHEN, FOR or BEGIN
  180. ** token is read and 'dist' equals 2, the condition stated above
  181. ** to be met.
  182. **
  183. ** Note that ON cannot be a database, table or column name, so
  184. ** there is no need to worry about syntax like
  185. ** "CREATE TRIGGER ... ON ON.ON BEGIN ..." etc.
  186. */
  187. dist++;
  188. if( token==TK_DOT || token==TK_ON ){
  189. dist = 0;
  190. }
  191. } while( dist!=2 || (token!=TK_WHEN && token!=TK_FOR && token!=TK_BEGIN) );
  192. /* Variable tname now contains the token that is the old table-name
  193. ** in the CREATE TRIGGER statement.
  194. */
  195. zRet = sqlite3MPrintf(db, "%.*s\"%w\"%s", ((u8*)tname.z) - zSql, zSql,
  196. zTableName, tname.z+tname.n);
  197. sqlite3_result_text(context, zRet, -1, SQLITE_DYNAMIC);
  198. }
  199. }
  200. #endif /* !SQLITE_OMIT_TRIGGER */
  201. /*
  202. ** Register built-in functions used to help implement ALTER TABLE
  203. */
  204. void sqlite3AlterFunctions(void){
  205. static SQLITE_WSD FuncDef aAlterTableFuncs[] = {
  206. FUNCTION(sqlite_rename_table, 2, 0, 0, renameTableFunc),
  207. #ifndef SQLITE_OMIT_TRIGGER
  208. FUNCTION(sqlite_rename_trigger, 2, 0, 0, renameTriggerFunc),
  209. #endif
  210. #ifndef SQLITE_OMIT_FOREIGN_KEY
  211. FUNCTION(sqlite_rename_parent, 3, 0, 0, renameParentFunc),
  212. #endif
  213. };
  214. int i;
  215. FuncDefHash *pHash = &GLOBAL(FuncDefHash, sqlite3GlobalFunctions);
  216. FuncDef *aFunc = (FuncDef*)&GLOBAL(FuncDef, aAlterTableFuncs);
  217. for(i=0; i<ArraySize(aAlterTableFuncs); i++){
  218. sqlite3FuncDefInsert(pHash, &aFunc[i]);
  219. }
  220. }
  221. /*
  222. ** This function is used to create the text of expressions of the form:
  223. **
  224. ** name=<constant1> OR name=<constant2> OR ...
  225. **
  226. ** If argument zWhere is NULL, then a pointer string containing the text
  227. ** "name=<constant>" is returned, where <constant> is the quoted version
  228. ** of the string passed as argument zConstant. The returned buffer is
  229. ** allocated using sqlite3DbMalloc(). It is the responsibility of the
  230. ** caller to ensure that it is eventually freed.
  231. **
  232. ** If argument zWhere is not NULL, then the string returned is
  233. ** "<where> OR name=<constant>", where <where> is the contents of zWhere.
  234. ** In this case zWhere is passed to sqlite3DbFree() before returning.
  235. **
  236. */
  237. static char *whereOrName(sqlite3 *db, char *zWhere, char *zConstant){
  238. char *zNew;
  239. if( !zWhere ){
  240. zNew = sqlite3MPrintf(db, "name=%Q", zConstant);
  241. }else{
  242. zNew = sqlite3MPrintf(db, "%s OR name=%Q", zWhere, zConstant);
  243. sqlite3DbFree(db, zWhere);
  244. }
  245. return zNew;
  246. }
  247. #if !defined(SQLITE_OMIT_FOREIGN_KEY) && !defined(SQLITE_OMIT_TRIGGER)
  248. /*
  249. ** Generate the text of a WHERE expression which can be used to select all
  250. ** tables that have foreign key constraints that refer to table pTab (i.e.
  251. ** constraints for which pTab is the parent table) from the sqlite_master
  252. ** table.
  253. */
  254. static char *whereForeignKeys(Parse *pParse, Table *pTab){
  255. FKey *p;
  256. char *zWhere = 0;
  257. for(p=sqlite3FkReferences(pTab); p; p=p->pNextTo){
  258. zWhere = whereOrName(pParse->db, zWhere, p->pFrom->zName);
  259. }
  260. return zWhere;
  261. }
  262. #endif
  263. /*
  264. ** Generate the text of a WHERE expression which can be used to select all
  265. ** temporary triggers on table pTab from the sqlite_temp_master table. If
  266. ** table pTab has no temporary triggers, or is itself stored in the
  267. ** temporary database, NULL is returned.
  268. */
  269. static char *whereTempTriggers(Parse *pParse, Table *pTab){
  270. Trigger *pTrig;
  271. char *zWhere = 0;
  272. const Schema *pTempSchema = pParse->db->aDb[1].pSchema; /* Temp db schema */
  273. /* If the table is not located in the temp-db (in which case NULL is
  274. ** returned, loop through the tables list of triggers. For each trigger
  275. ** that is not part of the temp-db schema, add a clause to the WHERE
  276. ** expression being built up in zWhere.
  277. */
  278. if( pTab->pSchema!=pTempSchema ){
  279. sqlite3 *db = pParse->db;
  280. for(pTrig=sqlite3TriggerList(pParse, pTab); pTrig; pTrig=pTrig->pNext){
  281. if( pTrig->pSchema==pTempSchema ){
  282. zWhere = whereOrName(db, zWhere, pTrig->zName);
  283. }
  284. }
  285. }
  286. if( zWhere ){
  287. char *zNew = sqlite3MPrintf(pParse->db, "type='trigger' AND (%s)", zWhere);
  288. sqlite3DbFree(pParse->db, zWhere);
  289. zWhere = zNew;
  290. }
  291. return zWhere;
  292. }
  293. /*
  294. ** Generate code to drop and reload the internal representation of table
  295. ** pTab from the database, including triggers and temporary triggers.
  296. ** Argument zName is the name of the table in the database schema at
  297. ** the time the generated code is executed. This can be different from
  298. ** pTab->zName if this function is being called to code part of an
  299. ** "ALTER TABLE RENAME TO" statement.
  300. */
  301. static void reloadTableSchema(Parse *pParse, Table *pTab, const char *zName){
  302. Vdbe *v;
  303. char *zWhere;
  304. int iDb; /* Index of database containing pTab */
  305. #ifndef SQLITE_OMIT_TRIGGER
  306. Trigger *pTrig;
  307. #endif
  308. v = sqlite3GetVdbe(pParse);
  309. if( NEVER(v==0) ) return;
  310. assert( sqlite3BtreeHoldsAllMutexes(pParse->db) );
  311. iDb = sqlite3SchemaToIndex(pParse->db, pTab->pSchema);
  312. assert( iDb>=0 );
  313. #ifndef SQLITE_OMIT_TRIGGER
  314. /* Drop any table triggers from the internal schema. */
  315. for(pTrig=sqlite3TriggerList(pParse, pTab); pTrig; pTrig=pTrig->pNext){
  316. int iTrigDb = sqlite3SchemaToIndex(pParse->db, pTrig->pSchema);
  317. assert( iTrigDb==iDb || iTrigDb==1 );
  318. sqlite3VdbeAddOp4(v, OP_DropTrigger, iTrigDb, 0, 0, pTrig->zName, 0);
  319. }
  320. #endif
  321. /* Drop the table and index from the internal schema. */
  322. sqlite3VdbeAddOp4(v, OP_DropTable, iDb, 0, 0, pTab->zName, 0);
  323. /* Reload the table, index and permanent trigger schemas. */
  324. zWhere = sqlite3MPrintf(pParse->db, "tbl_name=%Q", zName);
  325. if( !zWhere ) return;
  326. sqlite3VdbeAddParseSchemaOp(v, iDb, zWhere);
  327. #ifndef SQLITE_OMIT_TRIGGER
  328. /* Now, if the table is not stored in the temp database, reload any temp
  329. ** triggers. Don't use IN(...) in case SQLITE_OMIT_SUBQUERY is defined.
  330. */
  331. if( (zWhere=whereTempTriggers(pParse, pTab))!=0 ){
  332. sqlite3VdbeAddParseSchemaOp(v, 1, zWhere);
  333. }
  334. #endif
  335. }
  336. /*
  337. ** Parameter zName is the name of a table that is about to be altered
  338. ** (either with ALTER TABLE ... RENAME TO or ALTER TABLE ... ADD COLUMN).
  339. ** If the table is a system table, this function leaves an error message
  340. ** in pParse->zErr (system tables may not be altered) and returns non-zero.
  341. **
  342. ** Or, if zName is not a system table, zero is returned.
  343. */
  344. static int isSystemTable(Parse *pParse, const char *zName){
  345. if( sqlite3Strlen30(zName)>6 && 0==sqlite3StrNICmp(zName, "sqlite_", 7) ){
  346. sqlite3ErrorMsg(pParse, "table %s may not be altered", zName);
  347. return 1;
  348. }
  349. return 0;
  350. }
  351. /*
  352. ** Generate code to implement the "ALTER TABLE xxx RENAME TO yyy"
  353. ** command.
  354. */
  355. void sqlite3AlterRenameTable(
  356. Parse *pParse, /* Parser context. */
  357. SrcList *pSrc, /* The table to rename. */
  358. Token *pName /* The new table name. */
  359. ){
  360. int iDb; /* Database that contains the table */
  361. char *zDb; /* Name of database iDb */
  362. Table *pTab; /* Table being renamed */
  363. char *zName = 0; /* NULL-terminated version of pName */
  364. sqlite3 *db = pParse->db; /* Database connection */
  365. int nTabName; /* Number of UTF-8 characters in zTabName */
  366. const char *zTabName; /* Original name of the table */
  367. Vdbe *v;
  368. #ifndef SQLITE_OMIT_TRIGGER
  369. char *zWhere = 0; /* Where clause to locate temp triggers */
  370. #endif
  371. VTable *pVTab = 0; /* Non-zero if this is a v-tab with an xRename() */
  372. int savedDbFlags; /* Saved value of db->flags */
  373. savedDbFlags = db->flags;
  374. if( NEVER(db->mallocFailed) ) goto exit_rename_table;
  375. assert( pSrc->nSrc==1 );
  376. assert( sqlite3BtreeHoldsAllMutexes(pParse->db) );
  377. pTab = sqlite3LocateTableItem(pParse, 0, &pSrc->a[0]);
  378. if( !pTab ) goto exit_rename_table;
  379. iDb = sqlite3SchemaToIndex(pParse->db, pTab->pSchema);
  380. zDb = db->aDb[iDb].zName;
  381. db->flags |= SQLITE_PreferBuiltin;
  382. /* Get a NULL terminated version of the new table name. */
  383. zName = sqlite3NameFromToken(db, pName);
  384. if( !zName ) goto exit_rename_table;
  385. /* Check that a table or index named 'zName' does not already exist
  386. ** in database iDb. If so, this is an error.
  387. */
  388. if( sqlite3FindTable(db, zName, zDb) || sqlite3FindIndex(db, zName, zDb) ){
  389. sqlite3ErrorMsg(pParse,
  390. "there is already another table or index with this name: %s", zName);
  391. goto exit_rename_table;
  392. }
  393. /* Make sure it is not a system table being altered, or a reserved name
  394. ** that the table is being renamed to.
  395. */
  396. if( SQLITE_OK!=isSystemTable(pParse, pTab->zName) ){
  397. goto exit_rename_table;
  398. }
  399. if( SQLITE_OK!=sqlite3CheckObjectName(pParse, zName) ){ goto
  400. exit_rename_table;
  401. }
  402. #ifndef SQLITE_OMIT_VIEW
  403. if( pTab->pSelect ){
  404. sqlite3ErrorMsg(pParse, "view %s may not be altered", pTab->zName);
  405. goto exit_rename_table;
  406. }
  407. #endif
  408. #ifndef SQLITE_OMIT_AUTHORIZATION
  409. /* Invoke the authorization callback. */
  410. if( sqlite3AuthCheck(pParse, SQLITE_ALTER_TABLE, zDb, pTab->zName, 0) ){
  411. goto exit_rename_table;
  412. }
  413. #endif
  414. #ifndef SQLITE_OMIT_VIRTUALTABLE
  415. if( sqlite3ViewGetColumnNames(pParse, pTab) ){
  416. goto exit_rename_table;
  417. }
  418. if( IsVirtual(pTab) ){
  419. pVTab = sqlite3GetVTable(db, pTab);
  420. if( pVTab->pVtab->pModule->xRename==0 ){
  421. pVTab = 0;
  422. }
  423. }
  424. #endif
  425. /* Begin a transaction and code the VerifyCookie for database iDb.
  426. ** Then modify the schema cookie (since the ALTER TABLE modifies the
  427. ** schema). Open a statement transaction if the table is a virtual
  428. ** table.
  429. */
  430. v = sqlite3GetVdbe(pParse);
  431. if( v==0 ){
  432. goto exit_rename_table;
  433. }
  434. sqlite3BeginWriteOperation(pParse, pVTab!=0, iDb);
  435. sqlite3ChangeCookie(pParse, iDb);
  436. /* If this is a virtual table, invoke the xRename() function if
  437. ** one is defined. The xRename() callback will modify the names
  438. ** of any resources used by the v-table implementation (including other
  439. ** SQLite tables) that are identified by the name of the virtual table.
  440. */
  441. #ifndef SQLITE_OMIT_VIRTUALTABLE
  442. if( pVTab ){
  443. int i = ++pParse->nMem;
  444. sqlite3VdbeAddOp4(v, OP_String8, 0, i, 0, zName, 0);
  445. sqlite3VdbeAddOp4(v, OP_VRename, i, 0, 0,(const char*)pVTab, P4_VTAB);
  446. sqlite3MayAbort(pParse);
  447. }
  448. #endif
  449. /* figure out how many UTF-8 characters are in zName */
  450. zTabName = pTab->zName;
  451. nTabName = sqlite3Utf8CharLen(zTabName, -1);
  452. #if !defined(SQLITE_OMIT_FOREIGN_KEY) && !defined(SQLITE_OMIT_TRIGGER)
  453. if( db->flags&SQLITE_ForeignKeys ){
  454. /* If foreign-key support is enabled, rewrite the CREATE TABLE
  455. ** statements corresponding to all child tables of foreign key constraints
  456. ** for which the renamed table is the parent table. */
  457. if( (zWhere=whereForeignKeys(pParse, pTab))!=0 ){
  458. sqlite3NestedParse(pParse,
  459. "UPDATE \"%w\".%s SET "
  460. "sql = sqlite_rename_parent(sql, %Q, %Q) "
  461. "WHERE %s;", zDb, SCHEMA_TABLE(iDb), zTabName, zName, zWhere);
  462. sqlite3DbFree(db, zWhere);
  463. }
  464. }
  465. #endif
  466. /* Modify the sqlite_master table to use the new table name. */
  467. sqlite3NestedParse(pParse,
  468. "UPDATE %Q.%s SET "
  469. #ifdef SQLITE_OMIT_TRIGGER
  470. "sql = sqlite_rename_table(sql, %Q), "
  471. #else
  472. "sql = CASE "
  473. "WHEN type = 'trigger' THEN sqlite_rename_trigger(sql, %Q)"
  474. "ELSE sqlite_rename_table(sql, %Q) END, "
  475. #endif
  476. "tbl_name = %Q, "
  477. "name = CASE "
  478. "WHEN type='table' THEN %Q "
  479. "WHEN name LIKE 'sqlite_autoindex%%' AND type='index' THEN "
  480. "'sqlite_autoindex_' || %Q || substr(name,%d+18) "
  481. "ELSE name END "
  482. "WHERE tbl_name=%Q COLLATE nocase AND "
  483. "(type='table' OR type='index' OR type='trigger');",
  484. zDb, SCHEMA_TABLE(iDb), zName, zName, zName,
  485. #ifndef SQLITE_OMIT_TRIGGER
  486. zName,
  487. #endif
  488. zName, nTabName, zTabName
  489. );
  490. #ifndef SQLITE_OMIT_AUTOINCREMENT
  491. /* If the sqlite_sequence table exists in this database, then update
  492. ** it with the new table name.
  493. */
  494. if( sqlite3FindTable(db, "sqlite_sequence", zDb) ){
  495. sqlite3NestedParse(pParse,
  496. "UPDATE \"%w\".sqlite_sequence set name = %Q WHERE name = %Q",
  497. zDb, zName, pTab->zName);
  498. }
  499. #endif
  500. #ifndef SQLITE_OMIT_TRIGGER
  501. /* If there are TEMP triggers on this table, modify the sqlite_temp_master
  502. ** table. Don't do this if the table being ALTERed is itself located in
  503. ** the temp database.
  504. */
  505. if( (zWhere=whereTempTriggers(pParse, pTab))!=0 ){
  506. sqlite3NestedParse(pParse,
  507. "UPDATE sqlite_temp_master SET "
  508. "sql = sqlite_rename_trigger(sql, %Q), "
  509. "tbl_name = %Q "
  510. "WHERE %s;", zName, zName, zWhere);
  511. sqlite3DbFree(db, zWhere);
  512. }
  513. #endif
  514. #if !defined(SQLITE_OMIT_FOREIGN_KEY) && !defined(SQLITE_OMIT_TRIGGER)
  515. if( db->flags&SQLITE_ForeignKeys ){
  516. FKey *p;
  517. for(p=sqlite3FkReferences(pTab); p; p=p->pNextTo){
  518. Table *pFrom = p->pFrom;
  519. if( pFrom!=pTab ){
  520. reloadTableSchema(pParse, p->pFrom, pFrom->zName);
  521. }
  522. }
  523. }
  524. #endif
  525. /* Drop and reload the internal table schema. */
  526. reloadTableSchema(pParse, pTab, zName);
  527. exit_rename_table:
  528. sqlite3SrcListDelete(db, pSrc);
  529. sqlite3DbFree(db, zName);
  530. db->flags = savedDbFlags;
  531. }
  532. /*
  533. ** Generate code to make sure the file format number is at least minFormat.
  534. ** The generated code will increase the file format number if necessary.
  535. */
  536. void sqlite3MinimumFileFormat(Parse *pParse, int iDb, int minFormat){
  537. Vdbe *v;
  538. v = sqlite3GetVdbe(pParse);
  539. /* The VDBE should have been allocated before this routine is called.
  540. ** If that allocation failed, we would have quit before reaching this
  541. ** point */
  542. if( ALWAYS(v) ){
  543. int r1 = sqlite3GetTempReg(pParse);
  544. int r2 = sqlite3GetTempReg(pParse);
  545. int j1;
  546. sqlite3VdbeAddOp3(v, OP_ReadCookie, iDb, r1, BTREE_FILE_FORMAT);
  547. sqlite3VdbeUsesBtree(v, iDb);
  548. sqlite3VdbeAddOp2(v, OP_Integer, minFormat, r2);
  549. j1 = sqlite3VdbeAddOp3(v, OP_Ge, r2, 0, r1);
  550. sqlite3VdbeAddOp3(v, OP_SetCookie, iDb, BTREE_FILE_FORMAT, r2);
  551. sqlite3VdbeJumpHere(v, j1);
  552. sqlite3ReleaseTempReg(pParse, r1);
  553. sqlite3ReleaseTempReg(pParse, r2);
  554. }
  555. }
  556. /*
  557. ** This function is called after an "ALTER TABLE ... ADD" statement
  558. ** has been parsed. Argument pColDef contains the text of the new
  559. ** column definition.
  560. **
  561. ** The Table structure pParse->pNewTable was extended to include
  562. ** the new column during parsing.
  563. */
  564. void sqlite3AlterFinishAddColumn(Parse *pParse, Token *pColDef){
  565. Table *pNew; /* Copy of pParse->pNewTable */
  566. Table *pTab; /* Table being altered */
  567. int iDb; /* Database number */
  568. const char *zDb; /* Database name */
  569. const char *zTab; /* Table name */
  570. char *zCol; /* Null-terminated column definition */
  571. Column *pCol; /* The new column */
  572. Expr *pDflt; /* Default value for the new column */
  573. sqlite3 *db; /* The database connection; */
  574. db = pParse->db;
  575. if( pParse->nErr || db->mallocFailed ) return;
  576. pNew = pParse->pNewTable;
  577. assert( pNew );
  578. assert( sqlite3BtreeHoldsAllMutexes(db) );
  579. iDb = sqlite3SchemaToIndex(db, pNew->pSchema);
  580. zDb = db->aDb[iDb].zName;
  581. zTab = &pNew->zName[16]; /* Skip the "sqlite_altertab_" prefix on the name */
  582. pCol = &pNew->aCol[pNew->nCol-1];
  583. pDflt = pCol->pDflt;
  584. pTab = sqlite3FindTable(db, zTab, zDb);
  585. assert( pTab );
  586. #ifndef SQLITE_OMIT_AUTHORIZATION
  587. /* Invoke the authorization callback. */
  588. if( sqlite3AuthCheck(pParse, SQLITE_ALTER_TABLE, zDb, pTab->zName, 0) ){
  589. return;
  590. }
  591. #endif
  592. /* If the default value for the new column was specified with a
  593. ** literal NULL, then set pDflt to 0. This simplifies checking
  594. ** for an SQL NULL default below.
  595. */
  596. if( pDflt && pDflt->op==TK_NULL ){
  597. pDflt = 0;
  598. }
  599. /* Check that the new column is not specified as PRIMARY KEY or UNIQUE.
  600. ** If there is a NOT NULL constraint, then the default value for the
  601. ** column must not be NULL.
  602. */
  603. if( pCol->colFlags & COLFLAG_PRIMKEY ){
  604. sqlite3ErrorMsg(pParse, "Cannot add a PRIMARY KEY column");
  605. return;
  606. }
  607. if( pNew->pIndex ){
  608. sqlite3ErrorMsg(pParse, "Cannot add a UNIQUE column");
  609. return;
  610. }
  611. if( (db->flags&SQLITE_ForeignKeys) && pNew->pFKey && pDflt ){
  612. sqlite3ErrorMsg(pParse,
  613. "Cannot add a REFERENCES column with non-NULL default value");
  614. return;
  615. }
  616. if( pCol->notNull && !pDflt ){
  617. sqlite3ErrorMsg(pParse,
  618. "Cannot add a NOT NULL column with default value NULL");
  619. return;
  620. }
  621. /* Ensure the default expression is something that sqlite3ValueFromExpr()
  622. ** can handle (i.e. not CURRENT_TIME etc.)
  623. */
  624. if( pDflt ){
  625. sqlite3_value *pVal = 0;
  626. if( sqlite3ValueFromExpr(db, pDflt, SQLITE_UTF8, SQLITE_AFF_NONE, &pVal) ){
  627. db->mallocFailed = 1;
  628. return;
  629. }
  630. if( !pVal ){
  631. sqlite3ErrorMsg(pParse, "Cannot add a column with non-constant default");
  632. return;
  633. }
  634. sqlite3ValueFree(pVal);
  635. }
  636. /* Modify the CREATE TABLE statement. */
  637. zCol = sqlite3DbStrNDup(db, (char*)pColDef->z, pColDef->n);
  638. if( zCol ){
  639. char *zEnd = &zCol[pColDef->n-1];
  640. int savedDbFlags = db->flags;
  641. while( zEnd>zCol && (*zEnd==';' || sqlite3Isspace(*zEnd)) ){
  642. *zEnd-- = '\0';
  643. }
  644. db->flags |= SQLITE_PreferBuiltin;
  645. sqlite3NestedParse(pParse,
  646. "UPDATE \"%w\".%s SET "
  647. "sql = substr(sql,1,%d) || ', ' || %Q || substr(sql,%d) "
  648. "WHERE type = 'table' AND name = %Q",
  649. zDb, SCHEMA_TABLE(iDb), pNew->addColOffset, zCol, pNew->addColOffset+1,
  650. zTab
  651. );
  652. sqlite3DbFree(db, zCol);
  653. db->flags = savedDbFlags;
  654. }
  655. /* If the default value of the new column is NULL, then set the file
  656. ** format to 2. If the default value of the new column is not NULL,
  657. ** the file format becomes 3.
  658. */
  659. sqlite3MinimumFileFormat(pParse, iDb, pDflt ? 3 : 2);
  660. /* Reload the schema of the modified table. */
  661. reloadTableSchema(pParse, pTab, pTab->zName);
  662. }
  663. /*
  664. ** This function is called by the parser after the table-name in
  665. ** an "ALTER TABLE <table-name> ADD" statement is parsed. Argument
  666. ** pSrc is the full-name of the table being altered.
  667. **
  668. ** This routine makes a (partial) copy of the Table structure
  669. ** for the table being altered and sets Parse.pNewTable to point
  670. ** to it. Routines called by the parser as the column definition
  671. ** is parsed (i.e. sqlite3AddColumn()) add the new Column data to
  672. ** the copy. The copy of the Table structure is deleted by tokenize.c
  673. ** after parsing is finished.
  674. **
  675. ** Routine sqlite3AlterFinishAddColumn() will be called to complete
  676. ** coding the "ALTER TABLE ... ADD" statement.
  677. */
  678. void sqlite3AlterBeginAddColumn(Parse *pParse, SrcList *pSrc){
  679. Table *pNew;
  680. Table *pTab;
  681. Vdbe *v;
  682. int iDb;
  683. int i;
  684. int nAlloc;
  685. sqlite3 *db = pParse->db;
  686. /* Look up the table being altered. */
  687. assert( pParse->pNewTable==0 );
  688. assert( sqlite3BtreeHoldsAllMutexes(db) );
  689. if( db->mallocFailed ) goto exit_begin_add_column;
  690. pTab = sqlite3LocateTableItem(pParse, 0, &pSrc->a[0]);
  691. if( !pTab ) goto exit_begin_add_column;
  692. #ifndef SQLITE_OMIT_VIRTUALTABLE
  693. if( IsVirtual(pTab) ){
  694. sqlite3ErrorMsg(pParse, "virtual tables may not be altered");
  695. goto exit_begin_add_column;
  696. }
  697. #endif
  698. /* Make sure this is not an attempt to ALTER a view. */
  699. if( pTab->pSelect ){
  700. sqlite3ErrorMsg(pParse, "Cannot add a column to a view");
  701. goto exit_begin_add_column;
  702. }
  703. if( SQLITE_OK!=isSystemTable(pParse, pTab->zName) ){
  704. goto exit_begin_add_column;
  705. }
  706. assert( pTab->addColOffset>0 );
  707. iDb = sqlite3SchemaToIndex(db, pTab->pSchema);
  708. /* Put a copy of the Table struct in Parse.pNewTable for the
  709. ** sqlite3AddColumn() function and friends to modify. But modify
  710. ** the name by adding an "sqlite_altertab_" prefix. By adding this
  711. ** prefix, we insure that the name will not collide with an existing
  712. ** table because user table are not allowed to have the "sqlite_"
  713. ** prefix on their name.
  714. */
  715. pNew = (Table*)sqlite3DbMallocZero(db, sizeof(Table));
  716. if( !pNew ) goto exit_begin_add_column;
  717. pParse->pNewTable = pNew;
  718. pNew->nRef = 1;
  719. pNew->nCol = pTab->nCol;
  720. assert( pNew->nCol>0 );
  721. nAlloc = (((pNew->nCol-1)/8)*8)+8;
  722. assert( nAlloc>=pNew->nCol && nAlloc%8==0 && nAlloc-pNew->nCol<8 );
  723. pNew->aCol = (Column*)sqlite3DbMallocZero(db, sizeof(Column)*nAlloc);
  724. pNew->zName = sqlite3MPrintf(db, "sqlite_altertab_%s", pTab->zName);
  725. if( !pNew->aCol || !pNew->zName ){
  726. db->mallocFailed = 1;
  727. goto exit_begin_add_column;
  728. }
  729. memcpy(pNew->aCol, pTab->aCol, sizeof(Column)*pNew->nCol);
  730. for(i=0; i<pNew->nCol; i++){
  731. Column *pCol = &pNew->aCol[i];
  732. pCol->zName = sqlite3DbStrDup(db, pCol->zName);
  733. pCol->zColl = 0;
  734. pCol->zType = 0;
  735. pCol->pDflt = 0;
  736. pCol->zDflt = 0;
  737. }
  738. pNew->pSchema = db->aDb[iDb].pSchema;
  739. pNew->addColOffset = pTab->addColOffset;
  740. pNew->nRef = 1;
  741. /* Begin a transaction and increment the schema cookie. */
  742. sqlite3BeginWriteOperation(pParse, 0, iDb);
  743. v = sqlite3GetVdbe(pParse);
  744. if( !v ) goto exit_begin_add_column;
  745. sqlite3ChangeCookie(pParse, iDb);
  746. exit_begin_add_column:
  747. sqlite3SrcListDelete(db, pSrc);
  748. return;
  749. }
  750. #endif /* SQLITE_ALTER_TABLE */