From 5196160b1d2ed85e626166530135a8fa6a7600f7 Mon Sep 17 00:00:00 2001 From: Tamir Duberstein Date: Sun, 7 Jun 2015 19:57:44 -0400 Subject: [PATCH 01/14] Generate a static --- ext/mysql2/mysql_enc_name_to_ruby.h | 16 +++++----- ext/mysql2/mysql_enc_to_ruby.h | 47 +++++++++++++++-------------- support/mysql_enc_to_ruby.rb | 3 +- 3 files changed, 34 insertions(+), 32 deletions(-) diff --git a/ext/mysql2/mysql_enc_name_to_ruby.h b/ext/mysql2/mysql_enc_name_to_ruby.h index 60e029baf..9542e228a 100644 --- a/ext/mysql2/mysql_enc_name_to_ruby.h +++ b/ext/mysql2/mysql_enc_name_to_ruby.h @@ -1,4 +1,4 @@ -/* C code produced by gperf version 3.0.3 */ +/* C code produced by gperf version 3.0.4 */ /* Command-line: gperf */ /* Computed positions: -k'1,3,$' */ @@ -40,9 +40,9 @@ inline #endif #endif static unsigned int -mysql2_mysql_enc_name_to_rb_hash(str, len) +mysql2_mysql_enc_name_to_rb_hash (str, len) register const char *str; - register const unsigned int len; + register unsigned int len; { static const unsigned char asso_values[] = { @@ -78,14 +78,14 @@ mysql2_mysql_enc_name_to_rb_hash(str, len) #ifdef __GNUC__ __inline -#ifdef __GNUC_STDC_INLINE__ +#if defined __GNUC_STDC_INLINE__ || defined __GNUC_GNU_INLINE__ __attribute__ ((__gnu_inline__)) #endif #endif const struct mysql2_mysql_enc_name_to_rb_map * -mysql2_mysql_enc_name_to_rb(str, len) +mysql2_mysql_enc_name_to_rb (str, len) register const char *str; - register const unsigned int len; + register unsigned int len; { enum { @@ -154,9 +154,9 @@ mysql2_mysql_enc_name_to_rb(str, len) if (len <= MAX_WORD_LENGTH && len >= MIN_WORD_LENGTH) { - register const unsigned int key = mysql2_mysql_enc_name_to_rb_hash(str, len); + register int key = mysql2_mysql_enc_name_to_rb_hash (str, len); - if (key <= MAX_HASH_VALUE) + if (key <= MAX_HASH_VALUE && key >= 0) { register const char *s = wordlist[key].name; diff --git a/ext/mysql2/mysql_enc_to_ruby.h b/ext/mysql2/mysql_enc_to_ruby.h index 37dbf6f73..df167b2a6 100644 --- a/ext/mysql2/mysql_enc_to_ruby.h +++ b/ext/mysql2/mysql_enc_to_ruby.h @@ -1,4 +1,4 @@ -const char *mysql2_mysql_enc_to_rb[] = { +static const char *mysql2_mysql_enc_to_rb[] = { "Big5", "ISO-8859-2", NULL, @@ -54,13 +54,13 @@ const char *mysql2_mysql_enc_to_rb[] = { "macRoman", "UTF-16", "UTF-16", - NULL, + "", "Windows-1256", "Windows-1257", "Windows-1257", "UTF-32", "UTF-32", - NULL, + "", "ASCII-8BIT", NULL, "US-ASCII", @@ -119,10 +119,10 @@ const char *mysql2_mysql_enc_to_rb[] = { "UTF-16", "UTF-16", "UTF-16", - NULL, - NULL, - NULL, - NULL, + "UTF-16", + "UTF-16", + "UTF-16", + "UTF-16", NULL, NULL, NULL, @@ -146,6 +146,10 @@ const char *mysql2_mysql_enc_to_rb[] = { "UTF-16BE", "UTF-16BE", "UTF-16BE", + "UTF-16BE", + "UTF-16BE", + "UTF-16BE", + "UTF-16BE", NULL, NULL, NULL, @@ -153,11 +157,11 @@ const char *mysql2_mysql_enc_to_rb[] = { NULL, NULL, NULL, - NULL, - NULL, - NULL, - NULL, - NULL, + "UTF-16BE", + "UTF-32", + "UTF-32", + "UTF-32", + "UTF-32", "UTF-32", "UTF-32", "UTF-32", @@ -178,10 +182,6 @@ const char *mysql2_mysql_enc_to_rb[] = { "UTF-32", "UTF-32", "UTF-32", - NULL, - NULL, - NULL, - NULL, NULL, NULL, NULL, @@ -210,6 +210,10 @@ const char *mysql2_mysql_enc_to_rb[] = { "UTF-8", "UTF-8", "UTF-8", + "UTF-8", + "UTF-8", + "UTF-8", + "UTF-8", NULL, NULL, NULL, @@ -217,11 +221,11 @@ const char *mysql2_mysql_enc_to_rb[] = { NULL, NULL, NULL, - NULL, - NULL, - NULL, - NULL, - NULL, + "UTF-8", + "UTF-8", + "UTF-8", + "UTF-8", + "UTF-8", "UTF-8", "UTF-8", "UTF-8", @@ -243,4 +247,3 @@ const char *mysql2_mysql_enc_to_rb[] = { "UTF-8", "UTF-8" }; - diff --git a/support/mysql_enc_to_ruby.rb b/support/mysql_enc_to_ruby.rb index 4a3ef70db..39c513228 100644 --- a/support/mysql_enc_to_ruby.rb +++ b/support/mysql_enc_to_ruby.rb @@ -76,7 +76,6 @@ # start printing output -puts "const char *mysql2_mysql_enc_to_rb[] = {" +puts "static const char *mysql2_mysql_enc_to_rb[] = {" puts encodings_with_nil.join(",\n") puts "};" -puts From 1520b2b8b8b7ba544639e2d56f6662efda16fcb7 Mon Sep 17 00:00:00 2001 From: Tamir Duberstein Date: Thu, 11 Jun 2015 14:42:04 -0400 Subject: [PATCH 02/14] Include encodings only when needed --- ext/mysql2/result.c | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/ext/mysql2/result.c b/ext/mysql2/result.c index 7254e8e9c..c3cc00bc9 100644 --- a/ext/mysql2/result.c +++ b/ext/mysql2/result.c @@ -2,9 +2,9 @@ #include +#ifdef HAVE_RUBY_ENCODING_H #include "mysql_enc_to_ruby.h" -#ifdef HAVE_RUBY_ENCODING_H static rb_encoding *binaryEncoding; #endif From 8c90c4c552a1f2c5a9232004fe1083c6063e9494 Mon Sep 17 00:00:00 2001 From: Tamir Duberstein Date: Thu, 12 Mar 2015 17:03:48 -0700 Subject: [PATCH 03/14] Add RuboCop --- .rubocop.yml | 29 ++++ .rubocop_todo.yml | 330 ++++++++++++++++++++++++++++++++++++++++++++++ Gemfile | 1 + Rakefile | 10 +- 4 files changed, 369 insertions(+), 1 deletion(-) create mode 100644 .rubocop.yml create mode 100644 .rubocop_todo.yml diff --git a/.rubocop.yml b/.rubocop.yml new file mode 100644 index 000000000..5d3706d73 --- /dev/null +++ b/.rubocop.yml @@ -0,0 +1,29 @@ +inherit_from: .rubocop_todo.yml + +AllCops: + DisplayCopNames: true + Exclude: + - 'tmp/**/*' + +Lint/EndAlignment: + AlignWith: variable + +Style/CaseIndentation: + IndentWhenRelativeTo: end + +Style/IndentHash: + EnforcedStyle: consistent + +Style/TrailingComma: + EnforcedStyleForMultiline: comma + +Style/TrivialAccessors: + AllowPredicates: true + +# TODO: remove when we end support for < 1.9.3 + +Style/HashSyntax: + EnforcedStyle: hash_rockets + +Style/Lambda: + Enabled: false diff --git a/.rubocop_todo.yml b/.rubocop_todo.yml new file mode 100644 index 000000000..97d69cc20 --- /dev/null +++ b/.rubocop_todo.yml @@ -0,0 +1,330 @@ +# This configuration was generated by `rubocop --auto-gen-config` +# on 2015-03-12 17:39:18 -0700 using RuboCop version 0.29.1. +# The point is for the user to remove these configuration records +# one by one as the offenses are removed from the code base. +# Note that changes in the inspected code, or installation of new +# versions of RuboCop, may require this file to be generated again. + +# Offense count: 2 +# Configuration parameters: AllowSafeAssignment. +Lint/AssignmentInCondition: + Enabled: false + +# Offense count: 1 +# Cop supports --auto-correct. +Lint/DeprecatedClassMethods: + Enabled: false + +# Offense count: 1 +# Configuration parameters: AlignWith, SupportedStyles. +Lint/EndAlignment: + Enabled: false + +# Offense count: 1 +Lint/Eval: + Enabled: false + +# Offense count: 1 +Lint/RescueException: + Enabled: false + +# Offense count: 2 +Lint/ShadowingOuterLocalVariable: + Enabled: false + +# Offense count: 23 +# Cop supports --auto-correct. +Lint/UnusedBlockArgument: + Enabled: false + +# Offense count: 1 +Lint/UselessAccessModifier: + Enabled: false + +# Offense count: 4 +Lint/UselessAssignment: + Enabled: false + +# Offense count: 1 +Lint/Void: + Enabled: false + +# Offense count: 2 +Metrics/AbcSize: + Max: 64 + +# Offense count: 1 +Metrics/BlockNesting: + Max: 5 + +# Offense count: 2 +Metrics/CyclomaticComplexity: + Max: 21 + +# Offense count: 244 +# Configuration parameters: AllowURI, URISchemes. +Metrics/LineLength: + Max: 232 + +# Offense count: 4 +# Configuration parameters: CountComments. +Metrics/MethodLength: + Max: 40 + +# Offense count: 1 +Metrics/PerceivedComplexity: + Max: 20 + +# Offense count: 40 +# Cop supports --auto-correct. +Style/Blocks: + Enabled: false + +# Offense count: 8 +# Cop supports --auto-correct. +# Configuration parameters: EnforcedStyle, SupportedStyles. +Style/BracesAroundHashParameters: + Enabled: false + +# Offense count: 1 +# Configuration parameters: EnforcedStyle, SupportedStyles. +Style/ClassAndModuleChildren: + Enabled: false + +# Offense count: 1 +Style/ClassVars: + Enabled: false + +# Offense count: 2 +# Cop supports --auto-correct. +Style/CommentIndentation: + Enabled: false + +# Offense count: 1 +# Cop supports --auto-correct. +Style/DeprecatedHashMethods: + Enabled: false + +# Offense count: 9 +Style/Documentation: + Enabled: false + +# Offense count: 1 +Style/DoubleNegation: + Enabled: false + +# Offense count: 2 +# Cop supports --auto-correct. +Style/ElseAlignment: + Enabled: false + +# Offense count: 1 +# Cop supports --auto-correct. +Style/EmptyLines: + Enabled: false + +# Offense count: 1 +# Cop supports --auto-correct. +Style/EmptyLinesAroundAccessModifier: + Enabled: false + +# Offense count: 2 +# Cop supports --auto-correct. +# Configuration parameters: EnforcedStyle, SupportedStyles. +Style/EmptyLinesAroundModuleBody: + Enabled: false + +# Offense count: 9 +# Configuration parameters: AllowedVariables. +Style/GlobalVars: + Enabled: false + +# Offense count: 4 +# Configuration parameters: MaxLineLength. +Style/IfUnlessModifier: + Enabled: false + +# Offense count: 1 +# Cop supports --auto-correct. +Style/IndentationConsistency: + Enabled: false + +# Offense count: 3 +# Cop supports --auto-correct. +# Configuration parameters: Width. +Style/IndentationWidth: + Enabled: false + +# Offense count: 3 +# Cop supports --auto-correct. +# Configuration parameters: EnforcedStyle, SupportedStyles. +Style/MethodDefParentheses: + Enabled: false + +# Offense count: 1 +Style/MultilineBlockChain: + Enabled: false + +# Offense count: 2 +# Cop supports --auto-correct. +Style/MultilineIfThen: + Enabled: false + +# Offense count: 1 +# Cop supports --auto-correct. +Style/NegatedIf: + Enabled: false + +# Offense count: 1 +# Cop supports --auto-correct. +Style/NegatedWhile: + Enabled: false + +# Offense count: 1 +# Cop supports --auto-correct. +Style/Not: + Enabled: false + +# Offense count: 13 +# Cop supports --auto-correct. +Style/NumericLiterals: + MinDigits: 20 + +# Offense count: 7 +# Cop supports --auto-correct. +# Configuration parameters: PreferredDelimiters. +Style/PercentLiteralDelimiters: + Enabled: false + +# Offense count: 1 +# Configuration parameters: SupportedStyles. +Style/RaiseArgs: + EnforcedStyle: compact + +# Offense count: 1 +# Cop supports --auto-correct. +Style/RedundantSelf: + Enabled: false + +# Offense count: 1 +Style/RegexpLiteral: + MaxSlashes: 0 + +# Offense count: 2 +# Cop supports --auto-correct. +# Configuration parameters: EnforcedStyle, SupportedStyles. +Style/SignalException: + Enabled: false + +# Offense count: 9 +# Cop supports --auto-correct. +Style/SingleSpaceBeforeFirstArg: + Enabled: false + +# Offense count: 6 +# Cop supports --auto-correct. +Style/SpaceAfterComma: + Enabled: false + +# Offense count: 1 +# Cop supports --auto-correct. +Style/SpaceAfterControlKeyword: + Enabled: false + +# Offense count: 1 +# Cop supports --auto-correct. +Style/SpaceAfterNot: + Enabled: false + +# Offense count: 3 +# Cop supports --auto-correct. +# Configuration parameters: EnforcedStyle, SupportedStyles. +Style/SpaceAroundEqualsInParameterDefault: + Enabled: false + +# Offense count: 5 +# Cop supports --auto-correct. +Style/SpaceAroundOperators: + Enabled: false + +# Offense count: 5 +# Cop supports --auto-correct. +# Configuration parameters: EnforcedStyle, SupportedStyles. +Style/SpaceBeforeBlockBraces: + Enabled: false + +# Offense count: 14 +# Cop supports --auto-correct. +# Configuration parameters: EnforcedStyle, SupportedStyles, EnforcedStyleForEmptyBraces, SpaceBeforeBlockParameters. +Style/SpaceInsideBlockBraces: + Enabled: false + +# Offense count: 2 +# Cop supports --auto-correct. +Style/SpaceInsideBrackets: + Enabled: false + +# Offense count: 8 +# Cop supports --auto-correct. +# Configuration parameters: EnforcedStyle, EnforcedStyleForEmptyBraces, SupportedStyles. +Style/SpaceInsideHashLiteralBraces: + Enabled: false + +# Offense count: 4 +# Cop supports --auto-correct. +Style/SpaceInsideParens: + Enabled: false + +# Offense count: 2 +# Cop supports --auto-correct. +Style/SpecialGlobalVars: + Enabled: false + +# Offense count: 550 +# Cop supports --auto-correct. +# Configuration parameters: EnforcedStyle, SupportedStyles. +Style/StringLiterals: + Enabled: false + +# Offense count: 1 +# Cop supports --auto-correct. +# Configuration parameters: IgnoredMethods. +Style/SymbolProc: + Enabled: false + +# Offense count: 2 +# Cop supports --auto-correct. +# Configuration parameters: EnforcedStyle, SupportedStyles. +Style/TrailingBlankLines: + Enabled: false + +# Offense count: 6 +# Cop supports --auto-correct. +# Configuration parameters: EnforcedStyleForMultiline, SupportedStyles. +Style/TrailingComma: + Enabled: false + +# Offense count: 2 +Style/UnlessElse: + Enabled: false + +# Offense count: 4 +# Cop supports --auto-correct. +Style/UnneededPercentQ: + Enabled: false + +# Offense count: 1 +# Cop supports --auto-correct. +Style/WhileUntilDo: + Enabled: false + +# Offense count: 1 +# Configuration parameters: MaxLineLength. +Style/WhileUntilModifier: + Enabled: false + +# Offense count: 4 +# Cop supports --auto-correct. +# Configuration parameters: WordRegex. +Style/WordArray: + MinSize: 5 diff --git a/Gemfile b/Gemfile index 27be870e3..502541282 100644 --- a/Gemfile +++ b/Gemfile @@ -8,6 +8,7 @@ gem 'rake-compiler', '~> 0.9.5' group :test do gem 'eventmachine' unless RUBY_PLATFORM =~ /mswin|mingw/ gem 'rspec', '~> 3.2' + gem 'rubocop', '~> 0.29.1' unless RUBY_VERSION =~ /1.8/ end group :benchmarks do diff --git a/Rakefile b/Rakefile index 3ff7a8d24..433039c5b 100644 --- a/Rakefile +++ b/Rakefile @@ -8,4 +8,12 @@ load 'tasks/compile.rake' load 'tasks/generate.rake' load 'tasks/benchmarks.rake' -task :default => :spec +# TODO: remove when we end support for < 1.9.3 +if RUBY_VERSION =~ /1.8/ + task :default => :spec +else + require 'rubocop/rake_task' + RuboCop::RakeTask.new + + task :default => [:spec, :rubocop] +end From c5b8a1698d209982711e669a63ec3f833f73e58a Mon Sep 17 00:00:00 2001 From: Tamir Duberstein Date: Thu, 12 Mar 2015 17:30:11 -0700 Subject: [PATCH 04/14] Autocorrect the easy stuff --- .rubocop.yml | 2 +- .rubocop_todo.yml | 218 +--------------------------------- Gemfile | 2 +- benchmark/allocations.rb | 2 - benchmark/setup_db.rb | 10 +- examples/eventmachine.rb | 2 +- ext/mysql2/extconf.rb | 29 ++--- lib/mysql2.rb | 24 ++-- lib/mysql2/client.rb | 15 +-- lib/mysql2/em.rb | 4 +- lib/mysql2/error.rb | 6 +- lib/mysql2/field.rb | 3 +- mysql2.gemspec | 6 +- spec/em/em_spec.rb | 2 +- spec/mysql2/client_spec.rb | 32 ++--- spec/mysql2/result_spec.rb | 22 ++-- spec/mysql2/statement_spec.rb | 35 +++--- support/mysql_enc_to_ruby.rb | 4 +- support/ruby_enc_to_mysql.rb | 2 +- tasks/benchmarks.rake | 6 +- tasks/compile.rake | 8 +- tasks/rspec.rake | 24 ++-- tasks/vendor_mysql.rake | 4 +- 23 files changed, 125 insertions(+), 337 deletions(-) diff --git a/.rubocop.yml b/.rubocop.yml index 5d3706d73..0b7e938d4 100644 --- a/.rubocop.yml +++ b/.rubocop.yml @@ -15,7 +15,7 @@ Style/IndentHash: EnforcedStyle: consistent Style/TrailingComma: - EnforcedStyleForMultiline: comma + EnforcedStyleForMultiline: consistent_comma Style/TrivialAccessors: AllowPredicates: true diff --git a/.rubocop_todo.yml b/.rubocop_todo.yml index 97d69cc20..bdc588623 100644 --- a/.rubocop_todo.yml +++ b/.rubocop_todo.yml @@ -1,5 +1,5 @@ # This configuration was generated by `rubocop --auto-gen-config` -# on 2015-03-12 17:39:18 -0700 using RuboCop version 0.29.1. +# on 2015-03-12 17:46:21 -0700 using RuboCop version 0.29.1. # The point is for the user to remove these configuration records # one by one as the offenses are removed from the code base. # Note that changes in the inspected code, or installation of new @@ -10,16 +10,6 @@ Lint/AssignmentInCondition: Enabled: false -# Offense count: 1 -# Cop supports --auto-correct. -Lint/DeprecatedClassMethods: - Enabled: false - -# Offense count: 1 -# Configuration parameters: AlignWith, SupportedStyles. -Lint/EndAlignment: - Enabled: false - # Offense count: 1 Lint/Eval: Enabled: false @@ -59,9 +49,9 @@ Metrics/BlockNesting: # Offense count: 2 Metrics/CyclomaticComplexity: - Max: 21 + Max: 23 -# Offense count: 244 +# Offense count: 238 # Configuration parameters: AllowURI, URISchemes. Metrics/LineLength: Max: 232 @@ -77,13 +67,7 @@ Metrics/PerceivedComplexity: # Offense count: 40 # Cop supports --auto-correct. -Style/Blocks: - Enabled: false - -# Offense count: 8 -# Cop supports --auto-correct. -# Configuration parameters: EnforcedStyle, SupportedStyles. -Style/BracesAroundHashParameters: +Style/BlockDelimiters: Enabled: false # Offense count: 1 @@ -95,16 +79,6 @@ Style/ClassAndModuleChildren: Style/ClassVars: Enabled: false -# Offense count: 2 -# Cop supports --auto-correct. -Style/CommentIndentation: - Enabled: false - -# Offense count: 1 -# Cop supports --auto-correct. -Style/DeprecatedHashMethods: - Enabled: false - # Offense count: 9 Style/Documentation: Enabled: false @@ -113,27 +87,6 @@ Style/Documentation: Style/DoubleNegation: Enabled: false -# Offense count: 2 -# Cop supports --auto-correct. -Style/ElseAlignment: - Enabled: false - -# Offense count: 1 -# Cop supports --auto-correct. -Style/EmptyLines: - Enabled: false - -# Offense count: 1 -# Cop supports --auto-correct. -Style/EmptyLinesAroundAccessModifier: - Enabled: false - -# Offense count: 2 -# Cop supports --auto-correct. -# Configuration parameters: EnforcedStyle, SupportedStyles. -Style/EmptyLinesAroundModuleBody: - Enabled: false - # Offense count: 9 # Configuration parameters: AllowedVariables. Style/GlobalVars: @@ -144,187 +97,26 @@ Style/GlobalVars: Style/IfUnlessModifier: Enabled: false -# Offense count: 1 -# Cop supports --auto-correct. -Style/IndentationConsistency: - Enabled: false - -# Offense count: 3 -# Cop supports --auto-correct. -# Configuration parameters: Width. -Style/IndentationWidth: - Enabled: false - -# Offense count: 3 -# Cop supports --auto-correct. -# Configuration parameters: EnforcedStyle, SupportedStyles. -Style/MethodDefParentheses: - Enabled: false - # Offense count: 1 Style/MultilineBlockChain: Enabled: false -# Offense count: 2 -# Cop supports --auto-correct. -Style/MultilineIfThen: - Enabled: false - -# Offense count: 1 -# Cop supports --auto-correct. -Style/NegatedIf: - Enabled: false - -# Offense count: 1 -# Cop supports --auto-correct. -Style/NegatedWhile: - Enabled: false - -# Offense count: 1 -# Cop supports --auto-correct. -Style/Not: - Enabled: false - # Offense count: 13 # Cop supports --auto-correct. Style/NumericLiterals: MinDigits: 20 -# Offense count: 7 -# Cop supports --auto-correct. -# Configuration parameters: PreferredDelimiters. -Style/PercentLiteralDelimiters: - Enabled: false - -# Offense count: 1 -# Configuration parameters: SupportedStyles. -Style/RaiseArgs: - EnforcedStyle: compact - -# Offense count: 1 -# Cop supports --auto-correct. -Style/RedundantSelf: - Enabled: false - -# Offense count: 1 -Style/RegexpLiteral: - MaxSlashes: 0 - -# Offense count: 2 -# Cop supports --auto-correct. -# Configuration parameters: EnforcedStyle, SupportedStyles. -Style/SignalException: - Enabled: false - -# Offense count: 9 -# Cop supports --auto-correct. -Style/SingleSpaceBeforeFirstArg: - Enabled: false - -# Offense count: 6 -# Cop supports --auto-correct. -Style/SpaceAfterComma: - Enabled: false - -# Offense count: 1 -# Cop supports --auto-correct. -Style/SpaceAfterControlKeyword: - Enabled: false - -# Offense count: 1 -# Cop supports --auto-correct. -Style/SpaceAfterNot: - Enabled: false - -# Offense count: 3 -# Cop supports --auto-correct. -# Configuration parameters: EnforcedStyle, SupportedStyles. -Style/SpaceAroundEqualsInParameterDefault: - Enabled: false - -# Offense count: 5 -# Cop supports --auto-correct. -Style/SpaceAroundOperators: - Enabled: false - -# Offense count: 5 -# Cop supports --auto-correct. -# Configuration parameters: EnforcedStyle, SupportedStyles. -Style/SpaceBeforeBlockBraces: - Enabled: false - -# Offense count: 14 -# Cop supports --auto-correct. -# Configuration parameters: EnforcedStyle, SupportedStyles, EnforcedStyleForEmptyBraces, SpaceBeforeBlockParameters. -Style/SpaceInsideBlockBraces: - Enabled: false - -# Offense count: 2 -# Cop supports --auto-correct. -Style/SpaceInsideBrackets: - Enabled: false - -# Offense count: 8 -# Cop supports --auto-correct. -# Configuration parameters: EnforcedStyle, EnforcedStyleForEmptyBraces, SupportedStyles. -Style/SpaceInsideHashLiteralBraces: - Enabled: false - -# Offense count: 4 -# Cop supports --auto-correct. -Style/SpaceInsideParens: - Enabled: false - -# Offense count: 2 -# Cop supports --auto-correct. -Style/SpecialGlobalVars: - Enabled: false - -# Offense count: 550 +# Offense count: 549 # Cop supports --auto-correct. # Configuration parameters: EnforcedStyle, SupportedStyles. Style/StringLiterals: Enabled: false -# Offense count: 1 -# Cop supports --auto-correct. -# Configuration parameters: IgnoredMethods. -Style/SymbolProc: - Enabled: false - -# Offense count: 2 -# Cop supports --auto-correct. -# Configuration parameters: EnforcedStyle, SupportedStyles. -Style/TrailingBlankLines: - Enabled: false - -# Offense count: 6 -# Cop supports --auto-correct. -# Configuration parameters: EnforcedStyleForMultiline, SupportedStyles. -Style/TrailingComma: - Enabled: false - # Offense count: 2 Style/UnlessElse: Enabled: false -# Offense count: 4 -# Cop supports --auto-correct. -Style/UnneededPercentQ: - Enabled: false - -# Offense count: 1 -# Cop supports --auto-correct. -Style/WhileUntilDo: - Enabled: false - # Offense count: 1 # Configuration parameters: MaxLineLength. Style/WhileUntilModifier: Enabled: false - -# Offense count: 4 -# Cop supports --auto-correct. -# Configuration parameters: WordRegex. -Style/WordArray: - MinSize: 5 diff --git a/Gemfile b/Gemfile index 502541282..117579391 100644 --- a/Gemfile +++ b/Gemfile @@ -8,7 +8,7 @@ gem 'rake-compiler', '~> 0.9.5' group :test do gem 'eventmachine' unless RUBY_PLATFORM =~ /mswin|mingw/ gem 'rspec', '~> 3.2' - gem 'rubocop', '~> 0.29.1' unless RUBY_VERSION =~ /1.8/ + gem 'rubocop', '~> 0.32.0' unless RUBY_VERSION =~ /1.8/ end group :benchmarks do diff --git a/benchmark/allocations.rb b/benchmark/allocations.rb index 394c0c7e5..4e3579313 100644 --- a/benchmark/allocations.rb +++ b/benchmark/allocations.rb @@ -4,8 +4,6 @@ require 'rubygems' require 'active_record' -raise Mysql2::Error.new("GC allocation benchmarks only supported on Ruby 1.9!") unless RUBY_VERSION > '1.9' - ActiveRecord::Base.default_timezone = :local ActiveRecord::Base.time_zone_aware_attributes = true diff --git a/benchmark/setup_db.rb b/benchmark/setup_db.rb index 9ad8518e1..105d43ebc 100644 --- a/benchmark/setup_db.rb +++ b/benchmark/setup_db.rb @@ -86,10 +86,10 @@ def insert_record(args) :medium_int_test => rand(8388607), :int_test => rand(2147483647), :big_int_test => rand(9223372036854775807), - :float_test => rand(32767)/1.87, + :float_test => rand(32767) / 1.87, :float_zero_test => 0.0, - :double_test => rand(8388607)/1.87, - :decimal_test => rand(8388607)/1.87, + :double_test => rand(8388607) / 1.87, + :decimal_test => rand(8388607) / 1.87, :decimal_zero_test => 0, :date_test => '2010-4-4', :date_time_test => '2010-4-4 11:44:00', @@ -108,8 +108,8 @@ def insert_record(args) :medium_text_test => twenty5_paragraphs, :long_blob_test => twenty5_paragraphs, :long_text_test => twenty5_paragraphs, - :enum_test => ['val1', 'val2'][rand(2)], - :set_test => ['val1', 'val2', 'val1,val2'][rand(3)] + :enum_test => %w(val1 val2).sample, + :set_test => %w(val1 val2 val1,val2).sample, ) if n % 100 == 0 $stdout.putc '.' diff --git a/examples/eventmachine.rb b/examples/eventmachine.rb index a92ca4cb1..273f1bc52 100644 --- a/examples/eventmachine.rb +++ b/examples/eventmachine.rb @@ -18,4 +18,4 @@ defer2.callback do |result| puts "Result: #{result.to_a.inspect}" end -end \ No newline at end of file +end diff --git a/ext/mysql2/extconf.rb b/ext/mysql2/extconf.rb index 492766c45..452314647 100644 --- a/ext/mysql2/extconf.rb +++ b/ext/mysql2/extconf.rb @@ -1,7 +1,8 @@ # encoding: UTF-8 require 'mkmf' +require 'English' -def asplode lib +def asplode(lib) if RUBY_PLATFORM =~ /mingw|mswin/ abort "-----\n#{lib} is missing. Check your installation of MySQL or Connector/C, and try again.\n-----" elsif RUBY_PLATFORM =~ /darwin/ @@ -22,7 +23,7 @@ def asplode lib # borrowed from mysqlplus # http://github.com/oldmoe/mysqlplus/blob/master/ext/extconf.rb -dirs = ENV['PATH'].split(File::PATH_SEPARATOR) + %w[ +dirs = ENV.fetch('PATH').split(File::PATH_SEPARATOR) + %w( /opt /opt/local /opt/local/mysql @@ -34,7 +35,7 @@ def asplode lib /usr/local/mysql-* /usr/local/lib/mysql5* /usr/local/opt/mysql5* -].map{|dir| "#{dir}/bin" } +).map { |dir| dir << '/bin' } GLOB = "{#{dirs.join(',')}}/{mysql_config,mysql_config5,mariadb_config}" @@ -48,26 +49,26 @@ def asplode lib @libdir_basename = 'lib' inc, lib = dir_config('mysql') end - abort "-----\nCannot find include dir(s) #{inc}\n-----" unless inc && inc.split(File::PATH_SEPARATOR).any?{|dir| File.directory?(dir)} - abort "-----\nCannot find library dir(s) #{lib}\n-----" unless lib && lib.split(File::PATH_SEPARATOR).any?{|dir| File.directory?(dir)} - warn "-----\nUsing --with-mysql-dir=#{File.dirname inc}\n-----" + abort "-----\nCannot find include dir(s) #{inc}\n-----" unless inc && inc.split(File::PATH_SEPARATOR).any? { |dir| File.directory?(dir) } + abort "-----\nCannot find library dir(s) #{lib}\n-----" unless lib && lib.split(File::PATH_SEPARATOR).any? { |dir| File.directory?(dir) } + warn "-----\nUsing --with-mysql-dir=#{File.dirname inc}\n-----" rpath_dir = lib elsif mc = (with_config('mysql-config') || Dir[GLOB].first) # If the user has provided a --with-mysql-config argument, we must respect it or fail. # If the user gave --with-mysql-config with no argument means we should try to find it. mc = Dir[GLOB].first if mc == true - abort "-----\nCannot find mysql_config at #{mc}\n-----" unless mc && File.exists?(mc) + abort "-----\nCannot find mysql_config at #{mc}\n-----" unless mc && File.exist?(mc) abort "-----\nCannot execute mysql_config at #{mc}\n-----" unless File.executable?(mc) - warn "-----\nUsing mysql_config at #{mc}\n-----" + warn "-----\nUsing mysql_config at #{mc}\n-----" ver = `#{mc} --version`.chomp.to_f includes = `#{mc} --include`.chomp - exit 1 if $? != 0 + abort unless $CHILD_STATUS.success? libs = `#{mc} --libs_r`.chomp # MySQL 5.5 and above already have re-entrant code in libmysqlclient (no _r). if ver >= 5.5 || libs.empty? libs = `#{mc} --libs`.chomp end - exit 1 if $? != 0 + abort unless $CHILD_STATUS.success? $INCFLAGS += ' ' + includes $libs = libs + " " + $libs rpath_dir = libs @@ -87,7 +88,7 @@ def asplode lib asplode 'mysql.h' end -%w{ errmsg.h mysqld_error.h }.each do |h| +%w(errmsg.h mysqld_error.h).each do |h| header = [prefix, h].compact.join '/' asplode h unless have_header h end @@ -122,9 +123,9 @@ def asplode lib # Maybe in the future Ruby could provide RbConfig::CONFIG['DLLTOOL'] directly. dlltool = RbConfig::CONFIG['DLLWRAP'].gsub('dllwrap', 'dlltool') sh dlltool, '--kill-at', - '--dllname', 'libmysql.dll', - '--output-lib', 'libmysql.a', - '--input-def', deffile, libfile + '--dllname', 'libmysql.dll', + '--output-lib', 'libmysql.a', + '--input-def', deffile, libfile end end diff --git a/lib/mysql2.rb b/lib/mysql2.rb index 5c4e6aab4..92268bea3 100644 --- a/lib/mysql2.rb +++ b/lib/mysql2.rb @@ -8,16 +8,16 @@ # Or to bomb out with a clear error message instead of a linker crash if RUBY_PLATFORM =~ /mswin|mingw/ dll_path = if ENV['RUBY_MYSQL2_LIBMYSQL_DLL'] - # If this environment variable is set, it overrides any other paths - # The user is advised to use backslashes not forward slashes - ENV['RUBY_MYSQL2_LIBMYSQL_DLL'].dup - elsif File.exist?(File.expand_path('../vendor/libmysql.dll', File.dirname(__FILE__))) - # Use vendor/libmysql.dll if it exists, convert slashes for Win32 LoadLibrary - File.expand_path('../vendor/libmysql.dll', File.dirname(__FILE__)).gsub('/', '\\') - else - # This will use default / system library paths - 'libmysql.dll' - end + # If this environment variable is set, it overrides any other paths + # The user is advised to use backslashes not forward slashes + ENV['RUBY_MYSQL2_LIBMYSQL_DLL'].dup + elsif File.exist?(File.expand_path('../vendor/libmysql.dll', File.dirname(__FILE__))) + # Use vendor/libmysql.dll if it exists, convert slashes for Win32 LoadLibrary + File.expand_path('../vendor/libmysql.dll', File.dirname(__FILE__)).gsub('/', '\\') + else + # This will use default / system library paths + 'libmysql.dll' + end require 'Win32API' LoadLibrary = Win32API.new('Kernel32', 'LoadLibrary', ['P'], 'I') @@ -54,13 +54,11 @@ module Mysql2 # For holding utility methods module Mysql2::Util - # # Rekey a string-keyed hash with equivalent symbols. # def self.key_hash_as_symbols(hash) return nil unless hash - Hash[hash.map { |k,v| [k.to_sym, v] }] + Hash[hash.map { |k, v| [k.to_sym, v] }] end - end diff --git a/lib/mysql2/client.rb b/lib/mysql2/client.rb index 595cc8793..f67d78518 100644 --- a/lib/mysql2/client.rb +++ b/lib/mysql2/client.rb @@ -12,11 +12,11 @@ class Client :connect_flags => REMEMBER_OPTIONS | LONG_PASSWORD | LONG_FLAG | TRANSACTIONS | PROTOCOL_41 | SECURE_CONNECTION, :cast => true, :default_file => nil, - :default_group => nil + :default_group => nil, } def initialize(opts = {}) - opts = Mysql2::Util.key_hash_as_symbols( opts ) + opts = Mysql2::Util.key_hash_as_symbols(opts) @read_timeout = nil @query_options = @@default_query_options.dup @query_options.merge! opts @@ -48,9 +48,9 @@ def initialize(opts = {}) flags = 0 flags |= @query_options[:connect_flags] flags |= opts[:flags] if opts[:flags] - flags |= SSL_VERIFY_SERVER_CERT if opts[:sslverify] and ssl_options.any? + flags |= SSL_VERIFY_SERVER_CERT if opts[:sslverify] && ssl_options.any? - if [:user,:pass,:hostname,:dbname,:db,:sock].any?{|k| @query_options.has_key?(k) } + if [:user, :pass, :hostname, :dbname, :db, :sock].any? { |k| @query_options.key?(k) } warn "============= WARNING FROM mysql2 =============" warn "The options :user, :pass, :hostname, :dbname, :db, and :sock will be deprecated at some point in the future." warn "Instead, please use :username, :password, :host, :port, :database, :socket, :flags for the options." @@ -106,8 +106,9 @@ def info end private - def self.local_offset - ::Time.local(2010).utc_offset.to_r / 86400 - end + + def self.local_offset + ::Time.local(2010).utc_offset.to_r / 86400 + end end end diff --git a/lib/mysql2/em.rb b/lib/mysql2/em.rb index b21265994..cfb389d51 100644 --- a/lib/mysql2/em.rb +++ b/lib/mysql2/em.rb @@ -40,11 +40,11 @@ def close(*args) super(*args) end - def query(sql, opts={}) + def query(sql, opts = {}) if ::EM.reactor_running? super(sql, opts.merge(:async => true)) deferable = ::EM::DefaultDeferrable.new - @watch = ::EM.watch(self.socket, Watcher, self, deferable) + @watch = ::EM.watch(socket, Watcher, self, deferable) @watch.notify_readable = true deferable else diff --git a/lib/mysql2/error.rb b/lib/mysql2/error.rb index 1bcbb8d23..5eec6fff0 100644 --- a/lib/mysql2/error.rb +++ b/lib/mysql2/error.rb @@ -9,14 +9,14 @@ class Error < StandardError }.freeze attr_accessor :error_number - attr_reader :sql_state - attr_writer :server_version + attr_reader :sql_state + attr_writer :server_version # Mysql gem compatibility alias_method :errno, :error_number alias_method :error, :message - def initialize(msg, server_version=nil) + def initialize(msg, server_version = nil) self.server_version = server_version super(clean_message(msg)) diff --git a/lib/mysql2/field.rb b/lib/mysql2/field.rb index 4ca28ca0a..516ec17c2 100644 --- a/lib/mysql2/field.rb +++ b/lib/mysql2/field.rb @@ -1,4 +1,3 @@ module Mysql2 - class Field < Struct.new(:name, :type) - end + Field = Struct.new(:name, :type) end diff --git a/mysql2.gemspec b/mysql2.gemspec index 2132e1a6c..1113b6862 100644 --- a/mysql2.gemspec +++ b/mysql2.gemspec @@ -1,15 +1,15 @@ require File.expand_path('../lib/mysql2/version', __FILE__) Gem::Specification.new do |s| - s.name = %q{mysql2} + s.name = 'mysql2' s.version = Mysql2::VERSION s.authors = ['Brian Lopez', 'Aaron Stone'] s.license = "MIT" s.email = ['seniorlopez@gmail.com', 'aaron@serendipity.cx'] s.extensions = ["ext/mysql2/extconf.rb"] - s.homepage = %q{http://github.com/brianmario/mysql2} + s.homepage = 'http://github.com/brianmario/mysql2' s.rdoc_options = ["--charset=UTF-8"] - s.summary = %q{A simple, fast Mysql library for Ruby, binding to libmysql} + s.summary = 'A simple, fast Mysql library for Ruby, binding to libmysql' s.files = `git ls-files README.md CHANGELOG.md LICENSE ext lib support`.split s.test_files = `git ls-files spec examples`.split diff --git a/spec/em/em_spec.rb b/spec/em/em_spec.rb index 8890e285c..30e027e9d 100644 --- a/spec/em/em_spec.rb +++ b/spec/em/em_spec.rb @@ -55,7 +55,7 @@ defer = client.query "SELECT sleep(0.1) as first_query" defer.callback do |result| client.close - raise 'some error' + fail 'some error' end defer.errback do |err| # This _shouldn't_ be run, but it needed to prevent the specs from diff --git a/spec/mysql2/client_spec.rb b/spec/mysql2/client_spec.rb index 939bebc54..b84cf7441 100644 --- a/spec/mysql2/client_spec.rb +++ b/spec/mysql2/client_spec.rb @@ -46,7 +46,7 @@ it "should accept connect flags and pass them to #connect" do klient = Class.new(Mysql2::Client) do attr_reader :connect_args - def connect *args + def connect(*args) @connect_args ||= [] @connect_args << args end @@ -58,7 +58,7 @@ def connect *args it "should default flags to (REMEMBER_OPTIONS, LONG_PASSWORD, LONG_FLAG, TRANSACTIONS, PROTOCOL_41, SECURE_CONNECTION)" do klient = Class.new(Mysql2::Client) do attr_reader :connect_args - def connect *args + def connect(*args) @connect_args ||= [] @connect_args << args end @@ -117,9 +117,9 @@ def connect *args it "should be able to connect via SSL options" do ssl = @client.query "SHOW VARIABLES LIKE 'have_ssl'" - ssl_uncompiled = ssl.any? {|x| x['Value'] == 'OFF'} + ssl_uncompiled = ssl.any? { |x| x['Value'] == 'OFF' } pending("DON'T WORRY, THIS TEST PASSES - but SSL is not compiled into your MySQL daemon.") if ssl_uncompiled - ssl_disabled = ssl.any? {|x| x['Value'] == 'DISABLED'} + ssl_disabled = ssl.any? { |x| x['Value'] == 'DISABLED' } pending("DON'T WORRY, THIS TEST PASSES - but SSL is not enabled in your MySQL daemon.") if ssl_disabled # You may need to adjust the lines below to match your SSL certificate paths @@ -132,7 +132,7 @@ def connect *args :sslcert => '/etc/mysql/client-cert.pem', :sslca => '/etc/mysql/ca-cert.pem', :sslcipher => 'DHE-RSA-AES256-SHA', - :sslverify => true + :sslverify => true, ) ) }.not_to raise_error @@ -185,7 +185,7 @@ def run_gc # this empty `fork` call fixes this tests on RBX; without it, the next # `fork` call hangs forever. WTF? - fork { } + fork {} fork do client.query('SELECT 1') @@ -267,7 +267,7 @@ def run_gc # # Note that mysql_info() returns a non-NULL value for INSERT ... VALUES only for the multiple-row form of the statement (that is, only if multiple value lists are specified). @client.query("INSERT INTO infoTest (blah) VALUES (1234),(4535)") - expect(@client.query_info).to eql({:records => 2, :duplicates => 0, :warnings => 0}) + expect(@client.query_info).to eql(:records => 2, :duplicates => 0, :warnings => 0) expect(@client.query_info_string).to eq('Records: 2 Duplicates: 0 Warnings: 0') @client.query "DROP TABLE infoTest" @@ -279,7 +279,7 @@ def run_gc before(:all) do @client_i = Mysql2::Client.new DatabaseCredentials['root'].merge(:local_infile => true) local = @client_i.query "SHOW VARIABLES LIKE 'local_infile'" - local_enabled = local.any? {|x| x['Value'] == 'ON'} + local_enabled = local.any? { |x| x['Value'] == 'ON' } pending("DON'T WORRY, THIS TEST PASSES - but LOCAL INFILE is not enabled in your MySQL daemon.") unless local_enabled @client_i.query %[ @@ -311,10 +311,10 @@ def run_gc it "should LOAD DATA LOCAL INFILE" do @client_i.query "LOAD DATA LOCAL INFILE 'spec/test_data' INTO TABLE infileTest" info = @client_i.query_info - expect(info).to eql({:records => 1, :deleted => 0, :skipped => 0, :warnings => 0}) + expect(info).to eql(:records => 1, :deleted => 0, :skipped => 0, :warnings => 0) result = @client_i.query "SELECT * FROM infileTest" - expect(result.first).to eql({'id' => 1, 'foo' => 'Hello', 'bar' => 'World'}) + expect(result.first).to eql('id' => 1, 'foo' => 'Hello', 'bar' => 'World') end end @@ -564,21 +564,21 @@ def run_gc end it "returns multiple result sets" do - expect(@multi_client.query("SELECT 1 AS 'set_1'; SELECT 2 AS 'set_2'").first).to eql({ 'set_1' => 1 }) + expect(@multi_client.query("SELECT 1 AS 'set_1'; SELECT 2 AS 'set_2'").first).to eql('set_1' => 1) expect(@multi_client.next_result).to be true - expect(@multi_client.store_result.first).to eql({ 'set_2' => 2 }) + expect(@multi_client.store_result.first).to eql('set_2' => 2) expect(@multi_client.next_result).to be false end it "does not interfere with other statements" do @multi_client.query("SELECT 1 AS 'set_1'; SELECT 2 AS 'set_2'") - while( @multi_client.next_result ) + while @multi_client.next_result @multi_client.store_result end - expect(@multi_client.query("SELECT 3 AS 'next'").first).to eq({ 'next' => 3 }) + expect(@multi_client.query("SELECT 3 AS 'next'").first).to eq('next' => 3) end it "will raise on query if there are outstanding results to read" do @@ -609,11 +609,11 @@ def run_gc it "#more_results? should work with stored procedures" do @multi_client.query("DROP PROCEDURE IF EXISTS test_proc") @multi_client.query("CREATE PROCEDURE test_proc() BEGIN SELECT 1 AS 'set_1'; SELECT 2 AS 'set_2'; END") - expect(@multi_client.query("CALL test_proc()").first).to eql({ 'set_1' => 1 }) + expect(@multi_client.query("CALL test_proc()").first).to eql('set_1' => 1) expect(@multi_client.more_results?).to be true @multi_client.next_result - expect(@multi_client.store_result.first).to eql({ 'set_2' => 2 }) + expect(@multi_client.store_result.first).to eql('set_2' => 2) @multi_client.next_result expect(@multi_client.store_result).to be_nil # this is the result from CALL itself diff --git a/spec/mysql2/result_spec.rb b/spec/mysql2/result_spec.rb index 85f5c00c3..d867765ec 100644 --- a/spec/mysql2/result_spec.rb +++ b/spec/mysql2/result_spec.rb @@ -109,7 +109,7 @@ it "should return an array of field names in proper order" do result = @client.query "SELECT 'a', 'b', 'c'" - expect(result.fields).to eql(['a', 'b', 'c']) + expect(result.fields).to eql(%w(a b c)) end end @@ -132,7 +132,7 @@ it "should not yield nil at the end of streaming" do result = @client.query('SELECT * FROM mysql2_test', :stream => true, :cache_rows => false) - result.each { |r| expect(r).not_to be_nil} + result.each { |r| expect(r).not_to be_nil } end it "#count should be zero for rows after streaming when there were no results" do @@ -174,11 +174,11 @@ it "should return nil values for NULL and strings for everything else when :cast is false" do result = @client.query('SELECT null_test, tiny_int_test, bool_cast_test, int_test, date_test, enum_test FROM mysql2_test WHERE bool_cast_test = 1 LIMIT 1', :cast => false).first expect(result["null_test"]).to be_nil - expect(result["tiny_int_test"]).to eql("1") + expect(result["tiny_int_test"]).to eql("1") expect(result["bool_cast_test"]).to eql("1") - expect(result["int_test"]).to eql("10") - expect(result["date_test"]).to eql("2010-04-04") - expect(result["enum_test"]).to eql("val1") + expect(result["int_test"]).to eql("10") + expect(result["date_test"]).to eql("2010-04-04") + expect(result["enum_test"]).to eql("val1") end it "should return nil for a NULL value" do @@ -286,13 +286,13 @@ end it "should return DateTime when timestamp is < 1901-12-13 20:45:52" do - # 1901-12-13T20:45:52 is the min for 32bit Ruby 1.8 + # 1901-12-13T20:45:52 is the min for 32bit Ruby 1.8 r = @client.query("SELECT CAST('1901-12-13 20:45:51' AS DATETIME) as test") expect(r.first['test']).to be_an_instance_of(klass) end it "should return DateTime when timestamp is > 2038-01-19T03:14:07" do - # 2038-01-19T03:14:07 is the max for 32bit Ruby 1.8 + # 2038-01-19T03:14:07 is the max for 32bit Ruby 1.8 r = @client.query("SELECT CAST('2038-01-19 03:14:08' AS DATETIME) as test") expect(r.first['test']).to be_an_instance_of(klass) end @@ -413,7 +413,7 @@ it "should return String for a BINARY value" do expect(@test_result['binary_test']).to be_an_instance_of(String) - expect(@test_result['binary_test']).to eql("test#{"\000"*6}") + expect(@test_result['binary_test']).to eql("test#{"\000" * 6}") end context "string encoding for BINARY values" do @@ -450,7 +450,7 @@ 'medium_blob_test' => 'MEDIUMBLOB', 'medium_text_test' => 'MEDIUMTEXT', 'long_blob_test' => 'LONGBLOB', - 'long_text_test' => 'LONGTEXT' + 'long_text_test' => 'LONGTEXT', }.each do |field, type| it "should return a String for #{type}" do expect(@test_result[field]).to be_an_instance_of(String) @@ -460,7 +460,7 @@ context "string encoding for #{type} values" do before { pending('Encoding is undefined') unless defined?(Encoding) } - if ['VARBINARY', 'TINYBLOB', 'BLOB', 'MEDIUMBLOB', 'LONGBLOB'].include?(type) + if %w(VARBINARY TINYBLOB BLOB MEDIUMBLOB LONGBLOB).include?(type) it "should default to binary if Encoding.default_internal is nil" do with_internal_encoding nil do result = @client.query("SELECT * FROM mysql2_test ORDER BY id DESC LIMIT 1").first diff --git a/spec/mysql2/statement_spec.rb b/spec/mysql2/statement_spec.rb index 92169d1c1..8c5647d31 100644 --- a/spec/mysql2/statement_spec.rb +++ b/spec/mysql2/statement_spec.rb @@ -53,8 +53,8 @@ statement = @client.prepare 'SELECT 1' result = statement.execute rows = [] - result.each {|r| rows << r} - expect(rows).to eq([{"1"=>1}]) + result.each { |r| rows << r } + expect(rows).to eq([{ "1" => 1 }]) end it "should keep its result after other query" do @@ -64,8 +64,8 @@ stmt = @client.prepare('SELECT a FROM mysql2_stmt_q WHERE a = ?') result1 = stmt.execute(1) result2 = stmt.execute(2) - expect(result2.first).to eq({"a"=>2}) - expect(result1.first).to eq({"a"=>1}) + expect(result2.first).to eq("a" => 2) + expect(result1.first).to eq("a" => 1) @client.query 'DROP TABLE IF EXISTS mysql2_stmt_q' end @@ -91,11 +91,11 @@ @client.query 'INSERT INTO mysql2_stmt_q (a, b) VALUES (1, "Hello"), (2, "World")' statement = @client.prepare 'SELECT * FROM mysql2_stmt_q WHERE a < ?' results = statement.execute(2) - expect(results.first).to eq({"a" => 1, "b" => "Hello"}) + expect(results.first).to eq("a" => 1, "b" => "Hello") statement = @client.prepare 'SELECT * FROM mysql2_stmt_q WHERE b LIKE ?' results = statement.execute('%orld') - expect(results.first).to eq({"a" => 2, "b" => "World"}) + expect(results.first).to eq("a" => 2, "b" => "World") @client.query 'DROP TABLE IF EXISTS mysql2_stmt_q' end @@ -130,10 +130,10 @@ it "should be able to retrieve utf8 field names correctly" do stmt = @client.prepare 'SELECT * FROM `テーブル`' - expect(stmt.fields).to eq(['整数', '文字列']) + expect(stmt.fields).to eq(%w(整数 文字列)) result = stmt.execute - expect(result.to_a).to eq([{"整数"=>1, "文字列"=>"イチ"}, {"整数"=>2, "文字列"=>"弐"}, {"整数"=>3, "文字列"=>"さん"}]) + expect(result.to_a).to eq([{ "整数" => 1, "文字列" => "イチ" }, { "整数" => 2, "文字列" => "弐" }, { "整数" => 3, "文字列" => "さん" }]) end it "should be able to retrieve utf8 param query correctly" do @@ -142,7 +142,7 @@ result = stmt.execute 'イチ' - expect(result.to_a).to eq([{"整数"=>1}]) + expect(result.to_a).to eq([{ "整数" => 1 }]) end it "should be able to retrieve query with param in different encoding correctly" do @@ -152,9 +152,8 @@ param = 'イチ'.encode("EUC-JP") result = stmt.execute param - expect(result.to_a).to eq([{"整数"=>1}]) + expect(result.to_a).to eq([{ "整数" => 1 }]) end - end if defined? Encoding context "streaming result" do @@ -162,7 +161,7 @@ n = 1 stmt = @client.prepare("SELECT 1 UNION SELECT 2") - @client.query_options.merge!({:stream => true, :cache_rows => false, :as => :array}) + @client.query_options.merge!(:stream => true, :cache_rows => false, :as => :array) stmt.execute.each do |r| case n @@ -259,7 +258,7 @@ it "should return an array of field names in proper order" do result = @client.prepare("SELECT 'a', 'b', 'c'").execute - expect(result.fields).to eql(['a', 'b', 'c']) + expect(result.fields).to eql(%w(a b c)) end end @@ -374,13 +373,13 @@ end it "should return DateTime when timestamp is < 1901-12-13 20:45:52" do - # 1901-12-13T20:45:52 is the min for 32bit Ruby 1.8 + # 1901-12-13T20:45:52 is the min for 32bit Ruby 1.8 r = @client.query("SELECT CAST('1901-12-13 20:45:51' AS DATETIME) as test") expect(r.first['test']).to be_an_instance_of(klass) end it "should return DateTime when timestamp is > 2038-01-19T03:14:07" do - # 2038-01-19T03:14:07 is the max for 32bit Ruby 1.8 + # 2038-01-19T03:14:07 is the max for 32bit Ruby 1.8 r = @client.query("SELECT CAST('2038-01-19 03:14:08' AS DATETIME) as test") expect(r.first['test']).to be_an_instance_of(klass) end @@ -501,7 +500,7 @@ it "should return String for a BINARY value" do expect(@test_result['binary_test']).to be_an_instance_of(String) - expect(@test_result['binary_test']).to eql("test#{"\000"*6}") + expect(@test_result['binary_test']).to eql("test#{"\000" * 6}") end context "string encoding for BINARY values" do @@ -538,7 +537,7 @@ 'medium_blob_test' => 'MEDIUMBLOB', 'medium_text_test' => 'MEDIUMTEXT', 'long_blob_test' => 'LONGBLOB', - 'long_text_test' => 'LONGTEXT' + 'long_text_test' => 'LONGTEXT', }.each do |field, type| it "should return a String for #{type}" do expect(@test_result[field]).to be_an_instance_of(String) @@ -548,7 +547,7 @@ context "string encoding for #{type} values" do before { pending('Encoding is undefined') unless defined?(Encoding) } - if ['VARBINARY', 'TINYBLOB', 'BLOB', 'MEDIUMBLOB', 'LONGBLOB'].include?(type) + if %w(VARBINARY TINYBLOB BLOB MEDIUMBLOB LONGBLOB).include?(type) it "should default to binary if Encoding.default_internal is nil" do with_internal_encoding nil do result = @client.query("SELECT * FROM mysql2_test ORDER BY id DESC LIMIT 1").first diff --git a/support/mysql_enc_to_ruby.rb b/support/mysql_enc_to_ruby.rb index 39c513228..2d5987e9d 100644 --- a/support/mysql_enc_to_ruby.rb +++ b/support/mysql_enc_to_ruby.rb @@ -42,7 +42,7 @@ "binary" => "ASCII-8BIT", "geostd8" => "NULL", "cp932" => "Windows-31J", - "eucjpms" => "eucJP-ms" + "eucjpms" => "eucJP-ms", } client = Mysql2::Client.new(:username => user, :password => pass, :host => host, :port => port.to_i) @@ -53,7 +53,7 @@ collations.each do |collation| mysql_col_idx = collation[2].to_i rb_enc = mysql_to_rb[collation[1]] - encodings[mysql_col_idx-1] = [mysql_col_idx, rb_enc] + encodings[mysql_col_idx - 1] = [mysql_col_idx, rb_enc] end encodings.each_with_index do |encoding, idx| diff --git a/support/ruby_enc_to_mysql.rb b/support/ruby_enc_to_mysql.rb index 112016c94..52603b303 100644 --- a/support/ruby_enc_to_mysql.rb +++ b/support/ruby_enc_to_mysql.rb @@ -37,7 +37,7 @@ "binary" => "ASCII-8BIT", "geostd8" => nil, "cp932" => "Windows-31J", - "eucjpms" => "eucJP-ms" + "eucjpms" => "eucJP-ms", } puts <<-header diff --git a/tasks/benchmarks.rake b/tasks/benchmarks.rake index 33c85686c..79e1dc6a7 100644 --- a/tasks/benchmarks.rake +++ b/tasks/benchmarks.rake @@ -4,8 +4,8 @@ end.select { |x| x != 'setup_db' } namespace :bench do BENCHMARKS.each do |feature| - desc "Run #{feature} benchmarks" - task(feature){ ruby "benchmark/#{feature}.rb" } + desc "Run #{feature} benchmarks" + task(feature) { ruby "benchmark/#{feature}.rb" } end task :all do @@ -17,4 +17,4 @@ namespace :bench do task :setup do ruby 'benchmark/setup_db' end -end \ No newline at end of file +end diff --git a/tasks/compile.rake b/tasks/compile.rake index e5a903017..f7f977228 100644 --- a/tasks/compile.rake +++ b/tasks/compile.rake @@ -11,10 +11,10 @@ Rake::ExtensionTask.new("mysql2", gemspec) do |ext| # clean compiled extension CLEAN.include "#{ext.lib_dir}/*.#{RbConfig::CONFIG['DLEXT']}" - if RUBY_PLATFORM =~ /mswin|mingw/ then + if RUBY_PLATFORM =~ /mswin|mingw/ # Expand the path because the build dir is 3-4 levels deep in tmp/platform/version/ connector_dir = File.expand_path("../../vendor/#{vendor_mysql_dir}", __FILE__) - ext.config_options = [ "--with-mysql-dir=#{connector_dir}" ] + ext.config_options = ["--with-mysql-dir=#{connector_dir}"] else ext.cross_compile = true ext.cross_platform = ENV['CROSS_PLATFORMS'] ? ENV['CROSS_PLATFORMS'].split(':') : ['x86-mingw32', 'x86-mswin32-60', 'x64-mingw32'] @@ -78,11 +78,11 @@ task :devkit do end end -if RUBY_PLATFORM =~ /mingw|mswin/ then +if RUBY_PLATFORM =~ /mingw|mswin/ Rake::Task['compile'].prerequisites.unshift 'vendor:mysql' Rake::Task['compile'].prerequisites.unshift 'devkit' else - if Rake::Task.tasks.map {|t| t.name }.include? 'cross' + if Rake::Task.tasks.map(&:name).include? 'cross' Rake::Task['cross'].prerequisites.unshift 'vendor:mysql:cross' end end diff --git a/tasks/rspec.rake b/tasks/rspec.rake index 123343def..4be4d63dc 100644 --- a/tasks/rspec.rake +++ b/tasks/rspec.rake @@ -4,18 +4,18 @@ begin desc " Run all examples with Valgrind" namespace :spec do - task :valgrind do - VALGRIND_OPTS = %w{ - --num-callers=50 - --error-limit=no - --partial-loads-ok=yes - --undef-value-errors=no - --trace-children=yes - } - cmdline = "valgrind #{VALGRIND_OPTS.join(' ')} bundle exec rake spec" - puts cmdline - system cmdline - end + task :valgrind do + VALGRIND_OPTS = %w( + --num-callers=50 + --error-limit=no + --partial-loads-ok=yes + --undef-value-errors=no + --trace-children=yes + ) + cmdline = "valgrind #{VALGRIND_OPTS.join(' ')} bundle exec rake spec" + puts cmdline + system cmdline + end end desc "Run all examples with RCov" diff --git a/tasks/vendor_mysql.rake b/tasks/vendor_mysql.rake index 14c73659a..eae206a8e 100644 --- a/tasks/vendor_mysql.rake +++ b/tasks/vendor_mysql.rake @@ -3,7 +3,7 @@ require 'rake/extensioncompiler' CONNECTOR_VERSION = "6.1.6" # NOTE: Track the upstream version from time to time -def vendor_mysql_platform(platform=nil) +def vendor_mysql_platform(platform = nil) platform ||= RUBY_PLATFORM platform =~ /x64/ ? "winx64" : "win32" end @@ -38,7 +38,7 @@ task "vendor:mysql", [:platform] do |t, args| when_writing "downloading #{t.name}" do cd "vendor" do sh "curl", "-C", "-", "-O", url do |ok, res| - sh "wget", "-c", url if ! ok + sh "wget", "-c", url unless ok end end end From bb44a011fcdc4da3401b1380bd8d22f07fc9212a Mon Sep 17 00:00:00 2001 From: Tamir Duberstein Date: Thu, 12 Mar 2015 17:36:22 -0700 Subject: [PATCH 05/14] `Lint/Eval` --- .rubocop_todo.yml | 8 ++------ mysql2.gemspec | 2 +- tasks/compile.rake | 8 +++----- 3 files changed, 6 insertions(+), 12 deletions(-) diff --git a/.rubocop_todo.yml b/.rubocop_todo.yml index bdc588623..b126f98cd 100644 --- a/.rubocop_todo.yml +++ b/.rubocop_todo.yml @@ -1,5 +1,5 @@ # This configuration was generated by `rubocop --auto-gen-config` -# on 2015-03-12 17:46:21 -0700 using RuboCop version 0.29.1. +# on 2015-03-12 17:46:52 -0700 using RuboCop version 0.29.1. # The point is for the user to remove these configuration records # one by one as the offenses are removed from the code base. # Note that changes in the inspected code, or installation of new @@ -10,10 +10,6 @@ Lint/AssignmentInCondition: Enabled: false -# Offense count: 1 -Lint/Eval: - Enabled: false - # Offense count: 1 Lint/RescueException: Enabled: false @@ -51,7 +47,7 @@ Metrics/BlockNesting: Metrics/CyclomaticComplexity: Max: 23 -# Offense count: 238 +# Offense count: 237 # Configuration parameters: AllowURI, URISchemes. Metrics/LineLength: Max: 232 diff --git a/mysql2.gemspec b/mysql2.gemspec index 1113b6862..8596b5eec 100644 --- a/mysql2.gemspec +++ b/mysql2.gemspec @@ -1,6 +1,6 @@ require File.expand_path('../lib/mysql2/version', __FILE__) -Gem::Specification.new do |s| +Mysql2::GEMSPEC = Gem::Specification.new do |s| s.name = 'mysql2' s.version = Mysql2::VERSION s.authors = ['Brian Lopez', 'Aaron Stone'] diff --git a/tasks/compile.rake b/tasks/compile.rake index f7f977228..b0c2ee9b7 100644 --- a/tasks/compile.rake +++ b/tasks/compile.rake @@ -1,10 +1,8 @@ require "rake/extensiontask" -def gemspec - @clean_gemspec ||= eval(File.read(File.expand_path('../../mysql2.gemspec', __FILE__))) -end +load File.expand_path('../../mysql2.gemspec', __FILE__) -Rake::ExtensionTask.new("mysql2", gemspec) do |ext| +Rake::ExtensionTask.new("mysql2", Mysql2::GEMSPEC) do |ext| # put binaries into lib/mysql2/ or lib/mysql2/x.y/ ext.lib_dir = File.join 'lib', 'mysql2' @@ -60,7 +58,7 @@ file 'vendor/README' do |t| end file 'lib/mysql2/mysql2.rb' do |t| - name = gemspec.name + name = Mysql2::GEMSPEC.name File.open(t.name, 'wb') do |f| f.write <<-eoruby RUBY_VERSION =~ /(\\d+.\\d+)/ From 8f9eec4183d796246648c72f64578ae55829a409 Mon Sep 17 00:00:00 2001 From: Tamir Duberstein Date: Thu, 12 Mar 2015 17:38:07 -0700 Subject: [PATCH 06/14] `Lint/AssignmentInCondition` --- .rubocop_todo.yml | 5 ----- ext/mysql2/extconf.rb | 4 ++-- 2 files changed, 2 insertions(+), 7 deletions(-) diff --git a/.rubocop_todo.yml b/.rubocop_todo.yml index b126f98cd..639afe200 100644 --- a/.rubocop_todo.yml +++ b/.rubocop_todo.yml @@ -5,11 +5,6 @@ # Note that changes in the inspected code, or installation of new # versions of RuboCop, may require this file to be generated again. -# Offense count: 2 -# Configuration parameters: AllowSafeAssignment. -Lint/AssignmentInCondition: - Enabled: false - # Offense count: 1 Lint/RescueException: Enabled: false diff --git a/ext/mysql2/extconf.rb b/ext/mysql2/extconf.rb index 452314647..088e6e9cc 100644 --- a/ext/mysql2/extconf.rb +++ b/ext/mysql2/extconf.rb @@ -53,7 +53,7 @@ def asplode(lib) abort "-----\nCannot find library dir(s) #{lib}\n-----" unless lib && lib.split(File::PATH_SEPARATOR).any? { |dir| File.directory?(dir) } warn "-----\nUsing --with-mysql-dir=#{File.dirname inc}\n-----" rpath_dir = lib -elsif mc = (with_config('mysql-config') || Dir[GLOB].first) +elsif (mc = (with_config('mysql-config') || Dir[GLOB].first)) # If the user has provided a --with-mysql-config argument, we must respect it or fail. # If the user gave --with-mysql-config with no argument means we should try to find it. mc = Dir[GLOB].first if mc == true @@ -170,7 +170,7 @@ def asplode(lib) warn "-----\nSetting mysql rpath to #{explicit_rpath}\n-----" $LDFLAGS << rpath_flags else - if libdir = rpath_dir[%r{(-L)?(/[^ ]+)}, 2] + if (libdir = rpath_dir[%r{(-L)?(/[^ ]+)}, 2]) rpath_flags = " -Wl,-rpath,#{libdir}" if RbConfig::CONFIG["RPATHFLAG"].to_s.empty? && try_link('int main() {return 0;}', rpath_flags) # Usually Ruby sets RPATHFLAG the right way for each system, but not on OS X. From 97ea80d7f4f5b15274ba20526bc159c04d7d0b77 Mon Sep 17 00:00:00 2001 From: Tamir Duberstein Date: Thu, 12 Mar 2015 17:48:44 -0700 Subject: [PATCH 07/14] `Lint/RescueException` --- .rubocop_todo.yml | 4 ---- lib/mysql2/em.rb | 2 +- 2 files changed, 1 insertion(+), 5 deletions(-) diff --git a/.rubocop_todo.yml b/.rubocop_todo.yml index 639afe200..e0b0db15c 100644 --- a/.rubocop_todo.yml +++ b/.rubocop_todo.yml @@ -5,10 +5,6 @@ # Note that changes in the inspected code, or installation of new # versions of RuboCop, may require this file to be generated again. -# Offense count: 1 -Lint/RescueException: - Enabled: false - # Offense count: 2 Lint/ShadowingOuterLocalVariable: Enabled: false diff --git a/lib/mysql2/em.rb b/lib/mysql2/em.rb index cfb389d51..f580f147e 100644 --- a/lib/mysql2/em.rb +++ b/lib/mysql2/em.rb @@ -17,7 +17,7 @@ def notify_readable detach begin result = @client.async_result - rescue Exception => e + rescue => e @deferable.fail(e) else @deferable.succeed(result) From 0f56af3e619626716078a56e97479c383e47f3dd Mon Sep 17 00:00:00 2001 From: Tamir Duberstein Date: Thu, 12 Mar 2015 18:02:30 -0700 Subject: [PATCH 08/14] `Lint/UnusedBlockArgument` --- .rubocop_todo.yml | 13 ++----------- benchmark/query_with_mysql_casting.rb | 10 +++------- benchmark/query_without_mysql_casting.rb | 16 ++++------------ ext/mysql2/extconf.rb | 4 ++-- lib/mysql2/console.rb | 2 +- spec/em/em_spec.rb | 14 +++++++------- spec/mysql2/result_spec.rb | 2 +- tasks/compile.rake | 2 +- tasks/vendor_mysql.rake | 6 +++--- 9 files changed, 24 insertions(+), 45 deletions(-) diff --git a/.rubocop_todo.yml b/.rubocop_todo.yml index e0b0db15c..0f5d641af 100644 --- a/.rubocop_todo.yml +++ b/.rubocop_todo.yml @@ -1,24 +1,15 @@ # This configuration was generated by `rubocop --auto-gen-config` -# on 2015-03-12 17:46:52 -0700 using RuboCop version 0.29.1. +# on 2015-03-12 18:00:35 -0700 using RuboCop version 0.29.1. # The point is for the user to remove these configuration records # one by one as the offenses are removed from the code base. # Note that changes in the inspected code, or installation of new # versions of RuboCop, may require this file to be generated again. -# Offense count: 2 -Lint/ShadowingOuterLocalVariable: - Enabled: false - -# Offense count: 23 -# Cop supports --auto-correct. -Lint/UnusedBlockArgument: - Enabled: false - # Offense count: 1 Lint/UselessAccessModifier: Enabled: false -# Offense count: 4 +# Offense count: 10 Lint/UselessAssignment: Enabled: false diff --git a/benchmark/query_with_mysql_casting.rb b/benchmark/query_with_mysql_casting.rb index f2d493fb7..da42dfe1a 100644 --- a/benchmark/query_with_mysql_casting.rb +++ b/benchmark/query_with_mysql_casting.rb @@ -43,9 +43,7 @@ def mysql_cast(type, value) mysql2.query "USE #{database}" x.report "Mysql2" do mysql2_result = mysql2.query sql, :symbolize_keys => true - mysql2_result.each do |res| - # puts res.inspect - end + # mysql2_result.each { |res| puts res.inspect } end mysql = Mysql.new("localhost", "root") @@ -55,7 +53,7 @@ def mysql_cast(type, value) fields = mysql_result.fetch_fields mysql_result.each do |row| row_hash = row.each_with_index.each_with_object({}) do |(f, j), hash| - hash[fields[j].name.to_sym] = mysql_cast(fields[j].type, row[j]) + hash[fields[j].name.to_sym] = mysql_cast(fields[j].type, f) end # puts row_hash.inspect end @@ -65,9 +63,7 @@ def mysql_cast(type, value) command = do_mysql.create_command sql x.report "do_mysql" do do_result = command.execute_reader - do_result.each do |res| - # puts res.inspect - end + # do_result.each { |res| puts res.inspect } end x.compare! diff --git a/benchmark/query_without_mysql_casting.rb b/benchmark/query_without_mysql_casting.rb index 8fcd9a652..d473b1a27 100644 --- a/benchmark/query_without_mysql_casting.rb +++ b/benchmark/query_without_mysql_casting.rb @@ -15,34 +15,26 @@ mysql2.query "USE #{database}" x.report "Mysql2 (cast: true)" do mysql2_result = mysql2.query sql, :symbolize_keys => true, :cast => true - mysql2_result.each do |res| - # puts res.inspect - end + # mysql2_result.each { |res| puts res.inspect } end x.report "Mysql2 (cast: false)" do mysql2_result = mysql2.query sql, :symbolize_keys => true, :cast => false - mysql2_result.each do |res| - # puts res.inspect - end + # mysql2_result.each { |res| puts res.inspect } end mysql = Mysql.new("localhost", "root") mysql.query "USE #{database}" x.report "Mysql" do mysql_result = mysql.query sql - mysql_result.each_hash do |res| - # puts res.inspect - end + # mysql_result.each_hash { |res| puts res.inspect } end do_mysql = DataObjects::Connection.new("mysql://localhost/#{database}") command = DataObjects::Mysql::Command.new do_mysql, sql x.report "do_mysql" do do_result = command.execute_reader - do_result.each do |res| - # puts res.inspect - end + # do_result.each { |res| puts res.inspect } end x.compare! diff --git a/ext/mysql2/extconf.rb b/ext/mysql2/extconf.rb index 088e6e9cc..85c3cd3eb 100644 --- a/ext/mysql2/extconf.rb +++ b/ext/mysql2/extconf.rb @@ -117,7 +117,7 @@ def asplode(lib) # Use rake to rebuild only if these files change deffile = File.expand_path('../../../support/libmysql.def', __FILE__) libfile = File.expand_path(File.join(rpath_dir, 'libmysql.lib')) - file 'libmysql.a' => [deffile, libfile] do |t| + file 'libmysql.a' => [deffile, libfile] do when_writing 'building libmysql.a' do # Ruby kindly shows us where dllwrap is, but that tool does more than we want. # Maybe in the future Ruby could provide RbConfig::CONFIG['DLLTOOL'] directly. @@ -144,7 +144,7 @@ def asplode(lib) vendordll = File.join(vendordir, 'libmysql.dll') dllfile = File.expand_path(File.join(rpath_dir, 'libmysql.dll')) - file vendordll => [dllfile, vendordir] do |t| + file vendordll => [dllfile, vendordir] do when_writing 'copying libmysql.dll' do cp dllfile, vendordll end diff --git a/lib/mysql2/console.rb b/lib/mysql2/console.rb index cad824375..d8fb9e324 100644 --- a/lib/mysql2/console.rb +++ b/lib/mysql2/console.rb @@ -1,5 +1,5 @@ # Loaded by script/console. Land helpers here. -Pry.config.prompt = lambda do |context, nesting, pry| +Pry.config.prompt = lambda do |context, *| "[mysql2] #{context}> " end diff --git a/spec/em/em_spec.rb b/spec/em/em_spec.rb index 30e027e9d..fbb54d655 100644 --- a/spec/em/em_spec.rb +++ b/spec/em/em_spec.rb @@ -53,11 +53,11 @@ EM.run do client = Mysql2::EM::Client.new DatabaseCredentials['root'] defer = client.query "SELECT sleep(0.1) as first_query" - defer.callback do |result| + defer.callback do client.close fail 'some error' end - defer.errback do |err| + defer.errback do # This _shouldn't_ be run, but it needed to prevent the specs from # freezing if this test fails. EM.stop_event_loop @@ -75,7 +75,7 @@ errors = [] EM.run do defer = client.query "SELECT sleep(0.1) as first_query" - defer.callback do |result| + defer.callback do # This _shouldn't_ be run, but it is needed to prevent the specs from # freezing if this test fails. EM.stop_event_loop @@ -93,13 +93,13 @@ EM.run do defer = client.query "SELECT sleep(0.025) as first_query" EM.add_timer(0.1) do - defer.callback do |result| + defer.callback do callbacks_run << :callback # This _shouldn't_ be run, but it is needed to prevent the specs from # freezing if this test fails. EM.stop_event_loop end - defer.errback do |err| + defer.errback do callbacks_run << :errback EM.stop_event_loop end @@ -114,10 +114,10 @@ EM.run do client = Mysql2::EM::Client.new DatabaseCredentials['root'] defer = client.query("select sleep(0.025)") - defer.callback do |result| + defer.callback do callbacks_run << :callback end - defer.errback do |err| + defer.errback do callbacks_run << :errback end EM.add_timer(0.1) do diff --git a/spec/mysql2/result_spec.rb b/spec/mysql2/result_spec.rb index d867765ec..2d4d0ba50 100644 --- a/spec/mysql2/result_spec.rb +++ b/spec/mysql2/result_spec.rb @@ -158,7 +158,7 @@ res = client.query "SELECT * FROM streamingTest", :stream => true, :cache_rows => false expect { - res.each_with_index do |row, i| + res.each_with_index do |_, i| # Exhaust the first result packet then trigger a timeout sleep 2 if i > 0 && i % 1000 == 0 end diff --git a/tasks/compile.rake b/tasks/compile.rake index b0c2ee9b7..bd713e25f 100644 --- a/tasks/compile.rake +++ b/tasks/compile.rake @@ -50,7 +50,7 @@ Rake::ExtensionTask.new("mysql2", Mysql2::GEMSPEC) do |ext| end Rake::Task[:spec].prerequisites << :compile -file 'vendor/README' do |t| +file 'vendor/README' do connector_dir = File.expand_path("../../vendor/#{vendor_mysql_dir}", __FILE__) when_writing 'copying Connector/C README' do cp "#{connector_dir}/README", 'vendor/README' diff --git a/tasks/vendor_mysql.rake b/tasks/vendor_mysql.rake index eae206a8e..20e37e22d 100644 --- a/tasks/vendor_mysql.rake +++ b/tasks/vendor_mysql.rake @@ -21,13 +21,13 @@ def vendor_mysql_url(*args) end # vendor:mysql -task "vendor:mysql:cross" do |t| +task "vendor:mysql:cross" do # When cross-compiling, grab both 32 and 64 bit connectors Rake::Task['vendor:mysql'].invoke('x86') Rake::Task['vendor:mysql'].invoke('x64') end -task "vendor:mysql", [:platform] do |t, args| +task "vendor:mysql", [:platform] do |_t, args| puts "vendor:mysql for #{vendor_mysql_dir(args[:platform])}" # download mysql library and headers @@ -37,7 +37,7 @@ task "vendor:mysql", [:platform] do |t, args| url = vendor_mysql_url(args[:platform]) when_writing "downloading #{t.name}" do cd "vendor" do - sh "curl", "-C", "-", "-O", url do |ok, res| + sh "curl", "-C", "-", "-O", url do |ok| sh "wget", "-c", url unless ok end end From a253352b26f07d9926bfd35aada5e8cec73aeb33 Mon Sep 17 00:00:00 2001 From: Tamir Duberstein Date: Thu, 12 Mar 2015 18:11:57 -0700 Subject: [PATCH 09/14] `Lint/UselessAssignment` --- .rubocop_todo.yml | 4 ---- benchmark/query_with_mysql_casting.rb | 8 +++++--- benchmark/query_without_mysql_casting.rb | 10 ++++++---- ext/mysql2/extconf.rb | 9 +++++---- tasks/compile.rake | 2 +- 5 files changed, 17 insertions(+), 16 deletions(-) diff --git a/.rubocop_todo.yml b/.rubocop_todo.yml index 0f5d641af..7fbfadeaa 100644 --- a/.rubocop_todo.yml +++ b/.rubocop_todo.yml @@ -9,10 +9,6 @@ Lint/UselessAccessModifier: Enabled: false -# Offense count: 10 -Lint/UselessAssignment: - Enabled: false - # Offense count: 1 Lint/Void: Enabled: false diff --git a/benchmark/query_with_mysql_casting.rb b/benchmark/query_with_mysql_casting.rb index da42dfe1a..d856f71c1 100644 --- a/benchmark/query_with_mysql_casting.rb +++ b/benchmark/query_with_mysql_casting.rb @@ -38,12 +38,14 @@ def mysql_cast(type, value) end end +debug = ENV['DEBUG'] + Benchmark.ips do |x| mysql2 = Mysql2::Client.new(:host => "localhost", :username => "root") mysql2.query "USE #{database}" x.report "Mysql2" do mysql2_result = mysql2.query sql, :symbolize_keys => true - # mysql2_result.each { |res| puts res.inspect } + mysql2_result.each { |res| puts res.inspect } if debug end mysql = Mysql.new("localhost", "root") @@ -55,7 +57,7 @@ def mysql_cast(type, value) row_hash = row.each_with_index.each_with_object({}) do |(f, j), hash| hash[fields[j].name.to_sym] = mysql_cast(fields[j].type, f) end - # puts row_hash.inspect + puts row_hash.inspect if debug end end @@ -63,7 +65,7 @@ def mysql_cast(type, value) command = do_mysql.create_command sql x.report "do_mysql" do do_result = command.execute_reader - # do_result.each { |res| puts res.inspect } + do_result.each { |res| puts res.inspect } if debug end x.compare! diff --git a/benchmark/query_without_mysql_casting.rb b/benchmark/query_without_mysql_casting.rb index d473b1a27..6b4493506 100644 --- a/benchmark/query_without_mysql_casting.rb +++ b/benchmark/query_without_mysql_casting.rb @@ -10,31 +10,33 @@ database = 'test' sql = "SELECT * FROM mysql2_test LIMIT 100" +debug = ENV['DEBUG'] + Benchmark.ips do |x| mysql2 = Mysql2::Client.new(:host => "localhost", :username => "root") mysql2.query "USE #{database}" x.report "Mysql2 (cast: true)" do mysql2_result = mysql2.query sql, :symbolize_keys => true, :cast => true - # mysql2_result.each { |res| puts res.inspect } + mysql2_result.each { |res| puts res.inspect } if debug end x.report "Mysql2 (cast: false)" do mysql2_result = mysql2.query sql, :symbolize_keys => true, :cast => false - # mysql2_result.each { |res| puts res.inspect } + mysql2_result.each { |res| puts res.inspect } if debug end mysql = Mysql.new("localhost", "root") mysql.query "USE #{database}" x.report "Mysql" do mysql_result = mysql.query sql - # mysql_result.each_hash { |res| puts res.inspect } + mysql_result.each_hash { |res| puts res.inspect } if debug end do_mysql = DataObjects::Connection.new("mysql://localhost/#{database}") command = DataObjects::Mysql::Command.new do_mysql, sql x.report "do_mysql" do do_result = command.execute_reader - # do_result.each { |res| puts res.inspect } + do_result.each { |res| puts res.inspect } if debug end x.compare! diff --git a/ext/mysql2/extconf.rb b/ext/mysql2/extconf.rb index 85c3cd3eb..6fe06929f 100644 --- a/ext/mysql2/extconf.rb +++ b/ext/mysql2/extconf.rb @@ -42,6 +42,7 @@ def asplode(lib) # If the user has provided a --with-mysql-dir argument, we must respect it or fail. inc, lib = dir_config('mysql') if inc && lib + # TODO: Remove when 2.0.0 is the minimum supported version # Ruby versions not incorporating the mkmf fix at # https://bugs.ruby-lang.org/projects/ruby-trunk/repository/revisions/39717 # do not properly search for lib directories, and must be corrected @@ -73,11 +74,11 @@ def asplode(lib) $libs = libs + " " + $libs rpath_dir = libs else - inc, lib = dir_config('mysql', '/usr/local') + _, usr_local_lib = dir_config('mysql', '/usr/local') - asplode("mysql client") unless find_library('mysqlclient', 'mysql_query', lib, "#{lib}/mysql") + asplode("mysql client") unless find_library('mysqlclient', 'mysql_query', usr_local_lib, "#{usr_local_lib}/mysql") - rpath_dir = lib + rpath_dir = usr_local_lib end if have_header('mysql.h') @@ -90,7 +91,7 @@ def asplode(lib) %w(errmsg.h mysqld_error.h).each do |h| header = [prefix, h].compact.join '/' - asplode h unless have_header h + asplode h unless have_header header end # This is our wishlist. We use whichever flags work on the host. diff --git a/tasks/compile.rake b/tasks/compile.rake index bd713e25f..4ffbefca6 100644 --- a/tasks/compile.rake +++ b/tasks/compile.rake @@ -71,7 +71,7 @@ end task :devkit do begin require "devkit" - rescue LoadError => e + rescue LoadError abort "Failed to activate RubyInstaller's DevKit required for compilation." end end From 5b1d0952b5c42a320203961f9d76470415557cca Mon Sep 17 00:00:00 2001 From: Tamir Duberstein Date: Thu, 12 Mar 2015 18:29:10 -0700 Subject: [PATCH 10/14] Add several RuboCop checks --- .rubocop_todo.yml | 50 +++------------------------ benchmark/query_with_mysql_casting.rb | 4 +-- ext/mysql2/client.c | 2 +- ext/mysql2/extconf.rb | 10 ++---- lib/mysql2.rb | 18 +++++----- lib/mysql2/client.rb | 46 ++++++++++++------------ lib/mysql2/em.rb | 5 ++- spec/mysql2/client_spec.rb | 4 +-- spec/mysql2/result_spec.rb | 26 +++++++------- spec/mysql2/statement_spec.rb | 26 +++++++------- support/mysql_enc_to_ruby.rb | 8 ++--- tasks/benchmarks.rake | 2 +- 12 files changed, 79 insertions(+), 122 deletions(-) diff --git a/.rubocop_todo.yml b/.rubocop_todo.yml index 7fbfadeaa..28eb54429 100644 --- a/.rubocop_todo.yml +++ b/.rubocop_todo.yml @@ -1,21 +1,13 @@ # This configuration was generated by `rubocop --auto-gen-config` -# on 2015-03-12 18:00:35 -0700 using RuboCop version 0.29.1. +# on 2015-03-12 18:28:12 -0700 using RuboCop version 0.29.1. # The point is for the user to remove these configuration records # one by one as the offenses are removed from the code base. # Note that changes in the inspected code, or installation of new # versions of RuboCop, may require this file to be generated again. -# Offense count: 1 -Lint/UselessAccessModifier: - Enabled: false - -# Offense count: 1 -Lint/Void: - Enabled: false - # Offense count: 2 Metrics/AbcSize: - Max: 64 + Max: 66 # Offense count: 1 Metrics/BlockNesting: @@ -30,7 +22,7 @@ Metrics/CyclomaticComplexity: Metrics/LineLength: Max: 232 -# Offense count: 4 +# Offense count: 5 # Configuration parameters: CountComments. Metrics/MethodLength: Max: 40 @@ -44,53 +36,21 @@ Metrics/PerceivedComplexity: Style/BlockDelimiters: Enabled: false -# Offense count: 1 -# Configuration parameters: EnforcedStyle, SupportedStyles. -Style/ClassAndModuleChildren: - Enabled: false - -# Offense count: 1 -Style/ClassVars: - Enabled: false - -# Offense count: 9 +# Offense count: 10 Style/Documentation: Enabled: false -# Offense count: 1 -Style/DoubleNegation: - Enabled: false - # Offense count: 9 # Configuration parameters: AllowedVariables. Style/GlobalVars: Enabled: false -# Offense count: 4 -# Configuration parameters: MaxLineLength. -Style/IfUnlessModifier: - Enabled: false - -# Offense count: 1 -Style/MultilineBlockChain: - Enabled: false - -# Offense count: 13 +# Offense count: 12 # Cop supports --auto-correct. Style/NumericLiterals: MinDigits: 20 -# Offense count: 549 # Cop supports --auto-correct. # Configuration parameters: EnforcedStyle, SupportedStyles. Style/StringLiterals: Enabled: false - -# Offense count: 2 -Style/UnlessElse: - Enabled: false - -# Offense count: 1 -# Configuration parameters: MaxLineLength. -Style/WhileUntilModifier: - Enabled: false diff --git a/benchmark/query_with_mysql_casting.rb b/benchmark/query_with_mysql_casting.rb index d856f71c1..a6bec70c6 100644 --- a/benchmark/query_with_mysql_casting.rb +++ b/benchmark/query_with_mysql_casting.rb @@ -30,8 +30,8 @@ def mysql_cast(type, value) when Mysql::Field::TYPE_TIME, Mysql::Field::TYPE_DATETIME, Mysql::Field::TYPE_TIMESTAMP Time.parse(value) when Mysql::Field::TYPE_BLOB, Mysql::Field::TYPE_BIT, Mysql::Field::TYPE_STRING, - Mysql::Field::TYPE_VAR_STRING, Mysql::Field::TYPE_CHAR, Mysql::Field::TYPE_SET - Mysql::Field::TYPE_ENUM + Mysql::Field::TYPE_VAR_STRING, Mysql::Field::TYPE_CHAR, Mysql::Field::TYPE_SET, + Mysql::Field::TYPE_ENUM value else value diff --git a/ext/mysql2/client.c b/ext/mysql2/client.c index 1b87c2475..f6f03729c 100644 --- a/ext/mysql2/client.c +++ b/ext/mysql2/client.c @@ -648,7 +648,7 @@ static VALUE rb_mysql_client_abandon_results(VALUE self) { * client.query(sql, options = {}) * * Query the database with +sql+, with optional +options+. For the possible - * options, see @@default_query_options on the Mysql2::Client class. + * options, see default_query_options on the Mysql2::Client class. */ static VALUE rb_query(VALUE self, VALUE sql, VALUE current) { #ifndef _WIN32 diff --git a/ext/mysql2/extconf.rb b/ext/mysql2/extconf.rb index 6fe06929f..09cefe38e 100644 --- a/ext/mysql2/extconf.rb +++ b/ext/mysql2/extconf.rb @@ -66,9 +66,7 @@ def asplode(lib) abort unless $CHILD_STATUS.success? libs = `#{mc} --libs_r`.chomp # MySQL 5.5 and above already have re-entrant code in libmysqlclient (no _r). - if ver >= 5.5 || libs.empty? - libs = `#{mc} --libs`.chomp - end + libs = `#{mc} --libs`.chomp if ver >= 5.5 || libs.empty? abort unless $CHILD_STATUS.success? $INCFLAGS += ' ' + includes $libs = libs + " " + $libs @@ -104,10 +102,8 @@ def asplode(lib) -Wno-unused-function -Wno-declaration-after-statement -Wno-missing-field-initializers -).select do |flag| - try_link('int main() {return 0;}', flag) -end.each do |flag| - $CFLAGS << ' ' << flag +).each do |flag| + $CFLAGS << ' ' << flag if try_link('int main() {return 0;}', flag) end if RUBY_PLATFORM =~ /mswin|mingw/ diff --git a/lib/mysql2.rb b/lib/mysql2.rb index 92268bea3..a577c5cf3 100644 --- a/lib/mysql2.rb +++ b/lib/mysql2.rb @@ -10,7 +10,7 @@ dll_path = if ENV['RUBY_MYSQL2_LIBMYSQL_DLL'] # If this environment variable is set, it overrides any other paths # The user is advised to use backslashes not forward slashes - ENV['RUBY_MYSQL2_LIBMYSQL_DLL'].dup + ENV['RUBY_MYSQL2_LIBMYSQL_DLL'] elsif File.exist?(File.expand_path('../vendor/libmysql.dll', File.dirname(__FILE__))) # Use vendor/libmysql.dll if it exists, convert slashes for Win32 LoadLibrary File.expand_path('../vendor/libmysql.dll', File.dirname(__FILE__)).gsub('/', '\\') @@ -53,12 +53,14 @@ module Mysql2 end # For holding utility methods -module Mysql2::Util - # - # Rekey a string-keyed hash with equivalent symbols. - # - def self.key_hash_as_symbols(hash) - return nil unless hash - Hash[hash.map { |k, v| [k.to_sym, v] }] +module Mysql2 + module Util + # + # Rekey a string-keyed hash with equivalent symbols. + # + def self.key_hash_as_symbols(hash) + return nil unless hash + Hash[hash.map { |k, v| [k.to_sym, v] }] + end end end diff --git a/lib/mysql2/client.rb b/lib/mysql2/client.rb index f67d78518..2b60fc242 100644 --- a/lib/mysql2/client.rb +++ b/lib/mysql2/client.rb @@ -1,24 +1,27 @@ module Mysql2 class Client attr_reader :query_options, :read_timeout - @@default_query_options = { - :as => :hash, # the type of object you want each row back as; also supports :array (an array of values) - :async => false, # don't wait for a result after sending the query, you'll have to monitor the socket yourself then eventually call Mysql2::Client#async_result - :cast_booleans => false, # cast tinyint(1) fields as true/false in ruby - :symbolize_keys => false, # return field names as symbols instead of strings - :database_timezone => :local, # timezone Mysql2 will assume datetime objects are stored in - :application_timezone => nil, # timezone Mysql2 will convert to before handing the object back to the caller - :cache_rows => true, # tells Mysql2 to use it's internal row cache for results - :connect_flags => REMEMBER_OPTIONS | LONG_PASSWORD | LONG_FLAG | TRANSACTIONS | PROTOCOL_41 | SECURE_CONNECTION, - :cast => true, - :default_file => nil, - :default_group => nil, - } + + def self.default_query_options + @default_query_options ||= { + :as => :hash, # the type of object you want each row back as; also supports :array (an array of values) + :async => false, # don't wait for a result after sending the query, you'll have to monitor the socket yourself then eventually call Mysql2::Client#async_result + :cast_booleans => false, # cast tinyint(1) fields as true/false in ruby + :symbolize_keys => false, # return field names as symbols instead of strings + :database_timezone => :local, # timezone Mysql2 will assume datetime objects are stored in + :application_timezone => nil, # timezone Mysql2 will convert to before handing the object back to the caller + :cache_rows => true, # tells Mysql2 to use it's internal row cache for results + :connect_flags => REMEMBER_OPTIONS | LONG_PASSWORD | LONG_FLAG | TRANSACTIONS | PROTOCOL_41 | SECURE_CONNECTION, + :cast => true, + :default_file => nil, + :default_group => nil, + } + end def initialize(opts = {}) opts = Mysql2::Util.key_hash_as_symbols(opts) @read_timeout = nil - @query_options = @@default_query_options.dup + @query_options = self.class.default_query_options.dup @query_options.merge! opts initialize_ext @@ -26,11 +29,12 @@ def initialize(opts = {}) # Set default connect_timeout to avoid unlimited retries from signal interruption opts[:connect_timeout] = 120 unless opts.key?(:connect_timeout) + # TODO: stricter validation rather than silent massaging [:reconnect, :connect_timeout, :local_infile, :read_timeout, :write_timeout, :default_file, :default_group, :secure_auth, :init_command].each do |key| next unless opts.key?(key) case key when :reconnect, :local_infile, :secure_auth - send(:"#{key}=", !!opts[key]) + send(:"#{key}=", !!opts[key]) # rubocop:disable Style/DoubleNegation when :connect_timeout, :read_timeout, :write_timeout send(:"#{key}=", opts[key].to_i) else @@ -75,10 +79,6 @@ def initialize(opts = {}) connect user, pass, host, port, database, socket, flags end - def self.default_query_options - @@default_query_options - end - if Thread.respond_to?(:handle_interrupt) require 'timeout' @@ -105,10 +105,12 @@ def info self.class.info end - private + class << self + private - def self.local_offset - ::Time.local(2010).utc_offset.to_r / 86400 + def local_offset + ::Time.local(2010).utc_offset.to_r / 86400 + end end end end diff --git a/lib/mysql2/em.rb b/lib/mysql2/em.rb index f580f147e..b4210f089 100644 --- a/lib/mysql2/em.rb +++ b/lib/mysql2/em.rb @@ -34,9 +34,8 @@ def unbind end def close(*args) - if @watch - @watch.detach if @watch.watching? - end + @watch.detach if @watch && @watch.watching? + super(*args) end diff --git a/spec/mysql2/client_spec.rb b/spec/mysql2/client_spec.rb index b84cf7441..272767ec3 100644 --- a/spec/mysql2/client_spec.rb +++ b/spec/mysql2/client_spec.rb @@ -574,9 +574,7 @@ def run_gc it "does not interfere with other statements" do @multi_client.query("SELECT 1 AS 'set_1'; SELECT 2 AS 'set_2'") - while @multi_client.next_result - @multi_client.store_result - end + @multi_client.store_result while @multi_client.next_result expect(@multi_client.query("SELECT 3 AS 'next'").first).to eq('next' => 3) end diff --git a/spec/mysql2/result_spec.rb b/spec/mysql2/result_spec.rb index 2d4d0ba50..6844c88b1 100644 --- a/spec/mysql2/result_spec.rb +++ b/spec/mysql2/result_spec.rb @@ -279,10 +279,10 @@ end if 1.size == 4 # 32bit - unless RUBY_VERSION =~ /1.8/ - klass = Time + klass = if RUBY_VERSION =~ /1.8/ + DateTime else - klass = DateTime + Time end it "should return DateTime when timestamp is < 1901-12-13 20:45:52" do @@ -297,27 +297,27 @@ expect(r.first['test']).to be_an_instance_of(klass) end elsif 1.size == 8 # 64bit - unless RUBY_VERSION =~ /1.8/ - it "should return Time when timestamp is < 1901-12-13 20:45:52" do - r = @client.query("SELECT CAST('1901-12-13 20:45:51' AS DATETIME) as test") + if RUBY_VERSION =~ /1.8/ + it "should return Time when timestamp is > 0138-12-31 11:59:59" do + r = @client.query("SELECT CAST('0139-1-1 00:00:00' AS DATETIME) as test") expect(r.first['test']).to be_an_instance_of(Time) end + it "should return DateTime when timestamp is < 0139-1-1T00:00:00" do + r = @client.query("SELECT CAST('0138-12-31 11:59:59' AS DATETIME) as test") + expect(r.first['test']).to be_an_instance_of(DateTime) + end + it "should return Time when timestamp is > 2038-01-19T03:14:07" do r = @client.query("SELECT CAST('2038-01-19 03:14:08' AS DATETIME) as test") expect(r.first['test']).to be_an_instance_of(Time) end else - it "should return Time when timestamp is > 0138-12-31 11:59:59" do - r = @client.query("SELECT CAST('0139-1-1 00:00:00' AS DATETIME) as test") + it "should return Time when timestamp is < 1901-12-13 20:45:52" do + r = @client.query("SELECT CAST('1901-12-13 20:45:51' AS DATETIME) as test") expect(r.first['test']).to be_an_instance_of(Time) end - it "should return DateTime when timestamp is < 0139-1-1T00:00:00" do - r = @client.query("SELECT CAST('0138-12-31 11:59:59' AS DATETIME) as test") - expect(r.first['test']).to be_an_instance_of(DateTime) - end - it "should return Time when timestamp is > 2038-01-19T03:14:07" do r = @client.query("SELECT CAST('2038-01-19 03:14:08' AS DATETIME) as test") expect(r.first['test']).to be_an_instance_of(Time) diff --git a/spec/mysql2/statement_spec.rb b/spec/mysql2/statement_spec.rb index 8c5647d31..3fb97dcfb 100644 --- a/spec/mysql2/statement_spec.rb +++ b/spec/mysql2/statement_spec.rb @@ -366,10 +366,10 @@ end if 1.size == 4 # 32bit - unless RUBY_VERSION =~ /1.8/ - klass = Time + klass = if RUBY_VERSION =~ /1.8/ + DateTime else - klass = DateTime + Time end it "should return DateTime when timestamp is < 1901-12-13 20:45:52" do @@ -384,27 +384,27 @@ expect(r.first['test']).to be_an_instance_of(klass) end elsif 1.size == 8 # 64bit - unless RUBY_VERSION =~ /1.8/ - it "should return Time when timestamp is < 1901-12-13 20:45:52" do - r = @client.query("SELECT CAST('1901-12-13 20:45:51' AS DATETIME) as test") + if RUBY_VERSION =~ /1.8/ + it "should return Time when timestamp is > 0138-12-31 11:59:59" do + r = @client.query("SELECT CAST('0139-1-1 00:00:00' AS DATETIME) as test") expect(r.first['test']).to be_an_instance_of(Time) end + it "should return DateTime when timestamp is < 0139-1-1T00:00:00" do + r = @client.query("SELECT CAST('0138-12-31 11:59:59' AS DATETIME) as test") + expect(r.first['test']).to be_an_instance_of(DateTime) + end + it "should return Time when timestamp is > 2038-01-19T03:14:07" do r = @client.query("SELECT CAST('2038-01-19 03:14:08' AS DATETIME) as test") expect(r.first['test']).to be_an_instance_of(Time) end else - it "should return Time when timestamp is > 0138-12-31 11:59:59" do - r = @client.query("SELECT CAST('0139-1-1 00:00:00' AS DATETIME) as test") + it "should return Time when timestamp is < 1901-12-13 20:45:52" do + r = @client.query("SELECT CAST('1901-12-13 20:45:51' AS DATETIME) as test") expect(r.first['test']).to be_an_instance_of(Time) end - it "should return DateTime when timestamp is < 0139-1-1T00:00:00" do - r = @client.query("SELECT CAST('0138-12-31 11:59:59' AS DATETIME) as test") - expect(r.first['test']).to be_an_instance_of(DateTime) - end - it "should return Time when timestamp is > 2038-01-19T03:14:07" do r = @client.query("SELECT CAST('2038-01-19 03:14:08' AS DATETIME) as test") expect(r.first['test']).to be_an_instance_of(Time) diff --git a/support/mysql_enc_to_ruby.rb b/support/mysql_enc_to_ruby.rb index 2d5987e9d..fbe1562c3 100644 --- a/support/mysql_enc_to_ruby.rb +++ b/support/mysql_enc_to_ruby.rb @@ -65,10 +65,10 @@ end encodings_with_nil = encodings_with_nil.map do |encoding| - name = "NULL" - - if !encoding.nil? && encoding[1] != "NULL" - name = "\"#{encoding[1]}\"" + name = if encoding.nil? || encoding[1] == 'NULL' + 'NULL' + else + "\"#{encoding[1]}\"" end " #{name}" diff --git a/tasks/benchmarks.rake b/tasks/benchmarks.rake index 79e1dc6a7..b587ecdc0 100644 --- a/tasks/benchmarks.rake +++ b/tasks/benchmarks.rake @@ -1,6 +1,6 @@ BENCHMARKS = Dir["#{File.dirname(__FILE__)}/../benchmark/*.rb"].map do |path| File.basename(path, '.rb') -end.select { |x| x != 'setup_db' } +end - ['setup_db'] namespace :bench do BENCHMARKS.each do |feature| From 3b5b01eeb7f58fb960c28508bb2f5bf40ff66d29 Mon Sep 17 00:00:00 2001 From: Tamir Duberstein Date: Thu, 12 Mar 2015 20:41:08 -0700 Subject: [PATCH 11/14] 1.8.7 doesn't support trailing commas --- spec/mysql2/client_spec.rb | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/spec/mysql2/client_spec.rb b/spec/mysql2/client_spec.rb index 272767ec3..7e3befe26 100644 --- a/spec/mysql2/client_spec.rb +++ b/spec/mysql2/client_spec.rb @@ -125,6 +125,7 @@ def connect(*args) # You may need to adjust the lines below to match your SSL certificate paths ssl_client = nil expect { + # rubocop:disable Style/TrailingComma ssl_client = Mysql2::Client.new( DatabaseCredentials['root'].merge( 'host' => 'mysql2gem.example.com', # must match the certificates @@ -132,9 +133,10 @@ def connect(*args) :sslcert => '/etc/mysql/client-cert.pem', :sslca => '/etc/mysql/ca-cert.pem', :sslcipher => 'DHE-RSA-AES256-SHA', - :sslverify => true, + :sslverify => true ) ) + # rubocop:enable Style/TrailingComma }.not_to raise_error results = ssl_client.query("SHOW STATUS WHERE Variable_name = \"Ssl_version\" OR Variable_name = \"Ssl_cipher\"").to_a From 3a531112846449c7a059550c439e9330f0e854a1 Mon Sep 17 00:00:00 2001 From: Tamir Duberstein Date: Sun, 7 Jun 2015 18:28:26 -0400 Subject: [PATCH 12/14] Updates for Rubocop 0.32.0 --- .rubocop_todo.yml | 10 ++++++---- 1 file changed, 6 insertions(+), 4 deletions(-) diff --git a/.rubocop_todo.yml b/.rubocop_todo.yml index 28eb54429..83c498c72 100644 --- a/.rubocop_todo.yml +++ b/.rubocop_todo.yml @@ -1,5 +1,5 @@ # This configuration was generated by `rubocop --auto-gen-config` -# on 2015-03-12 18:28:12 -0700 using RuboCop version 0.29.1. +# on 2015-06-07 18:25:43 -0400 using RuboCop version 0.32.0. # The point is for the user to remove these configuration records # one by one as the offenses are removed from the code base. # Note that changes in the inspected code, or installation of new @@ -17,7 +17,7 @@ Metrics/BlockNesting: Metrics/CyclomaticComplexity: Max: 23 -# Offense count: 237 +# Offense count: 283 # Configuration parameters: AllowURI, URISchemes. Metrics/LineLength: Max: 232 @@ -33,10 +33,11 @@ Metrics/PerceivedComplexity: # Offense count: 40 # Cop supports --auto-correct. +# Configuration parameters: EnforcedStyle, SupportedStyles, ProceduralMethods, FunctionalMethods, IgnoredMethods. Style/BlockDelimiters: Enabled: false -# Offense count: 10 +# Offense count: 12 Style/Documentation: Enabled: false @@ -45,11 +46,12 @@ Style/Documentation: Style/GlobalVars: Enabled: false -# Offense count: 12 +# Offense count: 13 # Cop supports --auto-correct. Style/NumericLiterals: MinDigits: 20 +# Offense count: 673 # Cop supports --auto-correct. # Configuration parameters: EnforcedStyle, SupportedStyles. Style/StringLiterals: From dfc63952604a6ff0dae54d07bab25e78a40b8f17 Mon Sep 17 00:00:00 2001 From: Tamir Duberstein Date: Sun, 7 Jun 2015 18:33:52 -0400 Subject: [PATCH 13/14] Always iterate in benchmarks --- benchmark/query_with_mysql_casting.rb | 4 ++-- benchmark/query_without_mysql_casting.rb | 8 ++++---- 2 files changed, 6 insertions(+), 6 deletions(-) diff --git a/benchmark/query_with_mysql_casting.rb b/benchmark/query_with_mysql_casting.rb index a6bec70c6..7685926fa 100644 --- a/benchmark/query_with_mysql_casting.rb +++ b/benchmark/query_with_mysql_casting.rb @@ -45,7 +45,7 @@ def mysql_cast(type, value) mysql2.query "USE #{database}" x.report "Mysql2" do mysql2_result = mysql2.query sql, :symbolize_keys => true - mysql2_result.each { |res| puts res.inspect } if debug + mysql2_result.each { |res| puts res.inspect if debug } end mysql = Mysql.new("localhost", "root") @@ -65,7 +65,7 @@ def mysql_cast(type, value) command = do_mysql.create_command sql x.report "do_mysql" do do_result = command.execute_reader - do_result.each { |res| puts res.inspect } if debug + do_result.each { |res| puts res.inspect if debug } end x.compare! diff --git a/benchmark/query_without_mysql_casting.rb b/benchmark/query_without_mysql_casting.rb index 6b4493506..1afc7c9d3 100644 --- a/benchmark/query_without_mysql_casting.rb +++ b/benchmark/query_without_mysql_casting.rb @@ -17,26 +17,26 @@ mysql2.query "USE #{database}" x.report "Mysql2 (cast: true)" do mysql2_result = mysql2.query sql, :symbolize_keys => true, :cast => true - mysql2_result.each { |res| puts res.inspect } if debug + mysql2_result.each { |res| puts res.inspect if debug } end x.report "Mysql2 (cast: false)" do mysql2_result = mysql2.query sql, :symbolize_keys => true, :cast => false - mysql2_result.each { |res| puts res.inspect } if debug + mysql2_result.each { |res| puts res.inspect if debug } end mysql = Mysql.new("localhost", "root") mysql.query "USE #{database}" x.report "Mysql" do mysql_result = mysql.query sql - mysql_result.each_hash { |res| puts res.inspect } if debug + mysql_result.each_hash { |res| puts res.inspect if debug } end do_mysql = DataObjects::Connection.new("mysql://localhost/#{database}") command = DataObjects::Mysql::Command.new do_mysql, sql x.report "do_mysql" do do_result = command.execute_reader - do_result.each { |res| puts res.inspect } if debug + do_result.each { |res| puts res.inspect if debug } end x.compare! From ac93121200760a42eb3085c0e50ef12441c2bc97 Mon Sep 17 00:00:00 2001 From: Tamir Duberstein Date: Fri, 7 Aug 2015 11:09:23 -0400 Subject: [PATCH 14/14] Updates for Rubocop 0.34.0 --- .rubocop_todo.yml | 33 +++++++++++++++++++++++---------- Gemfile | 2 +- lib/mysql2.rb | 2 +- 3 files changed, 25 insertions(+), 12 deletions(-) diff --git a/.rubocop_todo.yml b/.rubocop_todo.yml index 83c498c72..5a28c920b 100644 --- a/.rubocop_todo.yml +++ b/.rubocop_todo.yml @@ -1,5 +1,6 @@ -# This configuration was generated by `rubocop --auto-gen-config` -# on 2015-06-07 18:25:43 -0400 using RuboCop version 0.32.0. +# This configuration was generated by +# `rubocop --auto-gen-config` +# on 2015-09-06 13:16:09 -0400 using RuboCop version 0.34.0. # The point is for the user to remove these configuration records # one by one as the offenses are removed from the code base. # Note that changes in the inspected code, or installation of new @@ -7,7 +8,7 @@ # Offense count: 2 Metrics/AbcSize: - Max: 66 + Max: 68 # Offense count: 1 Metrics/BlockNesting: @@ -17,7 +18,7 @@ Metrics/BlockNesting: Metrics/CyclomaticComplexity: Max: 23 -# Offense count: 283 +# Offense count: 290 # Configuration parameters: AllowURI, URISchemes. Metrics/LineLength: Max: 232 @@ -25,11 +26,11 @@ Metrics/LineLength: # Offense count: 5 # Configuration parameters: CountComments. Metrics/MethodLength: - Max: 40 + Max: 43 # Offense count: 1 Metrics/PerceivedComplexity: - Max: 20 + Max: 22 # Offense count: 40 # Cop supports --auto-correct. @@ -39,19 +40,31 @@ Style/BlockDelimiters: # Offense count: 12 Style/Documentation: - Enabled: false + Exclude: + - 'benchmark/active_record.rb' + - 'benchmark/allocations.rb' + - 'benchmark/query_with_mysql_casting.rb' + - 'lib/mysql2.rb' + - 'lib/mysql2/client.rb' + - 'lib/mysql2/em.rb' + - 'lib/mysql2/error.rb' + - 'lib/mysql2/field.rb' + - 'lib/mysql2/result.rb' + - 'lib/mysql2/statement.rb' + - 'lib/mysql2/version.rb' # Offense count: 9 # Configuration parameters: AllowedVariables. Style/GlobalVars: - Enabled: false + Exclude: + - 'ext/mysql2/extconf.rb' -# Offense count: 13 +# Offense count: 14 # Cop supports --auto-correct. Style/NumericLiterals: MinDigits: 20 -# Offense count: 673 +# Offense count: 680 # Cop supports --auto-correct. # Configuration parameters: EnforcedStyle, SupportedStyles. Style/StringLiterals: diff --git a/Gemfile b/Gemfile index 117579391..f4a9ca4f8 100644 --- a/Gemfile +++ b/Gemfile @@ -8,7 +8,7 @@ gem 'rake-compiler', '~> 0.9.5' group :test do gem 'eventmachine' unless RUBY_PLATFORM =~ /mswin|mingw/ gem 'rspec', '~> 3.2' - gem 'rubocop', '~> 0.32.0' unless RUBY_VERSION =~ /1.8/ + gem 'rubocop', '~> 0.34.0' unless RUBY_VERSION =~ /1.8/ end group :benchmarks do diff --git a/lib/mysql2.rb b/lib/mysql2.rb index a577c5cf3..3f4335a08 100644 --- a/lib/mysql2.rb +++ b/lib/mysql2.rb @@ -13,7 +13,7 @@ ENV['RUBY_MYSQL2_LIBMYSQL_DLL'] elsif File.exist?(File.expand_path('../vendor/libmysql.dll', File.dirname(__FILE__))) # Use vendor/libmysql.dll if it exists, convert slashes for Win32 LoadLibrary - File.expand_path('../vendor/libmysql.dll', File.dirname(__FILE__)).gsub('/', '\\') + File.expand_path('../vendor/libmysql.dll', File.dirname(__FILE__)).tr('/', '\\') else # This will use default / system library paths 'libmysql.dll'