XYLEX Group
DevelopmentResource FrameworkUtils

Csv

CSV and type inference utilities

These utilities help infer value types from CSV data, summarize column types, and check compatibility against database column types. They live in packages/resource-framework/utils/csv.ts and are re‑exported from @/packages/resource-framework.

Imports

import {
  inferValueType,
  inferCsvTypes,
  isTypeCompatible,
} from "@/packages/resource-framework";
```typescript

### inferValueType

- **Signature**: `(value: unknown) => "null" | "number" | "boolean" | "date" | "string"`
- **Behavior**:
  - Returns `"null"` for `null`, `undefined`, or empty string
  - Detects native numbers, booleans, and `Date` instances
  - Detects ISO-like date strings: `YYYY-MM-DD` optionally with time
  - Detects numeric strings (integer/decimal, with optional sign)
  - Falls back to `"string"`

```typescript
inferValueType(null); // "null"
inferValueType(42); // "number"
inferValueType("2024-06-01"); // "date"
inferValueType("-12.5"); // "number"
inferValueType("hello"); // "string"
```typescript

### inferCsvTypes

- **Signature**: `(rows: Array<Record<string, any>>, headers: string[]) => Record<string, string>`
- **Behavior**:
  - Samples up to the first 200 rows
  - Tallies detected types per header using `inferValueType`
  - Returns the most frequent type per header, or `"unknown"` if no data

```typescript
const headers = ["id", "created_at", "active", "amount"];
const rows = [
  { id: "1", created_at: "2024-01-01", active: "true", amount: "10.50" },
  { id: 2, created_at: "2024-01-02", active: false, amount: 99 },
];
const types = inferCsvTypes(rows, headers);
// Example:
// { id: "number", created_at: "date", active: "boolean", amount: "number" }
```typescript

### isTypeCompatible

- **Signature**: `(csvType?: string, tableType?: string) => boolean`
- **Behavior**:
  - Permissive when CSV type is `"unknown"`/`"null"` or table type is missing
  - Maps CSV `"number"` to DB types matching `/int|numeric|decimal|double|real|float|number/`
  - Maps CSV `"boolean"` to DB types matching `/bool/`
  - Maps CSV `"date"` to DB types matching `/date|timestamp|time/`
  - `"string"` is allowed for any table type

```typescript
isTypeCompatible("number", "integer"); // true
isTypeCompatible("date", "timestamp with time zone"); // true
isTypeCompatible("boolean", "text"); // false
isTypeCompatible("string", "jsonb"); // true
```typescript

### Example: building column mappings

```typescript
const csvTypes = inferCsvTypes(csvRows, csvHeaders);
const compatibleColumns = destinationColumns.filter((c) =>
  isTypeCompatible(csvTypes["amount"], destinationTypes[c]),
);
```typescript