1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
use crate::{IdentifierType, ObjectType, OutputField};
use psl::{
    datamodel_connector::{Connector, ConnectorCapabilities, ConnectorCapability, RelationMode},
    PreviewFeature, PreviewFeatures,
};
use query_structure::{ast, InternalDataModel};
use std::{collections::HashMap, fmt};

#[derive(Clone, Debug, Hash, Eq, PartialEq)]
enum Operation {
    Query,
    Mutation,
}

type LazyField = Box<dyn for<'a> Fn(&'a QuerySchema) -> OutputField<'a> + Send + Sync>;

/// The query schema defines which operations (query/mutations) are possible on a database, based
/// on a Prisma schema.
///
/// Conceptually, a query schema stores two trees (query/mutation) that consist of input and output
/// types.
pub struct QuerySchema {
    /// Internal abstraction over the datamodel AST.
    pub internal_data_model: InternalDataModel,

    pub(crate) enable_raw_queries: bool,
    pub(crate) connector: &'static dyn Connector,

    /// Indexes query and mutation fields by their own query info for easier access.
    query_info_map: HashMap<(Operation, QueryInfo), usize>,
    root_fields: HashMap<(Operation, String), usize>,
    query_fields: Vec<LazyField>,
    mutation_fields: Vec<LazyField>,

    preview_features: PreviewFeatures,

    /// Relation mode in the datasource.
    relation_mode: RelationMode,
}

impl QuerySchema {
    pub(crate) fn new(
        enable_raw_queries: bool,
        connector: &'static dyn Connector,
        preview_features: PreviewFeatures,
        internal_data_model: InternalDataModel,
    ) -> Self {
        let relation_mode = internal_data_model.schema.relation_mode();

        let mut query_schema = QuerySchema {
            preview_features,
            enable_raw_queries,
            query_info_map: Default::default(),
            root_fields: Default::default(),
            internal_data_model,
            connector,
            relation_mode,
            mutation_fields: Default::default(),
            query_fields: Default::default(),
        };

        query_schema.query_fields = crate::build::query_type::query_fields(&query_schema);
        query_schema.mutation_fields = crate::build::mutation_type::mutation_fields(&query_schema);

        let mut query_info_map: HashMap<(Operation, QueryInfo), _> = HashMap::new();
        let mut root_fields = HashMap::new();

        for (idx, field_fn) in query_schema.query_fields.iter().enumerate() {
            let field = field_fn(&query_schema);
            if let Some(query_info) = field.query_info() {
                query_info_map.insert((Operation::Query, query_info.to_owned()), idx);
            }
            root_fields.insert((Operation::Query, field.name.into_owned()), idx);
        }

        for (idx, field_fn) in query_schema.mutation_fields.iter().enumerate() {
            let field = field_fn(&query_schema);
            if let Some(query_info) = field.query_info() {
                query_info_map.insert((Operation::Mutation, query_info.to_owned()), idx);
            }
            root_fields.insert((Operation::Mutation, field.name.into_owned()), idx);
        }

        query_schema.query_info_map = query_info_map;
        query_schema.root_fields = root_fields;
        query_schema
    }

    pub(crate) fn supports_any(&self, capabilities: &[ConnectorCapability]) -> bool {
        capabilities.iter().any(|c| self.connector.has_capability(*c))
    }

    pub(crate) fn can_full_text_search(&self) -> bool {
        self.has_feature(PreviewFeature::FullTextSearch)
            && (self.has_capability(ConnectorCapability::FullTextSearchWithoutIndex)
                || self.has_capability(ConnectorCapability::FullTextSearchWithIndex))
    }

    pub fn can_resolve_relation_with_joins(&self) -> bool {
        self.has_feature(PreviewFeature::RelationJoins)
            && (self.has_capability(ConnectorCapability::LateralJoin)
                || self.has_capability(ConnectorCapability::CorrelatedSubqueries))
    }

    pub fn has_feature(&self, feature: PreviewFeature) -> bool {
        self.preview_features.contains(feature)
    }

    pub fn has_capability(&self, capability: ConnectorCapability) -> bool {
        self.connector.has_capability(capability)
    }

    pub fn capabilities(&self) -> ConnectorCapabilities {
        self.connector.capabilities()
    }

    pub fn find_mutation_field(&self, name: &str) -> Option<OutputField<'_>> {
        self.root_fields
            .get(&(Operation::Mutation, name.to_owned()))
            .map(|i| self.mutation_fields[*i](self))
    }

    pub fn find_query_field(&self, name: &str) -> Option<OutputField<'_>> {
        self.root_fields
            .get(&(Operation::Query, name.to_owned()))
            .map(|i| self.query_fields[*i](self))
    }

    pub fn find_query_field_by_model_and_action(
        &self,
        model_name: Option<&str>,
        tag: QueryTag,
    ) -> Option<OutputField<'_>> {
        let model = model_name
            .and_then(|name| self.internal_data_model.schema.db.find_model(name))
            .map(|m| m.id);
        let query_info = QueryInfo { model, tag };

        self.query_info_map
            .get(&(Operation::Query, query_info))
            .map(|i| self.query_fields[*i](self))
    }

    pub fn find_mutation_field_by_model_and_action(
        &self,
        model_name: Option<&str>,
        tag: QueryTag,
    ) -> Option<OutputField<'_>> {
        let model = model_name
            .and_then(|name| self.internal_data_model.schema.db.find_model(name))
            .map(|m| m.id);
        let query_info = QueryInfo { model, tag };

        self.query_info_map
            .get(&(Operation::Mutation, query_info))
            .map(|i| self.mutation_fields[*i](self))
    }

    pub fn mutation(&self) -> ObjectType<'_> {
        ObjectType::new(Identifier::new_prisma(IdentifierType::Mutation), || {
            self.mutation_fields.iter().map(|f| f(self)).collect()
        })
    }

    pub fn query(&self) -> ObjectType<'_> {
        ObjectType::new(Identifier::new_prisma(IdentifierType::Query), || {
            self.query_fields.iter().map(|f| f(self)).collect()
        })
    }

    pub fn relation_mode(&self) -> RelationMode {
        self.relation_mode
    }

    pub fn can_native_upsert(&self) -> bool {
        self.connector
            .capabilities()
            .contains(ConnectorCapability::NativeUpsert)
    }
}

/// Designates a specific top-level operation on a corresponding model.
#[derive(Debug, Clone, PartialEq, Hash, Eq)]
pub struct QueryInfo {
    pub model: Option<ast::ModelId>,
    pub tag: QueryTag,
}

/// A `QueryTag` designates a top level query possible with Prisma.
#[derive(Debug, Copy, Clone, PartialEq, Hash, Eq)]
pub enum QueryTag {
    FindUnique,
    FindUniqueOrThrow,
    FindFirst,
    FindFirstOrThrow,
    FindMany,
    CreateOne,
    CreateMany,
    UpdateOne,
    UpdateMany,
    DeleteOne,
    DeleteMany,
    UpsertOne,
    Aggregate,
    GroupBy,
    // Raw operations
    ExecuteRaw,
    QueryRaw,
    RunCommandRaw,
    FindRaw,
    AggregateRaw,
}

impl fmt::Display for QueryTag {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        let s = match self {
            Self::FindUnique => "findUnique",
            Self::FindUniqueOrThrow => "findUniqueOrThrow",
            Self::FindFirst => "findFirst",
            Self::FindFirstOrThrow => "findFirstOrThrow",
            Self::FindMany => "findMany",
            Self::CreateOne => "createOne",
            Self::CreateMany => "createMany",
            Self::UpdateOne => "updateOne",
            Self::UpdateMany => "updateMany",
            Self::DeleteOne => "deleteOne",
            Self::DeleteMany => "deleteMany",
            Self::UpsertOne => "upsertOne",
            Self::Aggregate => "aggregate",
            Self::GroupBy => "groupBy",
            Self::ExecuteRaw => "executeRaw",
            Self::QueryRaw => "queryRaw",
            Self::RunCommandRaw => "runCommandRaw",
            Self::FindRaw => "findRaw",
            Self::AggregateRaw => "aggregateRaw",
        };

        f.write_str(s)
    }
}

impl From<&str> for QueryTag {
    fn from(value: &str) -> Self {
        match value {
            "findUnique" => Self::FindUnique,
            "findUniqueOrThrow" => Self::FindUniqueOrThrow,
            "findFirst" => Self::FindFirst,
            "findFirstOrThrow" => Self::FindFirstOrThrow,
            "findMany" => Self::FindMany,
            "createOne" => Self::CreateOne,
            "createMany" => Self::CreateMany,
            "updateOne" => Self::UpdateOne,
            "updateMany" => Self::UpdateMany,
            "deleteOne" => Self::DeleteOne,
            "deleteMany" => Self::DeleteMany,
            "upsertOne" => Self::UpsertOne,
            "aggregate" => Self::Aggregate,
            "groupBy" => Self::GroupBy,
            "executeRaw" => Self::ExecuteRaw,
            "queryRaw" => Self::QueryRaw,
            "findRaw" => Self::FindRaw,
            "aggregateRaw" => Self::AggregateRaw,
            "runCommandRaw" => Self::RunCommandRaw,
            v => panic!("Unknown query tag: {v}"),
        }
    }
}

#[derive(PartialEq, Hash, Eq, Debug, Clone)]
pub struct Identifier {
    name: IdentifierType,
    namespace: IdentifierNamespace,
}

#[derive(PartialEq, Eq, Hash, Debug, Clone)]
enum IdentifierNamespace {
    Prisma,
    Model,
}

impl Identifier {
    pub(crate) fn new_prisma(name: impl Into<IdentifierType>) -> Self {
        Self {
            name: name.into(),
            namespace: IdentifierNamespace::Prisma,
        }
    }

    pub(crate) fn new_model(name: impl Into<IdentifierType>) -> Self {
        Self {
            name: name.into(),
            namespace: IdentifierNamespace::Model,
        }
    }

    pub fn name(&self) -> String {
        self.name.to_string()
    }

    pub fn namespace(&self) -> &str {
        match self.namespace {
            IdentifierNamespace::Prisma => "prisma",
            IdentifierNamespace::Model => "model",
        }
    }
}

#[derive(Debug, Clone, PartialEq, Copy)]
pub enum ScalarType {
    Null,
    String,
    Int,
    BigInt,
    Float,
    Decimal,
    Boolean,
    DateTime,
    Json,
    JsonList,
    UUID,
    Bytes,
}

impl fmt::Display for ScalarType {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        let typ = match self {
            ScalarType::Null => "Null",
            ScalarType::String => "String",
            ScalarType::Int => "Int",
            ScalarType::BigInt => "BigInt",
            ScalarType::Boolean => "Boolean",
            ScalarType::Float => "Float",
            ScalarType::Decimal => "Decimal",
            ScalarType::DateTime => "DateTime",
            ScalarType::Json => "Json",
            ScalarType::UUID => "UUID",
            ScalarType::JsonList => "Json",
            ScalarType::Bytes => "Bytes",
        };

        f.write_str(typ)
    }
}