-
-
Notifications
You must be signed in to change notification settings - Fork 6.2k
/
QueryCommand.ts
81 lines (74 loc) · 2.78 KB
/
QueryCommand.ts
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
import { QueryRunner } from "../query-runner/QueryRunner"
import { DataSource } from "../data-source/DataSource"
import { PlatformTools } from "../platform/PlatformTools"
import * as yargs from "yargs"
import chalk from "chalk"
import path from "path"
import process from "process"
import { CommandUtils } from "./CommandUtils"
/**
* Executes an SQL query on the given dataSource.
*/
export class QueryCommand implements yargs.CommandModule {
command = "query [query]"
describe =
"Executes given SQL query on a default dataSource. Specify connection name to run query on a specific dataSource."
builder(args: yargs.Argv) {
return args
.positional("query", {
describe: "The SQL Query to run",
type: "string",
})
.option("dataSource", {
alias: "d",
describe:
"Path to the file where your DataSource instance is defined.",
demandOption: true,
})
}
async handler(args: yargs.Arguments) {
let queryRunner: QueryRunner | undefined = undefined
let dataSource: DataSource | undefined = undefined
try {
dataSource = await CommandUtils.loadDataSource(
path.resolve(process.cwd(), args.dataSource as string),
)
dataSource.setOptions({
synchronize: false,
migrationsRun: false,
dropSchema: false,
logging: false,
})
await dataSource.initialize()
// create a query runner and execute query using it
queryRunner = dataSource.createQueryRunner()
const query = args.query as string
console.log(
chalk.green("Running query: ") +
PlatformTools.highlightSql(query),
)
const queryResult = await queryRunner.query(query)
if (typeof queryResult === "undefined") {
console.log(
chalk.green(
"Query has been executed. No result was returned.",
),
)
} else {
console.log(chalk.green("Query has been executed. Result: "))
console.log(
PlatformTools.highlightJson(
JSON.stringify(queryResult, undefined, 2),
),
)
}
await queryRunner.release()
await dataSource.destroy()
} catch (err) {
if (queryRunner) await (queryRunner as QueryRunner).release()
if (dataSource) await dataSource.destroy()
PlatformTools.logCmdErr("Error during query execution:", err)
process.exit(1)
}
}
}