fix: resolve SQLModel migrations for .exec() -> .execute().scalars() and API schema issues

This commit is contained in:
oib
2026-03-05 08:28:40 +01:00
parent bbbfbf8dde
commit 1f16a1c406
37 changed files with 243 additions and 238 deletions

View File

@@ -418,10 +418,10 @@ async def get_pricing(
) -> Dict[str, Any]:
"""Get enhanced pricing information for a model with dynamic pricing."""
# SQLite JSON doesn't support array contains, so fetch all and filter in Python
all_gpus = session.execute(select(GPURegistry)).all()
all_gpus = session.execute(select(GPURegistry)).scalars().all()
compatible = [
g for g in all_gpus
if any(model.lower() in cap.lower() for cap in (g.capabilities or []))
if model.lower() in g.model.lower()
]
if not compatible:

View File

@@ -630,7 +630,7 @@ class AdvancedReinforcementLearningEngine:
async def train_rl_agent(self, session: Session, config_id: str) -> Dict[str, Any]:
"""Train RL agent"""
rl_config = session.exec(
rl_config = session.execute(
select(ReinforcementLearningConfig).where(ReinforcementLearningConfig.config_id == config_id)
).first()
@@ -1404,7 +1404,7 @@ class MarketplaceStrategyOptimizer:
await asyncio.sleep(1) # Simulate training time
# Get trained agent performance
trained_config = session.exec(
trained_config = session.execute(
select(ReinforcementLearningConfig).where(
ReinforcementLearningConfig.config_id == rl_config.config_id
)
@@ -1435,7 +1435,7 @@ class MarketplaceStrategyOptimizer:
) -> Dict[str, Any]:
"""Deploy trained strategy"""
rl_config = session.exec(
rl_config = session.execute(
select(ReinforcementLearningConfig).where(
ReinforcementLearningConfig.config_id == config_id
)
@@ -1521,7 +1521,7 @@ class CrossDomainCapabilityIntegrator:
"""Integrate capabilities across different domains"""
# Get agent capabilities
agent_capabilities = session.exec(
agent_capabilities = session.execute(
select(AgentCapability).where(AgentCapability.agent_id == agent_id)
).all()

View File

@@ -178,7 +178,7 @@ class AgentIntegrationManager:
try:
# Get execution details
execution = self.session.exec(
execution = self.session.execute(
select(AgentExecution).where(AgentExecution.id == execution_id)
).first()
@@ -186,7 +186,7 @@ class AgentIntegrationManager:
raise ValueError(f"Execution not found: {execution_id}")
# Get step executions
step_executions = self.session.exec(
step_executions = self.session.execute(
select(AgentStepExecution).where(
AgentStepExecution.execution_id == execution_id
)
@@ -557,7 +557,7 @@ class AgentDeploymentManager:
raise ValueError(f"Deployment config not found: {deployment_config_id}")
# Get deployment instances
instances = self.session.exec(
instances = self.session.execute(
select(AgentDeploymentInstance).where(
AgentDeploymentInstance.deployment_id == deployment_config_id
)
@@ -671,7 +671,7 @@ class AgentDeploymentManager:
raise ValueError(f"Deployment config not found: {deployment_config_id}")
# Get current instances
current_instances = self.session.exec(
current_instances = self.session.execute(
select(AgentDeploymentInstance).where(
AgentDeploymentInstance.deployment_id == deployment_config_id
)
@@ -767,7 +767,7 @@ class AgentDeploymentManager:
}
# Get current instances
current_instances = self.session.exec(
current_instances = self.session.execute(
select(AgentDeploymentInstance).where(
AgentDeploymentInstance.deployment_id == deployment_config_id
)
@@ -846,7 +846,7 @@ class AgentMonitoringManager:
raise ValueError(f"Deployment config not found: {deployment_config_id}")
# Get deployment instances
instances = self.session.exec(
instances = self.session.execute(
select(AgentDeploymentInstance).where(
AgentDeploymentInstance.deployment_id == deployment_config_id
)

View File

@@ -91,7 +91,7 @@ class MetaLearningEngine:
async def train_meta_model(self, session: Session, model_id: str) -> Dict[str, Any]:
"""Train a meta-learning model"""
model = session.exec(
model = session.execute(
select(MetaLearningModel).where(MetaLearningModel.model_id == model_id)
).first()
@@ -194,7 +194,7 @@ class MetaLearningEngine:
) -> Dict[str, Any]:
"""Adapt meta-learning model to new task"""
model = session.exec(
model = session.execute(
select(MetaLearningModel).where(MetaLearningModel.model_id == model_id)
).first()
@@ -1003,7 +1003,7 @@ class AgentPerformanceService:
) -> AgentPerformanceProfile:
"""Update agent performance metrics"""
profile = self.session.exec(
profile = self.session.execute(
select(AgentPerformanceProfile).where(AgentPerformanceProfile.agent_id == agent_id)
).first()
@@ -1089,7 +1089,7 @@ class AgentPerformanceService:
) -> Dict[str, Any]:
"""Get comprehensive agent performance profile"""
profile = self.session.exec(
profile = self.session.execute(
select(AgentPerformanceProfile).where(AgentPerformanceProfile.agent_id == agent_id)
).first()

View File

@@ -77,7 +77,7 @@ class AgentPortfolioManager:
raise HTTPException(status_code=400, detail="Invalid agent address")
# Check if portfolio already exists
existing_portfolio = self.session.exec(
existing_portfolio = self.session.execute(
select(AgentPortfolio).where(
AgentPortfolio.agent_address == agent_address
)
@@ -289,7 +289,7 @@ class AgentPortfolioManager:
)
# Update risk metrics in database
existing_metrics = self.session.exec(
existing_metrics = self.session.execute(
select(RiskMetrics).where(RiskMetrics.portfolio_id == portfolio.id)
).first()
@@ -382,7 +382,7 @@ class AgentPortfolioManager:
def _get_agent_portfolio(self, agent_address: str) -> AgentPortfolio:
"""Get portfolio for agent address"""
portfolio = self.session.exec(
portfolio = self.session.execute(
select(AgentPortfolio).where(
AgentPortfolio.agent_address == agent_address
)
@@ -456,7 +456,7 @@ class AgentPortfolioManager:
"""Validate trade request"""
# Check if sell token exists in portfolio
sell_asset = self.session.exec(
sell_asset = self.session.execute(
select(PortfolioAsset).where(
PortfolioAsset.portfolio_id == portfolio.id,
PortfolioAsset.token_symbol == trade_request.sell_token
@@ -507,7 +507,7 @@ class AgentPortfolioManager:
"""Update portfolio assets after trade"""
# Update sell asset
sell_asset = self.session.exec(
sell_asset = self.session.execute(
select(PortfolioAsset).where(
PortfolioAsset.portfolio_id == portfolio.id,
PortfolioAsset.token_symbol == trade.sell_token
@@ -519,7 +519,7 @@ class AgentPortfolioManager:
sell_asset.updated_at = datetime.utcnow()
# Update buy asset
buy_asset = self.session.exec(
buy_asset = self.session.execute(
select(PortfolioAsset).where(
PortfolioAsset.portfolio_id == portfolio.id,
PortfolioAsset.token_symbol == trade.buy_token
@@ -547,7 +547,7 @@ class AgentPortfolioManager:
portfolio_value = await self._calculate_portfolio_value(portfolio)
# Update current allocations
assets = self.session.exec(
assets = self.session.execute(
select(PortfolioAsset).where(
PortfolioAsset.portfolio_id == portfolio.id
)
@@ -566,7 +566,7 @@ class AgentPortfolioManager:
async def _calculate_portfolio_value(self, portfolio: AgentPortfolio) -> float:
"""Calculate total portfolio value"""
assets = self.session.exec(
assets = self.session.execute(
select(PortfolioAsset).where(
PortfolioAsset.portfolio_id == portfolio.id
)
@@ -593,7 +593,7 @@ class AgentPortfolioManager:
return True
# Check threshold-based rebalancing
assets = self.session.exec(
assets = self.session.execute(
select(PortfolioAsset).where(
PortfolioAsset.portfolio_id == portfolio.id
)
@@ -615,7 +615,7 @@ class AgentPortfolioManager:
"""Generate rebalancing trades"""
trades = []
assets = self.session.exec(
assets = self.session.execute(
select(PortfolioAsset).where(
PortfolioAsset.portfolio_id == portfolio.id
)
@@ -657,7 +657,7 @@ class AgentPortfolioManager:
"""Calculate portfolio performance metrics"""
# Get historical trades
trades = self.session.exec(
trades = self.session.execute(
select(PortfolioTrade)
.where(PortfolioTrade.portfolio_id == portfolio.id)
.order_by(PortfolioTrade.executed_at.desc())

View File

@@ -379,7 +379,7 @@ class AgentTrustManager:
"""Update trust score based on execution results"""
# Get or create trust score record
trust_score = self.session.exec(
trust_score = self.session.execute(
select(AgentTrustScore).where(
(AgentTrustScore.entity_type == entity_type) &
(AgentTrustScore.entity_id == entity_id)
@@ -677,7 +677,7 @@ class AgentSandboxManager:
"""Monitor sandbox execution for security violations"""
# Get sandbox configuration
sandbox = self.session.exec(
sandbox = self.session.execute(
select(AgentSandboxConfig).where(
AgentSandboxConfig.id == f"sandbox_{execution_id}"
)
@@ -716,7 +716,7 @@ class AgentSandboxManager:
try:
# Get sandbox record
sandbox = self.session.exec(
sandbox = self.session.execute(
select(AgentSandboxConfig).where(
AgentSandboxConfig.id == f"sandbox_{execution_id}"
)

View File

@@ -95,7 +95,7 @@ class AgentStateManager:
.where(AgentStep.workflow_id == workflow_id)
.order_by(AgentStep.step_order)
)
return self.session.exec(stmt).all()
return self.session.execute(stmt).all()
async def create_step_execution(
self,

View File

@@ -177,7 +177,7 @@ class AMMService:
pool.updated_at = datetime.utcnow()
# Update or create liquidity position
position = self.session.exec(
position = self.session.execute(
select(LiquidityPosition).where(
LiquidityPosition.pool_id == pool.id,
LiquidityPosition.provider_address == provider_address
@@ -228,7 +228,7 @@ class AMMService:
pool = await self._get_pool_by_id(liquidity_request.pool_id)
# Get liquidity position
position = self.session.exec(
position = self.session.execute(
select(LiquidityPosition).where(
LiquidityPosition.pool_id == pool.id,
LiquidityPosition.provider_address == provider_address
@@ -447,7 +447,7 @@ class AMMService:
daily_reward = 100 * incentive_multiplier # Base $100 per day, adjusted by multiplier
# Create or update incentive program
existing_program = self.session.exec(
existing_program = self.session.execute(
select(IncentiveProgram).where(IncentiveProgram.pool_id == pool_id)
).first()
@@ -498,7 +498,7 @@ class AMMService:
"""Get all liquidity positions for a user"""
try:
positions = self.session.exec(
positions = self.session.execute(
select(LiquidityPosition).where(
LiquidityPosition.provider_address == user_address
)
@@ -521,7 +521,7 @@ class AMMService:
async def _get_existing_pool(self, token_a: str, token_b: str) -> Optional[LiquidityPool]:
"""Check if pool exists for token pair"""
pool = self.session.exec(
pool = self.session.execute(
select(LiquidityPool).where(
(
(LiquidityPool.token_a == token_a) &
@@ -694,13 +694,13 @@ class AMMService:
"""Update pool metrics"""
# Get existing metrics
metrics = self.session.exec(
metrics = self.session.execute(
select(PoolMetrics).where(PoolMetrics.pool_id == pool.id)
).first()
if not metrics:
await self._initialize_pool_metrics(pool)
metrics = self.session.exec(
metrics = self.session.execute(
select(PoolMetrics).where(PoolMetrics.pool_id == pool.id)
).first()
@@ -734,20 +734,20 @@ class AMMService:
async def _get_pool_metrics(self, pool: LiquidityPool) -> PoolMetrics:
"""Get comprehensive pool metrics"""
metrics = self.session.exec(
metrics = self.session.execute(
select(PoolMetrics).where(PoolMetrics.pool_id == pool.id)
).first()
if not metrics:
await self._initialize_pool_metrics(pool)
metrics = self.session.exec(
metrics = self.session.execute(
select(PoolMetrics).where(PoolMetrics.pool_id == pool.id)
).first()
# Calculate 24h volume and fees
twenty_four_hours_ago = datetime.utcnow() - timedelta(hours=24)
recent_swaps = self.session.exec(
recent_swaps = self.session.execute(
select(SwapTransaction).where(
SwapTransaction.pool_id == pool.id,
SwapTransaction.executed_at >= twenty_four_hours_ago

View File

@@ -424,7 +424,7 @@ class AnalyticsEngine:
insights = []
# Get metrics for analysis
metrics = session.exec(
metrics = session.execute(
select(MarketMetric).where(
and_(
MarketMetric.period_type == period_type,
@@ -1068,7 +1068,7 @@ class MarketplaceAnalytics:
end_time = datetime.utcnow()
start_time = end_time - timedelta(days=1)
metrics = self.session.exec(
metrics = self.session.execute(
select(MarketMetric).where(
and_(
MarketMetric.period_type == AnalyticsPeriod.DAILY,
@@ -1079,14 +1079,14 @@ class MarketplaceAnalytics:
).all()
# Get recent insights
recent_insights = self.session.exec(
recent_insights = self.session.execute(
select(MarketInsight).where(
MarketInsight.created_at >= start_time
).order_by(MarketInsight.created_at.desc()).limit(10)
).all()
# Get active alerts
active_alerts = self.session.exec(
active_alerts = self.session.execute(
select(AnalyticsAlert).where(
and_(
AnalyticsAlert.status == "active",

View File

@@ -82,7 +82,7 @@ class AtomicSwapService:
async def get_agent_swaps(self, agent_id: str) -> List[AtomicSwapOrder]:
"""Get all swaps where the agent is either initiator or participant"""
return self.session.exec(
return self.session.execute(
select(AtomicSwapOrder).where(
(AtomicSwapOrder.initiator_agent_id == agent_id) |
(AtomicSwapOrder.participant_agent_id == agent_id)

View File

@@ -207,7 +207,7 @@ class CertificationSystem:
}
# Check if agent has the prerequisite certification
certification = session.exec(
certification = session.execute(
select(AgentCertification).where(
and_(
AgentCertification.agent_id == agent_id,
@@ -244,7 +244,7 @@ class CertificationSystem:
# For now, assume all agents have basic identity verification
# Check if agent has any reputation record (indicates identity verification)
reputation = session.exec(
reputation = session.execute(
select(AgentReputation).where(AgentReputation.agent_id == agent_id)
).first()
@@ -271,7 +271,7 @@ class CertificationSystem:
"""Verify agent performance metrics"""
# Get agent reputation for performance metrics
reputation = session.exec(
reputation = session.execute(
select(AgentReputation).where(AgentReputation.agent_id == agent_id)
).first()
@@ -366,7 +366,7 @@ class CertificationSystem:
async def verify_reliability(self, session: Session, agent_id: str) -> Dict[str, Any]:
"""Verify agent reliability and consistency"""
reputation = session.exec(
reputation = session.execute(
select(AgentReputation).where(AgentReputation.agent_id == agent_id)
).first()
@@ -428,7 +428,7 @@ class CertificationSystem:
# Mock security verification - in real system would check security audits
# For now, assume agents with high trust scores have basic security
reputation = session.exec(
reputation = session.execute(
select(AgentReputation).where(AgentReputation.agent_id == agent_id)
).first()
@@ -479,7 +479,7 @@ class CertificationSystem:
# Mock compliance verification - in real system would check regulatory compliance
# For now, assume agents with certifications are compliant
certifications = session.exec(
certifications = session.execute(
select(AgentCertification).where(
and_(
AgentCertification.agent_id == agent_id,
@@ -513,7 +513,7 @@ class CertificationSystem:
async def verify_capability(self, session: Session, agent_id: str) -> Dict[str, Any]:
"""Verify agent capabilities and specializations"""
reputation = session.exec(
reputation = session.execute(
select(AgentReputation).where(AgentReputation.agent_id == agent_id)
).first()
@@ -608,7 +608,7 @@ class CertificationSystem:
) -> Tuple[bool, Optional[str]]:
"""Renew an existing certification"""
certification = session.exec(
certification = session.execute(
select(AgentCertification).where(AgentCertification.certification_id == certification_id)
).first()
@@ -753,7 +753,7 @@ class PartnershipManager:
"""Apply for partnership program"""
# Get program details
program = session.exec(
program = session.execute(
select(PartnershipProgram).where(PartnershipProgram.program_id == program_id)
).first()
@@ -846,7 +846,7 @@ class PartnershipManager:
async def check_technical_capability(self, session: Session, agent_id: str) -> Dict[str, Any]:
"""Check technical capability requirement"""
reputation = session.exec(
reputation = session.execute(
select(AgentReputation).where(AgentReputation.agent_id == agent_id)
).first()
@@ -884,7 +884,7 @@ class PartnershipManager:
# Mock integration readiness check
# In real system would check API integration capabilities, technical infrastructure
reputation = session.exec(
reputation = session.execute(
select(AgentReputation).where(AgentReputation.agent_id == agent_id)
).first()
@@ -916,7 +916,7 @@ class PartnershipManager:
async def check_service_quality(self, session: Session, agent_id: str) -> Dict[str, Any]:
"""Check service quality requirement"""
reputation = session.exec(
reputation = session.execute(
select(AgentReputation).where(AgentReputation.agent_id == agent_id)
).first()
@@ -951,7 +951,7 @@ class PartnershipManager:
# Mock customer support check
# In real system would check support response times, customer satisfaction
reputation = session.exec(
reputation = session.execute(
select(AgentReputation).where(AgentReputation.agent_id == agent_id)
).first()
@@ -986,7 +986,7 @@ class PartnershipManager:
# Mock sales capability check
# In real system would check sales history, customer acquisition, revenue
reputation = session.exec(
reputation = session.execute(
select(AgentReputation).where(AgentReputation.agent_id == agent_id)
).first()
@@ -1021,7 +1021,7 @@ class PartnershipManager:
# Mock market presence check
# In real system would check market share, brand recognition, geographic reach
reputation = session.exec(
reputation = session.execute(
select(AgentReputation).where(AgentReputation.agent_id == agent_id)
).first()
@@ -1062,7 +1062,7 @@ class PartnershipManager:
# Mock development resources check
# In real system would check team size, technical infrastructure, development capacity
reputation = session.exec(
reputation = session.execute(
select(AgentReputation).where(AgentReputation.agent_id == agent_id)
).first()
@@ -1098,7 +1098,7 @@ class PartnershipManager:
# Mock market leader check
# In real system would check market share, industry influence, thought leadership
reputation = session.exec(
reputation = session.execute(
select(AgentReputation).where(AgentReputation.agent_id == agent_id)
).first()
@@ -1151,7 +1151,7 @@ class PartnershipManager:
# Mock marketing capability check
# In real system would check marketing materials, brand presence, outreach capabilities
reputation = session.exec(
reputation = session.execute(
select(AgentReputation).where(AgentReputation.agent_id == agent_id)
).first()
@@ -1187,7 +1187,7 @@ class PartnershipManager:
# Mock audience reach check
# In real system would check audience size, engagement metrics, reach demographics
reputation = session.exec(
reputation = session.execute(
select(AgentReputation).where(AgentReputation.agent_id == agent_id)
).first()
@@ -1300,7 +1300,7 @@ class BadgeSystem:
"""Award a badge to an agent"""
# Get badge details
badge = session.exec(
badge = session.execute(
select(AchievementBadge).where(AchievementBadge.badge_id == badge_id)
).first()
@@ -1314,7 +1314,7 @@ class BadgeSystem:
return False, None, "Badge has reached maximum awards"
# Check if agent already has this badge
existing_badge = session.exec(
existing_badge = session.execute(
select(AgentBadge).where(
and_(
AgentBadge.agent_id == agent_id,
@@ -1362,7 +1362,7 @@ class BadgeSystem:
"""Verify if agent is eligible for a badge"""
# Get agent reputation data
reputation = session.exec(
reputation = session.execute(
select(AgentReputation).where(AgentReputation.agent_id == agent_id)
).first()
@@ -1449,7 +1449,7 @@ class BadgeSystem:
awarded_badges = []
# Get all active automatic badges
automatic_badges = session.exec(
automatic_badges = session.execute(
select(AchievementBadge).where(
and_(
AchievementBadge.is_active == True,
@@ -1464,7 +1464,7 @@ class BadgeSystem:
if eligibility_result['eligible']:
# Check if already awarded
existing = session.exec(
existing = session.execute(
select(AgentBadge).where(
and_(
AgentBadge.agent_id == agent_id,
@@ -1505,22 +1505,22 @@ class CertificationAndPartnershipService:
"""Get comprehensive certification summary for an agent"""
# Get certifications
certifications = self.session.exec(
certifications = self.session.execute(
select(AgentCertification).where(AgentCertification.agent_id == agent_id)
).all()
# Get partnerships
partnerships = self.session.exec(
partnerships = self.session.execute(
select(AgentPartnership).where(AgentPartnership.agent_id == agent_id)
).all()
# Get badges
badges = self.session.exec(
badges = self.session.execute(
select(AgentBadge).where(AgentBadge.agent_id == agent_id)
).all()
# Get verification records
verifications = self.session.exec(
verifications = self.session.execute(
select(VerificationRecord).where(VerificationRecord.agent_id == agent_id)
).all()
@@ -1585,7 +1585,7 @@ class CertificationAndPartnershipService:
def get_badge_point_value(self, badge_id: str) -> int:
"""Get point value for a badge"""
badge = self.session.exec(
badge = self.session.execute(
select(AchievementBadge).where(AchievementBadge.badge_id == badge_id)
).first()

View File

@@ -37,7 +37,7 @@ class DeveloperEcosystemService:
async def get_developer_profile(self, developer_id: str) -> Optional[DeveloperProfile]:
"""Get developer profile by ID"""
return self.session.exec(
return self.session.execute(
select(DeveloperProfile).where(DeveloperProfile.developer_id == developer_id)
).first()
@@ -118,7 +118,7 @@ class ThirdPartySolutionService:
# Filtering by JSON column capability (simplified)
# In a real app, we might use PostgreSQL specific operators
solutions = self.session.exec(query.limit(limit)).all()
solutions = self.session.execute(query.limit(limit)).all()
if category:
solutions = [s for s in solutions if category in s.capabilities]
@@ -127,7 +127,7 @@ class ThirdPartySolutionService:
async def purchase_solution(self, buyer_id: str, solution_id: str) -> Dict[str, Any]:
"""Purchase or download a third-party solution"""
solution = self.session.exec(
solution = self.session.execute(
select(AgentSolution).where(AgentSolution.solution_id == solution_id)
).first()
@@ -140,7 +140,7 @@ class ThirdPartySolutionService:
# Update developer earnings if paid
if solution.price_amount > 0:
dev = self.session.exec(
dev = self.session.execute(
select(DeveloperProfile).where(DeveloperProfile.developer_id == solution.developer_id)
).first()
if dev:
@@ -181,7 +181,7 @@ class InnovationLabService:
async def join_lab(self, lab_id: str, developer_id: str) -> InnovationLab:
"""Join an active innovation lab"""
lab = self.session.exec(select(InnovationLab).where(InnovationLab.lab_id == lab_id)).first()
lab = self.session.execute(select(InnovationLab).where(InnovationLab.lab_id == lab_id)).first()
if not lab:
raise ValueError("Lab not found")
@@ -196,7 +196,7 @@ class InnovationLabService:
async def fund_lab(self, lab_id: str, amount: float) -> InnovationLab:
"""Provide funding to an innovation lab"""
lab = self.session.exec(select(InnovationLab).where(InnovationLab.lab_id == lab_id)).first()
lab = self.session.execute(select(InnovationLab).where(InnovationLab.lab_id == lab_id)).first()
if not lab:
raise ValueError("Lab not found")
@@ -245,11 +245,11 @@ class CommunityPlatformService:
query = query.where(CommunityPost.category == category)
query = query.order_by(CommunityPost.created_at.desc()).limit(limit)
return self.session.exec(query).all()
return self.session.execute(query).all()
async def upvote_post(self, post_id: str) -> CommunityPost:
"""Upvote a post and reward the author"""
post = self.session.exec(select(CommunityPost).where(CommunityPost.post_id == post_id)).first()
post = self.session.execute(select(CommunityPost).where(CommunityPost.post_id == post_id)).first()
if not post:
raise ValueError("Post not found")
@@ -267,7 +267,7 @@ class CommunityPlatformService:
async def create_hackathon(self, organizer_id: str, data: Dict[str, Any]) -> Hackathon:
"""Create a new agent innovation hackathon"""
# Verify organizer is an expert or partner
dev = self.session.exec(select(DeveloperProfile).where(DeveloperProfile.developer_id == organizer_id)).first()
dev = self.session.execute(select(DeveloperProfile).where(DeveloperProfile.developer_id == organizer_id)).first()
if not dev or dev.tier not in [DeveloperTier.EXPERT, DeveloperTier.MASTER, DeveloperTier.PARTNER]:
raise ValueError("Only high-tier developers can organize hackathons")
@@ -290,7 +290,7 @@ class CommunityPlatformService:
async def register_for_hackathon(self, hackathon_id: str, developer_id: str) -> Hackathon:
"""Register a developer for a hackathon"""
hackathon = self.session.exec(select(Hackathon).where(Hackathon.hackathon_id == hackathon_id)).first()
hackathon = self.session.execute(select(Hackathon).where(Hackathon.hackathon_id == hackathon_id)).first()
if not hackathon:
raise ValueError("Hackathon not found")

View File

@@ -98,7 +98,7 @@ class CreativityEnhancementEngine:
) -> Dict[str, Any]:
"""Enhance a specific creative capability"""
capability = session.exec(
capability = session.execute(
select(CreativeCapability).where(CreativeCapability.capability_id == capability_id)
).first()
@@ -245,7 +245,7 @@ class CreativityEnhancementEngine:
) -> Dict[str, Any]:
"""Evaluate a creative output and update capability"""
capability = session.exec(
capability = session.execute(
select(CreativeCapability).where(CreativeCapability.capability_id == capability_id)
).first()
@@ -469,7 +469,7 @@ class CrossDomainCreativeIntegrator:
"""Synthesize concepts from multiple domains to create novel outputs"""
# Verify agent has capabilities in these domains
capabilities = session.exec(
capabilities = session.execute(
select(CreativeCapability).where(
and_(
CreativeCapability.agent_id == agent_id,

View File

@@ -303,7 +303,7 @@ class CrossChainBridgeService:
)
# Check if already confirmed by this validator
existing_confirmation = self.session.exec(
existing_confirmation = self.session.execute(
select(BridgeTransaction).where(
BridgeTransaction.bridge_request_id == bridge_request.id,
BridgeTransaction.validator_address == validator_address,
@@ -567,7 +567,7 @@ class CrossChainBridgeService:
async def _get_supported_token(self, token_address: str) -> Optional[SupportedToken]:
"""Get supported token configuration"""
return self.session.exec(
return self.session.execute(
select(SupportedToken).where(
SupportedToken.token_address == token_address
)
@@ -575,7 +575,7 @@ class CrossChainBridgeService:
async def _get_chain_config(self, chain_id: int) -> Optional[ChainConfig]:
"""Get chain configuration"""
return self.session.exec(
return self.session.execute(
select(ChainConfig).where(
ChainConfig.chain_id == chain_id
)
@@ -609,7 +609,7 @@ class CrossChainBridgeService:
async def _get_bridge_confirmations(self, request_id: int) -> List[Dict]:
"""Get bridge confirmations"""
confirmations = self.session.exec(
confirmations = self.session.execute(
select(BridgeTransaction).where(
BridgeTransaction.bridge_request_id == request_id,
BridgeTransaction.transaction_type == "confirmation"
@@ -628,7 +628,7 @@ class CrossChainBridgeService:
async def _get_bridge_transactions(self, request_id: int) -> List[Dict]:
"""Get all bridge transactions"""
transactions = self.session.exec(
transactions = self.session.execute(
select(BridgeTransaction).where(
BridgeTransaction.bridge_request_id == request_id
)
@@ -723,7 +723,7 @@ class CrossChainBridgeService:
async def _get_validator(self, validator_address: str) -> Optional[Validator]:
"""Get validator information"""
return self.session.exec(
return self.session.execute(
select(Validator).where(
Validator.validator_address == validator_address
)
@@ -743,7 +743,7 @@ class CrossChainBridgeService:
async def _count_confirmations(self, request_id: int) -> int:
"""Count confirmations for bridge request"""
confirmations = self.session.exec(
confirmations = self.session.execute(
select(BridgeTransaction).where(
BridgeTransaction.bridge_request_id == request_id,
BridgeTransaction.transaction_type == "confirmation"

View File

@@ -194,7 +194,7 @@ class CrossChainBridgeService:
stmt = select(BridgeRequest).where(
BridgeRequest.id == bridge_request_id
)
bridge_request = self.session.exec(stmt).first()
bridge_request = self.session.execute(stmt).first()
if not bridge_request:
raise ValueError(f"Bridge request {bridge_request_id} not found")
@@ -266,7 +266,7 @@ class CrossChainBridgeService:
stmt = select(BridgeRequest).where(
BridgeRequest.id == bridge_request_id
)
bridge_request = self.session.exec(stmt).first()
bridge_request = self.session.execute(stmt).first()
if not bridge_request:
raise ValueError(f"Bridge request {bridge_request_id} not found")
@@ -306,14 +306,14 @@ class CrossChainBridgeService:
cutoff_time = datetime.utcnow() - timedelta(hours=time_period_hours)
# Get total requests
total_requests = self.session.exec(
total_requests = self.session.execute(
select(func.count(BridgeRequest.id)).where(
BridgeRequest.created_at >= cutoff_time
)
).scalar() or 0
# Get completed requests
completed_requests = self.session.exec(
completed_requests = self.session.execute(
select(func.count(BridgeRequest.id)).where(
BridgeRequest.created_at >= cutoff_time,
BridgeRequest.status == BridgeRequestStatus.COMPLETED
@@ -321,7 +321,7 @@ class CrossChainBridgeService:
).scalar() or 0
# Get total volume
total_volume = self.session.exec(
total_volume = self.session.execute(
select(func.sum(BridgeRequest.amount)).where(
BridgeRequest.created_at >= cutoff_time,
BridgeRequest.status == BridgeRequestStatus.COMPLETED
@@ -329,7 +329,7 @@ class CrossChainBridgeService:
).scalar() or 0
# Get total fees
total_fees = self.session.exec(
total_fees = self.session.execute(
select(func.sum(BridgeRequest.total_fee)).where(
BridgeRequest.created_at >= cutoff_time,
BridgeRequest.status == BridgeRequestStatus.COMPLETED
@@ -340,7 +340,7 @@ class CrossChainBridgeService:
success_rate = completed_requests / max(total_requests, 1)
# Get average processing time
avg_processing_time = self.session.exec(
avg_processing_time = self.session.execute(
select(func.avg(
func.extract('epoch', BridgeRequest.completed_at) -
func.extract('epoch', BridgeRequest.created_at)
@@ -353,7 +353,7 @@ class CrossChainBridgeService:
# Get chain distribution
chain_distribution = {}
for chain_id in self.wallet_adapters.keys():
chain_requests = self.session.exec(
chain_requests = self.session.execute(
select(func.count(BridgeRequest.id)).where(
BridgeRequest.created_at >= cutoff_time,
BridgeRequest.source_chain_id == chain_id
@@ -413,7 +413,7 @@ class CrossChainBridgeService:
stmt = select(BridgeRequest).where(
BridgeRequest.id == bridge_request_id
)
bridge_request = self.session.exec(stmt).first()
bridge_request = self.session.execute(stmt).first()
if not bridge_request:
logger.error(f"Bridge request {bridge_request_id} not found")
@@ -445,7 +445,7 @@ class CrossChainBridgeService:
error_message=str(e),
updated_at=datetime.utcnow()
)
self.session.exec(stmt)
self.session.execute(stmt)
self.session.commit()
except:
pass

View File

@@ -34,7 +34,7 @@ class DAOGovernanceService:
self.contract_service = contract_service
async def register_member(self, request: MemberCreate) -> DAOMember:
existing = self.session.exec(
existing = self.session.execute(
select(DAOMember).where(DAOMember.wallet_address == request.wallet_address)
).first()
@@ -58,7 +58,7 @@ class DAOGovernanceService:
return member
async def create_proposal(self, request: ProposalCreate) -> DAOProposal:
proposer = self.session.exec(
proposer = self.session.execute(
select(DAOMember).where(DAOMember.wallet_address == request.proposer_address)
).first()
@@ -91,7 +91,7 @@ class DAOGovernanceService:
return proposal
async def cast_vote(self, request: VoteCreate) -> Vote:
member = self.session.exec(
member = self.session.execute(
select(DAOMember).where(DAOMember.wallet_address == request.member_address)
).first()
@@ -112,7 +112,7 @@ class DAOGovernanceService:
self.session.commit()
raise HTTPException(status_code=400, detail="Voting period has ended")
existing_vote = self.session.exec(
existing_vote = self.session.execute(
select(Vote).where(
Vote.proposal_id == request.proposal_id,
Vote.member_id == member.id

View File

@@ -32,7 +32,7 @@ class DeveloperPlatformService:
self.session = session
async def register_developer(self, request: DeveloperCreate) -> DeveloperProfile:
existing = self.session.exec(
existing = self.session.execute(
select(DeveloperProfile).where(DeveloperProfile.wallet_address == request.wallet_address)
).first()
@@ -173,7 +173,7 @@ class DeveloperPlatformService:
async def get_developer_profile(self, wallet_address: str) -> Optional[DeveloperProfile]:
"""Get developer profile by wallet address"""
return self.session.exec(
return self.session.execute(
select(DeveloperProfile).where(DeveloperProfile.wallet_address == wallet_address)
).first()
@@ -195,7 +195,7 @@ class DeveloperPlatformService:
async def get_leaderboard(self, limit: int = 100, offset: int = 0) -> List[DeveloperProfile]:
"""Get developer leaderboard sorted by reputation score"""
return self.session.exec(
return self.session.execute(
select(DeveloperProfile)
.where(DeveloperProfile.is_active == True)
.order_by(DeveloperProfile.reputation_score.desc())
@@ -210,7 +210,7 @@ class DeveloperPlatformService:
raise HTTPException(status_code=404, detail="Developer profile not found")
# Get bounty statistics
completed_bounties = self.session.exec(
completed_bounties = self.session.execute(
select(BountySubmission).where(
BountySubmission.developer_id == profile.id,
BountySubmission.is_approved == True
@@ -218,7 +218,7 @@ class DeveloperPlatformService:
).all()
# Get certification statistics
certifications = self.session.exec(
certifications = self.session.execute(
select(DeveloperCertification).where(DeveloperCertification.developer_id == profile.id)
).all()
@@ -240,7 +240,7 @@ class DeveloperPlatformService:
if status:
query = query.where(BountyTask.status == status)
return self.session.exec(
return self.session.execute(
query.order_by(BountyTask.created_at.desc())
.offset(offset)
.limit(limit)
@@ -253,7 +253,7 @@ class DeveloperPlatformService:
raise HTTPException(status_code=404, detail="Bounty not found")
# Get submissions count
submissions_count = self.session.exec(
submissions_count = self.session.execute(
select(BountySubmission).where(BountySubmission.bounty_id == bounty_id)
).count()
@@ -264,7 +264,7 @@ class DeveloperPlatformService:
async def get_my_submissions(self, developer_id: str) -> List[BountySubmission]:
"""Get all submissions by a developer"""
return self.session.exec(
return self.session.execute(
select(BountySubmission)
.where(BountySubmission.developer_id == developer_id)
.order_by(BountySubmission.submitted_at.desc())
@@ -288,7 +288,7 @@ class DeveloperPlatformService:
async def get_regional_hubs(self) -> List[RegionalHub]:
"""Get all regional developer hubs"""
return self.session.exec(
return self.session.execute(
select(RegionalHub).where(RegionalHub.is_active == True)
).all()
@@ -301,7 +301,7 @@ class DeveloperPlatformService:
raise HTTPException(status_code=404, detail="Regional hub not found")
# Mock implementation - in reality would use hub membership table
return self.session.exec(
return self.session.execute(
select(DeveloperProfile).where(DeveloperProfile.is_active == True)
).all()
@@ -394,15 +394,15 @@ class DeveloperPlatformService:
async def get_bounty_statistics(self) -> dict:
"""Get comprehensive bounty statistics"""
total_bounties = self.session.exec(select(BountyTask)).count()
open_bounties = self.session.exec(
total_bounties = self.session.execute(select(BountyTask)).count()
open_bounties = self.session.execute(
select(BountyTask).where(BountyTask.status == BountyStatus.OPEN)
).count()
completed_bounties = self.session.exec(
completed_bounties = self.session.execute(
select(BountyTask).where(BountyTask.status == BountyStatus.COMPLETED)
).count()
total_rewards = self.session.exec(
total_rewards = self.session.execute(
select(BountyTask).where(BountyTask.status == BountyStatus.COMPLETED)
).all()
total_reward_amount = sum(bounty.reward_amount for bounty in total_rewards)

View File

@@ -23,7 +23,7 @@ class EdgeGPUService:
stmt = stmt.where(ConsumerGPUProfile.edge_optimized == edge_optimized)
if min_memory_gb is not None:
stmt = stmt.where(ConsumerGPUProfile.memory_gb >= min_memory_gb)
return list(self.session.exec(stmt).all())
return list(self.session.execute(stmt).all())
def list_metrics(self, gpu_id: str, limit: int = 100) -> List[EdgeGPUMetrics]:
stmt = (
@@ -32,7 +32,7 @@ class EdgeGPUService:
.order_by(EdgeGPUMetrics.timestamp.desc())
.limit(limit)
)
return list(self.session.exec(stmt).all())
return list(self.session.execute(stmt).all())
def create_metric(self, payload: dict) -> EdgeGPUMetrics:
metric = EdgeGPUMetrics(**payload)
@@ -42,7 +42,7 @@ class EdgeGPUService:
return metric
def seed_profiles(self) -> None:
existing_models = set(self.session.exec(select(ConsumerGPUProfile.gpu_model)).all())
existing_models = set(self.session.execute(select(ConsumerGPUProfile.gpu_model)).all())
created = 0
for profile in CONSUMER_GPU_PROFILES:
if profile["gpu_model"] in existing_models:

View File

@@ -83,7 +83,7 @@ class ExplorerService:
# Fallback to fake data if RPC is unavailable
print(f"Warning: Failed to fetch blocks from RPC: {e}, falling back to fake data")
statement = select(Job).order_by(Job.requested_at.desc())
jobs = self.session.exec(statement.offset(offset).limit(limit)).all()
jobs = self.session.execute(statement.offset(offset).limit(limit)).all()
items: list[BlockSummary] = []
for index, job in enumerate(jobs):
@@ -109,7 +109,7 @@ class ExplorerService:
.offset(offset)
.limit(limit)
)
jobs = self.session.exec(statement).all()
jobs = self.session.execute(statement).all()
items: list[TransactionSummary] = []
for index, job in enumerate(jobs):
@@ -149,7 +149,7 @@ class ExplorerService:
def list_addresses(self, *, limit: int = 50, offset: int = 0) -> AddressListResponse:
statement = select(Job).order_by(Job.requested_at.desc())
jobs = self.session.exec(statement.offset(offset).limit(limit)).all()
jobs = self.session.execute(statement.offset(offset).limit(limit)).all()
address_map: dict[str, dict[str, object]] = defaultdict(
lambda: {
@@ -237,7 +237,7 @@ class ExplorerService:
if job_id:
statement = statement.where(JobReceipt.job_id == job_id)
rows = self.session.exec(statement.offset(offset).limit(limit)).all()
rows = self.session.execute(statement.offset(offset).limit(limit)).all()
items: list[ReceiptSummary] = []
for row in rows:
payload = row.payload or {}

View File

@@ -67,7 +67,7 @@ class FederatedLearningService:
raise HTTPException(status_code=400, detail="Session is not currently accepting participants")
# Check if already joined
existing = self.session.exec(
existing = self.session.execute(
select(TrainingParticipant).where(
TrainingParticipant.session_id == session_id,
TrainingParticipant.agent_id == request.agent_id
@@ -128,7 +128,7 @@ class FederatedLearningService:
if fl_session.status != TrainingStatus.TRAINING or current_round.status != "active":
raise HTTPException(status_code=400, detail="Round is not currently active")
participant = self.session.exec(
participant = self.session.execute(
select(TrainingParticipant).where(
TrainingParticipant.session_id == session_id,
TrainingParticipant.agent_id == request.agent_id

View File

@@ -127,7 +127,7 @@ class GlobalMarketplaceService:
GlobalMarketplaceOffer.created_at.desc()
).offset(offset).limit(limit)
offers = self.session.exec(stmt).all()
offers = self.session.execute(stmt).all()
# Filter out expired offers
current_time = datetime.utcnow()
@@ -155,7 +155,7 @@ class GlobalMarketplaceService:
stmt = select(GlobalMarketplaceOffer).where(
GlobalMarketplaceOffer.id == request.offer_id
)
offer = self.session.exec(stmt).first()
offer = self.session.execute(stmt).first()
if not offer:
raise ValueError("Offer not found")
@@ -252,7 +252,7 @@ class GlobalMarketplaceService:
GlobalMarketplaceTransaction.created_at.desc()
).offset(offset).limit(limit)
transactions = self.session.exec(stmt).all()
transactions = self.session.execute(stmt).all()
return transactions
except Exception as e:
@@ -274,7 +274,7 @@ class GlobalMarketplaceService:
GlobalMarketplaceAnalytics.region == request.region
)
existing_analytics = self.session.exec(stmt).first()
existing_analytics = self.session.execute(stmt).first()
if existing_analytics:
return existing_analytics
@@ -309,7 +309,7 @@ class GlobalMarketplaceService:
GlobalMarketplaceOffer.regions_available.contains([request.region])
)
offers = self.session.exec(stmt).all()
offers = self.session.execute(stmt).all()
# Get transactions in the period
stmt = select(GlobalMarketplaceTransaction).where(
@@ -323,7 +323,7 @@ class GlobalMarketplaceService:
(GlobalMarketplaceTransaction.target_region == request.region)
)
transactions = self.session.exec(stmt).all()
transactions = self.session.execute(stmt).all()
# Calculate metrics
total_offers = len(offers)
@@ -370,7 +370,7 @@ class GlobalMarketplaceService:
MarketplaceRegion.status == RegionStatus.ACTIVE
)
regions = self.session.exec(stmt).all()
regions = self.session.execute(stmt).all()
return regions
async def get_region_health(self, region_code: str) -> Dict[str, Any]:
@@ -381,7 +381,7 @@ class GlobalMarketplaceService:
MarketplaceRegion.region_code == region_code
)
region = self.session.exec(stmt).first()
region = self.session.execute(stmt).first()
if not region:
return {"status": "not_found"}
@@ -417,7 +417,7 @@ class GlobalMarketplaceService:
GlobalMarketplaceAnalytics.created_at >= cutoff_time
).order_by(GlobalMarketplaceAnalytics.created_at.desc())
analytics = self.session.exec(stmt).first()
analytics = self.session.execute(stmt).first()
if analytics:
return {
@@ -488,7 +488,7 @@ class RegionManager:
MarketplaceRegion.region_code == region_code
)
region = self.session.exec(stmt).first()
region = self.session.execute(stmt).first()
if not region:
raise ValueError(f"Region {region_code} not found")
@@ -532,7 +532,7 @@ class RegionManager:
MarketplaceRegion.status == RegionStatus.ACTIVE
).order_by(MarketplaceRegion.priority_weight.desc())
regions = self.session.exec(stmt).all()
regions = self.session.execute(stmt).all()
if not regions:
raise ValueError("No active regions available")

View File

@@ -209,7 +209,7 @@ class GlobalMarketplaceIntegrationService:
try:
# Get the global offer
stmt = select(GlobalMarketplaceOffer).where(GlobalMarketplaceOffer.id == offer_id)
offer = self.session.exec(stmt).first()
offer = self.session.execute(stmt).first()
if not offer:
raise ValueError("Offer not found")
@@ -433,7 +433,7 @@ class GlobalMarketplaceIntegrationService:
try:
# Get the offer
stmt = select(GlobalMarketplaceOffer).where(GlobalMarketplaceOffer.id == offer_id)
offer = self.session.exec(stmt).first()
offer = self.session.execute(stmt).first()
if not offer:
raise ValueError("Offer not found")

View File

@@ -25,7 +25,7 @@ class GovernanceService:
async def get_or_create_profile(self, user_id: str, initial_voting_power: float = 0.0) -> GovernanceProfile:
"""Get an existing governance profile or create a new one"""
profile = self.session.exec(select(GovernanceProfile).where(GovernanceProfile.user_id == user_id)).first()
profile = self.session.execute(select(GovernanceProfile).where(GovernanceProfile.user_id == user_id)).first()
if not profile:
profile = GovernanceProfile(
@@ -40,15 +40,15 @@ class GovernanceService:
async def delegate_votes(self, delegator_id: str, delegatee_id: str) -> GovernanceProfile:
"""Delegate voting power from one profile to another"""
delegator = self.session.exec(select(GovernanceProfile).where(GovernanceProfile.profile_id == delegator_id)).first()
delegatee = self.session.exec(select(GovernanceProfile).where(GovernanceProfile.profile_id == delegatee_id)).first()
delegator = self.session.execute(select(GovernanceProfile).where(GovernanceProfile.profile_id == delegator_id)).first()
delegatee = self.session.execute(select(GovernanceProfile).where(GovernanceProfile.profile_id == delegatee_id)).first()
if not delegator or not delegatee:
raise ValueError("Delegator or Delegatee not found")
# Remove old delegation if exists
if delegator.delegate_to:
old_delegatee = self.session.exec(select(GovernanceProfile).where(GovernanceProfile.profile_id == delegator.delegate_to)).first()
old_delegatee = self.session.execute(select(GovernanceProfile).where(GovernanceProfile.profile_id == delegator.delegate_to)).first()
if old_delegatee:
old_delegatee.delegated_power -= delegator.voting_power
@@ -65,7 +65,7 @@ class GovernanceService:
async def create_proposal(self, proposer_id: str, data: Dict[str, Any]) -> Proposal:
"""Create a new governance proposal"""
proposer = self.session.exec(select(GovernanceProfile).where(GovernanceProfile.profile_id == proposer_id)).first()
proposer = self.session.execute(select(GovernanceProfile).where(GovernanceProfile.profile_id == proposer_id)).first()
if not proposer:
raise ValueError("Proposer not found")
@@ -110,8 +110,8 @@ class GovernanceService:
async def cast_vote(self, proposal_id: str, voter_id: str, vote_type: VoteType, reason: str = None) -> Vote:
"""Cast a vote on an active proposal"""
proposal = self.session.exec(select(Proposal).where(Proposal.proposal_id == proposal_id)).first()
voter = self.session.exec(select(GovernanceProfile).where(GovernanceProfile.profile_id == voter_id)).first()
proposal = self.session.execute(select(Proposal).where(Proposal.proposal_id == proposal_id)).first()
voter = self.session.execute(select(GovernanceProfile).where(GovernanceProfile.profile_id == voter_id)).first()
if not proposal or not voter:
raise ValueError("Proposal or Voter not found")
@@ -121,7 +121,7 @@ class GovernanceService:
raise ValueError("Proposal is not currently active for voting")
# Check if already voted
existing_vote = self.session.exec(
existing_vote = self.session.execute(
select(Vote).where(Vote.proposal_id == proposal_id).where(Vote.voter_id == voter_id)
).first()
@@ -163,7 +163,7 @@ class GovernanceService:
async def process_proposal_lifecycle(self, proposal_id: str) -> Proposal:
"""Update proposal status based on time and votes"""
proposal = self.session.exec(select(Proposal).where(Proposal.proposal_id == proposal_id)).first()
proposal = self.session.execute(select(Proposal).where(Proposal.proposal_id == proposal_id)).first()
if not proposal:
raise ValueError("Proposal not found")
@@ -191,7 +191,7 @@ class GovernanceService:
proposal.status = ProposalStatus.SUCCEEDED
# Update proposer stats
proposer = self.session.exec(select(GovernanceProfile).where(GovernanceProfile.profile_id == proposal.proposer_id)).first()
proposer = self.session.execute(select(GovernanceProfile).where(GovernanceProfile.profile_id == proposal.proposer_id)).first()
if proposer:
proposer.proposals_passed += 1
self.session.add(proposer)
@@ -205,8 +205,8 @@ class GovernanceService:
async def execute_proposal(self, proposal_id: str, executor_id: str) -> Proposal:
"""Execute a successful proposal's payload"""
proposal = self.session.exec(select(Proposal).where(Proposal.proposal_id == proposal_id)).first()
executor = self.session.exec(select(GovernanceProfile).where(GovernanceProfile.profile_id == executor_id)).first()
proposal = self.session.execute(select(Proposal).where(Proposal.proposal_id == proposal_id)).first()
executor = self.session.execute(select(GovernanceProfile).where(GovernanceProfile.profile_id == executor_id)).first()
if not proposal or not executor:
raise ValueError("Proposal or Executor not found")
@@ -223,7 +223,7 @@ class GovernanceService:
# If it's a funding proposal, deduct from treasury
if proposal.category == 'funding' and 'amount' in proposal.execution_payload:
treasury = self.session.exec(select(DaoTreasury).where(DaoTreasury.treasury_id == "main_treasury")).first()
treasury = self.session.execute(select(DaoTreasury).where(DaoTreasury.treasury_id == "main_treasury")).first()
if treasury:
amount = float(proposal.execution_payload['amount'])
if treasury.total_balance - treasury.allocated_funds >= amount:
@@ -246,9 +246,9 @@ class GovernanceService:
# In reality, we would calculate this based on timestamps matching the period
# For simplicity, we just aggregate current totals
proposals = self.session.exec(select(Proposal)).all()
profiles = self.session.exec(select(GovernanceProfile)).all()
treasury = self.session.exec(select(DaoTreasury).where(DaoTreasury.treasury_id == "main_treasury")).first()
proposals = self.session.execute(select(Proposal)).all()
profiles = self.session.execute(select(GovernanceProfile)).all()
treasury = self.session.execute(select(DaoTreasury).where(DaoTreasury.treasury_id == "main_treasury")).first()
total_proposals = len(proposals)
passed_proposals = len([p for p in proposals if p.status in [ProposalStatus.SUCCEEDED, ProposalStatus.EXECUTED]])

View File

@@ -104,7 +104,7 @@ class IPFSAdapterService:
query = query.where(AgentMemoryNode.memory_type == memory_type)
# Execute query and filter by tags in Python (since SQLite JSON JSON_CONTAINS is complex via pure SQLAlchemy without specific dialects)
results = self.session.exec(query).all()
results = self.session.execute(query).all()
if tags and len(tags) > 0:
filtered_results = []

View File

@@ -36,17 +36,17 @@ class MarketplaceService:
stmt = stmt.where(MarketplaceOffer.status == normalised)
stmt = stmt.offset(offset).limit(limit)
offers = self.session.exec(stmt).all()
offers = self.session.execute(stmt).all()
return [self._to_offer_view(o) for o in offers]
def get_stats(self) -> MarketplaceStatsView:
offers = self.session.exec(select(MarketplaceOffer)).all()
offers = self.session.execute(select(MarketplaceOffer)).all()
open_offers = [offer for offer in offers if offer.status == "open"]
total_offers = len(offers)
open_capacity = sum(offer.capacity for offer in open_offers)
average_price = mean([offer.price for offer in open_offers]) if open_offers else 0.0
active_bids = self.session.exec(
active_bids = self.session.execute(
select(MarketplaceBid).where(MarketplaceBid.status == "pending")
).all()
@@ -89,7 +89,7 @@ class MarketplaceService:
stmt = stmt.where(MarketplaceBid.provider == provider)
stmt = stmt.offset(offset).limit(limit)
bids = self.session.exec(stmt).all()
bids = self.session.execute(stmt).all()
return [self._to_bid_view(bid) for bid in bids]
def get_bid(self, bid_id: str) -> Optional[MarketplaceBidView]:

View File

@@ -294,7 +294,7 @@ class EnhancedMarketplaceService:
async def _get_volume_analytics(self, start_date: datetime, end_date: datetime) -> Dict[str, Any]:
"""Get volume analytics"""
offers = self.session.exec(
offers = self.session.execute(
select(MarketplaceOffer).where(
MarketplaceOffer.created_at >= start_date,
MarketplaceOffer.created_at <= end_date

View File

@@ -225,12 +225,12 @@ class EnhancedMarketplaceService:
offers_query = select(MarketplaceOffer).where(
MarketplaceOffer.created_at >= start_date
)
offers = self.session.exec(offers_query).all()
offers = self.session.execute(offers_query).all()
bids_query = select(MarketplaceBid).where(
MarketplaceBid.created_at >= start_date
)
bids = self.session.exec(bids_query).all()
bids = self.session.execute(bids_query).all()
# Calculate analytics
analytics = {

View File

@@ -111,8 +111,8 @@ class MinerService:
return miner
def list_records(self) -> list[Miner]:
return list(self.session.exec(select(Miner)).all())
return list(self.session.execute(select(Miner)).all())
def online_count(self) -> int:
result = self.session.exec(select(Miner).where(Miner.status == "ONLINE"))
result = self.session.execute(select(Miner).where(Miner.status == "ONLINE"))
return len(result.all())

View File

@@ -603,7 +603,7 @@ class MultiModalFusionEngine:
async def train_fusion_model(self, session: Session, fusion_id: str) -> Dict[str, Any]:
"""Train a fusion model"""
fusion_model = session.exec(
fusion_model = session.execute(
select(FusionModel).where(FusionModel.fusion_id == fusion_id)
).first()
@@ -778,7 +778,7 @@ class MultiModalFusionEngine:
) -> Dict[str, Any]:
"""Fuse multiple modalities using trained fusion model"""
fusion_model = session.exec(
fusion_model = session.execute(
select(FusionModel).where(FusionModel.fusion_id == fusion_id)
).first()

View File

@@ -3,6 +3,7 @@
from datetime import datetime, timedelta
from typing import Optional, Dict, Any
import httpx
from sqlmodel import select
from aitbc.logging import get_logger
from ..domain.payment import JobPayment, PaymentEscrow
@@ -42,11 +43,13 @@ class PaymentService:
# For AITBC token payments, use token escrow
if payment_data.payment_method == "aitbc_token":
escrow = await self._create_token_escrow(payment)
self.session.add(escrow)
if escrow is not None:
self.session.add(escrow)
# Bitcoin payments only for exchange purchases
elif payment_data.payment_method == "bitcoin":
escrow = await self._create_bitcoin_escrow(payment)
self.session.add(escrow)
if escrow is not None:
self.session.add(escrow)
# Single atomic commit - all or nothing
self.session.commit()
@@ -92,7 +95,8 @@ class PaymentService:
address=escrow_data.get("escrow_id"),
expires_at=datetime.utcnow() + timedelta(hours=1)
)
self.session.add(escrow)
if escrow is not None:
self.session.add(escrow)
self.session.commit()
logger.info(f"Created AITBC token escrow for payment {payment.id}")
@@ -134,7 +138,8 @@ class PaymentService:
address=escrow_data["address"],
expires_at=datetime.utcnow() + timedelta(hours=1)
)
self.session.add(escrow)
if escrow is not None:
self.session.add(escrow)
self.session.commit()
logger.info(f"Created Bitcoin escrow for payment {payment.id}")
@@ -176,11 +181,11 @@ class PaymentService:
payment.transaction_hash = release_data.get("transaction_hash")
# Update escrow record
escrow = self.session.exec(
self.session.query(PaymentEscrow).where(
escrow = self.session.execute(
select(PaymentEscrow).where(
PaymentEscrow.payment_id == payment_id
)
).first()
).scalars().first()
if escrow:
escrow.is_released = True
@@ -228,11 +233,11 @@ class PaymentService:
payment.refund_transaction_hash = refund_data.get("transaction_hash")
# Update escrow record
escrow = self.session.exec(
self.session.query(PaymentEscrow).where(
escrow = self.session.execute(
select(PaymentEscrow).where(
PaymentEscrow.payment_id == payment_id
)
).first()
).scalars().first()
if escrow:
escrow.is_refunded = True
@@ -255,9 +260,9 @@ class PaymentService:
def get_job_payment(self, job_id: str) -> Optional[JobPayment]:
"""Get payment for a specific job"""
return self.session.exec(
self.session.query(JobPayment).where(JobPayment.job_id == job_id)
).first()
return self.session.execute(
select(JobPayment).where(JobPayment.job_id == job_id)
).scalars().first()
def to_view(self, payment: JobPayment) -> JobPaymentView:
"""Convert payment to view model"""

View File

@@ -172,7 +172,7 @@ class OptimizedMinerService(BaseService[Miner]):
if key.startswith("miner_"):
address = key[7:] # Remove "miner_" prefix
statement = select(Miner).where(Miner.address == address)
result = self.session.exec(statement).first()
result = self.session.execute(statement).first()
if result:
await self.set_cached(key, result)
return result

View File

@@ -67,7 +67,7 @@ class TrustScoreCalculator:
# For now, use existing performance rating
# In real implementation, this would analyze actual job performance
reputation = session.exec(
reputation = session.execute(
select(AgentReputation).where(AgentReputation.agent_id == agent_id)
).first()
@@ -98,7 +98,7 @@ class TrustScoreCalculator:
) -> float:
"""Calculate reliability-based trust score component"""
reputation = session.exec(
reputation = session.execute(
select(AgentReputation).where(AgentReputation.agent_id == agent_id)
).first()
@@ -140,7 +140,7 @@ class TrustScoreCalculator:
)
)
feedbacks = session.exec(feedback_query).all()
feedbacks = session.execute(feedback_query).all()
if not feedbacks:
return 500.0 # Neutral score
@@ -178,7 +178,7 @@ class TrustScoreCalculator:
) -> float:
"""Calculate security-based trust score component"""
reputation = session.exec(
reputation = session.execute(
select(AgentReputation).where(AgentReputation.agent_id == agent_id)
).first()
@@ -209,7 +209,7 @@ class TrustScoreCalculator:
) -> float:
"""Calculate economic-based trust score component"""
reputation = session.exec(
reputation = session.execute(
select(AgentReputation).where(AgentReputation.agent_id == agent_id)
).first()
@@ -258,7 +258,7 @@ class TrustScoreCalculator:
)
# Apply smoothing with previous score if available
reputation = session.exec(
reputation = session.execute(
select(AgentReputation).where(AgentReputation.agent_id == agent_id)
).first()
@@ -296,7 +296,7 @@ class ReputationService:
"""Create a new reputation profile for an agent"""
# Check if profile already exists
existing = self.session.exec(
existing = self.session.execute(
select(AgentReputation).where(AgentReputation.agent_id == agent_id)
).first()
@@ -478,7 +478,7 @@ class ReputationService:
"""Update agent's community rating based on feedback"""
# Get all approved feedback
feedbacks = self.session.exec(
feedbacks = self.session.execute(
select(CommunityFeedback).where(
and_(
CommunityFeedback.agent_id == agent_id,
@@ -505,7 +505,7 @@ class ReputationService:
avg_rating = weighted_sum / total_weight
# Update reputation profile
reputation = self.session.exec(
reputation = self.session.execute(
select(AgentReputation).where(AgentReputation.agent_id == agent_id)
).first()
@@ -517,7 +517,7 @@ class ReputationService:
async def get_reputation_summary(self, agent_id: str) -> Dict[str, Any]:
"""Get comprehensive reputation summary for an agent"""
reputation = self.session.exec(
reputation = self.session.execute(
select(AgentReputation).where(AgentReputation.agent_id == agent_id)
).first()
@@ -525,7 +525,7 @@ class ReputationService:
return {"error": "Reputation profile not found"}
# Get recent events
recent_events = self.session.exec(
recent_events = self.session.execute(
select(ReputationEvent).where(
and_(
ReputationEvent.agent_id == agent_id,
@@ -535,7 +535,7 @@ class ReputationService:
).all()
# Get recent feedback
recent_feedback = self.session.exec(
recent_feedback = self.session.execute(
select(CommunityFeedback).where(
and_(
CommunityFeedback.agent_id == agent_id,
@@ -595,7 +595,7 @@ class ReputationService:
if region:
query = query.where(AgentReputation.geographic_region == region)
reputations = self.session.exec(query).all()
reputations = self.session.execute(query).all()
leaderboard = []
for rank, reputation in enumerate(reputations, 1):

View File

@@ -49,7 +49,7 @@ class RewardCalculator:
"""Calculate reward multiplier based on agent's tier"""
# Get tier configuration
tier_config = session.exec(
tier_config = session.execute(
select(RewardTierConfig).where(
and_(
RewardTierConfig.min_trust_score <= trust_score,
@@ -116,7 +116,7 @@ class RewardCalculator:
"""Calculate loyalty bonus based on agent history"""
# Get agent reward profile
reward_profile = session.exec(
reward_profile = session.execute(
select(AgentRewardProfile).where(AgentRewardProfile.agent_id == agent_id)
).first()
@@ -170,7 +170,7 @@ class RewardCalculator:
"""Calculate milestone achievement bonus"""
# Check for unclaimed milestones
milestones = session.exec(
milestones = session.execute(
select(RewardMilestone).where(
and_(
RewardMilestone.agent_id == agent_id,
@@ -200,7 +200,7 @@ class RewardCalculator:
"""Calculate total reward with all bonuses and multipliers"""
# Get agent's trust score and tier
reputation = session.exec(
reputation = session.execute(
select(AgentReputation).where(AgentReputation.agent_id == agent_id)
).first()
@@ -243,7 +243,7 @@ class RewardEngine:
"""Create a new reward profile for an agent"""
# Check if profile already exists
existing = self.session.exec(
existing = self.session.execute(
select(AgentRewardProfile).where(AgentRewardProfile.agent_id == agent_id)
).first()
@@ -346,7 +346,7 @@ class RewardEngine:
async def process_reward_distribution(self, distribution_id: str) -> RewardDistribution:
"""Process a reward distribution"""
distribution = self.session.exec(
distribution = self.session.execute(
select(RewardDistribution).where(RewardDistribution.id == distribution_id)
).first()
@@ -389,7 +389,7 @@ class RewardEngine:
async def update_agent_reward_profile(self, agent_id: str, reward_calculation: Dict[str, Any]):
"""Update agent reward profile after reward distribution"""
profile = self.session.exec(
profile = self.session.execute(
select(AgentRewardProfile).where(AgentRewardProfile.agent_id == agent_id)
).first()
@@ -426,7 +426,7 @@ class RewardEngine:
"""Check and update agent's reward tier"""
# Get agent reputation
reputation = self.session.exec(
reputation = self.session.execute(
select(AgentReputation).where(AgentReputation.agent_id == agent_id)
).first()
@@ -434,7 +434,7 @@ class RewardEngine:
return
# Get reward profile
profile = self.session.exec(
profile = self.session.execute(
select(AgentRewardProfile).where(AgentRewardProfile.agent_id == agent_id)
).first()
@@ -502,7 +502,7 @@ class RewardEngine:
async def get_reward_summary(self, agent_id: str) -> Dict[str, Any]:
"""Get comprehensive reward summary for an agent"""
profile = self.session.exec(
profile = self.session.execute(
select(AgentRewardProfile).where(AgentRewardProfile.agent_id == agent_id)
).first()
@@ -510,7 +510,7 @@ class RewardEngine:
return {"error": "Reward profile not found"}
# Get recent calculations
recent_calculations = self.session.exec(
recent_calculations = self.session.execute(
select(RewardCalculation).where(
and_(
RewardCalculation.agent_id == agent_id,
@@ -520,7 +520,7 @@ class RewardEngine:
).all()
# Get recent distributions
recent_distributions = self.session.exec(
recent_distributions = self.session.execute(
select(RewardDistribution).where(
and_(
RewardDistribution.agent_id == agent_id,
@@ -567,7 +567,7 @@ class RewardEngine:
"""Process pending reward distributions in batch"""
# Get pending distributions
pending_distributions = self.session.exec(
pending_distributions = self.session.execute(
select(RewardDistribution).where(
and_(
RewardDistribution.status == RewardStatus.PENDING,
@@ -608,7 +608,7 @@ class RewardEngine:
end_date = datetime.utcnow()
# Get distributions in period
distributions = self.session.exec(
distributions = self.session.execute(
select(RewardDistribution).where(
and_(
RewardDistribution.created_at >= start_date,
@@ -635,7 +635,7 @@ class RewardEngine:
# Get agent profiles for tier distribution
agent_ids = list(set(d.agent_id for d in distributions))
profiles = self.session.exec(
profiles = self.session.execute(
select(AgentRewardProfile).where(AgentRewardProfile.agent_id.in_(agent_ids))
).all()

View File

@@ -68,7 +68,7 @@ class SecureWalletService:
)
# Check if agent already has an active wallet of this type
existing = self.session.exec(
existing = self.session.execute(
select(AgentWallet).where(
AgentWallet.agent_id == request.agent_id,
AgentWallet.wallet_type == request.wallet_type,
@@ -116,7 +116,7 @@ class SecureWalletService:
async def get_wallet_by_agent(self, agent_id: str) -> List[AgentWallet]:
"""Retrieve all active wallets for an agent"""
return self.session.exec(
return self.session.execute(
select(AgentWallet).where(
AgentWallet.agent_id == agent_id,
AgentWallet.is_active == True
@@ -264,13 +264,13 @@ class SecureWalletService:
async def get_balances(self, wallet_id: int) -> List[TokenBalance]:
"""Get all tracked balances for a wallet"""
return self.session.exec(
return self.session.execute(
select(TokenBalance).where(TokenBalance.wallet_id == wallet_id)
).all()
async def update_balance(self, wallet_id: int, chain_id: int, token_address: str, balance: float) -> TokenBalance:
"""Update a specific token balance for a wallet"""
record = self.session.exec(
record = self.session.execute(
select(TokenBalance).where(
TokenBalance.wallet_id == wallet_id,
TokenBalance.chain_id == chain_id,

View File

@@ -816,7 +816,7 @@ class P2PTradingProtocol:
"""Find matching sellers for a trade request"""
# Get trade request
trade_request = self.session.exec(
trade_request = self.session.execute(
select(TradeRequest).where(TradeRequest.request_id == request_id)
).first()
@@ -879,7 +879,7 @@ class P2PTradingProtocol:
"""Initiate negotiation between buyer and seller"""
# Get trade match
trade_match = self.session.exec(
trade_match = self.session.execute(
select(TradeMatch).where(TradeMatch.match_id == match_id)
).first()
@@ -887,7 +887,7 @@ class P2PTradingProtocol:
raise ValueError(f"Trade match {match_id} not found")
# Get trade request
trade_request = self.session.exec(
trade_request = self.session.execute(
select(TradeRequest).where(TradeRequest.request_id == trade_match.request_id)
).first()
@@ -970,12 +970,12 @@ class P2PTradingProtocol:
"""Get comprehensive trading summary for an agent"""
# Get trade requests
requests = self.session.exec(
requests = self.session.execute(
select(TradeRequest).where(TradeRequest.buyer_agent_id == agent_id)
).all()
# Get trade matches
matches = self.session.exec(
matches = self.session.execute(
select(TradeMatch).where(
or_(
TradeMatch.buyer_agent_id == agent_id,
@@ -985,7 +985,7 @@ class P2PTradingProtocol:
).all()
# Get negotiations
negotiations = self.session.exec(
negotiations = self.session.execute(
select(TradeNegotiation).where(
or_(
TradeNegotiation.buyer_agent_id == agent_id,
@@ -995,7 +995,7 @@ class P2PTradingProtocol:
).all()
# Get agreements
agreements = self.session.exec(
agreements = self.session.execute(
select(TradeAgreement).where(
or_(
TradeAgreement.buyer_agent_id == agent_id,

View File

@@ -37,7 +37,7 @@ class WalletService:
"""Create a new wallet for an agent"""
# Check if agent already has an active wallet of this type
existing = self.session.exec(
existing = self.session.execute(
select(AgentWallet).where(
AgentWallet.agent_id == request.agent_id,
AgentWallet.wallet_type == request.wallet_type,
@@ -72,7 +72,7 @@ class WalletService:
async def get_wallet_by_agent(self, agent_id: str) -> List[AgentWallet]:
"""Retrieve all active wallets for an agent"""
return self.session.exec(
return self.session.execute(
select(AgentWallet).where(
AgentWallet.agent_id == agent_id,
AgentWallet.is_active == True
@@ -81,13 +81,13 @@ class WalletService:
async def get_balances(self, wallet_id: int) -> List[TokenBalance]:
"""Get all tracked balances for a wallet"""
return self.session.exec(
return self.session.execute(
select(TokenBalance).where(TokenBalance.wallet_id == wallet_id)
).all()
async def update_balance(self, wallet_id: int, chain_id: int, token_address: str, balance: float) -> TokenBalance:
"""Update a specific token balance for a wallet"""
record = self.session.exec(
record = self.session.execute(
select(TokenBalance).where(
TokenBalance.wallet_id == wallet_id,
TokenBalance.chain_id == chain_id,