database.c 21 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815
  1. #include <sqlite3_ruby.h>
  2. #define REQUIRE_OPEN_DB(_ctxt) \
  3. if(!_ctxt->db) \
  4. rb_raise(rb_path2class("SQLite3::Exception"), "cannot use a closed database");
  5. VALUE cSqlite3Database;
  6. static VALUE sym_utf16, sym_results_as_hash, sym_type_translation;
  7. static void deallocate(void * ctx)
  8. {
  9. sqlite3RubyPtr c = (sqlite3RubyPtr)ctx;
  10. sqlite3 * db = c->db;
  11. if(db) sqlite3_close(db);
  12. xfree(c);
  13. }
  14. static VALUE allocate(VALUE klass)
  15. {
  16. sqlite3RubyPtr ctx = xcalloc((size_t)1, sizeof(sqlite3Ruby));
  17. return Data_Wrap_Struct(klass, NULL, deallocate, ctx);
  18. }
  19. static char *
  20. utf16_string_value_ptr(VALUE str)
  21. {
  22. StringValue(str);
  23. rb_str_buf_cat(str, "\x00", 1L);
  24. return RSTRING_PTR(str);
  25. }
  26. /* call-seq: SQLite3::Database.new(file, options = {})
  27. *
  28. * Create a new Database object that opens the given file. If utf16
  29. * is +true+, the filename is interpreted as a UTF-16 encoded string.
  30. *
  31. * By default, the new database will return result rows as arrays
  32. * (#results_as_hash) and has type translation disabled (#type_translation=).
  33. */
  34. static VALUE initialize(int argc, VALUE *argv, VALUE self)
  35. {
  36. sqlite3RubyPtr ctx;
  37. VALUE file;
  38. VALUE opts;
  39. VALUE zvfs;
  40. #ifdef HAVE_SQLITE3_OPEN_V2
  41. int mode = SQLITE_OPEN_READWRITE | SQLITE_OPEN_CREATE;
  42. #endif
  43. int status;
  44. Data_Get_Struct(self, sqlite3Ruby, ctx);
  45. rb_scan_args(argc, argv, "12", &file, &opts, &zvfs);
  46. #if defined StringValueCStr
  47. StringValuePtr(file);
  48. rb_check_safe_obj(file);
  49. #else
  50. Check_SafeStr(file);
  51. #endif
  52. if(NIL_P(opts)) opts = rb_hash_new();
  53. else Check_Type(opts, T_HASH);
  54. #ifdef HAVE_RUBY_ENCODING_H
  55. if(UTF16_LE_P(file) || UTF16_BE_P(file)) {
  56. status = sqlite3_open16(utf16_string_value_ptr(file), &ctx->db);
  57. } else {
  58. #endif
  59. if(Qtrue == rb_hash_aref(opts, sym_utf16)) {
  60. status = sqlite3_open16(utf16_string_value_ptr(file), &ctx->db);
  61. } else {
  62. #ifdef HAVE_RUBY_ENCODING_H
  63. if(!UTF8_P(file)) {
  64. file = rb_str_export_to_enc(file, rb_utf8_encoding());
  65. }
  66. #endif
  67. if (Qtrue == rb_hash_aref(opts, ID2SYM(rb_intern("readonly")))) {
  68. #ifdef HAVE_SQLITE3_OPEN_V2
  69. mode = SQLITE_OPEN_READONLY;
  70. #else
  71. rb_raise(rb_eNotImpError, "sqlite3-ruby was compiled against a version of sqlite that does not support readonly databases");
  72. #endif
  73. }
  74. #ifdef HAVE_SQLITE3_OPEN_V2
  75. status = sqlite3_open_v2(
  76. StringValuePtr(file),
  77. &ctx->db,
  78. mode,
  79. NIL_P(zvfs) ? NULL : StringValuePtr(zvfs)
  80. );
  81. #else
  82. status = sqlite3_open(
  83. StringValuePtr(file),
  84. &ctx->db
  85. );
  86. #endif
  87. }
  88. #ifdef HAVE_RUBY_ENCODING_H
  89. }
  90. #endif
  91. CHECK(ctx->db, status)
  92. rb_iv_set(self, "@tracefunc", Qnil);
  93. rb_iv_set(self, "@authorizer", Qnil);
  94. rb_iv_set(self, "@encoding", Qnil);
  95. rb_iv_set(self, "@busy_handler", Qnil);
  96. rb_iv_set(self, "@collations", rb_hash_new());
  97. rb_iv_set(self, "@functions", rb_hash_new());
  98. rb_iv_set(self, "@results_as_hash", rb_hash_aref(opts, sym_results_as_hash));
  99. rb_iv_set(self, "@type_translation", rb_hash_aref(opts, sym_type_translation));
  100. #ifdef HAVE_SQLITE3_OPEN_V2
  101. rb_iv_set(self, "@readonly", mode == SQLITE_OPEN_READONLY ? Qtrue : Qfalse);
  102. #else
  103. rb_iv_set(self, "@readonly", Qfalse);
  104. #endif
  105. if(rb_block_given_p()) {
  106. rb_yield(self);
  107. rb_funcall(self, rb_intern("close"), 0);
  108. }
  109. return self;
  110. }
  111. /* call-seq: db.close
  112. *
  113. * Closes this database.
  114. */
  115. static VALUE sqlite3_rb_close(VALUE self)
  116. {
  117. sqlite3RubyPtr ctx;
  118. sqlite3 * db;
  119. Data_Get_Struct(self, sqlite3Ruby, ctx);
  120. db = ctx->db;
  121. CHECK(db, sqlite3_close(ctx->db));
  122. ctx->db = NULL;
  123. return self;
  124. }
  125. /* call-seq: db.closed?
  126. *
  127. * Returns +true+ if this database instance has been closed (see #close).
  128. */
  129. static VALUE closed_p(VALUE self)
  130. {
  131. sqlite3RubyPtr ctx;
  132. Data_Get_Struct(self, sqlite3Ruby, ctx);
  133. if(!ctx->db) return Qtrue;
  134. return Qfalse;
  135. }
  136. /* call-seq: total_changes
  137. *
  138. * Returns the total number of changes made to this database instance
  139. * since it was opened.
  140. */
  141. static VALUE total_changes(VALUE self)
  142. {
  143. sqlite3RubyPtr ctx;
  144. Data_Get_Struct(self, sqlite3Ruby, ctx);
  145. REQUIRE_OPEN_DB(ctx);
  146. return INT2NUM((long)sqlite3_total_changes(ctx->db));
  147. }
  148. static void tracefunc(void * data, const char *sql)
  149. {
  150. VALUE self = (VALUE)data;
  151. VALUE thing = rb_iv_get(self, "@tracefunc");
  152. rb_funcall(thing, rb_intern("call"), 1, rb_str_new2(sql));
  153. }
  154. /* call-seq:
  155. * trace { |sql| ... }
  156. * trace(Class.new { def call sql; end }.new)
  157. *
  158. * Installs (or removes) a block that will be invoked for every SQL
  159. * statement executed. The block receives one parameter: the SQL statement
  160. * executed. If the block is +nil+, any existing tracer will be uninstalled.
  161. */
  162. static VALUE trace(int argc, VALUE *argv, VALUE self)
  163. {
  164. sqlite3RubyPtr ctx;
  165. VALUE block;
  166. Data_Get_Struct(self, sqlite3Ruby, ctx);
  167. REQUIRE_OPEN_DB(ctx);
  168. rb_scan_args(argc, argv, "01", &block);
  169. if(NIL_P(block) && rb_block_given_p()) block = rb_block_proc();
  170. rb_iv_set(self, "@tracefunc", block);
  171. sqlite3_trace(ctx->db, NIL_P(block) ? NULL : tracefunc, (void *)self);
  172. return self;
  173. }
  174. static int rb_sqlite3_busy_handler(void * ctx, int count)
  175. {
  176. VALUE self = (VALUE)(ctx);
  177. VALUE handle = rb_iv_get(self, "@busy_handler");
  178. VALUE result = rb_funcall(handle, rb_intern("call"), 1, INT2NUM((long)count));
  179. if(Qfalse == result) return 0;
  180. return 1;
  181. }
  182. /* call-seq:
  183. * busy_handler { |count| ... }
  184. * busy_handler(Class.new { def call count; end }.new)
  185. *
  186. * Register a busy handler with this database instance. When a requested
  187. * resource is busy, this handler will be invoked. If the handler returns
  188. * +false+, the operation will be aborted; otherwise, the resource will
  189. * be requested again.
  190. *
  191. * The handler will be invoked with the name of the resource that was
  192. * busy, and the number of times it has been retried.
  193. *
  194. * See also the mutually exclusive #busy_timeout.
  195. */
  196. static VALUE busy_handler(int argc, VALUE *argv, VALUE self)
  197. {
  198. sqlite3RubyPtr ctx;
  199. VALUE block;
  200. int status;
  201. Data_Get_Struct(self, sqlite3Ruby, ctx);
  202. REQUIRE_OPEN_DB(ctx);
  203. rb_scan_args(argc, argv, "01", &block);
  204. if(NIL_P(block) && rb_block_given_p()) block = rb_block_proc();
  205. rb_iv_set(self, "@busy_handler", block);
  206. status = sqlite3_busy_handler(
  207. ctx->db, NIL_P(block) ? NULL : rb_sqlite3_busy_handler, (void *)self);
  208. CHECK(ctx->db, status);
  209. return self;
  210. }
  211. /* call-seq: last_insert_row_id
  212. *
  213. * Obtains the unique row ID of the last row to be inserted by this Database
  214. * instance.
  215. */
  216. static VALUE last_insert_row_id(VALUE self)
  217. {
  218. sqlite3RubyPtr ctx;
  219. Data_Get_Struct(self, sqlite3Ruby, ctx);
  220. REQUIRE_OPEN_DB(ctx);
  221. return LL2NUM(sqlite3_last_insert_rowid(ctx->db));
  222. }
  223. static VALUE sqlite3val2rb(sqlite3_value * val)
  224. {
  225. switch(sqlite3_value_type(val)) {
  226. case SQLITE_INTEGER:
  227. return LL2NUM(sqlite3_value_int64(val));
  228. break;
  229. case SQLITE_FLOAT:
  230. return rb_float_new(sqlite3_value_double(val));
  231. break;
  232. case SQLITE_TEXT:
  233. return rb_tainted_str_new2((const char *)sqlite3_value_text(val));
  234. break;
  235. case SQLITE_BLOB:
  236. return rb_tainted_str_new2((const char *)sqlite3_value_blob(val));
  237. break;
  238. case SQLITE_NULL:
  239. return Qnil;
  240. break;
  241. default:
  242. rb_raise(rb_eRuntimeError, "bad type"); /* FIXME */
  243. }
  244. }
  245. static void set_sqlite3_func_result(sqlite3_context * ctx, VALUE result)
  246. {
  247. switch(TYPE(result)) {
  248. case T_NIL:
  249. sqlite3_result_null(ctx);
  250. break;
  251. case T_FIXNUM:
  252. sqlite3_result_int64(ctx, (sqlite3_int64)FIX2LONG(result));
  253. break;
  254. case T_BIGNUM:
  255. #if SIZEOF_LONG < 8
  256. if (RBIGNUM_LEN(result) * SIZEOF_BDIGITS <= 8) {
  257. sqlite3_result_int64(ctx, NUM2LL(result));
  258. break;
  259. }
  260. #endif
  261. case T_FLOAT:
  262. sqlite3_result_double(ctx, NUM2DBL(result));
  263. break;
  264. case T_STRING:
  265. sqlite3_result_text(
  266. ctx,
  267. (const char *)StringValuePtr(result),
  268. (int)RSTRING_LEN(result),
  269. SQLITE_TRANSIENT
  270. );
  271. break;
  272. default:
  273. rb_raise(rb_eRuntimeError, "can't return %s",
  274. rb_class2name(CLASS_OF(result)));
  275. }
  276. }
  277. static void rb_sqlite3_func(sqlite3_context * ctx, int argc, sqlite3_value **argv)
  278. {
  279. VALUE callable = (VALUE)sqlite3_user_data(ctx);
  280. VALUE * params = NULL;
  281. VALUE result;
  282. int i;
  283. if (argc > 0) {
  284. params = xcalloc((size_t)argc, sizeof(VALUE *));
  285. for(i = 0; i < argc; i++) {
  286. VALUE param = sqlite3val2rb(argv[i]);
  287. RB_GC_GUARD(param);
  288. params[i] = param;
  289. }
  290. }
  291. result = rb_funcall2(callable, rb_intern("call"), argc, params);
  292. xfree(params);
  293. set_sqlite3_func_result(ctx, result);
  294. }
  295. #ifndef HAVE_RB_PROC_ARITY
  296. int rb_proc_arity(VALUE self)
  297. {
  298. return (int)NUM2INT(rb_funcall(self, rb_intern("arity"), 0));
  299. }
  300. #endif
  301. /* call-seq: define_function(name) { |args,...| }
  302. *
  303. * Define a function named +name+ with +args+. The arity of the block
  304. * will be used as the arity for the function defined.
  305. */
  306. static VALUE define_function(VALUE self, VALUE name)
  307. {
  308. sqlite3RubyPtr ctx;
  309. VALUE block;
  310. int status;
  311. Data_Get_Struct(self, sqlite3Ruby, ctx);
  312. REQUIRE_OPEN_DB(ctx);
  313. block = rb_block_proc();
  314. status = sqlite3_create_function(
  315. ctx->db,
  316. StringValuePtr(name),
  317. rb_proc_arity(block),
  318. SQLITE_UTF8,
  319. (void *)block,
  320. rb_sqlite3_func,
  321. NULL,
  322. NULL
  323. );
  324. CHECK(ctx->db, status);
  325. rb_hash_aset(rb_iv_get(self, "@functions"), name, block);
  326. return self;
  327. }
  328. static int sqlite3_obj_method_arity(VALUE obj, ID id)
  329. {
  330. VALUE method = rb_funcall(obj, rb_intern("method"), 1, ID2SYM(id));
  331. VALUE arity = rb_funcall(method, rb_intern("arity"), 0);
  332. return (int)NUM2INT(arity);
  333. }
  334. static void rb_sqlite3_step(sqlite3_context * ctx, int argc, sqlite3_value **argv)
  335. {
  336. VALUE callable = (VALUE)sqlite3_user_data(ctx);
  337. VALUE * params = NULL;
  338. int i;
  339. if (argc > 0) {
  340. params = xcalloc((size_t)argc, sizeof(VALUE *));
  341. for(i = 0; i < argc; i++) {
  342. params[i] = sqlite3val2rb(argv[i]);
  343. }
  344. }
  345. rb_funcall2(callable, rb_intern("step"), argc, params);
  346. xfree(params);
  347. }
  348. static void rb_sqlite3_final(sqlite3_context * ctx)
  349. {
  350. VALUE callable = (VALUE)sqlite3_user_data(ctx);
  351. VALUE result = rb_funcall(callable, rb_intern("finalize"), 0);
  352. set_sqlite3_func_result(ctx, result);
  353. }
  354. /* call-seq: define_aggregator(name, aggregator)
  355. *
  356. * Define an aggregate function named +name+ using the object +aggregator+.
  357. * +aggregator+ must respond to +step+ and +finalize+. +step+ will be called
  358. * with row information and +finalize+ must return the return value for the
  359. * aggregator function.
  360. */
  361. static VALUE define_aggregator(VALUE self, VALUE name, VALUE aggregator)
  362. {
  363. sqlite3RubyPtr ctx;
  364. int arity, status;
  365. Data_Get_Struct(self, sqlite3Ruby, ctx);
  366. REQUIRE_OPEN_DB(ctx);
  367. arity = sqlite3_obj_method_arity(aggregator, rb_intern("step"));
  368. status = sqlite3_create_function(
  369. ctx->db,
  370. StringValuePtr(name),
  371. arity,
  372. SQLITE_UTF8,
  373. (void *)aggregator,
  374. NULL,
  375. rb_sqlite3_step,
  376. rb_sqlite3_final
  377. );
  378. rb_iv_set(self, "@agregator", aggregator);
  379. CHECK(ctx->db, status);
  380. return self;
  381. }
  382. /* call-seq: interrupt
  383. *
  384. * Interrupts the currently executing operation, causing it to abort.
  385. */
  386. static VALUE interrupt(VALUE self)
  387. {
  388. sqlite3RubyPtr ctx;
  389. Data_Get_Struct(self, sqlite3Ruby, ctx);
  390. REQUIRE_OPEN_DB(ctx);
  391. sqlite3_interrupt(ctx->db);
  392. return self;
  393. }
  394. /* call-seq: errmsg
  395. *
  396. * Return a string describing the last error to have occurred with this
  397. * database.
  398. */
  399. static VALUE errmsg(VALUE self)
  400. {
  401. sqlite3RubyPtr ctx;
  402. Data_Get_Struct(self, sqlite3Ruby, ctx);
  403. REQUIRE_OPEN_DB(ctx);
  404. return rb_str_new2(sqlite3_errmsg(ctx->db));
  405. }
  406. /* call-seq: errcode
  407. *
  408. * Return an integer representing the last error to have occurred with this
  409. * database.
  410. */
  411. static VALUE errcode_(VALUE self)
  412. {
  413. sqlite3RubyPtr ctx;
  414. Data_Get_Struct(self, sqlite3Ruby, ctx);
  415. REQUIRE_OPEN_DB(ctx);
  416. return INT2NUM((long)sqlite3_errcode(ctx->db));
  417. }
  418. /* call-seq: complete?(sql)
  419. *
  420. * Return +true+ if the string is a valid (ie, parsable) SQL statement, and
  421. * +false+ otherwise.
  422. */
  423. static VALUE complete_p(VALUE UNUSED(self), VALUE sql)
  424. {
  425. if(sqlite3_complete(StringValuePtr(sql)))
  426. return Qtrue;
  427. return Qfalse;
  428. }
  429. /* call-seq: changes
  430. *
  431. * Returns the number of changes made to this database instance by the last
  432. * operation performed. Note that a "delete from table" without a where
  433. * clause will not affect this value.
  434. */
  435. static VALUE changes(VALUE self)
  436. {
  437. sqlite3RubyPtr ctx;
  438. Data_Get_Struct(self, sqlite3Ruby, ctx);
  439. REQUIRE_OPEN_DB(ctx);
  440. return INT2NUM(sqlite3_changes(ctx->db));
  441. }
  442. static int rb_sqlite3_auth(
  443. void *ctx,
  444. int _action,
  445. const char * _a,
  446. const char * _b,
  447. const char * _c,
  448. const char * _d)
  449. {
  450. VALUE self = (VALUE)ctx;
  451. VALUE action = INT2NUM(_action);
  452. VALUE a = _a ? rb_str_new2(_a) : Qnil;
  453. VALUE b = _b ? rb_str_new2(_b) : Qnil;
  454. VALUE c = _c ? rb_str_new2(_c) : Qnil;
  455. VALUE d = _d ? rb_str_new2(_d) : Qnil;
  456. VALUE callback = rb_iv_get(self, "@authorizer");
  457. VALUE result = rb_funcall(callback, rb_intern("call"), 5, action, a, b, c, d);
  458. if(T_FIXNUM == TYPE(result)) return (int)NUM2INT(result);
  459. if(Qtrue == result) return SQLITE_OK;
  460. if(Qfalse == result) return SQLITE_DENY;
  461. return SQLITE_IGNORE;
  462. }
  463. /* call-seq: set_authorizer = auth
  464. *
  465. * Set the authorizer for this database. +auth+ must respond to +call+, and
  466. * +call+ must take 5 arguments.
  467. *
  468. * Installs (or removes) a block that will be invoked for every access
  469. * to the database. If the block returns 0 (or +true+), the statement
  470. * is allowed to proceed. Returning 1 or false causes an authorization error to
  471. * occur, and returning 2 or nil causes the access to be silently denied.
  472. */
  473. static VALUE set_authorizer(VALUE self, VALUE authorizer)
  474. {
  475. sqlite3RubyPtr ctx;
  476. int status;
  477. Data_Get_Struct(self, sqlite3Ruby, ctx);
  478. REQUIRE_OPEN_DB(ctx);
  479. status = sqlite3_set_authorizer(
  480. ctx->db, NIL_P(authorizer) ? NULL : rb_sqlite3_auth, (void *)self
  481. );
  482. CHECK(ctx->db, status);
  483. rb_iv_set(self, "@authorizer", authorizer);
  484. return self;
  485. }
  486. /* call-seq: db.busy_timeout = ms
  487. *
  488. * Indicates that if a request for a resource terminates because that
  489. * resource is busy, SQLite should sleep and retry for up to the indicated
  490. * number of milliseconds. By default, SQLite does not retry
  491. * busy resources. To restore the default behavior, send 0 as the
  492. * +ms+ parameter.
  493. *
  494. * See also the mutually exclusive #busy_handler.
  495. */
  496. static VALUE set_busy_timeout(VALUE self, VALUE timeout)
  497. {
  498. sqlite3RubyPtr ctx;
  499. Data_Get_Struct(self, sqlite3Ruby, ctx);
  500. REQUIRE_OPEN_DB(ctx);
  501. CHECK(ctx->db, sqlite3_busy_timeout(ctx->db, (int)NUM2INT(timeout)));
  502. return self;
  503. }
  504. int rb_comparator_func(void * ctx, int a_len, const void * a, int b_len, const void * b)
  505. {
  506. VALUE comparator;
  507. VALUE a_str;
  508. VALUE b_str;
  509. VALUE comparison;
  510. #ifdef HAVE_RUBY_ENCODING_H
  511. rb_encoding * internal_encoding;
  512. internal_encoding = rb_default_internal_encoding();
  513. #endif
  514. comparator = (VALUE)ctx;
  515. a_str = rb_str_new((const char *)a, a_len);
  516. b_str = rb_str_new((const char *)b, b_len);
  517. #ifdef HAVE_RUBY_ENCODING_H
  518. rb_enc_associate_index(a_str, rb_utf8_encindex());
  519. rb_enc_associate_index(b_str, rb_utf8_encindex());
  520. if(internal_encoding) {
  521. a_str = rb_str_export_to_enc(a_str, internal_encoding);
  522. b_str = rb_str_export_to_enc(b_str, internal_encoding);
  523. }
  524. #endif
  525. comparison = rb_funcall(comparator, rb_intern("compare"), 2, a_str, b_str);
  526. return NUM2INT(comparison);
  527. }
  528. /* call-seq: db.collation(name, comparator)
  529. *
  530. * Add a collation with name +name+, and a +comparator+ object. The
  531. * +comparator+ object should implement a method called "compare" that takes
  532. * two parameters and returns an integer less than, equal to, or greater than
  533. * 0.
  534. */
  535. static VALUE collation(VALUE self, VALUE name, VALUE comparator)
  536. {
  537. sqlite3RubyPtr ctx;
  538. Data_Get_Struct(self, sqlite3Ruby, ctx);
  539. REQUIRE_OPEN_DB(ctx);
  540. CHECK(ctx->db, sqlite3_create_collation(
  541. ctx->db,
  542. StringValuePtr(name),
  543. SQLITE_UTF8,
  544. (void *)comparator,
  545. NIL_P(comparator) ? NULL : rb_comparator_func));
  546. /* Make sure our comparator doesn't get garbage collected. */
  547. rb_hash_aset(rb_iv_get(self, "@collations"), name, comparator);
  548. return self;
  549. }
  550. #ifdef HAVE_SQLITE3_LOAD_EXTENSION
  551. /* call-seq: db.load_extension(file)
  552. *
  553. * Loads an SQLite extension library from the named file. Extension
  554. * loading must be enabled using db.enable_load_extension(true) prior
  555. * to calling this API.
  556. */
  557. static VALUE load_extension(VALUE self, VALUE file)
  558. {
  559. sqlite3RubyPtr ctx;
  560. int status;
  561. char *errMsg;
  562. VALUE errexp;
  563. Data_Get_Struct(self, sqlite3Ruby, ctx);
  564. REQUIRE_OPEN_DB(ctx);
  565. status = sqlite3_load_extension(ctx->db, RSTRING_PTR(file), 0, &errMsg);
  566. if (status != SQLITE_OK)
  567. {
  568. errexp = rb_exc_new2(rb_eRuntimeError, errMsg);
  569. sqlite3_free(errMsg);
  570. rb_exc_raise(errexp);
  571. }
  572. return self;
  573. }
  574. #endif
  575. #ifdef HAVE_SQLITE3_ENABLE_LOAD_EXTENSION
  576. /* call-seq: db.enable_load_extension(onoff)
  577. *
  578. * Enable or disable extension loading.
  579. */
  580. static VALUE enable_load_extension(VALUE self, VALUE onoff)
  581. {
  582. sqlite3RubyPtr ctx;
  583. int onoffparam;
  584. Data_Get_Struct(self, sqlite3Ruby, ctx);
  585. REQUIRE_OPEN_DB(ctx);
  586. if (Qtrue == onoff) {
  587. onoffparam = 1;
  588. } else if (Qfalse == onoff) {
  589. onoffparam = 0;
  590. } else {
  591. onoffparam = (int)NUM2INT(onoff);
  592. }
  593. CHECK(ctx->db, sqlite3_enable_load_extension(ctx->db, onoffparam));
  594. return self;
  595. }
  596. #endif
  597. #ifdef HAVE_RUBY_ENCODING_H
  598. static int enc_cb(void * _self, int UNUSED(columns), char **data, char **UNUSED(names))
  599. {
  600. VALUE self = (VALUE)_self;
  601. int index = rb_enc_find_index(data[0]);
  602. rb_encoding * e = rb_enc_from_index(index);
  603. rb_iv_set(self, "@encoding", rb_enc_from_encoding(e));
  604. return 0;
  605. }
  606. #else
  607. static int enc_cb(void * _self, int UNUSED(columns), char **data, char **UNUSED(names))
  608. {
  609. VALUE self = (VALUE)_self;
  610. rb_iv_set(self, "@encoding", rb_str_new2(data[0]));
  611. return 0;
  612. }
  613. #endif
  614. /* call-seq: db.encoding
  615. *
  616. * Fetch the encoding set on this database
  617. */
  618. static VALUE db_encoding(VALUE self)
  619. {
  620. sqlite3RubyPtr ctx;
  621. VALUE enc;
  622. Data_Get_Struct(self, sqlite3Ruby, ctx);
  623. REQUIRE_OPEN_DB(ctx);
  624. enc = rb_iv_get(self, "@encoding");
  625. if(NIL_P(enc)) {
  626. sqlite3_exec(ctx->db, "PRAGMA encoding", enc_cb, (void *)self, NULL);
  627. }
  628. return rb_iv_get(self, "@encoding");
  629. }
  630. /* call-seq: db.transaction_active?
  631. *
  632. * Returns +true+ if there is a transaction active, and +false+ otherwise.
  633. *
  634. */
  635. static VALUE transaction_active_p(VALUE self)
  636. {
  637. sqlite3RubyPtr ctx;
  638. Data_Get_Struct(self, sqlite3Ruby, ctx);
  639. REQUIRE_OPEN_DB(ctx);
  640. return sqlite3_get_autocommit(ctx->db) ? Qfalse : Qtrue;
  641. }
  642. void init_sqlite3_database()
  643. {
  644. ID id_utf16, id_results_as_hash, id_type_translation;
  645. #if 0
  646. VALUE mSqlite3 = rb_define_module("SQLite3");
  647. #endif
  648. cSqlite3Database = rb_define_class_under(mSqlite3, "Database", rb_cObject);
  649. rb_define_alloc_func(cSqlite3Database, allocate);
  650. rb_define_method(cSqlite3Database, "initialize", initialize, -1);
  651. rb_define_method(cSqlite3Database, "collation", collation, 2);
  652. rb_define_method(cSqlite3Database, "close", sqlite3_rb_close, 0);
  653. rb_define_method(cSqlite3Database, "closed?", closed_p, 0);
  654. rb_define_method(cSqlite3Database, "total_changes", total_changes, 0);
  655. rb_define_method(cSqlite3Database, "trace", trace, -1);
  656. rb_define_method(cSqlite3Database, "last_insert_row_id", last_insert_row_id, 0);
  657. rb_define_method(cSqlite3Database, "define_function", define_function, 1);
  658. rb_define_method(cSqlite3Database, "define_aggregator", define_aggregator, 2);
  659. rb_define_method(cSqlite3Database, "interrupt", interrupt, 0);
  660. rb_define_method(cSqlite3Database, "errmsg", errmsg, 0);
  661. rb_define_method(cSqlite3Database, "errcode", errcode_, 0);
  662. rb_define_method(cSqlite3Database, "complete?", complete_p, 1);
  663. rb_define_method(cSqlite3Database, "changes", changes, 0);
  664. rb_define_method(cSqlite3Database, "authorizer=", set_authorizer, 1);
  665. rb_define_method(cSqlite3Database, "busy_handler", busy_handler, -1);
  666. rb_define_method(cSqlite3Database, "busy_timeout=", set_busy_timeout, 1);
  667. rb_define_method(cSqlite3Database, "transaction_active?", transaction_active_p, 0);
  668. #ifdef HAVE_SQLITE3_LOAD_EXTENSION
  669. rb_define_method(cSqlite3Database, "load_extension", load_extension, 1);
  670. #endif
  671. #ifdef HAVE_SQLITE3_ENABLE_LOAD_EXTENSION
  672. rb_define_method(cSqlite3Database, "enable_load_extension", enable_load_extension, 1);
  673. #endif
  674. rb_define_method(cSqlite3Database, "encoding", db_encoding, 0);
  675. id_utf16 = rb_intern("utf16");
  676. sym_utf16 = ID2SYM(id_utf16);
  677. id_results_as_hash = rb_intern("results_as_hash");
  678. sym_results_as_hash = ID2SYM(id_results_as_hash);
  679. id_type_translation = rb_intern("type_translation");
  680. sym_type_translation = ID2SYM(id_type_translation);
  681. }