{"record":{"id":"60a307fd16fedcd6","repo":"nautechsystems/nautilus_trader","slug":"failed-to-load-order-snapshot-e","errorCode":null,"errorMessage":"Failed to load order snapshot: {e}","messagePattern":"Failed to load order snapshot: (.+?)","errorType":"exception","errorClass":null,"httpStatus":null,"severity":"error","filePath":"crates/infrastructure/src/sql/queries.rs","lineNumber":473,"sourceCode":"            .await\n            .map_err(|e| anyhow::anyhow!(\"Failed to commit transaction: {e}\"))\n    }\n\n    /// Loads an `OrderSnapshot` entry by client order ID via the provided `pool`.\n    ///\n    /// # Errors\n    ///\n    /// Returns an error if the SQL SELECT or deserialization fails.\n    pub async fn load_order_snapshot(\n        pool: &PgPool,\n        client_order_id: &ClientOrderId,\n    ) -> anyhow::Result<Option<OrderSnapshot>> {\n        sqlx::query_as::<_, OrderSnapshotRow>(r#\"SELECT * FROM \"order\" WHERE client_order_id = $1\"#)\n            .bind(client_order_id.to_string())\n            .fetch_optional(pool)\n            .await\n            .map(|row| row.map(|row| row.0))\n            .map_err(|e| anyhow::anyhow!(\"Failed to load order snapshot: {e}\"))\n    }\n\n    /// Inserts or updates a `PositionSnapshot` entry via the provided `pool`.\n    ///\n    /// # Errors\n    ///\n    /// Returns an error if the SQL INSERT or UPDATE operation fails, or if beginning the transaction fails.\n    pub async fn add_position_snapshot(\n        pool: &PgPool,\n        snapshot: PositionSnapshot,\n    ) -> anyhow::Result<()> {\n        let mut transaction = pool.begin().await?;\n\n        // Insert trader if it does not exist\n        // TODO remove this when node and trader initialization is implemented\n        sqlx::query(\n            r#\"\n            INSERT INTO \"trader\" (id) VALUES ($1) ON CONFLICT (id) DO NOTHING","sourceCodeStart":455,"sourceCodeEnd":491,"githubUrl":"https://github.com/nautechsystems/nautilus_trader/blob/18893faf8b356be3320add8de2f861b0b647cf06/crates/infrastructure/src/sql/queries.rs#L455-L491","documentation":"Raised by `load_order_snapshot` when the parameterized `SELECT * FROM \"order\" WHERE client_order_id = $1` query fails. Note this is NOT the 'order not found' case — a missing order returns `Ok(None)`. This error means the query itself failed (connection, schema, or decode problem), wrapped in `anyhow` with this message.","triggerScenarios":"Calling `load_order_snapshot(pool, client_order_id)` when: the connection is unhealthy; the `\"order\"` table does not exist; the row's columns cannot decode into `OrderSnapshotRow` (schema drift); or the query times out.","commonSituations":"Fresh/unmigrated database; crate upgrade changed `OrderSnapshotRow` fields while the DB schema is old; pooled stale connections after a DB restart; quoting issues if the table name was created without double quotes in a different tool.","solutions":["Distinguish this from a missing record: `Ok(None)` means not found, this error means the query failed.","Inspect the wrapped `{e}` to find the root cause (relation missing, decode error, connection).","Run the schema migrations and keep the crate version and DB schema in sync.","Verify pool health / reconnect settings so stale connections are detected."],"exampleFix":"// before: treating None and error the same\nlet snap = load_order_snapshot(&pool, cid).await.unwrap_or_default();\n\n// after: handle both outcomes explicitly\nmatch load_order_snapshot(&pool, cid).await? {\n    Some(snap) => replay(snap),\n    None => tracing::warn!(\"no snapshot for {cid}\"),\n}","handlingStrategy":"type-guard","validationCode":"let ok = sqlx::query_scalar::<_, i64>(\n    \"SELECT COUNT(*) FROM information_schema.tables WHERE table_name = 'order'\")\n    .fetch_one(pool).await? > 0;\nif !ok { return Err(anyhow::anyhow!(\"order table missing: run migrations\")); }","typeGuard":"// Distinguish 'query failed' from 'order not found' at the call site\nenum SnapshotLookup { Found(OrderSnapshot), NotFound, QueryFailed(anyhow::Error) }\nlet result = match load_order_snapshot(&pool, client_order_id).await {\n    Ok(Some(s)) => SnapshotLookup::Found(s),\n    Ok(None) => SnapshotLookup::NotFound,\n    Err(e) => SnapshotLookup::QueryFailed(e),\n};","tryCatchPattern":"match load_order_snapshot(&pool, cid).await {\n    Ok(Some(s)) => handle(s),\n    Ok(None) => tracing::debug!(\"no snapshot for {cid}\"),\n    Err(e) => return Err(anyhow::anyhow!(\"snapshot lookup failed: {e:#}\")),\n}","preventionTips":["Never conflate Ok(None) with an error — only Err indicates a failed query.","Run migrations and keep row structs aligned with the schema.","Use pool acquire timeouts to fail fast on connectivity issues.","Enable sqlx statement logging during development to catch decode mismatches."],"tags":["database","postgres","sqlx","rust","select"],"backgroundTag":"database-query-failed","analyzedSha":"18893faf8b356be3320add8de2f861b0b647cf06","analyzedAt":"2026-09-08T20:49:34.690Z","contentChangedAt":"2026-09-08T20:49:34.690Z","schemaVersion":2},"datasetVersion":"2026-09-14T05:17:10.506Z"}