From 895040f6bd607ee2103dd13d35e60a9341114be4 Mon Sep 17 00:00:00 2001 From: Mike Dalessio Date: Wed, 3 Jan 2024 13:31:55 -0500 Subject: [PATCH] style(c): adopt cruby conventions and some other conventions --- .editorconfig | 15 + ext/sqlite3/aggregator.c | 290 ++++++------ ext/sqlite3/aggregator.h | 6 +- ext/sqlite3/backup.c | 139 +++--- ext/sqlite3/backup.h | 4 +- ext/sqlite3/database.c | 950 ++++++++++++++++++++------------------- ext/sqlite3/database.h | 8 +- ext/sqlite3/exception.c | 185 ++++---- ext/sqlite3/exception.h | 2 +- ext/sqlite3/sqlite3.c | 225 +++++----- ext/sqlite3/statement.c | 546 +++++++++++----------- ext/sqlite3/statement.h | 6 +- rakelib/format.rake | 64 +++ 13 files changed, 1295 insertions(+), 1145 deletions(-) create mode 100644 .editorconfig create mode 100644 rakelib/format.rake diff --git a/.editorconfig b/.editorconfig new file mode 100644 index 00000000..d11eb878 --- /dev/null +++ b/.editorconfig @@ -0,0 +1,15 @@ +root = true + +[*.c,*.h] +end_of_line = lf +indent_size = 4 +indent_style = space +insert_final_newline = true +tab_width = 8 +trim_trailing_whitespace = true + +[*.rb,Rakefile,*.rake,*.gemspec] +indent_size = 2 + +[*.yml] +indent_size = 2 diff --git a/ext/sqlite3/aggregator.c b/ext/sqlite3/aggregator.c index c49ffd84..74558468 100644 --- a/ext/sqlite3/aggregator.c +++ b/ext/sqlite3/aggregator.c @@ -31,20 +31,20 @@ typedef struct rb_sqlite3_protected_funcall_args { static VALUE rb_sqlite3_protected_funcall_body(VALUE protected_funcall_args_ptr) { - protected_funcall_args_t *args = - (protected_funcall_args_t*)protected_funcall_args_ptr; + protected_funcall_args_t *args = + (protected_funcall_args_t *)protected_funcall_args_ptr; - return rb_funcall2(args->self, args->method, args->argc, args->params); + return rb_funcall2(args->self, args->method, args->argc, args->params); } static VALUE rb_sqlite3_protected_funcall(VALUE self, ID method, int argc, VALUE *params, - int* exc_status) + int *exc_status) { - protected_funcall_args_t args = { - .self = self, .method = method, .argc = argc, .params = params - }; - return rb_protect(rb_sqlite3_protected_funcall_body, (VALUE)(&args), exc_status); + protected_funcall_args_t args = { + .self = self, .method = method, .argc = argc, .params = params + }; + return rb_protect(rb_sqlite3_protected_funcall_body, (VALUE)(&args), exc_status); } /* called in rb_sqlite3_aggregator_step and rb_sqlite3_aggregator_final. It @@ -54,36 +54,36 @@ rb_sqlite3_protected_funcall(VALUE self, ID method, int argc, VALUE *params, static VALUE rb_sqlite3_aggregate_instance(sqlite3_context *ctx) { - VALUE aw = (VALUE) sqlite3_user_data(ctx); - VALUE handler_klass = rb_iv_get(aw, "-handler_klass"); - VALUE inst; - VALUE *inst_ptr = sqlite3_aggregate_context(ctx, (int)sizeof(VALUE)); + VALUE aw = (VALUE) sqlite3_user_data(ctx); + VALUE handler_klass = rb_iv_get(aw, "-handler_klass"); + VALUE inst; + VALUE *inst_ptr = sqlite3_aggregate_context(ctx, (int)sizeof(VALUE)); - if (!inst_ptr) { - rb_fatal("SQLite is out-of-merory"); - } + if (!inst_ptr) { + rb_fatal("SQLite is out-of-merory"); + } - inst = *inst_ptr; + inst = *inst_ptr; - if (inst == Qfalse) { /* Qfalse == 0 */ - VALUE instances = rb_iv_get(aw, "-instances"); - int exc_status; + if (inst == Qfalse) { /* Qfalse == 0 */ + VALUE instances = rb_iv_get(aw, "-instances"); + int exc_status; - inst = rb_class_new_instance(0, NULL, cAggregatorInstance); - rb_iv_set(inst, "-handler_instance", rb_sqlite3_protected_funcall( - handler_klass, rb_intern("new"), 0, NULL, &exc_status)); - rb_iv_set(inst, "-exc_status", INT2NUM(exc_status)); + inst = rb_class_new_instance(0, NULL, cAggregatorInstance); + rb_iv_set(inst, "-handler_instance", rb_sqlite3_protected_funcall( + handler_klass, rb_intern("new"), 0, NULL, &exc_status)); + rb_iv_set(inst, "-exc_status", INT2NUM(exc_status)); - rb_ary_push(instances, inst); + rb_ary_push(instances, inst); - *inst_ptr = inst; - } + *inst_ptr = inst; + } - if (inst == Qnil) { - rb_fatal("SQLite called us back on an already destroyed aggregate instance"); - } + if (inst == Qnil) { + rb_fatal("SQLite called us back on an already destroyed aggregate instance"); + } - return inst; + return inst; } /* called by rb_sqlite3_aggregator_final. Unlinks and frees the @@ -92,84 +92,84 @@ rb_sqlite3_aggregate_instance(sqlite3_context *ctx) static void rb_sqlite3_aggregate_instance_destroy(sqlite3_context *ctx) { - VALUE aw = (VALUE) sqlite3_user_data(ctx); - VALUE instances = rb_iv_get(aw, "-instances"); - VALUE *inst_ptr = sqlite3_aggregate_context(ctx, 0); - VALUE inst; + VALUE aw = (VALUE) sqlite3_user_data(ctx); + VALUE instances = rb_iv_get(aw, "-instances"); + VALUE *inst_ptr = sqlite3_aggregate_context(ctx, 0); + VALUE inst; - if (!inst_ptr || (inst = *inst_ptr)) { - return; - } + if (!inst_ptr || (inst = *inst_ptr)) { + return; + } - if (inst == Qnil) { - rb_fatal("attempt to destroy aggregate instance twice"); - } + if (inst == Qnil) { + rb_fatal("attempt to destroy aggregate instance twice"); + } - rb_iv_set(inst, "-handler_instance", Qnil); // may catch use-after-free - if (rb_ary_delete(instances, inst) == Qnil) { - rb_fatal("must be in instances at that point"); - } + rb_iv_set(inst, "-handler_instance", Qnil); // may catch use-after-free + if (rb_ary_delete(instances, inst) == Qnil) { + rb_fatal("must be in instances at that point"); + } - *inst_ptr = Qnil; + *inst_ptr = Qnil; } static void -rb_sqlite3_aggregator_step(sqlite3_context * ctx, int argc, sqlite3_value **argv) +rb_sqlite3_aggregator_step(sqlite3_context *ctx, int argc, sqlite3_value **argv) { - VALUE inst = rb_sqlite3_aggregate_instance(ctx); - VALUE handler_instance = rb_iv_get(inst, "-handler_instance"); - VALUE * params = NULL; - VALUE one_param; - int exc_status = NUM2INT(rb_iv_get(inst, "-exc_status")); - int i; - - if (exc_status) { - return; - } - - if (argc == 1) { - one_param = sqlite3val2rb(argv[0]); - params = &one_param; - } - if (argc > 1) { - params = xcalloc((size_t)argc, sizeof(VALUE)); - for(i = 0; i < argc; i++) { - params[i] = sqlite3val2rb(argv[i]); + VALUE inst = rb_sqlite3_aggregate_instance(ctx); + VALUE handler_instance = rb_iv_get(inst, "-handler_instance"); + VALUE *params = NULL; + VALUE one_param; + int exc_status = NUM2INT(rb_iv_get(inst, "-exc_status")); + int i; + + if (exc_status) { + return; + } + + if (argc == 1) { + one_param = sqlite3val2rb(argv[0]); + params = &one_param; + } + if (argc > 1) { + params = xcalloc((size_t)argc, sizeof(VALUE)); + for (i = 0; i < argc; i++) { + params[i] = sqlite3val2rb(argv[i]); + } + } + rb_sqlite3_protected_funcall( + handler_instance, rb_intern("step"), argc, params, &exc_status); + if (argc > 1) { + xfree(params); } - } - rb_sqlite3_protected_funcall( - handler_instance, rb_intern("step"), argc, params, &exc_status); - if (argc > 1) { - xfree(params); - } - - rb_iv_set(inst, "-exc_status", INT2NUM(exc_status)); + + rb_iv_set(inst, "-exc_status", INT2NUM(exc_status)); } /* we assume that this function is only called once per execution context */ static void -rb_sqlite3_aggregator_final(sqlite3_context * ctx) +rb_sqlite3_aggregator_final(sqlite3_context *ctx) { - VALUE inst = rb_sqlite3_aggregate_instance(ctx); - VALUE handler_instance = rb_iv_get(inst, "-handler_instance"); - int exc_status = NUM2INT(rb_iv_get(inst, "-exc_status")); + VALUE inst = rb_sqlite3_aggregate_instance(ctx); + VALUE handler_instance = rb_iv_get(inst, "-handler_instance"); + int exc_status = NUM2INT(rb_iv_get(inst, "-exc_status")); - if (!exc_status) { - VALUE result = rb_sqlite3_protected_funcall( - handler_instance, rb_intern("finalize"), 0, NULL, &exc_status); if (!exc_status) { - set_sqlite3_func_result(ctx, result); + VALUE result = rb_sqlite3_protected_funcall( + handler_instance, rb_intern("finalize"), 0, NULL, &exc_status); + if (!exc_status) { + set_sqlite3_func_result(ctx, result); + } } - } - if (exc_status) { - /* the user should never see this, as Statement.step() will pick up the - * outstanding exception and raise it instead of generating a new one - * for SQLITE_ERROR with message "Ruby Exception occurred" */ - sqlite3_result_error(ctx, "Ruby Exception occurred", -1); - } + if (exc_status) { + /* the user should never see this, as Statement.step() will pick up the + * outstanding exception and raise it instead of generating a new one + * for SQLITE_ERROR with message "Ruby Exception occurred" */ + sqlite3_result_error(ctx, "Ruby Exception occurred", -1); + } - rb_sqlite3_aggregate_instance_destroy(ctx); + rb_sqlite3_aggregate_instance_destroy(ctx); } /* call-seq: define_aggregator2(aggregator) @@ -205,69 +205,69 @@ rb_sqlite3_aggregator_final(sqlite3_context * ctx) VALUE rb_sqlite3_define_aggregator2(VALUE self, VALUE aggregator, VALUE ruby_name) { - /* define_aggregator is added as a method to SQLite3::Database in database.c */ - sqlite3RubyPtr ctx = sqlite3_database_unwrap(self); - int arity, status; - VALUE aw; - VALUE aggregators; - - if (!ctx->db) { - rb_raise(rb_path2class("SQLite3::Exception"), "cannot use a closed database"); - } - - if (rb_respond_to(aggregator, rb_intern("arity"))) { - VALUE ruby_arity = rb_funcall(aggregator, rb_intern("arity"), 0); - arity = NUM2INT(ruby_arity); - } else { - arity = -1; - } - - if (arity < -1 || arity > 127) { + /* define_aggregator is added as a method to SQLite3::Database in database.c */ + sqlite3RubyPtr ctx = sqlite3_database_unwrap(self); + int arity, status; + VALUE aw; + VALUE aggregators; + + if (!ctx->db) { + rb_raise(rb_path2class("SQLite3::Exception"), "cannot use a closed database"); + } + + if (rb_respond_to(aggregator, rb_intern("arity"))) { + VALUE ruby_arity = rb_funcall(aggregator, rb_intern("arity"), 0); + arity = NUM2INT(ruby_arity); + } else { + arity = -1; + } + + if (arity < -1 || arity > 127) { #ifdef PRIsVALUE - rb_raise(rb_eArgError, "%"PRIsVALUE" arity=%d out of range -1..127", - self, arity); + rb_raise(rb_eArgError, "%"PRIsVALUE" arity=%d out of range -1..127", + self, arity); #else - rb_raise(rb_eArgError, "Aggregator arity=%d out of range -1..127", arity); + rb_raise(rb_eArgError, "Aggregator arity=%d out of range -1..127", arity); #endif - } - - if (!rb_ivar_defined(self, rb_intern("-aggregators"))) { - rb_iv_set(self, "-aggregators", rb_ary_new()); - } - aggregators = rb_iv_get(self, "-aggregators"); - - aw = rb_class_new_instance(0, NULL, cAggregatorWrapper); - rb_iv_set(aw, "-handler_klass", aggregator); - rb_iv_set(aw, "-instances", rb_ary_new()); - - status = sqlite3_create_function( - ctx->db, - StringValueCStr(ruby_name), - arity, - SQLITE_UTF8, - (void*)aw, - NULL, - rb_sqlite3_aggregator_step, - rb_sqlite3_aggregator_final - ); - - if (status != SQLITE_OK) { - rb_sqlite3_raise(ctx->db, status); - return self; // just in case rb_sqlite3_raise returns. - } - - rb_ary_push(aggregators, aw); - - return self; + } + + if (!rb_ivar_defined(self, rb_intern("-aggregators"))) { + rb_iv_set(self, "-aggregators", rb_ary_new()); + } + aggregators = rb_iv_get(self, "-aggregators"); + + aw = rb_class_new_instance(0, NULL, cAggregatorWrapper); + rb_iv_set(aw, "-handler_klass", aggregator); + rb_iv_set(aw, "-instances", rb_ary_new()); + + status = sqlite3_create_function( + ctx->db, + StringValueCStr(ruby_name), + arity, + SQLITE_UTF8, + (void *)aw, + NULL, + rb_sqlite3_aggregator_step, + rb_sqlite3_aggregator_final + ); + + if (status != SQLITE_OK) { + rb_sqlite3_raise(ctx->db, status); + return self; // just in case rb_sqlite3_raise returns. + } + + rb_ary_push(aggregators, aw); + + return self; } void rb_sqlite3_aggregator_init(void) { - /* rb_class_new generatos class with undefined allocator in ruby 1.9 */ - cAggregatorWrapper = rb_funcall(rb_cClass, rb_intern("new"), 0); - rb_gc_register_mark_object(cAggregatorWrapper); + /* rb_class_new generatos class with undefined allocator in ruby 1.9 */ + cAggregatorWrapper = rb_funcall(rb_cClass, rb_intern("new"), 0); + rb_gc_register_mark_object(cAggregatorWrapper); - cAggregatorInstance = rb_funcall(rb_cClass, rb_intern("new"), 0); - rb_gc_register_mark_object(cAggregatorInstance); + cAggregatorInstance = rb_funcall(rb_cClass, rb_intern("new"), 0); + rb_gc_register_mark_object(cAggregatorInstance); } diff --git a/ext/sqlite3/aggregator.h b/ext/sqlite3/aggregator.h index 68968d15..3f528ba5 100644 --- a/ext/sqlite3/aggregator.h +++ b/ext/sqlite3/aggregator.h @@ -3,10 +3,8 @@ #include -VALUE -rb_sqlite3_define_aggregator2(VALUE self, VALUE aggregator, VALUE ruby_name); +VALUE rb_sqlite3_define_aggregator2(VALUE self, VALUE aggregator, VALUE ruby_name); -void -rb_sqlite3_aggregator_init(void); +void rb_sqlite3_aggregator_init(void); #endif diff --git a/ext/sqlite3/backup.c b/ext/sqlite3/backup.c index cd6cda24..b40b1403 100644 --- a/ext/sqlite3/backup.c +++ b/ext/sqlite3/backup.c @@ -8,11 +8,12 @@ VALUE cSqlite3Backup; -static size_t backup_memsize(const void *data) +static size_t +backup_memsize(const void *data) { - sqlite3BackupRubyPtr ctx = (sqlite3BackupRubyPtr)data; - // NB: can't account for ctx->p because the type is incomplete. - return sizeof(*ctx); + sqlite3BackupRubyPtr ctx = (sqlite3BackupRubyPtr)data; + // NB: can't account for ctx->p because the type is incomplete. + return sizeof(*ctx); } static const rb_data_type_t backup_type = { @@ -27,10 +28,11 @@ static const rb_data_type_t backup_type = { RUBY_TYPED_FREE_IMMEDIATELY | RUBY_TYPED_WB_PROTECTED, }; -static VALUE allocate(VALUE klass) +static VALUE +allocate(VALUE klass) { - sqlite3BackupRubyPtr ctx; - return TypedData_Make_Struct(klass, sqlite3BackupRuby, &backup_type, ctx); + sqlite3BackupRubyPtr ctx; + return TypedData_Make_Struct(klass, sqlite3BackupRuby, &backup_type, ctx); } /* call-seq: SQLite3::Backup.new(dstdb, dstname, srcdb, srcname) @@ -69,31 +71,33 @@ static VALUE allocate(VALUE klass) * b.finish * */ -static VALUE initialize(VALUE self, VALUE dstdb, VALUE dstname, VALUE srcdb, VALUE srcname) +static VALUE +initialize(VALUE self, VALUE dstdb, VALUE dstname, VALUE srcdb, VALUE srcname) { - sqlite3BackupRubyPtr ctx; - sqlite3RubyPtr ddb_ctx, sdb_ctx; - sqlite3_backup *pBackup; - - TypedData_Get_Struct(self, sqlite3BackupRuby, &backup_type, ctx); - ddb_ctx = sqlite3_database_unwrap(dstdb); - sdb_ctx = sqlite3_database_unwrap(srcdb); - - if(!sdb_ctx->db) - rb_raise(rb_eArgError, "cannot backup from a closed database"); - if(!ddb_ctx->db) - rb_raise(rb_eArgError, "cannot backup to a closed database"); - - pBackup = sqlite3_backup_init(ddb_ctx->db, StringValuePtr(dstname), - sdb_ctx->db, StringValuePtr(srcname)); - if( pBackup ){ - ctx->p = pBackup; - } - else { - CHECK(ddb_ctx->db, sqlite3_errcode(ddb_ctx->db)); - } - - return self; + sqlite3BackupRubyPtr ctx; + sqlite3RubyPtr ddb_ctx, sdb_ctx; + sqlite3_backup *pBackup; + + TypedData_Get_Struct(self, sqlite3BackupRuby, &backup_type, ctx); + ddb_ctx = sqlite3_database_unwrap(dstdb); + sdb_ctx = sqlite3_database_unwrap(srcdb); + + if (!sdb_ctx->db) { + rb_raise(rb_eArgError, "cannot backup from a closed database"); + } + if (!ddb_ctx->db) { + rb_raise(rb_eArgError, "cannot backup to a closed database"); + } + + pBackup = sqlite3_backup_init(ddb_ctx->db, StringValuePtr(dstname), + sdb_ctx->db, StringValuePtr(srcname)); + if (pBackup) { + ctx->p = pBackup; + } else { + CHECK(ddb_ctx->db, sqlite3_errcode(ddb_ctx->db)); + } + + return self; } /* call-seq: SQLite3::Backup#step(nPage) @@ -105,30 +109,32 @@ static VALUE initialize(VALUE self, VALUE dstdb, VALUE dstname, VALUE srcdb, VAL * When coping is not done, it returns SQLite3::Constants::ErrorCode::OK. * When some errors occur, it returns the error code. */ -static VALUE step(VALUE self, VALUE nPage) +static VALUE +step(VALUE self, VALUE nPage) { - sqlite3BackupRubyPtr ctx; - int status; + sqlite3BackupRubyPtr ctx; + int status; - TypedData_Get_Struct(self, sqlite3BackupRuby, &backup_type, ctx); - REQUIRE_OPEN_BACKUP(ctx); - status = sqlite3_backup_step(ctx->p, NUM2INT(nPage)); - return INT2NUM(status); + TypedData_Get_Struct(self, sqlite3BackupRuby, &backup_type, ctx); + REQUIRE_OPEN_BACKUP(ctx); + status = sqlite3_backup_step(ctx->p, NUM2INT(nPage)); + return INT2NUM(status); } /* call-seq: SQLite3::Backup#finish * * Destroy the backup object. */ -static VALUE finish(VALUE self) +static VALUE +finish(VALUE self) { - sqlite3BackupRubyPtr ctx; + sqlite3BackupRubyPtr ctx; - TypedData_Get_Struct(self, sqlite3BackupRuby, &backup_type, ctx); - REQUIRE_OPEN_BACKUP(ctx); - (void)sqlite3_backup_finish(ctx->p); - ctx->p = NULL; - return Qnil; + TypedData_Get_Struct(self, sqlite3BackupRuby, &backup_type, ctx); + REQUIRE_OPEN_BACKUP(ctx); + (void)sqlite3_backup_finish(ctx->p); + ctx->p = NULL; + return Qnil; } /* call-seq: SQLite3::Backup#remaining @@ -138,13 +144,14 @@ static VALUE finish(VALUE self) * Note that the value is only updated after step() is called, * so before calling step() returned value is invalid. */ -static VALUE remaining(VALUE self) +static VALUE +remaining(VALUE self) { - sqlite3BackupRubyPtr ctx; + sqlite3BackupRubyPtr ctx; - TypedData_Get_Struct(self, sqlite3BackupRuby, &backup_type, ctx); - REQUIRE_OPEN_BACKUP(ctx); - return INT2NUM(sqlite3_backup_remaining(ctx->p)); + TypedData_Get_Struct(self, sqlite3BackupRuby, &backup_type, ctx); + REQUIRE_OPEN_BACKUP(ctx); + return INT2NUM(sqlite3_backup_remaining(ctx->p)); } /* call-seq: SQLite3::Backup#pagecount @@ -154,28 +161,30 @@ static VALUE remaining(VALUE self) * Note that the value is only updated after step() is called, * so before calling step() returned value is invalid. */ -static VALUE pagecount(VALUE self) +static VALUE +pagecount(VALUE self) { - sqlite3BackupRubyPtr ctx; + sqlite3BackupRubyPtr ctx; - TypedData_Get_Struct(self, sqlite3BackupRuby, &backup_type, ctx); - REQUIRE_OPEN_BACKUP(ctx); - return INT2NUM(sqlite3_backup_pagecount(ctx->p)); + TypedData_Get_Struct(self, sqlite3BackupRuby, &backup_type, ctx); + REQUIRE_OPEN_BACKUP(ctx); + return INT2NUM(sqlite3_backup_pagecount(ctx->p)); } -void init_sqlite3_backup(void) +void +init_sqlite3_backup(void) { #if 0 - VALUE mSqlite3 = rb_define_module("SQLite3"); + VALUE mSqlite3 = rb_define_module("SQLite3"); #endif - cSqlite3Backup = rb_define_class_under(mSqlite3, "Backup", rb_cObject); - - rb_define_alloc_func(cSqlite3Backup, allocate); - rb_define_method(cSqlite3Backup, "initialize", initialize, 4); - rb_define_method(cSqlite3Backup, "step", step, 1); - rb_define_method(cSqlite3Backup, "finish", finish, 0); - rb_define_method(cSqlite3Backup, "remaining", remaining, 0); - rb_define_method(cSqlite3Backup, "pagecount", pagecount, 0); + cSqlite3Backup = rb_define_class_under(mSqlite3, "Backup", rb_cObject); + + rb_define_alloc_func(cSqlite3Backup, allocate); + rb_define_method(cSqlite3Backup, "initialize", initialize, 4); + rb_define_method(cSqlite3Backup, "step", step, 1); + rb_define_method(cSqlite3Backup, "finish", finish, 0); + rb_define_method(cSqlite3Backup, "remaining", remaining, 0); + rb_define_method(cSqlite3Backup, "pagecount", pagecount, 0); } #endif diff --git a/ext/sqlite3/backup.h b/ext/sqlite3/backup.h index 0c8c6202..55cc7f54 100644 --- a/ext/sqlite3/backup.h +++ b/ext/sqlite3/backup.h @@ -4,11 +4,11 @@ #include struct _sqlite3BackupRuby { - sqlite3_backup *p; + sqlite3_backup *p; }; typedef struct _sqlite3BackupRuby sqlite3BackupRuby; -typedef sqlite3BackupRuby * sqlite3BackupRubyPtr; +typedef sqlite3BackupRuby *sqlite3BackupRubyPtr; void init_sqlite3_backup(); diff --git a/ext/sqlite3/database.c b/ext/sqlite3/database.c index 8bbe9f6b..7180c0b0 100644 --- a/ext/sqlite3/database.c +++ b/ext/sqlite3/database.c @@ -12,98 +12,105 @@ VALUE cSqlite3Database; -static void deallocate(void * ctx) +static void +deallocate(void *ctx) { - sqlite3RubyPtr c = (sqlite3RubyPtr)ctx; - sqlite3 * db = c->db; + sqlite3RubyPtr c = (sqlite3RubyPtr)ctx; + sqlite3 *db = c->db; - if(db) sqlite3_close(db); - xfree(c); + if (db) { sqlite3_close(db); } + xfree(c); } -static size_t database_memsize(const void *ctx) +static size_t +database_memsize(const void *ctx) { - const sqlite3RubyPtr c = (const sqlite3RubyPtr)ctx; - // NB: can't account for ctx->db because the type is incomplete. - return sizeof(*c); + const sqlite3RubyPtr c = (const sqlite3RubyPtr)ctx; + // NB: can't account for ctx->db because the type is incomplete. + return sizeof(*c); } static const rb_data_type_t database_type = { - "SQLite3::Backup", - { - NULL, - deallocate, - database_memsize, - }, - 0, - 0, - RUBY_TYPED_WB_PROTECTED, // Not freed immediately because the dfree function do IOs. + "SQLite3::Backup", + { + NULL, + deallocate, + database_memsize, + }, + 0, + 0, + RUBY_TYPED_WB_PROTECTED, // Not freed immediately because the dfree function do IOs. }; -static VALUE allocate(VALUE klass) +static VALUE +allocate(VALUE klass) { - sqlite3RubyPtr ctx; - return TypedData_Make_Struct(klass, sqlite3Ruby, &database_type, ctx); + sqlite3RubyPtr ctx; + return TypedData_Make_Struct(klass, sqlite3Ruby, &database_type, ctx); } static char * utf16_string_value_ptr(VALUE str) { - StringValue(str); - rb_str_buf_cat(str, "\x00\x00", 2L); - return RSTRING_PTR(str); + StringValue(str); + rb_str_buf_cat(str, "\x00\x00", 2L); + return RSTRING_PTR(str); } static VALUE sqlite3_rb_close(VALUE self); -sqlite3RubyPtr sqlite3_database_unwrap(VALUE database){ - sqlite3RubyPtr ctx; - TypedData_Get_Struct(database, sqlite3Ruby, &database_type, ctx); - return ctx; +sqlite3RubyPtr +sqlite3_database_unwrap(VALUE database) +{ + sqlite3RubyPtr ctx; + TypedData_Get_Struct(database, sqlite3Ruby, &database_type, ctx); + return ctx; } -static VALUE rb_sqlite3_open_v2(VALUE self, VALUE file, VALUE mode, VALUE zvfs) +static VALUE +rb_sqlite3_open_v2(VALUE self, VALUE file, VALUE mode, VALUE zvfs) { - sqlite3RubyPtr ctx; - int status; + sqlite3RubyPtr ctx; + int status; - TypedData_Get_Struct(self, sqlite3Ruby, &database_type, ctx); + TypedData_Get_Struct(self, sqlite3Ruby, &database_type, ctx); #if defined TAINTING_SUPPORT # if defined StringValueCStr - StringValuePtr(file); - rb_check_safe_obj(file); + StringValuePtr(file); + rb_check_safe_obj(file); # else - Check_SafeStr(file); + Check_SafeStr(file); # endif #endif - status = sqlite3_open_v2( - StringValuePtr(file), - &ctx->db, - NUM2INT(mode), - NIL_P(zvfs) ? NULL : StringValuePtr(zvfs) - ); + status = sqlite3_open_v2( + StringValuePtr(file), + &ctx->db, + NUM2INT(mode), + NIL_P(zvfs) ? NULL : StringValuePtr(zvfs) + ); - CHECK(ctx->db, status) + CHECK(ctx->db, status) - return self; + return self; } -static VALUE rb_sqlite3_disable_quirk_mode(VALUE self) +static VALUE +rb_sqlite3_disable_quirk_mode(VALUE self) { #if defined SQLITE_DBCONFIG_DQS_DDL - sqlite3RubyPtr ctx; - TypedData_Get_Struct(self, sqlite3Ruby, &database_type, ctx); + sqlite3RubyPtr ctx; + TypedData_Get_Struct(self, sqlite3Ruby, &database_type, ctx); - if(!ctx->db) return Qfalse; + if (!ctx->db) { return Qfalse; } - sqlite3_db_config(ctx->db, SQLITE_DBCONFIG_DQS_DDL, 0, (void*)0); - sqlite3_db_config(ctx->db, SQLITE_DBCONFIG_DQS_DML, 0, (void*)0); + sqlite3_db_config(ctx->db, SQLITE_DBCONFIG_DQS_DDL, 0, (void *)0); + sqlite3_db_config(ctx->db, SQLITE_DBCONFIG_DQS_DML, 0, (void *)0); - return Qtrue; + return Qtrue; #else - return Qfalse; + return Qfalse; #endif } @@ -111,34 +118,36 @@ static VALUE rb_sqlite3_disable_quirk_mode(VALUE self) * * Closes this database. */ -static VALUE sqlite3_rb_close(VALUE self) +static VALUE +sqlite3_rb_close(VALUE self) { - sqlite3RubyPtr ctx; - sqlite3 * db; - TypedData_Get_Struct(self, sqlite3Ruby, &database_type, ctx); + sqlite3RubyPtr ctx; + sqlite3 *db; + TypedData_Get_Struct(self, sqlite3Ruby, &database_type, ctx); - db = ctx->db; - CHECK(db, sqlite3_close(ctx->db)); + db = ctx->db; + CHECK(db, sqlite3_close(ctx->db)); - ctx->db = NULL; + ctx->db = NULL; - rb_iv_set(self, "-aggregators", Qnil); + rb_iv_set(self, "-aggregators", Qnil); - return self; + return self; } /* call-seq: db.closed? * * Returns +true+ if this database instance has been closed (see #close). */ -static VALUE closed_p(VALUE self) +static VALUE +closed_p(VALUE self) { - sqlite3RubyPtr ctx; - TypedData_Get_Struct(self, sqlite3Ruby, &database_type, ctx); + sqlite3RubyPtr ctx; + TypedData_Get_Struct(self, sqlite3Ruby, &database_type, ctx); - if(!ctx->db) return Qtrue; + if (!ctx->db) { return Qtrue; } - return Qfalse; + return Qfalse; } /* call-seq: total_changes @@ -146,20 +155,22 @@ static VALUE closed_p(VALUE self) * Returns the total number of changes made to this database instance * since it was opened. */ -static VALUE total_changes(VALUE self) +static VALUE +total_changes(VALUE self) { - sqlite3RubyPtr ctx; - TypedData_Get_Struct(self, sqlite3Ruby, &database_type, ctx); - REQUIRE_OPEN_DB(ctx); + sqlite3RubyPtr ctx; + TypedData_Get_Struct(self, sqlite3Ruby, &database_type, ctx); + REQUIRE_OPEN_DB(ctx); - return INT2NUM(sqlite3_total_changes(ctx->db)); + return INT2NUM(sqlite3_total_changes(ctx->db)); } -static void tracefunc(void * data, const char *sql) +static void +tracefunc(void *data, const char *sql) { - VALUE self = (VALUE)data; - VALUE thing = rb_iv_get(self, "@tracefunc"); - rb_funcall(thing, rb_intern("call"), 1, rb_str_new2(sql)); + VALUE self = (VALUE)data; + VALUE thing = rb_iv_get(self, "@tracefunc"); + rb_funcall(thing, rb_intern("call"), 1, rb_str_new2(sql)); } /* call-seq: @@ -170,34 +181,36 @@ static void tracefunc(void * data, const char *sql) * statement executed. The block receives one parameter: the SQL statement * executed. If the block is +nil+, any existing tracer will be uninstalled. */ -static VALUE trace(int argc, VALUE *argv, VALUE self) +static VALUE +trace(int argc, VALUE *argv, VALUE self) { - sqlite3RubyPtr ctx; - VALUE block; + sqlite3RubyPtr ctx; + VALUE block; - TypedData_Get_Struct(self, sqlite3Ruby, &database_type, ctx); - REQUIRE_OPEN_DB(ctx); + TypedData_Get_Struct(self, sqlite3Ruby, &database_type, ctx); + REQUIRE_OPEN_DB(ctx); - rb_scan_args(argc, argv, "01", &block); + rb_scan_args(argc, argv, "01", &block); - if(NIL_P(block) && rb_block_given_p()) block = rb_block_proc(); + if (NIL_P(block) && rb_block_given_p()) { block = rb_block_proc(); } - rb_iv_set(self, "@tracefunc", block); + rb_iv_set(self, "@tracefunc", block); - sqlite3_trace(ctx->db, NIL_P(block) ? NULL : tracefunc, (void *)self); + sqlite3_trace(ctx->db, NIL_P(block) ? NULL : tracefunc, (void *)self); - return self; + return self; } -static int rb_sqlite3_busy_handler(void * ctx, int count) +static int +rb_sqlite3_busy_handler(void *ctx, int count) { - VALUE self = (VALUE)(ctx); - VALUE handle = rb_iv_get(self, "@busy_handler"); - VALUE result = rb_funcall(handle, rb_intern("call"), 1, INT2NUM(count)); + VALUE self = (VALUE)(ctx); + VALUE handle = rb_iv_get(self, "@busy_handler"); + VALUE result = rb_funcall(handle, rb_intern("call"), 1, INT2NUM(count)); - if(Qfalse == result) return 0; + if (Qfalse == result) { return 0; } - return 1; + return 1; } /* call-seq: @@ -214,27 +227,28 @@ static int rb_sqlite3_busy_handler(void * ctx, int count) * * See also the mutually exclusive #busy_timeout. */ -static VALUE busy_handler(int argc, VALUE *argv, VALUE self) +static VALUE +busy_handler(int argc, VALUE *argv, VALUE self) { - sqlite3RubyPtr ctx; - VALUE block; - int status; + sqlite3RubyPtr ctx; + VALUE block; + int status; - TypedData_Get_Struct(self, sqlite3Ruby, &database_type, ctx); - REQUIRE_OPEN_DB(ctx); + TypedData_Get_Struct(self, sqlite3Ruby, &database_type, ctx); + REQUIRE_OPEN_DB(ctx); - rb_scan_args(argc, argv, "01", &block); + rb_scan_args(argc, argv, "01", &block); - if(NIL_P(block) && rb_block_given_p()) block = rb_block_proc(); + if (NIL_P(block) && rb_block_given_p()) { block = rb_block_proc(); } - rb_iv_set(self, "@busy_handler", block); + rb_iv_set(self, "@busy_handler", block); - status = sqlite3_busy_handler( - ctx->db, NIL_P(block) ? NULL : rb_sqlite3_busy_handler, (void *)self); + status = sqlite3_busy_handler( + ctx->db, NIL_P(block) ? NULL : rb_sqlite3_busy_handler, (void *)self); - CHECK(ctx->db, status); + CHECK(ctx->db, status); - return self; + return self; } /* call-seq: last_insert_row_id @@ -242,115 +256,120 @@ static VALUE busy_handler(int argc, VALUE *argv, VALUE self) * Obtains the unique row ID of the last row to be inserted by this Database * instance. */ -static VALUE last_insert_row_id(VALUE self) -{ - sqlite3RubyPtr ctx; - TypedData_Get_Struct(self, sqlite3Ruby, &database_type, ctx); - REQUIRE_OPEN_DB(ctx); - - return LL2NUM(sqlite3_last_insert_rowid(ctx->db)); -} - -VALUE sqlite3val2rb(sqlite3_value * val) -{ - switch(sqlite3_value_type(val)) { - case SQLITE_INTEGER: - return LL2NUM(sqlite3_value_int64(val)); - break; - case SQLITE_FLOAT: - return rb_float_new(sqlite3_value_double(val)); - break; - case SQLITE_TEXT: - return rb_str_new2((const char *)sqlite3_value_text(val)); - break; - case SQLITE_BLOB: { - /* Sqlite warns calling sqlite3_value_bytes may invalidate pointer from sqlite3_value_blob, - so we explicitly get the length before getting blob pointer. - Note that rb_str_new apparently create string with ASCII-8BIT (BINARY) encoding, - which is what we want, as blobs are binary - */ - int len = sqlite3_value_bytes(val); - return rb_str_new((const char *)sqlite3_value_blob(val), len); - break; +static VALUE +last_insert_row_id(VALUE self) +{ + sqlite3RubyPtr ctx; + TypedData_Get_Struct(self, sqlite3Ruby, &database_type, ctx); + REQUIRE_OPEN_DB(ctx); + + return LL2NUM(sqlite3_last_insert_rowid(ctx->db)); +} + +VALUE +sqlite3val2rb(sqlite3_value *val) +{ + switch (sqlite3_value_type(val)) { + case SQLITE_INTEGER: + return LL2NUM(sqlite3_value_int64(val)); + break; + case SQLITE_FLOAT: + return rb_float_new(sqlite3_value_double(val)); + break; + case SQLITE_TEXT: + return rb_str_new2((const char *)sqlite3_value_text(val)); + break; + case SQLITE_BLOB: { + /* Sqlite warns calling sqlite3_value_bytes may invalidate pointer from sqlite3_value_blob, + so we explicitly get the length before getting blob pointer. + Note that rb_str_new apparently create string with ASCII-8BIT (BINARY) encoding, + which is what we want, as blobs are binary + */ + int len = sqlite3_value_bytes(val); + return rb_str_new((const char *)sqlite3_value_blob(val), len); + break; + } + case SQLITE_NULL: + return Qnil; + break; + default: + rb_raise(rb_eRuntimeError, "bad type"); /* FIXME */ } - case SQLITE_NULL: - return Qnil; - break; - default: - rb_raise(rb_eRuntimeError, "bad type"); /* FIXME */ - } -} - -void set_sqlite3_func_result(sqlite3_context * ctx, VALUE result) -{ - switch(TYPE(result)) { - case T_NIL: - sqlite3_result_null(ctx); - break; - case T_FIXNUM: - sqlite3_result_int64(ctx, (sqlite3_int64)FIX2LONG(result)); - break; - case T_BIGNUM: { +} + +void +set_sqlite3_func_result(sqlite3_context *ctx, VALUE result) +{ + switch (TYPE(result)) { + case T_NIL: + sqlite3_result_null(ctx); + break; + case T_FIXNUM: + sqlite3_result_int64(ctx, (sqlite3_int64)FIX2LONG(result)); + break; + case T_BIGNUM: { #if SIZEOF_LONG < 8 - sqlite3_int64 num64; + sqlite3_int64 num64; - if (bignum_to_int64(result, &num64)) { - sqlite3_result_int64(ctx, num64); - break; - } + if (bignum_to_int64(result, &num64)) { + sqlite3_result_int64(ctx, num64); + break; + } #endif + } + case T_FLOAT: + sqlite3_result_double(ctx, NUM2DBL(result)); + break; + case T_STRING: + if (CLASS_OF(result) == cSqlite3Blob + || rb_enc_get_index(result) == rb_ascii8bit_encindex() + ) { + sqlite3_result_blob( + ctx, + (const void *)StringValuePtr(result), + (int)RSTRING_LEN(result), + SQLITE_TRANSIENT + ); + } else { + sqlite3_result_text( + ctx, + (const char *)StringValuePtr(result), + (int)RSTRING_LEN(result), + SQLITE_TRANSIENT + ); + } + break; + default: + rb_raise(rb_eRuntimeError, "can't return %s", + rb_class2name(CLASS_OF(result))); } - case T_FLOAT: - sqlite3_result_double(ctx, NUM2DBL(result)); - break; - case T_STRING: - if(CLASS_OF(result) == cSqlite3Blob - || rb_enc_get_index(result) == rb_ascii8bit_encindex() - ) { - sqlite3_result_blob( - ctx, - (const void *)StringValuePtr(result), - (int)RSTRING_LEN(result), - SQLITE_TRANSIENT - ); - } else { - sqlite3_result_text( - ctx, - (const char *)StringValuePtr(result), - (int)RSTRING_LEN(result), - SQLITE_TRANSIENT - ); - } - break; - default: - rb_raise(rb_eRuntimeError, "can't return %s", - rb_class2name(CLASS_OF(result))); - } -} - -static void rb_sqlite3_func(sqlite3_context * ctx, int argc, sqlite3_value **argv) -{ - VALUE callable = (VALUE)sqlite3_user_data(ctx); - VALUE params = rb_ary_new2(argc); - VALUE result; - int i; - - if (argc > 0) { - for(i = 0; i < argc; i++) { - VALUE param = sqlite3val2rb(argv[i]); - rb_ary_push(params, param); +} + +static void +rb_sqlite3_func(sqlite3_context *ctx, int argc, sqlite3_value **argv) +{ + VALUE callable = (VALUE)sqlite3_user_data(ctx); + VALUE params = rb_ary_new2(argc); + VALUE result; + int i; + + if (argc > 0) { + for (i = 0; i < argc; i++) { + VALUE param = sqlite3val2rb(argv[i]); + rb_ary_push(params, param); + } } - } - result = rb_apply(callable, rb_intern("call"), params); + result = rb_apply(callable, rb_intern("call"), params); - set_sqlite3_func_result(ctx, result); + set_sqlite3_func_result(ctx, result); } #ifndef HAVE_RB_PROC_ARITY -int rb_proc_arity(VALUE self) +int +rb_proc_arity(VALUE self) { - return (int)NUM2INT(rb_funcall(self, rb_intern("arity"), 0)); + return (int)NUM2INT(rb_funcall(self, rb_intern("arity"), 0)); } #endif @@ -359,33 +378,34 @@ int rb_proc_arity(VALUE self) * Define a function named +name+ with +args+ using TextRep bitflags +flags+. The arity of the block * will be used as the arity for the function defined. */ -static VALUE define_function_with_flags(VALUE self, VALUE name, VALUE flags) +static VALUE +define_function_with_flags(VALUE self, VALUE name, VALUE flags) { - sqlite3RubyPtr ctx; - VALUE block; - int status; + sqlite3RubyPtr ctx; + VALUE block; + int status; - TypedData_Get_Struct(self, sqlite3Ruby, &database_type, ctx); - REQUIRE_OPEN_DB(ctx); + TypedData_Get_Struct(self, sqlite3Ruby, &database_type, ctx); + REQUIRE_OPEN_DB(ctx); - block = rb_block_proc(); + block = rb_block_proc(); - status = sqlite3_create_function( - ctx->db, - StringValuePtr(name), - rb_proc_arity(block), - NUM2INT(flags), - (void *)block, - rb_sqlite3_func, - NULL, - NULL - ); + status = sqlite3_create_function( + ctx->db, + StringValuePtr(name), + rb_proc_arity(block), + NUM2INT(flags), + (void *)block, + rb_sqlite3_func, + NULL, + NULL + ); - CHECK(ctx->db, status); + CHECK(ctx->db, status); - rb_hash_aset(rb_iv_get(self, "@functions"), name, block); + rb_hash_aset(rb_iv_get(self, "@functions"), name, block); - return self; + return self; } /* call-seq: define_function(name) { |args,...| } @@ -393,24 +413,26 @@ static VALUE define_function_with_flags(VALUE self, VALUE name, VALUE flags) * Define a function named +name+ with +args+. The arity of the block * will be used as the arity for the function defined. */ -static VALUE define_function(VALUE self, VALUE name) +static VALUE +define_function(VALUE self, VALUE name) { - return define_function_with_flags(self, name, INT2FIX(SQLITE_UTF8)); + return define_function_with_flags(self, name, INT2FIX(SQLITE_UTF8)); } /* call-seq: interrupt * * Interrupts the currently executing operation, causing it to abort. */ -static VALUE interrupt(VALUE self) +static VALUE +interrupt(VALUE self) { - sqlite3RubyPtr ctx; - TypedData_Get_Struct(self, sqlite3Ruby, &database_type, ctx); - REQUIRE_OPEN_DB(ctx); + sqlite3RubyPtr ctx; + TypedData_Get_Struct(self, sqlite3Ruby, &database_type, ctx); + REQUIRE_OPEN_DB(ctx); - sqlite3_interrupt(ctx->db); + sqlite3_interrupt(ctx->db); - return self; + return self; } /* call-seq: errmsg @@ -418,13 +440,14 @@ static VALUE interrupt(VALUE self) * Return a string describing the last error to have occurred with this * database. */ -static VALUE errmsg(VALUE self) +static VALUE +errmsg(VALUE self) { - sqlite3RubyPtr ctx; - TypedData_Get_Struct(self, sqlite3Ruby, &database_type, ctx); - REQUIRE_OPEN_DB(ctx); + sqlite3RubyPtr ctx; + TypedData_Get_Struct(self, sqlite3Ruby, &database_type, ctx); + REQUIRE_OPEN_DB(ctx); - return rb_str_new2(sqlite3_errmsg(ctx->db)); + return rb_str_new2(sqlite3_errmsg(ctx->db)); } /* call-seq: errcode @@ -432,13 +455,14 @@ static VALUE errmsg(VALUE self) * Return an integer representing the last error to have occurred with this * database. */ -static VALUE errcode_(VALUE self) +static VALUE +errcode_(VALUE self) { - sqlite3RubyPtr ctx; - TypedData_Get_Struct(self, sqlite3Ruby, &database_type, ctx); - REQUIRE_OPEN_DB(ctx); + sqlite3RubyPtr ctx; + TypedData_Get_Struct(self, sqlite3Ruby, &database_type, ctx); + REQUIRE_OPEN_DB(ctx); - return INT2NUM(sqlite3_errcode(ctx->db)); + return INT2NUM(sqlite3_errcode(ctx->db)); } /* call-seq: complete?(sql) @@ -446,12 +470,14 @@ static VALUE errcode_(VALUE self) * Return +true+ if the string is a valid (ie, parsable) SQL statement, and * +false+ otherwise. */ -static VALUE complete_p(VALUE UNUSED(self), VALUE sql) +static VALUE +complete_p(VALUE UNUSED(self), VALUE sql) { - if(sqlite3_complete(StringValuePtr(sql))) - return Qtrue; + if (sqlite3_complete(StringValuePtr(sql))) { + return Qtrue; + } - return Qfalse; + return Qfalse; } /* call-seq: changes @@ -460,37 +486,39 @@ static VALUE complete_p(VALUE UNUSED(self), VALUE sql) * operation performed. Note that a "delete from table" without a where * clause will not affect this value. */ -static VALUE changes(VALUE self) +static VALUE +changes(VALUE self) { - sqlite3RubyPtr ctx; - TypedData_Get_Struct(self, sqlite3Ruby, &database_type, ctx); - REQUIRE_OPEN_DB(ctx); + sqlite3RubyPtr ctx; + TypedData_Get_Struct(self, sqlite3Ruby, &database_type, ctx); + REQUIRE_OPEN_DB(ctx); - return INT2NUM(sqlite3_changes(ctx->db)); + return INT2NUM(sqlite3_changes(ctx->db)); } -static int rb_sqlite3_auth( +static int +rb_sqlite3_auth( void *ctx, int _action, - const char * _a, - const char * _b, - const char * _c, - const char * _d) + const char *_a, + const char *_b, + const char *_c, + const char *_d) { - VALUE self = (VALUE)ctx; - VALUE action = INT2NUM(_action); - VALUE a = _a ? rb_str_new2(_a) : Qnil; - VALUE b = _b ? rb_str_new2(_b) : Qnil; - VALUE c = _c ? rb_str_new2(_c) : Qnil; - VALUE d = _d ? rb_str_new2(_d) : Qnil; - VALUE callback = rb_iv_get(self, "@authorizer"); - VALUE result = rb_funcall(callback, rb_intern("call"), 5, action, a, b, c, d); + VALUE self = (VALUE)ctx; + VALUE action = INT2NUM(_action); + VALUE a = _a ? rb_str_new2(_a) : Qnil; + VALUE b = _b ? rb_str_new2(_b) : Qnil; + VALUE c = _c ? rb_str_new2(_c) : Qnil; + VALUE d = _d ? rb_str_new2(_d) : Qnil; + VALUE callback = rb_iv_get(self, "@authorizer"); + VALUE result = rb_funcall(callback, rb_intern("call"), 5, action, a, b, c, d); - if(T_FIXNUM == TYPE(result)) return (int)NUM2INT(result); - if(Qtrue == result) return SQLITE_OK; - if(Qfalse == result) return SQLITE_DENY; + if (T_FIXNUM == TYPE(result)) { return (int)NUM2INT(result); } + if (Qtrue == result) { return SQLITE_OK; } + if (Qfalse == result) { return SQLITE_DENY; } - return SQLITE_IGNORE; + return SQLITE_IGNORE; } /* call-seq: set_authorizer = auth @@ -503,23 +531,24 @@ static int rb_sqlite3_auth( * is allowed to proceed. Returning 1 or false causes an authorization error to * occur, and returning 2 or nil causes the access to be silently denied. */ -static VALUE set_authorizer(VALUE self, VALUE authorizer) +static VALUE +set_authorizer(VALUE self, VALUE authorizer) { - sqlite3RubyPtr ctx; - int status; + sqlite3RubyPtr ctx; + int status; - TypedData_Get_Struct(self, sqlite3Ruby, &database_type, ctx); - REQUIRE_OPEN_DB(ctx); + TypedData_Get_Struct(self, sqlite3Ruby, &database_type, ctx); + REQUIRE_OPEN_DB(ctx); - status = sqlite3_set_authorizer( - ctx->db, NIL_P(authorizer) ? NULL : rb_sqlite3_auth, (void *)self - ); + status = sqlite3_set_authorizer( + ctx->db, NIL_P(authorizer) ? NULL : rb_sqlite3_auth, (void *)self + ); - CHECK(ctx->db, status); + CHECK(ctx->db, status); - rb_iv_set(self, "@authorizer", authorizer); + rb_iv_set(self, "@authorizer", authorizer); - return self; + return self; } /* call-seq: db.busy_timeout = ms @@ -532,15 +561,16 @@ static VALUE set_authorizer(VALUE self, VALUE authorizer) * * See also the mutually exclusive #busy_handler. */ -static VALUE set_busy_timeout(VALUE self, VALUE timeout) +static VALUE +set_busy_timeout(VALUE self, VALUE timeout) { - sqlite3RubyPtr ctx; - TypedData_Get_Struct(self, sqlite3Ruby, &database_type, ctx); - REQUIRE_OPEN_DB(ctx); + sqlite3RubyPtr ctx; + TypedData_Get_Struct(self, sqlite3Ruby, &database_type, ctx); + REQUIRE_OPEN_DB(ctx); - CHECK(ctx->db, sqlite3_busy_timeout(ctx->db, (int)NUM2INT(timeout))); + CHECK(ctx->db, sqlite3_busy_timeout(ctx->db, (int)NUM2INT(timeout))); - return self; + return self; } /* call-seq: db.extended_result_codes = true @@ -548,42 +578,44 @@ static VALUE set_busy_timeout(VALUE self, VALUE timeout) * Enable extended result codes in SQLite. These result codes allow for more * detailed exception reporting, such a which type of constraint is violated. */ -static VALUE set_extended_result_codes(VALUE self, VALUE enable) +static VALUE +set_extended_result_codes(VALUE self, VALUE enable) { - sqlite3RubyPtr ctx; - TypedData_Get_Struct(self, sqlite3Ruby, &database_type, ctx); - REQUIRE_OPEN_DB(ctx); + sqlite3RubyPtr ctx; + TypedData_Get_Struct(self, sqlite3Ruby, &database_type, ctx); + REQUIRE_OPEN_DB(ctx); - CHECK(ctx->db, sqlite3_extended_result_codes(ctx->db, RTEST(enable) ? 1 : 0)); + CHECK(ctx->db, sqlite3_extended_result_codes(ctx->db, RTEST(enable) ? 1 : 0)); - return self; + return self; } -int rb_comparator_func(void * ctx, int a_len, const void * a, int b_len, const void * b) +int +rb_comparator_func(void *ctx, int a_len, const void *a, int b_len, const void *b) { - VALUE comparator; - VALUE a_str; - VALUE b_str; - VALUE comparison; - rb_encoding * internal_encoding; + VALUE comparator; + VALUE a_str; + VALUE b_str; + VALUE comparison; + rb_encoding *internal_encoding; - internal_encoding = rb_default_internal_encoding(); + internal_encoding = rb_default_internal_encoding(); - comparator = (VALUE)ctx; - a_str = rb_str_new((const char *)a, a_len); - b_str = rb_str_new((const char *)b, b_len); + comparator = (VALUE)ctx; + a_str = rb_str_new((const char *)a, a_len); + b_str = rb_str_new((const char *)b, b_len); - rb_enc_associate_index(a_str, rb_utf8_encindex()); - rb_enc_associate_index(b_str, rb_utf8_encindex()); + rb_enc_associate_index(a_str, rb_utf8_encindex()); + rb_enc_associate_index(b_str, rb_utf8_encindex()); - if(internal_encoding) { - a_str = rb_str_export_to_enc(a_str, internal_encoding); - b_str = rb_str_export_to_enc(b_str, internal_encoding); - } + if (internal_encoding) { + a_str = rb_str_export_to_enc(a_str, internal_encoding); + b_str = rb_str_export_to_enc(b_str, internal_encoding); + } - comparison = rb_funcall(comparator, rb_intern("compare"), 2, a_str, b_str); + comparison = rb_funcall(comparator, rb_intern("compare"), 2, a_str, b_str); - return NUM2INT(comparison); + return NUM2INT(comparison); } /* call-seq: db.collation(name, comparator) @@ -593,23 +625,24 @@ int rb_comparator_func(void * ctx, int a_len, const void * a, int b_len, const v * two parameters and returns an integer less than, equal to, or greater than * 0. */ -static VALUE collation(VALUE self, VALUE name, VALUE comparator) +static VALUE +collation(VALUE self, VALUE name, VALUE comparator) { - sqlite3RubyPtr ctx; - TypedData_Get_Struct(self, sqlite3Ruby, &database_type, ctx); - REQUIRE_OPEN_DB(ctx); + sqlite3RubyPtr ctx; + TypedData_Get_Struct(self, sqlite3Ruby, &database_type, ctx); + REQUIRE_OPEN_DB(ctx); - CHECK(ctx->db, sqlite3_create_collation( - ctx->db, - StringValuePtr(name), - SQLITE_UTF8, - (void *)comparator, - NIL_P(comparator) ? NULL : rb_comparator_func)); + CHECK(ctx->db, sqlite3_create_collation( + ctx->db, + StringValuePtr(name), + SQLITE_UTF8, + (void *)comparator, + NIL_P(comparator) ? NULL : rb_comparator_func)); - /* Make sure our comparator doesn't get garbage collected. */ - rb_hash_aset(rb_iv_get(self, "@collations"), name, comparator); + /* Make sure our comparator doesn't get garbage collected. */ + rb_hash_aset(rb_iv_get(self, "@collations"), name, comparator); - return self; + return self; } #ifdef HAVE_SQLITE3_LOAD_EXTENSION @@ -619,24 +652,24 @@ static VALUE collation(VALUE self, VALUE name, VALUE comparator) * loading must be enabled using db.enable_load_extension(true) prior * to calling this API. */ -static VALUE load_extension(VALUE self, VALUE file) -{ - sqlite3RubyPtr ctx; - int status; - char *errMsg; - VALUE errexp; - TypedData_Get_Struct(self, sqlite3Ruby, &database_type, ctx); - REQUIRE_OPEN_DB(ctx); - - status = sqlite3_load_extension(ctx->db, StringValuePtr(file), 0, &errMsg); - if (status != SQLITE_OK) - { - errexp = rb_exc_new2(rb_eRuntimeError, errMsg); - sqlite3_free(errMsg); - rb_exc_raise(errexp); - } +static VALUE +load_extension(VALUE self, VALUE file) +{ + sqlite3RubyPtr ctx; + int status; + char *errMsg; + VALUE errexp; + TypedData_Get_Struct(self, sqlite3Ruby, &database_type, ctx); + REQUIRE_OPEN_DB(ctx); + + status = sqlite3_load_extension(ctx->db, StringValuePtr(file), 0, &errMsg); + if (status != SQLITE_OK) { + errexp = rb_exc_new2(rb_eRuntimeError, errMsg); + sqlite3_free(errMsg); + rb_exc_raise(errexp); + } - return self; + return self; } #endif @@ -645,24 +678,25 @@ static VALUE load_extension(VALUE self, VALUE file) * * Enable or disable extension loading. */ -static VALUE enable_load_extension(VALUE self, VALUE onoff) -{ - sqlite3RubyPtr ctx; - int onoffparam; - TypedData_Get_Struct(self, sqlite3Ruby, &database_type, ctx); - REQUIRE_OPEN_DB(ctx); - - if (Qtrue == onoff) { - onoffparam = 1; - } else if (Qfalse == onoff) { - onoffparam = 0; - } else { - onoffparam = (int)NUM2INT(onoff); - } +static VALUE +enable_load_extension(VALUE self, VALUE onoff) +{ + sqlite3RubyPtr ctx; + int onoffparam; + TypedData_Get_Struct(self, sqlite3Ruby, &database_type, ctx); + REQUIRE_OPEN_DB(ctx); + + if (Qtrue == onoff) { + onoffparam = 1; + } else if (Qfalse == onoff) { + onoffparam = 0; + } else { + onoffparam = (int)NUM2INT(onoff); + } - CHECK(ctx->db, sqlite3_enable_load_extension(ctx->db, onoffparam)); + CHECK(ctx->db, sqlite3_enable_load_extension(ctx->db, onoffparam)); - return self; + return self; } #endif @@ -671,49 +705,52 @@ static VALUE enable_load_extension(VALUE self, VALUE onoff) * Returns +true+ if there is a transaction active, and +false+ otherwise. * */ -static VALUE transaction_active_p(VALUE self) +static VALUE +transaction_active_p(VALUE self) { - sqlite3RubyPtr ctx; - TypedData_Get_Struct(self, sqlite3Ruby, &database_type, ctx); - REQUIRE_OPEN_DB(ctx); + sqlite3RubyPtr ctx; + TypedData_Get_Struct(self, sqlite3Ruby, &database_type, ctx); + REQUIRE_OPEN_DB(ctx); - return sqlite3_get_autocommit(ctx->db) ? Qfalse : Qtrue; + return sqlite3_get_autocommit(ctx->db) ? Qfalse : Qtrue; } -static int hash_callback_function(VALUE callback_ary, int count, char **data, char **columns) +static int +hash_callback_function(VALUE callback_ary, int count, char **data, char **columns) { - VALUE new_hash = rb_hash_new(); - int i; + VALUE new_hash = rb_hash_new(); + int i; - for (i = 0; i < count; i++) { - if (data[i] == NULL) { - rb_hash_aset(new_hash, rb_str_new_cstr(columns[i]), Qnil); - } else { - rb_hash_aset(new_hash, rb_str_new_cstr(columns[i]), rb_str_new_cstr(data[i])); + for (i = 0; i < count; i++) { + if (data[i] == NULL) { + rb_hash_aset(new_hash, rb_str_new_cstr(columns[i]), Qnil); + } else { + rb_hash_aset(new_hash, rb_str_new_cstr(columns[i]), rb_str_new_cstr(data[i])); + } } - } - rb_ary_push(callback_ary, new_hash); + rb_ary_push(callback_ary, new_hash); - return 0; + return 0; } -static int regular_callback_function(VALUE callback_ary, int count, char **data, char **columns) +static int +regular_callback_function(VALUE callback_ary, int count, char **data, char **columns) { - VALUE new_ary = rb_ary_new(); - int i; + VALUE new_ary = rb_ary_new(); + int i; - for (i = 0; i < count; i++) { - if (data[i] == NULL) { - rb_ary_push(new_ary, Qnil); - } else { - rb_ary_push(new_ary, rb_str_new_cstr(data[i])); + for (i = 0; i < count; i++) { + if (data[i] == NULL) { + rb_ary_push(new_ary, Qnil); + } else { + rb_ary_push(new_ary, rb_str_new_cstr(data[i])); + } } - } - rb_ary_push(callback_ary, new_ary); + rb_ary_push(callback_ary, new_ary); - return 0; + return 0; } @@ -725,31 +762,35 @@ static int regular_callback_function(VALUE callback_ary, int count, char **data, * so the user may parse values with a block. * If no query is made, an empty array will be returned. */ -static VALUE exec_batch(VALUE self, VALUE sql, VALUE results_as_hash) -{ - sqlite3RubyPtr ctx; - int status; - VALUE callback_ary = rb_ary_new(); - char *errMsg; - VALUE errexp; - - TypedData_Get_Struct(self, sqlite3Ruby, &database_type, ctx); - REQUIRE_OPEN_DB(ctx); - - if(results_as_hash == Qtrue) { - status = sqlite3_exec(ctx->db, StringValuePtr(sql), (sqlite3_callback)hash_callback_function, (void*)callback_ary, &errMsg); - } else { - status = sqlite3_exec(ctx->db, StringValuePtr(sql), (sqlite3_callback)regular_callback_function, (void*)callback_ary, &errMsg); - } +static VALUE +exec_batch(VALUE self, VALUE sql, VALUE results_as_hash) +{ + sqlite3RubyPtr ctx; + int status; + VALUE callback_ary = rb_ary_new(); + char *errMsg; + VALUE errexp; + + TypedData_Get_Struct(self, sqlite3Ruby, &database_type, ctx); + REQUIRE_OPEN_DB(ctx); + + if (results_as_hash == Qtrue) { + status = sqlite3_exec(ctx->db, StringValuePtr(sql), (sqlite3_callback)hash_callback_function, + (void *)callback_ary, + &errMsg); + } else { + status = sqlite3_exec(ctx->db, StringValuePtr(sql), (sqlite3_callback)regular_callback_function, + (void *)callback_ary, + &errMsg); + } - if (status != SQLITE_OK) - { - errexp = rb_exc_new2(rb_eRuntimeError, errMsg); - sqlite3_free(errMsg); - rb_exc_raise(errexp); - } + if (status != SQLITE_OK) { + errexp = rb_exc_new2(rb_eRuntimeError, errMsg); + sqlite3_free(errMsg); + rb_exc_raise(errexp); + } - return callback_ary; + return callback_ary; } /* call-seq: db.db_filename(database_name) @@ -757,86 +798,89 @@ static VALUE exec_batch(VALUE self, VALUE sql, VALUE results_as_hash) * Returns the file associated with +database_name+. Can return nil or an * empty string if the database is temporary, or in-memory. */ -static VALUE db_filename(VALUE self, VALUE db_name) +static VALUE +db_filename(VALUE self, VALUE db_name) { - sqlite3RubyPtr ctx; - const char * fname; - TypedData_Get_Struct(self, sqlite3Ruby, &database_type, ctx); - REQUIRE_OPEN_DB(ctx); + sqlite3RubyPtr ctx; + const char *fname; + TypedData_Get_Struct(self, sqlite3Ruby, &database_type, ctx); + REQUIRE_OPEN_DB(ctx); - fname = sqlite3_db_filename(ctx->db, StringValueCStr(db_name)); + fname = sqlite3_db_filename(ctx->db, StringValueCStr(db_name)); - if(fname) return SQLITE3_UTF8_STR_NEW2(fname); - return Qnil; + if (fname) { return SQLITE3_UTF8_STR_NEW2(fname); } + return Qnil; } -static VALUE rb_sqlite3_open16(VALUE self, VALUE file) +static VALUE +rb_sqlite3_open16(VALUE self, VALUE file) { - int status; - sqlite3RubyPtr ctx; + int status; + sqlite3RubyPtr ctx; - TypedData_Get_Struct(self, sqlite3Ruby, &database_type, ctx); + TypedData_Get_Struct(self, sqlite3Ruby, &database_type, ctx); #if defined TAINTING_SUPPORT #if defined StringValueCStr - StringValuePtr(file); - rb_check_safe_obj(file); + StringValuePtr(file); + rb_check_safe_obj(file); #else - Check_SafeStr(file); + Check_SafeStr(file); #endif #endif - status = sqlite3_open16(utf16_string_value_ptr(file), &ctx->db); + status = sqlite3_open16(utf16_string_value_ptr(file), &ctx->db); - CHECK(ctx->db, status) + CHECK(ctx->db, status) - return INT2NUM(status); + return INT2NUM(status); } -void init_sqlite3_database(void) +void +init_sqlite3_database(void) { #if 0 - VALUE mSqlite3 = rb_define_module("SQLite3"); + VALUE mSqlite3 = rb_define_module("SQLite3"); #endif - cSqlite3Database = rb_define_class_under(mSqlite3, "Database", rb_cObject); - - rb_define_alloc_func(cSqlite3Database, allocate); - rb_define_private_method(cSqlite3Database, "open_v2", rb_sqlite3_open_v2, 3); - rb_define_private_method(cSqlite3Database, "open16", rb_sqlite3_open16, 1); - rb_define_method(cSqlite3Database, "collation", collation, 2); - rb_define_method(cSqlite3Database, "close", sqlite3_rb_close, 0); - rb_define_method(cSqlite3Database, "closed?", closed_p, 0); - rb_define_method(cSqlite3Database, "total_changes", total_changes, 0); - rb_define_method(cSqlite3Database, "trace", trace, -1); - rb_define_method(cSqlite3Database, "last_insert_row_id", last_insert_row_id, 0); - rb_define_method(cSqlite3Database, "define_function", define_function, 1); - rb_define_method(cSqlite3Database, "define_function_with_flags", define_function_with_flags, 2); - /* public "define_aggregator" is now a shim around define_aggregator2 - * implemented in Ruby */ - rb_define_private_method(cSqlite3Database, "define_aggregator2", rb_sqlite3_define_aggregator2, 2); - rb_define_private_method(cSqlite3Database, "disable_quirk_mode", rb_sqlite3_disable_quirk_mode, 0); - rb_define_method(cSqlite3Database, "interrupt", interrupt, 0); - rb_define_method(cSqlite3Database, "errmsg", errmsg, 0); - rb_define_method(cSqlite3Database, "errcode", errcode_, 0); - rb_define_method(cSqlite3Database, "complete?", complete_p, 1); - rb_define_method(cSqlite3Database, "changes", changes, 0); - rb_define_method(cSqlite3Database, "authorizer=", set_authorizer, 1); - rb_define_method(cSqlite3Database, "busy_handler", busy_handler, -1); - rb_define_method(cSqlite3Database, "busy_timeout=", set_busy_timeout, 1); - rb_define_method(cSqlite3Database, "extended_result_codes=", set_extended_result_codes, 1); - rb_define_method(cSqlite3Database, "transaction_active?", transaction_active_p, 0); - rb_define_private_method(cSqlite3Database, "exec_batch", exec_batch, 2); - rb_define_private_method(cSqlite3Database, "db_filename", db_filename, 1); + cSqlite3Database = rb_define_class_under(mSqlite3, "Database", rb_cObject); + + rb_define_alloc_func(cSqlite3Database, allocate); + rb_define_private_method(cSqlite3Database, "open_v2", rb_sqlite3_open_v2, 3); + rb_define_private_method(cSqlite3Database, "open16", rb_sqlite3_open16, 1); + rb_define_method(cSqlite3Database, "collation", collation, 2); + rb_define_method(cSqlite3Database, "close", sqlite3_rb_close, 0); + rb_define_method(cSqlite3Database, "closed?", closed_p, 0); + rb_define_method(cSqlite3Database, "total_changes", total_changes, 0); + rb_define_method(cSqlite3Database, "trace", trace, -1); + rb_define_method(cSqlite3Database, "last_insert_row_id", last_insert_row_id, 0); + rb_define_method(cSqlite3Database, "define_function", define_function, 1); + rb_define_method(cSqlite3Database, "define_function_with_flags", define_function_with_flags, 2); + /* public "define_aggregator" is now a shim around define_aggregator2 + * implemented in Ruby */ + rb_define_private_method(cSqlite3Database, "define_aggregator2", rb_sqlite3_define_aggregator2, 2); + rb_define_private_method(cSqlite3Database, "disable_quirk_mode", rb_sqlite3_disable_quirk_mode, 0); + rb_define_method(cSqlite3Database, "interrupt", interrupt, 0); + rb_define_method(cSqlite3Database, "errmsg", errmsg, 0); + rb_define_method(cSqlite3Database, "errcode", errcode_, 0); + rb_define_method(cSqlite3Database, "complete?", complete_p, 1); + rb_define_method(cSqlite3Database, "changes", changes, 0); + rb_define_method(cSqlite3Database, "authorizer=", set_authorizer, 1); + rb_define_method(cSqlite3Database, "busy_handler", busy_handler, -1); + rb_define_method(cSqlite3Database, "busy_timeout=", set_busy_timeout, 1); + rb_define_method(cSqlite3Database, "extended_result_codes=", set_extended_result_codes, 1); + rb_define_method(cSqlite3Database, "transaction_active?", transaction_active_p, 0); + rb_define_private_method(cSqlite3Database, "exec_batch", exec_batch, 2); + rb_define_private_method(cSqlite3Database, "db_filename", db_filename, 1); #ifdef HAVE_SQLITE3_LOAD_EXTENSION - rb_define_method(cSqlite3Database, "load_extension", load_extension, 1); + rb_define_method(cSqlite3Database, "load_extension", load_extension, 1); #endif #ifdef HAVE_SQLITE3_ENABLE_LOAD_EXTENSION - rb_define_method(cSqlite3Database, "enable_load_extension", enable_load_extension, 1); + rb_define_method(cSqlite3Database, "enable_load_extension", enable_load_extension, 1); #endif - rb_sqlite3_aggregator_init(); + rb_sqlite3_aggregator_init(); } #ifdef _MSC_VER diff --git a/ext/sqlite3/database.h b/ext/sqlite3/database.h index 06efea14..ad3527a2 100644 --- a/ext/sqlite3/database.h +++ b/ext/sqlite3/database.h @@ -4,16 +4,16 @@ #include struct _sqlite3Ruby { - sqlite3 *db; + sqlite3 *db; }; typedef struct _sqlite3Ruby sqlite3Ruby; -typedef sqlite3Ruby * sqlite3RubyPtr; +typedef sqlite3Ruby *sqlite3RubyPtr; void init_sqlite3_database(); -void set_sqlite3_func_result(sqlite3_context * ctx, VALUE result); +void set_sqlite3_func_result(sqlite3_context *ctx, VALUE result); sqlite3RubyPtr sqlite3_database_unwrap(VALUE database); -VALUE sqlite3val2rb(sqlite3_value * val); +VALUE sqlite3val2rb(sqlite3_value *val); #endif diff --git a/ext/sqlite3/exception.c b/ext/sqlite3/exception.c index 1dcfe18d..ba37a37e 100644 --- a/ext/sqlite3/exception.c +++ b/ext/sqlite3/exception.c @@ -1,98 +1,99 @@ #include -void rb_sqlite3_raise(sqlite3 * db, int status) +void +rb_sqlite3_raise(sqlite3 *db, int status) { - VALUE klass = Qnil; + VALUE klass = Qnil; - /* Consider only lower 8 bits, to work correctly when - extended result codes are enabled. */ - switch(status & 0xff) { - case SQLITE_OK: - return; - break; - case SQLITE_ERROR: - klass = rb_path2class("SQLite3::SQLException"); - break; - case SQLITE_INTERNAL: - klass = rb_path2class("SQLite3::InternalException"); - break; - case SQLITE_PERM: - klass = rb_path2class("SQLite3::PermissionException"); - break; - case SQLITE_ABORT: - klass = rb_path2class("SQLite3::AbortException"); - break; - case SQLITE_BUSY: - klass = rb_path2class("SQLite3::BusyException"); - break; - case SQLITE_LOCKED: - klass = rb_path2class("SQLite3::LockedException"); - break; - case SQLITE_NOMEM: - klass = rb_path2class("SQLite3::MemoryException"); - break; - case SQLITE_READONLY: - klass = rb_path2class("SQLite3::ReadOnlyException"); - break; - case SQLITE_INTERRUPT: - klass = rb_path2class("SQLite3::InterruptException"); - break; - case SQLITE_IOERR: - klass = rb_path2class("SQLite3::IOException"); - break; - case SQLITE_CORRUPT: - klass = rb_path2class("SQLite3::CorruptException"); - break; - case SQLITE_NOTFOUND: - klass = rb_path2class("SQLite3::NotFoundException"); - break; - case SQLITE_FULL: - klass = rb_path2class("SQLite3::FullException"); - break; - case SQLITE_CANTOPEN: - klass = rb_path2class("SQLite3::CantOpenException"); - break; - case SQLITE_PROTOCOL: - klass = rb_path2class("SQLite3::ProtocolException"); - break; - case SQLITE_EMPTY: - klass = rb_path2class("SQLite3::EmptyException"); - break; - case SQLITE_SCHEMA: - klass = rb_path2class("SQLite3::SchemaChangedException"); - break; - case SQLITE_TOOBIG: - klass = rb_path2class("SQLite3::TooBigException"); - break; - case SQLITE_CONSTRAINT: - klass = rb_path2class("SQLite3::ConstraintException"); - break; - case SQLITE_MISMATCH: - klass = rb_path2class("SQLite3::MismatchException"); - break; - case SQLITE_MISUSE: - klass = rb_path2class("SQLite3::MisuseException"); - break; - case SQLITE_NOLFS: - klass = rb_path2class("SQLite3::UnsupportedException"); - break; - case SQLITE_AUTH: - klass = rb_path2class("SQLite3::AuthorizationException"); - break; - case SQLITE_FORMAT: - klass = rb_path2class("SQLite3::FormatException"); - break; - case SQLITE_RANGE: - klass = rb_path2class("SQLite3::RangeException"); - break; - case SQLITE_NOTADB: - klass = rb_path2class("SQLite3::NotADatabaseException"); - break; - default: - klass = rb_eRuntimeError; - } + /* Consider only lower 8 bits, to work correctly when + extended result codes are enabled. */ + switch (status & 0xff) { + case SQLITE_OK: + return; + break; + case SQLITE_ERROR: + klass = rb_path2class("SQLite3::SQLException"); + break; + case SQLITE_INTERNAL: + klass = rb_path2class("SQLite3::InternalException"); + break; + case SQLITE_PERM: + klass = rb_path2class("SQLite3::PermissionException"); + break; + case SQLITE_ABORT: + klass = rb_path2class("SQLite3::AbortException"); + break; + case SQLITE_BUSY: + klass = rb_path2class("SQLite3::BusyException"); + break; + case SQLITE_LOCKED: + klass = rb_path2class("SQLite3::LockedException"); + break; + case SQLITE_NOMEM: + klass = rb_path2class("SQLite3::MemoryException"); + break; + case SQLITE_READONLY: + klass = rb_path2class("SQLite3::ReadOnlyException"); + break; + case SQLITE_INTERRUPT: + klass = rb_path2class("SQLite3::InterruptException"); + break; + case SQLITE_IOERR: + klass = rb_path2class("SQLite3::IOException"); + break; + case SQLITE_CORRUPT: + klass = rb_path2class("SQLite3::CorruptException"); + break; + case SQLITE_NOTFOUND: + klass = rb_path2class("SQLite3::NotFoundException"); + break; + case SQLITE_FULL: + klass = rb_path2class("SQLite3::FullException"); + break; + case SQLITE_CANTOPEN: + klass = rb_path2class("SQLite3::CantOpenException"); + break; + case SQLITE_PROTOCOL: + klass = rb_path2class("SQLite3::ProtocolException"); + break; + case SQLITE_EMPTY: + klass = rb_path2class("SQLite3::EmptyException"); + break; + case SQLITE_SCHEMA: + klass = rb_path2class("SQLite3::SchemaChangedException"); + break; + case SQLITE_TOOBIG: + klass = rb_path2class("SQLite3::TooBigException"); + break; + case SQLITE_CONSTRAINT: + klass = rb_path2class("SQLite3::ConstraintException"); + break; + case SQLITE_MISMATCH: + klass = rb_path2class("SQLite3::MismatchException"); + break; + case SQLITE_MISUSE: + klass = rb_path2class("SQLite3::MisuseException"); + break; + case SQLITE_NOLFS: + klass = rb_path2class("SQLite3::UnsupportedException"); + break; + case SQLITE_AUTH: + klass = rb_path2class("SQLite3::AuthorizationException"); + break; + case SQLITE_FORMAT: + klass = rb_path2class("SQLite3::FormatException"); + break; + case SQLITE_RANGE: + klass = rb_path2class("SQLite3::RangeException"); + break; + case SQLITE_NOTADB: + klass = rb_path2class("SQLite3::NotADatabaseException"); + break; + default: + klass = rb_eRuntimeError; + } - klass = rb_exc_new2(klass, sqlite3_errmsg(db)); - rb_iv_set(klass, "@code", INT2FIX(status)); - rb_exc_raise(klass); + klass = rb_exc_new2(klass, sqlite3_errmsg(db)); + rb_iv_set(klass, "@code", INT2FIX(status)); + rb_exc_raise(klass); } diff --git a/ext/sqlite3/exception.h b/ext/sqlite3/exception.h index 55b687e3..8783dfa7 100644 --- a/ext/sqlite3/exception.h +++ b/ext/sqlite3/exception.h @@ -3,6 +3,6 @@ #define CHECK(_db, _status) rb_sqlite3_raise(_db, _status); -void rb_sqlite3_raise(sqlite3 * db, int status); +void rb_sqlite3_raise(sqlite3 *db, int status); #endif diff --git a/ext/sqlite3/sqlite3.c b/ext/sqlite3/sqlite3.c index 5410293c..ba22e1a3 100644 --- a/ext/sqlite3/sqlite3.c +++ b/ext/sqlite3/sqlite3.c @@ -3,162 +3,167 @@ VALUE mSqlite3; VALUE cSqlite3Blob; -int bignum_to_int64(VALUE value, sqlite3_int64 *result) +int +bignum_to_int64(VALUE value, sqlite3_int64 *result) { #ifdef HAVE_RB_INTEGER_PACK - const int nails = 0; - int t = rb_integer_pack(value, result, 1, sizeof(*result), nails, - INTEGER_PACK_NATIVE_BYTE_ORDER| - INTEGER_PACK_2COMP); - switch (t) { - case -2: case +2: - return 0; - case +1: - if (!nails) { - if (*result < 0) return 0; + const int nails = 0; + int t = rb_integer_pack(value, result, 1, sizeof(*result), nails, + INTEGER_PACK_NATIVE_BYTE_ORDER | + INTEGER_PACK_2COMP); + switch (t) { + case -2: + case +2: + return 0; + case +1: + if (!nails) { + if (*result < 0) { return 0; } + } + break; + case -1: + if (!nails) { + if (*result >= 0) { return 0; } + } else { + *result += INT64_MIN; + } + break; } - break; - case -1: - if (!nails) { - if (*result >= 0) return 0; - } - else { - *result += INT64_MIN; - } - break; - } - return 1; + return 1; #else # ifndef RBIGNUM_LEN # define RBIGNUM_LEN(x) RBIGNUM(x)->len # endif - const long len = RBIGNUM_LEN(value); - if (len == 0) { - *result = 0; - return 1; - } - if (len > 63 / (SIZEOF_BDIGITS * CHAR_BIT) + 1) return 0; - if (len == 63 / (SIZEOF_BDIGITS * CHAR_BIT) + 1) { - const BDIGIT *digits = RBIGNUM_DIGITS(value); - BDIGIT blast = digits[len-1]; - BDIGIT bmax = (BDIGIT)1UL << (63 % (CHAR_BIT * SIZEOF_BDIGITS)); - if (blast > bmax) return 0; - if (blast == bmax) { - if (RBIGNUM_POSITIVE_P(value)) { - return 0; - } - else { - long i = len-1; - while (i) { - if (digits[--i]) return 0; - } - } + const long len = RBIGNUM_LEN(value); + if (len == 0) { + *result = 0; + return 1; + } + if (len > 63 / (SIZEOF_BDIGITS * CHAR_BIT) + 1) { return 0; } + if (len == 63 / (SIZEOF_BDIGITS * CHAR_BIT) + 1) { + const BDIGIT *digits = RBIGNUM_DIGITS(value); + BDIGIT blast = digits[len - 1]; + BDIGIT bmax = (BDIGIT)1UL << (63 % (CHAR_BIT * SIZEOF_BDIGITS)); + if (blast > bmax) { return 0; } + if (blast == bmax) { + if (RBIGNUM_POSITIVE_P(value)) { + return 0; + } else { + long i = len - 1; + while (i) { + if (digits[--i]) { return 0; } + } + } + } } - } - *result = (sqlite3_int64)NUM2LL(value); - return 1; + *result = (sqlite3_int64)NUM2LL(value); + return 1; #endif } -static VALUE libversion(VALUE UNUSED(klass)) +static VALUE +libversion(VALUE UNUSED(klass)) { - return INT2NUM(sqlite3_libversion_number()); + return INT2NUM(sqlite3_libversion_number()); } -static VALUE using_sqlcipher(VALUE UNUSED(klass)) +static VALUE +using_sqlcipher(VALUE UNUSED(klass)) { #ifdef USING_SQLCIPHER - return Qtrue; + return Qtrue; #else - return Qfalse; + return Qfalse; #endif } /* Returns the compile time setting of the SQLITE_THREADSAFE flag. * See: https://www.sqlite.org/c3ref/threadsafe.html */ -static VALUE threadsafe_p(VALUE UNUSED(klass)) +static VALUE +threadsafe_p(VALUE UNUSED(klass)) { - return INT2NUM(sqlite3_threadsafe()); + return INT2NUM(sqlite3_threadsafe()); } -void init_sqlite3_constants(void) +void +init_sqlite3_constants(void) { - VALUE mSqlite3Constants; - VALUE mSqlite3Open; + VALUE mSqlite3Constants; + VALUE mSqlite3Open; - mSqlite3Constants = rb_define_module_under(mSqlite3, "Constants"); + mSqlite3Constants = rb_define_module_under(mSqlite3, "Constants"); - /* sqlite3_open_v2 flags for Database::new */ - mSqlite3Open = rb_define_module_under(mSqlite3Constants, "Open"); + /* sqlite3_open_v2 flags for Database::new */ + mSqlite3Open = rb_define_module_under(mSqlite3Constants, "Open"); - /* symbols = IO.readlines('sqlite3.h').map { |n| /\A#define\s+(SQLITE_OPEN_\w+)\s/ =~ n && $1 }.compact - * pad = symbols.map(&:length).max - 9 - * symbols.each { |s| printf %Q{ rb_define_const(mSqlite3Open, %-#{pad}s INT2FIX(#{s}));\n}, '"' + s[12..-1] + '",' } - */ - rb_define_const(mSqlite3Open, "READONLY", INT2FIX(SQLITE_OPEN_READONLY)); - rb_define_const(mSqlite3Open, "READWRITE", INT2FIX(SQLITE_OPEN_READWRITE)); - rb_define_const(mSqlite3Open, "CREATE", INT2FIX(SQLITE_OPEN_CREATE)); - rb_define_const(mSqlite3Open, "DELETEONCLOSE", INT2FIX(SQLITE_OPEN_DELETEONCLOSE)); - rb_define_const(mSqlite3Open, "EXCLUSIVE", INT2FIX(SQLITE_OPEN_EXCLUSIVE)); - rb_define_const(mSqlite3Open, "MAIN_DB", INT2FIX(SQLITE_OPEN_MAIN_DB)); - rb_define_const(mSqlite3Open, "TEMP_DB", INT2FIX(SQLITE_OPEN_TEMP_DB)); - rb_define_const(mSqlite3Open, "TRANSIENT_DB", INT2FIX(SQLITE_OPEN_TRANSIENT_DB)); - rb_define_const(mSqlite3Open, "MAIN_JOURNAL", INT2FIX(SQLITE_OPEN_MAIN_JOURNAL)); - rb_define_const(mSqlite3Open, "TEMP_JOURNAL", INT2FIX(SQLITE_OPEN_TEMP_JOURNAL)); - rb_define_const(mSqlite3Open, "SUBJOURNAL", INT2FIX(SQLITE_OPEN_SUBJOURNAL)); - rb_define_const(mSqlite3Open, "MASTER_JOURNAL", INT2FIX(SQLITE_OPEN_MASTER_JOURNAL)); - rb_define_const(mSqlite3Open, "NOMUTEX", INT2FIX(SQLITE_OPEN_NOMUTEX)); - rb_define_const(mSqlite3Open, "FULLMUTEX", INT2FIX(SQLITE_OPEN_FULLMUTEX)); + /* symbols = IO.readlines('sqlite3.h').map { |n| /\A#define\s+(SQLITE_OPEN_\w+)\s/ =~ n && $1 }.compact + * pad = symbols.map(&:length).max - 9 + * symbols.each { |s| printf %Q{ rb_define_const(mSqlite3Open, %-#{pad}s INT2FIX(#{s}));\n}, '"' + s[12..-1] + '",' } + */ + rb_define_const(mSqlite3Open, "READONLY", INT2FIX(SQLITE_OPEN_READONLY)); + rb_define_const(mSqlite3Open, "READWRITE", INT2FIX(SQLITE_OPEN_READWRITE)); + rb_define_const(mSqlite3Open, "CREATE", INT2FIX(SQLITE_OPEN_CREATE)); + rb_define_const(mSqlite3Open, "DELETEONCLOSE", INT2FIX(SQLITE_OPEN_DELETEONCLOSE)); + rb_define_const(mSqlite3Open, "EXCLUSIVE", INT2FIX(SQLITE_OPEN_EXCLUSIVE)); + rb_define_const(mSqlite3Open, "MAIN_DB", INT2FIX(SQLITE_OPEN_MAIN_DB)); + rb_define_const(mSqlite3Open, "TEMP_DB", INT2FIX(SQLITE_OPEN_TEMP_DB)); + rb_define_const(mSqlite3Open, "TRANSIENT_DB", INT2FIX(SQLITE_OPEN_TRANSIENT_DB)); + rb_define_const(mSqlite3Open, "MAIN_JOURNAL", INT2FIX(SQLITE_OPEN_MAIN_JOURNAL)); + rb_define_const(mSqlite3Open, "TEMP_JOURNAL", INT2FIX(SQLITE_OPEN_TEMP_JOURNAL)); + rb_define_const(mSqlite3Open, "SUBJOURNAL", INT2FIX(SQLITE_OPEN_SUBJOURNAL)); + rb_define_const(mSqlite3Open, "MASTER_JOURNAL", INT2FIX(SQLITE_OPEN_MASTER_JOURNAL)); + rb_define_const(mSqlite3Open, "NOMUTEX", INT2FIX(SQLITE_OPEN_NOMUTEX)); + rb_define_const(mSqlite3Open, "FULLMUTEX", INT2FIX(SQLITE_OPEN_FULLMUTEX)); #ifdef SQLITE_OPEN_AUTOPROXY - /* SQLITE_VERSION_NUMBER>=3007002 */ - rb_define_const(mSqlite3Open, "AUTOPROXY", INT2FIX(SQLITE_OPEN_AUTOPROXY)); - rb_define_const(mSqlite3Open, "SHAREDCACHE", INT2FIX(SQLITE_OPEN_SHAREDCACHE)); - rb_define_const(mSqlite3Open, "PRIVATECACHE", INT2FIX(SQLITE_OPEN_PRIVATECACHE)); - rb_define_const(mSqlite3Open, "WAL", INT2FIX(SQLITE_OPEN_WAL)); + /* SQLITE_VERSION_NUMBER>=3007002 */ + rb_define_const(mSqlite3Open, "AUTOPROXY", INT2FIX(SQLITE_OPEN_AUTOPROXY)); + rb_define_const(mSqlite3Open, "SHAREDCACHE", INT2FIX(SQLITE_OPEN_SHAREDCACHE)); + rb_define_const(mSqlite3Open, "PRIVATECACHE", INT2FIX(SQLITE_OPEN_PRIVATECACHE)); + rb_define_const(mSqlite3Open, "WAL", INT2FIX(SQLITE_OPEN_WAL)); #endif #ifdef SQLITE_OPEN_URI - /* SQLITE_VERSION_NUMBER>=3007007 */ - rb_define_const(mSqlite3Open, "URI", INT2FIX(SQLITE_OPEN_URI)); + /* SQLITE_VERSION_NUMBER>=3007007 */ + rb_define_const(mSqlite3Open, "URI", INT2FIX(SQLITE_OPEN_URI)); #endif #ifdef SQLITE_OPEN_MEMORY - /* SQLITE_VERSION_NUMBER>=3007013 */ - rb_define_const(mSqlite3Open, "MEMORY", INT2FIX(SQLITE_OPEN_MEMORY)); + /* SQLITE_VERSION_NUMBER>=3007013 */ + rb_define_const(mSqlite3Open, "MEMORY", INT2FIX(SQLITE_OPEN_MEMORY)); #endif } RUBY_FUNC_EXPORTED -void Init_sqlite3_native(void) +void +Init_sqlite3_native(void) { - /* - * SQLite3 is a wrapper around the popular database - * sqlite[http://sqlite.org]. - * - * For an example of usage, see SQLite3::Database. - */ - mSqlite3 = rb_define_module("SQLite3"); + /* + * SQLite3 is a wrapper around the popular database + * sqlite[http://sqlite.org]. + * + * For an example of usage, see SQLite3::Database. + */ + mSqlite3 = rb_define_module("SQLite3"); - /* A class for differentiating between strings and blobs, when binding them - * into statements. - */ - cSqlite3Blob = rb_define_class_under(mSqlite3, "Blob", rb_cString); + /* A class for differentiating between strings and blobs, when binding them + * into statements. + */ + cSqlite3Blob = rb_define_class_under(mSqlite3, "Blob", rb_cString); - /* Initialize the sqlite3 library */ + /* Initialize the sqlite3 library */ #ifdef HAVE_SQLITE3_INITIALIZE - sqlite3_initialize(); + sqlite3_initialize(); #endif - init_sqlite3_constants(); - init_sqlite3_database(); - init_sqlite3_statement(); + init_sqlite3_constants(); + init_sqlite3_database(); + init_sqlite3_statement(); #ifdef HAVE_SQLITE3_BACKUP_INIT - init_sqlite3_backup(); + init_sqlite3_backup(); #endif - rb_define_singleton_method(mSqlite3, "sqlcipher?", using_sqlcipher, 0); - rb_define_singleton_method(mSqlite3, "libversion", libversion, 0); - rb_define_singleton_method(mSqlite3, "threadsafe", threadsafe_p, 0); - rb_define_const(mSqlite3, "SQLITE_VERSION", rb_str_new2(SQLITE_VERSION)); - rb_define_const(mSqlite3, "SQLITE_VERSION_NUMBER", INT2FIX(SQLITE_VERSION_NUMBER)); - rb_define_const(mSqlite3, "SQLITE_LOADED_VERSION", rb_str_new2(sqlite3_libversion())); + rb_define_singleton_method(mSqlite3, "sqlcipher?", using_sqlcipher, 0); + rb_define_singleton_method(mSqlite3, "libversion", libversion, 0); + rb_define_singleton_method(mSqlite3, "threadsafe", threadsafe_p, 0); + rb_define_const(mSqlite3, "SQLITE_VERSION", rb_str_new2(SQLITE_VERSION)); + rb_define_const(mSqlite3, "SQLITE_VERSION_NUMBER", INT2FIX(SQLITE_VERSION_NUMBER)); + rb_define_const(mSqlite3, "SQLITE_LOADED_VERSION", rb_str_new2(sqlite3_libversion())); } diff --git a/ext/sqlite3/statement.c b/ext/sqlite3/statement.c index 3ac04ace..99607c17 100644 --- a/ext/sqlite3/statement.c +++ b/ext/sqlite3/statement.c @@ -6,29 +6,31 @@ VALUE cSqlite3Statement; -static size_t statement_memsize(const void *data) +static size_t +statement_memsize(const void *data) { - const sqlite3StmtRubyPtr s = (const sqlite3StmtRubyPtr)data; - // NB: can't account for s->st because the type is incomplete. - return sizeof(*s); + const sqlite3StmtRubyPtr s = (const sqlite3StmtRubyPtr)data; + // NB: can't account for s->st because the type is incomplete. + return sizeof(*s); } static const rb_data_type_t statement_type = { - "SQLite3::Backup", - { - NULL, - RUBY_TYPED_DEFAULT_FREE, - statement_memsize, - }, - 0, - 0, - RUBY_TYPED_FREE_IMMEDIATELY | RUBY_TYPED_WB_PROTECTED, + "SQLite3::Backup", + { + NULL, + RUBY_TYPED_DEFAULT_FREE, + statement_memsize, + }, + 0, + 0, + RUBY_TYPED_FREE_IMMEDIATELY | RUBY_TYPED_WB_PROTECTED, }; -static VALUE allocate(VALUE klass) +static VALUE +allocate(VALUE klass) { - sqlite3StmtRubyPtr ctx; - return TypedData_Make_Struct(klass, sqlite3StmtRuby, &statement_type, ctx); + sqlite3StmtRubyPtr ctx; + return TypedData_Make_Struct(klass, sqlite3StmtRuby, &statement_type, ctx); } static VALUE @@ -48,12 +50,12 @@ prepare(VALUE self, VALUE db, VALUE sql) #else status = sqlite3_prepare( #endif - db_ctx->db, - (const char *)StringValuePtr(sql), - (int)RSTRING_LEN(sql), - &ctx->st, - &tail - ); + db_ctx->db, + (const char *)StringValuePtr(sql), + (int)RSTRING_LEN(sql), + &ctx->st, + &tail + ); CHECK(db_ctx->db, status); @@ -65,118 +67,119 @@ prepare(VALUE self, VALUE db, VALUE sql) * Closes the statement by finalizing the underlying statement * handle. The statement must not be used after being closed. */ -static VALUE sqlite3_rb_close(VALUE self) +static VALUE +sqlite3_rb_close(VALUE self) { - sqlite3StmtRubyPtr ctx; + sqlite3StmtRubyPtr ctx; - TypedData_Get_Struct(self, sqlite3StmtRuby, &statement_type, ctx); + TypedData_Get_Struct(self, sqlite3StmtRuby, &statement_type, ctx); - REQUIRE_OPEN_STMT(ctx); + REQUIRE_OPEN_STMT(ctx); - sqlite3_finalize(ctx->st); - ctx->st = NULL; + sqlite3_finalize(ctx->st); + ctx->st = NULL; - return self; + return self; } /* call-seq: stmt.closed? * * Returns true if the statement has been closed. */ -static VALUE closed_p(VALUE self) +static VALUE +closed_p(VALUE self) { - sqlite3StmtRubyPtr ctx; - TypedData_Get_Struct(self, sqlite3StmtRuby, &statement_type, ctx); + sqlite3StmtRubyPtr ctx; + TypedData_Get_Struct(self, sqlite3StmtRuby, &statement_type, ctx); - if(!ctx->st) return Qtrue; + if (!ctx->st) { return Qtrue; } - return Qfalse; + return Qfalse; } -static VALUE step(VALUE self) +static VALUE +step(VALUE self) { - sqlite3StmtRubyPtr ctx; - sqlite3_stmt *stmt; - int value, length; - VALUE list; - rb_encoding * internal_encoding; - - TypedData_Get_Struct(self, sqlite3StmtRuby, &statement_type, ctx); - - REQUIRE_OPEN_STMT(ctx); - - if(ctx->done_p) return Qnil; - - internal_encoding = rb_default_internal_encoding(); - - stmt = ctx->st; - - value = sqlite3_step(stmt); - if (rb_errinfo() != Qnil) { - /* some user defined function was invoked as a callback during step and - * it raised an exception that has been suppressed until step returns. - * Now re-raise it. */ - VALUE exception = rb_errinfo(); - rb_set_errinfo(Qnil); - rb_exc_raise(exception); - } - - length = sqlite3_column_count(stmt); - list = rb_ary_new2((long)length); - - switch(value) { - case SQLITE_ROW: - { - int i; - for(i = 0; i < length; i++) { - switch(sqlite3_column_type(stmt, i)) { - case SQLITE_INTEGER: - rb_ary_push(list, LL2NUM(sqlite3_column_int64(stmt, i))); - break; - case SQLITE_FLOAT: - rb_ary_push(list, rb_float_new(sqlite3_column_double(stmt, i))); - break; - case SQLITE_TEXT: - { - VALUE str = rb_str_new( - (const char *)sqlite3_column_text(stmt, i), - (long)sqlite3_column_bytes(stmt, i) - ); - rb_enc_associate_index(str, rb_utf8_encindex()); - if(internal_encoding) - str = rb_str_export_to_enc(str, internal_encoding); - rb_ary_push(list, str); - } - break; - case SQLITE_BLOB: - { - VALUE str = rb_str_new( - (const char *)sqlite3_column_blob(stmt, i), - (long)sqlite3_column_bytes(stmt, i) - ); - rb_ary_push(list, str); - } - break; - case SQLITE_NULL: - rb_ary_push(list, Qnil); - break; - default: - rb_raise(rb_eRuntimeError, "bad type"); - } + sqlite3StmtRubyPtr ctx; + sqlite3_stmt *stmt; + int value, length; + VALUE list; + rb_encoding *internal_encoding; + + TypedData_Get_Struct(self, sqlite3StmtRuby, &statement_type, ctx); + + REQUIRE_OPEN_STMT(ctx); + + if (ctx->done_p) { return Qnil; } + + internal_encoding = rb_default_internal_encoding(); + + stmt = ctx->st; + + value = sqlite3_step(stmt); + if (rb_errinfo() != Qnil) { + /* some user defined function was invoked as a callback during step and + * it raised an exception that has been suppressed until step returns. + * Now re-raise it. */ + VALUE exception = rb_errinfo(); + rb_set_errinfo(Qnil); + rb_exc_raise(exception); + } + + length = sqlite3_column_count(stmt); + list = rb_ary_new2((long)length); + + switch (value) { + case SQLITE_ROW: { + int i; + for (i = 0; i < length; i++) { + switch (sqlite3_column_type(stmt, i)) { + case SQLITE_INTEGER: + rb_ary_push(list, LL2NUM(sqlite3_column_int64(stmt, i))); + break; + case SQLITE_FLOAT: + rb_ary_push(list, rb_float_new(sqlite3_column_double(stmt, i))); + break; + case SQLITE_TEXT: { + VALUE str = rb_str_new( + (const char *)sqlite3_column_text(stmt, i), + (long)sqlite3_column_bytes(stmt, i) + ); + rb_enc_associate_index(str, rb_utf8_encindex()); + if (internal_encoding) { + str = rb_str_export_to_enc(str, internal_encoding); + } + rb_ary_push(list, str); + } + break; + case SQLITE_BLOB: { + VALUE str = rb_str_new( + (const char *)sqlite3_column_blob(stmt, i), + (long)sqlite3_column_bytes(stmt, i) + ); + rb_ary_push(list, str); + } + break; + case SQLITE_NULL: + rb_ary_push(list, Qnil); + break; + default: + rb_raise(rb_eRuntimeError, "bad type"); + } + } } - } - break; - case SQLITE_DONE: - ctx->done_p = 1; - return Qnil; - break; - default: - sqlite3_reset(stmt); - ctx->done_p = 0; - CHECK(sqlite3_db_handle(ctx->st), value); - } - - return list; + break; + case SQLITE_DONE: + ctx->done_p = 1; + return Qnil; + break; + default: + sqlite3_reset(stmt); + ctx->done_p = 0; + CHECK(sqlite3_db_handle(ctx->st), value); + } + + return list; } /* call-seq: stmt.bind_param(key, value) @@ -187,91 +190,93 @@ static VALUE step(VALUE self) * * See also #bind_params. */ -static VALUE bind_param(VALUE self, VALUE key, VALUE value) +static VALUE +bind_param(VALUE self, VALUE key, VALUE value) { - sqlite3StmtRubyPtr ctx; - int status; - int index; - - TypedData_Get_Struct(self, sqlite3StmtRuby, &statement_type, ctx); - REQUIRE_OPEN_STMT(ctx); - - switch(TYPE(key)) { - case T_SYMBOL: - key = rb_funcall(key, rb_intern("to_s"), 0); - case T_STRING: - if(RSTRING_PTR(key)[0] != ':') key = rb_str_plus(rb_str_new2(":"), key); - index = sqlite3_bind_parameter_index(ctx->st, StringValuePtr(key)); - break; - default: - index = (int)NUM2INT(key); - } - - if(index == 0) - rb_raise(rb_path2class("SQLite3::Exception"), "no such bind parameter"); - - switch(TYPE(value)) { - case T_STRING: - if(CLASS_OF(value) == cSqlite3Blob - || rb_enc_get_index(value) == rb_ascii8bit_encindex() - ) { - status = sqlite3_bind_blob( - ctx->st, - index, - (const char *)StringValuePtr(value), - (int)RSTRING_LEN(value), - SQLITE_TRANSIENT - ); - } else { - - - if (UTF16_LE_P(value) || UTF16_BE_P(value)) { - status = sqlite3_bind_text16( - ctx->st, - index, - (const char *)StringValuePtr(value), - (int)RSTRING_LEN(value), - SQLITE_TRANSIENT - ); - } else { - if (!UTF8_P(value) || !USASCII_P(value)) { - value = rb_str_encode(value, rb_enc_from_encoding(rb_utf8_encoding()), 0, Qnil); - } - status = sqlite3_bind_text( - ctx->st, - index, - (const char *)StringValuePtr(value), - (int)RSTRING_LEN(value), - SQLITE_TRANSIENT - ); + sqlite3StmtRubyPtr ctx; + int status; + int index; + + TypedData_Get_Struct(self, sqlite3StmtRuby, &statement_type, ctx); + REQUIRE_OPEN_STMT(ctx); + + switch (TYPE(key)) { + case T_SYMBOL: + key = rb_funcall(key, rb_intern("to_s"), 0); + case T_STRING: + if (RSTRING_PTR(key)[0] != ':') { key = rb_str_plus(rb_str_new2(":"), key); } + index = sqlite3_bind_parameter_index(ctx->st, StringValuePtr(key)); + break; + default: + index = (int)NUM2INT(key); + } + + if (index == 0) { + rb_raise(rb_path2class("SQLite3::Exception"), "no such bind parameter"); + } + + switch (TYPE(value)) { + case T_STRING: + if (CLASS_OF(value) == cSqlite3Blob + || rb_enc_get_index(value) == rb_ascii8bit_encindex() + ) { + status = sqlite3_bind_blob( + ctx->st, + index, + (const char *)StringValuePtr(value), + (int)RSTRING_LEN(value), + SQLITE_TRANSIENT + ); + } else { + + + if (UTF16_LE_P(value) || UTF16_BE_P(value)) { + status = sqlite3_bind_text16( + ctx->st, + index, + (const char *)StringValuePtr(value), + (int)RSTRING_LEN(value), + SQLITE_TRANSIENT + ); + } else { + if (!UTF8_P(value) || !USASCII_P(value)) { + value = rb_str_encode(value, rb_enc_from_encoding(rb_utf8_encoding()), 0, Qnil); + } + status = sqlite3_bind_text( + ctx->st, + index, + (const char *)StringValuePtr(value), + (int)RSTRING_LEN(value), + SQLITE_TRANSIENT + ); + } + } + break; + case T_BIGNUM: { + sqlite3_int64 num64; + if (bignum_to_int64(value, &num64)) { + status = sqlite3_bind_int64(ctx->st, index, num64); + break; + } } - } - break; - case T_BIGNUM: { - sqlite3_int64 num64; - if (bignum_to_int64(value, &num64)) { - status = sqlite3_bind_int64(ctx->st, index, num64); - break; - } + case T_FLOAT: + status = sqlite3_bind_double(ctx->st, index, NUM2DBL(value)); + break; + case T_FIXNUM: + status = sqlite3_bind_int64(ctx->st, index, (sqlite3_int64)FIX2LONG(value)); + break; + case T_NIL: + status = sqlite3_bind_null(ctx->st, index); + break; + default: + rb_raise(rb_eRuntimeError, "can't prepare %s", + rb_class2name(CLASS_OF(value))); + break; } - case T_FLOAT: - status = sqlite3_bind_double(ctx->st, index, NUM2DBL(value)); - break; - case T_FIXNUM: - status = sqlite3_bind_int64(ctx->st, index, (sqlite3_int64)FIX2LONG(value)); - break; - case T_NIL: - status = sqlite3_bind_null(ctx->st, index); - break; - default: - rb_raise(rb_eRuntimeError, "can't prepare %s", - rb_class2name(CLASS_OF(value))); - break; - } - - CHECK(sqlite3_db_handle(ctx->st), status); - - return self; + + CHECK(sqlite3_db_handle(ctx->st), status); + + return self; } /* call-seq: stmt.reset! @@ -279,18 +284,19 @@ static VALUE bind_param(VALUE self, VALUE key, VALUE value) * Resets the statement. This is typically done internally, though it might * occasionally be necessary to manually reset the statement. */ -static VALUE reset_bang(VALUE self) +static VALUE +reset_bang(VALUE self) { - sqlite3StmtRubyPtr ctx; + sqlite3StmtRubyPtr ctx; - TypedData_Get_Struct(self, sqlite3StmtRuby, &statement_type, ctx); - REQUIRE_OPEN_STMT(ctx); + TypedData_Get_Struct(self, sqlite3StmtRuby, &statement_type, ctx); + REQUIRE_OPEN_STMT(ctx); - sqlite3_reset(ctx->st); + sqlite3_reset(ctx->st); - ctx->done_p = 0; + ctx->done_p = 0; - return self; + return self; } /* call-seq: stmt.clear_bindings! @@ -298,93 +304,99 @@ static VALUE reset_bang(VALUE self) * Resets the statement. This is typically done internally, though it might * occasionally be necessary to manually reset the statement. */ -static VALUE clear_bindings_bang(VALUE self) +static VALUE +clear_bindings_bang(VALUE self) { - sqlite3StmtRubyPtr ctx; + sqlite3StmtRubyPtr ctx; - TypedData_Get_Struct(self, sqlite3StmtRuby, &statement_type, ctx); - REQUIRE_OPEN_STMT(ctx); + TypedData_Get_Struct(self, sqlite3StmtRuby, &statement_type, ctx); + REQUIRE_OPEN_STMT(ctx); - sqlite3_clear_bindings(ctx->st); + sqlite3_clear_bindings(ctx->st); - ctx->done_p = 0; + ctx->done_p = 0; - return self; + return self; } /* call-seq: stmt.done? * * returns true if all rows have been returned. */ -static VALUE done_p(VALUE self) +static VALUE +done_p(VALUE self) { - sqlite3StmtRubyPtr ctx; - TypedData_Get_Struct(self, sqlite3StmtRuby, &statement_type, ctx); + sqlite3StmtRubyPtr ctx; + TypedData_Get_Struct(self, sqlite3StmtRuby, &statement_type, ctx); - if(ctx->done_p) return Qtrue; - return Qfalse; + if (ctx->done_p) { return Qtrue; } + return Qfalse; } /* call-seq: stmt.column_count * * Returns the number of columns to be returned for this statement */ -static VALUE column_count(VALUE self) +static VALUE +column_count(VALUE self) { - sqlite3StmtRubyPtr ctx; - TypedData_Get_Struct(self, sqlite3StmtRuby, &statement_type, ctx); - REQUIRE_OPEN_STMT(ctx); + sqlite3StmtRubyPtr ctx; + TypedData_Get_Struct(self, sqlite3StmtRuby, &statement_type, ctx); + REQUIRE_OPEN_STMT(ctx); - return INT2NUM(sqlite3_column_count(ctx->st)); + return INT2NUM(sqlite3_column_count(ctx->st)); } /* call-seq: stmt.column_name(index) * * Get the column name at +index+. 0 based. */ -static VALUE column_name(VALUE self, VALUE index) +static VALUE +column_name(VALUE self, VALUE index) { - sqlite3StmtRubyPtr ctx; - const char * name; + sqlite3StmtRubyPtr ctx; + const char *name; - TypedData_Get_Struct(self, sqlite3StmtRuby, &statement_type, ctx); - REQUIRE_OPEN_STMT(ctx); + TypedData_Get_Struct(self, sqlite3StmtRuby, &statement_type, ctx); + REQUIRE_OPEN_STMT(ctx); - name = sqlite3_column_name(ctx->st, (int)NUM2INT(index)); + name = sqlite3_column_name(ctx->st, (int)NUM2INT(index)); - if(name) return SQLITE3_UTF8_STR_NEW2(name); - return Qnil; + if (name) { return SQLITE3_UTF8_STR_NEW2(name); } + return Qnil; } /* call-seq: stmt.column_decltype(index) * * Get the column type at +index+. 0 based. */ -static VALUE column_decltype(VALUE self, VALUE index) +static VALUE +column_decltype(VALUE self, VALUE index) { - sqlite3StmtRubyPtr ctx; - const char * name; + sqlite3StmtRubyPtr ctx; + const char *name; - TypedData_Get_Struct(self, sqlite3StmtRuby, &statement_type, ctx); - REQUIRE_OPEN_STMT(ctx); + TypedData_Get_Struct(self, sqlite3StmtRuby, &statement_type, ctx); + REQUIRE_OPEN_STMT(ctx); - name = sqlite3_column_decltype(ctx->st, (int)NUM2INT(index)); + name = sqlite3_column_decltype(ctx->st, (int)NUM2INT(index)); - if(name) return rb_str_new2(name); - return Qnil; + if (name) { return rb_str_new2(name); } + return Qnil; } /* call-seq: stmt.bind_parameter_count * * Return the number of bind parameters */ -static VALUE bind_parameter_count(VALUE self) +static VALUE +bind_parameter_count(VALUE self) { - sqlite3StmtRubyPtr ctx; - TypedData_Get_Struct(self, sqlite3StmtRuby, &statement_type, ctx); - REQUIRE_OPEN_STMT(ctx); + sqlite3StmtRubyPtr ctx; + TypedData_Get_Struct(self, sqlite3StmtRuby, &statement_type, ctx); + REQUIRE_OPEN_STMT(ctx); - return INT2NUM(sqlite3_bind_parameter_count(ctx->st)); + return INT2NUM(sqlite3_bind_parameter_count(ctx->st)); } #ifdef HAVE_SQLITE3_COLUMN_DATABASE_NAME @@ -393,37 +405,39 @@ static VALUE bind_parameter_count(VALUE self) * * Return the database name for the column at +column_index+ */ -static VALUE database_name(VALUE self, VALUE index) +static VALUE +database_name(VALUE self, VALUE index) { - sqlite3StmtRubyPtr ctx; - TypedData_Get_Struct(self, sqlite3StmtRuby, &statement_type, ctx); - REQUIRE_OPEN_STMT(ctx); + sqlite3StmtRubyPtr ctx; + TypedData_Get_Struct(self, sqlite3StmtRuby, &statement_type, ctx); + REQUIRE_OPEN_STMT(ctx); - return SQLITE3_UTF8_STR_NEW2( - sqlite3_column_database_name(ctx->st, NUM2INT(index))); + return SQLITE3_UTF8_STR_NEW2( + sqlite3_column_database_name(ctx->st, NUM2INT(index))); } #endif -void init_sqlite3_statement(void) +void +init_sqlite3_statement(void) { - cSqlite3Statement = rb_define_class_under(mSqlite3, "Statement", rb_cObject); - - rb_define_alloc_func(cSqlite3Statement, allocate); - rb_define_method(cSqlite3Statement, "close", sqlite3_rb_close, 0); - rb_define_method(cSqlite3Statement, "closed?", closed_p, 0); - rb_define_method(cSqlite3Statement, "bind_param", bind_param, 2); - rb_define_method(cSqlite3Statement, "reset!", reset_bang, 0); - rb_define_method(cSqlite3Statement, "clear_bindings!", clear_bindings_bang, 0); - rb_define_method(cSqlite3Statement, "step", step, 0); - rb_define_method(cSqlite3Statement, "done?", done_p, 0); - rb_define_method(cSqlite3Statement, "column_count", column_count, 0); - rb_define_method(cSqlite3Statement, "column_name", column_name, 1); - rb_define_method(cSqlite3Statement, "column_decltype", column_decltype, 1); - rb_define_method(cSqlite3Statement, "bind_parameter_count", bind_parameter_count, 0); - rb_define_private_method(cSqlite3Statement, "prepare", prepare, 2); + cSqlite3Statement = rb_define_class_under(mSqlite3, "Statement", rb_cObject); + + rb_define_alloc_func(cSqlite3Statement, allocate); + rb_define_method(cSqlite3Statement, "close", sqlite3_rb_close, 0); + rb_define_method(cSqlite3Statement, "closed?", closed_p, 0); + rb_define_method(cSqlite3Statement, "bind_param", bind_param, 2); + rb_define_method(cSqlite3Statement, "reset!", reset_bang, 0); + rb_define_method(cSqlite3Statement, "clear_bindings!", clear_bindings_bang, 0); + rb_define_method(cSqlite3Statement, "step", step, 0); + rb_define_method(cSqlite3Statement, "done?", done_p, 0); + rb_define_method(cSqlite3Statement, "column_count", column_count, 0); + rb_define_method(cSqlite3Statement, "column_name", column_name, 1); + rb_define_method(cSqlite3Statement, "column_decltype", column_decltype, 1); + rb_define_method(cSqlite3Statement, "bind_parameter_count", bind_parameter_count, 0); + rb_define_private_method(cSqlite3Statement, "prepare", prepare, 2); #ifdef HAVE_SQLITE3_COLUMN_DATABASE_NAME - rb_define_method(cSqlite3Statement, "database_name", database_name, 1); + rb_define_method(cSqlite3Statement, "database_name", database_name, 1); #endif } diff --git a/ext/sqlite3/statement.h b/ext/sqlite3/statement.h index e7ef1f3a..d5dd343f 100644 --- a/ext/sqlite3/statement.h +++ b/ext/sqlite3/statement.h @@ -4,12 +4,12 @@ #include struct _sqlite3StmtRuby { - sqlite3_stmt *st; - int done_p; + sqlite3_stmt *st; + int done_p; }; typedef struct _sqlite3StmtRuby sqlite3StmtRuby; -typedef sqlite3StmtRuby * sqlite3StmtRubyPtr; +typedef sqlite3StmtRuby *sqlite3StmtRubyPtr; void init_sqlite3_statement(); diff --git a/rakelib/format.rake b/rakelib/format.rake new file mode 100644 index 00000000..7647b856 --- /dev/null +++ b/rakelib/format.rake @@ -0,0 +1,64 @@ +require "rake/clean" + +module AstyleHelper + class << self + def run(files) + assert + command = ["astyle", args, files].flatten.shelljoin + system(command) + end + + def assert + require "mkmf" + find_executable0("astyle") || raise("Could not find command 'astyle'") + end + + def args + [ + # indentation + "--indent=spaces=4", + "--indent-switches", + + # brackets + "--style=1tbs", + "--keep-one-line-blocks", + + # where do we want spaces + "--unpad-paren", + "--pad-header", + "--pad-oper", + "--pad-comma", + + # "void *pointer" and not "void* pointer" + "--align-pointer=name", + + # function definitions and declarations + "--break-return-type", + "--attach-return-type-decl", + + # gotta set a limit somewhere + "--max-code-length=100", + + # be quiet about files that haven't changed + "--formatted", + "--verbose", + ] + end + + def c_files + SQLITE3_SPEC.files.grep(%r{ext/sqlite3/.*\.[ch]\Z}) + end + end +end + +namespace "format" do + desc "Format C code" + task "c" do + puts "Running astyle on C files ..." + AstyleHelper.run(AstyleHelper.c_files) + end + + CLEAN.add(AstyleHelper.c_files.map { |f| "#{f}.orig" }) +end + +task "format" => ["format:c"]