A dataset represents an SQL query, or more generally, an abstract set of rows in the database. Datasets can be used to create, retrieve, update and delete records.
Query results are always retrieved on demand, so a dataset can be kept around and reused indefinitely (datasets never cache results):
my_posts = DB[:posts].filter(:author => 'david') # no records are retrieved my_posts.all # records are retrieved my_posts.all # records are retrieved again
Most dataset methods return modified copies of the dataset (functional style), so you can reuse different datasets to access data:
posts = DB[:posts] davids_posts = posts.filter(:author => 'david') old_posts = posts.filter('stamp < ?', Date.today - 7) davids_old_posts = davids_posts.filter('stamp < ?', Date.today - 7)
Datasets are Enumerable objects, so they can be manipulated using any of the Enumerable methods, such as map, inject, etc.
For more information, see the “Dataset Basics” guide.
These methods, while public, are not designed to be used directly by the end user.
Given a type (e.g. select) and an array of clauses, return an array of methods to call to build the SQL string.
# File lib/sequel/dataset/sql.rb, line 182 def self.clause_methods(type, clauses) clauses.map{|clause| :"#{type}_#{clause}_sql"}.freeze end
SQL fragment for the aliased expression
# File lib/sequel/dataset/sql.rb, line 214 def aliased_expression_sql(ae) as_sql(literal(ae.expression), ae.aliaz) end
SQL fragment for BooleanConstants
# File lib/sequel/dataset/sql.rb, line 224 def boolean_constant_sql(constant) literal(constant) end
SQL fragment for specifying given CaseExpression.
# File lib/sequel/dataset/sql.rb, line 229 def case_expression_sql(ce) sql = '(CASE ' sql << "#{literal(ce.expression)} " if ce.expression ce.conditions.collect{ |c,r| sql << "WHEN #{literal(c)} THEN #{literal(r)} " } sql << "ELSE #{literal(ce.default)} END)" end
SQL fragment for specifying all columns in a given table.
# File lib/sequel/dataset/sql.rb, line 244 def column_all_sql(ca) "#{quote_schema_table(ca.table)}.*" end
SQL fragment for complex expressions
# File lib/sequel/dataset/sql.rb, line 249 def complex_expression_sql(op, args) case op when *IS_OPERATORS r = args.at(1) if r.nil? || supports_is_true? raise(InvalidOperation, 'Invalid argument used for IS operator') unless v = IS_LITERALS[r] "(#{literal(args.at(0))} #{op} #{v})" elsif op == :IS complex_expression_sql(:"=", args) else complex_expression_sql(:OR, [SQL::BooleanExpression.new(:"!=", *args), SQL::BooleanExpression.new(:IS, args.at(0), nil)]) end when :IN, :"NOT IN" cols = args.at(0) vals = args.at(1) col_array = true if cols.is_a?(Array) || cols.is_a?(SQL::SQLArray) if vals.is_a?(Array) || vals.is_a?(SQL::SQLArray) val_array = true empty_val_array = vals.to_a == [] end if col_array if empty_val_array if op == :IN literal(SQL::BooleanExpression.from_value_pairs(cols.to_a.map{|x| [x, x]}, :AND, true)) else literal(1=>1) end elsif !supports_multiple_column_in? if val_array 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]})}) literal(op == :IN ? expr : ~expr) else old_vals = vals vals = vals.to_a val_cols = old_vals.columns complex_expression_sql(op, [cols, vals.map!{|x| x.values_at(*val_cols)}]) end else "(#{literal(cols)} #{op} #{literal(vals)})" end else if empty_val_array if op == :IN literal(SQL::BooleanExpression.from_value_pairs([[cols, cols]], :AND, true)) else literal(1=>1) end else "(#{literal(cols)} #{op} #{literal(vals)})" end end when *TWO_ARITY_OPERATORS "(#{literal(args.at(0))} #{op} #{literal(args.at(1))})" when *N_ARITY_OPERATORS "(#{args.collect{|a| literal(a)}.join(" #{op} ")})" when :NOT "NOT #{literal(args.at(0))}" when :NOOP literal(args.at(0)) when :'B~' "~#{literal(args.at(0))}" else raise(InvalidOperation, "invalid operator #{op}") end end
SQL fragment for constants
# File lib/sequel/dataset/sql.rb, line 316 def constant_sql(constant) constant.to_s end
Yields a paginated dataset for each page and returns the receiver. Does a count to find the total number of records for this dataset.
# File lib/sequel/extensions/pagination.rb, line 20 def each_page(page_size, &block) raise(Error, "You cannot paginate a dataset that already has a limit") if @opts[:limit] record_count = count total_pages = (record_count / page_size.to_f).ceil (1..total_pages).each{|page_no| yield paginate(page_no, page_size, record_count)} self end
SQL fragment specifying a JOIN clause without ON or USING.
# File lib/sequel/dataset/sql.rb, line 327 def join_clause_sql(jc) table = jc.table table_alias = jc.table_alias table_alias = nil if table == table_alias tref = table_ref(table) " #{join_type_sql(jc.join_type)} #{table_alias ? as_sql(tref, table_alias) : tref}" end
SQL fragment specifying a JOIN clause with ON.
# File lib/sequel/dataset/sql.rb, line 336 def join_on_clause_sql(jc) "#{join_clause_sql(jc)} ON #{literal(filter_expr(jc.on))}" end
SQL fragment specifying a JOIN clause with USING.
# File lib/sequel/dataset/sql.rb, line 341 def join_using_clause_sql(jc) "#{join_clause_sql(jc)} USING (#{column_list(jc.using)})" end
SQL fragment for NegativeBooleanConstants
# File lib/sequel/dataset/sql.rb, line 346 def negative_boolean_constant_sql(constant) "NOT #{boolean_constant_sql(constant)}" end
SQL fragment for the ordered expression, used in the ORDER BY clause.
# File lib/sequel/dataset/sql.rb, line 352 def ordered_expression_sql(oe) "#{literal(oe.expression)} #{oe.descending ? 'DESC' : 'ASC'}" end
Returns a paginated dataset. The returned dataset is limited to the page size at the correct offset, and extended with the Pagination module. If a record count is not provided, does a count of total number of records for this dataset.
# File lib/sequel/extensions/pagination.rb, line 11 def paginate(page_no, page_size, record_count=nil) raise(Error, "You cannot paginate a dataset that already has a limit") if @opts[:limit] paginated = limit(page_size, (page_no - 1) * page_size) paginated.extend(Pagination) paginated.set_pagination_info(page_no, page_size, record_count || count) end
SQL fragment for a literal string with placeholders
# File lib/sequel/dataset/sql.rb, line 357 def placeholder_literal_string_sql(pls) args = pls.args s = if args.is_a?(Hash) re = /:(#{args.keys.map{|k| Regexp.escape(k.to_s)}.join('|')})\b/ pls.str.gsub(re){literal(args[$1.to_sym])} else i = -1 pls.str.gsub(QUESTION_MARK){literal(args.at(i+=1))} end s = "(#{s})" if pls.parens s end
Pretty prints the records in the dataset as plain-text table.
# File lib/sequel/extensions/pretty_table.rb, line 8 def print(*cols) Sequel::PrettyTable.print(naked.all, cols.empty? ? columns : cols) end
SQL fragment for the qualifed identifier, specifying a table and a column (or schema and table).
# File lib/sequel/dataset/sql.rb, line 372 def qualified_identifier_sql(qcr) [qcr.table, qcr.column].map{|x| [SQL::QualifiedIdentifier, SQL::Identifier, Symbol].any?{|c| x.is_a?(c)} ? literal(x) : quote_identifier(x)}.join('.') end
Translates a query block into a dataset. Query blocks can be useful when expressing complex SELECT statements, e.g.:
dataset = DB[:items].query do select :x, :y, :z filter{|o| (o.x > 1) & (o.y > 2)} order :z.desc end
Which is the same as:
dataset = DB[:items].select(:x, :y, :z).filter{|o| (o.x > 1) & (o.y > 2)}.order(:z.desc)
Note that inside a call to query, you cannot call each, insert, update, or delete (or any method that calls those), or Sequel will raise an error.
# File lib/sequel/extensions/query.rb, line 30 def query(&block) copy = clone({}) copy.extend(QueryBlockCopy) copy.instance_eval(&block) clone(copy.opts) end
Adds quoting to identifiers (columns and tables). If identifiers are not being quoted, returns name as a string. If identifiers are being quoted quote the name with quoted_identifier.
# File lib/sequel/dataset/sql.rb, line 379 def quote_identifier(name) return name if name.is_a?(LiteralString) name = name.value if name.is_a?(SQL::Identifier) name = input_identifier(name) name = quoted_identifier(name) if quote_identifiers? name end
Separates the schema from the table and returns a string with them quoted (if quoting identifiers)
# File lib/sequel/dataset/sql.rb, line 389 def quote_schema_table(table) schema, table = schema_and_table(table) "#{"#{quote_identifier(schema)}." if schema}#{quote_identifier(table)}" end
This method quotes the given name with the SQL standard double quote. should be overridden by subclasses to provide quoting not matching the SQL standard, such as backtick (used by MySQL and SQLite).
# File lib/sequel/dataset/sql.rb, line 397 def quoted_identifier(name) "\"#{name.to_s.gsub('"', '""')}\"" end
Split the schema information from the table
# File lib/sequel/dataset/sql.rb, line 402 def schema_and_table(table_name) sch = db.default_schema if db case table_name when Symbol s, t, a = split_symbol(table_name) [s||sch, t] when SQL::QualifiedIdentifier [table_name.table, table_name.column] when SQL::Identifier [sch, table_name.value] when String [sch, table_name] else raise Error, 'table_name should be a Symbol, SQL::QualifiedIdentifier, SQL::Identifier, or String' end end
The SQL fragment for the given window function’s function and window.
# File lib/sequel/dataset/sql.rb, line 444 def window_function_sql(function, window) "#{literal(function)} OVER #{literal(window)}" end
The SQL fragment for the given window’s options.
# File lib/sequel/dataset/sql.rb, line 425 def window_sql(opts) raise(Error, 'This dataset does not support window functions') unless supports_window_functions? window = literal(opts[:window]) if opts[:window] partition = "PARTITION BY #{expression_list(Array(opts[:partition]))}" if opts[:partition] order = "ORDER BY #{expression_list(Array(opts[:order]))}" if opts[:order] frame = case opts[:frame] when nil nil when :all "ROWS BETWEEN UNBOUNDED PRECEDING AND UNBOUNDED FOLLOWING" when :rows "ROWS UNBOUNDED PRECEDING" else raise Error, "invalid window frame clause, should be :all, :rows, or nil" end "(#{[window, partition, order, frame].compact.join(' ')})" end
Formats in INSERT statement using the stored columns and values.
# File lib/sequel/dataset/sql.rb, line 451 def _insert_sql clause_sql(:insert) end
Formats an UPDATE statement using the stored values.
# File lib/sequel/dataset/sql.rb, line 456 def _update_sql clause_sql(:update) end
Return a from_self dataset if an order or limit is specified, so it works as expected with UNION, EXCEPT, and INTERSECT clauses.
# File lib/sequel/dataset/sql.rb, line 462 def compound_from_self (@opts[:limit] || @opts[:order]) ? from_self : self end
These methods all return booleans, with most describing whether or not the dataset supports a feature.
Method used to check if WITH is supported
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.
# File lib/sequel/dataset/features.rb, line 20 def provides_accurate_rows_matched? true end
Whether this dataset quotes identifiers.
# File lib/sequel/dataset/features.rb, line 13 def quote_identifiers? @quote_identifiers end
Whether the dataset requires SQL standard datetimes (false by default, as most allow strings with ISO 8601 format.
# File lib/sequel/dataset/features.rb, line 26 def requires_sql_standard_datetimes? false end
Whether the dataset supports common table expressions (the WITH clause).
# File lib/sequel/dataset/features.rb, line 31 def supports_cte? select_clause_methods.include?(WITH_SUPPORTED) end
Whether the dataset supports the DISTINCT ON clause, false by default.
# File lib/sequel/dataset/features.rb, line 36 def supports_distinct_on? false end
Whether the dataset supports the INTERSECT and EXCEPT compound operations, true by default.
# File lib/sequel/dataset/features.rb, line 41 def supports_intersect_except? true end
Whether the dataset supports the INTERSECT ALL and EXCEPT ALL compound operations, true by default.
# File lib/sequel/dataset/features.rb, line 46 def supports_intersect_except_all? true end
Whether the dataset supports the IS TRUE syntax.
# File lib/sequel/dataset/features.rb, line 51 def supports_is_true? true end
Whether the dataset supports the JOIN table USING (column1, …) syntax.
# File lib/sequel/dataset/features.rb, line 56 def supports_join_using? true end
Whether modifying joined datasets is supported.
# File lib/sequel/dataset/features.rb, line 61 def supports_modifying_joins? false end
Whether the IN/NOT IN operators support multiple columns when an array of values is given.
# File lib/sequel/dataset/features.rb, line 67 def supports_multiple_column_in? true end
Whether the dataset supports timezones in literal timestamps
# File lib/sequel/dataset/features.rb, line 72 def supports_timestamp_timezones? false end
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.
Action methods defined by Sequel that execute code on the database.
Alias for insert, but not aliased directly so subclasses don’t have to override both methods.
# File lib/sequel/dataset/actions.rb, line 18 def <<(*args) insert(*args) end
Returns the first record matching the conditions. Examples:
ds[:id=>1] => {:id=1}
# File lib/sequel/dataset/actions.rb, line 25 def [](*conditions) raise(Error, ARRAY_ACCESS_ERROR_MSG) if (conditions.length == 1 and conditions.first.is_a?(Integer)) or conditions.length == 0 first(*conditions) end
Update all records matching the conditions with the values specified. Examples:
ds[:id=>1] = {:id=>2} # SQL: UPDATE ... SET id = 2 WHERE id = 1
# File lib/sequel/dataset/actions.rb, line 34 def []=(conditions, values) filter(conditions).update(values) end
Returns an array with all records in the dataset. If a block is given, the array is iterated over after all items have been loaded.
# File lib/sequel/dataset/actions.rb, line 40 def all(&block) a = [] each{|r| a << r} post_load(a) a.each(&block) if block a end
Returns the average value for the given column.
# File lib/sequel/dataset/actions.rb, line 49 def avg(column) aggregate_dataset.get{avg(column)} end
Returns the columns in the result set in order. If the columns are currently cached, returns the cached value. Otherwise, a SELECT query is performed to get a single row. Adapters are expected to fill the columns cache with the column information when a query is performed. If the dataset does not have any rows, this may be an empty array depending on how the adapter is programmed.
If you are looking for all columns for a single table and maybe some information about each column (e.g. type), see Database#schema.
# File lib/sequel/dataset/actions.rb, line 62 def columns return @columns if @columns ds = unfiltered.unordered.clone(:distinct => nil, :limit => 1) ds.each{break} @columns = ds.instance_variable_get(:@columns) @columns || [] end
Remove the cached list of columns and do a SELECT query to find the columns.
# File lib/sequel/dataset/actions.rb, line 72 def columns! @columns = nil columns end
Returns the number of records in the dataset.
# File lib/sequel/dataset/actions.rb, line 78 def count aggregate_dataset.get{COUNT(:*){}.as(count)}.to_i end
Deletes the records in the dataset. The returned value is generally the number of records deleted, but that is adapter dependent. See delete_sql.
# File lib/sequel/dataset/actions.rb, line 84 def delete execute_dui(delete_sql) end
Iterates over the records in the dataset as they are yielded from the database adapter, and returns self.
Note that this method is not safe to use on many adapters if you are running additional queries inside the provided block. If you are running queries inside the block, you use should all instead of each.
# File lib/sequel/dataset/actions.rb, line 94 def each(&block) if @opts[:graph] graph_each(&block) elsif row_proc = @row_proc fetch_rows(select_sql){|r| yield row_proc.call(r)} else fetch_rows(select_sql, &block) end self end
Returns true if no records exist in the dataset, false otherwise
# File lib/sequel/dataset/actions.rb, line 106 def empty? get(1).nil? end
Executes a select query and fetches records, passing each record to the supplied block. The yielded records should be hashes with symbol keys.
# File lib/sequel/dataset/actions.rb, line 112 def fetch_rows(sql, &block) raise NotImplemented, NOTIMPL_MSG 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:
ds.first => {:id=>7} ds.first(2) => [{:id=>6}, {:id=>4}] ds.order(:id).first(2) => [{:id=>1}, {:id=>2}] ds.first(:id=>2) => {:id=>2} ds.first("id = 3") => {:id=>3} ds.first("id = ?", 4) => {:id=>4} ds.first{|o| o.id > 2} => {:id=>5} ds.order(:id).first{|o| o.id > 2} => {:id=>3} ds.first{|o| o.id > 2} => {:id=>5} ds.first("id > ?", 4){|o| o.id < 6} => {:id=>5} ds.order(:id).first(2){|o| o.id < 2} => [{:id=>1}]
# File lib/sequel/dataset/actions.rb, line 135 def first(*args, &block) ds = block ? filter(&block) : self if args.empty? ds.single_record else args = (args.size == 1) ? args.first : args if Integer === args ds.limit(args).all else ds.filter(args).single_record end end end
Return the column value for the first matching record in the dataset. Raises an error if both an argument and block is given.
ds.get(:id) ds.get{|o| o.sum(:id)}
# File lib/sequel/dataset/actions.rb, line 155 def get(column=nil, &block) if column raise(Error, ARG_BLOCK_ERROR_MSG) if block select(column).single_value else select(&block).single_value end 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:
dataset.import([:x, :y], [[1, 2], [3, 4]])
This method also accepts a dataset instead of an array of value arrays:
dataset.import([:x, :y], other_dataset.select(:a___x, :b___y))
The method also accepts a :slice or :commit_every option that specifies the number of records to insert per transaction. This is useful especially when inserting a large number of records, e.g.:
# this will commit every 50 records dataset.import([:x, :y], [[1, 2], [3, 4], ...], :slice => 50)
# File lib/sequel/dataset/actions.rb, line 183 def import(columns, values, opts={}) return @db.transaction{insert(columns, values)} if values.is_a?(Dataset) return if values.empty? raise(Error, IMPORT_ERROR_MSG) if columns.empty? if slice_size = opts[:commit_every] || opts[:slice] offset = 0 loop do @db.transaction(opts){multi_insert_sql(columns, values[offset, slice_size]).each{|st| execute_dui(st)}} offset += slice_size break if offset >= values.length end else statements = multi_insert_sql(columns, values) @db.transaction{statements.each{|st| execute_dui(st)}} end 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. See insert_sql.
# File lib/sequel/dataset/actions.rb, line 205 def insert(*values) execute_insert(insert_sql(*values)) end
Inserts multiple values. If a block is given it is invoked for each item in the given array before inserting it. See multi_insert as a possible faster version that inserts multiple records in one SQL statement.
# File lib/sequel/dataset/actions.rb, line 213 def insert_multiple(array, &block) if block array.each {|i| insert(block[i])} else array.each {|i| insert(i)} end end
Returns the interval between minimum and maximum values for the given column.
# File lib/sequel/dataset/actions.rb, line 223 def interval(column) aggregate_dataset.get{max(column) - min(column)} end
Reverses the order and then runs first. Note that this will not necessarily give you the last record in the dataset, unless you have an unambiguous order. If there is not currently an order for this dataset, raises an Error.
# File lib/sequel/dataset/actions.rb, line 231 def last(*args, &block) raise(Error, 'No order specified') unless @opts[:order] reverse.first(*args, &block) end
Maps column values for each record in the dataset (if a column name is given), or performs the stock mapping functionality of Enumerable. Raises an error if both an argument and block are given. Examples:
ds.map(:id) => [1, 2, 3, ...] ds.map{|r| r[:id] * 2} => [2, 4, 6, ...]
# File lib/sequel/dataset/actions.rb, line 242 def map(column=nil, &block) if column raise(Error, ARG_BLOCK_ERROR_MSG) if block super(){|r| r[column]} else super(&block) end end
Returns the maximum value for the given column.
# File lib/sequel/dataset/actions.rb, line 252 def max(column) aggregate_dataset.get{max(column)} end
Returns the minimum value for the given column.
# File lib/sequel/dataset/actions.rb, line 257 def min(column) aggregate_dataset.get{min(column)} end
This is a front end for import that allows you to submit an array of hashes instead of arrays of columns and values:
dataset.multi_insert([{:x => 1}, {:x => 2}])
Be aware that all hashes should have the same keys if you use this calling method, otherwise some columns could be missed or set to null instead of to default values.
You can also use the :slice or :commit_every option that import accepts.
# File lib/sequel/dataset/actions.rb, line 271 def multi_insert(hashes, opts={}) return if hashes.empty? columns = hashes.first.keys import(columns, hashes.map{|h| columns.map{|c| h[c]}}, opts) end
Returns a Range object made from the minimum and maximum values for the given column.
# File lib/sequel/dataset/actions.rb, line 279 def range(column) if r = aggregate_dataset.select{[min(column).as(v1), max(column).as(v2)]}.first (r[:v1]..r[:v2]) end 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.
# File lib/sequel/dataset/actions.rb, line 287 def select_hash(key_column, value_column) select(key_column, value_column).to_hash(hash_key_symbol(key_column), hash_key_symbol(value_column)) 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.
# File lib/sequel/dataset/actions.rb, line 295 def select_map(column=nil, &block) ds = naked.ungraphed ds = if column raise(Error, ARG_BLOCK_ERROR_MSG) if block ds.select(column) else ds.select(&block) end ds.map{|r| r.values.first} end
The same as select_map, but in addition orders the array by the column.
# File lib/sequel/dataset/actions.rb, line 307 def select_order_map(column=nil, &block) ds = naked.ungraphed ds = if column raise(Error, ARG_BLOCK_ERROR_MSG) if block ds.select(column).order(unaliased_identifier(column)) else ds.select(&block).order(&block) end ds.map{|r| r.values.first} end
Alias for update, but not aliased directly so subclasses don’t have to override both methods.
# File lib/sequel/dataset/actions.rb, line 320 def set(*args) update(*args) end
Returns the first record in the dataset.
# File lib/sequel/dataset/actions.rb, line 325 def single_record clone(:limit=>1).each{|r| return r} nil end
Returns the first value of the first record in the dataset. Returns nil if dataset is empty.
# File lib/sequel/dataset/actions.rb, line 332 def single_value if r = naked.ungraphed.single_record r.values.first end end
Returns the sum for the given column.
# File lib/sequel/dataset/actions.rb, line 339 def sum(column) aggregate_dataset.get{sum(column)} 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.
# File lib/sequel/dataset/actions.rb, line 351 def to_csv(include_column_titles = true) n = naked cols = n.columns csv = '' csv << "#{cols.join(COMMA_SEPARATOR)}\r\n" if include_column_titles n.each{|r| csv << "#{cols.collect{|c| r[c]}.join(COMMA_SEPARATOR)}\r\n"} csv end
Returns a hash with one column used as key and another used as value. If rows have duplicate values for the key column, the latter row(s) will overwrite the value of the previous row(s). If the value_column is not given or nil, uses the entire hash as the value.
# File lib/sequel/dataset/actions.rb, line 364 def to_hash(key_column, value_column = nil) inject({}) do |m, r| m[r[key_column]] = value_column ? r[value_column] : r m end end
These methods all return modified copies of the receiver.
The dataset options that require the removal of cached columns if changed.
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.
All methods that return modified datasets with a joined table added.
Which options don’t affect the SQL generation. Used by simple_select_all? to determine if this is a simple SELECT * FROM table.
Methods that return modified datasets
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.
Adds an further filter to an existing filter using AND. If no filter exists an error is raised. This method is identical to filter except it expects an existing filter.
ds.filter(:a).and(:b) # SQL: WHERE a AND b
# File lib/sequel/dataset/query.rb, line 43 def and(*cond, &block) raise(InvalidOperation, "No existing filter found.") unless @opts[:having] || @opts[:where] filter(*cond, &block) end
Returns a new clone of the dataset with with the given options merged. If the options changed include options in COLUMN_CHANGE_OPTS, the cached columns are deleted.
# File lib/sequel/dataset/query.rb, line 51 def clone(opts = {}) c = super() c.opts = @opts.merge(opts) c.instance_variable_set(:@columns, nil) if opts.keys.any?{|o| COLUMN_CHANGE_OPTS.include?(o)} c 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.
dataset.distinct # SQL: SELECT DISTINCT * FROM items dataset.order(:id).distinct(:id) # SQL: SELECT DISTINCT ON (id) * FROM items ORDER BY id
# File lib/sequel/dataset/query.rb, line 67 def distinct(*args) raise(InvalidOperation, "DISTINCT ON not supported") if !args.empty? && !supports_distinct_on? clone(:distinct => args) 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:
: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.except(DB).sql #=> "SELECT * FROM items EXCEPT SELECT * FROM other_items"
# File lib/sequel/dataset/query.rb, line 82 def except(dataset, opts={}) opts = {:all=>opts} unless opts.is_a?(Hash) raise(InvalidOperation, "EXCEPT not supported") unless supports_intersect_except? raise(InvalidOperation, "EXCEPT ALL not supported") if opts[:all] && !supports_intersect_except_all? compound_clone(:except, dataset, opts) end
Performs the inverse of Dataset#filter.
dataset.exclude(:category => 'software').sql #=> "SELECT * FROM items WHERE (category != 'software')"
# File lib/sequel/dataset/query.rb, line 93 def exclude(*cond, &block) clause = (@opts[:having] ? :having : :where) cond = cond.first if cond.size == 1 cond = filter_expr(cond, &block) cond = SQL::BooleanExpression.invert(cond) cond = SQL::BooleanExpression.new(:AND, @opts[clause], cond) if @opts[clause] clone(clause => cond) 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.
String - taken literally
Symbol - taken as a boolean column argument (e.g. WHERE active)
Sequel::SQL::BooleanExpression - an existing condition expression, probably created using the Sequel expression filter DSL.
filter also takes a block, which should return one of the above argument types, and is treated the same way. This block yields a virtual row object, which is easy to use to create identifiers and functions. For more details on the virtual row support, see the “Virtual Rows” guide
If both a block and regular argument are provided, they get ANDed together.
Examples:
dataset.filter(:id => 3).sql #=> "SELECT * FROM items WHERE (id = 3)" dataset.filter('price < ?', 100).sql #=> "SELECT * FROM items WHERE price < 100" dataset.filter([[:id, (1,2,3)], [:id, 0..10]]).sql #=> "SELECT * FROM items WHERE ((id IN (1, 2, 3)) AND ((id >= 0) AND (id <= 10)))" dataset.filter('price < 100').sql #=> "SELECT * FROM items WHERE price < 100" dataset.filter(:active).sql #=> "SELECT * FROM items WHERE :active dataset.filter{|o| o.price < 100}.sql #=> "SELECT * FROM items WHERE (price < 100)"
Multiple filter calls can be chained for scoping:
software = dataset.filter(:category => 'software') software.filter{|o| o.price < 100}.sql #=> "SELECT * FROM items WHERE ((category = 'software') AND (price < 100))"
See the the “Dataset Filtering” guide for more examples and details.
# File lib/sequel/dataset/query.rb, line 150 def filter(*cond, &block) _filter(@opts[:having] ? :having : :where, *cond, &block) end
Returns a cloned dataset with a :update lock style.
# File lib/sequel/dataset/query.rb, line 155 def for_update lock_style(:update) end
Returns a copy of the dataset with the source changed.
dataset.from # SQL: SELECT * dataset.from(:blah) # SQL: SELECT * FROM blah dataset.from(:blah, :foo) # SQL: SELECT * FROM blah, foo
# File lib/sequel/dataset/query.rb, line 164 def from(*source) table_alias_num = 0 sources = [] source.each do |s| case s when Hash s.each{|k,v| sources << SQL::AliasedExpression.new(k,v)} when Dataset sources << SQL::AliasedExpression.new(s, dataset_alias(table_alias_num+=1)) when Symbol sch, table, aliaz = split_symbol(s) if aliaz s = sch ? SQL::QualifiedIdentifier.new(sch.to_sym, table.to_sym) : SQL::Identifier.new(table.to_sym) sources << SQL::AliasedExpression.new(s, aliaz.to_sym) else sources << s end else sources << s end end o = {:from=>sources.empty? ? nil : sources} o[:num_dataset_sources] = table_alias_num if table_alias_num > 0 clone(o) end
Returns a dataset selecting from the current dataset. Supplying the :alias option controls the name of the result.
ds = DB[:items].order(:name).select(:id, :name) ds.sql #=> "SELECT id,name FROM items ORDER BY name" ds.from_self.sql #=> "SELECT * FROM (SELECT id, name FROM items ORDER BY name) AS t1" ds.from_self(:alias=>:foo).sql #=> "SELECT * FROM (SELECT id, name FROM items ORDER BY name) AS foo"
# File lib/sequel/dataset/query.rb, line 197 def from_self(opts={}) fs = {} @opts.keys.each{|k| fs[k] = nil unless NON_SQL_OPTIONS.include?(k)} clone(fs).from(opts[:alias] ? as(opts[:alias]) : self) end
Pattern match any of the columns to any of the terms. The terms can be strings (which use LIKE) or regular expressions (which are only supported in some databases). See Sequel::SQL::StringExpression.like. Note that the total number of pattern matches will be cols.length * terms.length, which could cause performance issues.
dataset.grep(:a, '%test%') # SQL: SELECT * FROM items WHERE a LIKE '%test%' dataset.grep([:a, :b], %w'%test% foo') # SQL: SELECT * FROM items WHERE a LIKE '%test%' OR a LIKE 'foo' OR b LIKE '%test%' OR b LIKE 'foo'
# File lib/sequel/dataset/query.rb, line 211 def grep(cols, terms) filter(SQL::BooleanExpression.new(:OR, *Array(cols).collect{|c| SQL::StringExpression.like(c, *terms)})) end
Returns a copy of the dataset with the results grouped by the value of the given columns.
dataset.group(:id) # SELECT * FROM items GROUP BY id dataset.group(:id, :name) # SELECT * FROM items GROUP BY id, name
# File lib/sequel/dataset/query.rb, line 220 def group(*columns) clone(:group => (columns.compact.empty? ? nil : columns)) end
Returns a dataset grouped by the given column with count by group, order by the count of records. Column aliases may be supplied, and will be included in the select clause.
Examples:
ds.group_and_count(:name).all => [{:name=>'a', :count=>1}, ...] ds.group_and_count(:first_name, :last_name).all => [{:first_name=>'a', :last_name=>'b', :count=>1}, ...] ds.group_and_count(:first_name___name).all => [{:name=>'a', :count=>1}, ...]
# File lib/sequel/dataset/query.rb, line 238 def group_and_count(*columns) group(*columns.map{|c| unaliased_identifier(c)}).select(*(columns + [COUNT_OF_ALL_AS_COUNT])) end
Alias of group
# File lib/sequel/dataset/query.rb, line 225 def group_by(*columns) group(*columns) end
Returns a copy of the dataset with the HAVING conditions changed. See filter for argument types.
dataset.group(:sum).having(:sum=>10) # SQL: SELECT * FROM items GROUP BY sum HAVING sum = 10
# File lib/sequel/dataset/query.rb, line 245 def having(*cond, &block) _filter(:having, *cond, &block) 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:
: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.intersect(DB).sql #=> "SELECT * FROM items INTERSECT SELECT * FROM other_items"
# File lib/sequel/dataset/query.rb, line 259 def intersect(dataset, opts={}) opts = {:all=>opts} unless opts.is_a?(Hash) raise(InvalidOperation, "INTERSECT not supported") unless supports_intersect_except? raise(InvalidOperation, "INTERSECT ALL not supported") if opts[:all] && !supports_intersect_except_all? compound_clone(:intersect, dataset, opts) end
Inverts the current filter
dataset.filter(:category => 'software').invert.sql #=> "SELECT * FROM items WHERE (category != 'software')"
# File lib/sequel/dataset/query.rb, line 270 def invert having, where = @opts[:having], @opts[:where] raise(Error, "No current filter") unless having || where o = {} o[:having] = SQL::BooleanExpression.invert(having) if having o[:where] = SQL::BooleanExpression.invert(where) if where clone(o) end
Alias of inner_join
# File lib/sequel/dataset/query.rb, line 280 def join(*args, &block) inner_join(*args, &block) end
Returns a joined dataset. Uses the following arguments:
type - The type of join to do (e.g. :inner)
table - Depends on type:
expr - specifies conditions, depends on type:
Hash, Array with all two pairs - Assumes key (1st arg) is column of joined table (unless already qualified), and value (2nd arg) is column of the last joined or primary table (or the :implicit_qualifier option). To specify multiple conditions on a single joined table column, you must use an array. Uses a JOIN with an ON clause.
Array - If all members of the array are symbols, considers them as columns and uses a JOIN with a USING clause. Most databases will remove duplicate columns from the result set if this is used.
nil - If a block is not given, doesn’t use ON or USING, so the JOIN should be a NATURAL or CROSS join. If a block is given, uses a ON clause based on the block, see below.
Everything else - pretty much the same as a using the argument in a call to filter, so strings are considered literal, symbols specify boolean columns, and blockless filter expressions can be used. Uses a JOIN with an ON clause.
options - a hash of options, with any of the following keys:
:table_alias - the name of the table’s alias when joining, necessary for joining to the same table more than once. No alias is used by default.
:implicit_qualifier - The name to use for qualifying implicit conditions. By default, the last joined or primary table is used.
block - The block argument should only be given if a JOIN with an ON clause is used, in which case it yields the table alias/name for the table currently being joined, the table alias/name for the last joined (or first table), and an array of previous SQL::JoinClause.
# File lib/sequel/dataset/query.rb, line 314 def join_table(type, table, expr=nil, options={}, &block) using_join = expr.is_a?(Array) && !expr.empty? && expr.all?{|x| x.is_a?(Symbol)} if using_join && !supports_join_using? h = {} expr.each{|s| h[s] = s} return join_table(type, table, h, options) end case options when Hash table_alias = options[:table_alias] last_alias = options[:implicit_qualifier] when Symbol, String, SQL::Identifier table_alias = options last_alias = nil else raise Error, "invalid options format for join_table: #{options.inspect}" end if Dataset === table if table_alias.nil? table_alias_num = (@opts[:num_dataset_sources] || 0) + 1 table_alias = dataset_alias(table_alias_num) end table_name = table_alias else table = table.table_name if table.respond_to?(:table_name) table_name = table_alias || table end join = if expr.nil? and !block_given? SQL::JoinClause.new(type, table, table_alias) elsif using_join raise(Sequel::Error, "can't use a block if providing an array of symbols as expr") if block_given? SQL::JoinUsingClause.new(expr, type, table, table_alias) else last_alias ||= @opts[:last_joined_table] || first_source_alias if Sequel.condition_specifier?(expr) expr = expr.collect do |k, v| k = qualified_column_name(k, table_name) if k.is_a?(Symbol) v = qualified_column_name(v, last_alias) if v.is_a?(Symbol) [k,v] end end if block_given? expr2 = yield(table_name, last_alias, @opts[:join] || []) expr = expr ? SQL::BooleanExpression.new(:AND, expr, expr2) : expr2 end SQL::JoinOnClause.new(expr, type, table, table_alias) end opts = {:join => (@opts[:join] || []) + [join], :last_joined_table => table_name} opts[:num_dataset_sources] = table_alias_num if table_alias_num clone(opts) 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.
dataset.limit(10) # SQL: SELECT * FROM items LIMIT 10 dataset.limit(10, 20) # SQL: SELECT * FROM items LIMIT 10 OFFSET 20
# File lib/sequel/dataset/query.rb, line 383 def limit(l, o = nil) return from_self.limit(l, o) if @opts[:sql] if Range === l o = l.first l = l.last - l.first + (l.exclude_end? ? 0 : 1) end l = l.to_i if l.is_a?(String) && !l.is_a?(LiteralString) if l.is_a?(Integer) raise(Error, 'Limits must be greater than or equal to 1') unless l >= 1 end opts = {:limit => l} if o o = o.to_i if o.is_a?(String) && !o.is_a?(LiteralString) if o.is_a?(Integer) raise(Error, 'Offsets must be greater than or equal to 0') unless o >= 0 end opts[:offset] = o end clone(opts) 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.
# File lib/sequel/dataset/query.rb, line 409 def lock_style(style) clone(:lock => style) end
Returns a naked dataset clone - i.e. a dataset that returns records as hashes instead of calling the row proc.
# File lib/sequel/dataset/query.rb, line 415 def naked ds = clone ds.row_proc = nil ds end
Adds an alternate filter to an existing filter using OR. If no filter exists an error is raised.
dataset.filter(:a).or(:b) # SQL: SELECT * FROM items WHERE a OR b
# File lib/sequel/dataset/query.rb, line 425 def or(*cond, &block) clause = (@opts[:having] ? :having : :where) raise(InvalidOperation, "No existing filter found.") unless @opts[clause] cond = cond.first if cond.size == 1 clone(clause => SQL::BooleanExpression.new(:OR, @opts[clause], filter_expr(cond, &block))) end
Returns a copy of the dataset with the order changed. If a nil is given the returned dataset has no order. This can accept multiple arguments of varying kinds, and even SQL functions. If a block is given, it is treated as a virtual row block, similar to filter.
ds.order(:name).sql #=> 'SELECT * FROM items ORDER BY name' ds.order(:a, :b).sql #=> 'SELECT * FROM items ORDER BY a, b' ds.order('a + b'.lit).sql #=> 'SELECT * FROM items ORDER BY a + b' ds.order(:a + :b).sql #=> 'SELECT * FROM items ORDER BY (a + b)' ds.order(:name.desc).sql #=> 'SELECT * FROM items ORDER BY name DESC' ds.order(:name.asc).sql #=> 'SELECT * FROM items ORDER BY name ASC' ds.order{|o| o.sum(:name)}.sql #=> 'SELECT * FROM items ORDER BY sum(name)' ds.order(nil).sql #=> 'SELECT * FROM items'
# File lib/sequel/dataset/query.rb, line 445 def order(*columns, &block) columns += Array(Sequel.virtual_row(&block)) if block clone(:order => (columns.compact.empty?) ? nil : columns) end
Alias of order_more, for naming consistency with order_prepend.
# File lib/sequel/dataset/query.rb, line 451 def order_append(*columns, &block) order_more(*columns, &block) end
Alias of order
# File lib/sequel/dataset/query.rb, line 456 def order_by(*columns, &block) order(*columns, &block) end
Returns a copy of the dataset with the order columns added to the end of the existing order.
ds.order(:a).order(:b).sql #=> 'SELECT * FROM items ORDER BY b' ds.order(:a).order_more(:b).sql #=> 'SELECT * FROM items ORDER BY a, b'
# File lib/sequel/dataset/query.rb, line 465 def order_more(*columns, &block) columns = @opts[:order] + columns if @opts[:order] order(*columns, &block) end
Returns a copy of the dataset with the order columns added to the beginning of the existing order.
ds.order(:a).order(:b).sql #=> 'SELECT * FROM items ORDER BY b' ds.order(:a).order_prepend(:b).sql #=> 'SELECT * FROM items ORDER BY b, a'
# File lib/sequel/dataset/query.rb, line 475 def order_prepend(*columns, &block) ds = order(*columns, &block) @opts[:order] ? ds.order_more(*@opts[:order]) : ds end
Qualify to the given table, or first source if not table is given.
# File lib/sequel/dataset/query.rb, line 481 def qualify(table=first_source) qualify_to(table) 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.
# File lib/sequel/dataset/query.rb, line 489 def qualify_to(table) o = @opts return clone if o[:sql] h = {} (o.keys & QUALIFY_KEYS).each do |k| h[k] = qualified_expression(o[k], table) end h[:select] = [SQL::ColumnAll.new(table)] if !o[:select] || o[:select].empty? clone(h) 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.
# File lib/sequel/dataset/query.rb, line 505 def qualify_to_first_source qualify_to(first_source) end
Returns a copy of the dataset with the order reversed. If no order is given, the existing order is inverted.
# File lib/sequel/dataset/query.rb, line 511 def reverse(*order) order(*invert_order(order.empty? ? @opts[:order] : order)) end
Alias of reverse
# File lib/sequel/dataset/query.rb, line 516 def reverse_order(*order) reverse(*order) 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.
dataset.select(:a) # SELECT a FROM items dataset.select(:a, :b) # SELECT a, b FROM items dataset.select{|o| [o.a, o.sum(:b)]} # SELECT a, sum(b) FROM items
# File lib/sequel/dataset/query.rb, line 527 def select(*columns, &block) columns += Array(Sequel.virtual_row(&block)) if block m = [] columns.map do |i| i.is_a?(Hash) ? m.concat(i.map{|k, v| SQL::AliasedExpression.new(k,v)}) : m << i end clone(:select => m) end
Returns a copy of the dataset selecting the wildcard.
dataset.select(:a).select_all # SELECT * FROM items
# File lib/sequel/dataset/query.rb, line 539 def select_all clone(:select => nil) 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 *.
dataset.select(:a).select(:b) # SELECT b FROM items dataset.select(:a).select_append(:b) # SELECT a, b FROM items dataset.select_append(:b) # SELECT *, b FROM items
# File lib/sequel/dataset/query.rb, line 550 def select_append(*columns, &block) cur_sel = @opts[:select] cur_sel = [WILDCARD] if !cur_sel || cur_sel.empty? select(*(cur_sel + columns), &block) 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.
dataset.select(:a).select(:b) # SELECT b FROM items dataset.select(:a).select_more(:b) # SELECT a, b FROM items dataset.select_more(:b) # SELECT b FROM items
# File lib/sequel/dataset/query.rb, line 563 def select_more(*columns, &block) columns = @opts[:select] + columns if @opts[:select] select(*columns, &block) 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).
# File lib/sequel/dataset/query.rb, line 571 def server(servr) clone(:server=>servr) end
Set the default values for insert and update statements. The values hash passed to insert or update are merged into this hash.
# File lib/sequel/dataset/query.rb, line 577 def set_defaults(hash) clone(:defaults=>(@opts[:defaults]||{}).merge(hash)) 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.
# File lib/sequel/dataset/query.rb, line 583 def set_overrides(hash) clone(:overrides=>hash.merge(@opts[:overrides]||{})) end
Returns a copy of the dataset with no filters (HAVING or WHERE clause) applied.
dataset.group(:a).having(:a=>1).where(:b).unfiltered # SELECT * FROM items GROUP BY a
# File lib/sequel/dataset/query.rb, line 590 def unfiltered clone(:where => nil, :having => nil) end
Returns a copy of the dataset with no grouping (GROUP or HAVING clause) applied.
dataset.group(:a).having(:a=>1).where(:b).ungrouped # SELECT * FROM items WHERE b
# File lib/sequel/dataset/query.rb, line 597 def ungrouped clone(:group => nil, :having => nil) 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:
: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.union(DB).sql #=> "SELECT * FROM items UNION SELECT * FROM other_items"
# File lib/sequel/dataset/query.rb, line 610 def union(dataset, opts={}) opts = {:all=>opts} unless opts.is_a?(Hash) compound_clone(:union, dataset, opts) end
Returns a copy of the dataset with no limit or offset.
dataset.limit(10, 20).unlimited # SELECT * FROM items
# File lib/sequel/dataset/query.rb, line 618 def unlimited clone(:limit=>nil, :offset=>nil) end
Returns a copy of the dataset with no order.
dataset.order(:a).unordered # SELECT * FROM items
# File lib/sequel/dataset/query.rb, line 625 def unordered order(nil) end
Add a condition to the WHERE clause. See filter for argument types.
dataset.group(:a).having(:a).filter(:b) # SELECT * FROM items GROUP BY a HAVING a AND b dataset.group(:a).having(:a).where(:b) # SELECT * FROM items WHERE b GROUP BY a HAVING a
# File lib/sequel/dataset/query.rb, line 633 def where(*cond, &block) _filter(:where, *cond, &block) end
Add a simple common table expression (CTE) with the given name and a dataset that defines the CTE. A common table expression acts as an inline view for the query. Options:
:args - Specify the arguments/columns for the CTE, should be an array of symbols.
:recursive - Specify that this is a recursive CTE
# File lib/sequel/dataset/query.rb, line 642 def with(name, dataset, opts={}) raise(Error, 'This datatset does not support common table expressions') unless supports_cte? clone(:with=>(@opts[:with]||[]) + [opts.merge(:name=>name, :dataset=>dataset)]) 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.
# File lib/sequel/dataset/query.rb, line 652 def with_recursive(name, nonrecursive, recursive, opts={}) raise(Error, 'This datatset does not support common table expressions') unless supports_cte? clone(:with=>(@opts[:with]||[]) + [opts.merge(:recursive=>true, :name=>name, :dataset=>nonrecursive.union(recursive, {:all=>opts[:union_all] != false, :from_self=>false}))]) 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.
dataset.with_sql('SELECT * FROM foo') # SELECT * FROM foo
# File lib/sequel/dataset/query.rb, line 661 def with_sql(sql, *args) sql = SQL::PlaceholderLiteralString.new(sql, args) unless args.empty? clone(:sql=>sql) end
Return true if the dataset has a non-nil value for any key in opts.
# File lib/sequel/dataset/query.rb, line 669 def options_overlap(opts) !(@opts.collect{|k,v| k unless v.nil?}.compact & opts).empty? end
Whether this dataset is a simple SELECT * FROM table.
# File lib/sequel/dataset/query.rb, line 674 def simple_select_all? o = @opts.reject{|k,v| v.nil? || NON_SQL_OPTIONS.include?(k)} o.length == 1 && (f = o[:from]) && f.length == 1 && f.first.is_a?(Symbol) end
These methods don’t fit cleanly into another section.
Constructs a new Dataset instance with an associated database and options. Datasets are usually constructed by invoking the Database#[] method:
DB[:posts]
Sequel::Dataset is an abstract class that is not useful by itself. Each database adaptor should provide a subclass of Sequel::Dataset, and have the Database#dataset method return an instance of that class.
# File lib/sequel/dataset/misc.rb, line 27 def initialize(db, opts = nil) @db = db @quote_identifiers = db.quote_identifiers? if db.respond_to?(:quote_identifiers?) @identifier_input_method = db.identifier_input_method if db.respond_to?(:identifier_input_method) @identifier_output_method = db.identifier_output_method if db.respond_to?(:identifier_output_method) @opts = opts || {} @row_proc = nil 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.
# File lib/sequel/dataset/misc.rb, line 39 def as(aliaz) ::Sequel::SQL::AliasedExpression.new(self, aliaz) 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')}
# File lib/sequel/dataset/misc.rb, line 48 def each_server db.servers.each{|s| yield server(s)} end
Alias of first_source_alias
# File lib/sequel/dataset/misc.rb, line 53 def first_source first_source_alias 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.
# File lib/sequel/dataset/misc.rb, line 59 def first_source_alias source = @opts[:from] if source.nil? || source.empty? raise Error, 'No source specified for query' end case s = source.first when SQL::AliasedExpression s.aliaz when Symbol sch, table, aliaz = split_symbol(s) aliaz ? aliaz.to_sym : s else s end 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
# File lib/sequel/dataset/misc.rb, line 78 def first_source_table source = @opts[:from] if source.nil? || source.empty? raise Error, 'No source specified for query' end case s = source.first when SQL::AliasedExpression s.expression when Symbol sch, table, aliaz = split_symbol(s) aliaz ? (sch ? SQL::QualifiedIdentifier.new(sch, table) : table.to_sym) : s else s end end
Returns a string representation of the dataset including the class name and the corresponding SQL select statement.
# File lib/sequel/dataset/misc.rb, line 96 def inspect "#<#{self.class}: #{sql.inspect}>" 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.
# File lib/sequel/dataset/misc.rb, line 106 def unused_table_alias(table_alias) table_alias = alias_symbol(table_alias) used_aliases = [] used_aliases += opts[:from].map{|t| alias_symbol(t)} if opts[:from] used_aliases += opts[:join].map{|j| j.table_alias ? alias_alias_symbol(j.table_alias) : alias_symbol(j.table)} if opts[:join] if used_aliases.include?(table_alias) i = 0 loop do ta = :"#{table_alias}_#{i}" return ta unless used_aliases.include?(ta) i += 1 end else table_alias end end
These methods modify the receiving dataset and should be used with care.
All methods that should have a ! method added that modifies the receiver.
Set the method to call on identifiers going into the database for this dataset
Setup mutation (e.g. filter!) methods. These operate the same as the non-! methods, but replace the options of the current dataset with the options of the resulting dataset.
# File lib/sequel/dataset/mutation.rb, line 14 def self.def_mutation_method(*meths) meths.each do |meth| class_eval("def #{meth}!(*args, &block); mutation_method(:#{meth}, *args, &block) end", __FILE__, __LINE__) end end
Add a mutation method to this dataset instance.
# File lib/sequel/dataset/mutation.rb, line 39 def def_mutation_method(*meths) meths.each do |meth| instance_eval("def #{meth}!(*args, &block); mutation_method(:#{meth}, *args, &block) end", __FILE__, __LINE__) end end
These are methods you can call to see what SQL will be generated by the dataset.
Formats a DELETE statement using the given options and dataset options.
dataset.filter{|o| o.price >= 100}.delete_sql #=> "DELETE FROM items WHERE (price >= 100)"
# File lib/sequel/dataset/sql.rb, line 12 def delete_sql return static_sql(opts[:sql]) if opts[:sql] check_modification_allowed! clause_sql(:delete) end
Returns an EXISTS clause for the dataset as a LiteralString.
DB.select(1).where(DB[:items].exists).sql #=> "SELECT 1 WHERE (EXISTS (SELECT * FROM items))"
# File lib/sequel/dataset/sql.rb, line 22 def exists LiteralString.new("EXISTS (#{select_sql})") end
Formats an INSERT statement using the given values. The API is a little complex, and best explained by example:
# Default values DB[:items].insert_sql #=> 'INSERT INTO items DEFAULT VALUES' DB[:items].insert_sql({}) #=> 'INSERT INTO items DEFAULT VALUES' # Values without columns DB[:items].insert_sql(1,2,3) #=> 'INSERT INTO items VALUES (1, 2, 3)' DB[:items].insert_sql([1,2,3]) #=> 'INSERT INTO items VALUES (1, 2, 3)' # Values with columns DB[:items].insert_sql([:a, :b], [1,2]) #=> 'INSERT INTO items (a, b) VALUES (1, 2)' DB[:items].insert_sql(:a => 1, :b => 2) #=> 'INSERT INTO items (a, b) VALUES (1, 2)' # Using a subselect DB[:items].insert_sql(DB[:old_items]) #=> 'INSERT INTO items SELECT * FROM old_items # Using a subselect with columns DB[:items].insert_sql([:a, :b], DB[:old_items]) #=> 'INSERT INTO items (a, b) SELECT * FROM old_items
# File lib/sequel/dataset/sql.rb, line 42 def insert_sql(*values) return static_sql(@opts[:sql]) if @opts[:sql] check_modification_allowed! columns = [] case values.size when 0 return insert_sql({}) when 1 case vals = values.at(0) when Hash vals = @opts[:defaults].merge(vals) if @opts[:defaults] vals = vals.merge(@opts[:overrides]) if @opts[:overrides] values = [] vals.each do |k,v| columns << k values << v end when Dataset, Array, LiteralString values = vals else if vals.respond_to?(:values) && (v = vals.values).is_a?(Hash) return insert_sql(v) end end when 2 if (v0 = values.at(0)).is_a?(Array) && ((v1 = values.at(1)).is_a?(Array) || v1.is_a?(Dataset) || v1.is_a?(LiteralString)) columns, values = v0, v1 raise(Error, "Different number of values and columns given to insert_sql") if values.is_a?(Array) and columns.length != values.length end end columns = columns.map{|k| literal(String === k ? k.to_sym : k)} clone(:columns=>columns, :values=>values)._insert_sql end
Returns a literal representation of a value to be used as part of an SQL expression.
dataset.literal("abc'def\\") #=> "'abc''def\\\\'" dataset.literal(:items__id) #=> "items.id" dataset.literal([1, 2, 3]) => "(1, 2, 3)" dataset.literal(DB[:items]) => "(SELECT * FROM items)" dataset.literal(:x + 1 > :y) => "((x + 1) > y)"
If an unsupported object is given, an exception is raised.
# File lib/sequel/dataset/sql.rb, line 90 def literal(v) case v when String return v if v.is_a?(LiteralString) v.is_a?(SQL::Blob) ? literal_blob(v) : literal_string(v) when Symbol literal_symbol(v) when Integer literal_integer(v) when Hash literal_hash(v) when SQL::Expression literal_expression(v) when Float literal_float(v) when BigDecimal literal_big_decimal(v) when NilClass literal_nil when TrueClass literal_true when FalseClass literal_false when Array literal_array(v) when Time literal_time(v) when DateTime literal_datetime(v) when Date literal_date(v) when Dataset literal_dataset(v) else literal_other(v) end end
Returns an array of insert statements for inserting multiple records. This method is used by multi_insert to format insert statements and expects a keys array and and an array of value arrays.
This method should be overridden by descendants if the support inserting multiple records in a single SQL statement.
# File lib/sequel/dataset/sql.rb, line 134 def multi_insert_sql(columns, values) values.map{|r| insert_sql(columns, r)} end
Formats a SELECT statement
dataset.select_sql # => "SELECT * FROM items"
# File lib/sequel/dataset/sql.rb, line 141 def select_sql return static_sql(@opts[:sql]) if @opts[:sql] clause_sql(:select) end
Same as select_sql, not aliased directly to make subclassing simpler.
# File lib/sequel/dataset/sql.rb, line 147 def sql select_sql end
SQL query to truncate the table
# File lib/sequel/dataset/sql.rb, line 152 def truncate_sql if opts[:sql] static_sql(opts[:sql]) else check_modification_allowed! raise(InvalidOperation, "Can't truncate filtered datasets") if opts[:where] _truncate_sql(source_list(opts[:from])) end end
Formats an UPDATE statement using the given values.
dataset.update_sql(:price => 100, :category => 'software') #=> "UPDATE items SET price = 100, category = 'software'"
Raises an error if the dataset is grouped or includes more than one table.
# File lib/sequel/dataset/sql.rb, line 169 def update_sql(values = {}) return static_sql(opts[:sql]) if opts[:sql] check_modification_allowed! clone(:values=>values)._update_sql end
Generated with the Darkfish Rdoc Generator 2.