Skip to content

Sync

sync Setting

Configuration file

const options = {
sync: {
active: true;
}
};
module.exports = options;

sync

  • active: If true, sync is performed; if false, sync is not performed. (default is false)

about sync

If sync’s active is true, sync is performed.
sync is a function to synchronize schema and MySQL.

From the SQL below, assume that the generated schema.ts already exists.

CREATE TABLE `my_todo_list` (
`id` int NOT NULL AUTO_INCREMENT,
`status` text CHARACTER SET utf8mb4 COLLATE utf8mb4_0900_ai_ci NOT NULL,
`task` varchar(255) NOT NULL,
`description` text,
`due_date` date DEFAULT NULL,
`created_at` timestamp NULL DEFAULT CURRENT_TIMESTAMP,
`updated_at` timestamp NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_0900_ai_ci

The following schema was generated based on it. However, assume that the status is manually changed to allow only undone, in_progress and done.

export const myTodoListSchema = z.object({
id: z.number(),
status: z.union([
z.literal("undone"),
z.literal("in_progress"),
z.literal("done"),
]), // changed manually
task: z.string(),
description: z.string().nullish(),
due_date: z.date().nullish(),
created_at: z.date().nullish(),
updated_at: z.date().nullish(),
});

After this you want to add columns to the table and generate a new schema.
At this time, if sync’s active is false, it will generate a completely new schema.
Therefore, the status will revert to z.string().

If sync is enabled, the already existing schema will remain in place.
If there are newly added columns, they will be added to the existing schema as follows

export const myTodoListSchema = z.object({
id: z.number(),
status: z.union([
z.literal("undone"),
z.literal("in_progress"),
z.literal("done"),
]),
task: z.string(),
description: z.string().nullish(),
due_date: z.date().nullish(),
created_at: z.date().nullish(),
updated_at: z.date().nullish(),
new_column: z.string().nullish(), // added column
});

By enabling sync, you can always keep the schema up-to-date.
As a precaution, any description in the schema.ts file will be deleted when the schema is regenerated. We recommend that you write your own schema, auxiliary functions, etc. in a separate file.