1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423
|
require 'time'
require 'date'
require 'yaml'
require 'base64'
require File.join(File.dirname(__FILE__), 'dataset/sql')
require File.join(File.dirname(__FILE__), 'dataset/sequelizer')
require File.join(File.dirname(__FILE__), 'dataset/convenience')
require File.join(File.dirname(__FILE__), 'dataset/callback')
require File.join(File.dirname(__FILE__), 'dataset/pagination')
module Sequel
# A Dataset represents a view of a the data in a database, constrained by
# specific parameters such as filtering conditions, order, etc. Datasets
# can be used to create, retrieve, update and delete records.
#
# Query results are always retrieved on demand, so a dataset can be kept
# around and reused indefinitely:
# my_posts = DB[:posts].filter(:author => 'david') # no records are retrieved
# p my_posts.all # records are now retrieved
# ...
# p my_posts.all # records are retrieved again
#
# In order to provide this functionality, dataset methods such as where,
# select, order, etc. return modified copies of the dataset, so you can
# use different datasets to access data:
# posts = DB[:posts]
# davids_posts = posts.filter(:author => 'david')
# old_posts = posts.filter('stamp < ?', Date.today - 7)
#
# Datasets are Enumerable objects, so they can be manipulated using any
# of the Enumerable methods, such as map, inject, etc.
#
# === The Dataset Adapter Interface
#
# Each adapter should define its own dataset class as a descendant of
# Sequel::Dataset. The following methods should be overriden by the adapter
# Dataset class (each method with the stock implementation):
#
# # Iterate over the results of the SQL query and call the supplied
# # block with each record (as a hash).
# def fetch_rows(sql, &block)
# @db.synchronize do
# r = @db.execute(sql)
# r.each(&block)
# end
# end
#
# # Insert records.
# def insert(*values)
# @db.synchronize do
# @db.execute(insert_sql(*values)).last_insert_id
# end
# end
#
# # Update records.
# def update(*args, &block)
# @db.synchronize do
# @db.execute(update_sql(*args, &block)).affected_rows
# end
# end
#
# # Delete records.
# def delete(opts = nil)
# @db.synchronize do
# @db.execute(delete_sql(opts)).affected_rows
# end
# end
class Dataset
include Enumerable
include Sequelizer
include SQL
include Convenience
include Callback
attr_accessor :db, :opts, :row_proc
alias_method :size, :count
# Returns an array with all records in the dataset. If a block is given,
# the array is iterated over.
def all(opts = nil, &block)
a = []
each(opts) {|r| a << r}
post_load(a)
a.each(&block) if block
a
end
# Constructs a new instance of a dataset with a database instance, initial
# options and an optional record class. Datasets are usually constructed by
# invoking Database methods:
# DB[:posts]
# Or:
# DB.dataset # the returned dataset is blank
#
# Sequel::Dataset is an abstract class that is not useful by itself. Each
# database adaptor should provide a descendant class of Sequel::Dataset.
def initialize(db, opts = nil)
@db = db
@opts = opts || {}
@row_proc = nil
@transform = nil
end
# Returns a new clone of the dataset with with the given options merged.
def clone(opts = {})
c = super()
c.opts = @opts.merge(opts)
c.instance_variable_set(:@columns, nil)
c
end
NOTIMPL_MSG = "This method must be overriden in Sequel adapters".freeze
# Executes a select query and fetches records, passing each record to the
# supplied block. Adapters should override this method.
def fetch_rows(sql, &block)
# @db.synchronize do
# r = @db.execute(sql)
# r.each(&block)
# end
raise NotImplementedError, NOTIMPL_MSG
end
# Inserts values into the associated table. Adapters should override this
# method.
def insert(*values)
# @db.synchronize do
# @db.execute(insert_sql(*values)).last_insert_id
# end
raise NotImplementedError, NOTIMPL_MSG
end
# Updates values for the dataset. Adapters should override this method.
def update(values, opts = nil)
# @db.synchronize do
# @db.execute(update_sql(values, opts)).affected_rows
# end
raise NotImplementedError, NOTIMPL_MSG
end
# Deletes the records in the dataset. Adapters should override this method.
def delete(opts = nil)
# @db.synchronize do
# @db.execute(delete_sql(opts)).affected_rows
# end
raise NotImplementedError, NOTIMPL_MSG
end
# Returns the columns in the result set in their true order. The stock
# implementation returns the content of @columns. If @columns is nil,
# a query is performed. Adapters are expected to fill @columns with the
# column information when a query is performed.
def columns
first unless @columns
@columns || []
end
def columns!
first
@columns || []
end
# Inserts the supplied values into the associated table.
def <<(*args)
insert(*args)
end
# Updates the dataset with the given values.
def set(*args, &block)
update(*args, &block)
end
# Iterates over the records in the dataset
def each(opts = nil, &block)
if graph = @opts[:graph]
graph_each(opts, &block)
else
row_proc = @row_proc unless opts && opts[:naked]
transform = @transform
fetch_rows(select_sql(opts)) do |r|
r = transform_load(r) if transform
r = row_proc[r] if row_proc
yield r
end
end
self
end
# Returns the the model classes associated with the dataset as a hash.
def model_classes
@opts[:models]
end
# Returns the column name for the polymorphic key.
def polymorphic_key
@opts[:polymorphic_key]
end
# Returns a naked dataset clone - i.e. a dataset that returns records as
# hashes rather than model objects.
def naked
d = clone(:naked => true, :models => nil, :polymorphic_key => nil)
d.set_model(nil)
d
end
# Associates or disassociates the dataset with a model. If no argument or
# nil is specified, the dataset is turned into a naked dataset and returns
# records as hashes. If a model class specified, the dataset is modified
# to return records as instances of the model class, e.g:
#
# class MyModel
# def initialize(values)
# @values = values
# ...
# end
# end
#
# dataset.set_model(MyModel)
#
# You can also provide additional arguments to be passed to the model's
# initialize method:
#
# class MyModel
# def initialize(values, options)
# @values = values
# ...
# end
# end
#
# dataset.set_model(MyModel, :allow_delete => false)
#
# The dataset can be made polymorphic by specifying a column name as the
# polymorphic key and a hash mapping column values to model classes.
#
# dataset.set_model(:kind, {1 => Person, 2 => Business})
#
# You can also set a default model class to fall back on by specifying a
# class corresponding to nil:
#
# dataset.set_model(:kind, {nil => DefaultClass, 1 => Person, 2 => Business})
#
# To disassociate a model from the dataset, you can call the #set_model
# and specify nil as the class:
#
# dataset.set_model(nil)
#
def set_model(key, *args)
# pattern matching
case key
when nil # set_model(nil) => no
# no argument provided, so the dataset is denuded
@opts.merge!(:naked => true, :models => nil, :polymorphic_key => nil)
self.row_proc = nil
# extend_with_stock_each
when Class
# isomorphic model
@opts.merge!(:naked => nil, :models => {nil => key}, :polymorphic_key => nil)
if key.respond_to?(:load)
# the class has a values setter method, so we use it
self.row_proc = proc{|h| key.load(h, *args)}
else
# otherwise we just pass the hash to the constructor
self.row_proc = proc{|h| key.new(h, *args)}
end
extend_with_destroy
when Symbol
# polymorphic model
hash = args.shift || raise(ArgumentError, "No class hash supplied for polymorphic model")
@opts.merge!(:naked => true, :models => hash, :polymorphic_key => key)
if hash.values.first.respond_to?(:load)
# the class has a values setter method, so we use it
self.row_proc = proc do |h|
c = hash[h[key]] || hash[nil] || \
raise(Error, "No matching model class for record (#{polymorphic_key} => #{h[polymorphic_key].inspect})")
c.load(h, *args)
end
else
# otherwise we just pass the hash to the constructor
self.row_proc = proc do |h|
c = hash[h[key]] || hash[nil] || \
raise(Error, "No matching model class for record (#{polymorphic_key} => #{h[polymorphic_key].inspect})")
c.new(h, *args)
end
end
extend_with_destroy
else
raise ArgumentError, "Invalid model specified"
end
self
end
STOCK_TRANSFORMS = {
:marshal => [
# for backwards-compatibility we support also non-base64-encoded values.
proc {|v| Marshal.load(Base64.decode64(v)) rescue Marshal.load(v)},
proc {|v| Base64.encode64(Marshal.dump(v))}
],
:yaml => [
proc {|v| YAML.load v if v},
proc {|v| v.to_yaml}
]
}
# Sets a value transform which is used to convert values loaded and saved
# to/from the database. The transform should be supplied as a hash. Each
# value in the hash should be an array containing two proc objects - one
# for transforming loaded values, and one for transforming saved values.
# The following example demonstrates how to store Ruby objects in a dataset
# using Marshal serialization:
#
# dataset.transform(:obj => [
# proc {|v| Marshal.load(v)},
# proc {|v| Marshal.dump(v)}
# ])
#
# dataset.insert_sql(:obj => 1234) #=>
# "INSERT INTO items (obj) VALUES ('\004\bi\002\322\004')"
#
# Another form of using transform is by specifying stock transforms:
#
# dataset.transform(:obj => :marshal)
#
# The currently supported stock transforms are :marshal and :yaml.
def transform(t)
@transform = t
t.each do |k, v|
case v
when Array
if (v.size != 2) || !v.first.is_a?(Proc) && !v.last.is_a?(Proc)
raise Error::InvalidTransform, "Invalid transform specified"
end
else
unless v = STOCK_TRANSFORMS[v]
raise Error::InvalidTransform, "Invalid transform specified"
else
t[k] = v
end
end
end
self
end
# Applies the value transform for data loaded from the database.
def transform_load(r)
r.inject({}) do |m, kv|
k, v = *kv
m[k] = (tt = @transform[k]) ? tt[0][v] : v
m
end
end
# Applies the value transform for data saved to the database.
def transform_save(r)
r.inject({}) do |m, kv|
k, v = *kv
m[k] = (tt = @transform[k]) ? tt[1][v] : v
m
end
end
# Extends the dataset with a destroy method, that calls destroy for each
# record in the dataset.
def extend_with_destroy
unless respond_to?(:destroy)
meta_def(:destroy) do
unless @opts[:models]
raise Error, "No model associated with this dataset"
end
count = 0
@db.transaction {each {|r| count += 1; r.destroy}}
count
end
end
end
@@dataset_classes = []
def self.dataset_classes #:nodoc:
@@dataset_classes
end
def self.inherited(c) #:nodoc:
@@dataset_classes << c
end
# Returns a string representation of the dataset including the class name
# and the corresponding SQL select statement.
def inspect
'#<%s: %s>' % [self.class.to_s, sql.inspect]
end
# Setup mutation (e.g. filter!) methods
def self.def_mutation_method(*meths)
meths.each do |meth|
class_eval("def #{meth}!(*args, &block); mutation_method(:#{meth}, *args, &block) end")
end
end
def def_mutation_method(*meths)
meths.each do |meth|
instance_eval("def #{meth}!(*args, &block); mutation_method(:#{meth}, *args, &block) end")
end
end
MUTATION_METHODS = %w'and distinct exclude exists filter from from_self full_outer_join graph
group group_and_count group_by having inner_join intersect invert_order join
left_outer_join limit naked or order order_by order_more paginate query reject
reverse reverse_order right_outer_join select select_all select_more
set_graph_aliases set_model sort sort_by union unordered where'.collect{|x| x.to_sym}
def_mutation_method(*MUTATION_METHODS)
private
def mutation_method(meth, *args, &block)
copy = send(meth, *args, &block)
@opts.merge!(copy.opts)
self
end
end
end
|