-
-
Notifications
You must be signed in to change notification settings - Fork 160
/
sequelize.ts
197 lines (163 loc) · 5.67 KB
/
sequelize.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
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
/* eslint-disable @typescript-eslint/no-explicit-any */
/* eslint-disable @typescript-eslint/no-unsafe-assignment */
import type {SetRequired} from 'type-fest'
import type {UmzugStorage} from './contract'
type ModelTempInterface = {} & ModelClass & Record<string, any>
/**
* Minimal structure of a sequelize model, defined here to avoid a hard dependency.
* The type expected is `import { Model } from 'sequelize'`
*/
export type ModelClass = {
tableName: string
sequelize?: SequelizeType
getTableName(): string
sync(): Promise<void>
findAll(options?: {}): Promise<any[]>
create(options: {}): Promise<void>
destroy(options: {}): Promise<void>
}
/**
* Minimal structure of a sequelize model, defined here to avoid a hard dependency.
* The type expected is `import { Sequelize } from 'sequelize'`
*/
export type SequelizeType = {
getQueryInterface(): any
isDefined(modelName: string): boolean
model(modelName: string): any
define(modelName: string, columns: {}, options: {}): {}
dialect?: {
name?: string
}
}
const DIALECTS_WITH_CHARSET_AND_COLLATE = new Set(['mysql', 'mariadb'])
type ModelClassType = ModelClass & (new (values?: object, options?: any) => ModelTempInterface)
type _SequelizeStorageConstructorOptions = {
/**
The configured instance of Sequelize. If omitted, it is inferred from the `model` option.
*/
readonly sequelize?: SequelizeType
/**
The model representing the SequelizeMeta table. Must have a column that matches the `columnName` option. If omitted, it is created automatically.
*/
readonly model?: any
/**
The name of the model.
@default 'SequelizeMeta'
*/
readonly modelName?: string
/**
The name of the table. If omitted, defaults to the model name.
*/
readonly tableName?: string
/**
Name of the schema under which the table is to be created.
@default undefined
*/
readonly schema?: any
/**
Name of the table column holding the executed migration names.
@default 'name'
*/
readonly columnName?: string
/**
The type of the column holding the executed migration names.
For `utf8mb4` charsets under InnoDB, you may need to set this to less than 190
@default Sequelize.DataTypes.STRING
*/
readonly columnType?: any
/**
Option to add timestamps to the table
@default false
*/
readonly timestamps?: boolean
}
export type SequelizeStorageConstructorOptions =
| SetRequired<_SequelizeStorageConstructorOptions, 'sequelize'>
| SetRequired<_SequelizeStorageConstructorOptions, 'model'>
export class SequelizeStorage implements UmzugStorage {
public readonly sequelize: SequelizeType
public readonly columnType: string
public readonly columnName: string
public readonly timestamps: boolean
public readonly modelName: string
public readonly tableName?: string
public readonly schema: any
public readonly model: ModelClassType
/**
Constructs Sequelize based storage. Migrations will be stored in a SequelizeMeta table using the given instance of Sequelize.
If a model is given, it will be used directly as the model for the SequelizeMeta table. Otherwise, it will be created automatically according to the given options.
If the table does not exist it will be created automatically upon the logging of the first migration.
*/
constructor(options: SequelizeStorageConstructorOptions) {
if (!options || (!options.model && !options.sequelize)) {
throw new Error('One of "sequelize" or "model" storage option is required')
}
this.sequelize = options.sequelize ?? options.model.sequelize
this.columnType = options.columnType ?? (this.sequelize.constructor as any).DataTypes.STRING
this.columnName = options.columnName ?? 'name'
this.timestamps = options.timestamps ?? false
this.modelName = options.modelName ?? 'SequelizeMeta'
this.tableName = options.tableName
this.schema = options.schema
this.model = options.model ?? this.getModel()
}
getModel(): ModelClassType {
if (this.sequelize.isDefined(this.modelName)) {
// eslint-disable-next-line @typescript-eslint/no-unsafe-return
return this.sequelize.model(this.modelName)
}
const dialectName = this.sequelize.dialect?.name
const hasCharsetAndCollate = dialectName && DIALECTS_WITH_CHARSET_AND_COLLATE.has(dialectName)
return this.sequelize.define(
this.modelName,
{
[this.columnName]: {
type: this.columnType,
allowNull: false,
unique: true,
primaryKey: true,
autoIncrement: false,
},
},
{
tableName: this.tableName,
schema: this.schema,
timestamps: this.timestamps,
charset: hasCharsetAndCollate ? 'utf8' : undefined,
collate: hasCharsetAndCollate ? 'utf8_unicode_ci' : undefined,
},
) as ModelClassType
}
protected async syncModel() {
await this.model.sync()
}
async logMigration({name: migrationName}: {name: string}): Promise<void> {
await this.syncModel()
await this.model.create({
[this.columnName]: migrationName,
})
}
async unlogMigration({name: migrationName}: {name: string}): Promise<void> {
await this.syncModel()
await this.model.destroy({
where: {
[this.columnName]: migrationName,
},
})
}
async executed(): Promise<string[]> {
await this.syncModel()
const migrations: any[] = await this.model.findAll({order: [[this.columnName, 'ASC']]})
return migrations.map(migration => {
const name = migration[this.columnName]
if (typeof name !== 'string') {
throw new TypeError(`Unexpected migration name type: expected string, got ${typeof name}`)
}
return name
})
}
// TODO remove this
_model(): ModelClassType {
return this.model
}
}