@@ -162,11 +162,14 @@ def table_options(table_name) # :nodoc:
162162
163163 options [ :comment ] = comment if comment
164164
165+ partition_bound_definition = table_partition_bound_definition ( table_name )
165166 inherited_table_names = inherited_table_names ( table_name ) . presence
166167
167- options [ :options ] = "INHERITS (#{ inherited_table_names . join ( ", " ) } )" if inherited_table_names
168-
169- if !options [ :options ] && supports_native_partitioning?
168+ # Can't use :options for declarative partitioning. Partition will be attached
169+ # via a separate 'ALTER TABLE ... ATTACH PARTITION ...' call.
170+ if inherited_table_names && !partition_bound_definition
171+ options [ :options ] = "INHERITS (#{ inherited_table_names . join ( ", " ) } )"
172+ elsif supports_native_partitioning?
170173 partition_definition = table_partition_definition ( table_name )
171174
172175 options [ :options ] = "PARTITION BY #{ partition_definition } " if partition_definition
@@ -190,7 +193,7 @@ def table_comment(table_name) # :nodoc:
190193 end
191194 end
192195
193- # Returns the partition definition of a given table
196+ # Returns the partitioned table definition of a given table
194197 def table_partition_definition ( table_name ) # :nodoc:
195198 scope = quoted_scope ( table_name , type : "BASE TABLE" )
196199
@@ -220,6 +223,21 @@ def inherited_table_names(table_name) # :nodoc:
220223 SQL
221224 end
222225
226+ # Returns the partition definition of a given table
227+ def table_partition_bound_definition ( table_name ) # :nodoc:
228+ scope = quoted_scope ( table_name , type : "BASE TABLE" )
229+
230+ query_value ( <<~SQL , "SCHEMA" )
231+ SELECT pg_catalog.pg_get_expr(c.relpartbound, c.oid)
232+ FROM pg_catalog.pg_class c
233+ LEFT JOIN pg_namespace n ON n.oid = c.relnamespace
234+ WHERE c.relname = #{ scope [ :name ] }
235+ AND c.relkind IN (#{ scope [ :type ] } )
236+ AND n.nspname = #{ scope [ :schema ] }
237+ AND c.relispartition
238+ SQL
239+ end
240+
223241 # Returns the current database name.
224242 def current_database
225243 query_value ( "SELECT current_database()" , "SCHEMA" )
0 commit comments