@@ -160,7 +160,7 @@ def save_soilgrids_output(plot_id, model_version, soilgrids_blob):
160
160
conn .close ()
161
161
162
162
163
- def get_hwsd2_profile_data (conn , hwsd2_mu_select ):
163
+ def get_hwsd2_profile_data (connection , hwsd2_mu_select ):
164
164
"""
165
165
Retrieve HWSD v2 data based on selected hwsd2 (map unit) values.
166
166
This version reuses an existing connection.
@@ -177,7 +177,7 @@ def get_hwsd2_profile_data(conn, hwsd2_mu_select):
177
177
return pd .DataFrame ()
178
178
179
179
try :
180
- with conn .cursor () as cur :
180
+ with connection .cursor () as cur :
181
181
# Create placeholders for the SQL IN clause
182
182
placeholders = ", " .join (["%s" ] * len (hwsd2_mu_select ))
183
183
sql_query = f"""
@@ -220,7 +220,7 @@ def get_hwsd2_profile_data(conn, hwsd2_mu_select):
220
220
return pd .DataFrame ()
221
221
222
222
223
- def extract_hwsd2_data (lon , lat , buffer_dist , table_name ):
223
+ def extract_hwsd2_data (connection , lon , lat , buffer_dist , table_name ):
224
224
"""
225
225
Fetches HWSD soil data from a PostGIS table within a given buffer around a point,
226
226
performing distance and intersection calculations directly on geographic coordinates.
@@ -234,26 +234,24 @@ def extract_hwsd2_data(lon, lat, buffer_dist, table_name):
234
234
Returns:
235
235
DataFrame: Merged data from hwsdv2 and hwsdv2_data.
236
236
"""
237
- # Use a single connection for both queries.
238
- with get_datastore_connection () as conn :
239
- # Compute the buffer polygon (in WKT) around the problem point.
240
- # Here, we use the geography type to compute a buffer in meters,
241
- # then cast it back to geometry in EPSG:4326.
242
- buffer_query = """
243
- WITH buffer AS (
244
- SELECT ST_AsText(
245
- ST_Buffer(
246
- ST_SetSRID(ST_Point(%s, %s), 4326)::geography,
247
- %s
248
- )::geometry
249
- ) AS wkt
250
- )
251
- SELECT wkt FROM buffer;
252
- """
253
- with conn .cursor () as cur :
254
- cur .execute (buffer_query , (lon , lat , buffer_dist ))
255
- buffer_wkt = cur .fetchone ()[0 ]
256
- print ("Buffer WKT:" , buffer_wkt )
237
+ # Compute the buffer polygon (in WKT) around the problem point.
238
+ # Here, we use the geography type to compute a buffer in meters,
239
+ # then cast it back to geometry in EPSG:4326.
240
+ buffer_query = """
241
+ WITH buffer AS (
242
+ SELECT ST_AsText(
243
+ ST_Buffer(
244
+ ST_SetSRID(ST_Point(%s, %s), 4326)::geography,
245
+ %s
246
+ )::geometry
247
+ ) AS wkt
248
+ )
249
+ SELECT wkt FROM buffer;
250
+ """
251
+ with connection .cursor () as cur :
252
+ cur .execute (buffer_query , (lon , lat , buffer_dist ))
253
+ buffer_wkt = cur .fetchone ()[0 ]
254
+ print ("Buffer WKT:" , buffer_wkt )
257
255
258
256
# Build the main query that uses the computed buffer.
259
257
# Distance is computed by casting geometries to geography,
@@ -344,7 +342,7 @@ def extract_hwsd2_data(lon, lat, buffer_dist, table_name):
344
342
# """
345
343
346
344
# Use GeoPandas to execute the main query and load results into a GeoDataFrame.
347
- hwsd = gpd .read_postgis (main_query , conn , geom_col = "geom" )
345
+ hwsd = gpd .read_postgis (main_query , connection , geom_col = "geom" )
348
346
print ("Main query returned" , len (hwsd ), "rows." )
349
347
350
348
# Remove the geometry column (if not needed) from this dataset.
@@ -354,7 +352,7 @@ def extract_hwsd2_data(lon, lat, buffer_dist, table_name):
354
352
hwsd2_mu_select = hwsd ["hwsd2" ].tolist ()
355
353
356
354
# Call get_hwsd2_profile_data using the same connection.
357
- hwsd_data = get_hwsd2_profile_data (conn , hwsd2_mu_select )
355
+ hwsd_data = get_hwsd2_profile_data (connection , hwsd2_mu_select )
358
356
359
357
# Merge the two datasets.
360
358
merged = pd .merge (hwsd_data , hwsd , on = "hwsd2" , how = "left" ).drop_duplicates ()
@@ -365,46 +363,37 @@ def extract_hwsd2_data(lon, lat, buffer_dist, table_name):
365
363
366
364
367
365
# Function to fetch data from a PostgreSQL table
368
- def fetch_table_from_db (table_name ):
369
- conn = None
366
+ def fetch_table_from_db (connection , table_name ):
370
367
try :
371
- conn = get_datastore_connection ()
372
- cur = conn .cursor ()
373
-
374
- query = f"SELECT * FROM { table_name } ORDER BY id ASC;"
375
- cur .execute (query )
376
- rows = cur .fetchall ()
368
+ with connection .cursor () as cur :
369
+ query = f"SELECT * FROM { table_name } ORDER BY id ASC;"
370
+ cur .execute (query )
371
+ rows = cur .fetchall ()
377
372
378
- return rows
373
+ return rows
379
374
380
375
except Exception as err :
381
376
logging .error (f"Error querying PostgreSQL: { err } " )
382
377
return None
383
378
384
- finally :
385
- if conn :
386
- conn .close ()
387
-
388
379
389
- def get_WRB_descriptions (WRB_Comp_List ):
380
+ def get_WRB_descriptions (connection , WRB_Comp_List ):
390
381
"""
391
382
Retrieve WRB descriptions based on provided WRB component list.
392
383
"""
393
- conn = None
394
384
try :
395
- conn = get_datastore_connection ()
396
- cur = conn .cursor ()
397
-
398
- # Create placeholders for the SQL IN clause
399
- placeholders = ", " .join (["%s" ] * len (WRB_Comp_List ))
400
- sql = f"""SELECT WRB_tax, Description_en, Management_en, Description_es, Management_es,
401
- Description_ks, Management_ks, Description_fr, Management_fr
402
- FROM wrb_fao90_desc
403
- WHERE WRB_tax IN ({ placeholders } )"""
385
+ with connection .cursor () as cur :
404
386
405
- # Execute the query with the parameters
406
- cur .execute (sql , tuple (WRB_Comp_List ))
407
- results = cur .fetchall ()
387
+ # Create placeholders for the SQL IN clause
388
+ placeholders = ", " .join (["%s" ] * len (WRB_Comp_List ))
389
+ sql = f"""SELECT WRB_tax, Description_en, Management_en, Description_es, Management_es,
390
+ Description_ks, Management_ks, Description_fr, Management_fr
391
+ FROM wrb_fao90_desc
392
+ WHERE WRB_tax IN ({ placeholders } )"""
393
+
394
+ # Execute the query with the parameters
395
+ cur .execute (sql , tuple (WRB_Comp_List ))
396
+ results = cur .fetchall ()
408
397
409
398
# Convert the results to a pandas DataFrame
410
399
data = pd .DataFrame (
@@ -423,18 +412,13 @@ def get_WRB_descriptions(WRB_Comp_List):
423
412
)
424
413
425
414
return data
426
-
427
415
except Exception as err :
428
416
logging .error (f"Error querying PostgreSQL: { err } " )
429
417
return None
430
418
431
- finally :
432
- if conn :
433
- conn .close ()
434
-
435
419
436
420
# global only
437
- def getSG_descriptions (WRB_Comp_List ):
421
+ def getSG_descriptions (connection , WRB_Comp_List ):
438
422
"""
439
423
Fetch WRB descriptions from a PostgreSQL database using wrb2006_to_fao90
440
424
and wrb_fao90_desc tables. Returns a pandas DataFrame with columns:
@@ -447,13 +431,10 @@ def getSG_descriptions(WRB_Comp_List):
447
431
pandas.DataFrame or None if an error occurs.
448
432
"""
449
433
450
- conn = None
451
434
try :
452
- # 1. Get a connection to your datastore (replace with your actual function):
453
- conn = get_datastore_connection ()
454
435
455
436
def execute_query (query , params ):
456
- with conn .cursor () as cur :
437
+ with connection .cursor () as cur :
457
438
# Execute the query with the parameters
458
439
cur .execute (query , params )
459
440
return cur .fetchall ()
@@ -524,7 +505,3 @@ def execute_query(query, params):
524
505
except Exception as err :
525
506
logging .error (f"Error querying PostgreSQL: { err } " )
526
507
return None
527
-
528
- finally :
529
- if conn :
530
- conn .close ()
0 commit comments