Project Files
docs / components / schema-manager.md
[!ABSTRACT] Epigraf "Zarządza definicjami kolumn tabel — tworzenie, odczyt, walidacja i przechowywanie schematów w formacie JSON."
| Pole | Wartość |
|---|---|
| Nazwa | Schema Manager |
| Moduł | src/engine/schema.ts |
| Wersja | 1.0.0 |
| Status | Draft |
| Zależny od | — |
| Używany przez | CSV Engine, Table Tools, CRUD Tools |
Definiowanie i egzekwowanie struktury danych w tabelach CSV. Każda tabela ma plik <nazwa>.schema.json określający kolumny, typy, klucze główne i ograniczenia.
.schema.jsonloadSchema(path: string): Promise<TableSchema>.schema.json z dysku. Cache'uje w pamięci.SchemaNotFoundError jeśli plik nie istnieje, FilesystemError przy błędzie I/OsaveSchema(path: string, schema: TableSchema): Promise<void>.schema.json.validateRowAgainstSchema(row: Record<string, any>, schema: TableSchema): ValidationResultValidationResult z listą błędówvalidateRowsAgainstSchema(rows: Record<string, any>[], schema: TableSchema): ValidationResultinferSchemaFromRow(row: Record<string, any>): TableSchemaschemaPath(database: string, table: string): string.schema.json dla tabeli.| Parametr | Typ | Opis |
|---|---|---|
path | string | Ścieżka do pliku .schema.json |
schema | TableSchema | Obiekt schematu |
row | Record<string, any> | Pojedynczy wiersz do walidacji |
rows | Record<string, any>[] | Tablica wierszy do walidacji |
database | string | Nazwa bazy |
table | string | Nazwa tabeli |
| Funkcja | Zwraca |
|---|---|
loadSchema | Promise<TableSchema> |
saveSchema | Promise<void> |
validateRowAgainstSchema | ValidationResult |
validateRowsAgainstSchema | ValidationResult |
inferSchemaFromRow | TableSchema |
schemaPath | string |
| Typ Schema | Typ JavaScript | CSV reprezentacja |
|---|---|---|
string | string | Bez zmian |
number | number | Parsowany przez parseFloat |
boolean | boolean | true/false, 1/0, yes/no |
date | string (ISO) | ISO 8601 lub konfigurowalny format |
| Biblioteka | Wersja | Użycie |
|---|---|---|
path | (Node.js) | Manipulacje ścieżkami |
fs/promises | (Node.js) | Odczyt/zapis plików |
| Błąd | Kod | Przyczyna | Recovery |
|---|---|---|---|
SchemaNotFoundError | SCHEMA_NOT_FOUND | Brak pliku .schema.json | Stwórz domyślny schema z inferencji |
FilesystemError | FILESYSTEM_ERROR | Brak dostępu do pliku | Retry 2x |
ValidationError | VALIDATION_ERROR | Niezgodność typu / brak wymaganego pola | Zwróć ValidationResult z listą błędów |
| Given | When | Then |
|---|---|---|
| Poprawny schema.json na dysku | loadSchema(path) | Zwraca TableSchema |
| Brak schema.json | loadSchema(path) | Rzuca SchemaNotFoundError |
| Wiersz zgodny ze schematem | validateRowAgainstSchema(row, schema) | result.valid === true |
| Brak wymaganego pola | validateRowAgainstSchema(row, schema) | result.valid === false, error.code === REQUIRED_FIELD |
| Zły typ (string zamiast number) | validateRowAgainstSchema(row, schema) | result.valid === false, error.code === TYPE_MISMATCH |
| Pusty obiekt | inferSchemaFromRow({}) | Zwraca pustą tablicę [] |
| Row z polami różnych typów | inferSchemaFromRow(row) | Poprawne typy: string, number, boolean |
test/fixtures/valid-schema.json — poprawny schematest/fixtures/malformed-schema.json — niepoprawny JSONtest/fixtures/row-valid.json — wiersz zgodny ze schematemtest/fixtures/row-invalid.json — wiersz z błędami typów../../TDD.md — §5.1 Schema Manager APIcsv-engine.md — wykorzystuje schematy do walidacji przed zapisemtable-tools.md — wywołuje saveSchema przy create_tableinterface ColumnDef {
name: string;
type: "string" | "number" | "boolean" | "date";
required?: boolean;
primaryKey?: boolean;
unique?: boolean;
defaultValue?: any;
description?: string;
}
interface TableSchema {
columns: ColumnDef[];
createdAt: string; // ISO 8601
updatedAt?: string; // ISO 8601
description?: string;
version?: number;
}
interface ValidationError {
column: string;
message: string;
code: "TYPE_MISMATCH" | "REQUIRED_FIELD" | "INVALID_VALUE";
expected: string;
actual: any;
}
interface ValidationResult {
valid: boolean;
errors: ValidationError[];
}
import {
loadSchema,
saveSchema,
validateRowAgainstSchema,
inferSchemaFromRow,
} from "./schema";
// Definicja schematu
const schema: TableSchema = {
columns: [
{ name: "id", type: "string", primaryKey: true },
{ name: "name", type: "string", required: true },
{ name: "age", type: "number" },
{ name: "isAlive", type: "boolean", defaultValue: true },
],
createdAt: new Date().toISOString(),
description: "Main character data table",
};
// Zapis
await saveSchema("/data/schemas/walter-white.schema.json", schema);
// Walidacja
const result = validateRowAgainstSchema(
{ id: "ww-001", name: "Walter White", age: 50 },
schema,
);
console.log(result.valid); // true
// Zły typ
const badResult = validateRowAgainstSchema(
{ id: "ww-002", name: "Jesse", age: "twenty-five" },
schema,
);
console.log(badResult.errors);
// [{ column: "age", code: "TYPE_MISMATCH", expected: "number", actual: "twenty-five" }]
// Auto-detect
const inferred = inferSchemaFromRow({ name: "Saul", practice: "law" });
// → [{ name: "name", type: "string" }, { name: "practice", type: "string" }]
stateDiagram-v2
[*] -→ Idle
Idle -→ Loading: loadSchema()
Loading -→ Cached: success
Loading -→ NotFound: SchemaNotFoundError
Cached -→ Idle: retain in memory
Cached -→ Validating: validateRow()
Validating -→ Cached: ValidationResult
Idle -→ Saving: saveSchema()
Saving -→ Idle: success
Saving -→ Error: FilesystemError
NotFound -→ Idle: create & save new