Skip to content

Commit 2a70a76

Browse files
committed
feat: progress on dbt
1 parent bbb873d commit 2a70a76

File tree

15 files changed

+196
-19
lines changed

15 files changed

+196
-19
lines changed

crates/lib/Cargo.toml

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -38,6 +38,7 @@ name = "depth_map"
3838
harness = false
3939

4040
[features]
41+
default = ["python"]
4142
python = ["pyo3", "sqruff-lib-core/serde"]
4243

4344
[dependencies]

crates/lib/src/core/config.rs

Lines changed: 10 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -425,7 +425,16 @@ impl ConfigLoader {
425425
unimplemented!()
426426
} else if name_lowercase.ends_with("_path") || name_lowercase.ends_with("_dir")
427427
{
428-
unimplemented!()
428+
// if absolute_path, just keep
429+
// if relative path, make it absolute
430+
let path = PathBuf::from(value.as_string().unwrap());
431+
if !path.is_absolute() {
432+
unimplemented!(
433+
"Relative paths are not supported yet. {}, {}",
434+
name,
435+
path.to_str().unwrap_or_default()
436+
);
437+
}
429438
}
430439

431440
let mut key = key.clone();

crates/lib/src/templaters/dbt.rs

Lines changed: 63 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -9,6 +9,7 @@ use pyo3::{Py, PyAny, Python};
99
use sqruff_lib_core::errors::SQLFluffUserError;
1010
use sqruff_lib_core::templaters::base::TemplatedFile;
1111
use std::ffi::CString;
12+
use std::path::PathBuf;
1213
use std::sync::Arc;
1314

1415
pub struct DBTTemplater;
@@ -106,7 +107,7 @@ impl Templater for DBTTemplater {
106107
syspath.insert(0, temp_folder)?;
107108

108109
let file_contents = CString::new(DBT_FILE).unwrap();
109-
let main_module = PyModule::from_code(py, &file_contents, c"", c"")?;
110+
let main_module = PyModule::from_code(py, &file_contents, &c"dbt_templater.py", &c"dbt_templater")?;
110111
let fun: Py<PyAny> = main_module.getattr("process_from_rust")?.into();
111112

112113
let py_dict = config.to_python_context(py, "dbt").unwrap();
@@ -128,3 +129,64 @@ impl Templater for DBTTemplater {
128129
Ok(templated_file)
129130
}
130131
}
132+
133+
#[cfg(test)]
134+
mod tests {
135+
use super::*;
136+
use std::fmt::format;
137+
use std::path::Path;
138+
139+
#[test]
140+
fn test_dbt_simple() {
141+
let templater = DBTTemplater;
142+
143+
let crate_location = PathBuf::from(env!("CARGO_MANIFEST_DIR"));
144+
let file = crate_location.join("src").join("templaters").join("dbt.rs");
145+
let project_dir = file
146+
.parent()
147+
.unwrap()
148+
.join("sqruff_templaters")
149+
.join("sample_dbt")
150+
.canonicalize()
151+
.unwrap();
152+
let profiles_dir = project_dir.join(".profiles").canonicalize().unwrap();
153+
let file_path = project_dir
154+
.join("models/example/my_first_dbt_model.sql")
155+
.canonicalize()
156+
.unwrap();
157+
158+
let config = format!(
159+
r#"
160+
[sqruff]
161+
templater = dbt
162+
163+
[sqruff:templater:dbt]
164+
project_dir = {project_dir}
165+
profiles_dir = {profiles_dir}
166+
"#,
167+
project_dir = project_dir.to_str().unwrap(),
168+
profiles_dir = profiles_dir.to_str().unwrap()
169+
);
170+
171+
let fluff_config = FluffConfig::from_source(&config, None);
172+
173+
let templated_file = templater
174+
.process(
175+
r#"
176+
{{ config(materialized='table') }}
177+
178+
with source_data as (
179+
select 1 as id
180+
union all
181+
select null as id
182+
)
183+
"#,
184+
file_path.to_str().unwrap(),
185+
&fluff_config,
186+
&None,
187+
)
188+
.unwrap();
189+
190+
assert!(!templated_file.sliced_file.is_empty());
191+
}
192+
}

crates/lib/src/templaters/python_shared.rs

Lines changed: 16 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -85,11 +85,25 @@ impl From<FluffConfig> for PythonFluffConfig {
8585
.unwrap_or_default(),
8686

8787
dbt_profile: None,
88-
dbt_profiles_dir: None,
88+
dbt_profiles_dir: value
89+
.get_section("templater")
90+
.get("dbt")
91+
.map(|value| value.as_map().unwrap())
92+
.and_then(|value| {
93+
value
94+
.get("profiles_dir")
95+
.map(|v| v.as_string().unwrap().to_string())
96+
}),
8997
dbt_target: None,
9098
dbt_target_path: None,
9199
dbt_context: None,
92-
dbt_project_dir: None,
100+
dbt_project_dir: value.get_section("templater").get("dbt").and_then(|value| {
101+
value
102+
.as_map()
103+
.unwrap()
104+
.get("project_dir")
105+
.map(|v| v.as_string().unwrap().to_string())
106+
}),
93107
}
94108
}
95109
}

crates/lib/src/templaters/sqruff_templaters/dbt_templater.py

Lines changed: 1 addition & 15 deletions
Original file line numberDiff line numberDiff line change
@@ -266,14 +266,11 @@ def dbt_config(self):
266266

267267
# Attempt to silence internal logging at this point.
268268
# https://github.com/sqlfluff/sqlfluff/issues/5054
269-
print("dbt config")
270269
# self.try_silence_dbt_logs()
271270

272271
user_config = None
273272
cli_vars = self._get_cli_vars()
274273

275-
print("set user config and cli vars")
276-
277274
flags.set_from_args(
278275
DbtConfigArgs(
279276
project_dir=self.project_dir,
@@ -285,7 +282,6 @@ def dbt_config(self):
285282
),
286283
user_config,
287284
)
288-
print("flags set")
289285
_dbt_config = DbtRuntimeConfig.from_args(
290286
DbtConfigArgs(
291287
project_dir=self.project_dir,
@@ -297,10 +293,8 @@ def dbt_config(self):
297293
threads=1,
298294
)
299295
)
300-
print("dbt config set")
301296

302297
register_adapter(_dbt_config, get_mp_context())
303-
print("return dbt config")
304298
return _dbt_config
305299

306300
@cached_property
@@ -328,8 +322,6 @@ def dbt_manifest(self):
328322
# dbt 0.20.* and onward
329323
from dbt.parser.manifest import ManifestLoader
330324

331-
print(self.dbt_config)
332-
333325
return ManifestLoader.get_full_manifest(self.dbt_config)
334326

335327
@cached_property
@@ -447,10 +439,6 @@ def sequence_files(
447439
if not self.profiles_dir:
448440
self.profiles_dir = self._get_profiles_dir()
449441

450-
print("project_dir", self.project_dir)
451-
print("")
452-
print(self)
453-
454442
outs = []
455443

456444
# Populate full paths for selected files
@@ -861,15 +849,12 @@ def process_from_rust(
861849
config_string: str,
862850
live_context: Dict[str, Any],
863851
) -> TemplatedFile:
864-
print("sys.path:", sys.path)
865-
print("Current working directory:", os.getcwd())
866852
"""Process the call from the rust side."""
867853
config = fluff_config_from_json(config_string)
868854
templater = DbtTemplater(override_context=live_context, sqlfluff_config=config)
869855
try:
870856
fnames = templater.sequence_files([fname], config=config)
871857
fname = fnames[0]
872-
print(fname)
873858
(output, errors) = templater.process(
874859
in_str=string,
875860
fname=fname,
@@ -878,6 +863,7 @@ def process_from_rust(
878863
)
879864
except Exception as e:
880865
print("Error: ", e)
866+
print("Error Stack:", e.__traceback__)
881867
raise e
882868
if errors != []:
883869
raise ValueError
Lines changed: 15 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,15 @@
1+
Welcome to your new dbt project!
2+
3+
### Using the starter project
4+
5+
Try running the following commands:
6+
- dbt run
7+
- dbt test
8+
9+
10+
### Resources:
11+
- Learn more about dbt [in the docs](https://docs.getdbt.com/docs/introduction)
12+
- Check out [Discourse](https://discourse.getdbt.com/) for commonly asked questions and answers
13+
- Join the [chat](https://community.getdbt.com/) on Slack for live discussions and support
14+
- Find [dbt events](https://events.getdbt.com) near you
15+
- Check out [the blog](https://blog.getdbt.com/) for the latest news on dbt's development and best practices

crates/lib/test/fixtures/dbt/analyses/.gitkeep

Whitespace-only changes.
Lines changed: 36 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,36 @@
1+
2+
# Name your project! Project names should contain only lowercase characters
3+
# and underscores. A good package name should reflect your organization's
4+
# name or the intended use of these models
5+
name: 'test'
6+
version: '1.0.0'
7+
8+
# This setting configures which "profile" dbt uses for this project.
9+
profile: 'test'
10+
11+
# These configurations specify where dbt should look for different types of files.
12+
# The `model-paths` config, for example, states that models in this project can be
13+
# found in the "models/" directory. You probably won't need to change these!
14+
model-paths: ["models"]
15+
analysis-paths: ["analyses"]
16+
test-paths: ["tests"]
17+
seed-paths: ["seeds"]
18+
macro-paths: ["macros"]
19+
snapshot-paths: ["snapshots"]
20+
21+
clean-targets: # directories to be removed by `dbt clean`
22+
- "target"
23+
- "dbt_packages"
24+
25+
26+
# Configuring models
27+
# Full documentation: https://docs.getdbt.com/docs/configuring-models
28+
29+
# In this example config, we tell dbt to build all models in the example/
30+
# directory as views. These settings can be overridden in the individual model
31+
# files using the `{{ config(...) }}` macro.
32+
models:
33+
test:
34+
# Config indicated by + and applies to all files under models/example/
35+
example:
36+
+materialized: view

crates/lib/test/fixtures/dbt/macros/.gitkeep

Whitespace-only changes.
Lines changed: 27 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,27 @@
1+
2+
/*
3+
Welcome to your first dbt model!
4+
Did you know that you can also configure models directly within SQL files?
5+
This will override configurations stated in dbt_project.yml
6+
7+
Try changing "table" to "view" below
8+
*/
9+
10+
{{ config(materialized='table') }}
11+
12+
with source_data as (
13+
14+
select 1 as id
15+
union all
16+
select null as id
17+
18+
)
19+
20+
select *
21+
from source_data
22+
23+
/*
24+
Uncomment the line below to remove records with null `id` values
25+
*/
26+
27+
-- where id is not null
Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,6 @@
1+
2+
-- Use the `ref` function to select from other models
3+
4+
select *
5+
from {{ ref('my_first_dbt_model') }}
6+
where id = 1
Lines changed: 21 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,21 @@
1+
2+
version: 2
3+
4+
models:
5+
- name: my_first_dbt_model
6+
description: "A starter dbt model"
7+
columns:
8+
- name: id
9+
description: "The primary key for this table"
10+
data_tests:
11+
- unique
12+
- not_null
13+
14+
- name: my_second_dbt_model
15+
description: "A starter dbt model"
16+
columns:
17+
- name: id
18+
description: "The primary key for this table"
19+
data_tests:
20+
- unique
21+
- not_null

crates/lib/test/fixtures/dbt/seeds/.gitkeep

Whitespace-only changes.

crates/lib/test/fixtures/dbt/snapshots/.gitkeep

Whitespace-only changes.

crates/lib/test/fixtures/dbt/tests/.gitkeep

Whitespace-only changes.

0 commit comments

Comments
 (0)