/
Mysql.ts
167 lines (143 loc) · 4.63 KB
/
Mysql.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
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
/*
* @adonisjs/lucid
*
* (c) Harminder Virk <virk@adonisjs.com>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
/// <reference path="../../adonis-typings/index.ts" />
import { RawBuilder } from '../Database/StaticBuilder/Raw'
import { DialectContract, MysqlConfig, QueryClientContract } from '@ioc:Adonis/Lucid/Database'
export class MysqlDialect implements DialectContract {
public readonly name = 'mysql'
public readonly supportsAdvisoryLocks = true
public readonly supportsViews = true
public readonly supportsTypes = false
public readonly supportsReturningStatement = false
/**
* Reference to the database version. Knex.js fetches the version after
* the first database query, so it will be set to undefined initially
*/
public readonly version = this.client.getReadClient()['context']['client'].version
/**
* The default format for datetime column. The date formats is
* valid for luxon date parsing library
*/
public readonly dateTimeFormat = 'yyyy-MM-dd HH:mm:ss'
constructor(private client: QueryClientContract, private config: MysqlConfig) {}
/**
* Truncate mysql table with option to cascade
*/
public async truncate(table: string, cascade: boolean = false) {
if (!cascade) {
return this.client.knexQuery().table(table).truncate()
}
/**
* Cascade and truncate
*/
const trx = await this.client.transaction()
try {
await trx.rawQuery('SET FOREIGN_KEY_CHECKS=0;')
await trx.knexQuery().table(table).truncate()
await trx.rawQuery('SET FOREIGN_KEY_CHECKS=1;')
await trx.commit()
} catch (error) {
await trx.rollback()
throw error
}
}
/**
* Returns an array of table names
*/
public async getAllTables(): Promise<string[]> {
const tables = await this.client
.query()
.from('information_schema.tables')
.select('table_name as table_name')
.where('TABLE_TYPE', 'BASE TABLE')
.where('table_schema', new RawBuilder('database()'))
.orderBy('table_name', 'asc')
return tables.map(({ table_name }) => table_name)
}
/**
* Returns an array of all views names
*/
public async getAllViews(): Promise<string[]> {
const tables = await this.client
.query()
.from('information_schema.tables')
.select('table_name as table_name')
.where('TABLE_TYPE', 'VIEW')
.where('table_schema', new RawBuilder('database()'))
.orderBy('table_name', 'asc')
return tables.map(({ table_name }) => table_name)
}
/**
* Returns an array of all types names
*/
public async getAllTypes(): Promise<string[]> {
throw new Error("MySQL doesn't support types")
}
/**
* Drop all tables inside the database
*/
public async dropAllTables() {
let tables = await this.getAllTables()
/**
* Filter out tables that are not allowed to be dropped
*/
tables = tables.filter((table) => !(this.config.wipe?.ignoreTables || []).includes(table))
/**
* Add backquote around table names to avoid syntax errors
* in case of a table name with a reserved keyword
*/
tables = tables.map((table) => '`' + table + '`')
if (!tables.length) {
return
}
/**
* Cascade and truncate
*/
const trx = await this.client.transaction()
try {
await trx.rawQuery('SET FOREIGN_KEY_CHECKS=0;')
await trx.rawQuery(`DROP TABLE ${tables.join(',')};`)
await trx.rawQuery('SET FOREIGN_KEY_CHECKS=1;')
await trx.commit()
} catch (error) {
await trx.rollback()
throw error
}
}
/**
* Drop all views inside the database
*/
public async dropAllViews(): Promise<void> {
const views = await this.getAllViews()
return this.client.rawQuery(`DROP VIEW ${views.join(',')};`)
}
/**
* Drop all custom types inside the database
*/
public async dropAllTypes(): Promise<void> {
throw new Error("MySQL doesn't support types")
}
/**
* Attempts to add advisory lock to the database and
* returns it's status.
*/
public async getAdvisoryLock(key: string, timeout: number = 0): Promise<boolean> {
const response = await this.client.rawQuery(
`SELECT GET_LOCK('${key}', ${timeout}) as lock_status;`
)
return response[0] && response[0][0] && response[0][0].lock_status === 1
}
/**
* Releases the advisory lock
*/
public async releaseAdvisoryLock(key: string): Promise<boolean> {
const response = await this.client.rawQuery(`SELECT RELEASE_LOCK('${key}') as lock_status;`)
return response[0] && response[0][0] && response[0][0].lock_status === 1
}
}