andywer / squid

🦑 Provides SQL tagged template strings and schema definition functions.
MIT License
148 stars 7 forks source link

Benefits of `defineTable` over manual type definition #26

Closed jgonera closed 4 years ago

jgonera commented 4 years ago

Thanks for this library, I really like the simplicity of spread* functions. spreadInsert makes bulk inserts more straightforward than slonik's or pg-promise's approach.

I'm not sure I understand the benefit of using defineSchema when not using postguard though. It seems I can just define the types like this:

interface NewUserRecord {
  name: string;
}

interface UserRecord extends NewUserRecord {
  id: number;
}

instead of:

defineTable('users', {
  id: Schema.default(Schema.Number),
  name: Schema.String,
});

Is there anything I'm missing? If defineTable is only used by postguard maybe it should be a part of that library instead?

andywer commented 4 years ago

Hey @jgonera! Sorry for the delayed response…

Yes, I think you won't have any benefit from it right now, besides postguard. Originally I had the idea to also use this information at runtime, so you could run some assertions on your database on launch, á la "Is the data scheme of my database really what I expect it to be?"

Hasn't been implemented yet, though. Would you mind drafting a PR to update the docs to reflect that?

andywer commented 4 years ago

PS: There is one more benefit to using the Schema.* functions instead of just using plain TypeScript types / interfaces.

Schema.default() and Schema.nullable() allow columns to have different types for INSERTs vs. SELECT using TableRow<> and NewTableRow<>. Otherwise you would have to declare two interfaces for each table: The table record interface when INSERT-ing where certain columns are optional and a full interface that a SELECT * would return.