iTranslated by AI
Achieving Decent Type Safety with Zod for CSV Handling in DuckDB-WASM
When using DuckDB-WASM in the browser to handle CSV data, I encountered various issues, so I'll summarize them here.
Since there weren't any suitable query builders or ORMs that work well with DuckDB, I'll go with raw SQL without them, aiming for a state where I can get reasonable type safety using Zod.
For this article, I used the CSV distributed by ekidata.jp as a sample, so the sample code follows that.
1. Load CSV with all_varchar=true to treat everything as strings
When loading a CSV with read_csv in DuckDB, it normally reads each field and automatically determines the type.
Although this seems convenient at first glance, I encountered many inconveniences:
- Numeric values become BigInt, causing issues like
JSON.stringifyfailing. - Time formats like
12:34get unexpectedly converted to epoch time, making things confusing. - Float types sometimes become Buffer, which is subtly troublesome.
By specifying all_varchar=true as an option for read_csv, all values are treated as strings, so I decided to rely on this.
CREATE OR REPLACE TABLE ${table} AS SELECT * FROM read_csv('${url}', all_varchar=true);
I also tried parameters like auto_type_candidates and settings like [castBigIntToDouble](https://shell.duckdb.org/docs/interfaces/index.DuckDBQueryConfig.html), but none of them felt right, so I concluded that converting everything to strings for now is the happier path.
Cast when you need numeric values
A side effect of all_varchar=true is that everything becomes a string, which can cause issues with sorting, for example. In such cases, you need to explicitly cast like foo::DOUBLE.
SELECT station,
FROM station
ORDER BY station.open_ymd::DATE
(Aside) Sometimes it's better to use CREATE TABLE than SELECT * FROM read_csv
This is a bit off-topic, but DuckDB allows direct reading with SELECT * FROM read_csv(...).
However, I found that creating a table with CREATE TABLE has its own advantages.
Pros
- If you output the
CREATE TABLEstatement to console.log, you can copy and paste it for debugging withduckdb -uito reproduce the environment. This is especially useful for temporary queries like S3 signed URLs. - Since the table name is determined in advance, reusing queries becomes easier.
Cons
- It includes setup for tables you might not use, which can be problematic if you have many tables.
2. Convert results from Apache Arrow Table format to a Zod-typed state
DuckDB returns results in Apache Arrow format. This needs to be converted into a form that is easy to handle in JavaScript.
Apache Arrow data contains Proxy objects, so it cannot pass through Zod parsing as-is.
A somewhat tricky workaround is to use JSON.parse(JSON.stringify()). However, there are cases where bigint is included, so handle that with a replacer.
import * as arrow from 'apache-arrow'
export const parseArrowTable = (record: arrow.Table) => {
return record.toArray().map(t => {
return JSON.parse(
JSON.stringify(t, (_, value) => {
if (typeof value === "bigint") {
return Number(value)
}
return value
})
)
})
}
3. Writing the table name in SELECT instead of * makes it easy to structure the result
If you're used to MySQL, you might often write:
SELECT A.* FROM foo AS A
But by specifying the entire table:
SELECT A FROM foo AS A
the result comes back as a struct. As I'll explain later, this is convenient for adding types.
SELECT A,B FROM foo AS A JOIN baz AS B ON A.id = B.a_id
For a JOIN, it looks like this, returning in the form [{A: {...}, B: {...}}...].
Here's a concrete example:
SELECT company.*, line.* FROM company
JOIN line ON line.company_cd = company.company_cd
LIMIT 1
This would flatten to:
[
{
"company_cd": "3",
"rr_cd": "11",
"company_name": "JR東海",
"company_name_k": "ジェイアールトウカイ",
"company_name_h": "東海旅客鉄道株式会社",
"company_name_r": "JR東海",
"company_url": "http://jr-central.co.jp/",
"company_type": "1",
"e_status": "1",
"e_sort": "1001",
"line_cd": "1001",
"line_name": "中央新幹線",
"line_name_k": "チュウオウシンカンセン",
...
}
]
But if you write:
SELECT company, line FROM company JOIN line ON line.company_cd = company.company_cd LIMIT 1
the result becomes structured:
[
{
"company": {
"company_cd": "3",
"rr_cd": "11",
"company_name": "JR東海",
"company_name_k": "ジェイアールトウカイ",
"company_name_h": "東海旅客鉄道株式会社",
...
},
"line": {
"line_cd": "1001",
"company_cd": "3",
"line_name": "中央新幹線",
"line_name_k": "チュウオウシンカンセン",
"line_name_h": "中央新幹線",
...
}
}
]
4. Make it type-safe with Zod
Since we've stripped the Apache Arrow Table format in step 2, we can pass the data through Zod to achieve a reasonable level of type safety. You could keep it as Record<string, string> if you don't mind, but having the key names defined definitely improves the development experience.
Since we loaded the CSV with all_varchar=true, we can define a rough schema by setting all fields to z.string().nullable().
(I'm using Zod here, but you could use Valibot, ArkType, or any other library you prefer.)
export const StationSchema = z.record(z.enum([
"station_cd", "station_g_cd", "station_name", "station_name_k",
"station_name_r", "line_cd", "pref_cd", "post", "address",
"lon", "lat", "open_ymd", "close_ymd", "e_status", "e_sort"
] as const), z.string().nullable())
For the key names, you can extract them using something like:
const sample = await conn.query(`SELECT * FROM ${table} LIMIT 1;`)
console.log(r.toArray().map(t => Object.keys(t.toJSON()) ))
Even the results of JOINs can be received in a fairly simple way since we're receiving them as structs.
// SELECT station, line, company
// FROM station
// JOIN company ON station.company_cd = company.company_cd
// JOIN line ON line.line_cd = station.line_cd LIMIT 1
const resultSchema = z.object({
station: StationSchema,
company: CompanySchema,
line: LineSchema
})
Discussion