{"record":{"id":"af5796f4797a4330","repo":"nautechsystems/nautilus_trader","slug":"failed-to-insert-into-bar-table-e","errorCode":null,"errorMessage":"Failed to insert into bar table: {e}","messagePattern":"Failed to insert into bar table: (.+?)","errorType":"exception","errorClass":null,"httpStatus":null,"severity":"error","filePath":"crates/infrastructure/src/sql/queries.rs","lineNumber":1379,"sourceCode":"                instrument_id = $1, step = $2, bar_aggregation = $3::bar_aggregation, price_type = $4::price_type, aggregation_source = $5::aggregation_source,\n                open = $6, high = $7, low = $8, close = $9, volume = $10, ts_event = $11, ts_init = $12, updated_at = CURRENT_TIMESTAMP\n        \"#)\n            .bind(bar.bar_type.instrument_id().to_string())\n            .bind(bar_step)\n            .bind(BarAggregationPg(bar.bar_type.spec().aggregation))\n            .bind(PriceTypePg(bar.bar_type.spec().price_type))\n            .bind(AggregationSourcePg(bar.bar_type.aggregation_source()))\n            .bind(bar.open.to_string())\n            .bind(bar.high.to_string())\n            .bind(bar.low.to_string())\n            .bind(bar.close.to_string())\n            .bind(bar.volume.to_string())\n            .bind(bar.ts_event.to_string())\n            .bind(bar.ts_init.to_string())\n            .execute(pool)\n            .await\n            .map(|_| ())\n            .map_err(|e| anyhow::anyhow!(\"Failed to insert into bar table: {e}\"))\n    }\n\n    /// Loads all `Bar` entries for `instrument_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_bars(\n        pool: &PgPool,\n        instrument_id: &InstrumentId,\n    ) -> anyhow::Result<Vec<Bar>> {\n        sqlx::query_as::<_, BarRow>(\n            r#\"SELECT * FROM \"bar\" WHERE instrument_id = $1 ORDER BY ts_event ASC\"#,\n        )\n        .bind(instrument_id.to_string())\n        .fetch_all(pool)\n        .await\n        .map(|rows| rows.into_iter().map(|row| row.0).collect())","sourceCodeStart":1361,"sourceCodeEnd":1397,"githubUrl":"https://github.com/nautechsystems/nautilus_trader/blob/18893faf8b356be3320add8de2f861b0b647cf06/crates/infrastructure/src/sql/queries.rs#L1361-L1397","documentation":"add_bar wraps any sqlx error that occurs while binding/inserting a Bar row into the `bar` table inside anyhow::anyhow!, losing the concrete error type. It means the INSERT into the bar table failed at the database layer — typically a schema mismatch, constraint violation, or connection issue. The library throws it so callers get a single anyhow::Result with a descriptive message and the underlying sqlx error chained as source.","triggerScenarios":"Calling add_bar when the `bar` table does not exist or was created with an older schema, when bar fields exceed column types/precision (e.g. oversized instrument_id or volume), when the connection pool is dead, or when a UNIQUE/PRIMARY KEY constraint (instrument_id + ts_event) is violated.","commonSituations":"Running against a Postgres/SQLite database migrated with an outdated schema version; switching between SQLite and Postgres backends with incompatible types; network drop between pool creation and execute; inserting a duplicate bar for the same instrument/timestamp.","solutions":["Log/print the chained source (`e.source()`) or `{:?}` of the anyhow error to see the underlying sqlx message.","Verify the `bar` table exists and matches the current schema by running the crate's migration/initialization (e.g. `create_bar_tables`) before inserting.","Check DB connectivity and that the PgPool/SqlitePool is alive and credentials are valid.","Ensure you are not inserting a duplicate bar for the same instrument_id/ts_event if a uniqueness constraint applies.","Confirm column types can hold the stringified values (volume, ts_event, ts_init)."],"exampleFix":"// before\nlet pool = PgPool::connect_lazy(url)?;\nqueries::postgres::add_bar(&pool, &bar).await?;\n// after\nlet pool = PgPool::connect(url).await?; // fail fast on bad connection\nsqlx::migrate!().run(&pool).await?;      // ensure schema exists\nqueries::postgres::add_bar(&pool, &bar).await?;","handlingStrategy":"validation","validationCode":"// Rust\nasync fn bar_table_ready(pool: &sqlx::PgPool) -> anyhow::Result<()> {\n    sqlx::query(r#\"SELECT 1 FROM \\\"bar\\\" LIMIT 1\"#).fetch_optional(pool).await\n        .map(|_| ())\n        .map_err(|e| anyhow::anyhow!(\"bar table not initialized: {e}\"))\n}","typeGuard":null,"tryCatchPattern":"// Rust\nmatch queries::postgres::add_bar(&pool, &bar).await {\n    Ok(()) => (),\n    Err(e) => {\n        tracing::error!(source = ?std::error::Error::source(&e), \"bar insert failed\");\n        return Err(e);\n    }\n}","preventionTips":["Run schema creation/migrations at startup before any writes","Fail fast by connecting (not connect_lazy) so bad credentials surface early","Log the anyhow error source chain to expose the raw sqlx cause","Avoid duplicate bars per instrument_id/ts_event in your ingestion pipeline"],"tags":["rust","database","sqlx","anyhow","insert"],"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"}