{"record":{"id":"4579ccd18e17adc9","repo":"nautechsystems/nautilus_trader","slug":"failed-to-insert-into-order-event-table-e","errorCode":null,"errorMessage":"Failed to insert into order_event table: {e}","messagePattern":"Failed to insert into order_event table: (.+?)","errorType":"exception","errorClass":null,"httpStatus":null,"severity":"error","filePath":"crates/infrastructure/src/sql/queries.rs","lineNumber":760,"sourceCode":"            .bind(order_event.account_id().map(|x| x.to_string()))\n            .bind(order_event.position_id().map(|x| x.to_string()))\n            .bind(order_event.commission().map(|x| x.to_string()))\n            .bind(order_event.ts_event().to_string())\n            .bind(order_event.ts_init().to_string())\n            .bind(order_event.activation_price().map(|x| x.to_string()))\n            .bind(exec_algorithm_params)\n            .bind(order_event.tags().map(|x| x.iter().map(ToString::to_string).collect::<Vec<String>>()))\n            .bind(order_event.released_price().map(|x| x.to_string()))\n            .bind(order_event.protection_price().map(|x| x.to_string()))\n            .bind(order_event.due_post_only())\n            .bind(order_event.correction_id().map(|x| x.to_string()))\n            .bind(order_event.is_reopened())\n            .bind(info)\n            .bind(order_event.causation_id().map(|x| x.to_string()))\n            .execute(&mut *transaction)\n            .await\n            .map(|_| ())\n            .map_err(|e| anyhow::anyhow!(\"Failed to insert into order_event table: {e}\"))?;\n        transaction\n            .commit()\n            .await\n            .map_err(|e| anyhow::anyhow!(\"Failed to commit transaction: {e}\"))\n    }\n\n    /// Loads all order events for a `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_events(\n        pool: &PgPool,\n        client_order_id: &ClientOrderId,\n    ) -> anyhow::Result<Vec<OrderEventAny>> {\n        sqlx::query_as::<_, OrderEventAnyRow>(r#\"SELECT * FROM \"order_event\" event WHERE event.client_order_id = $1 ORDER BY created_at ASC\"#)\n        .bind(client_order_id.to_string())\n        .fetch_all(pool)","sourceCodeStart":742,"sourceCodeEnd":778,"githubUrl":"https://github.com/nautechsystems/nautilus_trader/blob/18893faf8b356be3320add8de2f861b0b647cf06/crates/infrastructure/src/sql/queries.rs#L742-L778","documentation":"Wraps the sqlx failure of the final INSERT into the `order_event` table inside `add_order_event`, just before commit. The transaction is aborted implicitly and the caller receives this anyhow-wrapped error. Common causes are constraint violations (PK/duplicate client_order_id+kind), column type mismatches, or connectivity loss.","triggerScenarios":"Calling `add_order_event` when the order_event INSERT violates a primary key/unique constraint (re-adding the same event), a column value exceeds its type/length, or the DB connection drops during the insert.","commonSituations":"Replaying the same event twice during reconciliation; schema drift between the Rust column list and the migrated table; oversized reason/info payloads; DB failover mid-transaction.","solutions":["Check `{e}` for a unique/PK violation and deduplicate before inserting (use the existence checks).","Run migrations so the `order_event` schema matches the Rust INSERT column list.","Verify JSON columns (`exec_algorithm_params`, `info`) accept the serialized values.","Retry `add_order_event`; the transaction ensures no partial rows remain."],"exampleFix":"// before\nadd_order_event(&mut tx, &event, None).await?;\n// after\nif !check_if_order_initialized_exists(&pool, event.client_order_id()).await? {\n    add_order_event(&mut tx, &event, None).await?;\n}","handlingStrategy":"try-catch","validationCode":"// Avoid duplicate inserts by checking first\nlet exists = sqlx::query(\n    r#\"SELECT EXISTS(SELECT 1 FROM \"order_event\" WHERE client_order_id = $1 AND kind = $2)\"#)\n    .bind(event.client_order_id().to_string())\n    .bind(event.kind().to_string())\n    .fetch_one(pool).await\n    .map(|row| row.get::<bool, _>(0))\n    .unwrap_or(false);\nif exists { return Ok(()); }","typeGuard":"fn is_unique_violation(e: &anyhow::Error) -> bool {\n    let s = e.to_string();\n    s.contains(\"duplicate key\") || s.contains(\"23505\")\n}","tryCatchPattern":"match add_order_event(&mut tx, &event, client_id).await {\n    Ok(()) => {}\n    Err(e) if is_unique_violation(&e) => { /* idempotent: already inserted */ }\n    Err(e) => return Err(e),\n}","preventionTips":["Deduplicate events before persisting (check existence by client_order_id + kind).","Run migrations so the column list matches the Rust INSERT.","Bound payload sizes (reason/info) to column limits.","Enable pool reconnects for long reconciliation runs."],"tags":["database","sqlx","transaction","insert","postgres"],"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"}