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,258 @@
1
+ # A ConnectionPool manages access to database connections by keeping
2
+ # multiple connections and giving threads exclusive access to each
3
+ # connection.
4
+ class Sequel::ConnectionPool
5
+ # The proc used to create a new database connection.
6
+ attr_accessor :connection_proc
7
+
8
+ # The proc used to disconnect a database connection.
9
+ attr_accessor :disconnection_proc
10
+
11
+ # The maximum number of connections.
12
+ attr_reader :max_size
13
+
14
+ # The mutex that protects access to the other internal vairables. You must use
15
+ # this if you want to manipulate the variables safely.
16
+ attr_reader :mutex
17
+
18
+ # Constructs a new pool with a maximum size. If a block is supplied, it
19
+ # is used to create new connections as they are needed.
20
+ #
21
+ # pool = ConnectionPool.new(:max_connections=>10) {MyConnection.new(opts)}
22
+ #
23
+ # The connection creation proc can be changed at any time by assigning a
24
+ # Proc to pool#connection_proc.
25
+ #
26
+ # pool = ConnectionPool.new(:max_connections=>10)
27
+ # pool.connection_proc = proc {MyConnection.new(opts)}
28
+ #
29
+ # The connection pool takes the following options:
30
+ #
31
+ # * :max_connections - The maximum number of connections the connection pool
32
+ # will open (default 4)
33
+ # * :pool_convert_exceptions - Whether to convert non-StandardError based exceptions
34
+ # to RuntimeError exceptions (default true)
35
+ # * :pool_sleep_time - The amount of time to sleep before attempting to acquire
36
+ # a connection again (default 0.001)
37
+ # * :pool_timeout - The amount of seconds to wait to acquire a connection
38
+ # before raising a PoolTimeoutError (default 5)
39
+ # * :servers - A hash of servers to use. Keys should be symbols. If not
40
+ # present, will use a single :default server. The server name symbol will
41
+ # be passed to the connection_proc.
42
+ def initialize(opts = {}, &block)
43
+ @max_size = opts[:max_connections] || 4
44
+ @mutex = Mutex.new
45
+ @connection_proc = block
46
+ @disconnection_proc = opts[:disconnection_proc]
47
+ @servers = [:default]
48
+ @servers += opts[:servers].keys - @servers if opts[:servers]
49
+ @available_connections = Hash.new{|h,k| h[:default]}
50
+ @allocated = Hash.new{|h,k| h[:default]}
51
+ @created_count = Hash.new{|h,k| h[:default]}
52
+ @servers.each do |s|
53
+ @available_connections[s] = []
54
+ @allocated[s] = {}
55
+ @created_count[s] = 0
56
+ end
57
+ @timeout = opts[:pool_timeout] || 5
58
+ @sleep_time = opts[:pool_sleep_time] || 0.001
59
+ @convert_exceptions = opts.include?(:pool_convert_exceptions) ? opts[:pool_convert_exceptions] : true
60
+ end
61
+
62
+ # A hash of connections currently being used for the given server, key is the
63
+ # Thread, value is the connection.
64
+ def allocated(server=:default)
65
+ @allocated[server]
66
+ end
67
+
68
+ # An array of connections opened but not currently used, for the given
69
+ # server.
70
+ def available_connections(server=:default)
71
+ @available_connections[server]
72
+ end
73
+
74
+ # The total number of connections opened for the given server, should
75
+ # be equal to available_connections.length + allocated.length
76
+ def created_count(server=:default)
77
+ @created_count[server]
78
+ end
79
+ alias size created_count
80
+
81
+ # Chooses the first available connection to the given server, or if none are
82
+ # available, creates a new connection. Passes the connection to the supplied
83
+ # block:
84
+ #
85
+ # pool.hold {|conn| conn.execute('DROP TABLE posts')}
86
+ #
87
+ # Pool#hold is re-entrant, meaning it can be called recursively in
88
+ # the same thread without blocking.
89
+ #
90
+ # If no connection is immediately available and the pool is already using the maximum
91
+ # number of connections, Pool#hold will block until a connection
92
+ # is available or the timeout expires. If the timeout expires before a
93
+ # connection can be acquired, a Sequel::Error::PoolTimeoutError is
94
+ # raised.
95
+ def hold(server=:default)
96
+ begin
97
+ t = Thread.current
98
+ time = Time.new
99
+ timeout = time + @timeout
100
+ sleep_time = @sleep_time
101
+ if conn = owned_connection(t, server)
102
+ return yield(conn)
103
+ end
104
+ until conn = acquire(t, server)
105
+ raise(::Sequel::Error::PoolTimeoutError) if Time.new > timeout
106
+ sleep sleep_time
107
+ end
108
+ begin
109
+ yield conn
110
+ rescue Sequel::DatabaseDisconnectError => dde
111
+ remove(t, conn, server)
112
+ raise
113
+ ensure
114
+ release(t, conn, server) unless dde
115
+ end
116
+ rescue Exception => e
117
+ raise(@convert_exceptions && !e.is_a?(StandardError) ? RuntimeError.new(e.message) : e)
118
+ end
119
+ end
120
+
121
+ # Removes all connection currently available on all servers, optionally
122
+ # yielding each connection to the given block. This method has the effect of
123
+ # disconnecting from the database, assuming that no connections are currently
124
+ # being used. Once a connection is requested using #hold, the connection pool
125
+ # creates new connections to the database.
126
+ def disconnect(&block)
127
+ block ||= @disconnection_proc
128
+ @mutex.synchronize do
129
+ @available_connections.each do |server, conns|
130
+ conns.each{|c| block.call(c)} if block
131
+ conns.clear
132
+ set_created_count(server, allocated(server).length)
133
+ end
134
+ end
135
+ end
136
+
137
+ private
138
+
139
+ # Assigns a connection to the supplied thread for the given server, if one
140
+ # is available.
141
+ def acquire(thread, server)
142
+ @mutex.synchronize do
143
+ if conn = available(server)
144
+ allocated(server)[thread] = conn
145
+ end
146
+ end
147
+ end
148
+
149
+ # Returns an available connection to the given server. If no connection is
150
+ # available, tries to create a new connection.
151
+ def available(server)
152
+ available_connections(server).pop || make_new(server)
153
+ end
154
+
155
+ # Creates a new connection to the given server if the size of the pool for
156
+ # the server is less than the maximum size of the pool.
157
+ def make_new(server)
158
+ if @created_count[server] < @max_size
159
+ raise(Sequel::Error, "No connection proc specified") unless @connection_proc
160
+ begin
161
+ conn = @connection_proc.call(server)
162
+ rescue Exception=>exception
163
+ e = Sequel::DatabaseConnectionError.new("#{exception.class} #{exception.message}")
164
+ e.set_backtrace(exception.backtrace)
165
+ raise e
166
+ end
167
+ raise(Sequel::DatabaseConnectionError, "Connection parameters not valid") unless conn
168
+ set_created_count(server, @created_count[server] + 1)
169
+ conn
170
+ end
171
+ end
172
+
173
+ # Returns the connection owned by the supplied thread for the given server,
174
+ # if any.
175
+ def owned_connection(thread, server)
176
+ @mutex.synchronize{@allocated[server][thread]}
177
+ end
178
+
179
+ # Releases the connection assigned to the supplied thread and server.
180
+ def release(thread, conn, server)
181
+ @mutex.synchronize do
182
+ allocated(server).delete(thread)
183
+ available_connections(server) << conn
184
+ end
185
+ end
186
+
187
+ # Removes the currently allocated connection from the connection pool.
188
+ def remove(thread, conn, server)
189
+ @mutex.synchronize do
190
+ allocated(server).delete(thread)
191
+ set_created_count(server, @created_count[server] - 1)
192
+ @disconnection_proc.call(conn) if @disconnection_proc
193
+ end
194
+ end
195
+
196
+ # Set the created count for the given server type
197
+ def set_created_count(server, value)
198
+ server = :default unless @created_count.include?(server)
199
+ @created_count[server] = value
200
+ end
201
+ end
202
+
203
+ # A SingleThreadedPool acts as a replacement for a ConnectionPool for use
204
+ # in single-threaded applications. ConnectionPool imposes a substantial
205
+ # performance penalty, so SingleThreadedPool is used to gain some speed.
206
+ #
207
+ # Note that using a single threaded pool with some adapters can cause
208
+ # errors in certain cases, see Sequel.single_threaded=.
209
+ class Sequel::SingleThreadedPool
210
+ # The proc used to create a new database connection
211
+ attr_writer :connection_proc
212
+
213
+ # The proc used to disconnect a database connection.
214
+ attr_accessor :disconnection_proc
215
+
216
+ # Initializes the instance with the supplied block as the connection_proc.
217
+ #
218
+ # The single threaded pool takes the following options:
219
+ #
220
+ # * :pool_convert_exceptions - Whether to convert non-StandardError based exceptions
221
+ # to RuntimeError exceptions (default true)
222
+ def initialize(opts={}, &block)
223
+ @connection_proc = block
224
+ @disconnection_proc = opts[:disconnection_proc]
225
+ @conns = {}
226
+ @convert_exceptions = opts.include?(:pool_convert_exceptions) ? opts[:pool_convert_exceptions] : true
227
+ end
228
+
229
+ # The connection for the given server.
230
+ def conn(server=:default)
231
+ @conns[server]
232
+ end
233
+
234
+ # Yields the connection to the supplied block for the given server.
235
+ # This method simulates the ConnectionPool#hold API.
236
+ def hold(server=:default)
237
+ begin
238
+ begin
239
+ yield(c = (@conns[server] ||= @connection_proc.call(server)))
240
+ rescue Sequel::DatabaseDisconnectError => dde
241
+ @conns.delete(server)
242
+ @disconnection_proc.call(c) if @disconnection_proc
243
+ raise
244
+ end
245
+ rescue Exception => e
246
+ # if the error is not a StandardError it is converted into RuntimeError.
247
+ raise(@convert_exceptions && !e.is_a?(StandardError) ? RuntimeError.new(e.message) : e)
248
+ end
249
+ end
250
+
251
+ # Disconnects from the database. Once a connection is requested using
252
+ # #hold, the connection is reestablished.
253
+ def disconnect(&block)
254
+ block ||= @disconnection_proc
255
+ @conns.values.each{|conn| block.call(conn) if block}
256
+ @conns = {}
257
+ end
258
+ end
@@ -0,0 +1,217 @@
1
+ if RUBY_VERSION < '1.9.0'
2
+ class Hash
3
+ alias key index
4
+ end
5
+ end
6
+
7
+ class Array
8
+ # True if the array is not empty and all of its elements are
9
+ # arrays of size 2. This is used to determine if the array
10
+ # could be a specifier of conditions, used similarly to a hash
11
+ # but allowing for duplicate keys.
12
+ #
13
+ # hash.to_a.all_two_pairs? # => true unless hash is empty
14
+ def all_two_pairs?
15
+ !empty? && all?{|i| (Array === i) && (i.length == 2)}
16
+ end
17
+
18
+ # Removes and returns the last member of the array if it is a hash. Otherwise,
19
+ # an empty hash is returned This method is useful when writing methods that
20
+ # take an options hash as the last parameter. For example:
21
+ #
22
+ # def validate_each(*args, &block)
23
+ # opts = args.extract_options!
24
+ # ...
25
+ # end
26
+ def extract_options!
27
+ last.is_a?(Hash) ? pop : {}
28
+ end
29
+ end
30
+
31
+ module Enumerable
32
+ # Invokes the specified method for each item, along with the supplied
33
+ # arguments.
34
+ def send_each(sym, *args)
35
+ each{|i| i.send(sym, *args)}
36
+ end
37
+ end
38
+
39
+ class FalseClass
40
+ # false is always blank
41
+ def blank?
42
+ true
43
+ end
44
+ end
45
+
46
+ # Add some metaprogramming methods to avoid class << self
47
+ class Module
48
+ # Defines an instance method within a class/module
49
+ def class_def(name, &block)
50
+ class_eval{define_method(name, &block)}
51
+ end
52
+
53
+ private
54
+
55
+ # Define instance method(s) that calls class method(s) of the
56
+ # same name, caching the result in an instance variable. Define
57
+ # standard attr_writer method for modifying that instance variable
58
+ def class_attr_overridable(*meths)
59
+ meths.each{|meth| class_eval("def #{meth}; !defined?(@#{meth}) ? (@#{meth} = self.class.#{meth}) : @#{meth} end")}
60
+ attr_writer(*meths)
61
+ public(*meths)
62
+ public(*meths.collect{|m|"#{m}="})
63
+ end
64
+
65
+ # Define instance method(s) that calls class method(s) of the
66
+ # same name. Replaces the construct:
67
+ #
68
+ # define_method(meth){self.class.send(meth)}
69
+ def class_attr_reader(*meths)
70
+ meths.each{|meth| define_method(meth){self.class.send(meth)}}
71
+ end
72
+
73
+ # Create an alias for a singleton/class method.
74
+ # Replaces the construct:
75
+ #
76
+ # class << self
77
+ # alias_method to, from
78
+ # end
79
+ def metaalias(to, from)
80
+ meta_eval{alias_method to, from}
81
+ end
82
+
83
+ # Make a singleton/class attribute accessor method(s).
84
+ # Replaces the construct:
85
+ #
86
+ # class << self
87
+ # attr_accessor *meths
88
+ # end
89
+ def metaattr_accessor(*meths)
90
+ meta_eval{attr_accessor(*meths)}
91
+ end
92
+
93
+ # Make a singleton/class method(s) private.
94
+ # Make a singleton/class attribute reader method(s).
95
+ # Replaces the construct:
96
+ #
97
+ # class << self
98
+ # attr_reader *meths
99
+ # end
100
+ def metaattr_reader(*meths)
101
+ meta_eval{attr_reader(*meths)}
102
+ end
103
+ end
104
+
105
+ # Helpers from Metaid and a bit more
106
+ class Object
107
+ # Objects are blank if they respond true to empty?
108
+ def blank?
109
+ respond_to?(:empty?) && empty?
110
+ end
111
+
112
+ # Returns true if the object is an instance of one of the classes
113
+ def is_one_of?(*classes)
114
+ !!classes.find{|c| is_a?(c)}
115
+ end
116
+
117
+ # Add methods to the object's metaclass
118
+ def meta_def(name, &block)
119
+ meta_eval{define_method(name, &block)}
120
+ end
121
+
122
+ # Evaluate the block in the context of the object's metaclass
123
+ def meta_eval(&block)
124
+ metaclass.instance_eval(&block)
125
+ end
126
+
127
+ # The hidden singleton lurks behind everyone
128
+ def metaclass
129
+ class << self
130
+ self
131
+ end
132
+ end
133
+ end
134
+
135
+ class NilClass
136
+ # nil is always blank
137
+ def blank?
138
+ true
139
+ end
140
+ end
141
+
142
+ class Numeric
143
+ # Numerics are never blank (not even 0)
144
+ def blank?
145
+ false
146
+ end
147
+ end
148
+
149
+ class Range
150
+ # Returns the interval between the beginning and end of the range.
151
+ #
152
+ # For exclusive ranges, is one less than the inclusive range:
153
+ #
154
+ # (0..10).interval # => 10
155
+ # (0...10).interval # => 9
156
+ #
157
+ # Only works for numeric ranges, for other ranges the result is undefined,
158
+ # and the method may raise an error.
159
+ def interval
160
+ last - first - (exclude_end? ? 1 : 0)
161
+ end
162
+ end
163
+
164
+ class String
165
+ # Strings are blank if they are empty or include only whitespace
166
+ def blank?
167
+ strip.empty?
168
+ end
169
+
170
+ # Converts a string into a Date object.
171
+ def to_date
172
+ begin
173
+ Date.parse(self, Sequel.convert_two_digit_years)
174
+ rescue => e
175
+ raise Sequel::Error::InvalidValue, "Invalid Date value '#{self}' (#{e.message})"
176
+ end
177
+ end
178
+
179
+ # Converts a string into a DateTime object.
180
+ def to_datetime
181
+ begin
182
+ DateTime.parse(self, Sequel.convert_two_digit_years)
183
+ rescue => e
184
+ raise Sequel::Error::InvalidValue, "Invalid DateTime value '#{self}' (#{e.message})"
185
+ end
186
+ end
187
+
188
+ # Converts a string into a Time or DateTime object, depending on the
189
+ # value of Sequel.datetime_class
190
+ def to_sequel_time
191
+ begin
192
+ if Sequel.datetime_class == DateTime
193
+ DateTime.parse(self, Sequel.convert_two_digit_years)
194
+ else
195
+ Sequel.datetime_class.parse(self)
196
+ end
197
+ rescue => e
198
+ raise Sequel::Error::InvalidValue, "Invalid #{Sequel.datetime_class} value '#{self}' (#{e.message})"
199
+ end
200
+ end
201
+
202
+ # Converts a string into a Time object.
203
+ def to_time
204
+ begin
205
+ Time.parse(self)
206
+ rescue => e
207
+ raise Sequel::Error::InvalidValue, "Invalid Time value '#{self}' (#{e.message})"
208
+ end
209
+ end
210
+ end
211
+
212
+ class TrueClass
213
+ # true is never blank
214
+ def blank?
215
+ false
216
+ end
217
+ end
@@ -0,0 +1,202 @@
1
+ class Array
2
+ # Return a Sequel::SQL::BooleanExpression created from this array, not matching any of the
3
+ # conditions.
4
+ def ~
5
+ sql_expr_if_all_two_pairs(:OR, true)
6
+ end
7
+
8
+ # Return a Sequel::SQL::CaseExpression with this array as the conditions and the given
9
+ # default value.
10
+ def case(default, expression = nil)
11
+ ::Sequel::SQL::CaseExpression.new(self, default, expression)
12
+ end
13
+
14
+ # Return a Sequel::SQL::Array created from this array. Used if this array contains
15
+ # all two pairs and you want it treated as an SQL array instead of a ordered hash-like
16
+ # conditions.
17
+ def sql_array
18
+ ::Sequel::SQL::SQLArray.new(self)
19
+ end
20
+
21
+ # Return a Sequel::SQL::BooleanExpression created from this array, matching all of the
22
+ # conditions.
23
+ def sql_expr
24
+ sql_expr_if_all_two_pairs
25
+ end
26
+
27
+ # Return a Sequel::SQL::BooleanExpression created from this array, matching none
28
+ # of the conditions.
29
+ def sql_negate
30
+ sql_expr_if_all_two_pairs(:AND, true)
31
+ end
32
+
33
+ # Return a Sequel::SQL::BooleanExpression created from this array, matching any of the
34
+ # conditions.
35
+ def sql_or
36
+ sql_expr_if_all_two_pairs(:OR)
37
+ end
38
+
39
+ # Return a Sequel::SQL::BooleanExpression representing an SQL string made up of the
40
+ # concatenation of this array's elements. If an argument is passed
41
+ # it is used in between each element of the array in the SQL
42
+ # concatenation.
43
+ def sql_string_join(joiner=nil)
44
+ if joiner
45
+ args = self.inject([]) do |m, a|
46
+ m << a
47
+ m << joiner
48
+ end
49
+ args.pop
50
+ else
51
+ args = self
52
+ end
53
+ args = args.collect{|a| a.is_one_of?(Symbol, ::Sequel::SQL::Expression, ::Sequel::LiteralString, TrueClass, FalseClass, NilClass) ? a : a.to_s}
54
+ ::Sequel::SQL::StringExpression.new(:'||', *args)
55
+ end
56
+
57
+ # Concatenates an array of strings into an SQL string. ANSI SQL and C-style
58
+ # comments are removed, as well as excessive white-space.
59
+ def to_sql
60
+ map {|l| ((m = /^(.*)--/.match(l)) ? m[1] : l).chomp}.join(' '). \
61
+ gsub(/\/\*.*\*\//, '').gsub(/\s+/, ' ').strip
62
+ end
63
+
64
+ private
65
+
66
+ # Raise an error if this array is not made up of all two pairs, otherwise create a Sequel::SQL::BooleanExpression from this array.
67
+ def sql_expr_if_all_two_pairs(*args)
68
+ raise(Sequel::Error, 'Not all elements of the array are arrays of size 2, so it cannot be converted to an SQL expression') unless all_two_pairs?
69
+ ::Sequel::SQL::BooleanExpression.from_value_pairs(self, *args)
70
+ end
71
+ end
72
+
73
+ class Hash
74
+ # Return a Sequel::SQL::BooleanExpression created from this hash, matching
75
+ # all of the conditions in this hash and the condition specified by
76
+ # the given argument.
77
+ def &(ce)
78
+ ::Sequel::SQL::BooleanExpression.new(:AND, self, ce)
79
+ end
80
+
81
+ # Return a Sequel::SQL::BooleanExpression created from this hash, matching
82
+ # all of the conditions in this hash or the condition specified by
83
+ # the given argument.
84
+ def |(ce)
85
+ ::Sequel::SQL::BooleanExpression.new(:OR, self, ce)
86
+ end
87
+
88
+ # Return a Sequel::SQL::BooleanExpression created from this hash, not matching any of the
89
+ # conditions.
90
+ def ~
91
+ ::Sequel::SQL::BooleanExpression.from_value_pairs(self, :OR, true)
92
+ end
93
+
94
+ # Return a Sequel::SQL::CaseExpression with this hash as the conditions and the given
95
+ # default value. Note that the order of the conditions will be arbitrary, so all
96
+ # conditions should be orthogonal.
97
+ def case(default, expression = nil)
98
+ ::Sequel::SQL::CaseExpression.new(to_a, default, expression)
99
+ end
100
+
101
+ # Return a Sequel::SQL::BooleanExpression created from this hash, matching all of the
102
+ # conditions.
103
+ def sql_expr
104
+ ::Sequel::SQL::BooleanExpression.from_value_pairs(self)
105
+ end
106
+
107
+ # Return a Sequel::SQL::BooleanExpression created from this hash, matching none
108
+ # of the conditions.
109
+ def sql_negate
110
+ ::Sequel::SQL::BooleanExpression.from_value_pairs(self, :AND, true)
111
+ end
112
+
113
+ # Return a Sequel::SQL::BooleanExpression created from this hash, matching any of the
114
+ # conditions.
115
+ def sql_or
116
+ ::Sequel::SQL::BooleanExpression.from_value_pairs(self, :OR)
117
+ end
118
+ end
119
+
120
+ class String
121
+ include Sequel::SQL::AliasMethods
122
+ include Sequel::SQL::CastMethods
123
+
124
+ # Converts a string into an LiteralString, in order to override string
125
+ # literalization, e.g.:
126
+ #
127
+ # DB[:items].filter(:abc => 'def').sql #=>
128
+ # "SELECT * FROM items WHERE (abc = 'def')"
129
+ #
130
+ # DB[:items].filter(:abc => 'def'.lit).sql #=>
131
+ # "SELECT * FROM items WHERE (abc = def)"
132
+ #
133
+ def lit
134
+ Sequel::LiteralString.new(self)
135
+ end
136
+ alias_method :expr, :lit
137
+
138
+ # Splits a string into separate SQL statements, removing comments
139
+ # and excessive white-space.
140
+ def split_sql
141
+ to_sql.split(';').map {|s| s.strip}
142
+ end
143
+
144
+ # Converts a string into an SQL string by removing comments.
145
+ # See also Array#to_sql.
146
+ def to_sql
147
+ split("\n").to_sql
148
+ end
149
+
150
+ # Returns a Blob that holds the same data as this string. Blobs provide proper
151
+ # escaping of binary data.
152
+ def to_sequel_blob
153
+ ::Sequel::SQL::Blob.new self
154
+ end
155
+ alias to_blob to_sequel_blob
156
+ end
157
+
158
+ class Symbol
159
+ include Sequel::SQL::QualifyingMethods
160
+ include Sequel::SQL::IdentifierMethods
161
+ include Sequel::SQL::AliasMethods
162
+ include Sequel::SQL::CastMethods
163
+ include Sequel::SQL::OrderMethods
164
+ include Sequel::SQL::BooleanMethods
165
+ include Sequel::SQL::NumericMethods
166
+ include Sequel::SQL::StringMethods
167
+ include Sequel::SQL::ComplexExpressionMethods
168
+ include Sequel::SQL::InequalityMethods if RUBY_VERSION < '1.9.0'
169
+
170
+ # If no argument is given, returns a Sequel::SQL::ColumnAll object specifying all
171
+ # columns for this table.
172
+ # If an argument is given, returns a Sequel::SQL::NumericExpression using the *
173
+ # (multiplication) operator with this and the given argument.
174
+ def *(ce=(arg=false;nil))
175
+ return super(ce) unless arg == false
176
+ Sequel::SQL::ColumnAll.new(self);
177
+ end
178
+
179
+ # Returns a Sequel::SQL::Function with this as the function name,
180
+ # and the given arguments. This is aliased as Symbol#[] if ruby 1.9
181
+ # is not being used. ruby 1.9 includes Symbol#[], and Sequel
182
+ # doesn't override methods defined by ruby itself.
183
+ def sql_function(*args)
184
+ Sequel::SQL::Function.new(self, *args)
185
+ end
186
+ alias_method(:[], :sql_function) if RUBY_VERSION < '1.9.0'
187
+
188
+ # If the given argument is an Integer or an array containing an Integer, returns
189
+ # a Sequel::SQL::Subscript with this column and the given arg.
190
+ # Otherwise returns a Sequel::SQL::BooleanExpression where this column (which should be boolean)
191
+ # or the given argument is true.
192
+ def |(sub)
193
+ return super unless (Integer === sub) || ((Array === sub) && sub.any?{|x| Integer === x})
194
+ Sequel::SQL::Subscript.new(self, Array(sub))
195
+ end
196
+
197
+ # Delegate the creation of the resulting SQL to the given dataset,
198
+ # since it may be database dependent.
199
+ def to_column_ref(ds)
200
+ ds.symbol_to_column_ref(self)
201
+ end
202
+ end