wwwouter / typed-knex

A TypeScript wrapper for Knex.js
MIT License
113 stars 13 forks source link

On update ? #18

Closed ghost closed 4 years ago

ghost commented 4 years ago

Issue type:

[x] Question [ ] Bug report [ ] Feature request [ ] Documentation issue

Database system/driver:

[ ] Postgres [ ] MSSQL [x] MySQL [x] MariaDB [ ] SQLite3 [ ] Oracle [ ] Amazon Redshift

typed-knex version:

[x] latest [ ] @next [ ] 0.x.x (or put your version here)

Knex.js version: last ?

Hi ! I don't know if it possible but I have a need. I need to update updated_at's timestamp each time my table is modified.

But, I would be compatible with mysql, mariadb and sqlite3. So 'ON UPDATE ...' doesn't work with sqlite3.

For example, my migration :

export async function up(knex: Knex): Promise<void> {
  await knex.schema.createTable(tableName, (table) => {
    table.uuid('id').notNullable().primary();
    table.string('firstname').notNullable();
    table.string('lastname').notNullable();
    table.string('email').notNullable().unique();
    table.date('birthdate').notNullable();
    table.string('gender', 1).notNullable();
    table.boolean('active').notNullable();
    table.boolean('termsofuse').notNullable();
    table.timestamps(true, true);
  });
}

Do you have any idea, maybe with flags, how to update my table ? Is typed-knex is the good solution ?

I think I will move from objectionJS to typed-knex !

Thanks for you work !

wwwouter commented 4 years ago

Hi, I've been using https://github.com/wwwouter/typed-knex#registerBeforeInsertTransform and https://github.com/wwwouter/typed-knex#registerBeforeUpdateTransform for this use case. As long as every update and insert in done through typed-knex, this works perfect. I've used this with Postgres and SQLite.

It wasn't documented yet, but it is now 😄

ghost commented 4 years ago

Thanks ! It's what I was looking for !

ghost commented 4 years ago

I have a suggestion to do. Theses functions are used to be executed each time a request is done ?

Is it a good idea to implement en function directly into the model, for example : _onUpdate(), _onInsert(), and typedKnex will check if it exsists et execute this function ? It maybe better to handle some case ?

What do you think ?

wwwouter commented 4 years ago

It would be a bit easier to use, but I'd like to keep the table mapping as simple as possible and nothing more than a table mapping.

ghost commented 4 years ago

Okay, you're right. Thanks you for you work, it's very useful !