{"record":{"id":"5634b7bea726a569","repo":"nautechsystems/nautilus_trader","slug":"failed-to-insert-into-order-position-index-table","errorCode":null,"errorMessage":"Failed to insert into order_position_index table: {e}","messagePattern":"Failed to insert into order_position_index table: (.+?)","errorType":"exception","errorClass":null,"httpStatus":null,"severity":"error","filePath":"crates/infrastructure/src/sql/queries.rs","lineNumber":1535,"sourceCode":"        sqlx::query(\n            r#\"\n            INSERT INTO \"order_position_index\" (\n                client_order_id, position_id, created_at, updated_at\n            ) VALUES (\n                $1, $2, CURRENT_TIMESTAMP, CURRENT_TIMESTAMP\n            )\n            ON CONFLICT (client_order_id)\n            DO UPDATE\n            SET\n                position_id = $2, updated_at = CURRENT_TIMESTAMP\n        \"#,\n        )\n        .bind(client_order_id.to_string())\n        .bind(position_id.to_string())\n        .execute(pool)\n        .await\n        .map(|_| ())\n        .map_err(|e| anyhow::anyhow!(\"Failed to insert into order_position_index table: {e}\"))\n    }\n\n    /// Loads the order ID to position ID index via the provided `pool`.\n    ///\n    /// # Errors\n    ///\n    /// Returns an error if the SQL SELECT or iteration fails.\n    pub async fn load_index_order_position(\n        pool: &PgPool,\n    ) -> anyhow::Result<AHashMap<ClientOrderId, PositionId>> {\n        let mut map: AHashMap<ClientOrderId, PositionId> = AHashMap::new();\n        let result = sqlx::query_as::<_, OrderPositionIndexRow>(\n            r#\"\n            SELECT\n                client_order_id AS \"client_order_id\",\n                position_id AS \"position_id\"\n            FROM \"order_position_index\"\n        \"#,","sourceCodeStart":1517,"sourceCodeEnd":1553,"githubUrl":"https://github.com/nautechsystems/nautilus_trader/blob/18893faf8b356be3320add8de2f861b0b647cf06/crates/infrastructure/src/sql/queries.rs#L1517-L1553","documentation":"index_order_position wraps any sqlx error from inserting a (client_order_id, position_id) row into the `order_position_index` table in anyhow. It means the mapping write failed at the database layer — schema mismatch, missing table, or connection problem. The typed sqlx error is preserved as the anyhow error source.","triggerScenarios":"Calling index_order_position when the `order_position_index` table doesn't exist, columns don't match (client_order_id/position_id), a constraint is violated, or the pool connection fails.","commonSituations":"Cache DB initialized with an older schema lacking the index table; wrong database URL; duplicate/conflicting index rows if unique constraints apply; DB offline during a session.","solutions":["Inspect the chained sqlx error source for the exact DB message.","Run schema initialization so `order_position_index` exists with the expected columns.","Check DB connectivity and pool health.","If a uniqueness constraint fires, use upsert semantics or delete the stale mapping first."],"exampleFix":"// before\nqueries::postgres::index_order_position(&pool, &client_order_id, &position_id).await?;\n// after\nsqlx::query(r#\"CREATE TABLE IF NOT EXISTS \"order_position_index\" (client_order_id VARCHAR PRIMARY KEY, position_id VARCHAR)\"#)\n    .execute(&pool).await?;\nqueries::postgres::index_order_position(&pool, &client_order_id, &position_id).await?;","handlingStrategy":"validation","validationCode":"let ready = sqlx::query(r#\"SELECT 1 FROM \\\"order_position_index\\\" LIMIT 1\"#)\n    .fetch_optional(pool).await.is_ok();\nanyhow::ensure!(ready, \"order_position_index table missing; run schema init\");","typeGuard":null,"tryCatchPattern":"match queries::postgres::index_order_position(&pool, &client_order_id, &position_id).await {\n    Ok(()) => (),\n    Err(e) => {\n        tracing::error!(source = ?std::error::Error::source(&e), \"order_position_index insert failed\");\n        return Err(e);\n    }\n}","preventionTips":["Create order_position_index via schema init before any position indexing","Migrate the schema when upgrading nautilus versions","Handle unique-constraint conflicts with upsert or delete-then-insert","Log sqlx source chains for fast diagnosis"],"tags":["rust","database","sqlx","insert","anyhow"],"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"}