module Sequel::SQLite::DatasetMethods
Constants
- CONSTANT_MAP
- EXTRACT_MAP
- INSERT_CONFLICT_RESOLUTIONS
-
The allowed values for
insert_conflict
Public Instance Methods
Source
# File lib/sequel/adapters/shared/sqlite.rb 620 def cast_sql_append(sql, expr, type) 621 if type == Time or type == DateTime 622 sql << "datetime(" 623 literal_append(sql, expr) 624 sql << ')' 625 elsif type == Date 626 sql << "date(" 627 literal_append(sql, expr) 628 sql << ')' 629 else 630 super 631 end 632 end
Source
# File lib/sequel/adapters/shared/sqlite.rb 636 def complex_expression_sql_append(sql, op, args) 637 case op 638 when :"NOT LIKE", :"NOT ILIKE" 639 sql << 'NOT ' 640 complex_expression_sql_append(sql, (op == :"NOT ILIKE" ? :ILIKE : :LIKE), args) 641 when :^ 642 complex_expression_arg_pairs_append(sql, args){|a, b| Sequel.lit(["((~(", " & ", ")) & (", " | ", "))"], a, b, a, b)} 643 when :** 644 unless (exp = args[1]).is_a?(Integer) 645 raise(Sequel::Error, "can only emulate exponentiation on SQLite if exponent is an integer, given #{exp.inspect}") 646 end 647 case exp 648 when 0 649 sql << '1' 650 else 651 sql << '(' 652 arg = args[0] 653 if exp < 0 654 invert = true 655 exp = exp.abs 656 sql << '(1.0 / (' 657 end 658 (exp - 1).times do 659 literal_append(sql, arg) 660 sql << " * " 661 end 662 literal_append(sql, arg) 663 sql << ')' 664 if invert 665 sql << "))" 666 end 667 end 668 when :extract 669 part = args[0] 670 raise(Sequel::Error, "unsupported extract argument: #{part.inspect}") unless format = EXTRACT_MAP[part] 671 sql << "CAST(strftime(" << format << ', ' 672 literal_append(sql, args[1]) 673 sql << ') AS ' << (part == :second ? 'NUMERIC' : 'INTEGER') << ')' 674 else 675 super 676 end 677 end
SQLite doesn’t support a NOT LIKE b, you need to use NOT (a LIKE b). It doesn’t support xor, power, or the extract function natively, so those have to be emulated.
Source
# File lib/sequel/adapters/shared/sqlite.rb 681 def constant_sql_append(sql, constant) 682 if (c = CONSTANT_MAP[constant]) && !db.current_timestamp_utc 683 sql << c 684 else 685 super 686 end 687 end
SQLite has CURRENT_TIMESTAMP and related constants in UTC instead of in localtime, so convert those constants to local time.
Source
# File lib/sequel/adapters/shared/sqlite.rb 692 def delete(&block) 693 @opts[:where] ? super : where(1=>1).delete(&block) 694 end
SQLite performs a TRUNCATE style DELETE if no filter is specified. Since we want to always return the count of records, add a condition that is always true and then delete.
Source
# File lib/sequel/adapters/shared/sqlite.rb 697 def empty? 698 return false if @opts[:values] 699 super 700 end
Always return false when using VALUES
Source
# File lib/sequel/adapters/shared/sqlite.rb 705 def explain(opts=nil) 706 # Load the PrettyTable class, needed for explain output 707 Sequel.extension(:_pretty_table) unless defined?(Sequel::PrettyTable) 708 709 keyword = (opts && opts[:query_plan]) ? "EXPLAIN QUERY PLAN" : "EXPLAIN" 710 ds = db.send(:metadata_dataset).clone(:sql=>"#{keyword} #{select_sql}".freeze) 711 rows = ds.all 712 Sequel::PrettyTable.string(rows, ds.columns) 713 end
Return a string specifying a query explanation for a SELECT of the current dataset. Options:
- :query_plan
-
Use EXPLAIN QUERY PLAN instead of EXPLAIN if true.
Source
# File lib/sequel/adapters/shared/sqlite.rb 716 def having(*cond) 717 raise(InvalidOperation, "Can only specify a HAVING clause on a grouped dataset") if !@opts[:group] && db.sqlite_version < 33900 718 super 719 end
HAVING requires GROUP BY on SQLite
Source
# File lib/sequel/adapters/shared/sqlite.rb 794 def insert_conflict(opts = :ignore) 795 case opts 796 when Symbol, String 797 unless INSERT_CONFLICT_RESOLUTIONS.include?(opts.to_s.upcase) 798 raise Error, "Invalid symbol or string passed to Dataset#insert_conflict: #{opts.inspect}. The allowed values are: :rollback, :abort, :fail, :ignore, or :replace" 799 end 800 clone(:insert_conflict => opts) 801 when Hash 802 clone(:insert_on_conflict => opts) 803 else 804 raise Error, "Invalid value passed to Dataset#insert_conflict: #{opts.inspect}, should use a symbol or a hash" 805 end 806 end
Handle uniqueness violations when inserting, by using a specified resolution algorithm. With no options, uses INSERT OR REPLACE. SQLite supports the following conflict resolution algorithms: ROLLBACK, ABORT, FAIL, IGNORE and REPLACE.
On SQLite 3.24.0+, you can pass a hash to use an ON CONFLICT clause. With out :update option, uses ON CONFLICT DO NOTHING. Options:
- :conflict_where
-
The index filter, when using a partial index to determine uniqueness.
- :target
-
The column name or expression to handle uniqueness violations on.
- :update
-
A hash of columns and values to set. Uses ON CONFLICT DO UPDATE.
- :update_where
-
A WHERE condition to use for the update.
Examples:
DB[:table].insert_conflict.insert(a: 1, b: 2) # INSERT OR IGNORE INTO TABLE (a, b) VALUES (1, 2) DB[:table].insert_conflict(:replace).insert(a: 1, b: 2) # INSERT OR REPLACE INTO TABLE (a, b) VALUES (1, 2) DB[:table].insert_conflict({}).insert(a: 1, b: 2) # INSERT INTO TABLE (a, b) VALUES (1, 2) # ON CONFLICT DO NOTHING DB[:table].insert_conflict(target: :a).insert(a: 1, b: 2) # INSERT INTO TABLE (a, b) VALUES (1, 2) # ON CONFLICT (a) DO NOTHING DB[:table].insert_conflict(target: :a, conflict_where: {c: true}).insert(a: 1, b: 2) # INSERT INTO TABLE (a, b) VALUES (1, 2) # ON CONFLICT (a) WHERE (c IS TRUE) DO NOTHING DB[:table].insert_conflict(target: :a, update: {b: Sequel[:excluded][:b]}).insert(a: 1, b: 2) # INSERT INTO TABLE (a, b) VALUES (1, 2) # ON CONFLICT (a) DO UPDATE SET b = excluded.b DB[:table].insert_conflict(target: :a, update: {b: Sequel[:excluded][:b]}, update_where: {Sequel[:table][:status_id] => 1}).insert(a: 1, b: 2) # INSERT INTO TABLE (a, b) VALUES (1, 2) # ON CONFLICT (a) DO UPDATE SET b = excluded.b WHERE (table.status_id = 1)
Source
# File lib/sequel/adapters/shared/sqlite.rb 813 def insert_ignore 814 insert_conflict(:ignore) 815 end
Ignore uniqueness/exclusion violations when inserting, using INSERT OR IGNORE. Exists mostly for compatibility to MySQL’s insert_ignore. Example:
DB[:table].insert_ignore.insert(a: 1, b: 2) # INSERT OR IGNORE INTO TABLE (a, b) VALUES (1, 2)
Source
# File lib/sequel/adapters/shared/sqlite.rb 723 def insert_select(*values) 724 return unless supports_insert_select? 725 # Handle case where query does not return a row 726 server?(:default).with_sql_first(insert_select_sql(*values)) || false 727 end
Support insert select for associations, so that the model code can use returning instead of a separate query.
Source
# File lib/sequel/adapters/shared/sqlite.rb 731 def insert_select_sql(*values) 732 ds = opts[:returning] ? self : returning 733 ds.insert_sql(*values) 734 end
The SQL to use for an insert_select, adds a RETURNING clause to the insert unless the RETURNING clause is already present.
Source
# File lib/sequel/adapters/shared/sqlite.rb 737 def quoted_identifier_append(sql, c) 738 sql << '`' << c.to_s.gsub('`', '``') << '`' 739 end
SQLite uses the nonstandard ‘ (backtick) for quoting identifiers.
Source
# File lib/sequel/adapters/shared/sqlite.rb 818 def returning(*values) 819 return super if values.empty? 820 raise Error, "RETURNING is not supported on #{db.database_type}" unless supports_returning?(:insert) 821 clone(:returning=>_returning_values(values).freeze) 822 end
Automatically add aliases to RETURNING values to work around SQLite bug.
Source
# File lib/sequel/adapters/shared/sqlite.rb 745 def select(*cols) 746 if ((f = @opts[:from]) && f.any?{|t| t.is_a?(Dataset) || (t.is_a?(SQL::AliasedExpression) && t.expression.is_a?(Dataset))}) || ((j = @opts[:join]) && j.any?{|t| t.table.is_a?(Dataset)}) 747 super(*cols.map{|c| alias_qualified_column(c)}) 748 else 749 super 750 end 751 end
When a qualified column is selected on SQLite and the qualifier is a subselect, the column name used is the full qualified name (including the qualifier) instead of just the column name. To get correct column names, you must use an alias.
Source
# File lib/sequel/adapters/shared/sqlite.rb 825 def supports_cte?(type=:select) 826 db.sqlite_version >= 30803 827 end
SQLite 3.8.3+ supports common table expressions.
Source
# File lib/sequel/adapters/shared/sqlite.rb 830 def supports_cte_in_subqueries? 831 supports_cte? 832 end
SQLite supports CTEs in subqueries if it supports CTEs.
Source
# File lib/sequel/adapters/shared/sqlite.rb 840 def supports_deleting_joins? 841 false 842 end
SQLite does not support deleting from a joined dataset
Source
# File lib/sequel/adapters/shared/sqlite.rb 835 def supports_derived_column_lists? 836 false 837 end
SQLite does not support table aliases with column aliases
Source
# File lib/sequel/adapters/shared/sqlite.rb 845 def supports_intersect_except_all? 846 false 847 end
SQLite does not support INTERSECT ALL or EXCEPT ALL
Source
# File lib/sequel/adapters/shared/sqlite.rb 850 def supports_is_true? 851 false 852 end
SQLite does not support IS TRUE
Source
# File lib/sequel/adapters/shared/sqlite.rb 855 def supports_modifying_joins? 856 db.sqlite_version >= 33300 857 end
SQLite 3.33.0 supports modifying joined datasets
Source
# File lib/sequel/adapters/shared/sqlite.rb 860 def supports_multiple_column_in? 861 false 862 end
SQLite does not support multiple columns for the IN/NOT IN operators
Source
# File lib/sequel/adapters/shared/sqlite.rb 865 def supports_returning?(_) 866 db.sqlite_version >= 33500 867 end
SQLite 3.35.0 supports RETURNING on INSERT/UPDATE/DELETE.
Source
# File lib/sequel/adapters/shared/sqlite.rb 872 def supports_timestamp_timezones? 873 db.use_timestamp_timezones? 874 end
Source
# File lib/sequel/adapters/shared/sqlite.rb 877 def supports_where_true? 878 false 879 end
SQLite cannot use WHERE ‘t’.
Source
# File lib/sequel/adapters/shared/sqlite.rb 882 def supports_window_clause? 883 db.sqlite_version >= 32800 884 end
SQLite 3.28+ supports the WINDOW clause.
Source
# File lib/sequel/adapters/shared/sqlite.rb 895 def supports_window_function_frame_option?(option) 896 db.sqlite_version >= 32800 ? true : super 897 end
Source
# File lib/sequel/adapters/shared/sqlite.rb 890 def supports_window_functions? 891 db.sqlite_version >= 32600 892 end
Private Instance Methods
Source
# File lib/sequel/adapters/shared/sqlite.rb 902 def _returning_values(values) 903 values.map do |v| 904 case v 905 when Symbol 906 _, c, a = split_symbol(v) 907 a ? v : Sequel.as(v, c) 908 when SQL::Identifier, SQL::QualifiedIdentifier 909 Sequel.as(v, unqualified_column_for(v)) 910 else 911 v 912 end 913 end 914 end
Add aliases to symbols and identifiers to work around SQLite bug.
Source
# File lib/sequel/adapters/shared/sqlite.rb 1074 def _truncate_sql(table) 1075 "DELETE FROM #{table}" 1076 end
SQLite treats a DELETE with no WHERE clause as a TRUNCATE
Source
# File lib/sequel/adapters/shared/sqlite.rb 917 def aggregate_dataset_use_from_self? 918 super || @opts[:values] 919 end
Use from_self for aggregate dataset using VALUES.
Source
# File lib/sequel/adapters/shared/sqlite.rb 930 def alias_qualified_column(col) 931 case col 932 when Symbol 933 t, c, a = split_symbol(col) 934 if t && !a 935 alias_qualified_column(SQL::QualifiedIdentifier.new(t, c)) 936 else 937 col 938 end 939 when SQL::QualifiedIdentifier 940 SQL::AliasedExpression.new(col, col.column) 941 else 942 col 943 end 944 end
If col is a qualified column, alias it to the same as the column name
Source
# File lib/sequel/adapters/shared/sqlite.rb 922 def as_sql_append(sql, aliaz, column_aliases=nil) 923 raise Error, "sqlite does not support derived column lists" if column_aliases 924 aliaz = aliaz.value if aliaz.is_a?(SQL::Identifier) 925 sql << ' AS ' 926 literal_append(sql, aliaz.to_s) 927 end
SQLite uses string literals instead of identifiers in AS clauses.
Source
# File lib/sequel/adapters/shared/sqlite.rb 947 def check_insert_allowed! 948 raise(InvalidOperation, "Grouped datasets cannot be modified") if opts[:group] 949 raise(InvalidOperation, "Joined datasets cannot be modified") if joined_dataset? 950 end
Raise an InvalidOperation exception if insert is not allowed for this dataset.
Source
# File lib/sequel/adapters/shared/sqlite.rb 954 def default_import_slice 955 500 956 end
SQLite supports a maximum of 500 rows in a VALUES clause.
Source
# File lib/sequel/adapters/shared/sqlite.rb 959 def default_timestamp_format 960 db.use_timestamp_timezones? ? "'%Y-%m-%d %H:%M:%S.%6N%z'" : super 961 end
The strftime format to use when literalizing the time.
Source
# File lib/sequel/adapters/shared/sqlite.rb 964 def identifier_list(columns) 965 columns.map{|i| quote_identifier(i)}.join(', ') 966 end
SQL fragment specifying a list of identifiers
Source
# File lib/sequel/adapters/shared/sqlite.rb 969 def insert_conflict_sql(sql) 970 if resolution = @opts[:insert_conflict] 971 sql << " OR " << resolution.to_s.upcase 972 end 973 end
Add OR clauses to SQLite INSERT statements
Source
# File lib/sequel/adapters/shared/sqlite.rb 976 def insert_on_conflict_sql(sql) 977 if opts = @opts[:insert_on_conflict] 978 sql << " ON CONFLICT" 979 980 if target = opts[:constraint] 981 sql << " ON CONSTRAINT " 982 identifier_append(sql, target) 983 elsif target = opts[:target] 984 sql << ' ' 985 identifier_append(sql, Array(target)) 986 if conflict_where = opts[:conflict_where] 987 sql << " WHERE " 988 literal_append(sql, conflict_where) 989 end 990 end 991 992 if values = opts[:update] 993 sql << " DO UPDATE SET " 994 update_sql_values_hash(sql, values) 995 if update_where = opts[:update_where] 996 sql << " WHERE " 997 literal_append(sql, update_where) 998 end 999 else 1000 sql << " DO NOTHING" 1001 end 1002 end 1003 end
Add ON CONFLICT clause if it should be used
Source
# File lib/sequel/adapters/shared/sqlite.rb 1006 def literal_blob_append(sql, v) 1007 sql << "X'" << v.unpack("H*").first << "'" 1008 end
SQLite uses a preceding X for hex escaping strings
Source
# File lib/sequel/adapters/shared/sqlite.rb 1011 def literal_false 1012 @db.integer_booleans ? '0' : "'f'" 1013 end
Respect the database integer_booleans setting, using 0 or ‘f’.
Source
# File lib/sequel/adapters/shared/sqlite.rb 1016 def literal_true 1017 @db.integer_booleans ? '1' : "'t'" 1018 end
Respect the database integer_booleans setting, using 1 or ‘t’.
Source
# File lib/sequel/adapters/shared/sqlite.rb 1022 def multi_insert_sql_strategy 1023 db.sqlite_version >= 30711 ? :values : :union 1024 end
SQLite only supporting multiple rows in the VALUES clause starting in 3.7.11. On older versions, fallback to using a UNION.
Source
# File lib/sequel/adapters/shared/sqlite.rb 1027 def native_function_name(emulated_function) 1028 if emulated_function == :char_length 1029 'length' 1030 else 1031 super 1032 end 1033 end
Emulate the char_length function with length
Source
# File lib/sequel/adapters/shared/sqlite.rb 1036 def requires_emulating_nulls_first? 1037 db.sqlite_version < 33000 1038 end
SQLite supports NULLS FIRST/LAST natively in 3.30+.
Source
# File lib/sequel/adapters/shared/sqlite.rb 1043 def select_lock_sql(sql) 1044 super unless @opts[:lock] == :update 1045 end
SQLite does not support FOR UPDATE, but silently ignore it instead of raising an error for compatibility with other databases.
Source
# File lib/sequel/adapters/shared/sqlite.rb 1047 def select_only_offset_sql(sql) 1048 sql << " LIMIT -1 OFFSET " 1049 literal_append(sql, @opts[:offset]) 1050 end
Source
# File lib/sequel/adapters/shared/sqlite.rb 1053 def select_values_sql(sql) 1054 sql << "VALUES " 1055 expression_list_append(sql, opts[:values]) 1056 end
Support VALUES clause instead of the SELECT clause to return rows.
Source
# File lib/sequel/adapters/shared/sqlite.rb 1059 def supports_cte_in_compounds? 1060 false 1061 end
SQLite does not support CTEs directly inside UNION/INTERSECT/EXCEPT.
Source
# File lib/sequel/adapters/shared/sqlite.rb 1064 def supports_filtered_aggregates? 1065 db.sqlite_version >= 33000 1066 end
SQLite 3.30 supports the FILTER clause for aggregate functions.
Source
# File lib/sequel/adapters/shared/sqlite.rb 1069 def supports_quoted_function_names? 1070 true 1071 end
SQLite supports quoted function names.
Source
# File lib/sequel/adapters/shared/sqlite.rb 1079 def update_from_sql(sql) 1080 if(from = @opts[:from][1..-1]).empty? 1081 raise(Error, 'Need multiple FROM tables if updating/deleting a dataset with JOINs') if @opts[:join] 1082 else 1083 sql << ' FROM ' 1084 source_list_append(sql, from) 1085 select_join_sql(sql) 1086 end 1087 end
Use FROM to specify additional tables in an update query
Source
# File lib/sequel/adapters/shared/sqlite.rb 1090 def update_table_sql(sql) 1091 sql << ' ' 1092 source_list_append(sql, @opts[:from][0..0]) 1093 end
Only include the primary table in the main update clause