Bogdanp/deta

Documentation request: default field values

Closed this issue · 2 comments

The field-definition arg includes the line:

(id default) field-type

There isn't really documentation for this (except perhaps a note about virtual entities -- ?). I was hoping I could say something like (id "gen_random_uuid()") uuid/f or even (id uuid-string), but those don't seem to work.

After playing around for a bit, I think the way it works is:

  • There's no way to specify a Postgres DEFAULT value/expression
  • You can optionally specify a literal constant for the default (for deta only, of course)
  • It doesn't have to match the ID type (e.g., you can use #f to signify "not set yet")
  • If you specify a field default, you don't need to specify a value when calling make-<entity> (but you can, in which case that value takes precedence)
  • To get a default for your field (through deta only), use #:pre-persist-hook (but be sure to have it check for the default-default value, because you don't want to change the ID of an already-persisted entity)

Is this roughly correct? I'm not sure the "right" way to do this. I kind of hope I'm missing something and it's simpler, or could be made simpler. Thanks!

I've gone ahead and updated the docs to explain some of this. Your understanding is mostly right, except the default value can be any expression, not just a literal, so this works too:

> (require buid)
> (define-schema foo
    ([(id (buid)) string/f]))
> (make-foo)
(foo #<meta> "0CWEihX3SbkProXicEA4Q9")
> (make-foo)
(foo #<meta> "0CWEnZq7J9V7VXfbmdFCGX")

Ah! I didn't try putting it in parens, because I assumed it would evaluate it only once. That's a much better solution, thanks.