-
-
Notifications
You must be signed in to change notification settings - Fork 2.9k
refactor: backend database migrations (@fehmer) #6479
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
Draft
fehmer
wants to merge
11
commits into
master
Choose a base branch
from
feature/reusable-backend-migrations
base: master
Could not load branches
Branch not found: {{ refName }}
Loading
Could not load tags
Nothing to show
Loading
Are you sure you want to change the base?
Some commits from the old base branch may be removed from the timeline,
and old review comments may become outdated.
Draft
Changes from 1 commit
Commits
Show all changes
11 commits
Select commit
Hold shift + click to select a range
842515d
refactor: backend database migrations (@fehmer)
fehmer f6ce766
wip
fehmer 34e3917
use index for results, migrate config.customLayoutfluid
fehmer 8c1ef45
add migration picker, export default all migrations
Miodec dd51ecc
missing param
Miodec 64be428
accidental comment
Miodec 60bc373
fix
Miodec 4dea653
test migrations
fehmer 853c09e
Merge branch 'master' into feature/reusable-backend-migrations
fehmer 72bbe06
cleanup
fehmer 8474072
Merge branch 'master' into feature/reusable-backend-migrations
fehmer File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or 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,47 @@ | ||
| import { Collection, Db } from "mongodb"; | ||
| import { Migration } from "./types"; | ||
| import type { DBConfig } from "../src/dal/config"; | ||
|
|
||
| export class FunboxConfig implements Migration { | ||
| private configCollection!: Collection<DBConfig>; | ||
| private filter = { "config.funbox": { $exists: true, $type: "string" } }; | ||
| private collectionName = "configs2"; //TODO rename | ||
|
|
||
| name: string = "FunboxConfig"; | ||
|
|
||
| async setup(db: Db): Promise<void> { | ||
| this.configCollection = db.collection(this.collectionName); | ||
| } | ||
| async getRemainingCount(): Promise<number> { | ||
| return this.configCollection.countDocuments(this.filter); | ||
| } | ||
|
|
||
| async migrate({ batchSize }: { batchSize: number }): Promise<number> { | ||
| await this.configCollection | ||
| .aggregate([ | ||
| { $match: this.filter }, | ||
| { $limit: batchSize }, | ||
| { | ||
| $addFields: { | ||
| "config.funbox": { | ||
| $cond: { | ||
| if: { $eq: ["$config.funbox", "none"] }, | ||
| // eslint-disable-next-line no-thenable | ||
| then: undefined, | ||
| else: { $split: ["$config.funbox", "#"] }, | ||
| }, | ||
| }, | ||
| }, | ||
| }, | ||
| { | ||
| $merge: { | ||
| into: this.collectionName, | ||
| on: "_id", | ||
| whenMatched: "merge", | ||
| }, | ||
| }, | ||
| ]) | ||
| .toArray(); | ||
| return batchSize; //TODO hmmm.... | ||
| } | ||
| } | ||
This file contains hidden or 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,46 @@ | ||
| import { Collection, Db } from "mongodb"; | ||
| import { Migration } from "./types"; | ||
| import type { DBResult } from "../src/utils/result"; | ||
|
|
||
| export class funboxResult implements Migration { | ||
| private resultCollection!: Collection<DBResult>; | ||
| private filter = { funbox: { $exists: true, $not: { $type: "array" } } }; | ||
| private collectionName = "results2"; //TODO rename | ||
| name: string = "FunboxResult"; | ||
|
|
||
| async setup(db: Db): Promise<void> { | ||
| this.resultCollection = db.collection(this.collectionName); | ||
| } | ||
| async getRemainingCount(): Promise<number> { | ||
| return this.resultCollection.countDocuments(this.filter); | ||
| } | ||
|
|
||
| async migrate({ batchSize }: { batchSize: number }): Promise<number> { | ||
| await this.resultCollection | ||
| .aggregate([ | ||
| { $match: this.filter }, | ||
| { $limit: batchSize }, | ||
| { | ||
| $addFields: { | ||
| funbox: { | ||
| $cond: { | ||
| if: { $eq: ["$funbox", "none"] }, | ||
| // eslint-disable-next-line no-thenable | ||
| then: undefined, | ||
| else: { $split: ["$funbox", "#"] }, | ||
| }, | ||
| }, | ||
| }, | ||
| }, | ||
| { | ||
| $merge: { | ||
| into: this.collectionName, | ||
| on: "_id", | ||
| whenMatched: "merge", | ||
| }, | ||
| }, | ||
| ]) | ||
| .toArray(); | ||
| return batchSize; //TODO hmmm.... | ||
| } | ||
| } |
This file contains hidden or 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,109 @@ | ||
| import "dotenv/config"; | ||
| import * as DB from "../src/init/db"; | ||
| import { Db } from "mongodb"; | ||
| import readlineSync from "readline-sync"; | ||
| import { funboxResult } from "./funboxResult"; | ||
|
|
||
| const batchSize = 50; | ||
| let appRunning = true; | ||
| let db: Db | undefined; | ||
| const migration = new funboxResult(); | ||
|
|
||
| process.on("SIGINT", () => { | ||
| console.log("\nshutting down..."); | ||
| appRunning = false; | ||
| }); | ||
|
|
||
| if (require.main === module) { | ||
| void main(); | ||
| } | ||
|
|
||
| async function main(): Promise<void> { | ||
| try { | ||
| console.log( | ||
| `Connecting to database ${process.env["DB_NAME"]} on ${process.env["DB_URI"]}...` | ||
| ); | ||
|
|
||
| if ( | ||
| !readlineSync.keyInYN(`Ready to start migration ${migration.name} ?`) | ||
| ) { | ||
| appRunning = false; | ||
| } | ||
|
|
||
| if (appRunning) { | ||
| await DB.connect(); | ||
| console.log("Connected to database"); | ||
| db = DB.getDb(); | ||
| if (db === undefined) { | ||
| throw Error("db connection failed"); | ||
| } | ||
|
|
||
| console.log(`Running migration ${migration.name}`); | ||
|
|
||
| await migrate(); | ||
| } | ||
|
|
||
| console.log(`\nMigration ${appRunning ? "done" : "aborted"}.`); | ||
| } catch (e) { | ||
| console.log("error occured:", { e }); | ||
| } finally { | ||
| await DB.close(); | ||
| } | ||
| } | ||
|
|
||
| export async function migrate(): Promise<void> { | ||
| await migration.setup(db as Db); | ||
|
|
||
| await migrateResults(); | ||
| } | ||
|
|
||
| async function migrateResults(): Promise<void> { | ||
| const remainingCount = await migration.getRemainingCount(); | ||
| if (remainingCount === 0) { | ||
| console.log("No documents to migrate."); | ||
| return; | ||
| } else { | ||
| console.log("Documents to migrate:", remainingCount); | ||
| } | ||
|
|
||
| console.log( | ||
| `Migrating ~${remainingCount} documents using batchSize=${batchSize}` | ||
| ); | ||
|
|
||
| let count = 0; | ||
| const start = new Date().valueOf(); | ||
|
|
||
| do { | ||
| const t0 = Date.now(); | ||
|
|
||
| const migratedCount = await migration.migrate({ batchSize }); | ||
|
|
||
| //progress tracker | ||
| count += migratedCount; | ||
| updateProgress(remainingCount, count, start, Date.now() - t0); | ||
| } while (remainingCount - count > 0 && appRunning); | ||
|
|
||
| if (appRunning) updateProgress(100, 100, start, 0); | ||
| } | ||
|
|
||
| function updateProgress( | ||
| all: number, | ||
| current: number, | ||
| start: number, | ||
| previousBatchSizeTime: number | ||
| ): void { | ||
| const percentage = (current / all) * 100; | ||
| const timeLeft = Math.round( | ||
| (((new Date().valueOf() - start) / percentage) * (100 - percentage)) / 1000 | ||
| ); | ||
|
|
||
| process.stdout.clearLine?.(0); | ||
| process.stdout.cursorTo?.(0); | ||
| process.stdout.write( | ||
| `Previous batch took ${Math.round(previousBatchSizeTime)}ms (~${ | ||
| previousBatchSizeTime / batchSize | ||
| }ms per document) ${Math.round( | ||
| percentage | ||
| )}% done, estimated time left ${timeLeft} seconds.` | ||
| ); | ||
| } |
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Uh oh!
There was an error while loading. Please reload this page.