-
-
Notifications
You must be signed in to change notification settings - Fork 2.2k
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
🗃️ Update non-string variable values in Database
- Loading branch information
1 parent
d75eceb
commit 461d2e2
Showing
3 changed files
with
80 additions
and
7 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,73 @@ | ||
import { PrismaClient } from 'db' | ||
import { promptAndSetEnvironment } from './utils' | ||
import { Result } from 'models' | ||
import { isDefined, isNotDefined } from 'utils' | ||
|
||
let progress = 0 | ||
|
||
const bulkUpdate = async () => { | ||
await promptAndSetEnvironment() | ||
const prisma = new PrismaClient({ | ||
log: [ | ||
{ | ||
emit: 'event', | ||
level: 'query', | ||
}, | ||
'info', | ||
'warn', | ||
'error', | ||
], | ||
}) | ||
|
||
const results = (await prisma.result.findMany({ | ||
where: { | ||
variables: { isEmpty: false }, | ||
}, | ||
select: { variables: true, id: true }, | ||
})) as Pick<Result, 'variables' | 'id'>[] | ||
|
||
const queries = results | ||
.map((result) => { | ||
if ( | ||
result.variables.some((variable) => typeof variable.value !== 'string') | ||
) { | ||
return prisma.result.updateMany({ | ||
where: { id: result.id }, | ||
data: { | ||
variables: result.variables | ||
.map((variable) => ({ | ||
...variable, | ||
value: | ||
typeof variable.value !== 'string' | ||
? safeStringify(variable.value) | ||
: variable.value, | ||
})) | ||
.filter(isDefined), | ||
}, | ||
}) | ||
} | ||
}) | ||
.filter(isDefined) | ||
|
||
const total = queries.length | ||
|
||
prisma.$on('query', () => { | ||
progress += 1 | ||
console.log(`Progress: ${progress}/${total}`) | ||
}) | ||
|
||
await prisma.$transaction(queries) | ||
} | ||
|
||
export const safeStringify = (val: unknown): string | null => { | ||
if (isNotDefined(val)) return null | ||
if (typeof val === 'string') return val | ||
try { | ||
return JSON.stringify(val) | ||
} catch { | ||
console.warn('Failed to safely stringify variable value', val) | ||
return null | ||
} | ||
} | ||
|
||
bulkUpdate() |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters