module Sequel::MSSQL
Constants
- CONSTANT_MAP
- EXTRACT_MAP
- LIMIT_ALL
Public Class Methods
# File lib/sequel/adapters/shared/mssql.rb, line 9 def self.mock_adapter_setup(db) db.instance_exec do @server_version = 11000000 end end
Public Instance Methods
# File lib/sequel/adapters/shared/mssql.rb, line 587 def complex_expression_sql_append(sql, op, args) case op when :'||' super(sql, :+, args) when :LIKE, :"NOT LIKE" super(sql, op, complex_expression_sql_like_args(args, " COLLATE Latin1_General_CS_AS)")) when :ILIKE, :"NOT ILIKE" super(sql, (op == :ILIKE ? :LIKE : :"NOT LIKE"), complex_expression_sql_like_args(args, " COLLATE Latin1_General_CI_AS)")) when :<<, :>> complex_expression_emulate_append(sql, op, args) when :extract part = args[0] raise(Sequel::Error, "unsupported extract argument: #{part.inspect}") unless format = EXTRACT_MAP[part] if part == :second expr = args[1] sql << "CAST((datepart(" << format.to_s << ', ' literal_append(sql, expr) sql << ') + datepart(ns, ' literal_append(sql, expr) sql << ")/1000000000.0) AS double precision)" else sql << "datepart(" << format.to_s << ', ' literal_append(sql, args[1]) sql << ')' end else super end end
For a dataset with custom SQL, since it may include ORDER BY, you cannot wrap it in a subquery. Load entire query in this case to get the number of rows. In general, you should avoid calling this method on datasets with custom SQL.
# File lib/sequel/adapters/shared/mssql.rb, line 630 def count(*a, &block) if (@opts[:sql] && a.empty? && !block) naked.to_a.length else super end end
Uses CROSS APPLY to join the given table into the current dataset.
# File lib/sequel/adapters/shared/mssql.rb, line 639 def cross_apply(table) join_table(:cross_apply, table) end
Disable the use of INSERT OUTPUT
# File lib/sequel/adapters/shared/mssql.rb, line 644 def disable_insert_output clone(:disable_insert_output=>true) end
For a dataset with custom SQL, since it may include ORDER BY, you cannot wrap it in a subquery. Run query, and if it returns any records, return true. In general, you should avoid calling this method on datasets with custom SQL.
# File lib/sequel/adapters/shared/mssql.rb, line 652 def empty? if @opts[:sql] naked.each{return false} true else super end end
MSSQL treats [] as a metacharacter in LIKE expresions.
# File lib/sequel/adapters/shared/mssql.rb, line 662 def escape_like(string) string.gsub(/[\\%_\[\]]/){|m| "\\#{m}"} end
MSSQL uses the CONTAINS keyword for full text search
# File lib/sequel/adapters/shared/mssql.rb, line 667 def full_text_search(cols, terms, opts = OPTS) terms = "\"#{terms.join('" OR "')}\"" if terms.is_a?(Array) where(Sequel.lit("CONTAINS (?, ?)", cols, terms)) end
Insert a record, returning the record inserted, using OUTPUT. Always returns nil without running an INSERT statement if #disable_insert_output is used. If the query runs but returns no values, returns false.
# File lib/sequel/adapters/shared/mssql.rb, line 675 def insert_select(*values) return unless supports_insert_select? with_sql_first(insert_select_sql(*values)) || false end
Add OUTPUT clause unless there is already an existing output clause, then return the SQL to insert.
# File lib/sequel/adapters/shared/mssql.rb, line 682 def insert_select_sql(*values) ds = (opts[:output] || opts[:returning]) ? self : output(nil, [SQL::ColumnAll.new(:inserted)]) ds.insert_sql(*values) end
Specify a table for a SELECT … INTO query.
# File lib/sequel/adapters/shared/mssql.rb, line 688 def into(table) clone(:into => table) end
Use the database's #mssql_unicode_strings setting if the dataset hasn't overridden it.
# File lib/sequel/adapters/shared/mssql.rb, line 578 def mssql_unicode_strings opts.has_key?(:mssql_unicode_strings) ? opts[:mssql_unicode_strings] : db.mssql_unicode_strings end
Allows you to do a dirty read of uncommitted data using WITH (NOLOCK).
# File lib/sequel/adapters/shared/mssql.rb, line 693 def nolock lock_style(:dirty) end
Uses OUTER APPLY to join the given table into the current dataset.
# File lib/sequel/adapters/shared/mssql.rb, line 698 def outer_apply(table) join_table(:outer_apply, table) end
Include an OUTPUT clause in the eventual INSERT, UPDATE, or DELETE query.
The first argument is the table to output into, and the second argument is either an Array of column values to select, or a Hash which maps output column names to selected values, in the style of insert or update.
Output into a returned result set is not currently supported.
Examples:
dataset.output(:output_table, [Sequel[:deleted][:id], Sequel[:deleted][:name]]) dataset.output(:output_table, id: Sequel[:inserted][:id], name: Sequel[:inserted][:name])
# File lib/sequel/adapters/shared/mssql.rb, line 714 def output(into, values) raise(Error, "SQL Server versions 2000 and earlier do not support the OUTPUT clause") unless supports_output_clause? output = {} case values when Hash output[:column_list], output[:select_list] = values.keys, values.values when Array output[:select_list] = values end output[:into] = into clone(:output => output) end
MSSQL uses [] to quote identifiers.
# File lib/sequel/adapters/shared/mssql.rb, line 728 def quoted_identifier_append(sql, name) sql << '[' << name.to_s.gsub(/\]/, ']]') << ']' end
Emulate RETURNING using the output clause. This only handles values that are simple column references.
# File lib/sequel/adapters/shared/mssql.rb, line 733 def returning(*values) values = values.map do |v| unless r = unqualified_column_for(v) raise(Error, "cannot emulate RETURNING via OUTPUT for value: #{v.inspect}") end r end clone(:returning=>values) end
On MSSQL 2012+ add a default order to the current dataset if an offset is used. The default offset emulation using a subquery would be used in the unordered case by default, and that also adds a default order, so it's better to just avoid the subquery.
# File lib/sequel/adapters/shared/mssql.rb, line 747 def select_sql if @opts[:offset] raise(Error, "Using with_ties is not supported with an offset on Microsoft SQL Server") if @opts[:limit_with_ties] return order(1).select_sql if is_2012_or_later? && !@opts[:order] end super end
The version of the database server.
# File lib/sequel/adapters/shared/mssql.rb, line 756 def server_version db.server_version(@opts[:server]) end
# File lib/sequel/adapters/shared/mssql.rb, line 760 def supports_cte?(type=:select) is_2005_or_later? end
MSSQL 2005+ supports GROUP BY CUBE.
# File lib/sequel/adapters/shared/mssql.rb, line 765 def supports_group_cube? is_2005_or_later? end
MSSQL 2005+ supports GROUP BY ROLLUP
# File lib/sequel/adapters/shared/mssql.rb, line 770 def supports_group_rollup? is_2005_or_later? end
MSSQL 2008+ supports GROUPING SETS
# File lib/sequel/adapters/shared/mssql.rb, line 775 def supports_grouping_sets? is_2008_or_later? end
MSSQL supports #insert_select via the OUTPUT clause.
# File lib/sequel/adapters/shared/mssql.rb, line 780 def supports_insert_select? supports_output_clause? && !opts[:disable_insert_output] end
MSSQL 2005+ supports INTERSECT and EXCEPT
# File lib/sequel/adapters/shared/mssql.rb, line 785 def supports_intersect_except? is_2005_or_later? end
MSSQL does not support IS TRUE
# File lib/sequel/adapters/shared/mssql.rb, line 790 def supports_is_true? false end
MSSQL doesn't support JOIN USING
# File lib/sequel/adapters/shared/mssql.rb, line 795 def supports_join_using? false end
MSSQL 2008+ supports MERGE
# File lib/sequel/adapters/shared/mssql.rb, line 800 def supports_merge? is_2008_or_later? end
MSSQL 2005+ supports modifying joined datasets
# File lib/sequel/adapters/shared/mssql.rb, line 805 def supports_modifying_joins? is_2005_or_later? end
MSSQL does not support multiple columns for the IN/NOT IN operators
# File lib/sequel/adapters/shared/mssql.rb, line 810 def supports_multiple_column_in? false end
MSSQL supports NOWAIT.
# File lib/sequel/adapters/shared/mssql.rb, line 815 def supports_nowait? true end
MSSQL 2005+ supports the OUTPUT clause.
# File lib/sequel/adapters/shared/mssql.rb, line 825 def supports_output_clause? is_2005_or_later? end
MSSQL 2005+ can emulate RETURNING via the OUTPUT clause.
# File lib/sequel/adapters/shared/mssql.rb, line 830 def supports_returning?(type) supports_insert_select? end
MSSQL uses READPAST to skip locked rows.
# File lib/sequel/adapters/shared/mssql.rb, line 835 def supports_skip_locked? true end
MSSQL cannot use WHERE 1.
# File lib/sequel/adapters/shared/mssql.rb, line 845 def supports_where_true? false end
MSSQL 2005+ supports window functions
# File lib/sequel/adapters/shared/mssql.rb, line 840 def supports_window_functions? true end
Return a cloned dataset with the #mssql_unicode_strings option set.
# File lib/sequel/adapters/shared/mssql.rb, line 583 def with_mssql_unicode_strings(v) clone(:mssql_unicode_strings=>v) end
Use WITH TIES when limiting the result set to also include additional rows matching the last row.
# File lib/sequel/adapters/shared/mssql.rb, line 851 def with_ties clone(:limit_with_ties=>true) end
Protected Instance Methods
If returned primary keys are requested, use OUTPUT unless already set on the dataset. If OUTPUT is already set, use existing returning values. If OUTPUT is only set to return a single columns, return an array of just that column. Otherwise, return an array of hashes.
# File lib/sequel/adapters/shared/mssql.rb, line 861 def _import(columns, values, opts=OPTS) if opts[:return] == :primary_key && !@opts[:output] output(nil, [SQL::QualifiedIdentifier.new(:inserted, first_primary_key)])._import(columns, values, opts) elsif @opts[:output] # no transaction: our multi_insert_sql_strategy should guarantee # that there's only ever a single statement. sql = multi_insert_sql(columns, values)[0] naked.with_sql(sql).map{|v| v.length == 1 ? v.values.first : v} else super end end
If the dataset using a order without a limit or offset or custom SQL, remove the order. Compounds on Microsoft SQL Server have undefined order unless the result is specifically ordered. Applying the current order before the compound doesn't work in all cases, such as when qualified identifiers are used. If you want to ensure a order for a compound dataset, apply the order after all compounds have been added.
# File lib/sequel/adapters/shared/mssql.rb, line 881 def compound_from_self if @opts[:offset] && !@opts[:limit] && !is_2012_or_later? clone(:limit=>LIMIT_ALL).from_self elsif @opts[:order] && !(@opts[:sql] || @opts[:limit] || @opts[:offset]) unordered else super end end
Private Instance Methods
Normalize conditions for MERGE WHEN.
# File lib/sequel/adapters/shared/mssql.rb, line 894 def _merge_when_conditions_sql(sql, data) if data.has_key?(:conditions) sql << " AND " literal_append(sql, _normalize_merge_when_conditions(data[:conditions])) end end
MSSQL requires a semicolon at the end of MERGE.
# File lib/sequel/adapters/shared/mssql.rb, line 917 def _merge_when_sql(sql) super sql << ';' end
Handle nil, false, and true MERGE WHEN conditions to avoid non-boolean type error.
# File lib/sequel/adapters/shared/mssql.rb, line 903 def _normalize_merge_when_conditions(conditions) case conditions when nil, false {1=>0} when true {1=>1} when Sequel::SQL::DelayedEvaluation Sequel.delay{_normalize_merge_when_conditions(conditions.call(self))} else conditions end end
MSSQL does not allow ordering in sub-clauses unless TOP (limit) is specified
# File lib/sequel/adapters/shared/mssql.rb, line 923 def aggregate_dataset (options_overlap(Sequel::Dataset::COUNT_FROM_SELF_OPTS) && !options_overlap([:limit])) ? unordered.from_self : super end
Allow update and delete for unordered, limited datasets only.
# File lib/sequel/adapters/shared/mssql.rb, line 928 def check_not_limited!(type) return if @opts[:skip_limit_check] && type != :truncate raise Sequel::InvalidOperation, "Dataset##{type} not suppored on ordered, limited datasets" if opts[:order] && opts[:limit] super if type == :truncate || @opts[:offset] end
Determine whether to add the COLLATE for LIKE arguments, based on the Database setting.
# File lib/sequel/adapters/shared/mssql.rb, line 950 def complex_expression_sql_like_args(args, collation) if db.like_without_collate args else args.map{|a| Sequel.lit(["(", collation], a)} end end
Use strict ISO-8601 format with T between date and time, since that is the format that is multilanguage and not DATEFORMAT dependent.
# File lib/sequel/adapters/shared/mssql.rb, line 961 def default_timestamp_format "'%Y-%m-%dT%H:%M:%S.%3N'" end
MSSQL supports FROM clauses in DELETE and UPDATE statements.
# File lib/sequel/adapters/shared/mssql.rb, line 972 def delete_from2_sql(sql) if joined_dataset? select_from_sql(sql) select_join_sql(sql) end end
Only include the primary table in the main delete clause
# File lib/sequel/adapters/shared/mssql.rb, line 966 def delete_from_sql(sql) sql << ' FROM ' source_list_append(sql, @opts[:from][0..0]) end
# File lib/sequel/adapters/shared/mssql.rb, line 980 def delete_output_sql(sql) output_sql(sql, :DELETED) end
There is no function on Microsoft SQL Server that does character length and respects trailing spaces (datalength respects trailing spaces, but counts bytes instead of characters). Use a hack to work around the trailing spaces issue.
# File lib/sequel/adapters/shared/mssql.rb, line 988 def emulate_function?(name) name == :char_length || name == :trim end
# File lib/sequel/adapters/shared/mssql.rb, line 992 def emulate_function_sql_append(sql, f) case f.name when :char_length literal_append(sql, SQL::Function.new(:len, Sequel.join([f.args.first, 'x'])) - 1) when :trim literal_append(sql, SQL::Function.new(:ltrim, SQL::Function.new(:rtrim, f.args.first))) end end
Microsoft SQL Server 2012+ has native support for offsets, but only for ordered datasets.
# File lib/sequel/adapters/shared/mssql.rb, line 1002 def emulate_offset_with_row_number? super && !(is_2012_or_later? && @opts[:order]) end
Return the first primary key for the current table. If this table has multiple primary keys, this will only return one of them. Used by #_import.
# File lib/sequel/adapters/shared/mssql.rb, line 1008 def first_primary_key @db.schema(self).map{|k, v| k if v[:primary_key] == true}.compact.first end
# File lib/sequel/adapters/shared/mssql.rb, line 1012 def insert_output_sql(sql) output_sql(sql, :INSERTED) end
Whether we are using SQL Server 2005 or later.
# File lib/sequel/adapters/shared/mssql.rb, line 935 def is_2005_or_later? server_version >= 9000000 end
Whether we are using SQL Server 2008 or later.
# File lib/sequel/adapters/shared/mssql.rb, line 940 def is_2008_or_later? server_version >= 10000000 end
Whether we are using SQL Server 2012 or later.
# File lib/sequel/adapters/shared/mssql.rb, line 945 def is_2012_or_later? server_version >= 11000000 end
Handle CROSS APPLY and OUTER APPLY JOIN types
# File lib/sequel/adapters/shared/mssql.rb, line 1018 def join_type_sql(join_type) case join_type when :cross_apply 'CROSS APPLY' when :outer_apply 'OUTER APPLY' else super end end
MSSQL uses a literal hexidecimal number for blob strings
# File lib/sequel/adapters/shared/mssql.rb, line 1030 def literal_blob_append(sql, v) sql << '0x' << v.unpack("H*").first end
Use YYYYmmdd format, since that's the only format that is multilanguage and not DATEFORMAT dependent.
# File lib/sequel/adapters/shared/mssql.rb, line 1036 def literal_date(v) v.strftime("'%Y%m%d'") end
Use 0 for false on MSSQL
# File lib/sequel/adapters/shared/mssql.rb, line 1041 def literal_false '0' end
Optionally use unicode string syntax for all strings. Don't double backslashes.
# File lib/sequel/adapters/shared/mssql.rb, line 1047 def literal_string_append(sql, v) sql << (mssql_unicode_strings ? "N'" : "'") sql << v.gsub("'", "''").gsub(/\\((?:\r\n)|\n)/, '\\\\\\\\\\1\\1') << "'" end
Use 1 for true on MSSQL
# File lib/sequel/adapters/shared/mssql.rb, line 1053 def literal_true '1' end
MSSQL 2008+ supports multiple rows in the VALUES clause, older versions can use UNION.
# File lib/sequel/adapters/shared/mssql.rb, line 1059 def multi_insert_sql_strategy is_2008_or_later? ? :values : :union end
# File lib/sequel/adapters/shared/mssql.rb, line 1063 def non_sql_option?(key) super || key == :disable_insert_output || key == :mssql_unicode_strings end
# File lib/sequel/adapters/shared/mssql.rb, line 1164 def output_list_sql(sql, output) sql << " OUTPUT " column_list_append(sql, output[:select_list]) if into = output[:into] sql << " INTO " identifier_append(sql, into) if column_list = output[:column_list] sql << ' (' source_list_append(sql, column_list) sql << ')' end end end
# File lib/sequel/adapters/shared/mssql.rb, line 1178 def output_returning_sql(sql, type, values) sql << " OUTPUT " if values.empty? literal_append(sql, SQL::ColumnAll.new(type)) else values = values.map do |v| case v when SQL::AliasedExpression Sequel.qualify(type, v.expression).as(v.alias) else Sequel.qualify(type, v) end end column_list_append(sql, values) end end
# File lib/sequel/adapters/shared/mssql.rb, line 1155 def output_sql(sql, type) return unless supports_output_clause? if output = @opts[:output] output_list_sql(sql, output) elsif values = @opts[:returning] output_returning_sql(sql, type, values) end end
MSSQL does not natively support NULLS FIRST/LAST.
# File lib/sequel/adapters/shared/mssql.rb, line 1196 def requires_emulating_nulls_first? true end
# File lib/sequel/adapters/shared/mssql.rb, line 1067 def select_into_sql(sql) if i = @opts[:into] sql << " INTO " identifier_append(sql, i) end end
MSSQL 2000 uses TOP N for limit. For MSSQL 2005+ TOP (N) is used to allow the limit to be a bound variable.
# File lib/sequel/adapters/shared/mssql.rb, line 1076 def select_limit_sql(sql) if l = @opts[:limit] return if is_2012_or_later? && @opts[:order] && @opts[:offset] shared_limit_sql(sql, l) end end
Handle dirty, skip locked, and for update locking
# File lib/sequel/adapters/shared/mssql.rb, line 1110 def select_lock_sql(sql) lock = @opts[:lock] skip_locked = @opts[:skip_locked] nowait = @opts[:nowait] for_update = lock == :update dirty = lock == :dirty lock_hint = for_update || dirty if lock_hint || skip_locked sql << " WITH (" if lock_hint sql << (for_update ? 'UPDLOCK' : 'NOLOCK') end if skip_locked || nowait sql << ', ' if lock_hint sql << (skip_locked ? "READPAST" : "NOWAIT") end sql << ')' else super end end
On 2012+ when there is an order with an offset, append the offset (and possible limit) at the end of the order clause.
# File lib/sequel/adapters/shared/mssql.rb, line 1138 def select_order_sql(sql) super if is_2012_or_later? && @opts[:order] if o = @opts[:offset] sql << " OFFSET " literal_append(sql, o) sql << " ROWS" if l = @opts[:limit] sql << " FETCH NEXT " literal_append(sql, l) sql << " ROWS ONLY" end end end end
MSSQL supports 100-nsec precision for time columns, but ruby by default only supports usec precision.
# File lib/sequel/adapters/shared/mssql.rb, line 1202 def sqltime_precision 6 end
# File lib/sequel/adapters/shared/mssql.rb, line 1102 def update_limit_sql(sql) if l = @opts[:limit] shared_limit_sql(sql, l) end end
Only include the primary table in the main update clause
# File lib/sequel/adapters/shared/mssql.rb, line 1214 def update_table_sql(sql) sql << ' ' source_list_append(sql, @opts[:from][0..0]) end
# File lib/sequel/adapters/shared/mssql.rb, line 1219 def uses_with_rollup? !is_2008_or_later? end