asg017 / sqlite-ulid

A SQLite extension for generating and working with ULIDs
Apache License 2.0
123 stars 6 forks source link

How to use ulid_with_prefix()? #5

Closed airblade closed 9 months ago

airblade commented 9 months ago

Hello!

I wasn't quite sure where to ask this question – hopefully this is the right place :)

I am using this extension with Rails via this mechanism so I can use ULIDs for my primary keys as described here.

It works perfectly when I use the plain ulid() function like this in a Rails database migration:

create_table :things, id: false do |t|
  t.primary_key :id, :string, default: -> { "ULID()" }
end

However I would like to have prefixed ULIDs, e.g. thing_01hcj2c9q1kfe2ny0z3957y18v. I tried to modify the migration like this:

create_table :things, id: false do |t|
  t.primary_key :id, :string, default: -> { "ULID_WITH_PREFIX('thing')" }
end

But this raised the error SQLite3::SQLException: invalid BLOB input to ulid().

Do you have any tips for fixing this please?

airblade commented 9 months ago

cc @fractaledmind :)

airblade commented 9 months ago

Oops, never mind, it works perfectly. I had a typo in the function name. Doh.

fractaledmind commented 9 months ago

Glad you got this sorted. You should write up your setup and share it. I'd love to read how you are using prefixed primary key ULIDs and what the experience has been like.

airblade commented 9 months ago
create_table :things, id: false do |t|
  t.primary_key :id, :string, default: -> { "ULID_WITH_PREFIX('thing')" }
  t.belongs_to :widget, null: false, foreign_key: true, type: :string
end

All in all, a straightforward and painless process :)

My only previous experience with prefixed IDs was using @excid's prefixed_ids gem on a Rails app with postgresql. That worked well, though it needs to inject code into your models, and your application code needs to be at least slightly aware of it, e.g. special finders.

Comparing the two approaches, I much prefer having the database, rather than the model, handle ID generation. My application code doesn't have to know anything about the models' IDs. It's much simpler. (And ULIDs seem at least as good as hashids, if not better, for my purposes.)