Built-in Field Types
Before we move to the next Ent API calls, let's talk about the Ent field types that are natively supported in Ent Framework:
{ type: String }
string
varchar, text, bigint, numeric, ...
{ type: ID }
string
varchar, text, bigint, ...
{ type: Number }
number
int, bigint, doube, ...
{ type: Date }
Date
timestamptz, timestamp
{ type: Boolean }
boolean
boolean
{ type: Enum<"a" | "b">() }
"a" | "b"
varchar, text, ...
{ type: Enum<42 | 101>() }
42 | 101
integer, ...
{ type: Enum<MyEnum>() }
MyEnum
varchar, text, integer, ...
{ type: YourCustomType }
jsonc, bytea or anything else
You can also define custom field types: Custom Field Types
Fields may be nullable and optional, with the corresponding support from TypeScript side.
Nullability and optionality concepts are often times mixed up. In Ent Framework, they are independent on each other and are used for different use cases.
Nullability: allowNull=true
By default, all fields can't store a null
TypeScript value. To allow storing of a null, use the allowNull
syntax:
Notice that if your field is nullable, it doesn't mean that it is optional. Nullability and optionality are independent concepts in both Ent Framework and TypeScript. E.g. you can have a required nullable field which allows saving null
in it, but you will still need to explicitly pass this null
in your TypeScript code:
By default, each field in the schema is required at insert time. I.e. if you run an insert*()
call, then TypeScript won't let you skip a required field.
Optionality: autoInsert="..."
To make a field optional, you can use autoInsert="sql expression"
modifier: it makes the field optional at insert time. Ent Framework will use the raw SQL expression provided if you don't mention an explicit field value on an insert (which is convenient when doing refactoring for instance).
Several examples:
Notice that now company_id
field is both optional and nullable. I.e. you can run this code:
An example of optional, but non-nullable field is created_at
. I.e. you can omit this field when inserting (and thus, Ent Framework will use now()
SQL expression for its value), but you can't pass a null
TypeScript value there, and your topic.created_at
will be of type Date
, not Date | null
or Date | undefined
.
autoUpdate
There is also one more way to mark the field as optional, use autoUpdate
modifier. It is very similar to autoInsert
, but additionally, if the value is omitted at an update*()
call, then it will be automatically set to the result of the provided SQL expression. A classical use case for it is updated_at
field:
Last updated
Was this helpful?