diff --git a/libs/prisma-models/src/model.rs b/libs/prisma-models/src/model.rs index ee49820968f3..07dca61c5d9d 100644 --- a/libs/prisma-models/src/model.rs +++ b/libs/prisma-models/src/model.rs @@ -51,7 +51,11 @@ impl ModelTemplate { self.id_field_names, ); - let indexes = self.indexes.into_iter().map(|i| i.build(&fields.all)).collect(); + let indexes = self + .indexes + .into_iter() + .map(|i| i.build(&fields.all)) + .collect(); // The model is created here and fields WILL BE UNSET before now! model.fields.set(fields).unwrap(); diff --git a/query-engine/prisma/src/cli.rs b/query-engine/prisma/src/cli.rs index 3690088ff08d..1ad3893dbd0e 100644 --- a/query-engine/prisma/src/cli.rs +++ b/query-engine/prisma/src/cli.rs @@ -1,34 +1,45 @@ +use crate::{ + configuration, + context::PrismaContext, + dmmf, + error::PrismaError, + request_handlers::{graphql::*, PrismaRequest, RequestHandler}, + PrismaResult, {CliOpt, PrismaOpt, Subcommand}, +}; +use prisma_models::DatamodelConverter; use query_core::{ schema::{QuerySchemaRef, SupportedCapabilities}, BuildMode, QuerySchemaBuilder, }; -use std::collections::HashMap; -use std::{convert::TryFrom, fs::File, io::Read, sync::Arc}; - -use crate::context::PrismaContext; -use crate::error::PrismaError; -use crate::request_handlers::{graphql::*, PrismaRequest, RequestHandler}; -use crate::{ - data_model_loader::{load_configuration, load_data_model_components}, - dmmf, PrismaResult, -}; -use crate::{CliOpt, PrismaOpt, Subcommand}; +use std::{collections::HashMap, convert::TryFrom, sync::Arc}; +#[derive(Debug)] pub struct ExecuteRequest { + legacy: bool, query: String, + datamodel: String, force_transactions: bool, enable_raw_queries: bool, - legacy: bool, + overwrite_datasources: Option, } +#[derive(Debug)] pub struct DmmfRequest { + datamodel: String, build_mode: BuildMode, enable_raw_queries: bool, + overwrite_datasources: Option, +} + +#[derive(Debug)] +pub struct GetConfigRequest { + datamodel: String, + overwrite_datasources: Option, } pub enum CliCommand { Dmmf(DmmfRequest), - GetConfig(String), + GetConfig(GetConfigRequest), ExecuteRequest(ExecuteRequest), } @@ -36,11 +47,18 @@ impl TryFrom<&PrismaOpt> for CliCommand { type Error = PrismaError; fn try_from(opts: &PrismaOpt) -> crate::PrismaResult { - match opts.subcommand { - None => Err(PrismaError::InvocationError(String::from( - "cli subcommand not present", - ))), - Some(Subcommand::Cli(ref cliopts)) => match cliopts { + let subcommand = opts.subcommand.clone().ok_or_else(|| { + PrismaError::InvocationError(String::from("cli subcommand not present")) + })?; + + let datamodel = opts + .datamodel + .clone() + .xor(opts.datamodel_path.clone()) + .expect("Datamodel should be provided either as path or base64-encoded string."); + + match subcommand { + Subcommand::Cli(ref cliopts) => match cliopts { CliOpt::Dmmf => { let build_mode = if opts.legacy { BuildMode::Legacy @@ -49,23 +67,23 @@ impl TryFrom<&PrismaOpt> for CliCommand { }; Ok(CliCommand::Dmmf(DmmfRequest { + datamodel, build_mode, enable_raw_queries: opts.enable_raw_queries, + overwrite_datasources: opts.overwrite_datasources.clone(), })) } - CliOpt::GetConfig(input) => { - let mut file = File::open(&input.path).expect("File should open read only"); - let mut datamodel = String::new(); - - file.read_to_string(&mut datamodel) - .expect("Couldn't read file"); - Ok(CliCommand::GetConfig(datamodel)) - } + CliOpt::GetConfig => Ok(CliCommand::GetConfig(GetConfigRequest { + datamodel, + overwrite_datasources: opts.overwrite_datasources.clone(), + })), CliOpt::ExecuteRequest(input) => Ok(CliCommand::ExecuteRequest(ExecuteRequest { query: input.query.clone(), force_transactions: opts.always_force_transactions, + overwrite_datasources: opts.overwrite_datasources.clone(), enable_raw_queries: opts.enable_raw_queries, legacy: input.legacy, + datamodel, })), }, } @@ -76,13 +94,16 @@ impl CliCommand { pub async fn execute(self) -> PrismaResult<()> { match self { CliCommand::Dmmf(request) => Self::dmmf(request), - CliCommand::GetConfig(input) => Self::get_config(input), + CliCommand::GetConfig(input) => { + Self::get_config(input.datamodel, input.overwrite_datasources) + } CliCommand::ExecuteRequest(request) => Self::execute_request(request).await, } } fn dmmf(request: DmmfRequest) -> PrismaResult<()> { - let (v2components, template) = load_data_model_components(true)?; + let dm = datamodel::parse_datamodel(&request.datamodel)?; + let template = DatamodelConverter::convert(&dm); // temporary code duplication let internal_data_model = template.build("".into()); @@ -97,7 +118,7 @@ impl CliCommand { let query_schema: QuerySchemaRef = Arc::new(schema_builder.build()); - let dmmf = dmmf::render_dmmf(&v2components.datamodel, query_schema); + let dmmf = dmmf::render_dmmf(&dm, query_schema); let serialized = serde_json::to_string_pretty(&dmmf)?; println!("{}", serialized); @@ -105,8 +126,8 @@ impl CliCommand { Ok(()) } - fn get_config(input: String) -> PrismaResult<()> { - let config = load_configuration(&input, false)?; + fn get_config(datamodel: String, overwrite_datasources: Option) -> PrismaResult<()> { + let config = configuration::load(&datamodel, overwrite_datasources, false)?; let json = datamodel::json::mcf::config_to_mcf_json_value(&config); let serialized = serde_json::to_string(&json)?; @@ -119,10 +140,11 @@ impl CliCommand { let decoded = base64::decode(&request.query)?; let decoded_request = String::from_utf8(decoded)?; - let ctx = PrismaContext::builder() + let ctx = PrismaContext::builder(request.datamodel) .legacy(request.legacy) .force_transactions(request.force_transactions) .enable_raw_queries(request.enable_raw_queries) + .overwrite_datasources(request.overwrite_datasources) .build() .await?; diff --git a/query-engine/prisma/src/configuration.rs b/query-engine/prisma/src/configuration.rs new file mode 100644 index 000000000000..89b3cb85ff5a --- /dev/null +++ b/query-engine/prisma/src/configuration.rs @@ -0,0 +1,50 @@ +use crate::{PrismaError, PrismaResult}; +use serde::Deserialize; +use serde_json; + +/// Loads data model components for the v2 data model. +/// The v2 data model is provided either as file (PRISMA_DML_PATH) or as string in the env (PRISMA_DML). +/// Attempts to construct a Prisma v2 datamodel. +/// Returns: DatamodelV2Components +/// Err If a source for v2 was found, but conversion failed. +/// Ok(Some) If a source for v2 was found, and the conversion suceeded. +/// Ok(None) If no source for a v2 data model was found. +pub fn load( + dml_string: &str, + datasource_overwrites: Option, + ignore_env_var_errors: bool, +) -> PrismaResult { + let config_result = if ignore_env_var_errors { + datamodel::parse_configuration_and_ignore_env_errors(&dml_string) + } else { + datamodel::parse_configuration(&dml_string) + }; + + match config_result { + Err(errors) => Err(PrismaError::ConversionError(errors, dml_string.to_string())), + Ok(mut configuration) => { + if let Some(overwrites) = datasource_overwrites { + let datasource_overwrites: Vec = serde_json::from_str(&overwrites)?; + + for datasource_override in datasource_overwrites { + for datasource in &mut configuration.datasources { + if &datasource_override.name == datasource.name() { + debug!( + "overwriting datasource {} with url {}", + &datasource_override.name, &datasource_override.url + ); + datasource.set_url(&datasource_override.url); + } + } + } + } + Ok(configuration) + } + } +} + +#[derive(Deserialize)] +struct SourceOverride { + name: String, + url: String, +} diff --git a/query-engine/prisma/src/context.rs b/query-engine/prisma/src/context.rs index 8c1c66ae3324..dd5e99f55824 100644 --- a/query-engine/prisma/src/context.rs +++ b/query-engine/prisma/src/context.rs @@ -1,9 +1,10 @@ -use crate::{data_model_loader::*, exec_loader, PrismaError, PrismaResult}; +use crate::{configuration, exec_loader, PrismaError, PrismaResult}; use query_core::{ schema::{QuerySchemaRef, SupportedCapabilities}, BuildMode, QueryExecutor, QuerySchemaBuilder, }; // use prisma_models::InternalDataModelRef; +use datamodel::Datamodel; use prisma_models::DatamodelConverter; use std::sync::Arc; @@ -16,7 +17,7 @@ pub struct PrismaContext { query_schema: QuerySchemaRef, /// DML-based v2 datamodel. - dm: datamodel::Datamodel, + dm: Datamodel, /// Central query executor. pub executor: Box, @@ -26,7 +27,8 @@ pub struct ContextBuilder { legacy: bool, force_transactions: bool, enable_raw_queries: bool, - datamodel: Option, + datamodel: String, + overwrite_datasources: Option, } impl ContextBuilder { @@ -45,9 +47,8 @@ impl ContextBuilder { self } - #[cfg(test)] - pub fn datamodel(mut self, val: String) -> Self { - self.datamodel = Some(val); + pub fn overwrite_datasources(mut self, val: Option) -> Self { + self.overwrite_datasources = val; self } @@ -57,6 +58,7 @@ impl ContextBuilder { self.force_transactions, self.enable_raw_queries, self.datamodel, + self.overwrite_datasources, ) .await } @@ -72,37 +74,18 @@ impl PrismaContext { legacy: bool, force_transactions: bool, enable_raw_queries: bool, - datamodel: Option, + datamodel: String, + overwrite_datasources: Option, ) -> PrismaResult { - // Load data model in order of precedence. - let (v2components, template) = match datamodel { - Some(datamodel_string) => { - let dm = datamodel::parse_datamodel(&datamodel_string)?; - - let components = load_configuration(&datamodel_string, false).map(|config| { - DatamodelV2Components { - datamodel: dm, - data_sources: config.datasources, - } - })?; - - let template = DatamodelConverter::convert(&components.datamodel); - - (components, template) - } - None => load_data_model_components(false)?, - }; - - let (dm, data_sources) = (v2components.datamodel, v2components.data_sources); + let dm = datamodel::parse_datamodel(&datamodel)?; + let config = configuration::load(&datamodel, overwrite_datasources, false)?; + let template = DatamodelConverter::convert(&dm); // We only support one data source at the moment, so take the first one (default not exposed yet). - let data_source = if data_sources.is_empty() { - return Err(PrismaError::ConfigurationError( - "No valid data source found".into(), - )); - } else { - data_sources.first().unwrap() - }; + let data_source = config + .datasources + .first() + .ok_or_else(|| PrismaError::ConfigurationError("No valid data source found".into()))?; // Load executor let (db_name, executor) = exec_loader::load(&**data_source, force_transactions).await?; @@ -116,6 +99,7 @@ impl PrismaContext { } else { BuildMode::Modern }; + let capabilities = SupportedCapabilities::empty(); // todo connector capabilities. let schema_builder = QuerySchemaBuilder::new( @@ -128,19 +112,19 @@ impl PrismaContext { let query_schema: QuerySchemaRef = Arc::new(schema_builder.build()); Ok(Self { - // internal_data_model, query_schema, dm, executor, }) } - pub fn builder() -> ContextBuilder { + pub fn builder(datamodel: String) -> ContextBuilder { ContextBuilder { legacy: false, force_transactions: false, enable_raw_queries: false, - datamodel: None, + overwrite_datasources: None, + datamodel, } } @@ -148,7 +132,7 @@ impl PrismaContext { &self.query_schema } - pub fn datamodel(&self) -> &datamodel::Datamodel { + pub fn datamodel(&self) -> &Datamodel { &self.dm } diff --git a/query-engine/prisma/src/data_model_loader.rs b/query-engine/prisma/src/data_model_loader.rs deleted file mode 100644 index 1ae5e0f8f620..000000000000 --- a/query-engine/prisma/src/data_model_loader.rs +++ /dev/null @@ -1,223 +0,0 @@ -use std::{fs::File, io::Read}; - -use serde::Deserialize; -use serde_json; - -use datamodel::{Datamodel, Source}; -use prisma_models::{DatamodelConverter, InternalDataModelTemplate}; - -use crate::{utilities, PrismaError, PrismaResult}; - -/// Wrapper type to unclutter the interface -pub struct DatamodelV2Components { - pub datamodel: Datamodel, - pub data_sources: Vec>, -} - -/// Private helper trait for operations on PrismaResult>. -/// PrismaResult> expresses 3 states: -/// - [Ok(Some)] Existing. -/// - [Ok(None)] Not existing / not set. -/// - [Err] Existing, but processing error. -/// -/// Err cases abort chaining, the other allow for further chaining. -trait PrismaResultOption { - fn inner_map(self, f: F) -> PrismaResult> - where - F: Fn(T) -> PrismaResult>; - - fn inner_or_else(self, f: F) -> PrismaResult> - where - F: Fn() -> PrismaResult>; - - fn on_success(self, f: F) -> PrismaResult> - where - F: Fn() -> (); -} - -impl PrismaResultOption for PrismaResult> { - fn inner_map(self, f: F) -> PrismaResult> - where - F: Fn(T) -> PrismaResult>, - { - match self? { - None => Ok(None), - Some(x) => f(x), - } - } - - fn inner_or_else(self, f: F) -> PrismaResult> - where - F: Fn() -> PrismaResult>, - { - match self? { - None => f(), - x => Ok(x), - } - } - - fn on_success(self, f: F) -> PrismaResult> - where - F: Fn() -> (), - { - self.inner_map(|x| { - f(); - Ok(Some(x)) - }) - } -} - -/// Loads data model components for the v2 data model. -/// The v2 data model is provided either as file (PRISMA_DML_PATH) or as string in the env (PRISMA_DML). -pub fn load_data_model_components( - ignore_env_var_errors: bool, -) -> PrismaResult<(DatamodelV2Components, InternalDataModelTemplate)> { - // Load data model in order of precedence. - match load_datamodel_v2(ignore_env_var_errors)? { - Some(v2components) => { - let template = DatamodelConverter::convert(&v2components.datamodel); - Ok((v2components, template)) - } - None => { - return Err(PrismaError::ConfigurationError( - "Unable to load data model v2 from any source.".into(), - )) - } - } -} - -/// Attempts to construct a Prisma v2 datamodel. -/// Returns: DatamodelV2Components -/// Err If a source for v2 was found, but conversion failed. -/// Ok(Some) If a source for v2 was found, and the conversion suceeded. -/// Ok(None) If no source for a v2 data model was found. -fn load_datamodel_v2(ignore_env_var_errors: bool) -> PrismaResult> { - debug!("Trying to load v2 data model..."); - - load_v2_dml_string().inner_map(|dml_string| { - let dml = if ignore_env_var_errors { - datamodel::parse_datamodel_and_ignore_env_errors(&dml_string) - } else { - datamodel::parse_datamodel(&dml_string) - }; - match dml { - Err(errors) => Err(PrismaError::ConversionError(errors, dml_string.clone())), - Ok(dm) => load_configuration(&dml_string, ignore_env_var_errors).map(|configuration| { - debug!("Loaded Prisma v2 data model."); - Some(DatamodelV2Components { - datamodel: dm, - data_sources: configuration.datasources, - }) - }), - } - }) -} - -pub fn load_configuration( - dml_string: &str, - ignore_env_var_errors: bool, -) -> PrismaResult { - let datasource_overwrites_string = - load_string_from_env("OVERWRITE_DATASOURCES")?.unwrap_or_else(|| r#"[]"#.to_string()); - let datasource_overwrites: Vec = - serde_json::from_str(&datasource_overwrites_string)?; - - let config_result = if ignore_env_var_errors { - datamodel::parse_configuration_and_ignore_env_errors(&dml_string) - } else { - datamodel::parse_configuration(&dml_string) - }; - match config_result { - Err(errors) => Err(PrismaError::ConversionError(errors, dml_string.to_string())), - Ok(mut configuration) => { - for datasource_override in datasource_overwrites { - for datasource in &mut configuration.datasources { - if &datasource_override.name == datasource.name() { - debug!( - "overwriting datasource {} with url {}", - &datasource_override.name, &datasource_override.url - ); - datasource.set_url(&datasource_override.url); - } - } - } - Ok(configuration) - } - } -} - -#[derive(Deserialize)] -struct SourceOverride { - name: String, - url: String, -} - -/// Attempts to load a Prisma DML (datamodel v2) string from either env or file. -/// Env has precedence over file. -fn load_v2_dml_string() -> PrismaResult> { - load_v2_string_from_env().inner_or_else(load_v2_dml_from_file) -} - -/// Attempts to load a Prisma DML (datamodel v2) string from env. -fn load_v2_string_from_env() -> PrismaResult> { - debug!("Trying to load Prisma v2 DML from env..."); - load_string_from_env("PRISMA_DML").on_success(|| debug!("Loaded Prisma v2 DML from env.")) -} - -/// Attempts to load a Prisma DML (datamodel v2) string from file. -fn load_v2_dml_from_file() -> PrismaResult> { - debug!("Trying to load Prisma v2 Datamodel from file..."); - load_from_file("PRISMA_DML_PATH").on_success(|| debug!("Loaded Prisma v2 DML from file.")) -} - -/// Attempts to load a string from given env var. -/// The contents of the env var can be base64 encoded if necessary (decoding will be attempted). -/// Returns: Env var contents as string. -/// Err If the env var was found, the contents were base64 encoded, but loading the base64 into a UTF-8 string failed. -/// Ok(Some) If the env var was found (if it was encoded, it was also decoded successfully). -/// Ok(None) If the env var was not found. -fn load_string_from_env(env_var: &str) -> PrismaResult> { - match utilities::get_env(env_var).ok() { - Some(string) => match base64::decode(&string) { - Ok(bytes) => match String::from_utf8(bytes) { - Ok(result) => { - trace!("Successfully decoded {} from Base64.", env_var); - Ok(Some(result)) - } - Err(err) => { - trace!( - "Error decoding {} from Base64 (invalid UTF-8): {:?}", - env_var, - err - ); - Err(PrismaError::ConfigurationError("Invalid Base64".into())) - } - }, - Err(e) => { - trace!("Decoding Base64 failed (might not be encoded): {:?}", e); - Ok(Some(string)) - } - }, - None => Ok(None), - } -} - -/// Attempts to load a string from a file pointed to by given env var. -/// Returns: File contents as string. -/// Err If the env var was found, but loading the file failed. -/// Ok(Some) If the env var was found and the file was successfully read. -/// Ok(None) If the env var was not found. -fn load_from_file(env_var: &str) -> PrismaResult> { - match utilities::get_env(env_var).ok() { - Some(path) => { - let mut f = File::open(&path)?; - let mut sdl = String::new(); - - f.read_to_string(&mut sdl)?; - trace!("Successfully loaded contents of {}", path); - - Ok(Some(sdl)) - } - None => Ok(None), - } -} diff --git a/query-engine/prisma/src/main.rs b/query-engine/prisma/src/main.rs index fd225e9d3668..eb1e445832d2 100644 --- a/query-engine/prisma/src/main.rs +++ b/query-engine/prisma/src/main.rs @@ -3,22 +3,22 @@ extern crate log; #[macro_use] extern crate rust_embed; -use std::{convert::TryFrom, error::Error, net::SocketAddr, process}; - -use structopt::StructOpt; -use tracing::subscriber; -use tracing_log::LogTracer; -use tracing_subscriber::{EnvFilter, FmtSubscriber}; - use cli::*; use error::*; use once_cell::sync::Lazy; use request_handlers::{PrismaRequest, PrismaResponse, RequestHandler}; use server::HttpServer; +use std::{ + convert::TryFrom, error::Error, ffi::OsStr, fs::File, io::Read, net::SocketAddr, process, +}; +use structopt::StructOpt; +use tracing::subscriber; +use tracing_log::LogTracer; +use tracing_subscriber::{EnvFilter, FmtSubscriber}; mod cli; +mod configuration; mod context; -mod data_model_loader; mod dmmf; mod error; mod exec_loader; @@ -26,7 +26,6 @@ mod request_handlers; mod server; #[cfg(test)] mod tests; -mod utilities; #[derive(Debug, Clone, PartialEq, Copy)] pub enum LogFormat { @@ -59,11 +58,6 @@ pub struct DmmfToDmlInput { pub path: String, } -#[derive(Debug, Clone, StructOpt)] -pub struct GetConfigInput { - pub path: String, -} - #[derive(Debug, Clone, StructOpt)] pub struct ExecuteRequestInput { /// GraphQL query to execute @@ -78,11 +72,35 @@ pub enum CliOpt { /// Output the DMMF from the loaded data model. Dmmf, /// Get the configuration from the given data model. - GetConfig(GetConfigInput), + GetConfig, /// Executes one request and then terminates. ExecuteRequest(ExecuteRequestInput), } +pub fn parse_base64_string(s: &str) -> PrismaResult { + match base64::decode(s) { + Ok(bytes) => String::from_utf8(bytes).map_err(|e| { + trace!("Error decoding {} from Base64 (invalid UTF-8): {:?}", s, e); + + PrismaError::ConfigurationError("Invalid Base64".into()) + }), + Err(e) => { + trace!("Decoding Base64 failed (might not be encoded): {:?}", e); + Ok(String::from(s)) + } + } +} + +pub fn load_datamodel_file(path: &OsStr) -> String { + let mut f = File::open(path).expect(&format!("Could not open datamodel file {:?}", path)); + let mut datamodel = String::new(); + + f.read_to_string(&mut datamodel) + .expect(&format!("Could not read datamodel file: {:?}", path)); + + datamodel +} + #[derive(Debug, StructOpt, Clone)] #[structopt(version = env!("GIT_HASH"))] pub struct PrismaOpt { @@ -92,6 +110,15 @@ pub struct PrismaOpt { /// The port the query engine should bind to. #[structopt(long, short, env, default_value = "4466")] port: u16, + /// Path to the Prisma datamodel file + #[structopt(long, env = "PRISMA_DML_PATH", parse(from_os_str = load_datamodel_file))] + datamodel_path: Option, + /// Base64 encoded Prisma datamodel + #[structopt(long, env = "PRISMA_DML", parse(try_from_str = parse_base64_string))] + datamodel: Option, + /// Base64 encoded datasources, overwriting the ones in the datamodel + #[structopt(long, env, parse(try_from_str = parse_base64_string))] + overwrite_datasources: Option, /// Switches query schema generation to Prisma 1 compatible mode. #[structopt(long, short)] legacy: bool, @@ -129,8 +156,14 @@ async fn main() -> Result<(), AnyError> { eprintln!("Printing to stderr for debugging"); eprintln!("Listening on {}:{}", opts.host, opts.port); - let builder = HttpServer::builder() + let datamodel = opts + .datamodel + .xor(opts.datamodel_path) + .expect("Datamodel should be provided either as path or base64-encoded string."); + + let builder = HttpServer::builder(datamodel) .legacy(opts.legacy) + .overwrite_datasources(opts.overwrite_datasources) .enable_raw_queries(opts.enable_raw_queries) .enable_playground(opts.enable_playground) .force_transactions(opts.always_force_transactions); diff --git a/query-engine/prisma/src/server.rs b/query-engine/prisma/src/server.rs index 787699781635..0400bcf393d6 100644 --- a/query-engine/prisma/src/server.rs +++ b/query-engine/prisma/src/server.rs @@ -32,10 +32,12 @@ impl RequestContext { } pub struct HttpServerBuilder { + datamodel: String, legacy_mode: bool, force_transactions: bool, enable_raw_queries: bool, enable_playground: bool, + overwrite_datasources: Option, } impl HttpServerBuilder { @@ -59,11 +61,17 @@ impl HttpServerBuilder { self } + pub fn overwrite_datasources(mut self, val: Option) -> Self { + self.overwrite_datasources = val; + self + } + pub async fn build_and_run(self, address: SocketAddr) -> PrismaResult<()> { - let ctx = PrismaContext::builder() + let ctx = PrismaContext::builder(self.datamodel) .legacy(self.legacy_mode) .force_transactions(self.force_transactions) .enable_raw_queries(self.enable_raw_queries) + .overwrite_datasources(self.overwrite_datasources) .build() .await?; @@ -74,12 +82,14 @@ impl HttpServerBuilder { pub struct HttpServer; impl HttpServer { - pub fn builder() -> HttpServerBuilder { + pub fn builder(datamodel: String) -> HttpServerBuilder { HttpServerBuilder { + datamodel, legacy_mode: false, force_transactions: false, enable_raw_queries: false, enable_playground: false, + overwrite_datasources: None, } } diff --git a/query-engine/prisma/src/tests/dmmf.rs b/query-engine/prisma/src/tests/dmmf.rs index b25686b3ded6..10d5e20fdfda 100644 --- a/query-engine/prisma/src/tests/dmmf.rs +++ b/query-engine/prisma/src/tests/dmmf.rs @@ -1,4 +1,4 @@ -use crate::data_model_loader; +use prisma_models::DatamodelConverter; use query_core::{BuildMode, QuerySchema, QuerySchemaBuilder, SupportedCapabilities}; use serial_test::serial; use std::sync::Arc; @@ -97,9 +97,8 @@ fn must_not_fail_on_missing_env_vars_in_a_datasource() { } fn get_query_schema(datamodel_string: &str) -> (QuerySchema, datamodel::dml::Datamodel) { - // this env var is read by the data_model_loader - std::env::set_var("PRISMA_DML", datamodel_string); - let (dm, internal_dm_template) = data_model_loader::load_data_model_components(true).unwrap(); + let dm = datamodel::parse_datamodel_and_ignore_env_errors(datamodel_string).unwrap(); + let internal_dm_template = DatamodelConverter::convert(&dm); let internal_ref = internal_dm_template.build("db".to_owned()); let supported_capabilities = SupportedCapabilities::empty(); ( @@ -110,6 +109,6 @@ fn get_query_schema(datamodel_string: &str) -> (QuerySchema, datamodel::dml::Dat false, ) .build(), - dm.datamodel, + dm, ) } diff --git a/query-engine/prisma/src/tests/test_api.rs b/query-engine/prisma/src/tests/test_api.rs index 74a1e9f62881..77cd5416cca0 100644 --- a/query-engine/prisma/src/tests/test_api.rs +++ b/query-engine/prisma/src/tests/test_api.rs @@ -78,9 +78,8 @@ impl TestApi { self.migration_api.apply_migration(&apply_input).await?; - let context = PrismaContext::builder() + let context = PrismaContext::builder(datamodel_string) .enable_raw_queries(true) - .datamodel(datamodel_string) .force_transactions(self.is_pgbouncer) .build() .await diff --git a/query-engine/prisma/src/tests/type_mappings/test_api.rs b/query-engine/prisma/src/tests/type_mappings/test_api.rs index 457263dfacb6..5f90cdc67fd2 100644 --- a/query-engine/prisma/src/tests/type_mappings/test_api.rs +++ b/query-engine/prisma/src/tests/type_mappings/test_api.rs @@ -40,9 +40,8 @@ impl TestApi { .await .map_err(|err| anyhow::anyhow!("{:?}", err.data))?; - let context = PrismaContext::builder() + let context = PrismaContext::builder(schema.clone()) .enable_raw_queries(true) - .datamodel(schema.clone()) .force_transactions(self.is_pgbouncer) .build() .await diff --git a/query-engine/prisma/src/utilities.rs b/query-engine/prisma/src/utilities.rs deleted file mode 100644 index f9cb46fd7982..000000000000 --- a/query-engine/prisma/src/utilities.rs +++ /dev/null @@ -1,11 +0,0 @@ -use crate::{error::PrismaError, PrismaResult}; -use std::env; - -pub fn get_env(key: &str) -> PrismaResult { - env::var(key).map_err(|_| { - PrismaError::ConfigurationError(format!( - "Environment variable {} required but not found", - key - )) - }) -}