Skip to main content
Version: 3.0 Beta

Attribute

Attributes decorate fields and models and attach extra behaviors or constraints to them.

ZModel's standard library provides a set of predefined attributes, plugins can provide additional attributes, and you can also define your own attributes in the schema.

Syntax​

Field attribute​

Definition​

Field attribute name is prefixed by a single @.

attribute NAME(PARAMS)
  • NAME

    Attribute name. Field attribute's name must start with '@'.

  • PARAMS

    Attribute parameters. See Parameters for details.

Example:

attribute @id(map: String?, length: Int?)

Application​

id String ATTR_NAME(ARGS)?
  • ATTR_NAME

    Attribute name.

  • ARGS

    Argument list. See Parameters for details.

Example:

model User {
id Int @id(map: "_id")
}

Model attribute​

Definition​

Field attribute name is prefixed by double @@.

attribute @@NAME(PARAMS)
  • NAME

    Attribute name. Model attribute's name must start with '@@'.

  • PARAMS

    Attribute parameters. See Parameters for details.

Example:

attribute @@unique(_ fields: FieldReference[], name: String?, map: String?)

Application​

model Model {
ATTR_NAME(ARGS)?
}
  • ATTR_NAME

    Attribute name.

  • ARGS

    Argument list. See Parameters for details.

Example:

model User {
org String
userName String
@@unique([org, userName])
}

Parameters​

Attribute can be declared with a list of parameters and applied with a comma-separated list of arguments.

Arguments are mapped to parameters by position or by name. Parameter names prefixed with _ are positional and arguments for such parameters can be provided without their names. For example, for the @default attribute declared as:

attribute @default(_ value: ContextType)

, the following two ways of applying it are equivalent:

published Boolean @default(value: false)
published Boolean @default(false)

Parameter types​

Attribute parameters are typed. The following types are supported:

  • Int

    Integer literal can be passed as argument.

    E.g., declaration:

    attribute @password(saltLength: Int?, salt: String?)

    application:

    password String @password(saltLength: 10)
  • String

    String literal can be passed as argument.

    E.g., declaration:

    attribute @id(map: String?)

    application:

    id String @id(map: "_id")
  • Boolean

    Boolean literal or expression can be passed as argument.

    E.g., declaration:

    attribute @@allow(_ operation: String, _ condition: Boolean)

    application:

    @@allow("read", true)
    @@allow("update", auth() != null)
  • ContextType

    A special type that represents the type of the field onto which the attribute is attached.

    E.g., declaration:

    attribute @default(_ value: ContextType)

    application:

    f1 String @default("hello")
    f2 Int @default(1)
  • FieldReference

    References to fields defined in the current model.

    E.g., declaration:

    attribute @relation(
    _ name: String?,
    fields: FieldReference[]?,
    references: FieldReference[]?,
    onDelete: ReferentialAction?,
    onUpdate: ReferentialAction?,
    map: String?)

    application:

    model Model {
    ...
    // [ownerId] is a list of FieldReference
    owner Owner @relation(fields: [ownerId], references: [id])
    ownerId
    }
  • Enum

    Attribute parameter can also be typed as predefined enum.

    E.g., declaration:

    attribute @relation(
    _ name: String?,
    fields: FieldReference[]?,
    references: FieldReference[]?,
    // ReferentialAction is a predefined enum
    onDelete: ReferentialAction?,
    onUpdate: ReferentialAction?,
    map: String?)

    application:

    model Model {
    // 'Cascade' is a predefined enum value
    owner Owner @relation(..., onDelete: Cascade)
    }

An attribute parameter can be typed as any of the types above, a list of the above type, or an optional of the types above.

model Model {
...
f1 String
f2 String
// a list of FieldReference
@@unique([f1, f2])
}

Predefined attributes​

@@id​

attribute @@id(_ fields: FieldReference[], name: String?, map: String?)

Defines a multi-field ID (composite ID) on the model.

Params:

NameDescription
fieldsA list of fields defined in the current model
nameThe name that the Client API will expose for the argument covering all fields
mapThe name of the underlying primary key constraint in the database

@@unique​

attribute @@unique(_ fields: FieldReference[], name: String?, map: String?)

Defines a compound unique constraint for the specified fields.

Params:

NameDescription
fieldsA list of fields defined in the current model
nameThe name of the unique combination of fields
mapThe name of the underlying unique constraint in the database

@@index​

attribute @@index(_ fields: FieldReference[], map: String?)

Defines an index in the database.

Params:

NameDescription
fieldsA list of fields defined in the current model
mapThe name of the underlying index in the database

@@map​

attribute @@map(_ name: String)

Maps the schema model name to a table with a different name, or an enum name to a different underlying enum in the database.

Params:

NameDescription
nameThe name of the underlying table or enum in the database

@@ignore​

attribute @@ignore()

Exclude a model from the ORM Client.

@@auth​

attribute @@auth()

Specify the model for resolving auth() function call.

@@delegate​

attribute @@delegate(_ discriminator: FieldReference)

Marks a model to be a delegated base. Used for modeling a polymorphic hierarchy.

Params:

NameDescription
discriminatorA String or enum field in the same model used to store the name of the concrete model that inherit from this base model.

@@meta​

attribute @@meta(_ name: String, _ value: Any)

Adds arbitrary metadata to a model. The metadata can be accessed by custom plugins for code generation, or at runtime from the modelMeta object exported from @zenstackhq/runtime/model-meta. The value parameter can be an arbitrary literal expression, including object literals.

model User {
id Int @id
@@meta('description', 'This is a user model')
}

@id​

attribute @id(map: String?)

Defines an ID on the model.

Params:

NameDescription
mapThe name of the underlying primary key constraint in the database

@default​

attribute @default(_ value: ContextType)

Defines a default value for a field.

Params:

NameDescription
valueThe default value expression

@unique​

attribute @unique(map: String?)

Defines a unique constraint for this field.

Params:

NameDescription
mapThe name of the underlying primary key constraint in the database

@relation​

attribute @relation(
_ name: String?,
fields: FieldReference[]?,
references: FieldReference[]?,
onDelete: ReferentialAction?,
onUpdate: ReferentialAction?,
map: String?)

Defines meta information about a relation.

Params:

NameDescription
nameThe name of the relationship
fieldsA list of fields defined in the current model
referencesA list of fields of the model on the other side of the relation
onDeleteReferential action to take on delete. See details here.
onUpdateReferential action to take on update. See details here.

@map​

attribute @map(_ name: String)

Maps a field name or enum value from the schema to a column with a different name in the database.

Params:

NameDescription
mapThe name of the underlying column in the database

@updatedAt​

attribute @updatedAt()

Automatically stores the time when a record was last updated.

@ignore​

attribute @ignore()

Exclude a field from the ORM Client (so that the field is not included in the input and output of ORM queries).

@json​

attribute @json()

@meta​

attribute @meta(_ name: String, _ value: Any)

Adds arbitrary metadata to a field. The metadata can be accessed by custom plugins for code generation, or at runtime from the modelMeta object exported from @zenstackhq/runtime/model-meta. The value parameter can be an arbitrary literal expression, including object literals.

model User {
id Int @id
name String @meta(name: "description", value: "The name of the user")
}

Native type mapping attributes​

Native type mapping attributes are a special set of field attributes that allow you to specify the native database type for a field. They are prefixed with @db..

Without native type mappings, ZModel types are by default mapped to the database types as follows:

ZModel TypeSQLite TypePostgreSQL Type
StringTEXTtext
BooleanINTEGERboolean
IntINTEGERinteger
BigIntINTEGERbigint
FloatREALdouble precision
DecimalDECIMALdecimal(65,30)
DateTimeNUMERICtimestamp(3)
JsonJSONBjsonb
BytesBLOBbytea

The following native type mapping attributes can be used to override the default mapping:

AttributeZModel TypeSQLite TypePostgreSQL Type
@db.TextString-text
@db.Char(x)String-char(x)
@db.VarChar(x)String-varchar(x)
@db.Bit(x)String Boolean Bytes-bit(x)
@db.VarBitString-varbit
@db.UuidString-uuid
@db.XmlString-xml
@db.InetString-inet
@db.CitextString-citext
@db.BooleanBoolean-boolean
@db.IntInt-serial serial4
@db.IntegerInt-integer int,int4
@db.SmallIntInt-smallint int2
@db.OidInt-oid
@db.BigIntBigInt-bigint int8
@db.DoublePrecisionFloat Decimal-double precision
@db.RealFloat Decimal-real
@db.DecimalFloat Decimal-decimal numeric
@db.MoneyFloat Decimal-money
@db.Timestamp(x)DateTime-timestamp(x)
@db.Timestamptz(x)DateTime-timestampz(x)
@db.DateDateTime-date
@db.Time(x)DateTime-time(x)
@db.TimetzDateTime-timez(x)
@db.JsonJson-json
@db.JsonBJson-jsonb
@db.ByteABytes-bytea
Comments
Feel free to ask questions, give feedback, or report issues.

Don't Spam


You can edit/delete your comments by going directly to the discussion, clicking on the 'comments' link below