Skip to content

Commit fd8d5f4

Browse files
committed
feat(builder): improve schema diff process, remove reserveOldData option
1 parent 7053e1e commit fd8d5f4

File tree

3 files changed

+31
-26
lines changed

3 files changed

+31
-26
lines changed

packages/sqlite-builder/src/schema/core.ts

Lines changed: 16 additions & 25 deletions
Original file line numberDiff line numberDiff line change
@@ -11,6 +11,7 @@ import {
1111
runCreateTableWithIndexAndTrigger,
1212
runCreateTimeTrigger,
1313
runDropTable,
14+
runRenameTable,
1415
} from './run'
1516
import { type ParsedCreateTableSQL, parseExistDB } from './parseExist'
1617

@@ -42,10 +43,6 @@ export type SyncOptions<T extends Schema> = {
4243
* do not restore data from old table to new table
4344
*/
4445
truncateIfExists?: boolean | Array<keyof T & string>
45-
/**
46-
* reserve old data in temp, clear after destroy
47-
*/
48-
reserveOldData?: boolean
4946
/**
5047
* trigger on update success
5148
* @param db kysely instance
@@ -64,7 +61,6 @@ export async function syncTables<T extends Schema>(
6461
logger?: DBLogger,
6562
): Promise<StatusResult> {
6663
const {
67-
reserveOldData,
6864
truncateIfExists = [],
6965
log,
7066
version: { current, skipSyncWhenSame } = {},
@@ -134,6 +130,10 @@ export async function syncTables<T extends Schema>(
134130
return { ready: false, error: e }
135131
})
136132

133+
/**
134+
* diff table data
135+
* @see {@link https://sqlite.org/lang_altertable.html official doc} 7. Making Other Kinds Of Table Schema Changes
136+
*/
137137
async function diffTable(
138138
trx: Transaction<any>,
139139
tableName: string,
@@ -158,35 +158,26 @@ export async function syncTables<T extends Schema>(
158158
debug('different table structure, update')
159159
const tempTableName = `_temp_${tableName}`
160160

161-
// 1. copy struct to temporary table
162-
// @ts-expect-error existColumns.columns has parsed column type
163-
await runCreateTable(trx, tempTableName, existColumns, true)
164-
165-
// 2. copy all data to temporary table
166-
await trx.insertInto(tempTableName)
167-
.expression(eb => eb.selectFrom(tableName).selectAll())
168-
.execute()
161+
// 1. create target table with temp name
162+
const _triggerOptions = await runCreateTable(trx, tempTableName, props)
169163

170-
// 3. remove exist table
171-
await runDropTable(trx, tableName)
172-
173-
// 4. create target table
174-
const _triggerOptions = await runCreateTable(trx, tableName, props)
175-
176-
// 5. diff and restore data from temporary table to target table
164+
// 2. diff and restore data from source table to target table
177165
if (restoreColumnList.length) {
178-
await trx.insertInto(tableName)
166+
await trx.insertInto(tempTableName)
179167
.columns(restoreColumnList)
180-
.expression(eb => eb.selectFrom(tempTableName).select(restoreColumnList))
168+
.expression(eb => eb.selectFrom(tableName).select(restoreColumnList))
181169
.execute()
182170
}
171+
// 3. remove old table
172+
await runDropTable(trx, tableName)
173+
174+
// 4. rename temp table to target table name
175+
await runRenameTable(trx, tempTableName, tableName)
183176

184-
// 6. add indexes and triggers
177+
// 5. add indexes and triggers
185178
await runCreateTableIndex(trx, tableName, index)
186179
await runCreateTimeTrigger(trx, tableName, _triggerOptions)
187180

188-
// 7. if not reserve old data, remove temporary table
189-
!reserveOldData && await runDropTable(trx, tempTableName)
190181
debug(`restore columns: ${restoreColumnList}`)
191182
}
192183
}

packages/sqlite-builder/src/schema/run.ts

Lines changed: 8 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -192,3 +192,11 @@ begin
192192
where ${sql.ref(triggerKey)} = NEW.${sql.ref(triggerKey)};
193193
end`.execute(trx)
194194
}
195+
196+
export async function runRenameTable(
197+
trx: Transaction<any>,
198+
tableName: string,
199+
newTableName: string,
200+
) {
201+
await trx.schema.alterTable(tableName).renameTo(newTableName).execute()
202+
}

test/builder.test.ts

Lines changed: 7 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -73,6 +73,7 @@ describe('test sync table', async () => {
7373
bool: Column.Boolean().NotNull(),
7474
array: Column.Object<string[]>(),
7575
buffer: Column.Blob(),
76+
newColumn: Column.Int(),
7677
},
7778
{
7879
primary: 'id',
@@ -96,6 +97,11 @@ describe('test sync table', async () => {
9697
.filter(({ name }) => name === 'bool')[0]
9798
.dataType,
9899
).toBe('TEXT')
100+
expect(_tables
101+
.columns
102+
.filter(({ name }) => name === 'newColumn')[0]
103+
.dataType,
104+
).toBe('INTEGER')
99105
})
100106
})
101107
describe('test builder', async () => {
@@ -160,7 +166,7 @@ describe('test builder', async () => {
160166
expect(result2.rows).toStrictEqual([])
161167
})
162168

163-
it('test soft delete', async () => {
169+
it('should soft delete', async () => {
164170
const softDeleteTable = defineTable({
165171
id: Column.Increments(),
166172
name: Column.String(),

0 commit comments

Comments
 (0)