@@ -117,14 +117,15 @@ def write_to_table(
117117 SQLAlchemyError: For database errors
118118
119119 """
120- if not isinstance (session , Session ):
121- raise TypeError ("Session must be a SQLAlchemy session" )
122120 if if_exists not in ["error" , "replace" , "update" , "ignore" ]:
123121 raise ValueError ("on_conflict must be one of: 'error', 'replace', 'update', 'ignore'" )
124122
125123 if ENV_VARS .ROUTE_TO_BACKEND .get_value ():
126124 return {"table" : table , "data" : data , "if_exists" : if_exists }
127125
126+ if not isinstance (session , Session ):
127+ raise TypeError ("Session must be a SQLAlchemy session" )
128+
128129 try :
129130 TableModel = resolve_table_model (table ) # noqa: N806
130131 inspector = inspect (TableModel )
@@ -201,7 +202,7 @@ def build_pk_conditions(
201202 pk_conditions .append (getattr (TableModel , pk ) == data [pk ])
202203 else :
203204 logger .debug (f"{ pk } is primary but not in data" )
204- logger .debug (f"{ pk_conditions = } " )
205+ logger .debug (f"pk_conditions={ ', ' . join ([ str ( x ) for x in pk_conditions ]) } " )
205206 return pk_conditions
206207
207208
@@ -225,7 +226,7 @@ def extract_unique_constraints(inspector: Any, data: dict[str, Any]):
225226 cols = [col .key for col in constraint .columns ]
226227 if all (col in data for col in cols ):
227228 unique_constraints .append ([(col , data [col ]) for col in cols ])
228- logger .debug (f"{ unique_constraints = } " )
229+ logger .debug (f"unique_constraints={ ', ' . join ([ str ( x ) for x in unique_constraints ]) } " )
229230 return unique_constraints
230231
231232
@@ -327,8 +328,6 @@ def handle_existing_entry( # noqa: PLR0913
327328@route_or_direct ("load_time_data" , send_file = True )
328329def load_time_data (probe_key : ProbeKey , data : pd .DataFrame , session : Optional [Session ] = None ):
329330 """Load time series data"""
330- if not isinstance (session , Session ):
331- raise TypeError ("Session must be a SQLAlchemy session" )
332331 route_to_backend = ENV_VARS .ROUTE_TO_BACKEND .get_value ()
333332 if route_to_backend :
334333 csv_data = data .to_csv (index = False ).encode ("utf-8" )
@@ -339,6 +338,8 @@ def load_time_data(probe_key: ProbeKey, data: pd.DataFrame, session: Optional[Se
339338
340339 from opensampl .db .orm import ProbeData , ProbeMetadata
341340
341+ if not isinstance (session , Session ):
342+ raise TypeError ("Session must be a SQLAlchemy session" )
342343 try :
343344 # Verify probe exists and get UUID
344345 probe = (
@@ -357,9 +358,10 @@ def load_time_data(probe_key: ProbeKey, data: pd.DataFrame, session: Optional[Se
357358 df ["probe_uuid" ] = probe .uuid
358359
359360 # Ensure correct dtypes
360- df = df .astype ({"time" : "datetime64[ns]" , "value" : "float64" , "probe_uuid" : str })
361+ df ["time" ] = pd .to_datetime (df ["time" ], utc = True , errors = "raise" )
362+ df = df .astype ({"value" : "float64" , "probe_uuid" : str })
361363
362- dtype = {column .name : column .type_ for column in ProbeData .__table__ .columns }
364+ dtype = {column .name : column .type for column in ProbeData .__table__ .columns }
363365
364366 # Write directly to database using pandas
365367 df .to_sql (
@@ -387,8 +389,6 @@ def load_probe_metadata(
387389 session : Optional [Session ] = None ,
388390):
389391 """Write object to table"""
390- if not isinstance (session , Session ):
391- raise TypeError ("Session must be a SQLAlchemy session" )
392392 route_to_backend = ENV_VARS .ROUTE_TO_BACKEND .get_value ()
393393 if route_to_backend :
394394 return {
@@ -397,6 +397,9 @@ def load_probe_metadata(
397397 "data" : data ,
398398 }
399399
400+ if not isinstance (session , Session ):
401+ raise TypeError ("Session must be a SQLAlchemy session" )
402+
400403 try :
401404 from opensampl .db .orm import ProbeMetadata
402405
@@ -428,11 +431,13 @@ def load_probe_metadata(
428431@route_or_direct ("create_new_tables" , method = "GET" )
429432def create_new_tables (create_schema : bool = True , session : Optional [Session ] = None ):
430433 """Use the ORM definition to create all tables, optionally creating the schema as well"""
431- if not isinstance (session , Session ):
432- raise TypeError ("Session must be a SQLAlchemy session" )
433434 route_to_backend = ENV_VARS .ROUTE_TO_BACKEND .get_value ()
434435 if route_to_backend :
435436 return {"create_schema" : create_schema }
437+
438+ if not isinstance (session , Session ):
439+ raise TypeError ("Session must be a SQLAlchemy session" )
440+
436441 try :
437442 if create_schema :
438443 session .execute (text (f"CREATE SCHEMA IF NOT EXISTS { Base .metadata .schema } " ))
0 commit comments