module Sequel::MSSQL::DatasetMethods
Constants
- CONSTANT_MAP
- EXTRACT_MAP
- LIMIT_ALL
Public Instance Methods
# File lib/sequel/adapters/shared/mssql.rb 550 def complex_expression_sql_append(sql, op, args) 551 case op 552 when :'||' 553 super(sql, :+, args) 554 when :LIKE, :"NOT LIKE" 555 super(sql, op, complex_expression_sql_like_args(args, " COLLATE Latin1_General_CS_AS)")) 556 when :ILIKE, :"NOT ILIKE" 557 super(sql, (op == :ILIKE ? :LIKE : :"NOT LIKE"), complex_expression_sql_like_args(args, " COLLATE Latin1_General_CI_AS)")) 558 when :<<, :>> 559 complex_expression_emulate_append(sql, op, args) 560 when :extract 561 part = args[0] 562 raise(Sequel::Error, "unsupported extract argument: #{part.inspect}") unless format = EXTRACT_MAP[part] 563 if part == :second 564 expr = args[1] 565 sql << "CAST((datepart(" << format.to_s << ', ' 566 literal_append(sql, expr) 567 sql << ') + datepart(ns, ' 568 literal_append(sql, expr) 569 sql << ")/1000000000.0) AS double precision)" 570 else 571 sql << "datepart(" << format.to_s << ', ' 572 literal_append(sql, args[1]) 573 sql << ')' 574 end 575 else 576 super 577 end 578 end
Uses CROSS APPLY to join the given table into the current dataset.
# File lib/sequel/adapters/shared/mssql.rb 590 def cross_apply(table) 591 join_table(:cross_apply, table) 592 end
Disable the use of INSERT OUTPUT
# File lib/sequel/adapters/shared/mssql.rb 595 def disable_insert_output 596 clone(:disable_insert_output=>true) 597 end
MSSQL
treats [] as a metacharacter in LIKE expresions.
# File lib/sequel/adapters/shared/mssql.rb 600 def escape_like(string) 601 string.gsub(/[\\%_\[\]]/){|m| "\\#{m}"} 602 end
MSSQL
uses the CONTAINS keyword for full text search
# File lib/sequel/adapters/shared/mssql.rb 605 def full_text_search(cols, terms, opts = OPTS) 606 terms = "\"#{terms.join('" OR "')}\"" if terms.is_a?(Array) 607 where(Sequel.lit("CONTAINS (?, ?)", cols, terms)) 608 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 613 def insert_select(*values) 614 return unless supports_insert_select? 615 with_sql_first(insert_select_sql(*values)) || false 616 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 620 def insert_select_sql(*values) 621 ds = (opts[:output] || opts[:returning]) ? self : output(nil, [SQL::ColumnAll.new(:inserted)]) 622 ds.insert_sql(*values) 623 end
Specify a table for a SELECT … INTO query.
# File lib/sequel/adapters/shared/mssql.rb 626 def into(table) 627 clone(:into => table) 628 end
Use the database’s mssql_unicode_strings
setting if the dataset hasn’t overridden it.
# File lib/sequel/adapters/shared/mssql.rb 541 def mssql_unicode_strings 542 opts.has_key?(:mssql_unicode_strings) ? opts[:mssql_unicode_strings] : db.mssql_unicode_strings 543 end
Allows you to do a dirty read of uncommitted data using WITH (NOLOCK).
# File lib/sequel/adapters/shared/mssql.rb 631 def nolock 632 lock_style(:dirty) 633 end
Uses OUTER APPLY to join the given table into the current dataset.
# File lib/sequel/adapters/shared/mssql.rb 636 def outer_apply(table) 637 join_table(:outer_apply, table) 638 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 652 def output(into, values) 653 raise(Error, "SQL Server versions 2000 and earlier do not support the OUTPUT clause") unless supports_output_clause? 654 output = {} 655 case values 656 when Hash 657 output[:column_list], output[:select_list] = values.keys, values.values 658 when Array 659 output[:select_list] = values 660 end 661 output[:into] = into 662 clone(:output => output) 663 end
MSSQL
uses [] to quote identifiers.
# File lib/sequel/adapters/shared/mssql.rb 666 def quoted_identifier_append(sql, name) 667 sql << '[' << name.to_s.gsub(/\]/, ']]') << ']' 668 end
Emulate RETURNING using the output clause. This only handles values that are simple column references.
# File lib/sequel/adapters/shared/mssql.rb 671 def returning(*values) 672 values = values.map do |v| 673 unless r = unqualified_column_for(v) 674 raise(Error, "cannot emulate RETURNING via OUTPUT for value: #{v.inspect}") 675 end 676 r 677 end 678 clone(:returning=>values) 679 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.
Sequel::EmulateOffsetWithRowNumber#select_sql
# File lib/sequel/adapters/shared/mssql.rb 685 def select_sql 686 if @opts[:offset] 687 raise(Error, "Using with_ties is not supported with an offset on Microsoft SQL Server") if @opts[:limit_with_ties] 688 return order(1).select_sql if is_2012_or_later? && !@opts[:order] 689 end 690 super 691 end
The version of the database server.
# File lib/sequel/adapters/shared/mssql.rb 694 def server_version 695 db.server_version(@opts[:server]) 696 end
# File lib/sequel/adapters/shared/mssql.rb 698 def supports_cte?(type=:select) 699 is_2005_or_later? 700 end
MSSQL
2005+ supports GROUP BY CUBE.
# File lib/sequel/adapters/shared/mssql.rb 703 def supports_group_cube? 704 is_2005_or_later? 705 end
MSSQL
2005+ supports GROUP BY ROLLUP
# File lib/sequel/adapters/shared/mssql.rb 708 def supports_group_rollup? 709 is_2005_or_later? 710 end
MSSQL
2008+ supports GROUPING SETS
# File lib/sequel/adapters/shared/mssql.rb 713 def supports_grouping_sets? 714 is_2008_or_later? 715 end
MSSQL
supports insert_select
via the OUTPUT clause.
# File lib/sequel/adapters/shared/mssql.rb 718 def supports_insert_select? 719 supports_output_clause? && !opts[:disable_insert_output] 720 end
MSSQL
2005+ supports INTERSECT and EXCEPT
# File lib/sequel/adapters/shared/mssql.rb 723 def supports_intersect_except? 724 is_2005_or_later? 725 end
MSSQL
does not support IS TRUE
# File lib/sequel/adapters/shared/mssql.rb 728 def supports_is_true? 729 false 730 end
MSSQL
doesn’t support JOIN USING
# File lib/sequel/adapters/shared/mssql.rb 733 def supports_join_using? 734 false 735 end
MSSQL
2005+ supports modifying joined datasets
# File lib/sequel/adapters/shared/mssql.rb 738 def supports_modifying_joins? 739 is_2005_or_later? 740 end
MSSQL
does not support multiple columns for the IN/NOT IN operators
# File lib/sequel/adapters/shared/mssql.rb 743 def supports_multiple_column_in? 744 false 745 end
MSSQL
supports NOWAIT.
# File lib/sequel/adapters/shared/mssql.rb 748 def supports_nowait? 749 true 750 end
MSSQL
2005+ supports the OUTPUT clause.
# File lib/sequel/adapters/shared/mssql.rb 758 def supports_output_clause? 759 is_2005_or_later? 760 end
MSSQL
2005+ can emulate RETURNING via the OUTPUT clause.
# File lib/sequel/adapters/shared/mssql.rb 763 def supports_returning?(type) 764 supports_insert_select? 765 end
MSSQL
uses READPAST to skip locked rows.
# File lib/sequel/adapters/shared/mssql.rb 768 def supports_skip_locked? 769 true 770 end
MSSQL
cannot use WHERE 1.
# File lib/sequel/adapters/shared/mssql.rb 778 def supports_where_true? 779 false 780 end
MSSQL
2005+ supports window functions
# File lib/sequel/adapters/shared/mssql.rb 773 def supports_window_functions? 774 true 775 end
Return a cloned dataset with the mssql_unicode_strings
option set.
# File lib/sequel/adapters/shared/mssql.rb 546 def with_mssql_unicode_strings(v) 547 clone(:mssql_unicode_strings=>v) 548 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 784 def with_ties 785 clone(:limit_with_ties=>true) 786 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 794 def _import(columns, values, opts=OPTS) 795 if opts[:return] == :primary_key && !@opts[:output] 796 output(nil, [SQL::QualifiedIdentifier.new(:inserted, first_primary_key)])._import(columns, values, opts) 797 elsif @opts[:output] 798 statements = multi_insert_sql(columns, values) 799 ds = naked 800 @db.transaction(opts.merge(:server=>@opts[:server])) do 801 statements.map{|st| ds.with_sql(st)} 802 end.first.map{|v| v.length == 1 ? v.values.first : v} 803 else 804 super 805 end 806 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 815 def compound_from_self 816 if @opts[:offset] && !@opts[:limit] && !is_2012_or_later? 817 clone(:limit=>LIMIT_ALL).from_self 818 elsif @opts[:order] && !(@opts[:sql] || @opts[:limit] || @opts[:offset]) 819 unordered 820 else 821 super 822 end 823 end
Private Instance Methods
MSSQL
does not allow ordering in sub-clauses unless TOP (limit) is specified
# File lib/sequel/adapters/shared/mssql.rb 828 def aggregate_dataset 829 (options_overlap(Sequel::Dataset::COUNT_FROM_SELF_OPTS) && !options_overlap([:limit])) ? unordered.from_self : super 830 end
Allow update and delete for unordered, limited datasets only.
# File lib/sequel/adapters/shared/mssql.rb 833 def check_not_limited!(type) 834 return if @opts[:skip_limit_check] && type != :truncate 835 raise Sequel::InvalidOperation, "Dataset##{type} not suppored on ordered, limited datasets" if opts[:order] && opts[:limit] 836 super if type == :truncate || @opts[:offset] 837 end
Determine whether to add the COLLATE for LIKE arguments, based on the Database
setting.
# File lib/sequel/adapters/shared/mssql.rb 855 def complex_expression_sql_like_args(args, collation) 856 if db.like_without_collate 857 args 858 else 859 args.map{|a| Sequel.lit(["(", collation], a)} 860 end 861 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 866 def default_timestamp_format 867 "'%Y-%m-%dT%H:%M:%S%N%z'" 868 end
MSSQL
supports FROM clauses in DELETE and UPDATE statements.
# File lib/sequel/adapters/shared/mssql.rb 877 def delete_from2_sql(sql) 878 if joined_dataset? 879 select_from_sql(sql) 880 select_join_sql(sql) 881 end 882 end
Only include the primary table in the main delete clause
# File lib/sequel/adapters/shared/mssql.rb 871 def delete_from_sql(sql) 872 sql << ' FROM ' 873 source_list_append(sql, @opts[:from][0..0]) 874 end
# File lib/sequel/adapters/shared/mssql.rb 885 def delete_output_sql(sql) 886 output_sql(sql, :DELETED) 887 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 893 def emulate_function?(name) 894 name == :char_length || name == :trim 895 end
# File lib/sequel/adapters/shared/mssql.rb 897 def emulate_function_sql_append(sql, f) 898 case f.name 899 when :char_length 900 literal_append(sql, SQL::Function.new(:len, Sequel.join([f.args.first, 'x'])) - 1) 901 when :trim 902 literal_append(sql, SQL::Function.new(:ltrim, SQL::Function.new(:rtrim, f.args.first))) 903 end 904 end
Microsoft SQL
Server 2012+ has native support for offsets, but only for ordered datasets.
Sequel::EmulateOffsetWithRowNumber#emulate_offset_with_row_number?
# File lib/sequel/adapters/shared/mssql.rb 907 def emulate_offset_with_row_number? 908 super && !(is_2012_or_later? && @opts[:order]) 909 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 913 def first_primary_key 914 @db.schema(self).map{|k, v| k if v[:primary_key] == true}.compact.first 915 end
# File lib/sequel/adapters/shared/mssql.rb 917 def insert_output_sql(sql) 918 output_sql(sql, :INSERTED) 919 end
Whether we are using SQL
Server 2005 or later.
# File lib/sequel/adapters/shared/mssql.rb 840 def is_2005_or_later? 841 server_version >= 9000000 842 end
Whether we are using SQL
Server 2008 or later.
# File lib/sequel/adapters/shared/mssql.rb 845 def is_2008_or_later? 846 server_version >= 10000000 847 end
Whether we are using SQL
Server 2012 or later.
# File lib/sequel/adapters/shared/mssql.rb 850 def is_2012_or_later? 851 server_version >= 11000000 852 end
Handle CROSS APPLY and OUTER APPLY JOIN types
# File lib/sequel/adapters/shared/mssql.rb 923 def join_type_sql(join_type) 924 case join_type 925 when :cross_apply 926 'CROSS APPLY' 927 when :outer_apply 928 'OUTER APPLY' 929 else 930 super 931 end 932 end
MSSQL
uses a literal hexidecimal number for blob strings
# File lib/sequel/adapters/shared/mssql.rb 935 def literal_blob_append(sql, v) 936 sql << '0x' << v.unpack("H*").first 937 end
Use YYYYmmdd format, since that’s the only format that is multilanguage and not DATEFORMAT dependent.
# File lib/sequel/adapters/shared/mssql.rb 941 def literal_date(v) 942 v.strftime("'%Y%m%d'") 943 end
Use 0 for false on MSSQL
# File lib/sequel/adapters/shared/mssql.rb 946 def literal_false 947 '0' 948 end
Optionally use unicode string syntax for all strings. Don’t double backslashes.
# File lib/sequel/adapters/shared/mssql.rb 952 def literal_string_append(sql, v) 953 sql << (mssql_unicode_strings ? "N'" : "'") 954 sql << v.gsub("'", "''").gsub(/\\((?:\r\n)|\n)/, '\\\\\\\\\\1\\1') << "'" 955 end
Use 1 for true on MSSQL
# File lib/sequel/adapters/shared/mssql.rb 958 def literal_true 959 '1' 960 end
MSSQL
2008+ supports multiple rows in the VALUES clause, older versions can use UNION.
# File lib/sequel/adapters/shared/mssql.rb 964 def multi_insert_sql_strategy 965 is_2008_or_later? ? :values : :union 966 end
# File lib/sequel/adapters/shared/mssql.rb 968 def non_sql_option?(key) 969 super || key == :disable_insert_output || key == :mssql_unicode_strings 970 end
# File lib/sequel/adapters/shared/mssql.rb 1069 def output_list_sql(sql, output) 1070 sql << " OUTPUT " 1071 column_list_append(sql, output[:select_list]) 1072 if into = output[:into] 1073 sql << " INTO " 1074 identifier_append(sql, into) 1075 if column_list = output[:column_list] 1076 sql << ' (' 1077 source_list_append(sql, column_list) 1078 sql << ')' 1079 end 1080 end 1081 end
# File lib/sequel/adapters/shared/mssql.rb 1083 def output_returning_sql(sql, type, values) 1084 sql << " OUTPUT " 1085 if values.empty? 1086 literal_append(sql, SQL::ColumnAll.new(type)) 1087 else 1088 values = values.map do |v| 1089 case v 1090 when SQL::AliasedExpression 1091 Sequel.qualify(type, v.expression).as(v.alias) 1092 else 1093 Sequel.qualify(type, v) 1094 end 1095 end 1096 column_list_append(sql, values) 1097 end 1098 end
# File lib/sequel/adapters/shared/mssql.rb 1060 def output_sql(sql, type) 1061 return unless supports_output_clause? 1062 if output = @opts[:output] 1063 output_list_sql(sql, output) 1064 elsif values = @opts[:returning] 1065 output_returning_sql(sql, type, values) 1066 end 1067 end
MSSQL
does not natively support NULLS FIRST/LAST.
# File lib/sequel/adapters/shared/mssql.rb 1101 def requires_emulating_nulls_first? 1102 true 1103 end
# File lib/sequel/adapters/shared/mssql.rb 972 def select_into_sql(sql) 973 if i = @opts[:into] 974 sql << " INTO " 975 identifier_append(sql, i) 976 end 977 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 981 def select_limit_sql(sql) 982 if l = @opts[:limit] 983 return if is_2012_or_later? && @opts[:order] && @opts[:offset] 984 shared_limit_sql(sql, l) 985 end 986 end
Handle dirty, skip locked, and for update locking
# File lib/sequel/adapters/shared/mssql.rb 1015 def select_lock_sql(sql) 1016 lock = @opts[:lock] 1017 skip_locked = @opts[:skip_locked] 1018 nowait = @opts[:nowait] 1019 for_update = lock == :update 1020 dirty = lock == :dirty 1021 lock_hint = for_update || dirty 1022 1023 if lock_hint || skip_locked 1024 sql << " WITH (" 1025 1026 if lock_hint 1027 sql << (for_update ? 'UPDLOCK' : 'NOLOCK') 1028 end 1029 1030 if skip_locked || nowait 1031 sql << ', ' if lock_hint 1032 sql << (skip_locked ? "READPAST" : "NOWAIT") 1033 end 1034 1035 sql << ')' 1036 else 1037 super 1038 end 1039 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 1043 def select_order_sql(sql) 1044 super 1045 if is_2012_or_later? && @opts[:order] 1046 if o = @opts[:offset] 1047 sql << " OFFSET " 1048 literal_append(sql, o) 1049 sql << " ROWS" 1050 1051 if l = @opts[:limit] 1052 sql << " FETCH NEXT " 1053 literal_append(sql, l) 1054 sql << " ROWS ONLY" 1055 end 1056 end 1057 end 1058 end
MSSQL
supports 100-nsec precision for time columns, but ruby by default only supports usec precision.
# File lib/sequel/adapters/shared/mssql.rb 1107 def sqltime_precision 1108 6 1109 end
# File lib/sequel/adapters/shared/mssql.rb 1007 def update_limit_sql(sql) 1008 if l = @opts[:limit] 1009 shared_limit_sql(sql, l) 1010 end 1011 end
Only include the primary table in the main update clause
# File lib/sequel/adapters/shared/mssql.rb 1119 def update_table_sql(sql) 1120 sql << ' ' 1121 source_list_append(sql, @opts[:from][0..0]) 1122 end
# File lib/sequel/adapters/shared/mssql.rb 1124 def uses_with_rollup? 1125 !is_2008_or_later? 1126 end