main.c 106 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349
  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. ** Main file for the SQLite library. The routines in this file
  13. ** implement the programmer interface to the library. Routines in
  14. ** other files are for internal use by SQLite and should not be
  15. ** accessed by users of the library.
  16. */
  17. #include "sqliteInt.h"
  18. #ifdef SQLITE_ENABLE_FTS3
  19. # include "fts3.h"
  20. #endif
  21. #ifdef SQLITE_ENABLE_RTREE
  22. # include "rtree.h"
  23. #endif
  24. #ifdef SQLITE_ENABLE_ICU
  25. # include "sqliteicu.h"
  26. #endif
  27. #ifndef SQLITE_AMALGAMATION
  28. /* IMPLEMENTATION-OF: R-46656-45156 The sqlite3_version[] string constant
  29. ** contains the text of SQLITE_VERSION macro.
  30. */
  31. const char sqlite3_version[] = SQLITE_VERSION;
  32. #endif
  33. /* IMPLEMENTATION-OF: R-53536-42575 The sqlite3_libversion() function returns
  34. ** a pointer to the to the sqlite3_version[] string constant.
  35. */
  36. const char *sqlite3_libversion(void){ return sqlite3_version; }
  37. /* IMPLEMENTATION-OF: R-63124-39300 The sqlite3_sourceid() function returns a
  38. ** pointer to a string constant whose value is the same as the
  39. ** SQLITE_SOURCE_ID C preprocessor macro.
  40. */
  41. const char *sqlite3_sourceid(void){ return SQLITE_SOURCE_ID; }
  42. /* IMPLEMENTATION-OF: R-35210-63508 The sqlite3_libversion_number() function
  43. ** returns an integer equal to SQLITE_VERSION_NUMBER.
  44. */
  45. int sqlite3_libversion_number(void){ return SQLITE_VERSION_NUMBER; }
  46. /* IMPLEMENTATION-OF: R-20790-14025 The sqlite3_threadsafe() function returns
  47. ** zero if and only if SQLite was compiled with mutexing code omitted due to
  48. ** the SQLITE_THREADSAFE compile-time option being set to 0.
  49. */
  50. int sqlite3_threadsafe(void){ return SQLITE_THREADSAFE; }
  51. #if !defined(SQLITE_OMIT_TRACE) && defined(SQLITE_ENABLE_IOTRACE)
  52. /*
  53. ** If the following function pointer is not NULL and if
  54. ** SQLITE_ENABLE_IOTRACE is enabled, then messages describing
  55. ** I/O active are written using this function. These messages
  56. ** are intended for debugging activity only.
  57. */
  58. void (*sqlite3IoTrace)(const char*, ...) = 0;
  59. #endif
  60. /*
  61. ** If the following global variable points to a string which is the
  62. ** name of a directory, then that directory will be used to store
  63. ** temporary files.
  64. **
  65. ** See also the "PRAGMA temp_store_directory" SQL command.
  66. */
  67. char *sqlite3_temp_directory = 0;
  68. /*
  69. ** If the following global variable points to a string which is the
  70. ** name of a directory, then that directory will be used to store
  71. ** all database files specified with a relative pathname.
  72. **
  73. ** See also the "PRAGMA data_store_directory" SQL command.
  74. */
  75. char *sqlite3_data_directory = 0;
  76. /*
  77. ** Initialize SQLite.
  78. **
  79. ** This routine must be called to initialize the memory allocation,
  80. ** VFS, and mutex subsystems prior to doing any serious work with
  81. ** SQLite. But as long as you do not compile with SQLITE_OMIT_AUTOINIT
  82. ** this routine will be called automatically by key routines such as
  83. ** sqlite3_open().
  84. **
  85. ** This routine is a no-op except on its very first call for the process,
  86. ** or for the first call after a call to sqlite3_shutdown.
  87. **
  88. ** The first thread to call this routine runs the initialization to
  89. ** completion. If subsequent threads call this routine before the first
  90. ** thread has finished the initialization process, then the subsequent
  91. ** threads must block until the first thread finishes with the initialization.
  92. **
  93. ** The first thread might call this routine recursively. Recursive
  94. ** calls to this routine should not block, of course. Otherwise the
  95. ** initialization process would never complete.
  96. **
  97. ** Let X be the first thread to enter this routine. Let Y be some other
  98. ** thread. Then while the initial invocation of this routine by X is
  99. ** incomplete, it is required that:
  100. **
  101. ** * Calls to this routine from Y must block until the outer-most
  102. ** call by X completes.
  103. **
  104. ** * Recursive calls to this routine from thread X return immediately
  105. ** without blocking.
  106. */
  107. int sqlite3_initialize(void){
  108. MUTEX_LOGIC( sqlite3_mutex *pMaster; ) /* The main static mutex */
  109. int rc; /* Result code */
  110. #ifdef SQLITE_EXTRA_INIT
  111. int bRunExtraInit = 0; /* Extra initialization needed */
  112. #endif
  113. #ifdef SQLITE_OMIT_WSD
  114. rc = sqlite3_wsd_init(4096, 24);
  115. if( rc!=SQLITE_OK ){
  116. return rc;
  117. }
  118. #endif
  119. /* If SQLite is already completely initialized, then this call
  120. ** to sqlite3_initialize() should be a no-op. But the initialization
  121. ** must be complete. So isInit must not be set until the very end
  122. ** of this routine.
  123. */
  124. if( sqlite3GlobalConfig.isInit ) return SQLITE_OK;
  125. #ifdef SQLITE_ENABLE_SQLLOG
  126. {
  127. extern void sqlite3_init_sqllog(void);
  128. sqlite3_init_sqllog();
  129. }
  130. #endif
  131. /* Make sure the mutex subsystem is initialized. If unable to
  132. ** initialize the mutex subsystem, return early with the error.
  133. ** If the system is so sick that we are unable to allocate a mutex,
  134. ** there is not much SQLite is going to be able to do.
  135. **
  136. ** The mutex subsystem must take care of serializing its own
  137. ** initialization.
  138. */
  139. rc = sqlite3MutexInit();
  140. if( rc ) return rc;
  141. /* Initialize the malloc() system and the recursive pInitMutex mutex.
  142. ** This operation is protected by the STATIC_MASTER mutex. Note that
  143. ** MutexAlloc() is called for a static mutex prior to initializing the
  144. ** malloc subsystem - this implies that the allocation of a static
  145. ** mutex must not require support from the malloc subsystem.
  146. */
  147. MUTEX_LOGIC( pMaster = sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER); )
  148. sqlite3_mutex_enter(pMaster);
  149. sqlite3GlobalConfig.isMutexInit = 1;
  150. if( !sqlite3GlobalConfig.isMallocInit ){
  151. rc = sqlite3MallocInit();
  152. }
  153. if( rc==SQLITE_OK ){
  154. sqlite3GlobalConfig.isMallocInit = 1;
  155. if( !sqlite3GlobalConfig.pInitMutex ){
  156. sqlite3GlobalConfig.pInitMutex =
  157. sqlite3MutexAlloc(SQLITE_MUTEX_RECURSIVE);
  158. if( sqlite3GlobalConfig.bCoreMutex && !sqlite3GlobalConfig.pInitMutex ){
  159. rc = SQLITE_NOMEM;
  160. }
  161. }
  162. }
  163. if( rc==SQLITE_OK ){
  164. sqlite3GlobalConfig.nRefInitMutex++;
  165. }
  166. sqlite3_mutex_leave(pMaster);
  167. /* If rc is not SQLITE_OK at this point, then either the malloc
  168. ** subsystem could not be initialized or the system failed to allocate
  169. ** the pInitMutex mutex. Return an error in either case. */
  170. if( rc!=SQLITE_OK ){
  171. return rc;
  172. }
  173. /* Do the rest of the initialization under the recursive mutex so
  174. ** that we will be able to handle recursive calls into
  175. ** sqlite3_initialize(). The recursive calls normally come through
  176. ** sqlite3_os_init() when it invokes sqlite3_vfs_register(), but other
  177. ** recursive calls might also be possible.
  178. **
  179. ** IMPLEMENTATION-OF: R-00140-37445 SQLite automatically serializes calls
  180. ** to the xInit method, so the xInit method need not be threadsafe.
  181. **
  182. ** The following mutex is what serializes access to the appdef pcache xInit
  183. ** methods. The sqlite3_pcache_methods.xInit() all is embedded in the
  184. ** call to sqlite3PcacheInitialize().
  185. */
  186. sqlite3_mutex_enter(sqlite3GlobalConfig.pInitMutex);
  187. if( sqlite3GlobalConfig.isInit==0 && sqlite3GlobalConfig.inProgress==0 ){
  188. FuncDefHash *pHash = &GLOBAL(FuncDefHash, sqlite3GlobalFunctions);
  189. sqlite3GlobalConfig.inProgress = 1;
  190. memset(pHash, 0, sizeof(sqlite3GlobalFunctions));
  191. sqlite3RegisterGlobalFunctions();
  192. if( sqlite3GlobalConfig.isPCacheInit==0 ){
  193. rc = sqlite3PcacheInitialize();
  194. }
  195. if( rc==SQLITE_OK ){
  196. sqlite3GlobalConfig.isPCacheInit = 1;
  197. rc = sqlite3OsInit();
  198. }
  199. if( rc==SQLITE_OK ){
  200. sqlite3PCacheBufferSetup( sqlite3GlobalConfig.pPage,
  201. sqlite3GlobalConfig.szPage, sqlite3GlobalConfig.nPage);
  202. sqlite3GlobalConfig.isInit = 1;
  203. #ifdef SQLITE_EXTRA_INIT
  204. bRunExtraInit = 1;
  205. #endif
  206. }
  207. sqlite3GlobalConfig.inProgress = 0;
  208. }
  209. sqlite3_mutex_leave(sqlite3GlobalConfig.pInitMutex);
  210. /* Go back under the static mutex and clean up the recursive
  211. ** mutex to prevent a resource leak.
  212. */
  213. sqlite3_mutex_enter(pMaster);
  214. sqlite3GlobalConfig.nRefInitMutex--;
  215. if( sqlite3GlobalConfig.nRefInitMutex<=0 ){
  216. assert( sqlite3GlobalConfig.nRefInitMutex==0 );
  217. sqlite3_mutex_free(sqlite3GlobalConfig.pInitMutex);
  218. sqlite3GlobalConfig.pInitMutex = 0;
  219. }
  220. sqlite3_mutex_leave(pMaster);
  221. /* The following is just a sanity check to make sure SQLite has
  222. ** been compiled correctly. It is important to run this code, but
  223. ** we don't want to run it too often and soak up CPU cycles for no
  224. ** reason. So we run it once during initialization.
  225. */
  226. #ifndef NDEBUG
  227. #ifndef SQLITE_OMIT_FLOATING_POINT
  228. /* This section of code's only "output" is via assert() statements. */
  229. if ( rc==SQLITE_OK ){
  230. u64 x = (((u64)1)<<63)-1;
  231. double y;
  232. assert(sizeof(x)==8);
  233. assert(sizeof(x)==sizeof(y));
  234. memcpy(&y, &x, 8);
  235. assert( sqlite3IsNaN(y) );
  236. }
  237. #endif
  238. #endif
  239. /* Do extra initialization steps requested by the SQLITE_EXTRA_INIT
  240. ** compile-time option.
  241. */
  242. #ifdef SQLITE_EXTRA_INIT
  243. if( bRunExtraInit ){
  244. int SQLITE_EXTRA_INIT(const char*);
  245. rc = SQLITE_EXTRA_INIT(0);
  246. }
  247. #endif
  248. return rc;
  249. }
  250. /*
  251. ** Undo the effects of sqlite3_initialize(). Must not be called while
  252. ** there are outstanding database connections or memory allocations or
  253. ** while any part of SQLite is otherwise in use in any thread. This
  254. ** routine is not threadsafe. But it is safe to invoke this routine
  255. ** on when SQLite is already shut down. If SQLite is already shut down
  256. ** when this routine is invoked, then this routine is a harmless no-op.
  257. */
  258. int sqlite3_shutdown(void){
  259. if( sqlite3GlobalConfig.isInit ){
  260. #ifdef SQLITE_EXTRA_SHUTDOWN
  261. void SQLITE_EXTRA_SHUTDOWN(void);
  262. SQLITE_EXTRA_SHUTDOWN();
  263. #endif
  264. sqlite3_os_end();
  265. sqlite3_reset_auto_extension();
  266. sqlite3GlobalConfig.isInit = 0;
  267. }
  268. if( sqlite3GlobalConfig.isPCacheInit ){
  269. sqlite3PcacheShutdown();
  270. sqlite3GlobalConfig.isPCacheInit = 0;
  271. }
  272. if( sqlite3GlobalConfig.isMallocInit ){
  273. sqlite3MallocEnd();
  274. sqlite3GlobalConfig.isMallocInit = 0;
  275. #ifndef SQLITE_OMIT_SHUTDOWN_DIRECTORIES
  276. /* The heap subsystem has now been shutdown and these values are supposed
  277. ** to be NULL or point to memory that was obtained from sqlite3_malloc(),
  278. ** which would rely on that heap subsystem; therefore, make sure these
  279. ** values cannot refer to heap memory that was just invalidated when the
  280. ** heap subsystem was shutdown. This is only done if the current call to
  281. ** this function resulted in the heap subsystem actually being shutdown.
  282. */
  283. sqlite3_data_directory = 0;
  284. sqlite3_temp_directory = 0;
  285. #endif
  286. }
  287. if( sqlite3GlobalConfig.isMutexInit ){
  288. sqlite3MutexEnd();
  289. sqlite3GlobalConfig.isMutexInit = 0;
  290. }
  291. return SQLITE_OK;
  292. }
  293. /*
  294. ** This API allows applications to modify the global configuration of
  295. ** the SQLite library at run-time.
  296. **
  297. ** This routine should only be called when there are no outstanding
  298. ** database connections or memory allocations. This routine is not
  299. ** threadsafe. Failure to heed these warnings can lead to unpredictable
  300. ** behavior.
  301. */
  302. int sqlite3_config(int op, ...){
  303. va_list ap;
  304. int rc = SQLITE_OK;
  305. /* sqlite3_config() shall return SQLITE_MISUSE if it is invoked while
  306. ** the SQLite library is in use. */
  307. if( sqlite3GlobalConfig.isInit ) return SQLITE_MISUSE_BKPT;
  308. va_start(ap, op);
  309. switch( op ){
  310. /* Mutex configuration options are only available in a threadsafe
  311. ** compile.
  312. */
  313. #if defined(SQLITE_THREADSAFE) && SQLITE_THREADSAFE>0
  314. case SQLITE_CONFIG_SINGLETHREAD: {
  315. /* Disable all mutexing */
  316. sqlite3GlobalConfig.bCoreMutex = 0;
  317. sqlite3GlobalConfig.bFullMutex = 0;
  318. break;
  319. }
  320. case SQLITE_CONFIG_MULTITHREAD: {
  321. /* Disable mutexing of database connections */
  322. /* Enable mutexing of core data structures */
  323. sqlite3GlobalConfig.bCoreMutex = 1;
  324. sqlite3GlobalConfig.bFullMutex = 0;
  325. break;
  326. }
  327. case SQLITE_CONFIG_SERIALIZED: {
  328. /* Enable all mutexing */
  329. sqlite3GlobalConfig.bCoreMutex = 1;
  330. sqlite3GlobalConfig.bFullMutex = 1;
  331. break;
  332. }
  333. case SQLITE_CONFIG_MUTEX: {
  334. /* Specify an alternative mutex implementation */
  335. sqlite3GlobalConfig.mutex = *va_arg(ap, sqlite3_mutex_methods*);
  336. break;
  337. }
  338. case SQLITE_CONFIG_GETMUTEX: {
  339. /* Retrieve the current mutex implementation */
  340. *va_arg(ap, sqlite3_mutex_methods*) = sqlite3GlobalConfig.mutex;
  341. break;
  342. }
  343. #endif
  344. case SQLITE_CONFIG_MALLOC: {
  345. /* Specify an alternative malloc implementation */
  346. sqlite3GlobalConfig.m = *va_arg(ap, sqlite3_mem_methods*);
  347. break;
  348. }
  349. case SQLITE_CONFIG_GETMALLOC: {
  350. /* Retrieve the current malloc() implementation */
  351. if( sqlite3GlobalConfig.m.xMalloc==0 ) sqlite3MemSetDefault();
  352. *va_arg(ap, sqlite3_mem_methods*) = sqlite3GlobalConfig.m;
  353. break;
  354. }
  355. case SQLITE_CONFIG_MEMSTATUS: {
  356. /* Enable or disable the malloc status collection */
  357. sqlite3GlobalConfig.bMemstat = va_arg(ap, int);
  358. break;
  359. }
  360. case SQLITE_CONFIG_SCRATCH: {
  361. /* Designate a buffer for scratch memory space */
  362. sqlite3GlobalConfig.pScratch = va_arg(ap, void*);
  363. sqlite3GlobalConfig.szScratch = va_arg(ap, int);
  364. sqlite3GlobalConfig.nScratch = va_arg(ap, int);
  365. break;
  366. }
  367. case SQLITE_CONFIG_PAGECACHE: {
  368. /* Designate a buffer for page cache memory space */
  369. sqlite3GlobalConfig.pPage = va_arg(ap, void*);
  370. sqlite3GlobalConfig.szPage = va_arg(ap, int);
  371. sqlite3GlobalConfig.nPage = va_arg(ap, int);
  372. break;
  373. }
  374. case SQLITE_CONFIG_PCACHE: {
  375. /* no-op */
  376. break;
  377. }
  378. case SQLITE_CONFIG_GETPCACHE: {
  379. /* now an error */
  380. rc = SQLITE_ERROR;
  381. break;
  382. }
  383. case SQLITE_CONFIG_PCACHE2: {
  384. /* Specify an alternative page cache implementation */
  385. sqlite3GlobalConfig.pcache2 = *va_arg(ap, sqlite3_pcache_methods2*);
  386. break;
  387. }
  388. case SQLITE_CONFIG_GETPCACHE2: {
  389. if( sqlite3GlobalConfig.pcache2.xInit==0 ){
  390. sqlite3PCacheSetDefault();
  391. }
  392. *va_arg(ap, sqlite3_pcache_methods2*) = sqlite3GlobalConfig.pcache2;
  393. break;
  394. }
  395. #if defined(SQLITE_ENABLE_MEMSYS3) || defined(SQLITE_ENABLE_MEMSYS5)
  396. case SQLITE_CONFIG_HEAP: {
  397. /* Designate a buffer for heap memory space */
  398. sqlite3GlobalConfig.pHeap = va_arg(ap, void*);
  399. sqlite3GlobalConfig.nHeap = va_arg(ap, int);
  400. sqlite3GlobalConfig.mnReq = va_arg(ap, int);
  401. if( sqlite3GlobalConfig.mnReq<1 ){
  402. sqlite3GlobalConfig.mnReq = 1;
  403. }else if( sqlite3GlobalConfig.mnReq>(1<<12) ){
  404. /* cap min request size at 2^12 */
  405. sqlite3GlobalConfig.mnReq = (1<<12);
  406. }
  407. if( sqlite3GlobalConfig.pHeap==0 ){
  408. /* If the heap pointer is NULL, then restore the malloc implementation
  409. ** back to NULL pointers too. This will cause the malloc to go
  410. ** back to its default implementation when sqlite3_initialize() is
  411. ** run.
  412. */
  413. memset(&sqlite3GlobalConfig.m, 0, sizeof(sqlite3GlobalConfig.m));
  414. }else{
  415. /* The heap pointer is not NULL, then install one of the
  416. ** mem5.c/mem3.c methods. The enclosing #if guarantees at
  417. ** least one of these methods is currently enabled.
  418. */
  419. #ifdef SQLITE_ENABLE_MEMSYS3
  420. sqlite3GlobalConfig.m = *sqlite3MemGetMemsys3();
  421. #endif
  422. #ifdef SQLITE_ENABLE_MEMSYS5
  423. sqlite3GlobalConfig.m = *sqlite3MemGetMemsys5();
  424. #endif
  425. }
  426. break;
  427. }
  428. #endif
  429. case SQLITE_CONFIG_LOOKASIDE: {
  430. sqlite3GlobalConfig.szLookaside = va_arg(ap, int);
  431. sqlite3GlobalConfig.nLookaside = va_arg(ap, int);
  432. break;
  433. }
  434. /* Record a pointer to the logger function and its first argument.
  435. ** The default is NULL. Logging is disabled if the function pointer is
  436. ** NULL.
  437. */
  438. case SQLITE_CONFIG_LOG: {
  439. /* MSVC is picky about pulling func ptrs from va lists.
  440. ** http://support.microsoft.com/kb/47961
  441. ** sqlite3GlobalConfig.xLog = va_arg(ap, void(*)(void*,int,const char*));
  442. */
  443. typedef void(*LOGFUNC_t)(void*,int,const char*);
  444. sqlite3GlobalConfig.xLog = va_arg(ap, LOGFUNC_t);
  445. sqlite3GlobalConfig.pLogArg = va_arg(ap, void*);
  446. break;
  447. }
  448. case SQLITE_CONFIG_URI: {
  449. sqlite3GlobalConfig.bOpenUri = va_arg(ap, int);
  450. break;
  451. }
  452. case SQLITE_CONFIG_COVERING_INDEX_SCAN: {
  453. sqlite3GlobalConfig.bUseCis = va_arg(ap, int);
  454. break;
  455. }
  456. #ifdef SQLITE_ENABLE_SQLLOG
  457. case SQLITE_CONFIG_SQLLOG: {
  458. typedef void(*SQLLOGFUNC_t)(void*, sqlite3*, const char*, int);
  459. sqlite3GlobalConfig.xSqllog = va_arg(ap, SQLLOGFUNC_t);
  460. sqlite3GlobalConfig.pSqllogArg = va_arg(ap, void *);
  461. break;
  462. }
  463. #endif
  464. case SQLITE_CONFIG_MMAP_SIZE: {
  465. sqlite3_int64 szMmap = va_arg(ap, sqlite3_int64);
  466. sqlite3_int64 mxMmap = va_arg(ap, sqlite3_int64);
  467. if( mxMmap<0 || mxMmap>SQLITE_MAX_MMAP_SIZE ){
  468. mxMmap = SQLITE_MAX_MMAP_SIZE;
  469. }
  470. sqlite3GlobalConfig.mxMmap = mxMmap;
  471. if( szMmap<0 ) szMmap = SQLITE_DEFAULT_MMAP_SIZE;
  472. if( szMmap>mxMmap) szMmap = mxMmap;
  473. sqlite3GlobalConfig.szMmap = szMmap;
  474. break;
  475. }
  476. default: {
  477. rc = SQLITE_ERROR;
  478. break;
  479. }
  480. }
  481. va_end(ap);
  482. return rc;
  483. }
  484. /*
  485. ** Set up the lookaside buffers for a database connection.
  486. ** Return SQLITE_OK on success.
  487. ** If lookaside is already active, return SQLITE_BUSY.
  488. **
  489. ** The sz parameter is the number of bytes in each lookaside slot.
  490. ** The cnt parameter is the number of slots. If pStart is NULL the
  491. ** space for the lookaside memory is obtained from sqlite3_malloc().
  492. ** If pStart is not NULL then it is sz*cnt bytes of memory to use for
  493. ** the lookaside memory.
  494. */
  495. static int setupLookaside(sqlite3 *db, void *pBuf, int sz, int cnt){
  496. void *pStart;
  497. if( db->lookaside.nOut ){
  498. return SQLITE_BUSY;
  499. }
  500. /* Free any existing lookaside buffer for this handle before
  501. ** allocating a new one so we don't have to have space for
  502. ** both at the same time.
  503. */
  504. if( db->lookaside.bMalloced ){
  505. sqlite3_free(db->lookaside.pStart);
  506. }
  507. /* The size of a lookaside slot after ROUNDDOWN8 needs to be larger
  508. ** than a pointer to be useful.
  509. */
  510. sz = ROUNDDOWN8(sz); /* IMP: R-33038-09382 */
  511. if( sz<=(int)sizeof(LookasideSlot*) ) sz = 0;
  512. if( cnt<0 ) cnt = 0;
  513. if( sz==0 || cnt==0 ){
  514. sz = 0;
  515. pStart = 0;
  516. }else if( pBuf==0 ){
  517. sqlite3BeginBenignMalloc();
  518. pStart = sqlite3Malloc( sz*cnt ); /* IMP: R-61949-35727 */
  519. sqlite3EndBenignMalloc();
  520. if( pStart ) cnt = sqlite3MallocSize(pStart)/sz;
  521. }else{
  522. pStart = pBuf;
  523. }
  524. db->lookaside.pStart = pStart;
  525. db->lookaside.pFree = 0;
  526. db->lookaside.sz = (u16)sz;
  527. if( pStart ){
  528. int i;
  529. LookasideSlot *p;
  530. assert( sz > (int)sizeof(LookasideSlot*) );
  531. p = (LookasideSlot*)pStart;
  532. for(i=cnt-1; i>=0; i--){
  533. p->pNext = db->lookaside.pFree;
  534. db->lookaside.pFree = p;
  535. p = (LookasideSlot*)&((u8*)p)[sz];
  536. }
  537. db->lookaside.pEnd = p;
  538. db->lookaside.bEnabled = 1;
  539. db->lookaside.bMalloced = pBuf==0 ?1:0;
  540. }else{
  541. db->lookaside.pEnd = 0;
  542. db->lookaside.bEnabled = 0;
  543. db->lookaside.bMalloced = 0;
  544. }
  545. return SQLITE_OK;
  546. }
  547. /*
  548. ** Return the mutex associated with a database connection.
  549. */
  550. sqlite3_mutex *sqlite3_db_mutex(sqlite3 *db){
  551. return db->mutex;
  552. }
  553. /*
  554. ** Free up as much memory as we can from the given database
  555. ** connection.
  556. */
  557. int sqlite3_db_release_memory(sqlite3 *db){
  558. int i;
  559. sqlite3_mutex_enter(db->mutex);
  560. sqlite3BtreeEnterAll(db);
  561. for(i=0; i<db->nDb; i++){
  562. Btree *pBt = db->aDb[i].pBt;
  563. if( pBt ){
  564. Pager *pPager = sqlite3BtreePager(pBt);
  565. sqlite3PagerShrink(pPager);
  566. }
  567. }
  568. sqlite3BtreeLeaveAll(db);
  569. sqlite3_mutex_leave(db->mutex);
  570. return SQLITE_OK;
  571. }
  572. /*
  573. ** Configuration settings for an individual database connection
  574. */
  575. int sqlite3_db_config(sqlite3 *db, int op, ...){
  576. va_list ap;
  577. int rc;
  578. va_start(ap, op);
  579. switch( op ){
  580. case SQLITE_DBCONFIG_LOOKASIDE: {
  581. void *pBuf = va_arg(ap, void*); /* IMP: R-26835-10964 */
  582. int sz = va_arg(ap, int); /* IMP: R-47871-25994 */
  583. int cnt = va_arg(ap, int); /* IMP: R-04460-53386 */
  584. rc = setupLookaside(db, pBuf, sz, cnt);
  585. break;
  586. }
  587. default: {
  588. static const struct {
  589. int op; /* The opcode */
  590. u32 mask; /* Mask of the bit in sqlite3.flags to set/clear */
  591. } aFlagOp[] = {
  592. { SQLITE_DBCONFIG_ENABLE_FKEY, SQLITE_ForeignKeys },
  593. { SQLITE_DBCONFIG_ENABLE_TRIGGER, SQLITE_EnableTrigger },
  594. };
  595. unsigned int i;
  596. rc = SQLITE_ERROR; /* IMP: R-42790-23372 */
  597. for(i=0; i<ArraySize(aFlagOp); i++){
  598. if( aFlagOp[i].op==op ){
  599. int onoff = va_arg(ap, int);
  600. int *pRes = va_arg(ap, int*);
  601. int oldFlags = db->flags;
  602. if( onoff>0 ){
  603. db->flags |= aFlagOp[i].mask;
  604. }else if( onoff==0 ){
  605. db->flags &= ~aFlagOp[i].mask;
  606. }
  607. if( oldFlags!=db->flags ){
  608. sqlite3ExpirePreparedStatements(db);
  609. }
  610. if( pRes ){
  611. *pRes = (db->flags & aFlagOp[i].mask)!=0;
  612. }
  613. rc = SQLITE_OK;
  614. break;
  615. }
  616. }
  617. break;
  618. }
  619. }
  620. va_end(ap);
  621. return rc;
  622. }
  623. /*
  624. ** Return true if the buffer z[0..n-1] contains all spaces.
  625. */
  626. static int allSpaces(const char *z, int n){
  627. while( n>0 && z[n-1]==' ' ){ n--; }
  628. return n==0;
  629. }
  630. /*
  631. ** This is the default collating function named "BINARY" which is always
  632. ** available.
  633. **
  634. ** If the padFlag argument is not NULL then space padding at the end
  635. ** of strings is ignored. This implements the RTRIM collation.
  636. */
  637. static int binCollFunc(
  638. void *padFlag,
  639. int nKey1, const void *pKey1,
  640. int nKey2, const void *pKey2
  641. ){
  642. int rc, n;
  643. n = nKey1<nKey2 ? nKey1 : nKey2;
  644. rc = memcmp(pKey1, pKey2, n);
  645. if( rc==0 ){
  646. if( padFlag
  647. && allSpaces(((char*)pKey1)+n, nKey1-n)
  648. && allSpaces(((char*)pKey2)+n, nKey2-n)
  649. ){
  650. /* Leave rc unchanged at 0 */
  651. }else{
  652. rc = nKey1 - nKey2;
  653. }
  654. }
  655. return rc;
  656. }
  657. /*
  658. ** Another built-in collating sequence: NOCASE.
  659. **
  660. ** This collating sequence is intended to be used for "case independent
  661. ** comparison". SQLite's knowledge of upper and lower case equivalents
  662. ** extends only to the 26 characters used in the English language.
  663. **
  664. ** At the moment there is only a UTF-8 implementation.
  665. */
  666. static int nocaseCollatingFunc(
  667. void *NotUsed,
  668. int nKey1, const void *pKey1,
  669. int nKey2, const void *pKey2
  670. ){
  671. int r = sqlite3StrNICmp(
  672. (const char *)pKey1, (const char *)pKey2, (nKey1<nKey2)?nKey1:nKey2);
  673. UNUSED_PARAMETER(NotUsed);
  674. if( 0==r ){
  675. r = nKey1-nKey2;
  676. }
  677. return r;
  678. }
  679. /*
  680. ** Return the ROWID of the most recent insert
  681. */
  682. sqlite_int64 sqlite3_last_insert_rowid(sqlite3 *db){
  683. return db->lastRowid;
  684. }
  685. /*
  686. ** Return the number of changes in the most recent call to sqlite3_exec().
  687. */
  688. int sqlite3_changes(sqlite3 *db){
  689. return db->nChange;
  690. }
  691. /*
  692. ** Return the number of changes since the database handle was opened.
  693. */
  694. int sqlite3_total_changes(sqlite3 *db){
  695. return db->nTotalChange;
  696. }
  697. /*
  698. ** Close all open savepoints. This function only manipulates fields of the
  699. ** database handle object, it does not close any savepoints that may be open
  700. ** at the b-tree/pager level.
  701. */
  702. void sqlite3CloseSavepoints(sqlite3 *db){
  703. while( db->pSavepoint ){
  704. Savepoint *pTmp = db->pSavepoint;
  705. db->pSavepoint = pTmp->pNext;
  706. sqlite3DbFree(db, pTmp);
  707. }
  708. db->nSavepoint = 0;
  709. db->nStatement = 0;
  710. db->isTransactionSavepoint = 0;
  711. }
  712. /*
  713. ** Invoke the destructor function associated with FuncDef p, if any. Except,
  714. ** if this is not the last copy of the function, do not invoke it. Multiple
  715. ** copies of a single function are created when create_function() is called
  716. ** with SQLITE_ANY as the encoding.
  717. */
  718. static void functionDestroy(sqlite3 *db, FuncDef *p){
  719. FuncDestructor *pDestructor = p->pDestructor;
  720. if( pDestructor ){
  721. pDestructor->nRef--;
  722. if( pDestructor->nRef==0 ){
  723. pDestructor->xDestroy(pDestructor->pUserData);
  724. sqlite3DbFree(db, pDestructor);
  725. }
  726. }
  727. }
  728. /*
  729. ** Disconnect all sqlite3_vtab objects that belong to database connection
  730. ** db. This is called when db is being closed.
  731. */
  732. static void disconnectAllVtab(sqlite3 *db){
  733. #ifndef SQLITE_OMIT_VIRTUALTABLE
  734. int i;
  735. sqlite3BtreeEnterAll(db);
  736. for(i=0; i<db->nDb; i++){
  737. Schema *pSchema = db->aDb[i].pSchema;
  738. if( db->aDb[i].pSchema ){
  739. HashElem *p;
  740. for(p=sqliteHashFirst(&pSchema->tblHash); p; p=sqliteHashNext(p)){
  741. Table *pTab = (Table *)sqliteHashData(p);
  742. if( IsVirtual(pTab) ) sqlite3VtabDisconnect(db, pTab);
  743. }
  744. }
  745. }
  746. sqlite3BtreeLeaveAll(db);
  747. #else
  748. UNUSED_PARAMETER(db);
  749. #endif
  750. }
  751. /*
  752. ** Return TRUE if database connection db has unfinalized prepared
  753. ** statements or unfinished sqlite3_backup objects.
  754. */
  755. static int connectionIsBusy(sqlite3 *db){
  756. int j;
  757. assert( sqlite3_mutex_held(db->mutex) );
  758. if( db->pVdbe ) return 1;
  759. for(j=0; j<db->nDb; j++){
  760. Btree *pBt = db->aDb[j].pBt;
  761. if( pBt && sqlite3BtreeIsInBackup(pBt) ) return 1;
  762. }
  763. return 0;
  764. }
  765. /*
  766. ** Close an existing SQLite database
  767. */
  768. static int sqlite3Close(sqlite3 *db, int forceZombie){
  769. if( !db ){
  770. return SQLITE_OK;
  771. }
  772. if( !sqlite3SafetyCheckSickOrOk(db) ){
  773. return SQLITE_MISUSE_BKPT;
  774. }
  775. sqlite3_mutex_enter(db->mutex);
  776. /* Force xDisconnect calls on all virtual tables */
  777. disconnectAllVtab(db);
  778. /* If a transaction is open, the disconnectAllVtab() call above
  779. ** will not have called the xDisconnect() method on any virtual
  780. ** tables in the db->aVTrans[] array. The following sqlite3VtabRollback()
  781. ** call will do so. We need to do this before the check for active
  782. ** SQL statements below, as the v-table implementation may be storing
  783. ** some prepared statements internally.
  784. */
  785. sqlite3VtabRollback(db);
  786. /* Legacy behavior (sqlite3_close() behavior) is to return
  787. ** SQLITE_BUSY if the connection can not be closed immediately.
  788. */
  789. if( !forceZombie && connectionIsBusy(db) ){
  790. sqlite3Error(db, SQLITE_BUSY, "unable to close due to unfinalized "
  791. "statements or unfinished backups");
  792. sqlite3_mutex_leave(db->mutex);
  793. return SQLITE_BUSY;
  794. }
  795. #ifdef SQLITE_ENABLE_SQLLOG
  796. if( sqlite3GlobalConfig.xSqllog ){
  797. /* Closing the handle. Fourth parameter is passed the value 2. */
  798. sqlite3GlobalConfig.xSqllog(sqlite3GlobalConfig.pSqllogArg, db, 0, 2);
  799. }
  800. #endif
  801. /* Convert the connection into a zombie and then close it.
  802. */
  803. db->magic = SQLITE_MAGIC_ZOMBIE;
  804. sqlite3LeaveMutexAndCloseZombie(db);
  805. return SQLITE_OK;
  806. }
  807. /*
  808. ** Two variations on the public interface for closing a database
  809. ** connection. The sqlite3_close() version returns SQLITE_BUSY and
  810. ** leaves the connection option if there are unfinalized prepared
  811. ** statements or unfinished sqlite3_backups. The sqlite3_close_v2()
  812. ** version forces the connection to become a zombie if there are
  813. ** unclosed resources, and arranges for deallocation when the last
  814. ** prepare statement or sqlite3_backup closes.
  815. */
  816. int sqlite3_close(sqlite3 *db){ return sqlite3Close(db,0); }
  817. int sqlite3_close_v2(sqlite3 *db){ return sqlite3Close(db,1); }
  818. /*
  819. ** Close the mutex on database connection db.
  820. **
  821. ** Furthermore, if database connection db is a zombie (meaning that there
  822. ** has been a prior call to sqlite3_close(db) or sqlite3_close_v2(db)) and
  823. ** every sqlite3_stmt has now been finalized and every sqlite3_backup has
  824. ** finished, then free all resources.
  825. */
  826. void sqlite3LeaveMutexAndCloseZombie(sqlite3 *db){
  827. HashElem *i; /* Hash table iterator */
  828. int j;
  829. /* If there are outstanding sqlite3_stmt or sqlite3_backup objects
  830. ** or if the connection has not yet been closed by sqlite3_close_v2(),
  831. ** then just leave the mutex and return.
  832. */
  833. if( db->magic!=SQLITE_MAGIC_ZOMBIE || connectionIsBusy(db) ){
  834. sqlite3_mutex_leave(db->mutex);
  835. return;
  836. }
  837. /* If we reach this point, it means that the database connection has
  838. ** closed all sqlite3_stmt and sqlite3_backup objects and has been
  839. ** passed to sqlite3_close (meaning that it is a zombie). Therefore,
  840. ** go ahead and free all resources.
  841. */
  842. /* If a transaction is open, roll it back. This also ensures that if
  843. ** any database schemas have been modified by an uncommitted transaction
  844. ** they are reset. And that the required b-tree mutex is held to make
  845. ** the pager rollback and schema reset an atomic operation. */
  846. sqlite3RollbackAll(db, SQLITE_OK);
  847. /* Free any outstanding Savepoint structures. */
  848. sqlite3CloseSavepoints(db);
  849. /* Close all database connections */
  850. for(j=0; j<db->nDb; j++){
  851. struct Db *pDb = &db->aDb[j];
  852. if( pDb->pBt ){
  853. sqlite3BtreeClose(pDb->pBt);
  854. pDb->pBt = 0;
  855. if( j!=1 ){
  856. pDb->pSchema = 0;
  857. }
  858. }
  859. }
  860. /* Clear the TEMP schema separately and last */
  861. if( db->aDb[1].pSchema ){
  862. sqlite3SchemaClear(db->aDb[1].pSchema);
  863. }
  864. sqlite3VtabUnlockList(db);
  865. /* Free up the array of auxiliary databases */
  866. sqlite3CollapseDatabaseArray(db);
  867. assert( db->nDb<=2 );
  868. assert( db->aDb==db->aDbStatic );
  869. /* Tell the code in notify.c that the connection no longer holds any
  870. ** locks and does not require any further unlock-notify callbacks.
  871. */
  872. sqlite3ConnectionClosed(db);
  873. for(j=0; j<ArraySize(db->aFunc.a); j++){
  874. FuncDef *pNext, *pHash, *p;
  875. for(p=db->aFunc.a[j]; p; p=pHash){
  876. pHash = p->pHash;
  877. while( p ){
  878. functionDestroy(db, p);
  879. pNext = p->pNext;
  880. sqlite3DbFree(db, p);
  881. p = pNext;
  882. }
  883. }
  884. }
  885. for(i=sqliteHashFirst(&db->aCollSeq); i; i=sqliteHashNext(i)){
  886. CollSeq *pColl = (CollSeq *)sqliteHashData(i);
  887. /* Invoke any destructors registered for collation sequence user data. */
  888. for(j=0; j<3; j++){
  889. if( pColl[j].xDel ){
  890. pColl[j].xDel(pColl[j].pUser);
  891. }
  892. }
  893. sqlite3DbFree(db, pColl);
  894. }
  895. sqlite3HashClear(&db->aCollSeq);
  896. #ifndef SQLITE_OMIT_VIRTUALTABLE
  897. for(i=sqliteHashFirst(&db->aModule); i; i=sqliteHashNext(i)){
  898. Module *pMod = (Module *)sqliteHashData(i);
  899. if( pMod->xDestroy ){
  900. pMod->xDestroy(pMod->pAux);
  901. }
  902. sqlite3DbFree(db, pMod);
  903. }
  904. sqlite3HashClear(&db->aModule);
  905. #endif
  906. sqlite3Error(db, SQLITE_OK, 0); /* Deallocates any cached error strings. */
  907. if( db->pErr ){
  908. sqlite3ValueFree(db->pErr);
  909. }
  910. sqlite3CloseExtensions(db);
  911. db->magic = SQLITE_MAGIC_ERROR;
  912. /* The temp-database schema is allocated differently from the other schema
  913. ** objects (using sqliteMalloc() directly, instead of sqlite3BtreeSchema()).
  914. ** So it needs to be freed here. Todo: Why not roll the temp schema into
  915. ** the same sqliteMalloc() as the one that allocates the database
  916. ** structure?
  917. */
  918. sqlite3DbFree(db, db->aDb[1].pSchema);
  919. sqlite3_mutex_leave(db->mutex);
  920. db->magic = SQLITE_MAGIC_CLOSED;
  921. sqlite3_mutex_free(db->mutex);
  922. assert( db->lookaside.nOut==0 ); /* Fails on a lookaside memory leak */
  923. if( db->lookaside.bMalloced ){
  924. sqlite3_free(db->lookaside.pStart);
  925. }
  926. sqlite3_free(db);
  927. }
  928. /*
  929. ** Rollback all database files. If tripCode is not SQLITE_OK, then
  930. ** any open cursors are invalidated ("tripped" - as in "tripping a circuit
  931. ** breaker") and made to return tripCode if there are any further
  932. ** attempts to use that cursor.
  933. */
  934. void sqlite3RollbackAll(sqlite3 *db, int tripCode){
  935. int i;
  936. int inTrans = 0;
  937. assert( sqlite3_mutex_held(db->mutex) );
  938. sqlite3BeginBenignMalloc();
  939. /* Obtain all b-tree mutexes before making any calls to BtreeRollback().
  940. ** This is important in case the transaction being rolled back has
  941. ** modified the database schema. If the b-tree mutexes are not taken
  942. ** here, then another shared-cache connection might sneak in between
  943. ** the database rollback and schema reset, which can cause false
  944. ** corruption reports in some cases. */
  945. sqlite3BtreeEnterAll(db);
  946. for(i=0; i<db->nDb; i++){
  947. Btree *p = db->aDb[i].pBt;
  948. if( p ){
  949. if( sqlite3BtreeIsInTrans(p) ){
  950. inTrans = 1;
  951. }
  952. sqlite3BtreeRollback(p, tripCode);
  953. }
  954. }
  955. sqlite3VtabRollback(db);
  956. sqlite3EndBenignMalloc();
  957. if( (db->flags&SQLITE_InternChanges)!=0 && db->init.busy==0 ){
  958. sqlite3ExpirePreparedStatements(db);
  959. sqlite3ResetAllSchemasOfConnection(db);
  960. }
  961. sqlite3BtreeLeaveAll(db);
  962. /* Any deferred constraint violations have now been resolved. */
  963. db->nDeferredCons = 0;
  964. db->nDeferredImmCons = 0;
  965. db->flags &= ~SQLITE_DeferFKs;
  966. /* If one has been configured, invoke the rollback-hook callback */
  967. if( db->xRollbackCallback && (inTrans || !db->autoCommit) ){
  968. db->xRollbackCallback(db->pRollbackArg);
  969. }
  970. }
  971. /*
  972. ** Return a static string containing the name corresponding to the error code
  973. ** specified in the argument.
  974. */
  975. #if defined(SQLITE_DEBUG) || defined(SQLITE_TEST) || \
  976. defined(SQLITE_DEBUG_OS_TRACE)
  977. const char *sqlite3ErrName(int rc){
  978. const char *zName = 0;
  979. int i, origRc = rc;
  980. for(i=0; i<2 && zName==0; i++, rc &= 0xff){
  981. switch( rc ){
  982. case SQLITE_OK: zName = "SQLITE_OK"; break;
  983. case SQLITE_ERROR: zName = "SQLITE_ERROR"; break;
  984. case SQLITE_INTERNAL: zName = "SQLITE_INTERNAL"; break;
  985. case SQLITE_PERM: zName = "SQLITE_PERM"; break;
  986. case SQLITE_ABORT: zName = "SQLITE_ABORT"; break;
  987. case SQLITE_ABORT_ROLLBACK: zName = "SQLITE_ABORT_ROLLBACK"; break;
  988. case SQLITE_BUSY: zName = "SQLITE_BUSY"; break;
  989. case SQLITE_BUSY_RECOVERY: zName = "SQLITE_BUSY_RECOVERY"; break;
  990. case SQLITE_BUSY_SNAPSHOT: zName = "SQLITE_BUSY_SNAPSHOT"; break;
  991. case SQLITE_LOCKED: zName = "SQLITE_LOCKED"; break;
  992. case SQLITE_LOCKED_SHAREDCACHE: zName = "SQLITE_LOCKED_SHAREDCACHE";break;
  993. case SQLITE_NOMEM: zName = "SQLITE_NOMEM"; break;
  994. case SQLITE_READONLY: zName = "SQLITE_READONLY"; break;
  995. case SQLITE_READONLY_RECOVERY: zName = "SQLITE_READONLY_RECOVERY"; break;
  996. case SQLITE_READONLY_CANTLOCK: zName = "SQLITE_READONLY_CANTLOCK"; break;
  997. case SQLITE_READONLY_ROLLBACK: zName = "SQLITE_READONLY_ROLLBACK"; break;
  998. case SQLITE_INTERRUPT: zName = "SQLITE_INTERRUPT"; break;
  999. case SQLITE_IOERR: zName = "SQLITE_IOERR"; break;
  1000. case SQLITE_IOERR_READ: zName = "SQLITE_IOERR_READ"; break;
  1001. case SQLITE_IOERR_SHORT_READ: zName = "SQLITE_IOERR_SHORT_READ"; break;
  1002. case SQLITE_IOERR_WRITE: zName = "SQLITE_IOERR_WRITE"; break;
  1003. case SQLITE_IOERR_FSYNC: zName = "SQLITE_IOERR_FSYNC"; break;
  1004. case SQLITE_IOERR_DIR_FSYNC: zName = "SQLITE_IOERR_DIR_FSYNC"; break;
  1005. case SQLITE_IOERR_TRUNCATE: zName = "SQLITE_IOERR_TRUNCATE"; break;
  1006. case SQLITE_IOERR_FSTAT: zName = "SQLITE_IOERR_FSTAT"; break;
  1007. case SQLITE_IOERR_UNLOCK: zName = "SQLITE_IOERR_UNLOCK"; break;
  1008. case SQLITE_IOERR_RDLOCK: zName = "SQLITE_IOERR_RDLOCK"; break;
  1009. case SQLITE_IOERR_DELETE: zName = "SQLITE_IOERR_DELETE"; break;
  1010. case SQLITE_IOERR_BLOCKED: zName = "SQLITE_IOERR_BLOCKED"; break;
  1011. case SQLITE_IOERR_NOMEM: zName = "SQLITE_IOERR_NOMEM"; break;
  1012. case SQLITE_IOERR_ACCESS: zName = "SQLITE_IOERR_ACCESS"; break;
  1013. case SQLITE_IOERR_CHECKRESERVEDLOCK:
  1014. zName = "SQLITE_IOERR_CHECKRESERVEDLOCK"; break;
  1015. case SQLITE_IOERR_LOCK: zName = "SQLITE_IOERR_LOCK"; break;
  1016. case SQLITE_IOERR_CLOSE: zName = "SQLITE_IOERR_CLOSE"; break;
  1017. case SQLITE_IOERR_DIR_CLOSE: zName = "SQLITE_IOERR_DIR_CLOSE"; break;
  1018. case SQLITE_IOERR_SHMOPEN: zName = "SQLITE_IOERR_SHMOPEN"; break;
  1019. case SQLITE_IOERR_SHMSIZE: zName = "SQLITE_IOERR_SHMSIZE"; break;
  1020. case SQLITE_IOERR_SHMLOCK: zName = "SQLITE_IOERR_SHMLOCK"; break;
  1021. case SQLITE_IOERR_SHMMAP: zName = "SQLITE_IOERR_SHMMAP"; break;
  1022. case SQLITE_IOERR_SEEK: zName = "SQLITE_IOERR_SEEK"; break;
  1023. case SQLITE_IOERR_DELETE_NOENT: zName = "SQLITE_IOERR_DELETE_NOENT";break;
  1024. case SQLITE_IOERR_MMAP: zName = "SQLITE_IOERR_MMAP"; break;
  1025. case SQLITE_IOERR_GETTEMPPATH: zName = "SQLITE_IOERR_GETTEMPPATH"; break;
  1026. case SQLITE_IOERR_CONVPATH: zName = "SQLITE_IOERR_CONVPATH"; break;
  1027. case SQLITE_CORRUPT: zName = "SQLITE_CORRUPT"; break;
  1028. case SQLITE_CORRUPT_VTAB: zName = "SQLITE_CORRUPT_VTAB"; break;
  1029. case SQLITE_NOTFOUND: zName = "SQLITE_NOTFOUND"; break;
  1030. case SQLITE_FULL: zName = "SQLITE_FULL"; break;
  1031. case SQLITE_CANTOPEN: zName = "SQLITE_CANTOPEN"; break;
  1032. case SQLITE_CANTOPEN_NOTEMPDIR: zName = "SQLITE_CANTOPEN_NOTEMPDIR";break;
  1033. case SQLITE_CANTOPEN_ISDIR: zName = "SQLITE_CANTOPEN_ISDIR"; break;
  1034. case SQLITE_CANTOPEN_FULLPATH: zName = "SQLITE_CANTOPEN_FULLPATH"; break;
  1035. case SQLITE_CANTOPEN_CONVPATH: zName = "SQLITE_CANTOPEN_CONVPATH"; break;
  1036. case SQLITE_PROTOCOL: zName = "SQLITE_PROTOCOL"; break;
  1037. case SQLITE_EMPTY: zName = "SQLITE_EMPTY"; break;
  1038. case SQLITE_SCHEMA: zName = "SQLITE_SCHEMA"; break;
  1039. case SQLITE_TOOBIG: zName = "SQLITE_TOOBIG"; break;
  1040. case SQLITE_CONSTRAINT: zName = "SQLITE_CONSTRAINT"; break;
  1041. case SQLITE_CONSTRAINT_UNIQUE: zName = "SQLITE_CONSTRAINT_UNIQUE"; break;
  1042. case SQLITE_CONSTRAINT_TRIGGER: zName = "SQLITE_CONSTRAINT_TRIGGER";break;
  1043. case SQLITE_CONSTRAINT_FOREIGNKEY:
  1044. zName = "SQLITE_CONSTRAINT_FOREIGNKEY"; break;
  1045. case SQLITE_CONSTRAINT_CHECK: zName = "SQLITE_CONSTRAINT_CHECK"; break;
  1046. case SQLITE_CONSTRAINT_PRIMARYKEY:
  1047. zName = "SQLITE_CONSTRAINT_PRIMARYKEY"; break;
  1048. case SQLITE_CONSTRAINT_NOTNULL: zName = "SQLITE_CONSTRAINT_NOTNULL";break;
  1049. case SQLITE_CONSTRAINT_COMMITHOOK:
  1050. zName = "SQLITE_CONSTRAINT_COMMITHOOK"; break;
  1051. case SQLITE_CONSTRAINT_VTAB: zName = "SQLITE_CONSTRAINT_VTAB"; break;
  1052. case SQLITE_CONSTRAINT_FUNCTION:
  1053. zName = "SQLITE_CONSTRAINT_FUNCTION"; break;
  1054. case SQLITE_MISMATCH: zName = "SQLITE_MISMATCH"; break;
  1055. case SQLITE_MISUSE: zName = "SQLITE_MISUSE"; break;
  1056. case SQLITE_NOLFS: zName = "SQLITE_NOLFS"; break;
  1057. case SQLITE_AUTH: zName = "SQLITE_AUTH"; break;
  1058. case SQLITE_FORMAT: zName = "SQLITE_FORMAT"; break;
  1059. case SQLITE_RANGE: zName = "SQLITE_RANGE"; break;
  1060. case SQLITE_NOTADB: zName = "SQLITE_NOTADB"; break;
  1061. case SQLITE_ROW: zName = "SQLITE_ROW"; break;
  1062. case SQLITE_NOTICE: zName = "SQLITE_NOTICE"; break;
  1063. case SQLITE_NOTICE_RECOVER_WAL: zName = "SQLITE_NOTICE_RECOVER_WAL";break;
  1064. case SQLITE_NOTICE_RECOVER_ROLLBACK:
  1065. zName = "SQLITE_NOTICE_RECOVER_ROLLBACK"; break;
  1066. case SQLITE_WARNING: zName = "SQLITE_WARNING"; break;
  1067. case SQLITE_WARNING_AUTOINDEX: zName = "SQLITE_WARNING_AUTOINDEX"; break;
  1068. case SQLITE_DONE: zName = "SQLITE_DONE"; break;
  1069. }
  1070. }
  1071. if( zName==0 ){
  1072. static char zBuf[50];
  1073. sqlite3_snprintf(sizeof(zBuf), zBuf, "SQLITE_UNKNOWN(%d)", origRc);
  1074. zName = zBuf;
  1075. }
  1076. return zName;
  1077. }
  1078. #endif
  1079. /*
  1080. ** Return a static string that describes the kind of error specified in the
  1081. ** argument.
  1082. */
  1083. const char *sqlite3ErrStr(int rc){
  1084. static const char* const aMsg[] = {
  1085. /* SQLITE_OK */ "not an error",
  1086. /* SQLITE_ERROR */ "SQL logic error or missing database",
  1087. /* SQLITE_INTERNAL */ 0,
  1088. /* SQLITE_PERM */ "access permission denied",
  1089. /* SQLITE_ABORT */ "callback requested query abort",
  1090. /* SQLITE_BUSY */ "database is locked",
  1091. /* SQLITE_LOCKED */ "database table is locked",
  1092. /* SQLITE_NOMEM */ "out of memory",
  1093. /* SQLITE_READONLY */ "attempt to write a readonly database",
  1094. /* SQLITE_INTERRUPT */ "interrupted",
  1095. /* SQLITE_IOERR */ "disk I/O error",
  1096. /* SQLITE_CORRUPT */ "database disk image is malformed",
  1097. /* SQLITE_NOTFOUND */ "unknown operation",
  1098. /* SQLITE_FULL */ "database or disk is full",
  1099. /* SQLITE_CANTOPEN */ "unable to open database file",
  1100. /* SQLITE_PROTOCOL */ "locking protocol",
  1101. /* SQLITE_EMPTY */ "table contains no data",
  1102. /* SQLITE_SCHEMA */ "database schema has changed",
  1103. /* SQLITE_TOOBIG */ "string or blob too big",
  1104. /* SQLITE_CONSTRAINT */ "constraint failed",
  1105. /* SQLITE_MISMATCH */ "datatype mismatch",
  1106. /* SQLITE_MISUSE */ "library routine called out of sequence",
  1107. /* SQLITE_NOLFS */ "large file support is disabled",
  1108. /* SQLITE_AUTH */ "authorization denied",
  1109. /* SQLITE_FORMAT */ "auxiliary database format error",
  1110. /* SQLITE_RANGE */ "bind or column index out of range",
  1111. /* SQLITE_NOTADB */ "file is encrypted or is not a database",
  1112. };
  1113. const char *zErr = "unknown error";
  1114. switch( rc ){
  1115. case SQLITE_ABORT_ROLLBACK: {
  1116. zErr = "abort due to ROLLBACK";
  1117. break;
  1118. }
  1119. default: {
  1120. rc &= 0xff;
  1121. if( ALWAYS(rc>=0) && rc<ArraySize(aMsg) && aMsg[rc]!=0 ){
  1122. zErr = aMsg[rc];
  1123. }
  1124. break;
  1125. }
  1126. }
  1127. return zErr;
  1128. }
  1129. /*
  1130. ** This routine implements a busy callback that sleeps and tries
  1131. ** again until a timeout value is reached. The timeout value is
  1132. ** an integer number of milliseconds passed in as the first
  1133. ** argument.
  1134. */
  1135. static int sqliteDefaultBusyCallback(
  1136. void *ptr, /* Database connection */
  1137. int count /* Number of times table has been busy */
  1138. ){
  1139. #if SQLITE_OS_WIN || (defined(HAVE_USLEEP) && HAVE_USLEEP)
  1140. static const u8 delays[] =
  1141. { 1, 2, 5, 10, 15, 20, 25, 25, 25, 50, 50, 100 };
  1142. static const u8 totals[] =
  1143. { 0, 1, 3, 8, 18, 33, 53, 78, 103, 128, 178, 228 };
  1144. # define NDELAY ArraySize(delays)
  1145. sqlite3 *db = (sqlite3 *)ptr;
  1146. int timeout = db->busyTimeout;
  1147. int delay, prior;
  1148. assert( count>=0 );
  1149. if( count < NDELAY ){
  1150. delay = delays[count];
  1151. prior = totals[count];
  1152. }else{
  1153. delay = delays[NDELAY-1];
  1154. prior = totals[NDELAY-1] + delay*(count-(NDELAY-1));
  1155. }
  1156. if( prior + delay > timeout ){
  1157. delay = timeout - prior;
  1158. if( delay<=0 ) return 0;
  1159. }
  1160. sqlite3OsSleep(db->pVfs, delay*1000);
  1161. return 1;
  1162. #else
  1163. sqlite3 *db = (sqlite3 *)ptr;
  1164. int timeout = ((sqlite3 *)ptr)->busyTimeout;
  1165. if( (count+1)*1000 > timeout ){
  1166. return 0;
  1167. }
  1168. sqlite3OsSleep(db->pVfs, 1000000);
  1169. return 1;
  1170. #endif
  1171. }
  1172. /*
  1173. ** Invoke the given busy handler.
  1174. **
  1175. ** This routine is called when an operation failed with a lock.
  1176. ** If this routine returns non-zero, the lock is retried. If it
  1177. ** returns 0, the operation aborts with an SQLITE_BUSY error.
  1178. */
  1179. int sqlite3InvokeBusyHandler(BusyHandler *p){
  1180. int rc;
  1181. if( NEVER(p==0) || p->xFunc==0 || p->nBusy<0 ) return 0;
  1182. rc = p->xFunc(p->pArg, p->nBusy);
  1183. if( rc==0 ){
  1184. p->nBusy = -1;
  1185. }else{
  1186. p->nBusy++;
  1187. }
  1188. return rc;
  1189. }
  1190. /*
  1191. ** This routine sets the busy callback for an Sqlite database to the
  1192. ** given callback function with the given argument.
  1193. */
  1194. int sqlite3_busy_handler(
  1195. sqlite3 *db,
  1196. int (*xBusy)(void*,int),
  1197. void *pArg
  1198. ){
  1199. sqlite3_mutex_enter(db->mutex);
  1200. db->busyHandler.xFunc = xBusy;
  1201. db->busyHandler.pArg = pArg;
  1202. db->busyHandler.nBusy = 0;
  1203. db->busyTimeout = 0;
  1204. sqlite3_mutex_leave(db->mutex);
  1205. return SQLITE_OK;
  1206. }
  1207. #ifndef SQLITE_OMIT_PROGRESS_CALLBACK
  1208. /*
  1209. ** This routine sets the progress callback for an Sqlite database to the
  1210. ** given callback function with the given argument. The progress callback will
  1211. ** be invoked every nOps opcodes.
  1212. */
  1213. void sqlite3_progress_handler(
  1214. sqlite3 *db,
  1215. int nOps,
  1216. int (*xProgress)(void*),
  1217. void *pArg
  1218. ){
  1219. sqlite3_mutex_enter(db->mutex);
  1220. if( nOps>0 ){
  1221. db->xProgress = xProgress;
  1222. db->nProgressOps = (unsigned)nOps;
  1223. db->pProgressArg = pArg;
  1224. }else{
  1225. db->xProgress = 0;
  1226. db->nProgressOps = 0;
  1227. db->pProgressArg = 0;
  1228. }
  1229. sqlite3_mutex_leave(db->mutex);
  1230. }
  1231. #endif
  1232. /*
  1233. ** This routine installs a default busy handler that waits for the
  1234. ** specified number of milliseconds before returning 0.
  1235. */
  1236. int sqlite3_busy_timeout(sqlite3 *db, int ms){
  1237. if( ms>0 ){
  1238. sqlite3_busy_handler(db, sqliteDefaultBusyCallback, (void*)db);
  1239. db->busyTimeout = ms;
  1240. }else{
  1241. sqlite3_busy_handler(db, 0, 0);
  1242. }
  1243. return SQLITE_OK;
  1244. }
  1245. /*
  1246. ** Cause any pending operation to stop at its earliest opportunity.
  1247. */
  1248. void sqlite3_interrupt(sqlite3 *db){
  1249. db->u1.isInterrupted = 1;
  1250. }
  1251. /*
  1252. ** This function is exactly the same as sqlite3_create_function(), except
  1253. ** that it is designed to be called by internal code. The difference is
  1254. ** that if a malloc() fails in sqlite3_create_function(), an error code
  1255. ** is returned and the mallocFailed flag cleared.
  1256. */
  1257. int sqlite3CreateFunc(
  1258. sqlite3 *db,
  1259. const char *zFunctionName,
  1260. int nArg,
  1261. int enc,
  1262. void *pUserData,
  1263. void (*xFunc)(sqlite3_context*,int,sqlite3_value **),
  1264. void (*xStep)(sqlite3_context*,int,sqlite3_value **),
  1265. void (*xFinal)(sqlite3_context*),
  1266. FuncDestructor *pDestructor
  1267. ){
  1268. FuncDef *p;
  1269. int nName;
  1270. assert( sqlite3_mutex_held(db->mutex) );
  1271. if( zFunctionName==0 ||
  1272. (xFunc && (xFinal || xStep)) ||
  1273. (!xFunc && (xFinal && !xStep)) ||
  1274. (!xFunc && (!xFinal && xStep)) ||
  1275. (nArg<-1 || nArg>SQLITE_MAX_FUNCTION_ARG) ||
  1276. (255<(nName = sqlite3Strlen30( zFunctionName))) ){
  1277. return SQLITE_MISUSE_BKPT;
  1278. }
  1279. #ifndef SQLITE_OMIT_UTF16
  1280. /* If SQLITE_UTF16 is specified as the encoding type, transform this
  1281. ** to one of SQLITE_UTF16LE or SQLITE_UTF16BE using the
  1282. ** SQLITE_UTF16NATIVE macro. SQLITE_UTF16 is not used internally.
  1283. **
  1284. ** If SQLITE_ANY is specified, add three versions of the function
  1285. ** to the hash table.
  1286. */
  1287. if( enc==SQLITE_UTF16 ){
  1288. enc = SQLITE_UTF16NATIVE;
  1289. }else if( enc==SQLITE_ANY ){
  1290. int rc;
  1291. rc = sqlite3CreateFunc(db, zFunctionName, nArg, SQLITE_UTF8,
  1292. pUserData, xFunc, xStep, xFinal, pDestructor);
  1293. if( rc==SQLITE_OK ){
  1294. rc = sqlite3CreateFunc(db, zFunctionName, nArg, SQLITE_UTF16LE,
  1295. pUserData, xFunc, xStep, xFinal, pDestructor);
  1296. }
  1297. if( rc!=SQLITE_OK ){
  1298. return rc;
  1299. }
  1300. enc = SQLITE_UTF16BE;
  1301. }
  1302. #else
  1303. enc = SQLITE_UTF8;
  1304. #endif
  1305. /* Check if an existing function is being overridden or deleted. If so,
  1306. ** and there are active VMs, then return SQLITE_BUSY. If a function
  1307. ** is being overridden/deleted but there are no active VMs, allow the
  1308. ** operation to continue but invalidate all precompiled statements.
  1309. */
  1310. p = sqlite3FindFunction(db, zFunctionName, nName, nArg, (u8)enc, 0);
  1311. if( p && (p->funcFlags & SQLITE_FUNC_ENCMASK)==enc && p->nArg==nArg ){
  1312. if( db->nVdbeActive ){
  1313. sqlite3Error(db, SQLITE_BUSY,
  1314. "unable to delete/modify user-function due to active statements");
  1315. assert( !db->mallocFailed );
  1316. return SQLITE_BUSY;
  1317. }else{
  1318. sqlite3ExpirePreparedStatements(db);
  1319. }
  1320. }
  1321. p = sqlite3FindFunction(db, zFunctionName, nName, nArg, (u8)enc, 1);
  1322. assert(p || db->mallocFailed);
  1323. if( !p ){
  1324. return SQLITE_NOMEM;
  1325. }
  1326. /* If an older version of the function with a configured destructor is
  1327. ** being replaced invoke the destructor function here. */
  1328. functionDestroy(db, p);
  1329. if( pDestructor ){
  1330. pDestructor->nRef++;
  1331. }
  1332. p->pDestructor = pDestructor;
  1333. p->funcFlags &= SQLITE_FUNC_ENCMASK;
  1334. p->xFunc = xFunc;
  1335. p->xStep = xStep;
  1336. p->xFinalize = xFinal;
  1337. p->pUserData = pUserData;
  1338. p->nArg = (u16)nArg;
  1339. return SQLITE_OK;
  1340. }
  1341. /*
  1342. ** Create new user functions.
  1343. */
  1344. int sqlite3_create_function(
  1345. sqlite3 *db,
  1346. const char *zFunc,
  1347. int nArg,
  1348. int enc,
  1349. void *p,
  1350. void (*xFunc)(sqlite3_context*,int,sqlite3_value **),
  1351. void (*xStep)(sqlite3_context*,int,sqlite3_value **),
  1352. void (*xFinal)(sqlite3_context*)
  1353. ){
  1354. return sqlite3_create_function_v2(db, zFunc, nArg, enc, p, xFunc, xStep,
  1355. xFinal, 0);
  1356. }
  1357. int sqlite3_create_function_v2(
  1358. sqlite3 *db,
  1359. const char *zFunc,
  1360. int nArg,
  1361. int enc,
  1362. void *p,
  1363. void (*xFunc)(sqlite3_context*,int,sqlite3_value **),
  1364. void (*xStep)(sqlite3_context*,int,sqlite3_value **),
  1365. void (*xFinal)(sqlite3_context*),
  1366. void (*xDestroy)(void *)
  1367. ){
  1368. int rc = SQLITE_ERROR;
  1369. FuncDestructor *pArg = 0;
  1370. sqlite3_mutex_enter(db->mutex);
  1371. if( xDestroy ){
  1372. pArg = (FuncDestructor *)sqlite3DbMallocZero(db, sizeof(FuncDestructor));
  1373. if( !pArg ){
  1374. xDestroy(p);
  1375. goto out;
  1376. }
  1377. pArg->xDestroy = xDestroy;
  1378. pArg->pUserData = p;
  1379. }
  1380. rc = sqlite3CreateFunc(db, zFunc, nArg, enc, p, xFunc, xStep, xFinal, pArg);
  1381. if( pArg && pArg->nRef==0 ){
  1382. assert( rc!=SQLITE_OK );
  1383. xDestroy(p);
  1384. sqlite3DbFree(db, pArg);
  1385. }
  1386. out:
  1387. rc = sqlite3ApiExit(db, rc);
  1388. sqlite3_mutex_leave(db->mutex);
  1389. return rc;
  1390. }
  1391. #ifndef SQLITE_OMIT_UTF16
  1392. int sqlite3_create_function16(
  1393. sqlite3 *db,
  1394. const void *zFunctionName,
  1395. int nArg,
  1396. int eTextRep,
  1397. void *p,
  1398. void (*xFunc)(sqlite3_context*,int,sqlite3_value**),
  1399. void (*xStep)(sqlite3_context*,int,sqlite3_value**),
  1400. void (*xFinal)(sqlite3_context*)
  1401. ){
  1402. int rc;
  1403. char *zFunc8;
  1404. sqlite3_mutex_enter(db->mutex);
  1405. assert( !db->mallocFailed );
  1406. zFunc8 = sqlite3Utf16to8(db, zFunctionName, -1, SQLITE_UTF16NATIVE);
  1407. rc = sqlite3CreateFunc(db, zFunc8, nArg, eTextRep, p, xFunc, xStep, xFinal,0);
  1408. sqlite3DbFree(db, zFunc8);
  1409. rc = sqlite3ApiExit(db, rc);
  1410. sqlite3_mutex_leave(db->mutex);
  1411. return rc;
  1412. }
  1413. #endif
  1414. /*
  1415. ** Declare that a function has been overloaded by a virtual table.
  1416. **
  1417. ** If the function already exists as a regular global function, then
  1418. ** this routine is a no-op. If the function does not exist, then create
  1419. ** a new one that always throws a run-time error.
  1420. **
  1421. ** When virtual tables intend to provide an overloaded function, they
  1422. ** should call this routine to make sure the global function exists.
  1423. ** A global function must exist in order for name resolution to work
  1424. ** properly.
  1425. */
  1426. int sqlite3_overload_function(
  1427. sqlite3 *db,
  1428. const char *zName,
  1429. int nArg
  1430. ){
  1431. int nName = sqlite3Strlen30(zName);
  1432. int rc = SQLITE_OK;
  1433. sqlite3_mutex_enter(db->mutex);
  1434. if( sqlite3FindFunction(db, zName, nName, nArg, SQLITE_UTF8, 0)==0 ){
  1435. rc = sqlite3CreateFunc(db, zName, nArg, SQLITE_UTF8,
  1436. 0, sqlite3InvalidFunction, 0, 0, 0);
  1437. }
  1438. rc = sqlite3ApiExit(db, rc);
  1439. sqlite3_mutex_leave(db->mutex);
  1440. return rc;
  1441. }
  1442. #ifndef SQLITE_OMIT_TRACE
  1443. /*
  1444. ** Register a trace function. The pArg from the previously registered trace
  1445. ** is returned.
  1446. **
  1447. ** A NULL trace function means that no tracing is executes. A non-NULL
  1448. ** trace is a pointer to a function that is invoked at the start of each
  1449. ** SQL statement.
  1450. */
  1451. void *sqlite3_trace(sqlite3 *db, void (*xTrace)(void*,const char*), void *pArg){
  1452. void *pOld;
  1453. sqlite3_mutex_enter(db->mutex);
  1454. pOld = db->pTraceArg;
  1455. db->xTrace = xTrace;
  1456. db->pTraceArg = pArg;
  1457. sqlite3_mutex_leave(db->mutex);
  1458. return pOld;
  1459. }
  1460. /*
  1461. ** Register a profile function. The pArg from the previously registered
  1462. ** profile function is returned.
  1463. **
  1464. ** A NULL profile function means that no profiling is executes. A non-NULL
  1465. ** profile is a pointer to a function that is invoked at the conclusion of
  1466. ** each SQL statement that is run.
  1467. */
  1468. void *sqlite3_profile(
  1469. sqlite3 *db,
  1470. void (*xProfile)(void*,const char*,sqlite_uint64),
  1471. void *pArg
  1472. ){
  1473. void *pOld;
  1474. sqlite3_mutex_enter(db->mutex);
  1475. pOld = db->pProfileArg;
  1476. db->xProfile = xProfile;
  1477. db->pProfileArg = pArg;
  1478. sqlite3_mutex_leave(db->mutex);
  1479. return pOld;
  1480. }
  1481. #endif /* SQLITE_OMIT_TRACE */
  1482. /*
  1483. ** Register a function to be invoked when a transaction commits.
  1484. ** If the invoked function returns non-zero, then the commit becomes a
  1485. ** rollback.
  1486. */
  1487. void *sqlite3_commit_hook(
  1488. sqlite3 *db, /* Attach the hook to this database */
  1489. int (*xCallback)(void*), /* Function to invoke on each commit */
  1490. void *pArg /* Argument to the function */
  1491. ){
  1492. void *pOld;
  1493. sqlite3_mutex_enter(db->mutex);
  1494. pOld = db->pCommitArg;
  1495. db->xCommitCallback = xCallback;
  1496. db->pCommitArg = pArg;
  1497. sqlite3_mutex_leave(db->mutex);
  1498. return pOld;
  1499. }
  1500. /*
  1501. ** Register a callback to be invoked each time a row is updated,
  1502. ** inserted or deleted using this database connection.
  1503. */
  1504. void *sqlite3_update_hook(
  1505. sqlite3 *db, /* Attach the hook to this database */
  1506. void (*xCallback)(void*,int,char const *,char const *,sqlite_int64),
  1507. void *pArg /* Argument to the function */
  1508. ){
  1509. void *pRet;
  1510. sqlite3_mutex_enter(db->mutex);
  1511. pRet = db->pUpdateArg;
  1512. db->xUpdateCallback = xCallback;
  1513. db->pUpdateArg = pArg;
  1514. sqlite3_mutex_leave(db->mutex);
  1515. return pRet;
  1516. }
  1517. /*
  1518. ** Register a callback to be invoked each time a transaction is rolled
  1519. ** back by this database connection.
  1520. */
  1521. void *sqlite3_rollback_hook(
  1522. sqlite3 *db, /* Attach the hook to this database */
  1523. void (*xCallback)(void*), /* Callback function */
  1524. void *pArg /* Argument to the function */
  1525. ){
  1526. void *pRet;
  1527. sqlite3_mutex_enter(db->mutex);
  1528. pRet = db->pRollbackArg;
  1529. db->xRollbackCallback = xCallback;
  1530. db->pRollbackArg = pArg;
  1531. sqlite3_mutex_leave(db->mutex);
  1532. return pRet;
  1533. }
  1534. #ifndef SQLITE_OMIT_WAL
  1535. /*
  1536. ** The sqlite3_wal_hook() callback registered by sqlite3_wal_autocheckpoint().
  1537. ** Invoke sqlite3_wal_checkpoint if the number of frames in the log file
  1538. ** is greater than sqlite3.pWalArg cast to an integer (the value configured by
  1539. ** wal_autocheckpoint()).
  1540. */
  1541. int sqlite3WalDefaultHook(
  1542. void *pClientData, /* Argument */
  1543. sqlite3 *db, /* Connection */
  1544. const char *zDb, /* Database */
  1545. int nFrame /* Size of WAL */
  1546. ){
  1547. if( nFrame>=SQLITE_PTR_TO_INT(pClientData) ){
  1548. sqlite3BeginBenignMalloc();
  1549. sqlite3_wal_checkpoint(db, zDb);
  1550. sqlite3EndBenignMalloc();
  1551. }
  1552. return SQLITE_OK;
  1553. }
  1554. #endif /* SQLITE_OMIT_WAL */
  1555. /*
  1556. ** Configure an sqlite3_wal_hook() callback to automatically checkpoint
  1557. ** a database after committing a transaction if there are nFrame or
  1558. ** more frames in the log file. Passing zero or a negative value as the
  1559. ** nFrame parameter disables automatic checkpoints entirely.
  1560. **
  1561. ** The callback registered by this function replaces any existing callback
  1562. ** registered using sqlite3_wal_hook(). Likewise, registering a callback
  1563. ** using sqlite3_wal_hook() disables the automatic checkpoint mechanism
  1564. ** configured by this function.
  1565. */
  1566. int sqlite3_wal_autocheckpoint(sqlite3 *db, int nFrame){
  1567. #ifdef SQLITE_OMIT_WAL
  1568. UNUSED_PARAMETER(db);
  1569. UNUSED_PARAMETER(nFrame);
  1570. #else
  1571. if( nFrame>0 ){
  1572. sqlite3_wal_hook(db, sqlite3WalDefaultHook, SQLITE_INT_TO_PTR(nFrame));
  1573. }else{
  1574. sqlite3_wal_hook(db, 0, 0);
  1575. }
  1576. #endif
  1577. return SQLITE_OK;
  1578. }
  1579. /*
  1580. ** Register a callback to be invoked each time a transaction is written
  1581. ** into the write-ahead-log by this database connection.
  1582. */
  1583. void *sqlite3_wal_hook(
  1584. sqlite3 *db, /* Attach the hook to this db handle */
  1585. int(*xCallback)(void *, sqlite3*, const char*, int),
  1586. void *pArg /* First argument passed to xCallback() */
  1587. ){
  1588. #ifndef SQLITE_OMIT_WAL
  1589. void *pRet;
  1590. sqlite3_mutex_enter(db->mutex);
  1591. pRet = db->pWalArg;
  1592. db->xWalCallback = xCallback;
  1593. db->pWalArg = pArg;
  1594. sqlite3_mutex_leave(db->mutex);
  1595. return pRet;
  1596. #else
  1597. return 0;
  1598. #endif
  1599. }
  1600. /*
  1601. ** Checkpoint database zDb.
  1602. */
  1603. int sqlite3_wal_checkpoint_v2(
  1604. sqlite3 *db, /* Database handle */
  1605. const char *zDb, /* Name of attached database (or NULL) */
  1606. int eMode, /* SQLITE_CHECKPOINT_* value */
  1607. int *pnLog, /* OUT: Size of WAL log in frames */
  1608. int *pnCkpt /* OUT: Total number of frames checkpointed */
  1609. ){
  1610. #ifdef SQLITE_OMIT_WAL
  1611. return SQLITE_OK;
  1612. #else
  1613. int rc; /* Return code */
  1614. int iDb = SQLITE_MAX_ATTACHED; /* sqlite3.aDb[] index of db to checkpoint */
  1615. /* Initialize the output variables to -1 in case an error occurs. */
  1616. if( pnLog ) *pnLog = -1;
  1617. if( pnCkpt ) *pnCkpt = -1;
  1618. assert( SQLITE_CHECKPOINT_FULL>SQLITE_CHECKPOINT_PASSIVE );
  1619. assert( SQLITE_CHECKPOINT_FULL<SQLITE_CHECKPOINT_RESTART );
  1620. assert( SQLITE_CHECKPOINT_PASSIVE+2==SQLITE_CHECKPOINT_RESTART );
  1621. if( eMode<SQLITE_CHECKPOINT_PASSIVE || eMode>SQLITE_CHECKPOINT_RESTART ){
  1622. return SQLITE_MISUSE;
  1623. }
  1624. sqlite3_mutex_enter(db->mutex);
  1625. if( zDb && zDb[0] ){
  1626. iDb = sqlite3FindDbName(db, zDb);
  1627. }
  1628. if( iDb<0 ){
  1629. rc = SQLITE_ERROR;
  1630. sqlite3Error(db, SQLITE_ERROR, "unknown database: %s", zDb);
  1631. }else{
  1632. rc = sqlite3Checkpoint(db, iDb, eMode, pnLog, pnCkpt);
  1633. sqlite3Error(db, rc, 0);
  1634. }
  1635. rc = sqlite3ApiExit(db, rc);
  1636. sqlite3_mutex_leave(db->mutex);
  1637. return rc;
  1638. #endif
  1639. }
  1640. /*
  1641. ** Checkpoint database zDb. If zDb is NULL, or if the buffer zDb points
  1642. ** to contains a zero-length string, all attached databases are
  1643. ** checkpointed.
  1644. */
  1645. int sqlite3_wal_checkpoint(sqlite3 *db, const char *zDb){
  1646. return sqlite3_wal_checkpoint_v2(db, zDb, SQLITE_CHECKPOINT_PASSIVE, 0, 0);
  1647. }
  1648. #ifndef SQLITE_OMIT_WAL
  1649. /*
  1650. ** Run a checkpoint on database iDb. This is a no-op if database iDb is
  1651. ** not currently open in WAL mode.
  1652. **
  1653. ** If a transaction is open on the database being checkpointed, this
  1654. ** function returns SQLITE_LOCKED and a checkpoint is not attempted. If
  1655. ** an error occurs while running the checkpoint, an SQLite error code is
  1656. ** returned (i.e. SQLITE_IOERR). Otherwise, SQLITE_OK.
  1657. **
  1658. ** The mutex on database handle db should be held by the caller. The mutex
  1659. ** associated with the specific b-tree being checkpointed is taken by
  1660. ** this function while the checkpoint is running.
  1661. **
  1662. ** If iDb is passed SQLITE_MAX_ATTACHED, then all attached databases are
  1663. ** checkpointed. If an error is encountered it is returned immediately -
  1664. ** no attempt is made to checkpoint any remaining databases.
  1665. **
  1666. ** Parameter eMode is one of SQLITE_CHECKPOINT_PASSIVE, FULL or RESTART.
  1667. */
  1668. int sqlite3Checkpoint(sqlite3 *db, int iDb, int eMode, int *pnLog, int *pnCkpt){
  1669. int rc = SQLITE_OK; /* Return code */
  1670. int i; /* Used to iterate through attached dbs */
  1671. int bBusy = 0; /* True if SQLITE_BUSY has been encountered */
  1672. assert( sqlite3_mutex_held(db->mutex) );
  1673. assert( !pnLog || *pnLog==-1 );
  1674. assert( !pnCkpt || *pnCkpt==-1 );
  1675. for(i=0; i<db->nDb && rc==SQLITE_OK; i++){
  1676. if( i==iDb || iDb==SQLITE_MAX_ATTACHED ){
  1677. rc = sqlite3BtreeCheckpoint(db->aDb[i].pBt, eMode, pnLog, pnCkpt);
  1678. pnLog = 0;
  1679. pnCkpt = 0;
  1680. if( rc==SQLITE_BUSY ){
  1681. bBusy = 1;
  1682. rc = SQLITE_OK;
  1683. }
  1684. }
  1685. }
  1686. return (rc==SQLITE_OK && bBusy) ? SQLITE_BUSY : rc;
  1687. }
  1688. #endif /* SQLITE_OMIT_WAL */
  1689. /*
  1690. ** This function returns true if main-memory should be used instead of
  1691. ** a temporary file for transient pager files and statement journals.
  1692. ** The value returned depends on the value of db->temp_store (runtime
  1693. ** parameter) and the compile time value of SQLITE_TEMP_STORE. The
  1694. ** following table describes the relationship between these two values
  1695. ** and this functions return value.
  1696. **
  1697. ** SQLITE_TEMP_STORE db->temp_store Location of temporary database
  1698. ** ----------------- -------------- ------------------------------
  1699. ** 0 any file (return 0)
  1700. ** 1 1 file (return 0)
  1701. ** 1 2 memory (return 1)
  1702. ** 1 0 file (return 0)
  1703. ** 2 1 file (return 0)
  1704. ** 2 2 memory (return 1)
  1705. ** 2 0 memory (return 1)
  1706. ** 3 any memory (return 1)
  1707. */
  1708. int sqlite3TempInMemory(const sqlite3 *db){
  1709. #if SQLITE_TEMP_STORE==1
  1710. return ( db->temp_store==2 );
  1711. #endif
  1712. #if SQLITE_TEMP_STORE==2
  1713. return ( db->temp_store!=1 );
  1714. #endif
  1715. #if SQLITE_TEMP_STORE==3
  1716. return 1;
  1717. #endif
  1718. #if SQLITE_TEMP_STORE<1 || SQLITE_TEMP_STORE>3
  1719. return 0;
  1720. #endif
  1721. }
  1722. /*
  1723. ** Return UTF-8 encoded English language explanation of the most recent
  1724. ** error.
  1725. */
  1726. const char *sqlite3_errmsg(sqlite3 *db){
  1727. const char *z;
  1728. if( !db ){
  1729. return sqlite3ErrStr(SQLITE_NOMEM);
  1730. }
  1731. if( !sqlite3SafetyCheckSickOrOk(db) ){
  1732. return sqlite3ErrStr(SQLITE_MISUSE_BKPT);
  1733. }
  1734. sqlite3_mutex_enter(db->mutex);
  1735. if( db->mallocFailed ){
  1736. z = sqlite3ErrStr(SQLITE_NOMEM);
  1737. }else{
  1738. z = (char*)sqlite3_value_text(db->pErr);
  1739. assert( !db->mallocFailed );
  1740. if( z==0 ){
  1741. z = sqlite3ErrStr(db->errCode);
  1742. }
  1743. }
  1744. sqlite3_mutex_leave(db->mutex);
  1745. return z;
  1746. }
  1747. #ifndef SQLITE_OMIT_UTF16
  1748. /*
  1749. ** Return UTF-16 encoded English language explanation of the most recent
  1750. ** error.
  1751. */
  1752. const void *sqlite3_errmsg16(sqlite3 *db){
  1753. static const u16 outOfMem[] = {
  1754. 'o', 'u', 't', ' ', 'o', 'f', ' ', 'm', 'e', 'm', 'o', 'r', 'y', 0
  1755. };
  1756. static const u16 misuse[] = {
  1757. 'l', 'i', 'b', 'r', 'a', 'r', 'y', ' ',
  1758. 'r', 'o', 'u', 't', 'i', 'n', 'e', ' ',
  1759. 'c', 'a', 'l', 'l', 'e', 'd', ' ',
  1760. 'o', 'u', 't', ' ',
  1761. 'o', 'f', ' ',
  1762. 's', 'e', 'q', 'u', 'e', 'n', 'c', 'e', 0
  1763. };
  1764. const void *z;
  1765. if( !db ){
  1766. return (void *)outOfMem;
  1767. }
  1768. if( !sqlite3SafetyCheckSickOrOk(db) ){
  1769. return (void *)misuse;
  1770. }
  1771. sqlite3_mutex_enter(db->mutex);
  1772. if( db->mallocFailed ){
  1773. z = (void *)outOfMem;
  1774. }else{
  1775. z = sqlite3_value_text16(db->pErr);
  1776. if( z==0 ){
  1777. sqlite3ValueSetStr(db->pErr, -1, sqlite3ErrStr(db->errCode),
  1778. SQLITE_UTF8, SQLITE_STATIC);
  1779. z = sqlite3_value_text16(db->pErr);
  1780. }
  1781. /* A malloc() may have failed within the call to sqlite3_value_text16()
  1782. ** above. If this is the case, then the db->mallocFailed flag needs to
  1783. ** be cleared before returning. Do this directly, instead of via
  1784. ** sqlite3ApiExit(), to avoid setting the database handle error message.
  1785. */
  1786. db->mallocFailed = 0;
  1787. }
  1788. sqlite3_mutex_leave(db->mutex);
  1789. return z;
  1790. }
  1791. #endif /* SQLITE_OMIT_UTF16 */
  1792. /*
  1793. ** Return the most recent error code generated by an SQLite routine. If NULL is
  1794. ** passed to this function, we assume a malloc() failed during sqlite3_open().
  1795. */
  1796. int sqlite3_errcode(sqlite3 *db){
  1797. if( db && !sqlite3SafetyCheckSickOrOk(db) ){
  1798. return SQLITE_MISUSE_BKPT;
  1799. }
  1800. if( !db || db->mallocFailed ){
  1801. return SQLITE_NOMEM;
  1802. }
  1803. return db->errCode & db->errMask;
  1804. }
  1805. int sqlite3_extended_errcode(sqlite3 *db){
  1806. if( db && !sqlite3SafetyCheckSickOrOk(db) ){
  1807. return SQLITE_MISUSE_BKPT;
  1808. }
  1809. if( !db || db->mallocFailed ){
  1810. return SQLITE_NOMEM;
  1811. }
  1812. return db->errCode;
  1813. }
  1814. /*
  1815. ** Return a string that describes the kind of error specified in the
  1816. ** argument. For now, this simply calls the internal sqlite3ErrStr()
  1817. ** function.
  1818. */
  1819. const char *sqlite3_errstr(int rc){
  1820. return sqlite3ErrStr(rc);
  1821. }
  1822. /*
  1823. ** Create a new collating function for database "db". The name is zName
  1824. ** and the encoding is enc.
  1825. */
  1826. static int createCollation(
  1827. sqlite3* db,
  1828. const char *zName,
  1829. u8 enc,
  1830. void* pCtx,
  1831. int(*xCompare)(void*,int,const void*,int,const void*),
  1832. void(*xDel)(void*)
  1833. ){
  1834. CollSeq *pColl;
  1835. int enc2;
  1836. int nName = sqlite3Strlen30(zName);
  1837. assert( sqlite3_mutex_held(db->mutex) );
  1838. /* If SQLITE_UTF16 is specified as the encoding type, transform this
  1839. ** to one of SQLITE_UTF16LE or SQLITE_UTF16BE using the
  1840. ** SQLITE_UTF16NATIVE macro. SQLITE_UTF16 is not used internally.
  1841. */
  1842. enc2 = enc;
  1843. testcase( enc2==SQLITE_UTF16 );
  1844. testcase( enc2==SQLITE_UTF16_ALIGNED );
  1845. if( enc2==SQLITE_UTF16 || enc2==SQLITE_UTF16_ALIGNED ){
  1846. enc2 = SQLITE_UTF16NATIVE;
  1847. }
  1848. if( enc2<SQLITE_UTF8 || enc2>SQLITE_UTF16BE ){
  1849. return SQLITE_MISUSE_BKPT;
  1850. }
  1851. /* Check if this call is removing or replacing an existing collation
  1852. ** sequence. If so, and there are active VMs, return busy. If there
  1853. ** are no active VMs, invalidate any pre-compiled statements.
  1854. */
  1855. pColl = sqlite3FindCollSeq(db, (u8)enc2, zName, 0);
  1856. if( pColl && pColl->xCmp ){
  1857. if( db->nVdbeActive ){
  1858. sqlite3Error(db, SQLITE_BUSY,
  1859. "unable to delete/modify collation sequence due to active statements");
  1860. return SQLITE_BUSY;
  1861. }
  1862. sqlite3ExpirePreparedStatements(db);
  1863. /* If collation sequence pColl was created directly by a call to
  1864. ** sqlite3_create_collation, and not generated by synthCollSeq(),
  1865. ** then any copies made by synthCollSeq() need to be invalidated.
  1866. ** Also, collation destructor - CollSeq.xDel() - function may need
  1867. ** to be called.
  1868. */
  1869. if( (pColl->enc & ~SQLITE_UTF16_ALIGNED)==enc2 ){
  1870. CollSeq *aColl = sqlite3HashFind(&db->aCollSeq, zName, nName);
  1871. int j;
  1872. for(j=0; j<3; j++){
  1873. CollSeq *p = &aColl[j];
  1874. if( p->enc==pColl->enc ){
  1875. if( p->xDel ){
  1876. p->xDel(p->pUser);
  1877. }
  1878. p->xCmp = 0;
  1879. }
  1880. }
  1881. }
  1882. }
  1883. pColl = sqlite3FindCollSeq(db, (u8)enc2, zName, 1);
  1884. if( pColl==0 ) return SQLITE_NOMEM;
  1885. pColl->xCmp = xCompare;
  1886. pColl->pUser = pCtx;
  1887. pColl->xDel = xDel;
  1888. pColl->enc = (u8)(enc2 | (enc & SQLITE_UTF16_ALIGNED));
  1889. sqlite3Error(db, SQLITE_OK, 0);
  1890. return SQLITE_OK;
  1891. }
  1892. /*
  1893. ** This array defines hard upper bounds on limit values. The
  1894. ** initializer must be kept in sync with the SQLITE_LIMIT_*
  1895. ** #defines in sqlite3.h.
  1896. */
  1897. static const int aHardLimit[] = {
  1898. SQLITE_MAX_LENGTH,
  1899. SQLITE_MAX_SQL_LENGTH,
  1900. SQLITE_MAX_COLUMN,
  1901. SQLITE_MAX_EXPR_DEPTH,
  1902. SQLITE_MAX_COMPOUND_SELECT,
  1903. SQLITE_MAX_VDBE_OP,
  1904. SQLITE_MAX_FUNCTION_ARG,
  1905. SQLITE_MAX_ATTACHED,
  1906. SQLITE_MAX_LIKE_PATTERN_LENGTH,
  1907. SQLITE_MAX_VARIABLE_NUMBER,
  1908. SQLITE_MAX_TRIGGER_DEPTH,
  1909. };
  1910. /*
  1911. ** Make sure the hard limits are set to reasonable values
  1912. */
  1913. #if SQLITE_MAX_LENGTH<100
  1914. # error SQLITE_MAX_LENGTH must be at least 100
  1915. #endif
  1916. #if SQLITE_MAX_SQL_LENGTH<100
  1917. # error SQLITE_MAX_SQL_LENGTH must be at least 100
  1918. #endif
  1919. #if SQLITE_MAX_SQL_LENGTH>SQLITE_MAX_LENGTH
  1920. # error SQLITE_MAX_SQL_LENGTH must not be greater than SQLITE_MAX_LENGTH
  1921. #endif
  1922. #if SQLITE_MAX_COMPOUND_SELECT<2
  1923. # error SQLITE_MAX_COMPOUND_SELECT must be at least 2
  1924. #endif
  1925. #if SQLITE_MAX_VDBE_OP<40
  1926. # error SQLITE_MAX_VDBE_OP must be at least 40
  1927. #endif
  1928. #if SQLITE_MAX_FUNCTION_ARG<0 || SQLITE_MAX_FUNCTION_ARG>1000
  1929. # error SQLITE_MAX_FUNCTION_ARG must be between 0 and 1000
  1930. #endif
  1931. #if SQLITE_MAX_ATTACHED<0 || SQLITE_MAX_ATTACHED>62
  1932. # error SQLITE_MAX_ATTACHED must be between 0 and 62
  1933. #endif
  1934. #if SQLITE_MAX_LIKE_PATTERN_LENGTH<1
  1935. # error SQLITE_MAX_LIKE_PATTERN_LENGTH must be at least 1
  1936. #endif
  1937. #if SQLITE_MAX_COLUMN>32767
  1938. # error SQLITE_MAX_COLUMN must not exceed 32767
  1939. #endif
  1940. #if SQLITE_MAX_TRIGGER_DEPTH<1
  1941. # error SQLITE_MAX_TRIGGER_DEPTH must be at least 1
  1942. #endif
  1943. /*
  1944. ** Change the value of a limit. Report the old value.
  1945. ** If an invalid limit index is supplied, report -1.
  1946. ** Make no changes but still report the old value if the
  1947. ** new limit is negative.
  1948. **
  1949. ** A new lower limit does not shrink existing constructs.
  1950. ** It merely prevents new constructs that exceed the limit
  1951. ** from forming.
  1952. */
  1953. int sqlite3_limit(sqlite3 *db, int limitId, int newLimit){
  1954. int oldLimit;
  1955. /* EVIDENCE-OF: R-30189-54097 For each limit category SQLITE_LIMIT_NAME
  1956. ** there is a hard upper bound set at compile-time by a C preprocessor
  1957. ** macro called SQLITE_MAX_NAME. (The "_LIMIT_" in the name is changed to
  1958. ** "_MAX_".)
  1959. */
  1960. assert( aHardLimit[SQLITE_LIMIT_LENGTH]==SQLITE_MAX_LENGTH );
  1961. assert( aHardLimit[SQLITE_LIMIT_SQL_LENGTH]==SQLITE_MAX_SQL_LENGTH );
  1962. assert( aHardLimit[SQLITE_LIMIT_COLUMN]==SQLITE_MAX_COLUMN );
  1963. assert( aHardLimit[SQLITE_LIMIT_EXPR_DEPTH]==SQLITE_MAX_EXPR_DEPTH );
  1964. assert( aHardLimit[SQLITE_LIMIT_COMPOUND_SELECT]==SQLITE_MAX_COMPOUND_SELECT);
  1965. assert( aHardLimit[SQLITE_LIMIT_VDBE_OP]==SQLITE_MAX_VDBE_OP );
  1966. assert( aHardLimit[SQLITE_LIMIT_FUNCTION_ARG]==SQLITE_MAX_FUNCTION_ARG );
  1967. assert( aHardLimit[SQLITE_LIMIT_ATTACHED]==SQLITE_MAX_ATTACHED );
  1968. assert( aHardLimit[SQLITE_LIMIT_LIKE_PATTERN_LENGTH]==
  1969. SQLITE_MAX_LIKE_PATTERN_LENGTH );
  1970. assert( aHardLimit[SQLITE_LIMIT_VARIABLE_NUMBER]==SQLITE_MAX_VARIABLE_NUMBER);
  1971. assert( aHardLimit[SQLITE_LIMIT_TRIGGER_DEPTH]==SQLITE_MAX_TRIGGER_DEPTH );
  1972. assert( SQLITE_LIMIT_TRIGGER_DEPTH==(SQLITE_N_LIMIT-1) );
  1973. if( limitId<0 || limitId>=SQLITE_N_LIMIT ){
  1974. return -1;
  1975. }
  1976. oldLimit = db->aLimit[limitId];
  1977. if( newLimit>=0 ){ /* IMP: R-52476-28732 */
  1978. if( newLimit>aHardLimit[limitId] ){
  1979. newLimit = aHardLimit[limitId]; /* IMP: R-51463-25634 */
  1980. }
  1981. db->aLimit[limitId] = newLimit;
  1982. }
  1983. return oldLimit; /* IMP: R-53341-35419 */
  1984. }
  1985. /*
  1986. ** This function is used to parse both URIs and non-URI filenames passed by the
  1987. ** user to API functions sqlite3_open() or sqlite3_open_v2(), and for database
  1988. ** URIs specified as part of ATTACH statements.
  1989. **
  1990. ** The first argument to this function is the name of the VFS to use (or
  1991. ** a NULL to signify the default VFS) if the URI does not contain a "vfs=xxx"
  1992. ** query parameter. The second argument contains the URI (or non-URI filename)
  1993. ** itself. When this function is called the *pFlags variable should contain
  1994. ** the default flags to open the database handle with. The value stored in
  1995. ** *pFlags may be updated before returning if the URI filename contains
  1996. ** "cache=xxx" or "mode=xxx" query parameters.
  1997. **
  1998. ** If successful, SQLITE_OK is returned. In this case *ppVfs is set to point to
  1999. ** the VFS that should be used to open the database file. *pzFile is set to
  2000. ** point to a buffer containing the name of the file to open. It is the
  2001. ** responsibility of the caller to eventually call sqlite3_free() to release
  2002. ** this buffer.
  2003. **
  2004. ** If an error occurs, then an SQLite error code is returned and *pzErrMsg
  2005. ** may be set to point to a buffer containing an English language error
  2006. ** message. It is the responsibility of the caller to eventually release
  2007. ** this buffer by calling sqlite3_free().
  2008. */
  2009. int sqlite3ParseUri(
  2010. const char *zDefaultVfs, /* VFS to use if no "vfs=xxx" query option */
  2011. const char *zUri, /* Nul-terminated URI to parse */
  2012. unsigned int *pFlags, /* IN/OUT: SQLITE_OPEN_XXX flags */
  2013. sqlite3_vfs **ppVfs, /* OUT: VFS to use */
  2014. char **pzFile, /* OUT: Filename component of URI */
  2015. char **pzErrMsg /* OUT: Error message (if rc!=SQLITE_OK) */
  2016. ){
  2017. int rc = SQLITE_OK;
  2018. unsigned int flags = *pFlags;
  2019. const char *zVfs = zDefaultVfs;
  2020. char *zFile;
  2021. char c;
  2022. int nUri = sqlite3Strlen30(zUri);
  2023. assert( *pzErrMsg==0 );
  2024. if( ((flags & SQLITE_OPEN_URI) || sqlite3GlobalConfig.bOpenUri)
  2025. && nUri>=5 && memcmp(zUri, "file:", 5)==0
  2026. ){
  2027. char *zOpt;
  2028. int eState; /* Parser state when parsing URI */
  2029. int iIn; /* Input character index */
  2030. int iOut = 0; /* Output character index */
  2031. int nByte = nUri+2; /* Bytes of space to allocate */
  2032. /* Make sure the SQLITE_OPEN_URI flag is set to indicate to the VFS xOpen
  2033. ** method that there may be extra parameters following the file-name. */
  2034. flags |= SQLITE_OPEN_URI;
  2035. for(iIn=0; iIn<nUri; iIn++) nByte += (zUri[iIn]=='&');
  2036. zFile = sqlite3_malloc(nByte);
  2037. if( !zFile ) return SQLITE_NOMEM;
  2038. iIn = 5;
  2039. #ifndef SQLITE_ALLOW_URI_AUTHORITY
  2040. /* Discard the scheme and authority segments of the URI. */
  2041. if( zUri[5]=='/' && zUri[6]=='/' ){
  2042. iIn = 7;
  2043. while( zUri[iIn] && zUri[iIn]!='/' ) iIn++;
  2044. if( iIn!=7 && (iIn!=16 || memcmp("localhost", &zUri[7], 9)) ){
  2045. *pzErrMsg = sqlite3_mprintf("invalid uri authority: %.*s",
  2046. iIn-7, &zUri[7]);
  2047. rc = SQLITE_ERROR;
  2048. goto parse_uri_out;
  2049. }
  2050. }
  2051. #endif
  2052. /* Copy the filename and any query parameters into the zFile buffer.
  2053. ** Decode %HH escape codes along the way.
  2054. **
  2055. ** Within this loop, variable eState may be set to 0, 1 or 2, depending
  2056. ** on the parsing context. As follows:
  2057. **
  2058. ** 0: Parsing file-name.
  2059. ** 1: Parsing name section of a name=value query parameter.
  2060. ** 2: Parsing value section of a name=value query parameter.
  2061. */
  2062. eState = 0;
  2063. while( (c = zUri[iIn])!=0 && c!='#' ){
  2064. iIn++;
  2065. if( c=='%'
  2066. && sqlite3Isxdigit(zUri[iIn])
  2067. && sqlite3Isxdigit(zUri[iIn+1])
  2068. ){
  2069. int octet = (sqlite3HexToInt(zUri[iIn++]) << 4);
  2070. octet += sqlite3HexToInt(zUri[iIn++]);
  2071. assert( octet>=0 && octet<256 );
  2072. if( octet==0 ){
  2073. /* This branch is taken when "%00" appears within the URI. In this
  2074. ** case we ignore all text in the remainder of the path, name or
  2075. ** value currently being parsed. So ignore the current character
  2076. ** and skip to the next "?", "=" or "&", as appropriate. */
  2077. while( (c = zUri[iIn])!=0 && c!='#'
  2078. && (eState!=0 || c!='?')
  2079. && (eState!=1 || (c!='=' && c!='&'))
  2080. && (eState!=2 || c!='&')
  2081. ){
  2082. iIn++;
  2083. }
  2084. continue;
  2085. }
  2086. c = octet;
  2087. }else if( eState==1 && (c=='&' || c=='=') ){
  2088. if( zFile[iOut-1]==0 ){
  2089. /* An empty option name. Ignore this option altogether. */
  2090. while( zUri[iIn] && zUri[iIn]!='#' && zUri[iIn-1]!='&' ) iIn++;
  2091. continue;
  2092. }
  2093. if( c=='&' ){
  2094. zFile[iOut++] = '\0';
  2095. }else{
  2096. eState = 2;
  2097. }
  2098. c = 0;
  2099. }else if( (eState==0 && c=='?') || (eState==2 && c=='&') ){
  2100. c = 0;
  2101. eState = 1;
  2102. }
  2103. zFile[iOut++] = c;
  2104. }
  2105. if( eState==1 ) zFile[iOut++] = '\0';
  2106. zFile[iOut++] = '\0';
  2107. zFile[iOut++] = '\0';
  2108. /* Check if there were any options specified that should be interpreted
  2109. ** here. Options that are interpreted here include "vfs" and those that
  2110. ** correspond to flags that may be passed to the sqlite3_open_v2()
  2111. ** method. */
  2112. zOpt = &zFile[sqlite3Strlen30(zFile)+1];
  2113. while( zOpt[0] ){
  2114. int nOpt = sqlite3Strlen30(zOpt);
  2115. char *zVal = &zOpt[nOpt+1];
  2116. int nVal = sqlite3Strlen30(zVal);
  2117. if( nOpt==3 && memcmp("vfs", zOpt, 3)==0 ){
  2118. zVfs = zVal;
  2119. }else{
  2120. struct OpenMode {
  2121. const char *z;
  2122. int mode;
  2123. } *aMode = 0;
  2124. char *zModeType = 0;
  2125. int mask = 0;
  2126. int limit = 0;
  2127. if( nOpt==5 && memcmp("cache", zOpt, 5)==0 ){
  2128. static struct OpenMode aCacheMode[] = {
  2129. { "shared", SQLITE_OPEN_SHAREDCACHE },
  2130. { "private", SQLITE_OPEN_PRIVATECACHE },
  2131. { 0, 0 }
  2132. };
  2133. mask = SQLITE_OPEN_SHAREDCACHE|SQLITE_OPEN_PRIVATECACHE;
  2134. aMode = aCacheMode;
  2135. limit = mask;
  2136. zModeType = "cache";
  2137. }
  2138. if( nOpt==4 && memcmp("mode", zOpt, 4)==0 ){
  2139. static struct OpenMode aOpenMode[] = {
  2140. { "ro", SQLITE_OPEN_READONLY },
  2141. { "rw", SQLITE_OPEN_READWRITE },
  2142. { "rwc", SQLITE_OPEN_READWRITE | SQLITE_OPEN_CREATE },
  2143. { "memory", SQLITE_OPEN_MEMORY },
  2144. { 0, 0 }
  2145. };
  2146. mask = SQLITE_OPEN_READONLY | SQLITE_OPEN_READWRITE
  2147. | SQLITE_OPEN_CREATE | SQLITE_OPEN_MEMORY;
  2148. aMode = aOpenMode;
  2149. limit = mask & flags;
  2150. zModeType = "access";
  2151. }
  2152. if( aMode ){
  2153. int i;
  2154. int mode = 0;
  2155. for(i=0; aMode[i].z; i++){
  2156. const char *z = aMode[i].z;
  2157. if( nVal==sqlite3Strlen30(z) && 0==memcmp(zVal, z, nVal) ){
  2158. mode = aMode[i].mode;
  2159. break;
  2160. }
  2161. }
  2162. if( mode==0 ){
  2163. *pzErrMsg = sqlite3_mprintf("no such %s mode: %s", zModeType, zVal);
  2164. rc = SQLITE_ERROR;
  2165. goto parse_uri_out;
  2166. }
  2167. if( (mode & ~SQLITE_OPEN_MEMORY)>limit ){
  2168. *pzErrMsg = sqlite3_mprintf("%s mode not allowed: %s",
  2169. zModeType, zVal);
  2170. rc = SQLITE_PERM;
  2171. goto parse_uri_out;
  2172. }
  2173. flags = (flags & ~mask) | mode;
  2174. }
  2175. }
  2176. zOpt = &zVal[nVal+1];
  2177. }
  2178. }else{
  2179. zFile = sqlite3_malloc(nUri+2);
  2180. if( !zFile ) return SQLITE_NOMEM;
  2181. memcpy(zFile, zUri, nUri);
  2182. zFile[nUri] = '\0';
  2183. zFile[nUri+1] = '\0';
  2184. flags &= ~SQLITE_OPEN_URI;
  2185. }
  2186. *ppVfs = sqlite3_vfs_find(zVfs);
  2187. if( *ppVfs==0 ){
  2188. *pzErrMsg = sqlite3_mprintf("no such vfs: %s", zVfs);
  2189. rc = SQLITE_ERROR;
  2190. }
  2191. parse_uri_out:
  2192. if( rc!=SQLITE_OK ){
  2193. sqlite3_free(zFile);
  2194. zFile = 0;
  2195. }
  2196. *pFlags = flags;
  2197. *pzFile = zFile;
  2198. return rc;
  2199. }
  2200. /*
  2201. ** This routine does the work of opening a database on behalf of
  2202. ** sqlite3_open() and sqlite3_open16(). The database filename "zFilename"
  2203. ** is UTF-8 encoded.
  2204. */
  2205. static int openDatabase(
  2206. const char *zFilename, /* Database filename UTF-8 encoded */
  2207. sqlite3 **ppDb, /* OUT: Returned database handle */
  2208. unsigned int flags, /* Operational flags */
  2209. const char *zVfs /* Name of the VFS to use */
  2210. ){
  2211. sqlite3 *db; /* Store allocated handle here */
  2212. int rc; /* Return code */
  2213. int isThreadsafe; /* True for threadsafe connections */
  2214. char *zOpen = 0; /* Filename argument to pass to BtreeOpen() */
  2215. char *zErrMsg = 0; /* Error message from sqlite3ParseUri() */
  2216. *ppDb = 0;
  2217. #ifndef SQLITE_OMIT_AUTOINIT
  2218. rc = sqlite3_initialize();
  2219. if( rc ) return rc;
  2220. #endif
  2221. /* Only allow sensible combinations of bits in the flags argument.
  2222. ** Throw an error if any non-sense combination is used. If we
  2223. ** do not block illegal combinations here, it could trigger
  2224. ** assert() statements in deeper layers. Sensible combinations
  2225. ** are:
  2226. **
  2227. ** 1: SQLITE_OPEN_READONLY
  2228. ** 2: SQLITE_OPEN_READWRITE
  2229. ** 6: SQLITE_OPEN_READWRITE | SQLITE_OPEN_CREATE
  2230. */
  2231. assert( SQLITE_OPEN_READONLY == 0x01 );
  2232. assert( SQLITE_OPEN_READWRITE == 0x02 );
  2233. assert( SQLITE_OPEN_CREATE == 0x04 );
  2234. testcase( (1<<(flags&7))==0x02 ); /* READONLY */
  2235. testcase( (1<<(flags&7))==0x04 ); /* READWRITE */
  2236. testcase( (1<<(flags&7))==0x40 ); /* READWRITE | CREATE */
  2237. if( ((1<<(flags&7)) & 0x46)==0 ) return SQLITE_MISUSE_BKPT;
  2238. if( sqlite3GlobalConfig.bCoreMutex==0 ){
  2239. isThreadsafe = 0;
  2240. }else if( flags & SQLITE_OPEN_NOMUTEX ){
  2241. isThreadsafe = 0;
  2242. }else if( flags & SQLITE_OPEN_FULLMUTEX ){
  2243. isThreadsafe = 1;
  2244. }else{
  2245. isThreadsafe = sqlite3GlobalConfig.bFullMutex;
  2246. }
  2247. if( flags & SQLITE_OPEN_PRIVATECACHE ){
  2248. flags &= ~SQLITE_OPEN_SHAREDCACHE;
  2249. }else if( sqlite3GlobalConfig.sharedCacheEnabled ){
  2250. flags |= SQLITE_OPEN_SHAREDCACHE;
  2251. }
  2252. /* Remove harmful bits from the flags parameter
  2253. **
  2254. ** The SQLITE_OPEN_NOMUTEX and SQLITE_OPEN_FULLMUTEX flags were
  2255. ** dealt with in the previous code block. Besides these, the only
  2256. ** valid input flags for sqlite3_open_v2() are SQLITE_OPEN_READONLY,
  2257. ** SQLITE_OPEN_READWRITE, SQLITE_OPEN_CREATE, SQLITE_OPEN_SHAREDCACHE,
  2258. ** SQLITE_OPEN_PRIVATECACHE, and some reserved bits. Silently mask
  2259. ** off all other flags.
  2260. */
  2261. flags &= ~( SQLITE_OPEN_DELETEONCLOSE |
  2262. SQLITE_OPEN_EXCLUSIVE |
  2263. SQLITE_OPEN_MAIN_DB |
  2264. SQLITE_OPEN_TEMP_DB |
  2265. SQLITE_OPEN_TRANSIENT_DB |
  2266. SQLITE_OPEN_MAIN_JOURNAL |
  2267. SQLITE_OPEN_TEMP_JOURNAL |
  2268. SQLITE_OPEN_SUBJOURNAL |
  2269. SQLITE_OPEN_MASTER_JOURNAL |
  2270. SQLITE_OPEN_NOMUTEX |
  2271. SQLITE_OPEN_FULLMUTEX |
  2272. SQLITE_OPEN_WAL
  2273. );
  2274. /* Allocate the sqlite data structure */
  2275. db = sqlite3MallocZero( sizeof(sqlite3) );
  2276. if( db==0 ) goto opendb_out;
  2277. if( isThreadsafe ){
  2278. db->mutex = sqlite3MutexAlloc(SQLITE_MUTEX_RECURSIVE);
  2279. if( db->mutex==0 ){
  2280. sqlite3_free(db);
  2281. db = 0;
  2282. goto opendb_out;
  2283. }
  2284. }
  2285. sqlite3_mutex_enter(db->mutex);
  2286. db->errMask = 0xff;
  2287. db->nDb = 2;
  2288. db->magic = SQLITE_MAGIC_BUSY;
  2289. db->aDb = db->aDbStatic;
  2290. assert( sizeof(db->aLimit)==sizeof(aHardLimit) );
  2291. memcpy(db->aLimit, aHardLimit, sizeof(db->aLimit));
  2292. db->autoCommit = 1;
  2293. db->nextAutovac = -1;
  2294. db->szMmap = sqlite3GlobalConfig.szMmap;
  2295. db->nextPagesize = 0;
  2296. db->flags |= SQLITE_ShortColNames | SQLITE_EnableTrigger | SQLITE_CacheSpill
  2297. #if !defined(SQLITE_DEFAULT_AUTOMATIC_INDEX) || SQLITE_DEFAULT_AUTOMATIC_INDEX
  2298. | SQLITE_AutoIndex
  2299. #endif
  2300. #if SQLITE_DEFAULT_FILE_FORMAT<4
  2301. | SQLITE_LegacyFileFmt
  2302. #endif
  2303. #ifdef SQLITE_ENABLE_LOAD_EXTENSION
  2304. | SQLITE_LoadExtension
  2305. #endif
  2306. #if SQLITE_DEFAULT_RECURSIVE_TRIGGERS
  2307. | SQLITE_RecTriggers
  2308. #endif
  2309. #if defined(SQLITE_DEFAULT_FOREIGN_KEYS) && SQLITE_DEFAULT_FOREIGN_KEYS
  2310. | SQLITE_ForeignKeys
  2311. #endif
  2312. ;
  2313. sqlite3HashInit(&db->aCollSeq);
  2314. #ifndef SQLITE_OMIT_VIRTUALTABLE
  2315. sqlite3HashInit(&db->aModule);
  2316. #endif
  2317. /* Add the default collation sequence BINARY. BINARY works for both UTF-8
  2318. ** and UTF-16, so add a version for each to avoid any unnecessary
  2319. ** conversions. The only error that can occur here is a malloc() failure.
  2320. */
  2321. createCollation(db, "BINARY", SQLITE_UTF8, 0, binCollFunc, 0);
  2322. createCollation(db, "BINARY", SQLITE_UTF16BE, 0, binCollFunc, 0);
  2323. createCollation(db, "BINARY", SQLITE_UTF16LE, 0, binCollFunc, 0);
  2324. createCollation(db, "RTRIM", SQLITE_UTF8, (void*)1, binCollFunc, 0);
  2325. if( db->mallocFailed ){
  2326. goto opendb_out;
  2327. }
  2328. db->pDfltColl = sqlite3FindCollSeq(db, SQLITE_UTF8, "BINARY", 0);
  2329. assert( db->pDfltColl!=0 );
  2330. /* Also add a UTF-8 case-insensitive collation sequence. */
  2331. createCollation(db, "NOCASE", SQLITE_UTF8, 0, nocaseCollatingFunc, 0);
  2332. /* Parse the filename/URI argument. */
  2333. db->openFlags = flags;
  2334. rc = sqlite3ParseUri(zVfs, zFilename, &flags, &db->pVfs, &zOpen, &zErrMsg);
  2335. if( rc!=SQLITE_OK ){
  2336. if( rc==SQLITE_NOMEM ) db->mallocFailed = 1;
  2337. sqlite3Error(db, rc, zErrMsg ? "%s" : 0, zErrMsg);
  2338. sqlite3_free(zErrMsg);
  2339. goto opendb_out;
  2340. }
  2341. /* Open the backend database driver */
  2342. rc = sqlite3BtreeOpen(db->pVfs, zOpen, db, &db->aDb[0].pBt, 0,
  2343. flags | SQLITE_OPEN_MAIN_DB);
  2344. if( rc!=SQLITE_OK ){
  2345. if( rc==SQLITE_IOERR_NOMEM ){
  2346. rc = SQLITE_NOMEM;
  2347. }
  2348. sqlite3Error(db, rc, 0);
  2349. goto opendb_out;
  2350. }
  2351. db->aDb[0].pSchema = sqlite3SchemaGet(db, db->aDb[0].pBt);
  2352. db->aDb[1].pSchema = sqlite3SchemaGet(db, 0);
  2353. /* The default safety_level for the main database is 'full'; for the temp
  2354. ** database it is 'NONE'. This matches the pager layer defaults.
  2355. */
  2356. db->aDb[0].zName = "main";
  2357. db->aDb[0].safety_level = 3;
  2358. db->aDb[1].zName = "temp";
  2359. db->aDb[1].safety_level = 1;
  2360. db->magic = SQLITE_MAGIC_OPEN;
  2361. if( db->mallocFailed ){
  2362. goto opendb_out;
  2363. }
  2364. /* Register all built-in functions, but do not attempt to read the
  2365. ** database schema yet. This is delayed until the first time the database
  2366. ** is accessed.
  2367. */
  2368. sqlite3Error(db, SQLITE_OK, 0);
  2369. sqlite3RegisterBuiltinFunctions(db);
  2370. /* Load automatic extensions - extensions that have been registered
  2371. ** using the sqlite3_automatic_extension() API.
  2372. */
  2373. rc = sqlite3_errcode(db);
  2374. if( rc==SQLITE_OK ){
  2375. sqlite3AutoLoadExtensions(db);
  2376. rc = sqlite3_errcode(db);
  2377. if( rc!=SQLITE_OK ){
  2378. goto opendb_out;
  2379. }
  2380. }
  2381. #ifdef SQLITE_ENABLE_FTS1
  2382. if( !db->mallocFailed ){
  2383. extern int sqlite3Fts1Init(sqlite3*);
  2384. rc = sqlite3Fts1Init(db);
  2385. }
  2386. #endif
  2387. #ifdef SQLITE_ENABLE_FTS2
  2388. if( !db->mallocFailed && rc==SQLITE_OK ){
  2389. extern int sqlite3Fts2Init(sqlite3*);
  2390. rc = sqlite3Fts2Init(db);
  2391. }
  2392. #endif
  2393. #ifdef SQLITE_ENABLE_FTS3
  2394. if( !db->mallocFailed && rc==SQLITE_OK ){
  2395. rc = sqlite3Fts3Init(db);
  2396. }
  2397. #endif
  2398. #ifdef SQLITE_ENABLE_ICU
  2399. if( !db->mallocFailed && rc==SQLITE_OK ){
  2400. rc = sqlite3IcuInit(db);
  2401. }
  2402. #endif
  2403. #ifdef SQLITE_ENABLE_RTREE
  2404. if( !db->mallocFailed && rc==SQLITE_OK){
  2405. rc = sqlite3RtreeInit(db);
  2406. }
  2407. #endif
  2408. sqlite3Error(db, rc, 0);
  2409. /* -DSQLITE_DEFAULT_LOCKING_MODE=1 makes EXCLUSIVE the default locking
  2410. ** mode. -DSQLITE_DEFAULT_LOCKING_MODE=0 make NORMAL the default locking
  2411. ** mode. Doing nothing at all also makes NORMAL the default.
  2412. */
  2413. #ifdef SQLITE_DEFAULT_LOCKING_MODE
  2414. db->dfltLockMode = SQLITE_DEFAULT_LOCKING_MODE;
  2415. sqlite3PagerLockingMode(sqlite3BtreePager(db->aDb[0].pBt),
  2416. SQLITE_DEFAULT_LOCKING_MODE);
  2417. #endif
  2418. /* Enable the lookaside-malloc subsystem */
  2419. setupLookaside(db, 0, sqlite3GlobalConfig.szLookaside,
  2420. sqlite3GlobalConfig.nLookaside);
  2421. sqlite3_wal_autocheckpoint(db, SQLITE_DEFAULT_WAL_AUTOCHECKPOINT);
  2422. opendb_out:
  2423. sqlite3_free(zOpen);
  2424. if( db ){
  2425. assert( db->mutex!=0 || isThreadsafe==0 || sqlite3GlobalConfig.bFullMutex==0 );
  2426. sqlite3_mutex_leave(db->mutex);
  2427. }
  2428. rc = sqlite3_errcode(db);
  2429. assert( db!=0 || rc==SQLITE_NOMEM );
  2430. if( rc==SQLITE_NOMEM ){
  2431. sqlite3_close(db);
  2432. db = 0;
  2433. }else if( rc!=SQLITE_OK ){
  2434. db->magic = SQLITE_MAGIC_SICK;
  2435. }
  2436. *ppDb = db;
  2437. #ifdef SQLITE_ENABLE_SQLLOG
  2438. if( sqlite3GlobalConfig.xSqllog ){
  2439. /* Opening a db handle. Fourth parameter is passed 0. */
  2440. void *pArg = sqlite3GlobalConfig.pSqllogArg;
  2441. sqlite3GlobalConfig.xSqllog(pArg, db, zFilename, 0);
  2442. }
  2443. #endif
  2444. return sqlite3ApiExit(0, rc);
  2445. }
  2446. /*
  2447. ** Open a new database handle.
  2448. */
  2449. int sqlite3_open(
  2450. const char *zFilename,
  2451. sqlite3 **ppDb
  2452. ){
  2453. return openDatabase(zFilename, ppDb,
  2454. SQLITE_OPEN_READWRITE | SQLITE_OPEN_CREATE, 0);
  2455. }
  2456. int sqlite3_open_v2(
  2457. const char *filename, /* Database filename (UTF-8) */
  2458. sqlite3 **ppDb, /* OUT: SQLite db handle */
  2459. int flags, /* Flags */
  2460. const char *zVfs /* Name of VFS module to use */
  2461. ){
  2462. return openDatabase(filename, ppDb, (unsigned int)flags, zVfs);
  2463. }
  2464. #ifndef SQLITE_OMIT_UTF16
  2465. /*
  2466. ** Open a new database handle.
  2467. */
  2468. int sqlite3_open16(
  2469. const void *zFilename,
  2470. sqlite3 **ppDb
  2471. ){
  2472. char const *zFilename8; /* zFilename encoded in UTF-8 instead of UTF-16 */
  2473. sqlite3_value *pVal;
  2474. int rc;
  2475. assert( zFilename );
  2476. assert( ppDb );
  2477. *ppDb = 0;
  2478. #ifndef SQLITE_OMIT_AUTOINIT
  2479. rc = sqlite3_initialize();
  2480. if( rc ) return rc;
  2481. #endif
  2482. pVal = sqlite3ValueNew(0);
  2483. sqlite3ValueSetStr(pVal, -1, zFilename, SQLITE_UTF16NATIVE, SQLITE_STATIC);
  2484. zFilename8 = sqlite3ValueText(pVal, SQLITE_UTF8);
  2485. if( zFilename8 ){
  2486. rc = openDatabase(zFilename8, ppDb,
  2487. SQLITE_OPEN_READWRITE | SQLITE_OPEN_CREATE, 0);
  2488. assert( *ppDb || rc==SQLITE_NOMEM );
  2489. if( rc==SQLITE_OK && !DbHasProperty(*ppDb, 0, DB_SchemaLoaded) ){
  2490. ENC(*ppDb) = SQLITE_UTF16NATIVE;
  2491. }
  2492. }else{
  2493. rc = SQLITE_NOMEM;
  2494. }
  2495. sqlite3ValueFree(pVal);
  2496. return sqlite3ApiExit(0, rc);
  2497. }
  2498. #endif /* SQLITE_OMIT_UTF16 */
  2499. /*
  2500. ** Register a new collation sequence with the database handle db.
  2501. */
  2502. int sqlite3_create_collation(
  2503. sqlite3* db,
  2504. const char *zName,
  2505. int enc,
  2506. void* pCtx,
  2507. int(*xCompare)(void*,int,const void*,int,const void*)
  2508. ){
  2509. int rc;
  2510. sqlite3_mutex_enter(db->mutex);
  2511. assert( !db->mallocFailed );
  2512. rc = createCollation(db, zName, (u8)enc, pCtx, xCompare, 0);
  2513. rc = sqlite3ApiExit(db, rc);
  2514. sqlite3_mutex_leave(db->mutex);
  2515. return rc;
  2516. }
  2517. /*
  2518. ** Register a new collation sequence with the database handle db.
  2519. */
  2520. int sqlite3_create_collation_v2(
  2521. sqlite3* db,
  2522. const char *zName,
  2523. int enc,
  2524. void* pCtx,
  2525. int(*xCompare)(void*,int,const void*,int,const void*),
  2526. void(*xDel)(void*)
  2527. ){
  2528. int rc;
  2529. sqlite3_mutex_enter(db->mutex);
  2530. assert( !db->mallocFailed );
  2531. rc = createCollation(db, zName, (u8)enc, pCtx, xCompare, xDel);
  2532. rc = sqlite3ApiExit(db, rc);
  2533. sqlite3_mutex_leave(db->mutex);
  2534. return rc;
  2535. }
  2536. #ifndef SQLITE_OMIT_UTF16
  2537. /*
  2538. ** Register a new collation sequence with the database handle db.
  2539. */
  2540. int sqlite3_create_collation16(
  2541. sqlite3* db,
  2542. const void *zName,
  2543. int enc,
  2544. void* pCtx,
  2545. int(*xCompare)(void*,int,const void*,int,const void*)
  2546. ){
  2547. int rc = SQLITE_OK;
  2548. char *zName8;
  2549. sqlite3_mutex_enter(db->mutex);
  2550. assert( !db->mallocFailed );
  2551. zName8 = sqlite3Utf16to8(db, zName, -1, SQLITE_UTF16NATIVE);
  2552. if( zName8 ){
  2553. rc = createCollation(db, zName8, (u8)enc, pCtx, xCompare, 0);
  2554. sqlite3DbFree(db, zName8);
  2555. }
  2556. rc = sqlite3ApiExit(db, rc);
  2557. sqlite3_mutex_leave(db->mutex);
  2558. return rc;
  2559. }
  2560. #endif /* SQLITE_OMIT_UTF16 */
  2561. /*
  2562. ** Register a collation sequence factory callback with the database handle
  2563. ** db. Replace any previously installed collation sequence factory.
  2564. */
  2565. int sqlite3_collation_needed(
  2566. sqlite3 *db,
  2567. void *pCollNeededArg,
  2568. void(*xCollNeeded)(void*,sqlite3*,int eTextRep,const char*)
  2569. ){
  2570. sqlite3_mutex_enter(db->mutex);
  2571. db->xCollNeeded = xCollNeeded;
  2572. db->xCollNeeded16 = 0;
  2573. db->pCollNeededArg = pCollNeededArg;
  2574. sqlite3_mutex_leave(db->mutex);
  2575. return SQLITE_OK;
  2576. }
  2577. #ifndef SQLITE_OMIT_UTF16
  2578. /*
  2579. ** Register a collation sequence factory callback with the database handle
  2580. ** db. Replace any previously installed collation sequence factory.
  2581. */
  2582. int sqlite3_collation_needed16(
  2583. sqlite3 *db,
  2584. void *pCollNeededArg,
  2585. void(*xCollNeeded16)(void*,sqlite3*,int eTextRep,const void*)
  2586. ){
  2587. sqlite3_mutex_enter(db->mutex);
  2588. db->xCollNeeded = 0;
  2589. db->xCollNeeded16 = xCollNeeded16;
  2590. db->pCollNeededArg = pCollNeededArg;
  2591. sqlite3_mutex_leave(db->mutex);
  2592. return SQLITE_OK;
  2593. }
  2594. #endif /* SQLITE_OMIT_UTF16 */
  2595. #ifndef SQLITE_OMIT_DEPRECATED
  2596. /*
  2597. ** This function is now an anachronism. It used to be used to recover from a
  2598. ** malloc() failure, but SQLite now does this automatically.
  2599. */
  2600. int sqlite3_global_recover(void){
  2601. return SQLITE_OK;
  2602. }
  2603. #endif
  2604. /*
  2605. ** Test to see whether or not the database connection is in autocommit
  2606. ** mode. Return TRUE if it is and FALSE if not. Autocommit mode is on
  2607. ** by default. Autocommit is disabled by a BEGIN statement and reenabled
  2608. ** by the next COMMIT or ROLLBACK.
  2609. */
  2610. int sqlite3_get_autocommit(sqlite3 *db){
  2611. return db->autoCommit;
  2612. }
  2613. /*
  2614. ** The following routines are subtitutes for constants SQLITE_CORRUPT,
  2615. ** SQLITE_MISUSE, SQLITE_CANTOPEN, SQLITE_IOERR and possibly other error
  2616. ** constants. They server two purposes:
  2617. **
  2618. ** 1. Serve as a convenient place to set a breakpoint in a debugger
  2619. ** to detect when version error conditions occurs.
  2620. **
  2621. ** 2. Invoke sqlite3_log() to provide the source code location where
  2622. ** a low-level error is first detected.
  2623. */
  2624. int sqlite3CorruptError(int lineno){
  2625. testcase( sqlite3GlobalConfig.xLog!=0 );
  2626. sqlite3_log(SQLITE_CORRUPT,
  2627. "database corruption at line %d of [%.10s]",
  2628. lineno, 20+sqlite3_sourceid());
  2629. return SQLITE_CORRUPT;
  2630. }
  2631. int sqlite3MisuseError(int lineno){
  2632. testcase( sqlite3GlobalConfig.xLog!=0 );
  2633. sqlite3_log(SQLITE_MISUSE,
  2634. "misuse at line %d of [%.10s]",
  2635. lineno, 20+sqlite3_sourceid());
  2636. return SQLITE_MISUSE;
  2637. }
  2638. int sqlite3CantopenError(int lineno){
  2639. testcase( sqlite3GlobalConfig.xLog!=0 );
  2640. sqlite3_log(SQLITE_CANTOPEN,
  2641. "cannot open file at line %d of [%.10s]",
  2642. lineno, 20+sqlite3_sourceid());
  2643. return SQLITE_CANTOPEN;
  2644. }
  2645. #ifndef SQLITE_OMIT_DEPRECATED
  2646. /*
  2647. ** This is a convenience routine that makes sure that all thread-specific
  2648. ** data for this thread has been deallocated.
  2649. **
  2650. ** SQLite no longer uses thread-specific data so this routine is now a
  2651. ** no-op. It is retained for historical compatibility.
  2652. */
  2653. void sqlite3_thread_cleanup(void){
  2654. }
  2655. #endif
  2656. /*
  2657. ** Return meta information about a specific column of a database table.
  2658. ** See comment in sqlite3.h (sqlite.h.in) for details.
  2659. */
  2660. #ifdef SQLITE_ENABLE_COLUMN_METADATA
  2661. int sqlite3_table_column_metadata(
  2662. sqlite3 *db, /* Connection handle */
  2663. const char *zDbName, /* Database name or NULL */
  2664. const char *zTableName, /* Table name */
  2665. const char *zColumnName, /* Column name */
  2666. char const **pzDataType, /* OUTPUT: Declared data type */
  2667. char const **pzCollSeq, /* OUTPUT: Collation sequence name */
  2668. int *pNotNull, /* OUTPUT: True if NOT NULL constraint exists */
  2669. int *pPrimaryKey, /* OUTPUT: True if column part of PK */
  2670. int *pAutoinc /* OUTPUT: True if column is auto-increment */
  2671. ){
  2672. int rc;
  2673. char *zErrMsg = 0;
  2674. Table *pTab = 0;
  2675. Column *pCol = 0;
  2676. int iCol;
  2677. char const *zDataType = 0;
  2678. char const *zCollSeq = 0;
  2679. int notnull = 0;
  2680. int primarykey = 0;
  2681. int autoinc = 0;
  2682. /* Ensure the database schema has been loaded */
  2683. sqlite3_mutex_enter(db->mutex);
  2684. sqlite3BtreeEnterAll(db);
  2685. rc = sqlite3Init(db, &zErrMsg);
  2686. if( SQLITE_OK!=rc ){
  2687. goto error_out;
  2688. }
  2689. /* Locate the table in question */
  2690. pTab = sqlite3FindTable(db, zTableName, zDbName);
  2691. if( !pTab || pTab->pSelect ){
  2692. pTab = 0;
  2693. goto error_out;
  2694. }
  2695. /* Find the column for which info is requested */
  2696. if( sqlite3IsRowid(zColumnName) ){
  2697. iCol = pTab->iPKey;
  2698. if( iCol>=0 ){
  2699. pCol = &pTab->aCol[iCol];
  2700. }
  2701. }else{
  2702. for(iCol=0; iCol<pTab->nCol; iCol++){
  2703. pCol = &pTab->aCol[iCol];
  2704. if( 0==sqlite3StrICmp(pCol->zName, zColumnName) ){
  2705. break;
  2706. }
  2707. }
  2708. if( iCol==pTab->nCol ){
  2709. pTab = 0;
  2710. goto error_out;
  2711. }
  2712. }
  2713. /* The following block stores the meta information that will be returned
  2714. ** to the caller in local variables zDataType, zCollSeq, notnull, primarykey
  2715. ** and autoinc. At this point there are two possibilities:
  2716. **
  2717. ** 1. The specified column name was rowid", "oid" or "_rowid_"
  2718. ** and there is no explicitly declared IPK column.
  2719. **
  2720. ** 2. The table is not a view and the column name identified an
  2721. ** explicitly declared column. Copy meta information from *pCol.
  2722. */
  2723. if( pCol ){
  2724. zDataType = pCol->zType;
  2725. zCollSeq = pCol->zColl;
  2726. notnull = pCol->notNull!=0;
  2727. primarykey = (pCol->colFlags & COLFLAG_PRIMKEY)!=0;
  2728. autoinc = pTab->iPKey==iCol && (pTab->tabFlags & TF_Autoincrement)!=0;
  2729. }else{
  2730. zDataType = "INTEGER";
  2731. primarykey = 1;
  2732. }
  2733. if( !zCollSeq ){
  2734. zCollSeq = "BINARY";
  2735. }
  2736. error_out:
  2737. sqlite3BtreeLeaveAll(db);
  2738. /* Whether the function call succeeded or failed, set the output parameters
  2739. ** to whatever their local counterparts contain. If an error did occur,
  2740. ** this has the effect of zeroing all output parameters.
  2741. */
  2742. if( pzDataType ) *pzDataType = zDataType;
  2743. if( pzCollSeq ) *pzCollSeq = zCollSeq;
  2744. if( pNotNull ) *pNotNull = notnull;
  2745. if( pPrimaryKey ) *pPrimaryKey = primarykey;
  2746. if( pAutoinc ) *pAutoinc = autoinc;
  2747. if( SQLITE_OK==rc && !pTab ){
  2748. sqlite3DbFree(db, zErrMsg);
  2749. zErrMsg = sqlite3MPrintf(db, "no such table column: %s.%s", zTableName,
  2750. zColumnName);
  2751. rc = SQLITE_ERROR;
  2752. }
  2753. sqlite3Error(db, rc, (zErrMsg?"%s":0), zErrMsg);
  2754. sqlite3DbFree(db, zErrMsg);
  2755. rc = sqlite3ApiExit(db, rc);
  2756. sqlite3_mutex_leave(db->mutex);
  2757. return rc;
  2758. }
  2759. #endif
  2760. /*
  2761. ** Sleep for a little while. Return the amount of time slept.
  2762. */
  2763. int sqlite3_sleep(int ms){
  2764. sqlite3_vfs *pVfs;
  2765. int rc;
  2766. pVfs = sqlite3_vfs_find(0);
  2767. if( pVfs==0 ) return 0;
  2768. /* This function works in milliseconds, but the underlying OsSleep()
  2769. ** API uses microseconds. Hence the 1000's.
  2770. */
  2771. rc = (sqlite3OsSleep(pVfs, 1000*ms)/1000);
  2772. return rc;
  2773. }
  2774. /*
  2775. ** Enable or disable the extended result codes.
  2776. */
  2777. int sqlite3_extended_result_codes(sqlite3 *db, int onoff){
  2778. sqlite3_mutex_enter(db->mutex);
  2779. db->errMask = onoff ? 0xffffffff : 0xff;
  2780. sqlite3_mutex_leave(db->mutex);
  2781. return SQLITE_OK;
  2782. }
  2783. /*
  2784. ** Invoke the xFileControl method on a particular database.
  2785. */
  2786. int sqlite3_file_control(sqlite3 *db, const char *zDbName, int op, void *pArg){
  2787. int rc = SQLITE_ERROR;
  2788. Btree *pBtree;
  2789. sqlite3_mutex_enter(db->mutex);
  2790. pBtree = sqlite3DbNameToBtree(db, zDbName);
  2791. if( pBtree ){
  2792. Pager *pPager;
  2793. sqlite3_file *fd;
  2794. sqlite3BtreeEnter(pBtree);
  2795. pPager = sqlite3BtreePager(pBtree);
  2796. assert( pPager!=0 );
  2797. fd = sqlite3PagerFile(pPager);
  2798. assert( fd!=0 );
  2799. if( op==SQLITE_FCNTL_FILE_POINTER ){
  2800. *(sqlite3_file**)pArg = fd;
  2801. rc = SQLITE_OK;
  2802. }else if( fd->pMethods ){
  2803. rc = sqlite3OsFileControl(fd, op, pArg);
  2804. }else{
  2805. rc = SQLITE_NOTFOUND;
  2806. }
  2807. sqlite3BtreeLeave(pBtree);
  2808. }
  2809. sqlite3_mutex_leave(db->mutex);
  2810. return rc;
  2811. }
  2812. /*
  2813. ** Interface to the testing logic.
  2814. */
  2815. int sqlite3_test_control(int op, ...){
  2816. int rc = 0;
  2817. #ifndef SQLITE_OMIT_BUILTIN_TEST
  2818. va_list ap;
  2819. va_start(ap, op);
  2820. switch( op ){
  2821. /*
  2822. ** Save the current state of the PRNG.
  2823. */
  2824. case SQLITE_TESTCTRL_PRNG_SAVE: {
  2825. sqlite3PrngSaveState();
  2826. break;
  2827. }
  2828. /*
  2829. ** Restore the state of the PRNG to the last state saved using
  2830. ** PRNG_SAVE. If PRNG_SAVE has never before been called, then
  2831. ** this verb acts like PRNG_RESET.
  2832. */
  2833. case SQLITE_TESTCTRL_PRNG_RESTORE: {
  2834. sqlite3PrngRestoreState();
  2835. break;
  2836. }
  2837. /*
  2838. ** Reset the PRNG back to its uninitialized state. The next call
  2839. ** to sqlite3_randomness() will reseed the PRNG using a single call
  2840. ** to the xRandomness method of the default VFS.
  2841. */
  2842. case SQLITE_TESTCTRL_PRNG_RESET: {
  2843. sqlite3PrngResetState();
  2844. break;
  2845. }
  2846. /*
  2847. ** sqlite3_test_control(BITVEC_TEST, size, program)
  2848. **
  2849. ** Run a test against a Bitvec object of size. The program argument
  2850. ** is an array of integers that defines the test. Return -1 on a
  2851. ** memory allocation error, 0 on success, or non-zero for an error.
  2852. ** See the sqlite3BitvecBuiltinTest() for additional information.
  2853. */
  2854. case SQLITE_TESTCTRL_BITVEC_TEST: {
  2855. int sz = va_arg(ap, int);
  2856. int *aProg = va_arg(ap, int*);
  2857. rc = sqlite3BitvecBuiltinTest(sz, aProg);
  2858. break;
  2859. }
  2860. /*
  2861. ** sqlite3_test_control(BENIGN_MALLOC_HOOKS, xBegin, xEnd)
  2862. **
  2863. ** Register hooks to call to indicate which malloc() failures
  2864. ** are benign.
  2865. */
  2866. case SQLITE_TESTCTRL_BENIGN_MALLOC_HOOKS: {
  2867. typedef void (*void_function)(void);
  2868. void_function xBenignBegin;
  2869. void_function xBenignEnd;
  2870. xBenignBegin = va_arg(ap, void_function);
  2871. xBenignEnd = va_arg(ap, void_function);
  2872. sqlite3BenignMallocHooks(xBenignBegin, xBenignEnd);
  2873. break;
  2874. }
  2875. /*
  2876. ** sqlite3_test_control(SQLITE_TESTCTRL_PENDING_BYTE, unsigned int X)
  2877. **
  2878. ** Set the PENDING byte to the value in the argument, if X>0.
  2879. ** Make no changes if X==0. Return the value of the pending byte
  2880. ** as it existing before this routine was called.
  2881. **
  2882. ** IMPORTANT: Changing the PENDING byte from 0x40000000 results in
  2883. ** an incompatible database file format. Changing the PENDING byte
  2884. ** while any database connection is open results in undefined and
  2885. ** dileterious behavior.
  2886. */
  2887. case SQLITE_TESTCTRL_PENDING_BYTE: {
  2888. rc = PENDING_BYTE;
  2889. #ifndef SQLITE_OMIT_WSD
  2890. {
  2891. unsigned int newVal = va_arg(ap, unsigned int);
  2892. if( newVal ) sqlite3PendingByte = newVal;
  2893. }
  2894. #endif
  2895. break;
  2896. }
  2897. /*
  2898. ** sqlite3_test_control(SQLITE_TESTCTRL_ASSERT, int X)
  2899. **
  2900. ** This action provides a run-time test to see whether or not
  2901. ** assert() was enabled at compile-time. If X is true and assert()
  2902. ** is enabled, then the return value is true. If X is true and
  2903. ** assert() is disabled, then the return value is zero. If X is
  2904. ** false and assert() is enabled, then the assertion fires and the
  2905. ** process aborts. If X is false and assert() is disabled, then the
  2906. ** return value is zero.
  2907. */
  2908. case SQLITE_TESTCTRL_ASSERT: {
  2909. volatile int x = 0;
  2910. assert( (x = va_arg(ap,int))!=0 );
  2911. rc = x;
  2912. break;
  2913. }
  2914. /*
  2915. ** sqlite3_test_control(SQLITE_TESTCTRL_ALWAYS, int X)
  2916. **
  2917. ** This action provides a run-time test to see how the ALWAYS and
  2918. ** NEVER macros were defined at compile-time.
  2919. **
  2920. ** The return value is ALWAYS(X).
  2921. **
  2922. ** The recommended test is X==2. If the return value is 2, that means
  2923. ** ALWAYS() and NEVER() are both no-op pass-through macros, which is the
  2924. ** default setting. If the return value is 1, then ALWAYS() is either
  2925. ** hard-coded to true or else it asserts if its argument is false.
  2926. ** The first behavior (hard-coded to true) is the case if
  2927. ** SQLITE_TESTCTRL_ASSERT shows that assert() is disabled and the second
  2928. ** behavior (assert if the argument to ALWAYS() is false) is the case if
  2929. ** SQLITE_TESTCTRL_ASSERT shows that assert() is enabled.
  2930. **
  2931. ** The run-time test procedure might look something like this:
  2932. **
  2933. ** if( sqlite3_test_control(SQLITE_TESTCTRL_ALWAYS, 2)==2 ){
  2934. ** // ALWAYS() and NEVER() are no-op pass-through macros
  2935. ** }else if( sqlite3_test_control(SQLITE_TESTCTRL_ASSERT, 1) ){
  2936. ** // ALWAYS(x) asserts that x is true. NEVER(x) asserts x is false.
  2937. ** }else{
  2938. ** // ALWAYS(x) is a constant 1. NEVER(x) is a constant 0.
  2939. ** }
  2940. */
  2941. case SQLITE_TESTCTRL_ALWAYS: {
  2942. int x = va_arg(ap,int);
  2943. rc = ALWAYS(x);
  2944. break;
  2945. }
  2946. /* sqlite3_test_control(SQLITE_TESTCTRL_RESERVE, sqlite3 *db, int N)
  2947. **
  2948. ** Set the nReserve size to N for the main database on the database
  2949. ** connection db.
  2950. */
  2951. case SQLITE_TESTCTRL_RESERVE: {
  2952. sqlite3 *db = va_arg(ap, sqlite3*);
  2953. int x = va_arg(ap,int);
  2954. sqlite3_mutex_enter(db->mutex);
  2955. sqlite3BtreeSetPageSize(db->aDb[0].pBt, 0, x, 0);
  2956. sqlite3_mutex_leave(db->mutex);
  2957. break;
  2958. }
  2959. /* sqlite3_test_control(SQLITE_TESTCTRL_OPTIMIZATIONS, sqlite3 *db, int N)
  2960. **
  2961. ** Enable or disable various optimizations for testing purposes. The
  2962. ** argument N is a bitmask of optimizations to be disabled. For normal
  2963. ** operation N should be 0. The idea is that a test program (like the
  2964. ** SQL Logic Test or SLT test module) can run the same SQL multiple times
  2965. ** with various optimizations disabled to verify that the same answer
  2966. ** is obtained in every case.
  2967. */
  2968. case SQLITE_TESTCTRL_OPTIMIZATIONS: {
  2969. sqlite3 *db = va_arg(ap, sqlite3*);
  2970. db->dbOptFlags = (u16)(va_arg(ap, int) & 0xffff);
  2971. break;
  2972. }
  2973. #ifdef SQLITE_N_KEYWORD
  2974. /* sqlite3_test_control(SQLITE_TESTCTRL_ISKEYWORD, const char *zWord)
  2975. **
  2976. ** If zWord is a keyword recognized by the parser, then return the
  2977. ** number of keywords. Or if zWord is not a keyword, return 0.
  2978. **
  2979. ** This test feature is only available in the amalgamation since
  2980. ** the SQLITE_N_KEYWORD macro is not defined in this file if SQLite
  2981. ** is built using separate source files.
  2982. */
  2983. case SQLITE_TESTCTRL_ISKEYWORD: {
  2984. const char *zWord = va_arg(ap, const char*);
  2985. int n = sqlite3Strlen30(zWord);
  2986. rc = (sqlite3KeywordCode((u8*)zWord, n)!=TK_ID) ? SQLITE_N_KEYWORD : 0;
  2987. break;
  2988. }
  2989. #endif
  2990. /* sqlite3_test_control(SQLITE_TESTCTRL_SCRATCHMALLOC, sz, &pNew, pFree);
  2991. **
  2992. ** Pass pFree into sqlite3ScratchFree().
  2993. ** If sz>0 then allocate a scratch buffer into pNew.
  2994. */
  2995. case SQLITE_TESTCTRL_SCRATCHMALLOC: {
  2996. void *pFree, **ppNew;
  2997. int sz;
  2998. sz = va_arg(ap, int);
  2999. ppNew = va_arg(ap, void**);
  3000. pFree = va_arg(ap, void*);
  3001. if( sz ) *ppNew = sqlite3ScratchMalloc(sz);
  3002. sqlite3ScratchFree(pFree);
  3003. break;
  3004. }
  3005. /* sqlite3_test_control(SQLITE_TESTCTRL_LOCALTIME_FAULT, int onoff);
  3006. **
  3007. ** If parameter onoff is non-zero, configure the wrappers so that all
  3008. ** subsequent calls to localtime() and variants fail. If onoff is zero,
  3009. ** undo this setting.
  3010. */
  3011. case SQLITE_TESTCTRL_LOCALTIME_FAULT: {
  3012. sqlite3GlobalConfig.bLocaltimeFault = va_arg(ap, int);
  3013. break;
  3014. }
  3015. #if defined(SQLITE_ENABLE_TREE_EXPLAIN)
  3016. /* sqlite3_test_control(SQLITE_TESTCTRL_EXPLAIN_STMT,
  3017. ** sqlite3_stmt*,const char**);
  3018. **
  3019. ** If compiled with SQLITE_ENABLE_TREE_EXPLAIN, each sqlite3_stmt holds
  3020. ** a string that describes the optimized parse tree. This test-control
  3021. ** returns a pointer to that string.
  3022. */
  3023. case SQLITE_TESTCTRL_EXPLAIN_STMT: {
  3024. sqlite3_stmt *pStmt = va_arg(ap, sqlite3_stmt*);
  3025. const char **pzRet = va_arg(ap, const char**);
  3026. *pzRet = sqlite3VdbeExplanation((Vdbe*)pStmt);
  3027. break;
  3028. }
  3029. #endif
  3030. }
  3031. va_end(ap);
  3032. #endif /* SQLITE_OMIT_BUILTIN_TEST */
  3033. return rc;
  3034. }
  3035. /*
  3036. ** This is a utility routine, useful to VFS implementations, that checks
  3037. ** to see if a database file was a URI that contained a specific query
  3038. ** parameter, and if so obtains the value of the query parameter.
  3039. **
  3040. ** The zFilename argument is the filename pointer passed into the xOpen()
  3041. ** method of a VFS implementation. The zParam argument is the name of the
  3042. ** query parameter we seek. This routine returns the value of the zParam
  3043. ** parameter if it exists. If the parameter does not exist, this routine
  3044. ** returns a NULL pointer.
  3045. */
  3046. const char *sqlite3_uri_parameter(const char *zFilename, const char *zParam){
  3047. if( zFilename==0 ) return 0;
  3048. zFilename += sqlite3Strlen30(zFilename) + 1;
  3049. while( zFilename[0] ){
  3050. int x = strcmp(zFilename, zParam);
  3051. zFilename += sqlite3Strlen30(zFilename) + 1;
  3052. if( x==0 ) return zFilename;
  3053. zFilename += sqlite3Strlen30(zFilename) + 1;
  3054. }
  3055. return 0;
  3056. }
  3057. /*
  3058. ** Return a boolean value for a query parameter.
  3059. */
  3060. int sqlite3_uri_boolean(const char *zFilename, const char *zParam, int bDflt){
  3061. const char *z = sqlite3_uri_parameter(zFilename, zParam);
  3062. bDflt = bDflt!=0;
  3063. return z ? sqlite3GetBoolean(z, bDflt) : bDflt;
  3064. }
  3065. /*
  3066. ** Return a 64-bit integer value for a query parameter.
  3067. */
  3068. sqlite3_int64 sqlite3_uri_int64(
  3069. const char *zFilename, /* Filename as passed to xOpen */
  3070. const char *zParam, /* URI parameter sought */
  3071. sqlite3_int64 bDflt /* return if parameter is missing */
  3072. ){
  3073. const char *z = sqlite3_uri_parameter(zFilename, zParam);
  3074. sqlite3_int64 v;
  3075. if( z && sqlite3Atoi64(z, &v, sqlite3Strlen30(z), SQLITE_UTF8)==SQLITE_OK ){
  3076. bDflt = v;
  3077. }
  3078. return bDflt;
  3079. }
  3080. /*
  3081. ** Return the Btree pointer identified by zDbName. Return NULL if not found.
  3082. */
  3083. Btree *sqlite3DbNameToBtree(sqlite3 *db, const char *zDbName){
  3084. int i;
  3085. for(i=0; i<db->nDb; i++){
  3086. if( db->aDb[i].pBt
  3087. && (zDbName==0 || sqlite3StrICmp(zDbName, db->aDb[i].zName)==0)
  3088. ){
  3089. return db->aDb[i].pBt;
  3090. }
  3091. }
  3092. return 0;
  3093. }
  3094. /*
  3095. ** Return the filename of the database associated with a database
  3096. ** connection.
  3097. */
  3098. const char *sqlite3_db_filename(sqlite3 *db, const char *zDbName){
  3099. Btree *pBt = sqlite3DbNameToBtree(db, zDbName);
  3100. return pBt ? sqlite3BtreeGetFilename(pBt) : 0;
  3101. }
  3102. /*
  3103. ** Return 1 if database is read-only or 0 if read/write. Return -1 if
  3104. ** no such database exists.
  3105. */
  3106. int sqlite3_db_readonly(sqlite3 *db, const char *zDbName){
  3107. Btree *pBt = sqlite3DbNameToBtree(db, zDbName);
  3108. return pBt ? sqlite3PagerIsreadonly(sqlite3BtreePager(pBt)) : -1;
  3109. }