sqliteInt.h 143 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390
  1. /*
  2. ** 2001 September 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. ** Internal interface definitions for SQLite.
  13. **
  14. */
  15. #include "sqlite3.h"
  16. #ifndef _SQLITEINT_H_
  17. #define _SQLITEINT_H_
  18. /*
  19. ** These #defines should enable >2GB file support on POSIX if the
  20. ** underlying operating system supports it. If the OS lacks
  21. ** large file support, or if the OS is windows, these should be no-ops.
  22. **
  23. ** Ticket #2739: The _LARGEFILE_SOURCE macro must appear before any
  24. ** system #includes. Hence, this block of code must be the very first
  25. ** code in all source files.
  26. **
  27. ** Large file support can be disabled using the -DSQLITE_DISABLE_LFS switch
  28. ** on the compiler command line. This is necessary if you are compiling
  29. ** on a recent machine (ex: Red Hat 7.2) but you want your code to work
  30. ** on an older machine (ex: Red Hat 6.0). If you compile on Red Hat 7.2
  31. ** without this option, LFS is enable. But LFS does not exist in the kernel
  32. ** in Red Hat 6.0, so the code won't work. Hence, for maximum binary
  33. ** portability you should omit LFS.
  34. **
  35. ** Similar is true for Mac OS X. LFS is only supported on Mac OS X 9 and later.
  36. */
  37. #ifndef SQLITE_DISABLE_LFS
  38. # define _LARGE_FILE 1
  39. # ifndef _FILE_OFFSET_BITS
  40. # define _FILE_OFFSET_BITS 64
  41. # endif
  42. # define _LARGEFILE_SOURCE 1
  43. #endif
  44. /*
  45. ** Include the configuration header output by 'configure' if we're using the
  46. ** autoconf-based build
  47. */
  48. #ifdef _HAVE_SQLITE_CONFIG_H
  49. #include "config.h"
  50. #endif
  51. #include "sqliteLimit.h"
  52. /* Disable nuisance warnings on Borland compilers */
  53. #if defined(__BORLANDC__)
  54. #pragma warn -rch /* unreachable code */
  55. #pragma warn -ccc /* Condition is always true or false */
  56. #pragma warn -aus /* Assigned value is never used */
  57. #pragma warn -csu /* Comparing signed and unsigned */
  58. #pragma warn -spa /* Suspicious pointer arithmetic */
  59. #endif
  60. /* Needed for various definitions... */
  61. #ifndef _GNU_SOURCE
  62. # define _GNU_SOURCE
  63. #endif
  64. #if defined(__OpenBSD__) && !defined(_BSD_SOURCE)
  65. # define _BSD_SOURCE
  66. #endif
  67. /*
  68. ** Include standard header files as necessary
  69. */
  70. #ifdef HAVE_STDINT_H
  71. #include <stdint.h>
  72. #endif
  73. #ifdef HAVE_INTTYPES_H
  74. #include <inttypes.h>
  75. #endif
  76. /*
  77. ** The following macros are used to cast pointers to integers and
  78. ** integers to pointers. The way you do this varies from one compiler
  79. ** to the next, so we have developed the following set of #if statements
  80. ** to generate appropriate macros for a wide range of compilers.
  81. **
  82. ** The correct "ANSI" way to do this is to use the intptr_t type.
  83. ** Unfortunately, that typedef is not available on all compilers, or
  84. ** if it is available, it requires an #include of specific headers
  85. ** that vary from one machine to the next.
  86. **
  87. ** Ticket #3860: The llvm-gcc-4.2 compiler from Apple chokes on
  88. ** the ((void*)&((char*)0)[X]) construct. But MSVC chokes on ((void*)(X)).
  89. ** So we have to define the macros in different ways depending on the
  90. ** compiler.
  91. */
  92. #if defined(__PTRDIFF_TYPE__) /* This case should work for GCC */
  93. # define SQLITE_INT_TO_PTR(X) ((void*)(__PTRDIFF_TYPE__)(X))
  94. # define SQLITE_PTR_TO_INT(X) ((int)(__PTRDIFF_TYPE__)(X))
  95. #elif !defined(__GNUC__) /* Works for compilers other than LLVM */
  96. # define SQLITE_INT_TO_PTR(X) ((void*)&((char*)0)[X])
  97. # define SQLITE_PTR_TO_INT(X) ((int)(((char*)X)-(char*)0))
  98. #elif defined(HAVE_STDINT_H) /* Use this case if we have ANSI headers */
  99. # define SQLITE_INT_TO_PTR(X) ((void*)(intptr_t)(X))
  100. # define SQLITE_PTR_TO_INT(X) ((int)(intptr_t)(X))
  101. #else /* Generates a warning - but it always works */
  102. # define SQLITE_INT_TO_PTR(X) ((void*)(X))
  103. # define SQLITE_PTR_TO_INT(X) ((int)(X))
  104. #endif
  105. /*
  106. ** The SQLITE_THREADSAFE macro must be defined as 0, 1, or 2.
  107. ** 0 means mutexes are permanently disable and the library is never
  108. ** threadsafe. 1 means the library is serialized which is the highest
  109. ** level of threadsafety. 2 means the library is multithreaded - multiple
  110. ** threads can use SQLite as long as no two threads try to use the same
  111. ** database connection at the same time.
  112. **
  113. ** Older versions of SQLite used an optional THREADSAFE macro.
  114. ** We support that for legacy.
  115. */
  116. #if !defined(SQLITE_THREADSAFE)
  117. # if defined(THREADSAFE)
  118. # define SQLITE_THREADSAFE THREADSAFE
  119. # else
  120. # define SQLITE_THREADSAFE 1 /* IMP: R-07272-22309 */
  121. # endif
  122. #endif
  123. /*
  124. ** Powersafe overwrite is on by default. But can be turned off using
  125. ** the -DSQLITE_POWERSAFE_OVERWRITE=0 command-line option.
  126. */
  127. #ifndef SQLITE_POWERSAFE_OVERWRITE
  128. # define SQLITE_POWERSAFE_OVERWRITE 1
  129. #endif
  130. /*
  131. ** The SQLITE_DEFAULT_MEMSTATUS macro must be defined as either 0 or 1.
  132. ** It determines whether or not the features related to
  133. ** SQLITE_CONFIG_MEMSTATUS are available by default or not. This value can
  134. ** be overridden at runtime using the sqlite3_config() API.
  135. */
  136. #if !defined(SQLITE_DEFAULT_MEMSTATUS)
  137. # define SQLITE_DEFAULT_MEMSTATUS 1
  138. #endif
  139. /*
  140. ** Exactly one of the following macros must be defined in order to
  141. ** specify which memory allocation subsystem to use.
  142. **
  143. ** SQLITE_SYSTEM_MALLOC // Use normal system malloc()
  144. ** SQLITE_WIN32_MALLOC // Use Win32 native heap API
  145. ** SQLITE_ZERO_MALLOC // Use a stub allocator that always fails
  146. ** SQLITE_MEMDEBUG // Debugging version of system malloc()
  147. **
  148. ** On Windows, if the SQLITE_WIN32_MALLOC_VALIDATE macro is defined and the
  149. ** assert() macro is enabled, each call into the Win32 native heap subsystem
  150. ** will cause HeapValidate to be called. If heap validation should fail, an
  151. ** assertion will be triggered.
  152. **
  153. ** If none of the above are defined, then set SQLITE_SYSTEM_MALLOC as
  154. ** the default.
  155. */
  156. #if defined(SQLITE_SYSTEM_MALLOC) \
  157. + defined(SQLITE_WIN32_MALLOC) \
  158. + defined(SQLITE_ZERO_MALLOC) \
  159. + defined(SQLITE_MEMDEBUG)>1
  160. # error "Two or more of the following compile-time configuration options\
  161. are defined but at most one is allowed:\
  162. SQLITE_SYSTEM_MALLOC, SQLITE_WIN32_MALLOC, SQLITE_MEMDEBUG,\
  163. SQLITE_ZERO_MALLOC"
  164. #endif
  165. #if defined(SQLITE_SYSTEM_MALLOC) \
  166. + defined(SQLITE_WIN32_MALLOC) \
  167. + defined(SQLITE_ZERO_MALLOC) \
  168. + defined(SQLITE_MEMDEBUG)==0
  169. # define SQLITE_SYSTEM_MALLOC 1
  170. #endif
  171. /*
  172. ** If SQLITE_MALLOC_SOFT_LIMIT is not zero, then try to keep the
  173. ** sizes of memory allocations below this value where possible.
  174. */
  175. #if !defined(SQLITE_MALLOC_SOFT_LIMIT)
  176. # define SQLITE_MALLOC_SOFT_LIMIT 1024
  177. #endif
  178. /*
  179. ** We need to define _XOPEN_SOURCE as follows in order to enable
  180. ** recursive mutexes on most Unix systems and fchmod() on OpenBSD.
  181. ** But _XOPEN_SOURCE define causes problems for Mac OS X, so omit
  182. ** it.
  183. */
  184. #if !defined(_XOPEN_SOURCE) && !defined(__DARWIN__) && !defined(__APPLE__)
  185. # define _XOPEN_SOURCE 600
  186. #endif
  187. /*
  188. ** NDEBUG and SQLITE_DEBUG are opposites. It should always be true that
  189. ** defined(NDEBUG)==!defined(SQLITE_DEBUG). If this is not currently true,
  190. ** make it true by defining or undefining NDEBUG.
  191. **
  192. ** Setting NDEBUG makes the code smaller and faster by disabling the
  193. ** assert() statements in the code. So we want the default action
  194. ** to be for NDEBUG to be set and NDEBUG to be undefined only if SQLITE_DEBUG
  195. ** is set. Thus NDEBUG becomes an opt-in rather than an opt-out
  196. ** feature.
  197. */
  198. #if !defined(NDEBUG) && !defined(SQLITE_DEBUG)
  199. # define NDEBUG 1
  200. #endif
  201. #if defined(NDEBUG) && defined(SQLITE_DEBUG)
  202. # undef NDEBUG
  203. #endif
  204. /*
  205. ** The testcase() macro is used to aid in coverage testing. When
  206. ** doing coverage testing, the condition inside the argument to
  207. ** testcase() must be evaluated both true and false in order to
  208. ** get full branch coverage. The testcase() macro is inserted
  209. ** to help ensure adequate test coverage in places where simple
  210. ** condition/decision coverage is inadequate. For example, testcase()
  211. ** can be used to make sure boundary values are tested. For
  212. ** bitmask tests, testcase() can be used to make sure each bit
  213. ** is significant and used at least once. On switch statements
  214. ** where multiple cases go to the same block of code, testcase()
  215. ** can insure that all cases are evaluated.
  216. **
  217. */
  218. #ifdef SQLITE_COVERAGE_TEST
  219. void sqlite3Coverage(int);
  220. # define testcase(X) if( X ){ sqlite3Coverage(__LINE__); }
  221. #else
  222. # define testcase(X)
  223. #endif
  224. /*
  225. ** The TESTONLY macro is used to enclose variable declarations or
  226. ** other bits of code that are needed to support the arguments
  227. ** within testcase() and assert() macros.
  228. */
  229. #if !defined(NDEBUG) || defined(SQLITE_COVERAGE_TEST)
  230. # define TESTONLY(X) X
  231. #else
  232. # define TESTONLY(X)
  233. #endif
  234. /*
  235. ** Sometimes we need a small amount of code such as a variable initialization
  236. ** to setup for a later assert() statement. We do not want this code to
  237. ** appear when assert() is disabled. The following macro is therefore
  238. ** used to contain that setup code. The "VVA" acronym stands for
  239. ** "Verification, Validation, and Accreditation". In other words, the
  240. ** code within VVA_ONLY() will only run during verification processes.
  241. */
  242. #ifndef NDEBUG
  243. # define VVA_ONLY(X) X
  244. #else
  245. # define VVA_ONLY(X)
  246. #endif
  247. /*
  248. ** The ALWAYS and NEVER macros surround boolean expressions which
  249. ** are intended to always be true or false, respectively. Such
  250. ** expressions could be omitted from the code completely. But they
  251. ** are included in a few cases in order to enhance the resilience
  252. ** of SQLite to unexpected behavior - to make the code "self-healing"
  253. ** or "ductile" rather than being "brittle" and crashing at the first
  254. ** hint of unplanned behavior.
  255. **
  256. ** In other words, ALWAYS and NEVER are added for defensive code.
  257. **
  258. ** When doing coverage testing ALWAYS and NEVER are hard-coded to
  259. ** be true and false so that the unreachable code they specify will
  260. ** not be counted as untested code.
  261. */
  262. #if defined(SQLITE_COVERAGE_TEST)
  263. # define ALWAYS(X) (1)
  264. # define NEVER(X) (0)
  265. #elif !defined(NDEBUG)
  266. # define ALWAYS(X) ((X)?1:(assert(0),0))
  267. # define NEVER(X) ((X)?(assert(0),1):0)
  268. #else
  269. # define ALWAYS(X) (X)
  270. # define NEVER(X) (X)
  271. #endif
  272. /*
  273. ** Return true (non-zero) if the input is a integer that is too large
  274. ** to fit in 32-bits. This macro is used inside of various testcase()
  275. ** macros to verify that we have tested SQLite for large-file support.
  276. */
  277. #define IS_BIG_INT(X) (((X)&~(i64)0xffffffff)!=0)
  278. /*
  279. ** The macro unlikely() is a hint that surrounds a boolean
  280. ** expression that is usually false. Macro likely() surrounds
  281. ** a boolean expression that is usually true. These hints could,
  282. ** in theory, be used by the compiler to generate better code, but
  283. ** currently they are just comments for human readers.
  284. */
  285. #define likely(X) (X)
  286. #define unlikely(X) (X)
  287. #include "hash.h"
  288. #include "parse.h"
  289. #include <stdio.h>
  290. #include <stdlib.h>
  291. #include <string.h>
  292. #include <assert.h>
  293. #include <stddef.h>
  294. /*
  295. ** If compiling for a processor that lacks floating point support,
  296. ** substitute integer for floating-point
  297. */
  298. #ifdef SQLITE_OMIT_FLOATING_POINT
  299. # define double sqlite_int64
  300. # define float sqlite_int64
  301. # define LONGDOUBLE_TYPE sqlite_int64
  302. # ifndef SQLITE_BIG_DBL
  303. # define SQLITE_BIG_DBL (((sqlite3_int64)1)<<50)
  304. # endif
  305. # define SQLITE_OMIT_DATETIME_FUNCS 1
  306. # define SQLITE_OMIT_TRACE 1
  307. # undef SQLITE_MIXED_ENDIAN_64BIT_FLOAT
  308. # undef SQLITE_HAVE_ISNAN
  309. #endif
  310. #ifndef SQLITE_BIG_DBL
  311. # define SQLITE_BIG_DBL (1e99)
  312. #endif
  313. /*
  314. ** OMIT_TEMPDB is set to 1 if SQLITE_OMIT_TEMPDB is defined, or 0
  315. ** afterward. Having this macro allows us to cause the C compiler
  316. ** to omit code used by TEMP tables without messy #ifndef statements.
  317. */
  318. #ifdef SQLITE_OMIT_TEMPDB
  319. #define OMIT_TEMPDB 1
  320. #else
  321. #define OMIT_TEMPDB 0
  322. #endif
  323. /*
  324. ** The "file format" number is an integer that is incremented whenever
  325. ** the VDBE-level file format changes. The following macros define the
  326. ** the default file format for new databases and the maximum file format
  327. ** that the library can read.
  328. */
  329. #define SQLITE_MAX_FILE_FORMAT 4
  330. #ifndef SQLITE_DEFAULT_FILE_FORMAT
  331. # define SQLITE_DEFAULT_FILE_FORMAT 4
  332. #endif
  333. /*
  334. ** Determine whether triggers are recursive by default. This can be
  335. ** changed at run-time using a pragma.
  336. */
  337. #ifndef SQLITE_DEFAULT_RECURSIVE_TRIGGERS
  338. # define SQLITE_DEFAULT_RECURSIVE_TRIGGERS 0
  339. #endif
  340. /*
  341. ** Provide a default value for SQLITE_TEMP_STORE in case it is not specified
  342. ** on the command-line
  343. */
  344. #ifndef SQLITE_TEMP_STORE
  345. # define SQLITE_TEMP_STORE 1
  346. # define SQLITE_TEMP_STORE_xc 1 /* Exclude from ctime.c */
  347. #endif
  348. /*
  349. ** GCC does not define the offsetof() macro so we'll have to do it
  350. ** ourselves.
  351. */
  352. #ifndef offsetof
  353. #define offsetof(STRUCTURE,FIELD) ((int)((char*)&((STRUCTURE*)0)->FIELD))
  354. #endif
  355. /*
  356. ** Macros to compute minimum and maximum of two numbers.
  357. */
  358. #define MIN(A,B) ((A)<(B)?(A):(B))
  359. #define MAX(A,B) ((A)>(B)?(A):(B))
  360. /*
  361. ** Check to see if this machine uses EBCDIC. (Yes, believe it or
  362. ** not, there are still machines out there that use EBCDIC.)
  363. */
  364. #if 'A' == '\301'
  365. # define SQLITE_EBCDIC 1
  366. #else
  367. # define SQLITE_ASCII 1
  368. #endif
  369. /*
  370. ** Integers of known sizes. These typedefs might change for architectures
  371. ** where the sizes very. Preprocessor macros are available so that the
  372. ** types can be conveniently redefined at compile-type. Like this:
  373. **
  374. ** cc '-DUINTPTR_TYPE=long long int' ...
  375. */
  376. #ifndef UINT32_TYPE
  377. # ifdef HAVE_UINT32_T
  378. # define UINT32_TYPE uint32_t
  379. # else
  380. # define UINT32_TYPE unsigned int
  381. # endif
  382. #endif
  383. #ifndef UINT16_TYPE
  384. # ifdef HAVE_UINT16_T
  385. # define UINT16_TYPE uint16_t
  386. # else
  387. # define UINT16_TYPE unsigned short int
  388. # endif
  389. #endif
  390. #ifndef INT16_TYPE
  391. # ifdef HAVE_INT16_T
  392. # define INT16_TYPE int16_t
  393. # else
  394. # define INT16_TYPE short int
  395. # endif
  396. #endif
  397. #ifndef UINT8_TYPE
  398. # ifdef HAVE_UINT8_T
  399. # define UINT8_TYPE uint8_t
  400. # else
  401. # define UINT8_TYPE unsigned char
  402. # endif
  403. #endif
  404. #ifndef INT8_TYPE
  405. # ifdef HAVE_INT8_T
  406. # define INT8_TYPE int8_t
  407. # else
  408. # define INT8_TYPE signed char
  409. # endif
  410. #endif
  411. #ifndef LONGDOUBLE_TYPE
  412. # define LONGDOUBLE_TYPE long double
  413. #endif
  414. typedef sqlite_int64 i64; /* 8-byte signed integer */
  415. typedef sqlite_uint64 u64; /* 8-byte unsigned integer */
  416. typedef UINT32_TYPE u32; /* 4-byte unsigned integer */
  417. typedef UINT16_TYPE u16; /* 2-byte unsigned integer */
  418. typedef INT16_TYPE i16; /* 2-byte signed integer */
  419. typedef UINT8_TYPE u8; /* 1-byte unsigned integer */
  420. typedef INT8_TYPE i8; /* 1-byte signed integer */
  421. /*
  422. ** SQLITE_MAX_U32 is a u64 constant that is the maximum u64 value
  423. ** that can be stored in a u32 without loss of data. The value
  424. ** is 0x00000000ffffffff. But because of quirks of some compilers, we
  425. ** have to specify the value in the less intuitive manner shown:
  426. */
  427. #define SQLITE_MAX_U32 ((((u64)1)<<32)-1)
  428. /*
  429. ** The datatype used to store estimates of the number of rows in a
  430. ** table or index. This is an unsigned integer type. For 99.9% of
  431. ** the world, a 32-bit integer is sufficient. But a 64-bit integer
  432. ** can be used at compile-time if desired.
  433. */
  434. #ifdef SQLITE_64BIT_STATS
  435. typedef u64 tRowcnt; /* 64-bit only if requested at compile-time */
  436. #else
  437. typedef u32 tRowcnt; /* 32-bit is the default */
  438. #endif
  439. /*
  440. ** Estimated quantities used for query planning are stored as 16-bit
  441. ** logarithms. For quantity X, the value stored is 10*log2(X). This
  442. ** gives a possible range of values of approximately 1.0e986 to 1e-986.
  443. ** But the allowed values are "grainy". Not every value is representable.
  444. ** For example, quantities 16 and 17 are both represented by a LogEst
  445. ** of 40. However, since LogEst quantatites are suppose to be estimates,
  446. ** not exact values, this imprecision is not a problem.
  447. **
  448. ** "LogEst" is short for "Logarithimic Estimate".
  449. **
  450. ** Examples:
  451. ** 1 -> 0 20 -> 43 10000 -> 132
  452. ** 2 -> 10 25 -> 46 25000 -> 146
  453. ** 3 -> 16 100 -> 66 1000000 -> 199
  454. ** 4 -> 20 1000 -> 99 1048576 -> 200
  455. ** 10 -> 33 1024 -> 100 4294967296 -> 320
  456. **
  457. ** The LogEst can be negative to indicate fractional values.
  458. ** Examples:
  459. **
  460. ** 0.5 -> -10 0.1 -> -33 0.0625 -> -40
  461. */
  462. typedef INT16_TYPE LogEst;
  463. /*
  464. ** Macros to determine whether the machine is big or little endian,
  465. ** evaluated at runtime.
  466. */
  467. #ifdef SQLITE_AMALGAMATION
  468. const int sqlite3one = 1;
  469. #else
  470. extern const int sqlite3one;
  471. #endif
  472. #if defined(i386) || defined(__i386__) || defined(_M_IX86)\
  473. || defined(__x86_64) || defined(__x86_64__)
  474. # define SQLITE_BIGENDIAN 0
  475. # define SQLITE_LITTLEENDIAN 1
  476. # define SQLITE_UTF16NATIVE SQLITE_UTF16LE
  477. #else
  478. # define SQLITE_BIGENDIAN (*(char *)(&sqlite3one)==0)
  479. # define SQLITE_LITTLEENDIAN (*(char *)(&sqlite3one)==1)
  480. # define SQLITE_UTF16NATIVE (SQLITE_BIGENDIAN?SQLITE_UTF16BE:SQLITE_UTF16LE)
  481. #endif
  482. /*
  483. ** Constants for the largest and smallest possible 64-bit signed integers.
  484. ** These macros are designed to work correctly on both 32-bit and 64-bit
  485. ** compilers.
  486. */
  487. #define LARGEST_INT64 (0xffffffff|(((i64)0x7fffffff)<<32))
  488. #define SMALLEST_INT64 (((i64)-1) - LARGEST_INT64)
  489. /*
  490. ** Round up a number to the next larger multiple of 8. This is used
  491. ** to force 8-byte alignment on 64-bit architectures.
  492. */
  493. #define ROUND8(x) (((x)+7)&~7)
  494. /*
  495. ** Round down to the nearest multiple of 8
  496. */
  497. #define ROUNDDOWN8(x) ((x)&~7)
  498. /*
  499. ** Assert that the pointer X is aligned to an 8-byte boundary. This
  500. ** macro is used only within assert() to verify that the code gets
  501. ** all alignment restrictions correct.
  502. **
  503. ** Except, if SQLITE_4_BYTE_ALIGNED_MALLOC is defined, then the
  504. ** underlying malloc() implemention might return us 4-byte aligned
  505. ** pointers. In that case, only verify 4-byte alignment.
  506. */
  507. #ifdef SQLITE_4_BYTE_ALIGNED_MALLOC
  508. # define EIGHT_BYTE_ALIGNMENT(X) ((((char*)(X) - (char*)0)&3)==0)
  509. #else
  510. # define EIGHT_BYTE_ALIGNMENT(X) ((((char*)(X) - (char*)0)&7)==0)
  511. #endif
  512. /*
  513. ** Disable MMAP on platforms where it is known to not work
  514. */
  515. #if defined(__OpenBSD__) || defined(__QNXNTO__)
  516. # undef SQLITE_MAX_MMAP_SIZE
  517. # define SQLITE_MAX_MMAP_SIZE 0
  518. #endif
  519. /*
  520. ** Default maximum size of memory used by memory-mapped I/O in the VFS
  521. */
  522. #ifdef __APPLE__
  523. # include <TargetConditionals.h>
  524. # if TARGET_OS_IPHONE
  525. # undef SQLITE_MAX_MMAP_SIZE
  526. # define SQLITE_MAX_MMAP_SIZE 0
  527. # endif
  528. #endif
  529. #ifndef SQLITE_MAX_MMAP_SIZE
  530. # if defined(SQLITE_OS_RTT)
  531. # define SQLITE_MAX_MMAP_SIZE 0
  532. # elif defined(__linux__) \
  533. || defined(_WIN32) \
  534. || (defined(__APPLE__) && defined(__MACH__)) \
  535. || defined(__sun)
  536. # define SQLITE_MAX_MMAP_SIZE 0x7fff0000 /* 2147418112 */
  537. # else
  538. # define SQLITE_MAX_MMAP_SIZE 0
  539. # endif
  540. # define SQLITE_MAX_MMAP_SIZE_xc 1 /* exclude from ctime.c */
  541. #endif
  542. /*
  543. ** The default MMAP_SIZE is zero on all platforms. Or, even if a larger
  544. ** default MMAP_SIZE is specified at compile-time, make sure that it does
  545. ** not exceed the maximum mmap size.
  546. */
  547. #ifndef SQLITE_DEFAULT_MMAP_SIZE
  548. # define SQLITE_DEFAULT_MMAP_SIZE 0
  549. # define SQLITE_DEFAULT_MMAP_SIZE_xc 1 /* Exclude from ctime.c */
  550. #endif
  551. #if SQLITE_DEFAULT_MMAP_SIZE>SQLITE_MAX_MMAP_SIZE
  552. # undef SQLITE_DEFAULT_MMAP_SIZE
  553. # define SQLITE_DEFAULT_MMAP_SIZE SQLITE_MAX_MMAP_SIZE
  554. #endif
  555. /*
  556. ** Only one of SQLITE_ENABLE_STAT3 or SQLITE_ENABLE_STAT4 can be defined.
  557. ** Priority is given to SQLITE_ENABLE_STAT4. If either are defined, also
  558. ** define SQLITE_ENABLE_STAT3_OR_STAT4
  559. */
  560. #ifdef SQLITE_ENABLE_STAT4
  561. # undef SQLITE_ENABLE_STAT3
  562. # define SQLITE_ENABLE_STAT3_OR_STAT4 1
  563. #elif SQLITE_ENABLE_STAT3
  564. # define SQLITE_ENABLE_STAT3_OR_STAT4 1
  565. #elif SQLITE_ENABLE_STAT3_OR_STAT4
  566. # undef SQLITE_ENABLE_STAT3_OR_STAT4
  567. #endif
  568. /*
  569. ** An instance of the following structure is used to store the busy-handler
  570. ** callback for a given sqlite handle.
  571. **
  572. ** The sqlite.busyHandler member of the sqlite struct contains the busy
  573. ** callback for the database handle. Each pager opened via the sqlite
  574. ** handle is passed a pointer to sqlite.busyHandler. The busy-handler
  575. ** callback is currently invoked only from within pager.c.
  576. */
  577. typedef struct BusyHandler BusyHandler;
  578. struct BusyHandler {
  579. int (*xFunc)(void *,int); /* The busy callback */
  580. void *pArg; /* First arg to busy callback */
  581. int nBusy; /* Incremented with each busy call */
  582. };
  583. /*
  584. ** Name of the master database table. The master database table
  585. ** is a special table that holds the names and attributes of all
  586. ** user tables and indices.
  587. */
  588. #define MASTER_NAME "sqlite_master"
  589. #define TEMP_MASTER_NAME "sqlite_temp_master"
  590. /*
  591. ** The root-page of the master database table.
  592. */
  593. #define MASTER_ROOT 1
  594. /*
  595. ** The name of the schema table.
  596. */
  597. #define SCHEMA_TABLE(x) ((!OMIT_TEMPDB)&&(x==1)?TEMP_MASTER_NAME:MASTER_NAME)
  598. /*
  599. ** A convenience macro that returns the number of elements in
  600. ** an array.
  601. */
  602. #define ArraySize(X) ((int)(sizeof(X)/sizeof(X[0])))
  603. /*
  604. ** Determine if the argument is a power of two
  605. */
  606. #define IsPowerOfTwo(X) (((X)&((X)-1))==0)
  607. /*
  608. ** The following value as a destructor means to use sqlite3DbFree().
  609. ** The sqlite3DbFree() routine requires two parameters instead of the
  610. ** one parameter that destructors normally want. So we have to introduce
  611. ** this magic value that the code knows to handle differently. Any
  612. ** pointer will work here as long as it is distinct from SQLITE_STATIC
  613. ** and SQLITE_TRANSIENT.
  614. */
  615. #define SQLITE_DYNAMIC ((sqlite3_destructor_type)sqlite3MallocSize)
  616. /*
  617. ** When SQLITE_OMIT_WSD is defined, it means that the target platform does
  618. ** not support Writable Static Data (WSD) such as global and static variables.
  619. ** All variables must either be on the stack or dynamically allocated from
  620. ** the heap. When WSD is unsupported, the variable declarations scattered
  621. ** throughout the SQLite code must become constants instead. The SQLITE_WSD
  622. ** macro is used for this purpose. And instead of referencing the variable
  623. ** directly, we use its constant as a key to lookup the run-time allocated
  624. ** buffer that holds real variable. The constant is also the initializer
  625. ** for the run-time allocated buffer.
  626. **
  627. ** In the usual case where WSD is supported, the SQLITE_WSD and GLOBAL
  628. ** macros become no-ops and have zero performance impact.
  629. */
  630. #ifdef SQLITE_OMIT_WSD
  631. #define SQLITE_WSD const
  632. #define GLOBAL(t,v) (*(t*)sqlite3_wsd_find((void*)&(v), sizeof(v)))
  633. #define sqlite3GlobalConfig GLOBAL(struct Sqlite3Config, sqlite3Config)
  634. int sqlite3_wsd_init(int N, int J);
  635. void *sqlite3_wsd_find(void *K, int L);
  636. #else
  637. #define SQLITE_WSD
  638. #define GLOBAL(t,v) v
  639. #define sqlite3GlobalConfig sqlite3Config
  640. #endif
  641. /*
  642. ** The following macros are used to suppress compiler warnings and to
  643. ** make it clear to human readers when a function parameter is deliberately
  644. ** left unused within the body of a function. This usually happens when
  645. ** a function is called via a function pointer. For example the
  646. ** implementation of an SQL aggregate step callback may not use the
  647. ** parameter indicating the number of arguments passed to the aggregate,
  648. ** if it knows that this is enforced elsewhere.
  649. **
  650. ** When a function parameter is not used at all within the body of a function,
  651. ** it is generally named "NotUsed" or "NotUsed2" to make things even clearer.
  652. ** However, these macros may also be used to suppress warnings related to
  653. ** parameters that may or may not be used depending on compilation options.
  654. ** For example those parameters only used in assert() statements. In these
  655. ** cases the parameters are named as per the usual conventions.
  656. */
  657. #define UNUSED_PARAMETER(x) (void)(x)
  658. #define UNUSED_PARAMETER2(x,y) UNUSED_PARAMETER(x),UNUSED_PARAMETER(y)
  659. /*
  660. ** Forward references to structures
  661. */
  662. typedef struct AggInfo AggInfo;
  663. typedef struct AuthContext AuthContext;
  664. typedef struct AutoincInfo AutoincInfo;
  665. typedef struct Bitvec Bitvec;
  666. typedef struct CollSeq CollSeq;
  667. typedef struct Column Column;
  668. typedef struct Db Db;
  669. typedef struct Schema Schema;
  670. typedef struct Expr Expr;
  671. typedef struct ExprList ExprList;
  672. typedef struct ExprSpan ExprSpan;
  673. typedef struct FKey FKey;
  674. typedef struct FuncDestructor FuncDestructor;
  675. typedef struct FuncDef FuncDef;
  676. typedef struct FuncDefHash FuncDefHash;
  677. typedef struct IdList IdList;
  678. typedef struct Index Index;
  679. typedef struct IndexSample IndexSample;
  680. typedef struct KeyClass KeyClass;
  681. typedef struct KeyInfo KeyInfo;
  682. typedef struct Lookaside Lookaside;
  683. typedef struct LookasideSlot LookasideSlot;
  684. typedef struct Module Module;
  685. typedef struct NameContext NameContext;
  686. typedef struct Parse Parse;
  687. typedef struct RowSet RowSet;
  688. typedef struct Savepoint Savepoint;
  689. typedef struct Select Select;
  690. typedef struct SelectDest SelectDest;
  691. typedef struct SrcList SrcList;
  692. typedef struct StrAccum StrAccum;
  693. typedef struct Table Table;
  694. typedef struct TableLock TableLock;
  695. typedef struct Token Token;
  696. typedef struct Trigger Trigger;
  697. typedef struct TriggerPrg TriggerPrg;
  698. typedef struct TriggerStep TriggerStep;
  699. typedef struct UnpackedRecord UnpackedRecord;
  700. typedef struct VTable VTable;
  701. typedef struct VtabCtx VtabCtx;
  702. typedef struct Walker Walker;
  703. typedef struct WhereInfo WhereInfo;
  704. /*
  705. ** Defer sourcing vdbe.h and btree.h until after the "u8" and
  706. ** "BusyHandler" typedefs. vdbe.h also requires a few of the opaque
  707. ** pointer types (i.e. FuncDef) defined above.
  708. */
  709. #include "btree.h"
  710. #include "vdbe.h"
  711. #include "pager.h"
  712. #include "pcache.h"
  713. #include "os.h"
  714. #include "mutex.h"
  715. /*
  716. ** Each database file to be accessed by the system is an instance
  717. ** of the following structure. There are normally two of these structures
  718. ** in the sqlite.aDb[] array. aDb[0] is the main database file and
  719. ** aDb[1] is the database file used to hold temporary tables. Additional
  720. ** databases may be attached.
  721. */
  722. struct Db {
  723. char *zName; /* Name of this database */
  724. Btree *pBt; /* The B*Tree structure for this database file */
  725. u8 safety_level; /* How aggressive at syncing data to disk */
  726. Schema *pSchema; /* Pointer to database schema (possibly shared) */
  727. };
  728. /*
  729. ** An instance of the following structure stores a database schema.
  730. **
  731. ** Most Schema objects are associated with a Btree. The exception is
  732. ** the Schema for the TEMP databaes (sqlite3.aDb[1]) which is free-standing.
  733. ** In shared cache mode, a single Schema object can be shared by multiple
  734. ** Btrees that refer to the same underlying BtShared object.
  735. **
  736. ** Schema objects are automatically deallocated when the last Btree that
  737. ** references them is destroyed. The TEMP Schema is manually freed by
  738. ** sqlite3_close().
  739. *
  740. ** A thread must be holding a mutex on the corresponding Btree in order
  741. ** to access Schema content. This implies that the thread must also be
  742. ** holding a mutex on the sqlite3 connection pointer that owns the Btree.
  743. ** For a TEMP Schema, only the connection mutex is required.
  744. */
  745. struct Schema {
  746. int schema_cookie; /* Database schema version number for this file */
  747. int iGeneration; /* Generation counter. Incremented with each change */
  748. Hash tblHash; /* All tables indexed by name */
  749. Hash idxHash; /* All (named) indices indexed by name */
  750. Hash trigHash; /* All triggers indexed by name */
  751. Hash fkeyHash; /* All foreign keys by referenced table name */
  752. Table *pSeqTab; /* The sqlite_sequence table used by AUTOINCREMENT */
  753. u8 file_format; /* Schema format version for this file */
  754. u8 enc; /* Text encoding used by this database */
  755. u16 flags; /* Flags associated with this schema */
  756. int cache_size; /* Number of pages to use in the cache */
  757. };
  758. /*
  759. ** These macros can be used to test, set, or clear bits in the
  760. ** Db.pSchema->flags field.
  761. */
  762. #define DbHasProperty(D,I,P) (((D)->aDb[I].pSchema->flags&(P))==(P))
  763. #define DbHasAnyProperty(D,I,P) (((D)->aDb[I].pSchema->flags&(P))!=0)
  764. #define DbSetProperty(D,I,P) (D)->aDb[I].pSchema->flags|=(P)
  765. #define DbClearProperty(D,I,P) (D)->aDb[I].pSchema->flags&=~(P)
  766. /*
  767. ** Allowed values for the DB.pSchema->flags field.
  768. **
  769. ** The DB_SchemaLoaded flag is set after the database schema has been
  770. ** read into internal hash tables.
  771. **
  772. ** DB_UnresetViews means that one or more views have column names that
  773. ** have been filled out. If the schema changes, these column names might
  774. ** changes and so the view will need to be reset.
  775. */
  776. #define DB_SchemaLoaded 0x0001 /* The schema has been loaded */
  777. #define DB_UnresetViews 0x0002 /* Some views have defined column names */
  778. #define DB_Empty 0x0004 /* The file is empty (length 0 bytes) */
  779. /*
  780. ** The number of different kinds of things that can be limited
  781. ** using the sqlite3_limit() interface.
  782. */
  783. #define SQLITE_N_LIMIT (SQLITE_LIMIT_TRIGGER_DEPTH+1)
  784. /*
  785. ** Lookaside malloc is a set of fixed-size buffers that can be used
  786. ** to satisfy small transient memory allocation requests for objects
  787. ** associated with a particular database connection. The use of
  788. ** lookaside malloc provides a significant performance enhancement
  789. ** (approx 10%) by avoiding numerous malloc/free requests while parsing
  790. ** SQL statements.
  791. **
  792. ** The Lookaside structure holds configuration information about the
  793. ** lookaside malloc subsystem. Each available memory allocation in
  794. ** the lookaside subsystem is stored on a linked list of LookasideSlot
  795. ** objects.
  796. **
  797. ** Lookaside allocations are only allowed for objects that are associated
  798. ** with a particular database connection. Hence, schema information cannot
  799. ** be stored in lookaside because in shared cache mode the schema information
  800. ** is shared by multiple database connections. Therefore, while parsing
  801. ** schema information, the Lookaside.bEnabled flag is cleared so that
  802. ** lookaside allocations are not used to construct the schema objects.
  803. */
  804. struct Lookaside {
  805. u16 sz; /* Size of each buffer in bytes */
  806. u8 bEnabled; /* False to disable new lookaside allocations */
  807. u8 bMalloced; /* True if pStart obtained from sqlite3_malloc() */
  808. int nOut; /* Number of buffers currently checked out */
  809. int mxOut; /* Highwater mark for nOut */
  810. int anStat[3]; /* 0: hits. 1: size misses. 2: full misses */
  811. LookasideSlot *pFree; /* List of available buffers */
  812. void *pStart; /* First byte of available memory space */
  813. void *pEnd; /* First byte past end of available space */
  814. };
  815. struct LookasideSlot {
  816. LookasideSlot *pNext; /* Next buffer in the list of free buffers */
  817. };
  818. /*
  819. ** A hash table for function definitions.
  820. **
  821. ** Hash each FuncDef structure into one of the FuncDefHash.a[] slots.
  822. ** Collisions are on the FuncDef.pHash chain.
  823. */
  824. struct FuncDefHash {
  825. FuncDef *a[23]; /* Hash table for functions */
  826. };
  827. /*
  828. ** Each database connection is an instance of the following structure.
  829. */
  830. struct sqlite3 {
  831. sqlite3_vfs *pVfs; /* OS Interface */
  832. struct Vdbe *pVdbe; /* List of active virtual machines */
  833. CollSeq *pDfltColl; /* The default collating sequence (BINARY) */
  834. sqlite3_mutex *mutex; /* Connection mutex */
  835. Db *aDb; /* All backends */
  836. int nDb; /* Number of backends currently in use */
  837. int flags; /* Miscellaneous flags. See below */
  838. i64 lastRowid; /* ROWID of most recent insert (see above) */
  839. i64 szMmap; /* Default mmap_size setting */
  840. unsigned int openFlags; /* Flags passed to sqlite3_vfs.xOpen() */
  841. int errCode; /* Most recent error code (SQLITE_*) */
  842. int errMask; /* & result codes with this before returning */
  843. u16 dbOptFlags; /* Flags to enable/disable optimizations */
  844. u8 autoCommit; /* The auto-commit flag. */
  845. u8 temp_store; /* 1: file 2: memory 0: default */
  846. u8 mallocFailed; /* True if we have seen a malloc failure */
  847. u8 dfltLockMode; /* Default locking-mode for attached dbs */
  848. signed char nextAutovac; /* Autovac setting after VACUUM if >=0 */
  849. u8 suppressErr; /* Do not issue error messages if true */
  850. u8 vtabOnConflict; /* Value to return for s3_vtab_on_conflict() */
  851. u8 isTransactionSavepoint; /* True if the outermost savepoint is a TS */
  852. int nextPagesize; /* Pagesize after VACUUM if >0 */
  853. u32 magic; /* Magic number for detect library misuse */
  854. int nChange; /* Value returned by sqlite3_changes() */
  855. int nTotalChange; /* Value returned by sqlite3_total_changes() */
  856. int aLimit[SQLITE_N_LIMIT]; /* Limits */
  857. struct sqlite3InitInfo { /* Information used during initialization */
  858. int newTnum; /* Rootpage of table being initialized */
  859. u8 iDb; /* Which db file is being initialized */
  860. u8 busy; /* TRUE if currently initializing */
  861. u8 orphanTrigger; /* Last statement is orphaned TEMP trigger */
  862. } init;
  863. int nVdbeActive; /* Number of VDBEs currently running */
  864. int nVdbeRead; /* Number of active VDBEs that read or write */
  865. int nVdbeWrite; /* Number of active VDBEs that read and write */
  866. int nVdbeExec; /* Number of nested calls to VdbeExec() */
  867. int nExtension; /* Number of loaded extensions */
  868. void **aExtension; /* Array of shared library handles */
  869. void (*xTrace)(void*,const char*); /* Trace function */
  870. void *pTraceArg; /* Argument to the trace function */
  871. void (*xProfile)(void*,const char*,u64); /* Profiling function */
  872. void *pProfileArg; /* Argument to profile function */
  873. void *pCommitArg; /* Argument to xCommitCallback() */
  874. int (*xCommitCallback)(void*); /* Invoked at every commit. */
  875. void *pRollbackArg; /* Argument to xRollbackCallback() */
  876. void (*xRollbackCallback)(void*); /* Invoked at every commit. */
  877. void *pUpdateArg;
  878. void (*xUpdateCallback)(void*,int, const char*,const char*,sqlite_int64);
  879. #ifndef SQLITE_OMIT_WAL
  880. int (*xWalCallback)(void *, sqlite3 *, const char *, int);
  881. void *pWalArg;
  882. #endif
  883. void(*xCollNeeded)(void*,sqlite3*,int eTextRep,const char*);
  884. void(*xCollNeeded16)(void*,sqlite3*,int eTextRep,const void*);
  885. void *pCollNeededArg;
  886. sqlite3_value *pErr; /* Most recent error message */
  887. union {
  888. volatile int isInterrupted; /* True if sqlite3_interrupt has been called */
  889. double notUsed1; /* Spacer */
  890. } u1;
  891. Lookaside lookaside; /* Lookaside malloc configuration */
  892. #ifndef SQLITE_OMIT_AUTHORIZATION
  893. int (*xAuth)(void*,int,const char*,const char*,const char*,const char*);
  894. /* Access authorization function */
  895. void *pAuthArg; /* 1st argument to the access auth function */
  896. #endif
  897. #ifndef SQLITE_OMIT_PROGRESS_CALLBACK
  898. int (*xProgress)(void *); /* The progress callback */
  899. void *pProgressArg; /* Argument to the progress callback */
  900. unsigned nProgressOps; /* Number of opcodes for progress callback */
  901. #endif
  902. #ifndef SQLITE_OMIT_VIRTUALTABLE
  903. int nVTrans; /* Allocated size of aVTrans */
  904. Hash aModule; /* populated by sqlite3_create_module() */
  905. VtabCtx *pVtabCtx; /* Context for active vtab connect/create */
  906. VTable **aVTrans; /* Virtual tables with open transactions */
  907. VTable *pDisconnect; /* Disconnect these in next sqlite3_prepare() */
  908. #endif
  909. FuncDefHash aFunc; /* Hash table of connection functions */
  910. Hash aCollSeq; /* All collating sequences */
  911. BusyHandler busyHandler; /* Busy callback */
  912. Db aDbStatic[2]; /* Static space for the 2 default backends */
  913. Savepoint *pSavepoint; /* List of active savepoints */
  914. int busyTimeout; /* Busy handler timeout, in msec */
  915. int nSavepoint; /* Number of non-transaction savepoints */
  916. int nStatement; /* Number of nested statement-transactions */
  917. i64 nDeferredCons; /* Net deferred constraints this transaction. */
  918. i64 nDeferredImmCons; /* Net deferred immediate constraints */
  919. int *pnBytesFreed; /* If not NULL, increment this in DbFree() */
  920. #ifdef SQLITE_ENABLE_UNLOCK_NOTIFY
  921. /* The following variables are all protected by the STATIC_MASTER
  922. ** mutex, not by sqlite3.mutex. They are used by code in notify.c.
  923. **
  924. ** When X.pUnlockConnection==Y, that means that X is waiting for Y to
  925. ** unlock so that it can proceed.
  926. **
  927. ** When X.pBlockingConnection==Y, that means that something that X tried
  928. ** tried to do recently failed with an SQLITE_LOCKED error due to locks
  929. ** held by Y.
  930. */
  931. sqlite3 *pBlockingConnection; /* Connection that caused SQLITE_LOCKED */
  932. sqlite3 *pUnlockConnection; /* Connection to watch for unlock */
  933. void *pUnlockArg; /* Argument to xUnlockNotify */
  934. void (*xUnlockNotify)(void **, int); /* Unlock notify callback */
  935. sqlite3 *pNextBlocked; /* Next in list of all blocked connections */
  936. #endif
  937. };
  938. /*
  939. ** A macro to discover the encoding of a database.
  940. */
  941. #define ENC(db) ((db)->aDb[0].pSchema->enc)
  942. /*
  943. ** Possible values for the sqlite3.flags.
  944. */
  945. #define SQLITE_VdbeTrace 0x00000001 /* True to trace VDBE execution */
  946. #define SQLITE_InternChanges 0x00000002 /* Uncommitted Hash table changes */
  947. #define SQLITE_FullFSync 0x00000004 /* Use full fsync on the backend */
  948. #define SQLITE_CkptFullFSync 0x00000008 /* Use full fsync for checkpoint */
  949. #define SQLITE_CacheSpill 0x00000010 /* OK to spill pager cache */
  950. #define SQLITE_FullColNames 0x00000020 /* Show full column names on SELECT */
  951. #define SQLITE_ShortColNames 0x00000040 /* Show short columns names */
  952. #define SQLITE_CountRows 0x00000080 /* Count rows changed by INSERT, */
  953. /* DELETE, or UPDATE and return */
  954. /* the count using a callback. */
  955. #define SQLITE_NullCallback 0x00000100 /* Invoke the callback once if the */
  956. /* result set is empty */
  957. #define SQLITE_SqlTrace 0x00000200 /* Debug print SQL as it executes */
  958. #define SQLITE_VdbeListing 0x00000400 /* Debug listings of VDBE programs */
  959. #define SQLITE_WriteSchema 0x00000800 /* OK to update SQLITE_MASTER */
  960. #define SQLITE_VdbeAddopTrace 0x00001000 /* Trace sqlite3VdbeAddOp() calls */
  961. #define SQLITE_IgnoreChecks 0x00002000 /* Do not enforce check constraints */
  962. #define SQLITE_ReadUncommitted 0x0004000 /* For shared-cache mode */
  963. #define SQLITE_LegacyFileFmt 0x00008000 /* Create new databases in format 1 */
  964. #define SQLITE_RecoveryMode 0x00010000 /* Ignore schema errors */
  965. #define SQLITE_ReverseOrder 0x00020000 /* Reverse unordered SELECTs */
  966. #define SQLITE_RecTriggers 0x00040000 /* Enable recursive triggers */
  967. #define SQLITE_ForeignKeys 0x00080000 /* Enforce foreign key constraints */
  968. #define SQLITE_AutoIndex 0x00100000 /* Enable automatic indexes */
  969. #define SQLITE_PreferBuiltin 0x00200000 /* Preference to built-in funcs */
  970. #define SQLITE_LoadExtension 0x00400000 /* Enable load_extension */
  971. #define SQLITE_EnableTrigger 0x00800000 /* True to enable triggers */
  972. #define SQLITE_DeferFKs 0x01000000 /* Defer all FK constraints */
  973. #define SQLITE_QueryOnly 0x02000000 /* Disable database changes */
  974. /*
  975. ** Bits of the sqlite3.dbOptFlags field that are used by the
  976. ** sqlite3_test_control(SQLITE_TESTCTRL_OPTIMIZATIONS,...) interface to
  977. ** selectively disable various optimizations.
  978. */
  979. #define SQLITE_QueryFlattener 0x0001 /* Query flattening */
  980. #define SQLITE_ColumnCache 0x0002 /* Column cache */
  981. #define SQLITE_GroupByOrder 0x0004 /* GROUPBY cover of ORDERBY */
  982. #define SQLITE_FactorOutConst 0x0008 /* Constant factoring */
  983. #define SQLITE_IdxRealAsInt 0x0010 /* Store REAL as INT in indices */
  984. #define SQLITE_DistinctOpt 0x0020 /* DISTINCT using indexes */
  985. #define SQLITE_CoverIdxScan 0x0040 /* Covering index scans */
  986. #define SQLITE_OrderByIdxJoin 0x0080 /* ORDER BY of joins via index */
  987. #define SQLITE_SubqCoroutine 0x0100 /* Evaluate subqueries as coroutines */
  988. #define SQLITE_Transitive 0x0200 /* Transitive constraints */
  989. #define SQLITE_OmitNoopJoin 0x0400 /* Omit unused tables in joins */
  990. #define SQLITE_Stat3 0x0800 /* Use the SQLITE_STAT3 table */
  991. #define SQLITE_AdjustOutEst 0x1000 /* Adjust output estimates using WHERE */
  992. #define SQLITE_AllOpts 0xffff /* All optimizations */
  993. /*
  994. ** Macros for testing whether or not optimizations are enabled or disabled.
  995. */
  996. #ifndef SQLITE_OMIT_BUILTIN_TEST
  997. #define OptimizationDisabled(db, mask) (((db)->dbOptFlags&(mask))!=0)
  998. #define OptimizationEnabled(db, mask) (((db)->dbOptFlags&(mask))==0)
  999. #else
  1000. #define OptimizationDisabled(db, mask) 0
  1001. #define OptimizationEnabled(db, mask) 1
  1002. #endif
  1003. /*
  1004. ** Possible values for the sqlite.magic field.
  1005. ** The numbers are obtained at random and have no special meaning, other
  1006. ** than being distinct from one another.
  1007. */
  1008. #define SQLITE_MAGIC_OPEN 0xa029a697 /* Database is open */
  1009. #define SQLITE_MAGIC_CLOSED 0x9f3c2d33 /* Database is closed */
  1010. #define SQLITE_MAGIC_SICK 0x4b771290 /* Error and awaiting close */
  1011. #define SQLITE_MAGIC_BUSY 0xf03b7906 /* Database currently in use */
  1012. #define SQLITE_MAGIC_ERROR 0xb5357930 /* An SQLITE_MISUSE error occurred */
  1013. #define SQLITE_MAGIC_ZOMBIE 0x64cffc7f /* Close with last statement close */
  1014. /*
  1015. ** Each SQL function is defined by an instance of the following
  1016. ** structure. A pointer to this structure is stored in the sqlite.aFunc
  1017. ** hash table. When multiple functions have the same name, the hash table
  1018. ** points to a linked list of these structures.
  1019. */
  1020. struct FuncDef {
  1021. i16 nArg; /* Number of arguments. -1 means unlimited */
  1022. u16 funcFlags; /* Some combination of SQLITE_FUNC_* */
  1023. void *pUserData; /* User data parameter */
  1024. FuncDef *pNext; /* Next function with same name */
  1025. void (*xFunc)(sqlite3_context*,int,sqlite3_value**); /* Regular function */
  1026. void (*xStep)(sqlite3_context*,int,sqlite3_value**); /* Aggregate step */
  1027. void (*xFinalize)(sqlite3_context*); /* Aggregate finalizer */
  1028. char *zName; /* SQL name of the function. */
  1029. FuncDef *pHash; /* Next with a different name but the same hash */
  1030. FuncDestructor *pDestructor; /* Reference counted destructor function */
  1031. };
  1032. /*
  1033. ** This structure encapsulates a user-function destructor callback (as
  1034. ** configured using create_function_v2()) and a reference counter. When
  1035. ** create_function_v2() is called to create a function with a destructor,
  1036. ** a single object of this type is allocated. FuncDestructor.nRef is set to
  1037. ** the number of FuncDef objects created (either 1 or 3, depending on whether
  1038. ** or not the specified encoding is SQLITE_ANY). The FuncDef.pDestructor
  1039. ** member of each of the new FuncDef objects is set to point to the allocated
  1040. ** FuncDestructor.
  1041. **
  1042. ** Thereafter, when one of the FuncDef objects is deleted, the reference
  1043. ** count on this object is decremented. When it reaches 0, the destructor
  1044. ** is invoked and the FuncDestructor structure freed.
  1045. */
  1046. struct FuncDestructor {
  1047. int nRef;
  1048. void (*xDestroy)(void *);
  1049. void *pUserData;
  1050. };
  1051. /*
  1052. ** Possible values for FuncDef.flags. Note that the _LENGTH and _TYPEOF
  1053. ** values must correspond to OPFLAG_LENGTHARG and OPFLAG_TYPEOFARG. There
  1054. ** are assert() statements in the code to verify this.
  1055. */
  1056. #define SQLITE_FUNC_ENCMASK 0x003 /* SQLITE_UTF8, SQLITE_UTF16BE or UTF16LE */
  1057. #define SQLITE_FUNC_LIKE 0x004 /* Candidate for the LIKE optimization */
  1058. #define SQLITE_FUNC_CASE 0x008 /* Case-sensitive LIKE-type function */
  1059. #define SQLITE_FUNC_EPHEM 0x010 /* Ephemeral. Delete with VDBE */
  1060. #define SQLITE_FUNC_NEEDCOLL 0x020 /* sqlite3GetFuncCollSeq() might be called */
  1061. #define SQLITE_FUNC_LENGTH 0x040 /* Built-in length() function */
  1062. #define SQLITE_FUNC_TYPEOF 0x080 /* Built-in typeof() function */
  1063. #define SQLITE_FUNC_COUNT 0x100 /* Built-in count(*) aggregate */
  1064. #define SQLITE_FUNC_COALESCE 0x200 /* Built-in coalesce() or ifnull() */
  1065. #define SQLITE_FUNC_UNLIKELY 0x400 /* Built-in unlikely() function */
  1066. /*
  1067. ** The following three macros, FUNCTION(), LIKEFUNC() and AGGREGATE() are
  1068. ** used to create the initializers for the FuncDef structures.
  1069. **
  1070. ** FUNCTION(zName, nArg, iArg, bNC, xFunc)
  1071. ** Used to create a scalar function definition of a function zName
  1072. ** implemented by C function xFunc that accepts nArg arguments. The
  1073. ** value passed as iArg is cast to a (void*) and made available
  1074. ** as the user-data (sqlite3_user_data()) for the function. If
  1075. ** argument bNC is true, then the SQLITE_FUNC_NEEDCOLL flag is set.
  1076. **
  1077. ** AGGREGATE(zName, nArg, iArg, bNC, xStep, xFinal)
  1078. ** Used to create an aggregate function definition implemented by
  1079. ** the C functions xStep and xFinal. The first four parameters
  1080. ** are interpreted in the same way as the first 4 parameters to
  1081. ** FUNCTION().
  1082. **
  1083. ** LIKEFUNC(zName, nArg, pArg, flags)
  1084. ** Used to create a scalar function definition of a function zName
  1085. ** that accepts nArg arguments and is implemented by a call to C
  1086. ** function likeFunc. Argument pArg is cast to a (void *) and made
  1087. ** available as the function user-data (sqlite3_user_data()). The
  1088. ** FuncDef.flags variable is set to the value passed as the flags
  1089. ** parameter.
  1090. */
  1091. #define FUNCTION(zName, nArg, iArg, bNC, xFunc) \
  1092. {nArg, SQLITE_UTF8|(bNC*SQLITE_FUNC_NEEDCOLL), \
  1093. SQLITE_INT_TO_PTR(iArg), 0, xFunc, 0, 0, #zName, 0, 0}
  1094. #define FUNCTION2(zName, nArg, iArg, bNC, xFunc, extraFlags) \
  1095. {nArg, SQLITE_UTF8|(bNC*SQLITE_FUNC_NEEDCOLL)|extraFlags, \
  1096. SQLITE_INT_TO_PTR(iArg), 0, xFunc, 0, 0, #zName, 0, 0}
  1097. #define STR_FUNCTION(zName, nArg, pArg, bNC, xFunc) \
  1098. {nArg, SQLITE_UTF8|(bNC*SQLITE_FUNC_NEEDCOLL), \
  1099. pArg, 0, xFunc, 0, 0, #zName, 0, 0}
  1100. #define LIKEFUNC(zName, nArg, arg, flags) \
  1101. {nArg, SQLITE_UTF8|flags, (void *)arg, 0, likeFunc, 0, 0, #zName, 0, 0}
  1102. #define AGGREGATE(zName, nArg, arg, nc, xStep, xFinal) \
  1103. {nArg, SQLITE_UTF8|(nc*SQLITE_FUNC_NEEDCOLL), \
  1104. SQLITE_INT_TO_PTR(arg), 0, 0, xStep,xFinal,#zName,0,0}
  1105. /*
  1106. ** All current savepoints are stored in a linked list starting at
  1107. ** sqlite3.pSavepoint. The first element in the list is the most recently
  1108. ** opened savepoint. Savepoints are added to the list by the vdbe
  1109. ** OP_Savepoint instruction.
  1110. */
  1111. struct Savepoint {
  1112. char *zName; /* Savepoint name (nul-terminated) */
  1113. i64 nDeferredCons; /* Number of deferred fk violations */
  1114. i64 nDeferredImmCons; /* Number of deferred imm fk. */
  1115. Savepoint *pNext; /* Parent savepoint (if any) */
  1116. };
  1117. /*
  1118. ** The following are used as the second parameter to sqlite3Savepoint(),
  1119. ** and as the P1 argument to the OP_Savepoint instruction.
  1120. */
  1121. #define SAVEPOINT_BEGIN 0
  1122. #define SAVEPOINT_RELEASE 1
  1123. #define SAVEPOINT_ROLLBACK 2
  1124. /*
  1125. ** Each SQLite module (virtual table definition) is defined by an
  1126. ** instance of the following structure, stored in the sqlite3.aModule
  1127. ** hash table.
  1128. */
  1129. struct Module {
  1130. const sqlite3_module *pModule; /* Callback pointers */
  1131. const char *zName; /* Name passed to create_module() */
  1132. void *pAux; /* pAux passed to create_module() */
  1133. void (*xDestroy)(void *); /* Module destructor function */
  1134. };
  1135. /*
  1136. ** information about each column of an SQL table is held in an instance
  1137. ** of this structure.
  1138. */
  1139. struct Column {
  1140. char *zName; /* Name of this column */
  1141. Expr *pDflt; /* Default value of this column */
  1142. char *zDflt; /* Original text of the default value */
  1143. char *zType; /* Data type for this column */
  1144. char *zColl; /* Collating sequence. If NULL, use the default */
  1145. u8 notNull; /* An OE_ code for handling a NOT NULL constraint */
  1146. char affinity; /* One of the SQLITE_AFF_... values */
  1147. u8 szEst; /* Estimated size of this column. INT==1 */
  1148. u8 colFlags; /* Boolean properties. See COLFLAG_ defines below */
  1149. };
  1150. /* Allowed values for Column.colFlags:
  1151. */
  1152. #define COLFLAG_PRIMKEY 0x0001 /* Column is part of the primary key */
  1153. #define COLFLAG_HIDDEN 0x0002 /* A hidden column in a virtual table */
  1154. /*
  1155. ** A "Collating Sequence" is defined by an instance of the following
  1156. ** structure. Conceptually, a collating sequence consists of a name and
  1157. ** a comparison routine that defines the order of that sequence.
  1158. **
  1159. ** If CollSeq.xCmp is NULL, it means that the
  1160. ** collating sequence is undefined. Indices built on an undefined
  1161. ** collating sequence may not be read or written.
  1162. */
  1163. struct CollSeq {
  1164. char *zName; /* Name of the collating sequence, UTF-8 encoded */
  1165. u8 enc; /* Text encoding handled by xCmp() */
  1166. void *pUser; /* First argument to xCmp() */
  1167. int (*xCmp)(void*,int, const void*, int, const void*);
  1168. void (*xDel)(void*); /* Destructor for pUser */
  1169. };
  1170. /*
  1171. ** A sort order can be either ASC or DESC.
  1172. */
  1173. #define SQLITE_SO_ASC 0 /* Sort in ascending order */
  1174. #define SQLITE_SO_DESC 1 /* Sort in ascending order */
  1175. /*
  1176. ** Column affinity types.
  1177. **
  1178. ** These used to have mnemonic name like 'i' for SQLITE_AFF_INTEGER and
  1179. ** 't' for SQLITE_AFF_TEXT. But we can save a little space and improve
  1180. ** the speed a little by numbering the values consecutively.
  1181. **
  1182. ** But rather than start with 0 or 1, we begin with 'a'. That way,
  1183. ** when multiple affinity types are concatenated into a string and
  1184. ** used as the P4 operand, they will be more readable.
  1185. **
  1186. ** Note also that the numeric types are grouped together so that testing
  1187. ** for a numeric type is a single comparison.
  1188. */
  1189. #define SQLITE_AFF_TEXT 'a'
  1190. #define SQLITE_AFF_NONE 'b'
  1191. #define SQLITE_AFF_NUMERIC 'c'
  1192. #define SQLITE_AFF_INTEGER 'd'
  1193. #define SQLITE_AFF_REAL 'e'
  1194. #define sqlite3IsNumericAffinity(X) ((X)>=SQLITE_AFF_NUMERIC)
  1195. /*
  1196. ** The SQLITE_AFF_MASK values masks off the significant bits of an
  1197. ** affinity value.
  1198. */
  1199. #define SQLITE_AFF_MASK 0x67
  1200. /*
  1201. ** Additional bit values that can be ORed with an affinity without
  1202. ** changing the affinity.
  1203. */
  1204. #define SQLITE_JUMPIFNULL 0x08 /* jumps if either operand is NULL */
  1205. #define SQLITE_STOREP2 0x10 /* Store result in reg[P2] rather than jump */
  1206. #define SQLITE_NULLEQ 0x80 /* NULL=NULL */
  1207. /*
  1208. ** An object of this type is created for each virtual table present in
  1209. ** the database schema.
  1210. **
  1211. ** If the database schema is shared, then there is one instance of this
  1212. ** structure for each database connection (sqlite3*) that uses the shared
  1213. ** schema. This is because each database connection requires its own unique
  1214. ** instance of the sqlite3_vtab* handle used to access the virtual table
  1215. ** implementation. sqlite3_vtab* handles can not be shared between
  1216. ** database connections, even when the rest of the in-memory database
  1217. ** schema is shared, as the implementation often stores the database
  1218. ** connection handle passed to it via the xConnect() or xCreate() method
  1219. ** during initialization internally. This database connection handle may
  1220. ** then be used by the virtual table implementation to access real tables
  1221. ** within the database. So that they appear as part of the callers
  1222. ** transaction, these accesses need to be made via the same database
  1223. ** connection as that used to execute SQL operations on the virtual table.
  1224. **
  1225. ** All VTable objects that correspond to a single table in a shared
  1226. ** database schema are initially stored in a linked-list pointed to by
  1227. ** the Table.pVTable member variable of the corresponding Table object.
  1228. ** When an sqlite3_prepare() operation is required to access the virtual
  1229. ** table, it searches the list for the VTable that corresponds to the
  1230. ** database connection doing the preparing so as to use the correct
  1231. ** sqlite3_vtab* handle in the compiled query.
  1232. **
  1233. ** When an in-memory Table object is deleted (for example when the
  1234. ** schema is being reloaded for some reason), the VTable objects are not
  1235. ** deleted and the sqlite3_vtab* handles are not xDisconnect()ed
  1236. ** immediately. Instead, they are moved from the Table.pVTable list to
  1237. ** another linked list headed by the sqlite3.pDisconnect member of the
  1238. ** corresponding sqlite3 structure. They are then deleted/xDisconnected
  1239. ** next time a statement is prepared using said sqlite3*. This is done
  1240. ** to avoid deadlock issues involving multiple sqlite3.mutex mutexes.
  1241. ** Refer to comments above function sqlite3VtabUnlockList() for an
  1242. ** explanation as to why it is safe to add an entry to an sqlite3.pDisconnect
  1243. ** list without holding the corresponding sqlite3.mutex mutex.
  1244. **
  1245. ** The memory for objects of this type is always allocated by
  1246. ** sqlite3DbMalloc(), using the connection handle stored in VTable.db as
  1247. ** the first argument.
  1248. */
  1249. struct VTable {
  1250. sqlite3 *db; /* Database connection associated with this table */
  1251. Module *pMod; /* Pointer to module implementation */
  1252. sqlite3_vtab *pVtab; /* Pointer to vtab instance */
  1253. int nRef; /* Number of pointers to this structure */
  1254. u8 bConstraint; /* True if constraints are supported */
  1255. int iSavepoint; /* Depth of the SAVEPOINT stack */
  1256. VTable *pNext; /* Next in linked list (see above) */
  1257. };
  1258. /*
  1259. ** Each SQL table is represented in memory by an instance of the
  1260. ** following structure.
  1261. **
  1262. ** Table.zName is the name of the table. The case of the original
  1263. ** CREATE TABLE statement is stored, but case is not significant for
  1264. ** comparisons.
  1265. **
  1266. ** Table.nCol is the number of columns in this table. Table.aCol is a
  1267. ** pointer to an array of Column structures, one for each column.
  1268. **
  1269. ** If the table has an INTEGER PRIMARY KEY, then Table.iPKey is the index of
  1270. ** the column that is that key. Otherwise Table.iPKey is negative. Note
  1271. ** that the datatype of the PRIMARY KEY must be INTEGER for this field to
  1272. ** be set. An INTEGER PRIMARY KEY is used as the rowid for each row of
  1273. ** the table. If a table has no INTEGER PRIMARY KEY, then a random rowid
  1274. ** is generated for each row of the table. TF_HasPrimaryKey is set if
  1275. ** the table has any PRIMARY KEY, INTEGER or otherwise.
  1276. **
  1277. ** Table.tnum is the page number for the root BTree page of the table in the
  1278. ** database file. If Table.iDb is the index of the database table backend
  1279. ** in sqlite.aDb[]. 0 is for the main database and 1 is for the file that
  1280. ** holds temporary tables and indices. If TF_Ephemeral is set
  1281. ** then the table is stored in a file that is automatically deleted
  1282. ** when the VDBE cursor to the table is closed. In this case Table.tnum
  1283. ** refers VDBE cursor number that holds the table open, not to the root
  1284. ** page number. Transient tables are used to hold the results of a
  1285. ** sub-query that appears instead of a real table name in the FROM clause
  1286. ** of a SELECT statement.
  1287. */
  1288. struct Table {
  1289. char *zName; /* Name of the table or view */
  1290. Column *aCol; /* Information about each column */
  1291. Index *pIndex; /* List of SQL indexes on this table. */
  1292. Select *pSelect; /* NULL for tables. Points to definition if a view. */
  1293. FKey *pFKey; /* Linked list of all foreign keys in this table */
  1294. char *zColAff; /* String defining the affinity of each column */
  1295. #ifndef SQLITE_OMIT_CHECK
  1296. ExprList *pCheck; /* All CHECK constraints */
  1297. #endif
  1298. tRowcnt nRowEst; /* Estimated rows in table - from sqlite_stat1 table */
  1299. int tnum; /* Root BTree node for this table (see note above) */
  1300. i16 iPKey; /* If not negative, use aCol[iPKey] as the primary key */
  1301. i16 nCol; /* Number of columns in this table */
  1302. u16 nRef; /* Number of pointers to this Table */
  1303. LogEst szTabRow; /* Estimated size of each table row in bytes */
  1304. u8 tabFlags; /* Mask of TF_* values */
  1305. u8 keyConf; /* What to do in case of uniqueness conflict on iPKey */
  1306. #ifndef SQLITE_OMIT_ALTERTABLE
  1307. int addColOffset; /* Offset in CREATE TABLE stmt to add a new column */
  1308. #endif
  1309. #ifndef SQLITE_OMIT_VIRTUALTABLE
  1310. int nModuleArg; /* Number of arguments to the module */
  1311. char **azModuleArg; /* Text of all module args. [0] is module name */
  1312. VTable *pVTable; /* List of VTable objects. */
  1313. #endif
  1314. Trigger *pTrigger; /* List of triggers stored in pSchema */
  1315. Schema *pSchema; /* Schema that contains this table */
  1316. Table *pNextZombie; /* Next on the Parse.pZombieTab list */
  1317. };
  1318. /*
  1319. ** Allowed values for Tabe.tabFlags.
  1320. */
  1321. #define TF_Readonly 0x01 /* Read-only system table */
  1322. #define TF_Ephemeral 0x02 /* An ephemeral table */
  1323. #define TF_HasPrimaryKey 0x04 /* Table has a primary key */
  1324. #define TF_Autoincrement 0x08 /* Integer primary key is autoincrement */
  1325. #define TF_Virtual 0x10 /* Is a virtual table */
  1326. /*
  1327. ** Test to see whether or not a table is a virtual table. This is
  1328. ** done as a macro so that it will be optimized out when virtual
  1329. ** table support is omitted from the build.
  1330. */
  1331. #ifndef SQLITE_OMIT_VIRTUALTABLE
  1332. # define IsVirtual(X) (((X)->tabFlags & TF_Virtual)!=0)
  1333. # define IsHiddenColumn(X) (((X)->colFlags & COLFLAG_HIDDEN)!=0)
  1334. #else
  1335. # define IsVirtual(X) 0
  1336. # define IsHiddenColumn(X) 0
  1337. #endif
  1338. /*
  1339. ** Each foreign key constraint is an instance of the following structure.
  1340. **
  1341. ** A foreign key is associated with two tables. The "from" table is
  1342. ** the table that contains the REFERENCES clause that creates the foreign
  1343. ** key. The "to" table is the table that is named in the REFERENCES clause.
  1344. ** Consider this example:
  1345. **
  1346. ** CREATE TABLE ex1(
  1347. ** a INTEGER PRIMARY KEY,
  1348. ** b INTEGER CONSTRAINT fk1 REFERENCES ex2(x)
  1349. ** );
  1350. **
  1351. ** For foreign key "fk1", the from-table is "ex1" and the to-table is "ex2".
  1352. **
  1353. ** Each REFERENCES clause generates an instance of the following structure
  1354. ** which is attached to the from-table. The to-table need not exist when
  1355. ** the from-table is created. The existence of the to-table is not checked.
  1356. */
  1357. struct FKey {
  1358. Table *pFrom; /* Table containing the REFERENCES clause (aka: Child) */
  1359. FKey *pNextFrom; /* Next foreign key in pFrom */
  1360. char *zTo; /* Name of table that the key points to (aka: Parent) */
  1361. FKey *pNextTo; /* Next foreign key on table named zTo */
  1362. FKey *pPrevTo; /* Previous foreign key on table named zTo */
  1363. int nCol; /* Number of columns in this key */
  1364. /* EV: R-30323-21917 */
  1365. u8 isDeferred; /* True if constraint checking is deferred till COMMIT */
  1366. u8 aAction[2]; /* ON DELETE and ON UPDATE actions, respectively */
  1367. Trigger *apTrigger[2]; /* Triggers for aAction[] actions */
  1368. struct sColMap { /* Mapping of columns in pFrom to columns in zTo */
  1369. int iFrom; /* Index of column in pFrom */
  1370. char *zCol; /* Name of column in zTo. If 0 use PRIMARY KEY */
  1371. } aCol[1]; /* One entry for each of nCol column s */
  1372. };
  1373. /*
  1374. ** SQLite supports many different ways to resolve a constraint
  1375. ** error. ROLLBACK processing means that a constraint violation
  1376. ** causes the operation in process to fail and for the current transaction
  1377. ** to be rolled back. ABORT processing means the operation in process
  1378. ** fails and any prior changes from that one operation are backed out,
  1379. ** but the transaction is not rolled back. FAIL processing means that
  1380. ** the operation in progress stops and returns an error code. But prior
  1381. ** changes due to the same operation are not backed out and no rollback
  1382. ** occurs. IGNORE means that the particular row that caused the constraint
  1383. ** error is not inserted or updated. Processing continues and no error
  1384. ** is returned. REPLACE means that preexisting database rows that caused
  1385. ** a UNIQUE constraint violation are removed so that the new insert or
  1386. ** update can proceed. Processing continues and no error is reported.
  1387. **
  1388. ** RESTRICT, SETNULL, and CASCADE actions apply only to foreign keys.
  1389. ** RESTRICT is the same as ABORT for IMMEDIATE foreign keys and the
  1390. ** same as ROLLBACK for DEFERRED keys. SETNULL means that the foreign
  1391. ** key is set to NULL. CASCADE means that a DELETE or UPDATE of the
  1392. ** referenced table row is propagated into the row that holds the
  1393. ** foreign key.
  1394. **
  1395. ** The following symbolic values are used to record which type
  1396. ** of action to take.
  1397. */
  1398. #define OE_None 0 /* There is no constraint to check */
  1399. #define OE_Rollback 1 /* Fail the operation and rollback the transaction */
  1400. #define OE_Abort 2 /* Back out changes but do no rollback transaction */
  1401. #define OE_Fail 3 /* Stop the operation but leave all prior changes */
  1402. #define OE_Ignore 4 /* Ignore the error. Do not do the INSERT or UPDATE */
  1403. #define OE_Replace 5 /* Delete existing record, then do INSERT or UPDATE */
  1404. #define OE_Restrict 6 /* OE_Abort for IMMEDIATE, OE_Rollback for DEFERRED */
  1405. #define OE_SetNull 7 /* Set the foreign key value to NULL */
  1406. #define OE_SetDflt 8 /* Set the foreign key value to its default */
  1407. #define OE_Cascade 9 /* Cascade the changes */
  1408. #define OE_Default 10 /* Do whatever the default action is */
  1409. /*
  1410. ** An instance of the following structure is passed as the first
  1411. ** argument to sqlite3VdbeKeyCompare and is used to control the
  1412. ** comparison of the two index keys.
  1413. **
  1414. ** Note that aSortOrder[] and aColl[] have nField+1 slots. There
  1415. ** are nField slots for the columns of an index then one extra slot
  1416. ** for the rowid at the end.
  1417. */
  1418. struct KeyInfo {
  1419. sqlite3 *db; /* The database connection */
  1420. u8 enc; /* Text encoding - one of the SQLITE_UTF* values */
  1421. u16 nField; /* Maximum index for aColl[] and aSortOrder[] */
  1422. u8 *aSortOrder; /* Sort order for each column. */
  1423. CollSeq *aColl[1]; /* Collating sequence for each term of the key */
  1424. };
  1425. /*
  1426. ** An instance of the following structure holds information about a
  1427. ** single index record that has already been parsed out into individual
  1428. ** values.
  1429. **
  1430. ** A record is an object that contains one or more fields of data.
  1431. ** Records are used to store the content of a table row and to store
  1432. ** the key of an index. A blob encoding of a record is created by
  1433. ** the OP_MakeRecord opcode of the VDBE and is disassembled by the
  1434. ** OP_Column opcode.
  1435. **
  1436. ** This structure holds a record that has already been disassembled
  1437. ** into its constituent fields.
  1438. */
  1439. struct UnpackedRecord {
  1440. KeyInfo *pKeyInfo; /* Collation and sort-order information */
  1441. u16 nField; /* Number of entries in apMem[] */
  1442. u8 flags; /* Boolean settings. UNPACKED_... below */
  1443. i64 rowid; /* Used by UNPACKED_PREFIX_SEARCH */
  1444. Mem *aMem; /* Values */
  1445. };
  1446. /*
  1447. ** Allowed values of UnpackedRecord.flags
  1448. */
  1449. #define UNPACKED_INCRKEY 0x01 /* Make this key an epsilon larger */
  1450. #define UNPACKED_PREFIX_MATCH 0x02 /* A prefix match is considered OK */
  1451. #define UNPACKED_PREFIX_SEARCH 0x04 /* Ignore final (rowid) field */
  1452. /*
  1453. ** Each SQL index is represented in memory by an
  1454. ** instance of the following structure.
  1455. **
  1456. ** The columns of the table that are to be indexed are described
  1457. ** by the aiColumn[] field of this structure. For example, suppose
  1458. ** we have the following table and index:
  1459. **
  1460. ** CREATE TABLE Ex1(c1 int, c2 int, c3 text);
  1461. ** CREATE INDEX Ex2 ON Ex1(c3,c1);
  1462. **
  1463. ** In the Table structure describing Ex1, nCol==3 because there are
  1464. ** three columns in the table. In the Index structure describing
  1465. ** Ex2, nColumn==2 since 2 of the 3 columns of Ex1 are indexed.
  1466. ** The value of aiColumn is {2, 0}. aiColumn[0]==2 because the
  1467. ** first column to be indexed (c3) has an index of 2 in Ex1.aCol[].
  1468. ** The second column to be indexed (c1) has an index of 0 in
  1469. ** Ex1.aCol[], hence Ex2.aiColumn[1]==0.
  1470. **
  1471. ** The Index.onError field determines whether or not the indexed columns
  1472. ** must be unique and what to do if they are not. When Index.onError=OE_None,
  1473. ** it means this is not a unique index. Otherwise it is a unique index
  1474. ** and the value of Index.onError indicate the which conflict resolution
  1475. ** algorithm to employ whenever an attempt is made to insert a non-unique
  1476. ** element.
  1477. */
  1478. struct Index {
  1479. char *zName; /* Name of this index */
  1480. int *aiColumn; /* Which columns are used by this index. 1st is 0 */
  1481. tRowcnt *aiRowEst; /* From ANALYZE: Est. rows selected by each column */
  1482. Table *pTable; /* The SQL table being indexed */
  1483. char *zColAff; /* String defining the affinity of each column */
  1484. Index *pNext; /* The next index associated with the same table */
  1485. Schema *pSchema; /* Schema containing this index */
  1486. u8 *aSortOrder; /* for each column: True==DESC, False==ASC */
  1487. char **azColl; /* Array of collation sequence names for index */
  1488. Expr *pPartIdxWhere; /* WHERE clause for partial indices */
  1489. int tnum; /* DB Page containing root of this index */
  1490. LogEst szIdxRow; /* Estimated average row size in bytes */
  1491. u16 nColumn; /* Number of columns in table used by this index */
  1492. u8 onError; /* OE_Abort, OE_Ignore, OE_Replace, or OE_None */
  1493. unsigned autoIndex:2; /* 1==UNIQUE, 2==PRIMARY KEY, 0==CREATE INDEX */
  1494. unsigned bUnordered:1; /* Use this index for == or IN queries only */
  1495. unsigned uniqNotNull:1; /* True if UNIQUE and NOT NULL for all columns */
  1496. #ifdef SQLITE_ENABLE_STAT3_OR_STAT4
  1497. int nSample; /* Number of elements in aSample[] */
  1498. int nSampleCol; /* Size of IndexSample.anEq[] and so on */
  1499. tRowcnt *aAvgEq; /* Average nEq values for keys not in aSample */
  1500. IndexSample *aSample; /* Samples of the left-most key */
  1501. #endif
  1502. };
  1503. /*
  1504. ** Each sample stored in the sqlite_stat3 table is represented in memory
  1505. ** using a structure of this type. See documentation at the top of the
  1506. ** analyze.c source file for additional information.
  1507. */
  1508. struct IndexSample {
  1509. void *p; /* Pointer to sampled record */
  1510. int n; /* Size of record in bytes */
  1511. tRowcnt *anEq; /* Est. number of rows where the key equals this sample */
  1512. tRowcnt *anLt; /* Est. number of rows where key is less than this sample */
  1513. tRowcnt *anDLt; /* Est. number of distinct keys less than this sample */
  1514. };
  1515. /*
  1516. ** Each token coming out of the lexer is an instance of
  1517. ** this structure. Tokens are also used as part of an expression.
  1518. **
  1519. ** Note if Token.z==0 then Token.dyn and Token.n are undefined and
  1520. ** may contain random values. Do not make any assumptions about Token.dyn
  1521. ** and Token.n when Token.z==0.
  1522. */
  1523. struct Token {
  1524. const char *z; /* Text of the token. Not NULL-terminated! */
  1525. unsigned int n; /* Number of characters in this token */
  1526. };
  1527. /*
  1528. ** An instance of this structure contains information needed to generate
  1529. ** code for a SELECT that contains aggregate functions.
  1530. **
  1531. ** If Expr.op==TK_AGG_COLUMN or TK_AGG_FUNCTION then Expr.pAggInfo is a
  1532. ** pointer to this structure. The Expr.iColumn field is the index in
  1533. ** AggInfo.aCol[] or AggInfo.aFunc[] of information needed to generate
  1534. ** code for that node.
  1535. **
  1536. ** AggInfo.pGroupBy and AggInfo.aFunc.pExpr point to fields within the
  1537. ** original Select structure that describes the SELECT statement. These
  1538. ** fields do not need to be freed when deallocating the AggInfo structure.
  1539. */
  1540. struct AggInfo {
  1541. u8 directMode; /* Direct rendering mode means take data directly
  1542. ** from source tables rather than from accumulators */
  1543. u8 useSortingIdx; /* In direct mode, reference the sorting index rather
  1544. ** than the source table */
  1545. int sortingIdx; /* Cursor number of the sorting index */
  1546. int sortingIdxPTab; /* Cursor number of pseudo-table */
  1547. int nSortingColumn; /* Number of columns in the sorting index */
  1548. ExprList *pGroupBy; /* The group by clause */
  1549. struct AggInfo_col { /* For each column used in source tables */
  1550. Table *pTab; /* Source table */
  1551. int iTable; /* Cursor number of the source table */
  1552. int iColumn; /* Column number within the source table */
  1553. int iSorterColumn; /* Column number in the sorting index */
  1554. int iMem; /* Memory location that acts as accumulator */
  1555. Expr *pExpr; /* The original expression */
  1556. } *aCol;
  1557. int nColumn; /* Number of used entries in aCol[] */
  1558. int nAccumulator; /* Number of columns that show through to the output.
  1559. ** Additional columns are used only as parameters to
  1560. ** aggregate functions */
  1561. struct AggInfo_func { /* For each aggregate function */
  1562. Expr *pExpr; /* Expression encoding the function */
  1563. FuncDef *pFunc; /* The aggregate function implementation */
  1564. int iMem; /* Memory location that acts as accumulator */
  1565. int iDistinct; /* Ephemeral table used to enforce DISTINCT */
  1566. } *aFunc;
  1567. int nFunc; /* Number of entries in aFunc[] */
  1568. };
  1569. /*
  1570. ** The datatype ynVar is a signed integer, either 16-bit or 32-bit.
  1571. ** Usually it is 16-bits. But if SQLITE_MAX_VARIABLE_NUMBER is greater
  1572. ** than 32767 we have to make it 32-bit. 16-bit is preferred because
  1573. ** it uses less memory in the Expr object, which is a big memory user
  1574. ** in systems with lots of prepared statements. And few applications
  1575. ** need more than about 10 or 20 variables. But some extreme users want
  1576. ** to have prepared statements with over 32767 variables, and for them
  1577. ** the option is available (at compile-time).
  1578. */
  1579. #if SQLITE_MAX_VARIABLE_NUMBER<=32767
  1580. typedef i16 ynVar;
  1581. #else
  1582. typedef int ynVar;
  1583. #endif
  1584. /*
  1585. ** Each node of an expression in the parse tree is an instance
  1586. ** of this structure.
  1587. **
  1588. ** Expr.op is the opcode. The integer parser token codes are reused
  1589. ** as opcodes here. For example, the parser defines TK_GE to be an integer
  1590. ** code representing the ">=" operator. This same integer code is reused
  1591. ** to represent the greater-than-or-equal-to operator in the expression
  1592. ** tree.
  1593. **
  1594. ** If the expression is an SQL literal (TK_INTEGER, TK_FLOAT, TK_BLOB,
  1595. ** or TK_STRING), then Expr.token contains the text of the SQL literal. If
  1596. ** the expression is a variable (TK_VARIABLE), then Expr.token contains the
  1597. ** variable name. Finally, if the expression is an SQL function (TK_FUNCTION),
  1598. ** then Expr.token contains the name of the function.
  1599. **
  1600. ** Expr.pRight and Expr.pLeft are the left and right subexpressions of a
  1601. ** binary operator. Either or both may be NULL.
  1602. **
  1603. ** Expr.x.pList is a list of arguments if the expression is an SQL function,
  1604. ** a CASE expression or an IN expression of the form "<lhs> IN (<y>, <z>...)".
  1605. ** Expr.x.pSelect is used if the expression is a sub-select or an expression of
  1606. ** the form "<lhs> IN (SELECT ...)". If the EP_xIsSelect bit is set in the
  1607. ** Expr.flags mask, then Expr.x.pSelect is valid. Otherwise, Expr.x.pList is
  1608. ** valid.
  1609. **
  1610. ** An expression of the form ID or ID.ID refers to a column in a table.
  1611. ** For such expressions, Expr.op is set to TK_COLUMN and Expr.iTable is
  1612. ** the integer cursor number of a VDBE cursor pointing to that table and
  1613. ** Expr.iColumn is the column number for the specific column. If the
  1614. ** expression is used as a result in an aggregate SELECT, then the
  1615. ** value is also stored in the Expr.iAgg column in the aggregate so that
  1616. ** it can be accessed after all aggregates are computed.
  1617. **
  1618. ** If the expression is an unbound variable marker (a question mark
  1619. ** character '?' in the original SQL) then the Expr.iTable holds the index
  1620. ** number for that variable.
  1621. **
  1622. ** If the expression is a subquery then Expr.iColumn holds an integer
  1623. ** register number containing the result of the subquery. If the
  1624. ** subquery gives a constant result, then iTable is -1. If the subquery
  1625. ** gives a different answer at different times during statement processing
  1626. ** then iTable is the address of a subroutine that computes the subquery.
  1627. **
  1628. ** If the Expr is of type OP_Column, and the table it is selecting from
  1629. ** is a disk table or the "old.*" pseudo-table, then pTab points to the
  1630. ** corresponding table definition.
  1631. **
  1632. ** ALLOCATION NOTES:
  1633. **
  1634. ** Expr objects can use a lot of memory space in database schema. To
  1635. ** help reduce memory requirements, sometimes an Expr object will be
  1636. ** truncated. And to reduce the number of memory allocations, sometimes
  1637. ** two or more Expr objects will be stored in a single memory allocation,
  1638. ** together with Expr.zToken strings.
  1639. **
  1640. ** If the EP_Reduced and EP_TokenOnly flags are set when
  1641. ** an Expr object is truncated. When EP_Reduced is set, then all
  1642. ** the child Expr objects in the Expr.pLeft and Expr.pRight subtrees
  1643. ** are contained within the same memory allocation. Note, however, that
  1644. ** the subtrees in Expr.x.pList or Expr.x.pSelect are always separately
  1645. ** allocated, regardless of whether or not EP_Reduced is set.
  1646. */
  1647. struct Expr {
  1648. u8 op; /* Operation performed by this node */
  1649. char affinity; /* The affinity of the column or 0 if not a column */
  1650. u32 flags; /* Various flags. EP_* See below */
  1651. union {
  1652. char *zToken; /* Token value. Zero terminated and dequoted */
  1653. int iValue; /* Non-negative integer value if EP_IntValue */
  1654. } u;
  1655. /* If the EP_TokenOnly flag is set in the Expr.flags mask, then no
  1656. ** space is allocated for the fields below this point. An attempt to
  1657. ** access them will result in a segfault or malfunction.
  1658. *********************************************************************/
  1659. Expr *pLeft; /* Left subnode */
  1660. Expr *pRight; /* Right subnode */
  1661. union {
  1662. ExprList *pList; /* op = IN, EXISTS, SELECT, CASE, FUNCTION, BETWEEN */
  1663. Select *pSelect; /* EP_xIsSelect and op = IN, EXISTS, SELECT */
  1664. } x;
  1665. /* If the EP_Reduced flag is set in the Expr.flags mask, then no
  1666. ** space is allocated for the fields below this point. An attempt to
  1667. ** access them will result in a segfault or malfunction.
  1668. *********************************************************************/
  1669. #if SQLITE_MAX_EXPR_DEPTH>0
  1670. int nHeight; /* Height of the tree headed by this node */
  1671. #endif
  1672. int iTable; /* TK_COLUMN: cursor number of table holding column
  1673. ** TK_REGISTER: register number
  1674. ** TK_TRIGGER: 1 -> new, 0 -> old
  1675. ** EP_Unlikely: 1000 times likelihood */
  1676. ynVar iColumn; /* TK_COLUMN: column index. -1 for rowid.
  1677. ** TK_VARIABLE: variable number (always >= 1). */
  1678. i16 iAgg; /* Which entry in pAggInfo->aCol[] or ->aFunc[] */
  1679. i16 iRightJoinTable; /* If EP_FromJoin, the right table of the join */
  1680. u8 op2; /* TK_REGISTER: original value of Expr.op
  1681. ** TK_COLUMN: the value of p5 for OP_Column
  1682. ** TK_AGG_FUNCTION: nesting depth */
  1683. AggInfo *pAggInfo; /* Used by TK_AGG_COLUMN and TK_AGG_FUNCTION */
  1684. Table *pTab; /* Table for TK_COLUMN expressions. */
  1685. };
  1686. /*
  1687. ** The following are the meanings of bits in the Expr.flags field.
  1688. */
  1689. #define EP_FromJoin 0x000001 /* Originated in ON or USING clause of a join */
  1690. #define EP_Agg 0x000002 /* Contains one or more aggregate functions */
  1691. #define EP_Resolved 0x000004 /* IDs have been resolved to COLUMNs */
  1692. #define EP_Error 0x000008 /* Expression contains one or more errors */
  1693. #define EP_Distinct 0x000010 /* Aggregate function with DISTINCT keyword */
  1694. #define EP_VarSelect 0x000020 /* pSelect is correlated, not constant */
  1695. #define EP_DblQuoted 0x000040 /* token.z was originally in "..." */
  1696. #define EP_InfixFunc 0x000080 /* True for an infix function: LIKE, GLOB, etc */
  1697. #define EP_Collate 0x000100 /* Tree contains a TK_COLLATE opeartor */
  1698. #define EP_FixedDest 0x000200 /* Result needed in a specific register */
  1699. #define EP_IntValue 0x000400 /* Integer value contained in u.iValue */
  1700. #define EP_xIsSelect 0x000800 /* x.pSelect is valid (otherwise x.pList is) */
  1701. #define EP_Skip 0x001000 /* COLLATE, AS, or UNLIKELY */
  1702. #define EP_Reduced 0x002000 /* Expr struct EXPR_REDUCEDSIZE bytes only */
  1703. #define EP_TokenOnly 0x004000 /* Expr struct EXPR_TOKENONLYSIZE bytes only */
  1704. #define EP_Static 0x008000 /* Held in memory not obtained from malloc() */
  1705. #define EP_MemToken 0x010000 /* Need to sqlite3DbFree() Expr.zToken */
  1706. #define EP_NoReduce 0x020000 /* Cannot EXPRDUP_REDUCE this Expr */
  1707. #define EP_Unlikely 0x040000 /* unlikely() or likelihood() function */
  1708. /*
  1709. ** These macros can be used to test, set, or clear bits in the
  1710. ** Expr.flags field.
  1711. */
  1712. #define ExprHasProperty(E,P) (((E)->flags&(P))!=0)
  1713. #define ExprHasAllProperty(E,P) (((E)->flags&(P))==(P))
  1714. #define ExprSetProperty(E,P) (E)->flags|=(P)
  1715. #define ExprClearProperty(E,P) (E)->flags&=~(P)
  1716. /* The ExprSetVVAProperty() macro is used for Verification, Validation,
  1717. ** and Accreditation only. It works like ExprSetProperty() during VVA
  1718. ** processes but is a no-op for delivery.
  1719. */
  1720. #ifdef SQLITE_DEBUG
  1721. # define ExprSetVVAProperty(E,P) (E)->flags|=(P)
  1722. #else
  1723. # define ExprSetVVAProperty(E,P)
  1724. #endif
  1725. /*
  1726. ** Macros to determine the number of bytes required by a normal Expr
  1727. ** struct, an Expr struct with the EP_Reduced flag set in Expr.flags
  1728. ** and an Expr struct with the EP_TokenOnly flag set.
  1729. */
  1730. #define EXPR_FULLSIZE sizeof(Expr) /* Full size */
  1731. #define EXPR_REDUCEDSIZE offsetof(Expr,iTable) /* Common features */
  1732. #define EXPR_TOKENONLYSIZE offsetof(Expr,pLeft) /* Fewer features */
  1733. /*
  1734. ** Flags passed to the sqlite3ExprDup() function. See the header comment
  1735. ** above sqlite3ExprDup() for details.
  1736. */
  1737. #define EXPRDUP_REDUCE 0x0001 /* Used reduced-size Expr nodes */
  1738. /*
  1739. ** A list of expressions. Each expression may optionally have a
  1740. ** name. An expr/name combination can be used in several ways, such
  1741. ** as the list of "expr AS ID" fields following a "SELECT" or in the
  1742. ** list of "ID = expr" items in an UPDATE. A list of expressions can
  1743. ** also be used as the argument to a function, in which case the a.zName
  1744. ** field is not used.
  1745. **
  1746. ** By default the Expr.zSpan field holds a human-readable description of
  1747. ** the expression that is used in the generation of error messages and
  1748. ** column labels. In this case, Expr.zSpan is typically the text of a
  1749. ** column expression as it exists in a SELECT statement. However, if
  1750. ** the bSpanIsTab flag is set, then zSpan is overloaded to mean the name
  1751. ** of the result column in the form: DATABASE.TABLE.COLUMN. This later
  1752. ** form is used for name resolution with nested FROM clauses.
  1753. */
  1754. struct ExprList {
  1755. int nExpr; /* Number of expressions on the list */
  1756. int iECursor; /* VDBE Cursor associated with this ExprList */
  1757. struct ExprList_item { /* For each expression in the list */
  1758. Expr *pExpr; /* The list of expressions */
  1759. char *zName; /* Token associated with this expression */
  1760. char *zSpan; /* Original text of the expression */
  1761. u8 sortOrder; /* 1 for DESC or 0 for ASC */
  1762. unsigned done :1; /* A flag to indicate when processing is finished */
  1763. unsigned bSpanIsTab :1; /* zSpan holds DB.TABLE.COLUMN */
  1764. u16 iOrderByCol; /* For ORDER BY, column number in result set */
  1765. u16 iAlias; /* Index into Parse.aAlias[] for zName */
  1766. } *a; /* Alloc a power of two greater or equal to nExpr */
  1767. };
  1768. /*
  1769. ** An instance of this structure is used by the parser to record both
  1770. ** the parse tree for an expression and the span of input text for an
  1771. ** expression.
  1772. */
  1773. struct ExprSpan {
  1774. Expr *pExpr; /* The expression parse tree */
  1775. const char *zStart; /* First character of input text */
  1776. const char *zEnd; /* One character past the end of input text */
  1777. };
  1778. /*
  1779. ** An instance of this structure can hold a simple list of identifiers,
  1780. ** such as the list "a,b,c" in the following statements:
  1781. **
  1782. ** INSERT INTO t(a,b,c) VALUES ...;
  1783. ** CREATE INDEX idx ON t(a,b,c);
  1784. ** CREATE TRIGGER trig BEFORE UPDATE ON t(a,b,c) ...;
  1785. **
  1786. ** The IdList.a.idx field is used when the IdList represents the list of
  1787. ** column names after a table name in an INSERT statement. In the statement
  1788. **
  1789. ** INSERT INTO t(a,b,c) ...
  1790. **
  1791. ** If "a" is the k-th column of table "t", then IdList.a[0].idx==k.
  1792. */
  1793. struct IdList {
  1794. struct IdList_item {
  1795. char *zName; /* Name of the identifier */
  1796. int idx; /* Index in some Table.aCol[] of a column named zName */
  1797. } *a;
  1798. int nId; /* Number of identifiers on the list */
  1799. };
  1800. /*
  1801. ** The bitmask datatype defined below is used for various optimizations.
  1802. **
  1803. ** Changing this from a 64-bit to a 32-bit type limits the number of
  1804. ** tables in a join to 32 instead of 64. But it also reduces the size
  1805. ** of the library by 738 bytes on ix86.
  1806. */
  1807. typedef u64 Bitmask;
  1808. /*
  1809. ** The number of bits in a Bitmask. "BMS" means "BitMask Size".
  1810. */
  1811. #define BMS ((int)(sizeof(Bitmask)*8))
  1812. /*
  1813. ** A bit in a Bitmask
  1814. */
  1815. #define MASKBIT(n) (((Bitmask)1)<<(n))
  1816. /*
  1817. ** The following structure describes the FROM clause of a SELECT statement.
  1818. ** Each table or subquery in the FROM clause is a separate element of
  1819. ** the SrcList.a[] array.
  1820. **
  1821. ** With the addition of multiple database support, the following structure
  1822. ** can also be used to describe a particular table such as the table that
  1823. ** is modified by an INSERT, DELETE, or UPDATE statement. In standard SQL,
  1824. ** such a table must be a simple name: ID. But in SQLite, the table can
  1825. ** now be identified by a database name, a dot, then the table name: ID.ID.
  1826. **
  1827. ** The jointype starts out showing the join type between the current table
  1828. ** and the next table on the list. The parser builds the list this way.
  1829. ** But sqlite3SrcListShiftJoinType() later shifts the jointypes so that each
  1830. ** jointype expresses the join between the table and the previous table.
  1831. **
  1832. ** In the colUsed field, the high-order bit (bit 63) is set if the table
  1833. ** contains more than 63 columns and the 64-th or later column is used.
  1834. */
  1835. struct SrcList {
  1836. u8 nSrc; /* Number of tables or subqueries in the FROM clause */
  1837. u8 nAlloc; /* Number of entries allocated in a[] below */
  1838. struct SrcList_item {
  1839. Schema *pSchema; /* Schema to which this item is fixed */
  1840. char *zDatabase; /* Name of database holding this table */
  1841. char *zName; /* Name of the table */
  1842. char *zAlias; /* The "B" part of a "A AS B" phrase. zName is the "A" */
  1843. Table *pTab; /* An SQL table corresponding to zName */
  1844. Select *pSelect; /* A SELECT statement used in place of a table name */
  1845. int addrFillSub; /* Address of subroutine to manifest a subquery */
  1846. int regReturn; /* Register holding return address of addrFillSub */
  1847. u8 jointype; /* Type of join between this able and the previous */
  1848. unsigned notIndexed :1; /* True if there is a NOT INDEXED clause */
  1849. unsigned isCorrelated :1; /* True if sub-query is correlated */
  1850. unsigned viaCoroutine :1; /* Implemented as a co-routine */
  1851. #ifndef SQLITE_OMIT_EXPLAIN
  1852. u8 iSelectId; /* If pSelect!=0, the id of the sub-select in EQP */
  1853. #endif
  1854. int iCursor; /* The VDBE cursor number used to access this table */
  1855. Expr *pOn; /* The ON clause of a join */
  1856. IdList *pUsing; /* The USING clause of a join */
  1857. Bitmask colUsed; /* Bit N (1<<N) set if column N of pTab is used */
  1858. char *zIndex; /* Identifier from "INDEXED BY <zIndex>" clause */
  1859. Index *pIndex; /* Index structure corresponding to zIndex, if any */
  1860. } a[1]; /* One entry for each identifier on the list */
  1861. };
  1862. /*
  1863. ** Permitted values of the SrcList.a.jointype field
  1864. */
  1865. #define JT_INNER 0x0001 /* Any kind of inner or cross join */
  1866. #define JT_CROSS 0x0002 /* Explicit use of the CROSS keyword */
  1867. #define JT_NATURAL 0x0004 /* True for a "natural" join */
  1868. #define JT_LEFT 0x0008 /* Left outer join */
  1869. #define JT_RIGHT 0x0010 /* Right outer join */
  1870. #define JT_OUTER 0x0020 /* The "OUTER" keyword is present */
  1871. #define JT_ERROR 0x0040 /* unknown or unsupported join type */
  1872. /*
  1873. ** Flags appropriate for the wctrlFlags parameter of sqlite3WhereBegin()
  1874. ** and the WhereInfo.wctrlFlags member.
  1875. */
  1876. #define WHERE_ORDERBY_NORMAL 0x0000 /* No-op */
  1877. #define WHERE_ORDERBY_MIN 0x0001 /* ORDER BY processing for min() func */
  1878. #define WHERE_ORDERBY_MAX 0x0002 /* ORDER BY processing for max() func */
  1879. #define WHERE_ONEPASS_DESIRED 0x0004 /* Want to do one-pass UPDATE/DELETE */
  1880. #define WHERE_DUPLICATES_OK 0x0008 /* Ok to return a row more than once */
  1881. #define WHERE_OMIT_OPEN_CLOSE 0x0010 /* Table cursors are already open */
  1882. #define WHERE_FORCE_TABLE 0x0020 /* Do not use an index-only search */
  1883. #define WHERE_ONETABLE_ONLY 0x0040 /* Only code the 1st table in pTabList */
  1884. #define WHERE_AND_ONLY 0x0080 /* Don't use indices for OR terms */
  1885. #define WHERE_GROUPBY 0x0100 /* pOrderBy is really a GROUP BY */
  1886. #define WHERE_DISTINCTBY 0x0200 /* pOrderby is really a DISTINCT clause */
  1887. #define WHERE_WANT_DISTINCT 0x0400 /* All output needs to be distinct */
  1888. /* Allowed return values from sqlite3WhereIsDistinct()
  1889. */
  1890. #define WHERE_DISTINCT_NOOP 0 /* DISTINCT keyword not used */
  1891. #define WHERE_DISTINCT_UNIQUE 1 /* No duplicates */
  1892. #define WHERE_DISTINCT_ORDERED 2 /* All duplicates are adjacent */
  1893. #define WHERE_DISTINCT_UNORDERED 3 /* Duplicates are scattered */
  1894. /*
  1895. ** A NameContext defines a context in which to resolve table and column
  1896. ** names. The context consists of a list of tables (the pSrcList) field and
  1897. ** a list of named expression (pEList). The named expression list may
  1898. ** be NULL. The pSrc corresponds to the FROM clause of a SELECT or
  1899. ** to the table being operated on by INSERT, UPDATE, or DELETE. The
  1900. ** pEList corresponds to the result set of a SELECT and is NULL for
  1901. ** other statements.
  1902. **
  1903. ** NameContexts can be nested. When resolving names, the inner-most
  1904. ** context is searched first. If no match is found, the next outer
  1905. ** context is checked. If there is still no match, the next context
  1906. ** is checked. This process continues until either a match is found
  1907. ** or all contexts are check. When a match is found, the nRef member of
  1908. ** the context containing the match is incremented.
  1909. **
  1910. ** Each subquery gets a new NameContext. The pNext field points to the
  1911. ** NameContext in the parent query. Thus the process of scanning the
  1912. ** NameContext list corresponds to searching through successively outer
  1913. ** subqueries looking for a match.
  1914. */
  1915. struct NameContext {
  1916. Parse *pParse; /* The parser */
  1917. SrcList *pSrcList; /* One or more tables used to resolve names */
  1918. ExprList *pEList; /* Optional list of result-set columns */
  1919. AggInfo *pAggInfo; /* Information about aggregates at this level */
  1920. NameContext *pNext; /* Next outer name context. NULL for outermost */
  1921. int nRef; /* Number of names resolved by this context */
  1922. int nErr; /* Number of errors encountered while resolving names */
  1923. u8 ncFlags; /* Zero or more NC_* flags defined below */
  1924. };
  1925. /*
  1926. ** Allowed values for the NameContext, ncFlags field.
  1927. */
  1928. #define NC_AllowAgg 0x01 /* Aggregate functions are allowed here */
  1929. #define NC_HasAgg 0x02 /* One or more aggregate functions seen */
  1930. #define NC_IsCheck 0x04 /* True if resolving names in a CHECK constraint */
  1931. #define NC_InAggFunc 0x08 /* True if analyzing arguments to an agg func */
  1932. #define NC_PartIdx 0x10 /* True if resolving a partial index WHERE */
  1933. /*
  1934. ** An instance of the following structure contains all information
  1935. ** needed to generate code for a single SELECT statement.
  1936. **
  1937. ** nLimit is set to -1 if there is no LIMIT clause. nOffset is set to 0.
  1938. ** If there is a LIMIT clause, the parser sets nLimit to the value of the
  1939. ** limit and nOffset to the value of the offset (or 0 if there is not
  1940. ** offset). But later on, nLimit and nOffset become the memory locations
  1941. ** in the VDBE that record the limit and offset counters.
  1942. **
  1943. ** addrOpenEphm[] entries contain the address of OP_OpenEphemeral opcodes.
  1944. ** These addresses must be stored so that we can go back and fill in
  1945. ** the P4_KEYINFO and P2 parameters later. Neither the KeyInfo nor
  1946. ** the number of columns in P2 can be computed at the same time
  1947. ** as the OP_OpenEphm instruction is coded because not
  1948. ** enough information about the compound query is known at that point.
  1949. ** The KeyInfo for addrOpenTran[0] and [1] contains collating sequences
  1950. ** for the result set. The KeyInfo for addrOpenEphm[2] contains collating
  1951. ** sequences for the ORDER BY clause.
  1952. */
  1953. struct Select {
  1954. ExprList *pEList; /* The fields of the result */
  1955. u8 op; /* One of: TK_UNION TK_ALL TK_INTERSECT TK_EXCEPT */
  1956. u16 selFlags; /* Various SF_* values */
  1957. int iLimit, iOffset; /* Memory registers holding LIMIT & OFFSET counters */
  1958. int addrOpenEphm[3]; /* OP_OpenEphem opcodes related to this select */
  1959. u64 nSelectRow; /* Estimated number of result rows */
  1960. SrcList *pSrc; /* The FROM clause */
  1961. Expr *pWhere; /* The WHERE clause */
  1962. ExprList *pGroupBy; /* The GROUP BY clause */
  1963. Expr *pHaving; /* The HAVING clause */
  1964. ExprList *pOrderBy; /* The ORDER BY clause */
  1965. Select *pPrior; /* Prior select in a compound select statement */
  1966. Select *pNext; /* Next select to the left in a compound */
  1967. Select *pRightmost; /* Right-most select in a compound select statement */
  1968. Expr *pLimit; /* LIMIT expression. NULL means not used. */
  1969. Expr *pOffset; /* OFFSET expression. NULL means not used. */
  1970. };
  1971. /*
  1972. ** Allowed values for Select.selFlags. The "SF" prefix stands for
  1973. ** "Select Flag".
  1974. */
  1975. #define SF_Distinct 0x0001 /* Output should be DISTINCT */
  1976. #define SF_Resolved 0x0002 /* Identifiers have been resolved */
  1977. #define SF_Aggregate 0x0004 /* Contains aggregate functions */
  1978. #define SF_UsesEphemeral 0x0008 /* Uses the OpenEphemeral opcode */
  1979. #define SF_Expanded 0x0010 /* sqlite3SelectExpand() called on this */
  1980. #define SF_HasTypeInfo 0x0020 /* FROM subqueries have Table metadata */
  1981. #define SF_UseSorter 0x0040 /* Sort using a sorter */
  1982. #define SF_Values 0x0080 /* Synthesized from VALUES clause */
  1983. #define SF_Materialize 0x0100 /* Force materialization of views */
  1984. #define SF_NestedFrom 0x0200 /* Part of a parenthesized FROM clause */
  1985. #define SF_MaybeConvert 0x0400 /* Need convertCompoundSelectToSubquery() */
  1986. /*
  1987. ** The results of a select can be distributed in several ways. The
  1988. ** "SRT" prefix means "SELECT Result Type".
  1989. */
  1990. #define SRT_Union 1 /* Store result as keys in an index */
  1991. #define SRT_Except 2 /* Remove result from a UNION index */
  1992. #define SRT_Exists 3 /* Store 1 if the result is not empty */
  1993. #define SRT_Discard 4 /* Do not save the results anywhere */
  1994. /* The ORDER BY clause is ignored for all of the above */
  1995. #define IgnorableOrderby(X) ((X->eDest)<=SRT_Discard)
  1996. #define SRT_Output 5 /* Output each row of result */
  1997. #define SRT_Mem 6 /* Store result in a memory cell */
  1998. #define SRT_Set 7 /* Store results as keys in an index */
  1999. #define SRT_Table 8 /* Store result as data with an automatic rowid */
  2000. #define SRT_EphemTab 9 /* Create transient tab and store like SRT_Table */
  2001. #define SRT_Coroutine 10 /* Generate a single row of result */
  2002. /*
  2003. ** An instance of this object describes where to put of the results of
  2004. ** a SELECT statement.
  2005. */
  2006. struct SelectDest {
  2007. u8 eDest; /* How to dispose of the results. On of SRT_* above. */
  2008. char affSdst; /* Affinity used when eDest==SRT_Set */
  2009. int iSDParm; /* A parameter used by the eDest disposal method */
  2010. int iSdst; /* Base register where results are written */
  2011. int nSdst; /* Number of registers allocated */
  2012. };
  2013. /*
  2014. ** During code generation of statements that do inserts into AUTOINCREMENT
  2015. ** tables, the following information is attached to the Table.u.autoInc.p
  2016. ** pointer of each autoincrement table to record some side information that
  2017. ** the code generator needs. We have to keep per-table autoincrement
  2018. ** information in case inserts are down within triggers. Triggers do not
  2019. ** normally coordinate their activities, but we do need to coordinate the
  2020. ** loading and saving of autoincrement information.
  2021. */
  2022. struct AutoincInfo {
  2023. AutoincInfo *pNext; /* Next info block in a list of them all */
  2024. Table *pTab; /* Table this info block refers to */
  2025. int iDb; /* Index in sqlite3.aDb[] of database holding pTab */
  2026. int regCtr; /* Memory register holding the rowid counter */
  2027. };
  2028. /*
  2029. ** Size of the column cache
  2030. */
  2031. #ifndef SQLITE_N_COLCACHE
  2032. # define SQLITE_N_COLCACHE 10
  2033. #endif
  2034. /*
  2035. ** At least one instance of the following structure is created for each
  2036. ** trigger that may be fired while parsing an INSERT, UPDATE or DELETE
  2037. ** statement. All such objects are stored in the linked list headed at
  2038. ** Parse.pTriggerPrg and deleted once statement compilation has been
  2039. ** completed.
  2040. **
  2041. ** A Vdbe sub-program that implements the body and WHEN clause of trigger
  2042. ** TriggerPrg.pTrigger, assuming a default ON CONFLICT clause of
  2043. ** TriggerPrg.orconf, is stored in the TriggerPrg.pProgram variable.
  2044. ** The Parse.pTriggerPrg list never contains two entries with the same
  2045. ** values for both pTrigger and orconf.
  2046. **
  2047. ** The TriggerPrg.aColmask[0] variable is set to a mask of old.* columns
  2048. ** accessed (or set to 0 for triggers fired as a result of INSERT
  2049. ** statements). Similarly, the TriggerPrg.aColmask[1] variable is set to
  2050. ** a mask of new.* columns used by the program.
  2051. */
  2052. struct TriggerPrg {
  2053. Trigger *pTrigger; /* Trigger this program was coded from */
  2054. TriggerPrg *pNext; /* Next entry in Parse.pTriggerPrg list */
  2055. SubProgram *pProgram; /* Program implementing pTrigger/orconf */
  2056. int orconf; /* Default ON CONFLICT policy */
  2057. u32 aColmask[2]; /* Masks of old.*, new.* columns accessed */
  2058. };
  2059. /*
  2060. ** The yDbMask datatype for the bitmask of all attached databases.
  2061. */
  2062. #if SQLITE_MAX_ATTACHED>30
  2063. typedef sqlite3_uint64 yDbMask;
  2064. #else
  2065. typedef unsigned int yDbMask;
  2066. #endif
  2067. /*
  2068. ** An SQL parser context. A copy of this structure is passed through
  2069. ** the parser and down into all the parser action routine in order to
  2070. ** carry around information that is global to the entire parse.
  2071. **
  2072. ** The structure is divided into two parts. When the parser and code
  2073. ** generate call themselves recursively, the first part of the structure
  2074. ** is constant but the second part is reset at the beginning and end of
  2075. ** each recursion.
  2076. **
  2077. ** The nTableLock and aTableLock variables are only used if the shared-cache
  2078. ** feature is enabled (if sqlite3Tsd()->useSharedData is true). They are
  2079. ** used to store the set of table-locks required by the statement being
  2080. ** compiled. Function sqlite3TableLock() is used to add entries to the
  2081. ** list.
  2082. */
  2083. struct Parse {
  2084. sqlite3 *db; /* The main database structure */
  2085. char *zErrMsg; /* An error message */
  2086. Vdbe *pVdbe; /* An engine for executing database bytecode */
  2087. int rc; /* Return code from execution */
  2088. u8 colNamesSet; /* TRUE after OP_ColumnName has been issued to pVdbe */
  2089. u8 checkSchema; /* Causes schema cookie check after an error */
  2090. u8 nested; /* Number of nested calls to the parser/code generator */
  2091. u8 nTempReg; /* Number of temporary registers in aTempReg[] */
  2092. u8 nTempInUse; /* Number of aTempReg[] currently checked out */
  2093. u8 nColCache; /* Number of entries in aColCache[] */
  2094. u8 iColCache; /* Next entry in aColCache[] to replace */
  2095. u8 isMultiWrite; /* True if statement may modify/insert multiple rows */
  2096. u8 mayAbort; /* True if statement may throw an ABORT exception */
  2097. u8 hasCompound; /* Need to invoke convertCompoundSelectToSubquery() */
  2098. int aTempReg[8]; /* Holding area for temporary registers */
  2099. int nRangeReg; /* Size of the temporary register block */
  2100. int iRangeReg; /* First register in temporary register block */
  2101. int nErr; /* Number of errors seen */
  2102. int nTab; /* Number of previously allocated VDBE cursors */
  2103. int nMem; /* Number of memory cells used so far */
  2104. int nSet; /* Number of sets used so far */
  2105. int nOnce; /* Number of OP_Once instructions so far */
  2106. int ckBase; /* Base register of data during check constraints */
  2107. int iPartIdxTab; /* Table corresponding to a partial index */
  2108. int iCacheLevel; /* ColCache valid when aColCache[].iLevel<=iCacheLevel */
  2109. int iCacheCnt; /* Counter used to generate aColCache[].lru values */
  2110. struct yColCache {
  2111. int iTable; /* Table cursor number */
  2112. int iColumn; /* Table column number */
  2113. u8 tempReg; /* iReg is a temp register that needs to be freed */
  2114. int iLevel; /* Nesting level */
  2115. int iReg; /* Reg with value of this column. 0 means none. */
  2116. int lru; /* Least recently used entry has the smallest value */
  2117. } aColCache[SQLITE_N_COLCACHE]; /* One for each column cache entry */
  2118. yDbMask writeMask; /* Start a write transaction on these databases */
  2119. yDbMask cookieMask; /* Bitmask of schema verified databases */
  2120. int cookieGoto; /* Address of OP_Goto to cookie verifier subroutine */
  2121. int cookieValue[SQLITE_MAX_ATTACHED+2]; /* Values of cookies to verify */
  2122. int regRowid; /* Register holding rowid of CREATE TABLE entry */
  2123. int regRoot; /* Register holding root page number for new objects */
  2124. int nMaxArg; /* Max args passed to user function by sub-program */
  2125. Token constraintName;/* Name of the constraint currently being parsed */
  2126. #ifndef SQLITE_OMIT_SHARED_CACHE
  2127. int nTableLock; /* Number of locks in aTableLock */
  2128. TableLock *aTableLock; /* Required table locks for shared-cache mode */
  2129. #endif
  2130. AutoincInfo *pAinc; /* Information about AUTOINCREMENT counters */
  2131. /* Information used while coding trigger programs. */
  2132. Parse *pToplevel; /* Parse structure for main program (or NULL) */
  2133. Table *pTriggerTab; /* Table triggers are being coded for */
  2134. u32 nQueryLoop; /* Est number of iterations of a query (10*log2(N)) */
  2135. u32 oldmask; /* Mask of old.* columns referenced */
  2136. u32 newmask; /* Mask of new.* columns referenced */
  2137. u8 eTriggerOp; /* TK_UPDATE, TK_INSERT or TK_DELETE */
  2138. u8 eOrconf; /* Default ON CONFLICT policy for trigger steps */
  2139. u8 disableTriggers; /* True to disable triggers */
  2140. /* Above is constant between recursions. Below is reset before and after
  2141. ** each recursion */
  2142. int nVar; /* Number of '?' variables seen in the SQL so far */
  2143. int nzVar; /* Number of available slots in azVar[] */
  2144. u8 explain; /* True if the EXPLAIN flag is found on the query */
  2145. #ifndef SQLITE_OMIT_VIRTUALTABLE
  2146. u8 declareVtab; /* True if inside sqlite3_declare_vtab() */
  2147. int nVtabLock; /* Number of virtual tables to lock */
  2148. #endif
  2149. int nAlias; /* Number of aliased result set columns */
  2150. int nHeight; /* Expression tree height of current sub-select */
  2151. #ifndef SQLITE_OMIT_EXPLAIN
  2152. int iSelectId; /* ID of current select for EXPLAIN output */
  2153. int iNextSelectId; /* Next available select ID for EXPLAIN output */
  2154. #endif
  2155. char **azVar; /* Pointers to names of parameters */
  2156. Vdbe *pReprepare; /* VM being reprepared (sqlite3Reprepare()) */
  2157. int *aAlias; /* Register used to hold aliased result */
  2158. const char *zTail; /* All SQL text past the last semicolon parsed */
  2159. Table *pNewTable; /* A table being constructed by CREATE TABLE */
  2160. Trigger *pNewTrigger; /* Trigger under construct by a CREATE TRIGGER */
  2161. const char *zAuthContext; /* The 6th parameter to db->xAuth callbacks */
  2162. Token sNameToken; /* Token with unqualified schema object name */
  2163. Token sLastToken; /* The last token parsed */
  2164. #ifndef SQLITE_OMIT_VIRTUALTABLE
  2165. Token sArg; /* Complete text of a module argument */
  2166. Table **apVtabLock; /* Pointer to virtual tables needing locking */
  2167. #endif
  2168. Table *pZombieTab; /* List of Table objects to delete after code gen */
  2169. TriggerPrg *pTriggerPrg; /* Linked list of coded triggers */
  2170. };
  2171. /*
  2172. ** Return true if currently inside an sqlite3_declare_vtab() call.
  2173. */
  2174. #ifdef SQLITE_OMIT_VIRTUALTABLE
  2175. #define IN_DECLARE_VTAB 0
  2176. #else
  2177. #define IN_DECLARE_VTAB (pParse->declareVtab)
  2178. #endif
  2179. /*
  2180. ** An instance of the following structure can be declared on a stack and used
  2181. ** to save the Parse.zAuthContext value so that it can be restored later.
  2182. */
  2183. struct AuthContext {
  2184. const char *zAuthContext; /* Put saved Parse.zAuthContext here */
  2185. Parse *pParse; /* The Parse structure */
  2186. };
  2187. /*
  2188. ** Bitfield flags for P5 value in various opcodes.
  2189. */
  2190. #define OPFLAG_NCHANGE 0x01 /* Set to update db->nChange */
  2191. #define OPFLAG_LASTROWID 0x02 /* Set to update db->lastRowid */
  2192. #define OPFLAG_ISUPDATE 0x04 /* This OP_Insert is an sql UPDATE */
  2193. #define OPFLAG_APPEND 0x08 /* This is likely to be an append */
  2194. #define OPFLAG_USESEEKRESULT 0x10 /* Try to avoid a seek in BtreeInsert() */
  2195. #define OPFLAG_CLEARCACHE 0x20 /* Clear pseudo-table cache in OP_Column */
  2196. #define OPFLAG_LENGTHARG 0x40 /* OP_Column only used for length() */
  2197. #define OPFLAG_TYPEOFARG 0x80 /* OP_Column only used for typeof() */
  2198. #define OPFLAG_BULKCSR 0x01 /* OP_Open** used to open bulk cursor */
  2199. #define OPFLAG_P2ISREG 0x02 /* P2 to OP_Open** is a register number */
  2200. #define OPFLAG_PERMUTE 0x01 /* OP_Compare: use the permutation */
  2201. /*
  2202. * Each trigger present in the database schema is stored as an instance of
  2203. * struct Trigger.
  2204. *
  2205. * Pointers to instances of struct Trigger are stored in two ways.
  2206. * 1. In the "trigHash" hash table (part of the sqlite3* that represents the
  2207. * database). This allows Trigger structures to be retrieved by name.
  2208. * 2. All triggers associated with a single table form a linked list, using the
  2209. * pNext member of struct Trigger. A pointer to the first element of the
  2210. * linked list is stored as the "pTrigger" member of the associated
  2211. * struct Table.
  2212. *
  2213. * The "step_list" member points to the first element of a linked list
  2214. * containing the SQL statements specified as the trigger program.
  2215. */
  2216. struct Trigger {
  2217. char *zName; /* The name of the trigger */
  2218. char *table; /* The table or view to which the trigger applies */
  2219. u8 op; /* One of TK_DELETE, TK_UPDATE, TK_INSERT */
  2220. u8 tr_tm; /* One of TRIGGER_BEFORE, TRIGGER_AFTER */
  2221. Expr *pWhen; /* The WHEN clause of the expression (may be NULL) */
  2222. IdList *pColumns; /* If this is an UPDATE OF <column-list> trigger,
  2223. the <column-list> is stored here */
  2224. Schema *pSchema; /* Schema containing the trigger */
  2225. Schema *pTabSchema; /* Schema containing the table */
  2226. TriggerStep *step_list; /* Link list of trigger program steps */
  2227. Trigger *pNext; /* Next trigger associated with the table */
  2228. };
  2229. /*
  2230. ** A trigger is either a BEFORE or an AFTER trigger. The following constants
  2231. ** determine which.
  2232. **
  2233. ** If there are multiple triggers, you might of some BEFORE and some AFTER.
  2234. ** In that cases, the constants below can be ORed together.
  2235. */
  2236. #define TRIGGER_BEFORE 1
  2237. #define TRIGGER_AFTER 2
  2238. /*
  2239. * An instance of struct TriggerStep is used to store a single SQL statement
  2240. * that is a part of a trigger-program.
  2241. *
  2242. * Instances of struct TriggerStep are stored in a singly linked list (linked
  2243. * using the "pNext" member) referenced by the "step_list" member of the
  2244. * associated struct Trigger instance. The first element of the linked list is
  2245. * the first step of the trigger-program.
  2246. *
  2247. * The "op" member indicates whether this is a "DELETE", "INSERT", "UPDATE" or
  2248. * "SELECT" statement. The meanings of the other members is determined by the
  2249. * value of "op" as follows:
  2250. *
  2251. * (op == TK_INSERT)
  2252. * orconf -> stores the ON CONFLICT algorithm
  2253. * pSelect -> If this is an INSERT INTO ... SELECT ... statement, then
  2254. * this stores a pointer to the SELECT statement. Otherwise NULL.
  2255. * target -> A token holding the quoted name of the table to insert into.
  2256. * pExprList -> If this is an INSERT INTO ... VALUES ... statement, then
  2257. * this stores values to be inserted. Otherwise NULL.
  2258. * pIdList -> If this is an INSERT INTO ... (<column-names>) VALUES ...
  2259. * statement, then this stores the column-names to be
  2260. * inserted into.
  2261. *
  2262. * (op == TK_DELETE)
  2263. * target -> A token holding the quoted name of the table to delete from.
  2264. * pWhere -> The WHERE clause of the DELETE statement if one is specified.
  2265. * Otherwise NULL.
  2266. *
  2267. * (op == TK_UPDATE)
  2268. * target -> A token holding the quoted name of the table to update rows of.
  2269. * pWhere -> The WHERE clause of the UPDATE statement if one is specified.
  2270. * Otherwise NULL.
  2271. * pExprList -> A list of the columns to update and the expressions to update
  2272. * them to. See sqlite3Update() documentation of "pChanges"
  2273. * argument.
  2274. *
  2275. */
  2276. struct TriggerStep {
  2277. u8 op; /* One of TK_DELETE, TK_UPDATE, TK_INSERT, TK_SELECT */
  2278. u8 orconf; /* OE_Rollback etc. */
  2279. Trigger *pTrig; /* The trigger that this step is a part of */
  2280. Select *pSelect; /* SELECT statment or RHS of INSERT INTO .. SELECT ... */
  2281. Token target; /* Target table for DELETE, UPDATE, INSERT */
  2282. Expr *pWhere; /* The WHERE clause for DELETE or UPDATE steps */
  2283. ExprList *pExprList; /* SET clause for UPDATE. VALUES clause for INSERT */
  2284. IdList *pIdList; /* Column names for INSERT */
  2285. TriggerStep *pNext; /* Next in the link-list */
  2286. TriggerStep *pLast; /* Last element in link-list. Valid for 1st elem only */
  2287. };
  2288. /*
  2289. ** The following structure contains information used by the sqliteFix...
  2290. ** routines as they walk the parse tree to make database references
  2291. ** explicit.
  2292. */
  2293. typedef struct DbFixer DbFixer;
  2294. struct DbFixer {
  2295. Parse *pParse; /* The parsing context. Error messages written here */
  2296. Schema *pSchema; /* Fix items to this schema */
  2297. int bVarOnly; /* Check for variable references only */
  2298. const char *zDb; /* Make sure all objects are contained in this database */
  2299. const char *zType; /* Type of the container - used for error messages */
  2300. const Token *pName; /* Name of the container - used for error messages */
  2301. };
  2302. /*
  2303. ** An objected used to accumulate the text of a string where we
  2304. ** do not necessarily know how big the string will be in the end.
  2305. */
  2306. struct StrAccum {
  2307. sqlite3 *db; /* Optional database for lookaside. Can be NULL */
  2308. char *zBase; /* A base allocation. Not from malloc. */
  2309. char *zText; /* The string collected so far */
  2310. int nChar; /* Length of the string so far */
  2311. int nAlloc; /* Amount of space allocated in zText */
  2312. int mxAlloc; /* Maximum allowed string length */
  2313. u8 useMalloc; /* 0: none, 1: sqlite3DbMalloc, 2: sqlite3_malloc */
  2314. u8 accError; /* STRACCUM_NOMEM or STRACCUM_TOOBIG */
  2315. };
  2316. #define STRACCUM_NOMEM 1
  2317. #define STRACCUM_TOOBIG 2
  2318. /*
  2319. ** A pointer to this structure is used to communicate information
  2320. ** from sqlite3Init and OP_ParseSchema into the sqlite3InitCallback.
  2321. */
  2322. typedef struct {
  2323. sqlite3 *db; /* The database being initialized */
  2324. char **pzErrMsg; /* Error message stored here */
  2325. int iDb; /* 0 for main database. 1 for TEMP, 2.. for ATTACHed */
  2326. int rc; /* Result code stored here */
  2327. } InitData;
  2328. /*
  2329. ** Structure containing global configuration data for the SQLite library.
  2330. **
  2331. ** This structure also contains some state information.
  2332. */
  2333. struct Sqlite3Config {
  2334. int bMemstat; /* True to enable memory status */
  2335. int bCoreMutex; /* True to enable core mutexing */
  2336. int bFullMutex; /* True to enable full mutexing */
  2337. int bOpenUri; /* True to interpret filenames as URIs */
  2338. int bUseCis; /* Use covering indices for full-scans */
  2339. int mxStrlen; /* Maximum string length */
  2340. int szLookaside; /* Default lookaside buffer size */
  2341. int nLookaside; /* Default lookaside buffer count */
  2342. sqlite3_mem_methods m; /* Low-level memory allocation interface */
  2343. sqlite3_mutex_methods mutex; /* Low-level mutex interface */
  2344. sqlite3_pcache_methods2 pcache2; /* Low-level page-cache interface */
  2345. void *pHeap; /* Heap storage space */
  2346. int nHeap; /* Size of pHeap[] */
  2347. int mnReq, mxReq; /* Min and max heap requests sizes */
  2348. sqlite3_int64 szMmap; /* mmap() space per open file */
  2349. sqlite3_int64 mxMmap; /* Maximum value for szMmap */
  2350. void *pScratch; /* Scratch memory */
  2351. int szScratch; /* Size of each scratch buffer */
  2352. int nScratch; /* Number of scratch buffers */
  2353. void *pPage; /* Page cache memory */
  2354. int szPage; /* Size of each page in pPage[] */
  2355. int nPage; /* Number of pages in pPage[] */
  2356. int mxParserStack; /* maximum depth of the parser stack */
  2357. int sharedCacheEnabled; /* true if shared-cache mode enabled */
  2358. /* The above might be initialized to non-zero. The following need to always
  2359. ** initially be zero, however. */
  2360. int isInit; /* True after initialization has finished */
  2361. int inProgress; /* True while initialization in progress */
  2362. int isMutexInit; /* True after mutexes are initialized */
  2363. int isMallocInit; /* True after malloc is initialized */
  2364. int isPCacheInit; /* True after malloc is initialized */
  2365. sqlite3_mutex *pInitMutex; /* Mutex used by sqlite3_initialize() */
  2366. int nRefInitMutex; /* Number of users of pInitMutex */
  2367. void (*xLog)(void*,int,const char*); /* Function for logging */
  2368. void *pLogArg; /* First argument to xLog() */
  2369. int bLocaltimeFault; /* True to fail localtime() calls */
  2370. #ifdef SQLITE_ENABLE_SQLLOG
  2371. void(*xSqllog)(void*,sqlite3*,const char*, int);
  2372. void *pSqllogArg;
  2373. #endif
  2374. };
  2375. /*
  2376. ** Context pointer passed down through the tree-walk.
  2377. */
  2378. struct Walker {
  2379. int (*xExprCallback)(Walker*, Expr*); /* Callback for expressions */
  2380. int (*xSelectCallback)(Walker*,Select*); /* Callback for SELECTs */
  2381. Parse *pParse; /* Parser context. */
  2382. int walkerDepth; /* Number of subqueries */
  2383. u8 bSelectDepthFirst; /* Do subqueries first */
  2384. union { /* Extra data for callback */
  2385. NameContext *pNC; /* Naming context */
  2386. int i; /* Integer value */
  2387. SrcList *pSrcList; /* FROM clause */
  2388. struct SrcCount *pSrcCount; /* Counting column references */
  2389. } u;
  2390. };
  2391. /* Forward declarations */
  2392. int sqlite3WalkExpr(Walker*, Expr*);
  2393. int sqlite3WalkExprList(Walker*, ExprList*);
  2394. int sqlite3WalkSelect(Walker*, Select*);
  2395. int sqlite3WalkSelectExpr(Walker*, Select*);
  2396. int sqlite3WalkSelectFrom(Walker*, Select*);
  2397. /*
  2398. ** Return code from the parse-tree walking primitives and their
  2399. ** callbacks.
  2400. */
  2401. #define WRC_Continue 0 /* Continue down into children */
  2402. #define WRC_Prune 1 /* Omit children but continue walking siblings */
  2403. #define WRC_Abort 2 /* Abandon the tree walk */
  2404. /*
  2405. ** Assuming zIn points to the first byte of a UTF-8 character,
  2406. ** advance zIn to point to the first byte of the next UTF-8 character.
  2407. */
  2408. #define SQLITE_SKIP_UTF8(zIn) { \
  2409. if( (*(zIn++))>=0xc0 ){ \
  2410. while( (*zIn & 0xc0)==0x80 ){ zIn++; } \
  2411. } \
  2412. }
  2413. /*
  2414. ** The SQLITE_*_BKPT macros are substitutes for the error codes with
  2415. ** the same name but without the _BKPT suffix. These macros invoke
  2416. ** routines that report the line-number on which the error originated
  2417. ** using sqlite3_log(). The routines also provide a convenient place
  2418. ** to set a debugger breakpoint.
  2419. */
  2420. int sqlite3CorruptError(int);
  2421. int sqlite3MisuseError(int);
  2422. int sqlite3CantopenError(int);
  2423. #define SQLITE_CORRUPT_BKPT sqlite3CorruptError(__LINE__)
  2424. #define SQLITE_MISUSE_BKPT sqlite3MisuseError(__LINE__)
  2425. #define SQLITE_CANTOPEN_BKPT sqlite3CantopenError(__LINE__)
  2426. /*
  2427. ** FTS4 is really an extension for FTS3. It is enabled using the
  2428. ** SQLITE_ENABLE_FTS3 macro. But to avoid confusion we also all
  2429. ** the SQLITE_ENABLE_FTS4 macro to serve as an alisse for SQLITE_ENABLE_FTS3.
  2430. */
  2431. #if defined(SQLITE_ENABLE_FTS4) && !defined(SQLITE_ENABLE_FTS3)
  2432. # define SQLITE_ENABLE_FTS3
  2433. #endif
  2434. /*
  2435. ** The ctype.h header is needed for non-ASCII systems. It is also
  2436. ** needed by FTS3 when FTS3 is included in the amalgamation.
  2437. */
  2438. #if !defined(SQLITE_ASCII) || \
  2439. (defined(SQLITE_ENABLE_FTS3) && defined(SQLITE_AMALGAMATION))
  2440. # include <ctype.h>
  2441. #endif
  2442. /*
  2443. ** The following macros mimic the standard library functions toupper(),
  2444. ** isspace(), isalnum(), isdigit() and isxdigit(), respectively. The
  2445. ** sqlite versions only work for ASCII characters, regardless of locale.
  2446. */
  2447. #ifdef SQLITE_ASCII
  2448. # define sqlite3Toupper(x) ((x)&~(sqlite3CtypeMap[(unsigned char)(x)]&0x20))
  2449. # define sqlite3Isspace(x) (sqlite3CtypeMap[(unsigned char)(x)]&0x01)
  2450. # define sqlite3Isalnum(x) (sqlite3CtypeMap[(unsigned char)(x)]&0x06)
  2451. # define sqlite3Isalpha(x) (sqlite3CtypeMap[(unsigned char)(x)]&0x02)
  2452. # define sqlite3Isdigit(x) (sqlite3CtypeMap[(unsigned char)(x)]&0x04)
  2453. # define sqlite3Isxdigit(x) (sqlite3CtypeMap[(unsigned char)(x)]&0x08)
  2454. # define sqlite3Tolower(x) (sqlite3UpperToLower[(unsigned char)(x)])
  2455. #else
  2456. # define sqlite3Toupper(x) toupper((unsigned char)(x))
  2457. # define sqlite3Isspace(x) isspace((unsigned char)(x))
  2458. # define sqlite3Isalnum(x) isalnum((unsigned char)(x))
  2459. # define sqlite3Isalpha(x) isalpha((unsigned char)(x))
  2460. # define sqlite3Isdigit(x) isdigit((unsigned char)(x))
  2461. # define sqlite3Isxdigit(x) isxdigit((unsigned char)(x))
  2462. # define sqlite3Tolower(x) tolower((unsigned char)(x))
  2463. #endif
  2464. /*
  2465. ** Internal function prototypes
  2466. */
  2467. #define sqlite3StrICmp sqlite3_stricmp
  2468. int sqlite3Strlen30(const char*);
  2469. #define sqlite3StrNICmp sqlite3_strnicmp
  2470. int sqlite3MallocInit(void);
  2471. void sqlite3MallocEnd(void);
  2472. void *sqlite3Malloc(int);
  2473. void *sqlite3MallocZero(int);
  2474. void *sqlite3DbMallocZero(sqlite3*, int);
  2475. void *sqlite3DbMallocRaw(sqlite3*, int);
  2476. char *sqlite3DbStrDup(sqlite3*,const char*);
  2477. char *sqlite3DbStrNDup(sqlite3*,const char*, int);
  2478. void *sqlite3Realloc(void*, int);
  2479. void *sqlite3DbReallocOrFree(sqlite3 *, void *, int);
  2480. void *sqlite3DbRealloc(sqlite3 *, void *, int);
  2481. void sqlite3DbFree(sqlite3*, void*);
  2482. int sqlite3MallocSize(void*);
  2483. int sqlite3DbMallocSize(sqlite3*, void*);
  2484. void *sqlite3ScratchMalloc(int);
  2485. void sqlite3ScratchFree(void*);
  2486. void *sqlite3PageMalloc(int);
  2487. void sqlite3PageFree(void*);
  2488. void sqlite3MemSetDefault(void);
  2489. void sqlite3BenignMallocHooks(void (*)(void), void (*)(void));
  2490. int sqlite3HeapNearlyFull(void);
  2491. /*
  2492. ** On systems with ample stack space and that support alloca(), make
  2493. ** use of alloca() to obtain space for large automatic objects. By default,
  2494. ** obtain space from malloc().
  2495. **
  2496. ** The alloca() routine never returns NULL. This will cause code paths
  2497. ** that deal with sqlite3StackAlloc() failures to be unreachable.
  2498. */
  2499. #ifdef SQLITE_USE_ALLOCA
  2500. # define sqlite3StackAllocRaw(D,N) alloca(N)
  2501. # define sqlite3StackAllocZero(D,N) memset(alloca(N), 0, N)
  2502. # define sqlite3StackFree(D,P)
  2503. #else
  2504. # define sqlite3StackAllocRaw(D,N) sqlite3DbMallocRaw(D,N)
  2505. # define sqlite3StackAllocZero(D,N) sqlite3DbMallocZero(D,N)
  2506. # define sqlite3StackFree(D,P) sqlite3DbFree(D,P)
  2507. #endif
  2508. #ifdef SQLITE_ENABLE_MEMSYS3
  2509. const sqlite3_mem_methods *sqlite3MemGetMemsys3(void);
  2510. #endif
  2511. #ifdef SQLITE_ENABLE_MEMSYS5
  2512. const sqlite3_mem_methods *sqlite3MemGetMemsys5(void);
  2513. #endif
  2514. #ifndef SQLITE_MUTEX_OMIT
  2515. sqlite3_mutex_methods const *sqlite3DefaultMutex(void);
  2516. sqlite3_mutex_methods const *sqlite3NoopMutex(void);
  2517. sqlite3_mutex *sqlite3MutexAlloc(int);
  2518. int sqlite3MutexInit(void);
  2519. int sqlite3MutexEnd(void);
  2520. #endif
  2521. int sqlite3StatusValue(int);
  2522. void sqlite3StatusAdd(int, int);
  2523. void sqlite3StatusSet(int, int);
  2524. #ifndef SQLITE_OMIT_FLOATING_POINT
  2525. int sqlite3IsNaN(double);
  2526. #else
  2527. # define sqlite3IsNaN(X) 0
  2528. #endif
  2529. void sqlite3VXPrintf(StrAccum*, int, const char*, va_list);
  2530. #ifndef SQLITE_OMIT_TRACE
  2531. void sqlite3XPrintf(StrAccum*, const char*, ...);
  2532. #endif
  2533. char *sqlite3MPrintf(sqlite3*,const char*, ...);
  2534. char *sqlite3VMPrintf(sqlite3*,const char*, va_list);
  2535. char *sqlite3MAppendf(sqlite3*,char*,const char*,...);
  2536. #if defined(SQLITE_TEST) || defined(SQLITE_DEBUG)
  2537. void sqlite3DebugPrintf(const char*, ...);
  2538. #endif
  2539. #if defined(SQLITE_TEST)
  2540. void *sqlite3TestTextToPtr(const char*);
  2541. #endif
  2542. /* Output formatting for SQLITE_TESTCTRL_EXPLAIN */
  2543. #if defined(SQLITE_ENABLE_TREE_EXPLAIN)
  2544. void sqlite3ExplainBegin(Vdbe*);
  2545. void sqlite3ExplainPrintf(Vdbe*, const char*, ...);
  2546. void sqlite3ExplainNL(Vdbe*);
  2547. void sqlite3ExplainPush(Vdbe*);
  2548. void sqlite3ExplainPop(Vdbe*);
  2549. void sqlite3ExplainFinish(Vdbe*);
  2550. void sqlite3ExplainSelect(Vdbe*, Select*);
  2551. void sqlite3ExplainExpr(Vdbe*, Expr*);
  2552. void sqlite3ExplainExprList(Vdbe*, ExprList*);
  2553. const char *sqlite3VdbeExplanation(Vdbe*);
  2554. #else
  2555. # define sqlite3ExplainBegin(X)
  2556. # define sqlite3ExplainSelect(A,B)
  2557. # define sqlite3ExplainExpr(A,B)
  2558. # define sqlite3ExplainExprList(A,B)
  2559. # define sqlite3ExplainFinish(X)
  2560. # define sqlite3VdbeExplanation(X) 0
  2561. #endif
  2562. void sqlite3SetString(char **, sqlite3*, const char*, ...);
  2563. void sqlite3ErrorMsg(Parse*, const char*, ...);
  2564. int sqlite3Dequote(char*);
  2565. int sqlite3KeywordCode(const unsigned char*, int);
  2566. int sqlite3RunParser(Parse*, const char*, char **);
  2567. void sqlite3FinishCoding(Parse*);
  2568. int sqlite3GetTempReg(Parse*);
  2569. void sqlite3ReleaseTempReg(Parse*,int);
  2570. int sqlite3GetTempRange(Parse*,int);
  2571. void sqlite3ReleaseTempRange(Parse*,int,int);
  2572. void sqlite3ClearTempRegCache(Parse*);
  2573. Expr *sqlite3ExprAlloc(sqlite3*,int,const Token*,int);
  2574. Expr *sqlite3Expr(sqlite3*,int,const char*);
  2575. void sqlite3ExprAttachSubtrees(sqlite3*,Expr*,Expr*,Expr*);
  2576. Expr *sqlite3PExpr(Parse*, int, Expr*, Expr*, const Token*);
  2577. Expr *sqlite3ExprAnd(sqlite3*,Expr*, Expr*);
  2578. Expr *sqlite3ExprFunction(Parse*,ExprList*, Token*);
  2579. void sqlite3ExprAssignVarNumber(Parse*, Expr*);
  2580. void sqlite3ExprDelete(sqlite3*, Expr*);
  2581. ExprList *sqlite3ExprListAppend(Parse*,ExprList*,Expr*);
  2582. void sqlite3ExprListSetName(Parse*,ExprList*,Token*,int);
  2583. void sqlite3ExprListSetSpan(Parse*,ExprList*,ExprSpan*);
  2584. void sqlite3ExprListDelete(sqlite3*, ExprList*);
  2585. int sqlite3Init(sqlite3*, char**);
  2586. int sqlite3InitCallback(void*, int, char**, char**);
  2587. void sqlite3Pragma(Parse*,Token*,Token*,Token*,int);
  2588. void sqlite3ResetAllSchemasOfConnection(sqlite3*);
  2589. void sqlite3ResetOneSchema(sqlite3*,int);
  2590. void sqlite3CollapseDatabaseArray(sqlite3*);
  2591. void sqlite3BeginParse(Parse*,int);
  2592. void sqlite3CommitInternalChanges(sqlite3*);
  2593. Table *sqlite3ResultSetOfSelect(Parse*,Select*);
  2594. void sqlite3OpenMasterTable(Parse *, int);
  2595. void sqlite3StartTable(Parse*,Token*,Token*,int,int,int,int);
  2596. void sqlite3AddColumn(Parse*,Token*);
  2597. void sqlite3AddNotNull(Parse*, int);
  2598. void sqlite3AddPrimaryKey(Parse*, ExprList*, int, int, int);
  2599. void sqlite3AddCheckConstraint(Parse*, Expr*);
  2600. void sqlite3AddColumnType(Parse*,Token*);
  2601. void sqlite3AddDefaultValue(Parse*,ExprSpan*);
  2602. void sqlite3AddCollateType(Parse*, Token*);
  2603. void sqlite3EndTable(Parse*,Token*,Token*,Select*);
  2604. int sqlite3ParseUri(const char*,const char*,unsigned int*,
  2605. sqlite3_vfs**,char**,char **);
  2606. Btree *sqlite3DbNameToBtree(sqlite3*,const char*);
  2607. int sqlite3CodeOnce(Parse *);
  2608. Bitvec *sqlite3BitvecCreate(u32);
  2609. int sqlite3BitvecTest(Bitvec*, u32);
  2610. int sqlite3BitvecSet(Bitvec*, u32);
  2611. void sqlite3BitvecClear(Bitvec*, u32, void*);
  2612. void sqlite3BitvecDestroy(Bitvec*);
  2613. u32 sqlite3BitvecSize(Bitvec*);
  2614. int sqlite3BitvecBuiltinTest(int,int*);
  2615. RowSet *sqlite3RowSetInit(sqlite3*, void*, unsigned int);
  2616. void sqlite3RowSetClear(RowSet*);
  2617. void sqlite3RowSetInsert(RowSet*, i64);
  2618. int sqlite3RowSetTest(RowSet*, u8 iBatch, i64);
  2619. int sqlite3RowSetNext(RowSet*, i64*);
  2620. void sqlite3CreateView(Parse*,Token*,Token*,Token*,Select*,int,int);
  2621. #if !defined(SQLITE_OMIT_VIEW) || !defined(SQLITE_OMIT_VIRTUALTABLE)
  2622. int sqlite3ViewGetColumnNames(Parse*,Table*);
  2623. #else
  2624. # define sqlite3ViewGetColumnNames(A,B) 0
  2625. #endif
  2626. void sqlite3DropTable(Parse*, SrcList*, int, int);
  2627. void sqlite3CodeDropTable(Parse*, Table*, int, int);
  2628. void sqlite3DeleteTable(sqlite3*, Table*);
  2629. #ifndef SQLITE_OMIT_AUTOINCREMENT
  2630. void sqlite3AutoincrementBegin(Parse *pParse);
  2631. void sqlite3AutoincrementEnd(Parse *pParse);
  2632. #else
  2633. # define sqlite3AutoincrementBegin(X)
  2634. # define sqlite3AutoincrementEnd(X)
  2635. #endif
  2636. int sqlite3CodeCoroutine(Parse*, Select*, SelectDest*);
  2637. void sqlite3Insert(Parse*, SrcList*, ExprList*, Select*, IdList*, int);
  2638. void *sqlite3ArrayAllocate(sqlite3*,void*,int,int*,int*);
  2639. IdList *sqlite3IdListAppend(sqlite3*, IdList*, Token*);
  2640. int sqlite3IdListIndex(IdList*,const char*);
  2641. SrcList *sqlite3SrcListEnlarge(sqlite3*, SrcList*, int, int);
  2642. SrcList *sqlite3SrcListAppend(sqlite3*, SrcList*, Token*, Token*);
  2643. SrcList *sqlite3SrcListAppendFromTerm(Parse*, SrcList*, Token*, Token*,
  2644. Token*, Select*, Expr*, IdList*);
  2645. void sqlite3SrcListIndexedBy(Parse *, SrcList *, Token *);
  2646. int sqlite3IndexedByLookup(Parse *, struct SrcList_item *);
  2647. void sqlite3SrcListShiftJoinType(SrcList*);
  2648. void sqlite3SrcListAssignCursors(Parse*, SrcList*);
  2649. void sqlite3IdListDelete(sqlite3*, IdList*);
  2650. void sqlite3SrcListDelete(sqlite3*, SrcList*);
  2651. Index *sqlite3CreateIndex(Parse*,Token*,Token*,SrcList*,ExprList*,int,Token*,
  2652. Expr*, int, int);
  2653. void sqlite3DropIndex(Parse*, SrcList*, int);
  2654. int sqlite3Select(Parse*, Select*, SelectDest*);
  2655. Select *sqlite3SelectNew(Parse*,ExprList*,SrcList*,Expr*,ExprList*,
  2656. Expr*,ExprList*,u16,Expr*,Expr*);
  2657. void sqlite3SelectDelete(sqlite3*, Select*);
  2658. Table *sqlite3SrcListLookup(Parse*, SrcList*);
  2659. int sqlite3IsReadOnly(Parse*, Table*, int);
  2660. void sqlite3OpenTable(Parse*, int iCur, int iDb, Table*, int);
  2661. #if defined(SQLITE_ENABLE_UPDATE_DELETE_LIMIT) && !defined(SQLITE_OMIT_SUBQUERY)
  2662. Expr *sqlite3LimitWhere(Parse*,SrcList*,Expr*,ExprList*,Expr*,Expr*,char*);
  2663. #endif
  2664. void sqlite3DeleteFrom(Parse*, SrcList*, Expr*);
  2665. void sqlite3Update(Parse*, SrcList*, ExprList*, Expr*, int);
  2666. WhereInfo *sqlite3WhereBegin(Parse*,SrcList*,Expr*,ExprList*,ExprList*,u16,int);
  2667. void sqlite3WhereEnd(WhereInfo*);
  2668. u64 sqlite3WhereOutputRowCount(WhereInfo*);
  2669. int sqlite3WhereIsDistinct(WhereInfo*);
  2670. int sqlite3WhereIsOrdered(WhereInfo*);
  2671. int sqlite3WhereContinueLabel(WhereInfo*);
  2672. int sqlite3WhereBreakLabel(WhereInfo*);
  2673. int sqlite3WhereOkOnePass(WhereInfo*);
  2674. int sqlite3ExprCodeGetColumn(Parse*, Table*, int, int, int, u8);
  2675. void sqlite3ExprCodeGetColumnOfTable(Vdbe*, Table*, int, int, int);
  2676. void sqlite3ExprCodeMove(Parse*, int, int, int);
  2677. void sqlite3ExprCacheStore(Parse*, int, int, int);
  2678. void sqlite3ExprCachePush(Parse*);
  2679. void sqlite3ExprCachePop(Parse*, int);
  2680. void sqlite3ExprCacheRemove(Parse*, int, int);
  2681. void sqlite3ExprCacheClear(Parse*);
  2682. void sqlite3ExprCacheAffinityChange(Parse*, int, int);
  2683. int sqlite3ExprCode(Parse*, Expr*, int);
  2684. int sqlite3ExprCodeTemp(Parse*, Expr*, int*);
  2685. int sqlite3ExprCodeTarget(Parse*, Expr*, int);
  2686. int sqlite3ExprCodeAndCache(Parse*, Expr*, int);
  2687. void sqlite3ExprCodeConstants(Parse*, Expr*);
  2688. int sqlite3ExprCodeExprList(Parse*, ExprList*, int, int);
  2689. void sqlite3ExprIfTrue(Parse*, Expr*, int, int);
  2690. void sqlite3ExprIfFalse(Parse*, Expr*, int, int);
  2691. Table *sqlite3FindTable(sqlite3*,const char*, const char*);
  2692. Table *sqlite3LocateTable(Parse*,int isView,const char*, const char*);
  2693. Table *sqlite3LocateTableItem(Parse*,int isView,struct SrcList_item *);
  2694. Index *sqlite3FindIndex(sqlite3*,const char*, const char*);
  2695. void sqlite3UnlinkAndDeleteTable(sqlite3*,int,const char*);
  2696. void sqlite3UnlinkAndDeleteIndex(sqlite3*,int,const char*);
  2697. void sqlite3Vacuum(Parse*);
  2698. int sqlite3RunVacuum(char**, sqlite3*);
  2699. char *sqlite3NameFromToken(sqlite3*, Token*);
  2700. int sqlite3ExprCompare(Expr*, Expr*, int);
  2701. int sqlite3ExprListCompare(ExprList*, ExprList*, int);
  2702. int sqlite3ExprImpliesExpr(Expr*, Expr*, int);
  2703. void sqlite3ExprAnalyzeAggregates(NameContext*, Expr*);
  2704. void sqlite3ExprAnalyzeAggList(NameContext*,ExprList*);
  2705. int sqlite3FunctionUsesThisSrc(Expr*, SrcList*);
  2706. Vdbe *sqlite3GetVdbe(Parse*);
  2707. void sqlite3PrngSaveState(void);
  2708. void sqlite3PrngRestoreState(void);
  2709. void sqlite3PrngResetState(void);
  2710. void sqlite3RollbackAll(sqlite3*,int);
  2711. void sqlite3CodeVerifySchema(Parse*, int);
  2712. void sqlite3CodeVerifyNamedSchema(Parse*, const char *zDb);
  2713. void sqlite3BeginTransaction(Parse*, int);
  2714. void sqlite3CommitTransaction(Parse*);
  2715. void sqlite3RollbackTransaction(Parse*);
  2716. void sqlite3Savepoint(Parse*, int, Token*);
  2717. void sqlite3CloseSavepoints(sqlite3 *);
  2718. void sqlite3LeaveMutexAndCloseZombie(sqlite3*);
  2719. int sqlite3ExprIsConstant(Expr*);
  2720. int sqlite3ExprIsConstantNotJoin(Expr*);
  2721. int sqlite3ExprIsConstantOrFunction(Expr*);
  2722. int sqlite3ExprIsInteger(Expr*, int*);
  2723. int sqlite3ExprCanBeNull(const Expr*);
  2724. void sqlite3ExprCodeIsNullJump(Vdbe*, const Expr*, int, int);
  2725. int sqlite3ExprNeedsNoAffinityChange(const Expr*, char);
  2726. int sqlite3IsRowid(const char*);
  2727. void sqlite3GenerateRowDelete(Parse*, Table*, int, int, int, Trigger *, int);
  2728. void sqlite3GenerateRowIndexDelete(Parse*, Table*, int, int*);
  2729. int sqlite3GenerateIndexKey(Parse*, Index*, int, int, int, int*);
  2730. void sqlite3GenerateConstraintChecks(Parse*,Table*,int,int,
  2731. int*,int,int,int,int,int*);
  2732. void sqlite3CompleteInsertion(Parse*, Table*, int, int, int*, int, int, int);
  2733. int sqlite3OpenTableAndIndices(Parse*, Table*, int, int);
  2734. void sqlite3BeginWriteOperation(Parse*, int, int);
  2735. void sqlite3MultiWrite(Parse*);
  2736. void sqlite3MayAbort(Parse*);
  2737. void sqlite3HaltConstraint(Parse*, int, int, char*, int);
  2738. Expr *sqlite3ExprDup(sqlite3*,Expr*,int);
  2739. ExprList *sqlite3ExprListDup(sqlite3*,ExprList*,int);
  2740. SrcList *sqlite3SrcListDup(sqlite3*,SrcList*,int);
  2741. IdList *sqlite3IdListDup(sqlite3*,IdList*);
  2742. Select *sqlite3SelectDup(sqlite3*,Select*,int);
  2743. void sqlite3FuncDefInsert(FuncDefHash*, FuncDef*);
  2744. FuncDef *sqlite3FindFunction(sqlite3*,const char*,int,int,u8,u8);
  2745. void sqlite3RegisterBuiltinFunctions(sqlite3*);
  2746. void sqlite3RegisterDateTimeFunctions(void);
  2747. void sqlite3RegisterGlobalFunctions(void);
  2748. int sqlite3SafetyCheckOk(sqlite3*);
  2749. int sqlite3SafetyCheckSickOrOk(sqlite3*);
  2750. void sqlite3ChangeCookie(Parse*, int);
  2751. #if !defined(SQLITE_OMIT_VIEW) && !defined(SQLITE_OMIT_TRIGGER)
  2752. void sqlite3MaterializeView(Parse*, Table*, Expr*, int);
  2753. #endif
  2754. #ifndef SQLITE_OMIT_TRIGGER
  2755. void sqlite3BeginTrigger(Parse*, Token*,Token*,int,int,IdList*,SrcList*,
  2756. Expr*,int, int);
  2757. void sqlite3FinishTrigger(Parse*, TriggerStep*, Token*);
  2758. void sqlite3DropTrigger(Parse*, SrcList*, int);
  2759. void sqlite3DropTriggerPtr(Parse*, Trigger*);
  2760. Trigger *sqlite3TriggersExist(Parse *, Table*, int, ExprList*, int *pMask);
  2761. Trigger *sqlite3TriggerList(Parse *, Table *);
  2762. void sqlite3CodeRowTrigger(Parse*, Trigger *, int, ExprList*, int, Table *,
  2763. int, int, int);
  2764. void sqlite3CodeRowTriggerDirect(Parse *, Trigger *, Table *, int, int, int);
  2765. void sqliteViewTriggers(Parse*, Table*, Expr*, int, ExprList*);
  2766. void sqlite3DeleteTriggerStep(sqlite3*, TriggerStep*);
  2767. TriggerStep *sqlite3TriggerSelectStep(sqlite3*,Select*);
  2768. TriggerStep *sqlite3TriggerInsertStep(sqlite3*,Token*, IdList*,
  2769. ExprList*,Select*,u8);
  2770. TriggerStep *sqlite3TriggerUpdateStep(sqlite3*,Token*,ExprList*, Expr*, u8);
  2771. TriggerStep *sqlite3TriggerDeleteStep(sqlite3*,Token*, Expr*);
  2772. void sqlite3DeleteTrigger(sqlite3*, Trigger*);
  2773. void sqlite3UnlinkAndDeleteTrigger(sqlite3*,int,const char*);
  2774. u32 sqlite3TriggerColmask(Parse*,Trigger*,ExprList*,int,int,Table*,int);
  2775. # define sqlite3ParseToplevel(p) ((p)->pToplevel ? (p)->pToplevel : (p))
  2776. #else
  2777. # define sqlite3TriggersExist(B,C,D,E,F) 0
  2778. # define sqlite3DeleteTrigger(A,B)
  2779. # define sqlite3DropTriggerPtr(A,B)
  2780. # define sqlite3UnlinkAndDeleteTrigger(A,B,C)
  2781. # define sqlite3CodeRowTrigger(A,B,C,D,E,F,G,H,I)
  2782. # define sqlite3CodeRowTriggerDirect(A,B,C,D,E,F)
  2783. # define sqlite3TriggerList(X, Y) 0
  2784. # define sqlite3ParseToplevel(p) p
  2785. # define sqlite3TriggerColmask(A,B,C,D,E,F,G) 0
  2786. #endif
  2787. int sqlite3JoinType(Parse*, Token*, Token*, Token*);
  2788. void sqlite3CreateForeignKey(Parse*, ExprList*, Token*, ExprList*, int);
  2789. void sqlite3DeferForeignKey(Parse*, int);
  2790. #ifndef SQLITE_OMIT_AUTHORIZATION
  2791. void sqlite3AuthRead(Parse*,Expr*,Schema*,SrcList*);
  2792. int sqlite3AuthCheck(Parse*,int, const char*, const char*, const char*);
  2793. void sqlite3AuthContextPush(Parse*, AuthContext*, const char*);
  2794. void sqlite3AuthContextPop(AuthContext*);
  2795. int sqlite3AuthReadCol(Parse*, const char *, const char *, int);
  2796. #else
  2797. # define sqlite3AuthRead(a,b,c,d)
  2798. # define sqlite3AuthCheck(a,b,c,d,e) SQLITE_OK
  2799. # define sqlite3AuthContextPush(a,b,c)
  2800. # define sqlite3AuthContextPop(a) ((void)(a))
  2801. #endif
  2802. void sqlite3Attach(Parse*, Expr*, Expr*, Expr*);
  2803. void sqlite3Detach(Parse*, Expr*);
  2804. void sqlite3FixInit(DbFixer*, Parse*, int, const char*, const Token*);
  2805. int sqlite3FixSrcList(DbFixer*, SrcList*);
  2806. int sqlite3FixSelect(DbFixer*, Select*);
  2807. int sqlite3FixExpr(DbFixer*, Expr*);
  2808. int sqlite3FixExprList(DbFixer*, ExprList*);
  2809. int sqlite3FixTriggerStep(DbFixer*, TriggerStep*);
  2810. int sqlite3AtoF(const char *z, double*, int, u8);
  2811. int sqlite3GetInt32(const char *, int*);
  2812. int sqlite3Atoi(const char*);
  2813. int sqlite3Utf16ByteLen(const void *pData, int nChar);
  2814. int sqlite3Utf8CharLen(const char *pData, int nByte);
  2815. u32 sqlite3Utf8Read(const u8**);
  2816. LogEst sqlite3LogEst(u64);
  2817. LogEst sqlite3LogEstAdd(LogEst,LogEst);
  2818. #ifndef SQLITE_OMIT_VIRTUALTABLE
  2819. LogEst sqlite3LogEstFromDouble(double);
  2820. #endif
  2821. u64 sqlite3LogEstToInt(LogEst);
  2822. /*
  2823. ** Routines to read and write variable-length integers. These used to
  2824. ** be defined locally, but now we use the varint routines in the util.c
  2825. ** file. Code should use the MACRO forms below, as the Varint32 versions
  2826. ** are coded to assume the single byte case is already handled (which
  2827. ** the MACRO form does).
  2828. */
  2829. int sqlite3PutVarint(unsigned char*, u64);
  2830. int sqlite3PutVarint32(unsigned char*, u32);
  2831. u8 sqlite3GetVarint(const unsigned char *, u64 *);
  2832. u8 sqlite3GetVarint32(const unsigned char *, u32 *);
  2833. int sqlite3VarintLen(u64 v);
  2834. /*
  2835. ** The header of a record consists of a sequence variable-length integers.
  2836. ** These integers are almost always small and are encoded as a single byte.
  2837. ** The following macros take advantage this fact to provide a fast encode
  2838. ** and decode of the integers in a record header. It is faster for the common
  2839. ** case where the integer is a single byte. It is a little slower when the
  2840. ** integer is two or more bytes. But overall it is faster.
  2841. **
  2842. ** The following expressions are equivalent:
  2843. **
  2844. ** x = sqlite3GetVarint32( A, &B );
  2845. ** x = sqlite3PutVarint32( A, B );
  2846. **
  2847. ** x = getVarint32( A, B );
  2848. ** x = putVarint32( A, B );
  2849. **
  2850. */
  2851. #define getVarint32(A,B) \
  2852. (u8)((*(A)<(u8)0x80)?((B)=(u32)*(A)),1:sqlite3GetVarint32((A),(u32 *)&(B)))
  2853. #define putVarint32(A,B) \
  2854. (u8)(((u32)(B)<(u32)0x80)?(*(A)=(unsigned char)(B)),1:\
  2855. sqlite3PutVarint32((A),(B)))
  2856. #define getVarint sqlite3GetVarint
  2857. #define putVarint sqlite3PutVarint
  2858. const char *sqlite3IndexAffinityStr(Vdbe *, Index *);
  2859. void sqlite3TableAffinityStr(Vdbe *, Table *);
  2860. char sqlite3CompareAffinity(Expr *pExpr, char aff2);
  2861. int sqlite3IndexAffinityOk(Expr *pExpr, char idx_affinity);
  2862. char sqlite3ExprAffinity(Expr *pExpr);
  2863. int sqlite3Atoi64(const char*, i64*, int, u8);
  2864. void sqlite3Error(sqlite3*, int, const char*,...);
  2865. void *sqlite3HexToBlob(sqlite3*, const char *z, int n);
  2866. u8 sqlite3HexToInt(int h);
  2867. int sqlite3TwoPartName(Parse *, Token *, Token *, Token **);
  2868. #if defined(SQLITE_DEBUG) || defined(SQLITE_TEST) || \
  2869. defined(SQLITE_DEBUG_OS_TRACE)
  2870. const char *sqlite3ErrName(int);
  2871. #endif
  2872. const char *sqlite3ErrStr(int);
  2873. int sqlite3ReadSchema(Parse *pParse);
  2874. CollSeq *sqlite3FindCollSeq(sqlite3*,u8 enc, const char*,int);
  2875. CollSeq *sqlite3LocateCollSeq(Parse *pParse, const char*zName);
  2876. CollSeq *sqlite3ExprCollSeq(Parse *pParse, Expr *pExpr);
  2877. Expr *sqlite3ExprAddCollateToken(Parse *pParse, Expr*, Token*);
  2878. Expr *sqlite3ExprAddCollateString(Parse*,Expr*,const char*);
  2879. Expr *sqlite3ExprSkipCollate(Expr*);
  2880. int sqlite3CheckCollSeq(Parse *, CollSeq *);
  2881. int sqlite3CheckObjectName(Parse *, const char *);
  2882. void sqlite3VdbeSetChanges(sqlite3 *, int);
  2883. int sqlite3AddInt64(i64*,i64);
  2884. int sqlite3SubInt64(i64*,i64);
  2885. int sqlite3MulInt64(i64*,i64);
  2886. int sqlite3AbsInt32(int);
  2887. #ifdef SQLITE_ENABLE_8_3_NAMES
  2888. void sqlite3FileSuffix3(const char*, char*);
  2889. #else
  2890. # define sqlite3FileSuffix3(X,Y)
  2891. #endif
  2892. u8 sqlite3GetBoolean(const char *z,int);
  2893. const void *sqlite3ValueText(sqlite3_value*, u8);
  2894. int sqlite3ValueBytes(sqlite3_value*, u8);
  2895. void sqlite3ValueSetStr(sqlite3_value*, int, const void *,u8,
  2896. void(*)(void*));
  2897. void sqlite3ValueFree(sqlite3_value*);
  2898. sqlite3_value *sqlite3ValueNew(sqlite3 *);
  2899. char *sqlite3Utf16to8(sqlite3 *, const void*, int, u8);
  2900. int sqlite3ValueFromExpr(sqlite3 *, Expr *, u8, u8, sqlite3_value **);
  2901. void sqlite3ValueApplyAffinity(sqlite3_value *, u8, u8);
  2902. #ifndef SQLITE_AMALGAMATION
  2903. extern const unsigned char sqlite3OpcodeProperty[];
  2904. extern const unsigned char sqlite3UpperToLower[];
  2905. extern const unsigned char sqlite3CtypeMap[];
  2906. extern const Token sqlite3IntTokens[];
  2907. extern SQLITE_WSD struct Sqlite3Config sqlite3Config;
  2908. extern SQLITE_WSD FuncDefHash sqlite3GlobalFunctions;
  2909. #ifndef SQLITE_OMIT_WSD
  2910. extern int sqlite3PendingByte;
  2911. #endif
  2912. #endif
  2913. void sqlite3RootPageMoved(sqlite3*, int, int, int);
  2914. void sqlite3Reindex(Parse*, Token*, Token*);
  2915. void sqlite3AlterFunctions(void);
  2916. void sqlite3AlterRenameTable(Parse*, SrcList*, Token*);
  2917. int sqlite3GetToken(const unsigned char *, int *);
  2918. void sqlite3NestedParse(Parse*, const char*, ...);
  2919. void sqlite3ExpirePreparedStatements(sqlite3*);
  2920. int sqlite3CodeSubselect(Parse *, Expr *, int, int);
  2921. void sqlite3SelectPrep(Parse*, Select*, NameContext*);
  2922. int sqlite3MatchSpanName(const char*, const char*, const char*, const char*);
  2923. int sqlite3ResolveExprNames(NameContext*, Expr*);
  2924. void sqlite3ResolveSelectNames(Parse*, Select*, NameContext*);
  2925. void sqlite3ResolveSelfReference(Parse*,Table*,int,Expr*,ExprList*);
  2926. int sqlite3ResolveOrderGroupBy(Parse*, Select*, ExprList*, const char*);
  2927. void sqlite3ColumnDefault(Vdbe *, Table *, int, int);
  2928. void sqlite3AlterFinishAddColumn(Parse *, Token *);
  2929. void sqlite3AlterBeginAddColumn(Parse *, SrcList *);
  2930. CollSeq *sqlite3GetCollSeq(Parse*, u8, CollSeq *, const char*);
  2931. char sqlite3AffinityType(const char*, u8*);
  2932. void sqlite3Analyze(Parse*, Token*, Token*);
  2933. int sqlite3InvokeBusyHandler(BusyHandler*);
  2934. int sqlite3FindDb(sqlite3*, Token*);
  2935. int sqlite3FindDbName(sqlite3 *, const char *);
  2936. int sqlite3AnalysisLoad(sqlite3*,int iDB);
  2937. void sqlite3DeleteIndexSamples(sqlite3*,Index*);
  2938. void sqlite3DefaultRowEst(Index*);
  2939. void sqlite3RegisterLikeFunctions(sqlite3*, int);
  2940. int sqlite3IsLikeFunction(sqlite3*,Expr*,int*,char*);
  2941. void sqlite3MinimumFileFormat(Parse*, int, int);
  2942. void sqlite3SchemaClear(void *);
  2943. Schema *sqlite3SchemaGet(sqlite3 *, Btree *);
  2944. int sqlite3SchemaToIndex(sqlite3 *db, Schema *);
  2945. KeyInfo *sqlite3KeyInfoAlloc(sqlite3*,int);
  2946. KeyInfo *sqlite3IndexKeyinfo(Parse *, Index *);
  2947. int sqlite3CreateFunc(sqlite3 *, const char *, int, int, void *,
  2948. void (*)(sqlite3_context*,int,sqlite3_value **),
  2949. void (*)(sqlite3_context*,int,sqlite3_value **), void (*)(sqlite3_context*),
  2950. FuncDestructor *pDestructor
  2951. );
  2952. int sqlite3ApiExit(sqlite3 *db, int);
  2953. int sqlite3OpenTempDatabase(Parse *);
  2954. void sqlite3StrAccumInit(StrAccum*, char*, int, int);
  2955. void sqlite3StrAccumAppend(StrAccum*,const char*,int);
  2956. void sqlite3AppendSpace(StrAccum*,int);
  2957. char *sqlite3StrAccumFinish(StrAccum*);
  2958. void sqlite3StrAccumReset(StrAccum*);
  2959. void sqlite3SelectDestInit(SelectDest*,int,int);
  2960. Expr *sqlite3CreateColumnExpr(sqlite3 *, SrcList *, int, int);
  2961. void sqlite3BackupRestart(sqlite3_backup *);
  2962. void sqlite3BackupUpdate(sqlite3_backup *, Pgno, const u8 *);
  2963. #ifdef SQLITE_ENABLE_STAT3_OR_STAT4
  2964. void sqlite3AnalyzeFunctions(void);
  2965. int sqlite3Stat4ProbeSetValue(Parse*,Index*,UnpackedRecord**,Expr*,u8,int,int*);
  2966. void sqlite3Stat4ProbeFree(UnpackedRecord*);
  2967. #endif
  2968. /*
  2969. ** The interface to the LEMON-generated parser
  2970. */
  2971. void *sqlite3ParserAlloc(void*(*)(size_t));
  2972. void sqlite3ParserFree(void*, void(*)(void*));
  2973. void sqlite3Parser(void*, int, Token, Parse*);
  2974. #ifdef YYTRACKMAXSTACKDEPTH
  2975. int sqlite3ParserStackPeak(void*);
  2976. #endif
  2977. void sqlite3AutoLoadExtensions(sqlite3*);
  2978. #ifndef SQLITE_OMIT_LOAD_EXTENSION
  2979. void sqlite3CloseExtensions(sqlite3*);
  2980. #else
  2981. # define sqlite3CloseExtensions(X)
  2982. #endif
  2983. #ifndef SQLITE_OMIT_SHARED_CACHE
  2984. void sqlite3TableLock(Parse *, int, int, u8, const char *);
  2985. #else
  2986. #define sqlite3TableLock(v,w,x,y,z)
  2987. #endif
  2988. #ifdef SQLITE_TEST
  2989. int sqlite3Utf8To8(unsigned char*);
  2990. #endif
  2991. #ifdef SQLITE_OMIT_VIRTUALTABLE
  2992. # define sqlite3VtabClear(Y)
  2993. # define sqlite3VtabSync(X,Y) SQLITE_OK
  2994. # define sqlite3VtabRollback(X)
  2995. # define sqlite3VtabCommit(X)
  2996. # define sqlite3VtabInSync(db) 0
  2997. # define sqlite3VtabLock(X)
  2998. # define sqlite3VtabUnlock(X)
  2999. # define sqlite3VtabUnlockList(X)
  3000. # define sqlite3VtabSavepoint(X, Y, Z) SQLITE_OK
  3001. # define sqlite3GetVTable(X,Y) ((VTable*)0)
  3002. #else
  3003. void sqlite3VtabClear(sqlite3 *db, Table*);
  3004. void sqlite3VtabDisconnect(sqlite3 *db, Table *p);
  3005. int sqlite3VtabSync(sqlite3 *db, Vdbe*);
  3006. int sqlite3VtabRollback(sqlite3 *db);
  3007. int sqlite3VtabCommit(sqlite3 *db);
  3008. void sqlite3VtabLock(VTable *);
  3009. void sqlite3VtabUnlock(VTable *);
  3010. void sqlite3VtabUnlockList(sqlite3*);
  3011. int sqlite3VtabSavepoint(sqlite3 *, int, int);
  3012. void sqlite3VtabImportErrmsg(Vdbe*, sqlite3_vtab*);
  3013. VTable *sqlite3GetVTable(sqlite3*, Table*);
  3014. # define sqlite3VtabInSync(db) ((db)->nVTrans>0 && (db)->aVTrans==0)
  3015. #endif
  3016. void sqlite3VtabMakeWritable(Parse*,Table*);
  3017. void sqlite3VtabBeginParse(Parse*, Token*, Token*, Token*, int);
  3018. void sqlite3VtabFinishParse(Parse*, Token*);
  3019. void sqlite3VtabArgInit(Parse*);
  3020. void sqlite3VtabArgExtend(Parse*, Token*);
  3021. int sqlite3VtabCallCreate(sqlite3*, int, const char *, char **);
  3022. int sqlite3VtabCallConnect(Parse*, Table*);
  3023. int sqlite3VtabCallDestroy(sqlite3*, int, const char *);
  3024. int sqlite3VtabBegin(sqlite3 *, VTable *);
  3025. FuncDef *sqlite3VtabOverloadFunction(sqlite3 *,FuncDef*, int nArg, Expr*);
  3026. void sqlite3InvalidFunction(sqlite3_context*,int,sqlite3_value**);
  3027. sqlite3_int64 sqlite3StmtCurrentTime(sqlite3_context*);
  3028. int sqlite3VdbeParameterIndex(Vdbe*, const char*, int);
  3029. int sqlite3TransferBindings(sqlite3_stmt *, sqlite3_stmt *);
  3030. int sqlite3Reprepare(Vdbe*);
  3031. void sqlite3ExprListCheckLength(Parse*, ExprList*, const char*);
  3032. CollSeq *sqlite3BinaryCompareCollSeq(Parse *, Expr *, Expr *);
  3033. int sqlite3TempInMemory(const sqlite3*);
  3034. const char *sqlite3JournalModename(int);
  3035. #ifndef SQLITE_OMIT_WAL
  3036. int sqlite3Checkpoint(sqlite3*, int, int, int*, int*);
  3037. int sqlite3WalDefaultHook(void*,sqlite3*,const char*,int);
  3038. #endif
  3039. /* Declarations for functions in fkey.c. All of these are replaced by
  3040. ** no-op macros if OMIT_FOREIGN_KEY is defined. In this case no foreign
  3041. ** key functionality is available. If OMIT_TRIGGER is defined but
  3042. ** OMIT_FOREIGN_KEY is not, only some of the functions are no-oped. In
  3043. ** this case foreign keys are parsed, but no other functionality is
  3044. ** provided (enforcement of FK constraints requires the triggers sub-system).
  3045. */
  3046. #if !defined(SQLITE_OMIT_FOREIGN_KEY) && !defined(SQLITE_OMIT_TRIGGER)
  3047. void sqlite3FkCheck(Parse*, Table*, int, int, int*, int);
  3048. void sqlite3FkDropTable(Parse*, SrcList *, Table*);
  3049. void sqlite3FkActions(Parse*, Table*, ExprList*, int, int*, int);
  3050. int sqlite3FkRequired(Parse*, Table*, int*, int);
  3051. u32 sqlite3FkOldmask(Parse*, Table*);
  3052. FKey *sqlite3FkReferences(Table *);
  3053. #else
  3054. #define sqlite3FkActions(a,b,c,d,e,f)
  3055. #define sqlite3FkCheck(a,b,c,d,e,f)
  3056. #define sqlite3FkDropTable(a,b,c)
  3057. #define sqlite3FkOldmask(a,b) 0
  3058. #define sqlite3FkRequired(a,b,c,d) 0
  3059. #endif
  3060. #ifndef SQLITE_OMIT_FOREIGN_KEY
  3061. void sqlite3FkDelete(sqlite3 *, Table*);
  3062. int sqlite3FkLocateIndex(Parse*,Table*,FKey*,Index**,int**);
  3063. #else
  3064. #define sqlite3FkDelete(a,b)
  3065. #define sqlite3FkLocateIndex(a,b,c,d,e)
  3066. #endif
  3067. /*
  3068. ** Available fault injectors. Should be numbered beginning with 0.
  3069. */
  3070. #define SQLITE_FAULTINJECTOR_MALLOC 0
  3071. #define SQLITE_FAULTINJECTOR_COUNT 1
  3072. /*
  3073. ** The interface to the code in fault.c used for identifying "benign"
  3074. ** malloc failures. This is only present if SQLITE_OMIT_BUILTIN_TEST
  3075. ** is not defined.
  3076. */
  3077. #ifndef SQLITE_OMIT_BUILTIN_TEST
  3078. void sqlite3BeginBenignMalloc(void);
  3079. void sqlite3EndBenignMalloc(void);
  3080. #else
  3081. #define sqlite3BeginBenignMalloc()
  3082. #define sqlite3EndBenignMalloc()
  3083. #endif
  3084. #define IN_INDEX_ROWID 1
  3085. #define IN_INDEX_EPH 2
  3086. #define IN_INDEX_INDEX_ASC 3
  3087. #define IN_INDEX_INDEX_DESC 4
  3088. int sqlite3FindInIndex(Parse *, Expr *, int*);
  3089. #ifdef SQLITE_ENABLE_ATOMIC_WRITE
  3090. int sqlite3JournalOpen(sqlite3_vfs *, const char *, sqlite3_file *, int, int);
  3091. int sqlite3JournalSize(sqlite3_vfs *);
  3092. int sqlite3JournalCreate(sqlite3_file *);
  3093. int sqlite3JournalExists(sqlite3_file *p);
  3094. #else
  3095. #define sqlite3JournalSize(pVfs) ((pVfs)->szOsFile)
  3096. #define sqlite3JournalExists(p) 1
  3097. #endif
  3098. void sqlite3MemJournalOpen(sqlite3_file *);
  3099. int sqlite3MemJournalSize(void);
  3100. int sqlite3IsMemJournal(sqlite3_file *);
  3101. #if SQLITE_MAX_EXPR_DEPTH>0
  3102. void sqlite3ExprSetHeight(Parse *pParse, Expr *p);
  3103. int sqlite3SelectExprHeight(Select *);
  3104. int sqlite3ExprCheckHeight(Parse*, int);
  3105. #else
  3106. #define sqlite3ExprSetHeight(x,y)
  3107. #define sqlite3SelectExprHeight(x) 0
  3108. #define sqlite3ExprCheckHeight(x,y)
  3109. #endif
  3110. u32 sqlite3Get4byte(const u8*);
  3111. void sqlite3Put4byte(u8*, u32);
  3112. #ifdef SQLITE_ENABLE_UNLOCK_NOTIFY
  3113. void sqlite3ConnectionBlocked(sqlite3 *, sqlite3 *);
  3114. void sqlite3ConnectionUnlocked(sqlite3 *db);
  3115. void sqlite3ConnectionClosed(sqlite3 *db);
  3116. #else
  3117. #define sqlite3ConnectionBlocked(x,y)
  3118. #define sqlite3ConnectionUnlocked(x)
  3119. #define sqlite3ConnectionClosed(x)
  3120. #endif
  3121. #ifdef SQLITE_DEBUG
  3122. void sqlite3ParserTrace(FILE*, char *);
  3123. #endif
  3124. /*
  3125. ** If the SQLITE_ENABLE IOTRACE exists then the global variable
  3126. ** sqlite3IoTrace is a pointer to a printf-like routine used to
  3127. ** print I/O tracing messages.
  3128. */
  3129. #ifdef SQLITE_ENABLE_IOTRACE
  3130. # define IOTRACE(A) if( sqlite3IoTrace ){ sqlite3IoTrace A; }
  3131. void sqlite3VdbeIOTraceSql(Vdbe*);
  3132. SQLITE_EXTERN void (*sqlite3IoTrace)(const char*,...);
  3133. #else
  3134. # define IOTRACE(A)
  3135. # define sqlite3VdbeIOTraceSql(X)
  3136. #endif
  3137. /*
  3138. ** These routines are available for the mem2.c debugging memory allocator
  3139. ** only. They are used to verify that different "types" of memory
  3140. ** allocations are properly tracked by the system.
  3141. **
  3142. ** sqlite3MemdebugSetType() sets the "type" of an allocation to one of
  3143. ** the MEMTYPE_* macros defined below. The type must be a bitmask with
  3144. ** a single bit set.
  3145. **
  3146. ** sqlite3MemdebugHasType() returns true if any of the bits in its second
  3147. ** argument match the type set by the previous sqlite3MemdebugSetType().
  3148. ** sqlite3MemdebugHasType() is intended for use inside assert() statements.
  3149. **
  3150. ** sqlite3MemdebugNoType() returns true if none of the bits in its second
  3151. ** argument match the type set by the previous sqlite3MemdebugSetType().
  3152. **
  3153. ** Perhaps the most important point is the difference between MEMTYPE_HEAP
  3154. ** and MEMTYPE_LOOKASIDE. If an allocation is MEMTYPE_LOOKASIDE, that means
  3155. ** it might have been allocated by lookaside, except the allocation was
  3156. ** too large or lookaside was already full. It is important to verify
  3157. ** that allocations that might have been satisfied by lookaside are not
  3158. ** passed back to non-lookaside free() routines. Asserts such as the
  3159. ** example above are placed on the non-lookaside free() routines to verify
  3160. ** this constraint.
  3161. **
  3162. ** All of this is no-op for a production build. It only comes into
  3163. ** play when the SQLITE_MEMDEBUG compile-time option is used.
  3164. */
  3165. #ifdef SQLITE_MEMDEBUG
  3166. void sqlite3MemdebugSetType(void*,u8);
  3167. int sqlite3MemdebugHasType(void*,u8);
  3168. int sqlite3MemdebugNoType(void*,u8);
  3169. #else
  3170. # define sqlite3MemdebugSetType(X,Y) /* no-op */
  3171. # define sqlite3MemdebugHasType(X,Y) 1
  3172. # define sqlite3MemdebugNoType(X,Y) 1
  3173. #endif
  3174. #define MEMTYPE_HEAP 0x01 /* General heap allocations */
  3175. #define MEMTYPE_LOOKASIDE 0x02 /* Might have been lookaside memory */
  3176. #define MEMTYPE_SCRATCH 0x04 /* Scratch allocations */
  3177. #define MEMTYPE_PCACHE 0x08 /* Page cache allocations */
  3178. #define MEMTYPE_DB 0x10 /* Uses sqlite3DbMalloc, not sqlite_malloc */
  3179. #endif /* _SQLITEINT_H_ */