-
Notifications
You must be signed in to change notification settings - Fork 69
Expand file tree
/
Copy pathAzureSqlAction.ts
More file actions
241 lines (201 loc) · 9.42 KB
/
Copy pathAzureSqlAction.ts
File metadata and controls
241 lines (201 loc) · 9.42 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
import * as path from 'path';
import * as core from '@actions/core';
import * as exec from '@actions/exec';
import AzureSqlActionHelper from './AzureSqlActionHelper';
import DotnetUtils from './DotnetUtils';
import Constants from './Constants';
import SqlConnectionConfig from './SqlConnectionConfig';
import SqlUtils from './SqlUtils';
export enum ActionType {
DacpacAction,
SqlAction,
BuildAndPublish
}
export interface IActionInputs {
actionType: ActionType;
connectionConfig?: SqlConnectionConfig;
filePath: string;
additionalArguments?: string;
skipFirewallCheck: boolean;
skipJobSummary: boolean;
}
export interface ISqlCmdInputs extends IActionInputs {
connectionConfig: SqlConnectionConfig;
}
export interface IDacpacActionInputs extends IActionInputs {
sqlpackageAction: SqlPackageAction;
sqlpackagePath?: string;
}
export interface IBuildAndPublishInputs extends IDacpacActionInputs {
buildArguments?: string;
}
export enum SqlPackageAction {
Publish,
Extract,
Export,
Import,
DriftReport,
DeployReport,
Script,
BuildOnly
}
export default class AzureSqlAction {
constructor(inputs: IActionInputs) {
this._inputs = inputs;
}
public async execute() {
if (this._inputs.actionType === ActionType.DacpacAction) {
await this._executeDacpacAction(this._inputs as IDacpacActionInputs);
}
else if (this._inputs.actionType === ActionType.SqlAction) {
await this._executeSqlFile(this._inputs as ISqlCmdInputs);
}
else if (this._inputs.actionType === ActionType.BuildAndPublish) {
const buildAndPublishInputs = this._inputs as IBuildAndPublishInputs;
const dacpacPath = await this._executeBuildProject(buildAndPublishInputs);
// Reuse DacpacAction for publish
const publishInputs = {
actionType: ActionType.DacpacAction,
connectionConfig: buildAndPublishInputs.connectionConfig,
filePath: dacpacPath,
additionalArguments: buildAndPublishInputs.additionalArguments,
sqlpackageAction: buildAndPublishInputs.sqlpackageAction,
sqlpackagePath: buildAndPublishInputs.sqlpackagePath
} as IDacpacActionInputs;
await this._executeDacpacAction(publishInputs);
}
else {
throw new Error(`Invalid AzureSqlAction '${this._inputs.actionType}'.`)
}
}
private async _executeDacpacAction(inputs: IDacpacActionInputs) {
if (inputs.sqlpackageAction === SqlPackageAction.BuildOnly) {
core.debug('Skipping sqlpackage action as action is set to BuildOnly');
return;
}
core.debug('Begin executing sqlpackage');
let sqlPackagePath = await AzureSqlActionHelper.getSqlPackagePath(inputs);
let sqlPackageArgs = this._getSqlPackageArguments(inputs);
await exec.exec(`"${sqlPackagePath}" ${sqlPackageArgs}`);
console.log(`Successfully executed action ${SqlPackageAction[inputs.sqlpackageAction]} on target database.`);
}
private async _executeSqlFile(inputs: ISqlCmdInputs) {
core.debug('Begin executing sql script');
let sqlcmdCall = SqlUtils.buildSqlCmdCallWithConnectionInfo(inputs.connectionConfig);
sqlcmdCall += ` -i "${inputs.filePath}"`;
if (!!inputs.additionalArguments) {
sqlcmdCall += ` ${inputs.additionalArguments}`;
}
await exec.exec(sqlcmdCall);
console.log(`Successfully executed SQL file on target database.`);
}
private async _executeBuildProject(inputs: IBuildAndPublishInputs): Promise<string> {
core.debug('Begin building project');
const projectName = path.basename(inputs.filePath, Constants.sqlprojExtension);
const additionalBuildArguments = inputs.buildArguments ?? '';
const parsedArgs = await DotnetUtils.parseCommandArguments(additionalBuildArguments);
let outputDir = '';
// Set output dir if it is set in the build arguments
const outputArgument = await DotnetUtils.findArgument(parsedArgs, "--output", "-o");
if (outputArgument) {
outputDir = outputArgument;
} else {
// Set output dir to ./bin/<configuration> if configuration is set via arguments
// Default to Debug if configuration is not set
const configuration = await DotnetUtils.findArgument(parsedArgs, "--configuration", "-c") ?? "Debug";
outputDir = path.join(path.dirname(inputs.filePath), "bin", configuration);
}
let buildOutput = '';
try {
await exec.exec(`dotnet build "${inputs.filePath}" -p:NetCoreBuild=true ${additionalBuildArguments}`
, [], {
listeners: {
stderr: (data: Buffer) => buildOutput += data.toString(),
stdout: (data: Buffer) => buildOutput += data.toString()
}
}
);
// check for process.env.GITHUB_STEP_SUMMARY to support unit tests and older GitHub enterprise environments
if (!inputs.skipJobSummary && process.env.GITHUB_STEP_SUMMARY) {
this._projectBuildJobSummary(buildOutput);
}
} catch (error) {
if (!inputs.skipJobSummary && process.env.GITHUB_STEP_SUMMARY) {
this._projectBuildJobSummary(buildOutput);
}
throw new Error(`Failed to build project: ${error}`);
}
const dacpacPath = path.join(outputDir, projectName + Constants.dacpacExtension);
console.log(`Successfully built database project to ${dacpacPath}`);
return dacpacPath;
}
/**
* parses the build output and adds a summary to the github job
* displays errors and warnings
* @param buildOutput The output of the dotnet build exec
*/
private _projectBuildJobSummary(buildOutput: string) {
try {
if (buildOutput.includes('Build succeeded.')) {
core.summary.addHeading(':white_check_mark: SQL project build succeeded.');
} else {
core.summary.addHeading(':rotating_light: SQL project build failed.');
}
core.summary.addEOL();
core.summary.addRaw('See the full build log for more details.', true);
const lines = buildOutput.split(/\r?\n/);
let warnings = lines.filter(line => (line.includes('Build warning') || line.includes('StaticCodeAnalysis warning')));
let errorMessages = lines.filter(line => (line.includes('Build error') || line.includes('StaticCodeAnalysis error')));
if (errorMessages.length > 0) {
errorMessages = [...new Set(errorMessages)];
core.summary.addHeading(':x: Errors', 2);
core.summary.addEOL();
errorMessages.forEach(error => {
// remove [project path] from the end of the line
error = error.lastIndexOf('[') > 0 ? error.substring(0, error.lastIndexOf('[')-1) : error;
// move the file info from the beginning of the line to the end
error = '- **'+error.substring(error.indexOf(':')+2) + '** ' + error.substring(0, error.indexOf(':'));
core.summary.addRaw(error, true);
});
}
if (warnings.length > 0) {
warnings = [...new Set(warnings)];
core.summary.addHeading(':warning: Warnings', 2);
core.summary.addEOL();
warnings.forEach(warning => {
// remove [project path] from the end of the line
warning = warning.lastIndexOf('[') > 0 ? warning.substring(0, warning.lastIndexOf('[')-1) : warning;
// move the file info from the beginning of the line to the end
warning = '- **'+warning.substring(warning.indexOf(':')+2) + '** ' + warning.substring(0, warning.indexOf(':'));
core.summary.addRaw(warning, true);
});
}
core.summary.write();
} catch (err) {
core.notice(`Error parsing build output for job summary: ${err}`);
}
}
private _getSqlPackageArguments(inputs: IDacpacActionInputs) {
let args = '';
if (!inputs.connectionConfig) {
throw new Error('Connection string is required for action to call SqlPackgage');
}
switch (inputs.sqlpackageAction) {
case SqlPackageAction.Publish:
case SqlPackageAction.Script:
case SqlPackageAction.DeployReport:
args += `/Action:${SqlPackageAction[inputs.sqlpackageAction]} /TargetConnectionString:"${inputs.connectionConfig.EscapedConnectionString}" /SourceFile:"${inputs.filePath}"`;
break;
case SqlPackageAction.DriftReport:
args += `/Action:${SqlPackageAction[inputs.sqlpackageAction]} /TargetConnectionString:"${inputs.connectionConfig.EscapedConnectionString}"`;
break;
default:
throw new Error(`Not supported SqlPackage action: '${SqlPackageAction[inputs.sqlpackageAction]}'`);
}
if (!!inputs.additionalArguments) {
args += ' ' + inputs.additionalArguments;
}
return args;
}
private _inputs: IActionInputs;
}