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.
Some methods are added via metaprogramming:
COLUMN_CHANGE_OPTS | = | [:select, :sql, :from, :join].freeze | The dataset options that require the removal of cached columns if changed. | |
DATASET_CLASSES | = | [] | Array of all subclasses of Dataset | |
MUTATION_METHODS | = | %w'add_graph_aliases and distinct exclude exists filter from from_self full_outer_join graph group group_and_count group_by having inner_join intersect invert 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_defaults set_graph_aliases set_model set_overrides sort sort_by unfiltered union unordered where'.collect{|x| x.to_sym} | All methods that should have a ! method added that modifies the receiver. | |
NOTIMPL_MSG | = | "This method must be overridden in Sequel adapters".freeze | ||
STOCK_TRANSFORMS | = | { :marshal => [ # for backwards-compatibility we support also non-base64-encoded values. proc {|v| Marshal.load(v.unpack('m')[0]) rescue Marshal.load(v)}, proc {|v| [Marshal.dump(v)].pack('m')} | ||
COMMA_SEPARATOR | = | ', '.freeze | ||
COUNT_OF_ALL_AS_COUNT | = | SQL::Function.new(:count, '*'.lit).as(:count) | ||
PREPARED_ARG_PLACEHOLDER | = | '?'.lit.freeze | ||
AND_SEPARATOR | = | " AND ".freeze | ||
BOOL_FALSE | = | "'f'".freeze | ||
BOOL_TRUE | = | "'t'".freeze | ||
COLUMN_REF_RE1 | = | /\A([\w ]+)__([\w ]+)___([\w ]+)\z/.freeze | ||
COLUMN_REF_RE2 | = | /\A([\w ]+)___([\w ]+)\z/.freeze | ||
COLUMN_REF_RE3 | = | /\A([\w ]+)__([\w ]+)\z/.freeze | ||
COUNT_FROM_SELF_OPTS | = | [:distinct, :group, :sql, :limit, :compounds] | ||
DATE_FORMAT | = | "DATE '%Y-%m-%d'".freeze | ||
N_ARITY_OPERATORS | = | ::Sequel::SQL::ComplexExpression::N_ARITY_OPERATORS | ||
NULL | = | "NULL".freeze | ||
QUESTION_MARK | = | '?'.freeze | ||
STOCK_COUNT_OPTS | = | {:select => ["COUNT(*)".lit], :order => nil}.freeze | ||
SELECT_CLAUSE_ORDER | = | %w'distinct columns from join where group having compounds order limit'.freeze | ||
TIMESTAMP_FORMAT | = | "TIMESTAMP '%Y-%m-%d %H:%M:%S'".freeze | ||
TWO_ARITY_OPERATORS | = | ::Sequel::SQL::ComplexExpression::TWO_ARITY_OPERATORS | ||
WILDCARD | = | '*'.freeze |
inner_join | -> | join |
db | [RW] | The database that corresponds to this dataset |
identifier_input_method | [RW] | Set the method to call on identifiers going into the database for this dataset |
identifier_output_method | [RW] | Set the method to call on identifiers coming the database for this dataset |
opts | [RW] | The hash of options for this dataset, keys are symbols. |
quote_identifiers | [W] | Whether to quote identifiers for this dataset |
row_proc | [RW] | The row_proc for this database, should be a Proc that takes a single hash argument and returns the object you want to fetch_rows to return. |
The array of dataset subclasses.
# File lib/sequel_core/dataset.rb, line 116 116: def self.dataset_classes 117: DATASET_CLASSES 118: end
Setup mutation (e.g. filter!) methods. These operate the same as the non-! methods, but replace the options of the current dataset with the options of the resulting dataset.
# File lib/sequel_core/dataset.rb, line 123 123: def self.def_mutation_method(*meths) 124: meths.each do |meth| 125: class_eval("def #{meth}!(*args, &block); mutation_method(:#{meth}, *args, &block) end") 126: end 127: end
Add the subclass to the array of subclasses.
# File lib/sequel_core/dataset.rb, line 130 130: def self.inherited(c) 131: DATASET_CLASSES << c 132: end
Constructs a new instance of a dataset with an associated database and options. 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.
# File lib/sequel_core/dataset.rb, line 103 103: def initialize(db, opts = nil) 104: @db = db 105: @quote_identifiers = db.quote_identifiers? if db.respond_to?(:quote_identifiers?) 106: @identifier_input_method = db.identifier_input_method if db.respond_to?(:identifier_input_method) 107: @identifier_output_method = db.identifier_output_method if db.respond_to?(:identifier_output_method) 108: @opts = opts || {} 109: @row_proc = nil 110: @transform = nil 111: end
Adds the give graph aliases to the list of graph aliases to use, unlike set_graph_aliases, which replaces the list. See set_graph_aliases.
# File lib/sequel_core/object_graph.rb, line 167 167: def add_graph_aliases(graph_aliases) 168: ds = select_more(*graph_alias_columns(graph_aliases)) 169: ds.opts[:graph_aliases] = (ds.opts[:graph_aliases] || {}).merge(graph_aliases) 170: ds 171: end
Returns an array with all records in the dataset. If a block is given, the array is iterated over after all items have been loaded.
# File lib/sequel_core/dataset.rb, line 150 150: def all(opts = nil, &block) 151: a = [] 152: each(opts) {|r| a << r} 153: post_load(a) 154: a.each(&block) if block 155: a 156: end
Adds an further filter to an existing filter using AND. If no filter exists an error is raised. This method is identical to filter except it expects an existing filter.
# File lib/sequel_core/dataset/sql.rb, line 23 23: def and(*cond, &block) 24: raise(Error::NoExistingFilter, "No existing filter found.") unless @opts[:having] || @opts[:where] 25: filter(*cond, &block) 26: end
Returns the average value for the given column.
# File lib/sequel_core/dataset/convenience.rb, line 18 18: def avg(column) 19: get(SQL::Function.new(:avg, column)) 20: end
For the given type (:select, :insert, :update, or :delete), run the sql with the bind variables specified in the hash. values is a hash of passed to insert or update (if one of those types is used), which may contain placeholders.
# File lib/sequel_core/dataset/prepared_statements.rb, line 181 181: def call(type, bind_variables={}, values=nil) 182: prepare(type, nil, values).call(bind_variables) 183: end
SQL fragment for specifying given CaseExpression.
# File lib/sequel_core/dataset/sql.rb, line 39 39: def case_expression_sql(ce) 40: sql = '(CASE ' 41: sql << "#{literal(ce.expression)} " if ce.expression 42: ce.conditions.collect{ |c,r| 43: sql << "WHEN #{literal(c)} THEN #{literal(r)} " 44: } 45: sql << "ELSE #{literal(ce.default)} END)" 46: end
Returns a new clone of the dataset with with the given options merged. If the options changed include options in COLUMN_CHANGE_OPTS, the cached columns are deleted.
# File lib/sequel_core/dataset.rb, line 161 161: def clone(opts = {}) 162: c = super() 163: c.opts = @opts.merge(opts) 164: c.instance_variable_set(:@columns, nil) if opts.keys.any?{|o| COLUMN_CHANGE_OPTS.include?(o)} 165: c 166: end
Returns the columns in the result set in their true order. If the columns are currently cached, returns the cached value. Otherwise, a SELECT query is performed to get a single row. Adapters are expected to fill the columns cache with the column information when a query is performed. If the dataset does not have any rows, this will be an empty array. If you are looking for all columns for a single table, see Schema::SQL#schema.
# File lib/sequel_core/dataset.rb, line 174 174: def columns 175: return @columns if @columns 176: ds = unfiltered.unordered.clone(:distinct => nil) 177: ds.single_record 178: @columns = ds.instance_variable_get(:@columns) 179: @columns || [] 180: end
SQL fragment for complex expressions
# File lib/sequel_core/dataset/sql.rb, line 54 54: def complex_expression_sql(op, args) 55: case op 56: when *TWO_ARITY_OPERATORS 57: "(#{literal(args.at(0))} #{op} #{literal(args.at(1))})" 58: when *N_ARITY_OPERATORS 59: "(#{args.collect{|a| literal(a)}.join(" #{op} ")})" 60: when :NOT 61: "NOT #{literal(args.at(0))}" 62: when :NOOP 63: literal(args.at(0)) 64: when 'B~''B~' 65: "~#{literal(args.at(0))}" 66: else 67: raise(Sequel::Error, "invalid operator #{op}") 68: end 69: end
Returns the number of records in the dataset.
# File lib/sequel_core/dataset/sql.rb, line 72 72: def count 73: options_overlap(COUNT_FROM_SELF_OPTS) ? from_self.count : single_value(STOCK_COUNT_OPTS).to_i 74: end
Creates a view in the database with the given named based on the current dataset.
# File lib/sequel_core/dataset/schema.rb, line 5 5: def create_view(name) 6: @db.create_view(name, self) 7: end
Add a mutation method to this dataset instance.
# File lib/sequel_core/dataset.rb, line 190 190: def def_mutation_method(*meths) 191: meths.each do |meth| 192: instance_eval("def #{meth}!(*args, &block); mutation_method(:#{meth}, *args, &block) end") 193: end 194: end
Deletes the records in the dataset. The returned value is generally the number of records deleted, but that is adapter dependent.
# File lib/sequel_core/dataset.rb, line 198 198: def delete(*args) 199: execute_dui(delete_sql(*args)) 200: end
Formats a DELETE statement using the given options and dataset options.
dataset.filter{|o| o.price >= 100}.delete_sql #=> "DELETE FROM items WHERE (price >= 100)"
# File lib/sequel_core/dataset/sql.rb, line 81 81: def delete_sql(opts = nil) 82: opts = opts ? @opts.merge(opts) : @opts 83: 84: return static_sql(opts[:sql]) if opts[:sql] 85: 86: if opts[:group] 87: raise Error::InvalidOperation, "Grouped datasets cannot be deleted from" 88: elsif opts[:from].is_a?(Array) && opts[:from].size > 1 89: raise Error::InvalidOperation, "Joined datasets cannot be deleted from" 90: end 91: 92: sql = "DELETE FROM #{source_list(opts[:from])}" 93: 94: if where = opts[:where] 95: sql << " WHERE #{literal(where)}" 96: end 97: 98: sql 99: end
Iterates over the records in the dataset and returns set. If opts have been passed that modify the columns, reset the column information.
# File lib/sequel_core/dataset.rb, line 204 204: def each(opts = nil, &block) 205: if opts && opts.keys.any?{|o| COLUMN_CHANGE_OPTS.include?(o)} 206: prev_columns = @columns 207: begin 208: _each(opts, &block) 209: ensure 210: @columns = prev_columns 211: end 212: else 213: _each(opts, &block) 214: end 215: self 216: end
Yields a paginated dataset for each page and returns the receiver. Does a count to find the total number of records for this dataset.
# File lib/sequel_core/dataset/pagination.rb, line 16 16: def each_page(page_size, &block) 17: raise(Error, "You cannot paginate a dataset that already has a limit") if @opts[:limit] 18: record_count = count 19: total_pages = (record_count / page_size.to_f).ceil 20: (1..total_pages).each{|page_no| yield paginate(page_no, page_size, record_count)} 21: self 22: end
Adds an EXCEPT clause using a second dataset object. If all is true the clause used is EXCEPT ALL, which may return duplicate rows.
DB[:items].except(DB[:other_items]).sql #=> "SELECT * FROM items EXCEPT SELECT * FROM other_items"
# File lib/sequel_core/dataset/sql.rb, line 106 106: def except(dataset, all = false) 107: compound_clone(:except, dataset, all) 108: end
Performs the inverse of Dataset#filter.
dataset.exclude(:category => 'software').sql #=> "SELECT * FROM items WHERE (category != 'software')"
# File lib/sequel_core/dataset/sql.rb, line 114 114: def exclude(*cond, &block) 115: clause = (@opts[:having] ? :having : :where) 116: cond = cond.first if cond.size == 1 117: cond = cond.sql_or if (Hash === cond) || ((Array === cond) && (cond.all_two_pairs?)) 118: cond = filter_expr(cond, &block) 119: cond = SQL::BooleanExpression.invert(cond) 120: cond = SQL::BooleanExpression.new(:AND, @opts[clause], cond) if @opts[clause] 121: clone(clause => cond) 122: end
Returns an EXISTS clause for the dataset as a LiteralString.
DB.select(1).where(DB[:items].exists).sql #=> "SELECT 1 WHERE EXISTS (SELECT * FROM items)"
# File lib/sequel_core/dataset/sql.rb, line 128 128: def exists(opts = nil) 129: "EXISTS (#{select_sql(opts)})".lit 130: end
Executes a select query and fetches records, passing each record to the supplied block. The yielded records are generally hashes with symbol keys, but that is adapter dependent.
# File lib/sequel_core/dataset.rb, line 221 221: def fetch_rows(sql, &block) 222: raise NotImplementedError, NOTIMPL_MSG 223: end
Execute the SQL on the database and yield the rows as hashes with symbol keys.
# File lib/sequel_core/adapters/do.rb, line 192 192: def fetch_rows(sql) 193: execute(sql) do |reader| 194: cols = @columns = reader.fields.map{|f| output_identifier(f)} 195: while(reader.next!) do 196: h = {} 197: cols.zip(reader.values).each{|k, v| h[k] = v} 198: yield h 199: end 200: end 201: self 202: end
Returns a copy of the dataset with the given conditions imposed upon it. If the query has been grouped, then the conditions are imposed in the HAVING clause. If not, then they are imposed in the WHERE clause. Filter
filter accepts the following argument types:
filter also takes a block, which should return one of the above argument types, and is treated the same way. If both a block and regular argument are provided, they get ANDed together.
Examples:
dataset.filter(:id => 3).sql #=> "SELECT * FROM items WHERE (id = 3)" dataset.filter('price < ?', 100).sql #=> "SELECT * FROM items WHERE price < 100" dataset.filter([[:id, (1,2,3)], [:id, 0..10]]).sql #=> "SELECT * FROM items WHERE ((id IN (1, 2, 3)) AND ((id >= 0) AND (id <= 10)))" dataset.filter('price < 100').sql #=> "SELECT * FROM items WHERE price < 100" dataset.filter(:active).sql #=> "SELECT * FROM items WHERE :active dataset.filter{|o| o.price < 100}.sql #=> "SELECT * FROM items WHERE (price < 100)"
Multiple filter calls can be chained for scoping:
software = dataset.filter(:category => 'software') software.filter{|o| o.price < 100}.sql #=> "SELECT * FROM items WHERE ((category = 'software') AND (price < 100))"
See doc/dataset_filters.rdoc for more examples and details.
# File lib/sequel_core/dataset/sql.rb, line 176 176: def filter(*cond, &block) 177: clause = (@opts[:having] ? :having : :where) 178: cond = cond.first if cond.size == 1 179: cond = transform_save(cond) if @transform if cond.is_a?(Hash) 180: cond = filter_expr(cond, &block) 181: cond = SQL::BooleanExpression.new(:AND, @opts[clause], cond) if @opts[clause] && !@opts[clause].blank? 182: clone(clause => cond) 183: end
Returns the first record in the dataset. If a numeric argument is given, it is interpreted as a limit, and then returns all matching records up to that limit. If no argument is passed, it returns the first matching record. If any other type of argument(s) is passed, it is given to filter and the first matching record is returned. If a block is given, it is used to filter the dataset before returning anything.
Examples:
ds.first => {:id=>7} ds.first(2) => [{:id=>6}, {:id=>4}] ds.order(:id).first(2) => [{:id=>1}, {:id=>2}] ds.first(:id=>2) => {:id=>2} ds.first("id = 3") => {:id=>3} ds.first("id = ?", 4) => {:id=>4} ds.first{|o| o.id > 2} => {:id=>5} ds.order(:id).first{|o| o.id > 2} => {:id=>3} ds.first{|o| o.id > 2} => {:id=>5} ds.first("id > ?", 4){|o| o.id < 6} => {:id=>5} ds.order(:id).first(2){|o| o.id < 2} => [{:id=>1}]
# File lib/sequel_core/dataset/convenience.rb, line 48 48: def first(*args, &block) 49: ds = block ? filter(&block) : self 50: 51: if args.empty? 52: ds.single_record 53: else 54: args = (args.size == 1) ? args.first : args 55: if Integer === args 56: ds.limit(args).all 57: else 58: ds.filter(args).single_record 59: end 60: end 61: end
The first source (primary table) for this dataset. If the dataset doesn‘t have a table, raises an error. If the table is aliased, returns the actual table name, not the alias.
# File lib/sequel_core/dataset/sql.rb, line 189 189: def first_source 190: source = @opts[:from] 191: if source.nil? || source.empty? 192: raise Error, 'No source specified for query' 193: end 194: case s = source.first 195: when Hash 196: s.values.first 197: when Symbol 198: sch, table, aliaz = split_symbol(s) 199: aliaz ? aliaz.to_sym : s 200: else 201: s 202: end 203: end
Returns a copy of the dataset with the source changed.
# File lib/sequel_core/dataset/sql.rb, line 206 206: def from(*source) 207: clone(:from => source) 208: end
Returns a dataset selecting from the current dataset.
ds = DB[:items].order(:name) ds.sql #=> "SELECT * FROM items ORDER BY name" ds.from_self.sql #=> "SELECT * FROM (SELECT * FROM items ORDER BY name)"
# File lib/sequel_core/dataset/sql.rb, line 215 215: def from_self 216: fs = {} 217: @opts.keys.each{|k| fs[k] = nil} 218: fs[:from] = [self] 219: clone(fs) 220: end
Allows you to join multiple datasets/tables and have the result set split into component tables.
This differs from the usual usage of join, which returns the result set as a single hash. For example:
# CREATE TABLE artists (id INTEGER, name TEXT); # CREATE TABLE albums (id INTEGER, name TEXT, artist_id INTEGER); DB[:artists].left_outer_join(:albums, :artist_id=>:id).first => {:id=>(albums.id||artists.id), :name=>(albums.name||artist.names), :artist_id=>albums.artist_id} DB[:artists].graph(:albums, :artist_id=>:id).first => {:artists=>{:id=>artists.id, :name=>artists.name}, :albums=>{:id=>albums.id, :name=>albums.name, :artist_id=>albums.artist_id}}
Using a join such as left_outer_join, the attribute names that are shared between the tables are combined in the single return hash. You can get around that by using .select with correct aliases for all of the columns, but it is simpler to use graph and have the result set split for you. In addition, graph respects any row_proc or transform attributes of the current dataset and the datasets you use with graph.
If you are graphing a table and all columns for that table are nil, this indicates that no matching rows existed in the table, so graph will return nil instead of a hash with all nil values:
# If the artist doesn't have any albums DB[:artists].graph(:albums, :artist_id=>:id).first => {:artists=>{:id=>artists.id, :name=>artists.name}, :albums=>nil}
Arguments:
# File lib/sequel_core/object_graph.rb, line 48 48: def graph(dataset, join_conditions = nil, options = {}, &block) 49: # Allow the use of a model, dataset, or symbol as the first argument 50: # Find the table name/dataset based on the argument 51: dataset = dataset.dataset if dataset.respond_to?(:dataset) 52: case dataset 53: when Symbol 54: table = dataset 55: dataset = @db[dataset] 56: when ::Sequel::Dataset 57: table = dataset.first_source 58: else 59: raise Error, "The dataset argument should be a symbol, dataset, or model" 60: end 61: 62: # Raise Sequel::Error with explanation that the table alias has been used 63: raise_alias_error = lambda do 64: raise(Error, "this #{options[:table_alias] ? 'alias' : 'table'} has already been been used, please specify " \ 65: "#{options[:table_alias] ? 'a different alias' : 'an alias via the :table_alias option'}") 66: end 67: 68: # Only allow table aliases that haven't been used 69: table_alias = options[:table_alias] || table 70: raise_alias_error.call if @opts[:graph] && @opts[:graph][:table_aliases] && @opts[:graph][:table_aliases].include?(table_alias) 71: 72: # Join the table early in order to avoid cloning the dataset twice 73: ds = join_table(options[:join_type] || :left_outer, table, join_conditions, :table_alias=>table_alias, :implicit_qualifier=>options[:implicit_qualifier], &block) 74: opts = ds.opts 75: 76: # Whether to include the table in the result set 77: add_table = options[:select] == false ? false : true 78: # Whether to add the columns to the list of column aliases 79: add_columns = !ds.opts.include?(:graph_aliases) 80: 81: # Setup the initial graph data structure if it doesn't exist 82: unless graph = opts[:graph] 83: master = ds.first_source 84: raise_alias_error.call if master == table_alias 85: # Master hash storing all .graph related information 86: graph = opts[:graph] = {} 87: # Associates column aliases back to tables and columns 88: column_aliases = graph[:column_aliases] = {} 89: # Associates table alias (the master is never aliased) 90: table_aliases = graph[:table_aliases] = {master=>self} 91: # Keep track of the alias numbers used 92: ca_num = graph[:column_alias_num] = Hash.new(0) 93: # All columns in the master table are never 94: # aliased, but are not included if set_graph_aliases 95: # has been used. 96: if add_columns 97: select = opts[:select] = [] 98: columns.each do |column| 99: column_aliases[column] = [master, column] 100: select.push(column.qualify(master)) 101: end 102: end 103: end 104: 105: # Add the table alias to the list of aliases 106: # Even if it isn't been used in the result set, 107: # we add a key for it with a nil value so we can check if it 108: # is used more than once 109: table_aliases = graph[:table_aliases] 110: table_aliases[table_alias] = add_table ? dataset : nil 111: 112: # Add the columns to the selection unless we are ignoring them 113: if add_table && add_columns 114: select = opts[:select] 115: column_aliases = graph[:column_aliases] 116: ca_num = graph[:column_alias_num] 117: # Which columns to add to the result set 118: cols = options[:select] || dataset.columns 119: # If the column hasn't been used yet, don't alias it. 120: # If it has been used, try table_column. 121: # If that has been used, try table_column_N 122: # using the next value of N that we know hasn't been 123: # used 124: cols.each do |column| 125: col_alias, identifier = if column_aliases[column] 126: column_alias = "#{table_alias}_#{column}""#{table_alias}_#{column}" 127: if column_aliases[column_alias] 128: column_alias_num = ca_num[column_alias] 129: column_alias = "#{column_alias}_#{column_alias_num}""#{column_alias}_#{column_alias_num}" 130: ca_num[column_alias] += 1 131: end 132: [column_alias, column.qualify(table_alias).as(column_alias)] 133: else 134: [column, column.qualify(table_alias)] 135: end 136: column_aliases[col_alias] = [table_alias, column] 137: select.push(identifier) 138: end 139: end 140: ds 141: end
Pattern match any of the columns to any of the terms. The terms can be strings (which use LIKE) or regular expressions (which are only supported in some databases). See Sequel::SQL::StringExpression.like. Note that the total number of pattern matches will be cols.length * terms.length, which could cause performance issues.
# File lib/sequel_core/dataset/sql.rb, line 233 233: def grep(cols, terms) 234: filter(SQL::BooleanExpression.new(:OR, *Array(cols).collect{|c| SQL::StringExpression.like(c, *terms)})) 235: end
Returns a copy of the dataset with the having conditions changed. Raises an error if the dataset has not been grouped. See also filter.
# File lib/sequel_core/dataset/sql.rb, line 246 246: def having(*cond, &block) 247: raise(Error::InvalidOperation, "Can only specify a HAVING clause on a grouped dataset") unless @opts[:group] 248: clone(:having=>{}).filter(*cond, &block) 249: end
Inserts values into the associated table. The returned value is generally the value of the primary key for the inserted row, but that is adapter dependent.
# File lib/sequel_core/dataset.rb, line 227 227: def insert(*values) 228: execute_insert(insert_sql(*values)) 229: end
Inserts multiple values. If a block is given it is invoked for each item in the given array before inserting it. See multi_insert as a possible faster version that inserts multiple records in one SQL statement.
# File lib/sequel_core/dataset/sql.rb, line 255 255: def insert_multiple(array, &block) 256: if block 257: array.each {|i| insert(block[i])} 258: else 259: array.each {|i| insert(i)} 260: end 261: end
Formats an INSERT statement using the given values. If a hash is given, the resulting statement includes column names. If no values are given, the resulting statement includes a DEFAULT VALUES clause.
dataset.insert_sql() #=> 'INSERT INTO items DEFAULT VALUES' dataset.insert_sql(1,2,3) #=> 'INSERT INTO items VALUES (1, 2, 3)' dataset.insert_sql(:a => 1, :b => 2) #=> 'INSERT INTO items (a, b) VALUES (1, 2)'
# File lib/sequel_core/dataset/sql.rb, line 271 271: def insert_sql(*values) 272: return static_sql(@opts[:sql]) if @opts[:sql] 273: 274: from = source_list(@opts[:from]) 275: case values.size 276: when 0 277: values = {} 278: when 1 279: vals = values.at(0) 280: if vals.is_one_of?(Hash, Dataset, Array) 281: values = vals 282: elsif vals.respond_to?(:values) 283: values = vals.values 284: end 285: end 286: 287: case values 288: when Array 289: if values.empty? 290: insert_default_values_sql 291: else 292: "INSERT INTO #{from} VALUES #{literal(values)}" 293: end 294: when Hash 295: values = @opts[:defaults].merge(values) if @opts[:defaults] 296: values = values.merge(@opts[:overrides]) if @opts[:overrides] 297: values = transform_save(values) if @transform 298: if values.empty? 299: insert_default_values_sql 300: else 301: fl, vl = [], [] 302: values.each do |k, v| 303: fl << literal(String === k ? k.to_sym : k) 304: vl << literal(v) 305: end 306: "INSERT INTO #{from} (#{fl.join(COMMA_SEPARATOR)}) VALUES (#{vl.join(COMMA_SEPARATOR)})" 307: end 308: when Dataset 309: "INSERT INTO #{from} #{literal(values)}" 310: end 311: end
Adds an INTERSECT clause using a second dataset object. If all is true the clause used is INTERSECT ALL, which may return duplicate rows.
DB[:items].intersect(DB[:other_items]).sql #=> "SELECT * FROM items INTERSECT SELECT * FROM other_items"
# File lib/sequel_core/dataset/sql.rb, line 318 318: def intersect(dataset, all = false) 319: compound_clone(:intersect, dataset, all) 320: end
Inverts the current filter
dataset.filter(:category => 'software').invert.sql #=> "SELECT * FROM items WHERE (category != 'software')"
# File lib/sequel_core/dataset/sql.rb, line 326 326: def invert 327: having, where = @opts[:having], @opts[:where] 328: raise(Error, "No current filter") unless having || where 329: o = {} 330: o[:having] = SQL::BooleanExpression.invert(having) if having 331: o[:where] = SQL::BooleanExpression.invert(where) if where 332: clone(o) 333: end
SQL fragment specifying a JOIN clause without ON or USING.
# File lib/sequel_core/dataset/sql.rb, line 341 341: def join_clause_sql(jc) 342: table = jc.table 343: table_alias = jc.table_alias 344: table_alias = nil if table == table_alias 345: tref = table_ref(table) 346: " #{join_type_sql(jc.join_type)} #{table_alias ? as_sql(tref, table_alias) : tref}" 347: end
Returns a joined dataset. Uses the following arguments:
# File lib/sequel_core/dataset/sql.rb, line 389 389: def join_table(type, table, expr=nil, options={}, &block) 390: if options.is_one_of?(Symbol, String) 391: table_alias = options 392: last_alias = nil 393: else 394: table_alias = options[:table_alias] 395: last_alias = options[:implicit_qualifier] 396: end 397: if Dataset === table 398: if table_alias.nil? 399: table_alias_num = (@opts[:num_dataset_sources] || 0) + 1 400: table_alias = "t#{table_alias_num}" 401: end 402: table_name = table_alias 403: else 404: table = table.table_name if table.respond_to?(:table_name) 405: table_name = table_alias || table 406: end 407: 408: join = if expr.nil? and !block_given? 409: SQL::JoinClause.new(type, table, table_alias) 410: elsif Array === expr and !expr.empty? and expr.all?{|x| Symbol === x} 411: raise(Sequel::Error, "can't use a block if providing an array of symbols as expr") if block_given? 412: SQL::JoinUsingClause.new(expr, type, table, table_alias) 413: else 414: last_alias ||= @opts[:last_joined_table] || (first_source.is_a?(Dataset) ? 't1' : first_source) 415: if Hash === expr or (Array === expr and expr.all_two_pairs?) 416: expr = expr.collect do |k, v| 417: k = qualified_column_name(k, table_name) if k.is_a?(Symbol) 418: v = qualified_column_name(v, last_alias) if v.is_a?(Symbol) 419: [k,v] 420: end 421: end 422: if block_given? 423: expr2 = yield(table_name, last_alias, @opts[:join] || []) 424: expr = expr ? SQL::BooleanExpression.new(:AND, expr, expr2) : expr2 425: end 426: SQL::JoinOnClause.new(expr, type, table, table_alias) 427: end 428: 429: opts = {:join => (@opts[:join] || []) + [join], :last_joined_table => table_name} 430: opts[:num_dataset_sources] = table_alias_num if table_alias_num 431: clone(opts) 432: end
Reverses the order and then runs first. Note that this will not necessarily give you the last record in the dataset, unless you have an unambiguous order. If there is not currently an order for this dataset, raises an Error.
# File lib/sequel_core/dataset/convenience.rb, line 83 83: def last(*args, &block) 84: raise(Error, 'No order specified') unless @opts[:order] 85: reverse.first(*args, &block) 86: end
If given an integer, the dataset will contain only the first l results. If given a range, it will contain only those at offsets within that range. If a second argument is given, it is used as an offset.
# File lib/sequel_core/dataset/sql.rb, line 437 437: def limit(l, o = nil) 438: return from_self.limit(l, o) if @opts[:sql] 439: 440: if Range === l 441: o = l.first 442: l = l.interval + 1 443: end 444: l = l.to_i 445: raise(Error, 'Limits must be greater than or equal to 1') unless l >= 1 446: opts = {:limit => l} 447: if o 448: o = o.to_i 449: raise(Error, 'Offsets must be greater than or equal to 0') unless o >= 0 450: opts[:offset] = o 451: end 452: clone(opts) 453: end
Use the ISO values for dates and times.
# File lib/sequel_core/adapters/jdbc.rb, line 418 418: def literal(v) 419: case v 420: when Time 421: literal(v.iso8601) 422: when Date, DateTime, Java::JavaSql::Timestamp, Java::JavaSql::Date 423: literal(v.to_s) 424: else 425: super 426: end 427: end
Handle the usual time class overrides.
# File lib/sequel_core/adapters/do.rb, line 179 179: def literal(v) 180: case v 181: when Time 182: literal(v.iso8601) 183: when Date, DateTime 184: literal(v.to_s) 185: else 186: super 187: end 188: end
Returns a literal representation of a value to be used as part of an SQL expression.
dataset.literal("abc'def\\") #=> "'abc''def\\\\'" dataset.literal(:items__id) #=> "items.id" dataset.literal([1, 2, 3]) => "(1, 2, 3)" dataset.literal(DB[:items]) => "(SELECT * FROM items)" dataset.literal(:x + 1 > :y) => "((x + 1) > y)"
If an unsupported object is given, an exception is raised.
# File lib/sequel_core/dataset/sql.rb, line 465 465: def literal(v) 466: case v 467: when LiteralString 468: v 469: when String 470: "'#{v.gsub(/\\/, "\\\\\\\\").gsub(/'/, "''")}'" 471: when Integer, Float 472: v.to_s 473: when BigDecimal 474: d = v.to_s("F") 475: d = "'#{d}'" if v.nan? || v.infinite? 476: d 477: when NilClass 478: NULL 479: when TrueClass 480: BOOL_TRUE 481: when FalseClass 482: BOOL_FALSE 483: when Symbol 484: symbol_to_column_ref(v) 485: when ::Sequel::SQL::Expression 486: v.to_s(self) 487: when Array 488: v.all_two_pairs? ? literal(v.sql_expr) : array_sql(v) 489: when Hash 490: literal(v.sql_expr) 491: when Time, DateTime 492: v.strftime(TIMESTAMP_FORMAT) 493: when Date 494: v.strftime(DATE_FORMAT) 495: when Dataset 496: "(#{subselect_sql(v)})" 497: else 498: raise Error, "can't express #{v.inspect} as a SQL literal" 499: end 500: end
Maps column values for each record in the dataset (if a column name is given), or performs the stock mapping functionality of Enumerable.
# File lib/sequel_core/dataset/convenience.rb, line 90 90: def map(column_name = nil, &block) 91: if column_name 92: super() {|r| r[column_name]} 93: else 94: super(&block) 95: end 96: end
Returns the maximum value for the given column.
# File lib/sequel_core/dataset/convenience.rb, line 99 99: def max(column) 100: get(SQL::Function.new(:max, column)) 101: end
Returns the minimum value for the given column.
# File lib/sequel_core/dataset/convenience.rb, line 104 104: def min(column) 105: get(SQL::Function.new(:min, column)) 106: end
Returns the the model classes associated with the dataset as a hash. If the dataset is associated with a single model class, a key of nil is used. For datasets with polymorphic models, the keys are values of the polymorphic column and the values are the corresponding model classes to which they map.
# File lib/sequel_core/dataset.rb, line 242 242: def model_classes 243: @opts[:models] 244: end
Inserts multiple records into the associated table. This method can be to efficiently insert a large amounts of records into a table. Inserts are automatically wrapped in a transaction.
This method should be called with a columns array and an array of value arrays:
dataset.multi_insert([:x, :y], [[1, 2], [3, 4]])
This method can also be called with an array of hashes:
dataset.multi_insert({:x => 1}, {:x => 2})
Be aware that all hashes should have the same keys if you use this calling method, otherwise some columns could be missed or set to null instead of to default values.
The method also accepts a :slice or :commit_every option that specifies the number of records to insert per transaction. This is useful especially when inserting a large number of records, e.g.:
# this will commit every 50 records dataset.multi_insert(lots_of_records, :slice => 50)
# File lib/sequel_core/dataset/convenience.rb, line 130 130: def multi_insert(*args) 131: if args.empty? 132: return 133: elsif args[0].is_a?(Array) && args[1].is_a?(Array) 134: columns, values, opts = *args 135: elsif args[0].is_a?(Array) && args[1].is_a?(Dataset) 136: table = @opts[:from].first 137: columns, dataset = *args 138: sql = "INSERT INTO #{quote_identifier(table)} (#{identifier_list(columns)}) VALUES #{literal(dataset)}" 139: return @db.transaction{execute_dui(sql)} 140: else 141: # we assume that an array of hashes is given 142: hashes, opts = *args 143: return if hashes.empty? 144: columns = hashes.first.keys 145: # convert the hashes into arrays 146: values = hashes.map {|h| columns.map {|c| h[c]}} 147: end 148: # make sure there's work to do 149: return if columns.empty? || values.empty? 150: 151: slice_size = opts && (opts[:commit_every] || opts[:slice]) 152: 153: if slice_size 154: values.each_slice(slice_size) do |slice| 155: statements = multi_insert_sql(columns, slice) 156: @db.transaction{statements.each{|st| execute_dui(st)}} 157: end 158: else 159: statements = multi_insert_sql(columns, values) 160: @db.transaction{statements.each{|st| execute_dui(st)}} 161: end 162: end
Returns an array of insert statements for inserting multiple records. This method is used by multi_insert to format insert statements and expects a keys array and and an array of value arrays.
This method should be overridden by descendants if the support inserting multiple records in a single SQL statement.
# File lib/sequel_core/dataset/sql.rb, line 508 508: def multi_insert_sql(columns, values) 509: table = quote_identifier(@opts[:from].first) 510: columns = identifier_list(columns) 511: values.map do |r| 512: "INSERT INTO #{table} (#{columns}) VALUES #{literal(r)}" 513: end 514: end
Adds an alternate filter to an existing filter using OR. If no filter exists an error is raised.
# File lib/sequel_core/dataset/sql.rb, line 518 518: def or(*cond, &block) 519: clause = (@opts[:having] ? :having : :where) 520: cond = cond.first if cond.size == 1 521: if @opts[clause] 522: clone(clause => SQL::BooleanExpression.new(:OR, @opts[clause], filter_expr(cond, &block))) 523: else 524: raise Error::NoExistingFilter, "No existing filter found." 525: end 526: end
Returns a copy of the dataset with the order changed. If a nil is given the returned dataset has no order. This can accept multiple arguments of varying kinds, and even SQL functions.
ds.order(:name).sql #=> 'SELECT * FROM items ORDER BY name' ds.order(:a, :b).sql #=> 'SELECT * FROM items ORDER BY a, b' ds.order('a + b'.lit).sql #=> 'SELECT * FROM items ORDER BY a + b' ds.order(:a + :b).sql #=> 'SELECT * FROM items ORDER BY (a + b)' ds.order(:name.desc).sql #=> 'SELECT * FROM items ORDER BY name DESC' ds.order(:name.asc).sql #=> 'SELECT * FROM items ORDER BY name ASC' ds.order(:arr|1).sql #=> 'SELECT * FROM items ORDER BY arr[1]' ds.order(nil).sql #=> 'SELECT * FROM items'
# File lib/sequel_core/dataset/sql.rb, line 540 540: def order(*order) 541: clone(:order => (order.compact.empty?) ? nil : order) 542: end
Returns a paginated dataset. The returned dataset is limited to the page size at the correct offset, and extended with the Pagination module. If a record count is not provided, does a count of total number of records for this dataset.
# File lib/sequel_core/dataset/pagination.rb, line 7 7: def paginate(page_no, page_size, record_count=nil) 8: raise(Error, "You cannot paginate a dataset that already has a limit") if @opts[:limit] 9: paginated = limit(page_size, (page_no - 1) * page_size) 10: paginated.extend(Pagination) 11: paginated.set_pagination_info(page_no, page_size, record_count || count) 12: end
Returns the column name for the polymorphic key.
# File lib/sequel_core/dataset.rb, line 253 253: def polymorphic_key 254: @opts[:polymorphic_key] 255: end
Create a named prepared statement that is stored in the database (and connection) for reuse.
# File lib/sequel_core/adapters/jdbc.rb, line 431 431: def prepare(type, name=nil, values=nil) 432: ps = to_prepared_statement(type, values) 433: ps.extend(PreparedStatementMethods) 434: if name 435: ps.prepared_statement_name = name 436: db.prepared_statements[name] = ps 437: end 438: ps 439: end
Prepare an SQL statement for later execution. This returns a clone of the dataset extended with PreparedStatementMethods, on which you can call call with the hash of bind variables to do substitution. The prepared statement is also stored in the associated database. The following usage is identical:
ps = prepare(:select, :select_by_name) ps.call(:name=>'Blah') db.call(:select_by_name, :name=>'Blah')
# File lib/sequel_core/dataset/prepared_statements.rb, line 194 194: def prepare(type, name=nil, values=nil) 195: ps = to_prepared_statement(type, values) 196: db.prepared_statements[name] = ps if name 197: ps 198: end
SQL fragment for the qualifed identifier, specifying a table and a column (or schema and table).
# File lib/sequel_core/dataset/sql.rb, line 567 567: def qualified_identifier_sql(qcr) 568: [qcr.table, qcr.column].map{|x| x.is_one_of?(SQL::QualifiedIdentifier, SQL::Identifier, Symbol) ? literal(x) : quote_identifier(x)}.join('.') 569: end
Translates a query block into a dataset. Query blocks can be useful when expressing complex SELECT statements, e.g.:
dataset = DB[:items].query do select :x, :y, :z filter{|o| (o.x > 1) & (o.y > 2)} order :z.desc end
Which is the same as:
dataset = DB[:items].select(:x, :y, :z).filter{|o| (o.x > 1) & (o.y > 2)}.order(:z.desc)
Note that inside a call to query, you cannot call each, insert, update, or delete (or any method that calls those), or Sequel will raise an error.
# File lib/sequel_core/dataset/query.rb, line 19 19: def query(&block) 20: copy = clone({}) 21: copy.extend(QueryBlockCopy) 22: copy.instance_eval(&block) 23: clone(copy.opts) 24: end
Adds quoting to identifiers (columns and tables). If identifiers are not being quoted, returns name as a string. If identifiers are being quoted quote the name with quoted_identifier.
# File lib/sequel_core/dataset/sql.rb, line 574 574: def quote_identifier(name) 575: return name if name.is_a?(LiteralString) 576: name = input_identifier(name) 577: name = quoted_identifier(name) if quote_identifiers? 578: name 579: end
Whether this dataset quotes identifiers.
# File lib/sequel_core/dataset.rb, line 258 258: def quote_identifiers? 259: @quote_identifiers 260: end
Separates the schema from the table and returns a string with them quoted (if quoting identifiers)
# File lib/sequel_core/dataset/sql.rb, line 584 584: def quote_schema_table(table) 585: schema, table = schema_and_table(table) 586: "#{"#{quote_identifier(schema)}." if schema}#{quote_identifier(table)}" 587: end
This method quotes the given name with the SQL standard double quote. should be overridden by subclasses to provide quoting not matching the SQL standard, such as backtick (used by MySQL and SQLite).
# File lib/sequel_core/dataset/sql.rb, line 592 592: def quoted_identifier(name) 593: "\"#{name.to_s.gsub('"', '""')}\"" 594: end
Returns a Range object made from the minimum and maximum values for the given column.
# File lib/sequel_core/dataset/convenience.rb, line 172 172: def range(column) 173: if r = select(SQL::Function.new(:min, column).as(:v1), SQL::Function.new(:max, column).as(:v2)).first 174: (r[:v1]..r[:v2]) 175: end 176: end
Split the schema information from the table
# File lib/sequel_core/dataset/sql.rb, line 604 604: def schema_and_table(table_name) 605: sch = db.default_schema if db 606: case table_name 607: when Symbol 608: s, t, a = split_symbol(table_name) 609: [s||sch, t] 610: when SQL::QualifiedIdentifier 611: [table_name.table, table_name.column] 612: when SQL::Identifier 613: [sch, table_name.value] 614: when String 615: [sch, table_name] 616: else 617: raise Error, 'table_name should be a Symbol, SQL::QualifiedIdentifier, SQL::Identifier, or String' 618: end 619: end
Returns a copy of the dataset selecting the wildcard.
# File lib/sequel_core/dataset/sql.rb, line 628 628: def select_all 629: clone(:select => nil) 630: end
Formats a SELECT statement using the given options and the dataset options.
# File lib/sequel_core/dataset/sql.rb, line 640 640: def select_sql(opts = nil) 641: opts = opts ? @opts.merge(opts) : @opts 642: return static_sql(opts[:sql]) if opts[:sql] 643: sql = 'SELECT' 644: select_clause_order.each{|x| send("select_#{x}_sql", sql, opts)} 645: sql 646: end
Set the server for this dataset to use. Used to pick a specific database shard to run a query against, or to override the default SELECT uses :read_only database and all other queries use the :default database.
# File lib/sequel_core/dataset.rb, line 265 265: def server(servr) 266: clone(:server=>servr) 267: end
This allows you to manually specify the graph aliases to use when using graph. You can use it to only select certain columns, and have those columns mapped to specific aliases in the result set. This is the equivalent of .select for a graphed dataset, and must be used instead of .select whenever graphing is used. Example:
DB[:artists].graph(:albums, :artist_id=>:id).set_graph_aliases(:artist_name=>[:artists, :name], :album_name=>[:albums, :name]).first => {:artists=>{:name=>artists.name}, :albums=>{:name=>albums.name}}
Arguments:
# File lib/sequel_core/object_graph.rb, line 158 158: def set_graph_aliases(graph_aliases) 159: ds = select(*graph_alias_columns(graph_aliases)) 160: ds.opts[:graph_aliases] = graph_aliases 161: ds 162: end
Associates or disassociates the dataset with a model(s). If 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 make sure that there is always a default model class, the hash provided should have a default value. To make the dataset map string values to model classes, and keep a good default, try:
dataset.set_model(:kind, Hash.new{|h,k| h[k] = (k.constantize rescue DefaultClass)})
# File lib/sequel_core/dataset.rb, line 322 322: def set_model(key, *args) 323: # This code is more verbose then necessary for performance reasons 324: case key 325: when nil # set_model(nil) => no argument provided, so the dataset is denuded 326: @opts.merge!(:naked => true, :models => nil, :polymorphic_key => nil) 327: self.row_proc = nil 328: when Class 329: # isomorphic model 330: @opts.merge!(:naked => nil, :models => {nil => key}, :polymorphic_key => nil) 331: if key.respond_to?(:load) 332: # the class has a values setter method, so we use it 333: self.row_proc = proc{|h| key.load(h, *args)} 334: else 335: # otherwise we just pass the hash to the constructor 336: self.row_proc = proc{|h| key.new(h, *args)} 337: end 338: when Symbol 339: # polymorphic model 340: hash = args.shift || raise(ArgumentError, "No class hash supplied for polymorphic model") 341: @opts.merge!(:naked => true, :models => hash, :polymorphic_key => key) 342: if (hash.empty? ? (hash[nil] rescue nil) : hash.values.first).respond_to?(:load) 343: # the class has a values setter method, so we use it 344: self.row_proc = proc do |h| 345: c = hash[h[key]] || hash[nil] || \ 346: raise(Error, "No matching model class for record (#{polymorphic_key} => #{h[polymorphic_key].inspect})") 347: c.load(h, *args) 348: end 349: else 350: # otherwise we just pass the hash to the constructor 351: self.row_proc = proc do |h| 352: c = hash[h[key]] || hash[nil] || \ 353: raise(Error, "No matching model class for record (#{polymorphic_key} => #{h[polymorphic_key].inspect})") 354: c.new(h, *args) 355: end 356: end 357: else 358: raise ArgumentError, "Invalid model specified" 359: end 360: self 361: end
Same as select_sql, not aliased directly to make subclassing simpler.
# File lib/sequel_core/dataset/sql.rb, line 649 649: def sql(*args) 650: select_sql(*args) 651: end
Converts a symbol into a column name. This method supports underscore notation in order to express qualified (two underscores) and aliased (three underscores) columns:
ds = DB[:items] :abc.to_column_ref(ds) #=> "abc" :abc___a.to_column_ref(ds) #=> "abc AS a" :items__abc.to_column_ref(ds) #=> "items.abc" :items__abc___a.to_column_ref(ds) #=> "items.abc AS a"
# File lib/sequel_core/dataset/sql.rb, line 668 668: def symbol_to_column_ref(sym) 669: c_table, column, c_alias = split_symbol(sym) 670: qc = "#{"#{quote_identifier(c_table)}." if c_table}#{quote_identifier(column)}" 671: c_alias ? as_sql(qc, c_alias) : qc 672: end
Returns true if the table exists. Will raise an error if the dataset has fixed SQL or selects from another dataset or more than one table.
# File lib/sequel_core/dataset/convenience.rb, line 200 200: def table_exists? 201: raise(Sequel::Error, "this dataset has fixed SQL") if @opts[:sql] 202: raise(Sequel::Error, "this dataset selects from multiple sources") if @opts[:from].size != 1 203: t = @opts[:from].first 204: raise(Sequel::Error, "this dataset selects from a sub query") if t.is_a?(Dataset) 205: @db.table_exists?(t) 206: end
Returns a string in CSV format containing the dataset records. By default the CSV representation includes the column titles in the first line. You can turn that off by passing false as the include_column_titles argument.
This does not use a CSV library or handle quoting of values in any way. If any values in any of the rows could include commas or line endings, you probably shouldn‘t use this.
# File lib/sequel_core/dataset/convenience.rb, line 216 216: def to_csv(include_column_titles = true) 217: n = naked 218: cols = n.columns 219: csv = '' 220: csv << "#{cols.join(COMMA_SEPARATOR)}\r\n" if include_column_titles 221: n.each{|r| csv << "#{cols.collect{|c| r[c]}.join(COMMA_SEPARATOR)}\r\n"} 222: csv 223: end
Returns a hash with one column used as key and another used as value. If rows have duplicate values for the key column, the latter row(s) will overwrite the value of the previous row(s). If the value_column is not given or nil, uses the entire hash as the value.
# File lib/sequel_core/dataset/convenience.rb, line 229 229: def to_hash(key_column, value_column = nil) 230: inject({}) do |m, r| 231: m[r[key_column]] = value_column ? r[value_column] : r 232: m 233: end 234: end
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.
# File lib/sequel_core/dataset.rb, line 389 389: def transform(t) 390: @transform = t 391: t.each do |k, v| 392: case v 393: when Array 394: if (v.size != 2) || !v.first.is_a?(Proc) && !v.last.is_a?(Proc) 395: raise Error::InvalidTransform, "Invalid transform specified" 396: end 397: else 398: unless v = STOCK_TRANSFORMS[v] 399: raise Error::InvalidTransform, "Invalid transform specified" 400: else 401: t[k] = v 402: end 403: end 404: end 405: self 406: end
Adds a UNION clause using a second dataset object. If all is true the clause used is UNION ALL, which may return duplicate rows.
DB[:items].union(DB[:other_items]).sql #=> "SELECT * FROM items UNION SELECT * FROM other_items"
# File lib/sequel_core/dataset/sql.rb, line 684 684: def union(dataset, all = false) 685: compound_clone(:union, dataset, all) 686: end
# File lib/sequel_core/dataset.rb, line 426 426: def upcase_identifiers=(v) 427: @identifier_input_method = v ? :upcase : nil 428: end
Whether this dataset upcases identifiers.
# File lib/sequel_core/dataset.rb, line 431 431: def upcase_identifiers? 432: @identifier_input_method == :upcase 433: end
Updates values for the dataset. The returned value is generally the number of rows updated, but that is adapter dependent.
# File lib/sequel_core/dataset.rb, line 437 437: def update(*args) 438: execute_dui(update_sql(*args)) 439: end
Formats an UPDATE statement using the given values.
dataset.update_sql(:price => 100, :category => 'software') #=> "UPDATE items SET price = 100, category = 'software'"
Accepts a block, but such usage is discouraged.
Raises an error if the dataset is grouped or includes more than one table.
# File lib/sequel_core/dataset/sql.rb, line 708 708: def update_sql(values = {}, opts = nil) 709: opts = opts ? @opts.merge(opts) : @opts 710: 711: return static_sql(opts[:sql]) if opts[:sql] 712: 713: if opts[:group] 714: raise Error::InvalidOperation, "A grouped dataset cannot be updated" 715: elsif (opts[:from].size > 1) or opts[:join] 716: raise Error::InvalidOperation, "A joined dataset cannot be updated" 717: end 718: 719: sql = "UPDATE #{source_list(@opts[:from])} SET " 720: set = if values.is_a?(Hash) 721: values = opts[:defaults].merge(values) if opts[:defaults] 722: values = values.merge(opts[:overrides]) if opts[:overrides] 723: # get values from hash 724: values = transform_save(values) if @transform 725: values.map do |k, v| 726: "#{k.is_one_of?(String, Symbol) ? quote_identifier(k) : literal(k)} = #{literal(v)}" 727: end.join(COMMA_SEPARATOR) 728: else 729: # copy values verbatim 730: values 731: end 732: sql << set 733: if where = opts[:where] 734: sql << " WHERE #{literal(where)}" 735: end 736: 737: sql 738: end
Return true if the dataset has a non-nil value for any key in opts.
# File lib/sequel_core/dataset.rb, line 447 447: def options_overlap(opts) 448: !(@opts.collect{|k,v| k unless v.nil?}.compact & opts).empty? 449: end
Return a cloned copy of the current dataset extended with PreparedStatementMethods, setting the type and modify values.
# File lib/sequel_core/dataset/prepared_statements.rb, line 204 204: def to_prepared_statement(type, values=nil) 205: ps = clone 206: ps.extend(PreparedStatementMethods) 207: ps.prepared_type = type 208: ps.prepared_modify_values = values 209: ps 210: end