-
-
Notifications
You must be signed in to change notification settings - Fork 2
/
database.native.ts
114 lines (105 loc) · 3.39 KB
/
database.native.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
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
// native file, if you want edit it, remove the "native" suffix from the filename
import * as app from "#app"
export default new app.Command({
name: "database",
description: "Run SQL query on database",
aliases: ["query", "db", "sql", "?"],
botOwnerOnly: true,
channelType: "all",
rest: {
name: "query",
description: "SQL query",
required: true,
all: true,
},
async run(message) {
const query = message.args.query
.replace(/\$guild/g, `'${message.guild?.id}'`)
.replace(/\$channel/g, `'${message.channel.id}'`)
.replace(/\$me/g, `'${message.author.id}'`)
.replace(/<(?:[#@][&!]?|a?:\w+:)(\d+)>/g, "'$1'")
.replace(/from ([a-z]+)/gi, 'from "$1"')
let result = await app.database.raw(query)
result = result.rows ?? result
const systemMessage = Array.isArray(result)
? await app.getSystemMessage("success", {
header: `SQL query done (${result.length} items)`,
body: await app.limitDataToShow(
result,
app.MaxLength.EmbedDescription,
(data) =>
app.code.stringify({
lang: "json",
format: { printWidth: 50 },
content: "const result = " + JSON.stringify(data),
}),
),
footer: `Result of : ${query}`,
})
: await app.getSystemMessage("success", {
body: `SQL query done`,
footer: `Query : ${query}`,
})
return message.channel.send(systemMessage)
},
subs: [
new app.Command({
name: "plan",
description: "Show database plan",
botOwnerOnly: true,
channelType: "all",
aliases: ["tables", "schema", "list", "view"],
async run(message) {
const fields = await Promise.all(
app.database.cachedTables.map(
async (table): Promise<app.EmbedField> => {
const columns: {
defaultValue: unknown
type: string
name: string
}[] = await table.getColumns().then((cols) => {
return Object.entries(cols).map(
([name, { defaultValue, type }]) => {
return { name, type, defaultValue }
},
)
})
const rowCount = await table.count()
return {
name: `${table.options.name} x${rowCount}`,
value: columns
.map(
({ name, type, defaultValue }) =>
`[\`${type.slice(0, 5)}\`] \`${name}${
defaultValue ? `?` : ""
}\``,
)
.join("\n"),
inline: true,
}
},
),
)
return message.channel.send({
embeds: [
new app.EmbedBuilder()
.setTitle("Database plan")
.setDescription(
`**${fields.length}** tables, **${fields.reduce(
(acc, current) => {
return acc + current.value.split("\n").length
},
0,
)}** columns`,
)
.setFields(
fields.sort((a, b) => {
return a.value.split("\n").length - b.value.split("\n").length
}),
),
],
})
},
}),
],
})