-
Notifications
You must be signed in to change notification settings - Fork 122
Expand file tree
/
Copy pathdbtProject.ts
More file actions
1868 lines (1702 loc) · 56.4 KB
/
dbtProject.ts
File metadata and controls
1868 lines (1702 loc) · 56.4 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
import { existsSync, writeFileSync } from "fs";
import {
Catalog,
CATALOG_FILE,
ColumnMetaData,
DataPilotHealtCheckParams,
DBColumn,
DBTCommand,
DBTCommandExecution,
DBTCommandExecutionInfrastructure,
DBTCommandFactory,
DBTDiagnosticData,
DBTNode,
DBTProjectIntegration,
DBTProjectIntegrationAdapter,
DBTProjectIntegrationAdapterEvents,
DBTTerminal,
DBT_PROJECT_FILE,
DeferConfig,
extractOutputColumns,
HealthcheckArgs,
isResourceHasDbColumns,
isResourceNode,
MANIFEST_FILE,
NoCredentialsError,
NodeMetaData,
ParsedManifest,
ProjectHealthcheck,
QueryExecution,
QueryExecutionResult,
RESOURCE_TYPE_MODEL,
RESOURCE_TYPE_SOURCE,
RunModelParams,
RunResultsEventData,
SourceNode,
Table,
validateSQL,
} from "@altimateai/dbt-integration";
import { inject } from "inversify";
import * as path from "path";
import { PythonException } from "python-bridge";
import {
commands,
Diagnostic,
DiagnosticCollection,
DiagnosticSeverity,
Disposable,
Event,
EventEmitter,
languages,
ProgressLocation,
Range,
RelativePattern,
Uri,
ViewColumn,
window,
workspace,
} from "vscode";
import { AltimateRequest, ModelNode } from "../altimate";
import { AltimateAuthService } from "../services/altimateAuthService";
import { RunHistoryService } from "../services/runHistoryService";
import { SharedStateService } from "../services/sharedStateService";
import { TelemetryService } from "../telemetry";
import { TelemetryEvents } from "../telemetry/events";
import {
extendErrorWithSupportLinks,
getColumnNameByCase,
getProjectRelativePath,
resolveSettingsVariables,
} from "../utils";
import { ValidationProvider } from "../validation_provider";
import { DBTProjectLog } from "./dbtProjectLog";
import {
ManifestCacheChangedEvent,
ManifestCacheProjectAddedEvent,
RebuildManifestStatusChange,
} from "./event/manifestCacheChangedEvent";
import { ProjectConfigChangedEvent } from "./event/projectConfigChangedEvent";
import { RunResultsEvent } from "./event/runResultsEvent";
import { PythonEnvironment } from "./pythonEnvironment";
interface FileNameTemplateMap {
[key: string]: string;
}
interface JsonObj {
[key: string]: string | number | undefined;
}
export class DBTProject implements Disposable {
private _manifestCacheEvent?: ManifestCacheProjectAddedEvent;
readonly projectRoot: Uri;
private dbtProjectIntegration: DBTProjectIntegrationAdapter;
private _onProjectConfigChanged =
new EventEmitter<ProjectConfigChangedEvent>();
public onProjectConfigChanged = this._onProjectConfigChanged.event;
private _onRunResults = new EventEmitter<RunResultsEvent>();
public onRunResults = this._onRunResults.event;
private _onSourceFileChanged = new EventEmitter<void>();
public onSourceFileChanged = this._onSourceFileChanged.event;
private dbtProjectLog?: DBTProjectLog;
public readonly projectHealth = languages.createDiagnosticCollection("dbt");
public readonly pythonBridgeDiagnostics =
languages.createDiagnosticCollection("dbt-python-bridge");
public readonly rebuildManifestDiagnostics =
languages.createDiagnosticCollection("dbt-rebuild-manifest");
public readonly projectConfigDiagnostics =
languages.createDiagnosticCollection("dbt-project-config");
private disposables: Disposable[] = [
this._onProjectConfigChanged,
this._onSourceFileChanged,
this.projectHealth,
this.pythonBridgeDiagnostics,
this.rebuildManifestDiagnostics,
this.projectConfigDiagnostics,
];
private _onRebuildManifestStatusChange =
new EventEmitter<RebuildManifestStatusChange>();
readonly onRebuildManifestStatusChange =
this._onRebuildManifestStatusChange.event;
private dbSchemaCache: Record<string, ModelNode> = {};
private queues: Map<string, DBTCommandExecution[]> = new Map<
string,
DBTCommandExecution[]
>();
private queueStates: Map<string, boolean> = new Map<string, boolean>();
constructor(
@inject(PythonEnvironment)
private PythonEnvironment: PythonEnvironment,
@inject("Factory<DBTProjectLog>")
private dbtProjectLogFactory: (
onProjectConfigChanged: Event<ProjectConfigChangedEvent>,
) => DBTProjectLog,
private dbtCommandFactory: DBTCommandFactory,
private terminal: DBTTerminal,
private eventEmitterService: SharedStateService,
private telemetry: TelemetryService,
private executionInfrastructure: DBTCommandExecutionInfrastructure,
private dbtIntegrationAdapterFactory: (
projectRoot: string,
deferConfig: DeferConfig | undefined,
) => DBTProjectIntegrationAdapter,
private altimate: AltimateRequest,
private validationProvider: ValidationProvider,
private altimateAuthService: AltimateAuthService,
private runHistoryService: RunHistoryService,
path: Uri,
_projectConfig: any,
private _onManifestChanged: EventEmitter<ManifestCacheChangedEvent>,
) {
this.projectRoot = path;
try {
this.validationProvider.validateCredentialsSilently();
} catch (error) {
this.terminal.error(
"validateCredentialsSilently",
"Credential validation failed",
error,
false,
);
}
this.dbtProjectLog = this.dbtProjectLogFactory(this.onProjectConfigChanged);
// Check if dbt loom is installed for telemetry (only for core integration)
const dbtIntegrationMode = workspace
.getConfiguration("dbt")
.get<string>("dbtIntegration", "core");
if (dbtIntegrationMode === "core") {
this.isDbtLoomInstalled().then((isInstalled) => {
this.telemetry.setTelemetryCustomAttribute(
"dbtLoomInstalled",
`${isInstalled}`,
);
});
}
// Create the integration adapter which will handle the integration selection internally
this.dbtProjectIntegration = this.dbtIntegrationAdapterFactory(
this.projectRoot.fsPath,
this.retrieveDeferConfigFromSettings(),
);
// Set up Node.js watcher events to emit VSCode events directly
this.dbtProjectIntegration.on(
DBTProjectIntegrationAdapterEvents.SOURCE_FILE_CHANGED,
() => {
this.terminal.debug(
"DBTProject",
"Received sourceFileChanged event from Node.js file watchers",
);
this._onSourceFileChanged.fire();
},
);
this.dbtProjectIntegration.on(
DBTProjectIntegrationAdapterEvents.PROJECT_CONFIG_CHANGED,
() => {
this.terminal.debug(
"DBTProject",
"Received projectConfigChanged event from Node.js project config watcher",
);
const event = new ProjectConfigChangedEvent(this);
this._onProjectConfigChanged.fire(event);
},
);
this.dbtProjectIntegration.on(
DBTProjectIntegrationAdapterEvents.REBUILD_MANIFEST_STATUS_CHANGE,
(status: { inProgress: boolean }) => {
this.terminal.debug(
"DBTProject",
`Received rebuildManifestStatusChange event: inProgress=${status.inProgress}`,
);
const event: RebuildManifestStatusChange = {
project: this,
inProgress: status.inProgress,
};
this._onRebuildManifestStatusChange.fire(event);
},
);
// Handle manifestCreated events from dbtIntegrationAdapter
this.dbtProjectIntegration.on(
DBTProjectIntegrationAdapterEvents.MANIFEST_PARSED,
(parsedManifest: ParsedManifest) => {
this.terminal.debug(
"DBTProject",
"Received manifestParsed event from dbtIntegrationAdapter",
);
const manifestCacheEvent: ManifestCacheProjectAddedEvent = {
project: this,
nodeMetaMap: parsedManifest.nodeMetaMap,
macroMetaMap: parsedManifest.macroMetaMap,
metricMetaMap: parsedManifest.metricMetaMap,
sourceMetaMap: parsedManifest.sourceMetaMap,
graphMetaMap: parsedManifest.graphMetaMap,
testMetaMap: parsedManifest.testMetaMap,
docMetaMap: parsedManifest.docMetaMap,
exposureMetaMap: parsedManifest.exposureMetaMap,
functionMetaMap: parsedManifest.functionMetaMap,
modelDepthMap: parsedManifest.modelDepthMap,
};
this._manifestCacheEvent = manifestCacheEvent;
this._onManifestChanged.fire({ added: [manifestCacheEvent] });
},
);
// Handle runResultsCreated events from dbtIntegrationAdapter
this.dbtProjectIntegration.on(
DBTProjectIntegrationAdapterEvents.RUN_RESULTS_PARSED,
(eventData: RunResultsEventData) => {
this.terminal.debug(
"DBTProject",
"Received runResultsParsed event from dbtIntegrationAdapter",
);
this.runHistoryService.addEntry(eventData);
const uniqueIds = eventData.results.map((r) => r.uniqueId);
const runResultsEvent = new RunResultsEvent(this, uniqueIds);
this._onRunResults.fire(runResultsEvent);
},
);
// Handle diagnosticsChanged events from dbtIntegrationAdapter
this.dbtProjectIntegration.on(
DBTProjectIntegrationAdapterEvents.DIAGNOSTICS_CHANGED,
() => {
this.terminal.debug(
"DBTProject",
"Received diagnosticsChanged event from dbtIntegrationAdapter",
);
this.updateDiagnosticsInProblemsPanel();
},
);
this.disposables.push(
this.dbtProjectIntegration,
this._onManifestChanged.event((event) => {
const addedEvent = event.added?.find(
(e) => e.project.projectRoot === this.projectRoot,
);
if (addedEvent) {
this._manifestCacheEvent = addedEvent;
}
}),
this.onRunResults((event) => {
this.invalidateCacheUsingUniqueIds(event.uniqueIds || []);
}),
);
// Initialize Python environment and set up change listener
this.initializePythonEnvironmentListener();
this.terminal.debug(
"DbtProject",
`Created ${dbtIntegrationMode} dbt project ${this.getProjectName()} at ${
this.projectRoot
}`,
);
}
private initializePythonEnvironmentListener(): void {
this.PythonEnvironment.initialize()
.then(() => {
this.disposables.push(
this.PythonEnvironment.onPythonEnvironmentChanged(() =>
this.onPythonEnvironmentChanged(),
),
);
})
.catch((err) => {
this.terminal.error(
"dbtProject:initializePythonEnvironmentListener",
"Failed to initialize Python environment listener",
err,
);
});
}
private async isDbtLoomInstalled(): Promise<boolean> {
const dbtLoomThread = this.executionInfrastructure.createPythonBridge(
this.projectRoot.fsPath,
);
try {
await dbtLoomThread.ex`from dbt_loom import *`;
return true;
} catch (error) {
return false;
} finally {
await this.executionInfrastructure.closePythonBridge(dbtLoomThread);
}
}
private invalidateCacheUsingUniqueIds(uniqueIds: string[]) {
for (const uniqueId of uniqueIds) {
if (uniqueId in this.dbSchemaCache) {
delete this.dbSchemaCache[uniqueId];
}
}
}
getProjectName() {
return this.dbtProjectIntegration.getProjectName();
}
getProjectRoot() {
return this.projectRoot.fsPath;
}
getSelectedTarget() {
return this.dbtProjectIntegration.getSelectedTarget();
}
getTargetNames() {
return this.dbtProjectIntegration.getTargetNames();
}
async setSelectedTarget(targetName: string) {
await window.withProgress(
{
location: ProgressLocation.Notification,
title: "Changing target...",
cancellable: false,
},
() => this.dbtProjectIntegration.setSelectedTarget(targetName),
);
}
getDBTProjectFilePath() {
return path.join(this.projectRoot.fsPath, DBT_PROJECT_FILE);
}
getTargetPath() {
return this.dbtProjectIntegration.getTargetPath();
}
getPackageInstallPath() {
return this.dbtProjectIntegration.getPackageInstallPath();
}
getModelPaths() {
return this.dbtProjectIntegration.getModelPaths();
}
getSeedPaths() {
return this.dbtProjectIntegration.getSeedPaths();
}
getMacroPaths() {
return this.dbtProjectIntegration.getMacroPaths();
}
getManifestPath() {
const targetPath = this.getTargetPath();
if (!targetPath) {
return;
}
return path.join(targetPath, MANIFEST_FILE);
}
getCatalogPath() {
const targetPath = this.getTargetPath();
if (!targetPath) {
return;
}
return path.join(targetPath, CATALOG_FILE);
}
getPythonBridgeStatus() {
return this.dbtProjectIntegration.getPythonBridgeStatus();
}
getAllDiagnostic(): Diagnostic[] {
const projectURI = Uri.file(
path.join(this.projectRoot.fsPath, DBT_PROJECT_FILE),
);
const integrationDiagnostics =
this.getCurrentProjectIntegration().getDiagnostics();
// Convert diagnostic data to VSCode Diagnostics
const convertedDiagnostics = [
...integrationDiagnostics.pythonBridgeDiagnostics.map(
(data) =>
new Diagnostic(
new Range(
data.range?.startLine || 0,
data.range?.startColumn || 0,
data.range?.endLine || 999,
data.range?.endColumn || 999,
),
data.message,
this.mapSeverityToVSCode(data.severity),
),
),
...integrationDiagnostics.rebuildManifestDiagnostics.map(
(data) =>
new Diagnostic(
new Range(
data.range?.startLine || 0,
data.range?.startColumn || 0,
data.range?.endLine || 999,
data.range?.endColumn || 999,
),
data.message,
this.mapSeverityToVSCode(data.severity),
),
),
...(integrationDiagnostics.projectConfigDiagnostics || []).map(
(data) =>
new Diagnostic(
new Range(
data.range?.startLine || 0,
data.range?.startColumn || 0,
data.range?.endLine || 999,
data.range?.endColumn || 999,
),
data.message,
this.mapSeverityToVSCode(data.severity),
),
),
];
return [
...convertedDiagnostics,
...(this.projectHealth.get(projectURI) || []),
];
}
private mapSeverityToVSCode(severity: string): DiagnosticSeverity {
switch (severity) {
case "error":
return DiagnosticSeverity.Error;
case "warning":
return DiagnosticSeverity.Warning;
case "info":
return DiagnosticSeverity.Information;
case "hint":
return DiagnosticSeverity.Hint;
default:
return DiagnosticSeverity.Error;
}
}
private convertDiagnosticDataToVSCode(data: DBTDiagnosticData): Diagnostic {
return new Diagnostic(
new Range(
data.range?.startLine || 0,
data.range?.startColumn || 0,
data.range?.endLine || 999,
data.range?.endColumn || 999,
),
data.message,
this.mapSeverityToVSCode(data.severity),
);
}
updateDiagnosticsInProblemsPanel(): void {
const projectURI = Uri.file(
path.join(this.projectRoot.fsPath, DBT_PROJECT_FILE),
);
const integrationDiagnostics =
this.getCurrentProjectIntegration().getDiagnostics();
// Update each diagnostic collection separately
this.pythonBridgeDiagnostics.set(
projectURI,
integrationDiagnostics.pythonBridgeDiagnostics.map((data) =>
this.convertDiagnosticDataToVSCode(data),
),
);
this.rebuildManifestDiagnostics.set(
projectURI,
integrationDiagnostics.rebuildManifestDiagnostics.map((data) =>
this.convertDiagnosticDataToVSCode(data),
),
);
this.projectConfigDiagnostics.set(
projectURI,
integrationDiagnostics.projectConfigDiagnostics.map((data) =>
this.convertDiagnosticDataToVSCode(data),
),
);
}
async performDatapilotHealthcheck(args: DataPilotHealtCheckParams) {
const manifestPath = this.getManifestPath();
if (!manifestPath) {
throw new Error(
`Unable to find manifest path for project ${this.getProjectName()}`,
);
}
const healthcheckArgs: HealthcheckArgs = { manifestPath };
if (args.configType === "Manual") {
healthcheckArgs.configPath = args.configPath;
} else {
if (args.configType === "Saas") {
healthcheckArgs.config = args.config;
}
if (
args.configType === "All" ||
args.config_schema.some((i) => i.files_required.includes("Catalog"))
) {
const docsGenerateCommand =
this.dbtCommandFactory.createDocsGenerateCommand();
docsGenerateCommand.focus = false;
docsGenerateCommand.logToTerminal = false;
docsGenerateCommand.showProgress = false;
await this.unsafeGenerateDocsImmediately();
healthcheckArgs.catalogPath = this.getCatalogPath();
if (!healthcheckArgs.catalogPath) {
throw new Error(
`Unable to find catalog path for project ${this.getProjectName()}`,
);
}
}
}
this.terminal.debug(
"performDatapilotHealthcheck",
"Performing healthcheck",
healthcheckArgs,
);
// Create isolated Python bridge for healthcheck
const healthCheckThread = this.executionInfrastructure.createPythonBridge(
this.projectRoot.fsPath,
);
let projectHealthcheck: ProjectHealthcheck;
try {
await healthCheckThread.ex`from dbt_utils import *`;
projectHealthcheck = await healthCheckThread.lock<ProjectHealthcheck>(
(python) =>
python!`to_dict(project_healthcheck(${healthcheckArgs.manifestPath}, ${healthcheckArgs.catalogPath}, ${healthcheckArgs.configPath}, ${healthcheckArgs.config}, ${this.altimate.getAIKey()}, ${this.altimate.getInstanceName()}, ${this.altimate.getAltimateUrl()}))`,
);
} finally {
await this.executionInfrastructure.closePythonBridge(healthCheckThread);
}
// temp fix: ideally datapilot should return absolute path
for (const key in projectHealthcheck.model_insights) {
for (const item of projectHealthcheck.model_insights[key]) {
item.path = path.join(this.projectRoot.fsPath, item.original_file_path);
}
}
return projectHealthcheck;
}
async initialize(): Promise<void> {
// Create command queue for this project
this.createQueue("all");
try {
await this.dbtProjectIntegration.initialize();
} catch (error) {
window.showErrorMessage(
extendErrorWithSupportLinks(
"An unexpected error occured while initializing the dbt project at " +
this.projectRoot +
": " +
error +
".",
),
);
}
// ensure all watchers are cleaned up
if (this.dbtProjectLog) {
this.disposables.push(this.dbtProjectLog);
}
this.terminal.debug(
"DbtProject",
`Initialized dbt project ${this.getProjectName()} at ${this.projectRoot}`,
);
}
async rebuildManifest(): Promise<void> {
this.dbtProjectIntegration.rebuildManifest();
}
private async onPythonEnvironmentChanged() {
this.terminal.debug(
"DbtProject",
`Python environment for dbt project ${this.getProjectName()} at ${
this.projectRoot
} has changed`,
);
await this.initialize();
}
async refreshProjectConfig(): Promise<void> {
this.dbtProjectIntegration.refreshProjectConfig();
}
async parseManifest(): Promise<ParsedManifest | undefined> {
return await this.dbtProjectIntegration.parseManifest();
}
getAdapterType() {
return this.dbtProjectIntegration.getAdapterType() || "unknown";
}
findPackageName(uri: Uri): string | undefined {
const documentPath = uri.path;
const pathSegments = documentPath
.replace(new RegExp(this.projectRoot + "/", "g"), "")
.split("/");
const packagesInstallPath = this.getPackageInstallPath();
if (packagesInstallPath && uri.fsPath.startsWith(packagesInstallPath)) {
return pathSegments[1];
}
return undefined;
}
contains(uri: Uri) {
return (
uri.fsPath === this.projectRoot.fsPath ||
uri.fsPath.startsWith(this.projectRoot.fsPath + path.sep)
);
}
async runModel(runModelParams: RunModelParams) {
if (!this.validateIntegrationPrerequisites()) {
return undefined;
}
const runModelCommand =
this.dbtCommandFactory.createRunModelCommand(runModelParams);
try {
const command =
await this.getCurrentProjectIntegration().runModel(runModelCommand);
this.telemetry.sendTelemetryEvent("runModel");
if (command) {
this.addCommandToQueue("all", command);
}
} catch (error) {
this.handleNoCredentialsError(error);
}
}
async unsafeRunModelImmediately(runModelParams: RunModelParams) {
this.telemetry.sendTelemetryEvent("runModel");
return this.dbtProjectIntegration.unsafeRunModelImmediately(runModelParams);
}
async buildModel(runModelParams: RunModelParams) {
if (!this.validateIntegrationPrerequisites()) {
return undefined;
}
const buildModelCommand =
this.dbtCommandFactory.createBuildModelCommand(runModelParams);
try {
const command =
await this.getCurrentProjectIntegration().buildModel(buildModelCommand);
this.telemetry.sendTelemetryEvent("buildModel");
if (command) {
this.addCommandToQueue("all", command);
}
} catch (error) {
this.handleNoCredentialsError(error);
}
}
async unsafeBuildModelImmediately(runModelParams: RunModelParams) {
this.telemetry.sendTelemetryEvent("buildModel");
return this.dbtProjectIntegration.unsafeBuildModelImmediately(
runModelParams,
);
}
async buildProject() {
if (!this.validateIntegrationPrerequisites()) {
return;
}
const buildProjectCommand =
this.dbtCommandFactory.createBuildProjectCommand();
try {
const command =
await this.getCurrentProjectIntegration().buildProject(
buildProjectCommand,
);
this.telemetry.sendTelemetryEvent("buildProject");
if (command) {
this.addCommandToQueue("all", command);
}
} catch (error) {
this.handleNoCredentialsError(error);
}
}
async unsafeBuildProjectImmediately() {
this.telemetry.sendTelemetryEvent("buildProject");
return this.dbtProjectIntegration.unsafeBuildProjectImmediately();
}
async runTest(testName: string) {
if (!this.validateIntegrationPrerequisites()) {
return undefined;
}
const testModelCommand =
this.dbtCommandFactory.createTestModelCommand(testName);
try {
const command =
await this.getCurrentProjectIntegration().runTest(testModelCommand);
this.telemetry.sendTelemetryEvent("runTest");
if (command) {
this.addCommandToQueue("all", command);
}
} catch (error) {
this.handleNoCredentialsError(error);
}
}
async unsafeRunTestImmediately(testName: string) {
this.telemetry.sendTelemetryEvent("runTest");
return this.dbtProjectIntegration.unsafeRunTestImmediately(testName);
}
async runModelTest(modelName: string) {
if (!this.validateIntegrationPrerequisites()) {
return undefined;
}
const testModelCommand =
this.dbtCommandFactory.createTestModelCommand(modelName);
try {
const command =
await this.getCurrentProjectIntegration().runModelTest(
testModelCommand,
);
this.telemetry.sendTelemetryEvent("runModelTest");
if (command) {
this.addCommandToQueue("all", command);
}
} catch (error) {
this.handleNoCredentialsError(error);
}
}
async unsafeRunModelTestImmediately(modelName: string) {
this.telemetry.sendTelemetryEvent("runModelTest");
return this.dbtProjectIntegration.unsafeRunModelTestImmediately(modelName);
}
private handleNoCredentialsError(error: unknown) {
if (error instanceof NoCredentialsError) {
this.altimateAuthService.handlePreviewFeatures();
return;
}
window.showErrorMessage((error as Error).message);
}
private validateIntegrationPrerequisites(): boolean {
// Validate different prerequisites based on integration type
const dbtIntegrationMode = workspace
.getConfiguration("dbt")
.get<string>("dbtIntegration", "core");
switch (dbtIntegrationMode) {
case "cloud":
case "fusion":
// For cloud/fusion integrations, validate authentication
try {
this.validationProvider.validateCredentialsSilently();
return true;
} catch (e) {
window.showErrorMessage((e as Error).message);
return false;
}
case "core":
case "corecommand":
default:
// For core integrations, check if we have a proper dbt installation
// We'll validate through the integration's diagnostic system
const diagnostics =
this.getCurrentProjectIntegration().getDiagnostics();
const hasErrors = [
...diagnostics.pythonBridgeDiagnostics,
...diagnostics.rebuildManifestDiagnostics,
].some((diagnostic) => diagnostic.severity === "error");
if (hasErrors) {
window.showErrorMessage(
"dbt installation or Python environment is not properly configured",
);
return false;
}
return true;
}
}
private requiresAuthentication(): boolean {
const dbtIntegrationMode = workspace
.getConfiguration("dbt")
.get<string>("dbtIntegration", "core");
return dbtIntegrationMode === "cloud";
}
throwIfNotAuthenticated() {
if (this.requiresAuthentication()) {
this.validationProvider.throwIfNotAuthenticated();
}
}
async compileModel(runModelParams: RunModelParams) {
if (!this.validateIntegrationPrerequisites()) {
return;
}
const compileModelCommand =
this.dbtCommandFactory.createCompileModelCommand(runModelParams);
const command =
await this.getCurrentProjectIntegration().compileModel(
compileModelCommand,
);
this.telemetry.sendTelemetryEvent("compileModel");
if (command) {
this.addCommandToQueue("all", command);
}
}
async unsafeCompileModelImmediately(runModelParams: RunModelParams) {
this.telemetry.sendTelemetryEvent("compileModel");
return this.dbtProjectIntegration.unsafeCompileModelImmediately(
runModelParams,
);
}
async unsafeGenerateDocsImmediately(args?: string[]) {
return this.dbtProjectIntegration.unsafeGenerateDocsImmediately(args);
}
async generateDocs() {
if (!this.validateIntegrationPrerequisites()) {
return;
}
const docsGenerateCommand =
this.dbtCommandFactory.createDocsGenerateCommand();
const command =
await this.getCurrentProjectIntegration().generateDocs(
docsGenerateCommand,
);
this.telemetry.sendTelemetryEvent("generateDocs");
if (command) {
this.addCommandToQueue("all", command);
}
}
clean() {
this.throwIfNotAuthenticated();
this.telemetry.sendTelemetryEvent("clean");
return this.dbtProjectIntegration.clean();
}
debug(focus: boolean = true) {
this.telemetry.sendTelemetryEvent("debug");
return this.dbtProjectIntegration.debug(focus);
}
async installDbtPackages(packages: string[]) {
this.telemetry.sendTelemetryEvent("installDbtPackages");
return this.dbtProjectIntegration.installDbtPackages(packages);
}
async installDeps(silent = false) {
this.telemetry.sendTelemetryEvent("installDeps");
return this.dbtProjectIntegration.installDeps(silent);
}
async compileNode(modelName: string): Promise<string | undefined> {
this.telemetry.sendTelemetryEvent("compileNode");
this.throwDiagnosticsErrorIfAvailable();
try {
return await this.dbtProjectIntegration.unsafeCompileNode(modelName);
} catch (exc: any) {
if (exc instanceof PythonException) {
window.showErrorMessage(
extendErrorWithSupportLinks(
`An error occured while trying to compile your node: ${modelName}` +
exc.exception.message +
".",
),
);
this.telemetry.sendTelemetryError("compileNodePythonError", exc);
return (
"Exception: " +
exc.exception.message +
"\n\n" +
"Detailed error information:\n" +
exc
);
}
this.telemetry.sendTelemetryError("compileNodeUnknownError", exc);
// Unknown error
window.showErrorMessage(
extendErrorWithSupportLinks(
"Could not compile model " +
modelName +
": " +
(exc as Error).message +
".",
),
);
return "Detailed error information:\n" + exc;
}
}
async unsafeCompileNode(modelName: string): Promise<string | undefined> {
this.telemetry.sendTelemetryEvent("unsafeCompileNode");
this.throwDiagnosticsErrorIfAvailable();
this.throwIfNotAuthenticated();
return this.dbtProjectIntegration.unsafeCompileNode(modelName);
}
async validateSql(request: {
sql: string;
dialect: string;
models: any[];
}): Promise<Awaited<ReturnType<typeof validateSQL>>> {
const { sql, dialect, models } = request;
this.throwDiagnosticsErrorIfAvailable();
this.throwIfNotAuthenticated();
const sqlValidationThread = this.executionInfrastructure.createPythonBridge(
this.projectRoot.fsPath,
);
try {
return await validateSQL(sql, dialect, models, sqlValidationThread);
} finally {
await this.executionInfrastructure.closePythonBridge(sqlValidationThread);
}
}
async validateSQLDryRun(query: string) {
this.throwIfNotAuthenticated();
try {
return this.dbtProjectIntegration.validateSQLDryRun(query);
} catch (exc) {
const exception = exc as { exception: { message: string } };
window.showErrorMessage(
exception.exception.message || "Could not validate sql with dry run.",
);
this.telemetry.sendTelemetryError("validateSQLDryRunError", {
error: exc,
});