Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

fix(mysql): migrate json initial of added columns on preparing #80

Merged
merged 1 commit into from
Apr 14, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
21 changes: 20 additions & 1 deletion packages/mysql/src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -55,8 +55,14 @@ export class MySQLDriver extends Driver<MySQLDriver.Config> {
charset: 'utf8mb4_general_ci',
multipleStatements: true,
typeCast: (field, next) => {
const { orgName, orgTable } = field.packet
const meta = this.database.tables[orgTable]?.fields[orgName]

if (field.type === 'BIT') {
return Boolean(field.buffer()?.readUint8(0))
} else if (meta?.type?.type === 'json') {
// for backward compatibility
return field.string() || meta.initial
} else {
return next()
}
Expand Down Expand Up @@ -133,6 +139,7 @@ export class MySQLDriver extends Driver<MySQLDriver.Config> {
const unique = [...table.unique]
const create: string[] = []
const update: string[] = []
const alterInit = Object.create(null)

// field definitions
for (const key in fields) {
Expand Down Expand Up @@ -160,6 +167,10 @@ export class MySQLDriver extends Driver<MySQLDriver.Config> {
if (initial && !typedef.startsWith('text') && !typedef.endsWith('blob')) {
def += ' default ' + this.sql.escape(initial, fields[key])
}

if (!column && initial && (typedef.startsWith('text') || typedef.endsWith('blob'))) {
alterInit[key] = this.sql.escape(initial, fields[key])
}
}

if (!column) {
Expand Down Expand Up @@ -215,6 +226,10 @@ export class MySQLDriver extends Driver<MySQLDriver.Config> {
await this.query(`ALTER TABLE ${escapeId(name)} ${operations.join(', ')}`)
}

if (Object.keys(alterInit).length) {
await this.query(`UPDATE ${escapeId(name)} SET ${Object.entries(alterInit).map(([key, val]) => `${escapeId(key)} = ${val}`).join(', ')}`)
}

// migrate deprecated fields (do not await)
const dropKeys: string[] = []
this.migrate(name, {
Expand Down Expand Up @@ -322,7 +337,11 @@ INSERT INTO mtt VALUES(json_extract(j, concat('$[', i, ']'))); SET i=i+1; END WH
async dropAll() {
const data = await this._select('information_schema.tables', ['TABLE_NAME'], 'TABLE_SCHEMA = ?', [this.config.database])
if (!data.length) return
await this.query(data.map(({ TABLE_NAME }) => `DROP TABLE ${escapeId(TABLE_NAME)}`).join('; '))
await this.query([
'SET foreign_key_checks = 0',
...data.map(({ TABLE_NAME }) => `DROP TABLE ${escapeId(TABLE_NAME)}`),
'SET foreign_key_checks = 1',
].join('; '))
}

async stats() {
Expand Down
33 changes: 33 additions & 0 deletions packages/tests/src/migration.ts
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@ interface Qux {
number: number
value: number
flag: boolean
obj: object
}

interface Qux2 {
Expand Down Expand Up @@ -116,6 +117,38 @@ function MigrationTests(database: Database<Tables>) {
{ id: 2, flag: false },
])
})

it('set json initial', async () => {
Reflect.deleteProperty(database.tables, 'qux')

database.extend('qux', {
id: 'unsigned',
text: 'string(64)',
})

await database.upsert('qux', [
{ id: 1, text: 'foo' },
{ id: 2, text: 'bar' },
])

await expect(database.get('qux', {})).to.eventually.deep.equal([
{ id: 1, text: 'foo' },
{ id: 2, text: 'bar' },
])

database.extend('qux', {
obj: {
type: 'json',
initial: {},
nullable: false,
}
})

await expect(database.get('qux', {})).to.eventually.deep.equal([
{ id: 1, text: 'foo', obj: {} },
{ id: 2, text: 'bar', obj: {} },
])
})
}

export default MigrationTests
Loading