Class: Sequel::DbOpts::DbOptions

Inherits:
Object
  • Object
show all
Defined in:
lib/sequel/extensions/db_opts.rb

Overview

Handles extraction and application of database-specific options.

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(db) ⇒ DbOptions

Creates a new DbOptions instance for the given database.

Parameters:

  • db (Sequel::Database)

    the database to configure



33
34
35
36
# File 'lib/sequel/extensions/db_opts.rb', line 33

def initialize(db)
  db.extension :settable
  @db = db
end

Instance Attribute Details

#dbObject (readonly)

Returns the value of attribute db.



28
29
30
# File 'lib/sequel/extensions/db_opts.rb', line 28

def db
  @db
end

Instance Method Details

#apply(c) ⇒ Object

Applies the database options to the given connection.

Executes the SQL statements generated from the options on the connection.

Parameters:

  • c (Object)

    the database connection



64
65
66
67
68
# File 'lib/sequel/extensions/db_opts.rb', line 64

def apply(c)
  sql_statements.each do |stmt|
    db.send(:log_connection_execute, c, stmt)
  end
end

#extract_db_optsHash

Extracts database-specific options from the database configuration.

Looks for options matching the pattern ‘database_typedb_optoption_name` and extracts the option name and value.

Returns:

  • (Hash)

    extracted options with symbolic keys



51
52
53
54
55
56
57
# File 'lib/sequel/extensions/db_opts.rb', line 51

def extract_db_opts
  opt_regexp = /^#{db.database_type}_db_opt_/i

  db.opts.select do |k, _|
    k.to_s.match(opt_regexp)
  end.to_h { |k, v| [k.to_s.gsub(opt_regexp, '').to_sym, prep_value(k, v)] }
end

#prep_value(_k, v) ⇒ String

Prepares a value for use in SQL statements.

Values containing non-word characters are treated as literals and quoted, while simple values are used as-is.

Parameters:

  • _k (Symbol)

    the option key (unused)

  • v (Object)

    the option value

Returns:

  • (String)

    the prepared value



78
79
80
# File 'lib/sequel/extensions/db_opts.rb', line 78

def prep_value(_k, v)
  v =~ /\W/ ? db.literal(v.to_s) : v
end

#sql_statementsArray<String>

Generates SQL SET statements for the database options.

Returns:

  • (Array<String>)

    array of SQL SET statements



85
86
87
# File 'lib/sequel/extensions/db_opts.rb', line 85

def sql_statements
  db.send(:set_sql, to_hash)
end

#to_hashHash

Returns a hash of database-specific options extracted from the database configuration.

Returns:

  • (Hash)

    hash of option names to values



41
42
43
# File 'lib/sequel/extensions/db_opts.rb', line 41

def to_hash
  @_to_hash ||= extract_db_opts
end