lib/monkey_patch_postgres.rb in partitioned-1.0.1 vs lib/monkey_patch_postgres.rb in partitioned-1.1.0
- old
+ new
@@ -1,8 +1,9 @@
require 'active_record'
require 'active_record/base'
require 'active_record/connection_adapters/abstract_adapter'
+require 'active_record/connection_adapters/postgresql_adapter'
#
# Patching {ActiveRecord::ConnectionAdapters::TableDefinition} and
# {ActiveRecord::ConnectionAdapters::PostgreSQLAdapter} to add functionality
# needed to abstract partition specific SQL statements.
@@ -26,18 +27,35 @@
# sequences (and sets of sequence values), schemas and foreign keys.
# These should go into AbstractAdapter allowing any database adapter
# to take advantage of these SQL builders.
#
class PostgreSQLAdapter < AbstractAdapter
+
#
+ # Returns the sequence name for a table's primary key or some other specified key.
+ #
+ # the default version strips off the schema name on the table (if it exists), as:
+ # serial_sequence(table_name, pk || 'id').split('.').last
+ # i can't see any good reason for that -- in fact, it seems completely
+ # broken -- if you have a table public.foos and other.foos, you'll fail to
+ # get the correct schema if you fetch the default schema name from model
+ # associated with other.foos
+ #
+ def default_sequence_name(table_name, pk = nil) #:nodoc:
+ serial_sequence(table_name, pk || 'id')
+ rescue ActiveRecord::StatementInvalid => e
+ "#{table_name}_#{pk || 'id'}_seq"
+ end
+
+ #
# Get the next value in a sequence. Used on INSERT operation for
# partitioning like by_id because the ID is required before the insert
# so that the specific child table is known ahead of time.
#
# @param [String] sequence_name the name of the sequence to fetch the next value from
# @return [Integer] the value from the sequence
def next_sequence_value(sequence_name)
- return execute("select nextval('#{sequence_name}')").field_values("nextval").first
+ return execute("select nextval('#{sequence_name}')").field_values("nextval").first.to_i
end
#
# Get the some next values in a sequence.
#