Class: Sequel::Dataset

Class | Sequel::Dataset
In: | lib/sequel_core/adapters/jdbc.rb lib/sequel_core/adapters/do.rb lib/sequel_core/dataset.rb lib/sequel_core/dataset/callback.rb lib/sequel_core/dataset/convenience.rb lib/sequel_core/dataset/pagination.rb lib/sequel_core/dataset/prepared_statements.rb lib/sequel_core/dataset/query.rb lib/sequel_core/dataset/schema.rb lib/sequel_core/dataset/sql.rb lib/sequel_core/dataset/unsupported.rb lib/sequel_core/dataset/stored_procedures.rb lib/sequel_core/object_graph.rb
Parent: | Sequel::Dataset

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.

### Methods added via metaprogramming

Some methods are added via metaprogramming:

- ! methods - These methods are the same as their non-! counterparts, but they modify the receiver instead of returning a modified copy of the dataset.
- inner_join, full_outer_join, right_outer_join, left_outer_join - This methods are shortcuts to join_table with the join type already specified.

### Methods

<< [] []= add_graph_aliases aliased_expression_sql all and array_sql as avg call case_expression_sql clone column_all_sql columns columns! complex_expression_sql count create_or_replace_view create_view dataset_classes def_mutation_method def_mutation_method delete delete_sql distinct each each_page empty? except exclude exists fetch_rows fetch_rows fetch_rows filter first first_source from from_self function_sql get graph grep group group_and_count group_by having import inherited insert insert_multiple insert_sql inspect intersect interval invert irregular_function_sql join_clause_sql join_on_clause_sql join_table join_using_clause_sql last limit literal literal literal map max min model_classes multi_insert multi_insert_sql naked new options_overlap or order order_by order_more ordered_expression_sql paginate placeholder_literal_string_sql polymorphic_key prepare prepare print qualified_identifier_sql query quote_column_ref quote_identifier quote_identifiers? quote_schema_table quoted_identifier range reverse reverse_order schema_and_table select select_all select_more select_sql server set set_defaults set_graph_aliases set_model set_overrides single_record single_value size sql subscript_sql sum symbol_to_column_ref table_exists? to_csv to_hash to_prepared_statement to_table_reference transform transform_load transform_save unfiltered union uniq unordered upcase_identifiers= upcase_identifiers? update update_sql where

### Included Modules

StoredProcedures Enumerable

### Classes and Modules

Module Sequel::Dataset::ArgumentMapper
Module Sequel::Dataset::Pagination
Module Sequel::Dataset::PreparedStatementMethods
Module Sequel::Dataset::QueryBlockCopy
Module Sequel::Dataset::StoredProcedureMethods
Module Sequel::Dataset::StoredProcedures
Module Sequel::Dataset::UnnumberedArgumentMapper
Module Sequel::Dataset::UnsupportedIntersectExcept
Module Sequel::Dataset::UnsupportedIntersectExceptAll

### Constants

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

### External Aliases

inner_join | -> | join

### Attributes

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.

### Public Class methods

dataset_classes()

The array of dataset subclasses.

[Source]

         # File lib/sequel_core/dataset.rb, line 116
    116:     def self.dataset_classes
    117:       DATASET_CLASSES
    118:     end

def_mutation_method(*meths)

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.

[Source]

         # 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

inherited(c)

Add the subclass to the array of subclasses.

[Source]

         # File lib/sequel_core/dataset.rb, line 130
    130:     def self.inherited(c)
    131:       DATASET_CLASSES << c
    132:     end

new(db, opts = nil)

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.

[Source]

         # 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

### Public Instance methods

<<(*args)

Alias for insert, but not aliased directly so subclasses don‘t have to override both methods.

[Source]

         # File lib/sequel_core/dataset.rb, line 138
    138:     def <<(*args)
    139:       insert(*args)
    140:     end

[](*conditions)

Returns the first record matching the conditions.

[Source]

       # File lib/sequel_core/dataset/convenience.rb, line 7
    7:     def [](*conditions)
    8:       first(*conditions)
    9:     end

[]=(conditions, values)

Update all records matching the conditions with the values specified.

[Source]

        # File lib/sequel_core/dataset/convenience.rb, line 13
    13:     def []=(conditions, values)
    14:       filter(conditions).update(values)
    15:     end

add_graph_aliases(graph_aliases)

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.

[Source]

         # 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

aliased_expression_sql(ae)

SQL fragment for the aliased expression

[Source]

        # File lib/sequel_core/dataset/sql.rb, line 29
    29:     def aliased_expression_sql(ae)
    30:       as_sql(literal(ae.expression), ae.aliaz)
    31:     end

all(opts = nil, &block)

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.

[Source]

         # 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

and(*cond, &block)

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.

[Source]

        # 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

array_sql(a)

SQL fragment for the SQL array.

[Source]

        # File lib/sequel_core/dataset/sql.rb, line 34
    34:     def array_sql(a)
    35:       a.empty? ? '(NULL)' : "(#{expression_list(a)})"
    36:     end

as(aliaz)

Return the dataset as a column with the given alias, so it can be used in the SELECT clause. This dataset should result in a single row and a single column.

[Source]

         # File lib/sequel_core/dataset.rb, line 144
    144:     def as(aliaz)
    145:       ::Sequel::SQL::AliasedExpression.new(self, aliaz)
    146:     end

avg(column)

Returns the average value for the given column.

[Source]

        # File lib/sequel_core/dataset/convenience.rb, line 18
    18:     def avg(column)
    19:       get(SQL::Function.new(:avg, column))
    20:     end

call(type, bind_variables={}, values=nil)

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.

[Source]

         # 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

case_expression_sql(ce)

SQL fragment for specifying given CaseExpression.

[Source]

        # 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

clone(opts = {})

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.

[Source]

         # 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

column_all_sql(ca)

SQL fragment for specifying all columns in a given table.

[Source]

        # File lib/sequel_core/dataset/sql.rb, line 49
    49:     def column_all_sql(ca)
    50:       "#{quote_schema_table(ca.table)}.*"
    51:     end

columns()

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.

[Source]

         # 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

columns!()

Remove the cached list of columns and do a SELECT query to find the columns.

[Source]

         # File lib/sequel_core/dataset.rb, line 184
    184:     def columns!
    185:       @columns = nil
    186:       columns
    187:     end

complex_expression_sql(op, args)

SQL fragment for complex expressions

[Source]

        # 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

count()

Returns the number of records in the dataset.

[Source]

        # 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

create_or_replace_view(name)

Creates or replaces a view in the database with the given named based on the current dataset.

[Source]

        # File lib/sequel_core/dataset/schema.rb, line 11
    11:     def create_or_replace_view(name)
    12:       @db.create_or_replace_view(name, self)
    13:     end

create_view(name)

Creates a view in the database with the given named based on the current dataset.

[Source]

       # File lib/sequel_core/dataset/schema.rb, line 5
    5:     def create_view(name)
    6:       @db.create_view(name, self)
    7:     end

def_mutation_method(*meths)

Add a mutation method to this dataset instance.

[Source]

         # 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

delete(*args)

Deletes the records in the dataset. The returned value is generally the number of records deleted, but that is adapter dependent.

[Source]

         # File lib/sequel_core/dataset.rb, line 198
    198:     def delete(*args)
    199:       execute_dui(delete_sql(*args))
    200:     end

delete_sql(opts = nil)

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)"

[Source]

        # 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

distinct(*args)

Alias for uniq

each(opts = nil, &block)

Iterates over the records in the dataset and returns set. If opts have been passed that modify the columns, reset the column information.

[Source]

         # 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

each_page(page_size) {|paginate(page_no, page_size, record_count)}| ...}

Yields a paginated dataset for each page and returns the receiver. Does a count to find the total number of records for this dataset.

[Source]

        # 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

empty?()

Returns true if no records exists in the dataset

[Source]

        # File lib/sequel_core/dataset/convenience.rb, line 23
    23:     def empty?
    24:       get(1).nil?
    25:     end

except(dataset, all = false)

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"

[Source]

         # File lib/sequel_core/dataset/sql.rb, line 106
    106:     def except(dataset, all = false)
    107:       compound_clone(:except, dataset, all)
    108:     end

exclude(*cond, &block)

Performs the inverse of Dataset#filter.

      dataset.exclude(:category => 'software').sql #=>
        "SELECT * FROM items WHERE (category != 'software')"

[Source]

         # 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

exists(opts = nil)

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)"

[Source]

         # File lib/sequel_core/dataset/sql.rb, line 128
    128:     def exists(opts = nil)
    129:       "EXISTS (#{select_sql(opts)})".lit
    130:     end

fetch_rows(sql, &block)

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.

[Source]

         # File lib/sequel_core/dataset.rb, line 221
    221:     def fetch_rows(sql, &block)
    222:       raise NotImplementedError, NOTIMPL_MSG
    223:     end

fetch_rows(sql) {|h| ...}

Execute the SQL on the database and yield the rows as hashes with symbol keys.

[Source]

         # 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

fetch_rows(sql, &block)

Correctly return rows from the database and return them as hashes.

[Source]

         # File lib/sequel_core/adapters/jdbc.rb, line 412
    412:       def fetch_rows(sql, &block)
    413:         execute(sql){|result| process_result_set(result, &block)}
    414:         self
    415:       end

filter(*cond, &block)

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:

- Hash - list of equality expressions
- Array - depends:
  - If first member is a string, assumes the rest of the arguments are parameters and interpolates them into the string.
  - If all members are arrays of length two, treats the same way as a hash, except it allows for duplicate keys to be specified.
- String - taken literally
- Symbol - taken as a boolean column argument (e.g. WHERE active)
- Sequel::SQL::BooleanExpression - an existing condition expression, probably created using the Sequel blockless filter DSL.

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.

[Source]

         # 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

first(*args, &block)

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}]

[Source]

        # 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

first_source()

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.

[Source]

         # 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

from(*source)

Returns a copy of the dataset with the source changed.

[Source]

         # File lib/sequel_core/dataset/sql.rb, line 206
    206:     def from(*source)
    207:       clone(:from => source)
    208:     end

from_self()

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)"

[Source]

         # 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

function_sql(f)

SQL fragment specifying an SQL function call

[Source]

         # File lib/sequel_core/dataset/sql.rb, line 223
    223:     def function_sql(f)
    224:       args = f.args
    225:       "#{f.f}#{args.empty? ? '()' : literal(args)}"
    226:     end

get(column)

Return the column value for the first matching record in the dataset.

[Source]

        # File lib/sequel_core/dataset/convenience.rb, line 64
    64:     def get(column)
    65:       select(column).single_value
    66:     end

graph(dataset, join_conditions = nil, options = {}, &block)

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:

- dataset - Can be a symbol (specifying a table), another dataset, or an object that responds to .dataset and yields a symbol or a dataset
- join_conditions - Any condition(s) allowed by join_table.
- options - A hash of graph options. The following options are currently used:
  - :implicit_qualifier - The qualifier of implicit conditions, see join_table.
  - :join_type - The type of join to use (passed to join_table). Defaults to :left_outer.
  - :select - An array of columns to select. When not used, selects all columns in the given dataset. When set to false, selects no columns and is like simply joining the tables, though graph keeps some metadata about join that makes it important to use graph instead of join.
  - :table_alias - The alias to use for the table. If not specified, doesn‘t alias the table. You will get an error if the the alias (or table) name is used more than once.
- block - A block that is passed to join_table.

[Source]

         # 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

grep(cols, terms)

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.

[Source]

         # 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

group(*columns)

Returns a copy of the dataset with the results grouped by the value of the given columns

[Source]

         # File lib/sequel_core/dataset/sql.rb, line 239
    239:     def group(*columns)
    240:       clone(:group => columns)
    241:     end

group_and_count(*columns)

Returns a dataset grouped by the given column with count by group.

[Source]

        # File lib/sequel_core/dataset/convenience.rb, line 69
    69:     def group_and_count(*columns)
    70:       group(*columns).select(*(columns + [COUNT_OF_ALL_AS_COUNT])).order(:count)
    71:     end

group_by(*columns)

Alias for group

having(*cond, &block)

Returns a copy of the dataset with the having conditions changed. Raises an error if the dataset has not been grouped. See also filter.

[Source]

         # 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

import(*args)

Alias for multi_insert

insert(*values)

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.

[Source]

         # File lib/sequel_core/dataset.rb, line 227
    227:     def insert(*values)
    228:       execute_insert(insert_sql(*values))
    229:     end

insert_multiple(array, &block)

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.

[Source]

         # 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

insert_sql(*values)

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)'

[Source]

         # 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

inspect()

Returns a string representation of the dataset including the class name and the corresponding SQL select statement.

[Source]

         # File lib/sequel_core/dataset.rb, line 233
    233:     def inspect
    234:       "#<#{self.class}: #{sql.inspect}>"
    235:     end

intersect(dataset, all = false)

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"

[Source]

         # File lib/sequel_core/dataset/sql.rb, line 318
    318:     def intersect(dataset, all = false)
    319:       compound_clone(:intersect, dataset, all)
    320:     end

interval(column)

Returns the interval between minimum and maximum values for the given column.

[Source]

        # File lib/sequel_core/dataset/convenience.rb, line 75
    75:     def interval(column)
    76:       get("(max(#{literal(column)}) - min(#{literal(column)}))".lit)
    77:     end

invert()

Inverts the current filter

      dataset.filter(:category => 'software').invert.sql #=>
        "SELECT * FROM items WHERE (category != 'software')"

[Source]

         # 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

irregular_function_sql(f)

SQL fragment specifying an Irregular (cast/extract) SQL function call

[Source]

         # File lib/sequel_core/dataset/sql.rb, line 336
    336:     def irregular_function_sql(f)
    337:       "#{f.f}(#{literal(f.arg1)} #{f.joiner} #{literal(f.arg2)})"
    338:     end

join_clause_sql(jc)

SQL fragment specifying a JOIN clause without ON or USING.

[Source]

         # 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

join_on_clause_sql(jc)

SQL fragment specifying a JOIN clause with ON.

[Source]

         # File lib/sequel_core/dataset/sql.rb, line 350
    350:     def join_on_clause_sql(jc)
    351:       "#{join_clause_sql(jc)} ON #{literal(filter_expr(jc.on))}"
    352:     end

join_table(type, table, expr=nil, options={}) {|table_name, last_alias, @opts[:join] || []| ...}

Returns a joined dataset. Uses the following arguments:

- type - The type of join to do (:inner, :left_outer, :right_outer, :full)
- table - Depends on type:
  - Dataset - a subselect is performed with an alias of tN for some value of N
  - Model (or anything responding to :table_name) - table.table_name
  - String, Symbol: table
- expr - specifies conditions, depends on type:
  - Hash, Array with all two pairs - Assumes key (1st arg) is column of joined table (unless already qualified), and value (2nd arg) is column of the last joined or primary table (or the :implicit_qualifier option). To specify multiple conditions on a single joined table column, you must use an array. Uses a JOIN with an ON clause.
  - Array - If all members of the array are symbols, considers them as columns and uses a JOIN with a USING clause. Most databases will remove duplicate columns from the result set if this is used.
  - nil - If a block is not given, doesn‘t use ON or USING, so the JOIN should be a NATURAL or CROSS join. If a block is given, uses a ON clause based on the block, see below.
  - Everything else - pretty much the same as a using the argument in a call to filter, so strings are considered literal, symbols specify boolean columns, and blockless filter expressions can be used. Uses a JOIN with an ON clause.
- options - a hash of options, with any of the following keys:
  - :table_alias - the name of the table‘s alias when joining, necessary for joining to the same table more than once. No alias is used by default.
  - :implicit_qualifer - The name to use for qualifying implicit conditions. By default, the last joined or primary table is used.
- block - The block argument should only be given if a JOIN with an ON clause is used, in which case it yields the table alias/name for the table currently being joined, the table alias/name for the last joined (or first table), and an array of previous SQL::JoinClause.

[Source]

         # 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

join_using_clause_sql(jc)

SQL fragment specifying a JOIN clause with USING.

[Source]

         # File lib/sequel_core/dataset/sql.rb, line 355
    355:     def join_using_clause_sql(jc)
    356:       "#{join_clause_sql(jc)} USING (#{column_list(jc.using)})"
    357:     end

last(*args, &block)

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.

[Source]

        # 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

limit(l, o = nil)

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.

[Source]

         # 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

literal(v)

Use the ISO values for dates and times.

[Source]

         # 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

literal(v)

Handle the usual time class overrides.

[Source]

         # 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

literal(v)

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.

[Source]

         # 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

map(column_name = nil, &block)

Maps column values for each record in the dataset (if a column name is given), or performs the stock mapping functionality of Enumerable.

[Source]

        # 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

max(column)

Returns the maximum value for the given column.

[Source]

         # File lib/sequel_core/dataset/convenience.rb, line 99
     99:     def max(column)
    100:       get(SQL::Function.new(:max, column))
    101:     end

min(column)

Returns the minimum value for the given column.

[Source]

         # File lib/sequel_core/dataset/convenience.rb, line 104
    104:     def min(column)
    105:       get(SQL::Function.new(:min, column))
    106:     end

model_classes()

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.

[Source]

         # File lib/sequel_core/dataset.rb, line 242
    242:     def model_classes
    243:       @opts[:models]
    244:     end

multi_insert(*args)

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)

[Source]

         # 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

multi_insert_sql(columns, values)

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.

[Source]

         # 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

naked()

Returns a naked dataset clone - i.e. a dataset that returns records as hashes rather than model objects.

[Source]

         # File lib/sequel_core/dataset.rb, line 248
    248:     def naked
    249:       clone.set_model(nil)
    250:     end

or(*cond, &block)

Adds an alternate filter to an existing filter using OR. If no filter exists an error is raised.

[Source]

         # 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

order(*order)

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'

[Source]

         # File lib/sequel_core/dataset/sql.rb, line 540
    540:     def order(*order)
    541:       clone(:order => (order.compact.empty?) ? nil : order)
    542:     end

order_by(*order)

Alias for order

order_more(*order)

Returns a copy of the dataset with the order columns added to the existing order.

[Source]

         # File lib/sequel_core/dataset/sql.rb, line 547
    547:     def order_more(*order)
    548:       order(*((@opts[:order] || []) + order))
    549:     end

ordered_expression_sql(oe)

SQL fragment for the ordered expression, used in the ORDER BY clause.

[Source]

         # File lib/sequel_core/dataset/sql.rb, line 553
    553:     def ordered_expression_sql(oe)
    554:       "#{literal(oe.expression)} #{oe.descending ? 'DESC' : 'ASC'}"
    555:     end

paginate(page_no, page_size, record_count=nil)

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.

[Source]

        # 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

placeholder_literal_string_sql(pls)

SQL fragment for a literal string with placeholders

[Source]

         # File lib/sequel_core/dataset/sql.rb, line 558
    558:     def placeholder_literal_string_sql(pls)
    559:       args = pls.args.dup
    560:       s = pls.str.gsub(QUESTION_MARK){literal(args.shift)}
    561:       s = "(#{s})" if pls.parens
    562:       s
    563:     end

polymorphic_key()

Returns the column name for the polymorphic key.

[Source]

         # File lib/sequel_core/dataset.rb, line 253
    253:     def polymorphic_key
    254:       @opts[:polymorphic_key]
    255:     end

prepare(type, name=nil, values=nil)

Create a named prepared statement that is stored in the database (and connection) for reuse.

[Source]

         # 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(type, name=nil, values=nil)

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')

[Source]

         # 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

print(*cols)

Pretty prints the records in the dataset as plain-text table.

[Source]

         # File lib/sequel_core/dataset/convenience.rb, line 166
    166:     def print(*cols)
    167:       Sequel::PrettyTable.print(naked.all, cols.empty? ? columns : cols)
    168:     end

qualified_identifier_sql(qcr)

SQL fragment for the qualifed identifier, specifying a table and a column (or schema and table).

[Source]

         # 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

query(&block)

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.

[Source]

        # 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

quote_column_ref(name)

Alias for quote_identifier

quote_identifier(name)

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.

[Source]

         # 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

quote_identifiers?()

Whether this dataset quotes identifiers.

[Source]

         # File lib/sequel_core/dataset.rb, line 258
    258:     def quote_identifiers?
    259:       @quote_identifiers
    260:     end

quote_schema_table(table)

Separates the schema from the table and returns a string with them quoted (if quoting identifiers)

[Source]

         # 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

quoted_identifier(name)

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).

[Source]

         # File lib/sequel_core/dataset/sql.rb, line 592
    592:     def quoted_identifier(name)
    593:       "\"#{name.to_s.gsub('"', '""')}\""
    594:     end

range(column)

Returns a Range object made from the minimum and maximum values for the given column.

[Source]

         # 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

reverse(*order)

Alias for reverse_order

reverse_order(*order)

Returns a copy of the dataset with the order reversed. If no order is given, the existing order is inverted.

[Source]

         # File lib/sequel_core/dataset/sql.rb, line 598
    598:     def reverse_order(*order)
    599:       order(*invert_order(order.empty? ? @opts[:order] : order))
    600:     end

schema_and_table(table_name)

Split the schema information from the table

[Source]

         # 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

select(*columns)

Returns a copy of the dataset with the columns selected changed to the given columns.

[Source]

         # File lib/sequel_core/dataset/sql.rb, line 623
    623:     def select(*columns)
    624:       clone(:select => columns)
    625:     end

select_all()

Returns a copy of the dataset selecting the wildcard.

[Source]

         # File lib/sequel_core/dataset/sql.rb, line 628
    628:     def select_all
    629:       clone(:select => nil)
    630:     end

select_more(*columns)

Returns a copy of the dataset with the given columns added to the existing selected columns.

[Source]

         # File lib/sequel_core/dataset/sql.rb, line 634
    634:     def select_more(*columns)
    635:       select(*((@opts[:select] || []) + columns))
    636:     end

select_sql(opts = nil)

Formats a SELECT statement using the given options and the dataset options.

[Source]

         # 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

server(servr)

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.

[Source]

         # File lib/sequel_core/dataset.rb, line 265
    265:     def server(servr)
    266:       clone(:server=>servr)
    267:     end

set(*args)

Alias for set, but not aliased directly so subclasses don‘t have to override both methods.

[Source]

         # File lib/sequel_core/dataset.rb, line 271
    271:     def set(*args)
    272:       update(*args)
    273:     end

set_defaults(hash)

Set the default values for insert and update statements. The values passed to insert or update are merged into this hash.

[Source]

         # File lib/sequel_core/dataset.rb, line 277
    277:     def set_defaults(hash)
    278:       clone(:defaults=>(@opts[:defaults]||{}).merge(hash))
    279:     end

set_graph_aliases(graph_aliases)

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:

- graph_aliases - Should be a hash with keys being symbols of column aliases, and values being arrays with two symbol elements. The first element of the array should be the table alias, and the second should be the actual column name.

[Source]

         # 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

set_model(key, *args)

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)})

[Source]

         # 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

set_overrides(hash)

Set values that override hash arguments given to insert and update statements. This hash is merged into the hash provided to insert or update.

[Source]

         # File lib/sequel_core/dataset.rb, line 365
    365:     def set_overrides(hash)
    366:       clone(:overrides=>hash.merge(@opts[:overrides]||{}))
    367:     end

single_record(opts = nil)

Returns the first record in the dataset.

[Source]

         # File lib/sequel_core/dataset/convenience.rb, line 179
    179:     def single_record(opts = nil)
    180:       each((opts||{}).merge(:limit=>1)){|r| return r}
    181:       nil
    182:     end

single_value(opts = nil)

Returns the first value of the first record in the dataset. Returns nil if dataset is empty.

[Source]

         # File lib/sequel_core/dataset/convenience.rb, line 186
    186:     def single_value(opts = nil)
    187:       if r = single_record((opts||{}).merge(:graph=>false, :naked=>true))
    188:         r.values.first
    189:       end
    190:     end

size()

Alias for count

sql(*args)

Same as select_sql, not aliased directly to make subclassing simpler.

[Source]

         # File lib/sequel_core/dataset/sql.rb, line 649
    649:     def sql(*args)
    650:       select_sql(*args)
    651:     end

subscript_sql(s)

SQL fragment for specifying subscripts (SQL arrays)

[Source]

         # File lib/sequel_core/dataset/sql.rb, line 654
    654:     def subscript_sql(s)
    655:       "#{s.f}[#{s.sub.join(COMMA_SEPARATOR)}]"
    656:     end

sum(column)

Returns the sum for the given column.

[Source]

         # File lib/sequel_core/dataset/convenience.rb, line 193
    193:     def sum(column)
    194:       get(SQL::Function.new(:sum, column))
    195:     end

symbol_to_column_ref(sym)

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"

[Source]

         # 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

table_exists?()

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.

[Source]

         # 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

to_csv(include_column_titles = true)

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.

[Source]

         # 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

to_hash(key_column, value_column = nil)

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.

[Source]

         # 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

transform(t)

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.

[Source]

         # 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

transform_load(r)

Applies the value transform for data loaded from the database.

[Source]

         # File lib/sequel_core/dataset.rb, line 409
    409:     def transform_load(r)
    410:       r.inject({}) do |m, kv|
    411:         k, v = *kv
    412:         m[k] = (tt = @transform[k]) ? tt[0][v] : v
    413:         m
    414:       end
    415:     end

transform_save(r)

Applies the value transform for data saved to the database.

[Source]

         # File lib/sequel_core/dataset.rb, line 418
    418:     def transform_save(r)
    419:       r.inject({}) do |m, kv|
    420:         k, v = *kv
    421:         m[k] = (tt = @transform[k]) ? tt[1][v] : v
    422:         m
    423:       end
    424:     end

unfiltered()

Returns a copy of the dataset with no filters (HAVING or WHERE clause) applied.

[Source]

         # File lib/sequel_core/dataset/sql.rb, line 675
    675:     def unfiltered
    676:       clone(:where => nil, :having => nil)
    677:     end

union(dataset, all = false)

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"

[Source]

         # File lib/sequel_core/dataset/sql.rb, line 684
    684:     def union(dataset, all = false)
    685:       compound_clone(:union, dataset, all)
    686:     end

uniq(*args)

Returns a copy of the dataset with the distinct option.

[Source]

         # File lib/sequel_core/dataset/sql.rb, line 689
    689:     def uniq(*args)
    690:       clone(:distinct => args)
    691:     end

unordered()

Returns a copy of the dataset with no order.

[Source]

         # File lib/sequel_core/dataset/sql.rb, line 695
    695:     def unordered
    696:       order(nil)
    697:     end

upcase_identifiers=(v)

[Source]

         # File lib/sequel_core/dataset.rb, line 426
    426:     def upcase_identifiers=(v)
    427:       @identifier_input_method = v ? :upcase : nil
    428:     end

upcase_identifiers?()

Whether this dataset upcases identifiers.

[Source]

         # File lib/sequel_core/dataset.rb, line 431
    431:     def upcase_identifiers?
    432:       @identifier_input_method == :upcase
    433:     end

update(*args)

Updates values for the dataset. The returned value is generally the number of rows updated, but that is adapter dependent.

[Source]

         # File lib/sequel_core/dataset.rb, line 437
    437:     def update(*args)
    438:       execute_dui(update_sql(*args))
    439:     end

update_sql(values = {}, opts = nil)

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.

[Source]

         # 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

where(*cond, &block)

Alias for filter

### Protected Instance methods

options_overlap(opts)

Return true if the dataset has a non-nil value for any key in opts.

[Source]

         # 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

to_prepared_statement(type, values=nil)

Return a cloned copy of the current dataset extended with PreparedStatementMethods, setting the type and modify values.

[Source]

         # 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

to_table_reference(table_alias=nil)

Returns a table reference for use in the FROM clause. Returns an SQL subquery frgament with an optional table alias.

[Source]

         # File lib/sequel_core/dataset/sql.rb, line 749
    749:     def to_table_reference(table_alias=nil)
    750:       s = "(#{sql})"
    751:       table_alias ? as_sql(s, table_alias) : s
    752:     end

[Validate]