class Mysql

Copyright (C) 2003-2008 TOMITA Masahiro tommy@tmtm.org

Copyright (C) 2003-2010 TOMITA Masahiro tommy@tmtm.org

Constants

CLIENT_COMPRESS
CLIENT_CONNECT_WITH_DB
CLIENT_FOUND_ROWS
CLIENT_IGNORE_SIGPIPE
CLIENT_IGNORE_SPACE
CLIENT_INTERACTIVE
CLIENT_LOCAL_FILES
CLIENT_LONG_FLAG
CLIENT_LONG_PASSWORD

Client flag

CLIENT_MULTI_RESULTS
CLIENT_MULTI_STATEMENTS
CLIENT_NO_SCHEMA
CLIENT_ODBC
CLIENT_PROTOCOL_41
CLIENT_RESERVED
CLIENT_SECURE_CONNECTION
CLIENT_SSL
CLIENT_TRANSACTIONS
COM_BINLOG_DUMP
COM_CHANGE_USER
COM_CONNECT
COM_CONNECT_OUT
COM_CREATE_DB
COM_DEBUG
COM_DELAYED_INSERT
COM_DROP_DB
COM_FIELD_LIST
COM_INIT_DB
COM_PING
COM_PROCESS_INFO
COM_PROCESS_KILL
COM_QUERY
COM_QUIT
COM_REFRESH
COM_REGISTER_SLAVE
COM_SET_OPTION
COM_SHUTDOWN
COM_SLEEP

Command

COM_STATISTICS
COM_STMT_CLOSE
COM_STMT_EXECUTE
COM_STMT_FETCH
COM_STMT_PREPARE
COM_STMT_RESET
COM_STMT_SEND_LONG_DATA
COM_TABLE_DUMP
COM_TIME
INIT_COMMAND
MYSQL_TCP_PORT
MYSQL_UNIX_PORT
OPTION_MULTI_STATEMENTS_OFF
OPTION_MULTI_STATEMENTS_ON

Server Option

OPT_COMPRESS
OPT_CONNECT_TIMEOUT

Connection Option

OPT_GUESS_CONNECTION
OPT_LOCAL_INFILE
OPT_NAMED_PIPE
OPT_PROTOCOL
OPT_READ_TIMEOUT
OPT_RECONNECT
OPT_SSL_VERIFY_SERVER_CERT
OPT_USE_EMBEDDED_CONNECTION
OPT_USE_REMOTE_CONNECTION
OPT_USE_RESULT
OPT_WRITE_TIMEOUT
READ_DEFAULT_FILE
READ_DEFAULT_GROUP
REFRESH_FAST
REFRESH_GRANT

Refresh parameter

REFRESH_HOSTS
REFRESH_LOG
REFRESH_MASTER
REFRESH_READ_LOCK
REFRESH_SLAVE
REFRESH_STATUS
REFRESH_TABLES
REFRESH_THREADS
REPORT_DATA_TRUNCATION
SECURE_AUTH
SERVER_MORE_RESULTS_EXISTS
SERVER_QUERY_NO_GOOD_INDEX_USED
SERVER_QUERY_NO_INDEX_USED
SERVER_STATUS_AUTOCOMMIT
SERVER_STATUS_CURSOR_EXISTS
SERVER_STATUS_DB_DROPPED
SERVER_STATUS_IN_TRANS

Server Status

SERVER_STATUS_LAST_ROW_SENT
SERVER_STATUS_NO_BACKSLASH_ESCAPES
SET_CHARSET_DIR
SET_CHARSET_NAME
SET_CLIENT_IP
SHARED_MEMORY_BASE_NAME
VERSION

Attributes

charset[R]

@return [Mysql::Charset] character set of MySQL connection

protocol[R]

@private

query_with_result[RW]

@return [Boolean] if true, {#query} return {Mysql::Result}.

Public Class Methods

client_info() click to toggle source

@return [String] client version. This value is dummy for MySQL/Ruby compatibility.

# File lib/vendor/mysql.rb, line 62
def client_info
  "5.0.0"
end
Also aliased as: get_client_info
client_version() click to toggle source

@return [Integer] client version. This value is dummy for MySQL/Ruby compatibility.

# File lib/vendor/mysql.rb, line 68
def client_version
  50000
end
Also aliased as: get_client_version
connect(*args)
Alias for: new
escape_string(str) click to toggle source

Escape special character in string. @param [String] str @return [String]

# File lib/vendor/mysql.rb, line 48
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
Also aliased as: quote
get_client_info()
Alias for: client_info
get_client_version()
Alias for: client_version
init() click to toggle source

Make Mysql object without connecting. @return [Mysql]

# File lib/vendor/mysql.rb, line 28
def init
  my = self.allocate
  my.instance_eval{initialize}
  my
end
new(*args) click to toggle source

Make Mysql object and connect to mysqld. @param args same as arguments for {#connect}. @return [Mysql]

# File lib/vendor/mysql.rb, line 37
def new(*args)
  my = self.init
  my.connect(*args)
end
Also aliased as: real_connect, connect
new() click to toggle source
# File lib/vendor/mysql.rb, line 74
def initialize
  @fields = nil
  @protocol = nil
  @charset = nil
  @connect_timeout = nil
  @read_timeout = nil
  @write_timeout = nil
  @init_command = nil
  @sqlstate = "00000"
  @query_with_result = true
  @host_info = nil
  @last_error = nil
  @result_exist = false
  @local_infile = nil
end
quote(str)
Alias for: escape_string
real_connect(*args)
Alias for: new

Public Instance Methods

affected_rows() click to toggle source

@return [Integer] number of affected records by insert/update/delete.

# File lib/vendor/mysql.rb, line 271
def affected_rows
  @protocol ? @protocol.affected_rows : 0
end
autocommit(flag) click to toggle source

Set autocommit mode @param [Boolean] flag @return [Mysql] self

# File lib/vendor/mysql.rb, line 499
def autocommit(flag)
  query "set autocommit=#{flag ? 1 : 0}"
  self
end
character_set_name() click to toggle source

@return [String] charset name

# File lib/vendor/mysql.rb, line 215
def character_set_name
  @charset.name
end
charset=(cs) click to toggle source

Set charset of MySQL connection. @param [String / Mysql::Charset] cs

# File lib/vendor/mysql.rb, line 204
def charset=(cs)
  charset = cs.is_a?(Charset) ? cs : Charset.by_name(cs)
  if @protocol
    @protocol.charset = charset
    query "SET NAMES #{charset.name}"
  end
  @charset = charset
  cs
end
client_info() click to toggle source

@return [String] client version

# File lib/vendor/mysql.rb, line 191
def client_info
  self.class.client_info
end
Also aliased as: get_client_info
client_version() click to toggle source

@return [Integer] client version

# File lib/vendor/mysql.rb, line 197
def client_version
  self.class.client_version
end
Also aliased as: get_client_version
close() click to toggle source

Disconnect from mysql. @return [Mysql] self

# File lib/vendor/mysql.rb, line 115
def close
  if @protocol
    @protocol.quit_command
    @protocol = nil
  end
  return self
end
close!() click to toggle source

Disconnect from mysql without QUIT packet. @return [Mysql] self

# File lib/vendor/mysql.rb, line 125
def close!
  if @protocol
    @protocol.close
    @protocol = nil
  end
  return self
end
commit() click to toggle source

Commit transaction @return [Mysql] self

# File lib/vendor/mysql.rb, line 484
def commit
  query 'commit'
  self
end
connect(host=nil, user=nil, passwd=nil, db=nil, port=nil, socket=nil, flag=0) click to toggle source

Connect to mysqld. @param [String / nil] host hostname mysqld running @param [String / nil] user username to connect to mysqld @param [String / nil] passwd password to connect to mysqld @param [String / nil] db initial database name @param [Integer / nil] port port number (used if host is not 'localhost' or nil) @param [String / nil] socket socket file name (used if host is 'localhost' or nil) @param [Integer / nil] flag connection flag. Mysql::CLIENT_* ORed @return self

# File lib/vendor/mysql.rb, line 99
def connect(host=nil, user=nil, passwd=nil, db=nil, port=nil, socket=nil, flag=0)
  if flag & CLIENT_COMPRESS != 0
    warn 'unsupported flag: CLIENT_COMPRESS' if $VERBOSE
    flag &= ~CLIENT_COMPRESS
  end
  @protocol = Protocol.new host, port, socket, @connect_timeout, @read_timeout, @write_timeout
  @protocol.authenticate user, passwd, db, (@local_infile ? CLIENT_LOCAL_FILES : 0) | flag, @charset
  @charset ||= @protocol.charset
  @host_info = (host.nil? || host == "localhost") ? 'Localhost via UNIX socket' : "#{host} via TCP/IP"
  query @init_command if @init_command
  return self
end
Also aliased as: real_connect
errno() click to toggle source

@return [Integer] last error number

# File lib/vendor/mysql.rb, line 220
def errno
  @last_error ? @last_error.errno : 0
end
error() click to toggle source

@return [String] last error message

# File lib/vendor/mysql.rb, line 225
def error
  @last_error && @last_error.error
end
escape_string(str) click to toggle source

Escape special character in MySQL.

In Ruby 1.8, this is not safe for multibyte charset such as 'SJIS'. You should use place-holder in prepared-statement. @param [String] str return [String]

# File lib/vendor/mysql.rb, line 182
def escape_string(str)
  if not defined? Encoding and @charset.unsafe
    raise ClientError, 'Mysql#escape_string is called for unsafe multibyte charset'
  end
  self.class.escape_string str
end
Also aliased as: quote
field_count() click to toggle source

@return [Integer] number of columns for last query

# File lib/vendor/mysql.rb, line 235
def field_count
  @fields.size
end
get_client_info()
Alias for: client_info
get_client_version()
Alias for: client_version
get_host_info()
Alias for: host_info
get_proto_info()
Alias for: proto_info
get_server_info()
Alias for: server_info
get_server_version()
Alias for: server_version
host_info() click to toggle source

@return [String] connection type

# File lib/vendor/mysql.rb, line 240
def host_info
  @host_info
end
Also aliased as: get_host_info
info() click to toggle source

@return [String] information for last query

# File lib/vendor/mysql.rb, line 266
def info
  @protocol && @protocol.message
end
insert_id() click to toggle source

@return [Integer] latest auto_increment value

# File lib/vendor/mysql.rb, line 276
def insert_id
  @protocol ? @protocol.insert_id : 0
end
kill(pid) click to toggle source

Kill query. @param [Integer] pid thread id @return [Mysql] self

# File lib/vendor/mysql.rb, line 288
def kill(pid)
  check_connection
  @protocol.kill_command pid
  self
end
list_dbs(db=nil) click to toggle source

database list. @param [String] db database name that may contain wild card. @return [Array<String>] database list

# File lib/vendor/mysql.rb, line 297
def list_dbs(db=nil)
  db &&= db.gsub(/[\\\']/){"\\#{$&}"}
  query(db ? "show databases like '#{db}'" : "show databases").map(&:first)
end
list_fields(table, field=nil) click to toggle source

Returns Mysql::Result object that is empty. Use fetch_fields to get list of fields. @param [String] table table name. @param [String] field field name that may contain wild card. @return [Mysql::Result]

# File lib/vendor/mysql.rb, line 411
def list_fields(table, field=nil)
  check_connection
  begin
    fields = @protocol.field_list_command table, field
    return Result.new fields
  rescue ServerError => e
    @last_error = e
    @sqlstate = e.sqlstate
    raise
  end
end
list_processes() click to toggle source

@return [Mysql::Result] containing process list

# File lib/vendor/mysql.rb, line 424
def list_processes
  check_connection
  @fields = @protocol.process_info_command
  @result_exist = true
  store_result
end
list_tables(table=nil) click to toggle source

@note for Ruby 1.8: This is not multi-byte safe. Don't use for multi-byte charset such as cp932. @param [String] table database name that may contain wild card. @return [Array<String>] list of table name.

# File lib/vendor/mysql.rb, line 434
def list_tables(table=nil)
  q = table ? "show tables like '#{quote table}'" : "show tables"
  query(q).map(&:first)
end
more_results() click to toggle source

@return [Boolean] true if multiple queries are specified and unexecuted queries exists.

# File lib/vendor/mysql.rb, line 371
def more_results
  @protocol.server_status & SERVER_MORE_RESULTS_EXISTS != 0
end
Also aliased as: more_results?
more_results?()
Alias for: more_results
next_result() click to toggle source

execute next query if multiple queries are specified. @return [Boolean] true if next query exists.

# File lib/vendor/mysql.rb, line 378
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
options(opt, value=nil) click to toggle source

Set option for connection.

Available options:

Mysql::INIT_COMMAND, Mysql::OPT_CONNECT_TIMEOUT, Mysql::OPT_READ_TIMEOUT,
Mysql::OPT_WRITE_TIMEOUT, Mysql::SET_CHARSET_NAME

@param [Integer] opt option @param [Integer] value option value that is depend on opt @return [Mysql] self

# File lib/vendor/mysql.rb, line 141
  def options(opt, value=nil)
    case opt
    when Mysql::INIT_COMMAND
      @init_command = value.to_s
#    when Mysql::OPT_COMPRESS
    when Mysql::OPT_CONNECT_TIMEOUT
      @connect_timeout = value
#    when Mysql::GUESS_CONNECTION
    when Mysql::OPT_LOCAL_INFILE
      @local_infile = value
#    when Mysql::OPT_NAMED_PIPE
#    when Mysql::OPT_PROTOCOL
    when Mysql::OPT_READ_TIMEOUT
      @read_timeout = value.to_i
#    when Mysql::OPT_RECONNECT
#    when Mysql::SET_CLIENT_IP
#    when Mysql::OPT_SSL_VERIFY_SERVER_CERT
#    when Mysql::OPT_USE_EMBEDDED_CONNECTION
#    when Mysql::OPT_USE_REMOTE_CONNECTION
    when Mysql::OPT_WRITE_TIMEOUT
      @write_timeout = value.to_i
#    when Mysql::READ_DEFAULT_FILE
#    when Mysql::READ_DEFAULT_GROUP
#    when Mysql::REPORT_DATA_TRUNCATION
#    when Mysql::SECURE_AUTH
#    when Mysql::SET_CHARSET_DIR
    when Mysql::SET_CHARSET_NAME
      @charset = Charset.by_name value.to_s
#    when Mysql::SHARED_MEMORY_BASE_NAME
    else
      warn "option not implemented: #{opt}" if $VERBOSE
    end
    self
  end
ping() click to toggle source

Check whether the connection is available. @return [Mysql] self

# File lib/vendor/mysql.rb, line 441
def ping
  check_connection
  @protocol.ping_command
  self
end
prepare(str) click to toggle source

Parse prepared-statement. @param [String] str query string @return [Mysql::Stmt] Prepared-statement object

# File lib/vendor/mysql.rb, line 393
def prepare(str)
  st = Stmt.new @protocol, @charset
  st.prepare str
  st
end
proto_info() click to toggle source

@return [Integer] protocol version

# File lib/vendor/mysql.rb, line 246
def proto_info
  Mysql::Protocol::VERSION
end
Also aliased as: get_proto_info
query(str, &block) click to toggle source

Execute query string. @param [String] str Query. @yield [Mysql::Result] evaluated per query. @return [Mysql::Result] If {#query_with_result} is true and result set exist. @return [nil] If {#query_with_result} is true and the query does not return result set. @return [Mysql] If {#query_with_result} is false or block is specified @example

my.query("select 1,NULL,'abc'").fetch  # => [1, nil, "abc"]
# File lib/vendor/mysql.rb, line 310
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
    if @query_with_result
      return @fields ? store_result : nil
    else
      return self
    end
  rescue ServerError => e
    @last_error = e
    @sqlstate = e.sqlstate
    raise
  end
end
Also aliased as: real_query
quote(str)
Alias for: escape_string
real_connect(host=nil, user=nil, passwd=nil, db=nil, port=nil, socket=nil, flag=0)
Alias for: connect
real_query(str, &block)
Alias for: query
refresh(op) click to toggle source

Flush tables or caches. @param [Integer] op operation. Use Mysql::REFRESH_* value. @return [Mysql] self

# File lib/vendor/mysql.rb, line 450
def refresh(op)
  check_connection
  @protocol.refresh_command op
  self
end
reload() click to toggle source

Reload grant tables. @return [Mysql] self

# File lib/vendor/mysql.rb, line 458
def reload
  refresh Mysql::REFRESH_GRANT
end
rollback() click to toggle source

Rollback transaction @return [Mysql] self

# File lib/vendor/mysql.rb, line 491
def rollback
  query 'rollback'
  self
end
select_db(db) click to toggle source

Select default database @return [Mysql] self

# File lib/vendor/mysql.rb, line 464
def select_db(db)
  query "use #{db}"
  self
end
server_info() click to toggle source

@return [String] server version

# File lib/vendor/mysql.rb, line 252
def server_info
  check_connection
  @protocol.server_info
end
Also aliased as: get_server_info
server_version() click to toggle source

@return [Integer] server version

# File lib/vendor/mysql.rb, line 259
def server_version
  check_connection
  @protocol.server_version
end
Also aliased as: get_server_version
set_server_option(opt) click to toggle source

Set server option. @param [Integer] opt {Mysql::OPTION_MULTI_STATEMENTS_ON} or {Mysql::OPTION_MULTI_STATEMENTS_OFF} @return [Mysql] self

# File lib/vendor/mysql.rb, line 364
def set_server_option(opt)
  check_connection
  @protocol.set_option_command opt
  self
end
shutdown(level=0) click to toggle source

shutdown server. @return [Mysql] self

# File lib/vendor/mysql.rb, line 471
def shutdown(level=0)
  check_connection
  @protocol.shutdown_command level
  self
end
sqlstate() click to toggle source

@return [String] sqlstate for last error

# File lib/vendor/mysql.rb, line 230
def sqlstate
  @last_error ? @last_error.sqlstate : "00000"
end
stat() click to toggle source

@return [String] statistics message

# File lib/vendor/mysql.rb, line 478
def stat
  @protocol ? @protocol.statistics_command : 'MySQL server has gone away'
end
stmt_init() click to toggle source

@private Make empty prepared-statement object. @return [Mysql::Stmt] If block is not specified.

# File lib/vendor/mysql.rb, line 402
def stmt_init
  Stmt.new @protocol, @charset
end
store_result() click to toggle source

Get all data for last query if query_with_result is false. @return [Mysql::Result]

# File lib/vendor/mysql.rb, line 341
def store_result
  check_connection
  raise ClientError, 'invalid usage' unless @result_exist
  res = Result.new @fields, @protocol
  @result_exist = false
  res
end
thread_id() click to toggle source

@return [Integer] Thread ID

# File lib/vendor/mysql.rb, line 350
def thread_id
  check_connection
  @protocol.thread_id
end
use_result() click to toggle source

Use result of query. The result data is retrieved when you use Mysql::Result#fetch. @return [Mysql::Result]

# File lib/vendor/mysql.rb, line 357
def use_result
  store_result
end
warning_count() click to toggle source

@return [Integer] number of warnings for previous query

# File lib/vendor/mysql.rb, line 281
def warning_count
  @protocol ? @protocol.warning_count : 0
end

Private Instance Methods

check_connection() click to toggle source
# File lib/vendor/mysql.rb, line 506
def check_connection
  raise ClientError::ServerGoneError, 'MySQL server has gone away' unless @protocol
end