Skip to content

Commit 94a7a7d

Browse files
author
Hein
committed
Add schema validation
1 parent 195fffd commit 94a7a7d

File tree

2 files changed

+29
-5
lines changed

2 files changed

+29
-5
lines changed

packages/common/src/db/schema/Schema.ts

Lines changed: 12 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -19,6 +19,18 @@ export class Schema<S extends SchemaType = SchemaType> {
1919

2020
constructor(tables: Table[] | S) {
2121
if (Array.isArray(tables)) {
22+
/*
23+
We need to validate that the tables have a name here because a user could pass in an array
24+
of Tables that don't have a name because they are using the V2 syntax.
25+
Therefore, 'convertToClassicTables' won't be called on the tables resulting in a runtime error.
26+
*/
27+
for (const table of tables) {
28+
if (table.name === '') {
29+
throw new Error(
30+
"It appears you are trying to create a new Schema with an array instead of an object. Passing in an object instead of an array into 'new Schema()' may resolve your issue."
31+
);
32+
}
33+
}
2234
this.tables = tables;
2335
} else {
2436
this.props = tables as S;

packages/common/tests/db/schema/Schema.test.ts

Lines changed: 17 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -2,14 +2,26 @@ import { describe, it, expect } from 'vitest';
22
import { Schema } from '../../../src/db/schema/Schema';
33
import { Table } from '../../../src/db/schema/Table';
44
import { column, ColumnType } from '../../../src/db/schema/Column';
5+
import { Column } from '../../../lib';
56

67
describe('Schema', () => {
8+
it('should fail if array is passed and not a table object', () => {
9+
const table1 = new Table({ name: column.text });
10+
const table2 = new Table({ age: { type: ColumnType.INTEGER } });
11+
expect(() => new Schema([table1, table2])).toThrow();
12+
});
13+
714
it('should create a schema with an array of tables', () => {
8-
const tables = [
9-
new Table({ name: column.text, }),
10-
new Table({ age: { type: ColumnType.INTEGER } })
11-
];
12-
const schema = new Schema(tables);
15+
const table1 = new Table({
16+
name: 'table1',
17+
columns: [new Column({ name: 'name', type: ColumnType.TEXT })]
18+
});
19+
const table2 = new Table({
20+
name: 'table2',
21+
columns: [new Column({ name: 'age', type: ColumnType.INTEGER })]
22+
});
23+
const schema = new Schema([table1, table2]);
24+
expect(() => schema.validate()).not.toThrow();
1325

1426
expect(schema.tables).toHaveLength(2);
1527
expect(schema.tables[0].columns[0].name).toBe('name');

0 commit comments

Comments
 (0)