Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
7 changes: 6 additions & 1 deletion src/selfgraph/_tables.py
Original file line number Diff line number Diff line change
Expand Up @@ -83,7 +83,12 @@ def from_tables(tables: Sequence[Mapping[str, Any]], name: str | None = None) ->
etype = names[table["name"]]
phrase = " ".join(_words(table["name"]))
properties = []
for j, column in enumerate(table.get("columns") or ()):
columns = table.get("columns")
if columns is not None and (isinstance(columns, str | Mapping) or not isinstance(columns, Sequence)):
raise ValidationError(
f"tables[{i}].columns must be a list of column mappings, got {type_name(columns)}", field="columns"
)
for j, column in enumerate(columns or ()):
if not isinstance(column, Mapping) or not isinstance(column.get("name"), str):
raise ValidationError(f"tables[{i}].columns[{j}]: each column needs a name")
target = column.get("references")
Expand Down
8 changes: 8 additions & 0 deletions tests/test_schema_regressions.py
Original file line number Diff line number Diff line change
Expand Up @@ -26,6 +26,14 @@ async def check():
asyncio.run(check())


def test_307_from_tables_rejects_a_non_list_columns_value():
for value, name in [(5, "number"), (True, "boolean"), (1.5, "number"), ("abc", "string")]:
with pytest.raises(ValidationError) as exc:
Schema.from_tables([{"name": "orders", "columns": value}])
assert (exc.value.code, exc.value.field) == ("invalid_argument", "columns")
assert str(exc.value) == f"tables[0].columns must be a list of column mappings, got {name}"


def test_309_from_tables_distinguishes_schema_qualified_names():
async def check():
schema = Schema.from_tables(
Expand Down
8 changes: 7 additions & 1 deletion typescript/src/tables.ts
Original file line number Diff line number Diff line change
Expand Up @@ -106,7 +106,13 @@ export function fromTables(tables: readonly object[], options: FromTablesOptions
const tableName = table.name as string;
const etype = names.get(tableName)!;
const properties: unknown[] = [];
for (const [j, column] of ((table.columns || []) as unknown[]).entries()) {
const columns = table.columns;
if (columns != null && !Array.isArray(columns)) {
throw new ValidationError(`tables[${i}].columns must be a list of column mappings, got ${typeName(columns)}`, {
field: "columns",
});
}
for (const [j, column] of ((columns || []) as unknown[]).entries()) {
if (!isPlainObject(column) || typeof column.name !== "string") {
throw new ValidationError(`tables[${i}].columns[${j}]: each column needs a name`);
}
Expand Down
9 changes: 7 additions & 2 deletions typescript/test/conformance/py_side.py
Original file line number Diff line number Diff line change
Expand Up @@ -537,16 +537,21 @@ def document(text):


def tables_reference_errors():
"""Draft a schema with each invalid column reference and return the resulting error messages.
"""Draft a schema with each invalid column reference and non-list columns value and return the error messages.

@return (list[str]): one message per reference, including unhashable ones.
@return (list[str]): one message per case, including unhashable references.
"""
messages = []
for reference in ({"table": "users"}, ["users"], 5):
try:
Schema.from_tables([{"name": "orders", "columns": [{"name": "user_id", "references": reference}]}])
except ValidationError as exc:
messages.append(str(exc))
for columns in (5, True, "abc"):
try:
Schema.from_tables([{"name": "orders", "columns": columns}])
except ValidationError as exc:
messages.append(str(exc))
return messages


Expand Down
12 changes: 11 additions & 1 deletion typescript/test/conformance/ts_side.ts
Original file line number Diff line number Diff line change
Expand Up @@ -561,7 +561,7 @@ function jsonConstants(): { flags: unknown[]; documents: unknown[] } {
* @return (string[]): one message per reference, including unhashable ones.
*/
function tablesReferenceErrors(): string[] {
return [{ table: "users" }, ["users"], 5].map((reference) => {
const messages = [{ table: "users" }, ["users"], 5].map((reference) => {
try {
fromTables([{ name: "orders", columns: [{ name: "user_id", references: reference }] }]);
return "accepted";
Expand All @@ -570,6 +570,16 @@ function tablesReferenceErrors(): string[] {
return exc.message;
}
});
for (const columns of [5, true, "abc"]) {
try {
fromTables([{ name: "orders", columns: columns as never }]);
messages.push("accepted");
} catch (exc) {
if (!(exc instanceof ValidationError)) throw exc;
messages.push(exc.message);
}
}
return messages;
}

/**
Expand Down
19 changes: 19 additions & 0 deletions typescript/test/schemaRegressions.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -31,6 +31,25 @@ it("306 rejects schema relation types that normalize to empty", async () => {
expect(parseOrThrow(Schema, { relations: [{ type: "works at" }] }, "schema").relations[0]!.type).toBe("works at");
});

it("307 rejects a non-list columns value", () => {
for (const [value, name] of [
[5, "number"],
[true, "boolean"],
[1.5, "number"],
["abc", "string"],
] as const) {
let err: ValidationError | undefined;
try {
fromTables([{ name: "orders", columns: value as never }]);
} catch (exc) {
err = exc as ValidationError;
}
expect(err).toBeInstanceOf(ValidationError);
expect([err?.code, err?.field]).toEqual(["invalid_argument", "columns"]);
expect(err?.message).toBe(`tables[0].columns must be a list of column mappings, got ${name}`);
}
});

it("309 distinguishes schema-qualified table names", async () => {
const schema = fromTables([
{ name: "sales.users", columns: [{ name: "support_id", references: "support.users" }] },
Expand Down
Loading