{"id":13463051,"url":"https://github.com/brianmario/mysql2","last_synced_at":"2025-05-13T16:04:32.569Z","repository":{"id":856099,"uuid":"588600","full_name":"brianmario/mysql2","owner":"brianmario","description":"A modern, simple and very fast Mysql library for Ruby - binding to libmysql","archived":false,"fork":false,"pushed_at":"2025-04-07T07:00:49.000Z","size":2142,"stargazers_count":2255,"open_issues_count":190,"forks_count":550,"subscribers_count":71,"default_branch":"master","last_synced_at":"2025-04-30T07:06:46.370Z","etag":null,"topics":[],"latest_commit_sha":null,"homepage":"http://github.com/brianmario/mysql2","language":"Ruby","has_issues":true,"has_wiki":null,"has_pages":null,"mirror_url":null,"source_name":null,"license":"mit","status":null,"scm":"git","pull_requests_enabled":true,"icon_url":"https://github.com/brianmario.png","metadata":{"files":{"readme":"README.md","changelog":"CHANGELOG.md","contributing":null,"funding":null,"license":"LICENSE","code_of_conduct":null,"threat_model":null,"audit":null,"citation":null,"codeowners":null,"security":null,"support":"support/3A79BD29.asc","governance":null,"roadmap":null,"authors":null,"dei":null,"publiccode":null,"codemeta":null,"zenodo":null}},"created_at":"2010-03-31T15:40:17.000Z","updated_at":"2025-04-29T22:37:34.000Z","dependencies_parsed_at":"2024-02-08T04:31:07.598Z","dependency_job_id":"6ac9d637-eb2d-4fc4-92a0-a6f740902734","html_url":"https://github.com/brianmario/mysql2","commit_stats":{"total_commits":1474,"total_committers":160,"mean_commits":9.2125,"dds":0.655359565807327,"last_synced_commit":"57b8df188c963ae0e4d4e1123d3e9de2bbcab637"},"previous_names":[],"tags_count":75,"template":false,"template_full_name":null,"repository_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/brianmario%2Fmysql2","tags_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/brianmario%2Fmysql2/tags","releases_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/brianmario%2Fmysql2/releases","manifests_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/brianmario%2Fmysql2/manifests","owner_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners/brianmario","download_url":"https://codeload.github.com/brianmario/mysql2/tar.gz/refs/heads/master","host":{"name":"GitHub","url":"https://github.com","kind":"github","repositories_count":252269033,"owners_count":21721241,"icon_url":"https://github.com/github.png","version":null,"created_at":"2022-05-30T11:31:42.601Z","updated_at":"2022-07-04T15:15:14.044Z","host_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub","repositories_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories","repository_names_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repository_names","owners_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners"}},"keywords":[],"created_at":"2024-07-31T13:00:45.011Z","updated_at":"2025-05-05T22:46:01.187Z","avatar_url":"https://github.com/brianmario.png","language":"Ruby","readme":"# Mysql2 - A modern, simple and very fast MySQL library for Ruby - binding to libmysql\n\nGitHub Actions\n[![GitHub Actions Status: Build](https://github.com/brianmario/mysql2/actions/workflows/build.yml/badge.svg)](https://github.com/brianmario/mysql2/actions/workflows/build.yml)\n[![GitHub Actions Status: Container](https://github.com/brianmario/mysql2/actions/workflows/container.yml/badge.svg)](https://github.com/brianmario/mysql2/actions/workflows/container.yml)\nAppveyor CI\n[![Appveyor CI Status](https://ci.appveyor.com/api/projects/status/github/sodabrew/mysql2)](https://ci.appveyor.com/project/sodabrew/mysql2)\n\nThe Mysql2 gem is meant to serve the extremely common use-case of connecting, querying and iterating on results.\nSome database libraries out there serve as direct 1:1 mappings of the already complex C APIs available.\nThis one is not.\n\nIt also forces the use of UTF-8 [or binary] for the connection and uses encoding-aware MySQL API calls where it can.\n\nThe API consists of three classes:\n\n`Mysql2::Client` - your connection to the database.\n\n`Mysql2::Result` - returned from issuing a #query on the connection. It includes Enumerable.\n\n`Mysql2::Statement` - returned from issuing a #prepare on the connection. Execute the statement to get a Result.\n\n## Installing\n\n### General Instructions\n\n``` sh\ngem install mysql2\n```\n\nThis gem links against MySQL's `libmysqlclient` library or `Connector/C`\nlibrary, and compatible alternatives such as MariaDB.\nYou may need to install a package such as `libmariadb-dev`, `libmysqlclient-dev`,\n`mysql-devel`, or other appropriate package for your system. See below for\nsystem-specific instructions.\n\nBy default, the mysql2 gem will try to find a copy of MySQL in this order:\n\n* Option `--with-mysql-dir`, if provided (see below).\n* Option `--with-mysql-config`, if provided (see below).\n* Several typical paths for `mysql_config` (default for the majority of users).\n* The directory `/usr/local`.\n\n### Configuration options\n\nUse these options by `gem install mysql2 -- [--optionA] [--optionB=argument]`.\n\n* `--with-mysql-dir[=/path/to/mysqldir]` -\nSpecify the directory where MySQL is installed. The mysql2 gem will not use\n`mysql_config`, but will instead look at `mysqldir/lib` and `mysqldir/include`\nfor the library and header files.\nThis option is mutually exclusive with `--with-mysql-config`.\n\n* `--with-mysql-config[=/path/to/mysql_config]` -\nSpecify a path to the `mysql_config` binary provided by your copy of MySQL. The\nmysql2 gem will ask this `mysql_config` binary about the compiler and linker\narguments needed.\nThis option is mutually exclusive with `--with-mysql-dir`.\n\n* `--with-mysql-rpath=/path/to/mysql/lib` / `--without-mysql-rpath` -\nOverride the runtime path used to find the MySQL libraries.\nThis may be needed if you deploy to a system where these libraries\nare located somewhere different than on your build system.\nThis overrides any rpath calculated by default or by the options above.\n\n* `--with-openssl-dir[=/path/to/openssl]` - Specify the directory where OpenSSL\nis installed. In most cases, the Ruby runtime and MySQL client libraries will\nlink against a system-installed OpenSSL library and this option is not needed.\nUse this option when non-default library paths are needed.\n\n* `--with-sanitize[=address,cfi,integer,memory,thread,undefined]` -\nEnable sanitizers for Clang / GCC. If no argument is given, try to enable\nall sanitizers or fail if none are available. If a command-separated list of\nspecific sanitizers is given, configure will fail unless they all are available.\nNote that the some sanitizers may incur a performance penalty, and the Address\nSanitizer may require a runtime library.\nTo see line numbers in backtraces, declare these environment variables\n(adjust the llvm-symbolizer path as needed for your system):\n\n``` sh\n  export ASAN_SYMBOLIZER_PATH=/usr/bin/llvm-symbolizer-3.4\n  export ASAN_OPTIONS=symbolize=1\n```\n\n### Linux and other Unixes\n\nYou may need to install a package such as `libmariadb-dev`, `libmysqlclient-dev`,\n`mysql-devel`, or `default-libmysqlclient-dev`; refer to your distribution's package guide to\nfind the particular package. The most common issue we see is a user who has\nthe library file `libmysqlclient.so` but is missing the header file `mysql.h`\n-- double check that you have the _-dev_ packages installed.\n\n### Mac OS X\n\nYou may use Homebrew, MacPorts, or a native MySQL installer package. The most\ncommon paths will be automatically searched. If you want to select a specific\nMySQL directory, use the `--with-mysql-dir` or `--with-mysql-config` options above.\n\nIf you have not done so already, you will need to install the XCode select tools by running\n`xcode-select --install`.\n\nLater versions of MacOS no longer distribute a linkable OpenSSL library. It is\ncommon to use Homebrew or MacPorts to install OpenSSL. Make sure that both the\nRuby runtime and MySQL client libraries are compiled with the same OpenSSL\nfamily, 1.0 or 1.1 or 3.0, since only one can be loaded at runtime.\n\n``` sh\n$ brew install openssl@1.1 zstd\n$ gem install mysql2 -- --with-openssl-dir=$(brew --prefix openssl@1.1)\n\nor\n\n$ sudo port install openssl11\n```\n\nSince most Ruby projects use Bundler, you can set build options in the Bundler\nconfig rather than manually installing a global mysql2 gem. This example shows\nhow to set build arguments with [Bundler config](https://bundler.io/man/bundle-config.1.html):\n\n``` sh\n$ bundle config --local build.mysql2 -- --with-openssl-dir=$(brew --prefix openssl@1.1)\n```\n\nAnother helpful trick is to use the same OpenSSL library that your Ruby was\nbuilt with, if it was built with an alternate OpenSSL path. This example finds\nthe argument `--with-openssl-dir=/some/path` from the Ruby build and adds that\nto the [Bundler config](https://bundler.io/man/bundle-config.1.html):\n\n``` sh\n$ bundle config --local build.mysql2 -- $(ruby -r rbconfig -e 'puts RbConfig::CONFIG[\"configure_args\"]' | xargs -n1 | grep with-openssl-dir)\n```\n\nNote the additional double dashes (`--`) these separate command-line arguments\nthat `gem` or `bundler` interpret from the additional arguments that are passed\nto the mysql2 build process.\n\n### Windows\n\nMake sure that you have Ruby and the DevKit compilers installed. We recommend\nthe [Ruby Installer](http://rubyinstaller.org) distribution.\n\nBy default, the mysql2 gem will download and use MySQL Connector/C from\nmysql.com. If you prefer to use a local installation of Connector/C, add the\nflag `--with-mysql-dir=c:/mysql-connector-c-x-y-z` (_this path may use forward slashes_).\n\nBy default, the `libmysql.dll` library will be copied into the mysql2 gem\ndirectory. To prevent this, add the flag `--no-vendor-libmysql`. The mysql2 gem\nwill search for `libmysql.dll` in the following paths, in order:\n\n* Environment variable `RUBY_MYSQL2_LIBMYSQL_DLL=C:\\path\\to\\libmysql.dll`\n  (_note the Windows-style backslashes_).\n* In the mysql2 gem's own directory `vendor/libmysql.dll`\n* In the system's default library search paths.\n\n## Usage\n\nConnect to a database:\n\n``` ruby\n# this takes a hash of options, almost all of which map directly\n# to the familiar database.yml in rails\n# See http://api.rubyonrails.org/classes/ActiveRecord/ConnectionAdapters/Mysql2Adapter.html\nclient = Mysql2::Client.new(:host =\u003e \"localhost\", :username =\u003e \"root\")\n```\n\nThen query it:\n\n``` ruby\nresults = client.query(\"SELECT * FROM users WHERE group='githubbers'\")\n```\n\nNeed to escape something first?\n\n``` ruby\nescaped = client.escape(\"gi'thu\\\"bbe\\0r's\")\nresults = client.query(\"SELECT * FROM users WHERE group='#{escaped}'\")\n```\n\nYou can get a count of your results with `results.count`.\n\nFinally, iterate over the results:\n\n``` ruby\nresults.each do |row|\n  # conveniently, row is a hash\n  # the keys are the fields, as you'd expect\n  # the values are pre-built ruby primitives mapped from their corresponding field types in MySQL\n  puts row[\"id\"] # row[\"id\"].is_a? Integer\n  if row[\"dne\"]  # non-existent hash entry is nil\n    puts row[\"dne\"]\n  end\nend\n```\n\nOr, you might just keep it simple:\n\n``` ruby\nclient.query(\"SELECT * FROM users WHERE group='githubbers'\").each do |row|\n  # do something with row, it's ready to rock\nend\n```\n\nHow about with symbolized keys?\n\n``` ruby\nclient.query(\"SELECT * FROM users WHERE group='githubbers'\", :symbolize_keys =\u003e true).each do |row|\n  # do something with row, it's ready to rock\nend\n```\n\nYou can get the headers, columns, and the field types in the order that they were returned\nby the query like this:\n\n``` ruby\nheaders = results.fields # \u003c= that's an array of field names, in order\ntypes = results.field_types # \u003c= that's an array of field types, in order\nresults.each(:as =\u003e :array) do |row|\n  # Each row is an array, ordered the same as the query results\n  # An otter's den is called a \"holt\" or \"couch\"\nend\n```\n\nPrepared statements are supported, as well. In a prepared statement, use a `?`\nin place of each value and then execute the statement to retrieve a result set.\nPass your arguments to the execute method in the same number and order as the\nquestion marks in the statement. Query options can be passed as keyword arguments\nto the execute method.\n\nBe sure to read about the known limitations of prepared statements at\n[https://dev.mysql.com/doc/refman/5.6/en/c-api-prepared-statement-problems.html](https://dev.mysql.com/doc/refman/5.6/en/c-api-prepared-statement-problems.html)\n\n``` ruby\nstatement = @client.prepare(\"SELECT * FROM users WHERE login_count = ?\")\nresult1 = statement.execute(1)\nresult2 = statement.execute(2)\n\nstatement = @client.prepare(\"SELECT * FROM users WHERE last_login \u003e= ? AND location LIKE ?\")\nresult = statement.execute(1, \"CA\")\n\nstatement = @client.prepare(\"SELECT * FROM users WHERE last_login \u003e= ? AND location LIKE ?\")\nresult = statement.execute(1, \"CA\", :as =\u003e :array)\n```\n\nSession Tracking information can be accessed with\n\n``` ruby\nc = Mysql2::Client.new(\n  host: \"127.0.0.1\",\n  username: \"root\",\n  flags: \"SESSION_TRACK\",\n  init_command: \"SET @@SESSION.session_track_schema=ON\"\n)\nc.query(\"INSERT INTO test VALUES (1)\")\nsession_track_type = Mysql2::Client::SESSION_TRACK_SCHEMA\nsession_track_data = c.session_track(session_track_type)\n```\n\nThe types of session track types can be found at\n[https://dev.mysql.com/doc/refman/5.7/en/session-state-tracking.html](https://dev.mysql.com/doc/refman/5.7/en/session-state-tracking.html)\n\n## Connection options\n\nYou may set the following connection options in Mysql2::Client.new(...):\n\n``` ruby\nMysql2::Client.new(\n  :host,\n  :username,\n  :password,\n  :port,\n  :database,\n  :socket = '/path/to/mysql.sock',\n  :flags = REMEMBER_OPTIONS | LONG_PASSWORD | LONG_FLAG | TRANSACTIONS | PROTOCOL_41 | SECURE_CONNECTION | MULTI_STATEMENTS,\n  :encoding = 'utf8mb4',\n  :read_timeout = seconds,\n  :write_timeout = seconds,\n  :connect_timeout = seconds,\n  :connect_attrs = {:program_name =\u003e $PROGRAM_NAME, ...},\n  :reconnect = true/false,\n  :local_infile = true/false,\n  :secure_auth = true/false,\n  :get_server_public_key = true/false,\n  :default_file = '/path/to/my.cfg',\n  :default_group = 'my.cfg section',\n  :default_auth = 'authentication_windows_client'\n  :init_command =\u003e sql\n  )\n```\n\n### Connecting to MySQL on localhost and elsewhere\n\nThe underlying MySQL client library uses the `:host` parameter to determine the\ntype of connection to make, with special interpretation you should be aware of:\n\n* An empty value or `\"localhost\"` will attempt a local connection:\n  * On Unix, connect to the default local socket path. (To set a custom socket\n    path, use the `:socket` parameter).\n  * On Windows, connect using a shared-memory connection, if enabled, or TCP.\n* A value of `\".\"` on Windows specifies a named-pipe connection.\n* An IPv4 or IPv6 address will result in a TCP connection.\n* Any other value will be looked up as a hostname for a TCP connection.\n\n### SSL/TLS options\n\nSetting any of the following options will enable an SSL/TLS connection, but\nonly if your MySQL client library and server have been compiled with SSL\nsupport. MySQL client library defaults will be used for any parameters that are\nleft out or set to nil. Relative paths are allowed, and may be required by\nmanaged hosting providers such as Heroku.\n\n``` ruby\nMysql2::Client.new(\n  # ...options as above...,\n  :sslkey =\u003e '/path/to/client-key.pem',\n  :sslcert =\u003e '/path/to/client-cert.pem',\n  :sslca =\u003e '/path/to/ca-cert.pem',\n  :sslcapath =\u003e '/path/to/cacerts',\n  :sslcipher =\u003e 'DHE-RSA-AES256-SHA',\n  :sslverify =\u003e true, # Removed in MySQL 8.0\n  :ssl_mode =\u003e :disabled / :preferred / :required / :verify_ca / :verify_identity,\n  )\n```\n\nFor MySQL versions 5.7.11 and higher, use `:ssl_mode` to prefer or require an\nSSL connection and certificate validation. For earlier versions of MySQL, use\nthe `:sslverify` boolean. For details on each of the `:ssl_mode` options, see\n[https://dev.mysql.com/doc/refman/8.0/en/connection-options.html](https://dev.mysql.com/doc/refman/8.0/en/connection-options.html#option_general_ssl-mode).\n\nThe `:ssl_mode` option will also set the appropriate MariaDB connection flags:\n\n| `:ssl_mode`        | MariaDB option value                 |\n| ---                | ---                                  |\n| `:disabled`        | MYSQL_OPT_SSL_ENFORCE = 0            |\n| `:required`        | MYSQL_OPT_SSL_ENFORCE = 1            |\n| `:verify_identity` | MYSQL_OPT_SSL_VERIFY_SERVER_CERT = 1 |\n\nMariaDB does not support the `:preferred` or `:verify_ca` options. For more\ninformation about SSL/TLS in MariaDB, see\n[https://mariadb.com/kb/en/securing-connections-for-client-and-server/](https://mariadb.com/kb/en/securing-connections-for-client-and-server/)\nand [https://mariadb.com/kb/en/mysql_optionsv/#tls-options](https://mariadb.com/kb/en/mysql_optionsv/#tls-options)\n\n### Secure auth\n\nStarting with MySQL 5.6.5, secure_auth is enabled by default on servers (it was disabled by default prior to this).\nWhen secure_auth is enabled, the server will refuse a connection if the account password is stored in old pre-MySQL 4.1 format.\nThe MySQL 5.6.5 client library may also refuse to attempt a connection if provided an older format password.\nTo bypass this restriction in the client, pass the option `:secure_auth =\u003e false` to Mysql2::Client.new().\n\n### Flags option parsing\n\nThe `:flags` parameter accepts an integer, a string, or an array. The integer\nform allows the client to assemble flags from constants defined under\n`Mysql2::Client` such as `Mysql2::Client::FOUND_ROWS`. Use a bitwise `|` (OR)\nto specify several flags.\n\nThe string form will be split on whitespace and parsed as with the array form:\nPlain flags are added to the default flags, while flags prefixed with `-`\n(minus) are removed from the default flags.\n\n### Using Active Record's database.yml\n\nActive Record typically reads its configuration from a file named `database.yml` or an environment variable `DATABASE_URL`.\nUse the value `mysql2` as the adapter name. For example:\n\n``` yaml\ndevelopment:\n  adapter: mysql2\n  encoding: utf8mb4\n  database: my_db_name\n  username: root\n  password: my_password\n  host: 127.0.0.1\n  port: 3306\n  flags:\n    - -COMPRESS\n    - FOUND_ROWS\n    - MULTI_STATEMENTS\n  secure_auth: false\n```\n\nIn this example, the compression flag is negated with `-COMPRESS`.\n\n### Using Active Record's DATABASE_URL\n\nActive Record typically reads its configuration from a file named `database.yml` or an environment variable `DATABASE_URL`.\nUse the value `mysql2` as the protocol name. For example:\n\n``` sh\nDATABASE_URL=mysql2://sql_user:sql_pass@sql_host_name:port/sql_db_name?option1=value1\u0026option2=value2\n```\n\n### Reading a MySQL config file\n\nYou may read configuration options from a MySQL configuration file by passing\nthe `:default_file` and `:default_group` parameters. For example:\n\n``` ruby\nMysql2::Client.new(:default_file =\u003e '/user/.my.cnf', :default_group =\u003e 'client')\n```\n\n### Initial command on connect and reconnect\n\nIf you specify the `:init_command` option, the SQL string you provide will be executed after the connection is established.\nIf `:reconnect` is set to `true`, init_command will also be executed after a successful reconnect.\nIt is useful if you want to provide session options which survive reconnection.\n\n``` ruby\nMysql2::Client.new(:init_command =\u003e \"SET @@SESSION.sql_mode = 'STRICT_ALL_TABLES'\")\n```\n\n### Multiple result sets\n\nYou can also retrieve multiple result sets. For this to work you need to\nconnect with flags `Mysql2::Client::MULTI_STATEMENTS`. Multiple result sets can\nbe used with stored procedures that return more than one result set, and for\nbundling several SQL statements into a single call to `client.query`.\n\n``` ruby\nclient = Mysql2::Client.new(:host =\u003e \"localhost\", :username =\u003e \"root\", :flags =\u003e Mysql2::Client::MULTI_STATEMENTS)\nresult = client.query('CALL sp_customer_list( 25, 10 )')\n# result now contains the first result set\nwhile client.next_result\n  result = client.store_result\n  # result now contains the next result set\nend\n```\n\nRepeated calls to `client.next_result` will return true, false, or raise an\nexception if the respective query erred. When `client.next_result` returns true,\ncall `client.store_result` to retrieve a result object. Exceptions are not\nraised until `client.next_result` is called to find the status of the respective\nquery. Subsequent queries are not executed if an earlier query raised an\nexception. Subsequent calls to `client.next_result` will return false.\n\n``` ruby\nresult = client.query('SELECT 1; SELECT 2; SELECT A; SELECT 3')\np result.first\n\nwhile client.next_result\n  result = client.store_result\n  p result.first\nend\n```\n\nYields:\n\n``` ruby\n{\"1\"=\u003e1}\n{\"2\"=\u003e2}\nnext_result: Unknown column 'A' in 'field list' (Mysql2::Error)\n```\n\n## Cascading config\n\nThe default config hash is at:\n\n``` ruby\nMysql2::Client.default_query_options\n```\n\nwhich defaults to:\n\n``` ruby\n{:async =\u003e false, :as =\u003e :hash, :symbolize_keys =\u003e false}\n```\n\nthat can be used as so:\n\n``` ruby\n# these are the defaults all Mysql2::Client instances inherit\nMysql2::Client.default_query_options.merge!(:as =\u003e :array)\n```\n\nor\n\n``` ruby\n# this will change the defaults for all future results returned by the #query method _for this connection only_\nc = Mysql2::Client.new\nc.query_options.merge!(:symbolize_keys =\u003e true)\n```\n\nor\n\n``` ruby\n# this will set the options for the Mysql2::Result instance returned from the #query method\nc = Mysql2::Client.new\nc.query(sql, :symbolize_keys =\u003e true)\n```\n\nor\n\n``` ruby\n# this will set the options for the Mysql2::Result instance returned from the #execute method\nc = Mysql2::Client.new\ns = c.prepare(sql)\ns.execute(arg1, args2, :symbolize_keys =\u003e true)\n```\n\n## Result types\n\n### Array of Arrays\n\nPass the `:as =\u003e :array` option to any of the above methods of configuration\n\n### Array of Hashes\n\nThe default result type is set to `:hash`, but you can override a previous setting to something else with `:as =\u003e :hash`\n\n### Timezones\n\nMysql2 now supports two timezone options:\n\n``` ruby\n: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\n:application_timezone # this is the timezone Mysql2 will convert to before finally handing back to the caller\n```\n\nIn 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.\nThen, if `:application_timezone` is set to say - `:local` - Mysql2 will then convert the just-created UTC Time object to local time.\n\nBoth options only allow two values - `:local` or `:utc` - with the exception that `:application_timezone` can be [and defaults to] nil\n\n### Casting \"boolean\" columns\n\nYou can now tell Mysql2 to cast `tinyint(1)` fields to boolean values in Ruby with the `:cast_booleans` option.\n\n``` ruby\nclient = Mysql2::Client.new\nresult = client.query(\"SELECT * FROM table_with_boolean_field\", :cast_booleans =\u003e true)\n```\n\nKeep in mind that this works only with fields and not with computed values, e.g. this result will contain `1`, not `true`:\n\n``` ruby\nclient = Mysql2::Client.new\nresult = client.query(\"SELECT true\", :cast_booleans =\u003e true)\n```\n\nCAST function wouldn't help here as there's no way to cast to TINYINT(1). Apparently the only way to solve this is to use a stored procedure with return type set to TINYINT(1).\n\n### Skipping casting\n\nMysql2 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 =\u003e false. (Note that :cast =\u003e false overrides :cast_booleans =\u003e true.)\n\n``` ruby\nclient = Mysql2::Client.new\nresult = client.query(\"SELECT * FROM table\", :cast =\u003e false)\n```\n\nHere are the results from the `query_without_mysql_casting.rb` script in the benchmarks folder:\n\n``` sh\n                           user     system      total        real\nMysql2 (cast: true)    0.340000   0.000000   0.340000 (  0.405018)\nMysql2 (cast: false)   0.160000   0.010000   0.170000 (  0.209937)\nMysql                  0.080000   0.000000   0.080000 (  0.129355)\ndo_mysql               0.520000   0.010000   0.530000 (  0.574619)\n```\n\nAlthough 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.\n\n### Async\n\nNOTE: Not supported on Windows.\n\n`Mysql2::Client` takes advantage of the MySQL C API's (undocumented) non-blocking function mysql_send_query for *all* queries.\nBut, in order to take full advantage of it in your Ruby code, you can do:\n\n``` ruby\nclient.query(\"SELECT sleep(5)\", :async =\u003e true)\n```\n\nWhich will return nil immediately. At this point you'll probably want to use some socket monitoring mechanism\nlike EventMachine or even IO.select. Once the socket becomes readable, you can do:\n\n``` ruby\n# result will be a Mysql2::Result instance\nresult = client.async_result\n```\n\nNOTE: Because of the way MySQL's query API works, this method will block until the result is ready.\nSo if you really need things to stay async, it's best to just monitor the socket with something like EventMachine.\nIf you need multiple query concurrency take a look at using a connection pool.\n\n### Row Caching\n\nBy default, Mysql2 will cache rows that have been created in Ruby (since this happens lazily).\nThis is especially helpful since it saves the cost of creating the row in Ruby if you were to iterate over the collection again.\n\nIf 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.\nThis 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.\n\n### Streaming\n\n`Mysql2::Client` can optionally only fetch rows from the server on demand by setting `:stream =\u003e true`. This is handy when handling very large result sets which might not fit in memory on the client.\n\n``` ruby\nresult = client.query(\"SELECT * FROM really_big_Table\", :stream =\u003e true)\n```\n\nThere are a few things that need to be kept in mind while using streaming:\n\n* `:cache_rows` is ignored currently. (if you want to use `:cache_rows` you probably don't want to be using `:stream`)\n* You must fetch all rows in the result set of your query before you can make new queries. (i.e. with `Mysql2::Result#each`)\n\nRead more about the consequences of using `mysql_use_result` (what streaming is implemented with) here: [http://dev.mysql.com/doc/refman/5.0/en/mysql-use-result.html](http://dev.mysql.com/doc/refman/5.0/en/mysql-use-result.html).\n\n### Lazy Everything\n\nWell... almost ;)\n\nField 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.\n\nRows themselves are lazily created in ruby-land when an attempt to yield it is made via #each.\nFor 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).\nNow 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.\nOnce the entire dataset has been converted into ruby objects, Mysql2::Result will free the Mysql C result object as it's no longer needed.\n\nThis caching behavior can be disabled by setting the `:cache_rows` option to false.\n\nAs for field values themselves, I'm workin on it - but expect that soon.\n\n## Compatibility\n\nThis gem is tested with the following Ruby versions on Linux and Mac OS X:\n\n* Ruby MRI 2.0 through 2.7 (all versions to date)\n* Ruby MRI 3.0, 3.1, 3.2 (all versions to date)\n* Rubinius 2.x and 3.x do work but may fail under some workloads\n\nThis gem is tested with the following MySQL and MariaDB versions:\n\n* MySQL 5.5, 5.6, 5.7, 8.0\n* MySQL Connector/C 6.0, 6.1, 8.0 (primarily on Windows)\n* MariaDB 5.5, 10.x, with a focus on 10.6 LTS and 10.11 LTS\n* MariaDB Connector/C 2.x, 3.x\n\n### Ruby on Rails / Active Record\n\n* mysql2 0.5.x works with Rails / Active Record 4.2.11, 5.0.7, 5.1.6, and higher.\n* mysql2 0.4.x works with Rails / Active Record 4.2.5 - 5.0 and higher.\n* mysql2 0.3.x works with Rails / Active Record 3.1, 3.2, 4.x, 5.0.\n* mysql2 0.2.x works with Rails / Active Record 2.3 - 3.0.\n\n### Asynchronous Active Record\n\nPlease see the [em-synchrony](https://github.com/igrigorik/em-synchrony) project for details about using EventMachine with mysql2 and Rails.\n\n### Sequel\n\nSequel includes a mysql2 adapter in all releases since 3.15 (2010-09-01).\nUse the prefix \"mysql2://\" in your connection specification.\n\n### EventMachine\n\nThe mysql2 EventMachine deferrable api allows you to make async queries using EventMachine,\nwhile specifying callbacks for success for failure. Here's a simple example:\n\n``` ruby\nrequire 'mysql2/em'\n\nEM.run do\n  client1 = Mysql2::EM::Client.new\n  defer1 = client1.query \"SELECT sleep(3) as first_query\"\n  defer1.callback do |result|\n    puts \"Result: #{result.to_a.inspect}\"\n  end\n\n  client2 = Mysql2::EM::Client.new\n  defer2 = client2.query \"SELECT sleep(1) second_query\"\n  defer2.callback do |result|\n    puts \"Result: #{result.to_a.inspect}\"\n  end\nend\n```\n\n## Benchmarks and Comparison\n\nThe mysql2 gem converts MySQL field types to Ruby data types in C code, providing a serious speed benefit.\n\nThe do_mysql gem also converts MySQL fields types, but has a considerably more complex API and is still ~2x slower than mysql2.\n\nThe mysql gem returns only nil or string data types, leaving you to convert field values to Ruby types in Ruby-land, which is much slower than mysql2's C code.\n\nFor a comparative benchmark, the script below performs a basic \"SELECT * FROM\"\nquery on a table with 30k rows and fields of nearly every Ruby-representable\ndata type, then iterating over every row using an #each like method yielding a\nblock:\n\n``` sh\n         user       system     total       real\nMysql2   0.750000   0.180000   0.930000   (1.821655)\ndo_mysql 1.650000   0.200000   1.850000   (2.811357)\nMysql    7.500000   0.210000   7.710000   (8.065871)\n```\n\nThese results are from the `query_with_mysql_casting.rb` script in the benchmarks folder.\n\n## Development\n\nUse 'bundle install' to install the necessary development and testing gems:\n\n``` sh\nbundle install\nrake\n```\n\nThe tests require the \"test\" database to exist, and expect to connect\nboth as root and the running user, both with a blank password:\n\n``` sql\nCREATE DATABASE test;\nCREATE USER '\u003cuser\u003e'@'localhost' IDENTIFIED BY '';\nGRANT ALL PRIVILEGES ON test.* TO '\u003cuser\u003e'@'localhost';\n```\n\nYou can change these defaults in the spec/configuration.yml which is generated\nautomatically when you run rake (or explicitly `rake spec/configuration.yml`).\n\nFor a normal installation on a Mac, you most likely do not need to do anything,\nthough.\n\n## Special Thanks\n\n* Eric Wong - for the contribution (and the informative explanations) of some thread-safety, non-blocking I/O and cleanup patches. You rock dude\n* [Yury Korolev](http://github.com/yury) - for TONS of help testing the Active Record adapter\n* [Aaron Patterson](http://github.com/tenderlove) - tons of contributions, suggestions and general badassness\n* [Mike Perham](http://github.com/mperham) - Async Active Record adapter (uses Fibers and EventMachine)\n* [Aaron Stone](http://github.com/sodabrew) - additional client settings, local files, microsecond time, maintenance support\n* [Kouhei Ueno](https://github.com/nyaxt) - for the original work on Prepared Statements way back in 2012\n* [John Cant](http://github.com/johncant) - polishing and updating Prepared Statements support\n* [Justin Case](http://github.com/justincase) - polishing and updating Prepared Statements support and getting it merged\n* [Tamir Duberstein](http://github.com/tamird) - for help with timeouts and all around updates and cleanups\n* [Jun Aruga](http://github.com/junaruga) - for migrating CI tests to GitHub Actions and other improvements\n","funding_links":[],"categories":["Data Persistence","Database Drivers","Ruby","Connectors"],"sub_categories":["SQL Database Adapters"],"project_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fbrianmario%2Fmysql2","html_url":"https://awesome.ecosyste.ms/projects/github.com%2Fbrianmario%2Fmysql2","lists_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fbrianmario%2Fmysql2/lists"}