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.
COLUMN_CHANGE_OPTS | = | [:select, :sql, :from, :join].freeze | The dataset options that require the removal of cached columns if changed. | |
MUTATION_METHODS | = | %w'add_graph_aliases and distinct except exclude filter from from_self full_outer_join graph group group_and_count group_by having inner_join intersect invert join join_table left_outer_join limit naked or order order_by order_more paginate qualify query reverse reverse_order right_outer_join select select_all 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} | All methods that should have a ! method added that modifies the receiver. | |
NON_SQL_OPTIONS | = | [:server, :defaults, :overrides] | Which options don‘t affect the SQL generation. Used by simple_select_all? to determine if this is a simple SELECT * FROM table. | |
NOTIMPL_MSG | = | "This method must be overridden in Sequel adapters".freeze | ||
WITH_SUPPORTED | = | :select_with_sql | ||
COMMA_SEPARATOR | = | ', '.freeze | ||
COUNT_OF_ALL_AS_COUNT | = | SQL::Function.new(:count, LiteralString.new('*'.freeze)).as(:count) | ||
ARRAY_ACCESS_ERROR_MSG | = | 'You cannot call Dataset#[] with an integer or with no arguments.'.freeze | ||
MAP_ERROR_MSG | = | 'Using Dataset#map with an argument and a block is not allowed'.freeze | ||
GET_ERROR_MSG | = | 'must provide argument or block to Dataset#get, not both'.freeze | ||
IMPORT_ERROR_MSG | = | 'Using Sequel::Dataset#import an empty column array is not allowed'.freeze | ||
PREPARED_ARG_PLACEHOLDER | = | LiteralString.new('?').freeze | ||
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. | |
AND_SEPARATOR | = | " AND ".freeze | ||
BOOL_FALSE | = | "'f'".freeze | ||
BOOL_TRUE | = | "'t'".freeze | ||
COLUMN_REF_RE1 | = | /\A([\w ]+)__([\w ]+)___([\w ]+)\z/.freeze | ||
COLUMN_REF_RE2 | = | /\A([\w ]+)___([\w ]+)\z/.freeze | ||
COLUMN_REF_RE3 | = | /\A([\w ]+)__([\w ]+)\z/.freeze | ||
COUNT_FROM_SELF_OPTS | = | [:distinct, :group, :sql, :limit, :compounds] | ||
DATASET_ALIAS_BASE_NAME | = | 't'.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') | ||
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 | = | '*'.freeze | ||
SQL_WITH | = | "WITH ".freeze | ||
FROM_SELF_KEEP_OPTS | = | [:graph, :eager_graph, :graph_aliases] |
inner_join | -> | join |
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. |
db | [RW] | The database that corresponds to this dataset |
identifier_input_method | [RW] | Set the method to call on identifiers going into the database for this dataset |
identifier_output_method | [RW] | Set the method to call on identifiers coming the database for this dataset |
opts | [RW] | The hash of options for this dataset, keys are symbols. |
quote_identifiers | [W] | Whether to quote identifiers for this dataset |
row_proc | [RW] | The row_proc for this database, should be a Proc that takes a single hash argument and returns the object you want each to return. |
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.rb, line 91 91: def self.def_mutation_method(*meths) 92: meths.each do |meth| 93: class_eval("def #{meth}!(*args, &block); mutation_method(:#{meth}, *args, &block) end", __FILE__, __LINE__) 94: end 95: end
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.rb, line 77 77: def initialize(db, opts = nil) 78: @db = db 79: @quote_identifiers = db.quote_identifiers? if db.respond_to?(:quote_identifiers?) 80: @identifier_input_method = db.identifier_input_method if db.respond_to?(:identifier_input_method) 81: @identifier_output_method = db.identifier_output_method if db.respond_to?(:identifier_output_method) 82: @opts = opts || {} 83: @row_proc = nil 84: end
Returns the first record matching the conditions. Examples:
ds[:id=>1] => {:id=1}
# File lib/sequel/dataset/convenience.rb, line 13 13: def [](*conditions) 14: raise(Error, ARRAY_ACCESS_ERROR_MSG) if (conditions.length == 1 and conditions.first.is_a?(Integer)) or conditions.length == 0 15: first(*conditions) 16: end
Adds the given graph aliases to the list of graph aliases to use, unlike set_graph_aliases, which replaces the list. See set_graph_aliases.
# File lib/sequel/dataset/graph.rb, line 6 6: def add_graph_aliases(graph_aliases) 7: ds = select_more(*graph_alias_columns(graph_aliases)) 8: ds.opts[:graph_aliases] = (ds.opts[:graph_aliases] || ds.opts[:graph][:column_aliases] || {}).merge(graph_aliases) 9: ds 10: end
Adds an further filter to an existing filter using AND. If no filter exists an error is raised. This method is identical to filter except it expects an existing filter.
ds.filter(:a).and(:b) # SQL: WHERE a AND b
# File lib/sequel/dataset/query.rb, line 11 11: def and(*cond, &block) 12: raise(InvalidOperation, "No existing filter found.") unless @opts[:having] || @opts[:where] 13: filter(*cond, &block) 14: end
Returns the average value for the given column.
# File lib/sequel/dataset/convenience.rb, line 27 27: def avg(column) 28: aggregate_dataset.get{avg(column)} 29: end
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.
# File lib/sequel/dataset/prepared_statements.rb, line 173 173: def bind(bind_vars={}) 174: clone(:bind_vars=>@opts[:bind_vars] ? @opts[:bind_vars].merge(bind_vars) : bind_vars) 175: end
For the given type (:select, :insert, :update, or :delete), run the sql with the bind variables specified in the hash. values is a hash of passed to insert or update (if one of those types is used), which may contain placeholders.
# File lib/sequel/dataset/prepared_statements.rb, line 182 182: def call(type, bind_variables={}, *values, &block) 183: prepare(type, nil, *values).call(bind_variables, &block) 184: end
SQL fragment for specifying given CaseExpression.
# File lib/sequel/dataset/sql.rb, line 56 56: def case_expression_sql(ce) 57: sql = '(CASE ' 58: sql << "#{literal(ce.expression)} " if ce.expression 59: ce.conditions.collect{ |c,r| 60: sql << "WHEN #{literal(c)} THEN #{literal(r)} " 61: } 62: sql << "ELSE #{literal(ce.default)} END)" 63: 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.rb, line 109 109: def clone(opts = {}) 110: c = super() 111: c.opts = @opts.merge(opts) 112: c.instance_variable_set(:@columns, nil) if opts.keys.any?{|o| COLUMN_CHANGE_OPTS.include?(o)} 113: c 114: 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 29 29: def columns 30: return @columns if @columns 31: ds = unfiltered.unordered.clone(:distinct => nil, :limit => 1) 32: ds.each{break} 33: @columns = ds.instance_variable_get(:@columns) 34: @columns || [] 35: end
SQL fragment for complex expressions
# File lib/sequel/dataset/sql.rb, line 76 76: def complex_expression_sql(op, args) 77: case op 78: when *IS_OPERATORS 79: r = args.at(1) 80: if r.nil? || supports_is_true? 81: raise(InvalidOperation, 'Invalid argument used for IS operator') unless v = IS_LITERALS[r] 82: "(#{literal(args.at(0))} #{op} #{v})" 83: elsif op == :IS 84: complex_expression_sql("=""=", args) 85: else 86: complex_expression_sql(:OR, [SQL::BooleanExpression.new("!=""!=", *args), SQL::BooleanExpression.new(:IS, args.at(0), nil)]) 87: end 88: when :IN, "NOT IN""NOT IN" 89: cols = args.at(0) 90: if !supports_multiple_column_in? && cols.is_a?(Array) 91: expr = SQL::BooleanExpression.new(:OR, *args.at(1).to_a.map{|vals| SQL::BooleanExpression.from_value_pairs(cols.zip(vals).map{|col, val| [col, val]})}) 92: literal(op == :IN ? expr : ~expr) 93: else 94: "(#{literal(cols)} #{op} #{literal(args.at(1))})" 95: end 96: when *TWO_ARITY_OPERATORS 97: "(#{literal(args.at(0))} #{op} #{literal(args.at(1))})" 98: when *N_ARITY_OPERATORS 99: "(#{args.collect{|a| literal(a)}.join(" #{op} ")})" 100: when :NOT 101: "NOT #{literal(args.at(0))}" 102: when :NOOP 103: literal(args.at(0)) 104: when 'B~''B~' 105: "~#{literal(args.at(0))}" 106: else 107: raise(InvalidOperation, "invalid operator #{op}") 108: end 109: end
Returns the number of records in the dataset.
# File lib/sequel/dataset/sql.rb, line 117 117: def count 118: aggregate_dataset.get{COUNT(:*){}.as(count)}.to_i 119: end
Add a mutation method to this dataset instance.
# File lib/sequel/dataset.rb, line 117 117: def def_mutation_method(*meths) 118: meths.each do |meth| 119: instance_eval("def #{meth}!(*args, &block); mutation_method(:#{meth}, *args, &block) end", __FILE__, __LINE__) 120: end 121: 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 46 46: def delete 47: execute_dui(delete_sql) 48: end
Formats a DELETE statement using the given options and dataset options.
dataset.filter{|o| o.price >= 100}.delete_sql #=> "DELETE FROM items WHERE (price >= 100)"
# File lib/sequel/dataset/sql.rb, line 125 125: def delete_sql 126: return static_sql(opts[:sql]) if opts[:sql] 127: check_modification_allowed! 128: clause_sql(:delete) 129: 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 25 25: def distinct(*args) 26: raise(InvalidOperation, "DISTINCT ON not supported") if !args.empty? && !supports_distinct_on? 27: clone(:distinct => args) 28: 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 56 56: def each(&block) 57: if @opts[:graph] 58: graph_each(&block) 59: else 60: if row_proc = @row_proc 61: fetch_rows(select_sql){|r| yield row_proc.call(r)} 62: else 63: fetch_rows(select_sql, &block) 64: end 65: end 66: self 67: 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 20: def each_page(page_size, &block) 21: raise(Error, "You cannot paginate a dataset that already has a limit") if @opts[:limit] 22: record_count = count 23: total_pages = (record_count / page_size.to_f).ceil 24: (1..total_pages).each{|page_no| yield paginate(page_no, page_size, record_count)} 25: self 26: end
Returns true if no records exist in the dataset, false otherwise
# File lib/sequel/dataset/convenience.rb, line 32 32: def empty? 33: get(1).nil? 34: 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:
DB[:items].except(DB).sql #=> "SELECT * FROM items EXCEPT SELECT * FROM other_items"
# File lib/sequel/dataset/query.rb, line 40 40: def except(dataset, opts={}) 41: opts = {:all=>opts} unless opts.is_a?(Hash) 42: raise(InvalidOperation, "EXCEPT not supported") unless supports_intersect_except? 43: raise(InvalidOperation, "EXCEPT ALL not supported") if opts[:all] && !supports_intersect_except_all? 44: compound_clone(:except, dataset, opts) 45: 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 51 51: def exclude(*cond, &block) 52: clause = (@opts[:having] ? :having : :where) 53: cond = cond.first if cond.size == 1 54: cond = filter_expr(cond, &block) 55: cond = SQL::BooleanExpression.invert(cond) 56: cond = SQL::BooleanExpression.new(:AND, @opts[clause], cond) if @opts[clause] 57: clone(clause => cond) 58: 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 135 135: def exists 136: LiteralString.new("EXISTS (#{select_sql})") 137: end
Execute the SQL on the database and yield the rows as hashes with symbol keys.
# File lib/sequel/adapters/do.rb, line 182 182: def fetch_rows(sql) 183: execute(sql) do |reader| 184: cols = @columns = reader.fields.map{|f| output_identifier(f)} 185: while(reader.next!) do 186: h = {} 187: cols.zip(reader.values).each{|k, v| h[k] = v} 188: yield h 189: end 190: end 191: self 192: 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:
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.
If both a block and regular argument are provided, they get ANDed together.
Examples:
dataset.filter(:id => 3).sql #=> "SELECT * FROM items WHERE (id = 3)" dataset.filter('price < ?', 100).sql #=> "SELECT * FROM items WHERE price < 100" dataset.filter([[:id, (1,2,3)], [:id, 0..10]]).sql #=> "SELECT * FROM items WHERE ((id IN (1, 2, 3)) AND ((id >= 0) AND (id <= 10)))" dataset.filter('price < 100').sql #=> "SELECT * FROM items WHERE price < 100" dataset.filter(:active).sql #=> "SELECT * FROM items WHERE :active dataset.filter{|o| o.price < 100}.sql #=> "SELECT * FROM items WHERE (price < 100)"
Multiple filter calls can be chained for scoping:
software = dataset.filter(:category => 'software') software.filter{|o| o.price < 100}.sql #=> "SELECT * FROM items WHERE ((category = 'software') AND (price < 100))"
See doc/dataset_filtering.rdoc for more examples and details.
# File lib/sequel/dataset/query.rb, line 107 107: def filter(*cond, &block) 108: _filter(@opts[:having] ? :having : :where, *cond, &block) 109: 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/convenience.rb, line 55 55: def first(*args, &block) 56: ds = block ? filter(&block) : self 57: 58: if args.empty? 59: ds.single_record 60: else 61: args = (args.size == 1) ? args.first : args 62: if Integer === args 63: ds.limit(args).all 64: else 65: ds.filter(args).single_record 66: end 67: end 68: 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/sql.rb, line 141 141: def first_source_alias 142: source = @opts[:from] 143: if source.nil? || source.empty? 144: raise Error, 'No source specified for query' 145: end 146: case s = source.first 147: when SQL::AliasedExpression 148: s.aliaz 149: when Symbol 150: sch, table, aliaz = split_symbol(s) 151: aliaz ? aliaz.to_sym : s 152: else 153: s 154: end 155: 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 116 116: def from(*source) 117: table_alias_num = 0 118: sources = [] 119: source.each do |s| 120: case s 121: when Hash 122: s.each{|k,v| sources << SQL::AliasedExpression.new(k,v)} 123: when Dataset 124: sources << SQL::AliasedExpression.new(s, dataset_alias(table_alias_num+=1)) 125: when Symbol 126: sch, table, aliaz = split_symbol(s) 127: if aliaz 128: s = sch ? SQL::QualifiedIdentifier.new(sch.to_sym, table.to_sym) : SQL::Identifier.new(table.to_sym) 129: sources << SQL::AliasedExpression.new(s, aliaz.to_sym) 130: else 131: sources << s 132: end 133: else 134: sources << s 135: end 136: end 137: o = {:from=>sources.empty? ? nil : sources} 138: o[:num_dataset_sources] = table_alias_num if table_alias_num > 0 139: clone(o) 140: 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 149 149: def from_self(opts={}) 150: fs = {} 151: @opts.keys.each{|k| fs[k] = nil unless FROM_SELF_KEEP_OPTS.include?(k)} 152: clone(fs).from(opts[:alias] ? as(opts[:alias]) : self) 153: 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/convenience.rb, line 75 75: def get(column=nil, &block) 76: if column 77: raise(Error, GET_ERROR_MSG) if block 78: select(column).single_value 79: else 80: select(&block).single_value 81: end 82: 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:
# File lib/sequel/dataset/graph.rb, line 60 60: def graph(dataset, join_conditions = nil, options = {}, &block) 61: # Allow the use of a model, dataset, or symbol as the first argument 62: # Find the table name/dataset based on the argument 63: dataset = dataset.dataset if dataset.respond_to?(:dataset) 64: table_alias = options[:table_alias] 65: case dataset 66: when Symbol 67: table = dataset 68: dataset = @db[dataset] 69: table_alias ||= table 70: when ::Sequel::Dataset 71: if dataset.simple_select_all? 72: table = dataset.opts[:from].first 73: table_alias ||= table 74: else 75: table = dataset 76: table_alias ||= dataset_alias((@opts[:num_dataset_sources] || 0)+1) 77: end 78: else 79: raise Error, "The dataset argument should be a symbol, dataset, or model" 80: end 81: 82: # Raise Sequel::Error with explanation that the table alias has been used 83: raise_alias_error = lambda do 84: raise(Error, "this #{options[:table_alias] ? 'alias' : 'table'} has already been been used, please specify " \ 85: "#{options[:table_alias] ? 'a different alias' : 'an alias via the :table_alias option'}") 86: end 87: 88: # Only allow table aliases that haven't been used 89: raise_alias_error.call if @opts[:graph] && @opts[:graph][:table_aliases] && @opts[:graph][:table_aliases].include?(table_alias) 90: 91: # Use a from_self if this is already a joined table 92: ds = (!@opts[:graph] && (@opts[:from].length > 1 || @opts[:join])) ? from_self(:alias=>options[:from_self_alias] || first_source) : self 93: 94: # Join the table early in order to avoid cloning the dataset twice 95: ds = ds.join_table(options[:join_type] || :left_outer, table, join_conditions, :table_alias=>table_alias, :implicit_qualifier=>options[:implicit_qualifier], &block) 96: opts = ds.opts 97: 98: # Whether to include the table in the result set 99: add_table = options[:select] == false ? false : true 100: # Whether to add the columns to the list of column aliases 101: add_columns = !ds.opts.include?(:graph_aliases) 102: 103: # Setup the initial graph data structure if it doesn't exist 104: unless graph = opts[:graph] 105: master = ds.first_source_alias 106: raise_alias_error.call if master == table_alias 107: # Master hash storing all .graph related information 108: graph = opts[:graph] = {} 109: # Associates column aliases back to tables and columns 110: column_aliases = graph[:column_aliases] = {} 111: # Associates table alias (the master is never aliased) 112: table_aliases = graph[:table_aliases] = {master=>self} 113: # Keep track of the alias numbers used 114: ca_num = graph[:column_alias_num] = Hash.new(0) 115: # All columns in the master table are never 116: # aliased, but are not included if set_graph_aliases 117: # has been used. 118: if add_columns 119: select = opts[:select] = [] 120: columns.each do |column| 121: column_aliases[column] = [master, column] 122: select.push(SQL::QualifiedIdentifier.new(master, column)) 123: end 124: end 125: end 126: 127: # Add the table alias to the list of aliases 128: # Even if it isn't been used in the result set, 129: # we add a key for it with a nil value so we can check if it 130: # is used more than once 131: table_aliases = graph[:table_aliases] 132: table_aliases[table_alias] = add_table ? dataset : nil 133: 134: # Add the columns to the selection unless we are ignoring them 135: if add_table && add_columns 136: select = opts[:select] 137: column_aliases = graph[:column_aliases] 138: ca_num = graph[:column_alias_num] 139: # Which columns to add to the result set 140: cols = options[:select] || dataset.columns 141: # If the column hasn't been used yet, don't alias it. 142: # If it has been used, try table_column. 143: # If that has been used, try table_column_N 144: # using the next value of N that we know hasn't been 145: # used 146: cols.each do |column| 147: col_alias, identifier = if column_aliases[column] 148: column_alias = "#{table_alias}_#{column}""#{table_alias}_#{column}" 149: if column_aliases[column_alias] 150: column_alias_num = ca_num[column_alias] 151: column_alias = "#{column_alias}_#{column_alias_num}""#{column_alias}_#{column_alias_num}" 152: ca_num[column_alias] += 1 153: end 154: [column_alias, SQL::QualifiedIdentifier.new(table_alias, column).as(column_alias)] 155: else 156: [column, SQL::QualifiedIdentifier.new(table_alias, column)] 157: end 158: column_aliases[col_alias] = [table_alias, column] 159: select.push(identifier) 160: end 161: end 162: ds 163: 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 163 163: def grep(cols, terms) 164: filter(SQL::BooleanExpression.new(:OR, *Array(cols).collect{|c| SQL::StringExpression.like(c, *terms)})) 165: 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 172 172: def group(*columns) 173: clone(:group => (columns.compact.empty? ? nil : columns)) 174: end
Returns a dataset grouped by the given column with count by group, order by the count of records (in ascending order). 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/convenience.rb, line 93 93: def group_and_count(*columns) 94: groups = columns.map do |c| 95: c_table, column, _ = split_symbol(c) 96: c_table ? column.to_sym.qualify(c_table) : column.to_sym 97: end 98: group(*groups).select(*(columns + [COUNT_OF_ALL_AS_COUNT])).order(:count) 99: 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 180 180: def having(*cond, &block) 181: _filter(:having, *cond, &block) 182: end
Inserts multiple records into the associated table. This method can be to efficiently insert a large amounts of records into a table. Inserts are automatically wrapped in a transaction.
This method 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/convenience.rb, line 119 119: def import(columns, values, opts={}) 120: return @db.transaction{insert(columns, values)} if values.is_a?(Dataset) 121: 122: return if values.empty? 123: raise(Error, IMPORT_ERROR_MSG) if columns.empty? 124: 125: if slice_size = opts[:commit_every] || opts[:slice] 126: offset = 0 127: loop do 128: @db.transaction(opts){multi_insert_sql(columns, values[offset, slice_size]).each{|st| execute_dui(st)}} 129: offset += slice_size 130: break if offset >= values.length 131: end 132: else 133: statements = multi_insert_sql(columns, values) 134: @db.transaction{statements.each{|st| execute_dui(st)}} 135: end 136: 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 78 78: def insert(*values) 79: execute_insert(insert_sql(*values)) 80: 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/sql.rb, line 168 168: def insert_multiple(array, &block) 169: if block 170: array.each {|i| insert(block[i])} 171: else 172: array.each {|i| insert(i)} 173: end 174: 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 192 192: def insert_sql(*values) 193: return static_sql(@opts[:sql]) if @opts[:sql] 194: 195: check_modification_allowed! 196: 197: columns = [] 198: 199: case values.size 200: when 0 201: return insert_sql({}) 202: when 1 203: case vals = values.at(0) 204: when Hash 205: vals = @opts[:defaults].merge(vals) if @opts[:defaults] 206: vals = vals.merge(@opts[:overrides]) if @opts[:overrides] 207: values = [] 208: vals.each do |k,v| 209: columns << k 210: values << v 211: end 212: when Dataset, Array, LiteralString 213: values = vals 214: else 215: if vals.respond_to?(:values) && (v = vals.values).is_a?(Hash) 216: return insert_sql(v) 217: end 218: end 219: when 2 220: if (v0 = values.at(0)).is_a?(Array) && ((v1 = values.at(1)).is_a?(Array) || v1.is_a?(Dataset) || v1.is_a?(LiteralString)) 221: columns, values = v0, v1 222: raise(Error, "Different number of values and columns given to insert_sql") if values.is_a?(Array) and columns.length != values.length 223: end 224: end 225: 226: columns = columns.map{|k| literal(String === k ? k.to_sym : k)} 227: clone(:columns=>columns, :values=>values)._insert_sql 228: 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:
DB[:items].intersect(DB).sql #=> "SELECT * FROM items INTERSECT SELECT * FROM other_items"
# File lib/sequel/dataset/query.rb, line 194 194: def intersect(dataset, opts={}) 195: opts = {:all=>opts} unless opts.is_a?(Hash) 196: raise(InvalidOperation, "INTERSECT not supported") unless supports_intersect_except? 197: raise(InvalidOperation, "INTERSECT ALL not supported") if opts[:all] && !supports_intersect_except_all? 198: compound_clone(:intersect, dataset, opts) 199: end
Inverts the current filter
dataset.filter(:category => 'software').invert.sql #=> "SELECT * FROM items WHERE (category != 'software')"
# File lib/sequel/dataset/query.rb, line 205 205: def invert 206: having, where = @opts[:having], @opts[:where] 207: raise(Error, "No current filter") unless having || where 208: o = {} 209: o[:having] = SQL::BooleanExpression.invert(having) if having 210: o[:where] = SQL::BooleanExpression.invert(where) if where 211: clone(o) 212: end
SQL fragment specifying a JOIN clause without ON or USING.
# File lib/sequel/dataset/sql.rb, line 231 231: def join_clause_sql(jc) 232: table = jc.table 233: table_alias = jc.table_alias 234: table_alias = nil if table == table_alias 235: tref = table_ref(table) 236: " #{join_type_sql(jc.join_type)} #{table_alias ? as_sql(tref, table_alias) : tref}" 237: end
Returns a joined dataset. Uses the following arguments:
# File lib/sequel/dataset/sql.rb, line 279 279: def join_table(type, table, expr=nil, options={}, &block) 280: using_join = expr.is_a?(Array) && !expr.empty? && expr.all?{|x| x.is_a?(Symbol)} 281: if using_join && !supports_join_using? 282: h = {} 283: expr.each{|s| h[s] = s} 284: return join_table(type, table, h, options) 285: end 286: 287: if [Symbol, String].any?{|c| options.is_a?(c)} 288: table_alias = options 289: last_alias = nil 290: else 291: table_alias = options[:table_alias] 292: last_alias = options[:implicit_qualifier] 293: end 294: if Dataset === table 295: if table_alias.nil? 296: table_alias_num = (@opts[:num_dataset_sources] || 0) + 1 297: table_alias = dataset_alias(table_alias_num) 298: end 299: table_name = table_alias 300: else 301: table = table.table_name if table.respond_to?(:table_name) 302: table_name = table_alias || table 303: end 304: 305: join = if expr.nil? and !block_given? 306: SQL::JoinClause.new(type, table, table_alias) 307: elsif using_join 308: raise(Sequel::Error, "can't use a block if providing an array of symbols as expr") if block_given? 309: SQL::JoinUsingClause.new(expr, type, table, table_alias) 310: else 311: last_alias ||= @opts[:last_joined_table] || first_source_alias 312: if Sequel.condition_specifier?(expr) 313: expr = expr.collect do |k, v| 314: k = qualified_column_name(k, table_name) if k.is_a?(Symbol) 315: v = qualified_column_name(v, last_alias) if v.is_a?(Symbol) 316: [k,v] 317: end 318: end 319: if block_given? 320: expr2 = yield(table_name, last_alias, @opts[:join] || []) 321: expr = expr ? SQL::BooleanExpression.new(:AND, expr, expr2) : expr2 322: end 323: SQL::JoinOnClause.new(expr, type, table, table_alias) 324: end 325: 326: opts = {:join => (@opts[:join] || []) + [join], :last_joined_table => table_name} 327: opts[:num_dataset_sources] = table_alias_num if table_alias_num 328: clone(opts) 329: 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/convenience.rb, line 148 148: def last(*args, &block) 149: raise(Error, 'No order specified') unless @opts[:order] 150: reverse.first(*args, &block) 151: 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 220 220: def limit(l, o = nil) 221: return from_self.limit(l, o) if @opts[:sql] 222: 223: if Range === l 224: o = l.first 225: l = l.last - l.first + (l.exclude_end? ? 0 : 1) 226: end 227: l = l.to_i 228: raise(Error, 'Limits must be greater than or equal to 1') unless l >= 1 229: opts = {:limit => l} 230: if o 231: o = o.to_i 232: raise(Error, 'Offsets must be greater than or equal to 0') unless o >= 0 233: opts[:offset] = o 234: end 235: clone(opts) 236: 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 341 341: def literal(v) 342: case v 343: when String 344: return v if v.is_a?(LiteralString) 345: v.is_a?(SQL::Blob) ? literal_blob(v) : literal_string(v) 346: when Symbol 347: literal_symbol(v) 348: when Integer 349: literal_integer(v) 350: when Hash 351: literal_hash(v) 352: when SQL::Expression 353: literal_expression(v) 354: when Float 355: literal_float(v) 356: when BigDecimal 357: literal_big_decimal(v) 358: when NilClass 359: NULL 360: when TrueClass 361: literal_true 362: when FalseClass 363: literal_false 364: when Array 365: literal_array(v) 366: when Time 367: literal_time(v) 368: when DateTime 369: literal_datetime(v) 370: when Date 371: literal_date(v) 372: when Dataset 373: literal_dataset(v) 374: else 375: literal_other(v) 376: end 377: 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/convenience.rb, line 159 159: def map(column=nil, &block) 160: if column 161: raise(Error, MAP_ERROR_MSG) if block 162: super(){|r| r[column]} 163: else 164: super(&block) 165: end 166: end
Returns the maximum value for the given column.
# File lib/sequel/dataset/convenience.rb, line 169 169: def max(column) 170: aggregate_dataset.get{max(column)} 171: end
Returns the minimum value for the given column.
# File lib/sequel/dataset/convenience.rb, line 174 174: def min(column) 175: aggregate_dataset.get{min(column)} 176: 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/convenience.rb, line 188 188: def multi_insert(hashes, opts={}) 189: return if hashes.empty? 190: columns = hashes.first.keys 191: import(columns, hashes.map{|h| columns.map{|c| h[c]}}, opts) 192: 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 385 385: def multi_insert_sql(columns, values) 386: values.map{|r| insert_sql(columns, r)} 387: 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 242 242: def or(*cond, &block) 243: clause = (@opts[:having] ? :having : :where) 244: raise(InvalidOperation, "No existing filter found.") unless @opts[clause] 245: cond = cond.first if cond.size == 1 246: clone(clause => SQL::BooleanExpression.new(:OR, @opts[clause], filter_expr(cond, &block))) 247: 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 262 262: def order(*columns, &block) 263: columns += Array(Sequel.virtual_row(&block)) if block 264: clone(:order => (columns.compact.empty?) ? nil : columns) 265: end
Returns a copy of the dataset with the order columns added to 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 273 273: def order_more(*columns, &block) 274: columns = @opts[:order] + columns if @opts[:order] 275: order(*columns, &block) 276: 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 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
SQL fragment for a literal string with placeholders
# File lib/sequel/dataset/sql.rb, line 396 396: def placeholder_literal_string_sql(pls) 397: args = pls.args 398: s = if args.is_a?(Hash) 399: re = /:(#{args.keys.map{|k| Regexp.escape(k.to_s)}.join('|')})\b/ 400: pls.str.gsub(re){literal(args[$1.to_sym])} 401: else 402: i = -1 403: pls.str.gsub(QUESTION_MARK){literal(args.at(i+=1))} 404: end 405: s = "(#{s})" if pls.parens 406: s 407: end
Prepare an SQL statement for later execution. This returns a clone of the dataset extended with PreparedStatementMethods, on which you can call call with the hash of bind variables to do substitution. The prepared statement is also stored in the associated database. The following usage is identical:
ps = prepare(:select, :select_by_name) ps.call(:name=>'Blah') db.call(:select_by_name, :name=>'Blah')
# File lib/sequel/dataset/prepared_statements.rb, line 195 195: def prepare(type, name=nil, *values) 196: ps = to_prepared_statement(type, values) 197: db.prepared_statements[name] = ps if name 198: ps 199: end
Create a named prepared statement that is stored in the database (and connection) for reuse.
# File lib/sequel/adapters/jdbc.rb, line 468 468: def prepare(type, name=nil, *values) 469: ps = to_prepared_statement(type, values) 470: ps.extend(PreparedStatementMethods) 471: if name 472: ps.prepared_statement_name = name 473: db.prepared_statements[name] = ps 474: end 475: ps 476: end
SQL fragment for the qualifed identifier, specifying a table and a column (or schema and table).
# File lib/sequel/dataset/sql.rb, line 411 411: def qualified_identifier_sql(qcr) 412: [qcr.table, qcr.column].map{|x| [SQL::QualifiedIdentifier, SQL::Identifier, Symbol].any?{|c| x.is_a?(c)} ? literal(x) : quote_identifier(x)}.join('.') 413: 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/sql.rb, line 424 424: def qualify_to(table) 425: o = @opts 426: return clone if o[:sql] 427: h = {} 428: (o.keys & QUALIFY_KEYS).each do |k| 429: h[k] = qualified_expression(o[k], table) 430: end 431: h[:select] = [SQL::ColumnAll.new(table)] if !o[:select] || o[:select].empty? 432: clone(h) 433: 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/sql.rb, line 440 440: def qualify_to_first_source 441: qualify_to(first_source) 442: 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 30: def query(&block) 31: copy = clone({}) 32: copy.extend(QueryBlockCopy) 33: copy.instance_eval(&block) 34: clone(copy.opts) 35: 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 447 447: def quote_identifier(name) 448: return name if name.is_a?(LiteralString) 449: name = name.value if name.is_a?(SQL::Identifier) 450: name = input_identifier(name) 451: name = quoted_identifier(name) if quote_identifiers? 452: name 453: end
Whether this dataset quotes identifiers.
# File lib/sequel/dataset/features.rb, line 4 4: def quote_identifiers? 5: @quote_identifiers 6: end
Separates the schema from the table and returns a string with them quoted (if quoting identifiers)
# File lib/sequel/dataset/sql.rb, line 457 457: def quote_schema_table(table) 458: schema, table = schema_and_table(table) 459: "#{"#{quote_identifier(schema)}." if schema}#{quote_identifier(table)}" 460: 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 465 465: def quoted_identifier(name) 466: "\"#{name.to_s.gsub('"', '""')}\"" 467: end
Split the schema information from the table
# File lib/sequel/dataset/sql.rb, line 470 470: def schema_and_table(table_name) 471: sch = db.default_schema if db 472: case table_name 473: when Symbol 474: s, t, a = split_symbol(table_name) 475: [s||sch, t] 476: when SQL::QualifiedIdentifier 477: [table_name.table, table_name.column] 478: when SQL::Identifier 479: [sch, table_name.value] 480: when String 481: [sch, table_name] 482: else 483: raise Error, 'table_name should be a Symbol, SQL::QualifiedIdentifier, SQL::Identifier, or String' 484: end 485: 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 292 292: def select(*columns, &block) 293: columns += Array(Sequel.virtual_row(&block)) if block 294: m = [] 295: columns.map do |i| 296: i.is_a?(Hash) ? m.concat(i.map{|k, v| SQL::AliasedExpression.new(k,v)}) : m << i 297: end 298: clone(:select => m) 299: 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 304 304: def select_all 305: clone(:select => nil) 306: end
Returns a copy of the dataset with the given columns added to the existing selected columns.
dataset.select(:a).select(:b) # SELECT b FROM items dataset.select(:a).select_more(:b) # SELECT a, b FROM items
# File lib/sequel/dataset/query.rb, line 313 313: def select_more(*columns, &block) 314: columns = @opts[:select] + columns if @opts[:select] 315: select(*columns, &block) 316: end
Formats a SELECT statement
dataset.select_sql # => "SELECT * FROM items"
# File lib/sequel/dataset/sql.rb, line 490 490: def select_sql 491: return static_sql(@opts[:sql]) if @opts[:sql] 492: clause_sql(:select) 493: 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.rb, line 140 140: def server(servr) 141: clone(:server=>servr) 142: end
This allows you to manually specify the graph aliases to use when using graph. You can use it to only select certain columns, and have those columns mapped to specific aliases in the result set. This is the equivalent of .select for a graphed dataset, and must be used instead of .select whenever graphing is used. Example:
DB[:artists].graph(:albums, :artist_id=>:id).set_graph_aliases(:artist_name=>[:artists, :name], :album_name=>[:albums, :name], :forty_two=>[:albums, :fourtwo, 42]).first => {:artists=>{:name=>artists.name}, :albums=>{:name=>albums.name, :fourtwo=>42}}
Arguments:
# File lib/sequel/dataset/graph.rb, line 182 182: def set_graph_aliases(graph_aliases) 183: ds = select(*graph_alias_columns(graph_aliases)) 184: ds.opts[:graph_aliases] = graph_aliases 185: ds 186: end
Same as select_sql, not aliased directly to make subclassing simpler.
# File lib/sequel/dataset/sql.rb, line 496 496: def sql 497: select_sql 498: end
Whether the dataset supports common table expressions (the WITH clause).
# File lib/sequel/dataset/features.rb, line 15 15: def supports_cte? 16: select_clause_methods.include?(WITH_SUPPORTED) 17: end
Whether the dataset supports the DISTINCT ON clause, true by default.
# File lib/sequel/dataset/features.rb, line 20 20: def supports_distinct_on? 21: true 22: end
Whether the dataset supports the IS TRUE syntax.
# File lib/sequel/dataset/features.rb, line 35 35: def supports_is_true? 36: true 37: end
Whether the dataset supports the JOIN table USING (column1, …) syntax.
# File lib/sequel/dataset/features.rb, line 40 40: def supports_join_using? 41: true 42: end
Whether the dataset supports window functions.
# File lib/sequel/dataset/features.rb, line 61 61: def supports_window_functions? 62: false 63: 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/convenience.rb, line 229 229: def to_csv(include_column_titles = true) 230: n = naked 231: cols = n.columns 232: csv = '' 233: csv << "#{cols.join(COMMA_SEPARATOR)}\r\n" if include_column_titles 234: n.each{|r| csv << "#{cols.collect{|c| r[c]}.join(COMMA_SEPARATOR)}\r\n"} 235: csv 236: 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/convenience.rb, line 242 242: def to_hash(key_column, value_column = nil) 243: inject({}) do |m, r| 244: m[r[key_column]] = value_column ? r[value_column] : r 245: m 246: end 247: end
Truncates the dataset. Returns nil.
# File lib/sequel/dataset/actions.rb, line 89 89: def truncate 90: execute_ddl(truncate_sql) 91: end
SQL query to truncate the table
# File lib/sequel/dataset/sql.rb, line 506 506: def truncate_sql 507: if opts[:sql] 508: static_sql(opts[:sql]) 509: else 510: check_modification_allowed! 511: raise(InvalidOperation, "Can't truncate filtered datasets") if opts[:where] 512: _truncate_sql(source_list(opts[:from])) 513: end 514: 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:
DB[:items].union(DB).sql #=> "SELECT * FROM items UNION SELECT * FROM other_items"
# File lib/sequel/dataset/query.rb, line 341 341: def union(dataset, opts={}) 342: opts = {:all=>opts} unless opts.is_a?(Hash) 343: compound_clone(:union, dataset, opts) 344: end
Updates values for the dataset. The returned value is generally the number of rows updated, but that is adapter dependent. See update_sql.
# File lib/sequel/dataset/actions.rb, line 95 95: def update(values={}) 96: execute_dui(update_sql(values)) 97: 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 523 523: def update_sql(values = {}) 524: return static_sql(opts[:sql]) if opts[:sql] 525: check_modification_allowed! 526: clone(:values=>values)._update_sql 527: 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/sql.rb, line 533 533: def where(*cond, &block) 534: _filter(:where, *cond, &block) 535: end
The SQL fragment for the given window‘s options.
# File lib/sequel/dataset/sql.rb, line 538 538: def window_sql(opts) 539: raise(Error, 'This dataset does not support window functions') unless supports_window_functions? 540: window = literal(opts[:window]) if opts[:window] 541: partition = "PARTITION BY #{expression_list(Array(opts[:partition]))}" if opts[:partition] 542: order = "ORDER BY #{expression_list(Array(opts[:order]))}" if opts[:order] 543: frame = case opts[:frame] 544: when nil 545: nil 546: when :all 547: "ROWS BETWEEN UNBOUNDED PRECEDING AND UNBOUNDED FOLLOWING" 548: when :rows 549: "ROWS UNBOUNDED PRECEDING" 550: else 551: raise Error, "invalid window frame clause, should be :all, :rows, or nil" 552: end 553: "(#{[window, partition, order, frame].compact.join(' ')})" 554: 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:
# File lib/sequel/dataset/sql.rb, line 566 566: def with(name, dataset, opts={}) 567: raise(Error, 'This datatset does not support common table expressions') unless supports_cte? 568: clone(:with=>(@opts[:with]||[]) + [opts.merge(:name=>name, :dataset=>dataset)]) 569: 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:
# File lib/sequel/dataset/sql.rb, line 576 576: def with_recursive(name, nonrecursive, recursive, opts={}) 577: raise(Error, 'This datatset does not support common table expressions') unless supports_cte? 578: clone(:with=>(@opts[:with]||[]) + [opts.merge(:recursive=>true, :name=>name, :dataset=>nonrecursive.union(recursive, {:all=>opts[:union_all] != false, :from_self=>false}))]) 579: 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/sql.rb, line 585 585: def with_sql(sql, *args) 586: sql = SQL::PlaceholderLiteralString.new(sql, args) unless args.empty? 587: clone(:sql=>sql) 588: end
Formats an UPDATE statement using the stored values.
# File lib/sequel/dataset/sql.rb, line 606 606: def _update_sql 607: clause_sql(:update) 608: end
Return true if the dataset has a non-nil value for any key in opts.
# File lib/sequel/dataset.rb, line 162 162: def options_overlap(opts) 163: !(@opts.collect{|k,v| k unless v.nil?}.compact & opts).empty? 164: end
Whether this dataset is a simple SELECT * FROM table.
# File lib/sequel/dataset.rb, line 167 167: def simple_select_all? 168: o = @opts.reject{|k,v| v.nil? || NON_SQL_OPTIONS.include?(k)} 169: o.length == 1 && (f = o[:from]) && f.length == 1 && f.first.is_a?(Symbol) 170: end
Return a cloned copy of the current dataset extended with PreparedStatementMethods, setting the type and modify values.
# File lib/sequel/dataset/prepared_statements.rb, line 205 205: def to_prepared_statement(type, values=nil) 206: ps = bind 207: ps.extend(PreparedStatementMethods) 208: ps.prepared_type = type 209: ps.prepared_modify_values = values 210: ps 211: end