diff options
author | Yasuo Honda <yasuo.honda@gmail.com> | 2017-04-18 12:16:58 +0000 |
---|---|---|
committer | Yasuo Honda <yasuo.honda@gmail.com> | 2017-05-30 16:45:20 +0000 |
commit | 47cb924d9122fc00deeb9aa4db7a92685ae9e7ef (patch) | |
tree | a919fe80ba9b08a745dc95f5f18eaed627c252ca | |
parent | eb804ad5a783e1e97720ef55a91b6aae7ebd724f (diff) | |
download | rails-47cb924d9122fc00deeb9aa4db7a92685ae9e7ef.tar.gz rails-47cb924d9122fc00deeb9aa4db7a92685ae9e7ef.tar.bz2 rails-47cb924d9122fc00deeb9aa4db7a92685ae9e7ef.zip |
Support PostgreSQL 10 `pg_sequence`
Another fix for #28780 based on discussions at #28789
- In PostgreSQL 10 each sequence does not know its `min_value`.
A new system catalog `pg_sequence` shows it as `seqmin`.
Refer https://github.com/postgres/postgres/commit/1753b1b027035029c2a2a1649065762fafbf63f3
- `setval` 3rd argument needs to set to `false` only when the table has no rows
to avoid `nextval(<sequence_name>)` returns `2` where `1` is expected.
- `min_value` is only necessary when the table has no rows. It used to be necessary
since the 3rd argument of `setval` is always `false`.
-rw-r--r-- | activerecord/lib/active_record/connection_adapters/postgresql/schema_statements.rb | 10 |
1 files changed, 9 insertions, 1 deletions
diff --git a/activerecord/lib/active_record/connection_adapters/postgresql/schema_statements.rb b/activerecord/lib/active_record/connection_adapters/postgresql/schema_statements.rb index 55566f1e34..cb45d7ba6b 100644 --- a/activerecord/lib/active_record/connection_adapters/postgresql/schema_statements.rb +++ b/activerecord/lib/active_record/connection_adapters/postgresql/schema_statements.rb @@ -290,9 +290,17 @@ module ActiveRecord if pk && sequence quoted_sequence = quote_table_name(sequence) + max_pk = select_value("select MAX(#{quote_column_name pk}) from #{quote_table_name(table)}") + if max_pk.nil? + if postgresql_version >= 100000 + minvalue = select_value("SELECT seqmin from pg_sequence where seqrelid = '#{quoted_sequence}'::regclass") + else + minvalue = select_value("SELECT min_value FROM #{quoted_sequence}") + end + end select_value(<<-end_sql, "SCHEMA") - SELECT setval('#{quoted_sequence}', (SELECT COALESCE(MAX(#{quote_column_name pk})+(SELECT increment_by FROM #{quoted_sequence}), (SELECT min_value FROM #{quoted_sequence})) FROM #{quote_table_name(table)}), false) + SELECT setval('#{quoted_sequence}', #{max_pk ? max_pk : minvalue}, #{max_pk ? true : false}) end_sql end end |