{"record":{"id":"33ba0d455ca46d1e","repo":"dbt-labs/dbt-core","slug":"target-is-not-set-in-state","errorCode":null,"errorMessage":"target is not set in state","messagePattern":"target is not set in state","errorType":"exception","errorClass":"minijinja::Error","httpStatus":null,"severity":"error","filePath":"crates/dbt-adapter/src/adapter/adapter_impl.rs","lineNumber":1705,"sourceCode":"        excluded_schemas: Option<Value>,\n    ) -> Result<Value, minijinja::Error> {\n        // Validate excluded_schemas if provided\n        if let Some(ref schemas) = excluded_schemas {\n            let _ =\n                minijinja_value_to_typed_struct::<Vec<String>>(schemas.clone()).map_err(|e| {\n                    minijinja::Error::new(\n                        minijinja::ErrorKind::SerdeDeserializeError,\n                        e.to_string(),\n                    )\n                })?;\n        }\n\n        // Get default database from state if not provided\n        let database_str = if let Some(db) = database {\n            db.to_string()\n        } else {\n            let target = state.lookup(\"target\", &[]).ok_or_else(|| {\n                minijinja::Error::new(\n                    minijinja::ErrorKind::InvalidOperation,\n                    \"target is not set in state\",\n                )\n            })?;\n            let db_value = target.get_attr(\"database\").unwrap_or_default();\n            db_value.as_str().unwrap_or_default().to_string()\n        };\n\n        // Build args array for macro call\n        // Note: For optional string parameters like 'exclude', we pass empty string instead of None\n        // because the macro expects a string and None gets converted to \"none\" string\n        let args = vec![\n            Value::from(schema_pattern),\n            Value::from(table_pattern),\n            exclude.map(Value::from).unwrap_or_else(|| Value::from(\"\")),\n            Value::from(database_str.as_str()),\n            quote_table\n                .map(Value::from)","sourceCodeStart":1687,"sourceCodeEnd":1723,"githubUrl":"https://github.com/dbt-labs/dbt-core/blob/0267ce9170576975b76b64ce856b2e5848e96617/crates/dbt-adapter/src/adapter/adapter_impl.rs#L1687-L1723","documentation":"get_relations_by_pattern derives a default database from the render state's `target` when no database argument is supplied. If `state.lookup(\"target\")` returns None — target not injected into state — this InvalidOperation error is raised. It indicates the adapter runtime was invoked without an initialized target context.","triggerScenarios":"Calling get_relations_by_pattern without a database argument while the minijinja state has no `target` object — e.g. invoking the function outside a normal dbt run context, in tests, or in tooling that builds the Jinja env manually.","commonSituations":"Unit-testing macros with a hand-rolled state missing target; custom scripts calling adapter methods before target resolution; partial state setup in embedded usage of the adapter runtime.","solutions":["Pass the database argument explicitly so state lookup is not needed.","Ensure the runtime injects `target` into the state before executing macros.","Fix test/embedded harnesses to populate state with a target containing a `database` attribute.","Catch the error and default to the configured target's database from your own config if acceptable."],"exampleFix":"// before\nlet rels = get_relations_by_pattern(pattern, None, excluded)?;\n\n// after\nlet rels = get_relations_by_pattern(pattern, Some(\"analytics_db\".into()), excluded)?;","handlingStrategy":"try-catch","validationCode":"{% set has_target = state is defined and state.get('target', none) is not none %}","typeGuard":"fn state_has_target(state: &Value) -> bool {\n    state.lookup(\"target\", &[]).is_some()\n}","tryCatchPattern":"{% try %}\n  {% set rels = get_relations_by_pattern(pattern, none, excluded) %}\n{% except %}\n  {% set rels = get_relations_by_pattern(pattern, target.database, excluded) %}\n{% endtry %}","preventionTips":["Pass the database explicitly when invoking adapter functions outside a full dbt run","Ensure test harnesses inject a target with a database attribute into state","Initialize the runtime fully (target resolution) before calling adapter methods"],"tags":["state","jinja","adapter","missing-context"],"backgroundTag":"missing-env-var","analyzedSha":"0267ce9170576975b76b64ce856b2e5848e96617","analyzedAt":"2026-09-07T21:53:39.732Z","contentChangedAt":"2026-09-07T21:53:39.732Z","schemaVersion":2},"datasetVersion":"2026-09-14T16:17:12.679Z"}