PageRenderTime 56ms CodeModel.GetById 3ms RepoModel.GetById 0ms app.codeStats 1ms

/library/Library/WP7/SQLiteDriver/sqlite/build_c.cs

https://bitbucket.org/digitalizarte/coolstorage
C# | 4331 lines | 3723 code | 86 blank | 522 comment | 288 complexity | e464bb4162b4f5b8e141695420744dce MD5 | raw file

Large files files are truncated, but you can click here to view the full file

  1. using System;
  2. using System.Diagnostics;
  3. using System.IO;
  4. using System.Text;
  5. using i16 = System.Int16;
  6. using u8 = System.Byte;
  7. using u16 = System.UInt16;
  8. using u32 = System.UInt32;
  9. using Pgno = System.UInt32;
  10. namespace Community.CsharpSqlite
  11. {
  12. public partial class Sqlite3
  13. {
  14. /*
  15. ** 2001 September 15
  16. **
  17. ** The author disclaims copyright to this source code. In place of
  18. ** a legal notice, here is a blessing:
  19. **
  20. ** May you do good and not evil.
  21. ** May you find forgiveness for yourself and forgive others.
  22. ** May you share freely, never taking more than you give.
  23. **
  24. *************************************************************************
  25. ** This file contains C code routines that are called by the SQLite parser
  26. ** when syntax rules are reduced. The routines in this file handle the
  27. ** following kinds of SQL syntax:
  28. **
  29. ** CREATE TABLE
  30. ** DROP TABLE
  31. ** CREATE INDEX
  32. ** DROP INDEX
  33. ** creating ID lists
  34. ** BEGIN TRANSACTION
  35. ** COMMIT
  36. ** ROLLBACK
  37. *************************************************************************
  38. ** Included in SQLite3 port to C#-SQLite; 2008 Noah B Hart
  39. ** C#-SQLite is an independent reimplementation of the SQLite software library
  40. **
  41. ** SQLITE_SOURCE_ID: 2010-12-07 20:14:09 a586a4deeb25330037a49df295b36aaf624d0f45
  42. **
  43. *************************************************************************
  44. */
  45. //#include "sqliteInt.h"
  46. /*
  47. ** This routine is called when a new SQL statement is beginning to
  48. ** be parsed. Initialize the pParse structure as needed.
  49. */
  50. static void sqlite3BeginParse( Parse pParse, int explainFlag )
  51. {
  52. pParse.explain = (byte)explainFlag;
  53. pParse.nVar = 0;
  54. }
  55. #if !SQLITE_OMIT_SHARED_CACHE
  56. /*
  57. ** The TableLock structure is only used by the sqlite3TableLock() and
  58. ** codeTableLocks() functions.
  59. */
  60. //struct TableLock {
  61. // int iDb; /* The database containing the table to be locked */
  62. // int iTab; /* The root page of the table to be locked */
  63. // u8 isWriteLock; /* True for write lock. False for a read lock */
  64. // string zName; /* Name of the table */
  65. //};
  66. public class TableLock
  67. {
  68. public int iDb; /* The database containing the table to be locked */
  69. public int iTab; /* The root page of the table to be locked */
  70. public u8 isWriteLock; /* True for write lock. False for a read lock */
  71. public string zName; /* Name of the table */
  72. }
  73. /*
  74. ** Record the fact that we want to lock a table at run-time.
  75. **
  76. ** The table to be locked has root page iTab and is found in database iDb.
  77. ** A read or a write lock can be taken depending on isWritelock.
  78. **
  79. ** This routine just records the fact that the lock is desired. The
  80. ** code to make the lock occur is generated by a later call to
  81. ** codeTableLocks() which occurs during sqlite3FinishCoding().
  82. */
  83. void sqlite3TableLock(
  84. Parse *pParse, /* Parsing context */
  85. int iDb, /* Index of the database containing the table to lock */
  86. int iTab, /* Root page number of the table to be locked */
  87. u8 isWriteLock, /* True for a write lock */
  88. const char *zName /* Name of the table to be locked */
  89. ){
  90. Parse *pToplevel = sqlite3ParseToplevel(pParse);
  91. int i;
  92. int nBytes;
  93. TableLock *p;
  94. assert( iDb>=0 );
  95. for(i=0; i<pToplevel->nTableLock; i++){
  96. p = &pToplevel->aTableLock[i];
  97. if( p->iDb==iDb && p->iTab==iTab ){
  98. p->isWriteLock = (p->isWriteLock || isWriteLock);
  99. return;
  100. }
  101. }
  102. nBytes = sizeof(TableLock) * (pToplevel->nTableLock+1);
  103. pToplevel->aTableLock =
  104. sqlite3DbReallocOrFree(pToplevel->db, pToplevel->aTableLock, nBytes);
  105. if( pToplevel->aTableLock ){
  106. p = &pToplevel->aTableLock[pToplevel->nTableLock++];
  107. p->iDb = iDb;
  108. p->iTab = iTab;
  109. p->isWriteLock = isWriteLock;
  110. p->zName = zName;
  111. }else{
  112. pToplevel->nTableLock = 0;
  113. pToplevel->db->mallocFailed = 1;
  114. }
  115. }
  116. /*
  117. ** Code an OP_TableLock instruction for each table locked by the
  118. ** statement (configured by calls to sqlite3TableLock()).
  119. */
  120. static void codeTableLocks( Parse pParse )
  121. {
  122. int i;
  123. Vdbe pVdbe;
  124. pVdbe = sqlite3GetVdbe( pParse );
  125. Debug.Assert( pVdbe != null ); /* sqlite3GetVdbe cannot fail: VDBE already allocated */
  126. for ( i = 0 ; i < pParse.nTableLock ; i++ )
  127. {
  128. TableLock p = pParse.aTableLock[i];
  129. int p1 = p.iDb;
  130. sqlite3VdbeAddOp4( pVdbe, OP_TableLock, p1, p.iTab, p.isWriteLock,
  131. p.zName, P4_STATIC );
  132. }
  133. }
  134. #else
  135. // #define codeTableLocks(x)
  136. static void codeTableLocks( Parse pParse )
  137. {
  138. }
  139. #endif
  140. /*
  141. ** This routine is called after a single SQL statement has been
  142. ** parsed and a VDBE program to execute that statement has been
  143. ** prepared. This routine puts the finishing touches on the
  144. ** VDBE program and resets the pParse structure for the next
  145. ** parse.
  146. **
  147. ** Note that if an error occurred, it might be the case that
  148. ** no VDBE code was generated.
  149. */
  150. static void sqlite3FinishCoding( Parse pParse )
  151. {
  152. sqlite3 db;
  153. Vdbe v;
  154. db = pParse.db;
  155. // if ( db.mallocFailed != 0 ) return;
  156. if ( pParse.nested != 0 )
  157. return;
  158. if ( pParse.nErr != 0 )
  159. return;
  160. /* Begin by generating some termination code at the end of the
  161. ** vdbe program
  162. */
  163. v = sqlite3GetVdbe( pParse );
  164. Debug.Assert( 0 == pParse.isMultiWrite
  165. || sqlite3VdbeAssertMayAbort( v, pParse.mayAbort ) != 0 );
  166. if ( v != null )
  167. {
  168. sqlite3VdbeAddOp0( v, OP_Halt );
  169. /* The cookie mask contains one bit for each database file open.
  170. ** (Bit 0 is for main, bit 1 is for temp, and so forth.) Bits are
  171. ** set for each database that is used. Generate code to start a
  172. ** transaction on each used database and to verify the schema cookie
  173. ** on each used database.
  174. */
  175. if ( pParse.cookieGoto > 0 )
  176. {
  177. u32 mask;
  178. int iDb;
  179. sqlite3VdbeJumpHere( v, pParse.cookieGoto - 1 );
  180. for ( iDb = 0, mask = 1; iDb < db.nDb; mask <<= 1, iDb++ )
  181. {
  182. if ( ( mask & pParse.cookieMask ) == 0 )
  183. continue;
  184. sqlite3VdbeUsesBtree( v, iDb );
  185. sqlite3VdbeAddOp2( v, OP_Transaction, iDb, ( mask & pParse.writeMask ) != 0 );
  186. if ( db.init.busy == 0 )
  187. {
  188. sqlite3VdbeAddOp2( v, OP_VerifyCookie, iDb, pParse.cookieValue[iDb] );
  189. }
  190. }
  191. #if !SQLITE_OMIT_VIRTUALTABLE
  192. {
  193. int i;
  194. for(i=0; i<pParse.nVtabLock; i++){
  195. char *vtab = (char *)sqlite3GetVTable(db, pParse->apVtabLock[i]);
  196. sqlite3VdbeAddOp4(v, OP_VBegin, 0, 0, 0, vtab, P4_VTAB);
  197. }
  198. pParse.nVtabLock = 0;
  199. }
  200. #endif
  201. /* Once all the cookies have been verified and transactions opened,
  202. ** obtain the required table-locks. This is a no-op unless the
  203. ** shared-cache feature is enabled.
  204. */
  205. codeTableLocks( pParse );
  206. /* Initialize any AUTOINCREMENT data structures required.
  207. */
  208. sqlite3AutoincrementBegin( pParse );
  209. /* Finally, jump back to the beginning of the executable code. */
  210. sqlite3VdbeAddOp2( v, OP_Goto, 0, pParse.cookieGoto );
  211. }
  212. }
  213. /* Get the VDBE program ready for execution
  214. */
  215. if ( v != null && ALWAYS( pParse.nErr == 0 ) /* && 0 == db.mallocFailed */ )
  216. {
  217. #if SQLITE_DEBUG
  218. TextWriter trace = ( db.flags & SQLITE_VdbeTrace ) != 0 ? Console.Out : null;
  219. sqlite3VdbeTrace( v, trace );
  220. #endif
  221. Debug.Assert( pParse.iCacheLevel == 0 ); /* Disables and re-enables match */
  222. /* A minimum of one cursor is required if autoincrement is used
  223. * See ticket [a696379c1f08866] */
  224. if ( pParse.pAinc != null && pParse.nTab == 0 )
  225. pParse.nTab = 1;
  226. sqlite3VdbeMakeReady( v, pParse.nVar, pParse.nMem,
  227. pParse.nTab, pParse.nMaxArg, pParse.explain,
  228. ( pParse.isMultiWrite != 0 && pParse.mayAbort != 0 ) ? 1 : 0 );
  229. pParse.rc = SQLITE_DONE;
  230. pParse.colNamesSet = 0;
  231. }
  232. else
  233. {
  234. pParse.rc = SQLITE_ERROR;
  235. }
  236. pParse.nTab = 0;
  237. pParse.nMem = 0;
  238. pParse.nSet = 0;
  239. pParse.nVar = 0;
  240. pParse.cookieMask = 0;
  241. pParse.cookieGoto = 0;
  242. }
  243. /*
  244. ** Run the parser and code generator recursively in order to generate
  245. ** code for the SQL statement given onto the end of the pParse context
  246. ** currently under construction. When the parser is run recursively
  247. ** this way, the final OP_Halt is not appended and other initialization
  248. ** and finalization steps are omitted because those are handling by the
  249. ** outermost parser.
  250. **
  251. ** Not everything is nestable. This facility is designed to permit
  252. ** INSERT, UPDATE, and DELETE operations against SQLITE_MASTER. Use
  253. ** care if you decide to try to use this routine for some other purposes.
  254. */
  255. static void sqlite3NestedParse( Parse pParse, string zFormat, params object[] ap )
  256. {
  257. string zSql; // char *zSql;
  258. string zErrMsg = "";// char* zErrMsg = 0;
  259. sqlite3 db = pParse.db;
  260. //# define SAVE_SZ (Parse.Length - offsetof(Parse,nVar))
  261. // char saveBuf[SAVE_SZ];
  262. if ( pParse.nErr != 0 )
  263. return;
  264. Debug.Assert( pParse.nested < 10 ); /* Nesting should only be of limited depth */
  265. // va_list ap;
  266. lock ( lock_va_list )
  267. {
  268. va_start( ap, zFormat );
  269. zSql = sqlite3VMPrintf( db, zFormat, ap );
  270. va_end( ref ap );
  271. }
  272. //if( zSql=="" ){
  273. // return; /* A malloc must have failed */
  274. //}
  275. lock ( nestingLock )
  276. {
  277. pParse.nested++;
  278. pParse.SaveMembers(); // memcpy(saveBuf, pParse.nVar, SAVE_SZ);
  279. pParse.ResetMembers(); // memset(pParse.nVar, 0, SAVE_SZ);
  280. sqlite3RunParser( pParse, zSql, ref zErrMsg );
  281. sqlite3DbFree( db, ref zErrMsg );
  282. sqlite3DbFree( db, ref zSql );
  283. pParse.RestoreMembers(); // memcpy(pParse.nVar, saveBuf, SAVE_SZ);
  284. pParse.nested--;
  285. }
  286. }
  287. static Object nestingLock = new Object();
  288. /*
  289. ** Locate the in-memory structure that describes a particular database
  290. ** table given the name of that table and (optionally) the name of the
  291. ** database containing the table. Return NULL if not found.
  292. **
  293. ** If zDatabase is 0, all databases are searched for the table and the
  294. ** first matching table is returned. (No checking for duplicate table
  295. ** names is done.) The search order is TEMP first, then MAIN, then any
  296. ** auxiliary databases added using the ATTACH command.
  297. **
  298. ** See also sqlite3LocateTable().
  299. */
  300. static Table sqlite3FindTable( sqlite3 db, string zName, string zDatabase )
  301. {
  302. Table p = null;
  303. int i;
  304. int nName;
  305. Debug.Assert( zName != null );
  306. nName = sqlite3Strlen30( zName );
  307. for ( i = OMIT_TEMPDB; i < db.nDb; i++ )
  308. {
  309. int j = ( i < 2 ) ? i ^ 1 : i; /* Search TEMP before MAIN */
  310. if ( zDatabase != null && !zDatabase.Equals( db.aDb[j].zName, StringComparison.InvariantCultureIgnoreCase ) )
  311. continue;
  312. p = sqlite3HashFind( db.aDb[j].pSchema.tblHash, zName, nName, (Table)null );
  313. if ( p != null )
  314. break;
  315. }
  316. return p;
  317. }
  318. /*
  319. ** Locate the in-memory structure that describes a particular database
  320. ** table given the name of that table and (optionally) the name of the
  321. ** database containing the table. Return NULL if not found. Also leave an
  322. ** error message in pParse.zErrMsg.
  323. **
  324. ** The difference between this routine and sqlite3FindTable() is that this
  325. ** routine leaves an error message in pParse.zErrMsg where
  326. ** sqlite3FindTable() does not.
  327. */
  328. static Table sqlite3LocateTable(
  329. Parse pParse, /* context in which to report errors */
  330. int isView, /* True if looking for a VIEW rather than a TABLE */
  331. string zName, /* Name of the table we are looking for */
  332. string zDbase /* Name of the database. Might be NULL */
  333. )
  334. {
  335. Table p;
  336. /* Read the database schema. If an error occurs, leave an error message
  337. ** and code in pParse and return NULL. */
  338. if ( SQLITE_OK != sqlite3ReadSchema( pParse ) )
  339. {
  340. return null;
  341. }
  342. p = sqlite3FindTable( pParse.db, zName, zDbase );
  343. if ( p == null )
  344. {
  345. string zMsg = isView != 0 ? "no such view" : "no such table";
  346. if ( zDbase != null )
  347. {
  348. sqlite3ErrorMsg( pParse, "%s: %s.%s", zMsg, zDbase, zName );
  349. }
  350. else
  351. {
  352. sqlite3ErrorMsg( pParse, "%s: %s", zMsg, zName );
  353. }
  354. pParse.checkSchema = 1;
  355. }
  356. return p;
  357. }
  358. /*
  359. ** Locate the in-memory structure that describes
  360. ** a particular index given the name of that index
  361. ** and the name of the database that contains the index.
  362. ** Return NULL if not found.
  363. **
  364. ** If zDatabase is 0, all databases are searched for the
  365. ** table and the first matching index is returned. (No checking
  366. ** for duplicate index names is done.) The search order is
  367. ** TEMP first, then MAIN, then any auxiliary databases added
  368. ** using the ATTACH command.
  369. */
  370. static Index sqlite3FindIndex( sqlite3 db, string zName, string zDb )
  371. {
  372. Index p = null;
  373. int i;
  374. int nName = sqlite3Strlen30( zName );
  375. for ( i = OMIT_TEMPDB; i < db.nDb; i++ )
  376. {
  377. int j = ( i < 2 ) ? i ^ 1 : i; /* Search TEMP before MAIN */
  378. Schema pSchema = db.aDb[j].pSchema;
  379. Debug.Assert( pSchema != null );
  380. if ( zDb != null && !zDb.Equals( db.aDb[j].zName, StringComparison.InvariantCultureIgnoreCase ) )
  381. continue;
  382. p = sqlite3HashFind( pSchema.idxHash, zName, nName, (Index)null );
  383. if ( p != null )
  384. break;
  385. }
  386. return p;
  387. }
  388. /*
  389. ** Reclaim the memory used by an index
  390. */
  391. static void freeIndex( sqlite3 db, ref Index p )
  392. {
  393. #if !SQLITE_OMIT_ANALYZE
  394. sqlite3DeleteIndexSamples( db, p );
  395. #endif
  396. sqlite3DbFree( db, ref p.zColAff );
  397. sqlite3DbFree( db, ref p );
  398. }
  399. /*
  400. ** For the index called zIdxName which is found in the database iDb,
  401. ** unlike that index from its Table then remove the index from
  402. ** the index hash table and free all memory structures associated
  403. ** with the index.
  404. */
  405. static void sqlite3UnlinkAndDeleteIndex( sqlite3 db, int iDb, string zIdxName )
  406. {
  407. Index pIndex;
  408. int len;
  409. Hash pHash = db.aDb[iDb].pSchema.idxHash;
  410. len = sqlite3Strlen30( zIdxName );
  411. pIndex = sqlite3HashInsert( ref pHash, zIdxName, len, (Index)null );
  412. if ( pIndex != null )
  413. {
  414. if ( pIndex.pTable.pIndex == pIndex )
  415. {
  416. pIndex.pTable.pIndex = pIndex.pNext;
  417. }
  418. else
  419. {
  420. Index p;
  421. /* Justification of ALWAYS(); The index must be on the list of
  422. ** indices. */
  423. p = pIndex.pTable.pIndex;
  424. while ( ALWAYS( p != null ) && p.pNext != pIndex )
  425. {
  426. p = p.pNext;
  427. }
  428. if ( ALWAYS( p != null && p.pNext == pIndex ) )
  429. {
  430. p.pNext = pIndex.pNext;
  431. }
  432. }
  433. freeIndex( db, ref pIndex );
  434. }
  435. db.flags |= SQLITE_InternChanges;
  436. }
  437. /*
  438. ** Erase all schema information from the in-memory hash tables of
  439. ** a single database. This routine is called to reclaim memory
  440. ** before the database closes. It is also called during a rollback
  441. ** if there were schema changes during the transaction or if a
  442. ** schema-cookie mismatch occurs.
  443. **
  444. ** If iDb==0 then reset the internal schema tables for all database
  445. ** files. If iDb>=1 then reset the internal schema for only the
  446. ** single file indicated.
  447. */
  448. static void sqlite3ResetInternalSchema( sqlite3 db, int iDb )
  449. {
  450. int i, j;
  451. Debug.Assert( iDb >= 0 && iDb < db.nDb );
  452. if ( iDb == 0 )
  453. {
  454. sqlite3BtreeEnterAll( db );
  455. }
  456. for ( i = iDb; i < db.nDb; i++ )
  457. {
  458. Db pDb = db.aDb[i];
  459. if ( pDb.pSchema != null )
  460. {
  461. Debug.Assert( i == 1 || ( pDb.pBt != null && sqlite3BtreeHoldsMutex( pDb.pBt ) ) );
  462. Debug.Assert( i == 1 || ( pDb.pBt != null ) );
  463. sqlite3SchemaFree( pDb.pSchema );
  464. }
  465. if ( iDb > 0 )
  466. return;
  467. }
  468. Debug.Assert( iDb == 0 );
  469. db.flags &= ~SQLITE_InternChanges;
  470. sqlite3VtabUnlockList( db );
  471. sqlite3BtreeLeaveAll( db );
  472. /* If one or more of the auxiliary database files has been closed,
  473. ** then remove them from the auxiliary database list. We take the
  474. ** opportunity to do this here since we have just deleted all of the
  475. ** schema hash tables and therefore do not have to make any changes
  476. ** to any of those tables.
  477. */
  478. for ( i = j = 2; i < db.nDb; i++ )
  479. {
  480. Db pDb = db.aDb[i];
  481. if ( pDb.pBt == null )
  482. {
  483. sqlite3DbFree( db, ref pDb.zName );
  484. continue;
  485. }
  486. if ( j < i )
  487. {
  488. db.aDb[j] = db.aDb[i];
  489. }
  490. j++;
  491. }
  492. if ( db.nDb != j )
  493. db.aDb[j] = new Db();//memset(db.aDb[j], 0, (db.nDb-j)*sizeof(db.aDb[j]));
  494. db.nDb = j;
  495. if ( db.nDb <= 2 && db.aDb != db.aDbStatic )
  496. {
  497. Array.Copy( db.aDb, db.aDbStatic, 2 );// memcpy(db.aDbStatic, db.aDb, 2*sizeof(db.aDb[0]));
  498. sqlite3DbFree( db, ref db.aDb );
  499. //db.aDb = db.aDbStatic;
  500. }
  501. }
  502. /*
  503. ** This routine is called when a commit occurs.
  504. */
  505. static void sqlite3CommitInternalChanges( sqlite3 db )
  506. {
  507. db.flags &= ~SQLITE_InternChanges;
  508. }
  509. /*
  510. ** Delete memory allocated for the column names of a table or view (the
  511. ** Table.aCol[] array).
  512. */
  513. static void sqliteDeleteColumnNames( sqlite3 db, Table pTable )
  514. {
  515. int i;
  516. Column pCol;
  517. Debug.Assert( pTable != null );
  518. for ( i = 0; i < pTable.nCol; i++ )
  519. {
  520. pCol = pTable.aCol[i];
  521. if ( pCol != null )
  522. {
  523. sqlite3DbFree( db, ref pCol.zName );
  524. sqlite3ExprDelete( db, ref pCol.pDflt );
  525. sqlite3DbFree( db, ref pCol.zDflt );
  526. sqlite3DbFree( db, ref pCol.zType );
  527. sqlite3DbFree( db, ref pCol.zColl );
  528. }
  529. }
  530. }
  531. /*
  532. ** Remove the memory data structures associated with the given
  533. ** Table. No changes are made to disk by this routine.
  534. **
  535. ** This routine just deletes the data structure. It does not unlink
  536. ** the table data structure from the hash table. But it does destroy
  537. ** memory structures of the indices and foreign keys associated with
  538. ** the table.
  539. */
  540. static void sqlite3DeleteTable( sqlite3 db, ref Table pTable )
  541. {
  542. Index pIndex;
  543. Index pNext;
  544. Debug.Assert( null == pTable || pTable.nRef > 0 );
  545. /* Do not delete the table until the reference count reaches zero. */
  546. if ( null == pTable )
  547. return;
  548. if ( (// ( !db || db->pnBytesFreed == 0 ) &&
  549. ( --pTable.nRef ) > 0 ) )
  550. return;
  551. /* Delete all indices associated with this table. */
  552. for ( pIndex = pTable.pIndex; pIndex != null; pIndex = pNext )
  553. {
  554. pNext = pIndex.pNext;
  555. Debug.Assert( pIndex.pSchema == pTable.pSchema );
  556. //if( null==db || db.pnBytesFreed==0 ){
  557. string zName = pIndex.zName;
  558. //
  559. #if !NDEBUG || SQLITE_COVERAGE_TEST
  560. // TESTONLY ( Index pOld = ) sqlite3HashInsert(
  561. //ref pIndex.pSchema.idxHash, zName, sqlite3Strlen30(zName), 0
  562. // );
  563. Index pOld = sqlite3HashInsert(
  564. ref pIndex.pSchema.idxHash, zName, sqlite3Strlen30( zName ), (Index)null
  565. );
  566. Debug.Assert( pOld == pIndex || pOld == null );
  567. #else
  568. // TESTONLY ( Index pOld = ) sqlite3HashInsert(
  569. //ref pIndex.pSchema.idxHash, zName, sqlite3Strlen30(zName), 0
  570. // );
  571. sqlite3HashInsert(
  572. ref pIndex.pSchema.idxHash, zName, sqlite3Strlen30(zName),(Index)null
  573. );
  574. #endif
  575. //}
  576. freeIndex( db, ref pIndex );
  577. }
  578. /* Delete any foreign keys attached to this table. */
  579. sqlite3FkDelete( db, pTable );
  580. /* Delete the Table structure itself.
  581. */
  582. sqliteDeleteColumnNames( db, pTable );
  583. sqlite3DbFree( db, ref pTable.zName );
  584. sqlite3DbFree( db, ref pTable.zColAff );
  585. sqlite3SelectDelete( db, ref pTable.pSelect );
  586. #if !SQLITE_OMIT_CHECK
  587. sqlite3ExprDelete( db, ref pTable.pCheck );
  588. #endif
  589. #if !SQLITE_OMIT_VIRTUALTABLE
  590. sqlite3VtabClear(db, pTable);
  591. #endif
  592. pTable = null;// sqlite3DbFree( db, ref pTable );
  593. }
  594. /*
  595. ** Unlink the given table from the hash tables and the delete the
  596. ** table structure with all its indices and foreign keys.
  597. */
  598. static void sqlite3UnlinkAndDeleteTable( sqlite3 db, int iDb, string zTabName )
  599. {
  600. Table p;
  601. Db pDb;
  602. Debug.Assert( db != null );
  603. Debug.Assert( iDb >= 0 && iDb < db.nDb );
  604. Debug.Assert( zTabName != null );
  605. testcase( zTabName.Length == 0 ); /* Zero-length table names are allowed */
  606. pDb = db.aDb[iDb];
  607. p = sqlite3HashInsert( ref pDb.pSchema.tblHash, zTabName,
  608. sqlite3Strlen30( zTabName ), (Table)null );
  609. sqlite3DeleteTable( db, ref p );
  610. db.flags |= SQLITE_InternChanges;
  611. }
  612. /*
  613. ** Given a token, return a string that consists of the text of that
  614. ** token. Space to hold the returned string
  615. ** is obtained from sqliteMalloc() and must be freed by the calling
  616. ** function.
  617. **
  618. ** Any quotation marks (ex: "name", 'name', [name], or `name`) that
  619. ** surround the body of the token are removed.
  620. **
  621. ** Tokens are often just pointers into the original SQL text and so
  622. ** are not \000 terminated and are not persistent. The returned string
  623. ** is \000 terminated and is persistent.
  624. */
  625. static string sqlite3NameFromToken( sqlite3 db, Token pName )
  626. {
  627. string zName;
  628. if ( pName != null && pName.z != null )
  629. {
  630. zName = pName.z.Substring( 0, pName.n );//sqlite3DbStrNDup(db, (char*)pName.z, pName.n);
  631. sqlite3Dequote( ref zName );
  632. }
  633. else
  634. {
  635. return null;
  636. }
  637. return zName;
  638. }
  639. /*
  640. ** Open the sqlite_master table stored in database number iDb for
  641. ** writing. The table is opened using cursor 0.
  642. */
  643. static void sqlite3OpenMasterTable( Parse p, int iDb )
  644. {
  645. Vdbe v = sqlite3GetVdbe( p );
  646. sqlite3TableLock( p, iDb, MASTER_ROOT, 1, SCHEMA_TABLE( iDb ) );
  647. sqlite3VdbeAddOp3( v, OP_OpenWrite, 0, MASTER_ROOT, iDb );
  648. sqlite3VdbeChangeP4( v, -1, (int)5, P4_INT32 ); /* 5 column table */
  649. if ( p.nTab == 0 )
  650. {
  651. p.nTab = 1;
  652. }
  653. }
  654. /*
  655. ** Parameter zName points to a nul-terminated buffer containing the name
  656. ** of a database ("main", "temp" or the name of an attached db). This
  657. ** function returns the index of the named database in db->aDb[], or
  658. ** -1 if the named db cannot be found.
  659. */
  660. static int sqlite3FindDbName( sqlite3 db, string zName )
  661. {
  662. int i = -1; /* Database number */
  663. if ( zName != null )
  664. {
  665. Db pDb;
  666. int n = sqlite3Strlen30( zName );
  667. for ( i = ( db.nDb - 1 ); i >= 0; i-- )
  668. {
  669. pDb = db.aDb[i];
  670. if ( ( OMIT_TEMPDB == 0 || i != 1 ) && n == sqlite3Strlen30( pDb.zName ) &&
  671. pDb.zName.Equals( zName, StringComparison.InvariantCultureIgnoreCase ) )
  672. {
  673. break;
  674. }
  675. }
  676. }
  677. return i;
  678. }
  679. /*
  680. ** The token *pName contains the name of a database (either "main" or
  681. ** "temp" or the name of an attached db). This routine returns the
  682. ** index of the named database in db->aDb[], or -1 if the named db
  683. ** does not exist.
  684. */
  685. static int sqlite3FindDb( sqlite3 db, Token pName )
  686. {
  687. int i; /* Database number */
  688. string zName; /* Name we are searching for */
  689. zName = sqlite3NameFromToken( db, pName );
  690. i = sqlite3FindDbName( db, zName );
  691. sqlite3DbFree( db, ref zName );
  692. return i;
  693. }
  694. /* The table or view or trigger name is passed to this routine via tokens
  695. ** pName1 and pName2. If the table name was fully qualified, for example:
  696. **
  697. ** CREATE TABLE xxx.yyy (...);
  698. **
  699. ** Then pName1 is set to "xxx" and pName2 "yyy". On the other hand if
  700. ** the table name is not fully qualified, i.e.:
  701. **
  702. ** CREATE TABLE yyy(...);
  703. **
  704. ** Then pName1 is set to "yyy" and pName2 is "".
  705. **
  706. ** This routine sets the ppUnqual pointer to point at the token (pName1 or
  707. ** pName2) that stores the unqualified table name. The index of the
  708. ** database "xxx" is returned.
  709. */
  710. static int sqlite3TwoPartName(
  711. Parse pParse, /* Parsing and code generating context */
  712. Token pName1, /* The "xxx" in the name "xxx.yyy" or "xxx" */
  713. Token pName2, /* The "yyy" in the name "xxx.yyy" */
  714. ref Token pUnqual /* Write the unqualified object name here */
  715. )
  716. {
  717. int iDb; /* Database holding the object */
  718. sqlite3 db = pParse.db;
  719. if ( ALWAYS( pName2 != null ) && pName2.n > 0 )
  720. {
  721. if ( db.init.busy != 0 )
  722. {
  723. sqlite3ErrorMsg( pParse, "corrupt database" );
  724. pParse.nErr++;
  725. return -1;
  726. }
  727. pUnqual = pName2;
  728. iDb = sqlite3FindDb( db, pName1 );
  729. if ( iDb < 0 )
  730. {
  731. sqlite3ErrorMsg( pParse, "unknown database %T", pName1 );
  732. pParse.nErr++;
  733. return -1;
  734. }
  735. }
  736. else
  737. {
  738. Debug.Assert( db.init.iDb == 0 || db.init.busy != 0 );
  739. iDb = db.init.iDb;
  740. pUnqual = pName1;
  741. }
  742. return iDb;
  743. }
  744. /*
  745. ** This routine is used to check if the UTF-8 string zName is a legal
  746. ** unqualified name for a new schema object (table, index, view or
  747. ** trigger). All names are legal except those that begin with the string
  748. ** "sqlite_" (in upper, lower or mixed case). This portion of the namespace
  749. ** is reserved for internal use.
  750. */
  751. static int sqlite3CheckObjectName( Parse pParse, string zName )
  752. {
  753. if ( 0 == pParse.db.init.busy && pParse.nested == 0
  754. && ( pParse.db.flags & SQLITE_WriteSchema ) == 0
  755. && zName.StartsWith( "sqlite_", System.StringComparison.InvariantCultureIgnoreCase ) )
  756. {
  757. sqlite3ErrorMsg( pParse, "object name reserved for internal use: %s", zName );
  758. return SQLITE_ERROR;
  759. }
  760. return SQLITE_OK;
  761. }
  762. /*
  763. ** Begin constructing a new table representation in memory. This is
  764. ** the first of several action routines that get called in response
  765. ** to a CREATE TABLE statement. In particular, this routine is called
  766. ** after seeing tokens "CREATE" and "TABLE" and the table name. The isTemp
  767. ** flag is true if the table should be stored in the auxiliary database
  768. ** file instead of in the main database file. This is normally the case
  769. ** when the "TEMP" or "TEMPORARY" keyword occurs in between
  770. ** CREATE and TABLE.
  771. **
  772. ** The new table record is initialized and put in pParse.pNewTable.
  773. ** As more of the CREATE TABLE statement is parsed, additional action
  774. ** routines will be called to add more information to this record.
  775. ** At the end of the CREATE TABLE statement, the sqlite3EndTable() routine
  776. ** is called to complete the construction of the new table record.
  777. */
  778. static void sqlite3StartTable(
  779. Parse pParse, /* Parser context */
  780. Token pName1, /* First part of the name of the table or view */
  781. Token pName2, /* Second part of the name of the table or view */
  782. int isTemp, /* True if this is a TEMP table */
  783. int isView, /* True if this is a VIEW */
  784. int isVirtual, /* True if this is a VIRTUAL table */
  785. int noErr /* Do nothing if table already exists */
  786. )
  787. {
  788. Table pTable;
  789. string zName = null; /* The name of the new table */
  790. sqlite3 db = pParse.db;
  791. Vdbe v;
  792. int iDb; /* Database number to create the table in */
  793. Token pName = new Token(); /* Unqualified name of the table to create */
  794. /* The table or view name to create is passed to this routine via tokens
  795. ** pName1 and pName2. If the table name was fully qualified, for example:
  796. **
  797. ** CREATE TABLE xxx.yyy (...);
  798. **
  799. ** Then pName1 is set to "xxx" and pName2 "yyy". On the other hand if
  800. ** the table name is not fully qualified, i.e.:
  801. **
  802. ** CREATE TABLE yyy(...);
  803. **
  804. ** Then pName1 is set to "yyy" and pName2 is "".
  805. **
  806. ** The call below sets the pName pointer to point at the token (pName1 or
  807. ** pName2) that stores the unqualified table name. The variable iDb is
  808. ** set to the index of the database that the table or view is to be
  809. ** created in.
  810. */
  811. iDb = sqlite3TwoPartName( pParse, pName1, pName2, ref pName );
  812. if ( iDb < 0 )
  813. return;
  814. if ( 0 == OMIT_TEMPDB && isTemp != 0 && pName2.n > 0 && iDb != 1 )
  815. {
  816. /* If creating a temp table, the name may not be qualified. Unless
  817. ** the database name is "temp" anyway. */
  818. sqlite3ErrorMsg( pParse, "temporary table name must be unqualified" );
  819. return;
  820. }
  821. if ( OMIT_TEMPDB == 0 && isTemp != 0 )
  822. iDb = 1;
  823. pParse.sNameToken = pName;
  824. zName = sqlite3NameFromToken( db, pName );
  825. if ( zName == null )
  826. return;
  827. if ( SQLITE_OK != sqlite3CheckObjectName( pParse, zName ) )
  828. {
  829. goto begin_table_error;
  830. }
  831. if ( db.init.iDb == 1 )
  832. isTemp = 1;
  833. #if !SQLITE_OMIT_AUTHORIZATION
  834. Debug.Assert( (isTemp & 1)==isTemp );
  835. {
  836. int code;
  837. char *zDb = db.aDb[iDb].zName;
  838. if( sqlite3AuthCheck(pParse, SQLITE_INSERT, SCHEMA_TABLE(isTemp), 0, zDb) ){
  839. goto begin_table_error;
  840. }
  841. if( isView ){
  842. if( OMIT_TEMPDB ==0&& isTemp ){
  843. code = SQLITE_CREATE_TEMP_VIEW;
  844. }else{
  845. code = SQLITE_CREATE_VIEW;
  846. }
  847. }else{
  848. if( OMIT_TEMPDB ==0&& isTemp ){
  849. code = SQLITE_CREATE_TEMP_TABLE;
  850. }else{
  851. code = SQLITE_CREATE_TABLE;
  852. }
  853. }
  854. if( !isVirtual && sqlite3AuthCheck(pParse, code, zName, 0, zDb) ){
  855. goto begin_table_error;
  856. }
  857. }
  858. #endif
  859. /* Make sure the new table name does not collide with an existing
  860. ** index or table name in the same database. Issue an error message if
  861. ** it does. The exception is if the statement being parsed was passed
  862. ** to an sqlite3_declare_vtab() call. In that case only the column names
  863. ** and types will be used, so there is no need to test for namespace
  864. ** collisions.
  865. */
  866. if ( !IN_DECLARE_VTAB )
  867. {
  868. String zDb = db.aDb[iDb].zName;
  869. if ( SQLITE_OK != sqlite3ReadSchema( pParse ) )
  870. {
  871. goto begin_table_error;
  872. }
  873. pTable = sqlite3FindTable( db, zName, zDb );
  874. if ( pTable != null )
  875. {
  876. if ( noErr == 0 )
  877. {
  878. sqlite3ErrorMsg( pParse, "table %T already exists", pName );
  879. }
  880. goto begin_table_error;
  881. }
  882. if ( sqlite3FindIndex( db, zName, zDb ) != null )
  883. {
  884. sqlite3ErrorMsg( pParse, "there is already an index named %s", zName );
  885. goto begin_table_error;
  886. }
  887. }
  888. pTable = new Table();// sqlite3DbMallocZero(db, Table).Length;
  889. if ( pTable == null )
  890. {
  891. // db.mallocFailed = 1;
  892. pParse.rc = SQLITE_NOMEM;
  893. pParse.nErr++;
  894. goto begin_table_error;
  895. }
  896. pTable.zName = zName;
  897. pTable.iPKey = -1;
  898. pTable.pSchema = db.aDb[iDb].pSchema;
  899. pTable.nRef = 1;
  900. pTable.nRowEst = 1000000;
  901. Debug.Assert( pParse.pNewTable == null );
  902. pParse.pNewTable = pTable;
  903. /* If this is the magic sqlite_sequence table used by autoincrement,
  904. ** then record a pointer to this table in the main database structure
  905. ** so that INSERT can find the table easily.
  906. */
  907. #if !SQLITE_OMIT_AUTOINCREMENT
  908. if ( pParse.nested == 0 && zName == "sqlite_sequence" )
  909. {
  910. pTable.pSchema.pSeqTab = pTable;
  911. }
  912. #endif
  913. /* Begin generating the code that will insert the table record into
  914. ** the SQLITE_MASTER table. Note in particular that we must go ahead
  915. ** and allocate the record number for the table entry now. Before any
  916. ** PRIMARY KEY or UNIQUE keywords are parsed. Those keywords will cause
  917. ** indices to be created and the table record must come before the
  918. ** indices. Hence, the record number for the table must be allocated
  919. ** now.
  920. */
  921. if ( 0 == db.init.busy && ( v = sqlite3GetVdbe( pParse ) ) != null )
  922. {
  923. int j1;
  924. int fileFormat;
  925. int reg1, reg2, reg3;
  926. sqlite3BeginWriteOperation( pParse, 0, iDb );
  927. if ( isVirtual != 0 )
  928. {
  929. sqlite3VdbeAddOp0( v, OP_VBegin );
  930. }
  931. /* If the file format and encoding in the database have not been set,
  932. ** set them now.
  933. */
  934. reg1 = pParse.regRowid = ++pParse.nMem;
  935. reg2 = pParse.regRoot = ++pParse.nMem;
  936. reg3 = ++pParse.nMem;
  937. sqlite3VdbeAddOp3( v, OP_ReadCookie, iDb, reg3, BTREE_FILE_FORMAT );
  938. sqlite3VdbeUsesBtree( v, iDb );
  939. j1 = sqlite3VdbeAddOp1( v, OP_If, reg3 );
  940. fileFormat = ( db.flags & SQLITE_LegacyFileFmt ) != 0 ?
  941. 1 : SQLITE_MAX_FILE_FORMAT;
  942. sqlite3VdbeAddOp2( v, OP_Integer, fileFormat, reg3 );
  943. sqlite3VdbeAddOp3( v, OP_SetCookie, iDb, BTREE_FILE_FORMAT, reg3 );
  944. sqlite3VdbeAddOp2( v, OP_Integer, ENC( db ), reg3 );
  945. sqlite3VdbeAddOp3( v, OP_SetCookie, iDb, BTREE_TEXT_ENCODING, reg3 );
  946. sqlite3VdbeJumpHere( v, j1 );
  947. /* This just creates a place-holder record in the sqlite_master table.
  948. ** The record created does not contain anything yet. It will be replaced
  949. ** by the real entry in code generated at sqlite3EndTable().
  950. **
  951. ** The rowid for the new entry is left in register pParse->regRowid.
  952. ** The root page number of the new table is left in reg pParse->regRoot.
  953. ** The rowid and root page number values are needed by the code that
  954. ** sqlite3EndTable will generate.
  955. */
  956. if ( isView != 0 || isVirtual != 0 )
  957. {
  958. sqlite3VdbeAddOp2( v, OP_Integer, 0, reg2 );
  959. }
  960. else
  961. {
  962. sqlite3VdbeAddOp2( v, OP_CreateTable, iDb, reg2 );
  963. }
  964. sqlite3OpenMasterTable( pParse, iDb );
  965. sqlite3VdbeAddOp2( v, OP_NewRowid, 0, reg1 );
  966. sqlite3VdbeAddOp2( v, OP_Null, 0, reg3 );
  967. sqlite3VdbeAddOp3( v, OP_Insert, 0, reg3, reg1 );
  968. sqlite3VdbeChangeP5( v, OPFLAG_APPEND );
  969. sqlite3VdbeAddOp0( v, OP_Close );
  970. }
  971. /* Normal (non-error) return. */
  972. return;
  973. /* If an error occurs, we jump here */
  974. begin_table_error:
  975. sqlite3DbFree( db, ref zName );
  976. return;
  977. }
  978. /*
  979. ** This macro is used to compare two strings in a case-insensitive manner.
  980. ** It is slightly faster than calling sqlite3StrICmp() directly, but
  981. ** produces larger code.
  982. **
  983. ** WARNING: This macro is not compatible with the strcmp() family. It
  984. ** returns true if the two strings are equal, otherwise false.
  985. */
  986. //#define STRICMP(x, y) (\
  987. //sqlite3UpperToLower[*(unsigned char *)(x)]== \
  988. //sqlite3UpperToLower[*(unsigned char *)(y)] \
  989. //&& sqlite3StrICmp((x)+1,(y)+1)==0 )
  990. /*
  991. ** Add a new column to the table currently being constructed.
  992. **
  993. ** The parser calls this routine once for each column declaration
  994. ** in a CREATE TABLE statement. sqlite3StartTable() gets called
  995. ** first to get things going. Then this routine is called for each
  996. ** column.
  997. */
  998. static void sqlite3AddColumn( Parse pParse, Token pName )
  999. {
  1000. Table p;
  1001. int i;
  1002. string z;
  1003. Column pCol;
  1004. sqlite3 db = pParse.db;
  1005. if ( ( p = pParse.pNewTable ) == null )
  1006. return;
  1007. #if SQLITE_MAX_COLUMN || !SQLITE_MAX_COLUMN
  1008. if ( p.nCol + 1 > db.aLimit[SQLITE_LIMIT_COLUMN] )
  1009. {
  1010. sqlite3ErrorMsg( pParse, "too many columns on %s", p.zName );
  1011. return;
  1012. }
  1013. #endif
  1014. z = sqlite3NameFromToken( db, pName );
  1015. if ( z == null )
  1016. return;
  1017. for ( i = 0; i < p.nCol; i++ )
  1018. {
  1019. if ( z.Equals( p.aCol[i].zName, StringComparison.InvariantCultureIgnoreCase ) )
  1020. {//STRICMP(z, p.aCol[i].zName) ){
  1021. sqlite3ErrorMsg( pParse, "duplicate column name: %s", z );
  1022. sqlite3DbFree( db, ref z );
  1023. return;
  1024. }
  1025. }
  1026. if ( ( p.nCol & 0x7 ) == 0 )
  1027. {
  1028. //aNew = sqlite3DbRealloc(db,p.aCol,(p.nCol+8)*sizeof(p.aCol[0]));
  1029. //if( aNew==0 ){
  1030. // sqlite3DbFree(db,ref z);
  1031. // return;
  1032. //}
  1033. Array.Resize( ref p.aCol, p.nCol + 8 );
  1034. }
  1035. p.aCol[p.nCol] = new Column();
  1036. pCol = p.aCol[p.nCol];
  1037. //memset(pCol, 0, sizeof(p.aCol[0]));
  1038. pCol.zName = z;
  1039. /* If there is no type specified, columns have the default affinity
  1040. ** 'NONE'. If there is a type specified, then sqlite3AddColumnType() will
  1041. ** be called next to set pCol.affinity correctly.
  1042. */
  1043. pCol.affinity = SQLITE_AFF_NONE;
  1044. p.nCol++;
  1045. }
  1046. /*
  1047. ** This routine is called by the parser while in the middle of
  1048. ** parsing a CREATE TABLE statement. A "NOT NULL" constraint has
  1049. ** been seen on a column. This routine sets the notNull flag on
  1050. ** the column currently under construction.
  1051. */
  1052. static void sqlite3AddNotNull( Parse pParse, int onError )
  1053. {
  1054. Table p;
  1055. p = pParse.pNewTable;
  1056. if ( p == null || NEVER( p.nCol < 1 ) )
  1057. return;
  1058. p.aCol[p.nCol - 1].notNull = (u8)onError;
  1059. }
  1060. /*
  1061. ** Scan the column type name zType (length nType) and return the
  1062. ** associated affinity type.
  1063. **
  1064. ** This routine does a case-independent search of zType for the
  1065. ** substrings in the following table. If one of the substrings is
  1066. ** found, the corresponding affinity is returned. If zType contains
  1067. ** more than one of the substrings, entries toward the top of
  1068. ** the table take priority. For example, if zType is 'BLOBINT',
  1069. ** SQLITE_AFF_INTEGER is returned.
  1070. **
  1071. ** Substring | Affinity
  1072. ** --------------------------------
  1073. ** 'INT' | SQLITE_AFF_INTEGER
  1074. ** 'CHAR' | SQLITE_AFF_TEXT
  1075. ** 'CLOB' | SQLITE_AFF_TEXT
  1076. ** 'TEXT' | SQLITE_AFF_TEXT
  1077. ** 'BLOB' | SQLITE_AFF_NONE
  1078. ** 'REAL' | SQLITE_AFF_REAL
  1079. ** 'FLOA' | SQLITE_AFF_REAL
  1080. ** 'DOUB' | SQLITE_AFF_REAL
  1081. **
  1082. ** If none of the substrings in the above table are found,
  1083. ** SQLITE_AFF_NUMERIC is returned.
  1084. */
  1085. static char sqlite3AffinityType( string zIn )
  1086. {
  1087. //u32 h = 0;
  1088. //char aff = SQLITE_AFF_NUMERIC;
  1089. zIn = zIn.ToLower();
  1090. if ( zIn.Contains( "char" ) || zIn.Contains( "clob" ) || zIn.Contains( "text" ) )
  1091. return SQLITE_AFF_TEXT;
  1092. if ( zIn.Contains( "blob" ) )
  1093. return SQLITE_AFF_NONE;
  1094. if ( zIn.Contains( "doub" ) || zIn.Contains( "floa" ) || zIn.Contains( "real" ) )
  1095. return SQLITE_AFF_REAL;
  1096. if ( zIn.Contains( "int" ) )
  1097. return SQLITE_AFF_INTEGER;
  1098. return SQLITE_AFF_NUMERIC;
  1099. // string zEnd = pType.z.Substring(pType.n);
  1100. // while( zIn!=zEnd ){
  1101. // h = (h<<8) + sqlite3UpperToLower[*zIn];
  1102. // zIn++;
  1103. // if( h==(('c'<<24)+('h'<<16)+('a'<<8)+'r') ){ /* CHAR */
  1104. // aff = SQLITE_AFF_TEXT;
  1105. // }else if( h==(('c'<<24)+('l'<<16)+('o'<<8)+'b') ){ /* CLOB */
  1106. // aff = SQLITE_AFF_TEXT;
  1107. // }else if( h==(('t'<<24)+('e'<<16)+('x'<<8)+'t') ){ /* TEXT */
  1108. // aff = SQLITE_AFF_TEXT;
  1109. // }else if( h==(('b'<<24)+('l'<<16)+('o'<<8)+'b') /* BLOB */
  1110. // && (aff==SQLITE_AFF_NUMERIC || aff==SQLITE_AFF_REAL) ){
  1111. // aff = SQLITE_AFF_NONE;
  1112. //#if !SQLITE_OMIT_FLOATING_POINT
  1113. // }else if( h==(('r'<<24)+('e'<<16)+('a'<<8)+'l') /* REAL */
  1114. // && aff==SQLITE_AFF_NUMERIC ){
  1115. // aff = SQLITE_AFF_REAL;
  1116. // }else if( h==(('f'<<24)+('l'<<16)+('o'<<8)+'a') /* FLOA */
  1117. // && aff==SQLITE_AFF_NUMERIC ){
  1118. // aff = SQLITE_AFF_REAL;
  1119. // }else if( h==(('d'<<24)+('o'<<16)+('u'<<8)+'b') /* DOUB */
  1120. // && aff==SQLITE_AFF_NUMERIC ){
  1121. // aff = SQLITE_AFF_REAL;
  1122. //#endif
  1123. // }else if( (h&0x00FFFFFF)==(('i'<<16)+('n'<<8)+'t') ){ /* INT */
  1124. // aff = SQLITE_AFF_INTEGER;
  1125. // break;
  1126. // }
  1127. // }
  1128. // return aff;
  1129. }
  1130. /*
  1131. ** This routine is called by the parser while in the middle of
  1132. ** parsing a CREATE TABLE statement. The pFirst token is the first
  1133. ** token in the sequence of tokens that describe the type of the
  1134. ** column currently under construction. pLast is the last token
  1135. ** in the sequence. Use this information to construct a string
  1136. ** that contains the typename of the column and store that string
  1137. ** in zType.
  1138. */
  1139. static void sqlite3AddColumnType( Parse pParse, Token pType )
  1140. {
  1141. Table p;
  1142. Column pCol;
  1143. p = pParse.pNewTable;
  1144. if ( p == null || NEVER( p.nCol < 1 ) )
  1145. return;
  1146. pCol = p.aCol[p.nCol - 1];
  1147. Debug.Assert( pCol.zType == null );
  1148. pCol.zType = sqlite3NameFromToken( pParse.db, pType );
  1149. pCol.affinity = sqlite3AffinityType( pCol.zType );
  1150. }
  1151. /*
  1152. ** The expression is the default value for the most recently added column
  1153. ** of the table currently under construction.
  1154. **
  1155. ** Default value expressions must be constant. Raise an exception if this
  1156. ** is not the case.
  1157. **
  1158. ** This routine is called by the parser while in the middle of
  1159. ** parsing a CREATE TABLE statement.
  1160. */
  1161. static void sqlite3AddDefaultValue( Parse pParse, ExprSpan pSpan )
  1162. {
  1163. Table p;
  1164. Column pCol;
  1165. sqlite3 db = pParse.db;
  1166. p = pParse.pNewTable;
  1167. if ( p != null )
  1168. {
  1169. pCol = ( p.aCol[p.nCol - 1] );
  1170. if ( sqlite3ExprIsConstantOrFunction( pSpan.pExpr ) == 0 )
  1171. {
  1172. sqlite3ErrorMsg( pParse, "default value of column [%s] is not constant",
  1173. pCol.zName );
  1174. }
  1175. else
  1176. {
  1177. /* A copy of pExpr is used instead of the original, as pExpr contains
  1178. ** tokens that point to volatile memory. The 'span' of the expression
  1179. ** is required by pragma table_info.
  1180. */
  1181. sqlite3ExprDelete( db, ref pCol.pDflt );
  1182. pCol.pDflt = sqlite3ExprDup( db, pSpan.pExpr, EXPRDUP_REDUCE );
  1183. sqlite3DbFree( db, ref pCol.zDflt );
  1184. pCol.zDflt = pSpan.zStart.Substring( 0, pSpan.zStart.Length - pSpan.zEnd.Length );
  1185. //sqlite3DbStrNDup( db, pSpan.zStart,
  1186. // (int)( pSpan.zEnd.Length - pSpan.zStart.Length ) );
  1187. }
  1188. }
  1189. sqlite3ExprDelete( db, ref pSpan.pExpr );
  1190. }
  1191. /*
  1192. ** Designate the PRIMARY KEY for the table. pList is a list of names
  1193. ** of columns that form the primary key. If pList is NULL, then the
  1194. ** most recently added column of the table is the primary key.
  1195. **
  1196. ** A table can have at most one primary key. If the table already has
  1197. ** a primary key (and this is the second primary key) then create an
  1198. ** error.
  1199. **
  1200. ** If the PRIMARY KEY is on a single column whose datatype is INTEGER,
  1201. ** then we will try to use that column as the rowid. Set the Table.iPKey
  1202. ** field of the table under construction to be the index of the
  1203. ** INTEGER PRIMARY KEY column. Table.iPKey is set to -1 if there is
  1204. ** no INTEGER PRIMARY KEY.
  1205. **
  1206. ** If the key is not an INTEGER PRIMARY KEY, then create a unique
  1207. ** index for the key. No index is created for INTEGER PRIMARY KEYs.
  1208. */
  1209. // OVERLOADS, so I don't need to rewrite parse.c
  1210. static void sqlite3AddPrimaryKey( Parse pParse, int null_2, int onError, int autoInc, int sortOrder )
  1211. {
  1212. sqlite3AddPrimaryKey( pParse, null, onError, autoInc, sortOrder );
  1213. }
  1214. static void sqlite3AddPrimaryKey(
  1215. Parse pParse, /* Parsing context */
  1216. ExprList pList, /* List of field names to be indexed */
  1217. int onError, /* What to do with a uniqueness conflict */
  1218. int autoInc, /* True if the AUTOINCREMENT keyword is present */
  1219. int sortOrder /* SQLITE_SO_ASC or SQLITE_SO_DESC */
  1220. )
  1221. {
  1222. Table pTab = pParse.pNewTable;
  1223. string zType = null;
  1224. int iCol = -1, i;
  1225. if ( pTab == null || IN_DECLARE_VTAB )
  1226. goto primary_key_exit;
  1227. if ( ( pTab.tabFlags & TF_HasPrimaryKey ) != 0 )
  1228. {
  1229. sqlite3ErrorMsg( pParse,
  1230. "table \"%s\" has more than one primary key", pTab.zName );
  1231. goto primary_key_exit;
  1232. }
  1233. pTab.tabFlags |= TF_HasPrimaryKey;
  1234. if ( pList == null )
  1235. {
  1236. iCol = pTab.nCol - 1;
  1237. pTab.aCol[iCol].isPrimKey = 1;
  1238. }
  1239. else
  1240. {
  1241. for ( i = 0; i < pList.nExpr; i++ )
  1242. {
  1243. for ( iCol = 0; iCol < pTab.nCol; iCol++ )
  1244. {
  1245. if ( pList.a[i].zName.Equals( pTab.aCol[iCol].zName, StringComparison.InvariantCultureIgnoreCase ) )
  1246. {
  1247. break;
  1248. }
  1249. }
  1250. if ( iCol < pTab.nCol )
  1251. {
  1252. pTab.aCol[iCol].isPrimKey = 1;
  1253. }
  1254. }
  1255. if ( pList.nExpr > 1 )
  1256. iCol = -1;
  1257. }
  1258. if ( iCol >= 0 && iCol < pTab.nCol )
  1259. {
  1260. zType = pTab.aCol[iCol].zType;
  1261. }
  1262. if ( zType != null && zType.Equals( "INTEGER", StringComparison.InvariantCultureIgnoreCase )
  1263. && sortOrder == SQLITE_SO_ASC )
  1264. {
  1265. pTab.iPKey = iCol;
  1266. pTab.keyConf = (byte)onError;
  1267. Debug.Assert( autoInc == 0 || autoInc == 1 );
  1268. pTab.tabFlags |= (u8)( autoInc * TF_Autoincrement );
  1269. }
  1270. else if ( autoInc != 0 )
  1271. {
  1272. #if !SQLITE_OMIT_AUTOINCREMENT
  1273. sqlite3ErrorMsg( pParse, "AUTOINCREMENT is only allowed on an " +
  1274. "INTEGER PRIMARY KEY" );
  1275. #endif
  1276. }
  1277. else
  1278. {
  1279. Index p;
  1280. p = sqlite3CreateIndex( pParse, 0, 0, 0, pList, onError, 0, 0, sortOrder, 0 );
  1281. if ( p != null )
  1282. {
  1283. p.autoIndex = 2;
  1284. }
  1285. pList = null;
  1286. }
  1287. primary_key_exit:
  1288. sqlite3ExprListDelete( pParse.db, ref pList );
  1289. return;
  1290. }
  1291. /*
  1292. ** Add a new CHECK constraint to the table currently under construction.
  1293. */
  1294. static void sqlite3AddCheckConstraint(
  1295. Parse pParse, /* Parsing context */
  1296. Expr pCheckExpr /* The check expression */
  1297. )
  1298. {
  1299. sqlite3 db = pParse.db;
  1300. #if !SQLITE_OMIT_CHECK
  1301. Table pTab = pParse.pNewTable;
  1302. if ( pTab != null && !IN_DECLARE_VTAB )
  1303. {
  1304. pTab.pCheck = sqlite3ExprAnd( db, pTab.pCheck, pCheckExpr );
  1305. }
  1306. else
  1307. #endif
  1308. {
  1309. sqlite3ExprDelete( db, ref pCheckExpr );
  1310. }
  1311. }
  1312. /*
  1313. ** Set the collation function of the most recently parsed table column
  1314. ** to the CollSeq given.
  1315. */
  1316. static void sqlite3AddCollateType( Parse pParse, Token pToken )
  1317. {
  1318. Table p;
  1319. int i;
  1320. string zColl; /* Dequoted name of collation sequence */
  1321. sqlite3 db;
  1322. if ( ( p = pParse.pNewTable ) == null )
  1323. return;
  1324. i = p.nCol - 1;
  1325. db = pParse.db;
  1326. zColl = sqlite3NameFromToken( db, pToken );
  1327. if ( zColl == null )
  1328. return;
  1329. if ( sqlite3LocateCollSeq( pParse, zColl ) != null )
  1330. {
  1331. Index pIdx;
  1332. p.aCol[i].zColl = zColl;
  1333. /* If the column is declared as "<name> PRIMARY KEY COLLATE <type>",
  1334. ** then an index may have been created on this column before the
  1335. ** collation type was added. Correct this if it is the case.
  1336. */
  1337. for ( pIdx = p.pIndex; pIdx != null; pIdx = pIdx.pNext )
  1338. {
  1339. Debug.Assert( pIdx.nColumn == 1 );
  1340. if ( pIdx.aiColumn[0] == i )
  1341. {
  1342. pIdx.azColl[0] = p.aCol[i].zColl;
  1343. }
  1344. }
  1345. }
  1346. else
  1347. {
  1348. sqlite3DbFree( db, ref zColl );
  1349. }
  1350. }
  1351. /*
  1352. ** This function returns the collation sequence for database native text
  1353. ** encoding identified by the string zName, length nName.
  1354. **
  1355. ** If the requested collation sequence is not available, or not available
  1356. ** in the database native encoding, the collation factory is invoked to
  1357. ** request it. If the collation factory does not supply such a sequence,
  1358. ** and the sequence is available in another text encoding, then that is
  1359. ** returned instead.
  1360. **
  1361. ** If no versions of the requested collations sequence are available, or
  1362. ** another error occurs, NULL is returned and an error message written into
  1363. ** pParse.
  1364. **
  1365. ** This routine is a wrapper around sqlite3FindCollSeq(). This routine
  1366. ** invokes the collation factory if the named collation cannot be found
  1367. ** and generates an error message.
  1368. **
  1369. ** See also: sqlite3FindCollSeq(), sqlite3GetCollSeq()
  1370. */
  1371. static CollSeq sqlite3LocateCollSeq( Parse pParse, string zName )
  1372. {
  1373. sqlite3 db = pParse.db;
  1374. u8 enc = db.aDb[0].pSchema.enc;// ENC(db);
  1375. u8 initbusy = db.init.busy;
  1376. CollSeq pColl;
  1377. pColl = sqlite3FindCollSeq( db, enc, zName, initbusy );
  1378. if ( 0 == initbusy && ( pColl == null || pColl.xCmp == null ) )

Large files files are truncated, but you can click here to view the full file