Skip to content

Separate

Separate Setting

Reason for separation

There will be times when you want to use different objects when you SELECT from mysql and when you do an INSERT. For example, suppose you have an id column. You want it to be not nullable for select, but nullable for insert. This is used in such a case.

Configuration file

const options = {
separate: {
isSeparate: true,
insertPrefix: "insert",
insertSuffix: "",
},
};
module.exports = options;

declared

  • isSeparate - Whether to separate the file (default: false)
  • insertPrefix - Prefix for insert (default: “insert”)
  • insertSuffix - Suffix for insert (default: "")

If there is no need to separate the schema for Select and Insert, leave it false or omit separate from options.

prefix

A string to be prepended to the schema and type name. (Default is Insert)

suffix

A string to be given after the schema and type name. (Default is an empty string)

example

CREATE TABLE `todo` (
`id` int NOT NULL AUTO_INCREMENT,
`task` varchar(255) NOT NULL,
`completed` tinyint(1) NOT NULL DEFAULT '0',
`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
export const todoSchema = z.object({
id: z.number(),
task: z.string(),
completed: z.number(),
created_at: z.date().nullish(),
updated_at: z.date().nullish(),
});
export type Todo = z.infer<typeof todoSchema>;
export const insertTodoSchema = z.object({
id: z.number().nullish(), // <- nullable!
task: z.string(),
completed: z.number(),
created_at: z.date().nullish(),
updated_at: z.date().nullish(),
});
export type InsertTodo = z.infer<typeof insertTodoSchema>;

Usage

const selectObj:Todo = {
id: 1,
task: "task",
completed: 0,
created_at: new Date(),
updated_at: new Date(),
};
const insertObj:InsertTodo = {
task: "task",
completed: 0,
};

This option allows you to create an object without an id when you want to do an INSERT using knex.