From 9a9522d700ef0fd6964bae664c9b3fdebd76b6d1 Mon Sep 17 00:00:00 2001 From: Mike Dalessio Date: Mon, 8 Jan 2024 22:06:09 -0500 Subject: [PATCH 1/8] style(standard): introduce rubocop/standard, do safe autocorrections --- .rubocop.yml | 15 ++ Gemfile | 17 +- bin/test-gem-file-contents | 172 +++++++++--------- ext/sqlite3/extconf.rb | 32 ++-- lib/sqlite3.rb | 10 +- lib/sqlite3/constants.rb | 92 +++++----- lib/sqlite3/database.rb | 181 ++++++++++--------- lib/sqlite3/errors.rb | 27 ++- lib/sqlite3/pragmas.rb | 261 ++++++++++++++-------------- lib/sqlite3/resultset.rb | 43 +++-- lib/sqlite3/statement.rb | 17 +- lib/sqlite3/translator.rb | 60 +++---- lib/sqlite3/value.rb | 37 ++-- rakelib/format.rake | 10 +- rakelib/native.rake | 8 +- sqlite3.gemspec | 6 +- test/helper.rb | 12 +- test/test_backup.rb | 52 +++--- test/test_collation.rb | 44 +++-- test/test_database.rb | 224 +++++++++++++----------- test/test_database_flags.rb | 40 ++--- test/test_database_readonly.rb | 16 +- test/test_database_readwrite.rb | 18 +- test/test_deprecated.rb | 12 +- test/test_encoding.rb | 71 ++++---- test/test_integration.rb | 159 ++++++++--------- test/test_integration_aggregate.rb | 170 ++++++++++-------- test/test_integration_open_close.rb | 32 ++-- test/test_integration_pending.rb | 38 ++-- test/test_integration_resultset.rb | 64 +++---- test/test_integration_statement.rb | 62 +++---- test/test_pragmas.rb | 2 +- test/test_resource_cleanup.rb | 8 +- test/test_result_set.rb | 16 +- test/test_sqlite3.rb | 2 +- test/test_statement.rb | 94 +++++----- test/test_statement_execute.rb | 13 +- 37 files changed, 1114 insertions(+), 1023 deletions(-) create mode 100644 .rubocop.yml diff --git a/.rubocop.yml b/.rubocop.yml new file mode 100644 index 00000000..8313530a --- /dev/null +++ b/.rubocop.yml @@ -0,0 +1,15 @@ +# from https://evilmartians.com/chronicles/rubocoping-with-legacy-bring-your-ruby-code-up-to-standard +require: + - standard + - standard-custom + - standard-performance + - rubocop-performance + +inherit_gem: + standard: config/base.yml + standard-custom: config/base.yml + standard-performance: config/base.yml + +AllCops: + SuggestExtensions: false + TargetRubyVersion: 3.0 diff --git a/Gemfile b/Gemfile index 14e42931..a0e9d3fa 100644 --- a/Gemfile +++ b/Gemfile @@ -2,9 +2,16 @@ source "https://rubygems.org" gemspec -gem("minitest", "5.20.0") -gem("rake-compiler", "1.2.5") -gem("rake-compiler-dock", "1.4.0") -gem("rdoc", "6.6.2") +group :development do + gem "minitest", "5.20.0" -gem("ruby_memcheck", "2.3.0") if Gem::Platform.local.os == "linux" + gem "rake-compiler", "1.2.5" + gem "rake-compiler-dock", "1.4.0" + + gem "ruby_memcheck", "2.3.0" if Gem::Platform.local.os == "linux" + + gem "rdoc", "6.6.2" + + gem "rubocop", require: false + gem "standardrb", require: false +end diff --git a/bin/test-gem-file-contents b/bin/test-gem-file-contents index 6a19d805..cbe98c24 100755 --- a/bin/test-gem-file-contents +++ b/bin/test-gem-file-contents @@ -36,7 +36,7 @@ gemfile_contents = Dir.mktmpdir do |dir| raise "could not unpack gem #{gemfile}" end - %x(tar -ztf data.tar.gz).split("\n") + `tar -ztf data.tar.gz`.split("\n") end end @@ -46,7 +46,7 @@ gemspec = Dir.mktmpdir do |dir| raise "could not unpack gem #{gemfile}" end - YAML.unsafe_load(%x(gunzip -c metadata.gz)) + YAML.unsafe_load(`gunzip -c metadata.gz`) end end @@ -96,7 +96,7 @@ describe File.basename(gemfile) do describe "all platforms" do ["lib", "test"].each do |dir| it "contains every ruby file in #{dir}/" do - expected = %x(git ls-files #{dir}).split("\n").grep(/\.rb$/).sort + expected = `git ls-files #{dir}`.split("\n").grep(/\.rb$/).sort skip "looks like this isn't a git repository" if expected.empty? actual = gemfile_contents.select { |f| f.start_with?("#{dir}/") }.grep(/\.rb$/).sort assert_equal(expected, actual) @@ -104,109 +104,113 @@ describe File.basename(gemfile) do end end - describe "ruby platform" do - it "depends on mini_portile2" do - assert(gemspec.dependencies.find { |d| d.name == "mini_portile2" }) - end + if gemspec.platform == Gem::Platform::RUBY + describe "ruby platform" do + it "depends on mini_portile2" do + assert(gemspec.dependencies.find { |d| d.name == "mini_portile2" }) + end - it "contains extension C and header files" do - assert_equal(6, gemfile_contents.count { |f| File.fnmatch?("ext/**/*.c", f) }) - assert_equal(6, gemfile_contents.count { |f| File.fnmatch?("ext/**/*.h", f) }) - end + it "contains extension C and header files" do + assert_equal(6, gemfile_contents.count { |f| File.fnmatch?("ext/**/*.c", f) }) + assert_equal(6, gemfile_contents.count { |f| File.fnmatch?("ext/**/*.h", f) }) + end - it "includes C files in extra_rdoc_files" do - assert_equal(6, gemspec.extra_rdoc_files.count { |f| File.fnmatch?("ext/**/*.c", f) }) - end + it "includes C files in extra_rdoc_files" do + assert_equal(6, gemspec.extra_rdoc_files.count { |f| File.fnmatch?("ext/**/*.c", f) }) + end - it "contains the port files" do - dependencies = YAML.load_file(File.join(__dir__, "..", "dependencies.yml"), symbolize_names: true) - sqlite_tarball = File.basename(dependencies[:sqlite3][:files].first[:url]) - actual_ports = gemfile_contents.grep(%r{^ports/}) + it "contains the port files" do + dependencies = YAML.load_file(File.join(__dir__, "..", "dependencies.yml"), symbolize_names: true) + sqlite_tarball = File.basename(dependencies[:sqlite3][:files].first[:url]) + actual_ports = gemfile_contents.grep(%r{^ports/}) - assert_equal(["ports/archives/#{sqlite_tarball}"], actual_ports) - end + assert_equal(["ports/archives/#{sqlite_tarball}"], actual_ports) + end - it "contains the patch files" do - assert_equal(Dir.glob("patches/*.patch").length, gemfile_contents.count { |f| File.fnmatch?("patches/*", f) }) - end + it "contains the patch files" do + assert_equal(Dir.glob("patches/*.patch").length, gemfile_contents.count { |f| File.fnmatch?("patches/*", f) }) + end - it "sets metadata for msys2" do - refute_nil(gemspec.metadata["msys2_mingw_dependencies"]) - end + it "sets metadata for msys2" do + refute_nil(gemspec.metadata["msys2_mingw_dependencies"]) + end - it "sets required_ruby_version appropriately" do - all_supported_ruby_versions.each do |v| - assert( - gemspec.required_ruby_version.satisfied_by?(Gem::Version.new(v)), - "required_ruby_version='#{gemspec.required_ruby_version}' should support ruby #{v}", - ) + it "sets required_ruby_version appropriately" do + all_supported_ruby_versions.each do |v| + assert( + gemspec.required_ruby_version.satisfied_by?(Gem::Version.new(v)), + "required_ruby_version='#{gemspec.required_ruby_version}' should support ruby #{v}" + ) + end end end - end if gemspec.platform == Gem::Platform::RUBY + end - describe "native platform" do - it "does not depend on mini_portile2" do - refute(gemspec.dependencies.find { |d| d.name == "mini_portile2" }) - end + if gemspec.platform.is_a?(Gem::Platform) && gemspec.platform.cpu + describe "native platform" do + it "does not depend on mini_portile2" do + refute(gemspec.dependencies.find { |d| d.name == "mini_portile2" }) + end - it "contains extension C and header files" do - assert_equal(6, gemfile_contents.count { |f| File.fnmatch?("ext/**/*.c", f) }) - assert_equal(6, gemfile_contents.count { |f| File.fnmatch?("ext/**/*.h", f) }) - end + it "contains extension C and header files" do + assert_equal(6, gemfile_contents.count { |f| File.fnmatch?("ext/**/*.c", f) }) + assert_equal(6, gemfile_contents.count { |f| File.fnmatch?("ext/**/*.h", f) }) + end - it "includes C files in extra_rdoc_files" do - assert_equal(6, gemspec.extra_rdoc_files.count { |f| File.fnmatch?("ext/**/*.c", f) }) - end + it "includes C files in extra_rdoc_files" do + assert_equal(6, gemspec.extra_rdoc_files.count { |f| File.fnmatch?("ext/**/*.c", f) }) + end - it "does not contain the port files" do - assert_empty(gemfile_contents.grep(%r{^ports/})) - end + it "does not contain the port files" do + assert_empty(gemfile_contents.grep(%r{^ports/})) + end - it "does not contain the patch files" do - assert_empty(gemfile_contents.grep(%r{^patches/})) - end + it "does not contain the patch files" do + assert_empty(gemfile_contents.grep(%r{^patches/})) + end + + it "contains expected shared library files " do + platform_supported_ruby_versions.each do |version| + actual = gemfile_contents.find do |p| + File.fnmatch?("lib/sqlite3/#{version}/sqlite3_native.{so,bundle}", p, File::FNM_EXTGLOB) + end + assert(actual, "expected to find shared library file for ruby #{version}") + end - it "contains expected shared library files " do - platform_supported_ruby_versions.each do |version| actual = gemfile_contents.find do |p| - File.fnmatch?("lib/sqlite3/#{version}/sqlite3_native.{so,bundle}", p, File::FNM_EXTGLOB) + File.fnmatch?("lib/sqlite3/sqlite3_native.{so,bundle}", p, File::FNM_EXTGLOB) end - assert(actual, "expected to find shared library file for ruby #{version}") - end + refute(actual, "did not expect to find shared library file in lib/sqlite3") - actual = gemfile_contents.find do |p| - File.fnmatch?("lib/sqlite3/sqlite3_native.{so,bundle}", p, File::FNM_EXTGLOB) + actual = gemfile_contents.find_all do |p| + File.fnmatch?("lib/sqlite3/**/*.{so,bundle}", p, File::FNM_EXTGLOB) + end + assert_equal( + platform_supported_ruby_versions.length, + actual.length, + "did not expect extra shared library files" + ) end - refute(actual, "did not expect to find shared library file in lib/sqlite3") - actual = gemfile_contents.find_all do |p| - File.fnmatch?("lib/sqlite3/**/*.{so,bundle}", p, File::FNM_EXTGLOB) + it "sets required_ruby_version appropriately" do + unsupported_versions = all_supported_ruby_versions - platform_supported_ruby_versions + platform_supported_ruby_versions.each do |v| + assert( + gemspec.required_ruby_version.satisfied_by?(Gem::Version.new(v)), + "required_ruby_version='#{gemspec.required_ruby_version}' should support ruby #{v}" + ) + end + unsupported_versions.each do |v| + refute( + gemspec.required_ruby_version.satisfied_by?(Gem::Version.new(v)), + "required_ruby_version='#{gemspec.required_ruby_version}' should not support ruby #{v}" + ) + end end - assert_equal( - platform_supported_ruby_versions.length, - actual.length, - "did not expect extra shared library files", - ) - end - it "sets required_ruby_version appropriately" do - unsupported_versions = all_supported_ruby_versions - platform_supported_ruby_versions - platform_supported_ruby_versions.each do |v| - assert( - gemspec.required_ruby_version.satisfied_by?(Gem::Version.new(v)), - "required_ruby_version='#{gemspec.required_ruby_version}' should support ruby #{v}", - ) + it "does not set metadata for msys2" do + assert_nil(gemspec.metadata["msys2_mingw_dependencies"]) end - unsupported_versions.each do |v| - refute( - gemspec.required_ruby_version.satisfied_by?(Gem::Version.new(v)), - "required_ruby_version='#{gemspec.required_ruby_version}' should not support ruby #{v}", - ) - end - end - - it "does not set metadata for msys2" do - assert_nil(gemspec.metadata["msys2_mingw_dependencies"]) end - end if gemspec.platform.is_a?(Gem::Platform) && gemspec.platform.cpu + end end diff --git a/ext/sqlite3/extconf.rb b/ext/sqlite3/extconf.rb index d48e84a2..733e22d5 100644 --- a/ext/sqlite3/extconf.rb +++ b/ext/sqlite3/extconf.rb @@ -19,7 +19,7 @@ def configure configure_extension - create_makefile('sqlite3/sqlite3_native') + create_makefile("sqlite3/sqlite3_native") end def configure_cross_compiler @@ -52,7 +52,7 @@ def configure_packaged_libraries recipe.configure_options += [ "--enable-shared=no", "--enable-static=yes", - "--enable-fts5", + "--enable-fts5" ] ENV.to_h.tap do |env| user_cflags = with_config("sqlite-cflags") @@ -60,11 +60,11 @@ def configure_packaged_libraries "-fPIC", # needed for linking the static library into a shared library "-O2", # see https://github.com/sparklemotion/sqlite3-ruby/issues/335 for some benchmarks "-fvisibility=hidden", # see https://github.com/rake-compiler/rake-compiler-dock/issues/87 - "-DSQLITE_DEFAULT_WAL_SYNCHRONOUS=1", + "-DSQLITE_DEFAULT_WAL_SYNCHRONOUS=1" ] env["CFLAGS"] = [user_cflags, env["CFLAGS"], more_cflags].flatten.join(" ") - recipe.configure_options += env.select { |k,v| ENV_ALLOWLIST.include?(k) } - .map { |key, value| "#{key}=#{value.strip}" } + recipe.configure_options += env.select { |k, v| ENV_ALLOWLIST.include?(k) } + .map { |key, value| "#{key}=#{value.strip}" } end unless File.exist?(File.join(recipe.target, recipe.host, recipe.name, recipe.version)) @@ -110,25 +110,25 @@ def configure_extension abort_could_not_find(libname) unless find_library(libname, "sqlite3_libversion_number", "sqlite3.h") # Functions defined in 1.9 but not 1.8 - have_func('rb_proc_arity') + have_func("rb_proc_arity") # Functions defined in 2.1 but not 2.0 - have_func('rb_integer_pack') + have_func("rb_integer_pack") # These functions may not be defined - have_func('sqlite3_initialize') - have_func('sqlite3_backup_init') - have_func('sqlite3_column_database_name') - have_func('sqlite3_enable_load_extension') - have_func('sqlite3_load_extension') + have_func("sqlite3_initialize") + have_func("sqlite3_backup_init") + have_func("sqlite3_column_database_name") + have_func("sqlite3_enable_load_extension") + have_func("sqlite3_load_extension") - unless have_func('sqlite3_open_v2') # https://www.sqlite.org/releaselog/3_5_0.html + unless have_func("sqlite3_open_v2") # https://www.sqlite.org/releaselog/3_5_0.html abort("\nPlease use a version of SQLite3 >= 3.5.0\n\n") end - have_func('sqlite3_prepare_v2') - have_type('sqlite3_int64', 'sqlite3.h') - have_type('sqlite3_uint64', 'sqlite3.h') + have_func("sqlite3_prepare_v2") + have_type("sqlite3_int64", "sqlite3.h") + have_type("sqlite3_uint64", "sqlite3.h") end def minimal_recipe diff --git a/lib/sqlite3.rb b/lib/sqlite3.rb index f6110e1c..790fd754 100644 --- a/lib/sqlite3.rb +++ b/lib/sqlite3.rb @@ -3,13 +3,15 @@ RUBY_VERSION =~ /(\d+\.\d+)/ require "sqlite3/#{$1}/sqlite3_native" rescue LoadError - require 'sqlite3/sqlite3_native' + require "sqlite3/sqlite3_native" end -require 'sqlite3/database' -require 'sqlite3/version' +require "sqlite3/database" +require "sqlite3/version" module SQLite3 # Was sqlite3 compiled with thread safety on? - def self.threadsafe?; threadsafe > 0; end + def self.threadsafe? + threadsafe > 0 + end end diff --git a/lib/sqlite3/constants.rb b/lib/sqlite3/constants.rb index 29f2a5a0..34d0a792 100644 --- a/lib/sqlite3/constants.rb +++ b/lib/sqlite3/constants.rb @@ -1,50 +1,50 @@ -module SQLite3 ; module Constants +module SQLite3 + module Constants + module TextRep + UTF8 = 1 + UTF16LE = 2 + UTF16BE = 3 + UTF16 = 4 + ANY = 5 + DETERMINISTIC = 0x800 + end - module TextRep - UTF8 = 1 - UTF16LE = 2 - UTF16BE = 3 - UTF16 = 4 - ANY = 5 - DETERMINISTIC = 0x800 - end - - module ColumnType - INTEGER = 1 - FLOAT = 2 - TEXT = 3 - BLOB = 4 - NULL = 5 - end + module ColumnType + INTEGER = 1 + FLOAT = 2 + TEXT = 3 + BLOB = 4 + NULL = 5 + end - module ErrorCode - OK = 0 # Successful result - ERROR = 1 # SQL error or missing database - INTERNAL = 2 # An internal logic error in SQLite - PERM = 3 # Access permission denied - ABORT = 4 # Callback routine requested an abort - BUSY = 5 # The database file is locked - LOCKED = 6 # A table in the database is locked - NOMEM = 7 # A malloc() failed - READONLY = 8 # Attempt to write a readonly database - INTERRUPT = 9 # Operation terminated by sqlite_interrupt() - IOERR = 10 # Some kind of disk I/O error occurred - CORRUPT = 11 # The database disk image is malformed - NOTFOUND = 12 # (Internal Only) Table or record not found - FULL = 13 # Insertion failed because database is full - CANTOPEN = 14 # Unable to open the database file - PROTOCOL = 15 # Database lock protocol error - EMPTY = 16 # (Internal Only) Database table is empty - SCHEMA = 17 # The database schema changed - TOOBIG = 18 # Too much data for one row of a table - CONSTRAINT = 19 # Abort due to constraint violation - MISMATCH = 20 # Data type mismatch - MISUSE = 21 # Library used incorrectly - NOLFS = 22 # Uses OS features not supported on host - AUTH = 23 # Authorization denied + module ErrorCode + OK = 0 # Successful result + ERROR = 1 # SQL error or missing database + INTERNAL = 2 # An internal logic error in SQLite + PERM = 3 # Access permission denied + ABORT = 4 # Callback routine requested an abort + BUSY = 5 # The database file is locked + LOCKED = 6 # A table in the database is locked + NOMEM = 7 # A malloc() failed + READONLY = 8 # Attempt to write a readonly database + INTERRUPT = 9 # Operation terminated by sqlite_interrupt() + IOERR = 10 # Some kind of disk I/O error occurred + CORRUPT = 11 # The database disk image is malformed + NOTFOUND = 12 # (Internal Only) Table or record not found + FULL = 13 # Insertion failed because database is full + CANTOPEN = 14 # Unable to open the database file + PROTOCOL = 15 # Database lock protocol error + EMPTY = 16 # (Internal Only) Database table is empty + SCHEMA = 17 # The database schema changed + TOOBIG = 18 # Too much data for one row of a table + CONSTRAINT = 19 # Abort due to constraint violation + MISMATCH = 20 # Data type mismatch + MISUSE = 21 # Library used incorrectly + NOLFS = 22 # Uses OS features not supported on host + AUTH = 23 # Authorization denied - ROW = 100 # sqlite_step() has another row ready - DONE = 101 # sqlite_step() has finished executing + ROW = 100 # sqlite_step() has another row ready + DONE = 101 # sqlite_step() has finished executing + end end - -end ; end +end diff --git a/lib/sqlite3/database.rb b/lib/sqlite3/database.rb index 206918f9..3dc14161 100644 --- a/lib/sqlite3/database.rb +++ b/lib/sqlite3/database.rb @@ -1,12 +1,11 @@ -require 'sqlite3/constants' -require 'sqlite3/errors' -require 'sqlite3/pragmas' -require 'sqlite3/statement' -require 'sqlite3/translator' -require 'sqlite3/value' +require "sqlite3/constants" +require "sqlite3/errors" +require "sqlite3/pragmas" +require "sqlite3/statement" +require "sqlite3/translator" +require "sqlite3/value" module SQLite3 - # The Database class encapsulates a single connection to a SQLite3 database. # Its usage is very straightforward: # @@ -38,11 +37,10 @@ class Database include Pragmas class << self - # Without block works exactly as new. # With block, like new closes the database at the end, but unlike new # returns the result of the block instead of the database instance. - def open( *args ) + def open(*args) database = new(*args) if block_given? @@ -59,10 +57,9 @@ def open( *args ) # Quotes the given string, making it safe to use in an SQL statement. # It replaces all instances of the single-quote character with two # single-quote characters. The modified string is returned. - def quote( string ) - string.gsub( /'/, "''" ) + def quote(string) + string.gsub("'", "''") end - end # A boolean that indicates whether rows in result sets should be returned @@ -120,16 +117,16 @@ def initialize file, options = {}, zvfs = nil end end - @tracefunc = nil - @authorizer = nil - @encoding = nil - @busy_handler = nil - @collations = {} - @functions = {} - @results_as_hash = options[:results_as_hash] + @tracefunc = nil + @authorizer = nil + @encoding = nil + @busy_handler = nil + @collations = {} + @functions = {} + @results_as_hash = options[:results_as_hash] @type_translation = options[:type_translation] - @type_translator = make_type_translator @type_translation - @readonly = mode & Constants::Open::READONLY != 0 + @type_translator = make_type_translator @type_translation + @readonly = mode & Constants::Open::READONLY != 0 @default_transaction_mode = options[:default_transaction_mode] || :deferred if block_given? @@ -149,10 +146,10 @@ def encoding end def type_translation= value # :nodoc: - warn(<<-eowarn) if $VERBOSE -#{caller[0]} is calling `SQLite3::Database#type_translation=` which is deprecated and will be removed in version 2.0.0. - eowarn - @type_translator = make_type_translator value + warn(<<~EOWARN) if $VERBOSE + #{caller(1..1).first} is calling `SQLite3::Database#type_translation=` which is deprecated and will be removed in version 2.0.0. + EOWARN + @type_translator = make_type_translator value @type_translation = value end attr_reader :type_translation # :nodoc: @@ -171,7 +168,7 @@ def translator # to the database. If the block returns 0 (or +nil+), the statement # is allowed to proceed. Returning 1 causes an authorization error to # occur, and returning 2 causes the access to be silently denied. - def authorizer( &block ) + def authorizer(&block) self.authorizer = block end @@ -181,7 +178,7 @@ def authorizer( &block ) # The Statement can then be executed using Statement#execute. # def prepare sql - stmt = SQLite3::Statement.new( self, sql ) + stmt = SQLite3::Statement.new(self, sql) return stmt unless block_given? begin @@ -194,7 +191,7 @@ def prepare sql # Returns the filename for the database named +db_name+. +db_name+ defaults # to "main". Main return `nil` or an empty string if the database is # temporary or in-memory. - def filename db_name = 'main' + def filename db_name = "main" db_filename db_name end @@ -214,22 +211,22 @@ def filename db_name = 'main' # executing statements. def execute sql, bind_vars = [], *args, &block if bind_vars.nil? || !args.empty? - if args.empty? - bind_vars = [] + bind_vars = if args.empty? + [] else - bind_vars = [bind_vars] + args + [bind_vars] + args end - warn(<<-eowarn) if $VERBOSE -#{caller[0]} is calling `SQLite3::Database#execute` with nil or multiple bind params without using an array. Please switch to passing bind parameters as an array. Support for bind parameters as *args will be removed in 2.0.0. - eowarn + warn(<<~EOWARN) if $VERBOSE + #{caller(1..1).first} is calling `SQLite3::Database#execute` with nil or multiple bind params without using an array. Please switch to passing bind parameters as an array. Support for bind parameters as *args will be removed in 2.0.0. + EOWARN end - prepare( sql ) do |stmt| + prepare(sql) do |stmt| stmt.bind_params(bind_vars) - stmt = ResultSet.new self, stmt + stmt = ResultSet.new self, stmt - if block_given? + if block stmt.each do |row| yield row end @@ -249,15 +246,16 @@ def execute sql, bind_vars = [], *args, &block # # See also #execute, #query, and #execute_batch for additional ways of # executing statements. - def execute2( sql, *bind_vars ) - prepare( sql ) do |stmt| - result = stmt.execute( *bind_vars ) + def execute2(sql, *bind_vars) + prepare(sql) do |stmt| + result = stmt.execute(*bind_vars) if block_given? yield stmt.columns result.each { |row| yield row } else - return result.inject( [ stmt.columns ] ) { |arr,row| - arr << row; arr } + return result.each_with_object([stmt.columns]) { |row, arr| + arr << row + } end end end @@ -273,31 +271,31 @@ def execute2( sql, *bind_vars ) # # See also #execute_batch2 for additional ways of # executing statements. - def execute_batch( sql, bind_vars = [], *args ) + def execute_batch(sql, bind_vars = [], *args) # FIXME: remove this stuff later unless [Array, Hash].include?(bind_vars.class) bind_vars = [bind_vars] - warn(<<-eowarn) if $VERBOSE -#{caller[0]} is calling `SQLite3::Database#execute_batch` with bind parameters that are not a list of a hash. Please switch to passing bind parameters as an array or hash. Support for this behavior will be removed in version 2.0.0. - eowarn + warn(<<~EOWARN) if $VERBOSE + #{caller(1..1).first} is calling `SQLite3::Database#execute_batch` with bind parameters that are not a list of a hash. Please switch to passing bind parameters as an array or hash. Support for this behavior will be removed in version 2.0.0. + EOWARN end # FIXME: remove this stuff later if bind_vars.nil? || !args.empty? - if args.empty? - bind_vars = [] + bind_vars = if args.empty? + [] else - bind_vars = [nil] + args + [nil] + args end - warn(<<-eowarn) if $VERBOSE -#{caller[0]} is calling `SQLite3::Database#execute_batch` with nil or multiple bind params without using an array. Please switch to passing bind parameters as an array. Support for this behavior will be removed in version 2.0.0. - eowarn + warn(<<~EOWARN) if $VERBOSE + #{caller(1..1).first} is calling `SQLite3::Database#execute_batch` with nil or multiple bind params without using an array. Please switch to passing bind parameters as an array. Support for this behavior will be removed in version 2.0.0. + EOWARN end sql = sql.strip - until sql.empty? do - prepare( sql ) do |stmt| + until sql.empty? + prepare(sql) do |stmt| unless stmt.closed? # FIXME: this should probably use sqlite3's api for batch execution # This implementation requires stepping over the results. @@ -327,7 +325,7 @@ def execute_batch( sql, bind_vars = [], *args ) # See also #execute_batch for additional ways of # executing statements. def execute_batch2(sql, &block) - if block_given? + if block result = exec_batch(sql, @results_as_hash) result.map do |val| yield val @@ -348,21 +346,20 @@ def execute_batch2(sql, &block) # returned, or you could have problems with locks on the table. If called # with a block, +close+ will be invoked implicitly when the block # terminates. - def query( sql, bind_vars = [], *args ) - + def query(sql, bind_vars = [], *args) if bind_vars.nil? || !args.empty? - if args.empty? - bind_vars = [] + bind_vars = if args.empty? + [] else - bind_vars = [bind_vars] + args + [bind_vars] + args end - warn(<<-eowarn) if $VERBOSE -#{caller[0]} is calling `SQLite3::Database#query` with nil or multiple bind params without using an array. Please switch to passing bind parameters as an array. Support for this will be removed in version 2.0.0. - eowarn + warn(<<~EOWARN) if $VERBOSE + #{caller(1..1).first} is calling `SQLite3::Database#query` with nil or multiple bind params without using an array. Please switch to passing bind parameters as an array. Support for this will be removed in version 2.0.0. + EOWARN end - result = prepare( sql ).execute( bind_vars ) + result = prepare(sql).execute(bind_vars) if block_given? begin yield result @@ -370,7 +367,7 @@ def query( sql, bind_vars = [], *args ) result.close end else - return result + result end end @@ -378,8 +375,8 @@ def query( sql, bind_vars = [], *args ) # discarding all others. It is otherwise identical to #execute. # # See also #get_first_value. - def get_first_row( sql, *bind_vars ) - execute( sql, *bind_vars ).first + def get_first_row(sql, *bind_vars) + execute(sql, *bind_vars).first end # A convenience method for obtaining the first value of the first row of a @@ -387,8 +384,8 @@ def get_first_row( sql, *bind_vars ) # identical to #execute. # # See also #get_first_row. - def get_first_value( sql, *bind_vars ) - query( sql, bind_vars ) do |rs| + def get_first_value(sql, *bind_vars) + query(sql, bind_vars) do |rs| if (row = rs.next) return @results_as_hash ? row[rs.columns[0]] : row[0] end @@ -396,7 +393,7 @@ def get_first_value( sql, *bind_vars ) nil end - alias :busy_timeout :busy_timeout= + alias_method :busy_timeout, :busy_timeout= # Creates a new function for use in SQL statements. It will be added as # +name+, with the given +arity+. (For variable arity functions, use @@ -421,7 +418,7 @@ def get_first_value( sql, *bind_vars ) # end # # puts db.get_first_value( "select maim(name) from table" ) - def create_function name, arity, text_rep=Constants::TextRep::UTF8, &block + def create_function name, arity, text_rep = Constants::TextRep::UTF8, &block define_function_with_flags(name, text_rep) do |*args| fp = FunctionProxy.new block.call(fp, *args) @@ -466,20 +463,20 @@ def create_function name, arity, text_rep=Constants::TextRep::UTF8, &block # # See also #create_aggregate_handler for a more object-oriented approach to # aggregate functions. - def create_aggregate( name, arity, step=nil, finalize=nil, - text_rep=Constants::TextRep::ANY, &block ) + def create_aggregate(name, arity, step = nil, finalize = nil, + text_rep = Constants::TextRep::ANY, &block) proxy = Class.new do - def self.step( &block ) + def self.step(&block) define_method(:step_with_ctx, &block) end - def self.finalize( &block ) + def self.finalize(&block) define_method(:finalize_with_ctx, &block) end end - if block_given? + if block proxy.instance_eval(&block) else proxy.class_eval do @@ -505,7 +502,7 @@ def initialize @ctx = FunctionProxy.new end - def step( *args ) + def step(*args) step_with_ctx(@ctx, *args) end @@ -564,7 +561,7 @@ def finalize # # db.create_aggregate_handler( LengthsAggregateHandler ) # puts db.get_first_value( "select lengths(name) from A" ) - def create_aggregate_handler( handler ) + def create_aggregate_handler(handler) # This is a compatibility shim so the (basically pointless) FunctionProxy # "ctx" object is passed as first argument to both step() and finalize(). # Now its up to the library user whether he prefers to store his @@ -578,7 +575,7 @@ def initialize @fp = FunctionProxy.new end - def step( *args ) + def step(*args) super(@fp, *args) end @@ -601,7 +598,7 @@ def finalize # individual instances of the aggregate function. Regular ruby objects # already provide a suitable +clone+. # The functions arity is the arity of the +step+ method. - def define_aggregator( name, aggregator ) + def define_aggregator(name, aggregator) # Previously, this has been implemented in C. Now this is just yet # another compatibility shim proxy = Class.new do @@ -655,9 +652,9 @@ def finalize # If a block is not given, it is the caller's responsibility to end the # transaction explicitly, either by calling #commit, or by calling # #rollback. - def transaction( mode = nil ) + def transaction(mode = nil) mode = @default_transaction_mode if mode.nil? - execute "begin #{mode.to_s} transaction" + execute "begin #{mode} transaction" if block_given? abort = false @@ -714,33 +711,33 @@ class FunctionProxy # it is non-nil, it must quack like a Hash. If it is nil, then none of # the context functions will be available. def initialize - @result = nil - @context = {} + @result = nil + @context = {} end # Set the result of the function to the given error message. # The function will then return that error. - def set_error( error ) - @driver.result_error( @func, error.to_s, -1 ) + def set_error(error) + @driver.result_error(@func, error.to_s, -1) end # (Only available to aggregate functions.) Returns the number of rows # that the aggregate has processed so far. This will include the current # row, and so will always return at least 1. def count - @driver.aggregate_count( @func ) + @driver.aggregate_count(@func) end # Returns the value with the given key from the context. This is only # available to aggregate functions. - def []( key ) - @context[ key ] + def [](key) + @context[key] end # Sets the value with the given key in the context. This is only # available to aggregate functions. - def []=( key, value ) - @context[ key ] = value + def []=(key, value) + @context[key] = value end end @@ -757,7 +754,7 @@ def make_type_translator should_translate if should_translate lambda { |types, row| types.zip(row).map do |type, value| - translator.translate( type, value ) + translator.translate(type, value) end } else diff --git a/lib/sqlite3/errors.rb b/lib/sqlite3/errors.rb index 87c7b4ee..d44936f7 100644 --- a/lib/sqlite3/errors.rb +++ b/lib/sqlite3/errors.rb @@ -1,4 +1,4 @@ -require 'sqlite3/constants' +require "sqlite3/constants" module SQLite3 class Exception < ::StandardError @@ -7,29 +7,54 @@ class Exception < ::StandardError end class SQLException < Exception; end + class InternalException < Exception; end + class PermissionException < Exception; end + class AbortException < Exception; end + class BusyException < Exception; end + class LockedException < Exception; end + class MemoryException < Exception; end + class ReadOnlyException < Exception; end + class InterruptException < Exception; end + class IOException < Exception; end + class CorruptException < Exception; end + class NotFoundException < Exception; end + class FullException < Exception; end + class CantOpenException < Exception; end + class ProtocolException < Exception; end + class EmptyException < Exception; end + class SchemaChangedException < Exception; end + class TooBigException < Exception; end + class ConstraintException < Exception; end + class MismatchException < Exception; end + class MisuseException < Exception; end + class UnsupportedException < Exception; end + class AuthorizationException < Exception; end + class FormatException < Exception; end + class RangeException < Exception; end + class NotADatabaseException < Exception; end end diff --git a/lib/sqlite3/pragmas.rb b/lib/sqlite3/pragmas.rb index 39ef8b3a..43816ef3 100644 --- a/lib/sqlite3/pragmas.rb +++ b/lib/sqlite3/pragmas.rb @@ -1,59 +1,57 @@ -require 'sqlite3/errors' +require "sqlite3/errors" module SQLite3 - # This module is intended for inclusion solely by the Database class. It # defines convenience methods for the various pragmas supported by SQLite3. # # For a detailed description of these pragmas, see the SQLite3 documentation # at http://sqlite.org/pragma.html. module Pragmas - # Returns +true+ or +false+ depending on the value of the named pragma. - def get_boolean_pragma( name ) - get_first_value( "PRAGMA #{name}" ) != 0 + def get_boolean_pragma(name) + get_first_value("PRAGMA #{name}") != 0 end # Sets the given pragma to the given boolean value. The value itself # may be +true+ or +false+, or any other commonly used string or # integer that represents truth. - def set_boolean_pragma( name, mode ) + def set_boolean_pragma(name, mode) case mode when String - case mode.downcase - when "on", "yes", "true", "y", "t"; mode = "'ON'" - when "off", "no", "false", "n", "f"; mode = "'OFF'" - else - raise Exception, - "unrecognized pragma parameter #{mode.inspect}" - end + case mode.downcase + when "on", "yes", "true", "y", "t" then mode = "'ON'" + when "off", "no", "false", "n", "f" then mode = "'OFF'" + else + raise Exception, + "unrecognized pragma parameter #{mode.inspect}" + end when true, 1 - mode = "ON" + mode = "ON" when false, 0, nil - mode = "OFF" + mode = "OFF" else - raise Exception, - "unrecognized pragma parameter #{mode.inspect}" + raise Exception, + "unrecognized pragma parameter #{mode.inspect}" end - execute( "PRAGMA #{name}=#{mode}" ) + execute("PRAGMA #{name}=#{mode}") end # Requests the given pragma (and parameters), and if the block is given, # each row of the result set will be yielded to it. Otherwise, the results # are returned as an array. - def get_query_pragma( name, *params, &block ) # :yields: row + def get_query_pragma(name, *params, &block) # :yields: row if params.empty? - execute( "PRAGMA #{name}", &block ) + execute("PRAGMA #{name}", &block) else args = "'" + params.join("','") + "'" - execute( "PRAGMA #{name}( #{args} )", &block ) + execute("PRAGMA #{name}( #{args} )", &block) end end # Return the value of the given pragma. - def get_enum_pragma( name ) - get_first_value( "PRAGMA #{name}" ) + def get_enum_pragma(name) + get_first_value("PRAGMA #{name}") end # Set the value of the given pragma to +mode+. The +mode+ parameter must @@ -61,51 +59,53 @@ def get_enum_pragma( name ) # the array is another array comprised of elements in the enumeration that # have duplicate values. See #synchronous, #default_synchronous, # #temp_store, and #default_temp_store for usage examples. - def set_enum_pragma( name, mode, enums ) + def set_enum_pragma(name, mode, enums) match = enums.find { |p| p.find { |i| i.to_s.downcase == mode.to_s.downcase } } - raise Exception, - "unrecognized #{name} #{mode.inspect}" unless match - execute( "PRAGMA #{name}='#{match.first.upcase}'" ) + unless match + raise Exception, + "unrecognized #{name} #{mode.inspect}" + end + execute("PRAGMA #{name}='#{match.first.upcase}'") end # Returns the value of the given pragma as an integer. - def get_int_pragma( name ) - get_first_value( "PRAGMA #{name}" ).to_i + def get_int_pragma(name) + get_first_value("PRAGMA #{name}").to_i end # Set the value of the given pragma to the integer value of the +value+ # parameter. - def set_int_pragma( name, value ) - execute( "PRAGMA #{name}=#{value.to_i}" ) + def set_int_pragma(name, value) + execute("PRAGMA #{name}=#{value.to_i}") end # The enumeration of valid synchronous modes. - SYNCHRONOUS_MODES = [ [ 'full', 2 ], [ 'normal', 1 ], [ 'off', 0 ] ] + SYNCHRONOUS_MODES = [["full", 2], ["normal", 1], ["off", 0]] # The enumeration of valid temp store modes. - TEMP_STORE_MODES = [ [ 'default', 0 ], [ 'file', 1 ], [ 'memory', 2 ] ] + TEMP_STORE_MODES = [["default", 0], ["file", 1], ["memory", 2]] # The enumeration of valid auto vacuum modes. - AUTO_VACUUM_MODES = [ [ 'none', 0 ], [ 'full', 1 ], [ 'incremental', 2 ] ] + AUTO_VACUUM_MODES = [["none", 0], ["full", 1], ["incremental", 2]] # The list of valid journaling modes. - JOURNAL_MODES = [ [ 'delete' ], [ 'truncate' ], [ 'persist' ], [ 'memory' ], - [ 'wal' ], [ 'off' ] ] + JOURNAL_MODES = [["delete"], ["truncate"], ["persist"], ["memory"], + ["wal"], ["off"]] # The list of valid locking modes. - LOCKING_MODES = [ [ 'normal' ], [ 'exclusive' ] ] + LOCKING_MODES = [["normal"], ["exclusive"]] # The list of valid encodings. - ENCODINGS = [ [ 'utf-8' ], [ 'utf-16' ], [ 'utf-16le' ], [ 'utf-16be ' ] ] + ENCODINGS = [["utf-8"], ["utf-16"], ["utf-16le"], ["utf-16be "]] # The list of valid WAL checkpoints. - WAL_CHECKPOINTS = [ [ 'passive' ], [ 'full' ], [ 'restart' ], [ 'truncate' ] ] + WAL_CHECKPOINTS = [["passive"], ["full"], ["restart"], ["truncate"]] def application_id get_int_pragma "application_id" end - def application_id=( integer ) + def application_id=(integer) set_int_pragma "application_id", integer end @@ -113,7 +113,7 @@ def auto_vacuum get_enum_pragma "auto_vacuum" end - def auto_vacuum=( mode ) + def auto_vacuum=(mode) set_enum_pragma "auto_vacuum", mode, AUTO_VACUUM_MODES end @@ -121,7 +121,7 @@ def automatic_index get_boolean_pragma "automatic_index" end - def automatic_index=( mode ) + def automatic_index=(mode) set_boolean_pragma "automatic_index", mode end @@ -129,7 +129,7 @@ def busy_timeout get_int_pragma "busy_timeout" end - def busy_timeout=( milliseconds ) + def busy_timeout=(milliseconds) set_int_pragma "busy_timeout", milliseconds end @@ -137,7 +137,7 @@ def cache_size get_int_pragma "cache_size" end - def cache_size=( size ) + def cache_size=(size) set_int_pragma "cache_size", size end @@ -145,11 +145,11 @@ def cache_spill get_boolean_pragma "cache_spill" end - def cache_spill=( mode ) + def cache_spill=(mode) set_boolean_pragma "cache_spill", mode end - def case_sensitive_like=( mode ) + def case_sensitive_like=(mode) set_boolean_pragma "case_sensitive_like", mode end @@ -157,7 +157,7 @@ def cell_size_check get_boolean_pragma "cell_size_check" end - def cell_size_check=( mode ) + def cell_size_check=(mode) set_boolean_pragma "cell_size_check", mode end @@ -165,15 +165,15 @@ def checkpoint_fullfsync get_boolean_pragma "checkpoint_fullfsync" end - def checkpoint_fullfsync=( mode ) + def checkpoint_fullfsync=(mode) set_boolean_pragma "checkpoint_fullfsync", mode end - def collation_list( &block ) # :yields: row + def collation_list(&block) # :yields: row get_query_pragma "collation_list", &block end - def compile_options( &block ) # :yields: row + def compile_options(&block) # :yields: row get_query_pragma "compile_options", &block end @@ -181,7 +181,7 @@ def count_changes get_boolean_pragma "count_changes" end - def count_changes=( mode ) + def count_changes=(mode) set_boolean_pragma "count_changes", mode end @@ -189,7 +189,7 @@ def data_version get_int_pragma "data_version" end - def database_list( &block ) # :yields: row + def database_list(&block) # :yields: row get_query_pragma "database_list", &block end @@ -197,7 +197,7 @@ def default_cache_size get_int_pragma "default_cache_size" end - def default_cache_size=( size ) + def default_cache_size=(size) set_int_pragma "default_cache_size", size end @@ -205,7 +205,7 @@ def default_synchronous get_enum_pragma "default_synchronous" end - def default_synchronous=( mode ) + def default_synchronous=(mode) set_enum_pragma "default_synchronous", mode, SYNCHRONOUS_MODES end @@ -213,7 +213,7 @@ def default_temp_store get_enum_pragma "default_temp_store" end - def default_temp_store=( mode ) + def default_temp_store=(mode) set_enum_pragma "default_temp_store", mode, TEMP_STORE_MODES end @@ -221,7 +221,7 @@ def defer_foreign_keys get_boolean_pragma "defer_foreign_keys" end - def defer_foreign_keys=( mode ) + def defer_foreign_keys=(mode) set_boolean_pragma "defer_foreign_keys", mode end @@ -229,15 +229,15 @@ def encoding get_enum_pragma "encoding" end - def encoding=( mode ) + def encoding=(mode) set_enum_pragma "encoding", mode, ENCODINGS end - def foreign_key_check( *table, &block ) # :yields: row + def foreign_key_check(*table, &block) # :yields: row get_query_pragma "foreign_key_check", *table, &block end - def foreign_key_list( table, &block ) # :yields: row + def foreign_key_list(table, &block) # :yields: row get_query_pragma "foreign_key_list", table, &block end @@ -245,7 +245,7 @@ def foreign_keys get_boolean_pragma "foreign_keys" end - def foreign_keys=( mode ) + def foreign_keys=(mode) set_boolean_pragma "foreign_keys", mode end @@ -257,7 +257,7 @@ def full_column_names get_boolean_pragma "full_column_names" end - def full_column_names=( mode ) + def full_column_names=(mode) set_boolean_pragma "full_column_names", mode end @@ -265,31 +265,31 @@ def fullfsync get_boolean_pragma "fullfsync" end - def fullfsync=( mode ) + def fullfsync=(mode) set_boolean_pragma "fullfsync", mode end - def ignore_check_constraints=( mode ) + def ignore_check_constraints=(mode) set_boolean_pragma "ignore_check_constraints", mode end - def incremental_vacuum( pages, &block ) # :yields: row + def incremental_vacuum(pages, &block) # :yields: row get_query_pragma "incremental_vacuum", pages, &block end - def index_info( index, &block ) # :yields: row + def index_info(index, &block) # :yields: row get_query_pragma "index_info", index, &block end - def index_list( table, &block ) # :yields: row + def index_list(table, &block) # :yields: row get_query_pragma "index_list", table, &block end - def index_xinfo( index, &block ) # :yields: row + def index_xinfo(index, &block) # :yields: row get_query_pragma "index_xinfo", index, &block end - def integrity_check( *num_errors, &block ) # :yields: row + def integrity_check(*num_errors, &block) # :yields: row get_query_pragma "integrity_check", *num_errors, &block end @@ -297,7 +297,7 @@ def journal_mode get_enum_pragma "journal_mode" end - def journal_mode=( mode ) + def journal_mode=(mode) set_enum_pragma "journal_mode", mode, JOURNAL_MODES end @@ -305,7 +305,7 @@ def journal_size_limit get_int_pragma "journal_size_limit" end - def journal_size_limit=( size ) + def journal_size_limit=(size) set_int_pragma "journal_size_limit", size end @@ -313,7 +313,7 @@ def legacy_file_format get_boolean_pragma "legacy_file_format" end - def legacy_file_format=( mode ) + def legacy_file_format=(mode) set_boolean_pragma "legacy_file_format", mode end @@ -321,7 +321,7 @@ def locking_mode get_enum_pragma "locking_mode" end - def locking_mode=( mode ) + def locking_mode=(mode) set_enum_pragma "locking_mode", mode, LOCKING_MODES end @@ -329,7 +329,7 @@ def max_page_count get_int_pragma "max_page_count" end - def max_page_count=( size ) + def max_page_count=(size) set_int_pragma "max_page_count", size end @@ -337,7 +337,7 @@ def mmap_size get_int_pragma "mmap_size" end - def mmap_size=( size ) + def mmap_size=(size) set_int_pragma "mmap_size", size end @@ -349,11 +349,11 @@ def page_size get_int_pragma "page_size" end - def page_size=( size ) + def page_size=(size) set_int_pragma "page_size", size end - def parser_trace=( mode ) + def parser_trace=(mode) set_boolean_pragma "parser_trace", mode end @@ -361,11 +361,11 @@ def query_only get_boolean_pragma "query_only" end - def query_only=( mode ) + def query_only=(mode) set_boolean_pragma "query_only", mode end - def quick_check( *num_errors, &block ) # :yields: row + def quick_check(*num_errors, &block) # :yields: row get_query_pragma "quick_check", *num_errors, &block end @@ -373,7 +373,7 @@ def read_uncommitted get_boolean_pragma "read_uncommitted" end - def read_uncommitted=( mode ) + def read_uncommitted=(mode) set_boolean_pragma "read_uncommitted", mode end @@ -381,7 +381,7 @@ def recursive_triggers get_boolean_pragma "recursive_triggers" end - def recursive_triggers=( mode ) + def recursive_triggers=(mode) set_boolean_pragma "recursive_triggers", mode end @@ -389,7 +389,7 @@ def reverse_unordered_selects get_boolean_pragma "reverse_unordered_selects" end - def reverse_unordered_selects=( mode ) + def reverse_unordered_selects=(mode) set_boolean_pragma "reverse_unordered_selects", mode end @@ -397,7 +397,7 @@ def schema_cookie get_int_pragma "schema_cookie" end - def schema_cookie=( cookie ) + def schema_cookie=(cookie) set_int_pragma "schema_cookie", cookie end @@ -405,7 +405,7 @@ def schema_version get_int_pragma "schema_version" end - def schema_version=( version ) + def schema_version=(version) set_int_pragma "schema_version", version end @@ -413,7 +413,7 @@ def secure_delete get_boolean_pragma "secure_delete" end - def secure_delete=( mode ) + def secure_delete=(mode) set_boolean_pragma "secure_delete", mode end @@ -421,23 +421,23 @@ def short_column_names get_boolean_pragma "short_column_names" end - def short_column_names=( mode ) + def short_column_names=(mode) set_boolean_pragma "short_column_names", mode end def shrink_memory - execute( "PRAGMA shrink_memory" ) + execute("PRAGMA shrink_memory") end def soft_heap_limit get_int_pragma "soft_heap_limit" end - def soft_heap_limit=( mode ) + def soft_heap_limit=(mode) set_int_pragma "soft_heap_limit", mode end - def stats( &block ) # :yields: row + def stats(&block) # :yields: row get_query_pragma "stats", &block end @@ -445,7 +445,7 @@ def synchronous get_enum_pragma "synchronous" end - def synchronous=( mode ) + def synchronous=(mode) set_enum_pragma "synchronous", mode, SYNCHRONOUS_MODES end @@ -453,7 +453,7 @@ def temp_store get_enum_pragma "temp_store" end - def temp_store=( mode ) + def temp_store=(mode) set_enum_pragma "temp_store", mode, TEMP_STORE_MODES end @@ -461,7 +461,7 @@ def threads get_int_pragma "threads" end - def threads=( count ) + def threads=(count) set_int_pragma "threads", count end @@ -469,7 +469,7 @@ def user_cookie get_int_pragma "user_cookie" end - def user_cookie=( cookie ) + def user_cookie=(cookie) set_int_pragma "user_cookie", cookie end @@ -477,19 +477,19 @@ def user_version get_int_pragma "user_version" end - def user_version=( version ) + def user_version=(version) set_int_pragma "user_version", version end - def vdbe_addoptrace=( mode ) + def vdbe_addoptrace=(mode) set_boolean_pragma "vdbe_addoptrace", mode end - def vdbe_debug=( mode ) + def vdbe_debug=(mode) set_boolean_pragma "vdbe_debug", mode end - def vdbe_listing=( mode ) + def vdbe_listing=(mode) set_boolean_pragma "vdbe_listing", mode end @@ -497,7 +497,7 @@ def vdbe_trace get_boolean_pragma "vdbe_trace" end - def vdbe_trace=( mode ) + def vdbe_trace=(mode) set_boolean_pragma "vdbe_trace", mode end @@ -505,7 +505,7 @@ def wal_autocheckpoint get_int_pragma "wal_autocheckpoint" end - def wal_autocheckpoint=( mode ) + def wal_autocheckpoint=(mode) set_int_pragma "wal_autocheckpoint", mode end @@ -513,11 +513,11 @@ def wal_checkpoint get_enum_pragma "wal_checkpoint" end - def wal_checkpoint=( mode ) + def wal_checkpoint=(mode) set_enum_pragma "wal_checkpoint", mode, WAL_CHECKPOINTS end - def writable_schema=( mode ) + def writable_schema=(mode) set_boolean_pragma "writable_schema", mode end @@ -525,7 +525,7 @@ def writable_schema=( mode ) # Returns information about +table+. Yields each row of table information # if a block is provided. def table_info table - stmt = prepare "PRAGMA table_info(#{table})" + stmt = prepare "PRAGMA table_info(#{table})" columns = stmt.columns needs_tweak_default = @@ -537,8 +537,8 @@ def table_info table # FIXME: This should be removed but is required for older versions # of rails - if(Object.const_defined?(:ActiveRecord)) - new_row['notnull'] = new_row['notnull'].to_s + if Object.const_defined?(:ActiveRecord) + new_row["notnull"] = new_row["notnull"].to_s end tweak_default(new_row) if needs_tweak_default @@ -546,8 +546,8 @@ def table_info table # Ensure the type value is downcased. On Mac and Windows # platforms this value is now being returned as all upper # case. - if new_row['type'] - new_row['type'] = new_row['type'].downcase + if new_row["type"] + new_row["type"] = new_row["type"].downcase end if block_given? @@ -563,33 +563,32 @@ def table_info table private - # Compares two version strings - def version_compare(v1, v2) - v1 = v1.split(".").map { |i| i.to_i } - v2 = v2.split(".").map { |i| i.to_i } - parts = [v1.length, v2.length].max - v1.push 0 while v1.length < parts - v2.push 0 while v2.length < parts - v1.zip(v2).each do |a,b| - return -1 if a < b - return 1 if a > b - end - return 0 + # Compares two version strings + def version_compare(v1, v2) + v1 = v1.split(".").map { |i| i.to_i } + v2 = v2.split(".").map { |i| i.to_i } + parts = [v1.length, v2.length].max + v1.push 0 while v1.length < parts + v2.push 0 while v2.length < parts + v1.zip(v2).each do |a, b| + return -1 if a < b + return 1 if a > b end - - # Since SQLite 3.3.8, the table_info pragma has returned the default - # value of the row as a quoted SQL value. This method essentially - # unquotes those values. - def tweak_default(hash) - case hash["dflt_value"] - when /^null$/i - hash["dflt_value"] = nil - when /^'(.*)'$/m - hash["dflt_value"] = $1.gsub(/''/, "'") - when /^"(.*)"$/m - hash["dflt_value"] = $1.gsub(/""/, '"') - end + 0 + end + + # Since SQLite 3.3.8, the table_info pragma has returned the default + # value of the row as a quoted SQL value. This method essentially + # unquotes those values. + def tweak_default(hash) + case hash["dflt_value"] + when /^null$/i + hash["dflt_value"] = nil + when /^'(.*)'$/m + hash["dflt_value"] = $1.gsub("''", "'") + when /^"(.*)"$/m + hash["dflt_value"] = $1.gsub('""', '"') end + end end - end diff --git a/lib/sqlite3/resultset.rb b/lib/sqlite3/resultset.rb index 40cfbe2a..6ab4e7a4 100644 --- a/lib/sqlite3/resultset.rb +++ b/lib/sqlite3/resultset.rb @@ -1,8 +1,7 @@ -require 'sqlite3/constants' -require 'sqlite3/errors' +require "sqlite3/constants" +require "sqlite3/errors" module SQLite3 - # The ResultSet object encapsulates the enumerability of a query's output. # It is a simple cursor over the data that the query returns. It will # very rarely (if ever) be instantiated directly. Instead, clients should @@ -19,16 +18,16 @@ class ArrayWithTypesAndFields < Array # :nodoc: attr_writer :fields def types - warn(<<-eowarn) if $VERBOSE -#{caller[0]} is calling `#{self.class}#types` which is deprecated and will be removed in sqlite3 version 2.0.0. Please call the `types` method on the SQLite3::ResultSet object that created this object. - eowarn + warn(<<~EOWARN) if $VERBOSE + #{caller(1..1).first} is calling `#{self.class}#types` which is deprecated and will be removed in sqlite3 version 2.0.0. Please call the `types` method on the SQLite3::ResultSet object that created this object. + EOWARN @types end def fields - warn(<<-eowarn) if $VERBOSE -#{caller[0]} is calling `#{self.class}#fields` which is deprecated and will be removed in sqlite3 version 2.0.0. Please call the `columns` method on the SQLite3::ResultSet object that created this object. - eowarn + warn(<<~EOWARN) if $VERBOSE + #{caller(1..1).first} is calling `#{self.class}#fields` which is deprecated and will be removed in sqlite3 version 2.0.0. Please call the `columns` method on the SQLite3::ResultSet object that created this object. + EOWARN @fields end end @@ -40,37 +39,37 @@ class HashWithTypesAndFields < Hash # :nodoc: attr_writer :fields def types - warn(<<-eowarn) if $VERBOSE -#{caller[0]} is calling `#{self.class}#types` which is deprecated and will be removed in sqlite3 version 2.0.0. Please call the `types` method on the SQLite3::ResultSet object that created this object. - eowarn + warn(<<~EOWARN) if $VERBOSE + #{caller(1..1).first} is calling `#{self.class}#types` which is deprecated and will be removed in sqlite3 version 2.0.0. Please call the `types` method on the SQLite3::ResultSet object that created this object. + EOWARN @types end def fields - warn(<<-eowarn) if $VERBOSE -#{caller[0]} is calling `#{self.class}#fields` which is deprecated and will be removed in sqlite3 version 2.0.0. Please call the `columns` method on the SQLite3::ResultSet object that created this object. - eowarn + warn(<<~EOWARN) if $VERBOSE + #{caller(1..1).first} is calling `#{self.class}#fields` which is deprecated and will be removed in sqlite3 version 2.0.0. Please call the `columns` method on the SQLite3::ResultSet object that created this object. + EOWARN @fields end def [] key key = fields[key] if key.is_a? Numeric - super key + super(key) end end # Create a new ResultSet attached to the given database, using the # given sql text. def initialize db, stmt - @db = db + @db = db @stmt = stmt end # Reset the cursor, so that a result set which has reached end-of-file # can be rewound and reiterated. - def reset( *bind_params ) + def reset(*bind_params) @stmt.reset! - @stmt.bind_params( *bind_params ) + @stmt.bind_params(*bind_params) @eof = false end @@ -102,16 +101,16 @@ def next row = @db.translate_from_db @stmt.types, row - if row.respond_to?(:fields) + row = if row.respond_to?(:fields) # FIXME: this can only happen if the translator returns something # that responds to `fields`. Since we're removing the translator # in 2.0, we can remove this branch in 2.0. - row = ArrayWithTypes.new(row) + ArrayWithTypes.new(row) else # FIXME: the `fields` and `types` methods are deprecated on this # object for version 2.0, so we can safely remove this branch # as well. - row = ArrayWithTypesAndFields.new(row) + ArrayWithTypesAndFields.new(row) end row.fields = @stmt.columns diff --git a/lib/sqlite3/statement.rb b/lib/sqlite3/statement.rb index 0692b81f..caae7f24 100644 --- a/lib/sqlite3/statement.rb +++ b/lib/sqlite3/statement.rb @@ -1,9 +1,9 @@ -require 'sqlite3/errors' -require 'sqlite3/resultset' +require "sqlite3/errors" +require "sqlite3/resultset" class String def to_blob - SQLite3::Blob.new( self ) + SQLite3::Blob.new(self) end end @@ -49,7 +49,7 @@ def initialize(db, sql) # # See also #execute, #bind_param, Statement#bind_param, and # Statement#bind_params. - def bind_params( *bind_vars ) + def bind_params(*bind_vars) index = 1 bind_vars.flatten.each do |var| if Hash === var @@ -75,7 +75,7 @@ def bind_params( *bind_vars ) # end # # See also #bind_params, #execute!. - def execute( *bind_vars ) + def execute(*bind_vars) reset! if active? || done? bind_params(*bind_vars) unless bind_vars.empty? @@ -101,9 +101,9 @@ def execute( *bind_vars ) # end # # See also #bind_params, #execute. - def execute!( *bind_vars, &block ) + def execute!(*bind_vars, &block) execute(*bind_vars) - block_given? ? each(&block) : to_a + block ? each(&block) : to_a end # Returns true if the statement is currently active, meaning it has an @@ -117,7 +117,7 @@ def active? # a (potentially) expensive operation. def columns get_metadata unless @columns - return @columns + @columns end def each @@ -146,6 +146,7 @@ def must_be_open! # :nodoc: end private + # A convenience method for obtaining the metadata about the query. Note # that this will actually execute the SQL, which means it can be a # (potentially) expensive operation. diff --git a/lib/sqlite3/translator.rb b/lib/sqlite3/translator.rb index 7a6055ae..b7456a26 100644 --- a/lib/sqlite3/translator.rb +++ b/lib/sqlite3/translator.rb @@ -1,8 +1,7 @@ -require 'time' -require 'date' +require "time" +require "date" module SQLite3 - # The Translator class encapsulates the logic and callbacks necessary for # converting string data to a value of some specified type. Every Database # instance may have a Translator instance, in order to assist in type @@ -12,11 +11,10 @@ module SQLite3 # by registering translator blocks with the corresponding database's # translator instance (Database#translator). class Translator - # Create a new Translator instance. It will be preinitialized with default # translators for most SQL data types. def initialize - @translators = Hash.new( proc { |type,value| value } ) + @translators = Hash.new(proc { |type, value| value }) @type_name_cache = {} register_default_translators end @@ -34,31 +32,31 @@ def initialize # is the (string) data to convert. # # The block should return the translated value. - def add_translator( type, &block ) # :yields: type, value - warn(<<-eowarn) if $VERBOSE -#{caller[0]} is calling `SQLite3::Translator#add_translator`. Built-in translators are deprecated and will be removed in version 2.0.0. - eowarn - @translators[ type_name( type ) ] = block + def add_translator(type, &block) # :yields: type, value + warn(<<~EOWARN) if $VERBOSE + #{caller(1..1).first} is calling `SQLite3::Translator#add_translator`. Built-in translators are deprecated and will be removed in version 2.0.0. + EOWARN + @translators[type_name(type)] = block end # Translate the given string value to a value of the given type. In the # absence of an installed translator block for the given type, the value # itself is always returned. Further, +nil+ values are never translated, # and are always passed straight through regardless of the type parameter. - def translate( type, value ) + def translate(type, value) unless value.nil? # FIXME: this is a hack to support Sequel - if type && %w{ datetime timestamp }.include?(type.downcase) - @translators[ type_name( type ) ].call( type, value.to_s ) + if type && %w[datetime timestamp].include?(type.downcase) + @translators[type_name(type)].call(type, value.to_s) else - @translators[ type_name( type ) ].call( type, value ) + @translators[type_name(type)].call(type, value) end end end # A convenience method for working with type names. This returns the "base" # type name, without any parenthetical data. - def type_name( type ) + def type_name(type) @type_name_cache[type] ||= begin type = "" if type.nil? type = $1 if type =~ /^(.*?)\(/ @@ -70,40 +68,40 @@ def type_name( type ) # Register the default translators for the current Translator instance. # This includes translators for most major SQL data types. def register_default_translators - [ "time", - "timestamp" ].each { |type| add_translator( type ) { |t, v| Time.parse( v ) } } + ["time", + "timestamp"].each { |type| add_translator(type) { |t, v| Time.parse(v) } } - add_translator( "date" ) { |t,v| Date.parse(v) } - add_translator( "datetime" ) { |t,v| DateTime.parse(v) } + add_translator("date") { |t, v| Date.parse(v) } + add_translator("datetime") { |t, v| DateTime.parse(v) } - [ "decimal", + ["decimal", "float", "numeric", "double", "real", "dec", - "fixed" ].each { |type| add_translator( type ) { |t,v| v.to_f } } + "fixed"].each { |type| add_translator(type) { |t, v| v.to_f } } - [ "integer", + ["integer", "smallint", "mediumint", "int", - "bigint" ].each { |type| add_translator( type ) { |t,v| v.to_i } } + "bigint"].each { |type| add_translator(type) { |t, v| v.to_i } } - [ "bit", + ["bit", "bool", - "boolean" ].each do |type| - add_translator( type ) do |t,v| - !( v.strip.gsub(/00+/,"0") == "0" || + "boolean"].each do |type| + add_translator(type) do |t, v| + !(v.strip.gsub(/00+/, "0") == "0" || v.downcase == "false" || v.downcase == "f" || v.downcase == "no" || - v.downcase == "n" ) + v.downcase == "n") end end - add_translator( "tinyint" ) do |type, value| - if type =~ /\(\s*1\s*\)/ + add_translator("tinyint") do |type, value| + if /\(\s*1\s*\)/.match?(type) value.to_i == 1 else value.to_i @@ -111,7 +109,5 @@ def register_default_translators end end private :register_default_translators - end - end diff --git a/lib/sqlite3/value.rb b/lib/sqlite3/value.rb index e5e5bf2c..6b007827 100644 --- a/lib/sqlite3/value.rb +++ b/lib/sqlite3/value.rb @@ -1,11 +1,10 @@ -require 'sqlite3/constants' +require "sqlite3/constants" module SQLite3 - class Value attr_reader :handle - def initialize( db, handle ) + def initialize(db, handle) @driver = db.driver @handle = handle end @@ -15,43 +14,41 @@ def null? end def to_blob - @driver.value_blob( @handle ) + @driver.value_blob(@handle) end - def length( utf16=false ) + def length(utf16 = false) if utf16 - @driver.value_bytes16( @handle ) + @driver.value_bytes16(@handle) else - @driver.value_bytes( @handle ) + @driver.value_bytes(@handle) end end def to_f - @driver.value_double( @handle ) + @driver.value_double(@handle) end def to_i - @driver.value_int( @handle ) + @driver.value_int(@handle) end def to_int64 - @driver.value_int64( @handle ) + @driver.value_int64(@handle) end - def to_s( utf16=false ) - @driver.value_text( @handle, utf16 ) + def to_s(utf16 = false) + @driver.value_text(@handle, utf16) end def type - case @driver.value_type( @handle ) - when Constants::ColumnType::INTEGER then :int - when Constants::ColumnType::FLOAT then :float - when Constants::ColumnType::TEXT then :text - when Constants::ColumnType::BLOB then :blob - when Constants::ColumnType::NULL then :null + case @driver.value_type(@handle) + when Constants::ColumnType::INTEGER then :int + when Constants::ColumnType::FLOAT then :float + when Constants::ColumnType::TEXT then :text + when Constants::ColumnType::BLOB then :blob + when Constants::ColumnType::NULL then :null end end - end - end diff --git a/rakelib/format.rake b/rakelib/format.rake index 7647b856..a4f0a323 100644 --- a/rakelib/format.rake +++ b/rakelib/format.rake @@ -1,4 +1,5 @@ require "rake/clean" +require "rubocop/rake_task" module AstyleHelper class << self @@ -41,7 +42,7 @@ module AstyleHelper # be quiet about files that haven't changed "--formatted", - "--verbose", + "--verbose" ] end @@ -59,6 +60,11 @@ namespace "format" do end CLEAN.add(AstyleHelper.c_files.map { |f| "#{f}.orig" }) + + desc "Format Ruby code" + task "ruby" => "rubocop:autocorrect" end -task "format" => ["format:c"] +RuboCop::RakeTask.new + +task "format" => ["format:c", "format:ruby"] diff --git a/rakelib/native.rake b/rakelib/native.rake index 5fea1d60..25e18ff5 100644 --- a/rakelib/native.rake +++ b/rakelib/native.rake @@ -15,7 +15,7 @@ cross_platforms = [ "x64-mingw32", "x86-linux", "x86_64-darwin", - "x86_64-linux", + "x86_64-linux" ] ENV["RUBY_CC_VERSION"] = cross_rubies.join(":") @@ -47,7 +47,7 @@ task gem_build_path do archive = Dir.glob(File.join("ports", "archives", sqlite_tarball)).first add_file_to_gem(archive) - patches = %x(#{["git", "ls-files", "patches"].shelljoin}).split("\n").grep(/\.patch\z/) + patches = `#{["git", "ls-files", "patches"].shelljoin}`.split("\n").grep(/\.patch\z/) patches.each { |patch| add_file_to_gem patch } end @@ -60,7 +60,7 @@ Rake::ExtensionTask.new("sqlite3_native", SQLITE3_SPEC) do |ext| ext.cross_compiling do |spec| # remove things not needed for precompiled gems spec.dependencies.reject! { |dep| dep.name == "mini_portile2" } - spec.metadata.delete('msys2_mingw_dependencies') + spec.metadata.delete("msys2_mingw_dependencies") end end @@ -107,7 +107,7 @@ task "set-version-to-timestamp" do raise("Could not hack the VERSION constant") end - File.open(version_file_path, "w") { |f| f.write(version_file_contents) } + File.write(version_file_path, version_file_contents) puts "NOTE: wrote version as \"#{fake_version}\"" end diff --git a/sqlite3.gemspec b/sqlite3.gemspec index 9fe6c590..2afa7521 100644 --- a/sqlite3.gemspec +++ b/sqlite3.gemspec @@ -1,5 +1,3 @@ -# -*- encoding: utf-8 -*- - begin require_relative "lib/sqlite3/version" rescue LoadError @@ -34,7 +32,7 @@ Gem::Specification.new do |s| "msys2_mingw_dependencies" => "sqlite3", # https://guides.rubygems.org/mfa-requirement-opt-in/ - "rubygems_mfa_required" => "true", + "rubygems_mfa_required" => "true" } s.files = [ @@ -93,7 +91,7 @@ Gem::Specification.new do |s| "test/test_result_set.rb", "test/test_sqlite3.rb", "test/test_statement.rb", - "test/test_statement_execute.rb", + "test/test_statement_execute.rb" ] s.extra_rdoc_files = [ diff --git a/test/helper.rb b/test/helper.rb index a5be6a44..5ea6da11 100644 --- a/test/helper.rb +++ b/test/helper.rb @@ -1,7 +1,7 @@ -require 'sqlite3' -require 'minitest/autorun' +require "sqlite3" +require "minitest/autorun" -if ENV['GITHUB_ACTIONS'] == 'true' || ENV['CI'] +if ENV["GITHUB_ACTIONS"] == "true" || ENV["CI"] $VERBOSE = nil end @@ -12,9 +12,9 @@ module SQLite3 class TestCase < Minitest::Test - alias :assert_not_equal :refute_equal - alias :assert_not_nil :refute_nil - alias :assert_raise :assert_raises + alias_method :assert_not_equal, :refute_equal + alias_method :assert_not_nil, :refute_nil + alias_method :assert_raise, :assert_raises def assert_nothing_raised yield diff --git a/test/test_backup.rb b/test/test_backup.rb index 4e9570b9..c92d7b59 100644 --- a/test/test_backup.rb +++ b/test/test_backup.rb @@ -1,33 +1,35 @@ -require 'helper' +require "helper" module SQLite3 - class TestBackup < SQLite3::TestCase - def setup - @sdb = SQLite3::Database.new(':memory:') - @ddb = SQLite3::Database.new(':memory:') - @sdb.execute('CREATE TABLE foo (idx, val);'); - @data = ('A'..'Z').map{|x|x * 40} - @data.each_with_index do |v, i| - @sdb.execute('INSERT INTO foo (idx, val) VALUES (?, ?);', [i, v]) + if defined?(SQLite3::Backup) + class TestBackup < SQLite3::TestCase + def setup + @sdb = SQLite3::Database.new(":memory:") + @ddb = SQLite3::Database.new(":memory:") + @sdb.execute("CREATE TABLE foo (idx, val);") + @data = ("A".."Z").map { |x| x * 40 } + @data.each_with_index do |v, i| + @sdb.execute("INSERT INTO foo (idx, val) VALUES (?, ?);", [i, v]) + end end - end - def test_backup_step - b = SQLite3::Backup.new(@ddb, 'main', @sdb, 'main') - while b.step(1) == SQLite3::Constants::ErrorCode::OK - assert_not_equal(0, b.remaining) + def test_backup_step + b = SQLite3::Backup.new(@ddb, "main", @sdb, "main") + while b.step(1) == SQLite3::Constants::ErrorCode::OK + assert_not_equal(0, b.remaining) + end + assert_equal(0, b.remaining) + b.finish + assert_equal(@data.length, @ddb.execute("SELECT * FROM foo;").length) end - assert_equal(0, b.remaining) - b.finish - assert_equal(@data.length, @ddb.execute('SELECT * FROM foo;').length) - end - def test_backup_all - b = SQLite3::Backup.new(@ddb, 'main', @sdb, 'main') - assert_equal(SQLite3::Constants::ErrorCode::DONE, b.step(-1)) - assert_equal(0, b.remaining) - b.finish - assert_equal(@data.length, @ddb.execute('SELECT * FROM foo;').length) + def test_backup_all + b = SQLite3::Backup.new(@ddb, "main", @sdb, "main") + assert_equal(SQLite3::Constants::ErrorCode::DONE, b.step(-1)) + assert_equal(0, b.remaining) + b.finish + assert_equal(@data.length, @ddb.execute("SELECT * FROM foo;").length) + end end - end if defined?(SQLite3::Backup) + end end diff --git a/test/test_collation.rb b/test/test_collation.rb index 42fafbbf..21c8871d 100644 --- a/test/test_collation.rb +++ b/test/test_collation.rb @@ -1,6 +1,4 @@ -# -*- coding: utf-8 -*- - -require 'helper' +require "helper" module SQLite3 class TestCollation < SQLite3::TestCase @@ -17,45 +15,45 @@ def compare left, right end def setup - @db = SQLite3::Database.new(':memory:') + @db = SQLite3::Database.new(":memory:") @create = "create table ex(id int, data string)" - @db.execute(@create); - [ [1, 'hello'], [2, 'world'] ].each do |vals| - @db.execute('insert into ex (id, data) VALUES (?, ?)', vals) + @db.execute(@create) + [[1, "hello"], [2, "world"]].each do |vals| + @db.execute("insert into ex (id, data) VALUES (?, ?)", vals) end end def test_custom_collation comparator = Comparator.new - @db.collation 'foo', comparator + @db.collation "foo", comparator - assert_equal comparator, @db.collations['foo'] - @db.execute('select data from ex order by 1 collate foo') + assert_equal comparator, @db.collations["foo"] + @db.execute("select data from ex order by 1 collate foo") assert_equal 1, comparator.calls.length end def test_remove_collation comparator = Comparator.new - @db.collation 'foo', comparator - @db.collation 'foo', nil + @db.collation "foo", comparator + @db.collation "foo", nil - assert_nil @db.collations['foo'] + assert_nil @db.collations["foo"] assert_raises(SQLite3::SQLException) do - @db.execute('select data from ex order by 1 collate foo') + @db.execute("select data from ex order by 1 collate foo") end end def test_encoding comparator = Comparator.new - @db.collation 'foo', comparator - @db.execute('select data from ex order by 1 collate foo') + @db.collation "foo", comparator + @db.execute("select data from ex order by 1 collate foo") a, b = *comparator.calls.first - assert_equal Encoding.find('UTF-8'), a.encoding - assert_equal Encoding.find('UTF-8'), b.encoding + assert_equal Encoding.find("UTF-8"), a.encoding + assert_equal Encoding.find("UTF-8"), b.encoding end def test_encoding_default_internal @@ -63,15 +61,15 @@ def test_encoding_default_internal $-w = false before_enc = Encoding.default_internal - Encoding.default_internal = 'EUC-JP' + Encoding.default_internal = "EUC-JP" comparator = Comparator.new - @db.collation 'foo', comparator - @db.execute('select data from ex order by 1 collate foo') + @db.collation "foo", comparator + @db.execute("select data from ex order by 1 collate foo") a, b = *comparator.calls.first - assert_equal Encoding.find('EUC-JP'), a.encoding - assert_equal Encoding.find('EUC-JP'), b.encoding + assert_equal Encoding.find("EUC-JP"), a.encoding + assert_equal Encoding.find("EUC-JP"), b.encoding ensure Encoding.default_internal = before_enc $-w = warn_before diff --git a/test/test_database.rb b/test/test_database.rb index da8088cc..3b16e69e 100644 --- a/test/test_database.rb +++ b/test/test_database.rb @@ -1,13 +1,13 @@ -require 'helper' -require 'tempfile' -require 'pathname' +require "helper" +require "tempfile" +require "pathname" module SQLite3 class TestDatabase < SQLite3::TestCase attr_reader :db def setup - @db = SQLite3::Database.new(':memory:') + @db = SQLite3::Database.new(":memory:") super end @@ -21,18 +21,18 @@ def test_segv def test_db_filename tf = nil - assert_equal '', @db.filename('main') - tf = Tempfile.new 'thing' + assert_equal "", @db.filename("main") + tf = Tempfile.new "thing" @db = SQLite3::Database.new tf.path - assert_equal File.realdirpath(tf.path), File.realdirpath(@db.filename('main')) + assert_equal File.realdirpath(tf.path), File.realdirpath(@db.filename("main")) ensure tf.unlink if tf end def test_filename tf = nil - assert_equal '', @db.filename - tf = Tempfile.new 'thing' + assert_equal "", @db.filename + tf = Tempfile.new "thing" @db = SQLite3::Database.new tf.path assert_equal File.realdirpath(tf.path), File.realdirpath(@db.filename) ensure @@ -41,18 +41,17 @@ def test_filename def test_filename_with_attachment tf = nil - assert_equal '', @db.filename - tf = Tempfile.new 'thing' + assert_equal "", @db.filename + tf = Tempfile.new "thing" @db.execute "ATTACH DATABASE '#{tf.path}' AS 'testing'" - assert_equal File.realdirpath(tf.path), File.realdirpath(@db.filename('testing')) + assert_equal File.realdirpath(tf.path), File.realdirpath(@db.filename("testing")) ensure tf.unlink if tf end - def test_filename_to_path - tf = Tempfile.new 'thing' + tf = Tempfile.new "thing" pn = Pathname tf.path db = SQLite3::Database.new pn assert_equal pn.realdirpath.to_s, File.realdirpath(db.filename) @@ -61,10 +60,9 @@ def test_filename_to_path db.close if db end - def test_error_code begin - db.execute 'SELECT' + db.execute "SELECT" rescue SQLite3::SQLException => e end assert_equal 1, e.code @@ -74,7 +72,7 @@ def test_extended_error_code db.extended_result_codes = true db.execute 'CREATE TABLE "employees" ("token" integer NOT NULL)' begin - db.execute 'INSERT INTO employees (token) VALUES (NULL)' + db.execute "INSERT INTO employees (token) VALUES (NULL)" rescue SQLite3::ConstraintException => e end assert_equal 1299, e.code @@ -84,7 +82,7 @@ def test_bignum num = 4907021672125087844 db.execute 'CREATE TABLE "employees" ("token" integer(8), "name" varchar(20) NOT NULL)' db.execute "INSERT INTO employees(name, token) VALUES('employee-1', ?)", [num] - rows = db.execute 'select token from employees' + rows = db.execute "select token from employees" assert_equal num, rows.first.first end @@ -92,18 +90,18 @@ def test_blob @db.execute("CREATE TABLE blobs ( id INTEGER, hash BLOB(10) )") blob = Blob.new("foo\0bar") @db.execute("INSERT INTO blobs VALUES (0, ?)", [blob]) - assert_equal [[0, blob, blob.length, blob.length*2]], @db.execute("SELECT id, hash, length(hash), length(hex(hash)) FROM blobs") + assert_equal [[0, blob, blob.length, blob.length * 2]], @db.execute("SELECT id, hash, length(hash), length(hex(hash)) FROM blobs") end def test_get_first_row - assert_equal [1], @db.get_first_row('SELECT 1') + assert_equal [1], @db.get_first_row("SELECT 1") end def test_get_first_row_with_type_translation_and_hash_results @db.results_as_hash = true capture_io do # hush translation deprecation warnings @db.type_translation = true - assert_equal({"1"=>1}, @db.get_first_row('SELECT 1')) + assert_equal({"1" => 1}, @db.get_first_row("SELECT 1")) end end @@ -113,14 +111,14 @@ def test_execute_with_type_translation_and_hash capture_io do # hush translation deprecation warnings @db.type_translation = true - @db.execute('SELECT 1') { |row| rows << row } + @db.execute("SELECT 1") { |row| rows << row } end - assert_equal({"1"=>1}, rows.first) + assert_equal({"1" => 1}, rows.first) end def test_encoding - assert @db.encoding, 'database has encoding' + assert @db.encoding, "database has encoding" end def test_changes @@ -130,88 +128,90 @@ def test_changes assert_equal 1, @db.changes @db.execute_batch( "UPDATE items SET number = (number + :nn) WHERE (number = :n)", - {"nn" => 20, "n" => 10}) + {"nn" => 20, "n" => 10} + ) assert_equal 1, @db.changes assert_equal [[30]], @db.execute("select number from items") end def test_batch_last_comment_is_processed # FIXME: nil as a successful return value is kinda dumb - assert_nil @db.execute_batch <<-eosql + assert_nil @db.execute_batch <<-EOSQL CREATE TABLE items (id integer PRIMARY KEY AUTOINCREMENT); -- omg - eosql + EOSQL end def test_execute_batch2 @db.results_as_hash = true - return_value = @db.execute_batch2 <<-eosql + return_value = @db.execute_batch2 <<-EOSQL CREATE TABLE items (id integer PRIMARY KEY AUTOINCREMENT, name string); INSERT INTO items (name) VALUES ("foo"); INSERT INTO items (name) VALUES ("bar"); SELECT * FROM items; - eosql - assert_equal return_value, [{"id"=>"1","name"=>"foo"}, {"id"=>"2", "name"=>"bar"}] + EOSQL + assert_equal return_value, [{"id" => "1", "name" => "foo"}, {"id" => "2", "name" => "bar"}] - return_value = @db.execute_batch2('SELECT * FROM items;') do |result| + return_value = @db.execute_batch2("SELECT * FROM items;") do |result| result["id"] = result["id"].to_i result end - assert_equal return_value, [{"id"=>1,"name"=>"foo"}, {"id"=>2, "name"=>"bar"}] + assert_equal return_value, [{"id" => 1, "name" => "foo"}, {"id" => 2, "name" => "bar"}] return_value = @db.execute_batch2('INSERT INTO items (name) VALUES ("oof")') assert_equal return_value, [] return_value = @db.execute_batch2( - 'CREATE TABLE employees (id integer PRIMARY KEY AUTOINCREMENT, name string, age integer(3)); + 'CREATE TABLE employees (id integer PRIMARY KEY AUTOINCREMENT, name string, age integer(3)); INSERT INTO employees (age) VALUES (30); INSERT INTO employees (age) VALUES (40); INSERT INTO employees (age) VALUES (20); - SELECT age FROM employees;') do |result| - result["age"] = result["age"].to_i - result - end - assert_equal return_value, [{"age"=>30}, {"age"=>40}, {"age"=>20}] + SELECT age FROM employees;' + ) do |result| + result["age"] = result["age"].to_i + result + end + assert_equal return_value, [{"age" => 30}, {"age" => 40}, {"age" => 20}] - return_value = @db.execute_batch2('SELECT name FROM employees'); - assert_equal return_value, [{"name"=>nil}, {"name"=>nil}, {"name"=>nil}] + return_value = @db.execute_batch2("SELECT name FROM employees") + assert_equal return_value, [{"name" => nil}, {"name" => nil}, {"name" => nil}] @db.results_as_hash = false return_value = @db.execute_batch2( 'CREATE TABLE managers (id integer PRIMARY KEY AUTOINCREMENT, age integer(3)); INSERT INTO managers (age) VALUES (50); INSERT INTO managers (age) VALUES (60); - SELECT id, age from managers;') do |result| - result = result.map do |res| - res.to_i - end - result + SELECT id, age from managers;' + ) do |result| + result = result.map do |res| + res.to_i end + result + end assert_equal return_value, [[1, 50], [2, 60]] - assert_raises (RuntimeError) do + assert_raises(RuntimeError) do # "names" is not a valid column @db.execute_batch2 'INSERT INTO items (names) VALUES ("bazz")' end - end def test_new - db = SQLite3::Database.new(':memory:') + db = SQLite3::Database.new(":memory:") assert_instance_of(SQLite3::Database, db) ensure db.close if db end def test_open - db = SQLite3::Database.open(':memory:') + db = SQLite3::Database.open(":memory:") assert_instance_of(SQLite3::Database, db) ensure db.close if db end def test_open_returns_block_result - result = SQLite3::Database.open(':memory:') do |db| + result = SQLite3::Database.open(":memory:") do |db| :foo end assert_equal :foo, result @@ -219,7 +219,7 @@ def test_open_returns_block_result def test_new_yields_self thing = nil - SQLite3::Database.new(':memory:') do |db| + SQLite3::Database.new(":memory:") do |db| thing = db end assert_instance_of(SQLite3::Database, thing) @@ -227,7 +227,7 @@ def test_new_yields_self def test_open_yields_self thing = nil - SQLite3::Database.open(':memory:') do |db| + SQLite3::Database.open(":memory:") do |db| thing = db end assert_instance_of(SQLite3::Database, thing) @@ -237,21 +237,21 @@ def test_new_with_options # determine if Ruby is running on Big Endian platform utf16 = ([1].pack("I") == [1].pack("N")) ? "UTF-16BE" : "UTF-16LE" - db = SQLite3::Database.new(':memory:'.encode(utf16), :utf16 => true) + db = SQLite3::Database.new(":memory:".encode(utf16), utf16: true) assert_instance_of(SQLite3::Database, db) ensure db.close if db end def test_close - db = SQLite3::Database.new(':memory:') + db = SQLite3::Database.new(":memory:") db.close assert db.closed? end def test_block_closes_self thing = nil - SQLite3::Database.new(':memory:') do |db| + SQLite3::Database.new(":memory:") do |db| thing = db assert !thing.closed? end @@ -260,7 +260,7 @@ def test_block_closes_self def test_open_with_block_closes_self thing = nil - SQLite3::Database.open(':memory:') do |db| + SQLite3::Database.open(":memory:") do |db| thing = db assert !thing.closed? end @@ -270,7 +270,7 @@ def test_open_with_block_closes_self def test_block_closes_self_even_raised thing = nil begin - SQLite3::Database.new(':memory:') do |db| + SQLite3::Database.new(":memory:") do |db| thing = db raise end @@ -282,7 +282,7 @@ def test_block_closes_self_even_raised def test_open_with_block_closes_self_even_raised thing = nil begin - SQLite3::Database.open(':memory:') do |db| + SQLite3::Database.open(":memory:") do |db| thing = db raise end @@ -292,7 +292,7 @@ def test_open_with_block_closes_self_even_raised end def test_prepare - db = SQLite3::Database.new(':memory:') + db = SQLite3::Database.new(":memory:") stmt = db.prepare('select "hello world"') assert_instance_of(SQLite3::Statement, stmt) ensure @@ -300,7 +300,7 @@ def test_prepare end def test_block_prepare_does_not_double_close - db = SQLite3::Database.new(':memory:') + db = SQLite3::Database.new(":memory:") r = db.prepare('select "hello world"') do |stmt| stmt.close :foo @@ -309,53 +309,53 @@ def test_block_prepare_does_not_double_close end def test_total_changes - db = SQLite3::Database.new(':memory:') + db = SQLite3::Database.new(":memory:") db.execute("create table foo ( a integer primary key, b text )") db.execute("insert into foo (b) values ('hello')") assert_equal 1, db.total_changes end def test_execute_returns_list_of_hash - db = SQLite3::Database.new(':memory:', :results_as_hash => true) + db = SQLite3::Database.new(":memory:", results_as_hash: true) db.execute("create table foo ( a integer primary key, b text )") db.execute("insert into foo (b) values ('hello')") rows = db.execute("select * from foo") - assert_equal [{"a"=>1, "b"=>"hello"}], rows + assert_equal [{"a" => 1, "b" => "hello"}], rows end def test_execute_yields_hash - db = SQLite3::Database.new(':memory:', :results_as_hash => true) + db = SQLite3::Database.new(":memory:", results_as_hash: true) db.execute("create table foo ( a integer primary key, b text )") db.execute("insert into foo (b) values ('hello')") db.execute("select * from foo") do |row| - assert_equal({"a"=>1, "b"=>"hello"}, row) + assert_equal({"a" => 1, "b" => "hello"}, row) end end def test_table_info - db = SQLite3::Database.new(':memory:', :results_as_hash => true) + db = SQLite3::Database.new(":memory:", results_as_hash: true) db.execute("create table foo ( a integer primary key, b text )") info = [{ - "name" => "a", - "pk" => 1, - "notnull" => 0, - "type" => "integer", + "name" => "a", + "pk" => 1, + "notnull" => 0, + "type" => "integer", "dflt_value" => nil, - "cid" => 0 + "cid" => 0 }, - { - "name" => "b", - "pk" => 0, - "notnull" => 0, - "type" => "text", - "dflt_value" => nil, - "cid" => 1 - }] - assert_equal info, db.table_info('foo') + { + "name" => "b", + "pk" => 0, + "notnull" => 0, + "type" => "text", + "dflt_value" => nil, + "cid" => 1 + }] + assert_equal info, db.table_info("foo") end def test_total_changes_closed - db = SQLite3::Database.new(':memory:') + db = SQLite3::Database.new(":memory:") db.close assert_raise(SQLite3::Exception) do db.total_changes @@ -379,7 +379,9 @@ def test_trace_with_block def test_trace_with_object obj = Class.new { attr_accessor :result - def call sql; @result = sql end + def call sql + @result = sql + end }.new @db.trace(obj) @@ -461,7 +463,7 @@ def test_function_gc_segfault @db.create_function("bug", -1) { |func, *values| func.result = values.join } # With a lot of data and a lot of threads, try to induce a GC segfault. params = Array.new(127, "?" * 28000) - proc = Proc.new { + proc = proc { db.execute("select bug(#{Array.new(params.length, "?").join(",")})", params) } m = Mutex.new @@ -478,7 +480,7 @@ def test_function_return_type_round_trip def test_define_function_closed @db.close assert_raise(SQLite3::Exception) do - @db.define_function('foo') { } + @db.define_function("foo") {} end end @@ -497,7 +499,7 @@ def test_define_aggregate acc = Class.new { attr_reader :sum - alias :finalize :sum + alias_method :finalize, :sum def initialize @sum = 0 end @@ -508,7 +510,7 @@ def step a }.new @db.define_aggregator("accumulate", acc) - value = @db.get_first_value( "select accumulate(a) from foo" ) + value = @db.get_first_value("select accumulate(a) from foo") assert_equal 6, value end @@ -516,12 +518,16 @@ def test_authorizer_ok statements = [] @db.authorizer = Class.new { - def call action, a, b, c, d; true end + def call action, a, b, c, d + true + end }.new statements << @db.prepare("select 'fooooo'") @db.authorizer = Class.new { - def call action, a, b, c, d; 0 end + def call action, a, b, c, d + 0 + end }.new statements << @db.prepare("select 'fooooo'") ensure @@ -530,7 +536,9 @@ def call action, a, b, c, d; 0 end def test_authorizer_ignore @db.authorizer = Class.new { - def call action, a, b, c, d; nil end + def call action, a, b, c, d + nil + end }.new stmt = @db.prepare("select 'fooooo'") assert_nil stmt.step @@ -540,7 +548,9 @@ def call action, a, b, c, d; nil end def test_authorizer_fail @db.authorizer = Class.new { - def call action, a, b, c, d; false end + def call action, a, b, c, d + false + end }.new assert_raises(SQLite3::AuthorizationException) do @db.prepare("select 'fooooo'") @@ -549,7 +559,9 @@ def call action, a, b, c, d; false end def test_remove_auth @db.authorizer = Class.new { - def call action, a, b, c, d; false end + def call action, a, b, c, d + false + end }.new assert_raises(SQLite3::AuthorizationException) do @db.prepare("select 'fooooo'") @@ -571,18 +583,18 @@ def test_close_with_open_statements end def test_execute_with_empty_bind_params - assert_equal [['foo']], @db.execute("select 'foo'", []) + assert_equal [["foo"]], @db.execute("select 'foo'", []) end def test_query_with_named_bind_params - resultset = @db.query("select :n", {'n' => 'foo'}) - assert_equal [['foo']], resultset.to_a + resultset = @db.query("select :n", {"n" => "foo"}) + assert_equal [["foo"]], resultset.to_a ensure resultset.close if resultset end def test_execute_with_named_bind_params - assert_equal [['foo']], @db.execute("select :n", {'n' => 'foo'}) + assert_equal [["foo"]], @db.execute("select :n", {"n" => "foo"}) end def test_strict_mode @@ -590,12 +602,12 @@ def test_strict_mode skip("strict mode feature not available in #{SQLite3::SQLITE_VERSION}") end - db = SQLite3::Database.new(':memory:') - db.execute('create table numbers (val int);') + db = SQLite3::Database.new(":memory:") + db.execute("create table numbers (val int);") db.execute('create index index_numbers_nope ON numbers ("nope");') # nothing raised - db = SQLite3::Database.new(':memory:', :strict => true) - db.execute('create table numbers (val int);') + db = SQLite3::Database.new(":memory:", strict: true) + db.execute("create table numbers (val int);") error = assert_raises SQLite3::SQLException do db.execute('create index index_numbers_nope ON numbers ("nope");') end @@ -603,7 +615,7 @@ def test_strict_mode end def test_load_extension_with_nonstring_argument - db = SQLite3::Database.new(':memory:') + db = SQLite3::Database.new(":memory:") skip("extensions are not enabled") unless db.respond_to?(:load_extension) assert_raises(TypeError) { db.load_extension(1) } assert_raises(TypeError) { db.load_extension(Pathname.new("foo.so")) } @@ -621,7 +633,7 @@ def test_raw_float_infinity end def test_default_transaction_mode - tf = Tempfile.new 'database_default_transaction_mode' + tf = Tempfile.new "database_default_transaction_mode" SQLite3::Database.new(tf.path) do |db| db.execute("create table foo (score int)") db.execute("insert into foo values (?)", 1) @@ -631,7 +643,7 @@ def test_default_transaction_mode {mode: nil, read: true, write: true}, {mode: :deferred, read: true, write: true}, {mode: :immediate, read: true, write: false}, - {mode: :exclusive, read: false, write: false}, + {mode: :exclusive, read: false, write: false} ] test_cases.each do |item| @@ -640,16 +652,16 @@ def test_default_transaction_mode db.transaction do sql_for_read_test = "select * from foo" if item[:read] - assert_nothing_raised{ db2.execute(sql_for_read_test) } + assert_nothing_raised { db2.execute(sql_for_read_test) } else - assert_raises(SQLite3::BusyException){ db2.execute(sql_for_read_test) } + assert_raises(SQLite3::BusyException) { db2.execute(sql_for_read_test) } end sql_for_write_test = "insert into foo values (2)" if item[:write] - assert_nothing_raised{ db2.execute(sql_for_write_test) } + assert_nothing_raised { db2.execute(sql_for_write_test) } else - assert_raises(SQLite3::BusyException){ db2.execute(sql_for_write_test) } + assert_raises(SQLite3::BusyException) { db2.execute(sql_for_write_test) } end end ensure diff --git a/test/test_database_flags.rb b/test/test_database_flags.rb index 9a1205e2..5c405afc 100644 --- a/test/test_database_flags.rb +++ b/test/test_database_flags.rb @@ -1,24 +1,24 @@ -require 'helper' +require "helper" module SQLite3 class TestDatabaseFlags < SQLite3::TestCase def setup - File.unlink 'test-flags.db' if File.exist?('test-flags.db') - @db = SQLite3::Database.new('test-flags.db') + File.unlink "test-flags.db" if File.exist?("test-flags.db") + @db = SQLite3::Database.new("test-flags.db") @db.execute("CREATE TABLE foos (id integer)") @db.close end def teardown @db.close unless @db.closed? - File.unlink 'test-flags.db' if File.exist?('test-flags.db') + File.unlink "test-flags.db" if File.exist?("test-flags.db") end def test_open_database_flags_constants defined_to_date = [:READONLY, :READWRITE, :CREATE, :DELETEONCLOSE, - :EXCLUSIVE, :MAIN_DB, :TEMP_DB, :TRANSIENT_DB, - :MAIN_JOURNAL, :TEMP_JOURNAL, :SUBJOURNAL, - :MASTER_JOURNAL, :NOMUTEX, :FULLMUTEX] + :EXCLUSIVE, :MAIN_DB, :TEMP_DB, :TRANSIENT_DB, + :MAIN_JOURNAL, :TEMP_JOURNAL, :SUBJOURNAL, + :MASTER_JOURNAL, :NOMUTEX, :FULLMUTEX] if SQLite3::SQLITE_VERSION_NUMBER > 3007002 defined_to_date += [:AUTOPROXY, :SHAREDCACHE, :PRIVATECACHE, :WAL] end @@ -33,61 +33,61 @@ def test_open_database_flags_constants def test_open_database_flags_conflicts_with_readonly assert_raise(RuntimeError) do - @db = SQLite3::Database.new('test-flags.db', :flags => 2, :readonly => true) + @db = SQLite3::Database.new("test-flags.db", flags: 2, readonly: true) end end def test_open_database_flags_conflicts_with_readwrite assert_raise(RuntimeError) do - @db = SQLite3::Database.new('test-flags.db', :flags => 2, :readwrite => true) + @db = SQLite3::Database.new("test-flags.db", flags: 2, readwrite: true) end end def test_open_database_readonly_flags - @db = SQLite3::Database.new('test-flags.db', :flags => SQLite3::Constants::Open::READONLY) + @db = SQLite3::Database.new("test-flags.db", flags: SQLite3::Constants::Open::READONLY) assert @db.readonly? end def test_open_database_readwrite_flags - @db = SQLite3::Database.new('test-flags.db', :flags => SQLite3::Constants::Open::READWRITE) + @db = SQLite3::Database.new("test-flags.db", flags: SQLite3::Constants::Open::READWRITE) assert !@db.readonly? end def test_open_database_readonly_flags_cant_open - File.unlink 'test-flags.db' + File.unlink "test-flags.db" assert_raise(SQLite3::CantOpenException) do - @db = SQLite3::Database.new('test-flags.db', :flags => SQLite3::Constants::Open::READONLY) + @db = SQLite3::Database.new("test-flags.db", flags: SQLite3::Constants::Open::READONLY) end end def test_open_database_readwrite_flags_cant_open - File.unlink 'test-flags.db' + File.unlink "test-flags.db" assert_raise(SQLite3::CantOpenException) do - @db = SQLite3::Database.new('test-flags.db', :flags => SQLite3::Constants::Open::READWRITE) + @db = SQLite3::Database.new("test-flags.db", flags: SQLite3::Constants::Open::READWRITE) end end def test_open_database_misuse_flags assert_raise(SQLite3::MisuseException) do flags = SQLite3::Constants::Open::READONLY | SQLite3::Constants::Open::READWRITE # <== incompatible flags - @db = SQLite3::Database.new('test-flags.db', :flags => flags) + @db = SQLite3::Database.new("test-flags.db", flags: flags) end end def test_open_database_create_flags - File.unlink 'test-flags.db' + File.unlink "test-flags.db" flags = SQLite3::Constants::Open::READWRITE | SQLite3::Constants::Open::CREATE - @db = SQLite3::Database.new('test-flags.db', :flags => flags) do |db| + @db = SQLite3::Database.new("test-flags.db", flags: flags) do |db| db.execute("CREATE TABLE foos (id integer)") db.execute("INSERT INTO foos (id) VALUES (12)") end - assert File.exist?('test-flags.db') + assert File.exist?("test-flags.db") end def test_open_database_exotic_flags flags = SQLite3::Constants::Open::READWRITE | SQLite3::Constants::Open::CREATE exotic_flags = SQLite3::Constants::Open::NOMUTEX | SQLite3::Constants::Open::TEMP_DB - @db = SQLite3::Database.new('test-flags.db', :flags => flags | exotic_flags) + @db = SQLite3::Database.new("test-flags.db", flags: flags | exotic_flags) @db.execute("INSERT INTO foos (id) VALUES (12)") assert @db.changes == 1 end diff --git a/test/test_database_readonly.rb b/test/test_database_readonly.rb index def34b22..7e8d7bc5 100644 --- a/test/test_database_readonly.rb +++ b/test/test_database_readonly.rb @@ -1,33 +1,33 @@ -require 'helper' +require "helper" module SQLite3 class TestDatabaseReadonly < SQLite3::TestCase def setup - File.unlink 'test-readonly.db' if File.exist?('test-readonly.db') - @db = SQLite3::Database.new('test-readonly.db') + File.unlink "test-readonly.db" if File.exist?("test-readonly.db") + @db = SQLite3::Database.new("test-readonly.db") @db.execute("CREATE TABLE foos (id integer)") @db.close end def teardown @db.close unless @db.closed? - File.unlink 'test-readonly.db' if File.exist?('test-readonly.db') + File.unlink "test-readonly.db" if File.exist?("test-readonly.db") end def test_open_readonly_database - @db = SQLite3::Database.new('test-readonly.db', :readonly => true) + @db = SQLite3::Database.new("test-readonly.db", readonly: true) assert @db.readonly? end def test_open_readonly_not_exists_database - File.unlink 'test-readonly.db' + File.unlink "test-readonly.db" assert_raise(SQLite3::CantOpenException) do - @db = SQLite3::Database.new('test-readonly.db', :readonly => true) + @db = SQLite3::Database.new("test-readonly.db", readonly: true) end end def test_insert_readonly_database - @db = SQLite3::Database.new('test-readonly.db', :readonly => true) + @db = SQLite3::Database.new("test-readonly.db", readonly: true) assert_raise(SQLite3::ReadOnlyException) do @db.execute("INSERT INTO foos (id) VALUES (12)") end diff --git a/test/test_database_readwrite.rb b/test/test_database_readwrite.rb index f8485738..9f923b63 100644 --- a/test/test_database_readwrite.rb +++ b/test/test_database_readwrite.rb @@ -1,39 +1,39 @@ -require 'helper' +require "helper" module SQLite3 class TestDatabaseReadwrite < SQLite3::TestCase def setup - File.unlink 'test-readwrite.db' if File.exist?('test-readwrite.db') - @db = SQLite3::Database.new('test-readwrite.db') + File.unlink "test-readwrite.db" if File.exist?("test-readwrite.db") + @db = SQLite3::Database.new("test-readwrite.db") @db.execute("CREATE TABLE foos (id integer)") @db.close end def teardown @db.close unless @db.closed? - File.unlink 'test-readwrite.db' if File.exist?('test-readwrite.db') + File.unlink "test-readwrite.db" if File.exist?("test-readwrite.db") end def test_open_readwrite_database - @db = SQLite3::Database.new('test-readwrite.db', :readwrite => true) + @db = SQLite3::Database.new("test-readwrite.db", readwrite: true) assert !@db.readonly? end def test_open_readwrite_readonly_database assert_raise(RuntimeError) do - @db = SQLite3::Database.new('test-readwrite.db', :readwrite => true, :readonly => true) + @db = SQLite3::Database.new("test-readwrite.db", readwrite: true, readonly: true) end end def test_open_readwrite_not_exists_database - File.unlink 'test-readwrite.db' + File.unlink "test-readwrite.db" assert_raise(SQLite3::CantOpenException) do - @db = SQLite3::Database.new('test-readwrite.db', :readonly => true) + @db = SQLite3::Database.new("test-readwrite.db", readonly: true) end end def test_insert_readwrite_database - @db = SQLite3::Database.new('test-readwrite.db', :readwrite => true) + @db = SQLite3::Database.new("test-readwrite.db", readwrite: true) @db.execute("INSERT INTO foos (id) VALUES (12)") assert @db.changes == 1 end diff --git a/test/test_deprecated.rb b/test/test_deprecated.rb index 1248cb9a..e16601db 100644 --- a/test/test_deprecated.rb +++ b/test/test_deprecated.rb @@ -1,4 +1,4 @@ -require 'helper' +require "helper" module SQLite3 class TestDeprecated < SQLite3::TestCase @@ -6,8 +6,8 @@ def setup super @warn_before = $-w $-w = false - @db = SQLite3::Database.new(':memory:') - @db.execute 'CREATE TABLE test_table (name text, age int)' + @db = SQLite3::Database.new(":memory:") + @db.execute "CREATE TABLE test_table (name text, age int)" end def teardown @@ -17,7 +17,7 @@ def teardown end def test_query_with_many_bind_params_not_nil - rs = @db.query('select ?, ?', 1, 2) + rs = @db.query("select ?, ?", 1, 2) assert_equal [[1, 2]], rs.to_a rs.close end @@ -34,7 +34,7 @@ def test_query_with_many_bind_params def test_query_with_nil_bind_params rs = @db.query("select 'foo'", nil) - assert_equal [['foo']], rs.to_a + assert_equal [["foo"]], rs.to_a rs.close end @@ -43,7 +43,7 @@ def test_execute_with_many_bind_params end def test_execute_with_nil_bind_params - assert_equal [['foo']], @db.execute("select 'foo'", nil) + assert_equal [["foo"]], @db.execute("select 'foo'", nil) end end end diff --git a/test/test_encoding.rb b/test/test_encoding.rb index a294a390..33c72c67 100644 --- a/test/test_encoding.rb +++ b/test/test_encoding.rb @@ -1,14 +1,12 @@ -# -*- coding: utf-8 -*- - -require 'helper' +require "helper" module SQLite3 class TestEncoding < SQLite3::TestCase def setup - @db = SQLite3::Database.new(':memory:') + @db = SQLite3::Database.new(":memory:") @create = "create table ex(id int, data string)" @insert = "insert into ex(id, data) values (?, ?)" - @db.execute(@create); + @db.execute(@create) end def teardown @@ -18,12 +16,12 @@ def teardown def test_select_encoding_on_utf_16 str = "foo" utf16 = ([1].pack("I") == [1].pack("N")) ? "UTF-16BE" : "UTF-16LE" - db = SQLite3::Database.new(':memory:'.encode(utf16)) + db = SQLite3::Database.new(":memory:".encode(utf16)) db.execute @create db.execute "insert into ex (id, data) values (1, \"#{str}\")" - stmt = db.prepare 'select * from ex where data = ?' - ['US-ASCII', utf16, 'EUC-JP', 'UTF-8'].each do |enc| + stmt = db.prepare "select * from ex where data = ?" + ["US-ASCII", utf16, "EUC-JP", "UTF-8"].each do |enc| stmt.bind_param 1, str.encode(enc) assert_equal 1, stmt.to_a.length stmt.reset! @@ -34,11 +32,11 @@ def test_select_encoding_on_utf_16 def test_insert_encoding str = "foo" utf16 = ([1].pack("I") == [1].pack("N")) ? "UTF-16BE" : "UTF-16LE" - db = SQLite3::Database.new(':memory:'.encode(utf16)) + db = SQLite3::Database.new(":memory:".encode(utf16)) db.execute @create stmt = db.prepare @insert - ['US-ASCII', utf16, 'EUC-JP', 'UTF-8'].each_with_index do |enc,i| + ["US-ASCII", utf16, "EUC-JP", "UTF-8"].each_with_index do |enc, i| stmt.bind_param 1, i stmt.bind_param 2, str.encode(enc) stmt.to_a @@ -46,7 +44,7 @@ def test_insert_encoding end stmt.close - db.execute('select data from ex').flatten.each do |s| + db.execute("select data from ex").flatten.each do |s| assert_equal str, s end end @@ -58,16 +56,16 @@ def test_default_internal_is_honored before_enc = Encoding.default_internal str = "壁に耳あり、障子に目あり" - stmt = @db.prepare('insert into ex(data) values (?)') + stmt = @db.prepare("insert into ex(data) values (?)") stmt.bind_param 1, str stmt.step stmt.close - Encoding.default_internal = 'EUC-JP' - string = @db.execute('select data from ex').first.first + Encoding.default_internal = "EUC-JP" + string = @db.execute("select data from ex").first.first assert_equal Encoding.default_internal, string.encoding - assert_equal str.encode('EUC-JP'), string + assert_equal str.encode("EUC-JP"), string assert_equal str, string.encode(str.encoding) ensure Encoding.default_internal = before_enc @@ -76,58 +74,58 @@ def test_default_internal_is_honored def test_blob_is_binary str = "猫舌" - @db.execute('create table foo(data text)') - stmt = @db.prepare('insert into foo(data) values (?)') + @db.execute("create table foo(data text)") + stmt = @db.prepare("insert into foo(data) values (?)") stmt.bind_param(1, SQLite3::Blob.new(str)) stmt.step stmt.close - string = @db.execute('select data from foo').first.first - assert_equal Encoding.find('ASCII-8BIT'), string.encoding - assert_equal str, string.force_encoding('UTF-8') + string = @db.execute("select data from foo").first.first + assert_equal Encoding.find("ASCII-8BIT"), string.encoding + assert_equal str, string.force_encoding("UTF-8") end def test_blob_is_ascii8bit str = "猫舌" - @db.execute('create table foo(data text)') - stmt = @db.prepare('insert into foo(data) values (?)') + @db.execute("create table foo(data text)") + stmt = @db.prepare("insert into foo(data) values (?)") stmt.bind_param(1, str.dup.force_encoding("ASCII-8BIT")) stmt.step stmt.close - string = @db.execute('select data from foo').first.first - assert_equal Encoding.find('ASCII-8BIT'), string.encoding - assert_equal str, string.force_encoding('UTF-8') + string = @db.execute("select data from foo").first.first + assert_equal Encoding.find("ASCII-8BIT"), string.encoding + assert_equal str, string.force_encoding("UTF-8") end def test_blob_with_eucjp str = "猫舌".encode("EUC-JP") - @db.execute('create table foo(data text)') - stmt = @db.prepare('insert into foo(data) values (?)') + @db.execute("create table foo(data text)") + stmt = @db.prepare("insert into foo(data) values (?)") stmt.bind_param(1, SQLite3::Blob.new(str)) stmt.step stmt.close - string = @db.execute('select data from foo').first.first - assert_equal Encoding.find('ASCII-8BIT'), string.encoding - assert_equal str, string.force_encoding('EUC-JP') + string = @db.execute("select data from foo").first.first + assert_equal Encoding.find("ASCII-8BIT"), string.encoding + assert_equal str, string.force_encoding("EUC-JP") end def test_db_with_eucjp - db = SQLite3::Database.new(':memory:'.encode('EUC-JP')) - assert_equal(Encoding.find('UTF-8'), db.encoding) + db = SQLite3::Database.new(":memory:".encode("EUC-JP")) + assert_equal(Encoding.find("UTF-8"), db.encoding) end def test_db_with_utf16 utf16 = ([1].pack("I") == [1].pack("N")) ? "UTF-16BE" : "UTF-16LE" - db = SQLite3::Database.new(':memory:'.encode(utf16)) + db = SQLite3::Database.new(":memory:".encode(utf16)) assert_equal(Encoding.find(utf16), db.encoding) end def test_statement_eucjp str = "猫舌" - @db.execute("insert into ex(data) values ('#{str}')".encode('EUC-JP')) + @db.execute("insert into ex(data) values ('#{str}')".encode("EUC-JP")) row = @db.execute("select data from ex") assert_equal @db.encoding, row.first.first.encoding assert_equal str, row.first.first @@ -154,12 +152,11 @@ def test_utf_8 end def test_euc_jp - str = "猫舌".encode('EUC-JP') + str = "猫舌".encode("EUC-JP") @db.execute(@insert, [10, str]) row = @db.execute("select data from ex") assert_equal @db.encoding, row.first.first.encoding - assert_equal str.encode('UTF-8'), row.first.first + assert_equal str.encode("UTF-8"), row.first.first end - end end diff --git a/test/test_integration.rb b/test/test_integration.rb index d5ea3a53..6008a56c 100644 --- a/test/test_integration.rb +++ b/test/test_integration.rb @@ -1,4 +1,4 @@ -require 'helper' +require "helper" class TC_Database_Integration < SQLite3::TestCase def setup @@ -22,7 +22,7 @@ def test_table_info_with_type_translation_active def test_table_info_with_defaults_for_version_3_3_8_and_higher @db.transaction do @db.execute "create table defaults_test ( a string default NULL, b string default 'Hello', c string default '--- []\n' )" - data = @db.table_info( "defaults_test" ) + data = @db.table_info("defaults_test") assert_equal({"name" => "a", "type" => "string", "dflt_value" => nil, "notnull" => 0, "cid" => 0, "pk" => 0}, data[0]) assert_equal({"name" => "b", "type" => "string", "dflt_value" => "Hello", "notnull" => 0, "cid" => 1, "pk" => 0}, @@ -35,7 +35,7 @@ def test_table_info_with_defaults_for_version_3_3_8_and_higher def test_table_info_without_defaults_for_version_3_3_8_and_higher @db.transaction do @db.execute "create table no_defaults_test ( a integer default 1, b integer )" - data = @db.table_info( "no_defaults_test" ) + data = @db.table_info("no_defaults_test") assert_equal({"name" => "a", "type" => "integer", "dflt_value" => "1", "notnull" => 0, "cid" => 0, "pk" => 0}, data[0]) assert_equal({"name" => "b", "type" => "integer", "dflt_value" => nil, "notnull" => 0, "cid" => 1, "pk" => 0}, @@ -44,31 +44,32 @@ def test_table_info_without_defaults_for_version_3_3_8_and_higher end def test_complete_fail - assert !@db.complete?( "select * from foo" ) + assert !@db.complete?("select * from foo") end + def test_complete_success - assert @db.complete?( "select * from foo;" ) + assert @db.complete?("select * from foo;") end # FIXME: do people really need UTF16 sql statements? - #def test_complete_fail_utf16 + # def test_complete_fail_utf16 # assert !@db.complete?( "select * from foo".to_utf16(false), true ) - #end + # end # FIXME: do people really need UTF16 sql statements? - #def test_complete_success_utf16 + # def test_complete_success_utf16 # assert @db.complete?( "select * from foo;".to_utf16(true), true ) - #end + # end def test_errmsg assert_equal "not an error", @db.errmsg end # FIXME: do people really need UTF16 error messages? - #def test_errmsg_utf16 + # def test_errmsg_utf16 # msg = Iconv.conv('UTF-16', 'UTF-8', 'not an error') # assert_equal msg, @db.errmsg(true) - #end + # end def test_errcode assert_equal 0, @db.errcode @@ -82,38 +83,38 @@ def test_trace end def test_authorizer_okay - @db.authorizer { |type,a,b,c,d| 0 } + @db.authorizer { |type, a, b, c, d| 0 } rows = @db.execute "select * from foo" assert_equal 3, rows.length end def test_authorizer_error - @db.authorizer { |type,a,b,c,d| 1 } - assert_raise( SQLite3::AuthorizationException ) do + @db.authorizer { |type, a, b, c, d| 1 } + assert_raise(SQLite3::AuthorizationException) do @db.execute "select * from foo" end end def test_authorizer_silent - @db.authorizer { |type,a,b,c,d| 2 } + @db.authorizer { |type, a, b, c, d| 2 } rows = @db.execute "select * from foo" assert rows.empty? end def test_prepare_invalid_syntax - assert_raise( SQLite3::SQLException ) do + assert_raise(SQLite3::SQLException) do @db.prepare "select from foo" end end def test_prepare_invalid_column - assert_raise( SQLite3::SQLException ) do + assert_raise(SQLite3::SQLException) do @db.prepare "select k from foo" end end def test_prepare_invalid_table - assert_raise( SQLite3::SQLException ) do + assert_raise(SQLite3::SQLException) do @db.prepare "select * from barf" end end @@ -134,111 +135,111 @@ def test_prepare_with_block end def test_execute_no_block_no_bind_no_match - rows = @db.execute( "select * from foo where a > 100" ) + rows = @db.execute("select * from foo where a > 100") assert rows.empty? end def test_execute_with_block_no_bind_no_match called = false - @db.execute( "select * from foo where a > 100" ) do |row| + @db.execute("select * from foo where a > 100") do |row| called = true end assert !called end def test_execute_no_block_with_bind_no_match - rows = @db.execute( "select * from foo where a > ?", 100 ) + rows = @db.execute("select * from foo where a > ?", 100) assert rows.empty? end def test_execute_with_block_with_bind_no_match called = false - @db.execute( "select * from foo where a > ?", 100 ) do |row| + @db.execute("select * from foo where a > ?", 100) do |row| called = true end assert !called end def test_execute_no_block_no_bind_with_match - rows = @db.execute( "select * from foo where a = 1" ) + rows = @db.execute("select * from foo where a = 1") assert_equal 1, rows.length end def test_execute_with_block_no_bind_with_match called = 0 - @db.execute( "select * from foo where a = 1" ) do |row| + @db.execute("select * from foo where a = 1") do |row| called += 1 end assert_equal 1, called end def test_execute_no_block_with_bind_with_match - rows = @db.execute( "select * from foo where a = ?", 1 ) + rows = @db.execute("select * from foo where a = ?", 1) assert_equal 1, rows.length end def test_execute_with_block_with_bind_with_match called = 0 - @db.execute( "select * from foo where a = ?", 1 ) do |row| + @db.execute("select * from foo where a = ?", 1) do |row| called += 1 end assert_equal 1, called end def test_execute2_no_block_no_bind_no_match - columns, *rows = @db.execute2( "select * from foo where a > 100" ) + columns, *rows = @db.execute2("select * from foo where a > 100") assert rows.empty? - assert_equal [ "a", "b" ], columns + assert_equal ["a", "b"], columns end def test_execute2_with_block_no_bind_no_match called = 0 - @db.execute2( "select * from foo where a > 100" ) do |row| - assert [ "a", "b" ], row unless called == 0 + @db.execute2("select * from foo where a > 100") do |row| + assert ["a", "b"], row unless called == 0 called += 1 end assert_equal 1, called end def test_execute2_no_block_with_bind_no_match - columns, *rows = @db.execute2( "select * from foo where a > ?", 100 ) + columns, *rows = @db.execute2("select * from foo where a > ?", 100) assert rows.empty? - assert_equal [ "a", "b" ], columns + assert_equal ["a", "b"], columns end def test_execute2_with_block_with_bind_no_match called = 0 - @db.execute2( "select * from foo where a > ?", 100 ) do |row| - assert_equal [ "a", "b" ], row unless called == 0 + @db.execute2("select * from foo where a > ?", 100) do |row| + assert_equal ["a", "b"], row unless called == 0 called += 1 end assert_equal 1, called end def test_execute2_no_block_no_bind_with_match - columns, *rows = @db.execute2( "select * from foo where a = 1" ) + columns, *rows = @db.execute2("select * from foo where a = 1") assert_equal 1, rows.length - assert_equal [ "a", "b" ], columns + assert_equal ["a", "b"], columns end def test_execute2_with_block_no_bind_with_match called = 0 - @db.execute2( "select * from foo where a = 1" ) do |row| - assert_equal [ 1, "foo" ], row unless called == 0 + @db.execute2("select * from foo where a = 1") do |row| + assert_equal [1, "foo"], row unless called == 0 called += 1 end assert_equal 2, called end def test_execute2_no_block_with_bind_with_match - columns, *rows = @db.execute2( "select * from foo where a = ?", 1 ) + columns, *rows = @db.execute2("select * from foo where a = ?", 1) assert_equal 1, rows.length - assert_equal [ "a", "b" ], columns + assert_equal ["a", "b"], columns end def test_execute2_with_block_with_bind_with_match called = 0 - @db.execute2( "select * from foo where a = ?", 1 ) do + @db.execute2("select * from foo where a = ?", 1) do called += 1 end assert_equal 2, called @@ -257,30 +258,30 @@ def test_execute_batch_no_bind insert into bar values ( 'seven', 8, 'nine' ); SQL end - rows = @db.execute( "select * from bar" ) + rows = @db.execute("select * from bar") assert_equal 3, rows.length end def test_execute_batch_with_bind - @db.execute_batch( <<-SQL, [1] ) + @db.execute_batch(<<-SQL, [1]) create table bar ( a, b, c ); insert into bar values ( 'one', 2, ? ); insert into bar values ( 'four', 5, ? ); insert into bar values ( 'seven', 8, ? ); SQL - rows = @db.execute( "select * from bar" ).map { |a,b,c| c } + rows = @db.execute("select * from bar").map { |a, b, c| c } assert_equal [1, 1, 1], rows end def test_query_no_block_no_bind_no_match - result = @db.query( "select * from foo where a > 100" ) + result = @db.query("select * from foo where a > 100") assert_nil result.next result.close end def test_query_with_block_no_bind_no_match r = nil - @db.query( "select * from foo where a > 100" ) do |result| + @db.query("select * from foo where a > 100") do |result| assert_nil result.next r = result end @@ -288,14 +289,14 @@ def test_query_with_block_no_bind_no_match end def test_query_no_block_with_bind_no_match - result = @db.query( "select * from foo where a > ?", 100 ) + result = @db.query("select * from foo where a > ?", 100) assert_nil result.next result.close end def test_query_with_block_with_bind_no_match r = nil - @db.query( "select * from foo where a > ?", 100 ) do |result| + @db.query("select * from foo where a > ?", 100) do |result| assert_nil result.next r = result end @@ -303,7 +304,7 @@ def test_query_with_block_with_bind_no_match end def test_query_no_block_no_bind_with_match - result = @db.query( "select * from foo where a = 1" ) + result = @db.query("select * from foo where a = 1") assert_not_nil result.next assert_nil result.next result.close @@ -311,7 +312,7 @@ def test_query_no_block_no_bind_with_match def test_query_with_block_no_bind_with_match r = nil - @db.query( "select * from foo where a = 1" ) do |result| + @db.query("select * from foo where a = 1") do |result| assert_not_nil result.next assert_nil result.next r = result @@ -320,7 +321,7 @@ def test_query_with_block_no_bind_with_match end def test_query_no_block_with_bind_with_match - result = @db.query( "select * from foo where a = ?", 1 ) + result = @db.query("select * from foo where a = ?", 1) assert_not_nil result.next assert_nil result.next result.close @@ -328,7 +329,7 @@ def test_query_no_block_with_bind_with_match def test_query_with_block_with_bind_with_match r = nil - @db.query( "select * from foo where a = ?", 1 ) do |result| + @db.query("select * from foo where a = ?", 1) do |result| assert_not_nil result.next assert_nil result.next r = result @@ -337,54 +338,54 @@ def test_query_with_block_with_bind_with_match end def test_get_first_row_no_bind_no_match - result = @db.get_first_row( "select * from foo where a=100" ) + result = @db.get_first_row("select * from foo where a=100") assert_nil result end def test_get_first_row_no_bind_with_match - result = @db.get_first_row( "select * from foo where a=1" ) - assert_equal [ 1, "foo" ], result + result = @db.get_first_row("select * from foo where a=1") + assert_equal [1, "foo"], result end def test_get_first_row_with_bind_no_match - result = @db.get_first_row( "select * from foo where a=?", 100 ) + result = @db.get_first_row("select * from foo where a=?", 100) assert_nil result end def test_get_first_row_with_bind_with_match - result = @db.get_first_row( "select * from foo where a=?", 1 ) - assert_equal [ 1, "foo" ], result + result = @db.get_first_row("select * from foo where a=?", 1) + assert_equal [1, "foo"], result end def test_get_first_value_no_bind_no_match - result = @db.get_first_value( "select b, a from foo where a=100" ) + result = @db.get_first_value("select b, a from foo where a=100") assert_nil result @db.results_as_hash = true - result = @db.get_first_value( "select b, a from foo where a=100" ) + result = @db.get_first_value("select b, a from foo where a=100") assert_nil result end def test_get_first_value_no_bind_with_match - result = @db.get_first_value( "select b, a from foo where a=1" ) + result = @db.get_first_value("select b, a from foo where a=1") assert_equal "foo", result @db.results_as_hash = true - result = @db.get_first_value( "select b, a from foo where a=1" ) + result = @db.get_first_value("select b, a from foo where a=1") assert_equal "foo", result end def test_get_first_value_with_bind_no_match - result = @db.get_first_value( "select b, a from foo where a=?", 100 ) + result = @db.get_first_value("select b, a from foo where a=?", 100) assert_nil result @db.results_as_hash = true - result = @db.get_first_value( "select b, a from foo where a=?", 100 ) + result = @db.get_first_value("select b, a from foo where a=?", 100) assert_nil result end def test_get_first_value_with_bind_with_match - result = @db.get_first_value( "select b, a from foo where a=?", 1 ) + result = @db.get_first_value("select b, a from foo where a=?", 1) assert_equal "foo", result @db.results_as_hash = true - result = @db.get_first_value( "select b, a from foo where a=?", 1 ) + result = @db.get_first_value("select b, a from foo where a=?", 1) assert_equal "foo", result end @@ -410,7 +411,7 @@ def test_total_changes end def test_transaction_nest - assert_raise( SQLite3::SQLException ) do + assert_raise(SQLite3::SQLException) do @db.transaction do @db.transaction do end @@ -445,7 +446,7 @@ def test_transaction_commit end def test_transaction_rollback_in_block - assert_raise( SQLite3::SQLException ) do + assert_raise(SQLite3::SQLException) do @db.transaction do @db.rollback end @@ -453,7 +454,7 @@ def test_transaction_rollback_in_block end def test_transaction_commit_in_block - assert_raise( SQLite3::SQLException ) do + assert_raise(SQLite3::SQLException) do @db.transaction do @db.commit end @@ -470,38 +471,38 @@ def test_transaction_active def test_transaction_implicit_rollback assert !@db.transaction_active? - @db.transaction - @db.execute('create table bar (x CHECK(1 = 0))') + @db.transaction + @db.execute("create table bar (x CHECK(1 = 0))") assert @db.transaction_active? - assert_raises( SQLite3::ConstraintException ) do + assert_raises(SQLite3::ConstraintException) do @db.execute("insert or rollback into bar (x) VALUES ('x')") end assert !@db.transaction_active? end def test_interrupt - @db.create_function( "abort", 1 ) do |func,x| + @db.create_function("abort", 1) do |func, x| @db.interrupt func.result = x end - assert_raise( SQLite3::InterruptException ) do + assert_raise(SQLite3::InterruptException) do @db.execute "select abort(a) from foo" end end def test_create_function - @db.create_function( "munge", 1 ) do |func,x| + @db.create_function("munge", 1) do |func, x| func.result = ">>>#{x}<<<" end - value = @db.get_first_value( "select munge(b) from foo where a=1" ) - assert_match( />>>.*<<>>.*<<= 1000 + assert time.real * 1000 >= 1000 end end diff --git a/test/test_integration_resultset.rb b/test/test_integration_resultset.rb index 444f83f9..479ca357 100644 --- a/test/test_integration_resultset.rb +++ b/test/test_integration_resultset.rb @@ -1,4 +1,4 @@ -require 'helper' +require "helper" class TC_ResultSet < SQLite3::TestCase def setup @@ -9,7 +9,7 @@ def setup @db.execute "insert into foo ( b ) values ( 'bar' )" @db.execute "insert into foo ( b ) values ( 'baz' )" end - @stmt = @db.prepare( "select * from foo where a in ( ?, ? )" ) + @stmt = @db.prepare("select * from foo where a in ( ?, ? )") @result = @stmt.execute end @@ -31,62 +31,62 @@ def test_reset_used def test_reset_with_bind @result.to_a - assert_nothing_raised { @result.reset( 1, 2 ) } + assert_nothing_raised { @result.reset(1, 2) } assert_equal 2, @result.to_a.length end def test_eof_inner - @result.reset( 1 ) + @result.reset(1) assert !@result.eof? end def test_eof_edge - @result.reset( 1 ) + @result.reset(1) @result.next # to first row @result.next # to end of result set assert @result.eof? end def test_next_eof - @result.reset( 1 ) + @result.reset(1) assert_not_nil @result.next assert_nil @result.next end def test_next_no_type_translation_no_hash - @result.reset( 1 ) - assert_equal [ 1, "foo" ], @result.next + @result.reset(1) + assert_equal [1, "foo"], @result.next end def test_next_type_translation - @result.reset( 1 ) - assert_equal [ 1, "foo" ], @result.next + @result.reset(1) + assert_equal [1, "foo"], @result.next end def test_next_type_translation_with_untyped_column - @db.query( "select count(*) from foo" ) do |result| + @db.query("select count(*) from foo") do |result| assert_equal [3], result.next end end def test_type_translation_with_null_column - time = '1974-07-25 14:39:00' + time = "1974-07-25 14:39:00" @db.execute "create table bar ( a integer, b time, c string )" @db.execute "insert into bar (a, b, c) values (NULL, '#{time}', 'hello')" @db.execute "insert into bar (a, b, c) values (1, NULL, 'hello')" @db.execute "insert into bar (a, b, c) values (2, '#{time}', NULL)" - @db.query( "select * from bar" ) do |result| - assert_equal [nil, time, 'hello'], result.next - assert_equal [1, nil, 'hello'], result.next + @db.query("select * from bar") do |result| + assert_equal [nil, time, "hello"], result.next + assert_equal [1, nil, "hello"], result.next assert_equal [2, time, nil], result.next end end def test_real_translation - @db.execute('create table foo_real(a real)') - @db.execute('insert into foo_real values (42)' ) - @db.query('select a, sum(a), typeof(a), typeof(sum(a)) from foo_real') do |result| + @db.execute("create table foo_real(a real)") + @db.execute("insert into foo_real values (42)") + @db.query("select a, sum(a), typeof(a), typeof(sum(a)) from foo_real") do |result| result = result.next assert result[0].is_a?(Float) assert result[1].is_a?(Float) @@ -97,46 +97,46 @@ def test_real_translation def test_next_results_as_hash @db.results_as_hash = true - @result.reset( 1 ) + @result.reset(1) hash = @result.next - assert_equal( { "a" => 1, "b" => "foo" }, - hash ) + assert_equal({"a" => 1, "b" => "foo"}, + hash) assert_equal hash[@result.columns[0]], 1 assert_equal hash[@result.columns[1]], "foo" end def test_each called = 0 - @result.reset( 1, 2 ) + @result.reset(1, 2) @result.each { |row| called += 1 } assert_equal 2, called end def test_enumerable - @result.reset( 1, 2 ) + @result.reset(1, 2) assert_equal 2, @result.to_a.length end def test_types - assert_equal [ "integer", "text" ], @result.types + assert_equal ["integer", "text"], @result.types end def test_columns - assert_equal [ "a", "b" ], @result.columns + assert_equal ["a", "b"], @result.columns end def test_close - stmt = @db.prepare( "select * from foo" ) + stmt = @db.prepare("select * from foo") result = stmt.execute assert !result.closed? result.close assert result.closed? assert stmt.closed? - assert_raise( SQLite3::Exception ) { result.reset } - assert_raise( SQLite3::Exception ) { result.next } - assert_raise( SQLite3::Exception ) { result.each } - assert_raise( SQLite3::Exception ) { result.close } - assert_raise( SQLite3::Exception ) { result.types } - assert_raise( SQLite3::Exception ) { result.columns } + assert_raise(SQLite3::Exception) { result.reset } + assert_raise(SQLite3::Exception) { result.next } + assert_raise(SQLite3::Exception) { result.each } + assert_raise(SQLite3::Exception) { result.close } + assert_raise(SQLite3::Exception) { result.types } + assert_raise(SQLite3::Exception) { result.columns } end end diff --git a/test/test_integration_statement.rb b/test/test_integration_statement.rb index 759941f3..0ab8c4af 100644 --- a/test/test_integration_statement.rb +++ b/test/test_integration_statement.rb @@ -1,4 +1,4 @@ -require 'helper' +require "helper" class TC_Statement < SQLite3::TestCase def setup @@ -9,7 +9,7 @@ def setup @db.execute "insert into foo ( b ) values ( 'bar' )" @db.execute "insert into foo ( b ) values ( 'baz' )" end - @stmt = @db.prepare( "select * from foo where a in ( ?, :named )" ) + @stmt = @db.prepare("select * from foo where a in ( ?, :named )") end def teardown @@ -23,7 +23,7 @@ def test_remainder_empty def test_remainder_nonempty called = false - @db.prepare( "select * from foo;\n blah" ) do |stmt| + @db.prepare("select * from foo;\n blah") do |stmt| called = true assert_equal "\n blah", stmt.remainder end @@ -51,26 +51,26 @@ def test_bind_params_hash_without_colon end def test_bind_params_hash_as_symbol - @stmt.bind_params :named => 2 + @stmt.bind_params named: 2 assert_equal 1, @stmt.execute!.length end def test_bind_params_mixed - @stmt.bind_params( 1, ":named" => 2 ) + @stmt.bind_params(1, ":named" => 2) assert_equal 2, @stmt.execute!.length end def test_bind_param_by_index - @stmt.bind_params( 1, 2 ) + @stmt.bind_params(1, 2) assert_equal 2, @stmt.execute!.length end def test_bind_param_by_name_bad - assert_raise( SQLite3::Exception ) { @stmt.bind_param( "@named", 2 ) } + assert_raise(SQLite3::Exception) { @stmt.bind_param("@named", 2) } end def test_bind_param_by_name_good - @stmt.bind_param( ":named", 2 ) + @stmt.bind_param(":named", 2) assert_equal 1, @stmt.execute!.length end @@ -80,9 +80,9 @@ def test_bind_param_with_various_types @db.execute "insert into all_types ( b, c, d ) values ( 1.5, 'hello', 68719476735 )" end - assert_equal 1, @db.execute( "select * from all_types where b = ?", 1.5 ).length - assert_equal 1, @db.execute( "select * from all_types where c = ?", 'hello').length - assert_equal 1, @db.execute( "select * from all_types where d = ?", 68719476735).length + assert_equal 1, @db.execute("select * from all_types where b = ?", 1.5).length + assert_equal 1, @db.execute("select * from all_types where c = ?", "hello").length + assert_equal 1, @db.execute("select * from all_types where d = ?", 68719476735).length end def test_execute_no_bind_no_block @@ -90,7 +90,7 @@ def test_execute_no_bind_no_block end def test_execute_with_bind_no_block - assert_instance_of SQLite3::ResultSet, @stmt.execute( 1, 2 ) + assert_instance_of SQLite3::ResultSet, @stmt.execute(1, 2) end def test_execute_no_bind_with_block @@ -101,14 +101,14 @@ def test_execute_no_bind_with_block def test_execute_with_bind_with_block called = 0 - @stmt.execute( 1, 2 ) { |row| called += 1 } + @stmt.execute(1, 2) { |row| called += 1 } assert_equal 1, called end def test_reexecute - r = @stmt.execute( 1, 2 ) + r = @stmt.execute(1, 2) assert_equal 2, r.to_a.length - assert_nothing_raised { r = @stmt.execute( 1, 2 ) } + assert_nothing_raised { r = @stmt.execute(1, 2) } assert_equal 2, r.to_a.length end @@ -117,7 +117,7 @@ def test_execute_bang_no_bind_no_block end def test_execute_bang_with_bind_no_block - assert_equal 2, @stmt.execute!( 1, 2 ).length + assert_equal 2, @stmt.execute!(1, 2).length end def test_execute_bang_no_bind_with_block @@ -128,7 +128,7 @@ def test_execute_bang_no_bind_with_block def test_execute_bang_with_bind_with_block called = 0 - @stmt.execute!( 1, 2 ) { |row| called += 1 } + @stmt.execute!(1, 2) { |row| called += 1 } assert_equal 2, called end @@ -141,9 +141,9 @@ def test_columns def test_columns_computed called = false - @db.prepare( "select count(*) from foo" ) do |stmt| + @db.prepare("select count(*) from foo") do |stmt| called = true - assert_equal [ "count(*)" ], stmt.columns + assert_equal ["count(*)"], stmt.columns end assert called end @@ -157,37 +157,37 @@ def test_types def test_types_computed called = false - @db.prepare( "select count(*) from foo" ) do |stmt| + @db.prepare("select count(*) from foo") do |stmt| called = true - assert_equal [ nil ], stmt.types + assert_equal [nil], stmt.types end assert called end def test_close - stmt = @db.prepare( "select * from foo" ) + stmt = @db.prepare("select * from foo") assert !stmt.closed? stmt.close assert stmt.closed? - assert_raise( SQLite3::Exception ) { stmt.execute } - assert_raise( SQLite3::Exception ) { stmt.execute! } - assert_raise( SQLite3::Exception ) { stmt.close } - assert_raise( SQLite3::Exception ) { stmt.bind_params 5 } - assert_raise( SQLite3::Exception ) { stmt.bind_param 1, 5 } - assert_raise( SQLite3::Exception ) { stmt.columns } - assert_raise( SQLite3::Exception ) { stmt.types } + assert_raise(SQLite3::Exception) { stmt.execute } + assert_raise(SQLite3::Exception) { stmt.execute! } + assert_raise(SQLite3::Exception) { stmt.close } + assert_raise(SQLite3::Exception) { stmt.bind_params 5 } + assert_raise(SQLite3::Exception) { stmt.bind_param 1, 5 } + assert_raise(SQLite3::Exception) { stmt.columns } + assert_raise(SQLite3::Exception) { stmt.types } end def test_committing_tx_with_statement_active called = false - @db.prepare( "select count(*) from foo" ) do |stmt| + @db.prepare("select count(*) from foo") do |stmt| called = true count = stmt.execute!.first.first.to_i @db.transaction do @db.execute "insert into foo ( b ) values ( 'hello' )" end new_count = stmt.execute!.first.first.to_i - assert_equal new_count, count+1 + assert_equal new_count, count + 1 end assert called end diff --git a/test/test_pragmas.rb b/test/test_pragmas.rb index 504e7091..10848c75 100644 --- a/test/test_pragmas.rb +++ b/test/test_pragmas.rb @@ -1,4 +1,4 @@ -require 'helper' +require "helper" module SQLite3 class TestPragmas < SQLite3::TestCase diff --git a/test/test_resource_cleanup.rb b/test/test_resource_cleanup.rb index ec32c929..fa23a0ac 100644 --- a/test/test_resource_cleanup.rb +++ b/test/test_resource_cleanup.rb @@ -5,15 +5,15 @@ module SQLite3 class TestResourceCleanup < SQLite3::TestCase def test_cleanup_unclosed_database_object 100.times do - SQLite3::Database.new(':memory:') + SQLite3::Database.new(":memory:") end end def test_cleanup_unclosed_statement_object 100.times do - db = SQLite3::Database.new(':memory:') - db.execute('create table foo(text BLOB)') - db.prepare('select * from foo') + db = SQLite3::Database.new(":memory:") + db.execute("create table foo(text BLOB)") + db.prepare("select * from foo") end end diff --git a/test/test_result_set.rb b/test/test_result_set.rb index f16ffdf6..2d3398e1 100644 --- a/test/test_result_set.rb +++ b/test/test_result_set.rb @@ -1,9 +1,9 @@ -require 'helper' +require "helper" module SQLite3 class TestResultSet < SQLite3::TestCase def setup - @db = SQLite3::Database.new ':memory:' + @db = SQLite3::Database.new ":memory:" super end @@ -14,32 +14,32 @@ def teardown def test_each_hash @db.execute "create table foo ( a integer primary key, b text )" - list = ('a'..'z').to_a + list = ("a".."z").to_a list.each do |t| @db.execute "insert into foo (b) values (\"#{t}\")" end - rs = @db.prepare('select * from foo').execute + rs = @db.prepare("select * from foo").execute rs.each_hash do |hash| - assert_equal list[hash['a'] - 1], hash['b'] + assert_equal list[hash["a"] - 1], hash["b"] end rs.close end def test_next_hash @db.execute "create table foo ( a integer primary key, b text )" - list = ('a'..'z').to_a + list = ("a".."z").to_a list.each do |t| @db.execute "insert into foo (b) values (\"#{t}\")" end - rs = @db.prepare('select * from foo').execute + rs = @db.prepare("select * from foo").execute rows = [] while row = rs.next_hash rows << row end rows.each do |hash| - assert_equal list[hash['a'] - 1], hash['b'] + assert_equal list[hash["a"] - 1], hash["b"] end rs.close end diff --git a/test/test_sqlite3.rb b/test/test_sqlite3.rb index f455c23f..e9fcf8a3 100644 --- a/test/test_sqlite3.rb +++ b/test/test_sqlite3.rb @@ -1,4 +1,4 @@ -require 'helper' +require "helper" module SQLite3 class TestSQLite3 < SQLite3::TestCase diff --git a/test/test_statement.rb b/test/test_statement.rb index 5e317cb6..bd94360d 100644 --- a/test/test_statement.rb +++ b/test/test_statement.rb @@ -1,9 +1,9 @@ -require 'helper' +require "helper" module SQLite3 class TestStatement < SQLite3::TestCase def setup - @db = SQLite3::Database.new(':memory:') + @db = SQLite3::Database.new(":memory:") @stmt = SQLite3::Statement.new(@db, "select 'foo'") end @@ -15,7 +15,7 @@ def teardown def test_double_close_does_not_segv @db.execute 'CREATE TABLE "things" ("number" float NOT NULL)' - stmt = @db.prepare 'INSERT INTO things (number) VALUES (?)' + stmt = @db.prepare "INSERT INTO things (number) VALUES (?)" assert_raises(SQLite3::ConstraintException) { stmt.execute(nil) } stmt.close @@ -25,16 +25,16 @@ def test_double_close_does_not_segv def test_raises_type_error assert_raises(TypeError) do - SQLite3::Statement.new( @db, nil ) + SQLite3::Statement.new(@db, nil) end end def test_insert_duplicate_records @db.execute 'CREATE TABLE "things" ("name" varchar(20) CONSTRAINT "index_things_on_name" UNIQUE)' stmt = @db.prepare("INSERT INTO things(name) VALUES(?)") - stmt.execute('ruby') + stmt.execute("ruby") - exception = assert_raises(SQLite3::ConstraintException) { stmt.execute('ruby') } + exception = assert_raises(SQLite3::ConstraintException) { stmt.execute("ruby") } # SQLite 3.8.2 returns new error message: # UNIQUE constraint failed: *table_name*.*column_name* # Older versions of SQLite return: @@ -47,27 +47,27 @@ def test_insert_duplicate_records ### # This method may not exist depending on how sqlite3 was compiled def test_database_name - @db.execute('create table foo(text BLOB)') - @db.execute('insert into foo(text) values (?)',SQLite3::Blob.new('hello')) - stmt = @db.prepare('select text from foo') + @db.execute("create table foo(text BLOB)") + @db.execute("insert into foo(text) values (?)", SQLite3::Blob.new("hello")) + stmt = @db.prepare("select text from foo") if stmt.respond_to?(:database_name) - assert_equal 'main', stmt.database_name(0) + assert_equal "main", stmt.database_name(0) end stmt.close end def test_prepare_blob - @db.execute('create table foo(text BLOB)') - stmt = @db.prepare('insert into foo(text) values (?)') - stmt.bind_param(1, SQLite3::Blob.new('hello')) + @db.execute("create table foo(text BLOB)") + stmt = @db.prepare("insert into foo(text) values (?)") + stmt.bind_param(1, SQLite3::Blob.new("hello")) stmt.step stmt.close end def test_select_blob - @db.execute('create table foo(text BLOB)') - @db.execute('insert into foo(text) values (?)',SQLite3::Blob.new('hello')) - assert_equal 'hello', @db.execute('select * from foo').first.first + @db.execute("create table foo(text BLOB)") + @db.execute("insert into foo(text) values (?)", SQLite3::Blob.new("hello")) + assert_equal "hello", @db.execute("select * from foo").first.first end def test_new @@ -75,7 +75,7 @@ def test_new end def test_new_closed_handle - @db = SQLite3::Database.new(':memory:') + @db = SQLite3::Database.new(":memory:") @db.close assert_raises(ArgumentError) do SQLite3::Statement.new(@db, 'select "foo"') @@ -84,12 +84,12 @@ def test_new_closed_handle def test_new_with_remainder stmt = SQLite3::Statement.new(@db, "select 'foo';bar") - assert_equal 'bar', stmt.remainder + assert_equal "bar", stmt.remainder stmt.close end def test_empty_remainder - assert_equal '', @stmt.remainder + assert_equal "", @stmt.remainder end def test_close @@ -109,7 +109,7 @@ def test_bind_param_string stmt.bind_param(1, "hello") result = nil stmt.each { |x| result = x } - assert_equal ['hello'], result + assert_equal ["hello"], result stmt.close end @@ -132,25 +132,25 @@ def test_bind_nil end def test_bind_blob - @db.execute('create table foo(text BLOB)') - stmt = SQLite3::Statement.new(@db, 'insert into foo(text) values (?)') - stmt.bind_param(1, SQLite3::Blob.new('hello')) + @db.execute("create table foo(text BLOB)") + stmt = SQLite3::Statement.new(@db, "insert into foo(text) values (?)") + stmt.bind_param(1, SQLite3::Blob.new("hello")) stmt.execute - row = @db.execute('select * from foo') + row = @db.execute("select * from foo") stmt.close - assert_equal ['hello'], row.first + assert_equal ["hello"], row.first capture_io do # hush deprecation warning - assert_equal ['blob'], row.first.types + assert_equal ["blob"], row.first.types end end def test_bind_64 stmt = SQLite3::Statement.new(@db, "select ?") - stmt.bind_param(1, 2 ** 31) + stmt.bind_param(1, 2**31) result = nil stmt.each { |x| result = x } - assert_equal [2 ** 31], result + assert_equal [2**31], result stmt.close end @@ -165,35 +165,35 @@ def test_bind_double def test_named_bind stmt = SQLite3::Statement.new(@db, "select :foo") - stmt.bind_param(':foo', 'hello') + stmt.bind_param(":foo", "hello") result = nil stmt.each { |x| result = x } - assert_equal ['hello'], result + assert_equal ["hello"], result stmt.close end def test_named_bind_no_colon stmt = SQLite3::Statement.new(@db, "select :foo") - stmt.bind_param('foo', 'hello') + stmt.bind_param("foo", "hello") result = nil stmt.each { |x| result = x } - assert_equal ['hello'], result + assert_equal ["hello"], result stmt.close end def test_named_bind_symbol stmt = SQLite3::Statement.new(@db, "select :foo") - stmt.bind_param(:foo, 'hello') + stmt.bind_param(:foo, "hello") result = nil stmt.each { |x| result = x } - assert_equal ['hello'], result + assert_equal ["hello"], result stmt.close end def test_named_bind_not_found stmt = SQLite3::Statement.new(@db, "select :foo") assert_raises(SQLite3::Exception) do - stmt.bind_param('bar', 'hello') + stmt.bind_param("bar", "hello") end stmt.close end @@ -203,7 +203,7 @@ def test_each @stmt.each do |row| r = row end - assert_equal(['foo'], r) + assert_equal(["foo"], r) end def test_reset! @@ -211,12 +211,12 @@ def test_reset! @stmt.each { |row| r << row } @stmt.reset! @stmt.each { |row| r << row } - assert_equal [['foo'], ['foo']], r + assert_equal [["foo"], ["foo"]], r end def test_step r = @stmt.step - assert_equal ['foo'], r + assert_equal ["foo"], r end def test_step_twice @@ -250,29 +250,33 @@ def test_bind_parameter_count end def test_execute_with_varargs - stmt = @db.prepare('select ?, ?') + stmt = @db.prepare("select ?, ?") assert_equal [[nil, nil]], stmt.execute(nil, nil).to_a stmt.close end def test_execute_with_hash - stmt = @db.prepare('select :n, :h') - assert_equal [[10, nil]], stmt.execute('n' => 10, 'h' => nil).to_a + stmt = @db.prepare("select :n, :h") + assert_equal [[10, nil]], stmt.execute("n" => 10, "h" => nil).to_a stmt.close end def test_with_error @db.execute('CREATE TABLE "employees" ("name" varchar(20) NOT NULL CONSTRAINT "index_employees_on_name" UNIQUE)') stmt = @db.prepare("INSERT INTO Employees(name) VALUES(?)") - stmt.execute('employee-1') - stmt.execute('employee-1') rescue SQLite3::ConstraintException + stmt.execute("employee-1") + begin + stmt.execute("employee-1") + rescue + SQLite3::ConstraintException + end stmt.reset! - assert stmt.execute('employee-2') + assert stmt.execute("employee-2") stmt.close end def test_clear_bindings! - stmt = @db.prepare('select ?, ?') + stmt = @db.prepare("select ?, ?") stmt.bind_param 1, "foo" stmt.bind_param 2, "bar" diff --git a/test/test_statement_execute.rb b/test/test_statement_execute.rb index 6ff0a527..e5f81393 100644 --- a/test/test_statement_execute.rb +++ b/test/test_statement_execute.rb @@ -1,11 +1,12 @@ -require 'helper' +require "helper" module SQLite3 class TestStatementExecute < SQLite3::TestCase def setup - @db = SQLite3::Database.new(':memory:') + @db = SQLite3::Database.new(":memory:") @db.execute_batch( - "CREATE TABLE items (id integer PRIMARY KEY, number integer)") + "CREATE TABLE items (id integer PRIMARY KEY, number integer)" + ) end def teardown @@ -14,7 +15,7 @@ def teardown def test_execute_insert ps = @db.prepare("INSERT INTO items (number) VALUES (:n)") - ps.execute('n'=>10) + ps.execute("n" => 10) assert_equal 1, @db.get_first_value("SELECT count(*) FROM items") ps.close end @@ -23,7 +24,7 @@ def test_execute_update @db.execute("INSERT INTO items (number) VALUES (?)", [10]) ps = @db.prepare("UPDATE items SET number = :new WHERE number = :old") - ps.execute('old'=>10, 'new'=>20) + ps.execute("old" => 10, "new" => 20) assert_equal 20, @db.get_first_value("SELECT number FROM items") ps.close end @@ -31,7 +32,7 @@ def test_execute_update def test_execute_delete @db.execute("INSERT INTO items (number) VALUES (?)", [20]) ps = @db.prepare("DELETE FROM items WHERE number = :n") - ps.execute('n' => 20) + ps.execute("n" => 20) assert_equal 0, @db.get_first_value("SELECT count(*) FROM items") ps.close end From 259b7a625afef406ac48b5fc1b5ea92e9e345416 Mon Sep 17 00:00:00 2001 From: Mike Dalessio Date: Mon, 8 Jan 2024 22:07:12 -0500 Subject: [PATCH 2/8] style(standard): unsafe autocorrections --- CHANGELOG.md | 5 +++++ lib/sqlite3/pragmas.rb | 8 ++++---- lib/sqlite3/statement.rb | 4 ++-- test/test_database.rb | 28 ++++++++++++++-------------- test/test_integration_aggregate.rb | 2 +- test/test_integration_pending.rb | 5 ++--- 6 files changed, 28 insertions(+), 24 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 52d0e213..e4964c33 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -20,6 +20,11 @@ This release drops support for Ruby 2.7. [#453] @flavorjones - Moved some C code into Ruby. [#451, #455] @tenderlove +### Changed + +- Raise `StandardError` in a few places where `Exception` was previously raised. + + ### Removed - Remove `SQLite3::VersionProxy` which has been deprecated since v1.3.2. [#453] @flavorjones diff --git a/lib/sqlite3/pragmas.rb b/lib/sqlite3/pragmas.rb index 43816ef3..6f8e83e8 100644 --- a/lib/sqlite3/pragmas.rb +++ b/lib/sqlite3/pragmas.rb @@ -22,7 +22,7 @@ def set_boolean_pragma(name, mode) when "on", "yes", "true", "y", "t" then mode = "'ON'" when "off", "no", "false", "n", "f" then mode = "'OFF'" else - raise Exception, + raise StandardError, "unrecognized pragma parameter #{mode.inspect}" end when true, 1 @@ -30,7 +30,7 @@ def set_boolean_pragma(name, mode) when false, 0, nil mode = "OFF" else - raise Exception, + raise StandardError, "unrecognized pragma parameter #{mode.inspect}" end @@ -62,7 +62,7 @@ def get_enum_pragma(name) def set_enum_pragma(name, mode, enums) match = enums.find { |p| p.find { |i| i.to_s.downcase == mode.to_s.downcase } } unless match - raise Exception, + raise StandardError, "unrecognized #{name} #{mode.inspect}" end execute("PRAGMA #{name}='#{match.first.upcase}'") @@ -533,7 +533,7 @@ def table_info table result = [] unless block_given? stmt.each do |row| - new_row = Hash[columns.zip(row)] + new_row = columns.zip(row).to_h # FIXME: This should be removed but is required for older versions # of rails diff --git a/lib/sqlite3/statement.rb b/lib/sqlite3/statement.rb index caae7f24..2ff452be 100644 --- a/lib/sqlite3/statement.rb +++ b/lib/sqlite3/statement.rb @@ -81,7 +81,7 @@ def execute(*bind_vars) bind_params(*bind_vars) unless bind_vars.empty? @results = ResultSet.new(@connection, self) - step if 0 == column_count + step if column_count == 0 yield @results if block_given? @results @@ -156,7 +156,7 @@ def get_metadata end @types = Array.new(column_count) do |column| val = column_decltype(column) - val.nil? ? nil : val.downcase + val&.downcase end end end diff --git a/test/test_database.rb b/test/test_database.rb index 3b16e69e..734e43b7 100644 --- a/test/test_database.rb +++ b/test/test_database.rb @@ -26,7 +26,7 @@ def test_db_filename @db = SQLite3::Database.new tf.path assert_equal File.realdirpath(tf.path), File.realdirpath(@db.filename("main")) ensure - tf.unlink if tf + tf&.unlink end def test_filename @@ -36,7 +36,7 @@ def test_filename @db = SQLite3::Database.new tf.path assert_equal File.realdirpath(tf.path), File.realdirpath(@db.filename) ensure - tf.unlink if tf + tf&.unlink end def test_filename_with_attachment @@ -47,7 +47,7 @@ def test_filename_with_attachment assert_equal File.realdirpath(tf.path), File.realdirpath(@db.filename("testing")) ensure - tf.unlink if tf + tf&.unlink end def test_filename_to_path @@ -56,8 +56,8 @@ def test_filename_to_path db = SQLite3::Database.new pn assert_equal pn.realdirpath.to_s, File.realdirpath(db.filename) ensure - tf.close! if tf - db.close if db + tf&.close! + db&.close end def test_error_code @@ -200,14 +200,14 @@ def test_new db = SQLite3::Database.new(":memory:") assert_instance_of(SQLite3::Database, db) ensure - db.close if db + db&.close end def test_open db = SQLite3::Database.open(":memory:") assert_instance_of(SQLite3::Database, db) ensure - db.close if db + db&.close end def test_open_returns_block_result @@ -240,7 +240,7 @@ def test_new_with_options db = SQLite3::Database.new(":memory:".encode(utf16), utf16: true) assert_instance_of(SQLite3::Database, db) ensure - db.close if db + db&.close end def test_close @@ -296,7 +296,7 @@ def test_prepare stmt = db.prepare('select "hello world"') assert_instance_of(SQLite3::Statement, stmt) ensure - stmt.close if stmt + stmt&.close end def test_block_prepare_does_not_double_close @@ -543,7 +543,7 @@ def call action, a, b, c, d stmt = @db.prepare("select 'fooooo'") assert_nil stmt.step ensure - stmt.close if stmt + stmt&.close end def test_authorizer_fail @@ -570,7 +570,7 @@ def call action, a, b, c, d @db.authorizer = nil s = @db.prepare("select 'fooooo'") ensure - s.close if s + s&.close end def test_close_with_open_statements @@ -579,7 +579,7 @@ def test_close_with_open_statements @db.close end ensure - s.close if s + s&.close end def test_execute_with_empty_bind_params @@ -590,7 +590,7 @@ def test_query_with_named_bind_params resultset = @db.query("select :n", {"n" => "foo"}) assert_equal [["foo"]], resultset.to_a ensure - resultset.close if resultset + resultset&.close end def test_execute_with_named_bind_params @@ -669,7 +669,7 @@ def test_default_transaction_mode db2.close if db2 && !db2.closed? end ensure - tf.unlink if tf + tf&.unlink end end end diff --git a/test/test_integration_aggregate.rb b/test/test_integration_aggregate.rb index 7dbc215d..b97d33bc 100644 --- a/test/test_integration_aggregate.rb +++ b/test/test_integration_aggregate.rb @@ -174,7 +174,7 @@ def test_create_aggregate_with_invalid_arity end end - class CustomException < Exception + class CustomException < RuntimeError end def test_create_aggregate_with_exception_in_step diff --git a/test/test_integration_pending.rb b/test/test_integration_pending.rb index 9b6886b4..9cfc679c 100644 --- a/test/test_integration_pending.rb +++ b/test/test_integration_pending.rb @@ -1,6 +1,5 @@ require "helper" -require "thread" require "benchmark" class TC_Integration_Pending < SQLite3::TestCase @@ -30,7 +29,7 @@ def test_busy_handler_impatient busy.lock end ensure - db2.close if db2 + db2&.close end sleep 1 @@ -60,7 +59,7 @@ def test_busy_timeout busy.lock end ensure - db2.close if db2 + db2&.close end sleep 1 From 8ea5350fb4cd1904344e11d218de519a6d5cf04c Mon Sep 17 00:00:00 2001 From: Mike Dalessio Date: Mon, 8 Jan 2024 22:09:59 -0500 Subject: [PATCH 3/8] style(standard): manual corrections --- lib/sqlite3/resultset.rb | 4 ++-- test/test_integration.rb | 2 +- test/test_integration_aggregate.rb | 2 +- test/test_integration_open_close.rb | 2 +- test/test_integration_pending.rb | 2 +- test/test_integration_resultset.rb | 2 +- test/test_integration_statement.rb | 2 +- test/test_result_set.rb | 2 +- test/test_statement.rb | 2 +- 9 files changed, 10 insertions(+), 10 deletions(-) diff --git a/lib/sqlite3/resultset.rb b/lib/sqlite3/resultset.rb index 6ab4e7a4..ef01d58b 100644 --- a/lib/sqlite3/resultset.rb +++ b/lib/sqlite3/resultset.rb @@ -121,7 +121,7 @@ def next # Required by the Enumerable mixin. Provides an internal iterator over the # rows of the result set. def each - while node = self.next + while (node = self.next) yield node end end @@ -129,7 +129,7 @@ def each # Provides an internal iterator over the rows of the result set where # each row is yielded as a hash. def each_hash - while node = next_hash + while (node = next_hash) yield node end end diff --git a/test/test_integration.rb b/test/test_integration.rb index 6008a56c..8ab6e344 100644 --- a/test/test_integration.rb +++ b/test/test_integration.rb @@ -1,6 +1,6 @@ require "helper" -class TC_Database_Integration < SQLite3::TestCase +class IntegrationTestCase < SQLite3::TestCase def setup @db = SQLite3::Database.new(":memory:") @db.transaction do diff --git a/test/test_integration_aggregate.rb b/test/test_integration_aggregate.rb index b97d33bc..5dd116a6 100644 --- a/test/test_integration_aggregate.rb +++ b/test/test_integration_aggregate.rb @@ -1,6 +1,6 @@ require "helper" -class TC_Integration_Aggregate < SQLite3::TestCase +class IntegrationAggregateTestCase < SQLite3::TestCase def setup @db = SQLite3::Database.new(":memory:") @db.transaction do diff --git a/test/test_integration_open_close.rb b/test/test_integration_open_close.rb index 1c9c03a0..86190257 100644 --- a/test/test_integration_open_close.rb +++ b/test/test_integration_open_close.rb @@ -1,6 +1,6 @@ require "helper" -class TC_OpenClose < SQLite3::TestCase +class IntegrationOpenCloseTestCase < SQLite3::TestCase def test_create_close db = SQLite3::Database.new("test-create.db") assert File.exist?("test-create.db") diff --git a/test/test_integration_pending.rb b/test/test_integration_pending.rb index 9cfc679c..ff05de2e 100644 --- a/test/test_integration_pending.rb +++ b/test/test_integration_pending.rb @@ -2,7 +2,7 @@ require "benchmark" -class TC_Integration_Pending < SQLite3::TestCase +class IntegrationPendingTestCase < SQLite3::TestCase def setup @db = SQLite3::Database.new("test.db") @db.transaction do diff --git a/test/test_integration_resultset.rb b/test/test_integration_resultset.rb index 479ca357..841b72b4 100644 --- a/test/test_integration_resultset.rb +++ b/test/test_integration_resultset.rb @@ -1,6 +1,6 @@ require "helper" -class TC_ResultSet < SQLite3::TestCase +class IntegrationResultSetTestCase < SQLite3::TestCase def setup @db = SQLite3::Database.new(":memory:") @db.transaction do diff --git a/test/test_integration_statement.rb b/test/test_integration_statement.rb index 0ab8c4af..795d752f 100644 --- a/test/test_integration_statement.rb +++ b/test/test_integration_statement.rb @@ -1,6 +1,6 @@ require "helper" -class TC_Statement < SQLite3::TestCase +class IntegrationStatementTestCase < SQLite3::TestCase def setup @db = SQLite3::Database.new(":memory:") @db.transaction do diff --git a/test/test_result_set.rb b/test/test_result_set.rb index 2d3398e1..4fc12280 100644 --- a/test/test_result_set.rb +++ b/test/test_result_set.rb @@ -35,7 +35,7 @@ def test_next_hash rs = @db.prepare("select * from foo").execute rows = [] - while row = rs.next_hash + while (row = rs.next_hash) rows << row end rows.each do |hash| diff --git a/test/test_statement.rb b/test/test_statement.rb index bd94360d..7b70fc6a 100644 --- a/test/test_statement.rb +++ b/test/test_statement.rb @@ -284,7 +284,7 @@ def test_clear_bindings! # the clear_bindings! method and assert that nil is returned stmt.clear_bindings! - while x = stmt.step + while (x = stmt.step) assert_equal [nil, nil], x end From bab0c090351f5a00d603934a3b05f3fec70b9f44 Mon Sep 17 00:00:00 2001 From: Mike Dalessio Date: Tue, 9 Jan 2024 11:49:59 -0500 Subject: [PATCH 4/8] style(rubocop): Minitest safe autocorrections --- .rubocop.yml | 70 +++++++++++++++++++++++++++++ Gemfile | 1 + test/test_database.rb | 22 ++++----- test/test_database_flags.rb | 8 ++-- test/test_database_readonly.rb | 2 +- test/test_database_readwrite.rb | 2 +- test/test_integration.rb | 26 +++++------ test/test_integration_open_close.rb | 4 +- test/test_integration_pending.rb | 2 +- test/test_integration_resultset.rb | 14 +++--- test/test_integration_statement.rb | 6 +-- test/test_sqlite3.rb | 4 +- test/test_statement.rb | 4 +- 13 files changed, 118 insertions(+), 47 deletions(-) diff --git a/.rubocop.yml b/.rubocop.yml index 8313530a..1b9237a9 100644 --- a/.rubocop.yml +++ b/.rubocop.yml @@ -4,6 +4,7 @@ require: - standard-custom - standard-performance - rubocop-performance + - rubocop-minitest inherit_gem: standard: config/base.yml @@ -13,3 +14,72 @@ inherit_gem: AllCops: SuggestExtensions: false TargetRubyVersion: 3.0 + +Minitest/AssertInDelta: # new in 0.10 + Enabled: true +Minitest/AssertKindOf: # new in 0.10 + Enabled: true +Minitest/AssertOperator: # new in 0.32 + Enabled: true +Minitest/AssertOutput: # new in 0.10 + Enabled: true +Minitest/AssertPathExists: # new in 0.10 + Enabled: true +Minitest/AssertPredicate: # new in 0.18 + Enabled: true +Minitest/AssertRaisesCompoundBody: # new in 0.21 + Enabled: true +Minitest/AssertRaisesWithRegexpArgument: # new in 0.22 + Enabled: true +Minitest/AssertSame: # new in 0.26 + Enabled: true +Minitest/AssertSilent: # new in 0.10 + Enabled: true +Minitest/AssertWithExpectedArgument: # new in 0.11 + Enabled: true +Minitest/AssertionInLifecycleHook: # new in 0.10 + Enabled: true +Minitest/DuplicateTestRun: # new in 0.19 + Enabled: true +Minitest/EmptyLineBeforeAssertionMethods: # new in 0.23 + Enabled: false +Minitest/LifecycleHooksOrder: # new in 0.28 + Enabled: true +Minitest/LiteralAsActualArgument: # new in 0.10 + Enabled: true +Minitest/MultipleAssertions: # new in 0.10 + Enabled: true +Minitest/NonExecutableTestMethod: # new in 0.34 + Enabled: true +Minitest/NonPublicTestMethod: # new in 0.27 + Enabled: true +Minitest/RedundantMessageArgument: # new in 0.34 + Enabled: true +Minitest/RefuteInDelta: # new in 0.10 + Enabled: true +Minitest/RefuteKindOf: # new in 0.10 + Enabled: true +Minitest/RefuteOperator: # new in 0.32 + Enabled: true +Minitest/RefutePathExists: # new in 0.10 + Enabled: true +Minitest/RefutePredicate: # new in 0.18 + Enabled: true +Minitest/RefuteSame: # new in 0.26 + Enabled: true +Minitest/ReturnInTestMethod: # new in 0.31 + Enabled: true +Minitest/SkipEnsure: # new in 0.20 + Enabled: true +Minitest/SkipWithoutReason: # new in 0.24 + Enabled: true +Minitest/TestFileName: # new in 0.26 + Enabled: true +Minitest/TestMethodName: # new in 0.10 + Enabled: true +Minitest/UnreachableAssertion: # new in 0.14 + Enabled: true +Minitest/UnspecifiedException: # new in 0.10 + Enabled: true +Minitest/UselessAssertion: # new in 0.26 + Enabled: true diff --git a/Gemfile b/Gemfile index a0e9d3fa..7c31addd 100644 --- a/Gemfile +++ b/Gemfile @@ -14,4 +14,5 @@ group :development do gem "rubocop", require: false gem "standardrb", require: false + gem "rubocop-minitest", require: false end diff --git a/test/test_database.rb b/test/test_database.rb index 734e43b7..33cd1188 100644 --- a/test/test_database.rb +++ b/test/test_database.rb @@ -150,16 +150,16 @@ def test_execute_batch2 INSERT INTO items (name) VALUES ("bar"); SELECT * FROM items; EOSQL - assert_equal return_value, [{"id" => "1", "name" => "foo"}, {"id" => "2", "name" => "bar"}] + assert_equal [{"id" => "1", "name" => "foo"}, {"id" => "2", "name" => "bar"}], return_value return_value = @db.execute_batch2("SELECT * FROM items;") do |result| result["id"] = result["id"].to_i result end - assert_equal return_value, [{"id" => 1, "name" => "foo"}, {"id" => 2, "name" => "bar"}] + assert_equal [{"id" => 1, "name" => "foo"}, {"id" => 2, "name" => "bar"}], return_value return_value = @db.execute_batch2('INSERT INTO items (name) VALUES ("oof")') - assert_equal return_value, [] + assert_empty return_value return_value = @db.execute_batch2( 'CREATE TABLE employees (id integer PRIMARY KEY AUTOINCREMENT, name string, age integer(3)); @@ -171,10 +171,10 @@ def test_execute_batch2 result["age"] = result["age"].to_i result end - assert_equal return_value, [{"age" => 30}, {"age" => 40}, {"age" => 20}] + assert_equal [{"age" => 30}, {"age" => 40}, {"age" => 20}], return_value return_value = @db.execute_batch2("SELECT name FROM employees") - assert_equal return_value, [{"name" => nil}, {"name" => nil}, {"name" => nil}] + assert_equal [{"name" => nil}, {"name" => nil}, {"name" => nil}], return_value @db.results_as_hash = false return_value = @db.execute_batch2( @@ -188,7 +188,7 @@ def test_execute_batch2 end result end - assert_equal return_value, [[1, 50], [2, 60]] + assert_equal [[1, 50], [2, 60]], return_value assert_raises(RuntimeError) do # "names" is not a valid column @@ -246,7 +246,7 @@ def test_new_with_options def test_close db = SQLite3::Database.new(":memory:") db.close - assert db.closed? + assert_predicate db, :closed? end def test_block_closes_self @@ -255,7 +255,7 @@ def test_block_closes_self thing = db assert !thing.closed? end - assert thing.closed? + assert_predicate thing, :closed? end def test_open_with_block_closes_self @@ -264,7 +264,7 @@ def test_open_with_block_closes_self thing = db assert !thing.closed? end - assert thing.closed? + assert_predicate thing, :closed? end def test_block_closes_self_even_raised @@ -276,7 +276,7 @@ def test_block_closes_self_even_raised end rescue end - assert thing.closed? + assert_predicate thing, :closed? end def test_open_with_block_closes_self_even_raised @@ -288,7 +288,7 @@ def test_open_with_block_closes_self_even_raised end rescue end - assert thing.closed? + assert_predicate thing, :closed? end def test_prepare diff --git a/test/test_database_flags.rb b/test/test_database_flags.rb index 5c405afc..be845509 100644 --- a/test/test_database_flags.rb +++ b/test/test_database_flags.rb @@ -28,7 +28,7 @@ def test_open_database_flags_constants if SQLite3::SQLITE_VERSION_NUMBER > 3007013 defined_to_date += [:MEMORY] end - assert defined_to_date.sort == SQLite3::Constants::Open.constants.sort + assert_equal defined_to_date.sort, SQLite3::Constants::Open.constants.sort end def test_open_database_flags_conflicts_with_readonly @@ -45,7 +45,7 @@ def test_open_database_flags_conflicts_with_readwrite def test_open_database_readonly_flags @db = SQLite3::Database.new("test-flags.db", flags: SQLite3::Constants::Open::READONLY) - assert @db.readonly? + assert_predicate @db, :readonly? end def test_open_database_readwrite_flags @@ -81,7 +81,7 @@ def test_open_database_create_flags db.execute("CREATE TABLE foos (id integer)") db.execute("INSERT INTO foos (id) VALUES (12)") end - assert File.exist?("test-flags.db") + assert_path_exists "test-flags.db" end def test_open_database_exotic_flags @@ -89,7 +89,7 @@ def test_open_database_exotic_flags exotic_flags = SQLite3::Constants::Open::NOMUTEX | SQLite3::Constants::Open::TEMP_DB @db = SQLite3::Database.new("test-flags.db", flags: flags | exotic_flags) @db.execute("INSERT INTO foos (id) VALUES (12)") - assert @db.changes == 1 + assert_equal 1, @db.changes end end end diff --git a/test/test_database_readonly.rb b/test/test_database_readonly.rb index 7e8d7bc5..352fd3d8 100644 --- a/test/test_database_readonly.rb +++ b/test/test_database_readonly.rb @@ -16,7 +16,7 @@ def teardown def test_open_readonly_database @db = SQLite3::Database.new("test-readonly.db", readonly: true) - assert @db.readonly? + assert_predicate @db, :readonly? end def test_open_readonly_not_exists_database diff --git a/test/test_database_readwrite.rb b/test/test_database_readwrite.rb index 9f923b63..90164b0d 100644 --- a/test/test_database_readwrite.rb +++ b/test/test_database_readwrite.rb @@ -35,7 +35,7 @@ def test_open_readwrite_not_exists_database def test_insert_readwrite_database @db = SQLite3::Database.new("test-readwrite.db", readwrite: true) @db.execute("INSERT INTO foos (id) VALUES (12)") - assert @db.changes == 1 + assert_equal 1, @db.changes end end end diff --git a/test/test_integration.rb b/test/test_integration.rb index 8ab6e344..31fc9be1 100644 --- a/test/test_integration.rb +++ b/test/test_integration.rb @@ -98,7 +98,7 @@ def test_authorizer_error def test_authorizer_silent @db.authorizer { |type, a, b, c, d| 2 } rows = @db.execute "select * from foo" - assert rows.empty? + assert_empty rows end def test_prepare_invalid_syntax @@ -121,7 +121,7 @@ def test_prepare_invalid_table def test_prepare_no_block stmt = @db.prepare "select * from foo" - assert stmt.respond_to?(:execute) + assert_respond_to stmt, :execute stmt.close end @@ -129,14 +129,14 @@ def test_prepare_with_block called = false @db.prepare "select * from foo" do |stmt| called = true - assert stmt.respond_to?(:execute) + assert_respond_to stmt, :execute end assert called end def test_execute_no_block_no_bind_no_match rows = @db.execute("select * from foo where a > 100") - assert rows.empty? + assert_empty rows end def test_execute_with_block_no_bind_no_match @@ -149,7 +149,7 @@ def test_execute_with_block_no_bind_no_match def test_execute_no_block_with_bind_no_match rows = @db.execute("select * from foo where a > ?", 100) - assert rows.empty? + assert_empty rows end def test_execute_with_block_with_bind_no_match @@ -188,7 +188,7 @@ def test_execute_with_block_with_bind_with_match def test_execute2_no_block_no_bind_no_match columns, *rows = @db.execute2("select * from foo where a > 100") - assert rows.empty? + assert_empty rows assert_equal ["a", "b"], columns end @@ -203,7 +203,7 @@ def test_execute2_with_block_no_bind_no_match def test_execute2_no_block_with_bind_no_match columns, *rows = @db.execute2("select * from foo where a > ?", 100) - assert rows.empty? + assert_empty rows assert_equal ["a", "b"], columns end @@ -285,7 +285,7 @@ def test_query_with_block_no_bind_no_match assert_nil result.next r = result end - assert r.closed? + assert_predicate r, :closed? end def test_query_no_block_with_bind_no_match @@ -300,7 +300,7 @@ def test_query_with_block_with_bind_no_match assert_nil result.next r = result end - assert r.closed? + assert_predicate r, :closed? end def test_query_no_block_no_bind_with_match @@ -317,7 +317,7 @@ def test_query_with_block_no_bind_with_match assert_nil result.next r = result end - assert r.closed? + assert_predicate r, :closed? end def test_query_no_block_with_bind_with_match @@ -334,7 +334,7 @@ def test_query_with_block_with_bind_with_match assert_nil result.next r = result end - assert r.closed? + assert_predicate r, :closed? end def test_get_first_row_no_bind_no_match @@ -464,7 +464,7 @@ def test_transaction_commit_in_block def test_transaction_active assert !@db.transaction_active? @db.transaction - assert @db.transaction_active? + assert_predicate @db, :transaction_active? @db.commit assert !@db.transaction_active? end @@ -473,7 +473,7 @@ def test_transaction_implicit_rollback assert !@db.transaction_active? @db.transaction @db.execute("create table bar (x CHECK(1 = 0))") - assert @db.transaction_active? + assert_predicate @db, :transaction_active? assert_raises(SQLite3::ConstraintException) do @db.execute("insert or rollback into bar (x) VALUES ('x')") end diff --git a/test/test_integration_open_close.rb b/test/test_integration_open_close.rb index 86190257..2f268af5 100644 --- a/test/test_integration_open_close.rb +++ b/test/test_integration_open_close.rb @@ -3,7 +3,7 @@ class IntegrationOpenCloseTestCase < SQLite3::TestCase def test_create_close db = SQLite3::Database.new("test-create.db") - assert File.exist?("test-create.db") + assert_path_exists "test-create.db" assert_nothing_raised { db.close } ensure begin @@ -15,7 +15,7 @@ def test_create_close def test_open_close File.open("test-open.db", "w") { |f| } - assert File.exist?("test-open.db") + assert_path_exists "test-open.db" db = SQLite3::Database.new("test-open.db") assert_nothing_raised { db.close } ensure diff --git a/test/test_integration_pending.rb b/test/test_integration_pending.rb index ff05de2e..a230a2cb 100644 --- a/test/test_integration_pending.rb +++ b/test/test_integration_pending.rb @@ -72,6 +72,6 @@ def test_busy_timeout busy.unlock t.join - assert time.real * 1000 >= 1000 + assert_operator time.real * 1000, :>=, 1000 end end diff --git a/test/test_integration_resultset.rb b/test/test_integration_resultset.rb index 841b72b4..d3058ad7 100644 --- a/test/test_integration_resultset.rb +++ b/test/test_integration_resultset.rb @@ -20,13 +20,13 @@ def teardown def test_reset_unused assert_nothing_raised { @result.reset } - assert @result.to_a.empty? + assert_empty @result.to_a end def test_reset_used @result.to_a assert_nothing_raised { @result.reset } - assert @result.to_a.empty? + assert_empty @result.to_a end def test_reset_with_bind @@ -44,7 +44,7 @@ def test_eof_edge @result.reset(1) @result.next # to first row @result.next # to end of result set - assert @result.eof? + assert_predicate @result, :eof? end def test_next_eof @@ -101,8 +101,8 @@ def test_next_results_as_hash hash = @result.next assert_equal({"a" => 1, "b" => "foo"}, hash) - assert_equal hash[@result.columns[0]], 1 - assert_equal hash[@result.columns[1]], "foo" + assert_equal 1, hash[@result.columns[0]] + assert_equal "foo", hash[@result.columns[1]] end def test_each @@ -130,8 +130,8 @@ def test_close result = stmt.execute assert !result.closed? result.close - assert result.closed? - assert stmt.closed? + assert_predicate result, :closed? + assert_predicate stmt, :closed? assert_raise(SQLite3::Exception) { result.reset } assert_raise(SQLite3::Exception) { result.next } assert_raise(SQLite3::Exception) { result.each } diff --git a/test/test_integration_statement.rb b/test/test_integration_statement.rb index 795d752f..e9a85e90 100644 --- a/test/test_integration_statement.rb +++ b/test/test_integration_statement.rb @@ -32,7 +32,7 @@ def test_remainder_nonempty def test_bind_params_empty assert_nothing_raised { @stmt.bind_params } - assert @stmt.execute!.empty? + assert_empty @stmt.execute! end def test_bind_params_array @@ -113,7 +113,7 @@ def test_reexecute end def test_execute_bang_no_bind_no_block - assert @stmt.execute!.empty? + assert_empty @stmt.execute! end def test_execute_bang_with_bind_no_block @@ -168,7 +168,7 @@ def test_close stmt = @db.prepare("select * from foo") assert !stmt.closed? stmt.close - assert stmt.closed? + assert_predicate stmt, :closed? assert_raise(SQLite3::Exception) { stmt.execute } assert_raise(SQLite3::Exception) { stmt.execute! } assert_raise(SQLite3::Exception) { stmt.close } diff --git a/test/test_sqlite3.rb b/test/test_sqlite3.rb index e9fcf8a3..3fe2e2de 100644 --- a/test/test_sqlite3.rb +++ b/test/test_sqlite3.rb @@ -12,9 +12,9 @@ def test_threadsafe def test_threadsafe? if SQLite3.threadsafe > 0 - assert SQLite3.threadsafe? + assert_predicate SQLite3, :threadsafe? else - refute SQLite3.threadsafe? + refute_predicate SQLite3, :threadsafe? end end diff --git a/test/test_statement.rb b/test/test_statement.rb index 7b70fc6a..3335f6a0 100644 --- a/test/test_statement.rb +++ b/test/test_statement.rb @@ -94,7 +94,7 @@ def test_empty_remainder def test_close @stmt.close - assert @stmt.closed? + assert_predicate @stmt, :closed? end def test_double_close @@ -223,7 +223,7 @@ def test_step_twice assert_not_nil @stmt.step assert !@stmt.done? assert_nil @stmt.step - assert @stmt.done? + assert_predicate @stmt, :done? @stmt.reset! assert !@stmt.done? From 7acaa13e50c654fde7e32c1de19b4f0f7f93ec02 Mon Sep 17 00:00:00 2001 From: Mike Dalessio Date: Tue, 9 Jan 2024 11:50:52 -0500 Subject: [PATCH 5/8] style(rubocop): Minitest unsafe autocorrections --- test/test_database.rb | 4 ++-- test/test_database_flags.rb | 2 +- test/test_database_readwrite.rb | 2 +- test/test_integration.rb | 14 +++++++------- test/test_integration_resultset.rb | 4 ++-- test/test_integration_statement.rb | 2 +- test/test_statement.rb | 4 ++-- 7 files changed, 16 insertions(+), 16 deletions(-) diff --git a/test/test_database.rb b/test/test_database.rb index 33cd1188..92a2fdd7 100644 --- a/test/test_database.rb +++ b/test/test_database.rb @@ -253,7 +253,7 @@ def test_block_closes_self thing = nil SQLite3::Database.new(":memory:") do |db| thing = db - assert !thing.closed? + refute_predicate thing, :closed? end assert_predicate thing, :closed? end @@ -262,7 +262,7 @@ def test_open_with_block_closes_self thing = nil SQLite3::Database.open(":memory:") do |db| thing = db - assert !thing.closed? + refute_predicate thing, :closed? end assert_predicate thing, :closed? end diff --git a/test/test_database_flags.rb b/test/test_database_flags.rb index be845509..9b437697 100644 --- a/test/test_database_flags.rb +++ b/test/test_database_flags.rb @@ -50,7 +50,7 @@ def test_open_database_readonly_flags def test_open_database_readwrite_flags @db = SQLite3::Database.new("test-flags.db", flags: SQLite3::Constants::Open::READWRITE) - assert !@db.readonly? + refute_predicate @db, :readonly? end def test_open_database_readonly_flags_cant_open diff --git a/test/test_database_readwrite.rb b/test/test_database_readwrite.rb index 90164b0d..cfcf81a8 100644 --- a/test/test_database_readwrite.rb +++ b/test/test_database_readwrite.rb @@ -16,7 +16,7 @@ def teardown def test_open_readwrite_database @db = SQLite3::Database.new("test-readwrite.db", readwrite: true) - assert !@db.readonly? + refute_predicate @db, :readonly? end def test_open_readwrite_readonly_database diff --git a/test/test_integration.rb b/test/test_integration.rb index 31fc9be1..1f161d25 100644 --- a/test/test_integration.rb +++ b/test/test_integration.rb @@ -44,7 +44,7 @@ def test_table_info_without_defaults_for_version_3_3_8_and_higher end def test_complete_fail - assert !@db.complete?("select * from foo") + refute @db.complete?("select * from foo") end def test_complete_success @@ -144,7 +144,7 @@ def test_execute_with_block_no_bind_no_match @db.execute("select * from foo where a > 100") do |row| called = true end - assert !called + refute called end def test_execute_no_block_with_bind_no_match @@ -157,7 +157,7 @@ def test_execute_with_block_with_bind_no_match @db.execute("select * from foo where a > ?", 100) do |row| called = true end - assert !called + refute called end def test_execute_no_block_no_bind_with_match @@ -462,22 +462,22 @@ def test_transaction_commit_in_block end def test_transaction_active - assert !@db.transaction_active? + refute_predicate @db, :transaction_active? @db.transaction assert_predicate @db, :transaction_active? @db.commit - assert !@db.transaction_active? + refute_predicate @db, :transaction_active? end def test_transaction_implicit_rollback - assert !@db.transaction_active? + refute_predicate @db, :transaction_active? @db.transaction @db.execute("create table bar (x CHECK(1 = 0))") assert_predicate @db, :transaction_active? assert_raises(SQLite3::ConstraintException) do @db.execute("insert or rollback into bar (x) VALUES ('x')") end - assert !@db.transaction_active? + refute_predicate @db, :transaction_active? end def test_interrupt diff --git a/test/test_integration_resultset.rb b/test/test_integration_resultset.rb index d3058ad7..28cbaad5 100644 --- a/test/test_integration_resultset.rb +++ b/test/test_integration_resultset.rb @@ -37,7 +37,7 @@ def test_reset_with_bind def test_eof_inner @result.reset(1) - assert !@result.eof? + refute_predicate @result, :eof? end def test_eof_edge @@ -128,7 +128,7 @@ def test_columns def test_close stmt = @db.prepare("select * from foo") result = stmt.execute - assert !result.closed? + refute_predicate result, :closed? result.close assert_predicate result, :closed? assert_predicate stmt, :closed? diff --git a/test/test_integration_statement.rb b/test/test_integration_statement.rb index e9a85e90..e1f86a91 100644 --- a/test/test_integration_statement.rb +++ b/test/test_integration_statement.rb @@ -166,7 +166,7 @@ def test_types_computed def test_close stmt = @db.prepare("select * from foo") - assert !stmt.closed? + refute_predicate stmt, :closed? stmt.close assert_predicate stmt, :closed? assert_raise(SQLite3::Exception) { stmt.execute } diff --git a/test/test_statement.rb b/test/test_statement.rb index 3335f6a0..7b55f0de 100644 --- a/test/test_statement.rb +++ b/test/test_statement.rb @@ -221,12 +221,12 @@ def test_step def test_step_twice assert_not_nil @stmt.step - assert !@stmt.done? + refute_predicate @stmt, :done? assert_nil @stmt.step assert_predicate @stmt, :done? @stmt.reset! - assert !@stmt.done? + refute_predicate @stmt, :done? end def test_step_never_moves_past_done From a4fb32c2e2622d83115593b3da105316d0e5fc1c Mon Sep 17 00:00:00 2001 From: Mike Dalessio Date: Tue, 9 Jan 2024 11:53:44 -0500 Subject: [PATCH 6/8] style(rubocop): Minitest manual corrections including fixing two incorrect tests --- test/test_database.rb | 2 +- test/test_integration.rb | 4 ++-- 2 files changed, 3 insertions(+), 3 deletions(-) diff --git a/test/test_database.rb b/test/test_database.rb index 92a2fdd7..1efcbf9f 100644 --- a/test/test_database.rb +++ b/test/test_database.rb @@ -16,7 +16,7 @@ def teardown end def test_segv - assert_raises { SQLite3::Database.new 1 } + assert_raises { SQLite3::Database.new 1 } # rubocop:disable Minitest/UnspecifiedException end def test_db_filename diff --git a/test/test_integration.rb b/test/test_integration.rb index 1f161d25..f0c005ab 100644 --- a/test/test_integration.rb +++ b/test/test_integration.rb @@ -195,7 +195,7 @@ def test_execute2_no_block_no_bind_no_match def test_execute2_with_block_no_bind_no_match called = 0 @db.execute2("select * from foo where a > 100") do |row| - assert ["a", "b"], row unless called == 0 + assert_equal(["a", "b"], row) if called == 0 called += 1 end assert_equal 1, called @@ -210,7 +210,7 @@ def test_execute2_no_block_with_bind_no_match def test_execute2_with_block_with_bind_no_match called = 0 @db.execute2("select * from foo where a > ?", 100) do |row| - assert_equal ["a", "b"], row unless called == 0 + assert_equal(["a", "b"], row) if called == 0 called += 1 end assert_equal 1, called From 1186f9a9924302af6ef632bb5cbbc6a3f0b54819 Mon Sep 17 00:00:00 2001 From: Mike Dalessio Date: Wed, 3 Jan 2024 21:03:54 -0500 Subject: [PATCH 7/8] style(rubocop): Naming/InclusiveLanguage. support SUPER_JOURNAL which is an alternative to MASTER_JOURNAL introduced in sqlite 3.33.0 --- .rubocop.yml | 3 +++ ext/sqlite3/sqlite3.c | 3 ++- test/test_database_flags.rb | 2 +- 3 files changed, 6 insertions(+), 2 deletions(-) diff --git a/.rubocop.yml b/.rubocop.yml index 1b9237a9..faeea9f9 100644 --- a/.rubocop.yml +++ b/.rubocop.yml @@ -15,6 +15,9 @@ AllCops: SuggestExtensions: false TargetRubyVersion: 3.0 +Naming/InclusiveLanguage: + Enabled: true + Minitest/AssertInDelta: # new in 0.10 Enabled: true Minitest/AssertKindOf: # new in 0.10 diff --git a/ext/sqlite3/sqlite3.c b/ext/sqlite3/sqlite3.c index ba22e1a3..0456cd91 100644 --- a/ext/sqlite3/sqlite3.c +++ b/ext/sqlite3/sqlite3.c @@ -111,7 +111,8 @@ init_sqlite3_constants(void) 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, "MASTER_JOURNAL", INT2FIX(SQLITE_OPEN_MASTER_JOURNAL)); /* pre-3.33.0 */ + rb_define_const(mSqlite3Open, "SUPER_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 diff --git a/test/test_database_flags.rb b/test/test_database_flags.rb index 9b437697..f6646871 100644 --- a/test/test_database_flags.rb +++ b/test/test_database_flags.rb @@ -18,7 +18,7 @@ def test_open_database_flags_constants defined_to_date = [:READONLY, :READWRITE, :CREATE, :DELETEONCLOSE, :EXCLUSIVE, :MAIN_DB, :TEMP_DB, :TRANSIENT_DB, :MAIN_JOURNAL, :TEMP_JOURNAL, :SUBJOURNAL, - :MASTER_JOURNAL, :NOMUTEX, :FULLMUTEX] + :MASTER_JOURNAL, :SUPER_JOURNAL, :NOMUTEX, :FULLMUTEX] if SQLite3::SQLITE_VERSION_NUMBER > 3007002 defined_to_date += [:AUTOPROXY, :SHAREDCACHE, :PRIVATECACHE, :WAL] end From c88044db19ec481303ab61ed785f1595b60139a7 Mon Sep 17 00:00:00 2001 From: Mike Dalessio Date: Tue, 9 Jan 2024 12:06:43 -0500 Subject: [PATCH 8/8] dev: make default rake task include rubocop and remove clobber --- Rakefile | 2 ++ rakelib/native.rake | 2 -- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/Rakefile b/Rakefile index 6bff83fc..4c8869b5 100644 --- a/Rakefile +++ b/Rakefile @@ -5,3 +5,5 @@ # require "bundler" SQLITE3_SPEC = Bundler.load_gemspec("sqlite3.gemspec") + +task default: [:rubocop, :compile, :test] diff --git a/rakelib/native.rake b/rakelib/native.rake index 25e18ff5..9e0f4006 100644 --- a/rakelib/native.rake +++ b/rakelib/native.rake @@ -112,8 +112,6 @@ task "set-version-to-timestamp" do puts "NOTE: wrote version as \"#{fake_version}\"" end -task default: [:clobber, :compile, :test] - CLEAN.add("{ext,lib}/**/*.{o,so}", "pkg") CLOBBER.add("ports/*").exclude(%r{ports/archives$})