Module: Sequel::MySQL::DatasetMethods

Includes:
Dataset::Replace, UnmodifiedIdentifiers::DatasetMethods
Included in:
Dataset, Sequel::Mysql2::Dataset, Trilogy::Dataset
Defined in:
lib/sequel/adapters/shared/mysql.rb

Overview

Dataset methods shared by datasets that use MySQL databases.

Constant Summary collapse

MATCH_AGAINST =
["MATCH ".freeze, " AGAINST (".freeze, ")".freeze].freeze
MATCH_AGAINST_BOOLEAN =
["MATCH ".freeze, " AGAINST (".freeze, " IN BOOLEAN MODE)".freeze].freeze

Instance Method Summary collapse

Methods included from Dataset::Replace

#multi_replace, #replace, #replace_sql, #supports_replace?

Instance Method Details

#calc_found_rowsObject

Sets up the select methods to use SQL_CALC_FOUND_ROWS option.

dataset.calc_found_rows.limit(10)
# SELECT SQL_CALC_FOUND_ROWS * FROM table LIMIT 10


761
762
763
# File 'lib/sequel/adapters/shared/mysql.rb', line 761

def calc_found_rows
  clone(:calc_found_rows => true)
end

#complex_expression_sql_append(sql, op, args) ⇒ Object



695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
# File 'lib/sequel/adapters/shared/mysql.rb', line 695

def complex_expression_sql_append(sql, op, args)
  case op
  when :IN, :"NOT IN"
    ds = args[1]
    if ds.is_a?(Sequel::Dataset) && ds.opts[:limit]
      super(sql, op, [args[0], ds.from_self])
    else
      super
    end
  when :~, :'!~', :'~*', :'!~*', :LIKE, :'NOT LIKE', :ILIKE, :'NOT ILIKE'
    if !db.mariadb? && db.server_version >= 80000 && [:~, :'!~'].include?(op)
      func = Sequel.function(:REGEXP_LIKE, args[0], args[1], 'c')
      func = ~func if op == :'!~'
      return literal_append(sql, func)
    end

    sql << '('
    literal_append(sql, args[0])
    sql << ' '
    sql << 'NOT ' if [:'NOT LIKE', :'NOT ILIKE', :'!~', :'!~*'].include?(op)
    sql << ([:~, :'!~', :'~*', :'!~*'].include?(op) ? 'REGEXP' : 'LIKE')
    sql << ' '
    sql << 'BINARY ' if [:~, :'!~', :LIKE, :'NOT LIKE'].include?(op)
    literal_append(sql, args[1])
    if [:LIKE, :'NOT LIKE', :ILIKE, :'NOT ILIKE'].include?(op)
      sql << " ESCAPE "
      literal_append(sql, "\\")
    end
    sql << ')'
  when :'||'
    if args.length > 1
      sql << "CONCAT"
      array_sql_append(sql, args)
    else
      literal_append(sql, args[0])
    end
  when :'B~'
    sql << "CAST(~"
    literal_append(sql, args[0])
    sql << " AS SIGNED INTEGER)"
  else
    super
  end
end

#constant_sql_append(sql, constant) ⇒ Object

MySQL’s CURRENT_TIMESTAMP does not use fractional seconds, even if the database itself supports fractional seconds. If MySQL 5.6.4+ is being used, use a value that will return fractional seconds.



744
745
746
747
748
749
750
# File 'lib/sequel/adapters/shared/mysql.rb', line 744

def constant_sql_append(sql, constant)
  if constant == :CURRENT_TIMESTAMP && supports_timestamp_usecs?
    sql << 'CURRENT_TIMESTAMP(6)'
  else
    super
  end
end

#delete_from(*tables) ⇒ Object

Sets up the select methods to delete from if deleting from a joined dataset:

DB[:a].join(:b, a_id: :id).delete
# DELETE a FROM a INNER JOIN b ON (b.a_id = a.id)

DB[:a].join(:b, a_id: :id).delete_from(:a, :b).delete
# DELETE a, b FROM a INNER JOIN b ON (b.a_id = a.id)


773
774
775
# File 'lib/sequel/adapters/shared/mysql.rb', line 773

def delete_from(*tables)
  clone(:delete_from=>tables)
end

#distinct(*args) ⇒ Object

Use GROUP BY instead of DISTINCT ON if arguments are provided.



753
754
755
# File 'lib/sequel/adapters/shared/mysql.rb', line 753

def distinct(*args)
  args.empty? ? super : group(*args)
end

#explain(opts = OPTS) ⇒ Object

Return the results of an EXPLAIN query as a string. Options:

:extended

Use EXPLAIN EXTENDED instead of EXPLAIN if true.



779
780
781
782
783
784
785
786
787
# File 'lib/sequel/adapters/shared/mysql.rb', line 779

def explain(opts=OPTS)
  # Load the PrettyTable class, needed for explain output
  Sequel.extension(:_pretty_table) unless defined?(Sequel::PrettyTable)

  sql = ((opts[:extended] && (db.mariadb? || db.server_version < 50700)) ? 'EXPLAIN EXTENDED ' : 'EXPLAIN ') + select_sql
  ds = db.send(:metadata_dataset).with_sql(sql.freeze).naked
  rows = ds.all
  Sequel::PrettyTable.string(rows, ds.columns)
end

#for_shareObject

Return a cloned dataset which will use LOCK IN SHARE MODE to lock returned rows.



790
791
792
# File 'lib/sequel/adapters/shared/mysql.rb', line 790

def for_share
  cached_lock_style_dataset(:_for_share_ds, :share)
end

#full_text_search(cols, terms, opts = OPTS) ⇒ Object

Adds full text filter



795
796
797
# File 'lib/sequel/adapters/shared/mysql.rb', line 795

def full_text_search(cols, terms, opts = OPTS)
  where(full_text_sql(cols, terms, opts))
end

#full_text_sql(cols, terms, opts = OPTS) ⇒ Object

MySQL specific full text search syntax.



800
801
802
803
# File 'lib/sequel/adapters/shared/mysql.rb', line 800

def full_text_sql(cols, terms, opts = OPTS)
  terms = Sequel.array_or_set_join(terms, ' ') if terms.is_a?(Array) || terms.is_a?(Set)
  SQL::PlaceholderLiteralString.new((opts[:boolean] ? MATCH_AGAINST_BOOLEAN : MATCH_AGAINST), [Array(cols), terms])
end

#insert_ignoreObject

Sets up the insert methods to use INSERT IGNORE. Useful if you have a unique key and want to just skip inserting rows that violate the unique key restriction.

dataset.insert_ignore.multi_insert(
  [{name: 'a', value: 1}, {name: 'b', value: 2}]
)
# INSERT IGNORE INTO tablename (name, value) VALUES (a, 1), (b, 2)


813
814
815
# File 'lib/sequel/adapters/shared/mysql.rb', line 813

def insert_ignore
  clone(:insert_ignore=>true)
end

#insert_select(*values) ⇒ Object

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



819
820
821
822
823
# File 'lib/sequel/adapters/shared/mysql.rb', line 819

def insert_select(*values)
  return unless supports_insert_select?
  # Handle case where query does not return a row
  server?(:default).with_sql_first(insert_select_sql(*values)) || false
end

#insert_select_sql(*values) ⇒ Object

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



827
828
829
830
# File 'lib/sequel/adapters/shared/mysql.rb', line 827

def insert_select_sql(*values)
  ds = opts[:returning] ? self : returning
  ds.insert_sql(*values)
end

#on_duplicate_key_update(*args) ⇒ Object

Sets up the insert methods to use ON DUPLICATE KEY UPDATE If you pass no arguments, ALL fields will be updated with the new values. If you pass the fields you want then ONLY those field will be updated. If you pass a hash you can customize the values (for example, to increment a numeric field).

Useful if you have a unique key and want to update inserting rows that violate the unique key restriction.

dataset.on_duplicate_key_update.multi_insert(
  [{name: 'a', value: 1}, {name: 'b', value: 2}]
)
# INSERT INTO tablename (name, value) VALUES (a, 1), (b, 2)
# ON DUPLICATE KEY UPDATE name=VALUES(name), value=VALUES(value)

dataset.on_duplicate_key_update(:value).multi_insert(
  [{name: 'a', value: 1}, {name: 'b', value: 2}]
)
# INSERT INTO tablename (name, value) VALUES (a, 1), (b, 2)
# ON DUPLICATE KEY UPDATE value=VALUES(value)

dataset.on_duplicate_key_update(
  value: Sequel.lit('value + VALUES(value)')
).multi_insert(
  [{name: 'a', value: 1}, {name: 'b', value: 2}]
)
# INSERT INTO tablename (name, value) VALUES (a, 1), (b, 2)
# ON DUPLICATE KEY UPDATE value=value + VALUES(value)


861
862
863
# File 'lib/sequel/adapters/shared/mysql.rb', line 861

def on_duplicate_key_update(*args)
  clone(:on_duplicate_key_update => args)
end

#quoted_identifier_append(sql, c) ⇒ Object

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



866
867
868
# File 'lib/sequel/adapters/shared/mysql.rb', line 866

def quoted_identifier_append(sql, c)
  sql << '`' << c.to_s.gsub('`', '``') << '`'
end

#supports_cte?(type = :select) ⇒ Boolean

MariaDB 10.2+ and MySQL 8+ support CTEs

Returns:

  • (Boolean)


871
872
873
874
875
876
877
878
879
880
# File 'lib/sequel/adapters/shared/mysql.rb', line 871

def supports_cte?(type=:select)
  if db.mariadb?
    type == :select && db.server_version >= 100200
  else
    case type
    when :select, :update, :delete
      db.server_version >= 80000
    end
  end
end

#supports_derived_column_lists?Boolean

MySQL does not support derived column lists

Returns:

  • (Boolean)


883
884
885
# File 'lib/sequel/adapters/shared/mysql.rb', line 883

def supports_derived_column_lists?
  false
end

#supports_distinct_on?Boolean

MySQL can emulate DISTINCT ON with its non-standard GROUP BY implementation, though the rows returned cannot be made deterministic through ordering.

Returns:

  • (Boolean)


889
890
891
# File 'lib/sequel/adapters/shared/mysql.rb', line 889

def supports_distinct_on?
  true
end

#supports_group_rollup?Boolean

MySQL supports GROUP BY WITH ROLLUP (but not CUBE)

Returns:

  • (Boolean)


894
895
896
# File 'lib/sequel/adapters/shared/mysql.rb', line 894

def supports_group_rollup?
  true
end

#supports_intersect_except?Boolean

MariaDB 10.3+ supports INTERSECT or EXCEPT

Returns:

  • (Boolean)


899
900
901
# File 'lib/sequel/adapters/shared/mysql.rb', line 899

def supports_intersect_except?
  db.mariadb? && db.server_version >= 100300
end

#supports_limits_in_correlated_subqueries?Boolean

MySQL does not support limits in correlated subqueries (or any subqueries that use IN).

Returns:

  • (Boolean)


904
905
906
# File 'lib/sequel/adapters/shared/mysql.rb', line 904

def supports_limits_in_correlated_subqueries?
  false
end

#supports_modifying_joins?Boolean

MySQL supports modifying joined datasets

Returns:

  • (Boolean)


909
910
911
# File 'lib/sequel/adapters/shared/mysql.rb', line 909

def supports_modifying_joins?
  true
end

#supports_nowait?Boolean

MySQL 8+ and MariaDB 10.3+ support NOWAIT.

Returns:

  • (Boolean)


914
915
916
# File 'lib/sequel/adapters/shared/mysql.rb', line 914

def supports_nowait?
  db.server_version >= (db.mariadb? ? 100300 : 80000)
end

#supports_ordered_distinct_on?Boolean

MySQL’s DISTINCT ON emulation using GROUP BY does not respect the query’s ORDER BY clause.

Returns:

  • (Boolean)


920
921
922
# File 'lib/sequel/adapters/shared/mysql.rb', line 920

def supports_ordered_distinct_on?
  false
end

#supports_regexp?Boolean

MySQL supports pattern matching via regular expressions

Returns:

  • (Boolean)


925
926
927
# File 'lib/sequel/adapters/shared/mysql.rb', line 925

def supports_regexp?
  true
end

#supports_returning?(type) ⇒ Boolean

MariaDB 10.5.0 supports INSERT RETURNING.

Returns:

  • (Boolean)


930
931
932
# File 'lib/sequel/adapters/shared/mysql.rb', line 930

def supports_returning?(type)
  (type == :insert && db.mariadb? && db.adapter_scheme != :jdbc) ? (db.server_version >= 100500) : false
end

#supports_skip_locked?Boolean

MySQL 8+ and MariaDB 10.6+ support SKIP LOCKED.

Returns:

  • (Boolean)


935
936
937
# File 'lib/sequel/adapters/shared/mysql.rb', line 935

def supports_skip_locked?
  db.server_version >= (db.mariadb? ? 100600 : 80000)
end

#supports_timestamp_usecs?Boolean

Check the database setting for whether fractional timestamps are suppported.

Returns:

  • (Boolean)


941
942
943
# File 'lib/sequel/adapters/shared/mysql.rb', line 941

def supports_timestamp_usecs?
  db.supports_timestamp_usecs?
end

#supports_window_clause?Boolean

MySQL 8+ supports WINDOW clause.

Returns:

  • (Boolean)


946
947
948
# File 'lib/sequel/adapters/shared/mysql.rb', line 946

def supports_window_clause?
  !db.mariadb? && db.server_version >= 80000
end

#supports_window_functions?Boolean

MariaDB 10.2+ and MySQL 8+ support window functions

Returns:

  • (Boolean)


951
952
953
# File 'lib/sequel/adapters/shared/mysql.rb', line 951

def supports_window_functions?
  db.server_version >= (db.mariadb? ? 100200 : 80000)
end

#update_ignoreObject

Sets up the update methods to use UPDATE IGNORE. Useful if you have a unique key and want to just skip updating rows that violate the unique key restriction.

dataset.update_ignore.update(name: 'a', value: 1)
# UPDATE IGNORE tablename SET name = 'a', value = 1


961
962
963
# File 'lib/sequel/adapters/shared/mysql.rb', line 961

def update_ignore
  clone(:update_ignore=>true)
end