Class: Sequel::MySQL::Database

Inherits:
Database show all
Includes:
DatabaseMethods, PreparedStatements::DatabaseMethods
Defined in:
lib/sequel/adapters/mysql.rb

Overview

Database class for MySQL databases used with Sequel.

Constant Summary collapse

AFFECTED_ROWS_RE =

Regular expression used for getting accurate number of rows matched by an update statement.

/Rows matched:\s+(\d+)\s+Changed:\s+\d+\s+Warnings:\s+\d+/.freeze
DatasetClass =
self

Constants included from PreparedStatements::DatabaseMethods

PreparedStatements::DatabaseMethods::MYSQL_DATABASE_DISCONNECT_ERRORS

Constants included from DatabaseMethods

Sequel::MySQL::DatabaseMethods::AUTO_INCREMENT, Sequel::MySQL::DatabaseMethods::CAST_TYPES, Sequel::MySQL::DatabaseMethods::COLUMN_DEFINITION_ORDER, Sequel::MySQL::DatabaseMethods::MYSQL_TIMESTAMP_RE, Sequel::MySQL::DatabaseMethods::PRIMARY

Constants inherited from Database

Database::ADAPTERS, Database::AUTOINCREMENT, Database::COLUMN_DEFINITION_ORDER, Database::COLUMN_SCHEMA_DATETIME_TYPES, Database::COLUMN_SCHEMA_STRING_TYPES, Database::COMBINABLE_ALTER_TABLE_OPS, Database::COMMA_SEPARATOR, Database::CURRENT_TIMESTAMP_RE, Database::DEFAULT_JOIN_TABLE_COLUMN_OPTIONS, Database::DEFAULT_STRING_COLUMN_SIZE, Database::EXTENSIONS, Database::NOT_NULL, Database::NULL, Database::PRIMARY_KEY, Database::SQL_BEGIN, Database::SQL_COMMIT, Database::SQL_RELEASE_SAVEPOINT, Database::SQL_ROLLBACK, Database::SQL_ROLLBACK_TO_SAVEPOINT, Database::SQL_SAVEPOINT, Database::STRING_DEFAULT_RE, Database::TEMPORARY, Database::TRANSACTION_BEGIN, Database::TRANSACTION_COMMIT, Database::TRANSACTION_ISOLATION_LEVELS, Database::TRANSACTION_ROLLBACK, Database::UNDERSCORE, Database::UNIQUE, Database::UNSIGNED

Instance Attribute Summary collapse

Attributes inherited from Database

#cache_schema, #dataset_class, #default_schema, #default_string_column_size, #log_warn_duration, #loggers, #opts, #pool, #prepared_statements, #sql_log_level, #timezone, #transaction_isolation_level

Instance Method Summary collapse

Methods included from PreparedStatements::DatabaseMethods

#call_sproc, #execute

Methods included from DatabaseMethods

#cast_type_literal, #commit_prepared_transaction, #database_type, #foreign_key_list, #global_index_namespace?, #indexes, #rollback_prepared_transaction, #supports_create_table_if_not_exists?, #supports_prepared_transactions?, #supports_savepoints?, #supports_savepoints_in_prepared_transactions?, #supports_transaction_isolation_levels?, #tables, #use, #views

Methods inherited from Database

#<<, #[], adapter_class, adapter_scheme, #adapter_scheme, #add_column, #add_index, #add_servers, #after_commit, #after_rollback, #alter_table, #alter_table_generator, #call, #cast_type_literal, connect, #create_join_table, #create_or_replace_view, #create_table, #create_table!, #create_table?, #create_table_generator, #create_view, #database_type, #dataset, #disconnect, #drop_column, #drop_index, #drop_join_table, #drop_table, #drop_table?, #drop_view, #dump_foreign_key_migration, #dump_indexes_migration, #dump_schema_cache, #dump_schema_cache?, #dump_schema_migration, #dump_table_schema, #each_server, #execute, #execute_ddl, #extend_datasets, #extension, #fetch, #foreign_key_list, #from, #from_application_timestamp, #get, #global_index_namespace?, #identifier_input_method, identifier_input_method, #identifier_input_method=, identifier_input_method=, #identifier_output_method, identifier_output_method, identifier_output_method=, #identifier_output_method=, #in_transaction?, #indexes, #inspect, #literal, #load_schema_cache, #load_schema_cache?, #log_exception, #log_info, #log_yield, #logger=, #prepared_statement, #query, quote_identifiers=, #quote_identifiers=, #quote_identifiers?, register_extension, #remove_servers, #rename_column, #rename_table, #run, #schema, #select, #serial_primary_key_options, #servers, #set_column_default, #set_column_type, #set_prepared_statement, single_threaded=, #single_threaded?, #supports_create_table_if_not_exists?, #supports_deferrable_constraints?, #supports_deferrable_foreign_key_constraints?, #supports_drop_table_if_exists?, #supports_prepared_transactions?, #supports_savepoints?, #supports_savepoints_in_prepared_transactions?, #supports_transaction_isolation_levels?, #supports_transactional_ddl?, #synchronize, #table_exists?, #tables, #test_connection, #to_application_timestamp, #transaction, #typecast_value, #uri, #url, #valid_connection?, #views

Methods included from Sequel::Metaprogramming

#meta_def

Constructor Details

#initialize(opts = {}) ⇒ Database

Returns a new instance of Database.



62
63
64
65
66
67
# File 'lib/sequel/adapters/mysql.rb', line 62

def initialize(opts={})
  super
  @conversion_procs = MYSQL_TYPES.dup
  self.convert_tinyint_to_bool = Sequel::MySQL.convert_tinyint_to_bool
  self.convert_invalid_date_time = Sequel::MySQL.convert_invalid_date_time
end

Instance Attribute Details

#conversion_procsObject (readonly)

Hash of conversion procs for the current database



51
52
53
# File 'lib/sequel/adapters/mysql.rb', line 51

def conversion_procs
  @conversion_procs
end

#convert_invalid_date_timeObject

By default, Sequel raises an exception if in invalid date or time is used. However, if this is set to nil or :nil, the adapter treats dates like 0000-00-00 and times like 838:00:00 as nil values. If set to :string, it returns the strings as is.



60
61
62
# File 'lib/sequel/adapters/mysql.rb', line 60

def convert_invalid_date_time
  @convert_invalid_date_time
end

#convert_tinyint_to_boolObject

Whether to convert tinyint columns to bool for the current database



54
55
56
# File 'lib/sequel/adapters/mysql.rb', line 54

def convert_tinyint_to_bool
  @convert_tinyint_to_bool
end

Instance Method Details

#connect(server) ⇒ Object

Connect to the database. In addition to the usual database options, the following options have effect:

  • :auto_is_null - Set to true to use MySQL default behavior of having a filter for an autoincrement column equals NULL to return the last inserted row.

  • :charset - Same as :encoding (:encoding takes precendence)

  • :compress - Set to false to not compress results from the server

  • :config_default_group - The default group to read from the in the MySQL config file.

  • :config_local_infile - If provided, sets the Mysql::OPT_LOCAL_INFILE option on the connection with the given value.

  • :connect_timeout - Set the timeout in seconds before a connection attempt is abandoned.

  • :encoding - Set all the related character sets for this connection (connection, client, database, server, and results).

  • :read_timeout - Set the timeout in seconds for reading back results to a query.

  • :socket - Use a unix socket file instead of connecting via TCP/IP.

  • :timeout - Set the timeout in seconds before the server will disconnect this connection (a.k.a @@wait_timeout).



90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
# File 'lib/sequel/adapters/mysql.rb', line 90

def connect(server)
  opts = server_opts(server)
  conn = Mysql.init
  conn.options(Mysql::READ_DEFAULT_GROUP, opts[:config_default_group] || "client")
  conn.options(Mysql::OPT_LOCAL_INFILE, opts[:config_local_infile]) if opts.has_key?(:config_local_infile)
  conn.ssl_set(opts[:sslkey], opts[:sslcert], opts[:sslca], opts[:sslcapath], opts[:sslcipher]) if opts[:sslca] || opts[:sslkey]
  if encoding = opts[:encoding] || opts[:charset]
    # Set encoding before connecting so that the mysql driver knows what
    # encoding we want to use, but this can be overridden by READ_DEFAULT_GROUP.
    conn.options(Mysql::SET_CHARSET_NAME, encoding)
  end
  if read_timeout = opts[:read_timeout] and defined? Mysql::OPT_READ_TIMEOUT
    conn.options(Mysql::OPT_READ_TIMEOUT, read_timeout)
  end
  if connect_timeout = opts[:connect_timeout] and defined? Mysql::OPT_CONNECT_TIMEOUT
    conn.options(Mysql::OPT_CONNECT_TIMEOUT, connect_timeout)
  end
  conn.real_connect(
    opts[:host] || 'localhost',
    opts[:user],
    opts[:password],
    opts[:database],
    (opts[:port].to_i if opts[:port]),
    opts[:socket],
    Mysql::CLIENT_MULTI_RESULTS +
    Mysql::CLIENT_MULTI_STATEMENTS +
    (opts[:compress] == false ? 0 : Mysql::CLIENT_COMPRESS)
  )
  sqls = mysql_connection_setting_sqls

  # Set encoding a slightly different way after connecting,
  # in case the READ_DEFAULT_GROUP overrode the provided encoding.
  # Doesn't work across implicit reconnects, but Sequel doesn't turn on
  # that feature.
  sqls.unshift("SET NAMES #{literal(encoding.to_s)}") if encoding

  sqls.each{|sql| log_yield(sql){conn.query(sql)}}

  add_prepared_statements_cache(conn)
  conn
end

#disconnect_connection(c) ⇒ Object

Closes given database connection.



133
134
135
136
137
# File 'lib/sequel/adapters/mysql.rb', line 133

def disconnect_connection(c)
  c.close
rescue Mysql::Error
  nil
end

#execute_dui(sql, opts = {}) ⇒ Object

Return the number of matched rows when executing a delete/update statement.



161
162
163
# File 'lib/sequel/adapters/mysql.rb', line 161

def execute_dui(sql, opts={})
  execute(sql, opts){|c| return affected_rows(c)}
end

#execute_insert(sql, opts = {}) ⇒ Object

Return the last inserted id when executing an insert statement.



166
167
168
# File 'lib/sequel/adapters/mysql.rb', line 166

def execute_insert(sql, opts={})
  execute(sql, opts){|c| return c.insert_id}
end

#server_version(server = nil) ⇒ Object

Return the version of the MySQL server two which we are connecting.



171
172
173
# File 'lib/sequel/adapters/mysql.rb', line 171

def server_version(server=nil)
  @server_version ||= (synchronize(server){|conn| conn.server_version if conn.respond_to?(:server_version)} || super)
end