Skip to content

Commit

Permalink
Add schema validation (#448)
Browse files Browse the repository at this point in the history
  • Loading branch information
HeinrichvonStein authored Dec 18, 2024
1 parent e1be20e commit 9fbe5b2
Show file tree
Hide file tree
Showing 2 changed files with 30 additions and 7 deletions.
12 changes: 12 additions & 0 deletions packages/common/src/db/schema/Schema.ts
Original file line number Diff line number Diff line change
Expand Up @@ -19,6 +19,18 @@ export class Schema<S extends SchemaType = SchemaType> {

constructor(tables: Table[] | S) {
if (Array.isArray(tables)) {
/*
We need to validate that the tables have a name here because a user could pass in an array
of Tables that don't have a name because they are using the V2 syntax.
Therefore, 'convertToClassicTables' won't be called on the tables resulting in a runtime error.
*/
for (const table of tables) {
if (table.name === '') {
throw new Error(
"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."
);
}
}
this.tables = tables;
} else {
this.props = tables as S;
Expand Down
25 changes: 18 additions & 7 deletions packages/common/tests/db/schema/Schema.test.ts
Original file line number Diff line number Diff line change
@@ -1,15 +1,26 @@
import { describe, it, expect } from 'vitest';
import { Schema } from '../../../src/db/schema/Schema';
import { Table } from '../../../src/db/schema/Table';
import { column, ColumnType } from '../../../src/db/schema/Column';
import { column, ColumnType, Column } from '../../../src/db/schema/Column';

describe('Schema', () => {
it('should create a schema with an array of tables', () => {
const tables = [
new Table({ name: column.text, }),
new Table({ age: { type: ColumnType.INTEGER } })
];
const schema = new Schema(tables);
it('should fail if an array of tables using the new syntax is passed to schema', () => {
const table1 = new Table({ name: column.text });
const table2 = new Table({ age: { type: ColumnType.INTEGER } });
expect(() => new Schema([table1, table2])).toThrow();
});

it('should create a schema with an array of tables using the old syntax', () => {
const table1 = new Table({
name: 'table1',
columns: [new Column({ name: 'name', type: ColumnType.TEXT })]
});
const table2 = new Table({
name: 'table2',
columns: [new Column({ name: 'age', type: ColumnType.INTEGER })]
});
const schema = new Schema([table1, table2]);
expect(() => schema.validate()).not.toThrow();

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

0 comments on commit 9fbe5b2

Please sign in to comment.