Class Sequel::Dataset
In: lib/sequel/extensions/query.rb
lib/sequel/extensions/pretty_table.rb
lib/sequel/extensions/pagination.rb
lib/sequel/dataset/mutation.rb
lib/sequel/dataset/sql.rb
lib/sequel/dataset/query.rb
lib/sequel/dataset/prepared_statements.rb
lib/sequel/dataset/misc.rb
lib/sequel/dataset/graph.rb
lib/sequel/dataset/features.rb
lib/sequel/dataset/actions.rb
lib/sequel/dataset.rb
lib/sequel/adapters/swift.rb
lib/sequel/adapters/utils/stored_procedures.rb
lib/sequel/adapters/jdbc.rb
lib/sequel/adapters/do.rb
Parent: Object

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?   eql?   except   exclude   exists   fetch_rows   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   hash   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   split_alias   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

Public Instance methods

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

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

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

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

Mutation methods

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

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

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

Add a mutation method to this dataset instance.

[Source]

    # File lib/sequel/dataset/mutation.rb, line 38
38:     def def_mutation_method(*meths)
39:       meths.each do |meth|
40:         instance_eval("def #{meth}!(*args, &block); mutation_method(:#{meth}, *args, &block) end", __FILE__, __LINE__)
41:       end
42:     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

Returns a DELETE SQL query string. See delete.

  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

Returns an EXISTS clause for the dataset as a LiteralString.

  DB.select(1).where(DB[:items].exists)
  # 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

Returns an INSERT SQL query string. See insert.

  DB[:items].insert_sql(:a=>1)
  # => "INSERT INTO items (a) VALUES (1)"

[Source]

    # File lib/sequel/dataset/sql.rb, line 30
30:     def insert_sql(*values)
31:       return static_sql(@opts[:sql]) if @opts[:sql]
32: 
33:       check_modification_allowed!
34: 
35:       columns = []
36: 
37:       case values.size
38:       when 0
39:         return insert_sql({})
40:       when 1
41:         case vals = values.at(0)
42:         when Hash
43:           vals = @opts[:defaults].merge(vals) if @opts[:defaults]
44:           vals = vals.merge(@opts[:overrides]) if @opts[:overrides]
45:           values = []
46:           vals.each do |k,v| 
47:             columns << k
48:             values << v
49:           end
50:         when Dataset, Array, LiteralString
51:           values = vals
52:         else
53:           if vals.respond_to?(:values) && (v = vals.values).is_a?(Hash)
54:             return insert_sql(v) 
55:           end
56:         end
57:       when 2
58:         if (v0 = values.at(0)).is_a?(Array) && ((v1 = values.at(1)).is_a?(Array) || v1.is_a?(Dataset) || v1.is_a?(LiteralString))
59:           columns, values = v0, v1
60:           raise(Error, "Different number of values and columns given to insert_sql") if values.is_a?(Array) and columns.length != values.length
61:         end
62:       end
63: 
64:       columns = columns.map{|k| literal(String === k ? k.to_sym : k)}
65:       clone(:columns=>columns, :values=>values)._insert_sql
66:     end

Returns a literal representation of a value to be used as part of an SQL expression.

  DB[:items].literal("abc'def\\") #=> "'abc''def\\\\'"
  DB[:items].literal(:items__id) #=> "items.id"
  DB[:items].literal([1, 2, 3]) => "(1, 2, 3)"
  DB[:items].literal(DB[:items]) => "(SELECT * FROM items)"
  DB[:items].literal(:x + 1 > :y) => "((x + 1) > y)"

If an unsupported object is given, an Error is raised.

[Source]

     # File lib/sequel/dataset/sql.rb, line 78
 78:     def literal(v)
 79:       case v
 80:       when String
 81:         return v if v.is_a?(LiteralString)
 82:         v.is_a?(SQL::Blob) ? literal_blob(v) : literal_string(v)
 83:       when Symbol
 84:         literal_symbol(v)
 85:       when Integer
 86:         literal_integer(v)
 87:       when Hash
 88:         literal_hash(v)
 89:       when SQL::Expression
 90:         literal_expression(v)
 91:       when Float
 92:         literal_float(v)
 93:       when BigDecimal
 94:         literal_big_decimal(v)
 95:       when NilClass
 96:         literal_nil
 97:       when TrueClass
 98:         literal_true
 99:       when FalseClass
100:         literal_false
101:       when Array
102:         literal_array(v)
103:       when Time
104:         literal_time(v)
105:       when DateTime
106:         literal_datetime(v)
107:       when Date
108:         literal_date(v)
109:       when Dataset
110:         literal_dataset(v)
111:       else
112:         literal_other(v)
113:       end
114:     end

Returns an array of insert statements for inserting multiple records. This method is used by multi_insert to format insert statements and expects a keys array and and an array of value arrays.

This method should be overridden by descendants if the support inserting multiple records in a single SQL statement.

[Source]

     # File lib/sequel/dataset/sql.rb, line 122
122:     def multi_insert_sql(columns, values)
123:       values.map{|r| insert_sql(columns, r)}
124:     end

Returns a SELECT SQL query string.

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

[Source]

     # File lib/sequel/dataset/sql.rb, line 129
129:     def select_sql
130:       return static_sql(@opts[:sql]) if @opts[:sql]
131:       clause_sql(:select)
132:     end

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

[Source]

     # File lib/sequel/dataset/sql.rb, line 135
135:     def sql
136:       select_sql
137:     end

Returns a TRUNCATE SQL query string. See truncate

  DB[:items].truncate_sql # => 'TRUNCATE items'

[Source]

     # File lib/sequel/dataset/sql.rb, line 142
142:     def truncate_sql
143:       if opts[:sql]
144:         static_sql(opts[:sql])
145:       else
146:         check_modification_allowed!
147:         raise(InvalidOperation, "Can't truncate filtered datasets") if opts[:where]
148:         _truncate_sql(source_list(opts[:from]))
149:       end
150:     end

Formats an UPDATE statement using the given values. See update.

  DB[:items].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 159
159:     def update_sql(values = {})
160:       return static_sql(opts[:sql]) if opts[:sql]
161:       check_modification_allowed!
162:       clone(:values=>values)._update_sql
163:     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

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 172
172:     def self.clause_methods(type, clauses)
173:       clauses.map{|clause| "#{type}_#{clause}_sql""#{type}_#{clause}_sql"}.freeze
174:     end

Public Instance methods

SQL fragment for AliasedExpression

[Source]

     # File lib/sequel/dataset/sql.rb, line 204
204:     def aliased_expression_sql(ae)
205:       as_sql(literal(ae.expression), ae.aliaz)
206:     end

SQL fragment for Array

[Source]

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

SQL fragment for BooleanConstants

[Source]

     # File lib/sequel/dataset/sql.rb, line 214
214:     def boolean_constant_sql(constant)
215:       literal(constant)
216:     end

SQL fragment for CaseExpression

[Source]

     # File lib/sequel/dataset/sql.rb, line 219
219:     def case_expression_sql(ce)
220:       sql = '(CASE '
221:       sql << "#{literal(ce.expression)} " if ce.expression?
222:       ce.conditions.collect{ |c,r|
223:         sql << "WHEN #{literal(c)} THEN #{literal(r)} "
224:       }
225:       sql << "ELSE #{literal(ce.default)} END)"
226:     end

SQL fragment for the SQL CAST expression

[Source]

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

SQL fragment for specifying all columns in a given table

[Source]

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

SQL fragment for complex expressions

[Source]

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

SQL fragment for constants

[Source]

     # File lib/sequel/dataset/sql.rb, line 309
309:     def constant_sql(constant)
310:       constant.to_s
311:     end

SQL fragment specifying an SQL function call

[Source]

     # File lib/sequel/dataset/sql.rb, line 314
314:     def function_sql(f)
315:       args = f.args
316:       "#{f.f}#{args.empty? ? '()' : literal(args)}"
317:     end

SQL fragment specifying a JOIN clause without ON or USING.

[Source]

     # File lib/sequel/dataset/sql.rb, line 320
320:     def join_clause_sql(jc)
321:       table = jc.table
322:       table_alias = jc.table_alias
323:       table_alias = nil if table == table_alias
324:       tref = table_ref(table)
325:       " #{join_type_sql(jc.join_type)} #{table_alias ? as_sql(tref, table_alias) : tref}"
326:     end

SQL fragment specifying a JOIN clause with ON.

[Source]

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

SQL fragment specifying a JOIN clause with USING.

[Source]

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

SQL fragment for NegativeBooleanConstants

[Source]

     # File lib/sequel/dataset/sql.rb, line 339
339:     def negative_boolean_constant_sql(constant)
340:       "NOT #{boolean_constant_sql(constant)}"
341:     end

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

[Source]

     # File lib/sequel/dataset/sql.rb, line 345
345:     def ordered_expression_sql(oe)
346:       s = "#{literal(oe.expression)} #{oe.descending ? 'DESC' : 'ASC'}"
347:       case oe.nulls
348:       when :first
349:         "#{s} NULLS FIRST"
350:       when :last
351:         "#{s} NULLS LAST"
352:       else
353:         s
354:       end
355:     end

SQL fragment for a literal string with placeholders

[Source]

     # File lib/sequel/dataset/sql.rb, line 358
358:     def placeholder_literal_string_sql(pls)
359:       args = pls.args
360:       s = if args.is_a?(Hash)
361:         re = /:(#{args.keys.map{|k| Regexp.escape(k.to_s)}.join('|')})\b/
362:         pls.str.gsub(re){literal(args[$1.to_sym])}
363:       else
364:         i = -1
365:         pls.str.gsub(QUESTION_MARK){literal(args.at(i+=1))}
366:       end
367:       s = "(#{s})" if pls.parens
368:       s
369:     end

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

[Source]

     # File lib/sequel/dataset/sql.rb, line 373
373:     def qualified_identifier_sql(qcr)
374:       [qcr.table, qcr.column].map{|x| [SQL::QualifiedIdentifier, SQL::Identifier, Symbol].any?{|c| x.is_a?(c)} ? literal(x) : quote_identifier(x)}.join('.')
375:     end

Adds quoting to identifiers (columns and tables). If identifiers are not being quoted, returns name as a string. If identifiers are being quoted quote the name with quoted_identifier.

[Source]

     # File lib/sequel/dataset/sql.rb, line 380
380:     def quote_identifier(name)
381:       return name if name.is_a?(LiteralString)
382:       name = name.value if name.is_a?(SQL::Identifier)
383:       name = input_identifier(name)
384:       name = quoted_identifier(name) if quote_identifiers?
385:       name
386:     end

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

[Source]

     # File lib/sequel/dataset/sql.rb, line 390
390:     def quote_schema_table(table)
391:       schema, table = schema_and_table(table)
392:       "#{"#{quote_identifier(schema)}." if schema}#{quote_identifier(table)}"
393:     end

This method quotes the given name with the SQL standard double quote. should be overridden by subclasses to provide quoting not matching the SQL standard, such as backtick (used by MySQL and SQLite).

[Source]

     # File lib/sequel/dataset/sql.rb, line 398
398:     def quoted_identifier(name)
399:       "\"#{name.to_s.gsub('"', '""')}\""
400:     end

Split the schema information from the table

[Source]

     # File lib/sequel/dataset/sql.rb, line 403
403:     def schema_and_table(table_name)
404:       sch = db.default_schema if db
405:       case table_name
406:       when Symbol
407:         s, t, a = split_symbol(table_name)
408:         [s||sch, t]
409:       when SQL::QualifiedIdentifier
410:         [table_name.table, table_name.column]
411:       when SQL::Identifier
412:         [sch, table_name.value]
413:       when String
414:         [sch, table_name]
415:       else
416:         raise Error, 'table_name should be a Symbol, SQL::QualifiedIdentifier, SQL::Identifier, or String'
417:       end
418:     end

SQL fragment for specifying subscripts (SQL array accesses)

[Source]

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

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

[Source]

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

The SQL fragment for the given window‘s options.

[Source]

     # File lib/sequel/dataset/sql.rb, line 426
426:     def window_sql(opts)
427:       raise(Error, 'This dataset does not support window functions') unless supports_window_functions?
428:       window = literal(opts[:window]) if opts[:window]
429:       partition = "PARTITION BY #{expression_list(Array(opts[:partition]))}" if opts[:partition]
430:       order = "ORDER BY #{expression_list(Array(opts[:order]))}" if opts[:order]
431:       frame = case opts[:frame]
432:         when nil
433:           nil
434:         when :all
435:           "ROWS BETWEEN UNBOUNDED PRECEDING AND UNBOUNDED FOLLOWING"
436:         when :rows
437:           "ROWS UNBOUNDED PRECEDING"
438:         when String
439:           opts[:frame]
440:         else
441:           raise Error, "invalid window frame clause, should be :all, :rows, a string, or nil"
442:       end
443:       "(#{[window, partition, order, frame].compact.join(' ')})"
444:     end

Protected Instance methods

Formats in INSERT statement using the stored columns and values.

[Source]

     # File lib/sequel/dataset/sql.rb, line 454
454:     def _insert_sql
455:       clause_sql(:insert)
456:     end

Formats an UPDATE statement using the stored values.

[Source]

     # File lib/sequel/dataset/sql.rb, line 459
459:     def _update_sql
460:       clause_sql(:update)
461:     end

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 465
465:     def compound_from_self
466:       (@opts[:limit] || @opts[:order]) ? from_self : self
467:     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

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.

  DB[:table].filter(:a).and(:b) # SELECT * FROM table 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

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. This method should generally not be called directly by user code.

[Source]

    # File lib/sequel/dataset/query.rb, line 52
52:     def clone(opts = {})
53:       c = super()
54:       c.opts = @opts.merge(opts)
55:       c.instance_variable_set(:@columns, nil) if opts.keys.any?{|o| COLUMN_CHANGE_OPTS.include?(o)}
56:       c
57:     end

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.

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

[Source]

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

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:

:alias :Use the given value as the from_self alias
: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[:other_items])
  # SELECT * FROM items EXCEPT SELECT * FROM other_items

  DB[:items].except(DB[:other_items], :all=>true, :from_self=>false)
  # SELECT * FROM items EXCEPT ALL SELECT * FROM other_items

  DB[:items].except(DB[:other_items], :alias=>:i)
  # SELECT * FROM (SELECT * FROM items EXCEPT SELECT * FROM other_items) AS i

[Source]

    # File lib/sequel/dataset/query.rb, line 90
90:     def except(dataset, opts={})
91:       opts = {:all=>opts} unless opts.is_a?(Hash)
92:       raise(InvalidOperation, "EXCEPT not supported") unless supports_intersect_except?
93:       raise(InvalidOperation, "EXCEPT ALL not supported") if opts[:all] && !supports_intersect_except_all?
94:       compound_clone(:except, dataset, opts)
95:     end

Performs the inverse of Dataset#filter. Note that if you have multiple filter conditions, this is not the same as a negation of all conditions.

  DB[:items].exclude(:category => 'software')
  # SELECT * FROM items WHERE (category != 'software')

  DB[:items].exclude(:category => 'software', :id=>3)
  # SELECT * FROM items WHERE ((category != 'software') OR (id != 3))

[Source]

     # File lib/sequel/dataset/query.rb, line 105
105:     def exclude(*cond, &block)
106:       clause = (@opts[:having] ? :having : :where)
107:       cond = cond.first if cond.size == 1
108:       cond = filter_expr(cond, &block)
109:       cond = SQL::BooleanExpression.invert(cond)
110:       cond = SQL::BooleanExpression.new(:AND, @opts[clause], cond) if @opts[clause]
111:       clone(clause => cond)
112:     end

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.
    • Otherwise, treats each argument as a separate condition.
  • 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:

  DB[:items].filter(:id => 3)
  # SELECT * FROM items WHERE (id = 3)

  DB[:items].filter('price < ?', 100)
  # SELECT * FROM items WHERE price < 100

  DB[:items].filter([[:id, (1,2,3)], [:id, 0..10]])
  # SELECT * FROM items WHERE ((id IN (1, 2, 3)) AND ((id >= 0) AND (id <= 10)))

  DB[:items].filter('price < 100')
  # SELECT * FROM items WHERE price < 100

  DB[:items].filter(:active)
  # SELECT * FROM items WHERE :active

  DB[:items].filter{price < 100}
  # SELECT * FROM items WHERE (price < 100)

Multiple filter calls can be chained for scoping:

  software = dataset.filter(:category => 'software').filter{price < 100}
  # 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 166
166:     def filter(*cond, &block)
167:       _filter(@opts[:having] ? :having : :where, *cond, &block)
168:     end

Returns a cloned dataset with a :update lock style.

  DB[:table].for_update # SELECT * FROM table FOR UPDATE

[Source]

     # File lib/sequel/dataset/query.rb, line 173
173:     def for_update
174:       lock_style(:update)
175:     end

Returns a copy of the dataset with the source changed. If no source is given, removes all tables. If multiple sources are given, it is the same as using a CROSS JOIN (cartesian product) between all tables.

  DB[:items].from # SQL: SELECT *
  DB[:items].from(:blah) # SQL: SELECT * FROM blah
  DB[:items].from(:blah, :foo) # SQL: SELECT * FROM blah, foo

[Source]

     # File lib/sequel/dataset/query.rb, line 184
184:     def from(*source)
185:       table_alias_num = 0
186:       sources = []
187:       source.each do |s|
188:         case s
189:         when Hash
190:           s.each{|k,v| sources << SQL::AliasedExpression.new(k,v)}
191:         when Dataset
192:           sources << SQL::AliasedExpression.new(s, dataset_alias(table_alias_num+=1))
193:         when Symbol
194:           sch, table, aliaz = split_symbol(s)
195:           if aliaz
196:             s = sch ? SQL::QualifiedIdentifier.new(sch.to_sym, table.to_sym) : SQL::Identifier.new(table.to_sym)
197:             sources << SQL::AliasedExpression.new(s, aliaz.to_sym)
198:           else
199:             sources << s
200:           end
201:         else
202:           sources << s
203:         end
204:       end
205:       o = {:from=>sources.empty? ? nil : sources}
206:       o[:num_dataset_sources] = table_alias_num if table_alias_num > 0
207:       clone(o)
208:     end

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

  ds = DB[:items].order(:name).select(:id, :name)
  # SELECT id,name FROM items ORDER BY name

  ds.from_self
  # SELECT * FROM (SELECT id, name FROM items ORDER BY name) AS t1

  ds.from_self(:alias=>:foo)
  # SELECT * FROM (SELECT id, name FROM items ORDER BY name) AS foo

[Source]

     # File lib/sequel/dataset/query.rb, line 221
221:     def from_self(opts={})
222:       fs = {}
223:       @opts.keys.each{|k| fs[k] = nil unless NON_SQL_OPTIONS.include?(k)}
224:       clone(fs).from(opts[:alias] ? as(opts[:alias]) : self)
225:     end

Match any of the columns to any of the patterns. The terms can be strings (which use LIKE) or regular expressions (which are only supported on MySQL and PostgreSQL). Note that the total number of pattern matches will be Array(columns).length * Array(terms).length, which could cause performance issues.

Options (all are boolean):

:all_columns :All columns must be matched to any of the given patterns.
:all_patterns :All patterns must match at least one of the columns.
:case_insensitive :Use a case insensitive pattern match (the default is case sensitive if the database supports it).

If both :all_columns and :all_patterns are true, all columns must match all patterns.

Examples:

  dataset.grep(:a, '%test%')
  # SELECT * FROM items WHERE (a LIKE '%test%')

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

  dataset.grep([:a, :b], %w'%foo% %bar%', :all_patterns=>true)
  # SELECT * FROM a WHERE (((a LIKE '%foo%') OR (b LIKE '%foo%')) AND ((a LIKE '%bar%') OR (b LIKE '%bar%')))

  dataset.grep([:a, :b], %w'%foo% %bar%', :all_columns=>true)
  # SELECT * FROM a WHERE (((a LIKE '%foo%') OR (a LIKE '%bar%')) AND ((b LIKE '%foo%') OR (b LIKE '%bar%')))

  dataset.grep([:a, :b], %w'%foo% %bar%', :all_patterns=>true, :all_columns=>true)
  # SELECT * FROM a WHERE ((a LIKE '%foo%') AND (b LIKE '%foo%') AND (a LIKE '%bar%') AND (b LIKE '%bar%'))

[Source]

     # File lib/sequel/dataset/query.rb, line 258
258:     def grep(columns, patterns, opts={})
259:       if opts[:all_patterns]
260:         conds = Array(patterns).map do |pat|
261:           SQL::BooleanExpression.new(opts[:all_columns] ? :AND : :OR, *Array(columns).map{|c| SQL::StringExpression.like(c, pat, opts)})
262:         end
263:         filter(SQL::BooleanExpression.new(opts[:all_patterns] ? :AND : :OR, *conds))
264:       else
265:         conds = Array(columns).map do |c|
266:           SQL::BooleanExpression.new(:OR, *Array(patterns).map{|pat| SQL::StringExpression.like(c, pat, opts)})
267:         end
268:         filter(SQL::BooleanExpression.new(opts[:all_columns] ? :AND : :OR, *conds))
269:       end
270:     end

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

  DB[:items].group(:id) # SELECT * FROM items GROUP BY id
  DB[:items].group(:id, :name) # SELECT * FROM items GROUP BY id, name

[Source]

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

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:

  DB[:items].group_and_count(:name).all
  # SELECT name, count(*) AS count FROM items GROUP BY name
  # => [{:name=>'a', :count=>1}, ...]

  DB[:items].group_and_count(:first_name, :last_name).all
  # SELECT first_name, last_name, count(*) AS count FROM items GROUP BY first_name, last_name
  # => [{:first_name=>'a', :last_name=>'b', :count=>1}, ...]

  DB[:items].group_and_count(:first_name___name).all
  # SELECT first_name AS name, count(*) AS count FROM items GROUP BY first_name
  # => [{:name=>'a', :count=>1}, ...]

[Source]

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

Alias of group

[Source]

     # File lib/sequel/dataset/query.rb, line 282
282:     def group_by(*columns)
283:       group(*columns)
284:     end

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

  DB[:items].group(:sum).having(:sum=>10)
  # SELECT * FROM items GROUP BY sum HAVING (sum = 10)

[Source]

     # File lib/sequel/dataset/query.rb, line 310
310:     def having(*cond, &block)
311:       _filter(:having, *cond, &block)
312:     end

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:

:alias :Use the given value as the from_self alias
: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[:other_items])
  # SELECT * FROM (SELECT * FROM items INTERSECT SELECT * FROM other_items) AS t1

  DB[:items].intersect(DB[:other_items], :all=>true, :from_self=>false)
  # SELECT * FROM items INTERSECT ALL SELECT * FROM other_items

  DB[:items].intersect(DB[:other_items], :alias=>:i)
  # SELECT * FROM (SELECT * FROM items INTERSECT SELECT * FROM other_items) AS i

[Source]

     # File lib/sequel/dataset/query.rb, line 331
331:     def intersect(dataset, opts={})
332:       opts = {:all=>opts} unless opts.is_a?(Hash)
333:       raise(InvalidOperation, "INTERSECT not supported") unless supports_intersect_except?
334:       raise(InvalidOperation, "INTERSECT ALL not supported") if opts[:all] && !supports_intersect_except_all?
335:       compound_clone(:intersect, dataset, opts)
336:     end

Inverts the current filter.

  DB[:items].filter(:category => 'software').invert
  # SELECT * FROM items WHERE (category != 'software')

  DB[:items].filter(:category => 'software', :id=>3).invert
  # SELECT * FROM items WHERE ((category != 'software') OR (id != 3))

[Source]

     # File lib/sequel/dataset/query.rb, line 345
345:     def invert
346:       having, where = @opts[:having], @opts[:where]
347:       raise(Error, "No current filter") unless having || where
348:       o = {}
349:       o[:having] = SQL::BooleanExpression.invert(having) if having
350:       o[:where] = SQL::BooleanExpression.invert(where) if where
351:       clone(o)
352:     end

Alias of inner_join

[Source]

     # File lib/sequel/dataset/query.rb, line 355
355:     def join(*args, &block)
356:       inner_join(*args, &block)
357:     end

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 of two element arrays - 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 an 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 Sequel 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. Unlike filter, this block is not treated as a virtual row block.

[Source]

     # File lib/sequel/dataset/query.rb, line 389
389:     def join_table(type, table, expr=nil, options={}, &block)
390:       using_join = expr.is_a?(Array) && !expr.empty? && expr.all?{|x| x.is_a?(Symbol)}
391:       if using_join && !supports_join_using?
392:         h = {}
393:         expr.each{|s| h[s] = s}
394:         return join_table(type, table, h, options)
395:       end
396: 
397:       case options
398:       when Hash
399:         table_alias = options[:table_alias]
400:         last_alias = options[:implicit_qualifier]
401:       when Symbol, String, SQL::Identifier
402:         table_alias = options
403:         last_alias = nil 
404:       else
405:         raise Error, "invalid options format for join_table: #{options.inspect}"
406:       end
407: 
408:       if Dataset === table
409:         if table_alias.nil?
410:           table_alias_num = (@opts[:num_dataset_sources] || 0) + 1
411:           table_alias = dataset_alias(table_alias_num)
412:         end
413:         table_name = table_alias
414:       else
415:         table = table.table_name if table.respond_to?(:table_name)
416:         table, implicit_table_alias = split_alias(table)
417:         table_alias ||= implicit_table_alias
418:         table_name = table_alias || table
419:       end
420: 
421:       join = if expr.nil? and !block_given?
422:         SQL::JoinClause.new(type, table, table_alias)
423:       elsif using_join
424:         raise(Sequel::Error, "can't use a block if providing an array of symbols as expr") if block_given?
425:         SQL::JoinUsingClause.new(expr, type, table, table_alias)
426:       else
427:         last_alias ||= @opts[:last_joined_table] || first_source_alias
428:         if Sequel.condition_specifier?(expr)
429:           expr = expr.collect do |k, v|
430:             k = qualified_column_name(k, table_name) if k.is_a?(Symbol)
431:             v = qualified_column_name(v, last_alias) if v.is_a?(Symbol)
432:             [k,v]
433:           end
434:         end
435:         if block_given?
436:           expr2 = yield(table_name, last_alias, @opts[:join] || [])
437:           expr = expr ? SQL::BooleanExpression.new(:AND, expr, expr2) : expr2
438:         end
439:         SQL::JoinOnClause.new(expr, type, table, table_alias)
440:       end
441: 
442:       opts = {:join => (@opts[:join] || []) + [join], :last_joined_table => table_name}
443:       opts[:num_dataset_sources] = table_alias_num if table_alias_num
444:       clone(opts)
445:     end

If given an integer, the dataset will contain only the first l results. If given a range, it will contain only those at offsets within that range. If a second argument is given, it is used as an offset. To use an offset without a limit, pass nil as the first argument.

  DB[:items].limit(10) # SELECT * FROM items LIMIT 10
  DB[:items].limit(10, 20) # SELECT * FROM items LIMIT 10 OFFSET 20
  DB[:items].limit(10...20) # SELECT * FROM items LIMIT 10 OFFSET 10
  DB[:items].limit(10..20) # SELECT * FROM items LIMIT 11 OFFSET 10
  DB[:items].limit(nil, 20) # SELECT * FROM items OFFSET 20

[Source]

     # File lib/sequel/dataset/query.rb, line 464
464:     def limit(l, o = nil)
465:       return from_self.limit(l, o) if @opts[:sql]
466: 
467:       if Range === l
468:         o = l.first
469:         l = l.last - l.first + (l.exclude_end? ? 0 : 1)
470:       end
471:       l = l.to_i if l.is_a?(String) && !l.is_a?(LiteralString)
472:       if l.is_a?(Integer)
473:         raise(Error, 'Limits must be greater than or equal to 1') unless l >= 1
474:       end
475:       opts = {:limit => l}
476:       if o
477:         o = o.to_i if o.is_a?(String) && !o.is_a?(LiteralString)
478:         if o.is_a?(Integer)
479:           raise(Error, 'Offsets must be greater than or equal to 0') unless o >= 0
480:         end
481:         opts[:offset] = o
482:       end
483:       clone(opts)
484:     end

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.

  DB[:items].lock_style('FOR SHARE') # SELECT * FROM items FOR SHARE

[Source]

     # File lib/sequel/dataset/query.rb, line 492
492:     def lock_style(style)
493:       clone(:lock => style)
494:     end

Returns a cloned dataset without a row_proc.

  ds = DB[:items]
  ds.row_proc = proc{|r| r.invert}
  ds.all # => [{2=>:id}]
  ds.naked.all # => [{:id=>2}]

[Source]

     # File lib/sequel/dataset/query.rb, line 502
502:     def naked
503:       ds = clone
504:       ds.row_proc = nil
505:       ds
506:     end

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

  DB[:items].filter(:a).or(:b) # SELECT * FROM items WHERE a OR b

[Source]

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

Returns a copy of the dataset with the order changed. If the dataset has an existing order, it is ignored and overwritten with this order. If a nil is given the returned dataset has no order. This can accept multiple arguments of varying kinds, such as SQL functions. If a block is given, it is treated as a virtual row block, similar to filter.

  DB[:items].order(:name) # SELECT * FROM items ORDER BY name
  DB[:items].order(:a, :b) # SELECT * FROM items ORDER BY a, b
  DB[:items].order('a + b'.lit) # SELECT * FROM items ORDER BY a + b
  DB[:items].order(:a + :b) # SELECT * FROM items ORDER BY (a + b)
  DB[:items].order(:name.desc) # SELECT * FROM items ORDER BY name DESC
  DB[:items].order(:name.asc(:nulls=>:last)) # SELECT * FROM items ORDER BY name ASC NULLS LAST
  DB[:items].order{sum(name).desc} # SELECT * FROM items ORDER BY sum(name) DESC
  DB[:items].order(nil) # SELECT * FROM items

[Source]

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

Alias of order_more, for naming consistency with order_prepend.

[Source]

     # File lib/sequel/dataset/query.rb, line 539
539:     def order_append(*columns, &block)
540:       order_more(*columns, &block)
541:     end

Alias of order

[Source]

     # File lib/sequel/dataset/query.rb, line 544
544:     def order_by(*columns, &block)
545:       order(*columns, &block)
546:     end

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

  DB[:items].order(:a).order(:b) # SELECT * FROM items ORDER BY b
  DB[:items].order(:a).order_more(:b) # SELECT * FROM items ORDER BY a, b

[Source]

     # File lib/sequel/dataset/query.rb, line 553
553:     def order_more(*columns, &block)
554:       columns = @opts[:order] + columns if @opts[:order]
555:       order(*columns, &block)
556:     end

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

  DB[:items].order(:a).order(:b) # SELECT * FROM items ORDER BY b
  DB[:items].order(:a).order_prepend(:b) # SELECT * FROM items ORDER BY b, a

[Source]

     # File lib/sequel/dataset/query.rb, line 563
563:     def order_prepend(*columns, &block)
564:       ds = order(*columns, &block)
565:       @opts[:order] ? ds.order_more(*@opts[:order]) : ds
566:     end

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

  DB[:items].filter(:id=>1).qualify
  # SELECT items.* FROM items WHERE (items.id = 1)

  DB[:items].filter(:id=>1).qualify(:i)
  # SELECT i.* FROM items WHERE (i.id = 1)

[Source]

     # File lib/sequel/dataset/query.rb, line 575
575:     def qualify(table=first_source)
576:       qualify_to(table)
577:     end

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.

  DB[:items].filter(:id=>1).qualify_to(:i)
  # SELECT i.* FROM items WHERE (i.id = 1)

[Source]

     # File lib/sequel/dataset/query.rb, line 586
586:     def qualify_to(table)
587:       o = @opts
588:       return clone if o[:sql]
589:       h = {}
590:       (o.keys & QUALIFY_KEYS).each do |k|
591:         h[k] = qualified_expression(o[k], table)
592:       end
593:       h[:select] = [SQL::ColumnAll.new(table)] if !o[:select] || o[:select].empty?
594:       clone(h)
595:     end

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.

  DB[:items].filter(:id=>1).qualify_to_first_source
  # SELECT items.* FROM items WHERE (items.id = 1)

[Source]

     # File lib/sequel/dataset/query.rb, line 605
605:     def qualify_to_first_source
606:       qualify_to(first_source)
607:     end

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

  DB[:items].reverse(:id) # SELECT * FROM items ORDER BY id DESC
  DB[:items].order(:id).reverse # SELECT * FROM items ORDER BY id DESC
  DB[:items].order(:id).reverse(:name.asc) # SELECT * FROM items ORDER BY name ASC

[Source]

     # File lib/sequel/dataset/query.rb, line 615
615:     def reverse(*order)
616:       order(*invert_order(order.empty? ? @opts[:order] : order))
617:     end

Alias of reverse

[Source]

     # File lib/sequel/dataset/query.rb, line 620
620:     def reverse_order(*order)
621:       reverse(*order)
622:     end

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.

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

[Source]

     # File lib/sequel/dataset/query.rb, line 631
631:     def select(*columns, &block)
632:       columns += Array(Sequel.virtual_row(&block)) if block
633:       m = []
634:       columns.each do |i|
635:         i.is_a?(Hash) ? m.concat(i.map{|k, v| SQL::AliasedExpression.new(k,v)}) : m << i
636:       end
637:       clone(:select => m)
638:     end

Returns a copy of the dataset selecting the wildcard.

  DB[:items].select(:a).select_all # SELECT * FROM items

[Source]

     # File lib/sequel/dataset/query.rb, line 643
643:     def select_all
644:       clone(:select => nil)
645:     end

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

  DB[:items].select(:a).select(:b) # SELECT b FROM items
  DB[:items].select(:a).select_append(:b) # SELECT a, b FROM items
  DB[:items].select_append(:b) # SELECT *, b FROM items

[Source]

     # File lib/sequel/dataset/query.rb, line 654
654:     def select_append(*columns, &block)
655:       cur_sel = @opts[:select]
656:       cur_sel = [WILDCARD] if !cur_sel || cur_sel.empty?
657:       select(*(cur_sel + columns), &block)
658:     end

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.

  DB[:items].select(:a).select(:b) # SELECT b FROM items
  DB[:items].select(:a).select_more(:b) # SELECT a, b FROM items
  DB[:items].select_more(:b) # SELECT b FROM items

[Source]

     # File lib/sequel/dataset/query.rb, line 667
667:     def select_more(*columns, &block)
668:       columns = @opts[:select] + columns if @opts[:select]
669:       select(*columns, &block)
670:     end

Set the server for this dataset to use. Used to pick a specific database shard to run a query against, or to override the default (which is SELECT uses :read_only database and all other queries use the :default database). This method is always available but is only useful when database sharding is being used.

  DB[:items].all # Uses the :read_only or :default server
  DB[:items].delete # Uses the :default server
  DB[:items].server(:blah).delete # Uses the :blah server

[Source]

     # File lib/sequel/dataset/query.rb, line 681
681:     def server(servr)
682:       clone(:server=>servr)
683:     end

Set the default values for insert and update statements. The values hash passed to insert or update are merged into this hash, so any values in the hash passed to insert or update will override values passed to this method.

  DB[:items].set_defaults(:a=>'a', :c=>'c').insert(:a=>'d', :b=>'b')
  # INSERT INTO items (a, c, b) VALUES ('d', 'c', 'b')

[Source]

     # File lib/sequel/dataset/query.rb, line 691
691:     def set_defaults(hash)
692:       clone(:defaults=>(@opts[:defaults]||{}).merge(hash))
693:     end

Set values that override hash arguments given to insert and update statements. This hash is merged into the hash provided to insert or update, so values will override any values given in the insert/update hashes.

  DB[:items].set_overrides(:a=>'a', :c=>'c').insert(:a=>'d', :b=>'b')
  # INSERT INTO items (a, c, b) VALUES ('a', 'c', 'b')

[Source]

     # File lib/sequel/dataset/query.rb, line 701
701:     def set_overrides(hash)
702:       clone(:overrides=>hash.merge(@opts[:overrides]||{}))
703:     end

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

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

[Source]

     # File lib/sequel/dataset/query.rb, line 709
709:     def unfiltered
710:       clone(:where => nil, :having => nil)
711:     end

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

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

[Source]

     # File lib/sequel/dataset/query.rb, line 717
717:     def ungrouped
718:       clone(:group => nil, :having => nil)
719:     end

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:

:alias :Use the given value as the from_self alias
: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[:other_items]).sql
  #=> "SELECT * FROM items UNION SELECT * FROM other_items"

  DB[:items].union(DB[:other_items], :all=>true, :from_self=>false)
  # SELECT * FROM items UNION ALL SELECT * FROM other_items

  DB[:items].union(DB[:other_items], :alias=>:i)
  # SELECT * FROM (SELECT * FROM items UNION SELECT * FROM other_items) AS i

[Source]

     # File lib/sequel/dataset/query.rb, line 737
737:     def union(dataset, opts={})
738:       opts = {:all=>opts} unless opts.is_a?(Hash)
739:       compound_clone(:union, dataset, opts)
740:     end

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

  DB[:items].limit(10, 20).unlimited # SELECT * FROM items

[Source]

     # File lib/sequel/dataset/query.rb, line 745
745:     def unlimited
746:       clone(:limit=>nil, :offset=>nil)
747:     end

Returns a copy of the dataset with no order.

  DB[:items].order(:a).unordered # SELECT * FROM items

[Source]

     # File lib/sequel/dataset/query.rb, line 752
752:     def unordered
753:       order(nil)
754:     end

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

  DB[:items].group(:a).having(:a).filter(:b)
  # SELECT * FROM items GROUP BY a HAVING a AND b

  DB[:items].group(:a).having(:a).where(:b)
  # SELECT * FROM items WHERE b GROUP BY a HAVING a

[Source]

     # File lib/sequel/dataset/query.rb, line 763
763:     def where(*cond, &block)
764:       _filter(:where, *cond, &block)
765:     end

Add a 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
  DB[:items].with(:items, DB[:syx].filter(:name.like('A%')))
  # WITH items AS (SELECT * FROM syx WHERE (name LIKE 'A%')) SELECT * FROM items

[Source]

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

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.
  DB[:t].select(:i___id, :pi___parent_id).
   with_recursive(:t,
                  DB[:i1].filter(:parent_id=>nil),
                  DB[:t].join(:t, :i=>:parent_id).select(:i1__id, :i1__parent_id),
                  :args=>[:i, :pi])
  # WITH RECURSIVE t(i, pi) AS (
  #   SELECT * FROM i1 WHERE (parent_id IS NULL)
  #   UNION ALL
  #   SELECT i1.id, i1.parent_id FROM t INNER JOIN t ON (t.i = t.parent_id)
  # )
  # SELECT i AS id, pi AS parent_id FROM t

[Source]

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

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.

  DB[:items].with_sql('SELECT * FROM foo') # SELECT * FROM foo

[Source]

     # File lib/sequel/dataset/query.rb, line 806
806:     def with_sql(sql, *args)
807:       sql = SQL::PlaceholderLiteralString.new(sql, args) unless args.empty?
808:       clone(:sql=>sql)
809:     end

Protected Instance methods

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

[Source]

     # File lib/sequel/dataset/query.rb, line 814
814:     def options_overlap(opts)
815:       !(@opts.collect{|k,v| k unless v.nil?}.compact & opts).empty?
816:     end

Whether this dataset is a simple SELECT * FROM table.

[Source]

     # File lib/sequel/dataset/query.rb, line 819
819:     def simple_select_all?
820:       o = @opts.reject{|k,v| v.nil? || NON_SQL_OPTIONS.include?(k)}
821:       o.length == 1 && (f = o[:from]) && f.length == 1 && (f.first.is_a?(Symbol) || f.first.is_a?(SQL::AliasedExpression))
822:     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.

Constants

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

Public Instance methods

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.

  DB[:table].filter(:id=>:$id).bind(:id=>1).call(:first)
  # SELECT * FROM table WHERE id = ? LIMIT 1 -- (1)
  # => {:id=>1}

[Source]

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

For the given type (:select, :insert, :update, or :delete), run the sql with the bind variables specified in the hash. values is a hash of passed to insert or update (if one of those types is used), which may contain placeholders.

  DB[:table].filter(:id=>:$id).call(:first, :id=>1)
  # SELECT * FROM table WHERE id = ? LIMIT 1 -- (1)
  # => {:id=>1}

[Source]

     # File lib/sequel/dataset/prepared_statements.rb, line 196
196:     def call(type, bind_variables={}, *values, &block)
197:       prepare(type, nil, *values).call(bind_variables, &block)
198:     end

Prepare an SQL statement for later execution. This returns a clone of the dataset extended with PreparedStatementMethods, on which you can call call with the hash of bind variables to do substitution. The prepared statement is also stored in the associated database. The following usage is identical:

  ps = DB[:table].filter(:name=>:$name).prepare(:first, :select_by_name)

  ps.call(:name=>'Blah')
  # SELECT * FROM table WHERE name = ? -- ('Blah')
  # => {:id=>1, :name=>'Blah'}

  DB.call(:select_by_name, :name=>'Blah') # Same thing

[Source]

     # File lib/sequel/dataset/prepared_statements.rb, line 213
213:     def prepare(type, name=nil, *values)
214:       ps = to_prepared_statement(type, values)
215:       db.prepared_statements[name] = ps if name
216:       ps
217:     end

Protected Instance methods

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 223
223:     def to_prepared_statement(type, values=nil)
224:       ps = bind
225:       ps.extend(PreparedStatementMethods)
226:       ps.prepared_type = type
227:       ps.prepared_modify_values = values
228:       ps
229:     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 related to this dataset. This is the Database instance that will execute all of this dataset‘s queries.
opts  [RW]  The hash of options for this dataset, keys are symbols.

Public Class methods

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 provides a subclass of Sequel::Dataset, and has the Database#dataset method return an instance of that subclass.

[Source]

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

Public Instance methods

Define a hash value such that datasets with the same DB, opts, and SQL will be consider equal.

[Source]

    # File lib/sequel/dataset/misc.rb, line 39
39:     def ==(o)
40:       o.is_a?(self.class) && db == o.db  && opts == o.opts && sql == o.sql
41:     end

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.

  DB.from(DB[:table].as(:b)) # SELECT * FROM (SELECT * FROM table) AS b

[Source]

    # File lib/sequel/dataset/misc.rb, line 53
53:     def as(aliaz)
54:       ::Sequel::SQL::AliasedExpression.new(self, aliaz)
55:     end

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 62
62:     def each_server
63:       db.servers.each{|s| yield server(s)}
64:     end

Alias for ==

[Source]

    # File lib/sequel/dataset/misc.rb, line 44
44:     def eql?(o)
45:       self == o
46:     end

Alias of first_source_alias

[Source]

    # File lib/sequel/dataset/misc.rb, line 67
67:     def first_source
68:       first_source_alias
69:     end

The first source (primary table) for this dataset. If the dataset doesn‘t have a table, raises an Error. If the table is aliased, returns the aliased name.

  DB[:table].first_source_alias
  # => :table

  DB[:table___t].first_source_alias
  # => :t

[Source]

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

The first source (primary table) for this dataset. If the dataset doesn‘t have a table, raises an error. If the table is aliased, returns the original table, not the alias

  DB[:table].first_source_alias
  # => :table

  DB[:table___t].first_source_alias
  # => :table

[Source]

     # File lib/sequel/dataset/misc.rb, line 104
104:     def first_source_table
105:       source = @opts[:from]
106:       if source.nil? || source.empty?
107:         raise Error, 'No source specified for query'
108:       end
109:       case s = source.first
110:       when SQL::AliasedExpression
111:         s.expression
112:       when Symbol
113:         sch, table, aliaz = split_symbol(s)
114:         aliaz ? (sch ? SQL::QualifiedIdentifier.new(sch, table) : table.to_sym) : s
115:       else
116:         s
117:       end
118:     end

Define a hash value such that datasets with the same DB, opts, and SQL will have the same hash value

[Source]

     # File lib/sequel/dataset/misc.rb, line 122
122:     def hash
123:       [db, opts.sort_by{|k| k.to_s}, sql].hash
124:     end

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 128
128:     def inspect
129:       "#<#{self.class}: #{sql.inspect}>"
130:     end

Splits a possible implicit alias in C, handling both SQL::AliasedExpressions and Symbols. Returns an array of two elements, with the first being the main expression, and the second being the alias.

[Source]

     # File lib/sequel/dataset/misc.rb, line 135
135:     def split_alias(c)
136:       case c
137:       when Symbol
138:         c_table, column, aliaz = split_symbol(c)
139:         [c_table ? SQL::QualifiedIdentifier.new(c_table, column.to_sym) : column.to_sym, aliaz]
140:       when SQL::AliasedExpression
141:         [c.expression, c.aliaz]
142:       else
143:         [c, nil]
144:       end
145:     end

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.

  DB[:table].unused_table_alias(:t)
  # => :t

  DB[:table].unused_table_alias(:table)
  # => :table_0

  DB[:table, :table_0].unused_table_alias(:table)
  # => :table_1

[Source]

     # File lib/sequel/dataset/misc.rb, line 162
162:     def unused_table_alias(table_alias)
163:       table_alias = alias_symbol(table_alias)
164:       used_aliases = []
165:       used_aliases += opts[:from].map{|t| alias_symbol(t)} if opts[:from]
166:       used_aliases += opts[:join].map{|j| j.table_alias ? alias_alias_symbol(j.table_alias) : alias_symbol(j.table)} if opts[:join]
167:       if used_aliases.include?(table_alias)
168:         i = 0
169:         loop do
170:           ta = "#{table_alias}_#{i}""#{table_alias}_#{i}"
171:           return ta unless used_aliases.include?(ta)
172:           i += 1 
173:         end
174:       else
175:         table_alias
176:       end
177:     end

Methods related to dataset graphing

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

Public Instance methods

Adds the given graph aliases to the list of graph aliases to use, unlike set_graph_aliases, which replaces the list (the equivalent of select_more when graphing). See set_graph_aliases.

  DB[:table].add_graph_aliases(:some_alias=>[:table, :column])
  # SELECT ..., table.column AS some_alias
  # => {:table=>{:column=>some_alias_value, ...}, ...}

[Source]

    # File lib/sequel/dataset/graph.rb, line 17
17:     def add_graph_aliases(graph_aliases)
18:       ds = select_more(*graph_alias_columns(graph_aliases))
19:       ds.opts[:graph_aliases] = (ds.opts[:graph_aliases] || (ds.opts[:graph][:column_aliases] rescue {}) || {}).merge(graph_aliases)
20:       ds
21:     end

Allows you to join multiple datasets/tables and have the result set split into component tables.

This differs from the usual usage of join, which returns the result set as a single hash. For example:

  # CREATE TABLE artists (id INTEGER, name TEXT);
  # CREATE TABLE albums (id INTEGER, name TEXT, artist_id INTEGER);

  DB[:artists].left_outer_join(:albums, :artist_id=>:id).first
  #=> {:id=>albums.id, :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 returns a symbol or a dataset
join_conditions :Any condition(s) allowed by join_table.
block :A block that is passed to join_table.

Options:

: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 the join that makes it important to use graph instead of join_table.
: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.

[Source]

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

This allows you to manually specify the graph aliases to use when using graph. You can use it to only select certain columns, and have those columns mapped to specific aliases in the result set. This is the equivalent of select for a graphed dataset, and must be used instead of select whenever graphing is used.

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.
  DB[:artists].graph(:albums, :artist_id=>:id).
    set_graph_aliases(:artist_name=>[:artists, :name],
                      :album_name=>[:albums, :name],
                      :forty_two=>[:albums, :fourtwo, 42]).first
  # SELECT artists.name AS artist_name, albums.name AS album_name, 42 AS forty_two FROM table
  # => {:artists=>{:name=>artists.name}, :albums=>{:name=>albums.name, :fourtwo=>42}}

[Source]

     # File lib/sequel/dataset/graph.rb, line 198
198:     def set_graph_aliases(graph_aliases)
199:       ds = select(*graph_alias_columns(graph_aliases))
200:       ds.opts[:graph_aliases] = graph_aliases
201:       ds
202:     end

Remove the splitting of results into subhashes, and all metadata related to the current graph (if any).

[Source]

     # File lib/sequel/dataset/graph.rb, line 206
206:     def ungraphed
207:       clone(:graph=>nil)
208:     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

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

Whether this dataset quotes identifiers.

[Source]

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

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

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

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

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

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

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

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

Whether modifying joined datasets is supported.

[Source]

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

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

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

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

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

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

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

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

Returns the first record matching the conditions. Examples:

  DB[:table][:id=>1] # SELECT * FROM table WHERE (id = 1) LIMIT 1
  # => {:id=1}

[Source]

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

Update all records matching the conditions with the values specified. Returns the number of rows affected.

  DB[:table][:id=>1] = {:id=>2} # UPDATE table SET id = 2 WHERE id = 1
  # => 1 # number of rows affected

[Source]

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

Returns an array with all records in the dataset. If a block is given, the array is iterated over after all items have been loaded.

  DB[:table].all # SELECT * FROM table
  # => [{:id=>1, ...}, {:id=>2, ...}, ...]

  # Iterate over all rows in the table
  DB[:table].all{|row| p row}

[Source]

    # File lib/sequel/dataset/actions.rb, line 48
48:     def all(&block)
49:       a = []
50:       each{|r| a << r}
51:       post_load(a)
52:       a.each(&block) if block
53:       a
54:     end

Returns the average value for the given column.

  DB[:table].avg(:number) # SELECT avg(number) FROM table LIMIT 1
  # => 3

[Source]

    # File lib/sequel/dataset/actions.rb, line 60
60:     def avg(column)
61:       aggregate_dataset.get{avg(column)}
62:     end

Returns the columns in the result set in order as an array of symbols. If the columns are currently cached, returns the cached value. Otherwise, a SELECT query is performed to retrieve a single row in order to get the columns.

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

  DB[:table].columns
  # => [:id, :name]

[Source]

    # File lib/sequel/dataset/actions.rb, line 73
73:     def columns
74:       return @columns if @columns
75:       ds = unfiltered.unordered.clone(:distinct => nil, :limit => 1)
76:       ds.each{break}
77:       @columns = ds.instance_variable_get(:@columns)
78:       @columns || []
79:     end

Ignore any cached column information and perform a query to retrieve a row in order to get the columns.

  DB[:table].columns!
  # => [:id, :name]

[Source]

    # File lib/sequel/dataset/actions.rb, line 86
86:     def columns!
87:       @columns = nil
88:       columns
89:     end

Returns the number of records in the dataset.

  DB[:table].count # SELECT COUNT(*) AS count FROM table LIMIT 1
  # => 3

[Source]

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

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

  DB[:table].delete # DELETE * FROM table
  # => 3

[Source]

     # File lib/sequel/dataset/actions.rb, line 104
104:     def delete
105:       execute_dui(delete_sql)
106:     end

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

  DB[:table].each{|row| p row} # SELECT * FROM table

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 117
117:     def each(&block)
118:       if @opts[:graph]
119:         graph_each(&block)
120:       elsif row_proc = @row_proc
121:         fetch_rows(select_sql){|r| yield row_proc.call(r)}
122:       else
123:         fetch_rows(select_sql, &block)
124:       end
125:       self
126:     end

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

  DB[:table].empty? # SELECT 1 FROM table LIMIT 1
  # => false

[Source]

     # File lib/sequel/dataset/actions.rb, line 132
132:     def empty?
133:       get(1).nil?
134:     end

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

Executes a select query and fetches records, passing each record to the supplied block. The yielded records should be hashes with symbol keys. This method should probably should not be called by user code, use each instead.

[Source]

     # File lib/sequel/dataset/actions.rb, line 140
140:     def fetch_rows(sql, &block)
141:       raise NotImplemented, NOTIMPL_MSG
142:     end

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

Set the columns and yield the hashes to the block.

[Source]

     # File lib/sequel/adapters/swift.rb, line 136
136:       def fetch_rows(sql, &block)
137:         execute(sql) do |res|
138:           @columns = res.fields
139:           res.each(&block)
140:         end
141:         self
142:       end

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:

  DB[:table].first # SELECT * FROM table LIMIT 1
  # => {:id=>7}

  DB[:table].first(2) # SELECT * FROM table LIMIT 2
  # => [{:id=>6}, {:id=>4}]

  DB[:table].first(:id=>2) # SELECT * FROM table WHERE (id = 2) LIMIT 1
  # => {:id=>2}

  DB[:table].first("id = 3") # SELECT * FROM table WHERE (id = 3) LIMIT 1
  # => {:id=>3}

  DB[:table].first("id = ?", 4) # SELECT * FROM table WHERE (id = 4) LIMIT 1
  # => {:id=>4}

  DB[:table].first{id > 2} # SELECT * FROM table WHERE (id > 2) LIMIT 1
  # => {:id=>5}

  DB[:table].first("id > ?", 4){id < 6} # SELECT * FROM table WHERE ((id > 4) AND (id < 6)) LIMIT 1
  # => {:id=>5}

  DB[:table].first(2){id < 2} # SELECT * FROM table WHERE (id < 2) LIMIT 2
  # => [{:id=>1}]

[Source]

     # File lib/sequel/dataset/actions.rb, line 174
174:     def first(*args, &block)
175:       ds = block ? filter(&block) : self
176: 
177:       if args.empty?
178:         ds.single_record
179:       else
180:         args = (args.size == 1) ? args.first : args
181:         if Integer === args
182:           ds.limit(args).all
183:         else
184:           ds.filter(args).single_record
185:         end
186:       end
187:     end

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

  DB[:table].get(:id) # SELECT id FROM table LIMIT 1
  # => 3

  ds.get{sum(id)} # SELECT sum(id) FROM table LIMIT 1
  # => 6

[Source]

     # File lib/sequel/dataset/actions.rb, line 197
197:     def get(column=nil, &block)
198:       if column
199:         raise(Error, ARG_BLOCK_ERROR_MSG) if block
200:         select(column).single_value
201:       else
202:         select(&block).single_value
203:       end
204:     end

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:

  DB[:table].import([:x, :y], [[1, 2], [3, 4]])
  # INSERT INTO table (x, y) VALUES (1, 2)
  # INSERT INTO table (x, y) VALUES (3, 4)

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

  DB[:table].import([:x, :y], DB[:table2].select(:a, :b))
  # INSERT INTO table (x, y) SELECT a, b FROM table2

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 228
228:     def import(columns, values, opts={})
229:       return @db.transaction{insert(columns, values)} if values.is_a?(Dataset)
230: 
231:       return if values.empty?
232:       raise(Error, IMPORT_ERROR_MSG) if columns.empty?
233:       
234:       if slice_size = opts[:commit_every] || opts[:slice]
235:         offset = 0
236:         loop do
237:           @db.transaction(opts){multi_insert_sql(columns, values[offset, slice_size]).each{|st| execute_dui(st)}}
238:           offset += slice_size
239:           break if offset >= values.length
240:         end
241:       else
242:         statements = multi_insert_sql(columns, values)
243:         @db.transaction{statements.each{|st| execute_dui(st)}}
244:       end
245:     end

Inserts values into the associated table. The returned value is generally the value of the primary key for the inserted row, but that is adapter dependent.

insert handles a number of different argument formats:

  • No arguments, single empty hash - Uses DEFAULT VALUES
  • Single hash - Most common format, treats keys as columns an values as values
  • Single array - Treats entries as values, with no columns
  • Two arrays - Treats first array as columns, second array as values
  • Single Dataset - Treats as an insert based on a selection from the dataset given, with no columns
  • Array and dataset - Treats as an insert based on a selection from the dataset given, with the columns given by the array.

    DB[:items].insert # INSERT INTO items DEFAULT VALUES

    DB[:items].insert({}) # INSERT INTO items DEFAULT VALUES

    DB[:items].insert() # INSERT INTO items VALUES (1, 2, 3)

    DB[:items].insert([:a, :b], [1,2]) # INSERT INTO items (a, b) VALUES (1, 2)

    DB[:items].insert(:a => 1, :b => 2) # INSERT INTO items (a, b) VALUES (1, 2)

    DB[:items].insert(DB) # INSERT INTO items SELECT * FROM old_items

    DB[:items].insert([:a, :b], DB[:old_items]) # INSERT INTO items (a, b) SELECT * FROM old_items

[Source]

     # File lib/sequel/dataset/actions.rb, line 280
280:     def insert(*values)
281:       execute_insert(insert_sql(*values))
282:     end

Inserts multiple values. If a block is given it is invoked for each item in the given array before inserting it. See multi_insert as a possible faster version that inserts multiple records in one SQL statement.

  DB[:table].insert_multiple([{:x=>1}, {:x=>2}])
  # INSERT INTO table (x) VALUES (1)
  # INSERT INTO table (x) VALUES (2)

  DB[:table].insert_multiple([{:x=>1}, {:x=>2}]){|row| row[:y] = row[:x] * 2}
  # INSERT INTO table (x, y) VALUES (1, 2)
  # INSERT INTO table (x, y) VALUES (2, 4)

[Source]

     # File lib/sequel/dataset/actions.rb, line 296
296:     def insert_multiple(array, &block)
297:       if block
298:         array.each {|i| insert(block[i])}
299:       else
300:         array.each {|i| insert(i)}
301:       end
302:     end

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

  DB[:table].interval(:id) # SELECT (max(id) - min(id)) FROM table LIMIT 1
  # => 6

[Source]

     # File lib/sequel/dataset/actions.rb, line 309
309:     def interval(column)
310:       aggregate_dataset.get{max(column) - min(column)}
311:     end

Reverses the order and then runs first. Note that this will not necessarily give you the last record in the dataset, unless you have an unambiguous order. If there is not currently an order for this dataset, raises an Error.

  DB[:table].order(:id).last # SELECT * FROM table ORDER BY id DESC LIMIT 1
  # => {:id=>10}

  DB[:table].order(:id.desc).last(2) # SELECT * FROM table ORDER BY id ASC LIMIT 2
  # => [{:id=>1}, {:id=>2}]

[Source]

     # File lib/sequel/dataset/actions.rb, line 323
323:     def last(*args, &block)
324:       raise(Error, 'No order specified') unless @opts[:order]
325:       reverse.first(*args, &block)
326:     end

Maps column values for each record in the dataset (if a column name is given), or performs the stock mapping functionality of Enumerable otherwise. Raises an Error if both an argument and block are given.

  DB[:table].map(:id) # SELECT * FROM table
  # => [1, 2, 3, ...]

  DB[:table].map{|r| r[:id] * 2} # SELECT * FROM table
  # => [2, 4, 6, ...]

[Source]

     # File lib/sequel/dataset/actions.rb, line 337
337:     def map(column=nil, &block)
338:       if column
339:         raise(Error, ARG_BLOCK_ERROR_MSG) if block
340:         super(){|r| r[column]}
341:       else
342:         super(&block)
343:       end
344:     end

Returns the maximum value for the given column.

  DB[:table].max(:id) # SELECT max(id) FROM table LIMIT 1
  # => 10

[Source]

     # File lib/sequel/dataset/actions.rb, line 350
350:     def max(column)
351:       aggregate_dataset.get{max(column)}
352:     end

Returns the minimum value for the given column.

  DB[:table].min(:id) # SELECT min(id) FROM table LIMIT 1
  # => 1

[Source]

     # File lib/sequel/dataset/actions.rb, line 358
358:     def min(column)
359:       aggregate_dataset.get{min(column)}
360:     end

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

  DB[:table].multi_insert([{:x => 1}, {:x => 2}])
  # INSERT INTO table (x) VALUES (1)
  # INSERT INTO table (x) VALUES (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 374
374:     def multi_insert(hashes, opts={})
375:       return if hashes.empty?
376:       columns = hashes.first.keys
377:       import(columns, hashes.map{|h| columns.map{|c| h[c]}}, opts)
378:     end

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

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

  DB[:table].range(:id) # SELECT max(id) AS v1, min(id) AS v2 FROM table LIMIT 1
  # => 1..10

[Source]

     # File lib/sequel/dataset/actions.rb, line 385
385:     def range(column)
386:       if r = aggregate_dataset.select{[min(column).as(v1), max(column).as(v2)]}.first
387:         (r[:v1]..r[:v2])
388:       end
389:     end

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.

  DB[:table].select_hash(:id, :name) # SELECT id, name FROM table
  # => {1=>'a', 2=>'b', ...}

[Source]

     # File lib/sequel/dataset/actions.rb, line 396
396:     def select_hash(key_column, value_column)
397:       select(key_column, value_column).to_hash(hash_key_symbol(key_column), hash_key_symbol(value_column))
398:     end

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.

  DB[:table].select_map(:id) # SELECT id FROM table
  # => [3, 5, 8, 1, ...]

  DB[:table].select_map{abs(id)} # SELECT abs(id) FROM table
  # => [3, 5, 8, 1, ...]

[Source]

     # File lib/sequel/dataset/actions.rb, line 410
410:     def select_map(column=nil, &block)
411:       ds = naked.ungraphed
412:       ds = if column
413:         raise(Error, ARG_BLOCK_ERROR_MSG) if block
414:         ds.select(column)
415:       else
416:         ds.select(&block)
417:       end
418:       ds.map{|r| r.values.first}
419:     end

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

  DB[:table].select_order_map(:id) # SELECT id FROM table ORDER BY id
  # => [1, 2, 3, 4, ...]

  DB[:table].select_order_map{abs(id)} # SELECT abs(id) FROM table ORDER BY abs(id)
  # => [1, 2, 3, 4, ...]

[Source]

     # File lib/sequel/dataset/actions.rb, line 428
428:     def select_order_map(column=nil, &block)
429:       ds = naked.ungraphed
430:       ds = if column
431:         raise(Error, ARG_BLOCK_ERROR_MSG) if block
432:         ds.select(column).order(unaliased_identifier(column))
433:       else
434:         ds.select(&block).order(&block)
435:       end
436:       ds.map{|r| r.values.first}
437:     end

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

[Source]

     # File lib/sequel/dataset/actions.rb, line 441
441:     def set(*args)
442:       update(*args)
443:     end

Returns the first record in the dataset, or nil if the dataset has no records. Users should probably use first instead of this method.

[Source]

     # File lib/sequel/dataset/actions.rb, line 448
448:     def single_record
449:       clone(:limit=>1).each{|r| return r}
450:       nil
451:     end

Returns the first value of the first record in the dataset. Returns nil if dataset is empty. Users should generally use get instead of this method.

[Source]

     # File lib/sequel/dataset/actions.rb, line 456
456:     def single_value
457:       if r = naked.ungraphed.single_record
458:         r.values.first
459:       end
460:     end

Returns the sum for the given column.

  DB[:table].sum(:id) # SELECT sum(id) FROM table LIMIT 1
  # => 55

[Source]

     # File lib/sequel/dataset/actions.rb, line 466
466:     def sum(column)
467:       aggregate_dataset.get{sum(column)}
468:     end

Returns a string in CSV format containing the dataset records. By default the CSV representation includes the column titles in the first line. You can turn that off by passing false as the include_column_titles argument.

This does not use a CSV library or handle quoting of values in any way. If any values in any of the rows could include commas or line endings, you shouldn‘t use this.

  puts DB[:table].to_csv # SELECT * FROM table
  # id,name
  # 1,Jim
  # 2,Bob

[Source]

     # File lib/sequel/dataset/actions.rb, line 483
483:     def to_csv(include_column_titles = true)
484:       n = naked
485:       cols = n.columns
486:       csv = ''
487:       csv << "#{cols.join(COMMA_SEPARATOR)}\r\n" if include_column_titles
488:       n.each{|r| csv << "#{cols.collect{|c| r[c]}.join(COMMA_SEPARATOR)}\r\n"}
489:       csv
490:     end

Returns a hash with one column used as key and another used as value. If rows have duplicate values for the key column, the latter row(s) will overwrite the value of the previous row(s). If the value_column is not given or nil, uses the entire hash as the value.

  DB[:table].to_hash(:id, :name) # SELECT * FROM table
  # {1=>'Jim', 2=>'Bob', ...}

  DB[:table].to_hash(:id) # SELECT * FROM table
  # {1=>{:id=>1, :name=>'Jim'}, 2=>{:id=>2, :name=>'Bob'}, ...}

[Source]

     # File lib/sequel/dataset/actions.rb, line 502
502:     def to_hash(key_column, value_column = nil)
503:       inject({}) do |m, r|
504:         m[r[key_column]] = value_column ? r[value_column] : r
505:         m
506:       end
507:     end

Truncates the dataset. Returns nil.

  DB[:table].truncate # TRUNCATE table
  # => nil

[Source]

     # File lib/sequel/dataset/actions.rb, line 513
513:     def truncate
514:       execute_ddl(truncate_sql)
515:     end

Updates values for the dataset. The returned value is generally the number of rows updated, but that is adapter dependent. values should a hash where the keys are columns to set and values are the values to which to set the columns.

  DB[:table].update(:x=>nil) # UPDATE table SET x = NULL
  # => 10

  DB[:table].update(:x=>:x+1, :y=>0) # UPDATE table SET x = (x + 1), :y = 0
  # => 10

[Source]

     # File lib/sequel/dataset/actions.rb, line 527
527:     def update(values={})
528:       execute_dui(update_sql(values))
529:     end