Skip to content

Commit 9fbe5b2

Browse files
Add schema validation (#448)
1 parent e1be20e commit 9fbe5b2

File tree

2 files changed

+30
-7
lines changed

2 files changed

+30
-7
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: 18 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -1,15 +1,26 @@
11
import { describe, it, expect } from 'vitest';
22
import { Schema } from '../../../src/db/schema/Schema';
33
import { Table } from '../../../src/db/schema/Table';
4-
import { column, ColumnType } from '../../../src/db/schema/Column';
4+
import { column, ColumnType, Column } from '../../../src/db/schema/Column';
55

66
describe('Schema', () => {
7-
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);
7+
it('should fail if an array of tables using the new syntax is passed to schema', () => {
8+
const table1 = new Table({ name: column.text });
9+
const table2 = new Table({ age: { type: ColumnType.INTEGER } });
10+
expect(() => new Schema([table1, table2])).toThrow();
11+
});
12+
13+
it('should create a schema with an array of tables using the old syntax', () => {
14+
const table1 = new Table({
15+
name: 'table1',
16+
columns: [new Column({ name: 'name', type: ColumnType.TEXT })]
17+
});
18+
const table2 = new Table({
19+
name: 'table2',
20+
columns: [new Column({ name: 'age', type: ColumnType.INTEGER })]
21+
});
22+
const schema = new Schema([table1, table2]);
23+
expect(() => schema.validate()).not.toThrow();
1324

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

0 commit comments

Comments
 (0)