Module: DBI::SQL::BasicBind

Included in:
DBD::ADO::Statement, PreparedStatement
Defined in:
lib/dbi/sql.rb

Overview

Mixin module useful for binding arguments to an SQL string.

Instance Method Summary collapse

Instance Method Details

#bind(quoter, sql, args) ⇒ Object

Bind the :sql string to an array of :args, quoting with :quoter.



125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
# File 'lib/dbi/sql.rb', line 125

def bind(quoter, sql, args)
  arg_index = 0
  result = ""
  tokens(sql).each { |part|
	case part
	when '?'
	  result << quoter.quote(args[arg_index])
	  arg_index += 1
	when '??'
	  result << "?"
	else
	  result << part
	end
  }
  if arg_index < args.size
    raise "Too many SQL parameters"
  elsif arg_index > args.size
    raise "Not enough SQL parameters"
  end
  result
end

#tokens(sql) ⇒ Object

Break the sql string into parts.

This is NOT a full lexer for SQL. It just breaks up the SQL string enough so that question marks, double question marks and quoted strings are separated. This is used when binding arguments to “?” in the SQL string.

C-style (/* */) and Ada-style (–) comments are handled. Note: Nested C-style comments are NOT handled!



157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
# File 'lib/dbi/sql.rb', line 157

def tokens(sql)
  sql.scan(%r{
    (
        -- .*                               (?# matches "--" style comments to the end of line or string )
    |   -                                   (?# matches single "-" )
    |
        /[*] .*? [*]/                       (?# matches C-style comments )
    |   /                                   (?# matches single slash )    
    |
        ' ( [^'\\]  |  ''  |  \\. )* '      (?# match strings surrounded by apostophes )
    |
        " ( [^"\\]  |  ""  |  \\. )* "      (?# match strings surrounded by " )
    |
        \?\??                               (?# match one or two question marks )
    |
        [^-/'"?]+                           (?# match all characters except ' " ? - and / )
        
    )}x).collect {|t| t.first}
end