sequel 5.35.0 → 5.40.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (65) hide show
  1. checksums.yaml +4 -4
  2. data/CHANGELOG +68 -0
  3. data/README.rdoc +2 -2
  4. data/doc/cheat_sheet.rdoc +5 -5
  5. data/doc/code_order.rdoc +0 -12
  6. data/doc/fork_safety.rdoc +84 -0
  7. data/doc/model_plugins.rdoc +1 -1
  8. data/doc/opening_databases.rdoc +5 -1
  9. data/doc/postgresql.rdoc +1 -1
  10. data/doc/querying.rdoc +3 -3
  11. data/doc/release_notes/5.36.0.txt +60 -0
  12. data/doc/release_notes/5.37.0.txt +30 -0
  13. data/doc/release_notes/5.38.0.txt +28 -0
  14. data/doc/release_notes/5.39.0.txt +19 -0
  15. data/doc/release_notes/5.40.0.txt +40 -0
  16. data/doc/transactions.rdoc +0 -8
  17. data/doc/validations.rdoc +1 -1
  18. data/lib/sequel/adapters/jdbc.rb +15 -3
  19. data/lib/sequel/adapters/jdbc/mysql.rb +4 -4
  20. data/lib/sequel/adapters/odbc.rb +4 -6
  21. data/lib/sequel/adapters/shared/mssql.rb +35 -5
  22. data/lib/sequel/adapters/shared/oracle.rb +13 -7
  23. data/lib/sequel/adapters/shared/postgres.rb +40 -2
  24. data/lib/sequel/adapters/shared/sqlite.rb +35 -1
  25. data/lib/sequel/adapters/utils/mysql_mysql2.rb +1 -0
  26. data/lib/sequel/core.rb +5 -6
  27. data/lib/sequel/database/connecting.rb +0 -1
  28. data/lib/sequel/database/misc.rb +14 -0
  29. data/lib/sequel/database/schema_generator.rb +6 -0
  30. data/lib/sequel/database/schema_methods.rb +16 -6
  31. data/lib/sequel/database/transactions.rb +2 -2
  32. data/lib/sequel/dataset/actions.rb +10 -6
  33. data/lib/sequel/dataset/features.rb +10 -0
  34. data/lib/sequel/dataset/prepared_statements.rb +2 -0
  35. data/lib/sequel/dataset/sql.rb +32 -10
  36. data/lib/sequel/extensions/blank.rb +6 -0
  37. data/lib/sequel/extensions/date_arithmetic.rb +6 -3
  38. data/lib/sequel/extensions/eval_inspect.rb +2 -0
  39. data/lib/sequel/extensions/inflector.rb +6 -0
  40. data/lib/sequel/extensions/migration.rb +10 -1
  41. data/lib/sequel/extensions/pg_array.rb +1 -0
  42. data/lib/sequel/extensions/pg_interval.rb +22 -6
  43. data/lib/sequel/extensions/pg_json_ops.rb +44 -2
  44. data/lib/sequel/extensions/pg_row.rb +1 -0
  45. data/lib/sequel/extensions/pg_row_ops.rb +24 -0
  46. data/lib/sequel/extensions/query.rb +3 -0
  47. data/lib/sequel/extensions/schema_dumper.rb +3 -3
  48. data/lib/sequel/model.rb +1 -1
  49. data/lib/sequel/model/associations.rb +1 -0
  50. data/lib/sequel/model/base.rb +23 -4
  51. data/lib/sequel/model/plugins.rb +6 -0
  52. data/lib/sequel/plugins/association_proxies.rb +3 -0
  53. data/lib/sequel/plugins/class_table_inheritance.rb +0 -5
  54. data/lib/sequel/plugins/composition.rb +5 -1
  55. data/lib/sequel/plugins/constraint_validations.rb +2 -1
  56. data/lib/sequel/plugins/dataset_associations.rb +4 -1
  57. data/lib/sequel/plugins/dirty.rb +44 -0
  58. data/lib/sequel/plugins/nested_attributes.rb +3 -1
  59. data/lib/sequel/plugins/pg_array_associations.rb +4 -0
  60. data/lib/sequel/plugins/pg_auto_constraint_validations.rb +2 -0
  61. data/lib/sequel/plugins/single_table_inheritance.rb +7 -0
  62. data/lib/sequel/plugins/tree.rb +9 -4
  63. data/lib/sequel/timezones.rb +8 -3
  64. data/lib/sequel/version.rb +1 -1
  65. metadata +33 -21
@@ -143,14 +143,6 @@ If you want the current savepoint to be rolled back when the savepoint block exi
143
143
  end # RELEASE SAVEPOINT
144
144
  end # COMMIT
145
145
 
146
- If you want the current savepoint to be rolled back when the savepoint block exits (even if an exception is not raised), use <tt>Database#rollback_on_exit(:savepoint=>true)</tt>
147
-
148
- DB.transaction do # BEGIN
149
- DB.transaction(savepoint: true) do # SAVEPOINT
150
- DB.rollback_on_exit(:savepoint=>true)
151
- end # ROLLBACK TO SAVEPOINT
152
- end # COMMIT
153
-
154
146
  If you want the current savepoint and potentially enclosing savepoints to be rolled back when the savepoint blocks exit (even if an exception is not raised), use <tt>Database#rollback_on_exit(:savepoint=>integer)</tt>
155
147
 
156
148
  DB.transaction do # BEGIN
@@ -232,7 +232,7 @@ These methods check that the specified attributes can be valid integers or valid
232
232
 
233
233
  === +validates_operator+
234
234
 
235
- +validates_operator+ checks that a given +operator+ method returns a truthy value when called on attribute with a specified value for comparison. Generally, this is used for inequality checks (>, >=, etc) but any method that can be called on the attribute that accepts an argument and returns a truthy value may be used.
235
+ +validates_operator+ checks that a given +operator+ method returns a truthy value when called on attribute with a specified value for comparison. Generally, this is used for inequality checks (>, >=, etc.) but any method that can be called on the attribute that accepts an argument and returns a truthy value may be used.
236
236
 
237
237
  class Album < Sequel::Model
238
238
  def validate
@@ -51,7 +51,19 @@ module Sequel
51
51
  # Raise a Sequel::AdapterNotFound if evaluating the class name raises a NameError.
52
52
  def self.load_driver(drv, gem=nil)
53
53
  load_gem(gem) if gem
54
- eval drv
54
+ if drv.is_a?(String)
55
+ eval drv
56
+ else
57
+ *try, last = drv
58
+ try.each do |try_drv|
59
+ begin
60
+ return eval(try_drv)
61
+ rescue NameError
62
+ end
63
+ end
64
+
65
+ eval last
66
+ end
55
67
  rescue NameError
56
68
  raise Sequel::AdapterNotFound, "#{drv} not loaded#{", try installing jdbc-#{gem.to_s.downcase} gem" if gem}"
57
69
  end
@@ -59,11 +71,11 @@ module Sequel
59
71
  class TypeConvertor
60
72
  CONVERTORS = convertors = {}
61
73
  %w'Boolean Float Double Int Long Short'.each do |meth|
62
- x = convertors[meth.to_sym] = Object.new
74
+ x = x = convertors[meth.to_sym] = Object.new
63
75
  class_eval("def x.call(r, i) v = r.get#{meth}(i); v unless r.wasNull end", __FILE__, __LINE__)
64
76
  end
65
77
  %w'Object Array String Time Date Timestamp BigDecimal Blob Bytes Clob'.each do |meth|
66
- x = convertors[meth.to_sym] = Object.new
78
+ x = x = convertors[meth.to_sym] = Object.new
67
79
  class_eval("def x.call(r, i) r.get#{meth}(i) end", __FILE__, __LINE__)
68
80
  end
69
81
  x = convertors[:RubyTime] = Object.new
@@ -1,15 +1,15 @@
1
1
  # frozen-string-literal: true
2
2
 
3
- Sequel::JDBC.load_driver('com.mysql.jdbc.Driver', :MySQL)
4
- require_relative '../shared/mysql'
5
-
6
3
  module Sequel
7
4
  module JDBC
5
+ driver = Sequel::JDBC.load_driver(%w'com.mysql.cj.jdbc.Driver com.mysql.jdbc.Driver', :MySQL)
6
+ require_relative '../shared/mysql'
7
+
8
8
  Sequel.synchronize do
9
9
  DATABASE_SETUP[:mysql] = proc do |db|
10
10
  db.extend(Sequel::JDBC::MySQL::DatabaseMethods)
11
11
  db.extend_datasets Sequel::MySQL::DatasetMethods
12
- com.mysql.jdbc.Driver
12
+ driver
13
13
  end
14
14
  end
15
15
 
@@ -92,12 +92,10 @@ module Sequel
92
92
  cols = s.columns(true).map{|c| [output_identifier(c.name), c.type, i+=1]}
93
93
  columns = cols.map{|c| c[0]}
94
94
  self.columns = columns
95
- if rows = s.fetch_all
96
- rows.each do |row|
97
- hash = {}
98
- cols.each{|n,t,j| hash[n] = convert_odbc_value(row[j], t)}
99
- yield hash
100
- end
95
+ s.each do |row|
96
+ hash = {}
97
+ cols.each{|n,t,j| hash[n] = convert_odbc_value(row[j], t)}
98
+ yield hash
101
99
  end
102
100
  end
103
101
  self
@@ -244,6 +244,16 @@ module Sequel
244
244
 
245
245
  private
246
246
 
247
+ # Add CLUSTERED or NONCLUSTERED as needed
248
+ def add_clustered_sql_fragment(sql, opts)
249
+ clustered = opts[:clustered]
250
+ unless clustered.nil?
251
+ sql += " #{'NON' unless clustered}CLUSTERED"
252
+ end
253
+
254
+ sql
255
+ end
256
+
247
257
  # Add dropping of the default constraint to the list of SQL queries.
248
258
  # This is necessary before dropping the column or changing its type.
249
259
  def add_drop_default_constraint_sql(sqls, table, column)
@@ -284,7 +294,7 @@ module Sequel
284
294
  when :set_column_null
285
295
  sch = schema(table).find{|k,v| k.to_s == op[:name].to_s}.last
286
296
  type = sch[:db_type]
287
- if [:string, :decimal].include?(sch[:type]) && !["text", "ntext"].include?(type) && (size = (sch[:max_chars] || sch[:column_size]))
297
+ if [:string, :decimal, :blob].include?(sch[:type]) && !["text", "ntext"].include?(type) && (size = (sch[:max_chars] || sch[:column_size]))
288
298
  size = "MAX" if size == -1
289
299
  type += "(#{size}#{", #{sch[:scale]}" if sch[:scale] && sch[:scale].to_i > 0})"
290
300
  end
@@ -396,6 +406,11 @@ module Sequel
396
406
  super.with_quote_identifiers(true)
397
407
  end
398
408
 
409
+ # Handle clustered and nonclustered primary keys
410
+ def primary_key_constraint_sql_fragment(opts)
411
+ add_clustered_sql_fragment(super, opts)
412
+ end
413
+
399
414
  # Use sp_rename to rename the table
400
415
  def rename_table_sql(name, new_name)
401
416
  "sp_rename #{literal(quote_schema_table(name))}, #{quote_identifier(schema_and_table(new_name).pop)}"
@@ -492,6 +507,11 @@ module Sequel
492
507
  :'varbinary(max)'
493
508
  end
494
509
 
510
+ # Handle clustered and nonclustered unique constraints
511
+ def unique_constraint_sql_fragment(opts)
512
+ add_clustered_sql_fragment(super, opts)
513
+ end
514
+
495
515
  # MSSQL supports views with check option, but not local.
496
516
  def view_with_check_option_support
497
517
  true
@@ -659,11 +679,11 @@ module Sequel
659
679
  # case by default, and that also adds a default order, so it's better to just
660
680
  # avoid the subquery.
661
681
  def select_sql
662
- if @opts[:offset] && !@opts[:order] && is_2012_or_later?
663
- order(1).select_sql
664
- else
665
- super
682
+ if @opts[:offset]
683
+ raise(Error, "Using with_ties is not supported with an offset on Microsoft SQL Server") if @opts[:limit_with_ties]
684
+ return order(1).select_sql if is_2012_or_later? && !@opts[:order]
666
685
  end
686
+ super
667
687
  end
668
688
 
669
689
  # The version of the database server.
@@ -755,6 +775,12 @@ module Sequel
755
775
  false
756
776
  end
757
777
 
778
+ # Use WITH TIES when limiting the result set to also include additional
779
+ # rows matching the last row.
780
+ def with_ties
781
+ clone(:limit_with_ties=>true)
782
+ end
783
+
758
784
  protected
759
785
 
760
786
  # If returned primary keys are requested, use OUTPUT unless already set on the
@@ -959,6 +985,10 @@ module Sequel
959
985
  sql << " TOP "
960
986
  literal_append(sql, l)
961
987
  end
988
+
989
+ if @opts[:limit_with_ties]
990
+ sql << " WITH TIES"
991
+ end
962
992
  end
963
993
 
964
994
  def update_limit_sql(sql)
@@ -103,12 +103,18 @@ module Sequel
103
103
  map{|r| m.call(r[:view_name])}
104
104
  end
105
105
 
106
- def view_exists?(name)
107
- m = input_identifier_meth
108
- metadata_dataset.from(:all_views).
109
- exclude(:owner=>IGNORE_OWNERS).
110
- where(:view_name=>m.call(name)).
111
- count > 0
106
+ # Whether a view with a given name exists. By default, looks in all schemas other than system
107
+ # schemas. If the :current_schema option is given, looks in the schema for the current user.
108
+ def view_exists?(name, opts=OPTS)
109
+ ds = metadata_dataset.from(:all_views).where(:view_name=>input_identifier_meth.call(name))
110
+
111
+ if opts[:current_schema]
112
+ ds = ds.where(:owner=>Sequel.function(:SYS_CONTEXT, 'userenv', 'current_schema'))
113
+ else
114
+ ds = ds.exclude(:owner=>IGNORE_OWNERS)
115
+ end
116
+
117
+ ds.count > 0
112
118
  end
113
119
 
114
120
  # The version of the Oracle server, used for determining capability.
@@ -178,7 +184,7 @@ module Sequel
178
184
 
179
185
  def create_table_from_generator(name, generator, options)
180
186
  drop_statement, create_statements = create_table_sql_list(name, generator, options)
181
- (execute_ddl(drop_statement) rescue nil) if drop_statement
187
+ swallow_database_error{execute_ddl(drop_statement)} if drop_statement
182
188
  create_statements.each{|sql| execute_ddl(sql)}
183
189
  end
184
190
 
@@ -781,7 +781,7 @@ module Sequel
781
781
  return @server_version if @server_version
782
782
  ds = dataset
783
783
  ds = ds.server(server) if server
784
- @server_version ||= ds.with_sql("SELECT CAST(current_setting('server_version_num') AS integer) AS v").single_value rescue 0
784
+ @server_version = swallow_database_error{ds.with_sql("SELECT CAST(current_setting('server_version_num') AS integer) AS v").single_value} || 0
785
785
  end
786
786
 
787
787
  # PostgreSQL supports CREATE TABLE IF NOT EXISTS on 9.1+
@@ -846,7 +846,7 @@ module Sequel
846
846
  # :schema :: The schema to search
847
847
  # :server :: The server to use
848
848
  def tables(opts=OPTS, &block)
849
- pg_class_relname('r', opts, &block)
849
+ pg_class_relname(['r', 'p'], opts, &block)
850
850
  end
851
851
 
852
852
  # Check whether the given type name string/symbol (e.g. :hstore) is supported by
@@ -1885,6 +1885,13 @@ module Sequel
1885
1885
  end
1886
1886
  end
1887
1887
 
1888
+ # Use WITH TIES when limiting the result set to also include additional
1889
+ # rules that have the same results for the order column as the final row.
1890
+ # Requires PostgreSQL 13.
1891
+ def with_ties
1892
+ clone(:limit_with_ties=>true)
1893
+ end
1894
+
1888
1895
  protected
1889
1896
 
1890
1897
  # If returned primary keys are requested, use RETURNING unless already set on the
@@ -2071,6 +2078,37 @@ module Sequel
2071
2078
  false
2072
2079
  end
2073
2080
 
2081
+ # Support FETCH FIRST WITH TIES on PostgreSQL 13+.
2082
+ def select_limit_sql(sql)
2083
+ l = @opts[:limit]
2084
+ o = @opts[:offset]
2085
+
2086
+ return unless l || o
2087
+
2088
+ if @opts[:limit_with_ties]
2089
+ if o
2090
+ sql << " OFFSET "
2091
+ literal_append(sql, o)
2092
+ end
2093
+
2094
+ if l
2095
+ sql << " FETCH FIRST "
2096
+ literal_append(sql, l)
2097
+ sql << " ROWS WITH TIES"
2098
+ end
2099
+ else
2100
+ if l
2101
+ sql << " LIMIT "
2102
+ literal_append(sql, l)
2103
+ end
2104
+
2105
+ if o
2106
+ sql << " OFFSET "
2107
+ literal_append(sql, o)
2108
+ end
2109
+ end
2110
+ end
2111
+
2074
2112
  # Support FOR SHARE locking when using the :share lock style.
2075
2113
  # Use SKIP LOCKED if skipping locked rows.
2076
2114
  def select_lock_sql(sql)
@@ -561,7 +561,7 @@ module Sequel
561
561
  Dataset.def_sql_method(self, :delete, [['if db.sqlite_version >= 30803', %w'with delete from where'], ["else", %w'delete from where']])
562
562
  Dataset.def_sql_method(self, :insert, [['if db.sqlite_version >= 30803', %w'with insert conflict into columns values on_conflict'], ["else", %w'insert conflict into columns values']])
563
563
  Dataset.def_sql_method(self, :select, [['if opts[:values]', %w'with values compounds'], ['else', %w'with select distinct columns from join where group having window compounds order limit lock']])
564
- Dataset.def_sql_method(self, :update, [['if db.sqlite_version >= 30803', %w'with update table set where'], ["else", %w'update table set where']])
564
+ Dataset.def_sql_method(self, :update, [['if db.sqlite_version >= 33300', %w'with update table set from where'], ['elsif db.sqlite_version >= 30803', %w'with update table set where'], ["else", %w'update table set where']])
565
565
 
566
566
  def cast_sql_append(sql, expr, type)
567
567
  if type == Time or type == DateTime
@@ -753,6 +753,11 @@ module Sequel
753
753
  false
754
754
  end
755
755
 
756
+ # SQLite does not support deleting from a joined dataset
757
+ def supports_deleting_joins?
758
+ false
759
+ end
760
+
756
761
  # SQLite does not support INTERSECT ALL or EXCEPT ALL
757
762
  def supports_intersect_except_all?
758
763
  false
@@ -763,6 +768,11 @@ module Sequel
763
768
  false
764
769
  end
765
770
 
771
+ # SQLite 3.33.0 supports modifying joined datasets
772
+ def supports_modifying_joins?
773
+ db.sqlite_version >= 33300
774
+ end
775
+
766
776
  # SQLite does not support multiple columns for the IN/NOT IN operators
767
777
  def supports_multiple_column_in?
768
778
  false
@@ -825,6 +835,13 @@ module Sequel
825
835
  end
826
836
  end
827
837
 
838
+ # Raise an InvalidOperation exception if insert is not allowed for this dataset.
839
+ def check_insert_allowed!
840
+ raise(InvalidOperation, "Grouped datasets cannot be modified") if opts[:group]
841
+ raise(InvalidOperation, "Joined datasets cannot be modified") if joined_dataset?
842
+ end
843
+ alias check_delete_allowed! check_insert_allowed!
844
+
828
845
  # SQLite supports a maximum of 500 rows in a VALUES clause.
829
846
  def default_import_slice
830
847
  500
@@ -944,6 +961,23 @@ module Sequel
944
961
  def _truncate_sql(table)
945
962
  "DELETE FROM #{table}"
946
963
  end
964
+
965
+ # Use FROM to specify additional tables in an update query
966
+ def update_from_sql(sql)
967
+ if(from = @opts[:from][1..-1]).empty?
968
+ raise(Error, 'Need multiple FROM tables if updating/deleting a dataset with JOINs') if @opts[:join]
969
+ else
970
+ sql << ' FROM '
971
+ source_list_append(sql, from)
972
+ select_join_sql(sql)
973
+ end
974
+ end
975
+
976
+ # Only include the primary table in the main update clause
977
+ def update_table_sql(sql)
978
+ sql << ' '
979
+ source_list_append(sql, @opts[:from][0..0])
980
+ end
947
981
  end
948
982
  end
949
983
  end
@@ -18,6 +18,7 @@ module Sequel
18
18
  This connection is still waiting for a result, try again once you have the result
19
19
  closed MySQL connection
20
20
  The MySQL server is running with the --read-only option so it cannot execute this statement
21
+ Connection was killed
21
22
  END
22
23
  # Error messages for mysql and mysql2 that indicate the current connection should be disconnected
23
24
  MYSQL_DATABASE_DISCONNECT_ERRORS = /\A#{Regexp.union(disconnect_errors)}/
@@ -52,13 +52,12 @@ module Sequel
52
52
  #
53
53
  # Sequel.datetime_class = DateTime
54
54
  #
55
- # Note that +Time+ and +DateTime+ objects
56
- # have a different API, and in cases where they implement the same methods,
57
- # they often implement them differently (e.g. + using seconds on +Time+ and
58
- # days on +DateTime+).
55
+ # Note that +Time+ and +DateTime+ objects have a different API, and in
56
+ # cases where they implement the same methods, they often implement them
57
+ # differently (e.g. + using seconds on +Time+ and days on +DateTime+).
59
58
  attr_accessor :datetime_class
60
59
 
61
- # Set whether Sequel is being used in single threaded mode. by default,
60
+ # Set whether Sequel is being used in single threaded mode. By default,
62
61
  # Sequel uses a thread-safe connection pool, which isn't as fast as the
63
62
  # single threaded connection pool, and also has some additional thread
64
63
  # safety checks. If your program will only have one thread,
@@ -67,7 +66,7 @@ module Sequel
67
66
  # Sequel.single_threaded = true
68
67
  attr_accessor :single_threaded
69
68
 
70
- # Alias of original require method, as Sequel.require is does a relative
69
+ # Alias of original require method, as Sequel.require does a relative
71
70
  # require for backwards compatibility.
72
71
  alias orig_require require
73
72
  private :orig_require
@@ -55,7 +55,6 @@ module Sequel
55
55
 
56
56
  begin
57
57
  db = c.new(opts)
58
- db.test_connection if db.send(:typecast_value_boolean, opts.fetch(:test, true))
59
58
  if block_given?
60
59
  return yield(db)
61
60
  end
@@ -166,6 +166,7 @@ module Sequel
166
166
  end
167
167
 
168
168
  initialize_load_extensions(:extensions)
169
+ test_connection if typecast_value_boolean(@opts.fetch(:test, true)) && respond_to?(:connect, true)
169
170
  rescue
170
171
  Sequel.synchronize{::Sequel::DATABASES.delete(self)} if keep_reference
171
172
  raise
@@ -446,6 +447,19 @@ module Sequel
446
447
  end
447
448
  end
448
449
 
450
+ # Swallow database errors, unless they are connect/disconnect errors.
451
+ def swallow_database_error
452
+ yield
453
+ rescue Sequel::DatabaseDisconnectError, DatabaseConnectionError
454
+ # Always raise disconnect errors
455
+ raise
456
+ rescue Sequel::DatabaseError
457
+ # Don't raise other database errors.
458
+ nil
459
+ # else
460
+ # Don't rescue other exceptions, they will be raised normally.
461
+ end
462
+
449
463
  # Typecast the value to an SQL::Blob
450
464
  def typecast_value_blob(value)
451
465
  value.is_a?(Sequel::SQL::Blob) ? value : Sequel::SQL::Blob.new(value)
@@ -143,8 +143,14 @@ module Sequel
143
143
  # :identity :: Create an identity column.
144
144
  #
145
145
  # MySQL specific options:
146
+ #
146
147
  # :generated_type :: Set the type of column when using :generated_always_as,
147
148
  # should be :virtual or :stored to force a type.
149
+ #
150
+ # Microsoft SQL Server specific options:
151
+ #
152
+ # :clustered :: When using :primary_key or :unique, marks the primary key or unique
153
+ # constraint as CLUSTERED (if true), or NONCLUSTERED (if false).
148
154
  def column(name, type, opts = OPTS)
149
155
  columns << {:name => name, :type => type}.merge!(opts)
150
156
  if index_opts = opts[:index]