Class | Sequel::Dataset

In:

lib/sequel/adapters/do.rb
lib/sequel/adapters/jdbc.rb
lib/sequel/adapters/utils/stored_procedures.rb
lib/sequel/dataset.rb
lib/sequel/dataset/actions.rb
lib/sequel/dataset/features.rb
lib/sequel/dataset/graph.rb
lib/sequel/dataset/misc.rb
lib/sequel/dataset/prepared_statements.rb
lib/sequel/dataset/query.rb
lib/sequel/dataset/sql.rb
lib/sequel/dataset/mutation.rb
lib/sequel/extensions/pagination.rb
lib/sequel/extensions/pretty_table.rb
lib/sequel/extensions/query.rb

Parent: | Sequel::Dataset

A dataset represents an SQL query, or more generally, an abstract set of rows in the database. 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 (datasets never cache results):

      my_posts = DB[:posts].filter(:author => 'david') # no records are retrieved
      my_posts.all # records are retrieved
      my_posts.all # records are retrieved again

Most dataset methods return modified copies of the dataset (functional style), so you can reuse different datasets to access data:

      posts = DB[:posts]
      davids_posts = posts.filter(:author => 'david')
      old_posts = posts.filter('stamp < ?', Date.today - 7)
      davids_old_posts = davids_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.

For more information, see the "Dataset Basics" guide.

### Contents

- Methods that execute code on the database
- Methods that describe what the dataset supports
- Methods related to dataset graphing
- Miscellaneous methods
- Methods related to prepared statements or bound variables
- Methods that return modified datasets
- User Methods relating to SQL Creation
- Internal Methods relating to SQL Creation
- Mutation methods

### Methods

<< [] []= _insert_sql _update_sql add_graph_aliases aliased_expression_sql all and array_sql as avg bind boolean_constant_sql call case_expression_sql cast_sql clause_methods clone column_all_sql columns columns! complex_expression_sql compound_from_self constant_sql count def_mutation_method def_mutation_method delete delete_sql distinct each each_page each_server empty? except exclude exists fetch_rows fetch_rows fetch_rows filter first first_source first_source_alias first_source_table for_update from from_self function_sql get graph grep group group_and_count group_by having import insert insert_multiple insert_sql inspect intersect interval invert join join_clause_sql join_on_clause_sql join_table join_using_clause_sql last limit literal lock_style map max min multi_insert multi_insert_sql naked negative_boolean_constant_sql new new options_overlap or order order_append order_by order_more order_prepend ordered_expression_sql paginate placeholder_literal_string_sql prepare prepare print provides_accurate_rows_matched? qualified_identifier_sql qualify qualify_to qualify_to_first_source query quote_identifier quote_identifiers? quote_schema_table quoted_identifier range requires_sql_standard_datetimes? reverse reverse_order schema_and_table select select_all select_append select_hash select_map select_more select_order_map select_sql server set set_defaults set_graph_aliases set_overrides simple_select_all? single_record single_value sql subscript_sql sum supports_cte? supports_distinct_on? supports_intersect_except? supports_intersect_except_all? supports_is_true? supports_join_using? supports_modifying_joins? supports_multiple_column_in? supports_timestamp_timezones? supports_timestamp_usecs? supports_window_functions? to_csv to_hash to_prepared_statement truncate truncate_sql unfiltered ungraphed ungrouped union unlimited unordered unused_table_alias update update_sql where window_function_sql window_sql with with_recursive with_sql

### Included Modules

StoredProcedures Metaprogramming Enumerable

### Classes and Modules

Module Sequel::Dataset::PreparedStatementMethods
Module Sequel::Dataset::StoredProcedureMethods
Module Sequel::Dataset::StoredProcedures

### Attributes

convert_types | [RW] | Whether to convert some Java types to ruby types when retrieving rows. Uses the database‘s setting by default, can be set to false to roughly double performance when fetching rows.

### Public Class methods

new(db, opts={})

Use the convert_types default setting from the database

[Source]

         # File lib/sequel/adapters/jdbc.rb, line 514
    514:       def initialize(db, opts={})
    515:         @convert_types = db.convert_types
    516:         super
    517:       end

### Public Instance methods

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

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

[Source]

         # File lib/sequel/adapters/do.rb, line 175
    175:       def fetch_rows(sql)
    176:         execute(sql) do |reader|
    177:           cols = @columns = reader.fields.map{|f| output_identifier(f)}
    178:           while(reader.next!) do
    179:             h = {}
    180:             cols.zip(reader.values).each{|k, v| h[k] = v}
    181:             yield h
    182:           end
    183:         end
    184:         self
    185:       end

fetch_rows(sql, &block)

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

[Source]

         # File lib/sequel/adapters/jdbc.rb, line 520
    520:       def fetch_rows(sql, &block)
    521:         execute(sql){|result| process_result_set(result, &block)}
    522:         self
    523:       end

prepare(type, name=nil, *values)

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

[Source]

         # File lib/sequel/adapters/jdbc.rb, line 527
    527:       def prepare(type, name=nil, *values)
    528:         ps = to_prepared_statement(type, values)
    529:         ps.extend(PreparedStatementMethods)
    530:         if name
    531:           ps.prepared_statement_name = name
    532:           db.prepared_statements[name] = ps
    533:         end
    534:         ps
    535:       end

## Methods that execute code on the database

These methods all execute the dataset‘s SQL on the database. They don‘t return modified datasets, so if used in a method chain they should be the last method called.

### Constants

ACTION_METHODS | = | %w'<< [] []= all avg count columns columns! delete each empty? fetch_rows first get import insert insert_multiple interval last map max min multi_insert range select_hash select_map select_order_map set single_record single_value sum to_csv to_hash truncate update'.map{|x| x.to_sym} |  | Action methods defined by Sequel that execute code on the database.

### Public Instance methods

<<(*args)

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

[Source]

        # File lib/sequel/dataset/actions.rb, line 18
    18:     def <<(*args)
    19:       insert(*args)
    20:     end

[](*conditions)

Returns the first record matching the conditions. Examples:

      ds[:id=>1] => {:id=1}

[Source]

        # File lib/sequel/dataset/actions.rb, line 25
    25:     def [](*conditions)
    26:       raise(Error, ARRAY_ACCESS_ERROR_MSG) if (conditions.length == 1 and conditions.first.is_a?(Integer)) or conditions.length == 0
    27:       first(*conditions)
    28:     end

[]=(conditions, values)

Update all records matching the conditions with the values specified. Examples:

      ds[:id=>1] = {:id=>2} # SQL: UPDATE ... SET id = 2 WHERE id = 1

[Source]

        # File lib/sequel/dataset/actions.rb, line 34
    34:     def []=(conditions, values)
    35:       filter(conditions).update(values)
    36:     end

all(&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/dataset/actions.rb, line 40
    40:     def all(&block)
    41:       a = []
    42:       each{|r| a << r}
    43:       post_load(a)
    44:       a.each(&block) if block
    45:       a
    46:     end

avg(column)

Returns the average value for the given column.

[Source]

        # File lib/sequel/dataset/actions.rb, line 49
    49:     def avg(column)
    50:       aggregate_dataset.get{avg(column)}
    51:     end

columns()

Returns the columns in the result set in 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 may be an empty array depending on how the adapter is programmed.

If you are looking for all columns for a single table and maybe some information about each column (e.g. type), see Database#schema.

[Source]

        # File lib/sequel/dataset/actions.rb, line 62
    62:     def columns
    63:       return @columns if @columns
    64:       ds = unfiltered.unordered.clone(:distinct => nil, :limit => 1)
    65:       ds.each{break}
    66:       @columns = ds.instance_variable_get(:@columns)
    67:       @columns || []
    68:     end

columns!()

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

[Source]

        # File lib/sequel/dataset/actions.rb, line 72
    72:     def columns!
    73:       @columns = nil
    74:       columns
    75:     end

count()

Returns the number of records in the dataset.

[Source]

        # File lib/sequel/dataset/actions.rb, line 78
    78:     def count
    79:       aggregate_dataset.get{COUNT(:*){}.as(count)}.to_i
    80:     end

delete()

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

[Source]

        # File lib/sequel/dataset/actions.rb, line 84
    84:     def delete
    85:       execute_dui(delete_sql)
    86:     end

each() {|row_proc.call(r)}| ...}

Iterates over the records in the dataset as they are yielded from the database adapter, and returns self.

Note that this method is not safe to use on many adapters if you are running additional queries inside the provided block. If you are running queries inside the block, you should use `all` instead of `each` for the outer queries, or use a separate thread or shard inside `each`.

[Source]

         # File lib/sequel/dataset/actions.rb, line 95
     95:     def each(&block)
     96:       if @opts[:graph]
     97:         graph_each(&block)
     98:       elsif row_proc = @row_proc
     99:         fetch_rows(select_sql){|r| yield row_proc.call(r)}
    100:       else
    101:         fetch_rows(select_sql, &block)
    102:       end
    103:       self
    104:     end

empty?()

Returns true if no records exist in the dataset, false otherwise

[Source]

         # File lib/sequel/dataset/actions.rb, line 107
    107:     def empty?
    108:       get(1).nil?
    109:     end

fetch_rows(sql, &block)

Executes a select query and fetches records, passing each record to the supplied block. The yielded records should be hashes with symbol keys.

[Source]

         # File lib/sequel/dataset/actions.rb, line 113
    113:     def fetch_rows(sql, &block)
    114:       raise NotImplemented, NOTIMPL_MSG
    115:     end

first(*args, &block)

If a integer 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/dataset/actions.rb, line 136
    136:     def first(*args, &block)
    137:       ds = block ? filter(&block) : self
    138:
    139:       if args.empty?
    140:         ds.single_record
    141:       else
    142:         args = (args.size == 1) ? args.first : args
    143:         if Integer === args
    144:           ds.limit(args).all
    145:         else
    146:           ds.filter(args).single_record
    147:         end
    148:       end
    149:     end

get(column=nil, &block)

Return the column value for the first matching record in the dataset. Raises an error if both an argument and block is given.

      ds.get(:id)
      ds.get{|o| o.sum(:id)}

[Source]

         # File lib/sequel/dataset/actions.rb, line 156
    156:     def get(column=nil, &block)
    157:       if column
    158:         raise(Error, ARG_BLOCK_ERROR_MSG) if block
    159:         select(column).single_value
    160:       else
    161:         select(&block).single_value
    162:       end
    163:     end

import(columns, values, opts={})

Inserts multiple records into the associated table. This method can be used to efficiently insert a large number of records into a table in a single query if the database supports it. Inserts are automatically wrapped in a transaction.

This method is called with a columns array and an array of value arrays:

      dataset.import([:x, :y], [[1, 2], [3, 4]])

This method also accepts a dataset instead of an array of value arrays:

      dataset.import([:x, :y], other_dataset.select(:a___x, :b___y))

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.import([:x, :y], [[1, 2], [3, 4], ...], :slice => 50)

[Source]

         # File lib/sequel/dataset/actions.rb, line 184
    184:     def import(columns, values, opts={})
    185:       return @db.transaction{insert(columns, values)} if values.is_a?(Dataset)
    186:
    187:       return if values.empty?
    188:       raise(Error, IMPORT_ERROR_MSG) if columns.empty?
    189:
    190:       if slice_size = opts[:commit_every] || opts[:slice]
    191:         offset = 0
    192:         loop do
    193:           @db.transaction(opts){multi_insert_sql(columns, values[offset, slice_size]).each{|st| execute_dui(st)}}
    194:           offset += slice_size
    195:           break if offset >= values.length
    196:         end
    197:       else
    198:         statements = multi_insert_sql(columns, values)
    199:         @db.transaction{statements.each{|st| execute_dui(st)}}
    200:       end
    201:     end

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. See insert_sql.

[Source]

         # File lib/sequel/dataset/actions.rb, line 206
    206:     def insert(*values)
    207:       execute_insert(insert_sql(*values))
    208:     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/dataset/actions.rb, line 214
    214:     def insert_multiple(array, &block)
    215:       if block
    216:         array.each {|i| insert(block[i])}
    217:       else
    218:         array.each {|i| insert(i)}
    219:       end
    220:     end

interval(column)

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

[Source]

         # File lib/sequel/dataset/actions.rb, line 224
    224:     def interval(column)
    225:       aggregate_dataset.get{max(column) - min(column)}
    226:     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/dataset/actions.rb, line 232
    232:     def last(*args, &block)
    233:       raise(Error, 'No order specified') unless @opts[:order]
    234:       reverse.first(*args, &block)
    235:     end

map(column=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. Raises an error if both an argument and block are given. Examples:

      ds.map(:id) => [1, 2, 3, ...]
      ds.map{|r| r[:id] * 2} => [2, 4, 6, ...]

[Source]

         # File lib/sequel/dataset/actions.rb, line 243
    243:     def map(column=nil, &block)
    244:       if column
    245:         raise(Error, ARG_BLOCK_ERROR_MSG) if block
    246:         super(){|r| r[column]}
    247:       else
    248:         super(&block)
    249:       end
    250:     end

max(column)

Returns the maximum value for the given column.

[Source]

         # File lib/sequel/dataset/actions.rb, line 253
    253:     def max(column)
    254:       aggregate_dataset.get{max(column)}
    255:     end

min(column)

Returns the minimum value for the given column.

[Source]

         # File lib/sequel/dataset/actions.rb, line 258
    258:     def min(column)
    259:       aggregate_dataset.get{min(column)}
    260:     end

multi_insert(hashes, opts={})

This is a front end for import that allows you to submit an array of hashes instead of arrays of columns and values:

      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.

You can also use the :slice or :commit_every option that import accepts.

[Source]

         # File lib/sequel/dataset/actions.rb, line 272
    272:     def multi_insert(hashes, opts={})
    273:       return if hashes.empty?
    274:       columns = hashes.first.keys
    275:       import(columns, hashes.map{|h| columns.map{|c| h[c]}}, opts)
    276:     end

range(column)

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

[Source]

         # File lib/sequel/dataset/actions.rb, line 280
    280:     def range(column)
    281:       if r = aggregate_dataset.select{[min(column).as(v1), max(column).as(v2)]}.first
    282:         (r[:v1]..r[:v2])
    283:       end
    284:     end

select_hash(key_column, value_column)

Returns a hash with key_column values as keys and value_column values as values. Similar to to_hash, but only selects the two columns.

[Source]

         # File lib/sequel/dataset/actions.rb, line 288
    288:     def select_hash(key_column, value_column)
    289:       select(key_column, value_column).to_hash(hash_key_symbol(key_column), hash_key_symbol(value_column))
    290:     end

select_map(column=nil, &block)

Selects the column given (either as an argument or as a block), and returns an array of all values of that column in the dataset. If you give a block argument that returns an array with multiple entries, the contents of the resulting array are undefined.

[Source]

         # File lib/sequel/dataset/actions.rb, line 296
    296:     def select_map(column=nil, &block)
    297:       ds = naked.ungraphed
    298:       ds = if column
    299:         raise(Error, ARG_BLOCK_ERROR_MSG) if block
    300:         ds.select(column)
    301:       else
    302:         ds.select(&block)
    303:       end
    304:       ds.map{|r| r.values.first}
    305:     end

select_order_map(column=nil, &block)

The same as select_map, but in addition orders the array by the column.

[Source]

         # File lib/sequel/dataset/actions.rb, line 308
    308:     def select_order_map(column=nil, &block)
    309:       ds = naked.ungraphed
    310:       ds = if column
    311:         raise(Error, ARG_BLOCK_ERROR_MSG) if block
    312:         ds.select(column).order(unaliased_identifier(column))
    313:       else
    314:         ds.select(&block).order(&block)
    315:       end
    316:       ds.map{|r| r.values.first}
    317:     end

set(*args)

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

[Source]

         # File lib/sequel/dataset/actions.rb, line 321
    321:     def set(*args)
    322:       update(*args)
    323:     end

single_record()

Returns the first record in the dataset.

[Source]

         # File lib/sequel/dataset/actions.rb, line 326
    326:     def single_record
    327:       clone(:limit=>1).each{|r| return r}
    328:       nil
    329:     end

single_value()

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

[Source]

         # File lib/sequel/dataset/actions.rb, line 333
    333:     def single_value
    334:       if r = naked.ungraphed.single_record
    335:         r.values.first
    336:       end
    337:     end

sum(column)

Returns the sum for the given column.

[Source]

         # File lib/sequel/dataset/actions.rb, line 340
    340:     def sum(column)
    341:       aggregate_dataset.get{sum(column)}
    342:     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 shouldn‘t use this.

[Source]

         # File lib/sequel/dataset/actions.rb, line 352
    352:     def to_csv(include_column_titles = true)
    353:       n = naked
    354:       cols = n.columns
    355:       csv = ''
    356:       csv << "#{cols.join(COMMA_SEPARATOR)}\r\n" if include_column_titles
    357:       n.each{|r| csv << "#{cols.collect{|c| r[c]}.join(COMMA_SEPARATOR)}\r\n"}
    358:       csv
    359:     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/dataset/actions.rb, line 365
    365:     def to_hash(key_column, value_column = nil)
    366:       inject({}) do |m, r|
    367:         m[r[key_column]] = value_column ? r[value_column] : r
    368:         m
    369:       end
    370:     end

truncate()

Truncates the dataset. Returns nil.

[Source]

         # File lib/sequel/dataset/actions.rb, line 373
    373:     def truncate
    374:       execute_ddl(truncate_sql)
    375:     end

update(values={})

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

[Source]

         # File lib/sequel/dataset/actions.rb, line 379
    379:     def update(values={})
    380:       execute_dui(update_sql(values))
    381:     end

## Methods that describe what the dataset supports

These methods all return booleans, with most describing whether or not the dataset supports a feature.

### Constants

WITH_SUPPORTED | = | :select_with_sql |  | Method used to check if WITH is supported

### Public Instance methods

provides_accurate_rows_matched?()

Whether this dataset will provide accurate number of rows matched for delete and update statements. Accurate in this case is the number of rows matched by the dataset‘s filter.

[Source]

        # File lib/sequel/dataset/features.rb, line 20
    20:     def provides_accurate_rows_matched?
    21:       true
    22:     end

quote_identifiers?()

Whether this dataset quotes identifiers.

[Source]

        # File lib/sequel/dataset/features.rb, line 13
    13:     def quote_identifiers?
    14:       @quote_identifiers
    15:     end

requires_sql_standard_datetimes?()

Whether the dataset requires SQL standard datetimes (false by default, as most allow strings with ISO 8601 format.

[Source]

        # File lib/sequel/dataset/features.rb, line 26
    26:     def requires_sql_standard_datetimes?
    27:       false
    28:     end

supports_cte?()

Whether the dataset supports common table expressions (the WITH clause).

[Source]

        # File lib/sequel/dataset/features.rb, line 31
    31:     def supports_cte?
    32:       select_clause_methods.include?(WITH_SUPPORTED)
    33:     end

supports_distinct_on?()

Whether the dataset supports the DISTINCT ON clause, false by default.

[Source]

        # File lib/sequel/dataset/features.rb, line 36
    36:     def supports_distinct_on?
    37:       false
    38:     end

supports_intersect_except?()

Whether the dataset supports the INTERSECT and EXCEPT compound operations, true by default.

[Source]

        # File lib/sequel/dataset/features.rb, line 41
    41:     def supports_intersect_except?
    42:       true
    43:     end

supports_intersect_except_all?()

Whether the dataset supports the INTERSECT ALL and EXCEPT ALL compound operations, true by default.

[Source]

        # File lib/sequel/dataset/features.rb, line 46
    46:     def supports_intersect_except_all?
    47:       true
    48:     end

supports_is_true?()

Whether the dataset supports the IS TRUE syntax.

[Source]

        # File lib/sequel/dataset/features.rb, line 51
    51:     def supports_is_true?
    52:       true
    53:     end

supports_join_using?()

Whether the dataset supports the JOIN table USING (column1, …) syntax.

[Source]

        # File lib/sequel/dataset/features.rb, line 56
    56:     def supports_join_using?
    57:       true
    58:     end

supports_modifying_joins?()

Whether modifying joined datasets is supported.

[Source]

        # File lib/sequel/dataset/features.rb, line 61
    61:     def supports_modifying_joins?
    62:       false
    63:     end

supports_multiple_column_in?()

Whether the IN/NOT IN operators support multiple columns when an array of values is given.

[Source]

        # File lib/sequel/dataset/features.rb, line 67
    67:     def supports_multiple_column_in?
    68:       true
    69:     end

supports_timestamp_timezones?()

Whether the dataset supports timezones in literal timestamps

[Source]

        # File lib/sequel/dataset/features.rb, line 72
    72:     def supports_timestamp_timezones?
    73:       false
    74:     end

supports_timestamp_usecs?()

Whether the dataset supports fractional seconds in literal timestamps

[Source]

        # File lib/sequel/dataset/features.rb, line 77
    77:     def supports_timestamp_usecs?
    78:       true
    79:     end

supports_window_functions?()

Whether the dataset supports window functions.

[Source]

        # File lib/sequel/dataset/features.rb, line 82
    82:     def supports_window_functions?
    83:       false
    84:     end

## Methods related to dataset graphing

Dataset graphing changes the dataset to yield hashes where keys are table name symbols and columns are hashes representing the values related to that table. All of these methods return modified copies of the receiver.

### Public Instance methods

add_graph_aliases(graph_aliases)

Adds the given 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/dataset/graph.rb, line 13
    13:     def add_graph_aliases(graph_aliases)
    14:       ds = select_more(*graph_alias_columns(graph_aliases))
    15:       ds.opts[:graph_aliases] = (ds.opts[:graph_aliases] || (ds.opts[:graph][:column_aliases] rescue {}) || {}).merge(graph_aliases)
    16:       ds
    17:     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, :name=>albums.name, :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 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 return 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:
  - :from_self_alias - The alias to use when the receiver is not a graphed dataset but it contains multiple FROM tables or a JOIN. In this case, the receiver is wrapped in a from_self before graphing, and this option determines the alias to use.
  - :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/dataset/graph.rb, line 67
     67:     def graph(dataset, join_conditions = nil, options = {}, &block)
     68:       # Allow the use of a model, dataset, or symbol as the first argument
     69:       # Find the table name/dataset based on the argument
     70:       dataset = dataset.dataset if dataset.respond_to?(:dataset)
     71:       table_alias = options[:table_alias]
     72:       case dataset
     73:       when Symbol
     74:         table = dataset
     75:         dataset = @db[dataset]
     76:         table_alias ||= table
     77:       when ::Sequel::Dataset
     78:         if dataset.simple_select_all?
     79:           table = dataset.opts[:from].first
     80:           table_alias ||= table
     81:         else
     82:           table = dataset
     83:           table_alias ||= dataset_alias((@opts[:num_dataset_sources] || 0)+1)
     84:         end
     85:       else
     86:         raise Error, "The dataset argument should be a symbol, dataset, or model"
     87:       end
     88:
     89:       # Raise Sequel::Error with explanation that the table alias has been used
     90:       raise_alias_error = lambda do
     91:         raise(Error, "this #{options[:table_alias] ? 'alias' : 'table'} has already been been used, please specify " \
     92:           "#{options[:table_alias] ? 'a different alias' : 'an alias via the :table_alias option'}")
     93:       end
     94:
     95:       # Only allow table aliases that haven't been used
     96:       raise_alias_error.call if @opts[:graph] && @opts[:graph][:table_aliases] && @opts[:graph][:table_aliases].include?(table_alias)
     97:
     98:       # Use a from_self if this is already a joined table
     99:       ds = (!@opts[:graph] && (@opts[:from].length > 1 || @opts[:join])) ? from_self(:alias=>options[:from_self_alias] || first_source) : self
    100:
    101:       # Join the table early in order to avoid cloning the dataset twice
    102:       ds = ds.join_table(options[:join_type] || :left_outer, table, join_conditions, :table_alias=>table_alias, :implicit_qualifier=>options[:implicit_qualifier], &block)
    103:       opts = ds.opts
    104:
    105:       # Whether to include the table in the result set
    106:       add_table = options[:select] == false ? false : true
    107:       # Whether to add the columns to the list of column aliases
    108:       add_columns = !ds.opts.include?(:graph_aliases)
    109:
    110:       # Setup the initial graph data structure if it doesn't exist
    111:       unless graph = opts[:graph]
    112:         master = alias_symbol(ds.first_source_alias)
    113:         raise_alias_error.call if master == table_alias
    114:         # Master hash storing all .graph related information
    115:         graph = opts[:graph] = {}
    116:         # Associates column aliases back to tables and columns
    117:         column_aliases = graph[:column_aliases] = {}
    118:         # Associates table alias (the master is never aliased)
    119:         table_aliases = graph[:table_aliases] = {master=>self}
    120:         # Keep track of the alias numbers used
    121:         ca_num = graph[:column_alias_num] = Hash.new(0)
    122:         # All columns in the master table are never
    123:         # aliased, but are not included if set_graph_aliases
    124:         # has been used.
    125:         if add_columns
    126:           select = opts[:select] = []
    127:           columns.each do |column|
    128:             column_aliases[column] = [master, column]
    129:             select.push(SQL::QualifiedIdentifier.new(master, column))
    130:           end
    131:         end
    132:       end
    133:
    134:       # Add the table alias to the list of aliases
    135:       # Even if it isn't been used in the result set,
    136:       # we add a key for it with a nil value so we can check if it
    137:       # is used more than once
    138:       table_aliases = graph[:table_aliases]
    139:       table_aliases[table_alias] = add_table ? dataset : nil
    140:
    141:       # Add the columns to the selection unless we are ignoring them
    142:       if add_table && add_columns
    143:         select = opts[:select]
    144:         column_aliases = graph[:column_aliases]
    145:         ca_num = graph[:column_alias_num]
    146:         # Which columns to add to the result set
    147:         cols = options[:select] || dataset.columns
    148:         # If the column hasn't been used yet, don't alias it.
    149:         # If it has been used, try table_column.
    150:         # If that has been used, try table_column_N
    151:         # using the next value of N that we know hasn't been
    152:         # used
    153:         cols.each do |column|
    154:           col_alias, identifier = if column_aliases[column]
    155:             column_alias = "#{table_alias}_#{column}""#{table_alias}_#{column}"
    156:             if column_aliases[column_alias]
    157:               column_alias_num = ca_num[column_alias]
    158:               column_alias = "#{column_alias}_#{column_alias_num}""#{column_alias}_#{column_alias_num}"
    159:               ca_num[column_alias] += 1
    160:             end
    161:             [column_alias, SQL::QualifiedIdentifier.new(table_alias, column).as(column_alias)]
    162:           else
    163:             [column, SQL::QualifiedIdentifier.new(table_alias, column)]
    164:           end
    165:           column_aliases[col_alias] = [table_alias, column]
    166:           select.push(identifier)
    167:         end
    168:       end
    169:       ds
    170:     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], :forty_two=>[:albums, :fourtwo, 42]).first
      => {:artists=>{:name=>artists.name}, :albums=>{:name=>albums.name, :fourtwo=>42}}

Arguments:

- graph_aliases - Should be a hash with keys being symbols of column aliases, and values being arrays with two or three elements. The first element of the array should be the table alias symbol, and the second should be the actual column name symbol. If the array has a third element, it is used as the value returned, instead of table_alias.column_name.

[Source]

         # File lib/sequel/dataset/graph.rb, line 189
    189:     def set_graph_aliases(graph_aliases)
    190:       ds = select(*graph_alias_columns(graph_aliases))
    191:       ds.opts[:graph_aliases] = graph_aliases
    192:       ds
    193:     end

ungraphed()

Remove the splitting of results into subhashes. Also removes metadata related to graphing, so you should not call graph any tables to this dataset after calling this method.

[Source]

         # File lib/sequel/dataset/graph.rb, line 198
    198:     def ungraphed
    199:       clone(:graph=>nil)
    200:     end

## Miscellaneous methods

These methods don‘t fit cleanly into another section.

### Constants

NOTIMPL_MSG | = | "This method must be overridden in Sequel adapters".freeze
ARRAY_ACCESS_ERROR_MSG | = | 'You cannot call Dataset#[] with an integer or with no arguments.'.freeze
ARG_BLOCK_ERROR_MSG | = | 'Must use either an argument or a block, not both'.freeze
IMPORT_ERROR_MSG | = | 'Using Sequel::Dataset#import an empty column array is not allowed'.freeze

### Attributes

db | [RW] | The database that corresponds to this dataset
opts | [RW] | The hash of options for this dataset, keys are symbols.

### Public Class methods

new(db, opts = nil)

Constructs a new Dataset instance with an associated database and options. Datasets are usually constructed by invoking the Database#[] method:

      DB[:posts]

Sequel::Dataset is an abstract class that is not useful by itself. Each database adaptor should provide a subclass of Sequel::Dataset, and have the Database#dataset method return an instance of that class.

[Source]

        # File lib/sequel/dataset/misc.rb, line 27
    27:     def initialize(db, opts = nil)
    28:       @db = db
    29:       @quote_identifiers = db.quote_identifiers? if db.respond_to?(:quote_identifiers?)
    30:       @identifier_input_method = db.identifier_input_method if db.respond_to?(:identifier_input_method)
    31:       @identifier_output_method = db.identifier_output_method if db.respond_to?(:identifier_output_method)
    32:       @opts = opts || {}
    33:       @row_proc = nil
    34:     end

### Public Instance methods

as(aliaz)

Return the dataset as an aliased expression with the given alias. You can use this as a FROM or JOIN dataset, or as a column if this dataset returns a single row and column.

[Source]

        # File lib/sequel/dataset/misc.rb, line 39
    39:     def as(aliaz)
    40:       ::Sequel::SQL::AliasedExpression.new(self, aliaz)
    41:     end

each_server() {|server(s)}| ...}

Yield a dataset for each server in the connection pool that is tied to that server. Intended for use in sharded environments where all servers need to be modified with the same data:

      DB[:configs].where(:key=>'setting').each_server{|ds| ds.update(:value=>'new_value')}

[Source]

        # File lib/sequel/dataset/misc.rb, line 48
    48:     def each_server
    49:       db.servers.each{|s| yield server(s)}
    50:     end

first_source()

Alias of first_source_alias

[Source]

        # File lib/sequel/dataset/misc.rb, line 53
    53:     def first_source
    54:       first_source_alias
    55:     end

first_source_alias()

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 aliased name.

[Source]

        # File lib/sequel/dataset/misc.rb, line 59
    59:     def first_source_alias
    60:       source = @opts[:from]
    61:       if source.nil? || source.empty?
    62:         raise Error, 'No source specified for query'
    63:       end
    64:       case s = source.first
    65:       when SQL::AliasedExpression
    66:         s.aliaz
    67:       when Symbol
    68:         sch, table, aliaz = split_symbol(s)
    69:         aliaz ? aliaz.to_sym : s
    70:       else
    71:         s
    72:       end
    73:     end

first_source_table()

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 original table, not the alias

[Source]

        # File lib/sequel/dataset/misc.rb, line 78
    78:     def first_source_table
    79:       source = @opts[:from]
    80:       if source.nil? || source.empty?
    81:         raise Error, 'No source specified for query'
    82:       end
    83:       case s = source.first
    84:       when SQL::AliasedExpression
    85:         s.expression
    86:       when Symbol
    87:         sch, table, aliaz = split_symbol(s)
    88:         aliaz ? (sch ? SQL::QualifiedIdentifier.new(sch, table) : table.to_sym) : s
    89:       else
    90:         s
    91:       end
    92:     end

inspect()

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

[Source]

        # File lib/sequel/dataset/misc.rb, line 96
    96:     def inspect
    97:       "#<#{self.class}: #{sql.inspect}>"
    98:     end

unused_table_alias(table_alias)

Creates a unique table alias that hasn‘t already been used in the dataset. table_alias can be any type of object accepted by alias_symbol. The symbol returned will be the implicit alias in the argument, possibly appended with "_N" if the implicit alias has already been used, where N is an integer starting at 0 and increasing until an unused one is found.

[Source]

         # File lib/sequel/dataset/misc.rb, line 106
    106:     def unused_table_alias(table_alias)
    107:       table_alias = alias_symbol(table_alias)
    108:       used_aliases = []
    109:       used_aliases += opts[:from].map{|t| alias_symbol(t)} if opts[:from]
    110:       used_aliases += opts[:join].map{|j| j.table_alias ? alias_alias_symbol(j.table_alias) : alias_symbol(j.table)} if opts[:join]
    111:       if used_aliases.include?(table_alias)
    112:         i = 0
    113:         loop do
    114:           ta = "#{table_alias}_#{i}""#{table_alias}_#{i}"
    115:           return ta unless used_aliases.include?(ta)
    116:           i += 1
    117:         end
    118:       else
    119:         table_alias
    120:       end
    121:     end

## Methods related to prepared statements or bound variables

On some adapters, these use native prepared statements and bound variables, on others support is emulated. For details, see the "Prepared Statements/Bound Variables" guide.

### Classes and Modules

Module Sequel::Dataset::ArgumentMapper
Module Sequel::Dataset::UnnumberedArgumentMapper

### Constants

PREPARED_ARG_PLACEHOLDER | = | LiteralString.new('?').freeze

### Public Instance methods

bind(bind_vars={})

Set the bind variables to use for the call. If bind variables have already been set for this dataset, they are updated with the contents of bind_vars.

[Source]

         # File lib/sequel/dataset/prepared_statements.rb, line 179
    179:     def bind(bind_vars={})
    180:       clone(:bind_vars=>@opts[:bind_vars] ? @opts[:bind_vars].merge(bind_vars) : bind_vars)
    181:     end

call(type, bind_variables={}, *values, &block)

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/dataset/prepared_statements.rb, line 188
    188:     def call(type, bind_variables={}, *values, &block)
    189:       prepare(type, nil, *values).call(bind_variables, &block)
    190:     end

prepare(type, name=nil, *values)

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/dataset/prepared_statements.rb, line 201
    201:     def prepare(type, name=nil, *values)
    202:       ps = to_prepared_statement(type, values)
    203:       db.prepared_statements[name] = ps if name
    204:       ps
    205:     end

### Protected Instance methods

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/dataset/prepared_statements.rb, line 211
    211:     def to_prepared_statement(type, values=nil)
    212:       ps = bind
    213:       ps.extend(PreparedStatementMethods)
    214:       ps.prepared_type = type
    215:       ps.prepared_modify_values = values
    216:       ps
    217:     end

## Methods that return modified datasets

These methods all return modified copies of the receiver.

### Constants

COLUMN_CHANGE_OPTS | = | [:select, :sql, :from, :join].freeze |  | The dataset options that require the removal of cached columns if changed.
NON_SQL_OPTIONS | = | [:server, :defaults, :overrides, :graph, :eager_graph, :graph_aliases] |  | Which options don‘t affect the SQL generation. Used by simple_select_all? to determine if this is a simple SELECT * FROM table.
CONDITIONED_JOIN_TYPES | = | [:inner, :full_outer, :right_outer, :left_outer, :full, :right, :left] |  | These symbols have _join methods created (e.g. inner_join) that call join_table with the symbol, passing along the arguments and block from the method call.
UNCONDITIONED_JOIN_TYPES | = | [:natural, :natural_left, :natural_right, :natural_full, :cross] |  | These symbols have _join methods created (e.g. natural_join) that call join_table with the symbol. They only accept a single table argument which is passed to join_table, and they raise an error if called with a block.
JOIN_METHODS | = | (CONDITIONED_JOIN_TYPES + UNCONDITIONED_JOIN_TYPES).map{|x| "#{x}_join".to_sym} + [:join, :join_table] |  | All methods that return modified datasets with a joined table added.

QUERY_METHODS

=

%w'add_graph_aliases and distinct except exclude filter for_update from from_self graph grep group group_and_count group_by having intersect invert limit lock_style naked or order order_append order_by order_more order_prepend paginate qualify query reverse reverse_order select select_all select_append select_more server set_defaults set_graph_aliases set_overrides unfiltered ungraphed ungrouped union unlimited unordered where with with_recursive with_sql'.collect{|x| x.to_sym} + JOIN_METHODS

Methods that return modified datasets

### Public Instance methods

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.

      ds.filter(:a).and(:b) # SQL: WHERE a AND b

[Source]

        # File lib/sequel/dataset/query.rb, line 43
    43:     def and(*cond, &block)
    44:       raise(InvalidOperation, "No existing filter found.") unless @opts[:having] || @opts[:where]
    45:       filter(*cond, &block)
    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/dataset/query.rb, line 51
    51:     def clone(opts = {})
    52:       c = super()
    53:       c.opts = @opts.merge(opts)
    54:       c.instance_variable_set(:@columns, nil) if opts.keys.any?{|o| COLUMN_CHANGE_OPTS.include?(o)}
    55:       c
    56:     end

distinct(*args)

Returns a copy of the dataset with the SQL DISTINCT clause. The DISTINCT clause is used to remove duplicate rows from the output. If arguments are provided, uses a DISTINCT ON clause, in which case it will only be distinct on those columns, instead of all returned columns. Raises an error if arguments are given and DISTINCT ON is not supported.

     dataset.distinct # SQL: SELECT DISTINCT * FROM items
     dataset.order(:id).distinct(:id) # SQL: SELECT DISTINCT ON (id) * FROM items ORDER BY id

[Source]

        # File lib/sequel/dataset/query.rb, line 67
    67:     def distinct(*args)
    68:       raise(InvalidOperation, "DISTINCT ON not supported") if !args.empty? && !supports_distinct_on?
    69:       clone(:distinct => args)
    70:     end

except(dataset, opts={})

Adds an EXCEPT clause using a second dataset object. An EXCEPT compound dataset returns all rows in the current dataset that are not in the given dataset. Raises an InvalidOperation if the operation is not supported. Options:

- :all - Set to true to use EXCEPT ALL instead of EXCEPT, so duplicate rows can occur
- :from_self - Set to false to not wrap the returned dataset in a from_self, use with care.

  DB[:items].except(DB).sql #=> "SELECT * FROM items EXCEPT SELECT * FROM other_items"

[Source]

        # File lib/sequel/dataset/query.rb, line 82
    82:     def except(dataset, opts={})
    83:       opts = {:all=>opts} unless opts.is_a?(Hash)
    84:       raise(InvalidOperation, "EXCEPT not supported") unless supports_intersect_except?
    85:       raise(InvalidOperation, "EXCEPT ALL not supported") if opts[:all] && !supports_intersect_except_all?
    86:       compound_clone(:except, dataset, opts)
    87:     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/dataset/query.rb, line 93
     93:     def exclude(*cond, &block)
     94:       clause = (@opts[:having] ? :having : :where)
     95:       cond = cond.first if cond.size == 1
     96:       cond = filter_expr(cond, &block)
     97:       cond = SQL::BooleanExpression.invert(cond)
     98:       cond = SQL::BooleanExpression.new(:AND, @opts[clause], cond) if @opts[clause]
     99:       clone(clause => cond)
    100:     end

filter(*cond, &block)

Returns a copy of the dataset with the given conditions imposed upon it. If the query already has a HAVING clause, then the conditions are imposed in the HAVING clause. If not, then they are imposed in the WHERE clause.

filter accepts the following argument types:

- Hash - list of equality/inclusion 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 expression filter DSL.

filter also takes a block, which should return one of the above argument types, and is treated the same way. This block yields a virtual row object, which is easy to use to create identifiers and functions. For more details on the virtual row support, see the "Virtual Rows" guide

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 the the "Dataset Filtering" guide for more examples and details.

[Source]

         # File lib/sequel/dataset/query.rb, line 150
    150:     def filter(*cond, &block)
    151:       _filter(@opts[:having] ? :having : :where, *cond, &block)
    152:     end

for_update()

Returns a cloned dataset with a :update lock style.

[Source]

         # File lib/sequel/dataset/query.rb, line 155
    155:     def for_update
    156:       lock_style(:update)
    157:     end

from(*source)

Returns a copy of the dataset with the source changed.

      dataset.from # SQL: SELECT *
      dataset.from(:blah) # SQL: SELECT * FROM blah
      dataset.from(:blah, :foo) # SQL: SELECT * FROM blah, foo

[Source]

         # File lib/sequel/dataset/query.rb, line 164
    164:     def from(*source)
    165:       table_alias_num = 0
    166:       sources = []
    167:       source.each do |s|
    168:         case s
    169:         when Hash
    170:           s.each{|k,v| sources << SQL::AliasedExpression.new(k,v)}
    171:         when Dataset
    172:           sources << SQL::AliasedExpression.new(s, dataset_alias(table_alias_num+=1))
    173:         when Symbol
    174:           sch, table, aliaz = split_symbol(s)
    175:           if aliaz
    176:             s = sch ? SQL::QualifiedIdentifier.new(sch.to_sym, table.to_sym) : SQL::Identifier.new(table.to_sym)
    177:             sources << SQL::AliasedExpression.new(s, aliaz.to_sym)
    178:           else
    179:             sources << s
    180:           end
    181:         else
    182:           sources << s
    183:         end
    184:       end
    185:       o = {:from=>sources.empty? ? nil : sources}
    186:       o[:num_dataset_sources] = table_alias_num if table_alias_num > 0
    187:       clone(o)
    188:     end

from_self(opts={})

Returns a dataset selecting from the current dataset. Supplying the :alias option controls the name of the result.

      ds = DB[:items].order(:name).select(:id, :name)
      ds.sql                         #=> "SELECT id,name FROM items ORDER BY name"
      ds.from_self.sql               #=> "SELECT * FROM (SELECT id, name FROM items ORDER BY name) AS t1"
      ds.from_self(:alias=>:foo).sql #=> "SELECT * FROM (SELECT id, name FROM items ORDER BY name) AS foo"

[Source]

         # File lib/sequel/dataset/query.rb, line 197
    197:     def from_self(opts={})
    198:       fs = {}
    199:       @opts.keys.each{|k| fs[k] = nil unless NON_SQL_OPTIONS.include?(k)}
    200:       clone(fs).from(opts[:alias] ? as(opts[:alias]) : self)
    201:     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.

      dataset.grep(:a, '%test%') # SQL: SELECT * FROM items WHERE a LIKE '%test%'
      dataset.grep([:a, :b], %w'%test% foo') # SQL: SELECT * FROM items WHERE a LIKE '%test%' OR a LIKE 'foo' OR b LIKE '%test%' OR b LIKE 'foo'

[Source]

         # File lib/sequel/dataset/query.rb, line 211
    211:     def grep(cols, terms)
    212:       filter(SQL::BooleanExpression.new(:OR, *Array(cols).collect{|c| SQL::StringExpression.like(c, *terms)}))
    213:     end

group(*columns)

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

      dataset.group(:id) # SELECT * FROM items GROUP BY id
      dataset.group(:id, :name) # SELECT * FROM items GROUP BY id, name

[Source]

         # File lib/sequel/dataset/query.rb, line 220
    220:     def group(*columns)
    221:       clone(:group => (columns.compact.empty? ? nil : columns))
    222:     end

group_and_count(*columns)

Returns a dataset grouped by the given column with count by group. Column aliases may be supplied, and will be included in the select clause.

Examples:

      ds.group_and_count(:name).all => [{:name=>'a', :count=>1}, ...]
      ds.group_and_count(:first_name, :last_name).all => [{:first_name=>'a', :last_name=>'b', :count=>1}, ...]
      ds.group_and_count(:first_name___name).all => [{:name=>'a', :count=>1}, ...]

[Source]

         # File lib/sequel/dataset/query.rb, line 237
    237:     def group_and_count(*columns)
    238:       group(*columns.map{|c| unaliased_identifier(c)}).select(*(columns + [COUNT_OF_ALL_AS_COUNT]))
    239:     end

group_by(*columns)

Alias of group

[Source]

         # File lib/sequel/dataset/query.rb, line 225
    225:     def group_by(*columns)
    226:       group(*columns)
    227:     end

having(*cond, &block)

Returns a copy of the dataset with the HAVING conditions changed. See filter for argument types.

      dataset.group(:sum).having(:sum=>10) # SQL: SELECT * FROM items GROUP BY sum HAVING sum = 10

[Source]

         # File lib/sequel/dataset/query.rb, line 244
    244:     def having(*cond, &block)
    245:       _filter(:having, *cond, &block)
    246:     end

intersect(dataset, opts={})

Adds an INTERSECT clause using a second dataset object. An INTERSECT compound dataset returns all rows in both the current dataset and the given dataset. Raises an InvalidOperation if the operation is not supported. Options:

- :all - Set to true to use INTERSECT ALL instead of INTERSECT, so duplicate rows can occur
- :from_self - Set to false to not wrap the returned dataset in a from_self, use with care.

  DB[:items].intersect(DB).sql #=> "SELECT * FROM items INTERSECT SELECT * FROM other_items"

[Source]

         # File lib/sequel/dataset/query.rb, line 258
    258:     def intersect(dataset, opts={})
    259:       opts = {:all=>opts} unless opts.is_a?(Hash)
    260:       raise(InvalidOperation, "INTERSECT not supported") unless supports_intersect_except?
    261:       raise(InvalidOperation, "INTERSECT ALL not supported") if opts[:all] && !supports_intersect_except_all?
    262:       compound_clone(:intersect, dataset, opts)
    263:     end

invert()

Inverts the current filter

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

[Source]

         # File lib/sequel/dataset/query.rb, line 269
    269:     def invert
    270:       having, where = @opts[:having], @opts[:where]
    271:       raise(Error, "No current filter") unless having || where
    272:       o = {}
    273:       o[:having] = SQL::BooleanExpression.invert(having) if having
    274:       o[:where] = SQL::BooleanExpression.invert(where) if where
    275:       clone(o)
    276:     end

join(*args, &block)

Alias of inner_join

[Source]

         # File lib/sequel/dataset/query.rb, line 279
    279:     def join(*args, &block)
    280:       inner_join(*args, &block)
    281:     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 (e.g. :inner)
- 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_qualifier - 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/dataset/query.rb, line 313
    313:     def join_table(type, table, expr=nil, options={}, &block)
    314:       using_join = expr.is_a?(Array) && !expr.empty? && expr.all?{|x| x.is_a?(Symbol)}
    315:       if using_join && !supports_join_using?
    316:         h = {}
    317:         expr.each{|s| h[s] = s}
    318:         return join_table(type, table, h, options)
    319:       end
    320:
    321:       case options
    322:       when Hash
    323:         table_alias = options[:table_alias]
    324:         last_alias = options[:implicit_qualifier]
    325:       when Symbol, String, SQL::Identifier
    326:         table_alias = options
    327:         last_alias = nil
    328:       else
    329:         raise Error, "invalid options format for join_table: #{options.inspect}"
    330:       end
    331:
    332:       if Dataset === table
    333:         if table_alias.nil?
    334:           table_alias_num = (@opts[:num_dataset_sources] || 0) + 1
    335:           table_alias = dataset_alias(table_alias_num)
    336:         end
    337:         table_name = table_alias
    338:       else
    339:         table = table.table_name if table.respond_to?(:table_name)
    340:         table_name = table_alias || table
    341:       end
    342:
    343:       join = if expr.nil? and !block_given?
    344:         SQL::JoinClause.new(type, table, table_alias)
    345:       elsif using_join
    346:         raise(Sequel::Error, "can't use a block if providing an array of symbols as expr") if block_given?
    347:         SQL::JoinUsingClause.new(expr, type, table, table_alias)
    348:       else
    349:         last_alias ||= @opts[:last_joined_table] || first_source_alias
    350:         if Sequel.condition_specifier?(expr)
    351:           expr = expr.collect do |k, v|
    352:             k = qualified_column_name(k, table_name) if k.is_a?(Symbol)
    353:             v = qualified_column_name(v, last_alias) if v.is_a?(Symbol)
    354:             [k,v]
    355:           end
    356:         end
    357:         if block_given?
    358:           expr2 = yield(table_name, last_alias, @opts[:join] || [])
    359:           expr = expr ? SQL::BooleanExpression.new(:AND, expr, expr2) : expr2
    360:         end
    361:         SQL::JoinOnClause.new(expr, type, table, table_alias)
    362:       end
    363:
    364:       opts = {:join => (@opts[:join] || []) + [join], :last_joined_table => table_name}
    365:       opts[:num_dataset_sources] = table_alias_num if table_alias_num
    366:       clone(opts)
    367:     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.

      dataset.limit(10) # SQL: SELECT * FROM items LIMIT 10
      dataset.limit(10, 20) # SQL: SELECT * FROM items LIMIT 10 OFFSET 20

[Source]

         # File lib/sequel/dataset/query.rb, line 382
    382:     def limit(l, o = nil)
    383:       return from_self.limit(l, o) if @opts[:sql]
    384:
    385:       if Range === l
    386:         o = l.first
    387:         l = l.last - l.first + (l.exclude_end? ? 0 : 1)
    388:       end
    389:       l = l.to_i if l.is_a?(String) && !l.is_a?(LiteralString)
    390:       if l.is_a?(Integer)
    391:         raise(Error, 'Limits must be greater than or equal to 1') unless l >= 1
    392:       end
    393:       opts = {:limit => l}
    394:       if o
    395:         o = o.to_i if o.is_a?(String) && !o.is_a?(LiteralString)
    396:         if o.is_a?(Integer)
    397:           raise(Error, 'Offsets must be greater than or equal to 0') unless o >= 0
    398:         end
    399:         opts[:offset] = o
    400:       end
    401:       clone(opts)
    402:     end

lock_style(style)

Returns a cloned dataset with the given lock style. If style is a string, it will be used directly. Otherwise, a symbol may be used for database independent locking. Currently :update is respected by most databases, and :share is supported by some.

[Source]

         # File lib/sequel/dataset/query.rb, line 408
    408:     def lock_style(style)
    409:       clone(:lock => style)
    410:     end

naked()

Returns a naked dataset clone - i.e. a dataset that returns records as hashes instead of calling the row proc.

[Source]

         # File lib/sequel/dataset/query.rb, line 414
    414:     def naked
    415:       ds = clone
    416:       ds.row_proc = nil
    417:       ds
    418:     end

or(*cond, &block)

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

      dataset.filter(:a).or(:b) # SQL: SELECT * FROM items WHERE a OR b

[Source]

         # File lib/sequel/dataset/query.rb, line 424
    424:     def or(*cond, &block)
    425:       clause = (@opts[:having] ? :having : :where)
    426:       raise(InvalidOperation, "No existing filter found.") unless @opts[clause]
    427:       cond = cond.first if cond.size == 1
    428:       clone(clause => SQL::BooleanExpression.new(:OR, @opts[clause], filter_expr(cond, &block)))
    429:     end

order(*columns, &block)

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. If a block is given, it is treated as a virtual row block, similar to filter.

      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{|o| o.sum(:name)}.sql #=> 'SELECT * FROM items ORDER BY sum(name)'
      ds.order(nil).sql #=> 'SELECT * FROM items'

[Source]

         # File lib/sequel/dataset/query.rb, line 444
    444:     def order(*columns, &block)
    445:       columns += Array(Sequel.virtual_row(&block)) if block
    446:       clone(:order => (columns.compact.empty?) ? nil : columns)
    447:     end

order_append(*columns, &block)

Alias of order_more, for naming consistency with order_prepend.

[Source]

         # File lib/sequel/dataset/query.rb, line 450
    450:     def order_append(*columns, &block)
    451:       order_more(*columns, &block)
    452:     end

order_by(*columns, &block)

Alias of order

[Source]

         # File lib/sequel/dataset/query.rb, line 455
    455:     def order_by(*columns, &block)
    456:       order(*columns, &block)
    457:     end

order_more(*columns, &block)

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

      ds.order(:a).order(:b).sql #=> 'SELECT * FROM items ORDER BY b'
      ds.order(:a).order_more(:b).sql #=> 'SELECT * FROM items ORDER BY a, b'

[Source]

         # File lib/sequel/dataset/query.rb, line 464
    464:     def order_more(*columns, &block)
    465:       columns = @opts[:order] + columns if @opts[:order]
    466:       order(*columns, &block)
    467:     end

order_prepend(*columns, &block)

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

      ds.order(:a).order(:b).sql #=> 'SELECT * FROM items ORDER BY b'
      ds.order(:a).order_prepend(:b).sql #=> 'SELECT * FROM items ORDER BY b, a'

[Source]

         # File lib/sequel/dataset/query.rb, line 474
    474:     def order_prepend(*columns, &block)
    475:       ds = order(*columns, &block)
    476:       @opts[:order] ? ds.order_more(*@opts[:order]) : ds
    477:     end

qualify(table=first_source)

Qualify to the given table, or first source if not table is given.

[Source]

         # File lib/sequel/dataset/query.rb, line 480
    480:     def qualify(table=first_source)
    481:       qualify_to(table)
    482:     end

qualify_to(table)

Return a copy of the dataset with unqualified identifiers in the SELECT, WHERE, GROUP, HAVING, and ORDER clauses qualified by the given table. If no columns are currently selected, select all columns of the given table.

[Source]

         # File lib/sequel/dataset/query.rb, line 488
    488:     def qualify_to(table)
    489:       o = @opts
    490:       return clone if o[:sql]
    491:       h = {}
    492:       (o.keys & QUALIFY_KEYS).each do |k|
    493:         h[k] = qualified_expression(o[k], table)
    494:       end
    495:       h[:select] = [SQL::ColumnAll.new(table)] if !o[:select] || o[:select].empty?
    496:       clone(h)
    497:     end

qualify_to_first_source()

Qualify the dataset to its current first source. This is useful if you have unqualified identifiers in the query that all refer to the first source, and you want to join to another table which has columns with the same name as columns in the current dataset. See qualify_to.

[Source]

         # File lib/sequel/dataset/query.rb, line 504
    504:     def qualify_to_first_source
    505:       qualify_to(first_source)
    506:     end

reverse(*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/dataset/query.rb, line 510
    510:     def reverse(*order)
    511:       order(*invert_order(order.empty? ? @opts[:order] : order))
    512:     end

reverse_order(*order)

Alias of reverse

[Source]

         # File lib/sequel/dataset/query.rb, line 515
    515:     def reverse_order(*order)
    516:       reverse(*order)
    517:     end

select(*columns, &block)

Returns a copy of the dataset with the columns selected changed to the given columns. This also takes a virtual row block, similar to filter.

      dataset.select(:a) # SELECT a FROM items
      dataset.select(:a, :b) # SELECT a, b FROM items
      dataset.select{|o| [o.a, o.sum(:b)]} # SELECT a, sum(b) FROM items

[Source]

         # File lib/sequel/dataset/query.rb, line 526
    526:     def select(*columns, &block)
    527:       columns += Array(Sequel.virtual_row(&block)) if block
    528:       m = []
    529:       columns.map do |i|
    530:         i.is_a?(Hash) ? m.concat(i.map{|k, v| SQL::AliasedExpression.new(k,v)}) : m << i
    531:       end
    532:       clone(:select => m)
    533:     end

select_all()

Returns a copy of the dataset selecting the wildcard.

      dataset.select(:a).select_all # SELECT * FROM items

[Source]

         # File lib/sequel/dataset/query.rb, line 538
    538:     def select_all
    539:       clone(:select => nil)
    540:     end

select_append(*columns, &block)

Returns a copy of the dataset with the given columns added to the existing selected columns. If no columns are currently selected it will select the columns given in addition to *.

      dataset.select(:a).select(:b) # SELECT b FROM items
      dataset.select(:a).select_append(:b) # SELECT a, b FROM items
      dataset.select_append(:b) # SELECT *, b FROM items

[Source]

         # File lib/sequel/dataset/query.rb, line 549
    549:     def select_append(*columns, &block)
    550:       cur_sel = @opts[:select]
    551:       cur_sel = [WILDCARD] if !cur_sel || cur_sel.empty?
    552:       select(*(cur_sel + columns), &block)
    553:     end

select_more(*columns, &block)

Returns a copy of the dataset with the given columns added to the existing selected columns. If no columns are currently selected it will just select the columns given.

      dataset.select(:a).select(:b) # SELECT b FROM items
      dataset.select(:a).select_more(:b) # SELECT a, b FROM items
      dataset.select_more(:b) # SELECT b FROM items

[Source]

         # File lib/sequel/dataset/query.rb, line 562
    562:     def select_more(*columns, &block)
    563:       columns = @opts[:select] + columns if @opts[:select]
    564:       select(*columns, &block)
    565:     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 (which is SELECT uses :read_only database and all other queries use the :default database).

[Source]

         # File lib/sequel/dataset/query.rb, line 570
    570:     def server(servr)
    571:       clone(:server=>servr)
    572:     end

set_defaults(hash)

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

[Source]

         # File lib/sequel/dataset/query.rb, line 576
    576:     def set_defaults(hash)
    577:       clone(:defaults=>(@opts[:defaults]||{}).merge(hash))
    578:     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/dataset/query.rb, line 582
    582:     def set_overrides(hash)
    583:       clone(:overrides=>hash.merge(@opts[:overrides]||{}))
    584:     end

unfiltered()

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

      dataset.group(:a).having(:a=>1).where(:b).unfiltered # SELECT * FROM items GROUP BY a

[Source]

         # File lib/sequel/dataset/query.rb, line 589
    589:     def unfiltered
    590:       clone(:where => nil, :having => nil)
    591:     end

ungrouped()

Returns a copy of the dataset with no grouping (GROUP or HAVING clause) applied.

      dataset.group(:a).having(:a=>1).where(:b).ungrouped # SELECT * FROM items WHERE b

[Source]

         # File lib/sequel/dataset/query.rb, line 596
    596:     def ungrouped
    597:       clone(:group => nil, :having => nil)
    598:     end

union(dataset, opts={})

Adds a UNION clause using a second dataset object. A UNION compound dataset returns all rows in either the current dataset or the given dataset. Options:

- :all - Set to true to use UNION ALL instead of UNION, so duplicate rows can occur
- :from_self - Set to false to not wrap the returned dataset in a from_self, use with care.

  DB[:items].union(DB).sql #=> "SELECT * FROM items UNION SELECT * FROM other_items"

[Source]

         # File lib/sequel/dataset/query.rb, line 609
    609:     def union(dataset, opts={})
    610:       opts = {:all=>opts} unless opts.is_a?(Hash)
    611:       compound_clone(:union, dataset, opts)
    612:     end

unlimited()

Returns a copy of the dataset with no limit or offset.

      dataset.limit(10, 20).unlimited # SELECT * FROM items

[Source]

         # File lib/sequel/dataset/query.rb, line 617
    617:     def unlimited
    618:       clone(:limit=>nil, :offset=>nil)
    619:     end

unordered()

Returns a copy of the dataset with no order.

      dataset.order(:a).unordered # SELECT * FROM items

[Source]

         # File lib/sequel/dataset/query.rb, line 624
    624:     def unordered
    625:       order(nil)
    626:     end

where(*cond, &block)

Add a condition to the WHERE clause. See filter for argument types.

      dataset.group(:a).having(:a).filter(:b) # SELECT * FROM items GROUP BY a HAVING a AND b
      dataset.group(:a).having(:a).where(:b) # SELECT * FROM items WHERE b GROUP BY a HAVING a

[Source]

         # File lib/sequel/dataset/query.rb, line 632
    632:     def where(*cond, &block)
    633:       _filter(:where, *cond, &block)
    634:     end

with(name, dataset, opts={})

Add a simple common table expression (CTE) with the given name and a dataset that defines the CTE. A common table expression acts as an inline view for the query. Options:

- :args - Specify the arguments/columns for the CTE, should be an array of symbols.
- :recursive - Specify that this is a recursive CTE

[Source]

         # File lib/sequel/dataset/query.rb, line 641
    641:     def with(name, dataset, opts={})
    642:       raise(Error, 'This datatset does not support common table expressions') unless supports_cte?
    643:       clone(:with=>(@opts[:with]||[]) + [opts.merge(:name=>name, :dataset=>dataset)])
    644:     end

with_recursive(name, nonrecursive, recursive, opts={})

Add a recursive common table expression (CTE) with the given name, a dataset that defines the nonrecursive part of the CTE, and a dataset that defines the recursive part of the CTE. Options:

- :args - Specify the arguments/columns for the CTE, should be an array of symbols.
- :union_all - Set to false to use UNION instead of UNION ALL combining the nonrecursive and recursive parts.

[Source]

         # File lib/sequel/dataset/query.rb, line 651
    651:     def with_recursive(name, nonrecursive, recursive, opts={})
    652:       raise(Error, 'This datatset does not support common table expressions') unless supports_cte?
    653:       clone(:with=>(@opts[:with]||[]) + [opts.merge(:recursive=>true, :name=>name, :dataset=>nonrecursive.union(recursive, {:all=>opts[:union_all] != false, :from_self=>false}))])
    654:     end

with_sql(sql, *args)

Returns a copy of the dataset with the static SQL used. This is useful if you want to keep the same row_proc/graph, but change the SQL used to custom SQL.

      dataset.with_sql('SELECT * FROM foo') # SELECT * FROM foo

[Source]

         # File lib/sequel/dataset/query.rb, line 660
    660:     def with_sql(sql, *args)
    661:       sql = SQL::PlaceholderLiteralString.new(sql, args) unless args.empty?
    662:       clone(:sql=>sql)
    663:     end

### 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/dataset/query.rb, line 668
    668:     def options_overlap(opts)
    669:       !(@opts.collect{|k,v| k unless v.nil?}.compact & opts).empty?
    670:     end

simple_select_all?()

Whether this dataset is a simple SELECT * FROM table.

[Source]

         # File lib/sequel/dataset/query.rb, line 673
    673:     def simple_select_all?
    674:       o = @opts.reject{|k,v| v.nil? || NON_SQL_OPTIONS.include?(k)}
    675:       o.length == 1 && (f = o[:from]) && f.length == 1 && f.first.is_a?(Symbol)
    676:     end

## User Methods relating to SQL Creation

These are methods you can call to see what SQL will be generated by the dataset.

### Public Instance methods

delete_sql()

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/dataset/sql.rb, line 12
    12:     def delete_sql
    13:       return static_sql(opts[:sql]) if opts[:sql]
    14:       check_modification_allowed!
    15:       clause_sql(:delete)
    16:     end

exists()

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/dataset/sql.rb, line 22
    22:     def exists
    23:       LiteralString.new("EXISTS (#{select_sql})")
    24:     end

insert_sql(*values)

Formats an INSERT statement using the given values. The API is a little complex, and best explained by example:

      # Default values
      DB[:items].insert_sql #=> 'INSERT INTO items DEFAULT VALUES'
      DB[:items].insert_sql({}) #=> 'INSERT INTO items DEFAULT VALUES'
      # Values without columns
      DB[:items].insert_sql(1,2,3) #=> 'INSERT INTO items VALUES (1, 2, 3)'
      DB[:items].insert_sql([1,2,3]) #=> 'INSERT INTO items VALUES (1, 2, 3)'
      # Values with columns
      DB[:items].insert_sql([:a, :b], [1,2]) #=> 'INSERT INTO items (a, b) VALUES (1, 2)'
      DB[:items].insert_sql(:a => 1, :b => 2) #=> 'INSERT INTO items (a, b) VALUES (1, 2)'
      # Using a subselect
      DB[:items].insert_sql(DB[:old_items]) #=> 'INSERT INTO items SELECT * FROM old_items
      # Using a subselect with columns
      DB[:items].insert_sql([:a, :b], DB[:old_items]) #=> 'INSERT INTO items (a, b) SELECT * FROM old_items

[Source]

        # File lib/sequel/dataset/sql.rb, line 42
    42:     def insert_sql(*values)
    43:       return static_sql(@opts[:sql]) if @opts[:sql]
    44:
    45:       check_modification_allowed!
    46:
    47:       columns = []
    48:
    49:       case values.size
    50:       when 0
    51:         return insert_sql({})
    52:       when 1
    53:         case vals = values.at(0)
    54:         when Hash
    55:           vals = @opts[:defaults].merge(vals) if @opts[:defaults]
    56:           vals = vals.merge(@opts[:overrides]) if @opts[:overrides]
    57:           values = []
    58:           vals.each do |k,v|
    59:             columns << k
    60:             values << v
    61:           end
    62:         when Dataset, Array, LiteralString
    63:           values = vals
    64:         else
    65:           if vals.respond_to?(:values) && (v = vals.values).is_a?(Hash)
    66:             return insert_sql(v)
    67:           end
    68:         end
    69:       when 2
    70:         if (v0 = values.at(0)).is_a?(Array) && ((v1 = values.at(1)).is_a?(Array) || v1.is_a?(Dataset) || v1.is_a?(LiteralString))
    71:           columns, values = v0, v1
    72:           raise(Error, "Different number of values and columns given to insert_sql") if values.is_a?(Array) and columns.length != values.length
    73:         end
    74:       end
    75:
    76:       columns = columns.map{|k| literal(String === k ? k.to_sym : k)}
    77:       clone(:columns=>columns, :values=>values)._insert_sql
    78:     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/dataset/sql.rb, line 90
     90:     def literal(v)
     91:       case v
     92:       when String
     93:         return v if v.is_a?(LiteralString)
     94:         v.is_a?(SQL::Blob) ? literal_blob(v) : literal_string(v)
     95:       when Symbol
     96:         literal_symbol(v)
     97:       when Integer
     98:         literal_integer(v)
     99:       when Hash
    100:         literal_hash(v)
    101:       when SQL::Expression
    102:         literal_expression(v)
    103:       when Float
    104:         literal_float(v)
    105:       when BigDecimal
    106:         literal_big_decimal(v)
    107:       when NilClass
    108:         literal_nil
    109:       when TrueClass
    110:         literal_true
    111:       when FalseClass
    112:         literal_false
    113:       when Array
    114:         literal_array(v)
    115:       when Time
    116:         literal_time(v)
    117:       when DateTime
    118:         literal_datetime(v)
    119:       when Date
    120:         literal_date(v)
    121:       when Dataset
    122:         literal_dataset(v)
    123:       else
    124:         literal_other(v)
    125:       end
    126:     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/dataset/sql.rb, line 134
    134:     def multi_insert_sql(columns, values)
    135:       values.map{|r| insert_sql(columns, r)}
    136:     end

select_sql()

Formats a SELECT statement

      dataset.select_sql # => "SELECT * FROM items"

[Source]

         # File lib/sequel/dataset/sql.rb, line 141
    141:     def select_sql
    142:       return static_sql(@opts[:sql]) if @opts[:sql]
    143:       clause_sql(:select)
    144:     end

sql()

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

[Source]

         # File lib/sequel/dataset/sql.rb, line 147
    147:     def sql
    148:       select_sql
    149:     end

truncate_sql()

SQL query to truncate the table

[Source]

         # File lib/sequel/dataset/sql.rb, line 152
    152:     def truncate_sql
    153:       if opts[:sql]
    154:         static_sql(opts[:sql])
    155:       else
    156:         check_modification_allowed!
    157:         raise(InvalidOperation, "Can't truncate filtered datasets") if opts[:where]
    158:         _truncate_sql(source_list(opts[:from]))
    159:       end
    160:     end

update_sql(values = {})

Formats an UPDATE statement using the given values.

      dataset.update_sql(:price => 100, :category => 'software') #=>
        "UPDATE items SET price = 100, category = 'software'"

Raises an error if the dataset is grouped or includes more than one table.

[Source]

         # File lib/sequel/dataset/sql.rb, line 169
    169:     def update_sql(values = {})
    170:       return static_sql(opts[:sql]) if opts[:sql]
    171:       check_modification_allowed!
    172:       clone(:values=>values)._update_sql
    173:     end

## Internal Methods relating to SQL Creation

These methods, while public, are not designed to be used directly by the end user.

### Constants

AND_SEPARATOR | = | " AND ".freeze
BOOL_FALSE | = | "'f'".freeze
BOOL_TRUE | = | "'t'".freeze
COMMA_SEPARATOR | = | ', '.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]
COUNT_OF_ALL_AS_COUNT | = | SQL::Function.new(:count, LiteralString.new('*'.freeze)).as(:count)
DATASET_ALIAS_BASE_NAME | = | 't'.freeze
FOR_UPDATE | = | ' FOR UPDATE'.freeze
IS_LITERALS | = | {nil=>'NULL'.freeze, true=>'TRUE'.freeze, false=>'FALSE'.freeze}.freeze
IS_OPERATORS | = | ::Sequel::SQL::ComplexExpression::IS_OPERATORS
N_ARITY_OPERATORS | = | ::Sequel::SQL::ComplexExpression::N_ARITY_OPERATORS
NULL | = | "NULL".freeze
QUALIFY_KEYS | = | [:select, :where, :having, :order, :group]
QUESTION_MARK | = | '?'.freeze
DELETE_CLAUSE_METHODS | = | clause_methods(:delete, %w'from where')
INSERT_CLAUSE_METHODS | = | clause_methods(:insert, %w'into columns values')
SELECT_CLAUSE_METHODS | = | clause_methods(:select, %w'with distinct columns from join where group having compounds order limit lock')
UPDATE_CLAUSE_METHODS | = | clause_methods(:update, %w'table set where')
TIMESTAMP_FORMAT | = | "'%Y-%m-%d %H:%M:%S%N%z'".freeze
STANDARD_TIMESTAMP_FORMAT | = | "TIMESTAMP #{TIMESTAMP_FORMAT}".freeze
TWO_ARITY_OPERATORS | = | ::Sequel::SQL::ComplexExpression::TWO_ARITY_OPERATORS
WILDCARD | = | LiteralString.new('*').freeze
SQL_WITH | = | "WITH ".freeze

### Public Class methods

clause_methods(type, clauses)

Given a type (e.g. select) and an array of clauses, return an array of methods to call to build the SQL string.

[Source]

         # File lib/sequel/dataset/sql.rb, line 182
    182:     def self.clause_methods(type, clauses)
    183:       clauses.map{|clause| "#{type}_#{clause}_sql""#{type}_#{clause}_sql"}.freeze
    184:     end

### Public Instance methods

aliased_expression_sql(ae)

SQL fragment for the aliased expression

[Source]

         # File lib/sequel/dataset/sql.rb, line 214
    214:     def aliased_expression_sql(ae)
    215:       as_sql(literal(ae.expression), ae.aliaz)
    216:     end

array_sql(a)

SQL fragment for the SQL array.

[Source]

         # File lib/sequel/dataset/sql.rb, line 219
    219:     def array_sql(a)
    220:       a.empty? ? '(NULL)' : "(#{expression_list(a)})"
    221:     end

boolean_constant_sql(constant)

SQL fragment for BooleanConstants

[Source]

         # File lib/sequel/dataset/sql.rb, line 224
    224:     def boolean_constant_sql(constant)
    225:       literal(constant)
    226:     end

case_expression_sql(ce)

SQL fragment for specifying given CaseExpression.

[Source]

         # File lib/sequel/dataset/sql.rb, line 229
    229:     def case_expression_sql(ce)
    230:       sql = '(CASE '
    231:       sql << "#{literal(ce.expression)} " if ce.expression?
    232:       ce.conditions.collect{ |c,r|
    233:         sql << "WHEN #{literal(c)} THEN #{literal(r)} "
    234:       }
    235:       sql << "ELSE #{literal(ce.default)} END)"
    236:     end

cast_sql(expr, type)

SQL fragment for the SQL CAST expression.

[Source]

         # File lib/sequel/dataset/sql.rb, line 239
    239:     def cast_sql(expr, type)
    240:       "CAST(#{literal(expr)} AS #{db.cast_type_literal(type)})"
    241:     end

column_all_sql(ca)

SQL fragment for specifying all columns in a given table.

[Source]

         # File lib/sequel/dataset/sql.rb, line 244
    244:     def column_all_sql(ca)
    245:       "#{quote_schema_table(ca.table)}.*"
    246:     end

complex_expression_sql(op, args)

SQL fragment for complex expressions

[Source]

         # File lib/sequel/dataset/sql.rb, line 249
    249:     def complex_expression_sql(op, args)
    250:       case op
    251:       when *IS_OPERATORS
    252:         r = args.at(1)
    253:         if r.nil? || supports_is_true?
    254:           raise(InvalidOperation, 'Invalid argument used for IS operator') unless v = IS_LITERALS[r]
    255:           "(#{literal(args.at(0))} #{op} #{v})"
    256:         elsif op == :IS
    257:           complex_expression_sql("=""=", args)
    258:         else
    259:           complex_expression_sql(:OR, [SQL::BooleanExpression.new("!=""!=", *args), SQL::BooleanExpression.new(:IS, args.at(0), nil)])
    260:         end
    261:       when :IN, "NOT IN""NOT IN"
    262:         cols = args.at(0)
    263:         vals = args.at(1)
    264:         col_array = true if cols.is_a?(Array)
    265:         if vals.is_a?(Array)
    266:           val_array = true
    267:           empty_val_array = vals == []
    268:         end
    269:         if col_array
    270:           if empty_val_array
    271:             if op == :IN
    272:               literal(SQL::BooleanExpression.from_value_pairs(cols.to_a.map{|x| [x, x]}, :AND, true))
    273:             else
    274:               literal(1=>1)
    275:             end
    276:           elsif !supports_multiple_column_in?
    277:             if val_array
    278:               expr = SQL::BooleanExpression.new(:OR, *vals.to_a.map{|vs| SQL::BooleanExpression.from_value_pairs(cols.to_a.zip(vs).map{|c, v| [c, v]})})
    279:               literal(op == :IN ? expr : ~expr)
    280:             else
    281:               old_vals = vals
    282:               vals = vals.to_a
    283:               val_cols = old_vals.columns
    284:               complex_expression_sql(op, [cols, vals.map!{|x| x.values_at(*val_cols)}])
    285:             end
    286:           else
    287:             # If the columns and values are both arrays, use array_sql instead of
    288:             # literal so that if values is an array of two element arrays, it
    289:             # will be treated as a value list instead of a condition specifier.
    290:             "(#{literal(cols)} #{op} #{val_array ? array_sql(vals) : literal(vals)})"
    291:           end
    292:         else
    293:           if empty_val_array
    294:             if op == :IN
    295:               literal(SQL::BooleanExpression.from_value_pairs([[cols, cols]], :AND, true))
    296:             else
    297:               literal(1=>1)
    298:             end
    299:           else
    300:             "(#{literal(cols)} #{op} #{literal(vals)})"
    301:           end
    302:         end
    303:       when *TWO_ARITY_OPERATORS
    304:         "(#{literal(args.at(0))} #{op} #{literal(args.at(1))})"
    305:       when *N_ARITY_OPERATORS
    306:         "(#{args.collect{|a| literal(a)}.join(" #{op} ")})"
    307:       when :NOT
    308:         "NOT #{literal(args.at(0))}"
    309:       when :NOOP
    310:         literal(args.at(0))
    311:       when 'B~''B~'
    312:         "~#{literal(args.at(0))}"
    313:       else
    314:         raise(InvalidOperation, "invalid operator #{op}")
    315:       end
    316:     end

constant_sql(constant)

SQL fragment for constants

[Source]

         # File lib/sequel/dataset/sql.rb, line 319
    319:     def constant_sql(constant)
    320:       constant.to_s
    321:     end

function_sql(f)

SQL fragment specifying an SQL function call

[Source]

         # File lib/sequel/dataset/sql.rb, line 324
    324:     def function_sql(f)
    325:       args = f.args
    326:       "#{f.f}#{args.empty? ? '()' : literal(args)}"
    327:     end

join_clause_sql(jc)

SQL fragment specifying a JOIN clause without ON or USING.

[Source]

         # File lib/sequel/dataset/sql.rb, line 330
    330:     def join_clause_sql(jc)
    331:       table = jc.table
    332:       table_alias = jc.table_alias
    333:       table_alias = nil if table == table_alias
    334:       tref = table_ref(table)
    335:       " #{join_type_sql(jc.join_type)} #{table_alias ? as_sql(tref, table_alias) : tref}"
    336:     end

join_on_clause_sql(jc)

SQL fragment specifying a JOIN clause with ON.

[Source]

         # File lib/sequel/dataset/sql.rb, line 339
    339:     def join_on_clause_sql(jc)
    340:       "#{join_clause_sql(jc)} ON #{literal(filter_expr(jc.on))}"
    341:     end

join_using_clause_sql(jc)

SQL fragment specifying a JOIN clause with USING.

[Source]

         # File lib/sequel/dataset/sql.rb, line 344
    344:     def join_using_clause_sql(jc)
    345:       "#{join_clause_sql(jc)} USING (#{column_list(jc.using)})"
    346:     end

negative_boolean_constant_sql(constant)

SQL fragment for NegativeBooleanConstants

[Source]

         # File lib/sequel/dataset/sql.rb, line 349
    349:     def negative_boolean_constant_sql(constant)
    350:       "NOT #{boolean_constant_sql(constant)}"
    351:     end

ordered_expression_sql(oe)

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

[Source]

         # File lib/sequel/dataset/sql.rb, line 355
    355:     def ordered_expression_sql(oe)
    356:       s = "#{literal(oe.expression)} #{oe.descending ? 'DESC' : 'ASC'}"
    357:       case oe.nulls
    358:       when :first
    359:         "#{s} NULLS FIRST"
    360:       when :last
    361:         "#{s} NULLS LAST"
    362:       else
    363:         s
    364:       end
    365:     end

placeholder_literal_string_sql(pls)

SQL fragment for a literal string with placeholders

[Source]

         # File lib/sequel/dataset/sql.rb, line 368
    368:     def placeholder_literal_string_sql(pls)
    369:       args = pls.args
    370:       s = if args.is_a?(Hash)
    371:         re = /:(#{args.keys.map{|k| Regexp.escape(k.to_s)}.join('|')})\b/
    372:         pls.str.gsub(re){literal(args[$1.to_sym])}
    373:       else
    374:         i = -1
    375:         pls.str.gsub(QUESTION_MARK){literal(args.at(i+=1))}
    376:       end
    377:       s = "(#{s})" if pls.parens
    378:       s
    379:     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/dataset/sql.rb, line 383
    383:     def qualified_identifier_sql(qcr)
    384:       [qcr.table, qcr.column].map{|x| [SQL::QualifiedIdentifier, SQL::Identifier, Symbol].any?{|c| x.is_a?(c)} ? literal(x) : quote_identifier(x)}.join('.')
    385:     end

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/dataset/sql.rb, line 390
    390:     def quote_identifier(name)
    391:       return name if name.is_a?(LiteralString)
    392:       name = name.value if name.is_a?(SQL::Identifier)
    393:       name = input_identifier(name)
    394:       name = quoted_identifier(name) if quote_identifiers?
    395:       name
    396:     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/dataset/sql.rb, line 400
    400:     def quote_schema_table(table)
    401:       schema, table = schema_and_table(table)
    402:       "#{"#{quote_identifier(schema)}." if schema}#{quote_identifier(table)}"
    403:     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/dataset/sql.rb, line 408
    408:     def quoted_identifier(name)
    409:       "\"#{name.to_s.gsub('"', '""')}\""
    410:     end

schema_and_table(table_name)

Split the schema information from the table

[Source]

         # File lib/sequel/dataset/sql.rb, line 413
    413:     def schema_and_table(table_name)
    414:       sch = db.default_schema if db
    415:       case table_name
    416:       when Symbol
    417:         s, t, a = split_symbol(table_name)
    418:         [s||sch, t]
    419:       when SQL::QualifiedIdentifier
    420:         [table_name.table, table_name.column]
    421:       when SQL::Identifier
    422:         [sch, table_name.value]
    423:       when String
    424:         [sch, table_name]
    425:       else
    426:         raise Error, 'table_name should be a Symbol, SQL::QualifiedIdentifier, SQL::Identifier, or String'
    427:       end
    428:     end

subscript_sql(s)

SQL fragment for specifying subscripts (SQL arrays)

[Source]

         # File lib/sequel/dataset/sql.rb, line 431
    431:     def subscript_sql(s)
    432:       "#{literal(s.f)}[#{expression_list(s.sub)}]"
    433:     end

window_function_sql(function, window)

The SQL fragment for the given window function‘s function and window.

[Source]

         # File lib/sequel/dataset/sql.rb, line 457
    457:     def window_function_sql(function, window)
    458:       "#{literal(function)} OVER #{literal(window)}"
    459:     end

window_sql(opts)

The SQL fragment for the given window‘s options.

[Source]

         # File lib/sequel/dataset/sql.rb, line 436
    436:     def window_sql(opts)
    437:       raise(Error, 'This dataset does not support window functions') unless supports_window_functions?
    438:       window = literal(opts[:window]) if opts[:window]
    439:       partition = "PARTITION BY #{expression_list(Array(opts[:partition]))}" if opts[:partition]
    440:       order = "ORDER BY #{expression_list(Array(opts[:order]))}" if opts[:order]
    441:       frame = case opts[:frame]
    442:         when nil
    443:           nil
    444:         when :all
    445:           "ROWS BETWEEN UNBOUNDED PRECEDING AND UNBOUNDED FOLLOWING"
    446:         when :rows
    447:           "ROWS UNBOUNDED PRECEDING"
    448:         when String
    449:           opts[:frame]
    450:         else
    451:           raise Error, "invalid window frame clause, should be :all, :rows, a string, or nil"
    452:       end
    453:       "(#{[window, partition, order, frame].compact.join(' ')})"
    454:     end

### Protected Instance methods

_insert_sql()

Formats in INSERT statement using the stored columns and values.

[Source]

         # File lib/sequel/dataset/sql.rb, line 464
    464:     def _insert_sql
    465:       clause_sql(:insert)
    466:     end

_update_sql()

Formats an UPDATE statement using the stored values.

[Source]

         # File lib/sequel/dataset/sql.rb, line 469
    469:     def _update_sql
    470:       clause_sql(:update)
    471:     end

compound_from_self()

Return a from_self dataset if an order or limit is specified, so it works as expected with UNION, EXCEPT, and INTERSECT clauses.

[Source]

         # File lib/sequel/dataset/sql.rb, line 475
    475:     def compound_from_self
    476:       (@opts[:limit] || @opts[:order]) ? from_self : self
    477:     end

## Mutation methods

These methods modify the receiving dataset and should be used with care.

### Classes and Modules

Module Sequel::Dataset::Pagination
Module Sequel::Dataset::QueryBlockCopy

### Constants

MUTATION_METHODS | = | QUERY_METHODS |  | All methods that should have a ! method added that modifies the receiver.

### Attributes

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
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 each to return.

### Public Class methods

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/dataset/mutation.rb, line 14
    14:     def self.def_mutation_method(*meths)
    15:       meths.each do |meth|
    16:         class_eval("def #{meth}!(*args, &block); mutation_method(:#{meth}, *args, &block) end", __FILE__, __LINE__)
    17:       end
    18:     end

### Public Instance methods

def_mutation_method(*meths)

Add a mutation method to this dataset instance.

[Source]

        # File lib/sequel/dataset/mutation.rb, line 39
    39:     def def_mutation_method(*meths)
    40:       meths.each do |meth|
    41:         instance_eval("def #{meth}!(*args, &block); mutation_method(:#{meth}, *args, &block) end", __FILE__, __LINE__)
    42:       end
    43:     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/extensions/pagination.rb, line 20
    20:     def each_page(page_size, &block)
    21:       raise(Error, "You cannot paginate a dataset that already has a limit") if @opts[:limit]
    22:       record_count = count
    23:       total_pages = (record_count / page_size.to_f).ceil
    24:       (1..total_pages).each{|page_no| yield paginate(page_no, page_size, record_count)}
    25:       self
    26:     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/extensions/pagination.rb, line 11
    11:     def paginate(page_no, page_size, record_count=nil)
    12:       raise(Error, "You cannot paginate a dataset that already has a limit") if @opts[:limit]
    13:       paginated = limit(page_size, (page_no - 1) * page_size)
    14:       paginated.extend(Pagination)
    15:       paginated.set_pagination_info(page_no, page_size, record_count || count)
    16:     end

print(*cols)

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

[Source]

        # File lib/sequel/extensions/pretty_table.rb, line 8
     8:     def print(*cols)
     9:       Sequel::PrettyTable.print(naked.all, cols.empty? ? columns : cols)
    10:     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/extensions/query.rb, line 30
    30:     def query(&block)
    31:       copy = clone({})
    32:       copy.extend(QueryBlockCopy)
    33:       copy.instance_eval(&block)
    34:       clone(copy.opts)
    35:     end

[Validate]