mysqlnode.jstypescriptdrizzle

how to create a SET data type with drizzle-orm


What happens is that I am working with drizzle-orm, and I need a table which has to have a Set type field.

This is the one I should save: ['mon', 'tue', 'wed', 'thur', 'fri', 'sat', 'sun']

Can somebody help me. I'm stuck with the mysql-core

drizzle-orm doesn't seem to have a type of data set for its models,

so I'm looking for a way to do it, perhaps using the custom data types that drizzle offers


Solution

  • I managed to solve the problem in the following way:

    I used the custom types of drizzle-orm,

    import { customType } from 'drizzle-orm/mysql-core';
    

    create a function 'customSet' which receives as a parameter the name that it will have in the table and the array of the elements that I want to use to form my set

    the function returns the function the customType function of drizzle-orm We can pass a configuration object as a parameter to the function, In the configuration we can execute a function to transform the data before saving it in the database and after obtaining it.

    dataType: we pass it a string that must be an SQL statement, in my case I tell it that I want to save a set of data in the SET(value1, value2, ...) format.

    toDriver - A function that converts input values into a string that will be sent to the "driver" or data access layer. Here, it appears to simply concatenate the values with commas.

    fromDriver - A function that converts data received from the "driver" back to a usable format.

    This 'customType' function is called with the 'name' provided as an argument, this makes the field name the one provided in "name"

      function customSet(name: string, values: string[]) {
          return customType<{ data: string[]; driverData: string }>({
            dataType: () => `SET(${values.map((value) => `'${value}'`).join(',')})`,
        toDriver: (inputValues) => `${inputValues.join(',')}`,
        fromDriver: (driverValues: string) => driverValues.replace(/{|}/g, '').split(','),
      })(name);
    }