{"record":{"id":"dad0f14b956c09e6","repo":"nautechsystems/nautilus_trader","slug":"failed-to-insert-into-order-table-e","errorCode":null,"errorMessage":"Failed to insert into order table: {e}","messagePattern":"Failed to insert into order table: (.+?)","errorType":"exception","errorClass":null,"httpStatus":null,"severity":"error","filePath":"crates/infrastructure/src/sql/queries.rs","lineNumber":451,"sourceCode":"            .bind(snapshot.contingency_type.map_or_else(\n                || \"NO_CONTINGENCY\".to_string(),\n                |value| value.to_string(),\n            ))\n            .bind(snapshot.order_list_id.map(|x| x.to_string()))\n            .bind(snapshot.linked_order_ids.map(|x| x.iter().map(ToString::to_string).collect::<Vec<String>>()))\n            .bind(snapshot.parent_order_id.map(|x| x.to_string()))\n            .bind(snapshot.exec_algorithm_id.map(|x| x.to_string()))\n            .bind(snapshot.exec_algorithm_params.map(|x| serde_json::to_value(x).unwrap()))\n            .bind(snapshot.exec_spawn_id.map(|x| x.to_string()))\n            .bind(snapshot.tags.map(|x| x.iter().map(ToString::to_string).collect::<Vec<String>>()))\n            .bind(snapshot.init_id.to_string())\n            .bind(snapshot.ts_init.to_string())\n            .bind(snapshot.ts_last.to_string())\n            .bind(snapshot.activation_price.map(|x| x.to_string()))\n            .execute(&mut *transaction)\n            .await\n            .map(|_| ())\n            .map_err(|e| anyhow::anyhow!(\"Failed to insert into order table: {e}\"))?;\n\n        transaction\n            .commit()\n            .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())","sourceCodeStart":433,"sourceCodeEnd":469,"githubUrl":"https://github.com/nautechsystems/nautilus_trader/blob/18893faf8b356be3320add8de2f861b0b647cf06/crates/infrastructure/src/sql/queries.rs#L433-L469","documentation":"Raised by `add_order_snapshot` on the second step of its transaction: the INSERT into the `\"order\"` table fails. At this point the trader-table insert already succeeded, but since the transaction is never committed it is rolled back, so no partial data is persisted. The sqlx error is wrapped in `anyhow` with this message.","triggerScenarios":"Calling `add_order_snapshot` when: the `\"order\"` table is missing; a required column is NULL (e.g. venue_order_id, position_id constraints); a value exceeds a column's length/precision; a bound value's string form fails to parse into the column type; or a unique constraint on client_order_id is violated by a duplicate snapshot.","commonSituations":"Writing the same order snapshot twice during replay recovery; migrations not applied; enum-like values (order_type, order_side) written as strings not matching the DB enum/CHECK constraints; schema changed after a crate upgrade so bind count/types mismatch.","solutions":["Read the wrapped `{e}` to identify the exact constraint or type error.","Ensure migrations have created the `\"order\"` table with the expected schema.","Avoid duplicate writes: check `load_order_snapshot` first or add ON CONFLICT handling for client_order_id.","Verify optional fields (price, trigger_price, venue_order_id) match column nullability and types."],"exampleFix":"// before: blindly inserting duplicates\nadd_order_snapshot(&pool, &snapshot).await?;\n\n// after: skip if already persisted\nif load_order_snapshot(&pool, snapshot.client_order_id).await?.is_none() {\n    add_order_snapshot(&pool, &snapshot).await?;\n}","handlingStrategy":"validation","validationCode":"// Avoid the most common cause: duplicate client_order_id\nlet dup = sqlx::query_scalar::<_, i64>(\n    \"SELECT COUNT(*) FROM \\\"order\\\" WHERE client_order_id = $1\")\n    .bind(snapshot.client_order_id.to_string())\n    .fetch_one(pool).await? > 0;\nif dup { return Ok(()); }","typeGuard":null,"tryCatchPattern":"match add_order_snapshot(&pool, &snapshot).await {\n    Ok(()) => (),\n    Err(e) if format!(\"{e:#}\").contains(\"duplicate key\") => {\n        tracing::warn!(\"snapshot already exists for {}\", snapshot.client_order_id);\n    }\n    Err(e) => return Err(e),\n}","preventionTips":["Check for an existing snapshot (load_order_snapshot) before writing.","Ensure order_type/order_side values match DB enum/CHECK constraints.","Verify optional fields (price, trigger_price, venue_order_id) match column nullability.","Apply schema migrations before replay/ingestion jobs."],"tags":["database","postgres","sqlx","transaction","rust"],"backgroundTag":"database-write-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"}