RobinBlomberg / kysely-codegen

Generate Kysely type definitions from your database.
MIT License
819 stars 73 forks source link

Configure introspect to make the date or timestamp a string type. #177

Closed tzezar closed 1 month ago

tzezar commented 4 months ago

Is it possible to configure to what type in this case date/timestamp is introspected to? I would love to work on strings instead eg. Timestamp type.

Upvote & Fund

Fund with Polar

RobinBlomberg commented 4 months ago

Which SQL dialect are you using? If the database driver supports inserting/updating with strings, then kysely-codegen should always support strings as well.

iffa commented 3 months ago

+1 on this, I'd love to throw away all usages of Date - we are using pg

lqmanh commented 3 months ago

I'm also encountering this issue. pg returns string for DATE and return Date object for TIMESTAMP

tzezar commented 3 months ago

I created script that fixes it by changing generated types. It allows to work with strings. Remember to change path! Run it after kysely-codegen script in package.json.

I fixed some bugs I found, fresh code is here: https://github.com/tzezar/kysely-codegen-timestamp-to-string-script

Mine looks like this: "database:push": "npm run database:generate:migration && npm run database:migrate && npm run database:generate:types && node src/utils/kysely-codegen-replace-date-to-string.js"

// kysely-codegen-replace-date-to-string.js 

import fs from 'fs';
import path from 'path';
import { fileURLToPath } from 'url';

// Get the current directory name
const __filename = fileURLToPath(import.meta.url);
const __dirname = path.dirname(__filename);

// Specify the file path you want to modify
const filePath = path.join(__dirname, '../database/kysely-codegen-types.ts');

// Function to replace "Date" with "string"
const replaceDateInFile = (file) => {
  fs.readFile(file, 'utf8', (err, data) => {
    if (err) {
      console.error(`Error reading file: ${err}`);
      return;
    }

    // Replace "Date" with "string"
    const updatedData = data.replace(/Date/g, 'string');

    // Write the updated content back to the file
    fs.writeFile(file, updatedData, 'utf8', (err) => {
      if (err) {
        console.error(`Error writing file: ${err}`);
      } else {
        console.log('File updated successfully.');
      }
    });
  });
};

// Run the function
replaceDateInFile(filePath);
RobinBlomberg commented 1 month ago

Should be fixed now in kysely-codegen@0.17.0!