The psl-core crate provides the core functionality for parsing, validating, and working with Prisma schema files. It transforms PSL text into a validated internal representation.
Overview
This library is the foundation of all Prisma tooling that works with schema files. It parses .prisma files, validates them, and provides a rich API for working with models, fields, relations, and configuration.
Installation
[dependencies]
psl-core = "0.1.0"
Core Functions
validate
Parse and validate a Prisma schema file.
pub fn validate(
file: SourceFile,
connectors: ConnectorRegistry<'_>,
extension_types: &dyn ExtensionTypes,
) -> ValidatedSchema
The schema file source to parse
connectors
ConnectorRegistry
required
Registry of available database connectors
extension_types
&dyn ExtensionTypes
required
Extension types for custom type validation
Contains the validated schema, configuration, and diagnostics
validate_multi_file
Parse and validate multiple Prisma schema files.
pub fn validate_multi_file(
files: &[(String, SourceFile)],
connectors: ConnectorRegistry<'_>,
extension_types: &dyn ExtensionTypes,
) -> ValidatedSchema
files
&[(String, SourceFile)]
required
List of (filename, source) pairs to parse
parse_configuration
Parse only the configuration blocks (datasource, generator) from a schema.
pub fn parse_configuration(
schema: &str,
connectors: ConnectorRegistry<'_>,
) -> Result<Configuration, Diagnostics>
The schema string to parse
Contains datasources and generators configuration
Reformat a Prisma schema file.
pub fn reformat(
schema: &str,
indent_width: usize,
) -> Result<String, String>
The schema string to reformat
Number of spaces per indentation level
The reformatted schema string
Core Types
ValidatedSchema
The result of validating a Prisma schema.
pub struct ValidatedSchema {
pub configuration: Configuration,
pub db: ParserDatabase,
pub connector: &'static dyn Connector,
pub diagnostics: Diagnostics,
}
Parsed datasources and generators
The parsed and validated schema database
The active database connector
Errors and warnings from parsing/validation
Methods
impl ValidatedSchema {
pub fn relation_mode(&self) -> RelationMode
pub fn render_own_diagnostics(&self) -> String
}
Configuration
Configuration blocks from the schema.
pub struct Configuration {
pub generators: Vec<Generator>,
pub datasources: Vec<Datasource>,
pub warnings: Vec<String>,
}
List of datasource blocks
Datasource
Represents a datasource block in the schema.
pub struct Datasource {
pub name: String,
pub provider: String,
pub active_provider: &'static str,
pub documentation: Option<String>,
pub active_connector: &'static dyn Connector,
pub relation_mode: Option<RelationMode>,
pub namespaces: Vec<(String, Span)>,
}
The datasource name (e.g., “db”)
The provider string from the schema
The resolved active provider name
The connector implementation for this datasource
Explicit relation mode (foreignKeys or prisma)
Database schemas/namespaces (for multi-schema support)
Methods
impl Datasource {
pub fn capabilities(&self) -> ConnectorCapabilities
pub fn relation_mode(&self) -> RelationMode
pub fn provider_defined(&self) -> bool
pub fn schemas_defined(&self) -> bool
}
Generator
Represents a generator block in the schema.
pub struct Generator {
pub name: String,
pub provider: StringFromEnvVar,
pub output: Option<StringFromEnvVar>,
pub config: HashMap<String, GeneratorConfigValue>,
pub documentation: Option<String>,
pub preview_features: Option<BitFlags<PreviewFeature>>,
}
The generator provider (can reference env var)
Output path for generated code
preview_features
Option<BitFlags<PreviewFeature>>
Enabled preview features
PreviewFeature
Enum of available preview features.
pub enum PreviewFeature {
FullTextSearch,
FullTextIndex,
Metrics,
MultiSchema,
Views,
// ... and more
}
Parser Database
The ParserDatabase provides access to the parsed schema:
use psl::parser_database::ParserDatabase;
let db: &ParserDatabase = &validated_schema.db;
// Walk models
for model in db.walk_models() {
println!("Model: {}", model.name());
for field in model.scalar_fields() {
println!(" Field: {} ({})", field.name(), field.field_type());
}
}
Connector Registry
Built-in connectors are available:
use psl::builtin_connectors::BUILTIN_CONNECTORS;
let schema = psl::validate(
source_file,
BUILTIN_CONNECTORS,
&extension_types,
);
Feature Flags
Database-specific features:
[features]
postgresql = []
sqlite = []
mysql = []
cockroachdb = ["postgresql"]
mssql = []
mongodb = []
Dependencies
Key dependencies:
diagnostics - Error and warning reporting
parser-database - Internal database representation
schema-ast - Abstract syntax tree types
prisma-value - Prisma value types
serde - Serialization support
regex - Regular expression support
Re-exports
Commonly used types are re-exported:
pub use diagnostics;
pub use parser_database::{self, coerce, coerce_array, generators, is_reserved_type_name};
pub use schema_ast;
Examples
Parsing a Schema
use psl::{SourceFile, validate, builtin_connectors::BUILTIN_CONNECTORS};
use std::sync::Arc;
let schema = r#"
datasource db {
provider = "postgresql"
}
model User {
id Int @id @default(autoincrement())
email String @unique
name String?
}
"#;
let source = SourceFile::new_allocated(Arc::from(schema.into()));
let validated = validate(source, BUILTIN_CONNECTORS, &());
if validated.diagnostics.has_errors() {
eprintln!("Errors: {}", validated.render_own_diagnostics());
} else {
println!("Schema is valid!");
// Access models
for model in validated.db.walk_models() {
println!("Found model: {}", model.name());
}
}
Parsing Configuration Only
use psl::{parse_configuration, builtin_connectors::BUILTIN_CONNECTORS};
let schema = r#"
datasource db {
provider = "postgresql"
}
generator client {
provider = "prisma-client-js"
previewFeatures = ["multiSchema"]
}
"#;
match parse_configuration(schema, BUILTIN_CONNECTORS) {
Ok(config) => {
println!("Found {} datasources", config.datasources.len());
println!("Found {} generators", config.generators.len());
for ds in &config.datasources {
println!("Datasource '{}': provider={}", ds.name, ds.provider);
}
}
Err(diagnostics) => {
eprintln!("Configuration errors: {:#?}", diagnostics);
}
}
Multi-file Schema
use psl::{SourceFile, validate_multi_file, builtin_connectors::BUILTIN_CONNECTORS};
use std::sync::Arc;
let files = vec![
(
"schema.prisma".to_string(),
SourceFile::new_allocated(Arc::from("datasource db { provider = \"postgresql\" }".into())),
),
(
"models.prisma".to_string(),
SourceFile::new_allocated(Arc::from("model User { id Int @id }".into())),
),
];
let validated = validate_multi_file(&files, BUILTIN_CONNECTORS, &());
println!("Validated multi-file schema");
use psl::reformat;
let messy_schema = r#"
model User{
id Int @id
email String
}
"#;
match reformat(messy_schema, 2) {
Ok(formatted) => println!("Formatted:\n{}", formatted),
Err(e) => eprintln!("Format error: {}", e),
}