module Sequel::SQLite::DatasetMethods

  1. lib/sequel/adapters/shared/sqlite.rb

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 insert_conflict

Public Instance methods

cast_sql_append(sql, expr, type)
[show 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
complex_expression_sql_append(sql, op, args)

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.

[show 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
constant_sql_append(sql, constant)

SQLite has CURRENT_TIMESTAMP and related constants in UTC instead of in localtime, so convert those constants to local time.

[show 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
delete(&block)

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.

[show source]
    # File lib/sequel/adapters/shared/sqlite.rb
692 def delete(&block)
693   @opts[:where] ? super : where(1=>1).delete(&block)
694 end
empty?()

Always return false when using VALUES

[show source]
    # File lib/sequel/adapters/shared/sqlite.rb
697 def empty?
698   return false if @opts[:values]
699   super
700 end
explain(opts=nil)

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.

[show 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
having(*cond)

HAVING requires GROUP BY on SQLite

[show 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
insert_conflict(opts = :ignore)

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)
[show 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
insert_ignore()

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)
[show source]
    # File lib/sequel/adapters/shared/sqlite.rb
813 def insert_ignore
814   insert_conflict(:ignore)
815 end
insert_select(*values)

Support insert select for associations, so that the model code can use returning instead of a separate query.

[show 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
insert_select_sql(*values)

The SQL to use for an insert_select, adds a RETURNING clause to the insert unless the RETURNING clause is already present.

[show 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
quoted_identifier_append(sql, c)

SQLite uses the nonstandard ‘ (backtick) for quoting identifiers.

[show source]
    # File lib/sequel/adapters/shared/sqlite.rb
737 def quoted_identifier_append(sql, c)
738   sql << '`' << c.to_s.gsub('`', '``') << '`'
739 end
returning(*values)

Automatically add aliases to RETURNING values to work around SQLite bug.

[show 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
select(*cols)

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.

[show 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
supports_cte?(type=:select)

SQLite 3.8.3+ supports common table expressions.

[show source]
    # File lib/sequel/adapters/shared/sqlite.rb
825 def supports_cte?(type=:select)
826   db.sqlite_version >= 30803
827 end
supports_cte_in_subqueries?()

SQLite supports CTEs in subqueries if it supports CTEs.

[show source]
    # File lib/sequel/adapters/shared/sqlite.rb
830 def supports_cte_in_subqueries?
831   supports_cte?
832 end
supports_deleting_joins?()

SQLite does not support deleting from a joined dataset

[show source]
    # File lib/sequel/adapters/shared/sqlite.rb
840 def supports_deleting_joins?
841   false
842 end
supports_derived_column_lists?()

SQLite does not support table aliases with column aliases

[show source]
    # File lib/sequel/adapters/shared/sqlite.rb
835 def supports_derived_column_lists?
836   false
837 end
supports_intersect_except_all?()

SQLite does not support INTERSECT ALL or EXCEPT ALL

[show source]
    # File lib/sequel/adapters/shared/sqlite.rb
845 def supports_intersect_except_all?
846   false
847 end
supports_is_true?()

SQLite does not support IS TRUE

[show source]
    # File lib/sequel/adapters/shared/sqlite.rb
850 def supports_is_true?
851   false
852 end
supports_modifying_joins?()

SQLite 3.33.0 supports modifying joined datasets

[show source]
    # File lib/sequel/adapters/shared/sqlite.rb
855 def supports_modifying_joins?
856   db.sqlite_version >= 33300
857 end
supports_multiple_column_in?()

SQLite does not support multiple columns for the IN/NOT IN operators

[show source]
    # File lib/sequel/adapters/shared/sqlite.rb
860 def supports_multiple_column_in?
861   false
862 end
supports_returning?(_)

SQLite 3.35.0 supports RETURNING on INSERT/UPDATE/DELETE.

[show source]
    # File lib/sequel/adapters/shared/sqlite.rb
865 def supports_returning?(_)
866   db.sqlite_version >= 33500
867 end
supports_timestamp_timezones?()

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.

[show source]
    # File lib/sequel/adapters/shared/sqlite.rb
872 def supports_timestamp_timezones?
873   db.use_timestamp_timezones?
874 end
supports_where_true?()

SQLite cannot use WHERE ‘t’.

[show source]
    # File lib/sequel/adapters/shared/sqlite.rb
877 def supports_where_true?
878   false
879 end
supports_window_clause?()

SQLite 3.28+ supports the WINDOW clause.

[show source]
    # File lib/sequel/adapters/shared/sqlite.rb
882 def supports_window_clause?
883   db.sqlite_version >= 32800
884 end
supports_window_function_frame_option?(option)

SQLite 3.28.0+ supports all window frame options that Sequel supports

[show 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
supports_window_functions?()

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.

[show source]
    # File lib/sequel/adapters/shared/sqlite.rb
890 def supports_window_functions?
891   db.sqlite_version >= 32600
892 end