mysql2-sp 0.3.10

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (46) hide show
  1. data/.gitignore +12 -0
  2. data/.rspec +3 -0
  3. data/.rvmrc +1 -0
  4. data/.travis.yml +7 -0
  5. data/CHANGELOG.md +230 -0
  6. data/Gemfile +3 -0
  7. data/MIT-LICENSE +20 -0
  8. data/README.md +350 -0
  9. data/Rakefile +5 -0
  10. data/benchmark/active_record.rb +51 -0
  11. data/benchmark/active_record_threaded.rb +42 -0
  12. data/benchmark/allocations.rb +33 -0
  13. data/benchmark/escape.rb +36 -0
  14. data/benchmark/query_with_mysql_casting.rb +80 -0
  15. data/benchmark/query_without_mysql_casting.rb +56 -0
  16. data/benchmark/sequel.rb +37 -0
  17. data/benchmark/setup_db.rb +119 -0
  18. data/benchmark/threaded.rb +44 -0
  19. data/examples/eventmachine.rb +21 -0
  20. data/examples/threaded.rb +20 -0
  21. data/ext/mysql2/client.c +955 -0
  22. data/ext/mysql2/client.h +42 -0
  23. data/ext/mysql2/extconf.rb +73 -0
  24. data/ext/mysql2/mysql2_ext.c +12 -0
  25. data/ext/mysql2/mysql2_ext.h +42 -0
  26. data/ext/mysql2/result.c +568 -0
  27. data/ext/mysql2/result.h +20 -0
  28. data/ext/mysql2/wait_for_single_fd.h +36 -0
  29. data/lib/mysql2.rb +21 -0
  30. data/lib/mysql2/client.rb +242 -0
  31. data/lib/mysql2/em.rb +37 -0
  32. data/lib/mysql2/error.rb +15 -0
  33. data/lib/mysql2/result.rb +5 -0
  34. data/lib/mysql2/version.rb +3 -0
  35. data/mysql2.gemspec +29 -0
  36. data/spec/em/em_spec.rb +50 -0
  37. data/spec/mysql2/client_spec.rb +491 -0
  38. data/spec/mysql2/error_spec.rb +69 -0
  39. data/spec/mysql2/result_spec.rb +388 -0
  40. data/spec/rcov.opts +3 -0
  41. data/spec/spec_helper.rb +67 -0
  42. data/tasks/benchmarks.rake +20 -0
  43. data/tasks/compile.rake +71 -0
  44. data/tasks/rspec.rake +16 -0
  45. data/tasks/vendor_mysql.rake +40 -0
  46. metadata +198 -0
data/.gitignore ADDED
@@ -0,0 +1,12 @@
1
+ Makefile
2
+ *.dSYM
3
+ *.o
4
+ *.bundle
5
+ *.so
6
+ *.a
7
+ *.rbc
8
+ mkmf.log
9
+ pkg/
10
+ tmp
11
+ vendor
12
+ lib/mysql2/mysql2.rb
data/.rspec ADDED
@@ -0,0 +1,3 @@
1
+ --format documentation
2
+ --colour
3
+ --fail-fast
data/.rvmrc ADDED
@@ -0,0 +1 @@
1
+ rvm use 1.9.3@mysql2 --create
data/.travis.yml ADDED
@@ -0,0 +1,7 @@
1
+ rvm:
2
+ - 1.8.7
3
+ - 1.9.2
4
+ - 1.9.3
5
+ - ree
6
+ before_script:
7
+ - "mysql -e 'create database test;' >/dev/null"
data/CHANGELOG.md ADDED
@@ -0,0 +1,230 @@
1
+ # Changelog
2
+
3
+ ## 0.3.10 (November 9th, 2011)
4
+
5
+ ## 0.3.9 (November 9th, 2011)
6
+
7
+ ## 0.3.8 (November 9th, 2011)
8
+ * remove fiber support from mysql2, the code has moved to the
9
+ em-synchrony gem.
10
+ * use rb_wait_for_single_fd() if available
11
+ * fixed a bug with inheriting query options
12
+ * remove ext/ from the default loadpath
13
+ * fix build issues on OSX with Xcode 4.2 (gcc-llvm compiler)
14
+
15
+ ## 0.3.7 (August 16th, 2011)
16
+ * ensure symbolized column names support encodings in 1.9
17
+
18
+ ## 0.3.6 (June 17th, 2011)
19
+ * fix bug in Time/DateTime range detection
20
+ * (win32) fix bug where the Mysql2::Client object wasn't cleaned up properly if interrupted during a query
21
+ * add Mysql2::Result#count (aliased as size) to get the row count for the dataset
22
+ this can be especially helpful if you want to get the number of rows without having to inflate
23
+ the entire dataset into ruby (since this happens lazily)
24
+
25
+ ## 0.3.5 (June 15th, 2011)
26
+ * bug fix for Time/DateTime usage depending on 32/64bit Ruby
27
+
28
+ ## 0.3.4 (June 15th, 2011)
29
+ * fix a long standing bug where a signal would interrupt rb_thread_select and put the connection in a permanently broken state
30
+ * turn on casting in the ActiveRecord again, users can disable it if they need to for performance reasons
31
+
32
+ ## 0.3.3 (June 14th, 2011)
33
+ * disable async support, and access to the underlying file descriptor under Windows. It's never worked reliably and ruby-core has a lot of work to do in order to make it possible.
34
+ * added support for turning eager-casting off. This is especially useful in ORMs that will lazily cast values upon access.
35
+ * added a warning if a 0.2.x release is being used with ActiveRecord 3.1 since both the 0.2.x releases and AR 3.1 have mysql2 adapters, we want you to use the one in AR 3.1
36
+ * added Mysql2::Client.escape (class-level method)
37
+ * disabled eager-casting in the bundled ActiveRecord adapter (for Rails 3.0 or less)
38
+
39
+ ## 0.3.2 (April 26th, 2011)
40
+ * Fix typo in initialization for older ActiveRecord versions
41
+
42
+ ## 0.3.1 (April 26th, 2011)
43
+ * Fix typo in initialization for older ActiveRecord versions
44
+
45
+ ## 0.3.0 (April 26th, 2011)
46
+ * switch to MySQL Connector/C for win32 builds
47
+ * win32 bugfixes
48
+ * BREAKING CHANGE: the ActiveRecord adapter has been pulled into Rails 3.1 and is no longer part of the gem
49
+ * added Mysql2::Client.escape (class-level) for raw one-off non-encoding-aware escaping
50
+
51
+ ## 0.2.17 (November 9th, 2011)
52
+
53
+ ## 0.2.16 (November 9th, 2011)
54
+
55
+ ## 0.2.15 (November 9th, 2011)
56
+
57
+ ## 0.2.14 (November 9th, 2011)
58
+ * use rb_wait_for_single_fd() if available
59
+ * fixed a bug with inheriting query options
60
+ * remove ext/ from the default loadpath
61
+ * fix build issues on OSX with Xcode 4.2 (gcc-llvm compiler)
62
+
63
+ ## 0.2.13 (August 16th, 2011)
64
+ * fix stupid bug around symbol encoding support (thanks coderrr!)
65
+
66
+ ## 0.2.12 (August 16th, 2011)
67
+ * ensure symbolized column names support encodings in 1.9
68
+ * plugging sql vulnerability in mysql2 adapter
69
+
70
+ ## 0.2.11 (June 17th, 2011)
71
+ * fix bug in Time/DateTime range detection
72
+ * (win32) fix bug where the Mysql2::Client object wasn't cleaned up properly if interrupted during a query
73
+ * add Mysql2::Result#count (aliased as size) to get the row count for the dataset
74
+ this can be especially helpful if you want to get the number of rows without having to inflate
75
+ the entire dataset into ruby (since this happens lazily)
76
+
77
+ ## 0.2.10 (June 15th, 2011)
78
+ * bug fix for Time/DateTime usage depending on 32/64bit Ruby
79
+
80
+ ## 0.2.9 (June 15th, 2011)
81
+ * fix a long standing bug where a signal would interrupt rb_thread_select and put the connection in a permanently broken state
82
+ * turn on casting in the ActiveRecord again, users can disable it if they need to for performance reasons
83
+
84
+ ## 0.2.8 (June 14th, 2011)
85
+ * disable async support, and access to the underlying file descriptor under Windows. It's never worked reliably and ruby-core has a lot of work to do in order to make it possible.
86
+ * added support for turning eager-casting off. This is especially useful in ORMs that will lazily cast values upon access.
87
+ * added a warning if a 0.2.x release is being used with ActiveRecord 3.1 since both the 0.2.x releases and AR 3.1 have mysql2 adapters, we want you to use the one in AR 3.1
88
+ * added Mysql2::Client.escape (class-level method)
89
+ * disabled eager-casting in the bundled ActiveRecord adapter (for Rails 3.0 or less)
90
+
91
+ ## 0.2.7 (March 28th, 2011)
92
+ * various fixes for em_mysql2 and fiber usage
93
+ * use our own Mysql2IndexDefinition class for better compatibility across ActiveRecord versions
94
+ * ensure the query is a string earlier in the Mysql2::Client#query codepath for 1.9
95
+ * only set binary ruby encoding on fields that have a binary flag *and* encoding set
96
+ * a few various optimizations
97
+ * add support for :read_timeout to be set on a connection
98
+ * Fix to install with MariDB on Windows
99
+ * add fibered em connection without activerecord
100
+ * fix some 1.9.3 compilation warnings
101
+ * add LD_RUN_PATH when using hard coded mysql paths - this should help users with MySQL installed in non-standard locations
102
+ * for windows support, duplicate the socket from libmysql and create a temporary CRT fd
103
+ * fix for handling years before 1970 on Windows
104
+ * fixes to the Fiber adapter
105
+ * set wait_timeout maximum on Windows to 2147483
106
+ * update supported range for Time objects
107
+ * upon being required, make sure the libmysql we're using is the one we were built against
108
+ * add Mysql2::Client#thread_id
109
+ * add Mysql2::Client#ping
110
+ * switch connection check in AR adapter to use Mysql2::Client#ping for efficiency
111
+ * prefer linking against thread-safe version of libmysqlclient
112
+ * define RSTRING_NOT_MODIFIED for an awesome rbx speed boost
113
+ * expose Mysql2::Client#encoding in 1.9, make sure we set the error message and sqlstate encodings accordingly
114
+ * do not segfault when raising for invalid charset (found in 1.9.3dev)
115
+
116
+ ## 0.2.6 (October 19th, 2010)
117
+ * version bump since the 0.2.5 win32 binary gems were broken
118
+
119
+ ## 0.2.5 (October 19th, 2010)
120
+ * fixes for easier Win32 binary gem deployment for targeting 1.8 and 1.9 in the same gem
121
+ * refactor of connection checks and management to avoid race conditions with the GC/threading to prevent the unexpected loss of connections
122
+ * update the default flags during connection
123
+ * add support for setting wait_timeout on AR adapter
124
+ * upgrade to rspec2
125
+ * bugfix for an edge case where the GC would clean up a Mysql2::Client object before the underlying MYSQL pointer had been initialized
126
+ * fix to CFLAGS to allow compilation on SPARC with sunstudio compiler - Anko painting <anko.com+github@gmail.com>
127
+
128
+ ## 0.2.4 (September 17th, 2010)
129
+ * a few patches for win32 support from Luis Lavena - thanks man!
130
+ * bugfix from Eric Wong to avoid a potential stack overflow during Mysql2::Client#escape
131
+ * added the ability to turn internal row caching on/off via the :cache_rows => true/false option
132
+ * a couple of small patches for rbx compatibility
133
+ * set IndexDefinition#length in AR adapter - Kouhei Yanagita <yanagi@shakenbu.org>
134
+ * fix a long-standing data corruption bug - thank you thank you thank you to @joedamato (http://github.com/ice799)
135
+ * bugfix from calling mysql_close on a closed/freed connection surfaced by the above fix
136
+
137
+ ## 0.2.3 (August 20th, 2010)
138
+ * connection flags can now be passed to the constructor via the :flags key
139
+ * switch AR adapter connection over to use FOUND_ROWS option
140
+ * patch to ensure we use DateTime objects in place of Time for timestamps that are out of the supported range on 32bit platforms < 1.9.2
141
+
142
+ ## 0.2.2 (August 19th, 2010)
143
+ * Change how AR adapter would send initial commands upon connecting
144
+ ** we can make multiple session variable assignments in a single query
145
+ * fix signal handling when waiting on queries
146
+ * retry connect if interrupted by signals
147
+
148
+ ## 0.2.1 (August 16th, 2010)
149
+ * bring mysql2 ActiveRecord adapter back into gem
150
+
151
+ ## 0.2.0 (August 16th, 2010)
152
+ * switch back to letting libmysql manage all allocation/thread-state/freeing for the connection
153
+ * cache various numeric type conversions in hot-spots of the code for a little speed boost
154
+ * ActiveRecord adapter moved into Rails 3 core
155
+ ** Don't worry 2.3.x users! We'll either release the adapter as a separate gem, or try to get it into 2.3.9
156
+ * Fix for the "closed MySQL connection" error (GH #31)
157
+ * Fix for the "can't modify frozen object" error in 1.9.2 (GH #37)
158
+ * Introduce cascading query and result options (more info in README)
159
+ * Sequel adapter pulled into core (will be in the next release - 3.15.0 at the time of writing)
160
+ * add a safety check when attempting to send a query before a result has been fetched
161
+
162
+ ## 0.1.9 (July 17th, 2010)
163
+ * Support async ActiveRecord access with fibers and EventMachine (mperham)
164
+ * string encoding support for 1.9, respecting Encoding.default_internal
165
+ * added support for rake-compiler (tenderlove)
166
+ * bugfixes for ActiveRecord driver
167
+ ** one minor bugfix for TimeZone support
168
+ ** fix the select_rows method to return what it should according to the docs (r-stu31)
169
+ * Mysql2::Client#fields method added - returns the array of field names from a resultset, as strings
170
+ * Sequel adapter
171
+ ** bugfix regarding sybolized field names (Eric Wong)
172
+ ** fix query logging in Sequel adapter
173
+ * Lots of nice code cleanup (tenderlove)
174
+ ** Mysql2::Error definition moved to pure-Ruby
175
+ ** Mysql2::client#initialize definition moved to pure-Ruby
176
+ ** Mysql2::Result partially moved to pure-Ruby
177
+
178
+ ## 0.1.8 (June 2nd, 2010)
179
+ * fixes for AR adapter for timezone juggling
180
+ * fixes to be able to run benchmarks and specs under 1.9.2
181
+
182
+ ## 0.1.7 (May 22nd, 2010)
183
+ * fix a bug when using the disconnect! method on a closed connection in the AR driver
184
+
185
+ ## 0.1.6 (May 14th, 2010)
186
+ * more fixes to the AR adapter related to casting
187
+ * add missing index creation override method to AR adapter
188
+ * added sql_state and error_number methods to the Mysql2::Error exception class
189
+
190
+ ## 0.1.5 (May 12th, 2010)
191
+ * quite a few patches from Eric Wong related to thread-safety, non-blocking I/O and general cleanup
192
+ ** wrap mysql_real_connect with rb_thread_blocking_region
193
+ ** release GVL for possibly blocking mysql_* library calls
194
+ ** [cleanup] quiet down warnings
195
+ ** [cleanup] make all C symbols static
196
+ ** add Mysql2::Client#close method
197
+ ** correctly free the wrapped result in case of EOF
198
+ ** Fix memory leak from the result wrapper struct itself
199
+ ** make Mysql2::Client destructor safely non-blocking
200
+ * bug fixes for ActiveRecord adapter
201
+ ** added casting for default values since they all come back from Mysql as strings (!?!)
202
+ ** missing constant was added
203
+ ** fixed a typo in the show_variable method
204
+ * switched over sscanf for date/time parsing in C
205
+ * made some specs a little finer-grained
206
+ * initial Sequel adapter added
207
+ * updated query benchmarks to reflect the difference between casting in C and in Ruby
208
+
209
+ ## 0.1.4 (April 23rd, 2010)
210
+ * optimization: implemented a local cache for rows that are lazily created in ruby during iteration. The MySQL C result is freed as soon as all the results have been cached
211
+ * optimization: implemented a local cache for field names so every row reuses the same objects as field names/keys
212
+ * refactor the Mysql2 connection adapter for ActiveRecord to not extend the Mysql adapter - now being a free-standing connection adapter
213
+
214
+ ## 0.1.3 (April 15th, 2010)
215
+ * added an EventMachine Deferrable API
216
+ * added an ActiveRecord connection adapter
217
+ ** should be compatible with 2.3.5 and 3.0 (including Arel)
218
+
219
+ ## 0.1.2 (April 9th, 2010)
220
+ * fix a bug (copy/paste fail) around checking for empty TIME values and returning nil (thanks @marius)
221
+
222
+ ## 0.1.1 (April 6th, 2010)
223
+ * added affected_rows method (mysql_affected_rows)
224
+ * added last_id method (last_insert_id)
225
+ * enable reconnect option by default
226
+ * added initial async query support
227
+ * updated extconf (thanks to the mysqlplus project) for easier gem building
228
+
229
+ ## 0.1.0 (April 6th, 2010)
230
+ * initial release
data/Gemfile ADDED
@@ -0,0 +1,3 @@
1
+ source :rubygems
2
+
3
+ gemspec
data/MIT-LICENSE ADDED
@@ -0,0 +1,20 @@
1
+ Copyright (c) 2010-2011 Brian Lopez - http://github.com/brianmario
2
+
3
+ Permission is hereby granted, free of charge, to any person obtaining
4
+ a copy of this software and associated documentation files (the
5
+ "Software"), to deal in the Software without restriction, including
6
+ without limitation the rights to use, copy, modify, merge, publish,
7
+ distribute, sublicense, and/or sell copies of the Software, and to
8
+ permit persons to whom the Software is furnished to do so, subject to
9
+ the following conditions:
10
+
11
+ The above copyright notice and this permission notice shall be
12
+ included in all copies or substantial portions of the Software.
13
+
14
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
15
+ EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
16
+ MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
17
+ NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
18
+ LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
19
+ OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
20
+ WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
data/README.md ADDED
@@ -0,0 +1,350 @@
1
+ # Mysql2 - A modern, simple and very fast Mysql library for Ruby - binding to libmysql
2
+
3
+ The Mysql2 gem is meant to serve the extremely common use-case of connecting, querying and iterating on results.
4
+ Some database libraries out there serve as direct 1:1 mappings of the already complex C API's available.
5
+ This one is not.
6
+
7
+ It also forces the use of UTF-8 [or binary] for the connection [and all strings in 1.9, unless Encoding.default_internal is set then it'll convert from UTF-8 to that encoding] and uses encoding-aware MySQL API calls where it can.
8
+
9
+ The API consists of two classes:
10
+
11
+ Mysql2::Client - your connection to the database
12
+
13
+ Mysql2::Result - returned from issuing a #query on the connection. It includes Enumerable.
14
+
15
+ ## Installing
16
+
17
+ ``` sh
18
+ gem install mysql2
19
+ ```
20
+
21
+ You may have to specify --with-mysql-config=/some/random/path/bin/mysql_config
22
+
23
+ ## Usage
24
+
25
+ Connect to a database:
26
+
27
+ ``` ruby
28
+ # this takes a hash of options, almost all of which map directly
29
+ # to the familiar database.yml in rails
30
+ # See http://api.rubyonrails.org/classes/ActiveRecord/ConnectionAdapters/MysqlAdapter.html
31
+ client = Mysql2::Client.new(:host => "localhost", :username => "root")
32
+ ```
33
+
34
+ Then query it:
35
+
36
+ ``` ruby
37
+ results = client.query("SELECT * FROM users WHERE group='githubbers'")
38
+ ```
39
+
40
+ Need to escape something first?
41
+
42
+ ``` ruby
43
+ escaped = client.escape("gi'thu\"bbe\0r's")
44
+ results = client.query("SELECT * FROM users WHERE group='#{escaped}'")
45
+ ```
46
+
47
+ You can get a count of your results with `results.count`.
48
+
49
+ Finally, iterate over the results:
50
+
51
+ ``` ruby
52
+ results.each do |row|
53
+ # conveniently, row is a hash
54
+ # the keys are the fields, as you'd expect
55
+ # the values are pre-built ruby primitives mapped from their corresponding field types in MySQL
56
+ # Here's an otter: http://farm1.static.flickr.com/130/398077070_b8795d0ef3_b.jpg
57
+ end
58
+ ```
59
+
60
+ Or, you might just keep it simple:
61
+
62
+ ``` ruby
63
+ client.query("SELECT * FROM users WHERE group='githubbers'").each do |row|
64
+ # do something with row, it's ready to rock
65
+ end
66
+ ```
67
+
68
+ How about with symbolized keys?
69
+
70
+ ``` ruby
71
+ # NOTE: the :symbolize_keys and future options will likely move to the #query method soon
72
+ client.query("SELECT * FROM users WHERE group='githubbers'").each(:symbolize_keys => true) do |row|
73
+ # do something with row, it's ready to rock
74
+ end
75
+ ```
76
+
77
+ You can get the headers and the columns in the order that they were returned
78
+ by the query like this:
79
+
80
+ ``` ruby
81
+ headers = results.fields # <= that's an array of field names, in order
82
+ results.each(:as => :array) do |row|
83
+ # Each row is an array, ordered the same as the query results
84
+ # An otter's den is called a "holt" or "couch"
85
+ end
86
+ ```
87
+
88
+ You can also retrieve multiple result sets. For this to work you need to connect with
89
+ flags `Mysql2::Client::MULTI_STATEMENTS`. Using multiple result sets is normally used
90
+ when calling stored procedures that return more than one result set
91
+
92
+ ``` ruby
93
+ client = Mysql2::Client.new(:host => "localhost", :username => "root", :flags => Mysql2::Client::MULTI_STATEMENTS )
94
+ result = client.query( 'CALL sp_customer_list( 25, 10 )')
95
+ # result now contains the first result set
96
+ while ( client.next_result)
97
+ result = client.store_result
98
+ # result now contains the next result set
99
+ end
100
+ ```
101
+
102
+ See https://gist.github.com/1367987 for using MULTI_STATEMENTS with ActiveRecord.
103
+
104
+ ## Cascading config
105
+
106
+ The default config hash is at:
107
+
108
+ ``` ruby
109
+ Mysql2::Client.default_query_options
110
+ ```
111
+
112
+ which defaults to:
113
+
114
+ ``` ruby
115
+ {:async => false, :as => :hash, :symbolize_keys => false}
116
+ ```
117
+
118
+ that can be used as so:
119
+
120
+ ``` ruby
121
+ # these are the defaults all Mysql2::Client instances inherit
122
+ Mysql2::Client.default_query_options.merge!(:as => :array)
123
+ ```
124
+
125
+ or
126
+
127
+ ``` ruby
128
+ # this will change the defaults for all future results returned by the #query method _for this connection only_
129
+ c = Mysql2::Client.new
130
+ c.query_options.merge!(:symbolize_keys => true)
131
+ ```
132
+
133
+ or
134
+
135
+ ``` ruby
136
+ # this will set the options for the Mysql2::Result instance returned from the #query method
137
+ c = Mysql2::Client.new
138
+ c.query(sql, :symbolize_keys => true)
139
+ ```
140
+
141
+ ## Result types
142
+
143
+ ### Array of Arrays
144
+
145
+ Pass the `:as => :array` option to any of the above methods of configuration
146
+
147
+ ### Array of Hashes
148
+
149
+ The default result type is set to :hash, but you can override a previous setting to something else with :as => :hash
150
+
151
+ ### Others...
152
+
153
+ I may add support for `:as => :csv` or even `:as => :json` to allow for *much* more efficient generation of those data types from result sets.
154
+ If you'd like to see either of these (or others), open an issue and start bugging me about it ;)
155
+
156
+ ### Timezones
157
+
158
+ Mysql2 now supports two timezone options:
159
+
160
+ ``` ruby
161
+ :database_timezone # this is the timezone Mysql2 will assume fields are already stored as, and will use this when creating the initial Time objects in ruby
162
+ :application_timezone # this is the timezone Mysql2 will convert to before finally handing back to the caller
163
+ ```
164
+
165
+ In other words, if `:database_timezone` is set to `:utc` - Mysql2 will create the Time objects using `Time.utc(...)` from the raw value libmysql hands over initially.
166
+ Then, if `:application_timezone` is set to say - `:local` - Mysql2 will then convert the just-created UTC Time object to local time.
167
+
168
+ Both options only allow two values - `:local` or `:utc` - with the exception that `:application_timezone` can be [and defaults to] nil
169
+
170
+ ### Casting "boolean" columns
171
+
172
+ You can now tell Mysql2 to cast `tinyint(1)` fields to boolean values in Ruby with the `:cast_booleans` option.
173
+
174
+ ``` ruby
175
+ client = Mysql2::Client.new
176
+ result = client.query("SELECT * FROM table_with_boolean_field", :cast_booleans => true)
177
+ ```
178
+
179
+ ### Skipping casting
180
+
181
+ Mysql2 casting is fast, but not as fast as not casting data. In rare cases where typecasting is not needed, it will be faster to disable it by providing :cast => false.
182
+
183
+ ``` ruby
184
+ client = Mysql2::Client.new
185
+ result = client.query("SELECT * FROM table", :cast => false)
186
+ ```
187
+
188
+ Here are the results from the `query_without_mysql_casting.rb` script in the benchmarks folder:
189
+
190
+ ``` sh
191
+ user system total real
192
+ Mysql2 (cast: true) 0.340000 0.000000 0.340000 ( 0.405018)
193
+ Mysql2 (cast: false) 0.160000 0.010000 0.170000 ( 0.209937)
194
+ Mysql 0.080000 0.000000 0.080000 ( 0.129355)
195
+ do_mysql 0.520000 0.010000 0.530000 ( 0.574619)
196
+ ```
197
+
198
+ Although Mysql2 performs reasonably well at retrieving uncasted data, it (currently) is not as fast as the Mysql gem. In spite of this small disadvantage, Mysql2 still sports a friendlier interface and doesn't block the entire ruby process when querying.
199
+
200
+ ### Async
201
+
202
+ NOTE: Not supported on Windows.
203
+
204
+ `Mysql2::Client` takes advantage of the MySQL C API's (undocumented) non-blocking function mysql_send_query for *all* queries.
205
+ But, in order to take full advantage of it in your Ruby code, you can do:
206
+
207
+ ``` ruby
208
+ client.query("SELECT sleep(5)", :async => true)
209
+ ```
210
+
211
+ Which will return nil immediately. At this point you'll probably want to use some socket monitoring mechanism
212
+ like EventMachine or even IO.select. Once the socket becomes readable, you can do:
213
+
214
+ ``` ruby
215
+ # result will be a Mysql2::Result instance
216
+ result = client.async_result
217
+ ```
218
+
219
+ NOTE: Because of the way MySQL's query API works, this method will block until the result is ready.
220
+ So if you really need things to stay async, it's best to just monitor the socket with something like EventMachine.
221
+ If you need multiple query concurrency take a look at using a connection pool.
222
+
223
+ ### Row Caching
224
+
225
+ By default, Mysql2 will cache rows that have been created in Ruby (since this happens lazily).
226
+ This is especially helpful since it saves the cost of creating the row in Ruby if you were to iterate over the collection again.
227
+
228
+ If you only plan on using each row once, then it's much more efficient to disable this behavior by setting the `:cache_rows` option to false.
229
+ This would be helpful if you wanted to iterate over the results in a streaming manner. Meaning the GC would cleanup rows you don't need anymore as you're iterating over the result set.
230
+
231
+ ## ActiveRecord
232
+
233
+ To use the ActiveRecord driver (with or without rails), all you should need to do is have this gem installed and set the adapter in your database.yml to "mysql2".
234
+ That was easy right? :)
235
+
236
+ NOTE: as of 0.3.0, and ActiveRecord 3.1 - the ActiveRecord adapter has been pulled out of this gem and into ActiveRecord itself. If you need to use mysql2 with
237
+ Rails versions < 3.1 make sure and specify `gem "mysql2", "~> 0.2.7"` in your Gemfile
238
+
239
+ ## Asynchronous ActiveRecord
240
+
241
+ Please see the [em-synchrony](https://github.com/igrigorik/em-synchrony) project for details about using EventMachine with mysql2 and Rails.
242
+
243
+ ## Sequel
244
+
245
+ The Sequel adapter was pulled out into Sequel core (will be part of the next release) and can be used by specifying the "mysql2://" prefix to your connection specification.
246
+
247
+ ## EventMachine
248
+
249
+ The mysql2 EventMachine deferrable api allows you to make async queries using EventMachine,
250
+ while specifying callbacks for success for failure. Here's a simple example:
251
+
252
+ ``` ruby
253
+ require 'mysql2/em'
254
+
255
+ EM.run do
256
+ client1 = Mysql2::EM::Client.new
257
+ defer1 = client1.query "SELECT sleep(3) as first_query"
258
+ defer1.callback do |result|
259
+ puts "Result: #{result.to_a.inspect}"
260
+ end
261
+
262
+ client2 = Mysql2::EM::Client.new
263
+ defer2 = client2.query "SELECT sleep(1) second_query"
264
+ defer2.callback do |result|
265
+ puts "Result: #{result.to_a.inspect}"
266
+ end
267
+ end
268
+ ```
269
+
270
+ ## Lazy Everything
271
+
272
+ Well... almost ;)
273
+
274
+ Field name strings/symbols are shared across all the rows so only one object is ever created to represent the field name for an entire dataset.
275
+
276
+ Rows themselves are lazily created in ruby-land when an attempt to yield it is made via #each.
277
+ For example, if you were to yield 4 rows from a 100 row dataset, only 4 hashes will be created. The rest will sit and wait in C-land until you want them (or when the GC goes to cleanup your `Mysql2::Result` instance).
278
+ Now say you were to iterate over that same collection again, this time yielding 15 rows - the 4 previous rows that had already been turned into ruby hashes would be pulled from an internal cache, then 11 more would be created and stored in that cache.
279
+ Once the entire dataset has been converted into ruby objects, Mysql2::Result will free the Mysql C result object as it's no longer needed.
280
+
281
+ This caching behavior can be disabled by setting the :cache_rows option to false.
282
+
283
+ As for field values themselves, I'm workin on it - but expect that soon.
284
+
285
+ ## Compatibility
286
+
287
+ The specs pass on my system (SL 10.6.3, x86_64) in these rubies:
288
+
289
+ * 1.8.7-p249
290
+ * ree-1.8.7-2010.01
291
+ * 1.9.1-p378
292
+ * ruby-trunk
293
+ * rbx-head - broken at the moment, working with the rbx team for a solution
294
+
295
+ The ActiveRecord driver should work on 2.3.5 and 3.0
296
+
297
+ ## Yeah... but why?
298
+
299
+ Someone: Dude, the Mysql gem works fiiiiiine.
300
+
301
+ Me: It sure does, but it only hands you nil and strings for field values. Leaving you to convert
302
+ them into proper Ruby types in Ruby-land - which is slow as balls.
303
+
304
+
305
+ Someone: OK fine, but do_mysql can already give me back values with Ruby objects mapped to MySQL types.
306
+
307
+ Me: Yep, but it's API is considerably more complex *and* can be ~2x slower.
308
+
309
+ ## Benchmarks
310
+
311
+ Performing a basic "SELECT * FROM" query on a table with 30k rows and fields of nearly every Ruby-representable data type,
312
+ then iterating over every row using an #each like method yielding a block:
313
+
314
+ These results are from the `query_with_mysql_casting.rb` script in the benchmarks folder
315
+
316
+ ``` sh
317
+ user system total real
318
+ Mysql2
319
+ 0.750000 0.180000 0.930000 ( 1.821655)
320
+ do_mysql
321
+ 1.650000 0.200000 1.850000 ( 2.811357)
322
+ Mysql
323
+ 7.500000 0.210000 7.710000 ( 8.065871)
324
+ ```
325
+
326
+ ## Development
327
+
328
+ To run the tests, you can use RVM and Bundler to create a pristine environment for mysql2 development/hacking.
329
+ Use 'bundle install' to install the necessary development and testing gems:
330
+
331
+ ``` sh
332
+ bundle install
333
+ rake
334
+ ```
335
+
336
+ The tests require the "test" database to exist, and expect to connect
337
+ both as root and the running user, both with a blank password:
338
+
339
+ ``` sql
340
+ CREATE DATABASE test;
341
+ CREATE USER '<user>'@'localhost' IDENTIFIED BY '';
342
+ GRANT ALL PRIVILEGES ON test.* TO '<user>'@'localhost';
343
+ ```
344
+
345
+ ## Special Thanks
346
+
347
+ * Eric Wong - for the contribution (and the informative explanations) of some thread-safety, non-blocking I/O and cleanup patches. You rock dude
348
+ * Yury Korolev (http://github.com/yury) - for TONS of help testing the ActiveRecord adapter
349
+ * Aaron Patterson (http://github.com/tenderlove) - tons of contributions, suggestions and general badassness
350
+ * Mike Perham (http://github.com/mperham) - Async ActiveRecord adapter (uses Fibers and EventMachine)