I have a database that has some temporal tables. I have zod schemas for those tables and I am using those zod schemas to define the tables in Kysely. The schemas can be as follows:
CREATE TABLE temporal (
version_id SERIAL PRIMARY KEY,
some_id TEXT,
some_data TEXT,
valid_from TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP,
valid_to TIMESTAMP DEFAULT NULL,
is_current BOOLEAN NOT NULL DEFAULT TRUE
);
const TemporalTableSchema = z.object({
versionId: z.number(),
someId: z.string(),
someData: z.string(),
validFrom: z.coerce.date(),
validTo: z.coerce.date().optional().nullable(),
isCurrent: z.boolean()
})
type TemporalTableSchema = z.infer<typeof TemporalTableSchema>
Now if I want to insert into a such table I would never pass the version id, is_current or the timestamps myself (I have a trigger to update the valid_to and is_current fields when needed). So how can I do this with Kysely?
If I create my Kysely instance using the type from the zod schema Kysely is complaining that the insert is missing some required fields. This is what I would like to do somehow:
const db = new Kysely<{ temporal: TemporalTableSchema }>(someConfig)
await db.insertInto('temporal').values({
someId: someData.id,
someData: someData.data,
})
however, here Kysely would complain as it sees that for example versionId field is required based on the zod schema. Then on the other hand when querying data I would like to be able to validate and parse the returned data with the given schema and now all those fields should be in the data
// Here I want all the fields including the values from the autogenerated fields
const result = await db.selectFrom('temporal').selectAll()
So is there a way to tell Kysely that when inserting we don't need all the fields from a schema? I wouldn't want to mark all those fields optional as it would be annoying to do all kind of checks when using the data after it is queried from the db.
.values()method doc: You must provide all fields you haven't explicitly marked as nullable or optional usingGeneratedorColumnType. I'm not sure if you can just wrap the zod methodsversion_id: Generated<z.number()>