66#include "access/nbtree.h"
77#include "access/xact.h"
88#include "catalog/pg_type.h"
9- #include "executor/spi.h"
9+ // #include "executor/spi.h"
1010#include "storage/lmgr.h"
1111
1212
13+ #include "miscadmin.h"
14+
15+
1316/* declarations */
1417PG_FUNCTION_INFO_V1 (on_partitions_created );
1518PG_FUNCTION_INFO_V1 (on_partitions_updated );
@@ -116,16 +119,9 @@ find_or_create_range_partition(PG_FUNCTION_ARGS)
116119PG_RETURN_OID (ranges [pos ].child_oid );
117120else
118121{
119- int ret ;
120- Datum vals [4 ];
121- Oid oids []= {OIDOID ,value_type ,value_type ,value_type };
122- bool nulls []= {false, false, false, false};
123- RangeEntry * re = & ranges [rangerel -> ranges .length - 1 ];
124- int cmp_upper = FunctionCall2 (& cmp_func ,value ,ranges [rangerel -> ranges .length - 1 ].max );
125- int cmp_lower = FunctionCall2 (& cmp_func ,value ,ranges [0 ].min );
126- char * sql ;
127-
128- /* Lock relation before appending new partitions */
122+ Oid child_oid ;
123+
124+ /* Lock config before appending new partitions */
129125LWLockAcquire (load_config_lock ,LW_EXCLUSIVE );
130126
131127/*
@@ -139,45 +135,17 @@ find_or_create_range_partition(PG_FUNCTION_ARGS)
139135PG_RETURN_OID (ranges [pos ].child_oid );
140136}
141137
142- /* Determine nearest range partition */
143- if (cmp_upper > 0 )
144- re = & ranges [rangerel -> ranges .length - 1 ];
145- else if (cmp_lower < 0 )
146- re = & ranges [0 ];
147-
148- vals [0 ]= ObjectIdGetDatum (relid );
149- vals [1 ]= re -> min ;
150- vals [2 ]= re -> max ;
151- vals [3 ]= value ;
152-
153- /* Create new partitions */
154- SPI_connect ();
155- sql = psprintf ("SELECT %s.append_partitions_on_demand_internal($1, $2, $3, $4)" ,
156- get_extension_schema ());
157- ret = SPI_execute_with_args (sql ,4 ,oids ,vals ,nulls , false,0 );
158- // ret = SPI_execute_with_args("SELECT append_partitions_on_demand_internal($1, $2, $3, $4)",
159- // 4, oids, vals, nulls, false, 0);
160- if (ret > 0 )
161- {
162- /* Update relation info */
163- free_dsm_array (& rangerel -> ranges );
164- free_dsm_array (& prel -> children );
165- load_check_constraints (relid ,GetCatalogSnapshot (relid ));
166- }
167- else
168- elog (WARNING ,"Attempt to create new partitions failed" );
169-
170- SPI_finish ();
138+ /* Start background worker to create new partitions */
139+ child_oid = create_partitions_bg_worker (relid ,value ,value_type );
171140
172- /* Releaselocks */
141+ /* Releaselock */
173142LWLockRelease (load_config_lock );
174- // pfree(sql);
175143
176144/* Repeat binary search */
177145ranges = dsm_array_get_pointer (& rangerel -> ranges );
178146pos = range_binary_search (rangerel ,& cmp_func ,value ,& found );
179147if (found )
180- PG_RETURN_OID (ranges [ pos ]. child_oid );
148+ PG_RETURN_OID (child_oid );
181149}
182150
183151PG_RETURN_NULL ();