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
598 def cast_sql_append(sql, expr, type)
599   if type == Time or type == DateTime
600     sql << "datetime("
601     literal_append(sql, expr)
602     sql << ')'
603   elsif type == Date
604     sql << "date("
605     literal_append(sql, expr)
606     sql << ')'
607   else
608     super
609   end
610 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
614 def complex_expression_sql_append(sql, op, args)
615   case op
616   when :"NOT LIKE", :"NOT ILIKE"
617     sql << 'NOT '
618     complex_expression_sql_append(sql, (op == :"NOT ILIKE" ? :ILIKE : :LIKE), args)
619   when :^
620     complex_expression_arg_pairs_append(sql, args){|a, b| Sequel.lit(["((~(", " & ", ")) & (", " | ", "))"], a, b, a, b)}
621   when :**
622     unless (exp = args[1]).is_a?(Integer)
623       raise(Sequel::Error, "can only emulate exponentiation on SQLite if exponent is an integer, given #{exp.inspect}")
624     end
625     case exp
626     when 0
627       sql << '1'
628     else
629       sql << '('
630       arg = args[0]
631       if exp < 0
632         invert = true
633         exp = exp.abs
634         sql << '(1.0 / ('
635       end
636       (exp - 1).times do 
637         literal_append(sql, arg)
638         sql << " * "
639       end
640       literal_append(sql, arg)
641       sql << ')'
642       if invert
643         sql << "))"
644       end
645     end
646   when :extract
647     part = args[0]
648     raise(Sequel::Error, "unsupported extract argument: #{part.inspect}") unless format = EXTRACT_MAP[part]
649     sql << "CAST(strftime(" << format << ', '
650     literal_append(sql, args[1])
651     sql << ') AS ' << (part == :second ? 'NUMERIC' : 'INTEGER') << ')'
652   else
653     super
654   end
655 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
659 def constant_sql_append(sql, constant)
660   if (c = CONSTANT_MAP[constant]) && !db.current_timestamp_utc
661     sql << c
662   else
663     super
664   end
665 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
670 def delete(&block)
671   @opts[:where] ? super : where(1=>1).delete(&block)
672 end
empty?()

Always return false when using VALUES

[show source]
    # File lib/sequel/adapters/shared/sqlite.rb
675 def empty?
676   return false if @opts[:values]
677   super
678 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
683 def explain(opts=nil)
684   # Load the PrettyTable class, needed for explain output
685   Sequel.extension(:_pretty_table) unless defined?(Sequel::PrettyTable)
686 
687   keyword = (opts && opts[:query_plan]) ? "EXPLAIN QUERY PLAN" : "EXPLAIN"
688   ds = db.send(:metadata_dataset).clone(:sql=>"#{keyword} #{select_sql}".freeze)
689   rows = ds.all
690   Sequel::PrettyTable.string(rows, ds.columns)
691 end
having(*cond)

HAVING requires GROUP BY on SQLite

[show source]
    # File lib/sequel/adapters/shared/sqlite.rb
694 def having(*cond)
695   raise(InvalidOperation, "Can only specify a HAVING clause on a grouped dataset") if !@opts[:group] && db.sqlite_version < 33900
696   super
697 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 algoriths: 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
772 def insert_conflict(opts = :ignore)
773   case opts
774   when Symbol, String
775     unless INSERT_CONFLICT_RESOLUTIONS.include?(opts.to_s.upcase)
776       raise Error, "Invalid symbol or string passed to Dataset#insert_conflict: #{opts.inspect}.  The allowed values are: :rollback, :abort, :fail, :ignore, or :replace"
777     end
778     clone(:insert_conflict => opts)
779   when Hash
780     clone(:insert_on_conflict => opts)
781   else
782     raise Error, "Invalid value passed to Dataset#insert_conflict: #{opts.inspect}, should use a symbol or a hash"
783   end
784 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
791 def insert_ignore
792   insert_conflict(:ignore)
793 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
701 def insert_select(*values)
702   return unless supports_insert_select?
703   # Handle case where query does not return a row
704   server?(:default).with_sql_first(insert_select_sql(*values)) || false
705 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
709 def insert_select_sql(*values)
710   ds = opts[:returning] ? self : returning
711   ds.insert_sql(*values)
712 end
quoted_identifier_append(sql, c)

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

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

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

[show source]
    # File lib/sequel/adapters/shared/sqlite.rb
796 def returning(*values)
797   return super if values.empty?
798   raise Error, "RETURNING is not supported on #{db.database_type}" unless supports_returning?(:insert)
799   clone(:returning=>_returning_values(values).freeze)
800 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
723 def select(*cols)
724   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)})
725     super(*cols.map{|c| alias_qualified_column(c)})
726   else
727     super
728   end
729 end
supports_cte?(type=:select)

SQLite 3.8.3+ supports common table expressions.

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

SQLite supports CTEs in subqueries if it supports CTEs.

[show source]
    # File lib/sequel/adapters/shared/sqlite.rb
808 def supports_cte_in_subqueries?
809   supports_cte?
810 end
supports_deleting_joins?()

SQLite does not support deleting from a joined dataset

[show source]
    # File lib/sequel/adapters/shared/sqlite.rb
818 def supports_deleting_joins?
819   false
820 end
supports_derived_column_lists?()

SQLite does not support table aliases with column aliases

[show source]
    # File lib/sequel/adapters/shared/sqlite.rb
813 def supports_derived_column_lists?
814   false
815 end
supports_intersect_except_all?()

SQLite does not support INTERSECT ALL or EXCEPT ALL

[show source]
    # File lib/sequel/adapters/shared/sqlite.rb
823 def supports_intersect_except_all?
824   false
825 end
supports_is_true?()

SQLite does not support IS TRUE

[show source]
    # File lib/sequel/adapters/shared/sqlite.rb
828 def supports_is_true?
829   false
830 end
supports_modifying_joins?()

SQLite 3.33.0 supports modifying joined datasets

[show source]
    # File lib/sequel/adapters/shared/sqlite.rb
833 def supports_modifying_joins?
834   db.sqlite_version >= 33300
835 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
838 def supports_multiple_column_in?
839   false
840 end
supports_returning?(_)

SQLite 3.35.0 supports RETURNING on INSERT/UPDATE/DELETE.

[show source]
    # File lib/sequel/adapters/shared/sqlite.rb
843 def supports_returning?(_)
844   db.sqlite_version >= 33500
845 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
850 def supports_timestamp_timezones?
851   db.use_timestamp_timezones?
852 end
supports_where_true?()

SQLite cannot use WHERE ‘t’.

[show source]
    # File lib/sequel/adapters/shared/sqlite.rb
855 def supports_where_true?
856   false
857 end
supports_window_clause?()

SQLite 3.28+ supports the WINDOW clause.

[show source]
    # File lib/sequel/adapters/shared/sqlite.rb
860 def supports_window_clause?
861   db.sqlite_version >= 32800
862 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
873 def supports_window_function_frame_option?(option)
874   db.sqlite_version >= 32800 ? true : super
875 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
868 def supports_window_functions?
869   db.sqlite_version >= 32600
870 end