Skip to content

Commit

Permalink
Add new migration strategy for updating DB. Add 'test' migration on n…
Browse files Browse the repository at this point in the history
…ew join table for custom shows (#3)
  • Loading branch information
chrisbenincasa authored Jan 19, 2024
1 parent 6d2bbf1 commit 70527b4
Show file tree
Hide file tree
Showing 6 changed files with 97 additions and 35 deletions.
37 changes: 14 additions & 23 deletions server/dao/dataSource.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,23 +3,18 @@ import type {
SqlEntityManager,
} from '@mikro-orm/better-sqlite'; // or any other driver package
import { MikroORM } from '@mikro-orm/better-sqlite';
import {
CreateContextOptions,
RequestContext,
UnderscoreNamingStrategy,
} from '@mikro-orm/core';
import { CreateContextOptions, RequestContext } from '@mikro-orm/core';
import fs from 'fs';
import { isUndefined, once } from 'lodash-es';
import path, { dirname } from 'node:path';
import path from 'node:path';
import 'reflect-metadata';
import { globalOptions } from '../globals.js';
import createLogger from '../logger.js';
import { TsMorphMetadataProvider } from '@mikro-orm/reflection';
import { fileURLToPath } from 'node:url';
import dbConfig from '../mikro-orm.config.js';

// Temporary
const __filename = fileURLToPath(import.meta.url);
const __dirname = dirname(__filename);
// const __filename = fileURLToPath(import.meta.url);
// const __dirname = dirname(__filename);

const logger = createLogger(import.meta);

Expand All @@ -28,25 +23,21 @@ export const initOrm = once(async () => {
const hasExistingDb = fs.existsSync(dbPath);
logger.debug(`${hasExistingDb ? 'Existing' : 'No Existing'} DB at ${dbPath}`);

const orm = await MikroORM.init<BetterSqliteDriver>({
const orm = await MikroORM.init({
...dbConfig,
dbName: dbPath,
baseDir: __dirname,
entities: ['../build/dao/entities'],
entitiesTs: ['./entities'],
debug: !!process.env['DATABASE_DEBUG_LOGGING'],
namingStrategy: UnderscoreNamingStrategy,
forceUndefined: true,
dynamicImportProvider: (id) => import(id),
metadataProvider: TsMorphMetadataProvider,
});

// Dynamically loading the config doesn't work in tests...figure out why
// const orm = await MikroORM.init();
const migrator = orm.getMigrator();

// First launch
if (!hasExistingDb) {
if (
!hasExistingDb ||
(await migrator.checkMigrationNeeded()) ||
(await migrator.getPendingMigrations()).length > 0
) {
logger.debug('Synchronizing DB');
await orm.getSchemaGenerator().createSchema();
await migrator.up();
}

return orm;
Expand Down
3 changes: 2 additions & 1 deletion server/dao/entities/CustomShow.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,13 +2,14 @@ import { Collection, Entity, ManyToMany, Property } from '@mikro-orm/core';
import { BaseEntity } from './BaseEntity.js';
import { Program } from './Program.js';
import { Channel } from './Channel.js';
import { CustomShowContent } from './CustomShowContent.js';

@Entity()
export class CustomShow extends BaseEntity {
@Property()
name!: string;

@ManyToMany(() => Program, 'customShows', { owner: true })
@ManyToMany({ entity: () => Program, pivotEntity: () => CustomShowContent })
content = new Collection<Program>(this);

@ManyToMany(() => Channel, (channel) => channel.customShows)
Expand Down
35 changes: 35 additions & 0 deletions server/dao/entities/CustomShowContent.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,35 @@
import {
Entity,
ManyToOne,
PrimaryKeyProp,
Property,
Rel,
Unique,
} from '@mikro-orm/core';
import { CustomShow } from './CustomShow.js';
import { Program } from './Program.js';

@Entity()
@Unique({ properties: ['customShow', 'content', 'index'] })
export class CustomShowContent {
@ManyToOne({ primary: true, entity: () => CustomShow })
customShow!: Rel<CustomShow>;

@ManyToOne({ primary: true, entity: () => Program })
content!: Rel<Program>;

@Property()
index!: number;

[PrimaryKeyProp]?: ['customShow', 'content'];

constructor(
customShow: Rel<CustomShow>,
content: Rel<Program>,
index: number,
) {
this.customShow = customShow;
this.content = content;
this.index = index;
}
}
4 changes: 3 additions & 1 deletion server/dao/entities/Program.ts
Original file line number Diff line number Diff line change
Expand Up @@ -118,8 +118,10 @@ export class Program extends BaseEntity {
@ManyToMany(() => Channel, (channel) => channel.fallback, { eager: false })
channelFallbacks = new Collection<Channel>(this);

@ManyToMany(() => CustomShow, (customShow) => customShow.content, {
@ManyToMany({
entity: () => CustomShow,
eager: false,
mappedBy: (e) => e.content,
})
customShows = new Collection<CustomShow>(this);

Expand Down
39 changes: 29 additions & 10 deletions server/migrations/.snapshot-db.db.json
Original file line number Diff line number Diff line change
Expand Up @@ -1015,14 +1015,23 @@
"nullable": false,
"mappedType": "text"
},
"program_uuid": {
"name": "program_uuid",
"content_uuid": {
"name": "content_uuid",
"type": "text",
"unsigned": false,
"autoincrement": false,
"primary": false,
"nullable": false,
"mappedType": "text"
},
"index": {
"name": "index",
"type": "integer",
"unsigned": false,
"autoincrement": false,
"primary": false,
"nullable": false,
"mappedType": "integer"
}
},
"name": "custom_show_content",
Expand All @@ -1039,19 +1048,31 @@
},
{
"columnNames": [
"program_uuid"
"content_uuid"
],
"composite": false,
"keyName": "custom_show_content_program_uuid_index",
"keyName": "custom_show_content_content_uuid_index",
"constraint": false,
"primary": false,
"unique": false
},
{
"keyName": "custom_show_content_custom_show_uuid_content_uuid_index_unique",
"columnNames": [
"custom_show_uuid",
"content_uuid",
"index"
],
"composite": true,
"constraint": true,
"primary": false,
"unique": true
},
{
"keyName": "primary",
"columnNames": [
"custom_show_uuid",
"program_uuid"
"content_uuid"
],
"composite": true,
"constraint": true,
Expand All @@ -1071,20 +1092,18 @@
"uuid"
],
"referencedTableName": "custom_show",
"deleteRule": "cascade",
"updateRule": "cascade"
},
"custom_show_content_program_uuid_foreign": {
"constraintName": "custom_show_content_program_uuid_foreign",
"custom_show_content_content_uuid_foreign": {
"constraintName": "custom_show_content_content_uuid_foreign",
"columnNames": [
"program_uuid"
"content_uuid"
],
"localTableName": "custom_show_content",
"referencedColumnNames": [
"uuid"
],
"referencedTableName": "program",
"deleteRule": "cascade",
"updateRule": "cascade"
}
},
Expand Down
14 changes: 14 additions & 0 deletions server/migrations/Migration20240119164121.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,14 @@
import { Migration } from '@mikro-orm/migrations';

export class Migration20240119164121 extends Migration {

async up(): Promise<void> {
this.addSql('drop index `custom_show_content_program_uuid_index`;');

this.addSql('alter table `custom_show_content` add column `index` integer not null constraint `custom_show_content_content_uuid_foreign` references `program` (`uuid`) on update cascade constraint `custom_show_content_custom_show_uuid_foreign` references `custom_show` (`uuid`) on update cascade;');
this.addSql('alter table `custom_show_content` rename column `program_uuid` to `content_uuid`;');
this.addSql('create index `custom_show_content_content_uuid_index` on `custom_show_content` (`content_uuid`);');
this.addSql('create unique index `custom_show_content_custom_show_uuid_content_uuid_index_unique` on `custom_show_content` (`custom_show_uuid`, `content_uuid`, `index`);');
}

}

0 comments on commit 70527b4

Please sign in to comment.