-
Notifications
You must be signed in to change notification settings - Fork 584
Expand file tree
/
Copy pathpublishProjectWebViewController.ts
More file actions
1781 lines (1615 loc) · 73.5 KB
/
publishProjectWebViewController.ts
File metadata and controls
1781 lines (1615 loc) · 73.5 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
/*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*--------------------------------------------------------------------------------------------*/
import * as vscode from "vscode";
import * as path from "path";
import * as mssql from "vscode-mssql";
import * as constants from "../constants/constants";
import { FormWebviewController } from "../forms/formWebviewController";
import VscodeWrapper from "../controllers/vscodeWrapper";
import ConnectionManager from "../controllers/connectionManager";
import { IConnectionProfile } from "../models/interfaces";
import { PublishProject as Loc } from "../constants/locConstants";
import {
PublishDialogReducers,
PublishDialogFormItemSpec,
IPublishForm,
PublishFormFields,
PublishFormContainerFields,
PublishDialogState,
PublishTarget,
GenerateSqlPackageCommandRequest,
} from "../sharedInterfaces/publishDialog";
import { IConnectionDialogProfile } from "../sharedInterfaces/connectionDialog";
import { SqlPackageService } from "../services/sqlPackageService";
import { sendActionEvent, sendErrorEvent } from "../telemetry/telemetry";
import { generatePublishFormComponents } from "./formComponentHelpers";
import {
parsePublishProfileXml,
readProjectProperties,
validateSqlCmdVariables,
validateSqlServerPortNumber,
getSqlServerContainerTagsForTargetVersion,
updateDatabaseInConnectionString,
} from "./projectUtils";
import { SqlProjectsService } from "../services/sqlProjectsService";
import { Deferred } from "../protocol";
import { TelemetryViews, TelemetryActions } from "../sharedInterfaces/telemetry";
import { TaskExecutionMode, DeploymentScenario } from "../enums";
import { hasAnyMissingRequiredValues, getErrorMessage, uuid } from "../utils/utils";
import { ConnectionCredentials } from "../models/connectionCredentials";
import { ProjectController } from "../controllers/projectController";
import { generateOperationId } from "../schemaCompare/schemaCompareUtils";
import { UserSurvey } from "../nps/userSurvey";
import * as dockerUtils from "../docker/dockerUtils";
import * as sqlServerContainer from "../deployment/sqlServerContainer";
import { DockerConnectionProfile, DockerStepOrder } from "../sharedInterfaces/localContainers";
import MainController from "../controllers/mainController";
import { getConnectionDisplayName, getServerTypes, ServerType } from "../models/connectionInfo";
import { ApiStatus } from "../sharedInterfaces/webview";
const SQLPROJ_PUBLISH_VIEW_ID = "publishProject";
export class PublishProjectWebViewController extends FormWebviewController<
IPublishForm,
PublishDialogState,
PublishDialogFormItemSpec,
PublishDialogReducers
> {
private _cachedDatabaseList?: { displayName: string; value: string }[];
private _cachedSelectedDatabase?: string;
private _preloadedContainerPort?: Promise<number>;
private _deploymentOptionsPromise?: Promise<void>;
private _connectionUri?: string;
private _serverTypes: string = "";
private _availableConnections?: IConnectionDialogProfile[];
public readonly initialized: Deferred<void> = new Deferred<void>();
private readonly _sqlProjectsService?: SqlProjectsService;
private readonly _dacFxService?: mssql.IDacFxService;
private readonly _sqlPackageService?: SqlPackageService;
private readonly _connectionManager: ConnectionManager;
private readonly _projectController: ProjectController;
private readonly _mainController: MainController;
private readonly _operationId: string;
constructor(
context: vscode.ExtensionContext,
_vscodeWrapper: VscodeWrapper,
connectionManager: ConnectionManager,
projectFilePath: string,
mainController: MainController,
sqlProjectsService?: SqlProjectsService,
dacFxService?: mssql.IDacFxService,
sqlPackageService?: SqlPackageService,
) {
super(
context,
_vscodeWrapper,
"publishProject",
"publishProject",
{
formState: {
publishProfilePath: "",
serverName: "",
databaseName: path.basename(projectFilePath, path.extname(projectFilePath)),
publishTarget: PublishTarget.ExistingServer,
sqlCmdVariables: {},
},
formComponents: {},
projectFilePath,
inProgress: false,
lastPublishResult: undefined,
hasFormErrors: true,
deploymentOptions: undefined,
defaultDeploymentOptions: undefined,
} as PublishDialogState,
{
title: Loc.Title,
viewColumn: vscode.ViewColumn.Active,
iconPath: {
dark: vscode.Uri.joinPath(
context.extensionUri,
"media",
"publishProject_dark.svg",
),
light: vscode.Uri.joinPath(
context.extensionUri,
"media",
"publishProject_light.svg",
),
},
},
);
// Fire port detection immediately so it runs in the background while the dialog initializes.
this._preloadedContainerPort = dockerUtils.findAvailablePort(constants.defaultPortNumber);
this._sqlProjectsService = sqlProjectsService;
this._dacFxService = dacFxService;
this._sqlPackageService = sqlPackageService;
this._connectionManager = connectionManager;
this._projectController = new ProjectController();
this._mainController = mainController;
this._operationId = generateOperationId();
// Send telemetry for dialog opened
sendActionEvent(TelemetryViews.SqlProjects, TelemetryActions.PublishDialogOpened, {
operationId: this._operationId,
});
this.registerRpcHandlers();
this.updateState();
// Listen for new connections being added elsewhere (e.g., Object Explorer)
// Refresh the saved connections list so new connections appear in the dropdown
this.registerDisposable(
this._connectionManager.onSuccessfulConnection(async () => {
// Refresh available connections when new connections are added
this._availableConnections = await this.listSavedConnections();
this.updateServerDropdownOptions();
this.updateState();
}),
);
void this.initializeDialog(projectFilePath)
.then(() => {
this.updateState();
this.initialized.resolve();
})
.catch((err) => {
this.logger.error(
`Error initializing PublishProjectWebViewController: ${getErrorMessage(err)}`,
);
this.initialized.reject(err);
});
}
/**
* Builds the SQL project and returns the DACPAC path
* @param state Current dialog state
* @returns Path to the built DACPAC file, or undefined if build fails
*/
private async buildProject(state: PublishDialogState): Promise<string | undefined> {
try {
const dacpacPath = await this._projectController.buildProject(state.projectProperties);
return dacpacPath;
} catch (error) {
sendErrorEvent(
TelemetryViews.SqlProjects,
TelemetryActions.BuildProject,
error instanceof Error ? error : new Error(getErrorMessage(error)),
false,
undefined,
undefined,
{
operationId: this._operationId,
success: "false",
},
);
return undefined;
}
}
/**
* Publishes the DACPAC to the target database
* @param state Current dialog state
* @param dacpacPath Path to the DACPAC file
* @param databaseName Target database name
* @param upgradeExisting Whether to upgrade an existing database
*/
private async publishToDatabase(
state: PublishDialogState,
dacpacPath: string,
databaseName: string,
upgradeExisting: boolean,
): Promise<void> {
// Ensure deployment options are loaded before executing DacFx operations.
await this._deploymentOptionsPromise;
const connectionUri = this._connectionUri || "";
const sqlCmdVariables = new Map(Object.entries(state.formState.sqlCmdVariables || {}));
try {
const result = await this._dacFxService!.deployDacpac(
dacpacPath,
databaseName,
upgradeExisting,
connectionUri,
TaskExecutionMode.execute,
sqlCmdVariables,
state.deploymentOptions,
);
if (result.success) {
sendActionEvent(TelemetryViews.SqlProjects, TelemetryActions.PublishProject, {
operationId: this._operationId,
success: "true",
serverTypes: this._serverTypes,
});
// Prompt user for NPS feedback after successful publish
void UserSurvey.getInstance().promptUserForNPSFeedback(SQLPROJ_PUBLISH_VIEW_ID);
} else {
sendErrorEvent(
TelemetryViews.SqlProjects,
TelemetryActions.PublishProject,
new Error(getErrorMessage(result.errorMessage)),
false,
undefined,
undefined,
{
operationId: this._operationId,
success: "false",
serverTypes: this._serverTypes,
},
);
}
} catch (error) {
sendErrorEvent(
TelemetryViews.SqlProjects,
TelemetryActions.PublishProject,
error instanceof Error ? error : new Error(getErrorMessage(error)),
false,
undefined,
undefined,
{
operationId: this._operationId,
success: "false",
serverTypes: this._serverTypes,
},
);
}
}
/**
* Generates a deployment script for the DACPAC
* @param state Current dialog state
* @param dacpacPath Path to the DACPAC file
* @param databaseName Target database name
*/
private async generateDeploymentScript(
state: PublishDialogState,
dacpacPath: string,
databaseName: string,
): Promise<void> {
// Ensure deployment options are loaded before executing DacFx operations.
await this._deploymentOptionsPromise;
const connectionUri = this._connectionUri || "";
const sqlCmdVariables = new Map(Object.entries(state.formState.sqlCmdVariables || {}));
try {
const result = await this._dacFxService!.generateDeployScript(
dacpacPath,
databaseName,
connectionUri,
TaskExecutionMode.script,
sqlCmdVariables,
state.deploymentOptions,
);
if (result.success) {
sendActionEvent(TelemetryViews.SqlProjects, TelemetryActions.GenerateScript, {
operationId: this._operationId,
success: "true",
serverTypes: this._serverTypes,
});
} else {
sendErrorEvent(
TelemetryViews.SqlProjects,
TelemetryActions.GenerateScript,
new Error(getErrorMessage(result.errorMessage)),
false,
undefined,
undefined,
{
operationId: this._operationId,
success: "false",
serverTypes: this._serverTypes,
},
);
}
} catch (error) {
sendErrorEvent(
TelemetryViews.SqlProjects,
TelemetryActions.GenerateScript,
error instanceof Error ? error : new Error(getErrorMessage(error)),
false,
undefined,
undefined,
{
operationId: this._operationId,
success: "false",
serverTypes: this._serverTypes,
},
);
}
}
/**
* Determines if the target database already exists
* @param state Current dialog state
* @param databaseName Target database name
* @returns True if database exists, false otherwise
*/
private isDatabaseExisting(state: PublishDialogState, databaseName: string): boolean {
if (state.formState.publishTarget === PublishTarget.ExistingServer && this._connectionUri) {
const databaseComponent = this.state.formComponents[PublishFormFields.DatabaseName];
if (databaseComponent?.options) {
return databaseComponent.options.some((option) => option.value === databaseName);
}
} else if (state.formState.publishTarget === PublishTarget.LocalContainer) {
return false;
}
return true;
}
/**
* Executes publish and generate script operations
* @param state Current dialog state
* @param isPublish If true, publishes to database; if false, generates script
*/
private async executePublishAndGenerateScript(
state: PublishDialogState,
isPublish: boolean,
): Promise<void> {
const databaseName = state.formState.databaseName;
// Step 1: Build the project
const dacpacPath = await this.buildProject(state);
if (!dacpacPath) {
return;
}
// Step 2: Determine if database exists
const upgradeExisting = this.isDatabaseExisting(state, databaseName);
// Step 3: Execute publish or generate script
if (isPublish) {
await this.publishToDatabase(state, dacpacPath, databaseName, upgradeExisting);
} else {
await this.generateDeploymentScript(state, dacpacPath, databaseName);
}
}
/**
* Step 1: Runs Docker prerequisite checks (install, start, engine).
* Must pass before proceeding with container creation.
* @returns Success flag and optional error message if failed
*/
private async runDockerPrerequisiteChecks(): Promise<{
success: boolean;
error?: string;
}> {
const dockerSteps = sqlServerContainer.initializeDockerSteps();
const dummyProfile = {} as DockerConnectionProfile;
// Run prerequisite steps up to and including checkDockerEngine
for (let stepIndex = 0; stepIndex <= DockerStepOrder.checkDockerEngine; stepIndex++) {
const currentStep = dockerSteps[stepIndex];
const args = currentStep.argNames.map(
(argName) => (dummyProfile as unknown as Record<string, unknown>)[argName],
);
const result = await currentStep.stepAction(...args);
if (!result.success) {
return {
success: false,
error: result.error,
};
}
// Show success message matching deployment UI format
void vscode.window.showInformationMessage(`✓ ${currentStep.headerText}`);
}
return { success: true };
}
/**
* Step 2: Prepares container configuration values.
* Form validation already ensures password, port, and EULA are valid.
* This step generates container name and parses port number.
* @param state Current publish dialog state
* @returns Configuration values ready for container creation
*/
private async prepareContainerConfiguration(state: PublishDialogState): Promise<{
containerName: string;
port: number;
}> {
// Auto-generate unique container name
const containerName = await dockerUtils.validateContainerName("");
// Port availability is validated in validateForm before publish runs,
// so we can safely use the parsed value here.
const port = parseInt(state.formState.containerPort, 10);
return { containerName, port };
}
/**
* Step 3: Creates Docker container using validated configuration.
* Runs steps 3-6: pull image, start container, check ready, connect.
* @param validatedContainerName - Validated unique container name
* @param validatedPort - Validated available port
* @param state Current publish dialog state
* @returns Connection URI if successful, error info if failed
*/
private async createDockerContainer(
validatedContainerName: string,
validatedPort: number,
state: PublishDialogState,
): Promise<{
success: boolean;
connectionUri?: string;
error?: string;
fullErrorText?: string;
}> {
// Build Docker profile using validated values
const dockerProfile = {
version: state.formState.containerImageTag || "",
password: state.formState.containerAdminPassword || "",
containerName: validatedContainerName,
port: validatedPort,
hostname: "",
profileName: validatedContainerName,
savePassword: true,
acceptEula: state.formState.acceptContainerLicense || false,
} as unknown as DockerConnectionProfile;
const dockerSteps = sqlServerContainer.initializeDockerSteps();
// Execute container creation steps: from pullImage to checkContainer
// Dynamic iteration ensures we don't miss any steps added in the future
for (
let stepIndex = DockerStepOrder.pullImage;
stepIndex <= DockerStepOrder.checkContainer;
stepIndex++
) {
const currentStep = dockerSteps[stepIndex];
const args = currentStep.argNames.map(
(argName) => (dockerProfile as unknown as Record<string, unknown>)[argName],
);
const result = await currentStep.stepAction(...args);
if (!result.success) {
return {
success: false,
error: result.error,
fullErrorText: result.fullErrorText,
};
}
// Show success message matching deployment UI format
void vscode.window.showInformationMessage(`✓ ${currentStep.headerText}`);
}
// Register connection gives us a real connection URI that can be used for DacFx operations
const connectionProfile = {
server: `${constants.localhost},${validatedPort}`,
profileName: validatedContainerName,
savePassword: true,
emptyPasswordInput: false,
authenticationType: constants.sqlAuthentication,
user: constants.sa,
password: dockerProfile.password,
trustServerCertificate: true,
} as IConnectionProfile;
// SQL Server logs "ready for client connections" slightly before SA auth is fully
// initialized. Retry with exponential backoff (baseDelay × 2^attempt) to give
// the container enough time to become fully responsive after a failure.
let lastConnectionError: string | undefined;
for (let attempt = 0; attempt < constants.containerConnectionMaxAttempts; attempt++) {
try {
// Save the connection profile to VS Code settings (idempotent on retry)
const savedProfile =
await this._mainController.connectionManager.connectionUI.saveProfile(
connectionProfile,
);
// Open in Object Explorer (this also establishes the connection)
await this._mainController.createObjectExplorerSession(savedProfile);
// Get the connection URI from the saved profile
const connectionUri =
this._mainController.connectionManager.getUriForConnection(savedProfile);
if (connectionUri) {
// Send telemetry for successful container creation and connection
sendActionEvent(
TelemetryViews.SqlProjects,
TelemetryActions.ConnectToContainer,
{
operationId: this._operationId,
publishTarget: PublishTarget.LocalContainer,
success: "true",
},
);
return {
success: true,
connectionUri: connectionUri,
};
}
// Session was created but no URI yet – treat as a soft failure and retry
lastConnectionError = Loc.FailedToConnectToServer;
} catch (error) {
lastConnectionError = getErrorMessage(error);
}
// Wait before the next attempt using exponential backoff: baseDelay × 2^attempt
// (attempt 0 → 3s, attempt 1 → 6s). No wait after the last attempt.
if (attempt + 1 < constants.containerConnectionMaxAttempts) {
await new Promise((resolve) =>
setTimeout(
resolve,
constants.containerConnectionRetryDelayMs * Math.pow(2, attempt),
),
);
}
}
// All attempts exhausted
sendErrorEvent(
TelemetryViews.SqlProjects,
TelemetryActions.ConnectToContainer,
new Error(lastConnectionError),
false,
undefined,
undefined,
{
operationId: this._operationId,
success: "false",
},
);
return {
success: false,
error: lastConnectionError,
};
}
/**
* Lists all saved connections from the connection store.
* Returns all connection profiles, not just active connections.
*/
private async listSavedConnections(): Promise<IConnectionDialogProfile[]> {
try {
const savedConnections =
await this._connectionManager.connectionStore.readAllConnections();
return savedConnections as IConnectionDialogProfile[];
} catch (error) {
this.logger.error(`Failed to list saved connections: ${getErrorMessage(error)}`);
sendErrorEvent(
TelemetryViews.SqlProjects,
TelemetryActions.LoadConnections,
error instanceof Error ? error : new Error(getErrorMessage(error)),
false,
undefined,
undefined,
{
operationId: this._operationId,
success: "false",
},
);
return [];
}
}
/**
* Fetches the list of databases for the given connection URI.
* Returns an empty array if the fetch fails.
*/
private async fetchDatabaseList(ownerUri: string): Promise<string[]> {
try {
return await this._connectionManager.listDatabases(ownerUri);
} catch (error) {
this.logger.warn(`Failed to list databases: ${getErrorMessage(error)}`);
return [];
}
}
/**
* Connects to a server using the specified connection ID.
* If already connected, returns the existing ownerUri.
* Otherwise, establishes a new connection.
*/
private async connectToServerByConnectionId(connectionId: string): Promise<{
ownerUri: string;
isConnected: boolean;
serverName?: string;
databases?: string[];
errorMessage?: string;
}> {
try {
// Find the profile from cached available connections (already loaded from store)
const profile = this._availableConnections?.find((conn) => conn.id === connectionId);
if (!profile) {
// Profile should always be found since dropdown is populated from saved connections.
// If not found, the connection may have been deleted - treat as error.
return {
ownerUri: "",
isConnected: false,
errorMessage: Loc.ConnectionProfileNotFound,
};
}
// Profile found - compute server types once here for telemetry
this._serverTypes = getServerTypes(profile).join(",");
// Check if already connected
let ownerUri = this._connectionManager.getUriForConnection(profile);
if (ownerUri && this._connectionManager.isConnected(ownerUri)) {
// Connection is active - fetch databases
const databases = await this.fetchDatabaseList(ownerUri);
return {
ownerUri,
isConnected: true,
serverName: profile.server,
databases,
};
}
// Not connected - establish new connection
const result = await this._connectionManager.connect("", profile);
if (result) {
ownerUri = this._connectionManager.getUriForConnection(profile);
// Fetch databases from the new connection
const databases = await this.fetchDatabaseList(ownerUri);
return {
ownerUri,
isConnected: true,
serverName: profile.server,
databases,
};
} else {
// Connection failed
ownerUri = this._connectionManager.getUriForConnection(profile);
const connectionInfo = ownerUri
? this._connectionManager.activeConnections[ownerUri]
: undefined;
const errorMessage = connectionInfo?.errorMessage || Loc.FailedToConnectToServer;
sendErrorEvent(
TelemetryViews.SqlProjects,
TelemetryActions.Connect,
new Error(errorMessage),
false,
undefined,
undefined,
{
operationId: this._operationId,
success: "false",
},
);
return {
ownerUri: "",
isConnected: false,
errorMessage,
};
}
} catch (error) {
this.logger.error(`Failed to connect to server: ${error}`);
sendErrorEvent(
TelemetryViews.SqlProjects,
TelemetryActions.Connect,
error instanceof Error ? error : new Error(getErrorMessage(error)),
false,
undefined,
undefined,
{
operationId: this._operationId,
success: "false",
},
);
return {
ownerUri: "",
isConnected: false,
errorMessage: getErrorMessage(error),
};
}
}
/**
* Fetches the connection string on-demand from the active connection.
* @returns The connection string (without password)
* @throws Error if connection string cannot be retrieved
*/
private async getConnectionStringOnDemand(): Promise<string> {
if (!this._connectionUri) {
const error = new Error(Loc.NoActiveConnection);
this.logger.error(`Failed to get connection string: ${error.message}`);
sendErrorEvent(
TelemetryViews.SqlProjects,
TelemetryActions.LoadFromConnectionString,
error,
false,
undefined,
undefined,
{
operationId: this._operationId,
success: "false",
},
);
throw error;
}
try {
return await this._connectionManager.getConnectionString(
this._connectionUri,
false, // includePassword
true, // includeApplicationName
);
} catch (error) {
this.logger.error(`Failed to get connection string: ${getErrorMessage(error)}`);
sendErrorEvent(
TelemetryViews.SqlProjects,
TelemetryActions.LoadFromConnectionString,
error instanceof Error ? error : new Error(getErrorMessage(error)),
false,
undefined,
undefined,
{
operationId: this._operationId,
success: "false",
},
);
throw error;
}
}
/**
* Updates the server dropdown options from availableConnections.
* Uses getConnectionDisplayName() to compute display names for each profile.
*/
private updateServerDropdownOptions(): void {
const serverComponent = this.state.formComponents[PublishFormFields.ServerName];
if (serverComponent && this._availableConnections) {
serverComponent.options = this._availableConnections.map((profile) => ({
displayName: getConnectionDisplayName(profile),
value: profile.id || "",
}));
}
}
private async initializeDialog(projectFilePath: string) {
if (projectFilePath) {
this.state.projectFilePath = projectFilePath;
}
// Fetch deployment options in the background while other init work proceeds.
// Cache the promise so consumers can await it if they run before the fetch completes.
if (this._dacFxService) {
// getDeploymentOptions returns a Thenable; wrap in Promise.resolve() for .catch support.
this._deploymentOptionsPromise = Promise.resolve(
this._dacFxService.getDeploymentOptions(DeploymentScenario.Deployment),
)
.then((result) => {
if (this.isDisposed) {
return;
}
const options = result?.defaultDeploymentOptions;
if (options) {
// Clear default excludeObjectTypes — no default exclude options for the publish dialog.
if (options.excludeObjectTypes !== undefined) {
options.excludeObjectTypes.value = [];
}
this.state.deploymentOptions = options;
// Clone after clearing so reset uses the correct defaults.
this.state.defaultDeploymentOptions = structuredClone(options);
this.updateState();
}
})
.catch((err) => {
this.logger.error("Failed to fetch deployment options:", err);
});
// Intentionally not awaited here — callers await _deploymentOptionsPromise before using the options.
void this._deploymentOptionsPromise;
}
// Get the project properties from the proj file
let projectTargetVersion: string | undefined;
try {
if (this._sqlProjectsService && projectFilePath) {
const props = await readProjectProperties(
this._sqlProjectsService,
projectFilePath,
);
if (props) {
this.state.projectProperties = props;
projectTargetVersion = props.targetVersion;
}
// Load SQLCMD variables from the project
const sqlCmdVarsResult =
await this._sqlProjectsService.getSqlCmdVariables(projectFilePath);
if (sqlCmdVarsResult?.success && sqlCmdVarsResult.sqlCmdVariables) {
// Convert array to object for form state
const sqlCmdVarsObject: { [key: string]: string } = {};
for (const sqlCmdVar of sqlCmdVarsResult.sqlCmdVariables) {
// Use the defaultValue which contains the actual values, not variable references like $(SqlCmdVar__1)
const varValue = sqlCmdVar.defaultValue || "";
sqlCmdVarsObject[sqlCmdVar.varName] = varValue;
}
this.state.formState.sqlCmdVariables = sqlCmdVarsObject;
// Store immutable default values (project defaults initially)
this.state.defaultSqlCmdVariables = { ...sqlCmdVarsObject };
}
}
} catch (error) {
// Log error and send telemetry, but keep dialog resilient
this.logger.error("Failed to read project properties:", error);
sendErrorEvent(
TelemetryViews.SqlProjects,
TelemetryActions.PublishProjectProperties,
error instanceof Error ? error : new Error(String(error)),
false,
undefined,
undefined,
{
operationId: this._operationId,
success: "false",
},
);
}
// Load publish form components
this.state.formComponents = generatePublishFormComponents(
projectTargetVersion,
this.state.formState.databaseName,
);
// Fetch Docker tags for the container image dropdown
const tagComponent = this.state.formComponents[PublishFormFields.ContainerImageTag];
if (tagComponent) {
try {
const tagOptions =
await getSqlServerContainerTagsForTargetVersion(projectTargetVersion);
tagComponent.options = tagOptions;
if (!this.state.formState.containerImageTag && tagOptions.length > 0) {
this.state.formState.containerImageTag = tagOptions[0].value;
}
} catch (error) {
this.state.formMessage = {
message: Loc.FailedToFetchContainerTags(getErrorMessage(error)),
intent: "error",
};
}
}
// Update item visibility before updating state to ensure SQLCMD table is visible if needed
await this.updateItemVisibility();
// Load all saved connections for the server dropdown
this._availableConnections = await this.listSavedConnections();
this.updateServerDropdownOptions();
this.updateState();
// Run initial validation to set hasFormErrors state for button enablement
await this.validateForm(this.state.formState, undefined, true);
}
private registerRpcHandlers(): void {
this.registerReducer("publishNow", async (state: PublishDialogState) => {
// Check if publishing to local container
if (state.formState.publishTarget === PublishTarget.LocalContainer) {
// Keep panel open to show progress through all steps
state.inProgress = true;
this.updateState(state);
try {
// STEP 1: Run Docker prerequisite checks (Docker install, start, engine)
const prereqResult = await vscode.window.withProgress(
{
location: vscode.ProgressLocation.Notification,
title: Loc.CheckingDockerPrerequisites,
cancellable: false,
},
async () => {
return await this.runDockerPrerequisiteChecks();
},
);
if (!prereqResult.success) {
sendErrorEvent(
TelemetryViews.SqlProjects,
TelemetryActions.PublishDialogLocalContainersPrerequisites,
new Error(prereqResult.error),
false,
undefined,
undefined,
{
operationId: this._operationId,
success: "false",
},
);
state.formMessage = {
message: prereqResult.error,
intent: "error",
};
state.inProgress = false;
this.updateState(state);
return state;
}
// STEP 2: Prepare container configuration (generate name, parse port)
// Form validation already ensured password, port, and EULA are valid
const config = await this.prepareContainerConfiguration(state);
// STEP 3: Create Docker container (pull, start, check, connect)
const containerResult = await vscode.window.withProgress(
{
location: vscode.ProgressLocation.Notification,
title: Loc.CreatingSqlServerContainer,
cancellable: false,
},
async () => {
return await this.createDockerContainer(
config.containerName,
config.port,
state,
);
},
);
if (!containerResult.success) {
sendErrorEvent(
TelemetryViews.SqlProjects,
TelemetryActions.PublishDialogCreateLocalContainers,
new Error(containerResult.fullErrorText || containerResult.error),
false,
undefined,
undefined,
{
operationId: this._operationId,
success: "false",
},
);
state.formMessage = {
message: containerResult.fullErrorText || containerResult.error,
intent: "error",
};
state.inProgress = false;
this.updateState(state);
return state;
}
// STEP 4: Store connection URI for DacFx publish
this._connectionUri = containerResult.connectionUri;
this._serverTypes = [ServerType.Local, ServerType.Sql].join(",");
// STEP 5: Build DACPAC from project
const dacpacPath = await this.buildProject(state);
if (!dacpacPath) {
// Note: buildProject already sends its own telemetry on failure
state.inProgress = false;
this.updateState(state);
return state;
}
// STEP 6: Publish DACPAC to container using existing DacFx API
await this.publishToDatabase(