sq_sqlite3.cpp 104 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561
  1. /* Code generated by script */
  2. #include "sq_sqlite3.h"
  3. #include <assert.h>
  4. #include <stdlib.h>
  5. #include "lua-regex.h"
  6. SQ_OPT_STRING_STRLEN();
  7. const SQChar *SQLite3_TAG = "SQLite3";
  8. static const SQChar *SQLite3_Stmt_TAG = "SQLite3Stmt";
  9. static const SQChar *SQLite3_Blob_TAG = "SQLite3Blob";
  10. static const SQChar sqlite3_NULL_Name[] = _SC("sqlite3_NULL");
  11. static const SQChar nullName[] = _SC("Null");
  12. //return error if parameter exists but is not a blob
  13. //return 1 if the parameter exists and is a blob
  14. //return 0 if the parameter doesn't exists and creates a new blob
  15. static SQRESULT getOptionalBlob(HSQUIRRELVM v, SQInteger idx, SQBlob **blob)
  16. {
  17. if(sq_gettop(v) >= idx) {
  18. if(SQ_FAILED(sq_getinstanceup(v,3,(SQUserPointer*)blob,(SQUserPointer)SQBlob::SQBlob_TAG)))
  19. return sq_throwerror(v,_SC("expect a blob as second parameter"));
  20. if(!(*blob) || !(*blob)->IsValid())
  21. return sq_throwerror(v,_SC("the blob is invalid"));
  22. } else {
  23. *blob = new SQBlob(0, 8192);
  24. return 0;
  25. }
  26. return 1;
  27. }
  28. static SQRESULT sqlite3_NULL_tostring(HSQUIRRELVM v)
  29. {
  30. sq_pushstring(v, "", 0);
  31. return 1;
  32. }
  33. SQRegFunction sqlite3_NULL_methods[]=
  34. {
  35. {_SC("_tostring"),sqlite3_NULL_tostring,1, _SC("u")},
  36. {0,0}
  37. };
  38. static SQRESULT get_sqlite3_instance(HSQUIRRELVM v, SQInteger idx, sq_sqlite3_sdb **sdb)
  39. {
  40. SQRESULT _rc_;
  41. if((_rc_ = sq_getinstanceup(v,idx,(SQUserPointer*)sdb,(void*)SQLite3_TAG)) < 0) return _rc_;
  42. if(!*sdb) return sq_throwerror(v, _SC("database is closed"));
  43. return _rc_;
  44. }
  45. static SQRESULT get_sqlite3_stmt_instance(HSQUIRRELVM v, SQInteger idx, sqlite3_stmt **stmt)
  46. {
  47. SQRESULT _rc_;
  48. if((_rc_ = sq_getinstanceup(v,idx,(SQUserPointer*)stmt,(void*)SQLite3_Stmt_TAG)) < 0) return _rc_;
  49. if(!*stmt) return sq_throwerror(v, _SC("statement is closed"));
  50. return _rc_;
  51. }
  52. static SQRESULT get_sqlite3_blob_instance(HSQUIRRELVM v, SQInteger idx, sqlite3_blob **blob)
  53. {
  54. SQRESULT _rc_;
  55. if((_rc_ = sq_getinstanceup(v,idx,(SQUserPointer*)blob,(void*)SQLite3_Blob_TAG)) < 0) return _rc_;
  56. if(!*blob) return sq_throwerror(v, _SC("blob is closed"));
  57. return _rc_;
  58. }
  59. //#define push_sqlite3_null(v) sq_getonregistrytable(v, sqlite3_NULL_Name, sizeof(sqlite3_NULL_Name)-1);
  60. //#define push_sqlite3_null(v) sq_pushobject(v, sqlite3_NULL);
  61. //#define push_sqlite3_null(v) sq_getbyname(v, 1, nullName, sizeof(nullName)-1)
  62. //#define push_sqlite3_null(v) sq_pushfromregistrytable(v, nullName, sizeof(nullName)-1)
  63. //#define push_sqlite3_null(v) {sq_pushregistrytable(v);sq_pushstring(v, sqlite3_NULL_Name, sizeof(sqlite3_NULL_Name)-1);sq_get(v, -2);sq_remove(v,-2);}
  64. //the line bellow is the fastest one, any other attempt till now was slower
  65. #define push_sqlite3_null(v) {sq_pushstring(v, nullName, sizeof(nullName)-1);sq_get(v, 1);}
  66. #define GET_sqlite3_INSTANCE_AT_VAR(idx, self) \
  67. sq_sqlite3_sdb *sdb=NULL; \
  68. if((_rc_ = get_sqlite3_instance(v,idx,&sdb)) < 0) return _rc_;\
  69. sqlite3 *self = sdb->db;
  70. #define GET_sqlite3_INSTANCE_AT(idx) GET_sqlite3_INSTANCE_AT_VAR(idx, self)
  71. #define GET_sqlite3_INSTANCE() GET_sqlite3_INSTANCE_AT(1)
  72. //#define GET_sqlite3_INSTANCE() SQ_GET_INSTANCE(v, 1, sqlite3, SQLite3_TAG)
  73. #define GET_sqlite3_stmt_INSTANCE_AT(idx, var_name) \
  74. sqlite3_stmt *var_name=NULL; \
  75. if((_rc_ = get_sqlite3_stmt_instance(v,idx,&var_name)) < 0) return _rc_;
  76. #define GET_sqlite3_stmt_INSTANCE() GET_sqlite3_stmt_INSTANCE_AT(1, self)
  77. #define GET_sqlite3_blob_INSTANCE_AT(idx, var_name) \
  78. sqlite3_blob *var_name=NULL; \
  79. if((_rc_ = get_sqlite3_blob_instance(v,idx,&var_name)) < 0) return _rc_;
  80. #define GET_sqlite3_blob_INSTANCE() GET_sqlite3_blob_INSTANCE_AT(1, self)
  81. enum e_type_result {tr_first_row_first_col, tr_first_row, tr_all_rows, tr_ddml};
  82. #define AS_STRING_ALWAYS 0x01
  83. #define NULL_AS_EMPTY_STR 0x02
  84. #define WITH_COL_NAMES 0x04
  85. #define WITH_BLOB_AS_NULL 0x08
  86. #define WITH_SQ_NULL 0x100
  87. static void sqlite3_stmt_push_string(HSQUIRRELVM v, sqlite3_stmt *stmt, int col, int flags)
  88. {
  89. const char *value = (const char*) sqlite3_column_text(stmt, col);
  90. if(value) sq_pushstring(v, value, sqlite3_column_bytes(stmt, col));
  91. else
  92. {
  93. if(flags & AS_STRING_ALWAYS) sq_pushliteral(v, "");
  94. else push_sqlite3_null(v);
  95. }
  96. }
  97. static SQRESULT sqlite3_stmt_push_value(HSQUIRRELVM v, sqlite3_stmt *stmt, int col, int flags)
  98. {
  99. const char *value;
  100. int col_type = 0;
  101. if(flags & WITH_BLOB_AS_NULL)
  102. {
  103. col_type = sqlite3_column_type(stmt, col);
  104. if(col_type == SQLITE_BLOB)
  105. {
  106. if(flags & AS_STRING_ALWAYS) sq_pushliteral(v, "");
  107. else push_sqlite3_null(v);
  108. return 1;
  109. }
  110. }
  111. if(flags & AS_STRING_ALWAYS)
  112. {
  113. sqlite3_stmt_push_string(v, stmt, col, flags);
  114. }
  115. else
  116. {
  117. if(!col_type) col_type = sqlite3_column_type(stmt, col);
  118. switch (col_type)
  119. {
  120. case SQLITE_INTEGER:
  121. {
  122. sqlite_int64 i64 = sqlite3_column_int64(stmt, col);
  123. SQInteger n = (SQInteger)i64;
  124. if (n == i64)
  125. sq_pushinteger(v, n);
  126. else
  127. sq_pushstring(v, (const char*) sqlite3_column_text(stmt, col), sqlite3_column_bytes(stmt, col));
  128. }
  129. break;
  130. case SQLITE_FLOAT:
  131. sq_pushfloat(v, sqlite3_column_double(stmt, col));
  132. break;
  133. case SQLITE_TEXT:
  134. sqlite3_stmt_push_string(v, stmt, col, flags);
  135. break;
  136. case SQLITE_BLOB:
  137. value = (const char*) sqlite3_column_blob(stmt, col);
  138. if(value) sq_pushstring(v, value, sqlite3_column_bytes(stmt, col));
  139. else push_sqlite3_null(v);
  140. break;
  141. case SQLITE_NULL:
  142. if(flags & WITH_SQ_NULL) sq_pushnull(v);
  143. else push_sqlite3_null(v);
  144. break;
  145. default:
  146. if(flags & WITH_SQ_NULL) sq_pushnull(v);
  147. else push_sqlite3_null(v);
  148. break;
  149. }
  150. }
  151. return 1;
  152. }
  153. static void sqlite3_stmt_row_asArray(HSQUIRRELVM v, sqlite3_stmt *stmt, int flags)
  154. {
  155. int col_count = sqlite3_column_count(stmt);
  156. sq_newarray(v, col_count);
  157. for(int i=0; i<col_count; ++i)
  158. {
  159. sqlite3_stmt_push_value(v, stmt, i, flags);
  160. sq_arrayset(v, -2, i);
  161. }
  162. }
  163. static void sqlite3_stmt_row_asTable(HSQUIRRELVM v, sqlite3_stmt *stmt, int flags)
  164. {
  165. int col_count = sqlite3_column_count(stmt);
  166. sq_newtable(v);
  167. for(int i=0; i<col_count; ++i)
  168. {
  169. sq_pushstring(v, sqlite3_column_name(stmt, i), -1);
  170. sqlite3_stmt_push_value(v, stmt, i, flags);
  171. sq_rawset(v, -3);
  172. }
  173. }
  174. static void sqlite3_stmt_asArrayOfArrays(HSQUIRRELVM v, sqlite3_stmt *stmt, int flags)
  175. {
  176. sq_newarray(v, 0);
  177. if(flags & WITH_COL_NAMES)
  178. {
  179. int col_count = sqlite3_column_count(stmt);
  180. sq_newarray(v, col_count);
  181. for(int i=0; i<col_count; ++i)
  182. {
  183. sq_pushstring(v, sqlite3_column_name(stmt, i), -1);
  184. sq_arrayset(v, -2, i);
  185. }
  186. sq_arrayappend(v, -2);
  187. }
  188. while(sqlite3_step(stmt) == SQLITE_ROW)
  189. {
  190. sqlite3_stmt_row_asArray(v, stmt, flags);
  191. sq_arrayappend(v, -2);
  192. }
  193. }
  194. static void sqlite3_stmt_asArrayOfTables(HSQUIRRELVM v, sqlite3_stmt *stmt, int flags)
  195. {
  196. sq_newarray(v, 0);
  197. while(sqlite3_step(stmt) == SQLITE_ROW)
  198. {
  199. sqlite3_stmt_row_asTable(v, stmt, flags);
  200. sq_arrayappend(v, -2);
  201. }
  202. }
  203. static SQRESULT sqlite3_stmt_bind_value(HSQUIRRELVM v, sqlite3_stmt *stmt, int npar, int argn)
  204. {
  205. int _rc_ = 0;
  206. SQObjectType ptype = sq_gettype(v, argn);
  207. switch(ptype)
  208. {
  209. case OT_BOOL:
  210. SQ_GET_BOOL(v, argn, param_bool);
  211. _rc_ = sqlite3_bind_int(stmt, npar, param_bool == SQTrue ? 1 : 0);
  212. break;
  213. case OT_INTEGER:
  214. SQ_GET_INTEGER(v, argn, param_integer);
  215. _rc_ = sqlite3_bind_int64(stmt, npar, param_integer);
  216. break;
  217. case OT_FLOAT:
  218. SQ_GET_FLOAT(v, argn, param_float);
  219. _rc_ = sqlite3_bind_double(stmt, npar, param_float);
  220. break;
  221. case OT_STRING:
  222. {
  223. SQ_GET_STRING(v, argn, param_string);
  224. _rc_ = sqlite3_bind_text(stmt, npar, param_string, param_string_size, SQLITE_TRANSIENT);
  225. }
  226. break;
  227. case OT_USERDATA:
  228. {
  229. SQUserPointer ttag = 0;
  230. if((sq_gettypetag(v, argn, &ttag) != SQ_OK) || (ttag != sqlite3_NULL_Name))
  231. return sq_throwerror(v, "Invalid bind parameter %d", npar);
  232. }
  233. //fallthrough
  234. case OT_NULL:
  235. _rc_ = sqlite3_bind_null(stmt, npar);
  236. break;
  237. default:
  238. return sq_throwerror(v, "Invalid bind parameter %d", npar);
  239. }
  240. if(_rc_ != SQLITE_OK)
  241. {
  242. sqlite3 *db = sqlite3_db_handle(stmt);
  243. return sq_throwerror(v, sqlite3_errmsg(db));
  244. }
  245. return SQ_OK;
  246. }
  247. static SQRESULT sq_sqlite3_stmt_bind_vargv(HSQUIRRELVM v, sqlite3 *db, sqlite3_stmt *stmt, int params_start)
  248. {
  249. SQ_FUNC_VARS(v);
  250. if(_top_ > params_start)
  251. {
  252. int nparams = sqlite3_bind_parameter_count(stmt);
  253. int nparams_given = _top_-params_start;
  254. if(nparams != nparams_given)
  255. {
  256. return sq_throwerror(v, "expect %d parameters but only %d given", nparams, nparams_given);
  257. }
  258. for(int i=1; i <= nparams; ++i)
  259. {
  260. int argn = i+params_start;
  261. _rc_ = sqlite3_stmt_bind_value(v, stmt, i, argn);
  262. if(_rc_ < 0) return _rc_;
  263. }
  264. }
  265. return SQ_OK;
  266. }
  267. static SQRESULT sq_sqlite3_stmt_prepare_aux(HSQUIRRELVM v, sqlite3 *db, sqlite3_stmt **stmt, int params_start)
  268. {
  269. SQ_FUNC_VARS_NO_TOP(v);
  270. SQ_GET_STRING(v, params_start, szSQL);
  271. if(sqlite3_prepare_v2(db, szSQL, szSQL_size, stmt, 0) != SQLITE_OK)
  272. {
  273. return sq_throwerror(v, sqlite3_errmsg(db));
  274. }
  275. return sq_sqlite3_stmt_bind_vargv(v, db, *stmt, params_start);
  276. }
  277. static SQRESULT sq_sqlite3_stmt_releasehook(SQUserPointer p, SQInteger size, void */*ep*/)
  278. {
  279. sqlite3_stmt *stmt = ((sqlite3_stmt *)p);
  280. if(stmt) sqlite3_finalize(stmt);
  281. return 0;
  282. }
  283. static SQRESULT sq_sqlite3_stmt_constructor(HSQUIRRELVM v)
  284. {
  285. SQ_FUNC_VARS(v);
  286. _rc_ = SQ_ERROR;
  287. GET_sqlite3_INSTANCE_AT(2);
  288. sqlite3_stmt *stmt = 0;
  289. if(_top_ > 2)
  290. {
  291. _rc_ = sq_sqlite3_stmt_prepare_aux(v, self, &stmt, 3);
  292. }
  293. else
  294. {
  295. if(sqlite3_prepare_v2(self, "select 'statement not prepared';", -1, &stmt, 0) != SQLITE_OK)
  296. {
  297. _rc_ = sq_throwerror(v, sqlite3_errmsg(self));
  298. }
  299. else _rc_ = SQ_OK;
  300. }
  301. sq_setinstanceup(v, 1, stmt); //replace self for this instance with this new sqlite3_stmt
  302. sq_setreleasehook(v,1, sq_sqlite3_stmt_releasehook);
  303. return _rc_;
  304. }
  305. static SQRESULT sq_sqlite3_stmt_get_db(HSQUIRRELVM v)
  306. {
  307. SQ_FUNC_VARS_NO_TOP(v);
  308. GET_sqlite3_stmt_INSTANCE();
  309. sqlite3 *db = sqlite3_db_handle(self);
  310. sq_pushuserpointer(v, db);
  311. if(sq_getonregistrytable(v) == SQ_OK)
  312. {
  313. sq_getweakrefval(v, -1);
  314. }
  315. else return sq_throwerror(v, _SC("could not retrive database, maybe it was already closed"));
  316. return 1;
  317. }
  318. static SQRESULT sq_sqlite3_stmt_stmt_ptr(HSQUIRRELVM v)
  319. {
  320. SQ_FUNC_VARS_NO_TOP(v);
  321. GET_sqlite3_stmt_INSTANCE();
  322. sq_pushuserpointer(v, self);
  323. return 1;
  324. }
  325. static SQRESULT sq_sqlite3_stmt_finalize(HSQUIRRELVM v)
  326. {
  327. SQ_FUNC_VARS_NO_TOP(v);
  328. GET_sqlite3_stmt_INSTANCE();
  329. sq_setinstanceup(v, 1, 0); //next calls will fail with "statement is closed"
  330. //printf("sq_sqlite3_stmt_finalize: %p : %s\n", self, sqlite3_sql(self));
  331. sq_pushinteger(v, sqlite3_finalize(self));
  332. return 1;
  333. }
  334. static SQRESULT sq_sqlite3_stmt_prepare(HSQUIRRELVM v)
  335. {
  336. SQ_FUNC_VARS_NO_TOP(v);
  337. GET_sqlite3_stmt_INSTANCE();
  338. sqlite3 *db = sqlite3_db_handle(self);
  339. sqlite3_stmt *stmt = 0;
  340. _rc_ = sq_sqlite3_stmt_prepare_aux(v, db, &stmt, 2);
  341. if(stmt)
  342. {
  343. sqlite3_finalize(self); //finalize the previous sqlite3_stmt
  344. sq_setinstanceup(v, 1, stmt); //replace self for this instance with this new sqlite3_stmt
  345. }
  346. return _rc_;
  347. }
  348. static SQRESULT sq_sqlite3_stmt_get_sql(HSQUIRRELVM v)
  349. {
  350. SQ_FUNC_VARS_NO_TOP(v);
  351. GET_sqlite3_stmt_INSTANCE();
  352. sq_pushstring(v, sqlite3_sql(self), -1);
  353. return 1;
  354. }
  355. static SQRESULT sq_sqlite3_stmt_bind(HSQUIRRELVM v)
  356. {
  357. SQ_FUNC_VARS_NO_TOP(v);
  358. GET_sqlite3_stmt_INSTANCE();
  359. SQ_GET_INTEGER(v, 2, npar);
  360. return sqlite3_stmt_bind_value(v, self, npar, 3);
  361. }
  362. /**
  363. The number/order of fields should be the same to use this function
  364. it'll save temporary data convertion.
  365. */
  366. static SQRESULT sq_sqlite3_stmt_bind_stmt0(HSQUIRRELVM v, int doExec)
  367. {
  368. SQ_FUNC_VARS_NO_TOP(v);
  369. GET_sqlite3_stmt_INSTANCE();
  370. GET_sqlite3_stmt_INSTANCE_AT(2, stmt_src);
  371. int rc = SQLITE_OK, bind_count = sqlite3_bind_parameter_count(self);
  372. for(int i=0; i < bind_count; ++i)
  373. {
  374. rc = sqlite3_bind_value(self, i+1, sqlite3_column_value(stmt_src, i));
  375. if(rc != SQLITE_OK) break;
  376. }
  377. if(doExec && rc == SQLITE_OK)
  378. {
  379. rc = sqlite3_step(self);
  380. sqlite3_reset(self);
  381. }
  382. sq_pushinteger(v, rc);
  383. return 1;
  384. }
  385. static SQRESULT sq_sqlite3_stmt_bind_stmt(HSQUIRRELVM v)
  386. {
  387. return sq_sqlite3_stmt_bind_stmt0(v, 0);
  388. }
  389. static SQRESULT sq_sqlite3_stmt_bind_exec_stmt(HSQUIRRELVM v)
  390. {
  391. return sq_sqlite3_stmt_bind_stmt0(v, 1);
  392. }
  393. static SQRESULT sq_sqlite3_stmt_bind_empty_null(HSQUIRRELVM v)
  394. {
  395. SQ_FUNC_VARS_NO_TOP(v);
  396. GET_sqlite3_stmt_INSTANCE();
  397. SQ_GET_INTEGER(v, 2, npar);
  398. if(sq_gettype(v, 3) == OT_STRING && sq_getsize(v, 3) == 0)
  399. {
  400. sq_pushnull(v);
  401. sq_replace(v, 3);
  402. }
  403. return sqlite3_stmt_bind_value(v, self, npar, 3);
  404. }
  405. static SQRESULT sq_sqlite3_stmt_bind_blob(HSQUIRRELVM v)
  406. {
  407. SQ_FUNC_VARS_NO_TOP(v);
  408. GET_sqlite3_stmt_INSTANCE();
  409. SQ_GET_INTEGER(v, 2, npar);
  410. SQ_GET_STRING(v, 3, blob);
  411. if(sqlite3_bind_blob(self, npar, blob, blob_size, SQLITE_TRANSIENT) != SQLITE_OK)
  412. {
  413. sqlite3 *db = sqlite3_db_handle(self);
  414. return sq_throwerror(v, sqlite3_errmsg(db));
  415. }
  416. return SQ_OK;
  417. }
  418. static SQRESULT sq_sqlite3_stmt_bind_zeroblob(HSQUIRRELVM v)
  419. {
  420. SQ_FUNC_VARS_NO_TOP(v);
  421. GET_sqlite3_stmt_INSTANCE();
  422. SQ_GET_INTEGER(v, 2, npar);
  423. SQ_GET_INTEGER(v, 3, nsize);
  424. if(sqlite3_bind_zeroblob(self, npar, nsize))
  425. {
  426. sqlite3 *db = sqlite3_db_handle(self);
  427. return sq_throwerror(v, sqlite3_errmsg(db));
  428. }
  429. return SQ_OK;
  430. }
  431. static SQRESULT sq_sqlite3_stmt_bind_values0(HSQUIRRELVM v, int isExec)
  432. {
  433. SQ_FUNC_VARS(v);
  434. GET_sqlite3_stmt_INSTANCE();
  435. if (_top_ - 1 != sqlite3_bind_parameter_count(self))
  436. return sq_throwerror(v,
  437. _SC("incorrect number of parameters to bind (%d given, %d to bind)"),
  438. _top_ - 1,
  439. sqlite3_bind_parameter_count(self));
  440. for (int n = 2; n <= _top_; ++n)
  441. {
  442. if (sqlite3_stmt_bind_value(v, self, n-1, n) != SQ_OK) return SQ_ERROR;
  443. }
  444. if(isExec)
  445. {
  446. int rc = sqlite3_step(self);
  447. sqlite3_reset(self);
  448. sq_pushinteger(v, rc);
  449. return 1;
  450. }
  451. return 0;
  452. }
  453. static SQRESULT sq_sqlite3_stmt_bind_values(HSQUIRRELVM v)
  454. {
  455. return sq_sqlite3_stmt_bind_values0(v, 0);
  456. }
  457. static SQRESULT sq_sqlite3_stmt_bind_exec(HSQUIRRELVM v)
  458. {
  459. return sq_sqlite3_stmt_bind_values0(v, 1);
  460. }
  461. static SQRESULT sq_sqlite3_stmt_bind_exec_get_one(HSQUIRRELVM v)
  462. {
  463. SQ_FUNC_VARS_NO_TOP(v);
  464. GET_sqlite3_stmt_INSTANCE();
  465. SQInteger rc = sq_sqlite3_stmt_bind_values0(v, 0);
  466. if(rc != SQ_OK) return rc;
  467. sq_getinteger(v, -1, &rc);
  468. if(rc == SQLITE_OK)
  469. {
  470. rc = sqlite3_step(self);
  471. if(rc == SQLITE_ROW) sqlite3_stmt_push_value(v, self, 0, 0);
  472. else sq_pushnull(v);
  473. sqlite3_reset(self);
  474. }
  475. else sq_pushnull(v);
  476. return 1;
  477. }
  478. static SQRESULT sq_sqlite3_stmt_bind_exec_get_first_row(HSQUIRRELVM v)
  479. {
  480. SQ_FUNC_VARS_NO_TOP(v);
  481. GET_sqlite3_stmt_INSTANCE();
  482. SQInteger rc = sq_sqlite3_stmt_bind_values0(v, 0);
  483. if(rc != SQ_OK) return rc;
  484. sq_getinteger(v, -1, &rc);
  485. if(rc == SQLITE_OK)
  486. {
  487. rc = sqlite3_step(self);
  488. if(rc == SQLITE_ROW) sqlite3_stmt_row_asArray(v, self, NULL_AS_EMPTY_STR|AS_STRING_ALWAYS);
  489. else sq_pushnull(v);
  490. sqlite3_reset(self);
  491. }
  492. else sq_pushnull(v);
  493. return 1;
  494. }
  495. static SQRESULT sq_sqlite3_stmt_bind_names(HSQUIRRELVM v)
  496. {
  497. SQ_FUNC_VARS_NO_TOP(v);
  498. GET_sqlite3_stmt_INSTANCE();
  499. SQObjectType ptype = sq_gettype(v, 2);
  500. int count = sqlite3_bind_parameter_count(self);
  501. int result;
  502. for (int n = 1; n <= count; ++n)
  503. {
  504. const char *name = sqlite3_bind_parameter_name(self, n);
  505. if (name && (name[0] == ':' || name[0] == '$' || name[0] == '@'))
  506. {
  507. if(ptype == OT_TABLE)
  508. {
  509. sq_pushstring(v, ++name, -1);
  510. if(sq_get(v, 2) == SQ_OK)
  511. {
  512. result = sqlite3_stmt_bind_value(v, self, n, -1);
  513. sq_poptop(v);
  514. }
  515. else return sq_throwerror(v, _SC("bind parameter (%s) not found"), name);
  516. }
  517. else return sq_throwerror(v, _SC("table expected to bind named parameters"));
  518. }
  519. else
  520. {
  521. if(ptype == OT_ARRAY)
  522. {
  523. sq_pushinteger(v, n);
  524. if(sq_get(v, 2) == SQ_OK)
  525. {
  526. result = sqlite3_stmt_bind_value(v, self, n, -1);
  527. sq_poptop(v);
  528. }
  529. else return sq_throwerror(v, _SC("bind parameter (%d) not found"), n);
  530. }
  531. else return sq_throwerror(v, _SC("array expected to bind numbered parameters"));
  532. }
  533. if (result != SQ_OK) return result;
  534. }
  535. return 0;
  536. }
  537. static SQRESULT sq_sqlite3_stmt_bind_parameter_index(HSQUIRRELVM v)
  538. {
  539. SQ_FUNC_VARS_NO_TOP(v);
  540. GET_sqlite3_stmt_INSTANCE();
  541. SQ_GET_STRING(v, 2, spar);
  542. sq_pushinteger(v, sqlite3_bind_parameter_index(self, spar));
  543. return 1;
  544. }
  545. static SQRESULT sq_sqlite3_stmt_bind_parameter_count(HSQUIRRELVM v)
  546. {
  547. SQ_FUNC_VARS_NO_TOP(v);
  548. GET_sqlite3_stmt_INSTANCE();
  549. sq_pushinteger(v, sqlite3_bind_parameter_count(self));
  550. return 1;
  551. }
  552. static SQRESULT sq_sqlite3_stmt_reset(HSQUIRRELVM v)
  553. {
  554. SQ_FUNC_VARS_NO_TOP(v);
  555. GET_sqlite3_stmt_INSTANCE();
  556. sq_pushinteger(v, sqlite3_reset(self));
  557. return 1;
  558. }
  559. static SQRESULT sq_sqlite3_stmt_step(HSQUIRRELVM v)
  560. {
  561. SQ_FUNC_VARS_NO_TOP(v);
  562. GET_sqlite3_stmt_INSTANCE();
  563. sq_pushinteger(v, sqlite3_step(self));
  564. return 1;
  565. }
  566. static SQRESULT sq_sqlite3_stmt_next_row(HSQUIRRELVM v)
  567. {
  568. SQ_FUNC_VARS_NO_TOP(v);
  569. GET_sqlite3_stmt_INSTANCE();
  570. sq_pushbool(v, sqlite3_step(self) == SQLITE_ROW);
  571. return 1;
  572. }
  573. static SQRESULT sq_sqlite3_stmt_col_count(HSQUIRRELVM v)
  574. {
  575. SQ_FUNC_VARS_NO_TOP(v);
  576. GET_sqlite3_stmt_INSTANCE();
  577. sq_pushinteger(v, sqlite3_column_count(self));
  578. return 1;
  579. }
  580. static SQRESULT sq_sqlite3_stmt_col_name(HSQUIRRELVM v)
  581. {
  582. SQ_FUNC_VARS_NO_TOP(v);
  583. GET_sqlite3_stmt_INSTANCE();
  584. SQ_GET_INTEGER(v, 2, col);
  585. sq_pushstring(v, sqlite3_column_name(self, col), -1);
  586. return 1;
  587. }
  588. static SQRESULT sq_sqlite3_stmt_col_type(HSQUIRRELVM v)
  589. {
  590. SQ_FUNC_VARS_NO_TOP(v);
  591. GET_sqlite3_stmt_INSTANCE();
  592. SQ_GET_INTEGER(v, 2, col);
  593. sq_pushinteger(v, sqlite3_column_type(self, col));
  594. return 1;
  595. }
  596. static const char *get_column_type(sqlite3_stmt *stmt, int col)
  597. {
  598. const char *column_type;
  599. int icol_type = sqlite3_column_type(stmt, col);
  600. switch(icol_type)
  601. {
  602. case SQLITE_INTEGER: column_type = "INTEGER"; break;
  603. case SQLITE_FLOAT: column_type = "FLOAT"; break;
  604. case SQLITE_BLOB: column_type = "BLOB"; break;
  605. case SQLITE_TEXT: column_type = "TEXT"; break;
  606. case SQLITE_NULL: column_type = "NULL"; break;
  607. default:
  608. column_type = "unknown";
  609. }
  610. return column_type;
  611. }
  612. static const char *get_column_dcltype(sqlite3_stmt *stmt, int col)
  613. {
  614. const char *column_type = sqlite3_column_decltype(stmt, col);
  615. if(!column_type) column_type = get_column_type(stmt, col);
  616. return column_type;
  617. }
  618. static SQRESULT sq_sqlite3_stmt_col_declared_type(HSQUIRRELVM v)
  619. {
  620. SQ_FUNC_VARS_NO_TOP(v);
  621. GET_sqlite3_stmt_INSTANCE();
  622. SQ_GET_INTEGER(v, 2, col);
  623. sq_pushstring(v, get_column_dcltype(self, col), -1);
  624. return 1;
  625. }
  626. static SQRESULT sq_sqlite3_stmt_colsAsArray(HSQUIRRELVM v)
  627. {
  628. SQ_FUNC_VARS_NO_TOP(v);
  629. GET_sqlite3_stmt_INSTANCE();
  630. int col_count = sqlite3_column_count(self);
  631. sq_newarray(v, col_count);
  632. for(int i=0; i<col_count; ++i)
  633. {
  634. sq_pushstring(v, sqlite3_column_name(self, i), -1);
  635. sq_arrayset(v, -2, i);
  636. }
  637. return 1;
  638. }
  639. static SQRESULT sq_sqlite3_stmt_colsTypeAsArray(HSQUIRRELVM v)
  640. {
  641. SQ_FUNC_VARS_NO_TOP(v);
  642. GET_sqlite3_stmt_INSTANCE();
  643. int col_count = sqlite3_column_count(self);
  644. sq_newarray(v, col_count);
  645. for(int i=0; i<col_count; ++i)
  646. {
  647. sq_pushstring(v, get_column_type(self, i), -1);
  648. sq_arrayset(v, -2, i);
  649. }
  650. return 1;
  651. }
  652. static SQRESULT sq_sqlite3_stmt_colsDeclTypeAsArray(HSQUIRRELVM v)
  653. {
  654. SQ_FUNC_VARS_NO_TOP(v);
  655. GET_sqlite3_stmt_INSTANCE();
  656. int col_count = sqlite3_column_count(self);
  657. sq_newarray(v, col_count);
  658. for(int i=0; i<col_count; ++i)
  659. {
  660. sq_pushstring(v, get_column_dcltype(self, i), -1);
  661. sq_arrayset(v, -2, i);
  662. }
  663. return 1;
  664. }
  665. static SQRESULT sq_sqlite3_stmt_colsNameAsArray(HSQUIRRELVM v)
  666. {
  667. SQ_FUNC_VARS_NO_TOP(v);
  668. GET_sqlite3_stmt_INSTANCE();
  669. int col_count = sqlite3_column_count(self);
  670. sq_newarray(v, col_count);
  671. for(int i=0; i<col_count; ++i)
  672. {
  673. sq_pushstring(v, sqlite3_column_name(self, i), -1);
  674. sq_arrayset(v, -2, i);
  675. }
  676. return 1;
  677. }
  678. static SQRESULT sq_sqlite3_stmt_colsAsTable(HSQUIRRELVM v)
  679. {
  680. SQ_FUNC_VARS_NO_TOP(v);
  681. GET_sqlite3_stmt_INSTANCE();
  682. int col_count = sqlite3_column_count(self);
  683. sq_newtable(v);
  684. for(int i=0; i<col_count; ++i)
  685. {
  686. sq_pushstring(v, sqlite3_column_name(self, i), -1);
  687. sq_pushinteger(v, i);
  688. sq_rawset(v, -3);
  689. }
  690. return 1;
  691. }
  692. static int get_col_index(HSQUIRRELVM v, sqlite3_stmt *self)
  693. {
  694. SQInteger _rc_, col;
  695. switch(sq_gettype(v, 2))
  696. {
  697. case OT_INTEGER:
  698. sq_getinteger(v, 2, &col);
  699. break;
  700. case OT_STRING:
  701. {
  702. SQ_GET_STRING(v, 2, col_name);
  703. if(col_name_size == 0) return sq_throwerror(v, "column name can not be empty");
  704. col = -1;
  705. for(int i=0, len=sqlite3_column_count(self); i<len; ++i)
  706. {
  707. if(strcasecmp(col_name, sqlite3_column_name(self, i)) == 0)
  708. {
  709. col = i;
  710. break;
  711. }
  712. }
  713. if(col == -1) return sq_throwerror(v, "column name not found \"%s\"", col_name);
  714. }
  715. break;
  716. default:
  717. return sq_throwerror(v, "wrong parameter expected integer|string");
  718. }
  719. return col;
  720. }
  721. static SQRESULT sq_sqlite3_stmt_col(HSQUIRRELVM v)
  722. {
  723. SQ_FUNC_VARS_NO_TOP(v);
  724. GET_sqlite3_stmt_INSTANCE();
  725. int col = get_col_index(v, self);
  726. if(col < 0) return col;
  727. sqlite3_stmt_push_value(v, self, col, 0);
  728. return 1;
  729. }
  730. static SQRESULT sq_sqlite3_stmt_col_slice(HSQUIRRELVM v)
  731. {
  732. SQ_FUNC_VARS_NO_TOP(v);
  733. GET_sqlite3_stmt_INSTANCE();
  734. int col = get_col_index(v, self);
  735. if(col < 0) return col;
  736. SQ_GET_INTEGER(v, 3, start_pos);
  737. SQ_GET_INTEGER(v, 4, size);
  738. if((start_pos < 0) || (size < 0))
  739. return sq_throwerror(v, _SC("slice start_pos or size can't be negative"));
  740. const char *value = NULL;
  741. int col_type = sqlite3_column_type(self, col);
  742. switch (col_type)
  743. {
  744. case SQLITE_TEXT:
  745. value = (const char*) sqlite3_column_text(self, col);
  746. break;
  747. case SQLITE_BLOB:
  748. value = (const char*) sqlite3_column_blob(self, col);
  749. break;
  750. case SQLITE_NULL:
  751. break;
  752. default:
  753. return sq_throwerror(v, _SC("column type do not allow slice %d:%d"), col, col_type);
  754. }
  755. if(value)
  756. {
  757. int col_size = sqlite3_column_bytes(self, col);
  758. if(col_size > start_pos)
  759. {
  760. int space_left = col_size - start_pos;
  761. sq_pushstring(v, value + start_pos, (space_left > size) ? size : space_left);
  762. }
  763. else value = NULL;
  764. }
  765. if(!value) push_sqlite3_null(v);
  766. return 1;
  767. }
  768. static SQRESULT sq_sqlite3_stmt_asBool(HSQUIRRELVM v)
  769. {
  770. SQ_FUNC_VARS_NO_TOP(v);
  771. GET_sqlite3_stmt_INSTANCE();
  772. int col = get_col_index(v, self);
  773. if(col < 0) return col;
  774. const unsigned char *b = sqlite3_column_text(self, col);
  775. sq_pushbool(v, b && *b == '1');
  776. return 1;
  777. }
  778. static SQRESULT sq_sqlite3_stmt_asInteger(HSQUIRRELVM v)
  779. {
  780. SQ_FUNC_VARS_NO_TOP(v);
  781. GET_sqlite3_stmt_INSTANCE();
  782. int col = get_col_index(v, self);
  783. if(col < 0) return col;
  784. sq_pushinteger(v, sqlite3_column_int64(self, col));
  785. return 1;
  786. }
  787. static SQRESULT sq_sqlite3_stmt_asFloat(HSQUIRRELVM v)
  788. {
  789. SQ_FUNC_VARS_NO_TOP(v);
  790. GET_sqlite3_stmt_INSTANCE();
  791. int col = get_col_index(v, self);
  792. if(col < 0) return col;
  793. sq_pushfloat(v, sqlite3_column_double(self, col));
  794. return 1;
  795. }
  796. static SQRESULT sq_sqlite3_stmt_StringOrNull(HSQUIRRELVM v, int withNull)
  797. {
  798. SQ_FUNC_VARS_NO_TOP(v);
  799. GET_sqlite3_stmt_INSTANCE();
  800. int col = get_col_index(v, self);
  801. if(col < 0) return col;
  802. sqlite3_stmt_push_string(v, self, col, withNull ? 0 : NULL_AS_EMPTY_STR);
  803. return 1;
  804. }
  805. static SQRESULT sq_sqlite3_stmt_asString(HSQUIRRELVM v)
  806. {
  807. return sq_sqlite3_stmt_StringOrNull(v, 0);
  808. }
  809. static SQRESULT sq_sqlite3_stmt_asStringOrNull(HSQUIRRELVM v)
  810. {
  811. return sq_sqlite3_stmt_StringOrNull(v, 1);
  812. }
  813. static SQRESULT sq_sqlite3_stmt_asTable(HSQUIRRELVM v)
  814. {
  815. SQ_FUNC_VARS(v);
  816. GET_sqlite3_stmt_INSTANCE();
  817. SQ_OPT_INTEGER(v, 2, flags, 0);
  818. sqlite3_stmt_row_asTable(v, self, flags);
  819. return 1;
  820. }
  821. static SQRESULT sq_sqlite3_stmt_asArray(HSQUIRRELVM v)
  822. {
  823. SQ_FUNC_VARS(v);
  824. GET_sqlite3_stmt_INSTANCE();
  825. SQ_OPT_INTEGER(v, 2, flags, 0);
  826. sqlite3_stmt_row_asArray(v, self, flags);
  827. return 1;
  828. }
  829. static SQRESULT sq_sqlite3_stmt_asArrayOfArrays(HSQUIRRELVM v)
  830. {
  831. SQ_FUNC_VARS(v);
  832. GET_sqlite3_stmt_INSTANCE();
  833. SQ_OPT_INTEGER(v, 2, flags, 0);
  834. sqlite3_stmt_asArrayOfArrays(v, self, flags);
  835. sqlite3_reset(self);
  836. return 1;
  837. }
  838. static SQRESULT sq_sqlite3_stmt_asArrayOfTables(HSQUIRRELVM v)
  839. {
  840. SQ_FUNC_VARS(v);
  841. GET_sqlite3_stmt_INSTANCE();
  842. SQ_OPT_INTEGER(v, 2, flags, 0);
  843. sqlite3_stmt_asArrayOfTables(v, self, flags);
  844. sqlite3_reset(self);
  845. return 1;
  846. }
  847. /*utility functions*/
  848. static void append_escaping_json(SQBlob &json, const char *sz)
  849. {
  850. if(sz) //escape string
  851. {
  852. int last_idx, idx;
  853. idx = last_idx = 0;
  854. for(; sz[idx]; ++idx)
  855. {
  856. char c = sz[idx];
  857. switch(c)
  858. {
  859. case '"':
  860. case '\n':
  861. case '\r':
  862. case '\t':
  863. case '\b':
  864. case '\f':
  865. case '\\':
  866. {
  867. json.Write(sz+last_idx, idx-last_idx);
  868. last_idx = idx;
  869. if(c == '\n')
  870. {
  871. json.Write("\\n", 2);
  872. ++last_idx;
  873. }
  874. else if(c == '\t')
  875. {
  876. json.Write("\\t", 2);
  877. ++last_idx;
  878. }
  879. else if(c == '\b')
  880. {
  881. json.Write("\\b", 2);
  882. ++last_idx;
  883. }
  884. else if(c == '\f')
  885. {
  886. json.Write("\\f", 2);
  887. ++last_idx;
  888. }
  889. else if(c == '\r')
  890. {
  891. json.Write("\\r", 2);
  892. ++last_idx;
  893. }
  894. else
  895. {
  896. json.Write("\\", 1);
  897. }
  898. }
  899. }
  900. }
  901. //last part
  902. json.Write(sz+last_idx, idx-last_idx);
  903. }
  904. }
  905. static SQRESULT sq_sqlite3_stmt_asJsonArray(HSQUIRRELVM v)
  906. {
  907. SQ_FUNC_VARS(v);
  908. GET_sqlite3_stmt_INSTANCE();
  909. SQ_OPT_BOOL(v, 2, withMetadata, 0);
  910. int col_count = sqlite3_column_count(self);
  911. int i, value_type;
  912. const char* value;
  913. SQBlob *json = NULL;
  914. int has_blob = getOptionalBlob(v, 3, &json);
  915. if(has_blob == SQ_ERROR) return SQ_ERROR;
  916. if(withMetadata)
  917. {
  918. json->WriteZstr("{\n\"columns\":[\n");
  919. for(i=0; i < col_count; ++i)
  920. {
  921. json->WriteZstr((i == 0 ? "\"" : ",\""));
  922. const char *column_name = sqlite3_column_name(self, i);
  923. json->WriteZstr(column_name ? column_name : "unknown");
  924. json->WriteZstr("\"");
  925. }
  926. json->WriteZstr("\n],\n\"column_types\":[\n");
  927. for(i=0; i < col_count; ++i)
  928. {
  929. json->WriteZstr((i == 0 ? "\"" : ",\""));
  930. json->WriteZstr(get_column_dcltype(self, i));
  931. json->WriteZstr("\"");
  932. }
  933. json->WriteZstr("\n],\n\"rows\":[\n");
  934. }
  935. else
  936. {
  937. json->WriteZstr("[\n");
  938. }
  939. int row_count = 0;
  940. while(sqlite3_step(self) == SQLITE_ROW)
  941. {
  942. json->WriteZstr((row_count++ == 0 ? "[" : ",["));
  943. for(i=0; i < col_count; ++i)
  944. {
  945. json->WriteZstr((i == 0 ? "\"" : ",\""));
  946. //if get the type after sqlite3_column_text it always returns SQLITE_TEXT
  947. value_type = sqlite3_column_type(self, i);
  948. value = (const char*)sqlite3_column_text(self, i);
  949. if(value)
  950. {
  951. switch(value_type)
  952. {
  953. case SQLITE_BLOB:
  954. break; //no blobs in json
  955. case SQLITE_TEXT:
  956. {
  957. append_escaping_json(*json, value);
  958. }
  959. break;
  960. default:
  961. json->WriteZstr(value);
  962. }
  963. }
  964. json->WriteZstr("\"");
  965. }
  966. json->WriteZstr("]\n");
  967. }
  968. json->WriteZstr("]");
  969. if(withMetadata) json->WriteZstr("\n}");
  970. if(has_blob) return 0;
  971. sq_pushstring(v, (const SQChar*)json->GetBuf(), json->Len());
  972. delete json;
  973. return 1;
  974. }
  975. static SQRESULT sq_sqlite3_stmt_asJsonObject(HSQUIRRELVM v)
  976. {
  977. SQ_FUNC_VARS_NO_TOP(v);
  978. GET_sqlite3_stmt_INSTANCE();
  979. int col_count = sqlite3_column_count(self);
  980. int i, value_type, record_count = 0;
  981. const char* value;
  982. SQBlob *json = NULL;
  983. int has_blob = getOptionalBlob(v, 2, &json);
  984. if(has_blob == SQ_ERROR) return SQ_ERROR;
  985. json->WriteZstr("{");
  986. if(sqlite3_step(self) == SQLITE_ROW)
  987. {
  988. ++record_count;
  989. for(i=0; i < col_count; ++i)
  990. {
  991. json->WriteZstr((i == 0 ? "\"" : "\",\""));
  992. append_escaping_json(*json, (const char*)sqlite3_column_name(self, i));
  993. json->WriteZstr("\":\"");
  994. //if get the type after sqlite3_column_text it always returns SQLITE_TEXT
  995. value_type = sqlite3_column_type(self, i);
  996. value = (const char*)sqlite3_column_text(self, i);
  997. if(value)
  998. {
  999. switch(value_type)
  1000. {
  1001. case SQLITE_BLOB:
  1002. break; //no blobs in json
  1003. case SQLITE_TEXT:
  1004. {
  1005. append_escaping_json(*json, value);
  1006. }
  1007. break;
  1008. default:
  1009. json->WriteZstr(value);
  1010. }
  1011. }
  1012. }
  1013. json->WriteZstr("\"");
  1014. }
  1015. json->WriteZstr("}");
  1016. if(has_blob) return 0;
  1017. if(record_count) sq_pushstring(v, (const SQChar*)json->GetBuf(), json->Len());
  1018. else sq_pushnull(v);
  1019. delete json;
  1020. return 1;
  1021. }
  1022. #define UNSIGNED(n) n##U
  1023. #define IBYTE_MAX UNSIGNED(256)
  1024. #define IBYTE1 UNSIGNED(240)
  1025. #define IBYTE2 UNSIGNED(2287)
  1026. #define IBYTE3 UNSIGNED(67823)
  1027. #define IBYTE4 UNSIGNED(16777215)
  1028. #define SLEMARK 254
  1029. #define SLEEND 255
  1030. static SQRESULT sle2array(HSQUIRRELVM v, const unsigned char *p, size_t sle_size, const unsigned char **next)
  1031. {
  1032. size_t size, data_len = 0;
  1033. if(sle_size == 0)
  1034. {
  1035. *next = 0;
  1036. return 0;
  1037. }
  1038. while(*p != SLEEND) //data finished now follow digest
  1039. {
  1040. size = *p++;
  1041. if(size > IBYTE1)
  1042. {
  1043. if(size <= 248)
  1044. {
  1045. size = (size-241)*IBYTE_MAX + (*p++) + IBYTE1;
  1046. }
  1047. else if(size == 249)
  1048. {
  1049. const unsigned char *p1 = p++, *p2 = p++;
  1050. size = 2288 + (IBYTE_MAX * (*p1)) + (*p2);
  1051. }
  1052. else if(size == 250)
  1053. {
  1054. const unsigned char *p1 = p++, *p2 = p++, *p3 = p++;
  1055. size = ((*p1)<<16) + ((*p2)<<8) + (*p3);
  1056. }
  1057. else if(size == 251)
  1058. {
  1059. const unsigned char *p1 = p++, *p2 = p++, *p3 = p++, *p4 = p++;
  1060. size = ((*p1)<<24) + ((*p2)<<16) + ((*p3)<<8) + (*p4);
  1061. }
  1062. else if(size == SLEMARK)
  1063. {
  1064. //reserved can be used for multi part data, metadata, digest, ...
  1065. break;
  1066. }
  1067. }
  1068. sq_pushstring(v, (const char*)p, size);
  1069. sq_arrayappend(v, -2);
  1070. p += size;
  1071. data_len += size;
  1072. if(data_len > sle_size)
  1073. {
  1074. //something went wrong here
  1075. return sq_throwerror(v, "We got more data than expected !");
  1076. }
  1077. }
  1078. *next = ++p;
  1079. return 0;
  1080. }
  1081. static SQRESULT sle2vec(HSQUIRRELVM v, const unsigned char *sle,
  1082. size_t sle_size,
  1083. const unsigned char **next)
  1084. {
  1085. int rc;
  1086. sq_newarray(v, 0);
  1087. if(sle[0] != '[')
  1088. {
  1089. return sq_throwerror(v, "Invalid encoded vector !");
  1090. }
  1091. if(sle[1] == ']')
  1092. {
  1093. *next = sle+2; //empty array
  1094. return 0;
  1095. }
  1096. if((rc = sle2array(v, sle+1, sle_size-1, next)) < 0) return rc;
  1097. if(!*next || *next[0] != ']')
  1098. {
  1099. return sq_throwerror(v, "Invalid end of vector !");
  1100. }
  1101. (*next)++;
  1102. return 0;
  1103. }
  1104. static SQRESULT sq_sle2vecOfvec(HSQUIRRELVM v)
  1105. {
  1106. SQ_FUNC_VARS(v);
  1107. SQBlob *blob = NULL;
  1108. const SQChar *sle, *sle_start;
  1109. SQInteger sle_size;
  1110. SQObjectType ptype = sq_gettype(v, 2);
  1111. switch(ptype)
  1112. {
  1113. case OT_STRING:
  1114. sq_getstr_and_size(v, 2, &sle, &sle_size);
  1115. break;
  1116. case OT_INSTANCE:
  1117. if(SQ_FAILED(sq_getinstanceup(v,2,(SQUserPointer*)&blob,(SQUserPointer)SQBlob::SQBlob_TAG)))
  1118. return sq_throwerror(v,_SC("invalid type tag"));
  1119. if(!blob || !blob->IsValid())
  1120. return sq_throwerror(v,_SC("the blob is invalid"));
  1121. sle = (const SQChar*)blob->GetBuf();
  1122. sle_size = blob->Len();
  1123. break;
  1124. default:
  1125. return sq_throwerror(v,_SC("invalid parameter 1 of type %s"), sq_gettypename(v, 2));
  1126. }
  1127. if(sq_gettype(v, 3) != OT_ARRAY)
  1128. return sq_throwerror(v,_SC("invalid parameter 2 of type %s"), sq_gettypename(v, 3));
  1129. SQ_OPT_INTEGER(v, 4, start, 0);
  1130. if(start < 0) return sq_throwerror(v, _SC("invalid start position (%d)"), start);
  1131. sq_push(v, 3);
  1132. int rc, data_count = 1;
  1133. const unsigned char *next;
  1134. sle_start = sle + start;
  1135. sle_size -= start;
  1136. if(sle_start[0] != '[')
  1137. {
  1138. return sq_throwerror(v, "Invalid encoded vector !");
  1139. }
  1140. if(sle_start[1] == ']')
  1141. {
  1142. //sq_pushinteger(v, start+2);
  1143. return 1; //empty array
  1144. }
  1145. int saved_top = sq_gettop(v);
  1146. if((rc=sle2vec(v, (const unsigned char *)sle_start+1, sle_size-1, &next)) < 0) return rc;
  1147. while(next && *next == '[')
  1148. {
  1149. sq_arrayappend(v, -2);
  1150. data_count++;
  1151. if((rc=sle2vec(v, next, sle_size - (next - (const unsigned char *)sle_start), &next)) < 0) return rc;
  1152. }
  1153. if(sq_gettop(v) != saved_top)
  1154. {
  1155. //last added table left
  1156. sq_arrayappend(v, -2);
  1157. data_count++;
  1158. }
  1159. if(!next || *next != ']')
  1160. {
  1161. return sq_throwerror(v, "Invalid end of vector !");
  1162. }
  1163. sq_pushinteger(v, ((const SQChar*)(++next)) - sle);
  1164. return 1;
  1165. }
  1166. typedef unsigned char slebuf_t[8];
  1167. static int sleSize2buf(slebuf_t sle, size_t size)
  1168. {
  1169. size_t next_size;
  1170. if(size <= IBYTE1)
  1171. {
  1172. sle[0] = size;
  1173. return 1;
  1174. }
  1175. else if(size <= IBYTE2)
  1176. {
  1177. next_size = size - IBYTE1;
  1178. sle[0] = next_size/IBYTE_MAX + 241;
  1179. sle[1] = next_size%IBYTE_MAX;
  1180. return 2;
  1181. }
  1182. else if(size <= IBYTE3)
  1183. {
  1184. sle[0] = 249;
  1185. next_size = size - 2288;
  1186. sle[1] = next_size/IBYTE_MAX;
  1187. sle[2] = next_size%IBYTE_MAX;
  1188. return 3;
  1189. }
  1190. else if(size <= IBYTE4)
  1191. {
  1192. sle[0] = 250;
  1193. sle[1] = size >> 16;
  1194. sle[2] = size >> 8;
  1195. sle[3] = size;
  1196. return 4;
  1197. }
  1198. else
  1199. {
  1200. sle[0] = 251;
  1201. sle[1] = size >> 24;
  1202. sle[2] = size >> 16;
  1203. sle[3] = size >> 8;
  1204. sle[4] = size;
  1205. return 5;
  1206. }
  1207. return 0;
  1208. }
  1209. static SQRESULT sq_get_sle_size(HSQUIRRELVM v)
  1210. {
  1211. SQ_FUNC_VARS_NO_TOP(v);
  1212. slebuf_t slebuf;
  1213. SQ_GET_INTEGER(v, 2, size);
  1214. int slesize = sleSize2buf(slebuf, size);
  1215. if(slesize)
  1216. {
  1217. sq_pushstring(v, (const char *)slebuf, slesize);
  1218. return 1;
  1219. }
  1220. return 0;
  1221. }
  1222. static int add2sle(SQBlob &sle, const char *str, size_t size)
  1223. {
  1224. slebuf_t slebuf;
  1225. int slesize = sleSize2buf(slebuf, size);
  1226. if(slesize) sle.Write((const char *)slebuf, slesize);
  1227. if(size) sle.Write(str, size);
  1228. return size;
  1229. }
  1230. static SQRESULT sq_add2sle(HSQUIRRELVM v)
  1231. {
  1232. SQ_FUNC_VARS(v);
  1233. SQ_GET_INSTANCE_VAR(v, 2, SQBlob, blob, SQBlob::SQBlob_TAG);
  1234. SQ_GET_STRING(v, 3, str);
  1235. SQ_OPT_INTEGER(v, 4, size, str_size);
  1236. if(size < 0) return sq_throwerror(v, _SC("invalid size value (%d)"), size);
  1237. sq_pushinteger(v, add2sle(*blob, str, size));
  1238. return 1;
  1239. }
  1240. static SQRESULT sq_sqlite3_stmt_asSleArray(HSQUIRRELVM v)
  1241. {
  1242. SQ_FUNC_VARS_NO_TOP(v);
  1243. GET_sqlite3_stmt_INSTANCE();
  1244. int col_count = sqlite3_column_count(self);
  1245. int i;
  1246. const char *value;
  1247. SQBlob *sle = NULL;
  1248. int has_blob = getOptionalBlob(v, 2, &sle);
  1249. if(has_blob == SQ_ERROR) return SQ_ERROR;
  1250. sle->WriteZstr("[[");
  1251. for(i=0; i < col_count; ++i)
  1252. {
  1253. value = sqlite3_column_name(self, i);
  1254. add2sle(*sle, value, strlen(value));
  1255. }
  1256. sle->WriteChar(SLEEND);
  1257. sle->WriteChar(']');
  1258. while(sqlite3_step(self) == SQLITE_ROW)
  1259. {
  1260. sle->WriteChar('[');
  1261. for(i=0; i < col_count; ++i)
  1262. {
  1263. switch(sqlite3_column_type(self, i))
  1264. {
  1265. case SQLITE_BLOB:
  1266. {
  1267. add2sle(*sle, (const char*)sqlite3_column_blob(self, i),
  1268. sqlite3_column_bytes(self, i));
  1269. }
  1270. break;
  1271. default:
  1272. add2sle(*sle, (const char*)sqlite3_column_text(self, i),
  1273. sqlite3_column_bytes(self, i));
  1274. }
  1275. }
  1276. sle->WriteChar(SLEEND);
  1277. sle->WriteChar(']');
  1278. }
  1279. sle->WriteChar(']');
  1280. if(has_blob) return 0;
  1281. sq_pushstring(v, (const SQChar*)sle->GetBuf(), sle->Len());
  1282. delete sle;
  1283. return 1;
  1284. }
  1285. static SQRESULT sq_sqlite3_stmt_all_blobs_size(HSQUIRRELVM v)
  1286. {
  1287. SQ_FUNC_VARS_NO_TOP(v);
  1288. GET_sqlite3_stmt_INSTANCE();
  1289. int total_size = 0, col_count = sqlite3_column_count(self);
  1290. for(int i=0; i < col_count; ++i)
  1291. {
  1292. if(sqlite3_column_type(self, i) == SQLITE_BLOB)
  1293. {
  1294. total_size += sqlite3_column_bytes(self, i);
  1295. }
  1296. }
  1297. sq_pushinteger(v, total_size);
  1298. return 1;
  1299. }
  1300. static SQRESULT sq_sqlite3_stmt_colsSizeAsArray(HSQUIRRELVM v)
  1301. {
  1302. SQ_FUNC_VARS_NO_TOP(v);
  1303. GET_sqlite3_stmt_INSTANCE();
  1304. int col_count = sqlite3_column_count(self);
  1305. sq_newarray(v, col_count);
  1306. for(int i=0; i<col_count; ++i)
  1307. {
  1308. sq_pushinteger(v, sqlite3_column_bytes(self, i));
  1309. sq_arrayset(v, -2, i);
  1310. }
  1311. return 1;
  1312. }
  1313. #define _DECL_FUNC(name,nparams,tycheck, isStatic) {_SC(#name), sq_sqlite3_stmt_##name,nparams,tycheck, isStatic}
  1314. static SQRegFunction sq_sqlite3_stmt_methods[] =
  1315. {
  1316. _DECL_FUNC(constructor, -2, _SC("xxs s|n|b|o"), SQFalse),
  1317. _DECL_FUNC(stmt_ptr, 1, _SC("x"), SQFalse),
  1318. _DECL_FUNC(get_db, 1, _SC("x"), SQFalse),
  1319. _DECL_FUNC(finalize, 1, _SC("x"), SQFalse),
  1320. _DECL_FUNC(prepare, -2, _SC("xs s|n|b|o|u"), SQFalse),
  1321. _DECL_FUNC(get_sql, 1, _SC("x"), SQFalse),
  1322. _DECL_FUNC(bind, 3, _SC("xi s|n|b|o|u"), SQFalse),
  1323. _DECL_FUNC(bind_stmt, 2, _SC("xx"), SQFalse),
  1324. _DECL_FUNC(bind_exec_stmt, 2, _SC("xx"), SQFalse),
  1325. _DECL_FUNC(bind_empty_null, 3, _SC("xi s|n|b|o|u"), SQFalse),
  1326. _DECL_FUNC(bind_blob, 3, _SC("xis|u"), SQFalse),
  1327. _DECL_FUNC(bind_zeroblob, 3, _SC("xii"), SQFalse),
  1328. _DECL_FUNC(bind_values, -2, _SC("x s|n|b|o|u"), SQFalse),
  1329. _DECL_FUNC(bind_exec, -2, _SC("x s|n|b|o|u"), SQFalse),
  1330. _DECL_FUNC(bind_exec_get_one, -2, _SC("x s|n|b|o|u"), SQFalse),
  1331. _DECL_FUNC(bind_exec_get_first_row, -2, _SC("x s|n|b|o|u"), SQFalse),
  1332. _DECL_FUNC(bind_names, 2, _SC("x t|a"), SQFalse),
  1333. _DECL_FUNC(bind_parameter_index, 2, _SC("xs"), SQFalse),
  1334. _DECL_FUNC(bind_parameter_count, 1, _SC("x"), SQFalse),
  1335. _DECL_FUNC(step, 1, _SC("x"), SQFalse),
  1336. _DECL_FUNC(reset, 1, _SC("x"), SQFalse),
  1337. _DECL_FUNC(next_row, 1, _SC("x"), SQFalse),
  1338. _DECL_FUNC(colsAsArray, 1, _SC("x"), SQFalse),
  1339. _DECL_FUNC(colsAsTable, 1, _SC("x"), SQFalse),
  1340. _DECL_FUNC(colsTypeAsArray, 1, _SC("x"), SQFalse),
  1341. _DECL_FUNC(colsDeclTypeAsArray, 1, _SC("x"), SQFalse),
  1342. _DECL_FUNC(col_count, 1, _SC("x"), SQFalse),
  1343. _DECL_FUNC(col_name, 2, _SC("xi"), SQFalse),
  1344. _DECL_FUNC(colsNameAsArray, 1, _SC("x"), SQFalse),
  1345. _DECL_FUNC(col_type, 2, _SC("xi"), SQFalse),
  1346. _DECL_FUNC(col_declared_type, 2, _SC("xi"), SQFalse),
  1347. _DECL_FUNC(asArray, -1, _SC("xi"), SQFalse),
  1348. _DECL_FUNC(asTable, -1, _SC("xi"), SQFalse),
  1349. _DECL_FUNC(asArrayOfArrays, -1, _SC("xi"), SQFalse),
  1350. _DECL_FUNC(asArrayOfTables, -1, _SC("xi"), SQFalse),
  1351. _DECL_FUNC(asSleArray, -1, _SC("xx"), SQFalse),
  1352. //todo manage/skip blobs for json
  1353. _DECL_FUNC(asJsonArray, -1, _SC("xbx"), SQFalse),
  1354. _DECL_FUNC(asJsonObject, -1, _SC("xx"), SQFalse),
  1355. _DECL_FUNC(col, 2, _SC("x i|s"), SQFalse),
  1356. _DECL_FUNC(col_slice, 4, _SC("x i|s ii"), SQFalse),
  1357. _DECL_FUNC(asString, 2, _SC("x i|s"), SQFalse),
  1358. _DECL_FUNC(asStringOrNull, 2, _SC("x i|s"), SQFalse),
  1359. _DECL_FUNC(asInteger, 2, _SC("x i|s"), SQFalse),
  1360. _DECL_FUNC(asBool, 2, _SC("x i|s"), SQFalse),
  1361. _DECL_FUNC(asFloat, 2, _SC("x i|s"), SQFalse),
  1362. _DECL_FUNC(all_blobs_size, 1, _SC("x"), SQFalse),
  1363. _DECL_FUNC(colsSizeAsArray, 1, _SC("x"), SQFalse),
  1364. {0,0}
  1365. };
  1366. #undef _DECL_FUNC
  1367. #ifdef SQLITE_ENABLE_SESSION
  1368. static const SQChar *SQLite3_Session_TAG = "SQLite3Session";
  1369. static SQRESULT get_sqlite3_session_instance(HSQUIRRELVM v, SQInteger idx, sqlite3_session **session)
  1370. {
  1371. SQRESULT _rc_;
  1372. if((_rc_ = sq_getinstanceup(v,idx,(SQUserPointer*)session,(void*)SQLite3_Session_TAG)) < 0) return _rc_;
  1373. if(!*session) return sq_throwerror(v, _SC("session is closed"));
  1374. return _rc_;
  1375. }
  1376. #define GET_sqlite3_session_INSTANCE_AT(idx, var_name) \
  1377. sqlite3_session *var_name=NULL; \
  1378. if((_rc_ = get_sqlite3_session_instance(v,idx,&var_name)) < 0) return _rc_;
  1379. #define GET_sqlite3_session_INSTANCE() GET_sqlite3_session_INSTANCE_AT(1, self)
  1380. static SQRESULT sq_sqlite3_session_releasehook(SQUserPointer p, SQInteger size, void */*ep*/)
  1381. {
  1382. sqlite3_session *session = ((sqlite3_session *)p);
  1383. if(session) sqlite3session_delete(session);
  1384. return 0;
  1385. }
  1386. static SQRESULT sq_sqlite3_session_constructor(HSQUIRRELVM v)
  1387. {
  1388. SQ_FUNC_VARS(v);
  1389. _rc_ = SQ_ERROR;
  1390. GET_sqlite3_INSTANCE_AT(2);
  1391. SQ_OPT_STRING(v, 3, dbname, _SC("main"))
  1392. sqlite3_session *session = 0;
  1393. if(sqlite3session_create(self, dbname, &session) != SQLITE_OK)
  1394. {
  1395. _rc_ = sq_throwerror(v, sqlite3_errmsg(self));
  1396. }
  1397. else _rc_ = SQ_OK;
  1398. sq_setinstanceup(v, 1, session); //replace self for this instance with this new sqlite3_stmt
  1399. sq_setreleasehook(v,1, sq_sqlite3_session_releasehook);
  1400. return _rc_;
  1401. }
  1402. static SQRESULT sq_sqlite3_session_attach(HSQUIRRELVM v)
  1403. {
  1404. SQ_FUNC_VARS(v);
  1405. GET_sqlite3_session_INSTANCE();
  1406. SQ_OPT_STRING(v, 2, tables, NULL);
  1407. sq_pushinteger(v, sqlite3session_attach(self, tables));
  1408. return 1;
  1409. }
  1410. static SQRESULT sq_sqlite3_session_delete(HSQUIRRELVM v)
  1411. {
  1412. SQ_FUNC_VARS_NO_TOP(v);
  1413. GET_sqlite3_session_INSTANCE();
  1414. sqlite3session_delete(self);
  1415. sq_setinstanceup(v, 1, 0); //next calls will fail with "database is closed"
  1416. return 0;
  1417. }
  1418. static SQRESULT sq_sqlite3_session_changeset(HSQUIRRELVM v)
  1419. {
  1420. SQ_FUNC_VARS_NO_TOP(v);
  1421. GET_sqlite3_session_INSTANCE();
  1422. int nChangeset; /* OUT: Size of changeset blob in bytes */
  1423. void *pChangeset; /* OUT: Pointer to changeset blob */
  1424. if(sqlite3session_changeset(self, &nChangeset, &pChangeset) != SQ_OK) return SQ_ERROR;
  1425. sq_pushstring(v, (SQChar*)pChangeset, nChangeset);
  1426. sqlite3_free(pChangeset);
  1427. return 1;
  1428. }
  1429. static int xConflict(void *pCtx, int eConflict, sqlite3_changeset_iter *pIter){
  1430. int ret = (int)(ptrdiff_t)pCtx;
  1431. return ret;
  1432. }
  1433. static SQRESULT sq_sqlite3_session_apply(HSQUIRRELVM v)
  1434. {
  1435. SQ_FUNC_VARS_NO_TOP(v);
  1436. GET_sqlite3_session_INSTANCE();
  1437. GET_sqlite3_INSTANCE_AT_VAR(2, db);
  1438. SQ_GET_STRING(v, 3, changeset);
  1439. if(sqlite3changeset_apply(db, changeset_size, (void*)changeset, 0, xConflict, (void*)0) != SQ_OK) return SQ_ERROR;
  1440. return 0;
  1441. }
  1442. #define _DECL_FUNC(name,nparams,tycheck, isStatic) {_SC(#name), sq_sqlite3_session_##name,nparams,tycheck, isStatic}
  1443. static SQRegFunction sq_sqlite3_session_methods[] =
  1444. {
  1445. _DECL_FUNC(constructor, -2, _SC("xxs"), SQFalse),
  1446. _DECL_FUNC(attach, -1, _SC("xs"), SQFalse),
  1447. _DECL_FUNC(changeset, 1, _SC("x"), SQFalse),
  1448. _DECL_FUNC(delete, 1, _SC("x"), SQFalse),
  1449. _DECL_FUNC(apply, 3, _SC("xxs"), SQFalse),
  1450. {0,0}
  1451. };
  1452. #undef _DECL_FUNC
  1453. #endif // SQLITE_ENABLE_SESSION
  1454. static SQRESULT sqlite3_exec_fmt(HSQUIRRELVM v, e_type_result type_result, int null_as_empty_str=1)
  1455. {
  1456. SQ_FUNC_VARS_NO_TOP(v);
  1457. GET_sqlite3_INSTANCE();
  1458. //SQ_GET_STRING(v, 2, szSQL);
  1459. sqlite3_stmt *stmt = 0;
  1460. SQObjectType ptype = sq_gettype(v, 2);
  1461. switch(ptype)
  1462. {
  1463. case OT_STRING:
  1464. _rc_ = sq_sqlite3_stmt_prepare_aux(v, self, &stmt, 2);
  1465. if(_rc_ < 0)
  1466. {
  1467. if(stmt) sqlite3_finalize(stmt);
  1468. return _rc_;
  1469. }
  1470. break;
  1471. case OT_INSTANCE:
  1472. _rc_ = get_sqlite3_stmt_instance(v, 2, &stmt);
  1473. if(_rc_ < 0) return _rc_;
  1474. _rc_ = sq_sqlite3_stmt_bind_vargv(v, self, stmt, 2);
  1475. if(_rc_ < 0) return _rc_;
  1476. break;
  1477. }
  1478. int rc = sqlite3_step(stmt);
  1479. if(type_result == tr_ddml)
  1480. {
  1481. if(rc != SQLITE_DONE)
  1482. {
  1483. if(ptype == OT_STRING) sqlite3_finalize(stmt);
  1484. else sqlite3_reset(stmt);
  1485. return sq_throwerror(v, "SQL is not a DDML %d %s", rc, sqlite3_errmsg(self));
  1486. }
  1487. sq_pushinteger(v, sqlite3_changes(sqlite3_db_handle(stmt)));
  1488. }
  1489. else
  1490. {
  1491. if(rc != SQLITE_ROW)
  1492. {
  1493. if(ptype == OT_STRING) sqlite3_finalize(stmt);
  1494. else sqlite3_reset(stmt);
  1495. return sq_throwerror(v, "%d %s", rc, sqlite3_errmsg(self));
  1496. }
  1497. switch(type_result)
  1498. {
  1499. case tr_first_row_first_col:
  1500. sqlite3_stmt_push_value(v, stmt, 0, 0);
  1501. break;
  1502. case tr_first_row:
  1503. sqlite3_stmt_row_asArray(v, stmt, NULL_AS_EMPTY_STR|AS_STRING_ALWAYS);
  1504. break;
  1505. case tr_all_rows:
  1506. sqlite3_stmt_asArrayOfArrays(v, stmt, NULL_AS_EMPTY_STR|AS_STRING_ALWAYS);
  1507. break;
  1508. default:
  1509. if(ptype == OT_STRING) sqlite3_finalize(stmt);
  1510. else sqlite3_reset(stmt);
  1511. return sq_throwerror(v, "Unknown requested return type %d", type_result);
  1512. }
  1513. }
  1514. if(ptype == OT_STRING) sqlite3_finalize(stmt);
  1515. else sqlite3_reset(stmt);
  1516. return 1;
  1517. }
  1518. //lua_regex
  1519. #define FUNC_IS_REGEXP 1
  1520. #define FUNC_IS_FIND 2
  1521. #define FUNC_IS_FIND_COUNT 3
  1522. #define FUNC_IS_MATCH 4
  1523. static inline void push_match_capture(sqlite3_context *context, int i, LuaMatchState *ms)
  1524. {
  1525. ptrdiff_t len = ms->capture[i].len;
  1526. if(len == CAP_POSITION) sqlite3_result_int(context, ms->capture[i].init - ms->src_init);
  1527. else sqlite3_result_text(context, ms->capture[0].init, ms->capture[0].len, SQLITE_TRANSIENT);
  1528. }
  1529. static void sqlite3_lua_find_base( sqlite3_context *context, int argc, sqlite3_value **argv, int funcType ) {
  1530. assert(argc == 2);
  1531. LuaMatchState ms;
  1532. int isRegexp = funcType == FUNC_IS_REGEXP;
  1533. const char *pattern = (const char *)sqlite3_value_text(argv[isRegexp ? 0 : 1]);
  1534. const char *subject = (const char *)sqlite3_value_text(argv[isRegexp ? 1 : 0]);
  1535. assert(argc == 2);
  1536. if(!subject || !pattern){
  1537. sqlite3_result_null(context);
  1538. return;
  1539. }
  1540. size_t pattern_len = strlen(pattern);
  1541. size_t subject_len = strlen(subject);
  1542. switch(funcType)
  1543. {
  1544. case FUNC_IS_MATCH:
  1545. {
  1546. ptrdiff_t rc = lua_str_match(&ms, subject, subject_len, pattern, pattern_len, 0, 0, 0, 0);
  1547. if(ms.error) sqlite3_result_error(context, ms.error, strlen(ms.error));
  1548. else if(rc < 0) sqlite3_result_null(context);
  1549. else if(ms.level){
  1550. if(ms.level == 1) push_match_capture(context, 0, &ms);
  1551. else {
  1552. //no way to differentiate more than one match
  1553. push_match_capture(context, 0, &ms);
  1554. }
  1555. } else {
  1556. sqlite3_result_text(context, subject + ms.start_pos, ms.end_pos-ms.start_pos+1, SQLITE_TRANSIENT);
  1557. }
  1558. }
  1559. break;
  1560. case FUNC_IS_FIND_COUNT:
  1561. {
  1562. int count = 0;
  1563. ms.end_pos = 0;
  1564. ptrdiff_t idx = -1;
  1565. while((idx = lua_str_find(&ms, subject, subject_len, pattern, pattern_len, ms.end_pos, 0, 0, 0)) >= 0) ++count;
  1566. sqlite3_result_int(context, count);
  1567. }
  1568. break;
  1569. case FUNC_IS_FIND:
  1570. case FUNC_IS_REGEXP:
  1571. {
  1572. ptrdiff_t idx = lua_str_find(&ms, subject, subject_len, pattern, pattern_len, 0, 0, NULL, NULL);
  1573. if(idx >= 0)
  1574. {
  1575. sqlite3_result_int(context, funcType == FUNC_IS_FIND ? idx : 1);
  1576. }
  1577. else
  1578. {
  1579. if(ms.error) sqlite3_result_error(context, ms.error, strlen(ms.error));
  1580. else sqlite3_result_int(context, funcType == FUNC_IS_FIND ? idx : 0);
  1581. }
  1582. }
  1583. break;
  1584. }
  1585. }
  1586. static void sqlite3_lua_regexp( sqlite3_context *context, int argc, sqlite3_value **argv ) {
  1587. sqlite3_lua_find_base(context, argc, argv, FUNC_IS_REGEXP);
  1588. }
  1589. static void sqlite3_lua_find( sqlite3_context *context, int argc, sqlite3_value **argv ) {
  1590. sqlite3_lua_find_base(context, argc, argv, FUNC_IS_FIND);
  1591. }
  1592. static void sqlite3_lua_find_count( sqlite3_context *context, int argc, sqlite3_value **argv ) {
  1593. sqlite3_lua_find_base(context, argc, argv, FUNC_IS_FIND_COUNT);
  1594. }
  1595. static void sqlite3_lua_match( sqlite3_context *context, int argc, sqlite3_value **argv ) {
  1596. sqlite3_lua_find_base(context, argc, argv, FUNC_IS_MATCH);
  1597. }
  1598. static void sqlite3_lua_gsub( sqlite3_context *context, int argc, sqlite3_value **argv ) {
  1599. assert(argc == 4);
  1600. lua_char_buffer_st *result;
  1601. const char *error_ptr;
  1602. const char *subject = (const char *)sqlite3_value_text(argv[0]);
  1603. const char *pattern = (const char *)sqlite3_value_text(argv[1]);
  1604. const char *replacement = (const char *)sqlite3_value_text(argv[2]);
  1605. int ntimes = sqlite3_value_int(argv[3]);
  1606. if(ntimes < 0) ntimes = 0;
  1607. if(!subject || !pattern || !replacement){
  1608. sqlite3_result_null(context);
  1609. return;
  1610. }
  1611. result = lua_str_gsub(subject, strlen(subject), pattern, strlen(pattern),
  1612. replacement, strlen(replacement), ntimes, &error_ptr, NULL, NULL);
  1613. if(result){
  1614. sqlite3_result_text(context, result->buf, result->used, SQLITE_TRANSIENT);
  1615. free(result);
  1616. }
  1617. else sqlite3_result_error(context, error_ptr, strlen(error_ptr));
  1618. }
  1619. int set_sqlite3_lua_regex_func(sqlite3 *db)
  1620. {
  1621. int nErr = sqlite3_create_function(db, "lua_find", 2, SQLITE_UTF8, 0, sqlite3_lua_find, 0, 0);
  1622. nErr += sqlite3_create_function(db, "lua_find_count", 2, SQLITE_UTF8, 0, sqlite3_lua_find_count, 0, 0);
  1623. nErr += sqlite3_create_function(db, "lua_match", 2, SQLITE_UTF8, 0, sqlite3_lua_match, 0, 0);
  1624. nErr += sqlite3_create_function(db, "lua_gsub", 4, SQLITE_UTF8, 0, sqlite3_lua_gsub, 0, 0);
  1625. nErr += sqlite3_create_function(db, "lua_regexp", 2, SQLITE_UTF8, 0, sqlite3_lua_regexp, 0, 0);
  1626. return nErr ? SQLITE_ERROR : SQLITE_OK;
  1627. }
  1628. static SQRESULT sq_sqlite3_close_release(HSQUIRRELVM v, sq_sqlite3_sdb *sdb)
  1629. {
  1630. SQRESULT rc = SQ_ERROR;
  1631. //printf("sq_sqlite3_close_release:%p\n", sdb);
  1632. if(sdb && sdb->db)
  1633. {
  1634. sqlite3 *db = sdb->db;
  1635. sdb->db = NULL; //prevent double entry/free, see sq_pushregistrytable(sdb->v) bellow
  1636. /*
  1637. sqlite3_stmt* statement = NULL;
  1638. int count = 0;
  1639. while ((statement = sqlite3_next_stmt(db, NULL)))
  1640. {
  1641. printf("sq_sqlite3_close_release:stmt: %p : %s\n", statement, sqlite3_sql(statement));
  1642. sqlite3_finalize(statement);
  1643. statement = c;
  1644. count++;
  1645. }
  1646. if (count) return sq_throwerror(v, _SC("closing database with %d statements not closed."), count);
  1647. */
  1648. int close_rc = sqlite3_close_v2(db) == SQLITE_OK;
  1649. if(!v || (v && close_rc))
  1650. {
  1651. rc = SQ_OK;
  1652. //remove waekref from registrytable
  1653. //printf("Closing %s\n", sqlite3_db_filename(db, "main"));
  1654. sq_delete_on_registry_table(sdb->v, db);
  1655. if(sdb->func)
  1656. {
  1657. sq_sqlite3_sdb_func *func, *func_next;
  1658. func = sdb->func;
  1659. while (func)
  1660. {
  1661. func_next = func->next;
  1662. sq_release(sdb->v, &func->fn_step);
  1663. sq_release(sdb->v, &func->fn_finalize);
  1664. sq_release(sdb->v, &func->udata);
  1665. sq_free(func, sizeof(sq_sqlite3_sdb_func));
  1666. func = func_next;
  1667. }
  1668. sdb->func = NULL;
  1669. }
  1670. /* 'free' all references */
  1671. sq_release(sdb->v, &sdb->busy_cb);
  1672. sq_release(sdb->v, &sdb->busy_udata);
  1673. sq_release(sdb->v, &sdb->progress_cb);
  1674. sq_release(sdb->v, &sdb->progress_udata);
  1675. sq_release(sdb->v, &sdb->trace_cb);
  1676. sq_release(sdb->v, &sdb->trace_udata);
  1677. sq_release(sdb->v, &sdb->update_hook_cb);
  1678. sq_release(sdb->v, &sdb->update_hook_udata);
  1679. sq_release(sdb->v, &sdb->authorizer_hook_cb);
  1680. sq_release(sdb->v, &sdb->authorizer_hook_udata);
  1681. sq_release(sdb->v, &sdb->null_value);
  1682. sq_free(sdb, sizeof(sq_sqlite3_sdb));
  1683. }
  1684. else
  1685. {
  1686. if(v) return sq_throwerror(v, sqlite3_errmsg(db));
  1687. }
  1688. }
  1689. return rc;
  1690. }
  1691. static SQRESULT sq_sqlite3_releasehook(SQUserPointer p, SQInteger size, void */*ep*/)
  1692. {
  1693. sq_sqlite3_sdb *sdb = ((sq_sqlite3_sdb *)p);
  1694. sq_sqlite3_close_release(0, sdb);
  1695. return 0;
  1696. }
  1697. static SQRESULT sq_sqlite3_constructor(HSQUIRRELVM v)
  1698. {
  1699. SQ_FUNC_VARS(v);
  1700. SQ_GET_STRING(v, 2, dbname);
  1701. SQ_OPT_INTEGER(v, 3, flags, SQLITE_OPEN_CREATE | SQLITE_OPEN_READWRITE | SQLITE_OPEN_SHAREDCACHE | SQLITE_OPEN_SUBLATIN_NA_LIKE);
  1702. //SQ_OPT_INTEGER(v, 3, flags, SQLITE_OPEN_CREATE | SQLITE_OPEN_READWRITE | SQLITE_OPEN_SHAREDCACHE);
  1703. sqlite3 *db;
  1704. int rc = sqlite3_open_v2(dbname, &db, flags, 0);
  1705. if(rc != SQLITE_OK) return sq_throwerror(v, "Failed to open database ! %d", rc);
  1706. set_sqlite3_lua_regex_func(db);
  1707. sq_sqlite3_sdb *sdb = (sq_sqlite3_sdb *)sq_malloc(sizeof(sq_sqlite3_sdb));
  1708. memset(sdb, 0, sizeof(sq_sqlite3_sdb));
  1709. sdb->db = db;
  1710. sdb->v = v;
  1711. sq_resetobject(&sdb->busy_cb);
  1712. sq_resetobject(&sdb->busy_udata);
  1713. sq_resetobject(&sdb->progress_cb);
  1714. sq_resetobject(&sdb->progress_udata);
  1715. sq_resetobject(&sdb->trace_cb);
  1716. sq_resetobject(&sdb->trace_udata);
  1717. sq_resetobject(&sdb->update_hook_cb);
  1718. sq_resetobject(&sdb->update_hook_udata);
  1719. sq_resetobject(&sdb->authorizer_hook_cb);
  1720. sq_resetobject(&sdb->authorizer_hook_udata);
  1721. sq_resetobject(&sdb->null_value);
  1722. sq_setinstanceup(v, 1, sdb);
  1723. sq_setreleasehook(v,1, sq_sqlite3_releasehook);
  1724. //save a weakref to allow statement return it's db
  1725. sq_pushuserpointer(v, sdb->db);
  1726. sq_weakref(v, 1);
  1727. sq_setonregistrytable(v);
  1728. return 1;
  1729. }
  1730. static SQRESULT sq_sqlite3_close(HSQUIRRELVM v)
  1731. {
  1732. SQ_FUNC_VARS_NO_TOP(v);
  1733. GET_sqlite3_INSTANCE();
  1734. if(sq_sqlite3_close_release(v, sdb) != SQ_OK) return SQ_ERROR;
  1735. sq_setinstanceup(v, 1, 0); //next calls will fail with "database is closed"
  1736. return 0;
  1737. }
  1738. static SQRESULT sq_sqlite3_db_ptr(HSQUIRRELVM v)
  1739. {
  1740. SQ_FUNC_VARS_NO_TOP(v);
  1741. GET_sqlite3_INSTANCE();
  1742. sq_pushuserpointer(v, self);
  1743. return 1;
  1744. }
  1745. /* bool IsAutoCommitOn( ) */
  1746. static SQRESULT sq_sqlite3_IsAutoCommitOn(HSQUIRRELVM v)
  1747. {
  1748. SQ_FUNC_VARS_NO_TOP(v);
  1749. GET_sqlite3_INSTANCE();
  1750. sq_pushbool(v, sqlite3_get_autocommit(self) ? SQTrue : SQFalse);
  1751. return 1;
  1752. }
  1753. /* int changes( ) */
  1754. static SQRESULT sq_sqlite3_changes(HSQUIRRELVM v)
  1755. {
  1756. SQ_FUNC_VARS_NO_TOP(v);
  1757. GET_sqlite3_INSTANCE();
  1758. sq_pushinteger(v, sqlite3_changes(self));
  1759. return 1;
  1760. }
  1761. static SQRESULT sq_sqlite3_exec(HSQUIRRELVM v)
  1762. {
  1763. return sqlite3_exec_fmt(v, tr_all_rows);
  1764. }
  1765. /* int exec_one_dml( const char * szSQL, ... ) */
  1766. static SQRESULT sq_sqlite3_exec_one_dml(HSQUIRRELVM v)
  1767. {
  1768. return sqlite3_exec_fmt(v, tr_ddml);
  1769. }
  1770. /* int exec_dml( const char * szSQL ) */
  1771. static SQRESULT sq_sqlite3_exec_dml(HSQUIRRELVM v)
  1772. {
  1773. SQ_FUNC_VARS_NO_TOP(v);
  1774. GET_sqlite3_INSTANCE();
  1775. SQ_GET_STRING(v, 2, szSQL);
  1776. char *errmsg;
  1777. if(sqlite3_exec(self, szSQL, NULL, NULL, &errmsg) != SQLITE_OK){
  1778. sq_throwerror(v, errmsg);
  1779. sqlite3_free(errmsg);
  1780. return SQ_ERROR;
  1781. }
  1782. sq_pushinteger(v, sqlite3_changes(self));
  1783. return 1;
  1784. }
  1785. /* bool exec_get_one( std::string & result , const char * szSQL ) */
  1786. static SQRESULT sq_sqlite3_exec_get_one(HSQUIRRELVM v)
  1787. {
  1788. return sqlite3_exec_fmt(v, tr_first_row_first_col);
  1789. }
  1790. static SQRESULT sq_sqlite3_exec_get_first_row(HSQUIRRELVM v)
  1791. {
  1792. return sqlite3_exec_fmt(v, tr_first_row);
  1793. }
  1794. /* const char * get_db_name( ) */
  1795. static SQRESULT sq_sqlite3_get_db_name(HSQUIRRELVM v)
  1796. {
  1797. SQ_FUNC_VARS_NO_TOP(v);
  1798. GET_sqlite3_INSTANCE();
  1799. sq_pushstring(v, sqlite3_db_filename(self, "main"), -1);
  1800. return 1;
  1801. }
  1802. /* sqlite3_int64 last_row_id( ) */
  1803. static SQRESULT sq_sqlite3_last_row_id(HSQUIRRELVM v)
  1804. {
  1805. SQ_FUNC_VARS_NO_TOP(v);
  1806. GET_sqlite3_INSTANCE();
  1807. sq_pushinteger(v, sqlite3_last_insert_rowid(self));
  1808. return 1;
  1809. }
  1810. /* stmt * prepare( const char * sql ) */
  1811. static SQRESULT sq_sqlite3_prepare(HSQUIRRELVM v)
  1812. {
  1813. SQ_FUNC_VARS_NO_TOP(v);
  1814. //GET_sqlite3_INSTANCE();
  1815. SQ_GET_STRING(v, 2, sql);
  1816. sq_pushstring(v, SQLite3_Stmt_TAG, -1);
  1817. if(sq_getonroottable(v) == SQ_ERROR) return SQ_ERROR;
  1818. sq_pushroottable(v);
  1819. sq_push(v, 1);
  1820. sq_push(v, 2);
  1821. if(sq_call(v, 3, SQTrue, SQFalse) != SQ_OK) return SQ_ERROR;
  1822. return 1;
  1823. }
  1824. //sqlite3_blob
  1825. static SQRESULT sq_sqlite3_blob_releasehook(SQUserPointer p, SQInteger size, void */*ep*/)
  1826. {
  1827. sqlite3_blob *self = ((sqlite3_blob *)p);
  1828. if(self) sqlite3_blob_close(self);
  1829. return 0;
  1830. }
  1831. static SQRESULT sq_sqlite3_blob_close(HSQUIRRELVM v)
  1832. {
  1833. SQ_FUNC_VARS_NO_TOP(v);
  1834. GET_sqlite3_blob_INSTANCE();
  1835. sq_setinstanceup(v, 1, 0); //next calls will fail with "blob is closed"
  1836. sq_pushinteger(v, sqlite3_blob_close(self));
  1837. return 1;
  1838. }
  1839. static SQRESULT sq_sqlite3_blob_reopen(HSQUIRRELVM v)
  1840. {
  1841. SQ_FUNC_VARS_NO_TOP(v);
  1842. GET_sqlite3_blob_INSTANCE();
  1843. SQ_GET_INTEGER(v, 2, iRow);
  1844. int rc = sqlite3_blob_reopen(self, iRow);
  1845. if(rc != SQLITE_OK) return sq_sqlite3_blob_close(v);
  1846. sq_pushinteger(v, rc);
  1847. return 1;
  1848. }
  1849. static SQRESULT sq_sqlite3_blob_bytes(HSQUIRRELVM v)
  1850. {
  1851. SQ_FUNC_VARS_NO_TOP(v);
  1852. GET_sqlite3_blob_INSTANCE();
  1853. sq_pushinteger(v, sqlite3_blob_bytes(self));
  1854. return 1;
  1855. }
  1856. static SQRESULT sq_sqlite3_blob_read(HSQUIRRELVM v)
  1857. {
  1858. SQ_FUNC_VARS(v);
  1859. GET_sqlite3_blob_INSTANCE();
  1860. SQ_OPT_INTEGER(v, 2, size, 0);
  1861. SQ_OPT_INTEGER(v, 3, offset, 0);
  1862. if(!size) size = sqlite3_blob_bytes(self);
  1863. SQChar *buf = sq_getscratchpad(v, size);
  1864. int rc = sqlite3_blob_read(self, buf, size, offset);
  1865. if(rc == SQLITE_OK) sq_pushstring(v, buf, size);
  1866. else sq_pushnull(v);
  1867. return 1;
  1868. }
  1869. static SQRESULT sq_sqlite3_blob_write(HSQUIRRELVM v)
  1870. {
  1871. SQ_FUNC_VARS(v);
  1872. GET_sqlite3_blob_INSTANCE();
  1873. SQ_GET_STRING(v, 2, buf);
  1874. SQ_OPT_INTEGER(v, 3, size, buf_size);
  1875. SQ_OPT_INTEGER(v, 4, offset, 0);
  1876. int rc = sqlite3_blob_write(self, buf, size, offset);
  1877. sq_pushinteger(v, rc);
  1878. return 1;
  1879. }
  1880. static SQRESULT sq_sqlite3_blob_open(HSQUIRRELVM v)
  1881. {
  1882. SQ_FUNC_VARS(v);
  1883. GET_sqlite3_INSTANCE();
  1884. SQ_GET_STRING(v, 2, zDb);
  1885. SQ_GET_STRING(v, 3, zTable);
  1886. SQ_GET_STRING(v, 4, zColumn);
  1887. SQ_GET_INTEGER(v, 5, iRow);
  1888. SQ_OPT_INTEGER(v, 6, flags, 0);
  1889. sqlite3_blob *pBlob;
  1890. int rc = sqlite3_blob_open(self, zDb, zTable, zColumn, iRow, flags, &pBlob);
  1891. if(rc == SQLITE_OK)
  1892. {
  1893. sq_pushstring(v, SQLite3_Blob_TAG, -1);
  1894. if(sq_getonregistrytable(v) == SQ_ERROR) return SQ_ERROR;
  1895. sq_createinstance(v, -1);
  1896. sq_setinstanceup(v, -1, pBlob);
  1897. sq_setreleasehook(v, -1, sq_sqlite3_blob_releasehook);
  1898. }
  1899. else sq_pushnull(v);
  1900. return 1;
  1901. }
  1902. #define _DECL_FUNC(name,nparams,tycheck) {_SC(#name), sq_sqlite3_blob_##name,nparams,tycheck}
  1903. static SQRegFunction sq_sqlite3_blob_methods[] =
  1904. {
  1905. _DECL_FUNC(close, 1, _SC("x")),
  1906. _DECL_FUNC(reopen, 2, _SC("xi")),
  1907. _DECL_FUNC(bytes, 1, _SC("x")),
  1908. _DECL_FUNC(read, -1, _SC("xii")),
  1909. _DECL_FUNC(write, -2, _SC("xsii")),
  1910. {0,0}
  1911. };
  1912. #undef _DECL_FUNC
  1913. /* void set_busy_timeout( int nMillisecs ) */
  1914. static SQRESULT sq_sqlite3_set_busy_timeout(HSQUIRRELVM v)
  1915. {
  1916. SQ_FUNC_VARS_NO_TOP(v);
  1917. //GET_sqlite3_INSTANCE();
  1918. SQ_GET_INTEGER(v, 2, nMillisecs);
  1919. //self->set_busy_timeout(nMillisecs);
  1920. return 0;
  1921. }
  1922. /* int total_changes( ) */
  1923. static SQRESULT sq_sqlite3_total_changes(HSQUIRRELVM v)
  1924. {
  1925. SQ_FUNC_VARS_NO_TOP(v);
  1926. GET_sqlite3_INSTANCE();
  1927. sq_pushinteger(v, sqlite3_total_changes(self));
  1928. return 1;
  1929. }
  1930. static SQRESULT sq_sqlite3_enable_shared_cache(HSQUIRRELVM v)
  1931. {
  1932. SQ_FUNC_VARS_NO_TOP(v);
  1933. SQ_GET_BOOL(v, 2, bhow);
  1934. sq_pushbool(v, sqlite3_enable_shared_cache(bhow) == SQLITE_OK);
  1935. return 1;
  1936. }
  1937. static SQRESULT sq_sqlite3_sleep(HSQUIRRELVM v)
  1938. {
  1939. SQ_FUNC_VARS_NO_TOP(v);
  1940. SQ_GET_INTEGER(v, 2, n);
  1941. sqlite3_sleep(n);
  1942. return 0;
  1943. }
  1944. static SQRESULT sq_sqlite3_version(HSQUIRRELVM v)
  1945. {
  1946. sq_pushstring(v, sqlite3_libversion(), -1);
  1947. return 1;
  1948. }
  1949. static SQRESULT sq_sqlite3_threadsafe(HSQUIRRELVM v)
  1950. {
  1951. sq_pushinteger(v, sqlite3_threadsafe());
  1952. return 1;
  1953. }
  1954. static SQRESULT sq_sqlite3_config_single_thread(HSQUIRRELVM v)
  1955. {
  1956. sq_pushinteger(v, sqlite3_config(SQLITE_CONFIG_SINGLETHREAD));
  1957. return 1;
  1958. }
  1959. static SQRESULT sq_sqlite3_config_multi_thread(HSQUIRRELVM v)
  1960. {
  1961. sq_pushinteger(v, sqlite3_config(SQLITE_CONFIG_MULTITHREAD));
  1962. return 1;
  1963. }
  1964. static SQRESULT sq_sqlite3_config_serialized(HSQUIRRELVM v)
  1965. {
  1966. sq_pushinteger(v, sqlite3_config(SQLITE_CONFIG_SERIALIZED));
  1967. return 1;
  1968. }
  1969. static SQRESULT sq_sqlite3_errcode(HSQUIRRELVM v)
  1970. {
  1971. SQ_FUNC_VARS_NO_TOP(v);
  1972. GET_sqlite3_INSTANCE();
  1973. sq_pushinteger(v, sqlite3_errcode(self));
  1974. return 1;
  1975. }
  1976. static SQRESULT sq_sqlite3_errmsg(HSQUIRRELVM v)
  1977. {
  1978. SQ_FUNC_VARS_NO_TOP(v);
  1979. GET_sqlite3_INSTANCE();
  1980. sq_pushstring(v, sqlite3_errmsg(self), -1);
  1981. return 1;
  1982. }
  1983. #ifndef WIN32
  1984. static SQRESULT sq_sqlite3_temp_directory(HSQUIRRELVM v)
  1985. {
  1986. SQ_FUNC_VARS(v);
  1987. const char *oldtemp = sqlite3_temp_directory;
  1988. sq_pushstring(v, oldtemp, -1);
  1989. if (_top_ > 1)
  1990. {
  1991. SQ_GET_STRING(v, 2, temp);
  1992. if (sqlite3_temp_directory)
  1993. {
  1994. sqlite3_free((char*)sqlite3_temp_directory);
  1995. }
  1996. if (temp && temp_size)
  1997. {
  1998. sqlite3_temp_directory = sqlite3_mprintf("%s", temp);
  1999. }
  2000. else
  2001. {
  2002. sqlite3_temp_directory = NULL;
  2003. }
  2004. }
  2005. return 1;
  2006. }
  2007. #endif
  2008. #ifdef SQLITE_HAS_CODEC
  2009. //#include "codecext.h"
  2010. /*
  2011. ** Params: db, sql
  2012. ** returns: code, compiled length or error message
  2013. */
  2014. static SQRESULT sq_sqlite3_key(HSQUIRRELVM v)
  2015. {
  2016. SQ_FUNC_VARS_NO_TOP(v);
  2017. GET_sqlite3_INSTANCE();
  2018. SQ_GET_STRING(v, 2, key);
  2019. sq_pushinteger(v, sqlite3_key_v2(self, 0, key, key_size));
  2020. return 1;
  2021. }
  2022. /*
  2023. ** Params: db, sql
  2024. ** returns: code, compiled length or error message
  2025. */
  2026. static SQRESULT sq_sqlite3_rekey(HSQUIRRELVM v)
  2027. {
  2028. SQ_FUNC_VARS_NO_TOP(v);
  2029. GET_sqlite3_INSTANCE();
  2030. SQ_GET_STRING(v, 2, key);
  2031. sq_pushinteger(v, sqlite3_rekey_v2(self, 0, key, key_size));
  2032. return 1;
  2033. }
  2034. #endif
  2035. #if !defined(SQLITE_OMIT_PROGRESS_CALLBACK) || !SQLITE_OMIT_PROGRESS_CALLBACK
  2036. /*
  2037. ** progress handler:
  2038. ** Params: database, number of opcodes, callback function, userdata
  2039. **
  2040. ** callback function:
  2041. ** Params: userdata
  2042. ** returns: 0 to return immediatly and return SQLITE_ABORT, non-zero to continue
  2043. */
  2044. static int db_progress_callback(void *udata)
  2045. {
  2046. SQInteger result = 1; /* abort by default */
  2047. sq_sqlite3_sdb *sdb = (sq_sqlite3_sdb*)udata;
  2048. HSQUIRRELVM v = sdb->v;
  2049. int top = sq_gettop(v);
  2050. sq_pushobject(v, sdb->progress_cb);
  2051. sq_pushroottable(v); //this
  2052. sq_pushobject(v, sdb->progress_udata);
  2053. /* call squilu function */
  2054. if (sq_call(v, 2, SQTrue, SQFalse) == SQ_OK)
  2055. sq_getinteger(v, -1, &result);
  2056. sq_settop(v, top);
  2057. return result;
  2058. }
  2059. static SQRESULT sq_sqlite3_progress_handler(HSQUIRRELVM v)
  2060. {
  2061. SQ_FUNC_VARS(v);
  2062. GET_sqlite3_INSTANCE();
  2063. /* clear progress handler */
  2064. sqlite3_progress_handler(self, 0, NULL, NULL);
  2065. sq_release(v, &sdb->progress_cb);
  2066. sq_release(v, &sdb->progress_udata);
  2067. sq_resetobject(&sdb->progress_cb);
  2068. sq_resetobject(&sdb->progress_udata);
  2069. SQObjectType otype = sq_gettype(v, 2);
  2070. if (_top_ > 1 && (otype != OT_NULL))
  2071. {
  2072. SQ_GET_INTEGER(v, 2, nop);
  2073. if(sq_gettype(v, 3) != OT_CLOSURE)
  2074. return sq_throwerror(v, _SC("invalid second parameter expected closure"));
  2075. sq_getstackobj(v, 3, &sdb->progress_cb);
  2076. sq_addref(v, &sdb->progress_cb);
  2077. if(_top_ > 3)
  2078. {
  2079. sq_getstackobj(v, 4, &sdb->progress_udata);
  2080. sq_addref(v, &sdb->progress_udata);
  2081. }
  2082. /* set progress callback */
  2083. sqlite3_progress_handler(self, nop, db_progress_callback, sdb);
  2084. }
  2085. return 0;
  2086. }
  2087. #else /* #if !defined(SQLITE_OMIT_PROGRESS_CALLBACK) || !SQLITE_OMIT_PROGRESS_CALLBACK */
  2088. static SQRESULT sq_sqlite3_progress_handler(HSQUIRRELVM v)
  2089. {
  2090. return sq_throwerror(v, _SC("progress callback support disabled at compile time"));
  2091. return 0;
  2092. }
  2093. #endif /* #if !defined(SQLITE_OMIT_PROGRESS_CALLBACK) || !SQLITE_OMIT_PROGRESS_CALLBACK */
  2094. /*
  2095. ** trace callback:
  2096. ** Params: database, callback function, userdata
  2097. **
  2098. ** callback function:
  2099. ** Params: userdata, sql
  2100. */
  2101. static void db_trace_callback(void *udata, const char *sql)
  2102. {
  2103. sq_sqlite3_sdb *sdb = (sq_sqlite3_sdb*)udata;
  2104. HSQUIRRELVM v = sdb->v;
  2105. int top = sq_gettop(v);
  2106. /* setup squirrel callback call */
  2107. sq_pushobject(v, sdb->trace_cb);
  2108. sq_pushroottable(v);
  2109. sq_pushobject(v, sdb->trace_udata);
  2110. sq_pushstring(v, sql, -1); /* traced sql statement */
  2111. /* call squirrel function */
  2112. sq_call(v, 3, SQFalse, SQFalse);
  2113. /* ignore any error generated by this function */
  2114. sq_settop(v, top);
  2115. }
  2116. static SQRESULT sq_sqlite3_trace(HSQUIRRELVM v)
  2117. {
  2118. SQ_FUNC_VARS(v);
  2119. GET_sqlite3_INSTANCE();
  2120. /* clear trace handler */
  2121. sqlite3_trace(self, NULL, NULL);
  2122. sq_release(v, &sdb->trace_cb);
  2123. sq_release(v, &sdb->trace_udata);
  2124. sq_resetobject(&sdb->trace_cb);
  2125. sq_resetobject(&sdb->trace_udata);
  2126. SQObjectType otype = sq_gettype(v, 2);
  2127. if (_top_ > 1 && (otype != OT_NULL))
  2128. {
  2129. if(sq_gettype(v, 2) != OT_CLOSURE)
  2130. return sq_throwerror(v, _SC("invalid fisrt parameter expected closure"));
  2131. sq_getstackobj(v, 2, &sdb->trace_cb);
  2132. sq_addref(v, &sdb->trace_cb);
  2133. if(_top_ > 2)
  2134. {
  2135. sq_getstackobj(v, 3, &sdb->trace_udata);
  2136. sq_addref(v, &sdb->trace_udata);
  2137. }
  2138. /* set trace callback */
  2139. if(_top_ > 3)
  2140. {
  2141. SQBool b;
  2142. sq_getbool(v, 4, &b);
  2143. sqlite3_trace_v0(self, db_trace_callback, sdb, b == SQTrue);
  2144. }
  2145. else sqlite3_trace(self, db_trace_callback, sdb);
  2146. }
  2147. return 0;
  2148. }
  2149. /*
  2150. ** update hook callback:
  2151. ** Params: database, callback function, userdata
  2152. **
  2153. ** callback function:
  2154. ** Params: userdata, sql
  2155. */
  2156. static void db_update_hook_callback(void *udata, int update_type,
  2157. char const *db_name, char const *table_name, sqlite3_int64 rowid)
  2158. {
  2159. sq_sqlite3_sdb *sdb = (sq_sqlite3_sdb*)udata;
  2160. HSQUIRRELVM v = sdb->v;
  2161. int top = sq_gettop(v);
  2162. /* setup squirrel callback call */
  2163. sq_pushobject(v, sdb->update_hook_cb);
  2164. sq_pushroottable(v);
  2165. sq_pushobject(v, sdb->update_hook_udata);
  2166. sq_pushinteger(v, update_type);
  2167. sq_pushstring(v, db_name, -1);
  2168. sq_pushstring(v, table_name, -1);
  2169. sq_pushinteger(v, rowid);
  2170. /* call squirrel function */
  2171. sq_call(v, 6, SQFalse, SQFalse);
  2172. /* ignore any error generated by this function */
  2173. sq_settop(v, top);
  2174. }
  2175. static SQRESULT sq_sqlite3_update_hook(HSQUIRRELVM v)
  2176. {
  2177. SQ_FUNC_VARS(v);
  2178. GET_sqlite3_INSTANCE();
  2179. /* clear update handler */
  2180. sqlite3_update_hook(self, NULL, NULL);
  2181. sq_release(v, &sdb->update_hook_cb);
  2182. sq_release(v, &sdb->update_hook_udata);
  2183. sq_resetobject(&sdb->update_hook_cb);
  2184. sq_resetobject(&sdb->update_hook_udata);
  2185. SQObjectType otype = sq_gettype(v, 2);
  2186. if (_top_ > 1 && (otype != OT_NULL))
  2187. {
  2188. if(sq_gettype(v, 2) != OT_CLOSURE)
  2189. return sq_throwerror(v, _SC("invalid fisrt parameter expected closure"));
  2190. sq_getstackobj(v, 2, &sdb->update_hook_cb);
  2191. sq_addref(v, &sdb->update_hook_cb);
  2192. if(_top_ > 2)
  2193. {
  2194. sq_getstackobj(v, 3, &sdb->update_hook_udata);
  2195. sq_addref(v, &sdb->update_hook_udata);
  2196. }
  2197. /* set update_hook callback */
  2198. sqlite3_update_hook(self, db_update_hook_callback, sdb);
  2199. }
  2200. return 0;
  2201. }
  2202. /*
  2203. ** authorizer hook callback:
  2204. ** Params: database, callback function, userdata
  2205. **
  2206. ** callback function:
  2207. ** Params: userdata, sql
  2208. */
  2209. #if 0
  2210. /******************************************* 3rd ************ 4th ***********/
  2211. #define SQLITE_CREATE_INDEX 1 /* Index Name Table Name */
  2212. #define SQLITE_CREATE_TABLE 2 /* Table Name NULL */
  2213. #define SQLITE_CREATE_TEMP_INDEX 3 /* Index Name Table Name */
  2214. #define SQLITE_CREATE_TEMP_TABLE 4 /* Table Name NULL */
  2215. #define SQLITE_CREATE_TEMP_TRIGGER 5 /* Trigger Name Table Name */
  2216. #define SQLITE_CREATE_TEMP_VIEW 6 /* View Name NULL */
  2217. #define SQLITE_CREATE_TRIGGER 7 /* Trigger Name Table Name */
  2218. #define SQLITE_CREATE_VIEW 8 /* View Name NULL */
  2219. #define SQLITE_DELETE 9 /* Table Name NULL */
  2220. #define SQLITE_DROP_INDEX 10 /* Index Name Table Name */
  2221. #define SQLITE_DROP_TABLE 11 /* Table Name NULL */
  2222. #define SQLITE_DROP_TEMP_INDEX 12 /* Index Name Table Name */
  2223. #define SQLITE_DROP_TEMP_TABLE 13 /* Table Name NULL */
  2224. #define SQLITE_DROP_TEMP_TRIGGER 14 /* Trigger Name Table Name */
  2225. #define SQLITE_DROP_TEMP_VIEW 15 /* View Name NULL */
  2226. #define SQLITE_DROP_TRIGGER 16 /* Trigger Name Table Name */
  2227. #define SQLITE_DROP_VIEW 17 /* View Name NULL */
  2228. #define SQLITE_INSERT 18 /* Table Name NULL */
  2229. #define SQLITE_PRAGMA 19 /* Pragma Name 1st arg or NULL */
  2230. #define SQLITE_READ 20 /* Table Name Column Name */
  2231. #define SQLITE_SELECT 21 /* NULL NULL */
  2232. #define SQLITE_TRANSACTION 22 /* Operation NULL */
  2233. #define SQLITE_UPDATE 23 /* Table Name Column Name */
  2234. #define SQLITE_ATTACH 24 /* Filename NULL */
  2235. #define SQLITE_DETACH 25 /* Database Name NULL */
  2236. #define SQLITE_ALTER_TABLE 26 /* Database Name Table Name */
  2237. #define SQLITE_REINDEX 27 /* Index Name NULL */
  2238. #define SQLITE_ANALYZE 28 /* Table Name NULL */
  2239. #define SQLITE_CREATE_VTABLE 29 /* Table Name Module Name */
  2240. #define SQLITE_DROP_VTABLE 30 /* Table Name Module Name */
  2241. #define SQLITE_FUNCTION 31 /* NULL Function Name */
  2242. #define SQLITE_SAVEPOINT 32 /* Operation Savepoint Name */
  2243. #define SQLITE_COPY 0 /* No longer used */
  2244. #define SQLITE_RECURSIVE 33 /* NULL NULL */
  2245. #endif
  2246. static int db_authorizer_hook_callback(void *udata, int action_code,
  2247. char const *param3, char const *param4,
  2248. char const *param5, char const *param6)
  2249. {
  2250. sq_sqlite3_sdb *sdb = (sq_sqlite3_sdb*)udata;
  2251. HSQUIRRELVM v = sdb->v;
  2252. int top = sq_gettop(v);
  2253. SQInteger result = SQLITE_OK;
  2254. /* setup squirrel callback call */
  2255. sq_pushobject(v, sdb->authorizer_hook_cb);
  2256. sq_pushroottable(v);
  2257. sq_pushobject(v, sdb->authorizer_hook_udata);
  2258. sq_pushinteger(v, action_code);
  2259. sq_pushstring(v, param3, -1);
  2260. sq_pushstring(v, param4, -1);
  2261. sq_pushstring(v, param5, -1);
  2262. sq_pushstring(v, param6, -1);
  2263. /* call squilu function */
  2264. /* ignore any error generated by this function */
  2265. if (sq_call(v, 7, SQTrue, SQFalse) == SQ_OK)
  2266. sq_getinteger(v, -1, &result);
  2267. sq_settop(v, top);
  2268. return result;
  2269. }
  2270. static SQRESULT sq_sqlite3_set_authorizer(HSQUIRRELVM v)
  2271. {
  2272. SQ_FUNC_VARS(v);
  2273. GET_sqlite3_INSTANCE();
  2274. /* clear trace handler */
  2275. sqlite3_set_authorizer(self, NULL, NULL);
  2276. sq_release(v, &sdb->authorizer_hook_cb);
  2277. sq_release(v, &sdb->authorizer_hook_udata);
  2278. sq_resetobject(&sdb->authorizer_hook_cb);
  2279. sq_resetobject(&sdb->authorizer_hook_udata);
  2280. SQObjectType otype = sq_gettype(v, 2);
  2281. if (_top_ > 1 && (otype != OT_NULL))
  2282. {
  2283. if(sq_gettype(v, 2) != OT_CLOSURE)
  2284. return sq_throwerror(v, _SC("invalid fisrt parameter expected closure"));
  2285. sq_getstackobj(v, 2, &sdb->authorizer_hook_cb);
  2286. sq_addref(v, &sdb->authorizer_hook_cb);
  2287. if(_top_ > 2)
  2288. {
  2289. sq_getstackobj(v, 3, &sdb->authorizer_hook_udata);
  2290. sq_addref(v, &sdb->authorizer_hook_udata);
  2291. }
  2292. /* set authorizer_hook callback */
  2293. sqlite3_set_authorizer(self, db_authorizer_hook_callback, sdb);
  2294. }
  2295. return 0;
  2296. }
  2297. /*
  2298. ** busy handler:
  2299. ** Params: database, callback function, userdata
  2300. **
  2301. ** callback function:
  2302. ** Params: userdata, number of tries
  2303. ** returns: 0 to return immediatly and return SQLITE_BUSY, non-zero to try again
  2304. */
  2305. static int db_busy_callback(void *udata, int tries)
  2306. {
  2307. SQBool retry = SQFalse; /* abort by default */
  2308. sq_sqlite3_sdb *sdb = (sq_sqlite3_sdb*)udata;
  2309. HSQUIRRELVM v = sdb->v;
  2310. int top = sq_gettop(v);
  2311. sq_pushobject(v, sdb->busy_cb);
  2312. sq_pushroottable(v);
  2313. sq_pushobject(v, sdb->busy_udata);
  2314. sq_pushinteger(v, tries);
  2315. /* call squilu function */
  2316. if (sq_call(v, 3, SQTrue, SQFalse) == SQ_OK)
  2317. sq_getbool(v, -1, &retry);
  2318. sq_settop(v, top);
  2319. return retry == SQTrue;
  2320. }
  2321. static SQRESULT sq_sqlite3_busy_handler(HSQUIRRELVM v)
  2322. {
  2323. SQ_FUNC_VARS(v);
  2324. GET_sqlite3_INSTANCE();
  2325. /* clear busy handler */
  2326. sqlite3_busy_handler(self, NULL, NULL);
  2327. sq_release(v, &sdb->busy_cb);
  2328. sq_release(v, &sdb->busy_udata);
  2329. sq_resetobject(&sdb->busy_cb);
  2330. sq_resetobject(&sdb->busy_udata);
  2331. SQObjectType otype = sq_gettype(v, 2);
  2332. if (_top_ > 1 && (otype != OT_NULL))
  2333. {
  2334. if(sq_gettype(v, 2) != OT_CLOSURE)
  2335. return sq_throwerror(v, _SC("invalid fisrt parameter expected closure"));
  2336. sq_getstackobj(v, 2, &sdb->busy_cb);
  2337. sq_addref(v, &sdb->busy_cb);
  2338. if(_top_ > 2)
  2339. {
  2340. sq_getstackobj(v, 3, &sdb->busy_udata);
  2341. sq_addref(v, &sdb->busy_udata);
  2342. }
  2343. /* set busy callback */
  2344. sqlite3_busy_handler(self, db_busy_callback, sdb);
  2345. }
  2346. return 0;
  2347. }
  2348. static SQRESULT sq_sqlite3_busy_timeout(HSQUIRRELVM v)
  2349. {
  2350. SQ_FUNC_VARS_NO_TOP(v);
  2351. GET_sqlite3_INSTANCE();
  2352. SQ_GET_INTEGER(v, 2, timeout);
  2353. sqlite3_busy_timeout(self, timeout);
  2354. /* if there was a timeout callback registered, it is now
  2355. ** invalid/useless. free any references we may have */
  2356. sq_release(v, &sdb->busy_cb);
  2357. sq_resetobject(&sdb->busy_cb);
  2358. sq_release(v, &sdb->busy_udata);
  2359. sq_resetobject(&sdb->busy_udata);
  2360. return 0;
  2361. }
  2362. static SQRESULT sq_sqlite3_interrupt(HSQUIRRELVM v)
  2363. {
  2364. SQ_FUNC_VARS_NO_TOP(v);
  2365. GET_sqlite3_INSTANCE();
  2366. sqlite3_interrupt(self);
  2367. return 0;
  2368. }
  2369. /*
  2370. ** =======================================================
  2371. ** User Defined Functions - Context Methods
  2372. ** =======================================================
  2373. */
  2374. typedef struct
  2375. {
  2376. sqlite3_context *ctx;
  2377. HSQOBJECT udata;
  2378. } sq_sqlite3_context_st;
  2379. static const SQChar sq_sqlite3_context_TAG[] = _SC(":sqlite3:ctx");
  2380. static SQRESULT sq_sqlite3_context_releasehook(SQUserPointer p, SQInteger size, void */*ep*/)
  2381. {
  2382. sq_sqlite3_context_st *ctx = ((sq_sqlite3_context_st *)p);
  2383. /* 'free' all references */
  2384. sq_free(ctx, sizeof(sq_sqlite3_context_st));
  2385. return 0;
  2386. }
  2387. static SQRESULT sq_sqlite3_context_constructor(HSQUIRRELVM v)
  2388. {
  2389. sq_sqlite3_context_st *ctx = (sq_sqlite3_context_st*)sq_malloc(sizeof(sq_sqlite3_context_st));
  2390. ctx->ctx = NULL;
  2391. sq_resetobject(&ctx->udata);
  2392. sq_setinstanceup(v, 1, ctx);
  2393. sq_setreleasehook(v,1, sq_sqlite3_context_releasehook);
  2394. return 1;
  2395. }
  2396. #define SQ_SQLITE3_GETCONTEXT(v, idx) \
  2397. sq_sqlite3_context_st *self;\
  2398. if((_rc_ = sq_getinstanceup(v, idx, (void**)&self, (void*)sq_sqlite3_context_TAG)) < 0) return _rc_;
  2399. #define GET_sqlite3_context_INSTANCE() SQ_SQLITE3_GETCONTEXT(v,1)
  2400. static SQRESULT sq_sqlite3_context__tostring(HSQUIRRELVM v)
  2401. {
  2402. SQ_FUNC_VARS_NO_TOP(v);
  2403. GET_sqlite3_context_INSTANCE();
  2404. char buff[64];
  2405. snprintf(buff, sizeof(buff), "sqlite function context (%p)", self);
  2406. sq_pushstring(v, buff, -1);
  2407. return 1;
  2408. }
  2409. static SQRESULT sq_sqlite3_context_check_aggregate(HSQUIRRELVM v, sq_sqlite3_context_st *ctx)
  2410. {
  2411. sq_sqlite3_sdb_func *func = (sq_sqlite3_sdb_func*)sqlite3_user_data(ctx->ctx);
  2412. if (sq_isclosure(func->fn_finalize))
  2413. {
  2414. return sq_throwerror(v, "attempt to call aggregate method from scalar function");
  2415. }
  2416. return 1;
  2417. }
  2418. static SQRESULT sq_sqlite3_context_user_data(HSQUIRRELVM v)
  2419. {
  2420. SQ_FUNC_VARS_NO_TOP(v);
  2421. GET_sqlite3_context_INSTANCE();
  2422. sq_sqlite3_sdb_func *func = (sq_sqlite3_sdb_func*)sqlite3_user_data(self->ctx);
  2423. sq_pushobject(v, func->udata);
  2424. return 1;
  2425. }
  2426. static SQRESULT sq_sqlite3_context_aggregate_data(HSQUIRRELVM v)
  2427. {
  2428. SQ_FUNC_VARS(v);
  2429. GET_sqlite3_context_INSTANCE();
  2430. sq_sqlite3_context_check_aggregate(v, self);
  2431. if(_top_ < 2)
  2432. {
  2433. sq_pushobject(v, self->udata);
  2434. }
  2435. else
  2436. {
  2437. sq_release(v, &self->udata);
  2438. sq_getstackobj(v, 2, &self->udata);
  2439. sq_addref(v, &self->udata);
  2440. }
  2441. return 0;
  2442. }
  2443. static SQRESULT sq_sqlite3_context_aggregate_count(HSQUIRRELVM v)
  2444. {
  2445. SQ_FUNC_VARS_NO_TOP(v);
  2446. GET_sqlite3_context_INSTANCE();
  2447. sq_sqlite3_context_check_aggregate(v, self);
  2448. sq_pushinteger(v, sqlite3_aggregate_count(self->ctx));
  2449. return 1;
  2450. }
  2451. struct sq_sqlite3_context_aux_data_st
  2452. {
  2453. HSQUIRRELVM vm;
  2454. HSQOBJECT data;
  2455. };
  2456. static SQRESULT sq_sqlite3_context_get_aux_data(HSQUIRRELVM v)
  2457. {
  2458. SQ_FUNC_VARS_NO_TOP(v);
  2459. GET_sqlite3_context_INSTANCE();
  2460. SQ_GET_INTEGER(v, 2, argn);
  2461. sq_sqlite3_context_aux_data_st *data = (sq_sqlite3_context_aux_data_st*)sqlite3_get_auxdata(self->ctx, argn);
  2462. if(data)
  2463. {
  2464. sq_pushobject(v, data->data);
  2465. }
  2466. else
  2467. {
  2468. sq_pushnull(v);
  2469. }
  2470. return 1;
  2471. }
  2472. static void sq_sqlite3_context_free_aux_data(void *aux_data)
  2473. {
  2474. sq_sqlite3_context_aux_data_st *data = (sq_sqlite3_context_aux_data_st*)aux_data;
  2475. if(data)
  2476. {
  2477. sq_release(data->vm, &data->data);
  2478. sqlite3_free(data);
  2479. }
  2480. }
  2481. static SQRESULT sq_sqlite3_context_set_aux_data(HSQUIRRELVM v)
  2482. {
  2483. SQ_FUNC_VARS_NO_TOP(v);
  2484. GET_sqlite3_context_INSTANCE();
  2485. SQ_GET_INTEGER(v, 2, argn);
  2486. sq_sqlite3_context_aux_data_st *data = (sq_sqlite3_context_aux_data_st*)sqlite3_malloc(sizeof(*data));
  2487. if(data)
  2488. {
  2489. data->vm = v;
  2490. sq_resetobject(&data->data);
  2491. sq_getstackobj(v, 3, &data->data);
  2492. sq_addref(v, &data->data);
  2493. sqlite3_set_auxdata(self->ctx, argn, data, sq_sqlite3_context_free_aux_data);
  2494. }
  2495. return 0;
  2496. }
  2497. static SQRESULT sq_sqlite3_context_result_blob(HSQUIRRELVM v)
  2498. {
  2499. SQ_FUNC_VARS_NO_TOP(v);
  2500. GET_sqlite3_context_INSTANCE();
  2501. SQ_GET_STRING(v, 2, blob);
  2502. sqlite3_result_blob(self->ctx, (const void*)blob, blob_size, SQLITE_TRANSIENT);
  2503. return 0;
  2504. }
  2505. static SQRESULT sq_sqlite3_context_result_double(HSQUIRRELVM v)
  2506. {
  2507. SQ_FUNC_VARS_NO_TOP(v);
  2508. GET_sqlite3_context_INSTANCE();
  2509. SQ_GET_FLOAT(v, 2, d);
  2510. sqlite3_result_double(self->ctx, d);
  2511. return 0;
  2512. }
  2513. static SQRESULT sq_sqlite3_context_result_error(HSQUIRRELVM v)
  2514. {
  2515. SQ_FUNC_VARS_NO_TOP(v);
  2516. GET_sqlite3_context_INSTANCE();
  2517. SQ_GET_STRING(v,2, err);
  2518. sqlite3_result_error(self->ctx, err, err_size);
  2519. return 0;
  2520. }
  2521. static SQRESULT sq_sqlite3_context_result_int(HSQUIRRELVM v)
  2522. {
  2523. SQ_FUNC_VARS_NO_TOP(v);
  2524. GET_sqlite3_context_INSTANCE();
  2525. SQ_GET_INTEGER(v, 2, i);
  2526. sqlite3_result_int(self->ctx, i);
  2527. return 0;
  2528. }
  2529. static SQRESULT sq_sqlite3_context_result_null(HSQUIRRELVM v)
  2530. {
  2531. SQ_FUNC_VARS_NO_TOP(v);
  2532. GET_sqlite3_context_INSTANCE();
  2533. sqlite3_result_null(self->ctx);
  2534. return 0;
  2535. }
  2536. static SQRESULT sq_sqlite3_context_result_text(HSQUIRRELVM v)
  2537. {
  2538. SQ_FUNC_VARS_NO_TOP(v);
  2539. GET_sqlite3_context_INSTANCE();
  2540. SQ_GET_STRING(v, 2, text);
  2541. sqlite3_result_text(self->ctx, text, text_size, SQLITE_TRANSIENT);
  2542. return 0;
  2543. }
  2544. static SQRESULT sq_sqlite3_context_result_subtype(HSQUIRRELVM v)
  2545. {
  2546. SQ_FUNC_VARS_NO_TOP(v);
  2547. GET_sqlite3_context_INSTANCE();
  2548. SQ_GET_INTEGER(v, 2, subtype);
  2549. sqlite3_result_subtype(self->ctx, subtype);
  2550. return 0;
  2551. }
  2552. /* no way to recover parameter value after function call
  2553. static SQRESULT sq_sqlite3_context_value_subtype(HSQUIRRELVM v)
  2554. {
  2555. SQ_FUNC_VARS_NO_TOP(v);
  2556. GET_sqlite3_context_INSTANCE();
  2557. SQ_GET_INTEGER(v, 2, param_idx);
  2558. sq_pushinteger(v, sqlite3_value_subtype(self->ctx, subtype));
  2559. return 1;
  2560. }
  2561. */
  2562. #define _DECL_FUNC(name,nparams,tycheck) {_SC(#name), sq_sqlite3_context_##name,nparams,tycheck}
  2563. static SQRegFunction sq_sqlite3_context_methods[] =
  2564. {
  2565. _DECL_FUNC(constructor, 1, _SC("x")),
  2566. _DECL_FUNC(user_data, 1, _SC("x")),
  2567. _DECL_FUNC(aggregate_data, -1, _SC("x.")),
  2568. _DECL_FUNC(aggregate_count, 1, _SC("x")),
  2569. _DECL_FUNC(result_null, 1, _SC("x")),
  2570. _DECL_FUNC(result_double, 2, _SC("xn")),
  2571. _DECL_FUNC(result_int, 2, _SC("xi")),
  2572. _DECL_FUNC(result_text, 2, _SC("xs")),
  2573. _DECL_FUNC(result_blob, 2, _SC("xs")),
  2574. _DECL_FUNC(result_error, 2, _SC("xs")),
  2575. _DECL_FUNC(result_subtype, 2, _SC("xi")),
  2576. //_DECL_FUNC(value_subtype, 2, _SC("xi")),
  2577. _DECL_FUNC(get_aux_data, 2, _SC("xi")),
  2578. _DECL_FUNC(set_aux_data, 3, _SC("xi.")),
  2579. _DECL_FUNC(_tostring, -1, _SC("x")),
  2580. {0,0}
  2581. };
  2582. #undef _DECL_FUNC
  2583. /*
  2584. ** callback functions used when calling registered sql functions
  2585. */
  2586. static void sqlite3_push_value(HSQUIRRELVM v, sqlite3_value *value)
  2587. {
  2588. const char *tmp_value;
  2589. switch (sqlite3_value_type(value))
  2590. {
  2591. case SQLITE_TEXT:
  2592. tmp_value = (const char*) sqlite3_value_text(value);
  2593. if(tmp_value) sq_pushstring(v, tmp_value, sqlite3_value_bytes(value));
  2594. else push_sqlite3_null(v);
  2595. break;
  2596. case SQLITE_INTEGER:
  2597. {
  2598. sqlite_int64 i64 = sqlite3_value_int64(value);
  2599. SQInteger n = (SQInteger)i64;
  2600. if (n == i64)
  2601. sq_pushinteger(v, n);
  2602. else
  2603. sq_pushstring(v, (const char*) sqlite3_value_text(value), sqlite3_value_bytes(value));
  2604. }
  2605. break;
  2606. case SQLITE_FLOAT:
  2607. sq_pushfloat(v, sqlite3_value_double(value));
  2608. break;
  2609. case SQLITE_BLOB:
  2610. tmp_value = (const char*) sqlite3_value_blob(value);
  2611. if(tmp_value) sq_pushstring(v, tmp_value, sqlite3_value_bytes(value));
  2612. else push_sqlite3_null(v);
  2613. break;
  2614. case SQLITE_NULL:
  2615. push_sqlite3_null(v);
  2616. break;
  2617. default:
  2618. /* things done properly (SQLite + SquiLu SQLite)
  2619. ** this should never happen */
  2620. push_sqlite3_null(v);
  2621. break;
  2622. }
  2623. }
  2624. //#if 0
  2625. static SQRESULT new_context_instance(HSQUIRRELVM v, sq_sqlite3_context_st **ctx)
  2626. {
  2627. sq_pushregistrytable(v);
  2628. sq_pushstring(v,_SC("sqite3_context"),-1);
  2629. int rc = sq_rawget(v, -2);
  2630. sq_remove(v, -2); //remove registrytable
  2631. sq_pushroottable(v);
  2632. rc = sq_call(v, 1, SQTrue, SQFalse);
  2633. sq_remove(v, -2); //class
  2634. rc = sq_getinstanceup(v, -1, (void**)ctx, (void*)sq_sqlite3_context_TAG);
  2635. return rc;
  2636. }
  2637. /* scalar function to be called
  2638. ** callback params: context, values... */
  2639. static void db_sql_normal_function(sqlite3_context *context, int argc, sqlite3_value **argv)
  2640. {
  2641. sq_sqlite3_sdb_func *func = (sq_sqlite3_sdb_func*)sqlite3_user_data(context);
  2642. HSQUIRRELVM v = func->sdb->v;
  2643. int n;
  2644. sq_sqlite3_context_st *ctx;
  2645. int top = sq_gettop(v);
  2646. /* ensure there is enough space in the stack */
  2647. sq_reservestack(v, argc + 5);
  2648. sq_pushobject(v, func->fn_step);
  2649. sq_pushroottable(v);
  2650. if (!sq_isclosure(func->fn_finalize))
  2651. {
  2652. new_context_instance(v, &ctx);
  2653. }
  2654. else
  2655. {
  2656. /* reuse context userdata value */
  2657. void *p = sqlite3_aggregate_context(context, 1);
  2658. /* i think it is OK to use assume that using a light user data
  2659. ** as an entry on SquiLu REGISTRY table will be unique */
  2660. sq_pushregistrytable(v);
  2661. sq_pushuserpointer(v, p);
  2662. /* context table */
  2663. if(sq_rawget(v, -2) != SQ_OK)
  2664. {
  2665. /* not yet created? */
  2666. sq_poptop(v); //remove null
  2667. new_context_instance(v, &ctx);
  2668. sq_pushuserpointer(v, p);
  2669. sq_push(v, -2);
  2670. sq_rawset(v, -4); //insert into registrytable
  2671. }
  2672. sq_remove(v, -2); //remove registrytable
  2673. }
  2674. /* push params */
  2675. for (n = 0; n < argc; ++n)
  2676. {
  2677. sqlite3_push_value(v, argv[n]);
  2678. }
  2679. /* set context */
  2680. ctx->ctx = context;
  2681. if (sq_call(v, argc + 2, SQFalse, SQFalse) != SQ_OK) //2 = roottable + ctx
  2682. {
  2683. sqlite3_result_error(context, sq_getlasterror_str(v), -1);
  2684. }
  2685. /* invalidate context */
  2686. ctx->ctx = NULL;
  2687. if (!sq_isclosure(func->fn_finalize))
  2688. {
  2689. sq_release(v, &ctx->udata);
  2690. sq_resetobject(&ctx->udata);
  2691. }
  2692. sq_settop(v, top);
  2693. }
  2694. static void db_sql_finalize_function(sqlite3_context *context)
  2695. {
  2696. sq_sqlite3_sdb_func *func = (sq_sqlite3_sdb_func*)sqlite3_user_data(context);
  2697. HSQUIRRELVM v = func->sdb->v;
  2698. void *p = sqlite3_aggregate_context(context, 1); /* minimal mem usage */
  2699. sq_sqlite3_context_st *ctx;
  2700. int top = sq_gettop(v);
  2701. sq_pushobject(v, func->fn_finalize);
  2702. sq_pushroottable(v);
  2703. /* i think it is OK to use assume that using a light user data
  2704. ** as an entry on SquiLu REGISTRY table will be unique */
  2705. sq_pushregistrytable(v);
  2706. sq_pushuserpointer(v, p);
  2707. /* remove it from registry but we'll use it last time here */
  2708. /* context table */
  2709. if(sq_deleteslot(v, -2, SQTrue) != SQ_OK)
  2710. {
  2711. /* not yet created? - shouldn't happen in finalize function */
  2712. sq_pop(v, 1);
  2713. new_context_instance(v, &ctx);
  2714. sq_pushuserpointer(v, p);
  2715. sq_push(v, -2);
  2716. sq_rawset(v, -4);
  2717. }
  2718. sq_remove(v, -2); //registrytable
  2719. /* set context */
  2720. ctx->ctx = context;
  2721. if (sq_call(v, 1, SQFalse, SQFalse) != SQ_OK)
  2722. {
  2723. sqlite3_result_error(context, sq_getlasterror_str(v), -1);
  2724. }
  2725. /* invalidate context */
  2726. ctx->ctx = NULL;
  2727. /* cleanup context */
  2728. sq_release(v, &ctx->udata);
  2729. sq_resetobject(&ctx->udata);
  2730. sq_settop(v, top);
  2731. }
  2732. /*
  2733. ** Register a normal function
  2734. ** Params: db, function name, number arguments, [ callback | step, finalize], user data
  2735. ** Returns: true on sucess
  2736. **
  2737. ** Normal function:
  2738. ** Params: context, params
  2739. **
  2740. ** Aggregate function:
  2741. ** Params of step: context, params
  2742. ** Params of finalize: context
  2743. */
  2744. static SQRESULT db_register_function(HSQUIRRELVM v, int aggregate)
  2745. {
  2746. SQ_FUNC_VARS(v);
  2747. SQInteger ftype = 0;
  2748. GET_sqlite3_INSTANCE();
  2749. SQ_GET_STRING(v, 2, name);
  2750. SQ_GET_INTEGER(v, 3, nargs);
  2751. if(sq_gettype(v, 4) != OT_CLOSURE)
  2752. return sq_throwerror(v, "invalid parameter 3 expected closure");
  2753. if (aggregate)
  2754. {
  2755. if(sq_gettype(v,5) != OT_CLOSURE)
  2756. return sq_throwerror(v, "invalid parameter 4 expected closure");
  2757. } else {
  2758. sq_optinteger(v, 5, &ftype, 0);
  2759. }
  2760. sq_sqlite3_sdb_func *func;
  2761. /* maybe an alternative way to allocate memory should be used/avoided */
  2762. func = (sq_sqlite3_sdb_func*)sq_malloc(sizeof(sq_sqlite3_sdb_func));
  2763. memset(func, 0, sizeof(sq_sqlite3_sdb_func));
  2764. _rc_ = sqlite3_create_function(
  2765. self, name, nargs, SQLITE_UTF8 | (ftype == SQLITE_DETERMINISTIC ? ftype : 0),
  2766. func,
  2767. aggregate ? NULL : db_sql_normal_function,
  2768. aggregate ? db_sql_normal_function : NULL,
  2769. aggregate ? db_sql_finalize_function : NULL
  2770. );
  2771. if (_rc_ == SQLITE_OK)
  2772. {
  2773. /* save registered function in db function list */
  2774. func->sdb = sdb;
  2775. func->next = sdb->func;
  2776. sdb->func = func;
  2777. /* save the setp/normal function callback */
  2778. sq_resetobject(&func->fn_step);
  2779. sq_getstackobj(v, 4, &func->fn_step);
  2780. sq_addref(v, &func->fn_step);
  2781. /* save the finalize function callback */
  2782. sq_resetobject(&func->fn_finalize);
  2783. if (aggregate)
  2784. {
  2785. sq_getstackobj(v, 5, &func->fn_finalize);
  2786. sq_addref(v, &func->fn_finalize);
  2787. }
  2788. /* save user data */
  2789. sq_resetobject(&func->udata);
  2790. int udata_idx = aggregate ? 6 : 5;
  2791. if(_top_ >= udata_idx)
  2792. {
  2793. sq_getstackobj(v, udata_idx, &func->udata);
  2794. sq_addref(v, &func->udata);
  2795. }
  2796. }
  2797. else
  2798. {
  2799. /* free allocated memory */
  2800. sq_free(func, sizeof(sq_sqlite3_sdb_func));
  2801. }
  2802. sq_pushbool(v, _rc_ == SQLITE_OK ? 1 : 0);
  2803. return 1;
  2804. }
  2805. //#endif
  2806. static SQRESULT sq_sqlite3_create_function(HSQUIRRELVM v)
  2807. {
  2808. return db_register_function(v, 0);
  2809. }
  2810. static SQRESULT sq_sqlite3_create_aggregate(HSQUIRRELVM v)
  2811. {
  2812. return db_register_function(v, 1);
  2813. }
  2814. static SQRESULT sq_sqlite3_backup(HSQUIRRELVM v)
  2815. {
  2816. SQ_FUNC_VARS(v);
  2817. GET_sqlite3_INSTANCE();
  2818. SQ_GET_STRING(v, 2, fname);
  2819. SQ_OPT_STRING(v, 3, dbSrcName, _SC("main"));
  2820. SQ_OPT_STRING(v, 4, dbDestName, _SC("main"));
  2821. sqlite3 *pDest;
  2822. sqlite3_backup *pBackup;
  2823. int rc = sqlite3_open(fname, &pDest);
  2824. if(rc!=SQLITE_OK)
  2825. {
  2826. sqlite3_close(pDest);
  2827. return sq_throwerror(v, _SC("SQLite can't open %s"), fname);
  2828. }
  2829. pBackup = sqlite3_backup_init(pDest, dbDestName, self, dbSrcName);
  2830. if( pBackup==0 ){
  2831. rc = sq_throwerror(v, _SC("Error: %s\n"), sqlite3_errmsg(pDest));
  2832. sqlite3_close(pDest);
  2833. }
  2834. while( (rc = sqlite3_backup_step(pBackup,100))==SQLITE_OK ){}
  2835. sqlite3_backup_finish(pBackup);
  2836. if( rc==SQLITE_DONE ){
  2837. rc = SQ_OK;
  2838. }else{
  2839. rc = sq_throwerror(v, _SC("Error: %s\n"), sqlite3_errmsg(pDest));
  2840. }
  2841. sqlite3_close(pDest);
  2842. return rc;
  2843. }
  2844. static SQRESULT sq_sqlite3_restore(HSQUIRRELVM v)
  2845. {
  2846. SQ_FUNC_VARS(v);
  2847. GET_sqlite3_INSTANCE();
  2848. SQ_GET_STRING(v, 2, fname);
  2849. SQ_OPT_STRING(v, 3, dbSrcName, _SC("main"));
  2850. SQ_OPT_STRING(v, 4, dbDestName, _SC("main"));
  2851. sqlite3 *pSrc;
  2852. sqlite3_backup *pBackup;
  2853. int nTimeout = 0;
  2854. int rc = sqlite3_open(fname, &pSrc);
  2855. if(rc!=SQLITE_OK)
  2856. {
  2857. sqlite3_close(pSrc);
  2858. return sq_throwerror(v, _SC("SQLite can't open %s"), fname);
  2859. }
  2860. pBackup = sqlite3_backup_init(self, dbDestName, pSrc, dbSrcName);
  2861. if( pBackup==0 ){
  2862. sqlite3_close(pSrc);
  2863. return sq_throwerror(v, _SC("Error: %s\n"), sqlite3_errmsg(self));
  2864. }
  2865. while( (rc = sqlite3_backup_step(pBackup,100))==SQLITE_OK
  2866. || rc==SQLITE_BUSY ){
  2867. if( rc==SQLITE_BUSY ){
  2868. if( nTimeout++ >= 3 ) break;
  2869. sqlite3_sleep(100);
  2870. }
  2871. }
  2872. sqlite3_backup_finish(pBackup);
  2873. if( rc==SQLITE_DONE ){
  2874. rc = SQ_OK;
  2875. }else if( rc==SQLITE_BUSY || rc==SQLITE_LOCKED ){
  2876. rc = sq_throwerror(v, _SC("Error: source database is busy\n"));
  2877. }else{
  2878. rc = sq_throwerror(v, _SC("Error: %s\n"), sqlite3_errmsg(self));
  2879. }
  2880. sqlite3_close(pSrc);
  2881. return rc;
  2882. }
  2883. #ifndef SQLITE_OMIT_LOAD_EXTENSION
  2884. static SQRESULT sq_sqlite3_enable_load_extension(HSQUIRRELVM v)
  2885. {
  2886. SQ_FUNC_VARS_NO_TOP(v);
  2887. GET_sqlite3_INSTANCE();
  2888. SQ_GET_BOOL(v, 2, onOff);
  2889. sqlite3_enable_load_extension(self, onOff);
  2890. return 0;
  2891. }
  2892. #endif
  2893. #if 0
  2894. /**
  2895. The number/order of fields should be the same to use this function
  2896. it'll save temporary data convertion.
  2897. */
  2898. static SQRESULT sq_sqlite3_exec_loop(HSQUIRRELVM v)
  2899. {
  2900. SQ_FUNC_VARS(v);
  2901. GET_sqlite3_INSTANCE();
  2902. SQ_GET_STRING(v, 2, outer_sql);
  2903. SQ_GET_STRING(v, 3, inner1_sql);
  2904. SQ_OPT_STRING(v, 4, inner2_sql, NULL);
  2905. sqlite3_stmt *stmt_outer = NULL, *stmt_inner1 = NULL, *stmt_inner2 = NULL;
  2906. int rc = sqlite3_prepare_v2(self, outer_sql, outer_sql_size, &stmt_outer, NULL);
  2907. if(rc == SQLITE_OK)
  2908. {
  2909. rc = sqlite3_prepare_v2(self, inner1_sql, inner1_sql_size, &stmt_inner1, NULL);
  2910. if(rc == SQLITE_OK)
  2911. {
  2912. if(inner2_sql)
  2913. {
  2914. rc = sqlite3_prepare_v2(self, inner2_sql, inner2_sql_size, &stmt_inner2, NULL);
  2915. }
  2916. if(rc == SQLITE_OK)
  2917. {
  2918. int outer_col_count = sqlite3_column_count(stmt_outer);
  2919. int inner1_param_count = sqlite3_bind_parameter_count(stmt_inner1);
  2920. int inner2_param_count = stmt_inner2 ? sqlite3_bind_parameter_count(stmt_inner2) : -1;
  2921. if( (inner1_param_count <= outer_col_count) && ((inner2_param_count > 0)
  2922. && (inner2_param_count <= outer_col_count) ) )
  2923. {
  2924. while(sqlite3_step(stmt_outer) == SQLITE_ROW)
  2925. {
  2926. for(int i=0; i < inner1_param_count; ++i)
  2927. {
  2928. rc = sqlite3_bind_value(stmt_inner1, i+1, sqlite3_column_value(stmt_outer, i));
  2929. if(rc != SQLITE_OK) break;
  2930. }
  2931. if(rc == SQLITE_OK)
  2932. {
  2933. rc = sqlite3_step(stmt_inner1);
  2934. sqlite3_reset(stmt_inner1);
  2935. }
  2936. if(rc != SQLITE_DONE) break;
  2937. if((inner2_param_count > 0) && (sqlite3_changes(self) == 0))
  2938. {
  2939. for(int i=0; i < inner2_param_count; ++i)
  2940. {
  2941. rc = sqlite3_bind_value(stmt_inner2, i+1, sqlite3_column_value(stmt_outer, i));
  2942. if(rc != SQLITE_OK) break;
  2943. }
  2944. if(rc == SQLITE_OK)
  2945. {
  2946. rc = sqlite3_step(stmt_inner2);
  2947. sqlite3_reset(stmt_inner2);
  2948. }
  2949. if(rc != SQLITE_DONE) break;
  2950. }
  2951. }
  2952. }
  2953. else
  2954. {
  2955. return sq_throwerror(v, _SC("bind parameter count mismatch expect %d : %d but got outer %d"),
  2956. inner1_param_count, inner2_param_count, outer_col_count);
  2957. }
  2958. }
  2959. }
  2960. }
  2961. if(stmt_outer) sqlite3_finalize(stmt_outer);
  2962. if(stmt_inner1) sqlite3_finalize(stmt_inner1);
  2963. if(stmt_inner2) sqlite3_finalize(stmt_inner2);
  2964. sq_pushinteger(v, rc);
  2965. return 1;
  2966. }
  2967. #endif // 0
  2968. #define _DECL_FUNC(name,nparams,tycheck) {_SC(#name), sq_sqlite3_##name,nparams,tycheck}
  2969. static SQRegFunction sq_sqlite3_methods[] =
  2970. {
  2971. _DECL_FUNC(constructor, -2, _SC("xsi")),
  2972. _DECL_FUNC(close, 1, _SC("x")),
  2973. _DECL_FUNC(db_ptr, 1, _SC("x")),
  2974. _DECL_FUNC(IsAutoCommitOn, 1, _SC("x")),
  2975. _DECL_FUNC(version, 1, _SC("x|y")),
  2976. _DECL_FUNC(threadsafe, 1, _SC("x|y")),
  2977. _DECL_FUNC(config_single_thread, 1, _SC("y")),
  2978. _DECL_FUNC(config_multi_thread, 1, _SC("y")),
  2979. _DECL_FUNC(config_serialized, 1, _SC("y")),
  2980. _DECL_FUNC(errcode, 1, _SC("x")),
  2981. _DECL_FUNC(errmsg, 1, _SC("x")),
  2982. _DECL_FUNC(sleep, 1, _SC("x")),
  2983. _DECL_FUNC(interrupt, 1, _SC("x")),
  2984. _DECL_FUNC(progress_handler, -2, _SC("x i|o c .")),
  2985. _DECL_FUNC(trace, -2, _SC("x c|o .")),
  2986. _DECL_FUNC(update_hook, -2, _SC("x c|o .")),
  2987. _DECL_FUNC(set_authorizer, -2, _SC("x c|o .")),
  2988. _DECL_FUNC(busy_handler, -2, _SC("x c|o .")),
  2989. _DECL_FUNC(busy_timeout, 2, _SC("xi")),
  2990. _DECL_FUNC(create_function, -4, _SC("xsic.")),
  2991. _DECL_FUNC(create_aggregate, -5, _SC("xsicc.")),
  2992. #ifndef WIN32
  2993. _DECL_FUNC(temp_directory, 2, _SC("xs")),
  2994. #endif
  2995. _DECL_FUNC(enable_shared_cache, 2, _SC("xb")),
  2996. _DECL_FUNC(changes, 1, _SC("x")),
  2997. _DECL_FUNC(exec, -2, _SC("x s|x")),
  2998. _DECL_FUNC(exec_dml, 2, _SC("xs")),
  2999. _DECL_FUNC(exec_one_dml, -2, _SC("x s|x")),
  3000. _DECL_FUNC(exec_get_first_row, -2, _SC("x s|x")),
  3001. _DECL_FUNC(exec_get_one, -2, _SC("x s|x")),
  3002. //_DECL_FUNC(exec_loop, -3, _SC("x sss")),
  3003. _DECL_FUNC(get_db_name, 1, _SC("x")),
  3004. _DECL_FUNC(last_row_id, 1, _SC("x")),
  3005. _DECL_FUNC(prepare, 2, _SC("xs")),
  3006. _DECL_FUNC(blob_open, -5, _SC("xsssii")),
  3007. _DECL_FUNC(set_busy_timeout, -1, _SC("xi")),
  3008. _DECL_FUNC(total_changes, 1, _SC("x")),
  3009. _DECL_FUNC(backup, -2, _SC("xsss")),
  3010. _DECL_FUNC(restore, -2, _SC("xsss")),
  3011. #ifndef SQLITE_OMIT_LOAD_EXTENSION
  3012. _DECL_FUNC(enable_load_extension, 2, _SC("xb")),
  3013. #endif
  3014. #ifdef SQLITE_HAS_CODEC
  3015. _DECL_FUNC(key, 2, _SC("xs")),
  3016. _DECL_FUNC(rekey, 2, _SC("xs")),
  3017. #endif
  3018. {0,0}
  3019. };
  3020. #undef _DECL_FUNC
  3021. #define INT_CONST(v,num) sq_pushstring(v,_SC(#num),-1);sq_pushinteger(v,num);sq_newslot(v,-3,SQTrue);
  3022. #ifdef __cplusplus
  3023. extern "C" {
  3024. #endif
  3025. SQRESULT sqext_register_SQLite3(HSQUIRRELVM v)
  3026. {
  3027. sq_insertfunc(v, _SC("sle2vecOfvec"), sq_sle2vecOfvec, -2, _SC(". s|x a i"), SQTrue);
  3028. sq_insertfunc(v, _SC("get_sle_size"), sq_get_sle_size, -2, _SC(".i"), SQTrue);
  3029. sq_insertfunc(v, _SC("add2sle"), sq_add2sle, -3, _SC(".xsi"), SQTrue);
  3030. sq_pushconsttable(v);
  3031. #define INT_SLE_CONST(num) sq_pushstring(v,_SC("SLE_" #num),-1);sq_pushinteger(v,num);sq_newslot(v,-3,SQTrue);
  3032. INT_SLE_CONST(IBYTE1);
  3033. INT_SLE_CONST(IBYTE2);
  3034. INT_SLE_CONST(IBYTE3);
  3035. INT_SLE_CONST(IBYTE4);
  3036. INT_SLE_CONST(IBYTE_MAX);
  3037. INT_SLE_CONST(SLEMARK);
  3038. INT_SLE_CONST(SLEEND);
  3039. sq_poptop(v); //remove const table
  3040. HSQOBJECT sqlite3_NULL;
  3041. sq_pushregistrytable(v);
  3042. sq_pushstring(v, sqlite3_NULL_Name,-1);
  3043. sq_newuserdata(v, sizeof(void*));
  3044. sq_settypetag(v, -1, (SQUserPointer)sqlite3_NULL_Name);
  3045. sq_resetobject(&sqlite3_NULL);
  3046. sq_getstackobj(v, -1, &sqlite3_NULL);
  3047. sq_newtable(v);
  3048. sq_insert_reg_funcs(v, sqlite3_NULL_methods);
  3049. sq_setdelegate(v, -2);
  3050. sq_newslot(v,-3,SQTrue);
  3051. sq_pushstring(v,_SC("sqite3_context"),-1);
  3052. sq_newclass(v,SQFalse);
  3053. sq_settypetag(v,-1,(SQUserPointer)sq_sqlite3_context_TAG);
  3054. sq_insert_reg_funcs(v, sq_sqlite3_context_methods);
  3055. sq_newslot(v,-3,SQTrue);
  3056. sq_pushstring(v,SQLite3_Blob_TAG,-1);
  3057. sq_newclass(v,SQFalse);
  3058. sq_settypetag(v,-1,(SQUserPointer)SQLite3_Blob_TAG);
  3059. sq_insert_reg_funcs(v, sq_sqlite3_blob_methods);
  3060. sq_newslot(v,-3,SQTrue);
  3061. sq_poptop(v); //remove registrytable
  3062. sq_pushstring(v,SQLite3_TAG,-1);
  3063. sq_newclass(v,SQFalse);
  3064. sq_settypetag(v,-1,(SQUserPointer)SQLite3_TAG);
  3065. sq_insert_reg_funcs(v, sq_sqlite3_methods);
  3066. INT_CONST(v,SQLITE_OPEN_CREATE);
  3067. INT_CONST(v,SQLITE_OPEN_READWRITE);
  3068. INT_CONST(v,SQLITE_OPEN_SHAREDCACHE);
  3069. INT_CONST(v,SQLITE_OPEN_SUBLATIN_NA_LIKE);
  3070. INT_CONST(v,SQLITE_OK);
  3071. INT_CONST(v,SQLITE_BUSY);
  3072. INT_CONST(v,SQLITE_DONE);
  3073. INT_CONST(v,SQLITE_DETERMINISTIC);
  3074. INT_CONST(v,SQLITE_ERROR);
  3075. INT_CONST(v,SQLITE_INTERRUPT);
  3076. INT_CONST(v,SQLITE_MISUSE);
  3077. INT_CONST(v,SQLITE_ROW);
  3078. INT_CONST(v,SQLITE_LOCKED_SHAREDCACHE);
  3079. INT_CONST(v,SQLITE_BUSY_RECOVERY);
  3080. INT_CONST(v,SQLITE_BUSY_SNAPSHOT);
  3081. INT_CONST(v,SQLITE_CANTOPEN_NOTEMPDIR);
  3082. INT_CONST(v,SQLITE_CANTOPEN_ISDIR);
  3083. INT_CONST(v,SQLITE_CANTOPEN_FULLPATH);
  3084. INT_CONST(v,SQLITE_CANTOPEN_CONVPATH);
  3085. INT_CONST(v,SQLITE_CORRUPT_VTAB);
  3086. INT_CONST(v,SQLITE_READONLY_RECOVERY);
  3087. INT_CONST(v,SQLITE_READONLY_CANTLOCK);
  3088. INT_CONST(v,SQLITE_READONLY_ROLLBACK);
  3089. INT_CONST(v,SQLITE_READONLY_DBMOVED);
  3090. INT_CONST(v,SQLITE_ABORT_ROLLBACK);
  3091. INT_CONST(v,SQLITE_CONSTRAINT_CHECK);
  3092. INT_CONST(v,SQLITE_CONSTRAINT_COMMITHOOK);
  3093. INT_CONST(v,SQLITE_CONSTRAINT_FOREIGNKEY);
  3094. INT_CONST(v,SQLITE_CONSTRAINT_FUNCTION);
  3095. INT_CONST(v,SQLITE_CONSTRAINT_NOTNULL);
  3096. INT_CONST(v,SQLITE_CONSTRAINT_PRIMARYKEY);
  3097. INT_CONST(v,SQLITE_CONSTRAINT_TRIGGER);
  3098. INT_CONST(v,SQLITE_CONSTRAINT_UNIQUE);
  3099. INT_CONST(v,SQLITE_CONSTRAINT_VTAB);
  3100. INT_CONST(v,SQLITE_CONSTRAINT_ROWID);
  3101. INT_CONST(v,SQLITE_NOTICE_RECOVER_WAL);
  3102. INT_CONST(v,SQLITE_NOTICE_RECOVER_ROLLBACK);
  3103. INT_CONST(v,SQLITE_WARNING_AUTOINDEX);
  3104. /*Authorizer codes*/
  3105. INT_CONST(v, SQLITE_IGNORE);
  3106. INT_CONST(v, SQLITE_DENY);
  3107. INT_CONST(v, SQLITE_CREATE_INDEX);
  3108. INT_CONST(v, SQLITE_CREATE_TABLE);
  3109. INT_CONST(v, SQLITE_CREATE_TEMP_INDEX);
  3110. INT_CONST(v, SQLITE_CREATE_TEMP_TABLE);
  3111. INT_CONST(v, SQLITE_CREATE_TEMP_TRIGGER);
  3112. INT_CONST(v, SQLITE_CREATE_TEMP_VIEW);
  3113. INT_CONST(v, SQLITE_CREATE_TRIGGER);
  3114. INT_CONST(v, SQLITE_CREATE_VIEW);
  3115. INT_CONST(v, SQLITE_DELETE);
  3116. INT_CONST(v, SQLITE_DROP_INDEX);
  3117. INT_CONST(v, SQLITE_DROP_TABLE);
  3118. INT_CONST(v, SQLITE_DROP_TEMP_INDEX);
  3119. INT_CONST(v, SQLITE_DROP_TEMP_TABLE);
  3120. INT_CONST(v, SQLITE_DROP_TEMP_TRIGGER);
  3121. INT_CONST(v, SQLITE_DROP_TEMP_VIEW);
  3122. INT_CONST(v, SQLITE_DROP_TRIGGER);
  3123. INT_CONST(v, SQLITE_DROP_VIEW);
  3124. INT_CONST(v, SQLITE_INSERT);
  3125. INT_CONST(v, SQLITE_PRAGMA);
  3126. INT_CONST(v, SQLITE_READ);
  3127. INT_CONST(v, SQLITE_SELECT);
  3128. INT_CONST(v, SQLITE_TRANSACTION);
  3129. INT_CONST(v, SQLITE_UPDATE);
  3130. INT_CONST(v, SQLITE_ATTACH);
  3131. INT_CONST(v, SQLITE_DETACH);
  3132. INT_CONST(v, SQLITE_ALTER_TABLE);
  3133. INT_CONST(v, SQLITE_REINDEX);
  3134. INT_CONST(v, SQLITE_ANALYZE);
  3135. INT_CONST(v, SQLITE_CREATE_VTABLE);
  3136. INT_CONST(v, SQLITE_DROP_VTABLE);
  3137. INT_CONST(v, SQLITE_FUNCTION);
  3138. INT_CONST(v, SQLITE_SAVEPOINT);
  3139. INT_CONST(v, SQLITE_COPY);
  3140. INT_CONST(v, SQLITE_RECURSIVE);
  3141. //push sqlite3_NULL as a member
  3142. sq_pushstring(v, nullName,-1);
  3143. sq_pushobject(v, sqlite3_NULL);
  3144. sq_newslot(v,-3,SQTrue);
  3145. sq_newslot(v,-3,SQTrue);
  3146. #ifdef SQLITE_ENABLE_SESSION
  3147. sq_pushstring(v, SQLite3_Session_TAG,-1);
  3148. sq_newclass(v,SQFalse);
  3149. sq_settypetag(v,-1,(SQUserPointer)SQLite3_Session_TAG);
  3150. sq_insert_reg_funcs(v, sq_sqlite3_session_methods);
  3151. sq_newslot(v,-3,SQTrue);
  3152. #endif // SQLITE_ENABLE_SESSION
  3153. sq_pushstring(v, SQLite3_Stmt_TAG,-1);
  3154. sq_newclass(v,SQFalse);
  3155. sq_settypetag(v,-1,(SQUserPointer)SQLite3_Stmt_TAG);
  3156. sq_insert_reg_funcs(v, sq_sqlite3_stmt_methods);
  3157. INT_CONST(v,SQLITE_INTEGER);
  3158. INT_CONST(v,SQLITE_FLOAT);
  3159. INT_CONST(v,SQLITE_NULL);
  3160. INT_CONST(v,SQLITE_TEXT);
  3161. INT_CONST(v,SQLITE_BLOB);
  3162. INT_CONST(v,SQLITE_OK);
  3163. INT_CONST(v,SQLITE_DONE);
  3164. INT_CONST(v,SQLITE_ROW);
  3165. INT_CONST(v,AS_STRING_ALWAYS);
  3166. INT_CONST(v,NULL_AS_EMPTY_STR);
  3167. INT_CONST(v,WITH_COL_NAMES);
  3168. INT_CONST(v,WITH_BLOB_AS_NULL);
  3169. INT_CONST(v,WITH_SQ_NULL);
  3170. //push sqlite3_NULL as a member
  3171. sq_pushstring(v, nullName,-1);
  3172. sq_pushobject(v, sqlite3_NULL);
  3173. sq_newslot(v,-3,SQTrue);
  3174. sq_newslot(v,-3,SQTrue);
  3175. return 1;
  3176. }
  3177. #ifdef __cplusplus
  3178. }
  3179. #endif