Skip to content

Commit

Permalink
Merge branch 'main' into feat/d1-compatible-sqlite-migration
Browse files Browse the repository at this point in the history
  • Loading branch information
jkomyno committed Apr 12, 2024
2 parents 3a5827e + 6d35870 commit 61ede41
Show file tree
Hide file tree
Showing 139 changed files with 2,244 additions and 710 deletions.
2 changes: 1 addition & 1 deletion .github/workflows/test-query-engine-driver-adapters.yml
Expand Up @@ -70,7 +70,7 @@ jobs:
node-version: ${{ matrix.node_version }}

- name: "Setup pnpm"
uses: pnpm/action-setup@v2
uses: pnpm/action-setup@v3.0.0
with:
version: 8

Expand Down
2 changes: 1 addition & 1 deletion .github/workflows/wasm-benchmarks.yml
Expand Up @@ -30,7 +30,7 @@ jobs:
uses: actions/setup-node@v4

- name: "Setup pnpm"
uses: pnpm/action-setup@v2
uses: pnpm/action-setup@v3.0.0
with:
version: 8

Expand Down
6 changes: 4 additions & 2 deletions Cargo.lock

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

33 changes: 22 additions & 11 deletions prisma-fmt/src/code_actions.rs
Expand Up @@ -31,8 +31,13 @@ pub(crate) fn available_actions(schema: String, params: CodeActionParams) -> Vec

let datasource = config.datasources.first();

for source in validated_schema.db.ast().sources() {
relation_mode::edit_referential_integrity(&mut actions, &params, validated_schema.db.source(), source)
for source in validated_schema.db.ast_assert_single().sources() {
relation_mode::edit_referential_integrity(
&mut actions,
&params,
validated_schema.db.source_assert_single(),
source,
)
}

// models AND views
Expand All @@ -45,21 +50,27 @@ pub(crate) fn available_actions(schema: String, params: CodeActionParams) -> Vec
multi_schema::add_schema_block_attribute_model(
&mut actions,
&params,
validated_schema.db.source(),
validated_schema.db.source_assert_single(),
config,
model,
);

multi_schema::add_schema_to_schemas(&mut actions, &params, validated_schema.db.source(), config, model);
multi_schema::add_schema_to_schemas(
&mut actions,
&params,
validated_schema.db.source_assert_single(),
config,
model,
);
}

if matches!(datasource, Some(ds) if ds.active_provider == "mongodb") {
mongodb::add_at_map_for_id(&mut actions, &params, validated_schema.db.source(), model);
mongodb::add_at_map_for_id(&mut actions, &params, validated_schema.db.source_assert_single(), model);

mongodb::add_native_for_auto_id(
&mut actions,
&params,
validated_schema.db.source(),
validated_schema.db.source_assert_single(),
model,
datasource.unwrap(),
);
Expand All @@ -71,7 +82,7 @@ pub(crate) fn available_actions(schema: String, params: CodeActionParams) -> Vec
multi_schema::add_schema_block_attribute_enum(
&mut actions,
&params,
validated_schema.db.source(),
validated_schema.db.source_assert_single(),
config,
enumerator,
)
Expand All @@ -88,15 +99,15 @@ pub(crate) fn available_actions(schema: String, params: CodeActionParams) -> Vec
relations::add_referenced_side_unique(
&mut actions,
&params,
validated_schema.db.source(),
validated_schema.db.source_assert_single(),
complete_relation,
);

if relation.is_one_to_one() {
relations::add_referencing_side_unique(
&mut actions,
&params,
validated_schema.db.source(),
validated_schema.db.source_assert_single(),
complete_relation,
);
}
Expand All @@ -105,7 +116,7 @@ pub(crate) fn available_actions(schema: String, params: CodeActionParams) -> Vec
relations::add_index_for_relation_fields(
&mut actions,
&params,
validated_schema.db.source(),
validated_schema.db.source_assert_single(),
complete_relation.referencing_field(),
);
}
Expand All @@ -114,7 +125,7 @@ pub(crate) fn available_actions(schema: String, params: CodeActionParams) -> Vec
relation_mode::replace_set_default_mysql(
&mut actions,
&params,
validated_schema.db.source(),
validated_schema.db.source_assert_single(),
complete_relation,
config,
)
Expand Down
5 changes: 2 additions & 3 deletions prisma-fmt/src/code_actions/multi_schema.rs
Expand Up @@ -142,13 +142,12 @@ pub(super) fn add_schema_to_schemas(
formatted_attribute,
true,
// todo: update spans so that we can just append to the end of the _inside_ of the array. Instead of needing to re-append the `]` or taking the span end -1
Span::new(span.start, span.end - 1),
Span::new(span.start, span.end - 1, psl::parser_database::FileId::ZERO),
params,
)
}
None => {
let has_properties = datasource.provider_defined()
|| datasource.url_defined()
let has_properties = datasource.provider_defined() | datasource.url_defined()
|| datasource.direct_url_defined()
|| datasource.shadow_url_defined()
|| datasource.relation_mode_defined()
Expand Down
49 changes: 29 additions & 20 deletions prisma-fmt/src/get_config.rs
@@ -1,14 +1,14 @@
use psl::Diagnostics;
use psl::{Diagnostics, ValidatedSchema};
use serde::Deserialize;
use serde_json::json;
use std::collections::HashMap;

use crate::validate::SCHEMA_PARSER_ERROR_CODE;
use crate::{schema_file_input::SchemaFileInput, validate::SCHEMA_PARSER_ERROR_CODE};

#[derive(Deserialize, Debug)]
#[serde(rename_all = "camelCase")]
struct GetConfigParams {
prisma_schema: String,
prisma_schema: SchemaFileInput,
#[serde(default)]
ignore_env_var_errors: bool,
#[serde(default)]
Expand Down Expand Up @@ -43,29 +43,38 @@ pub(crate) fn get_config(params: &str) -> Result<String, String> {
}

fn get_config_impl(params: GetConfigParams) -> Result<serde_json::Value, GetConfigError> {
let wrap_get_config_err = |errors: Diagnostics| -> GetConfigError {
use std::fmt::Write as _;

let mut full_error = errors.to_pretty_string("schema.prisma", &params.prisma_schema);
write!(full_error, "\nValidation Error Count: {}", errors.errors().len()).unwrap();

GetConfigError {
// this mirrors user_facing_errors::common::SchemaParserError
error_code: Some(SCHEMA_PARSER_ERROR_CODE),
message: full_error,
}
};

let mut config = psl::parse_configuration(&params.prisma_schema).map_err(wrap_get_config_err)?;
let mut schema = psl::validate_multi_file(params.prisma_schema.into());
if schema.diagnostics.has_errors() {
return Err(create_get_config_error(&schema, &schema.diagnostics));
}

if !params.ignore_env_var_errors {
let overrides: Vec<(_, _)> = params.datasource_overrides.into_iter().collect();
config
schema
.configuration
.resolve_datasource_urls_prisma_fmt(&overrides, |key| params.env.get(key).map(String::from))
.map_err(wrap_get_config_err)?;
.map_err(|diagnostics| create_get_config_error(&schema, &diagnostics))?;
}

Ok(psl::get_config(&config))
Ok(psl::get_config(&schema.configuration))
}

fn create_get_config_error(schema: &ValidatedSchema, diagnostics: &Diagnostics) -> GetConfigError {
use std::fmt::Write as _;

let mut rendered_diagnostics = schema.render_diagnostics(diagnostics);
write!(
rendered_diagnostics,
"\nValidation Error Count: {}",
diagnostics.errors().len()
)
.unwrap();

GetConfigError {
// this mirrors user_facing_errors::common::SchemaParserError
error_code: Some(SCHEMA_PARSER_ERROR_CODE),
message: rendered_diagnostics,
}
}

#[cfg(test)]
Expand Down
47 changes: 44 additions & 3 deletions prisma-fmt/src/get_dmmf.rs

Large diffs are not rendered by default.

49 changes: 41 additions & 8 deletions prisma-fmt/src/lib.rs
Expand Up @@ -3,14 +3,17 @@ mod code_actions;
mod get_config;
mod get_dmmf;
mod lint;
mod merge_schemas;
mod native;
mod preview;
mod schema_file_input;
mod text_document_completion;
mod validate;

use log::*;
use lsp_types::{Position, Range};
use psl::parser_database::ast;
use schema_file_input::SchemaFileInput;

/// The API is modelled on an LSP [completion
/// request](https://github.com/microsoft/language-server-protocol/blob/gh-pages/_specifications/specification-3-16.md#textDocument_completion).
Expand Down Expand Up @@ -43,27 +46,49 @@ pub fn code_actions(schema: String, params: &str) -> String {
}

/// The two parameters are:
/// - The Prisma schema to reformat, as a string.
/// - The [`SchemaFileInput`] to reformat, as a string.
/// - An LSP
/// [DocumentFormattingParams](https://github.com/microsoft/language-server-protocol/blob/gh-pages/_specifications/specification-3-16.md#textDocument_formatting) object, as JSON.
///
/// The function returns the formatted schema, as a string.
/// If the schema or any of the provided parameters is invalid, the function returns the original schema.
/// This function never panics.
///
/// Of the DocumentFormattingParams, we only take into account tabSize, at the moment.
pub fn format(schema: &str, params: &str) -> String {
pub fn format(datamodel: String, params: &str) -> String {
let schema: SchemaFileInput = match serde_json::from_str(&datamodel) {
Ok(params) => params,
Err(_) => {
return datamodel;
}
};

let params: lsp_types::DocumentFormattingParams = match serde_json::from_str(params) {
Ok(params) => params,
Err(err) => {
warn!("Error parsing DocumentFormattingParams params: {}", err);
return schema.to_owned();
Err(_) => {
return datamodel;
}
};

psl::reformat(schema, params.options.tab_size as usize).unwrap_or_else(|| schema.to_owned())
let indent_width = params.options.tab_size as usize;

match schema {
SchemaFileInput::Single(single) => psl::reformat(&single, indent_width).unwrap_or(datamodel),
SchemaFileInput::Multiple(multiple) => {
let result = psl::reformat_multiple(multiple, indent_width);
serde_json::to_string(&result).unwrap_or(datamodel)
}
}
}

pub fn lint(schema: String) -> String {
lint::run(&schema)
let schema: SchemaFileInput = match serde_json::from_str(&schema) {
Ok(params) => params,
Err(serde_err) => {
panic!("Failed to deserialize SchemaFileInput: {serde_err}");
}
};
lint::run(schema)
}

/// Function that throws a human-friendly error message when the schema is invalid, following the JSON formatting
Expand All @@ -89,6 +114,14 @@ pub fn validate(validate_params: String) -> Result<(), String> {
validate::validate(&validate_params)
}

/// Given a list of Prisma schema files (and their locations), returns the merged schema.
/// This is useful for `@prisma/client` generation, where the client needs a single - potentially large - schema,
/// while still allowing the user to split their schema copies into multiple files.
/// Internally, it uses `[validate]`.
pub fn merge_schemas(params: String) -> Result<String, String> {
merge_schemas::merge_schemas(&params)
}

pub fn native_types(schema: String) -> String {
native::run(&schema)
}
Expand Down Expand Up @@ -225,7 +258,7 @@ pub(crate) fn range_to_span(range: Range, document: &str) -> ast::Span {
let start = position_to_offset(&range.start, document).unwrap();
let end = position_to_offset(&range.end, document).unwrap();

ast::Span::new(start, end)
ast::Span::new(start, end, psl::parser_database::FileId::ZERO)
}

/// Gives the LSP position right after the given span.
Expand Down

0 comments on commit 61ede41

Please sign in to comment.