Methods
Public Instance
- cast_sql_append
- complex_expression_sql_append
- constant_sql_append
- delete
- empty?
- explain
- having
- insert_conflict
- insert_ignore
- insert_select
- insert_select_sql
- quoted_identifier_append
- returning
- select
- supports_cte?
- supports_cte_in_subqueries?
- supports_deleting_joins?
- supports_derived_column_lists?
- supports_intersect_except_all?
- supports_is_true?
- supports_modifying_joins?
- supports_multiple_column_in?
- supports_returning?
- supports_timestamp_timezones?
- supports_where_true?
- supports_window_clause?
- supports_window_function_frame_option?
- supports_window_functions?
Included modules
Constants
| CONSTANT_MAP | = | {:CURRENT_DATE=>"date(CURRENT_TIMESTAMP, 'localtime')".freeze, :CURRENT_TIMESTAMP=>"datetime(CURRENT_TIMESTAMP, 'localtime')".freeze, :CURRENT_TIME=>"time(CURRENT_TIMESTAMP, 'localtime')".freeze}.freeze | ||
| EXTRACT_MAP | = | {:year=>"'%Y'", :month=>"'%m'", :day=>"'%d'", :hour=>"'%H'", :minute=>"'%M'", :second=>"'%f'"}.freeze | ||
| INSERT_CONFLICT_RESOLUTIONS | = | %w'ROLLBACK ABORT FAIL IGNORE REPLACE'.each(&:freeze).freeze |
The allowed values for |
Public Instance methods
# 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
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.
# 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 has CURRENT_TIMESTAMP and related constants in UTC instead of in localtime, so convert those constants to local time.
# 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 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.
# File lib/sequel/adapters/shared/sqlite.rb 692 def delete(&block) 693 @opts[:where] ? super : where(1=>1).delete(&block) 694 end
Always return false when using VALUES
# File lib/sequel/adapters/shared/sqlite.rb 697 def empty? 698 return false if @opts[:values] 699 super 700 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. |
# 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
HAVING requires GROUP BY on SQLite
# 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
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)
# 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
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)
# File lib/sequel/adapters/shared/sqlite.rb 813 def insert_ignore 814 insert_conflict(:ignore) 815 end
Support insert select for associations, so that the model code can use returning instead of a separate query.
# 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
The SQL to use for an insert_select, adds a RETURNING clause to the insert unless the RETURNING clause is already present.
# 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
SQLite uses the nonstandard ‘ (backtick) for quoting identifiers.
# File lib/sequel/adapters/shared/sqlite.rb 737 def quoted_identifier_append(sql, c) 738 sql << '`' << c.to_s.gsub('`', '``') << '`' 739 end
Automatically add aliases to RETURNING values to work around SQLite bug.
# 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
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.
# 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
SQLite 3.8.3+ supports common table expressions.
# File lib/sequel/adapters/shared/sqlite.rb 825 def supports_cte?(type=:select) 826 db.sqlite_version >= 30803 827 end
SQLite supports CTEs in subqueries if it supports CTEs.
# File lib/sequel/adapters/shared/sqlite.rb 830 def supports_cte_in_subqueries? 831 supports_cte? 832 end
SQLite does not support deleting from a joined dataset
# File lib/sequel/adapters/shared/sqlite.rb 840 def supports_deleting_joins? 841 false 842 end
SQLite does not support table aliases with column aliases
# File lib/sequel/adapters/shared/sqlite.rb 835 def supports_derived_column_lists? 836 false 837 end
SQLite does not support INTERSECT ALL or EXCEPT ALL
# File lib/sequel/adapters/shared/sqlite.rb 845 def supports_intersect_except_all? 846 false 847 end
SQLite does not support IS TRUE
# File lib/sequel/adapters/shared/sqlite.rb 850 def supports_is_true? 851 false 852 end
SQLite 3.33.0 supports modifying joined datasets
# File lib/sequel/adapters/shared/sqlite.rb 855 def supports_modifying_joins? 856 db.sqlite_version >= 33300 857 end
SQLite does not support multiple columns for the IN/NOT IN operators
# File lib/sequel/adapters/shared/sqlite.rb 860 def supports_multiple_column_in? 861 false 862 end
SQLite 3.35.0 supports RETURNING on INSERT/UPDATE/DELETE.
# File lib/sequel/adapters/shared/sqlite.rb 865 def supports_returning?(_) 866 db.sqlite_version >= 33500 867 end
SQLite supports timezones in literal timestamps, since it stores them as text. But using timezones in timestamps breaks SQLite datetime functions, so we allow the user to override the default per database.
# File lib/sequel/adapters/shared/sqlite.rb 872 def supports_timestamp_timezones? 873 db.use_timestamp_timezones? 874 end
SQLite cannot use WHERE ‘t’.
# File lib/sequel/adapters/shared/sqlite.rb 877 def supports_where_true? 878 false 879 end
SQLite 3.28+ supports the WINDOW clause.
# File lib/sequel/adapters/shared/sqlite.rb 882 def supports_window_clause? 883 db.sqlite_version >= 32800 884 end
# File lib/sequel/adapters/shared/sqlite.rb 895 def supports_window_function_frame_option?(option) 896 db.sqlite_version >= 32800 ? true : super 897 end
SQLite 3.25+ supports window functions. However, support is only enabled on SQLite 3.26.0+ because internal Sequel usage of window functions to implement eager loading of limited associations triggers an SQLite crash bug in versions 3.25.0-3.25.3.
# File lib/sequel/adapters/shared/sqlite.rb 890 def supports_window_functions? 891 db.sqlite_version >= 32600 892 end