for account in accounts: account_id = account.get("account_id", "") account_name = account.get("account_name", "") with crm_db_manager.get_session() as session: # Method 1: Raw SQL query (most reliable) try: result = session.execute( "SELECT * FROM crm_accounts WHERE unique_id = :account_id", {"account_id": account_id} ).fetchone() logger.info(f"Raw SQL result: {result}") except Exception as e: logger.error(f"Raw SQL query failed: {e}") # Method 2: Dynamic table query using reflection try: from sqlalchemy import Table, MetaData metadata = MetaData() crm_accounts_table = Table('crm_accounts', metadata, autoload_with=crm_db_manager.engine) result = session.query(crm_accounts_table).filter( crm_accounts_table.c.unique_id == account_id ).first() logger.info(f"Dynamic table result: {result}") except Exception as e: logger.error(f"Dynamic table query failed: {e}") # Method 3: Get table columns first, then query try: # Get actual columns from database columns_result = session.execute( "SHOW COLUMNS FROM crm_accounts" ).fetchall() actual_columns = [col[0] for col in columns_result] logger.info(f"Actual columns in crm_accounts: {actual_columns}") # Build query with only existing columns select_columns = ", ".join(actual_columns) result = session.execute( f"SELECT {select_columns} FROM crm_accounts WHERE unique_id = :account_id", {"account_id": account_id} ).fetchone() logger.info(f"Column-aware result: {result}") except Exception as e: logger.error(f"Column-aware query failed: {e}") # Original method (commented out due to model mismatch) # account = session.query(CRMAccount).filter(CRMAccount.unique_id == account_id).first() # logger.info(f"account: {account}")