edgedb / edgedb-js

The official TypeScript/JS client library and query builder for EdgeDB
https://edgedb.com
Apache License 2.0
511 stars 65 forks source link

Is there a way of generating nanoids through the ESDL file? #1010

Open psygo opened 5 months ago

psygo commented 5 months ago

I would like to have an extra, short nanoid for one of my tables. How do I do that? Is it possible to do it through the .esdl file?

On Drizzle, for example, I do something like this:

import { nanoid } from "nanoid"

...

nanoId: varchar("nano_id", { length: 256 })
  .unique()
  .notNull()
  .$defaultFn(() => nanoid()),

That's TypeScript, but there are PostgreSQL implementations of it, like viascom/nanoid-postgres.

Anyway, my question is not about nanoid specifically, but about how to do a custom ID.

scotttrinh commented 5 months ago

nanoid is just a string at the type level, right? We don't expose a way to create random types at the database level (it would need to be something implemented like the pg extension), but you absolutely can create one in your data layer that inserts objects. Rough sketch:

function createFoo(data) {
  return e.insert(e.Foo, {
    nano_id: nanoid(),
    ...data,
  }).run(client);
}

Making this a generic helper is left as an exercise for the reader 😅 I'd probably just have some function that inserts a nanoid at a default (overridable) key in a source object to abstract out the nanoid insertion. Or really, I'd just do it inline in the places I want them.

It's on our medium-term radar to add some higher level wrappers for doing more generic/abstract things that go beyond just mapping EdgeQL to TypeScript, and we'd probably want to have some similar thing affordance within that context in the future.

psygo commented 5 months ago

Thank you for the quick response!

It's just that I find Drizzle's option of setting up custom functions from TypeScript incredibly practical, and it helps cleaning up the code quite a bit to setup defaults like that.

kelbyfaessler commented 3 months ago

+1 to everything in this thread.

When I was using drizzle, I used $defaultFn(() => nanoid() in the same way, and also similarly wish I could define something similar via either the .esdl file or a custom configuration to the typescript client.

Looks like there is a postgres extension for this https://github.com/viascom/nanoid-postgres

And it looks like the question has been asked to other postgres providers as well https://community.neon.tech/t/extension-request-nanoid/1092