-
Notifications
You must be signed in to change notification settings - Fork 322
Expand file tree
/
Copy pathtypes.rs
More file actions
1745 lines (1640 loc) Β· 57.7 KB
/
Copy pathtypes.rs
File metadata and controls
1745 lines (1640 loc) Β· 57.7 KB
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
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
pub(crate) mod index_fields;
use crate::{
DatamodelError, ParserDatabase, context::Context, extension::ExtensionTypeId, interner::StringId,
walkers::IndexFieldWalker,
};
use either::Either;
use enumflags2::bitflags;
use rustc_hash::FxHashMap as HashMap;
use schema_ast::ast::{self, EnumValueId, WithName};
use serde::{Deserialize, Serialize};
use std::{
collections::BTreeMap,
fmt::{self, Write as _},
};
pub(super) fn resolve_types(ctx: &mut Context<'_>) {
for ((file_id, top_id), top) in ctx.iter_tops() {
match (top_id, top) {
(ast::TopId::Model(model_id), ast::Top::Model(model)) => visit_model((file_id, model_id), model, ctx),
(ast::TopId::Enum(_), ast::Top::Enum(enm)) => visit_enum(enm, ctx),
(ast::TopId::CompositeType(ct_id), ast::Top::CompositeType(ct)) => {
visit_composite_type((file_id, ct_id), ct, ctx)
}
(_, ast::Top::Source(_)) | (_, ast::Top::Generator(_)) => (),
_ => unreachable!(),
}
}
}
pub enum RefinedFieldVariant {
Relation(RelationFieldId),
Scalar(ScalarFieldId),
Unknown,
}
#[derive(Debug, Default)]
pub(super) struct Types {
pub(super) composite_type_fields: BTreeMap<(crate::CompositeTypeId, ast::FieldId), CompositeTypeField>,
scalar_fields: Vec<ScalarField>,
/// This contains only the relation fields actually present in the schema
/// source text.
relation_fields: Vec<RelationField>,
pub(super) enum_attributes: HashMap<crate::EnumId, EnumAttributes>,
pub(super) model_attributes: HashMap<crate::ModelId, ModelAttributes>,
/// Sorted array of scalar fields that have an `@default()` attribute with a function that is
/// not part of the base Prisma ones. This is meant for later validation in the datamodel
/// connector.
pub(super) unknown_function_defaults: Vec<ScalarFieldId>,
}
impl Types {
pub(super) fn find_model_scalar_field(
&self,
model_id: crate::ModelId,
field_id: ast::FieldId,
) -> Option<ScalarFieldId> {
self.scalar_fields
.binary_search_by_key(&(model_id, field_id), |sf| (sf.model_id, sf.field_id))
.ok()
.map(|idx| ScalarFieldId(idx as u32))
}
pub(super) fn range_model_scalar_fields(
&self,
model_id: crate::ModelId,
) -> impl Iterator<Item = (ScalarFieldId, &ScalarField)> + Clone {
let start = self.scalar_fields.partition_point(|sf| sf.model_id < model_id);
self.scalar_fields[start..]
.iter()
.take_while(move |sf| sf.model_id == model_id)
.enumerate()
.map(move |(idx, sf)| (ScalarFieldId((start + idx) as u32), sf))
}
pub(super) fn iter_relation_field_ids(&self) -> impl Iterator<Item = RelationFieldId> + 'static {
(0..self.relation_fields.len()).map(|idx| RelationFieldId(idx as u32))
}
pub(super) fn iter_relation_fields(&self) -> impl Iterator<Item = (RelationFieldId, &RelationField)> {
self.relation_fields
.iter()
.enumerate()
.map(|(idx, rf)| (RelationFieldId(idx as u32), rf))
}
pub(super) fn range_model_scalar_field_ids(
&self,
model_id: crate::ModelId,
) -> impl Iterator<Item = ScalarFieldId> + Clone + use<> {
let end = self.scalar_fields.partition_point(|sf| sf.model_id <= model_id);
let start = self.scalar_fields[..end].partition_point(|sf| sf.model_id < model_id);
(start..end).map(|idx| ScalarFieldId(idx as u32))
}
pub(super) fn range_model_relation_fields(
&self,
model_id: crate::ModelId,
) -> impl Iterator<Item = (RelationFieldId, &RelationField)> + Clone {
let first_relation_field_idx = self.relation_fields.partition_point(|rf| rf.model_id < model_id);
self.relation_fields[first_relation_field_idx..]
.iter()
.take_while(move |rf| rf.model_id == model_id)
.enumerate()
.map(move |(idx, rf)| (RelationFieldId((first_relation_field_idx + idx) as u32), rf))
}
pub(super) fn refine_field(&self, id: (crate::ModelId, ast::FieldId)) -> RefinedFieldVariant {
self.relation_fields
.binary_search_by_key(&id, |rf| (rf.model_id, rf.field_id))
.map(|idx| RefinedFieldVariant::Relation(RelationFieldId(idx as u32)))
.or_else(|_| {
self.scalar_fields
.binary_search_by_key(&id, |sf| (sf.model_id, sf.field_id))
.map(|id| RefinedFieldVariant::Scalar(ScalarFieldId(id as u32)))
})
.unwrap_or(RefinedFieldVariant::Unknown)
}
pub(super) fn push_relation_field(&mut self, relation_field: RelationField) -> RelationFieldId {
let id = RelationFieldId(self.relation_fields.len() as u32);
self.relation_fields.push(relation_field);
id
}
pub(super) fn push_scalar_field(&mut self, scalar_field: ScalarField) -> ScalarFieldId {
let id = ScalarFieldId(self.scalar_fields.len() as u32);
self.scalar_fields.push(scalar_field);
id
}
}
impl std::ops::Index<RelationFieldId> for Types {
type Output = RelationField;
fn index(&self, index: RelationFieldId) -> &Self::Output {
&self.relation_fields[index.0 as usize]
}
}
impl std::ops::IndexMut<RelationFieldId> for Types {
fn index_mut(&mut self, index: RelationFieldId) -> &mut Self::Output {
&mut self.relation_fields[index.0 as usize]
}
}
impl std::ops::Index<ScalarFieldId> for Types {
type Output = ScalarField;
fn index(&self, index: ScalarFieldId) -> &Self::Output {
&self.scalar_fields[index.0 as usize]
}
}
impl std::ops::IndexMut<ScalarFieldId> for Types {
fn index_mut(&mut self, index: ScalarFieldId) -> &mut Self::Output {
&mut self.scalar_fields[index.0 as usize]
}
}
#[derive(Debug, Clone)]
pub(super) struct CompositeTypeField {
pub(super) r#type: ScalarFieldType,
pub(super) mapped_name: Option<StringId>,
pub(super) default: Option<DefaultAttribute>,
/// Native type name and arguments
///
/// (attribute scope, native type name, arguments, span)
///
/// For example: `@db.Text` would translate to ("db", "Text", &[], <the span>)
pub(crate) native_type: Option<(StringId, StringId, Vec<String>, ast::Span)>,
}
#[derive(Debug)]
enum FieldType {
Model(crate::ModelId),
Scalar(ScalarFieldType),
}
#[derive(Debug, Clone, Copy, PartialEq)]
pub struct UnsupportedType {
name: StringId,
}
impl UnsupportedType {
pub(crate) fn new(name: StringId) -> Self {
Self { name }
}
}
/// OGC / PostGIS geometry subtype for [`ScalarFieldType::Geometry`].
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize, Deserialize)]
pub enum GeometrySubtype {
/// `POINT` subtype.
Point,
/// `LINESTRING` subtype.
LineString,
/// `POLYGON` subtype.
Polygon,
/// `MULTIPOINT` subtype.
MultiPoint,
/// `MULTILINESTRING` subtype.
MultiLineString,
/// `MULTIPOLYGON` subtype.
MultiPolygon,
/// `GEOMETRYCOLLECTION` subtype.
GeometryCollection,
/// Unrestricted `GEOMETRY` subtype.
Geometry,
}
impl GeometrySubtype {
/// PSL spelling of the subtype (e.g. `Point`).
pub fn as_str(self) -> &'static str {
match self {
GeometrySubtype::Point => "Point",
GeometrySubtype::LineString => "LineString",
GeometrySubtype::Polygon => "Polygon",
GeometrySubtype::MultiPoint => "MultiPoint",
GeometrySubtype::MultiLineString => "MultiLineString",
GeometrySubtype::MultiPolygon => "MultiPolygon",
GeometrySubtype::GeometryCollection => "GeometryCollection",
GeometrySubtype::Geometry => "Geometry",
}
}
}
impl From<ast::GeometrySubtype> for GeometrySubtype {
fn from(s: ast::GeometrySubtype) -> Self {
match s {
ast::GeometrySubtype::Point => Self::Point,
ast::GeometrySubtype::LineString => Self::LineString,
ast::GeometrySubtype::Polygon => Self::Polygon,
ast::GeometrySubtype::MultiPoint => Self::MultiPoint,
ast::GeometrySubtype::MultiLineString => Self::MultiLineString,
ast::GeometrySubtype::MultiPolygon => Self::MultiPolygon,
ast::GeometrySubtype::GeometryCollection => Self::GeometryCollection,
ast::GeometrySubtype::Geometry => Self::Geometry,
}
}
}
/// PostGIS base type for a [`GeometrySpec`] (`geometry` vs `geography` in PostgreSQL).
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize, Deserialize, Default)]
pub enum PostgisSpatialKind {
/// `geometry(...)` columns (planar).
#[default]
Geometry,
/// `geography(...)` columns (geodetic).
Geography,
}
/// Parameters for a `Geometry(subtype, srid?)` scalar field type.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize, Deserialize)]
pub struct GeometrySpec {
/// Geometry subtype (OGC / PostGIS).
pub subtype: GeometrySubtype,
/// Spatial reference ID; `None` when omitted in the schema (distinct from SRID 0 in the database).
pub srid: Option<i32>,
/// Whether the physical column uses PostGIS `geometry` or `geography`.
#[serde(default)]
pub spatial: PostgisSpatialKind,
}
impl GeometrySpec {
/// SQL column type for PostgreSQL / PostGIS (e.g. `geometry(Point,4326)` or `geography(Point,4326)`).
pub fn postgres_sql_type(&self) -> String {
let base = match self.spatial {
PostgisSpatialKind::Geometry => "geometry",
PostgisSpatialKind::Geography => "geography",
};
let subtype = self.subtype.as_str();
match self.srid {
Some(srid) => format!("{base}({subtype},{srid})"),
None => format!("{base}({subtype})"),
}
}
}
/// The type of a scalar field, parsed and categorized.
#[derive(Debug, Clone, Copy, PartialEq)]
pub enum ScalarFieldType {
/// A composite type
CompositeType(crate::CompositeTypeId),
/// An enum
Enum(crate::EnumId),
/// A type defined in an extension
Extension(ExtensionTypeId),
/// A Prisma scalar type
BuiltInScalar(ScalarType),
/// PostGIS-style `Geometry(Point, 4326)` scalar
Geometry(GeometrySpec),
/// An `Unsupported("...")` type
Unsupported(UnsupportedType),
}
impl ScalarFieldType {
/// Try to interpret this field type as a known Prisma scalar type.
pub fn as_builtin_scalar(self) -> Option<ScalarType> {
match self {
ScalarFieldType::BuiltInScalar(s) => Some(s),
_ => None,
}
}
/// Try to interpret this field type as a Composite Type.
pub fn as_composite_type(self) -> Option<crate::CompositeTypeId> {
match self {
ScalarFieldType::CompositeType(id) => Some(id),
_ => None,
}
}
/// Try to interpret this field type as an Extension type.
pub fn as_extension_type(self) -> Option<ExtensionTypeId> {
match self {
ScalarFieldType::Extension(id) => Some(id),
_ => None,
}
}
/// Try to interpret this field type as an enum.
pub fn as_enum(self) -> Option<crate::EnumId> {
match self {
ScalarFieldType::Enum(id) => Some(id),
_ => None,
}
}
/// Is the type of the field `Unsupported("...")`?
pub fn is_unsupported(self) -> bool {
matches!(self, Self::Unsupported(_))
}
/// True if the field's type is Json.
pub fn is_json(self) -> bool {
matches!(self, Self::BuiltInScalar(ScalarType::Json))
}
/// True if the field's type is String.
pub fn is_string(self) -> bool {
matches!(self, Self::BuiltInScalar(ScalarType::String))
}
/// True if the field's type is Bytes.
pub fn is_bytes(self) -> bool {
matches!(self, Self::BuiltInScalar(ScalarType::Bytes))
}
/// True if the field's type is DateTime.
pub fn is_datetime(self) -> bool {
matches!(self, Self::BuiltInScalar(ScalarType::DateTime))
}
/// True if the field's type is Float.
pub fn is_float(self) -> bool {
matches!(self, Self::BuiltInScalar(ScalarType::Float))
}
/// True if the field's type is Int.
pub fn is_int(self) -> bool {
matches!(self, Self::BuiltInScalar(ScalarType::Int))
}
/// True if the field's type is BigInt.
pub fn is_bigint(self) -> bool {
matches!(self, Self::BuiltInScalar(ScalarType::BigInt))
}
/// True if the field's type is Decimal.
pub fn is_decimal(self) -> bool {
matches!(self, Self::BuiltInScalar(ScalarType::Decimal))
}
/// True if the field's type is `Geometry(...)`.
pub fn is_geometry(self) -> bool {
matches!(self, Self::Geometry(_))
}
/// Display the field type as it would appear in the Prisma schema.
pub fn display<'a>(&'a self, db: &'a ParserDatabase) -> impl fmt::Display + 'a {
DisplayScalarFieldType { field_type: self, db }
}
}
struct DisplayScalarFieldType<'a> {
field_type: &'a ScalarFieldType,
db: &'a ParserDatabase,
}
impl fmt::Display for DisplayScalarFieldType<'_> {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
match self.field_type {
ScalarFieldType::BuiltInScalar(t) => write!(f, "{t}"),
ScalarFieldType::Enum(id) => {
write!(f, "{}", self.db.walk(*id).name())
}
ScalarFieldType::CompositeType(id) => {
write!(f, "{}", self.db.walk(*id).name())
}
ScalarFieldType::Extension(ext_id) => {
let name = self
.db
.extension_metadata
.id_to_prisma_name
.get(ext_id)
.expect("extension type id to have a name");
write!(f, "{}", self.db.interner.get(*name).unwrap())
}
ScalarFieldType::Geometry(spec) => {
write!(f, "Geometry({}", spec.subtype.as_str())?;
if let Some(srid) = spec.srid {
write!(f, ", {srid}")?;
}
f.write_char(')')
}
ScalarFieldType::Unsupported(ut) => {
write!(f, "Unsupported(\"{}\")", self.db.interner.get(ut.name).unwrap())
}
}
}
}
#[derive(Debug, Clone)]
pub(crate) struct DefaultAttribute {
pub(crate) mapped_name: Option<StringId>,
pub(crate) argument_idx: usize,
pub(crate) default_attribute: crate::AttributeId,
}
#[derive(Debug)]
pub(crate) struct ScalarField {
pub(crate) model_id: crate::ModelId,
pub(crate) field_id: ast::FieldId,
pub(crate) r#type: ScalarFieldType,
pub(crate) is_ignored: bool,
pub(crate) is_updated_at: bool,
pub(crate) default: Option<DefaultAttribute>,
/// @map
pub(crate) mapped_name: Option<StringId>,
/// Native type name and arguments
///
/// (attribute scope, native type name, arguments, span)
///
/// For example: `@db.Text` would translate to ("db", "Text", &[], <the span>)
pub(crate) native_type: Option<(StringId, StringId, Vec<String>, ast::Span)>,
}
#[derive(Debug)]
pub(crate) struct RelationField {
pub(crate) model_id: crate::ModelId,
pub(crate) field_id: ast::FieldId,
pub(crate) referenced_model: crate::ModelId,
pub(crate) on_delete: Option<(crate::ReferentialAction, ast::Span)>,
pub(crate) on_update: Option<(crate::ReferentialAction, ast::Span)>,
/// The fields _explicitly present_ in the AST.
pub(crate) fields: Option<Vec<ScalarFieldId>>,
/// The `references` fields _explicitly present_ in the AST.
pub(crate) references: Option<Vec<ScalarFieldId>>,
/// The name _explicitly present_ in the AST.
pub(crate) name: Option<StringId>,
pub(crate) is_ignored: bool,
/// The foreign key name _explicitly present_ in the AST through the `@map` attribute.
pub(crate) mapped_name: Option<StringId>,
pub(crate) relation_attribute: Option<ast::AttributeId>,
}
impl RelationField {
fn new(model_id: crate::ModelId, field_id: ast::FieldId, referenced_model: crate::ModelId) -> Self {
RelationField {
model_id,
field_id,
referenced_model,
on_delete: None,
on_update: None,
fields: None,
references: None,
name: None,
is_ignored: false,
mapped_name: None,
relation_attribute: None,
}
}
}
/// Information gathered from validating attributes on a model.
#[derive(Default, Debug)]
pub(crate) struct ModelAttributes {
/// @(@)id
pub(super) primary_key: Option<IdAttribute>,
/// @@ignore
pub(crate) is_ignored: bool,
/// @@index and @(@)unique explicitely written to the schema AST.
pub(super) ast_indexes: Vec<(ast::AttributeId, IndexAttribute)>,
/// @@map
pub(crate) mapped_name: Option<StringId>,
/// ```ignore
/// @@schema("public")
/// ^^^^^^^^
/// ```
pub(crate) schema: Option<(StringId, ast::Span)>,
/// @(@)shardKey
pub(crate) shard_key: Option<ShardKeyAttribute>,
}
/// A type of index as defined by the `type: ...` argument on an index attribute.
///
/// ```ignore
/// @@index([a, b], type: Hash)
/// ^^^^^^^^^^
/// ```
#[bitflags]
#[repr(u8)]
#[derive(Debug, Clone, Copy, PartialEq, Default)]
pub enum IndexAlgorithm {
/// Binary tree index (the default in most databases)
#[default]
BTree,
/// Hash index
Hash,
/// GiST index
Gist,
/// GIN index
Gin,
/// SP-GiST index
SpGist,
/// Brin index
Brin,
}
impl fmt::Display for IndexAlgorithm {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
match self {
IndexAlgorithm::BTree => f.write_str("BTree"),
IndexAlgorithm::Hash => f.write_str("Hash"),
IndexAlgorithm::Gist => f.write_str("Gist"),
IndexAlgorithm::Gin => f.write_str("Gin"),
IndexAlgorithm::SpGist => f.write_str("SpGist"),
IndexAlgorithm::Brin => f.write_str("Brin"),
}
}
}
impl IndexAlgorithm {
/// Is this a B-Tree index?
pub fn is_btree(self) -> bool {
matches!(self, Self::BTree)
}
/// Hash?
pub fn is_hash(self) -> bool {
matches!(self, Self::Hash)
}
/// GiST?
pub fn is_gist(self) -> bool {
matches!(self, Self::Gist)
}
/// GIN?
pub fn is_gin(self) -> bool {
matches!(self, Self::Gin)
}
/// SP-GiST?
pub fn is_spgist(self) -> bool {
matches!(self, Self::SpGist)
}
/// BRIN?
pub fn is_brin(self) -> bool {
matches!(self, Self::Brin)
}
/// True if the operator class can be used with the given scalar type.
pub fn supports_field_type(self, field: IndexFieldWalker<'_>) -> bool {
let r#type = field.scalar_field_type();
if r#type.is_unsupported() {
return true;
}
if r#type.is_geometry() {
return matches!(self, IndexAlgorithm::BTree | IndexAlgorithm::Gist);
}
match self {
IndexAlgorithm::BTree => true,
IndexAlgorithm::Hash => true,
IndexAlgorithm::Gist => r#type.is_string(),
IndexAlgorithm::Gin => r#type.is_json() || field.ast_field().arity.is_list(),
IndexAlgorithm::SpGist => r#type.is_string(),
IndexAlgorithm::Brin => {
r#type.is_string()
|| r#type.is_bytes()
|| r#type.is_datetime()
|| r#type.is_float()
|| r#type.is_int()
|| r#type.is_bigint()
|| r#type.is_decimal()
}
}
}
/// Documentation for editor autocompletion.
pub fn documentation(self) -> &'static str {
match self {
IndexAlgorithm::BTree => {
"Can handle equality and range queries on data that can be sorted into some ordering (default)."
}
IndexAlgorithm::Hash => {
"Can handle simple equality queries, but no ordering. Faster than BTree, if ordering is not needed."
}
IndexAlgorithm::Gist => {
"Generalized Search Tree. A framework for building specialized indices for custom data types."
}
IndexAlgorithm::Gin => {
"Generalized Inverted Index. Useful for indexing composite items, such as arrays or text."
}
IndexAlgorithm::SpGist => {
"Space-partitioned Generalized Search Tree. For implenting a wide range of different non-balanced data structures."
}
IndexAlgorithm::Brin => {
"Block Range Index. If the data has some natural correlation with their physical location within the table, can compress very large amount of data into a small space."
}
}
}
}
/// The different types of indexes supported in the Prisma Schema Language.
#[derive(Debug, Default, Clone, Copy, PartialEq)]
pub enum IndexType {
/// @@index
#[default]
Normal,
/// @(@)unique
Unique,
/// @(@)fulltext
Fulltext,
}
/// A condition operator in a partial index WHERE clause.
#[derive(Debug, Clone, PartialEq)]
pub enum WhereCondition {
/// `IS NULL`
IsNull,
/// `IS NOT NULL`
IsNotNull,
/// `= value`
Equals(WhereValue),
/// `!= value`
NotEquals(WhereValue),
}
/// A literal value in a partial index WHERE condition.
#[derive(Debug, Clone, PartialEq)]
pub enum WhereValue {
/// A string literal.
String(String),
/// A numeric literal.
Number(String),
/// A boolean literal.
Boolean(bool),
}
/// A field condition in an object-syntax WHERE clause.
#[derive(Debug, Clone)]
pub struct WhereFieldCondition {
/// The scalar field referenced by this condition.
pub scalar_field_id: ScalarFieldId,
/// The condition to apply.
pub condition: WhereCondition,
}
/// The WHERE clause of a partial index.
#[derive(Debug, Clone)]
pub enum WhereClause {
/// A raw SQL predicate string.
Raw(String),
/// Structured conditions from the object syntax.
Object(Vec<WhereFieldCondition>),
}
#[derive(Debug, Default)]
pub(crate) struct IndexAttribute {
pub(crate) r#type: IndexType,
pub(crate) fields: Vec<FieldWithArgs>,
pub(crate) source_field: Option<ScalarFieldId>,
pub(crate) name: Option<StringId>,
pub(crate) mapped_name: Option<StringId>,
pub(crate) algorithm: Option<IndexAlgorithm>,
pub(crate) clustered: Option<bool>,
pub(crate) where_clause: Option<WhereClause>,
}
impl IndexAttribute {
pub(crate) fn is_unique(&self) -> bool {
matches!(self.r#type, IndexType::Unique)
}
pub(crate) fn is_fulltext(&self) -> bool {
matches!(self.r#type, IndexType::Fulltext)
}
pub(crate) fn is_normal(&self) -> bool {
matches!(self.r#type, IndexType::Normal)
}
}
#[derive(Debug)]
pub(crate) struct IdAttribute {
pub(crate) fields: Vec<FieldWithArgs>,
pub(super) source_field: Option<ast::FieldId>,
pub(super) source_attribute: crate::AttributeId,
pub(super) name: Option<StringId>,
pub(super) mapped_name: Option<StringId>,
pub(super) clustered: Option<bool>,
}
#[derive(Debug)]
pub(crate) struct ShardKeyAttribute {
pub(crate) fields: Vec<ScalarFieldId>,
pub(super) source_field: Option<ast::FieldId>,
pub(super) source_attribute: crate::AttributeId,
}
/// Defines a path to a field that is not directly in the model.
///
/// ```ignore
/// type A {
/// field String
/// }
///
/// model A {
/// id Int @id
/// a A
///
/// @@index([a.field])
/// // ^this thing here, path separated with `.`
/// }
/// ```
#[derive(Debug, Clone, PartialEq)]
pub struct IndexFieldPath {
/// The field in the model that starts the path to the final field included
/// in the index. The type of this field has to be a composite type.
///
/// ```ignore
/// type A {
/// field String
/// }
///
/// model A {
/// id Int @id
/// a A
/// //^this one is the root
/// @@index([a.field])
/// }
/// ```
root: ScalarFieldId,
/// Path from the root, one composite type at a time. The final item is the
/// field that gets included in the index.
///
/// ```ignore
/// type A {
/// field String
/// }
///
/// model A {
/// id Int @id
/// a A
/// @@index([a.field])
/// // ^this one is the path. in this case a vector of one element
/// }
/// ```
path: Vec<(crate::CompositeTypeId, ast::FieldId)>,
}
impl IndexFieldPath {
pub(crate) fn new(root: ScalarFieldId) -> Self {
Self { root, path: Vec::new() }
}
pub(crate) fn push_field(&mut self, ctid: crate::CompositeTypeId, field_id: ast::FieldId) {
self.path.push((ctid, field_id));
}
/// The starting point of the index path. If the indexed field is not in a
/// composite type, returns the same value as [`field_in_index`](Self::field_in_index()).
///
/// ```ignore
/// type A {
/// field String
/// }
///
/// model A {
/// id Int @id
/// a A
/// //^here
///
/// @@index([a.field])
/// }
/// ```
pub fn root(&self) -> ScalarFieldId {
self.root
}
/// The path after [`root`](Self::root()). Empty if the field is not pointing to a
/// composite type.
///
/// ```ignore
/// type A {
/// field String
/// //^the path is a vector of one element, pointing to this field.
/// }
///
/// model A {
/// id Int @id
/// a A
///
/// @@index([a.field])
/// }
/// ```
pub fn path(&self) -> &[(crate::CompositeTypeId, ast::FieldId)] {
&self.path
}
/// The field that gets included in the index. Can either be in the model,
/// or in a composite type embedded in the model. Returns the same value as
/// the [`root`](Self::root()) method if the field is in a model rather than in a
/// composite type.
pub fn field_in_index(&self) -> Either<ScalarFieldId, (crate::CompositeTypeId, ast::FieldId)> {
self.path
.last()
.map(|(ct, field)| Either::Right((*ct, *field)))
.unwrap_or(Either::Left(self.root))
}
}
#[derive(Debug, Clone)]
pub struct FieldWithArgs {
pub(crate) path: IndexFieldPath,
pub(crate) sort_order: Option<SortOrder>,
pub(crate) length: Option<u32>,
pub(crate) operator_class: Option<OperatorClassStore>,
}
#[derive(Debug, Default)]
pub(super) struct EnumAttributes {
pub(super) mapped_name: Option<StringId>,
/// @map on enum values.
pub(super) mapped_values: HashMap<EnumValueId, StringId>,
/// ```ignore
/// @@schema("public")
/// ^^^^^^^^
/// ```
pub(crate) schema: Option<(StringId, ast::Span)>,
}
fn visit_model<'db>(model_id: crate::ModelId, ast_model: &'db ast::Model, ctx: &mut Context<'db>) {
for (field_id, ast_field) in ast_model.iter_fields() {
match field_type(ast_field, ctx) {
Ok(FieldType::Model(referenced_model)) => {
let rf = RelationField::new(model_id, field_id, referenced_model);
ctx.types.push_relation_field(rf);
}
Ok(FieldType::Scalar(scalar_field_type)) => {
ctx.types.push_scalar_field(ScalarField {
model_id,
field_id,
r#type: scalar_field_type,
is_ignored: false,
is_updated_at: false,
default: None,
mapped_name: None,
native_type: None,
});
}
Err(supported) => {
let top_names: Vec<_> = ctx
.iter_tops()
.filter_map(|(_, top)| match top {
ast::Top::Source(_) | ast::Top::Generator(_) => None,
_ => Some(&top.identifier().name),
})
.collect();
match top_names.iter().find(|&name| name.to_lowercase() == supported) {
Some(ignore_case_match) => {
ctx.push_error(DatamodelError::new_type_for_case_not_found_error(
supported,
ignore_case_match.as_str(),
ast_field.field_type.span(),
));
}
None => match ScalarType::try_from_str(supported, true) {
Some(ignore_case_match) => {
ctx.push_error(DatamodelError::new_type_for_case_not_found_error(
supported,
ignore_case_match.as_str(),
ast_field.field_type.span(),
));
}
None => {
ctx.push_error(DatamodelError::new_type_not_found_error(
supported,
ast_field.field_type.span(),
));
}
},
}
}
}
}
}
fn visit_composite_type<'db>(ct_id: crate::CompositeTypeId, ct: &'db ast::CompositeType, ctx: &mut Context<'db>) {
for (field_id, ast_field) in ct.iter_fields() {
match field_type(ast_field, ctx) {
Ok(FieldType::Scalar(scalar_type)) => {
let field = CompositeTypeField {
r#type: scalar_type,
mapped_name: None,
default: None,
native_type: None,
};
ctx.types.composite_type_fields.insert((ct_id, field_id), field);
}
Ok(FieldType::Model(referenced_model_id)) => {
let referenced_model_name = ctx.asts[referenced_model_id].name();
ctx.push_error(DatamodelError::new_composite_type_validation_error(&format!("{referenced_model_name} refers to a model, making this a relation field. Relation fields inside composite types are not supported."), ct.name(), ast_field.field_type.span()))
}
Err(supported) => ctx.push_error(DatamodelError::new_type_not_found_error(
supported,
ast_field.field_type.span(),
)),
}
}
}
fn visit_enum<'db>(enm: &'db ast::Enum, ctx: &mut Context<'db>) {
if enm.values.is_empty() {
let msg = "An enum must have at least one value.";
ctx.push_error(DatamodelError::new_validation_error(msg, enm.span))
}
}
/// Either a structured, supported type, or an Err(unsupported) if the type name
/// does not match any we know of.
fn field_type<'db>(field: &'db ast::Field, ctx: &mut Context<'db>) -> Result<FieldType, &'db str> {
match &field.field_type {
ast::FieldType::Geometry { subtype, srid, .. } => {
Ok(FieldType::Scalar(ScalarFieldType::Geometry(GeometrySpec {
subtype: (*subtype).into(),
srid: *srid,
spatial: PostgisSpatialKind::Geometry,
})))
}
ast::FieldType::Unsupported(name, _) => {
let unsupported = UnsupportedType::new(ctx.interner.intern(name));
Ok(FieldType::Scalar(ScalarFieldType::Unsupported(unsupported)))
}
ast::FieldType::Supported(ident) => {
let supported = ident.name.as_str();
if let Some(tpe) = ScalarType::try_from_str(supported, false) {
return Ok(FieldType::Scalar(ScalarFieldType::BuiltInScalar(tpe)));
}
let supported_string_id = ctx.interner.intern(supported);
match ctx
.names
.tops
.get(&supported_string_id)
.map(|id| (id.0, id.1, &ctx.asts[*id]))
{
Some((file_id, ast::TopId::Model(model_id), ast::Top::Model(_))) => {
Ok(FieldType::Model((file_id, model_id)))
}
Some((file_id, ast::TopId::Enum(enum_id), ast::Top::Enum(_))) => {
Ok(FieldType::Scalar(ScalarFieldType::Enum((file_id, enum_id))))
}
Some((file_id, ast::TopId::CompositeType(ctid), ast::Top::CompositeType(_))) => {
Ok(FieldType::Scalar(ScalarFieldType::CompositeType((file_id, ctid))))
}
Some((_, _, ast::Top::Generator(_))) | Some((_, _, ast::Top::Source(_))) => unreachable!(),
None => {
if let Some(type_id) = ctx.extension_types().get_by_prisma_name(supported) {
Ok(FieldType::Scalar(ScalarFieldType::Extension(type_id)))
} else {
Err(supported)
}
}
_ => unreachable!(),
}
}
}
}
/// Defines operators captured by the index. Used with PostgreSQL
/// GiST/SP-GiST/GIN/BRIN indices.