lib/pgslice.rb in pgslice-0.1.2 vs lib/pgslice.rb in pgslice-0.1.3

- old
+ new

@@ -61,11 +61,11 @@ queries = [] queries << <<-SQL CREATE TABLE #{intermediate_table} ( - LIKE #{table} INCLUDING INDEXES INCLUDING DEFAULTS + LIKE #{table} INCLUDING ALL ); SQL sql_format = SQL_FORMAT[period.to_sym] queries << <<-SQL @@ -120,21 +120,29 @@ period, field, name_format, inc, today = settings_from_table(original_table, table) days = range.map { |n| today + (n * inc) } queries = [] + index_defs = execute("select pg_get_indexdef(indexrelid) from pg_index where indrelid = $1::regclass AND indisprimary = 'f'", [original_table]).map { |r| r["pg_get_indexdef"] } + primary_key = self.primary_key(table) + days.each do |day| partition_name = "#{original_table}_#{day.strftime(name_format)}" next if table_exists?(partition_name) date_format = "%Y-%m-%d" queries << <<-SQL CREATE TABLE #{partition_name} ( - LIKE #{table} INCLUDING INDEXES INCLUDING DEFAULTS, CHECK (#{field} >= '#{day.strftime(date_format)}'::date AND #{field} < '#{(day + inc).strftime(date_format)}'::date) ) INHERITS (#{table}); SQL + + queries << "ALTER TABLE #{partition_name} ADD PRIMARY KEY (#{primary_key});" + + index_defs.each do |index_def| + queries << index_def.sub(" ON #{original_table} USING ", " ON #{partition_name} USING ").sub(/ INDEX .+ ON /, " INDEX ON ") + ";" + end end run_queries(queries) if queries.any? end