colincasey-sequel 2.10.0 → 2.10.1

Sign up to get free protection for your applications and to get access to all the features.
Files changed (137) hide show
  1. data/CHANGELOG +7 -1
  2. data/doc/advanced_associations.rdoc +614 -0
  3. data/doc/cheat_sheet.rdoc +223 -0
  4. data/doc/dataset_filtering.rdoc +158 -0
  5. data/doc/prepared_statements.rdoc +104 -0
  6. data/doc/release_notes/1.0.txt +38 -0
  7. data/doc/release_notes/1.1.txt +143 -0
  8. data/doc/release_notes/1.3.txt +101 -0
  9. data/doc/release_notes/1.4.0.txt +53 -0
  10. data/doc/release_notes/1.5.0.txt +155 -0
  11. data/doc/release_notes/2.0.0.txt +298 -0
  12. data/doc/release_notes/2.1.0.txt +271 -0
  13. data/doc/release_notes/2.10.0.txt +328 -0
  14. data/doc/release_notes/2.2.0.txt +253 -0
  15. data/doc/release_notes/2.3.0.txt +88 -0
  16. data/doc/release_notes/2.4.0.txt +106 -0
  17. data/doc/release_notes/2.5.0.txt +137 -0
  18. data/doc/release_notes/2.6.0.txt +157 -0
  19. data/doc/release_notes/2.7.0.txt +166 -0
  20. data/doc/release_notes/2.8.0.txt +171 -0
  21. data/doc/release_notes/2.9.0.txt +97 -0
  22. data/doc/schema.rdoc +29 -0
  23. data/doc/sharding.rdoc +113 -0
  24. data/lib/sequel.rb +1 -0
  25. data/lib/sequel_core/adapters/ado.rb +89 -0
  26. data/lib/sequel_core/adapters/db2.rb +143 -0
  27. data/lib/sequel_core/adapters/dbi.rb +112 -0
  28. data/lib/sequel_core/adapters/do/mysql.rb +38 -0
  29. data/lib/sequel_core/adapters/do/postgres.rb +92 -0
  30. data/lib/sequel_core/adapters/do/sqlite.rb +31 -0
  31. data/lib/sequel_core/adapters/do.rb +205 -0
  32. data/lib/sequel_core/adapters/firebird.rb +298 -0
  33. data/lib/sequel_core/adapters/informix.rb +85 -0
  34. data/lib/sequel_core/adapters/jdbc/h2.rb +69 -0
  35. data/lib/sequel_core/adapters/jdbc/mysql.rb +66 -0
  36. data/lib/sequel_core/adapters/jdbc/oracle.rb +23 -0
  37. data/lib/sequel_core/adapters/jdbc/postgresql.rb +113 -0
  38. data/lib/sequel_core/adapters/jdbc/sqlite.rb +43 -0
  39. data/lib/sequel_core/adapters/jdbc.rb +491 -0
  40. data/lib/sequel_core/adapters/mysql.rb +369 -0
  41. data/lib/sequel_core/adapters/odbc.rb +174 -0
  42. data/lib/sequel_core/adapters/openbase.rb +68 -0
  43. data/lib/sequel_core/adapters/oracle.rb +107 -0
  44. data/lib/sequel_core/adapters/postgres.rb +456 -0
  45. data/lib/sequel_core/adapters/shared/ms_access.rb +110 -0
  46. data/lib/sequel_core/adapters/shared/mssql.rb +102 -0
  47. data/lib/sequel_core/adapters/shared/mysql.rb +325 -0
  48. data/lib/sequel_core/adapters/shared/oracle.rb +61 -0
  49. data/lib/sequel_core/adapters/shared/postgres.rb +715 -0
  50. data/lib/sequel_core/adapters/shared/progress.rb +31 -0
  51. data/lib/sequel_core/adapters/shared/sqlite.rb +265 -0
  52. data/lib/sequel_core/adapters/sqlite.rb +248 -0
  53. data/lib/sequel_core/connection_pool.rb +258 -0
  54. data/lib/sequel_core/core_ext.rb +217 -0
  55. data/lib/sequel_core/core_sql.rb +202 -0
  56. data/lib/sequel_core/database/schema.rb +164 -0
  57. data/lib/sequel_core/database.rb +691 -0
  58. data/lib/sequel_core/dataset/callback.rb +13 -0
  59. data/lib/sequel_core/dataset/convenience.rb +237 -0
  60. data/lib/sequel_core/dataset/pagination.rb +96 -0
  61. data/lib/sequel_core/dataset/prepared_statements.rb +220 -0
  62. data/lib/sequel_core/dataset/query.rb +41 -0
  63. data/lib/sequel_core/dataset/schema.rb +15 -0
  64. data/lib/sequel_core/dataset/sql.rb +1010 -0
  65. data/lib/sequel_core/dataset/stored_procedures.rb +75 -0
  66. data/lib/sequel_core/dataset/unsupported.rb +43 -0
  67. data/lib/sequel_core/dataset.rb +511 -0
  68. data/lib/sequel_core/deprecated.rb +26 -0
  69. data/lib/sequel_core/exceptions.rb +44 -0
  70. data/lib/sequel_core/migration.rb +212 -0
  71. data/lib/sequel_core/object_graph.rb +230 -0
  72. data/lib/sequel_core/pretty_table.rb +71 -0
  73. data/lib/sequel_core/schema/generator.rb +320 -0
  74. data/lib/sequel_core/schema/sql.rb +325 -0
  75. data/lib/sequel_core/schema.rb +2 -0
  76. data/lib/sequel_core/sql.rb +887 -0
  77. data/lib/sequel_core/version.rb +11 -0
  78. data/lib/sequel_core.rb +172 -0
  79. data/lib/sequel_model/association_reflection.rb +267 -0
  80. data/lib/sequel_model/associations.rb +499 -0
  81. data/lib/sequel_model/base.rb +523 -0
  82. data/lib/sequel_model/caching.rb +82 -0
  83. data/lib/sequel_model/dataset_methods.rb +26 -0
  84. data/lib/sequel_model/eager_loading.rb +370 -0
  85. data/lib/sequel_model/exceptions.rb +7 -0
  86. data/lib/sequel_model/hooks.rb +101 -0
  87. data/lib/sequel_model/inflector.rb +281 -0
  88. data/lib/sequel_model/plugins.rb +62 -0
  89. data/lib/sequel_model/record.rb +568 -0
  90. data/lib/sequel_model/schema.rb +49 -0
  91. data/lib/sequel_model/validations.rb +429 -0
  92. data/lib/sequel_model.rb +91 -0
  93. data/spec/adapters/ado_spec.rb +46 -0
  94. data/spec/adapters/firebird_spec.rb +376 -0
  95. data/spec/adapters/informix_spec.rb +96 -0
  96. data/spec/adapters/mysql_spec.rb +881 -0
  97. data/spec/adapters/oracle_spec.rb +244 -0
  98. data/spec/adapters/postgres_spec.rb +687 -0
  99. data/spec/adapters/spec_helper.rb +10 -0
  100. data/spec/adapters/sqlite_spec.rb +555 -0
  101. data/spec/integration/dataset_test.rb +134 -0
  102. data/spec/integration/eager_loader_test.rb +696 -0
  103. data/spec/integration/prepared_statement_test.rb +130 -0
  104. data/spec/integration/schema_test.rb +180 -0
  105. data/spec/integration/spec_helper.rb +58 -0
  106. data/spec/integration/type_test.rb +96 -0
  107. data/spec/rcov.opts +6 -0
  108. data/spec/sequel_core/connection_pool_spec.rb +526 -0
  109. data/spec/sequel_core/core_ext_spec.rb +156 -0
  110. data/spec/sequel_core/core_sql_spec.rb +522 -0
  111. data/spec/sequel_core/database_spec.rb +1188 -0
  112. data/spec/sequel_core/dataset_spec.rb +3481 -0
  113. data/spec/sequel_core/expression_filters_spec.rb +363 -0
  114. data/spec/sequel_core/migration_spec.rb +261 -0
  115. data/spec/sequel_core/object_graph_spec.rb +272 -0
  116. data/spec/sequel_core/pretty_table_spec.rb +58 -0
  117. data/spec/sequel_core/schema_generator_spec.rb +167 -0
  118. data/spec/sequel_core/schema_spec.rb +780 -0
  119. data/spec/sequel_core/spec_helper.rb +55 -0
  120. data/spec/sequel_core/version_spec.rb +7 -0
  121. data/spec/sequel_model/association_reflection_spec.rb +93 -0
  122. data/spec/sequel_model/associations_spec.rb +1767 -0
  123. data/spec/sequel_model/base_spec.rb +419 -0
  124. data/spec/sequel_model/caching_spec.rb +215 -0
  125. data/spec/sequel_model/dataset_methods_spec.rb +78 -0
  126. data/spec/sequel_model/eager_loading_spec.rb +1165 -0
  127. data/spec/sequel_model/hooks_spec.rb +485 -0
  128. data/spec/sequel_model/inflector_spec.rb +119 -0
  129. data/spec/sequel_model/model_spec.rb +588 -0
  130. data/spec/sequel_model/plugins_spec.rb +80 -0
  131. data/spec/sequel_model/record_spec.rb +1184 -0
  132. data/spec/sequel_model/schema_spec.rb +90 -0
  133. data/spec/sequel_model/spec_helper.rb +78 -0
  134. data/spec/sequel_model/validations_spec.rb +1067 -0
  135. data/spec/spec.opts +0 -0
  136. data/spec/spec_config.rb.example +10 -0
  137. metadata +177 -3
@@ -0,0 +1,887 @@
1
+ module Sequel
2
+ # The SQL module holds classes whose instances represent SQL fragments.
3
+ # It also holds modules that are included in core ruby classes that
4
+ # make Sequel a friendly DSL.
5
+ module SQL
6
+ ### Parent Classes ###
7
+
8
+ # Classes/Modules aren't an alphabetical order due to the fact that
9
+ # some reference constants defined in others at load time.
10
+
11
+ # Base class for all SQL fragments
12
+ class Expression
13
+ # Returns self, because SQL::Expression already acts like
14
+ # LiteralString.
15
+ def lit
16
+ self
17
+ end
18
+ end
19
+
20
+ # Represents a complex SQL expression, with a given operator and one
21
+ # or more attributes (which may also be ComplexExpressions, forming
22
+ # a tree). This class is the backbone of the blockless filter support in
23
+ # Sequel.
24
+ #
25
+ # This is an abstract class that is not that useful by itself. The
26
+ # subclasses BooleanExpression, NumericExpression, and StringExpression
27
+ # define the behavior of the DSL via operators.
28
+ class ComplexExpression < Expression
29
+ # A hash of the opposite for each operator symbol, used for inverting
30
+ # objects.
31
+ OPERTATOR_INVERSIONS = {:AND => :OR, :OR => :AND, :< => :>=, :> => :<=,
32
+ :<= => :>, :>= => :<, :'=' => :'!=' , :'!=' => :'=', :LIKE => :'NOT LIKE',
33
+ :'NOT LIKE' => :LIKE, :~ => :'!~', :'!~' => :~, :IN => :'NOT IN',
34
+ :'NOT IN' => :IN, :IS => :'IS NOT', :'IS NOT' => :IS, :'~*' => :'!~*',
35
+ :'!~*' => :'~*', :NOT => :NOOP, :NOOP => :NOT, :ILIKE => :'NOT ILIKE',
36
+ :'NOT ILIKE'=>:ILIKE}
37
+
38
+ # Mathematical Operators used in NumericMethods
39
+ MATHEMATICAL_OPERATORS = [:+, :-, :/, :*]
40
+
41
+ # Mathematical Operators used in NumericMethods
42
+ BITWISE_OPERATORS = [:&, :|, :^, :<<, :>>]
43
+
44
+ # Inequality Operators used in InequalityMethods
45
+ INEQUALITY_OPERATORS = [:<, :>, :<=, :>=]
46
+
47
+ # Hash of ruby operator symbols to SQL operators, used in BooleanMethods
48
+ BOOLEAN_OPERATOR_METHODS = {:& => :AND, :| =>:OR}
49
+
50
+ # Operator symbols that take exactly two arguments
51
+ TWO_ARITY_OPERATORS = [:'=', :'!=', :IS, :'IS NOT', :LIKE, :'NOT LIKE', \
52
+ :~, :'!~', :'~*', :'!~*', :IN, :'NOT IN', :ILIKE, :'NOT ILIKE'] + \
53
+ INEQUALITY_OPERATORS + BITWISE_OPERATORS
54
+
55
+ # Operator symbols that take one or more arguments
56
+ N_ARITY_OPERATORS = [:AND, :OR, :'||'] + MATHEMATICAL_OPERATORS
57
+
58
+ # Operator symbols that take one argument
59
+ ONE_ARITY_OPERATORS = [:NOT, :NOOP, :'B~']
60
+
61
+ # An array of args for this object
62
+ attr_reader :args
63
+
64
+ # The operator symbol for this object
65
+ attr_reader :op
66
+
67
+ # Set the operator symbol and arguments for this object to the ones given.
68
+ # Convert all args that are hashes or arrays with all two pairs to ComplexExpressions.
69
+ # Raise an error if the operator doesn't allow boolean input and a boolean argument is given.
70
+ # Raise an error if the wrong number of arguments for a given operator is used.
71
+ def initialize(op, *args)
72
+ args.collect! do |a|
73
+ case a
74
+ when Hash
75
+ a.sql_expr
76
+ when Array
77
+ a.all_two_pairs? ? a.sql_expr : a
78
+ else
79
+ a
80
+ end
81
+ end
82
+ case op
83
+ when *N_ARITY_OPERATORS
84
+ raise(Error, "The #{op} operator requires at least 1 argument") unless args.length >= 1
85
+ when *TWO_ARITY_OPERATORS
86
+ raise(Error, "The #{op} operator requires precisely 2 arguments") unless args.length == 2
87
+ when *ONE_ARITY_OPERATORS
88
+ raise(Error, "The #{op} operator requires a single argument") unless args.length == 1
89
+ else
90
+ raise(Error, "Invalid operator #{op}")
91
+ end
92
+ @op = op
93
+ @args = args
94
+ end
95
+
96
+ # Delegate the creation of the resulting SQL to the given dataset,
97
+ # since it may be database dependent.
98
+ def to_s(ds)
99
+ ds.complex_expression_sql(@op, @args)
100
+ end
101
+
102
+ # Returns true if the receiver is the same expression as the
103
+ # the +other+ expression.
104
+ def eql?( other )
105
+ return other.is_a?( self.class ) &&
106
+ @op.eql?( other.op ) &&
107
+ @args.eql?( other.args )
108
+ end
109
+ alias_method :==, :eql?
110
+ end
111
+
112
+ # The base class for expressions that can be used in multiple places in
113
+ # the SQL query.
114
+ class GenericExpression < Expression
115
+ end
116
+
117
+ # The base class for expressions that are specific and can only be used
118
+ # in a certain place in the SQL query (ordering, selecting).
119
+ class SpecificExpression < Expression
120
+ end
121
+
122
+ ### Modules ###
123
+
124
+ # Methods the create aliased identifiers
125
+ module AliasMethods
126
+ # Create an SQL column alias of the receiving column to the given alias.
127
+ def as(aliaz)
128
+ AliasedExpression.new(self, aliaz)
129
+ end
130
+ end
131
+
132
+ # This defines the bitwise methods &, |, ^, ~, <<, and >>. Because these
133
+ # methods overlap with the standard BooleanMethods methods, and they only
134
+ # make sense for numbers, they are only included in NumericExpression.
135
+ module BitwiseMethods
136
+ ComplexExpression::BITWISE_OPERATORS.each do |o|
137
+ define_method(o) do |ce|
138
+ case ce
139
+ when NumericExpression
140
+ NumericExpression.new(o, self, ce)
141
+ when ComplexExpression
142
+ raise(Sequel::Error, "cannot apply #{o} to a non-numeric expression")
143
+ else
144
+ NumericExpression.new(o, self, ce)
145
+ end
146
+ end
147
+ end
148
+
149
+ # Do the bitwise compliment of the self
150
+ def ~
151
+ NumericExpression.new(:'B~', self)
152
+ end
153
+ end
154
+
155
+ # This module includes the methods that are defined on objects that can be
156
+ # used in a boolean context in SQL (Symbol, LiteralString, SQL::Function,
157
+ # and SQL::BooleanExpression).
158
+ #
159
+ # This defines the ~ (NOT), & (AND), and | (OR) methods.
160
+ module BooleanMethods
161
+ # Create a new BooleanExpression with NOT, representing the inversion of whatever self represents.
162
+ def ~
163
+ BooleanExpression.invert(self)
164
+ end
165
+
166
+ ComplexExpression::BOOLEAN_OPERATOR_METHODS.each do |m, o|
167
+ define_method(m) do |ce|
168
+ case ce
169
+ when BooleanExpression
170
+ BooleanExpression.new(o, self, ce)
171
+ when ComplexExpression
172
+ raise(Sequel::Error, "cannot apply #{o} to a non-boolean expression")
173
+ else
174
+ BooleanExpression.new(o, self, ce)
175
+ end
176
+ end
177
+ end
178
+ end
179
+
180
+ # Holds methods that are used to cast objects to differen SQL types.
181
+ module CastMethods
182
+ # Cast the reciever to the given SQL type
183
+ def cast(sql_type)
184
+ Cast.new(self, sql_type)
185
+ end
186
+ alias_method :cast_as, :cast
187
+
188
+ # Cast the reciever to the given SQL type (or integer if none given),
189
+ # and return the result as a NumericExpression.
190
+ def cast_numeric(sql_type = nil)
191
+ cast(sql_type || Integer).sql_number
192
+ end
193
+
194
+ # Cast the reciever to the given SQL type (or text if none given),
195
+ # and return the result as a StringExpression, so you can use +
196
+ # directly on the result for SQL string concatenation.
197
+ def cast_string(sql_type = nil)
198
+ cast(sql_type || String).sql_string
199
+ end
200
+ end
201
+
202
+ # Includes a method that returns Identifiers.
203
+ module IdentifierMethods
204
+ # Return self wrapped as an identifier.
205
+ def identifier
206
+ Identifier.new(self)
207
+ end
208
+ end
209
+
210
+ # This module includes the methods that are defined on objects that can be
211
+ # used in a numeric or string context in SQL (Symbol, LiteralString,
212
+ # SQL::Function, and SQL::StringExpression).
213
+ #
214
+ # This defines the >, <, >=, and <= methods.
215
+ module InequalityMethods
216
+ ComplexExpression::INEQUALITY_OPERATORS.each do |o|
217
+ define_method(o) do |ce|
218
+ case ce
219
+ when BooleanExpression, TrueClass, FalseClass, NilClass, Hash, Array
220
+ raise(Error, "cannot apply #{o} to a boolean expression")
221
+ else
222
+ BooleanExpression.new(o, self, ce)
223
+ end
224
+ end
225
+ end
226
+ end
227
+
228
+ # This module augments the default initalize method for the
229
+ # ComplexExpression subclass it is included in, so that
230
+ # attempting to use boolean input when initializing a NumericExpression
231
+ # or StringExpression results in an error.
232
+ module NoBooleanInputMethods
233
+ # Raise an Error if one of the args would be boolean in an SQL
234
+ # context, otherwise call super.
235
+ def initialize(op, *args)
236
+ args.each do |a|
237
+ case a
238
+ when BooleanExpression, TrueClass, FalseClass, NilClass, Hash, Array
239
+ raise(Error, "cannot apply #{op} to a boolean expression")
240
+ end
241
+ end
242
+ super
243
+ end
244
+ end
245
+
246
+ # This module includes the methods that are defined on objects that can be
247
+ # used in a numeric context in SQL (Symbol, LiteralString, SQL::Function,
248
+ # and SQL::NumericExpression).
249
+ #
250
+ # This defines the +, -, *, and / methods.
251
+ module NumericMethods
252
+ ComplexExpression::MATHEMATICAL_OPERATORS.each do |o|
253
+ define_method(o) do |ce|
254
+ case ce
255
+ when NumericExpression
256
+ NumericExpression.new(o, self, ce)
257
+ when ComplexExpression
258
+ raise(Sequel::Error, "cannot apply #{o} to a non-numeric expression")
259
+ else
260
+ NumericExpression.new(o, self, ce)
261
+ end
262
+ end
263
+ end
264
+ end
265
+
266
+ # Methods that create OrderedExpressions, used for sorting by columns
267
+ # or more complex expressions.
268
+ module OrderMethods
269
+ # Mark the receiving SQL column as sorting in a descending fashion.
270
+ def desc
271
+ OrderedExpression.new(self)
272
+ end
273
+
274
+ # Mark the receiving SQL column as sorting in an ascending fashion (generally a no-op).
275
+ def asc
276
+ OrderedExpression.new(self, false)
277
+ end
278
+ end
279
+
280
+ # Methods that created QualifiedIdentifiers, used for qualifying column
281
+ # names with a table or table names with a schema.
282
+ module QualifyingMethods
283
+ # Qualify the current object with the given table/schema.
284
+ def qualify(ts)
285
+ QualifiedIdentifier.new(ts, self)
286
+ end
287
+ end
288
+
289
+ # This module includes the methods that are defined on objects that can be
290
+ # used in a numeric context in SQL (Symbol, LiteralString, SQL::Function,
291
+ # and SQL::StringExpression).
292
+ #
293
+ # This defines the like (LIKE) method, used for pattern matching.
294
+ module StringMethods
295
+ # Create a BooleanExpression case insensitive pattern match of self
296
+ # with the given patterns. See StringExpression.like.
297
+ def ilike(*ces)
298
+ StringExpression.like(self, *(ces << {:case_insensitive=>true}))
299
+ end
300
+
301
+ # Create a BooleanExpression case sensitive pattern match of self with
302
+ # the given patterns. See StringExpression.like.
303
+ def like(*ces)
304
+ StringExpression.like(self, *ces)
305
+ end
306
+ end
307
+
308
+ # This module is included in StringExpression and can be included elsewhere
309
+ # to allow the use of the + operator to represent concatenation of SQL
310
+ # Strings:
311
+ #
312
+ # :x.sql_string + :y => # SQL: x || y
313
+ module StringConcatenationMethods
314
+ def +(ce)
315
+ StringExpression.new(:'||', self, ce)
316
+ end
317
+ end
318
+
319
+ ### Modules that include other modules ###
320
+
321
+ # This module includes other Sequel::SQL::*Methods modules and is
322
+ # included in other classes that are could be either booleans,
323
+ # strings, or numbers. It also adds three methods so that
324
+ # can specify behavior in case one of the operator methods has
325
+ # been overridden (such as Symbol#/).
326
+ #
327
+ # For example, if Symbol#/ is overridden to produce a string (for
328
+ # example, to make file system path creation easier), the
329
+ # following code will not do what you want:
330
+ #
331
+ # :price/10 > 100
332
+ #
333
+ # In that case, you need to do the following:
334
+ #
335
+ # :price.sql_number/10 > 100
336
+ module ComplexExpressionMethods
337
+ # Extract a datetime_part (e.g. year, month) from self:
338
+ #
339
+ # :date.extract(:year) # SQL: extract(year FROM date)
340
+ #
341
+ # Also has the benefit of returning the result as a
342
+ # NumericExpression instead of a generic ComplexExpression.
343
+ def extract(datetime_part)
344
+ IrregularFunction.new(:extract, datetime_part.to_s.lit, :FROM, self).sql_number
345
+ end
346
+
347
+ # Return a BooleanExpression representation of self.
348
+ def sql_boolean
349
+ BooleanExpression.new(:NOOP, self)
350
+ end
351
+
352
+ # Return a NumericExpression representation of self.
353
+ def sql_number
354
+ NumericExpression.new(:NOOP, self)
355
+ end
356
+
357
+ # Return a StringExpression representation of self.
358
+ def sql_string
359
+ StringExpression.new(:NOOP, self)
360
+ end
361
+ end
362
+
363
+ class ComplexExpression
364
+ include AliasMethods
365
+ include CastMethods
366
+ include OrderMethods
367
+ end
368
+
369
+ class GenericExpression
370
+ include AliasMethods
371
+ include CastMethods
372
+ include OrderMethods
373
+ include ComplexExpressionMethods
374
+ include BooleanMethods
375
+ include NumericMethods
376
+ include StringMethods
377
+ include InequalityMethods
378
+ end
379
+
380
+ ### Classes ###
381
+
382
+ # Represents an aliasing of an expression/column to a given name.
383
+ class AliasedExpression < SpecificExpression
384
+ # The expression to alias
385
+ attr_reader :expression
386
+
387
+ # The alias to use for the expression, not alias since that is
388
+ # a keyword in ruby.
389
+ attr_reader :aliaz
390
+
391
+ # Create an object with the given expression and alias.
392
+ def initialize(expression, aliaz)
393
+ @expression, @aliaz = expression, aliaz
394
+ end
395
+
396
+ # Delegate the creation of the resulting SQL to the given dataset,
397
+ # since it may be database dependent.
398
+ def to_s(ds)
399
+ ds.aliased_expression_sql(self)
400
+ end
401
+ end
402
+
403
+ # Blob is used to represent binary data in the Ruby environment that is
404
+ # stored as a blob type in the database. In PostgreSQL, the blob type is
405
+ # called bytea. Sequel represents binary data as a Blob object because
406
+ # certain database engines, such as PostgreSQL, require binary data to be
407
+ # escaped.
408
+ class Blob < ::String
409
+ # return self.
410
+ def to_sequel_blob
411
+ self
412
+ end
413
+ alias to_blob to_sequel_blob
414
+ end
415
+
416
+ # Subclass of ComplexExpression where the expression results
417
+ # in a boolean value in SQL.
418
+ class BooleanExpression < ComplexExpression
419
+ include BooleanMethods
420
+
421
+ # Take pairs of values (e.g. a hash or array of arrays of two pairs)
422
+ # and converts it to a BooleanExpression. The operator and args
423
+ # used depends on the case of the right (2nd) argument:
424
+ #
425
+ # * 0..10 - left >= 0 AND left <= 10
426
+ # * [1,2] - left IN (1,2)
427
+ # * nil - left IS NULL
428
+ # * /as/ - left ~ 'as'
429
+ # * :blah - left = blah
430
+ # * 'blah' - left = 'blah'
431
+ #
432
+ # If multiple arguments are given, they are joined with the op given (AND
433
+ # by default, OR possible). If negate is set to true,
434
+ # all subexpressions are inverted before used. Therefore, the following
435
+ # expressions are equivalent:
436
+ #
437
+ # ~from_value_pairs(hash)
438
+ # from_value_pairs(hash, :OR, true)
439
+ def self.from_value_pairs(pairs, op=:AND, negate=false)
440
+ pairs = pairs.collect do |l,r|
441
+ ce = case r
442
+ when Range
443
+ new(:AND, new(:>=, l, r.begin), new(r.exclude_end? ? :< : :<=, l, r.end))
444
+ when Array, ::Sequel::Dataset, SQLArray
445
+ new(:IN, l, r)
446
+ when NilClass
447
+ new(:IS, l, r)
448
+ when Regexp
449
+ StringExpression.like(l, r)
450
+ else
451
+ new(:'=', l, r)
452
+ end
453
+ negate ? invert(ce) : ce
454
+ end
455
+ pairs.length == 1 ? pairs.at(0) : new(op, *pairs)
456
+ end
457
+
458
+ # Invert the expression, if possible. If the expression cannot
459
+ # be inverted, raise an error. An inverted expression should match everything that the
460
+ # uninverted expression did not match, and vice-versa.
461
+ def self.invert(ce)
462
+ case ce
463
+ when BooleanExpression
464
+ case op = ce.op
465
+ when :AND, :OR
466
+ BooleanExpression.new(OPERTATOR_INVERSIONS[op], *ce.args.collect{|a| BooleanExpression.invert(a)})
467
+ else
468
+ BooleanExpression.new(OPERTATOR_INVERSIONS[op], *ce.args.dup)
469
+ end
470
+ when ComplexExpression
471
+ raise(Sequel::Error, "operator #{ce.op} cannot be inverted")
472
+ else
473
+ BooleanExpression.new(:NOT, ce)
474
+ end
475
+ end
476
+ end
477
+
478
+ # Represents an SQL CASE expression, used for conditions.
479
+ class CaseExpression < GenericExpression
480
+ # An array of all two pairs with the first element specifying the
481
+ # condition and the second element specifying the result.
482
+ attr_reader :conditions
483
+
484
+ # The default value if no conditions are true
485
+ attr_reader :default
486
+
487
+ # The expression to test the conditions against
488
+ attr_reader :expression
489
+
490
+ # Create an object with the given conditions and
491
+ # default value.
492
+ def initialize(conditions, default, expression = nil)
493
+ raise(Sequel::Error, 'CaseExpression conditions must be an array with all_two_pairs') unless Array === conditions and conditions.all_two_pairs?
494
+ @conditions, @default, @expression = conditions, default, expression
495
+ end
496
+
497
+ # Delegate the creation of the resulting SQL to the given dataset,
498
+ # since it may be database dependent.
499
+ def to_s(ds)
500
+ ds.case_expression_sql(self)
501
+ end
502
+ end
503
+
504
+ # Represents a cast of an SQL expression to a specific type.
505
+ class Cast < GenericExpression
506
+ # The expression to cast
507
+ attr_reader :expr
508
+
509
+ # The type to which to cast the expression
510
+ attr_reader :type
511
+
512
+ # Set the attributes to the given arguments
513
+ def initialize(expr, type)
514
+ @expr = expr
515
+ @type = type
516
+ end
517
+
518
+ # Delegate the creation of the resulting SQL to the given dataset,
519
+ # since it may be database dependent.
520
+ def to_s(ds)
521
+ ds.cast_sql(expr, type)
522
+ end
523
+ end
524
+
525
+ # Represents all columns in a given table, table.* in SQL
526
+ class ColumnAll < SpecificExpression
527
+ # The table containing the columns being selected
528
+ attr_reader :table
529
+
530
+ # Create an object with the given table
531
+ def initialize(table)
532
+ @table = table
533
+ end
534
+
535
+ # ColumnAll expressions are considered equivalent if they
536
+ # have the same class and string representation
537
+ def ==(x)
538
+ x.class == self.class && @table == x.table
539
+ end
540
+
541
+ # Delegate the creation of the resulting SQL to the given dataset,
542
+ # since it may be database dependent.
543
+ def to_s(ds)
544
+ ds.column_all_sql(self)
545
+ end
546
+ end
547
+
548
+ # Represents an SQL function call.
549
+ class Function < GenericExpression
550
+ # The array of arguments to pass to the function (may be blank)
551
+ attr_reader :args
552
+
553
+ # The SQL function to call
554
+ attr_reader :f
555
+
556
+ # Set the attributes to the given arguments
557
+ def initialize(f, *args)
558
+ @f, @args = f, args
559
+ end
560
+
561
+ # Functions are considered equivalent if they
562
+ # have the same class, function, and arguments.
563
+ def ==(x)
564
+ x.class == self.class && @f == x.f && @args == x.args
565
+ end
566
+
567
+ # Delegate the creation of the resulting SQL to the given dataset,
568
+ # since it may be database dependent.
569
+ def to_s(ds)
570
+ ds.function_sql(self)
571
+ end
572
+ end
573
+
574
+ # Represents an identifier (column or table). Can be used
575
+ # to specify a Symbol with multiple underscores should not be
576
+ # split, or for creating an identifier without using a symbol.
577
+ class Identifier < GenericExpression
578
+ include QualifyingMethods
579
+
580
+ # The table and column to reference
581
+ attr_reader :value
582
+
583
+ # Set the value to the given argument
584
+ def initialize(value)
585
+ @value = value
586
+ end
587
+
588
+ # Delegate the creation of the resulting SQL to the given dataset,
589
+ # since it may be database dependent.
590
+ def to_s(ds)
591
+ ds.quote_identifier(@value)
592
+ end
593
+ end
594
+
595
+ # IrregularFunction is used for the SQL EXTRACT function,
596
+ # which don't use regular function calling syntax. The IrregularFunction
597
+ # replaces the commas the regular function uses with a custom
598
+ # join string.
599
+ #
600
+ # This shouldn't be used directly, see
601
+ # ComplexExpressionMethods#extract.
602
+ class IrregularFunction < Function
603
+ # The arguments to pass to the function (may be blank)
604
+ attr_reader :arg1, :arg2
605
+
606
+ # The SQL function to call
607
+ attr_reader :f
608
+
609
+ # The literal string to use in place of a comma to join arguments
610
+ attr_reader :joiner
611
+
612
+ # Set the attributes to the given arguments
613
+ def initialize(f, arg1, joiner, arg2)
614
+ @f, @arg1, @joiner, @arg2 = f, arg1, joiner, arg2
615
+ end
616
+
617
+ # Delegate the creation of the resulting SQL to the given dataset,
618
+ # since it may be database dependent.
619
+ def to_s(ds)
620
+ ds.irregular_function_sql(self)
621
+ end
622
+ end
623
+
624
+ # Represents an SQL JOIN clause, used for joining tables.
625
+ class JoinClause < SpecificExpression
626
+ # The type of join to do
627
+ attr_reader :join_type
628
+
629
+ # The actual table to join
630
+ attr_reader :table
631
+
632
+ # The table alias to use for the join, if any
633
+ attr_reader :table_alias
634
+
635
+ # Create an object with the given conditions and
636
+ # default value.
637
+ def initialize(join_type, table, table_alias = nil)
638
+ @join_type, @table, @table_alias = join_type, table, table_alias
639
+ end
640
+
641
+ # Delegate the creation of the resulting SQL to the given dataset,
642
+ # since it may be database dependent.
643
+ def to_s(ds)
644
+ ds.join_clause_sql(self)
645
+ end
646
+ end
647
+
648
+ # Represents an SQL JOIN table ON conditions clause.
649
+ class JoinOnClause < JoinClause
650
+ # The conditions for the join
651
+ attr_reader :on
652
+
653
+ # Create an object with the given conditions and
654
+ # default value.
655
+ def initialize(on, *args)
656
+ @on = on
657
+ super(*args)
658
+ end
659
+
660
+ # Delegate the creation of the resulting SQL to the given dataset,
661
+ # since it may be database dependent.
662
+ def to_s(ds)
663
+ ds.join_on_clause_sql(self)
664
+ end
665
+ end
666
+
667
+ # Represents an SQL JOIN table USING (columns) clause.
668
+ class JoinUsingClause < JoinClause
669
+ # The columns that appear both tables that should be equal
670
+ # for the conditions to match.
671
+ attr_reader :using
672
+
673
+ # Create an object with the given conditions and
674
+ # default value.
675
+ def initialize(using, *args)
676
+ @using = using
677
+ super(*args)
678
+ end
679
+
680
+ # Delegate the creation of the resulting SQL to the given dataset,
681
+ # since it may be database dependent.
682
+ def to_s(ds)
683
+ ds.join_using_clause_sql(self)
684
+ end
685
+ end
686
+
687
+ # Represents a literal string with placeholders and arguments.
688
+ # This is necessary to ensure delayed literalization of the arguments
689
+ # required for the prepared statement support
690
+ class PlaceholderLiteralString < SpecificExpression
691
+ # The arguments that will be subsituted into the placeholders.
692
+ attr_reader :args
693
+
694
+ # The literal string containing placeholders
695
+ attr_reader :str
696
+
697
+ # Whether to surround the expression with parantheses
698
+ attr_reader :parens
699
+
700
+ # Create an object with the given conditions and
701
+ # default value.
702
+ def initialize(str, args, parens=false)
703
+ @str = str
704
+ @args = args
705
+ @parens = parens
706
+ end
707
+
708
+ # Delegate the creation of the resulting SQL to the given dataset,
709
+ # since it may be database dependent.
710
+ def to_s(ds)
711
+ ds.placeholder_literal_string_sql(self)
712
+ end
713
+ end
714
+
715
+ # Subclass of ComplexExpression where the expression results
716
+ # in a numeric value in SQL.
717
+ class NumericExpression < ComplexExpression
718
+ include BitwiseMethods
719
+ include NumericMethods
720
+ include InequalityMethods
721
+ include NoBooleanInputMethods
722
+ end
723
+
724
+ # Represents a column/expression to order the result set by.
725
+ class OrderedExpression < SpecificExpression
726
+ # The expression to order the result set by.
727
+ attr_reader :expression
728
+
729
+ # Whether the expression should order the result set in a descending manner
730
+ attr_reader :descending
731
+
732
+ # Set the expression and descending attributes to the given values.
733
+ def initialize(expression, descending = true)
734
+ @expression, @descending = expression, descending
735
+ end
736
+
737
+ # Delegate the creation of the resulting SQL to the given dataset,
738
+ # since it may be database dependent.
739
+ def to_s(ds)
740
+ ds.ordered_expression_sql(self)
741
+ end
742
+ end
743
+
744
+ # Represents a qualified (column with table) reference. Used when
745
+ # joining tables to disambiguate columns.
746
+ class QualifiedIdentifier < GenericExpression
747
+ # The table and column to reference
748
+ attr_reader :table, :column
749
+
750
+ # Set the attributes to the given arguments
751
+ def initialize(table, column)
752
+ @table, @column = table, column
753
+ end
754
+
755
+ # Delegate the creation of the resulting SQL to the given dataset,
756
+ # since it may be database dependent.
757
+ def to_s(ds)
758
+ ds.qualified_identifier_sql(self)
759
+ end
760
+ end
761
+
762
+ # Subclass of ComplexExpression where the expression results
763
+ # in a text/string/varchar value in SQL.
764
+ class StringExpression < ComplexExpression
765
+ include StringMethods
766
+ include StringConcatenationMethods
767
+ include InequalityMethods
768
+ include NoBooleanInputMethods
769
+
770
+ # Creates a SQL pattern match exprssion. left (l) is the SQL string we
771
+ # are matching against, and ces are the patterns we are matching.
772
+ # The match succeeds if any of the patterns match (SQL OR). Patterns
773
+ # can be given as strings or regular expressions. Strings will cause
774
+ # the SQL LIKE operator to be used, and should be supported by most
775
+ # databases. Regular expressions will probably only work on MySQL
776
+ # and PostgreSQL, and SQL regular expression syntax is not fully compatible
777
+ # with ruby regular expression syntax, so be careful if using regular
778
+ # expressions.
779
+ #
780
+ # The pattern match will be case insensitive if the last argument is a hash
781
+ # with a key of :case_insensitive that is not false or nil. Also,
782
+ # if a case insensitive regular expression is used (//i), that particular
783
+ # pattern which will always be case insensitive.
784
+ def self.like(l, *ces)
785
+ case_insensitive = ces.extract_options![:case_insensitive]
786
+ ces.collect! do |ce|
787
+ op, expr = Regexp === ce ? [ce.casefold? || case_insensitive ? :'~*' : :~, ce.source] : [case_insensitive ? :ILIKE : :LIKE, ce]
788
+ BooleanExpression.new(op, l, expr)
789
+ end
790
+ ces.length == 1 ? ces.at(0) : BooleanExpression.new(:OR, *ces)
791
+ end
792
+ end
793
+
794
+ # Represents an SQL array. Added so it is possible to deal with a
795
+ # ruby array of all two pairs as an SQL array instead of an ordered
796
+ # hash-like conditions specifier.
797
+ class SQLArray < Expression
798
+ # Create an object with the given array.
799
+ def initialize(array)
800
+ @array = array
801
+ end
802
+
803
+ # Delegate the creation of the resulting SQL to the given dataset,
804
+ # since it may be database dependent.
805
+ def to_s(ds)
806
+ ds.array_sql(@array)
807
+ end
808
+ end
809
+
810
+ # Represents an SQL array access, with multiple possible arguments.
811
+ class Subscript < GenericExpression
812
+ # The SQL array column
813
+ attr_reader :f
814
+
815
+ # The array of subscripts to use (should be an array of numbers)
816
+ attr_reader :sub
817
+
818
+ # Set the attributes to the given arguments
819
+ def initialize(f, sub)
820
+ @f, @sub = f, sub
821
+ end
822
+
823
+ # Create a new subscript appending the given subscript(s)
824
+ # the the current array of subscripts.
825
+ def |(sub)
826
+ Subscript.new(@f, @sub + Array(sub))
827
+ end
828
+
829
+ # Delegate the creation of the resulting SQL to the given dataset,
830
+ # since it may be database dependent.
831
+ def to_s(ds)
832
+ ds.subscript_sql(self)
833
+ end
834
+ end
835
+
836
+ if RUBY_VERSION >= '1.9.0'
837
+ class VirtualRow < BasicObject
838
+ end
839
+ else
840
+ class VirtualRow
841
+ (instance_methods - %w"__id__ __send__ instance_eval == equal?").each{|m| undef_method(m)}
842
+ end
843
+ end
844
+
845
+ # An instance of this class is yielded to the block supplied to filter.
846
+ # Useful if another library also defines the operator methods that
847
+ # Sequel defines for symbols.
848
+ #
849
+ # Examples:
850
+ #
851
+ # ds = DB[:t]
852
+ # ds.filter{|r| r.name < 2} # SELECT * FROM t WHERE (name < 2)
853
+ # ds.filter{|r| r.table__column + 1 < 2} # SELECT * FROM t WHERE ((table.column + 1) < 2)
854
+ # ds.filter{|r| r.is_active(1, 'arg2')} # SELECT * FROM t WHERE is_active(1, 'arg2')
855
+ class VirtualRow
856
+ # Can return Identifiers, QualifiedIdentifiers, or Functions:
857
+ #
858
+ # * Function - returned if any arguments are supplied, using the method name
859
+ # as the function name, and the arguments as the function arguments.
860
+ # * QualifiedIdentifier - returned if the method name contains __, with the
861
+ # table being the part before __, and the column being the part after.
862
+ # * Identifier - returned otherwise, using the method name.
863
+ def method_missing(m, *args)
864
+ if args.empty?
865
+ table, column = m.to_s.split('__', 2)
866
+ column ? QualifiedIdentifier.new(table, column) : Identifier.new(m)
867
+ else
868
+ Function.new(m, *args)
869
+ end
870
+ end
871
+ end
872
+ end
873
+
874
+ # LiteralString is used to represent literal SQL expressions. A
875
+ # LiteralString is copied verbatim into an SQL statement. Instances of
876
+ # LiteralString can be created by calling String#lit.
877
+ # LiteralStrings can also use all of the SQL::OrderMethods and the
878
+ # SQL::ComplexExpressionMethods.
879
+ class LiteralString < ::String
880
+ include SQL::OrderMethods
881
+ include SQL::ComplexExpressionMethods
882
+ include SQL::BooleanMethods
883
+ include SQL::NumericMethods
884
+ include SQL::StringMethods
885
+ include SQL::InequalityMethods
886
+ end
887
+ end