ZModel Language Reference
Overview​
ZModel, the modeling DSL of ZenStack, is the main concept you'll deal with when using this toolkit. The ZModel syntax is a superset of Prisma Schema. Therefore, every valid Prisma schema is a valid ZModel.
We made that choice to extend the Prisma schema for several reasons:
-
Creating a new ORM adds little value to the community. Instead, extending Prisma - the overall best ORM toolkit for Typescript - sounds more sensible.
-
Prisma's schema language is simple and intuitive.
-
Extending an existing popular language lowers the learning curve compared to inventing a new one.
However, the standard capability of Prisma schema doesn't allow us to build the functionalities we want in a natural way, so we made a few extensions to the language by adding the following:
- Custom attributes
- Custom attribute functions
- Built-in attributes and functions for defining access policies
- Built-in attributes for defining field validation rules
- Utility attributes like
@passwordand@omit - Multi-schema files support
Some of these extensions have been asked for by the Prisma community for some time, so we hope that ZenStack can be helpful even just as an extensible version of Prisma.
This section provides detailed descriptions of all aspects of the ZModel language, so you don't have to jump over to Prisma's documentation for extra learning.
Import​
ZModel allows to import other ZModel files. This is useful when you want to split your schema into multiple files for better organization. Under the hood, it will recursively merge all the imported schemas, and generate a single Prisma schema file for the Prisma CLI to consume.
Syntax​
import [IMPORT_SPECIFICATION]
-
[IMPORT_SPECIFICATION]: Path to the ZModel file to be imported. It can be:
- An absolute path, e.g., "/path/to/user".
- A relative path, e.g., "./user".
- A module resolved to an installed NPM package, e.g., "my-package/base".
If the import specification doesn't end with ".zmodel", the resolver will automatically append it. Once a file is imported, all the declarations in that file will be included in the building process.
Examples​
// there is a file called "user.zmodel" in the same directory
import "user"
Data source​
Every model needs to include exactly one datasource declaration, providing information on how to connect to the underlying database.
Syntax​
datasource [NAME] {
provider = [PROVIDER]
url = [DB_URL]
}
-
[NAME]:
Name of the data source. Needs to be a valid identifier matching regular expression
[A-Za-z][a-za-z0-9_]\*. Name is only informational and serves no other purposes. -
[PROVIDER]:
Name of database connector. Valid values:
- sqlite
- postgresql
- mysql
- sqlserver
- cockroachdb
-
[DB_URL]:
Database connection string. Either a plain string or an invocation of
envfunction to fetch from an environment variable.
Examples​
datasource db {
provider = "postgresql"
url = "postgresql://postgres:abc123@localhost:5432/todo?schema=public"
}
It's highly recommended that you not commit sensitive database connection strings into source control. Alternatively, you can load it from an environment variable:
datasource db {
provider = "postgresql"
url = env("DATABASE_URL")
}
Supported databases​
ZenStack uses Prisma to talk to databases, so all relational databases supported by Prisma are also supported by ZenStack.
Here's a list for your reference:
| Database | Version |
|---|---|
| PostgreSQL | 9.6 |
| PostgreSQL | 10 |
| PostgreSQL | 11 |
| PostgreSQL | 12 |
| PostgreSQL | 13 |
| PostgreSQL | 14 |
| PostgreSQL | 15 |
| MySQL | 5.6 |
| MySQL | 5.7 |
| MySQL | 8 |
| MariaDB | 10 |
| SQLite | * |
| AWS Aurora | * |
| AWS Aurora Serverless | * |
| Microsoft SQL Server | 2022 |
| Microsoft SQL Server | 2019 |
| Microsoft SQL Server | 2017 |
| Azure SQL | * |
| CockroachDB | 21.2.4+ |
You can find the orignal list here.
Generator​
Generators are used for creating assets (usually code) from a Prisma schema. Check here for a list of official and community generators.
Syntax​
generator [GENERATOR_NAME] {
[OPTION]*
}
-
[GENERATOR_NAME]
Name of the generator. Needs to be unique in the entire model. Needs to be a valid identifier matching regular expression
[A-Za-z][a-za-z0-9_]\*. -
[OPTION]
A generator configuration option, in form of "[NAME] = [VALUE]". A generator needs to have at least a "provider" option that specify its provider.
Example​
generator client {
provider = "prisma-client-js"
output = "./generated/prisma-client-js"
Plugin​
Plugins are ZenStack's extensibility mechanism. It's usage is similar to Generator. Users can define their own plugins to generate artifacts from the ZModel schema. Plugins differ from generators mainly in the following ways:
- They have a cleaner interface without the complexity of JSON-RPC.
- They use an easier-to-program AST representation than generators.
- They have access to language features that ZenStack adds to Prisma, like custom attributes and functions.
Syntax​
plugin [PLUGIN_NAME] {
[OPTION]*
}
-
[PLUGIN_NAME]
Name of the plugin. Needs to be unique in the entire model. Needs to be a valid identifier matching regular expression
[A-Za-z][a-za-z0-9_]\*. -
[OPTION]
A plugin configuration option, in form of "[NAME] = [VALUE]". A plugin needs to have at least a "provider" option that specify its provider.
Example​
plugin swr {
provider = '@zenstackhq/swr'
output = 'lib/hooks'
}
Enum​
Enums are container declarations for grouping constant identifiers. You can use them to express concepts like user roles, product categories, etc.
Syntax​
enum [ENUM_NAME] {
[FIELD]*
}
-
[ENUM_NAME]
Name of the enum. Needs to be unique in the entire model. Needs to be a valid identifier matching regular expression
[A-Za-z][a-za-z0-9_]\*. -
[FIELD]
Field identifier. Needs to be unique in the model. Needs to be a valid identifier matching regular expression
[A-Za-z][a-za-z0-9_]\*.
Example​
enum UserRole {
USER
ADMIN
}
Model​
Models represent the business entities of your application. A model inherits all fields and attributes from extended abstract models. Abstract models are eliminated in the generated prisma schema file.
Syntax​
(abstract)? model [NAME] (extends [ABSTRACT_MODEL_NAME](,[ABSTRACT_MODEL_NAME])*)? {
[FIELD]*
}
-
[abstract]:
Optional. If present, the model is marked as abstract would not be mapped to a database table. Abstract models are only used as base classes for other models.
-
[NAME]:
Name of the model. Needs to be unique in the entire model. Needs to be a valid identifier matching regular expression
[A-Za-z][a-za-z0-9_]\*. -
[FIELD]:
Arbitrary number of fields. See next section for details.
-
[ABSTRACT_MODEL_NAME]:
Name of an abstract model.
Note​
A model must include a field marked with @id attribute. The id field serves as a unique identifier for a model entity and is mapped to the database table's primary key.
See here for more details about attributes.
Example​
abstract model Basic {
id String @id
createdAt DateTime @default(now())
updatedAt DateTime @updatedAt
}
model User extends Basic {
name String
}
The generated prisma file only contains one User model:
model User {
id String @id
createdAt DateTime @default(now())
updatedAt DateTime @updatedAt
name String @id
}
Attribute​
Attributes decorate fields and models and attach extra behaviors or constraints to them.
Syntax​
Field attribute​
Field attribute name is prefixed by a single @.
id String @[ATTR_NAME](ARGS)?
- [ATTR_NAME]
Attribute name. See below for a full list of attributes.
- [ARGS]
See attribute arguments.
Model attribute​
Field attribute name is prefixed double @@.
model Model {
@@[ATTR_NAME](ARGS)?
}
- [ATTR_NAME]
Attribute name. See below for a full list of attributes.
- [ARGS]
See attribute arguments.
Arguments​
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. 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])
}
Attribute functions​
Attribute functions are used for providing values for attribute arguments, e.g., current DateTime, an autoincrement Int, etc. They can be used in place of attribute arguments, like:
model Model {
...
serial Int @default(autoincrement())
createdAt DateTime @default(now())
}
You can find a list of predefined attribute functions here.