Class: Mysql

Inherits:
Object
  • Object
show all
Defined in:
lib/mysql.rb,
lib/mysql/error.rb,
lib/mysql/packet.rb,
lib/mysql/charset.rb,
lib/mysql/protocol.rb,
lib/mysql/constants.rb,
lib/mysql/authenticator.rb,
lib/mysql/authenticator/sha256_password.rb,
lib/mysql/authenticator/caching_sha2_password.rb,
lib/mysql/authenticator/mysql_native_password.rb

Overview

Copyright (C) 2003 TOMITA Masahiro [email protected]

Defined Under Namespace

Classes: Authenticator, Charset, ClientError, Error, Field, Packet, Protocol, ProtocolError, RawRecord, Result, ResultBase, ServerError, Stmt, StmtRawRecord

Constant Summary collapse

VERSION =

Version number of this library

'3.0.1'
MYSQL_UNIX_PORT =

UNIX domain socket filename

"/tmp/mysql.sock"
MYSQL_TCP_PORT =

TCP socket port number

3306
DEFAULT_OPTS =
{
  host: nil,
  username: nil,
  password: nil,
  database: nil,
  port: nil,
  socket: nil,
  flags: 0,
  charset: nil,
  connect_timeout: nil,
  read_timeout: nil,
  write_timeout: nil,
  init_command: nil,
  local_infile: nil,
  load_data_local_dir: nil,
  ssl_mode: SSL_MODE_PREFERRED,
  get_server_public_key: false,
}.freeze
COM_SLEEP =

Command

0
COM_QUIT =
1
COM_INIT_DB =
2
COM_QUERY =
3
COM_FIELD_LIST =
4
COM_CREATE_DB =
5
COM_DROP_DB =
6
COM_REFRESH =
7
COM_SHUTDOWN =
8
COM_STATISTICS =
9
COM_PROCESS_INFO =
10
COM_CONNECT =
11
COM_PROCESS_KILL =
12
COM_DEBUG =
13
COM_PING =
14
COM_TIME =
15
COM_DELAYED_INSERT =
16
COM_CHANGE_USER =
17
COM_BINLOG_DUMP =
18
COM_TABLE_DUMP =
19
COM_CONNECT_OUT =
20
COM_REGISTER_SLAVE =
21
COM_STMT_PREPARE =
22
COM_STMT_EXECUTE =
23
COM_STMT_SEND_LONG_DATA =
24
COM_STMT_CLOSE =
25
COM_STMT_RESET =
26
COM_SET_OPTION =
27
COM_STMT_FETCH =
28
COM_DAEMON =
29
COM_BINLOG_DUMP_GTID =
30
COM_RESET_CONNECTION =
31
COM_CLONE =
32
CLIENT_LONG_PASSWORD =

Client flag

1
CLIENT_FOUND_ROWS =

new more secure passwords

1 << 1
CLIENT_LONG_FLAG =

Found instead of affected rows

1 << 2
CLIENT_CONNECT_WITH_DB =

Get all column flags

1 << 3
CLIENT_NO_SCHEMA =

One can specify db on connect

1 << 4
CLIENT_COMPRESS =

Don't allow database.table.column

1 << 5
CLIENT_ODBC =

Can use compression protocol

1 << 6
CLIENT_LOCAL_FILES =

Odbc client

1 << 7
CLIENT_IGNORE_SPACE =

Can use LOAD DATA LOCAL

1 << 8
CLIENT_PROTOCOL_41 =

Ignore spaces before '('

1 << 9
CLIENT_INTERACTIVE =

New 4.1 protocol

1 << 10
CLIENT_SSL =

This is an interactive client

1 << 11
CLIENT_IGNORE_SIGPIPE =

Switch to SSL after handshake

1 << 12
CLIENT_TRANSACTIONS =

IGNORE sigpipes

1 << 13
CLIENT_RESERVED =

Client knows about transactions

1 << 14
CLIENT_SECURE_CONNECTION =

Old flag for 4.1 protocol

1 << 15
CLIENT_MULTI_STATEMENTS =

New 4.1 authentication

1 << 16
CLIENT_MULTI_RESULTS =

Enable/disable multi-stmt support

1 << 17
CLIENT_PS_MULTI_RESULTS =

Enable/disable multi-results

1 << 18
CLIENT_PLUGIN_AUTH =

Multi-results in PS-protocol

1 << 19
CLIENT_CONNECT_ATTRS =

Client supports plugin authentication

1 << 20
CLIENT_PLUGIN_AUTH_LENENC_CLIENT_DATA =

Client supports connection attribute

1 << 21
CLIENT_CAN_HANDLE_EXPIRED_PASSWORDS =

Enable authentication response packet to be larger than 255 bytes.

1 << 22
CLIENT_SESSION_TRACK =

Don't close the connection for a connection with expired password.

1 << 23
CLIENT_DEPRECATE_EOF =

Capable of handling server state change information. Its a hint to the server to include the state change information in Ok packet.

1 << 24
CLIENT_OPTIONAL_RESULTSET_METADATA =

Client no longer needs EOF packet

1 << 25
CLIENT_ZSTD_COMPRESSION_ALGORITHM =

The client can handle optional metadata information in the resultset.

1 << 26
CLIENT_CAPABILITY_EXTENSION =

Compression protocol extended to support zstd compression method

1 << 29
CLIENT_SSL_VERIFY_SERVER_CERT =

This flag will be reserved to extend the 32bit capabilities structure to 64bits.

1 << 30
CLIENT_REMEMBER_OPTIONS =

Verify server certificate.

1 << 31
OPT_CONNECT_TIMEOUT =

Connection Option

0
OPT_COMPRESS =
1
OPT_NAMED_PIPE =
2
INIT_COMMAND =
3
READ_DEFAULT_FILE =
4
READ_DEFAULT_GROUP =
5
SET_CHARSET_DIR =
6
SET_CHARSET_NAME =
7
OPT_LOCAL_INFILE =
8
OPT_PROTOCOL =
9
SHARED_MEMORY_BASE_NAME =
10
OPT_READ_TIMEOUT =
11
OPT_WRITE_TIMEOUT =
12
OPT_USE_RESULT =
13
REPORT_DATA_TRUNCATION =
14
OPT_RECONNECT =
15
PLUGIN_DIR =
16
DEFAULT_AUTH =
17
OPT_BIND =
18
OPT_SSL_KEY =
19
OPT_SSL_CERT =
20
OPT_SSL_CA =
21
OPT_SSL_CAPATH =
22
OPT_SSL_CIPHER =
23
OPT_SSL_CRL =
24
OPT_SSL_CRLPATH =
25
OPT_CONNECT_ATTR_RESET =
26
OPT_CONNECT_ATTR_ADD =
27
OPT_CONNECT_ATTR_DELETE =
28
SERVER_PUBLIC_KEY =
29
ENABLE_CLEARTEXT_PLUGIN =
30
OPT_CAN_HANDLE_EXPIRED_PASSWORDS =
31
OPT_MAX_ALLOWED_PACKET =
32
OPT_NET_BUFFER_LENGTH =
33
OPT_TLS_VERSION =
34
OPT_SSL_MODE =
35
OPT_GET_SERVER_PUBLIC_KEY =
36
OPT_RETRY_COUNT =
37
OPT_OPTIONAL_RESULTSET_METADATA =
38
OPT_SSL_FIPS_MODE =
39
OPT_TLS_CIPHERSUITES =
40
OPT_COMPRESSION_ALGORITHMS =
41
OPT_ZSTD_COMPRESSION_LEVEL =
42
OPT_LOAD_DATA_LOCAL_DIR =
43
SSL_MODE_DISABLED =

SSL Mode

1
SSL_MODE_PREFERRED =
2
SSL_MODE_REQUIRED =
3
SSL_MODE_VERIFY_CA =
4
SSL_MODE_VERIFY_IDENTITY =
5
OPTION_MULTI_STATEMENTS_ON =

Server Option

0
OPTION_MULTI_STATEMENTS_OFF =
1
SERVER_STATUS_IN_TRANS =

Server Status

1
SERVER_STATUS_AUTOCOMMIT =
1 << 1
SERVER_MORE_RESULTS_EXISTS =
1 << 3
SERVER_QUERY_NO_GOOD_INDEX_USED =
1 << 4
SERVER_QUERY_NO_INDEX_USED =
1 << 5
SERVER_STATUS_CURSOR_EXISTS =
1 << 6
SERVER_STATUS_LAST_ROW_SENT =
1 << 7
SERVER_STATUS_DB_DROPPED =
1 << 8
SERVER_STATUS_NO_BACKSLASH_ESCAPES =
1 << 9
SERVER_STATUS_METADATA_CHANGED =
1 << 10
SERVER_QUERY_WAS_SLOW =
1 << 11
SERVER_PS_OUT_PARAMS =
1 << 12
SERVER_STATUS_IN_TRANS_READONLY =
1 << 13
SERVER_SESSION_STATE_CHANGED =
1 << 14
REFRESH_GRANT =

Refresh parameter

1
REFRESH_LOG =
1 << 1
REFRESH_TABLES =
1 << 2
REFRESH_HOSTS =
1 << 3
REFRESH_STATUS =
1 << 4
REFRESH_THREADS =
1 << 5
REFRESH_SLAVE =
1 << 6
REFRESH_MASTER =
1 << 7
REFRESH_ERROR_LOG =
1 << 8
REFRESH_ENGINE_LOG =
1 << 9
REFRESH_BINARY_LOG =
1 << 10
REFRESH_RELAY_LOG =
1 << 11
REFRESH_GENERAL_LOG =
1 << 12
REFRESH_SLOW_LOG =
1 << 13
REFRESH_READ_LOCK =
1 << 14
REFRESH_FAST =
1 << 15
REFRESH_QUERY_CACHE =
1 << 16
REFRESH_QUERY_CACHE_FREE =
1 << 17
REFRESH_DES_KEY_FILE =
1 << 18
REFRESH_USER_RESOURCES =
1 << 19
REFRESH_FOR_EXPORT =
1 << 20
REFRESH_OPTIMIZER_COSTS =
1 << 21
REFRESH_PERSIST =
1 << 22

Instance Attribute Summary collapse

Class Method Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(uri, **opts) ⇒ Mysql #initialize(host, username, password, database, port, socket, flags, **opts) ⇒ Mysql #initialize(host: nil, username: nil, password: nil, database: nil, port: nil, socket: nil, flags: nil, **opts) ⇒ Mysql

Returns a new instance of Mysql.

Overloads:

  • #initialize(uri, **opts) ⇒ Mysql

    Parameters:

  • #initialize(host, username, password, database, port, socket, flags, **opts) ⇒ Mysql

    Parameters:

    • host (String)

      hostname mysqld running

    • username (String)

      username to connect to mysqld

    • password (String)

      password to connect to mysqld

    • database (String)

      initial database name

    • port (String)

      port number (used if host is not 'localhost' or nil)

    • socket (String)

      socket filename (used if host is 'localhost' or nil)

    • flags (Integer)

      connection flag. Mysql::CLIENT_* ORed

    • opts (Hash)

      options

  • #initialize(host: nil, username: nil, password: nil, database: nil, port: nil, socket: nil, flags: nil, **opts) ⇒ Mysql

    Parameters:

    • host (String) (defaults to: nil)

      hostname mysqld running

    • username (String) (defaults to: nil)

      username to connect to mysqld

    • password (String) (defaults to: nil)

      password to connect to mysqld

    • database (String) (defaults to: nil)

      initial database name

    • port (String) (defaults to: nil)

      port number (used if host is not 'localhost' or nil)

    • socket (String) (defaults to: nil)

      socket filename (used if host is 'localhost' or nil)

    • flags (Integer) (defaults to: nil)

      connection flag. Mysql::CLIENT_* ORed

    • opts (Hash)

      options

    Options Hash (**opts):

    • :host (String)

      hostname mysqld running

    • :username (String)

      username to connect to mysqld

    • :password (String)

      password to connect to mysqld

    • :database (String)

      initial database name

    • :port (String)

      port number (used if host is not 'localhost' or nil)

    • :socket (String)

      socket filename (used if host is 'localhost' or nil)

    • :flags (Integer)

      connection flag. Mysql::CLIENT_* ORed

    • :charset (Mysql::Charset, String)

      character set

    • :connect_timeout (Numeric, nil)
    • :read_timeout (Numeric, nil)
    • :write_timeout (Numeric, nil)
    • :local_infile (Boolean)
    • :load_data_local_dir (String)
    • :ssl_mode (Integer)
    • :get_server_public_key (Boolean)

139
140
141
142
143
144
145
146
147
148
# File 'lib/mysql.rb', line 139

def initialize(*args, **opts)
  @fields = nil
  @protocol = nil
  @sqlstate = "00000"
  @host_info = nil
  @last_error = nil
  @result_exist = false
  @opts = DEFAULT_OPTS.dup
  parse_args(args, opts)
end

Instance Attribute Details

#connect_timeoutNumeric?

Returns:

  • (Numeric, nil)

56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
# File 'lib/mysql.rb', line 56

DEFAULT_OPTS = {
  host: nil,
  username: nil,
  password: nil,
  database: nil,
  port: nil,
  socket: nil,
  flags: 0,
  charset: nil,
  connect_timeout: nil,
  read_timeout: nil,
  write_timeout: nil,
  init_command: nil,
  local_infile: nil,
  load_data_local_dir: nil,
  ssl_mode: SSL_MODE_PREFERRED,
  get_server_public_key: false,
}.freeze

#databaseString?

Returns:

  • (String, nil)

56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
# File 'lib/mysql.rb', line 56

DEFAULT_OPTS = {
  host: nil,
  username: nil,
  password: nil,
  database: nil,
  port: nil,
  socket: nil,
  flags: 0,
  charset: nil,
  connect_timeout: nil,
  read_timeout: nil,
  write_timeout: nil,
  init_command: nil,
  local_infile: nil,
  load_data_local_dir: nil,
  ssl_mode: SSL_MODE_PREFERRED,
  get_server_public_key: false,
}.freeze

#flagsInteger?

Returns:

  • (Integer, nil)

56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
# File 'lib/mysql.rb', line 56

DEFAULT_OPTS = {
  host: nil,
  username: nil,
  password: nil,
  database: nil,
  port: nil,
  socket: nil,
  flags: 0,
  charset: nil,
  connect_timeout: nil,
  read_timeout: nil,
  write_timeout: nil,
  init_command: nil,
  local_infile: nil,
  load_data_local_dir: nil,
  ssl_mode: SSL_MODE_PREFERRED,
  get_server_public_key: false,
}.freeze

#get_server_public_keyBoolean

Returns:

  • (Boolean)

56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
# File 'lib/mysql.rb', line 56

DEFAULT_OPTS = {
  host: nil,
  username: nil,
  password: nil,
  database: nil,
  port: nil,
  socket: nil,
  flags: 0,
  charset: nil,
  connect_timeout: nil,
  read_timeout: nil,
  write_timeout: nil,
  init_command: nil,
  local_infile: nil,
  load_data_local_dir: nil,
  ssl_mode: SSL_MODE_PREFERRED,
  get_server_public_key: false,
}.freeze

#hostString?

Returns:

  • (String, nil)

56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
# File 'lib/mysql.rb', line 56

DEFAULT_OPTS = {
  host: nil,
  username: nil,
  password: nil,
  database: nil,
  port: nil,
  socket: nil,
  flags: 0,
  charset: nil,
  connect_timeout: nil,
  read_timeout: nil,
  write_timeout: nil,
  init_command: nil,
  local_infile: nil,
  load_data_local_dir: nil,
  ssl_mode: SSL_MODE_PREFERRED,
  get_server_public_key: false,
}.freeze

#init_commandString?

Returns:

  • (String, nil)

56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
# File 'lib/mysql.rb', line 56

DEFAULT_OPTS = {
  host: nil,
  username: nil,
  password: nil,
  database: nil,
  port: nil,
  socket: nil,
  flags: 0,
  charset: nil,
  connect_timeout: nil,
  read_timeout: nil,
  write_timeout: nil,
  init_command: nil,
  local_infile: nil,
  load_data_local_dir: nil,
  ssl_mode: SSL_MODE_PREFERRED,
  get_server_public_key: false,
}.freeze

#load_data_local_dirString?

Returns:

  • (String, nil)

56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
# File 'lib/mysql.rb', line 56

DEFAULT_OPTS = {
  host: nil,
  username: nil,
  password: nil,
  database: nil,
  port: nil,
  socket: nil,
  flags: 0,
  charset: nil,
  connect_timeout: nil,
  read_timeout: nil,
  write_timeout: nil,
  init_command: nil,
  local_infile: nil,
  load_data_local_dir: nil,
  ssl_mode: SSL_MODE_PREFERRED,
  get_server_public_key: false,
}.freeze

#local_infileBoolean

Returns:

  • (Boolean)

56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
# File 'lib/mysql.rb', line 56

DEFAULT_OPTS = {
  host: nil,
  username: nil,
  password: nil,
  database: nil,
  port: nil,
  socket: nil,
  flags: 0,
  charset: nil,
  connect_timeout: nil,
  read_timeout: nil,
  write_timeout: nil,
  init_command: nil,
  local_infile: nil,
  load_data_local_dir: nil,
  ssl_mode: SSL_MODE_PREFERRED,
  get_server_public_key: false,
}.freeze

#passwordString?

Returns:

  • (String, nil)

56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
# File 'lib/mysql.rb', line 56

DEFAULT_OPTS = {
  host: nil,
  username: nil,
  password: nil,
  database: nil,
  port: nil,
  socket: nil,
  flags: 0,
  charset: nil,
  connect_timeout: nil,
  read_timeout: nil,
  write_timeout: nil,
  init_command: nil,
  local_infile: nil,
  load_data_local_dir: nil,
  ssl_mode: SSL_MODE_PREFERRED,
  get_server_public_key: false,
}.freeze

#portInteger, ...

Returns:

  • (Integer, String, nil)

56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
# File 'lib/mysql.rb', line 56

DEFAULT_OPTS = {
  host: nil,
  username: nil,
  password: nil,
  database: nil,
  port: nil,
  socket: nil,
  flags: 0,
  charset: nil,
  connect_timeout: nil,
  read_timeout: nil,
  write_timeout: nil,
  init_command: nil,
  local_infile: nil,
  load_data_local_dir: nil,
  ssl_mode: SSL_MODE_PREFERRED,
  get_server_public_key: false,
}.freeze

#protocolObject (readonly)


76
77
78
# File 'lib/mysql.rb', line 76

def protocol
  @protocol
end

#read_timeoutNumeric?

Returns:

  • (Numeric, nil)

56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
# File 'lib/mysql.rb', line 56

DEFAULT_OPTS = {
  host: nil,
  username: nil,
  password: nil,
  database: nil,
  port: nil,
  socket: nil,
  flags: 0,
  charset: nil,
  connect_timeout: nil,
  read_timeout: nil,
  write_timeout: nil,
  init_command: nil,
  local_infile: nil,
  load_data_local_dir: nil,
  ssl_mode: SSL_MODE_PREFERRED,
  get_server_public_key: false,
}.freeze

#socketString?

Returns socket filename.

Returns:

  • (String, nil)

    socket filename


56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
# File 'lib/mysql.rb', line 56

DEFAULT_OPTS = {
  host: nil,
  username: nil,
  password: nil,
  database: nil,
  port: nil,
  socket: nil,
  flags: 0,
  charset: nil,
  connect_timeout: nil,
  read_timeout: nil,
  write_timeout: nil,
  init_command: nil,
  local_infile: nil,
  load_data_local_dir: nil,
  ssl_mode: SSL_MODE_PREFERRED,
  get_server_public_key: false,
}.freeze

#ssl_modeString, Integer

Returns 1 or “disabled” / 2 or “preferred” / 3 or “required”.

Returns:

  • (String, Integer)

    1 or "disabled" / 2 or "preferred" / 3 or "required"


56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
# File 'lib/mysql.rb', line 56

DEFAULT_OPTS = {
  host: nil,
  username: nil,
  password: nil,
  database: nil,
  port: nil,
  socket: nil,
  flags: 0,
  charset: nil,
  connect_timeout: nil,
  read_timeout: nil,
  write_timeout: nil,
  init_command: nil,
  local_infile: nil,
  load_data_local_dir: nil,
  ssl_mode: SSL_MODE_PREFERRED,
  get_server_public_key: false,
}.freeze

#usernameString?

Returns:

  • (String, nil)

56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
# File 'lib/mysql.rb', line 56

DEFAULT_OPTS = {
  host: nil,
  username: nil,
  password: nil,
  database: nil,
  port: nil,
  socket: nil,
  flags: 0,
  charset: nil,
  connect_timeout: nil,
  read_timeout: nil,
  write_timeout: nil,
  init_command: nil,
  local_infile: nil,
  load_data_local_dir: nil,
  ssl_mode: SSL_MODE_PREFERRED,
  get_server_public_key: false,
}.freeze

#write_timeoutNumeric?

Returns:

  • (Numeric, nil)

56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
# File 'lib/mysql.rb', line 56

DEFAULT_OPTS = {
  host: nil,
  username: nil,
  password: nil,
  database: nil,
  port: nil,
  socket: nil,
  flags: 0,
  charset: nil,
  connect_timeout: nil,
  read_timeout: nil,
  write_timeout: nil,
  init_command: nil,
  local_infile: nil,
  load_data_local_dir: nil,
  ssl_mode: SSL_MODE_PREFERRED,
  get_server_public_key: false,
}.freeze

Class Method Details

.connect(*args, **opts) ⇒ Mysql

Make Mysql object and connect to mysqld. parameter is same as arguments for #initialize.

Returns:


82
83
84
# File 'lib/mysql.rb', line 82

def connect(*args, **opts)
  self.new(*args, **opts).connect
end

.escape_string(str) ⇒ String

Escape special character in string.

Parameters:

  • str (String)

Returns:

  • (String)

89
90
91
92
93
94
95
96
97
98
99
# File 'lib/mysql.rb', line 89

def escape_string(str)
  str.gsub(/[\0\n\r\\\'\"\x1a]/) do |s|
    case s
    when "\0" then "\\0"
    when "\n" then "\\n"
    when "\r" then "\\r"
    when "\x1a" then "\\Z"
    else "\\#{s}"
    end
  end
end

.quoteString

Escape special character in string.

Parameters:

  • str (String)

Returns:

  • (String)

100
101
102
103
104
105
106
107
108
109
110
# File 'lib/mysql.rb', line 100

def escape_string(str)
  str.gsub(/[\0\n\r\\\'\"\x1a]/) do |s|
    case s
    when "\0" then "\\0"
    when "\n" then "\\n"
    when "\r" then "\\r"
    when "\x1a" then "\\Z"
    else "\\#{s}"
    end
  end
end

Instance Method Details

#affected_rowsInteger

Returns number of affected records by insert/update/delete.

Returns:

  • (Integer)

    number of affected records by insert/update/delete.


306
307
308
# File 'lib/mysql.rb', line 306

def affected_rows
  @protocol ? @protocol.affected_rows : 0
end

#autocommit(flag) ⇒ Mysql

Set autocommit mode

Parameters:

  • flag (Boolean)

Returns:


486
487
488
489
# File 'lib/mysql.rb', line 486

def autocommit(flag)
  query "set autocommit=#{flag ? 1 : 0}"
  self
end

#character_set_nameString

Returns charset name.

Returns:

  • (String)

    charset name


259
260
261
# File 'lib/mysql.rb', line 259

def character_set_name
  @protocol.charset.name
end

#charsetMysql::Charset

Returns character set of MySQL connection.

Returns:


242
243
244
# File 'lib/mysql.rb', line 242

def charset
  @opts[:charset]
end

#charset=(cs) ⇒ Object

Set charset of MySQL connection.

Parameters:


248
249
250
251
252
253
254
255
256
# File 'lib/mysql.rb', line 248

def charset=(cs)
  charset = cs.is_a?(Charset) ? cs : Charset.by_name(cs)
  if @protocol
    @protocol.charset = charset
    query "SET NAMES #{charset.name}"
  end
  @opts[:charset] = charset
  cs
end

#closeMysql

Disconnect from mysql.

Returns:


214
215
216
217
218
219
220
# File 'lib/mysql.rb', line 214

def close
  if @protocol
    @protocol.quit_command
    @protocol = nil
  end
  return self
end

#close!Mysql

Disconnect from mysql without QUIT packet.

Returns:


224
225
226
227
228
229
230
# File 'lib/mysql.rb', line 224

def close!
  if @protocol
    @protocol.close
    @protocol = nil
  end
  return self
end

#commitMysql

Commit transaction

Returns:


471
472
473
474
# File 'lib/mysql.rb', line 471

def commit
  query 'commit'
  self
end

#connect(*args, **opts) ⇒ Mysql

Connect to mysqld. parameter is same as arguments for #initialize.

Returns:


153
154
155
156
157
158
159
160
161
162
163
164
# File 'lib/mysql.rb', line 153

def connect(*args, **opts)
  parse_args(args, opts)
  if @opts[:flags] & CLIENT_COMPRESS != 0
    warn 'unsupported flag: CLIENT_COMPRESS' if $VERBOSE
    @opts[:flags] &= ~CLIENT_COMPRESS
  end
  @protocol = Protocol.new(@opts)
  @protocol.authenticate
  @host_info = (@opts[:host].nil? || @opts[:host] == "localhost") ? 'Localhost via UNIX socket' : "#{@opts[:host]} via TCP/IP"
  query @opts[:init_command] if @opts[:init_command]
  return self
end

#errnoInteger

Returns last error number.

Returns:

  • (Integer)

    last error number


264
265
266
# File 'lib/mysql.rb', line 264

def errno
  @last_error ? @last_error.errno : 0
end

#errorString

Returns last error message.

Returns:

  • (String)

    last error message


269
270
271
# File 'lib/mysql.rb', line 269

def error
  @last_error && @last_error.error
end

#escape_string(str) ⇒ Object Also known as: quote

Escape special character in MySQL.

return [String]

Parameters:

  • str (String)

236
237
238
# File 'lib/mysql.rb', line 236

def escape_string(str)
  self.class.escape_string str
end

#field_countInteger

Returns number of columns for last query.

Returns:

  • (Integer)

    number of columns for last query


279
280
281
# File 'lib/mysql.rb', line 279

def field_count
  @fields.size
end

#host_infoString

Returns connection type.

Returns:

  • (String)

    connection type


284
285
286
# File 'lib/mysql.rb', line 284

def host_info
  @host_info
end

#infoString

Returns information for last query.

Returns:

  • (String)

    information for last query


301
302
303
# File 'lib/mysql.rb', line 301

def info
  @protocol && @protocol.message
end

#insert_idInteger

Returns latest auto_increment value.

Returns:

  • (Integer)

    latest auto_increment value


311
312
313
# File 'lib/mysql.rb', line 311

def insert_id
  @protocol ? @protocol.insert_id : 0
end

#kill(pid) ⇒ Mysql

Kill query.

Parameters:

  • pid (Integer)

    thread id

Returns:


323
324
325
326
327
# File 'lib/mysql.rb', line 323

def kill(pid)
  check_connection
  @protocol.kill_command pid
  self
end

#more_resultsBoolean Also known as: more_results?

Returns true if multiple queries are specified and unexecuted queries exists.

Returns:

  • (Boolean)

    true if multiple queries are specified and unexecuted queries exists.


391
392
393
# File 'lib/mysql.rb', line 391

def more_results
  @protocol.server_status & SERVER_MORE_RESULTS_EXISTS != 0
end

#next_resultBoolean

execute next query if multiple queries are specified.

Returns:

  • (Boolean)

    true if next query exists.


398
399
400
401
402
403
404
405
406
407
408
# File 'lib/mysql.rb', line 398

def next_result
  return false unless more_results
  check_connection
  @fields = nil
  nfields = @protocol.get_result
  if nfields
    @fields = @protocol.retr_fields nfields
    @result_exist = true
  end
  return true
end

#parse_args(args, opts) ⇒ Object


166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
# File 'lib/mysql.rb', line 166

def parse_args(args, opts)
  case args[0]
  when URI
    uri = args[0]
  when /\Amysql:\/\//
    uri = URI.parse(args[0])
  when String
    @opts[:host], user, passwd, dbname, port, socket, flags = *args
    @opts[:username] = user if user
    @opts[:password] = passwd if passwd
    @opts[:database] = dbname if dbname
    @opts[:port] = port if port
    @opts[:socket] = socket if socket
    @opts[:flags] = flags if flags
  when Hash
    # skip
  when nil
    # skip
  end
  if uri
    host = uri.hostname.to_s
    host = URI.decode_www_form_component(host)
    if host.start_with?('/')
      @opts[:socket] = host
      host = ''
    end
    @opts[:host] = host
    @opts[:username] = URI.decode_www_form_component(uri.user.to_s)
    @opts[:password] = URI.decode_www_form_component(uri.password.to_s)
    @opts[:database] = uri.path.sub(/\A\/+/, '')
    @opts[:port] = uri.port
    opts = URI.decode_www_form(uri.query).to_h.transform_keys(&:intern).merge(opts) if uri.query
    opts[:flags] = opts[:flags].to_i if opts[:flags]
  end
  if args.last.kind_of? Hash
    opts = opts.merge(args.last)
  end
  @opts.update(opts)
end

#pingMysql

Check whether the connection is available.

Returns:


428
429
430
431
432
# File 'lib/mysql.rb', line 428

def ping
  check_connection
  @protocol.ping_command
  self
end

#prepare(str) ⇒ Mysql::Stmt

Parse prepared-statement.

Parameters:

  • str (String)

    query string

Returns:


413
414
415
416
417
# File 'lib/mysql.rb', line 413

def prepare(str)
  st = Stmt.new @protocol
  st.prepare str
  st
end

#query(str) ⇒ Mysql::Result? #query(str) {|Mysql::Result| ... } ⇒ self

Execute query string.

Examples:

my.query("select 1,NULL,'abc'").fetch  # => [1, nil, "abc"]
my.query("select 1,NULL,'abc'"){|res| res.fetch}

Overloads:

  • #query(str) ⇒ Mysql::Result?

    Parameters:

    • str (String)

      Query.

    Returns:

    • (Mysql::Result)
    • (nil)

      if the query does not return result set.

  • #query(str) {|Mysql::Result| ... } ⇒ self

    Parameters:

    • str (String)

      Query.

    Yields:

    Returns:

    • (self)

341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
# File 'lib/mysql.rb', line 341

def query(str, &block)
  check_connection
  @fields = nil
  begin
    nfields = @protocol.query_command str
    if nfields
      @fields = @protocol.retr_fields nfields
      @result_exist = true
    end
    if block
      while true
        block.call store_result if @fields
        break unless next_result
      end
      return self
    end
    return @fields ? store_result : nil
  rescue ServerError => e
    @last_error = e
    @sqlstate = e.sqlstate
    raise
  end
end

#refresh(op) ⇒ Mysql

Flush tables or caches.

Parameters:

  • op (Integer)

    operation. Use Mysql::REFRESH_* value.

Returns:


437
438
439
440
441
# File 'lib/mysql.rb', line 437

def refresh(op)
  check_connection
  @protocol.refresh_command op
  self
end

#reloadMysql

Reload grant tables.

Returns:


445
446
447
# File 'lib/mysql.rb', line 445

def reload
  refresh Mysql::REFRESH_GRANT
end

#rollbackMysql

Rollback transaction

Returns:


478
479
480
481
# File 'lib/mysql.rb', line 478

def rollback
  query 'rollback'
  self
end

#select_db(db) ⇒ Mysql

Select default database

Returns:


451
452
453
454
# File 'lib/mysql.rb', line 451

def select_db(db)
  query "use #{db}"
  self
end

#server_infoString

Returns server version.

Returns:

  • (String)

    server version


289
290
291
292
# File 'lib/mysql.rb', line 289

def server_info
  check_connection
  @protocol.server_info
end

#server_versionInteger

Returns server version.

Returns:

  • (Integer)

    server version


295
296
297
298
# File 'lib/mysql.rb', line 295

def server_version
  check_connection
  @protocol.server_version
end

#set_server_option(opt) ⇒ Mysql

Set server option.

Parameters:

Returns:


384
385
386
387
388
# File 'lib/mysql.rb', line 384

def set_server_option(opt)
  check_connection
  @protocol.set_option_command opt
  self
end

#shutdown(level = 0) ⇒ Mysql

shutdown server.

Returns:


458
459
460
461
462
# File 'lib/mysql.rb', line 458

def shutdown(level=0)
  check_connection
  @protocol.shutdown_command level
  self
end

#sqlstateString

Returns sqlstate for last error.

Returns:

  • (String)

    sqlstate for last error


274
275
276
# File 'lib/mysql.rb', line 274

def sqlstate
  @last_error ? @last_error.sqlstate : "00000"
end

#statString

Returns statistics message.

Returns:

  • (String)

    statistics message


465
466
467
# File 'lib/mysql.rb', line 465

def stat
  @protocol ? @protocol.statistics_command : 'MySQL server has gone away'
end

#stmtMysql::Stmt

Make empty prepared-statement object.

Returns:


422
423
424
# File 'lib/mysql.rb', line 422

def stmt
  Stmt.new @protocol
end

#store_resultMysql::Result

Get all data for last query.

Returns:

Raises:


367
368
369
370
371
372
373
# File 'lib/mysql.rb', line 367

def store_result
  check_connection
  raise ClientError, 'invalid usage' unless @result_exist
  res = Result.new @fields, @protocol
  @result_exist = false
  res
end

#thread_idInteger

Returns Thread ID.

Returns:

  • (Integer)

    Thread ID


376
377
378
379
# File 'lib/mysql.rb', line 376

def thread_id
  check_connection
  @protocol.thread_id
end

#warning_countInteger

Returns number of warnings for previous query.

Returns:

  • (Integer)

    number of warnings for previous query


316
317
318
# File 'lib/mysql.rb', line 316

def warning_count
  @protocol ? @protocol.warning_count : 0
end