Module: Sequel::Dataset::PreparedStatementMethods

Defined in:
lib/sequel_core/dataset/prepared_statements.rb

Overview

Backbone of the prepared statement support. Grafts bind variable support into datasets by hijacking #literal and using placeholders. By default, emulates prepared statements and bind variables by taking the hash of bind variables and directly substituting them into the query, which works on all databases, as it is no different from using the dataset without bind variables.

Constant Summary collapse

PLACEHOLDER_RE =
/\A\$(.*)\z/

Instance Attribute Summary collapse

Instance Method Summary collapse

Instance Attribute Details

#prepared_argsObject

The bind variable hash to use when substituting



59
60
61
# File 'lib/sequel_core/dataset/prepared_statements.rb', line 59

def prepared_args
  @prepared_args
end

#prepared_modify_valuesObject

The argument to supply to insert and update, which may use placeholders specified by prepared_args



63
64
65
# File 'lib/sequel_core/dataset/prepared_statements.rb', line 63

def prepared_modify_values
  @prepared_modify_values
end

#prepared_typeObject

The type of prepared statement, should be one of :select, :insert, :update, or :delete



56
57
58
# File 'lib/sequel_core/dataset/prepared_statements.rb', line 56

def prepared_type
  @prepared_type
end

Instance Method Details

#call(hash, &block) ⇒ Object

Sets the prepared_args to the given hash and runs the prepared statement.



67
68
69
70
71
# File 'lib/sequel_core/dataset/prepared_statements.rb', line 67

def call(hash, &block)
  ds = clone
  ds.prepared_args = hash
  ds.run(&block)
end

#inspectObject

Programmer friendly string showing this is a prepared statement, with the prepared SQL it represents (which in general won’t have substituted variables).



109
110
111
# File 'lib/sequel_core/dataset/prepared_statements.rb', line 109

def inspect
  "<#{self.class.name}/PreparedStatement #{prepared_sql.inspect}>"
end

#literal(v) ⇒ Object

Changes the values of symbols if they start with $ and prepared_args is present. If so, they are considered placeholders, and they are substituted using prepared_arg.



93
94
95
96
97
98
99
100
101
102
103
104
# File 'lib/sequel_core/dataset/prepared_statements.rb', line 93

def literal(v)
  case v
  when Symbol
    if match = PLACEHOLDER_RE.match(v.to_s) and @prepared_args
      super(prepared_arg(match[1].to_sym))
    else
      super
    end
  else
    super
  end
end

#prepared_sqlObject

Returns the SQL for the prepared statement, depending on the type of the statement and the prepared_modify_values.



75
76
77
78
79
80
81
82
83
84
85
86
87
88
# File 'lib/sequel_core/dataset/prepared_statements.rb', line 75

def prepared_sql
  case @prepared_type
  when :select, :all
    select_sql
  when :first
    select_sql(:limit=>1)
  when :insert
    insert_sql(@prepared_modify_values)
  when :update
    update_sql(@prepared_modify_values)
  when :delete
    delete_sql
  end
end