-
Notifications
You must be signed in to change notification settings - Fork 32
/
completions.ts
1046 lines (956 loc) 路 32.4 KB
/
completions.ts
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
import {
CompletionItem,
CompletionList,
CompletionItemKind,
Position,
MarkupKind,
InsertTextFormat,
} from 'vscode-languageserver'
import type { TextDocument } from 'vscode-languageserver-textdocument'
import { klona } from 'klona'
import {
blockAttributes,
fieldAttributes,
allowedBlockTypes,
corePrimitiveTypes,
supportedDataSourceFields,
supportedGeneratorFields,
relationArguments,
dataSourceUrlArguments,
dataSourceProviders,
dataSourceProviderArguments,
generatorProviders,
generatorProviderArguments,
engineTypes,
engineTypeArguments,
givenBlockAttributeParams,
givenFieldAttributeParams,
sortLengthProperties,
filterSortLengthBasedOnInput,
toCompletionItems,
removeInvalidAttributeSuggestions,
removeInvalidFieldSuggestions,
getNativeTypes,
handlePreviewFeatures,
relationModeValues,
} from './completionUtils'
import listAllAvailablePreviewFeatures from '../prisma-fmt/listAllAvailablePreviewFeatures'
import {
Block,
BlockType,
getModelOrTypeOrEnumBlock,
declaredNativeTypes,
getAllRelationNames,
isInsideAttribute,
isInsideQuotationMark,
isInsideFieldArgument,
isInsideGivenProperty,
getFirstDatasourceName,
getFirstDatasourceProvider,
getAllPreviewFeaturesFromGenerators,
getFieldsFromCurrentBlock,
getFieldType,
getFieldTypesFromCurrentBlock,
getValuesInsideSquareBrackets,
getCompositeTypeFieldsRecursively,
} from '../util'
function getSuggestionForModelBlockAttribute(block: Block, lines: string[]): CompletionItem[] {
if (block.type !== 'model') {
return []
}
// create deep copy
const suggestions: CompletionItem[] = removeInvalidAttributeSuggestions(klona(blockAttributes), block, lines)
// We can filter on the datasource
const datasourceProvider = getFirstDatasourceProvider(lines)
// We can filter on the previewFeatures enabled
const previewFeatures = getAllPreviewFeaturesFromGenerators(lines)
// Full text indexes (MySQL and MongoDB)
// https://www.prisma.io/docs/concepts/components/prisma-schema/indexes#full-text-indexes-mysql-and-mongodb
const isFullTextAvailable = Boolean(
datasourceProvider &&
['mysql', 'mongodb'].includes(datasourceProvider) &&
previewFeatures?.includes('fulltextindex'),
)
if (isFullTextAvailable === false) {
// fullTextIndex is not available, we need to filter it out
return suggestions.filter((arg) => arg.label !== '@@fulltext')
}
return suggestions
}
export function getSuggestionForNativeTypes(
foundBlock: Block,
lines: string[],
wordsBeforePosition: string[],
document: TextDocument,
): CompletionList | undefined {
const activeFeatureFlag = declaredNativeTypes(document)
if (
// TODO type? native "@db." types?
foundBlock.type !== 'model' ||
!activeFeatureFlag ||
wordsBeforePosition.length < 2
) {
return undefined
}
const datasourceName = getFirstDatasourceName(lines)
if (!datasourceName || wordsBeforePosition[wordsBeforePosition.length - 1] !== `@${datasourceName}`) {
return undefined
}
// line
const prismaType = wordsBeforePosition[1].replace('?', '').replace('[]', '')
const suggestions = getNativeTypes(document, prismaType)
return {
items: suggestions,
isIncomplete: true,
}
}
export function getSuggestionForFieldAttribute(
block: Block,
currentLine: string,
lines: string[],
wordsBeforePosition: string[],
document: TextDocument,
): CompletionList | undefined {
// TODO type? suggestions for "@..." for type?
if (block.type !== 'model') {
return
}
let suggestions: CompletionItem[] = []
const enabledNativeTypes = declaredNativeTypes(document)
// Because @.?
if (enabledNativeTypes && wordsBeforePosition.length >= 2) {
const datasourceName = getFirstDatasourceName(lines)
const prismaType = wordsBeforePosition[1]
const nativeTypeSuggestions = getNativeTypes(document, prismaType)
if (datasourceName && nativeTypeSuggestions.length !== 0) {
if (!currentLine.includes('@' + datasourceName)) {
suggestions.push({
// https://code.visualstudio.com/docs/editor/intellisense#_types-of-completions
kind: CompletionItemKind.Property,
label: '@' + datasourceName,
documentation:
'Defines a native database type that should be used for this field. See https://www.prisma.io/docs/concepts/components/prisma-schema/data-model#native-types-mapping',
insertText: `@${datasourceName}$0`,
insertTextFormat: InsertTextFormat.Snippet,
})
} else if (
// Check that we are not separated by a space like `@db. |`
wordsBeforePosition[wordsBeforePosition.length - 1] === `@${datasourceName}`
) {
suggestions.push(...nativeTypeSuggestions)
return {
items: suggestions,
isIncomplete: false,
}
}
} else {
console.log('Did not receive any native type suggestions from prisma-fmt call.')
}
}
suggestions.push(...fieldAttributes)
const fieldType = getFieldType(currentLine)
// If we don't find a field type (e.g. String, Int...), return no suggestion
if (!fieldType) {
return
}
const modelOrTypeOrEnum = getModelOrTypeOrEnumBlock(fieldType, lines)
if (modelOrTypeOrEnum?.type === 'type') {
// @default & @relation are invalid on field referencing a composite type
// we filter them out
suggestions = suggestions.filter((sugg) => sugg.label !== '@default' && sugg.label !== '@relation')
}
// Tom: I think we allow ids on basically everything except relation fields
// so it doesn't need to be restricted to Int and String.
// These are terrible, terrible ideas of course, but you can have id DateTime @id or id Float @id.
// TODO: decide if we want to only suggest things that make most sense or everything that is technically possible.
const isAtIdAllowed = fieldType === 'Int' || fieldType === 'String' || modelOrTypeOrEnum?.type === 'enum'
if (!isAtIdAllowed) {
// id not allowed
suggestions = suggestions.filter((sugg) => sugg.label !== '@id')
}
const isUpdatedAtAllowed = fieldType === 'DateTime'
if (!isUpdatedAtAllowed) {
// updatedAt not allowed
suggestions = suggestions.filter((sugg) => sugg.label !== '@updatedAt')
}
suggestions = removeInvalidAttributeSuggestions(suggestions, block, lines)
return {
items: suggestions,
isIncomplete: false,
}
}
export function getSuggestionsForFieldTypes(
foundBlock: Block,
lines: string[],
position: Position,
currentLineUntrimmed: string,
): CompletionList {
const suggestions: CompletionItem[] = []
const datasourceProvider = getFirstDatasourceProvider(lines)
// MongoDB doesn't support Decimal
if (datasourceProvider === 'mongodb') {
suggestions.push(...corePrimitiveTypes.filter((s) => s.label !== 'Decimal'))
} else {
suggestions.push(...corePrimitiveTypes)
}
if (foundBlock instanceof Block) {
// get all model names
const modelNames: string[] = getAllRelationNames(lines)
suggestions.push(...toCompletionItems(modelNames, CompletionItemKind.Reference))
}
const wordsBeforePosition = currentLineUntrimmed.slice(0, position.character).split(' ')
const wordBeforePosition = wordsBeforePosition[wordsBeforePosition.length - 1]
const completeSuggestions = suggestions.filter((s) => s.label.length === wordBeforePosition.length)
if (completeSuggestions.length !== 0) {
for (const sugg of completeSuggestions) {
suggestions.push(
{
label: `${sugg.label}?`,
kind: sugg.kind,
documentation: sugg.documentation,
},
{
label: `${sugg.label}[]`,
kind: sugg.kind,
documentation: sugg.documentation,
},
)
}
}
return {
items: suggestions,
isIncomplete: true,
}
}
function getSuggestionForDataSourceField(block: Block, lines: string[], position: Position): CompletionItem[] {
// create deep copy
const suggestions: CompletionItem[] = klona(supportedDataSourceFields)
const labels: string[] = removeInvalidFieldSuggestions(
suggestions.map((item) => item.label),
block,
lines,
position,
)
return suggestions.filter((item) => labels.includes(item.label))
}
function getSuggestionForGeneratorField(block: Block, lines: string[], position: Position): CompletionItem[] {
// create deep copy
const suggestions: CompletionItem[] = klona(supportedGeneratorFields)
const labels = removeInvalidFieldSuggestions(
suggestions.map((item) => item.label),
block,
lines,
position,
)
return suggestions.filter((item) => labels.includes(item.label))
}
/**
* gets suggestions for block type
*/
export function getSuggestionForFirstInsideBlock(
blockType: BlockType,
lines: string[],
position: Position,
block: Block,
): CompletionList {
let suggestions: CompletionItem[] = []
switch (blockType) {
case 'datasource':
suggestions = getSuggestionForDataSourceField(block, lines, position)
break
case 'generator':
suggestions = getSuggestionForGeneratorField(block, lines, position)
break
case 'model':
suggestions = getSuggestionForModelBlockAttribute(block, lines)
break
case 'type':
// No suggestions
break
}
return {
items: suggestions,
isIncomplete: false,
}
}
export function getSuggestionForBlockTypes(lines: string[]): CompletionList {
// create deep copy
const suggestions: CompletionItem[] = klona(allowedBlockTypes)
// enum is not supported in sqlite
let foundDataSourceBlock = false
for (const item of lines) {
if (item.includes('datasource')) {
foundDataSourceBlock = true
continue
}
if (foundDataSourceBlock) {
if (item.includes('}')) {
break
}
if (item.startsWith('provider') && item.includes('sqlite')) {
suggestions.pop()
}
}
if (!suggestions.map((sugg) => sugg.label).includes('enum')) {
break
}
}
return {
items: suggestions,
isIncomplete: false,
}
}
export function suggestEqualSymbol(blockType: BlockType): CompletionList | undefined {
if (!(blockType == 'datasource' || blockType == 'generator')) {
return
}
const equalSymbol: CompletionItem = { label: '=' }
return {
items: [equalSymbol],
isIncomplete: false,
}
}
// Suggest fields for a BlockType
export function getSuggestionForSupportedFields(
blockType: BlockType,
currentLine: string,
currentLineUntrimmed: string,
position: Position,
lines: string[],
): CompletionList | undefined {
let suggestions: string[] = []
const isInsideQuotation: boolean = isInsideQuotationMark(currentLineUntrimmed, position)
// We can filter on the datasource
const datasourceProvider = getFirstDatasourceProvider(lines)
// We can filter on the previewFeatures enabled
const previewFeatures = getAllPreviewFeaturesFromGenerators(lines)
switch (blockType) {
case 'generator':
// provider
if (currentLine.startsWith('provider')) {
const providers: CompletionItem[] = generatorProviders
if (isInsideQuotation) {
return {
items: providers,
isIncomplete: true,
}
} else {
return {
items: generatorProviderArguments,
isIncomplete: true,
}
}
}
// previewFeatures
else if (currentLine.startsWith('previewFeatures')) {
const generatorPreviewFeatures: string[] = listAllAvailablePreviewFeatures()
if (generatorPreviewFeatures.length > 0) {
return handlePreviewFeatures(generatorPreviewFeatures, position, currentLineUntrimmed, isInsideQuotation)
}
}
// engineType
else if (currentLine.startsWith('engineType')) {
const engineTypesCompletion: CompletionItem[] = engineTypes
if (isInsideQuotation) {
return {
items: engineTypesCompletion,
isIncomplete: true,
}
} else {
return {
items: engineTypeArguments,
isIncomplete: true,
}
}
}
break
case 'datasource':
// provider
if (currentLine.startsWith('provider')) {
const providers: CompletionItem[] = dataSourceProviders
if (isInsideQuotation) {
return {
items: providers,
isIncomplete: true,
}
} else {
return {
items: dataSourceProviderArguments,
isIncomplete: true,
}
}
// url
} else if (currentLine.startsWith('url')) {
// check if inside env
if (isInsideAttribute(currentLineUntrimmed, position, '()')) {
suggestions = ['DATABASE_URL']
} else {
if (currentLine.includes('env')) {
return {
items: dataSourceUrlArguments.filter((a) => !a.label.includes('env')),
isIncomplete: true,
}
}
return {
items: dataSourceUrlArguments,
isIncomplete: true,
}
}
}
// `relationMode` can only be set for SQL databases
// TODO remove conditional on preview feature flag when going GA
else if (
previewFeatures?.includes('referentialintegrity') &&
currentLine.startsWith('relationMode') &&
datasourceProvider !== 'mongodb'
) {
const relationModeValuesSuggestion: CompletionItem[] = relationModeValues
// values inside quotes `"value"`
const relationModeValuesSuggestionWithQuotes: CompletionItem[] = klona(relationModeValuesSuggestion).map(
(suggestion) => {
suggestion.label = `"${suggestion.label}"`
// eslint-disable-next-line @typescript-eslint/no-non-null-assertion
suggestion.insertText = `"${suggestion.insertText!}"`
return suggestion
},
)
if (isInsideQuotation) {
return {
items: relationModeValuesSuggestion,
isIncomplete: true,
}
}
// If line ends with `"`, a value is already set.
else if (!currentLine.endsWith('"')) {
return {
items: relationModeValuesSuggestionWithQuotes,
isIncomplete: true,
}
}
}
break
}
return {
items: toCompletionItems(suggestions, CompletionItemKind.Constant),
isIncomplete: false,
}
}
function getDefaultValues({
currentLine,
lines,
wordsBeforePosition,
}: {
currentLine: string
lines: string[]
wordsBeforePosition: string[]
}): CompletionItem[] {
const suggestions: CompletionItem[] = []
const datasourceProvider = getFirstDatasourceProvider(lines)
// Completions for sequence(|)
if (datasourceProvider === 'cockroachdb') {
if (wordsBeforePosition.some((a) => a.includes('sequence('))) {
const sequenceProperties = ['virtual', 'minValue', 'maxValue', 'cache', 'increment', 'start']
// No suggestions if virtual is present
if (currentLine.includes('virtual')) {
return suggestions
}
// Only suggests if empty
if (!sequenceProperties.some((it) => currentLine.includes(it))) {
suggestions.push({
label: 'virtual',
insertText: 'virtual',
kind: CompletionItemKind.Property,
documentation:
'Virtual sequences are sequences that do not generate monotonically increasing values and instead produce values like those generated by the built-in function unique_rowid(). They are intended for use in combination with SERIAL-typed columns.',
})
}
if (!currentLine.includes('minValue')) {
suggestions.push({
label: 'minValue',
insertText: 'minValue: $0',
kind: CompletionItemKind.Property,
documentation: 'The new minimum value of the sequence.',
})
}
if (!currentLine.includes('maxValue')) {
suggestions.push({
label: 'maxValue',
insertText: 'maxValue: $0',
kind: CompletionItemKind.Property,
documentation: 'The new maximum value of the sequence.',
})
}
if (!currentLine.includes('cache')) {
suggestions.push({
label: 'cache',
insertText: 'cache: $0',
kind: CompletionItemKind.Property,
documentation:
'The number of sequence values to cache in memory for reuse in the session. A cache size of 1 means that there is no cache, and cache sizes of less than 1 are not valid.',
})
}
if (!currentLine.includes('increment')) {
suggestions.push({
label: 'increment',
insertText: 'increment: $0',
kind: CompletionItemKind.Property,
documentation:
'The new value by which the sequence is incremented. A negative number creates a descending sequence. A positive number creates an ascending sequence.',
})
}
if (!currentLine.includes('start')) {
suggestions.push({
label: 'start',
insertText: 'start: $0',
kind: CompletionItemKind.Property,
documentation:
'The value the sequence starts at if you RESTART or if the sequence hits the MAXVALUE and CYCLE is set.',
})
}
return suggestions
}
}
// MongoDB only
if (datasourceProvider === 'mongodb') {
suggestions.push({
label: 'auto()',
kind: CompletionItemKind.Function,
documentation: 'Represents default values that are automatically generated by the database.',
insertText: 'auto()',
insertTextFormat: InsertTextFormat.Snippet,
})
} else {
suggestions.push({
label: 'dbgenerated("")',
kind: CompletionItemKind.Function,
documentation:
'The SQL definition of the default value which is generated by the database. This is not validated by Prisma.',
insertText: 'dbgenerated("$0")',
insertTextFormat: InsertTextFormat.Snippet,
})
}
const fieldType = getFieldType(currentLine)
// If we don't find a field type (e.g. String, Int...), return no suggestion
if (!fieldType) {
return []
}
switch (fieldType) {
case 'BigInt':
case 'Int':
if (datasourceProvider === 'cockroachdb') {
suggestions.push({
label: 'sequence()',
kind: CompletionItemKind.Function,
documentation:
'Create a sequence of integers in the underlying database and assign the incremented values to the ID values of the created records based on the sequence.',
})
if (fieldType === 'Int') {
// @default(autoincrement()) is only supported on BigInt fields for cockroachdb.
break
}
}
suggestions.push({
label: 'autoincrement()',
kind: CompletionItemKind.Function,
documentation:
'Create a sequence of integers in the underlying database and assign the incremented values to the ID values of the created records based on the sequence.',
})
break
case 'DateTime':
suggestions.push({
label: 'now()',
kind: CompletionItemKind.Function,
documentation: {
kind: MarkupKind.Markdown,
value: 'Set a timestamp of the time when a record is created.',
},
})
break
case 'String':
suggestions.push(
{
label: 'uuid()',
kind: CompletionItemKind.Function,
documentation: {
kind: MarkupKind.Markdown,
value:
'Generate a globally unique identifier based on the [UUID](https://en.wikipedia.org/wiki/Universally_unique_identifier) spec.',
},
},
{
label: 'cuid()',
kind: CompletionItemKind.Function,
documentation: {
kind: MarkupKind.Markdown,
value:
'Generate a globally unique identifier based on the [cuid](https://github.com/ericelliott/cuid) spec.',
},
},
)
break
case 'Boolean':
suggestions.push(
{ label: 'true', kind: CompletionItemKind.Value },
{ label: 'false', kind: CompletionItemKind.Value },
)
break
}
const isScalarList = fieldType.endsWith('[]')
if (isScalarList) {
suggestions.unshift({
label: '[]',
insertText: '[$0]',
insertTextFormat: InsertTextFormat.Snippet,
documentation: 'Set a default value on the list field',
kind: CompletionItemKind.Value,
})
}
const modelOrEnum = getModelOrTypeOrEnumBlock(fieldType, lines)
if (modelOrEnum && modelOrEnum.type === 'enum') {
// get fields from enum block for suggestions
const values: string[] = getFieldsFromCurrentBlock(lines, modelOrEnum)
values.forEach((v) => suggestions.push({ label: v, kind: CompletionItemKind.Value }))
}
return suggestions
}
function getSuggestionsForAttribute(
{
attribute,
wordsBeforePosition,
untrimmedCurrentLine,
lines,
block,
position,
}: {
attribute?: '@relation'
wordsBeforePosition: string[]
untrimmedCurrentLine: string
lines: string[]
block: Block
position: Position
}, // eslint-disable-line @typescript-eslint/no-unused-vars
): CompletionList | undefined {
const firstWordBeforePosition = wordsBeforePosition[wordsBeforePosition.length - 1]
const secondWordBeforePosition = wordsBeforePosition[wordsBeforePosition.length - 2]
const wordBeforePosition = firstWordBeforePosition === '' ? secondWordBeforePosition : firstWordBeforePosition
let suggestions: CompletionItem[] = []
// We can filter on the datasource
const datasourceProvider = getFirstDatasourceProvider(lines)
// We can filter on the previewFeatures enabled
const previewFeatures = getAllPreviewFeaturesFromGenerators(lines)
if (attribute === '@relation') {
if (datasourceProvider === 'mongodb') {
suggestions = relationArguments.filter(
(arg) => arg.label !== 'map' && arg.label !== 'onDelete' && arg.label !== 'onUpdate',
)
} else {
suggestions = relationArguments
}
// If we are right after @relation(
if (wordBeforePosition.includes('@relation')) {
return {
items: suggestions,
isIncomplete: false,
}
}
// TODO check fields with [] shortcut
if (isInsideGivenProperty(untrimmedCurrentLine, wordsBeforePosition, 'fields', position)) {
return {
items: toCompletionItems(getFieldsFromCurrentBlock(lines, block, position), CompletionItemKind.Field),
isIncomplete: false,
}
}
if (isInsideGivenProperty(untrimmedCurrentLine, wordsBeforePosition, 'references', position)) {
// Get the name by potentially removing ? and [] from Foo? or Foo[]
const referencedModelName = wordsBeforePosition[1].replace('?', '').replace('[]', '')
const referencedBlock = getModelOrTypeOrEnumBlock(referencedModelName, lines)
// referenced model does not exist
// TODO type?
if (!referencedBlock || referencedBlock.type !== 'model') {
return
}
return {
items: toCompletionItems(getFieldsFromCurrentBlock(lines, referencedBlock), CompletionItemKind.Field),
isIncomplete: false,
}
}
} else {
// @id, @unique
// @@id, @@unique, @@index, @@fulltext
// The length argument is available on MySQL only on the
// @id, @@id, @unique, @@unique and @@index fields.
// The sort argument is available for all databases on the
// @unique, @@unique and @@index fields.
// Additionally, SQL Server also allows it on @id and @@id.
let attribute: '@@unique' | '@unique' | '@@id' | '@id' | '@@index' | '@@fulltext' | undefined = undefined
if (wordsBeforePosition.some((a) => a.includes('@@id'))) {
attribute = '@@id'
} else if (wordsBeforePosition.some((a) => a.includes('@id'))) {
attribute = '@id'
} else if (wordsBeforePosition.some((a) => a.includes('@@unique'))) {
attribute = '@@unique'
} else if (wordsBeforePosition.some((a) => a.includes('@unique'))) {
attribute = '@unique'
} else if (wordsBeforePosition.some((a) => a.includes('@@index'))) {
attribute = '@@index'
} else if (wordsBeforePosition.some((a) => a.includes('@@fulltext'))) {
attribute = '@@fulltext'
}
/**
* inside []
* suggest composite types for MongoDB
* suggest fields and extendedIndexes arguments (sort / length)
*
* Examples
* field attribute: slug String @unique(sort: Desc, length: 42) @db.VarChar(3000)
* block attribute: @@id([title(length: 100, sort: Desc), abstract(length: 10)])
*/
if (attribute && attribute !== '@@fulltext' && isInsideAttribute(untrimmedCurrentLine, position, '[]')) {
if (isInsideFieldArgument(untrimmedCurrentLine, position)) {
// extendedIndexes
const items: CompletionItem[] = []
// https://www.notion.so/prismaio/Proposal-More-PostgreSQL-index-types-GiST-GIN-SP-GiST-and-BRIN-e27ef762ee4846a9a282eec1a5129270
if (datasourceProvider === 'postgresql' && attribute === '@@index') {
items.push({
label: 'ops',
insertText: 'ops: $0',
insertTextFormat: InsertTextFormat.Snippet,
kind: CompletionItemKind.Property,
documentation: 'Specify the operator class for an indexed field.',
})
}
items.push(
...filterSortLengthBasedOnInput(
attribute,
previewFeatures,
datasourceProvider,
wordBeforePosition,
sortLengthProperties,
),
)
return {
items,
isIncomplete: false,
}
}
const fieldsFromLine = getValuesInsideSquareBrackets(untrimmedCurrentLine)
/*
* MongoDB composite type fields, see https://www.prisma.io/docs/concepts/components/prisma-schema/data-model#composite-type-unique-constraints
* Examples
* @@unique([address.|]) or @@unique(fields: [address.|])
* @@index([address.|]) or @@index(fields: [address.|])
*/
if (datasourceProvider === 'mongodb' && fieldsFromLine && firstWordBeforePosition.endsWith('.')) {
const getFieldName = (text: string): string => {
const [_, __, value] = new RegExp(/(.*\[)?(.+)/).exec(text) || []
let name = value
// Example for `@@index([email,address.|])` when there is no space between fields
if (name?.includes(',')) {
name = name.split(',').pop()!
}
// Remove . to only get the name
if (name?.endsWith('.')) {
name = name.slice(0, -1)
}
return name
}
const currentFieldName = getFieldName(firstWordBeforePosition)
if (!currentFieldName) {
return {
isIncomplete: false,
items: [],
}
}
const currentCompositeAsArray = currentFieldName.split('.')
const fieldTypesFromCurrentBlock = getFieldTypesFromCurrentBlock(lines, block)
const fields = getCompositeTypeFieldsRecursively(lines, currentCompositeAsArray, fieldTypesFromCurrentBlock)
return {
items: toCompletionItems(fields, CompletionItemKind.Field),
isIncomplete: false,
}
}
let fieldsFromCurrentBlock = getFieldsFromCurrentBlock(lines, block, position)
if (fieldsFromLine.length > 0) {
// If we are in a composite type, exit here, to not pollute results with first level fields
if (firstWordBeforePosition.includes('.')) {
return {
isIncomplete: false,
items: [],
}
}
// Remove items already used
fieldsFromCurrentBlock = fieldsFromCurrentBlock.filter((s) => !fieldsFromLine.includes(s))
// Return fields
// `onCompletionResolve` will take care of filtering the partial matches
if (
firstWordBeforePosition !== '' &&
!firstWordBeforePosition.endsWith(',') &&
!firstWordBeforePosition.endsWith(', ')
) {
return {
items: toCompletionItems(fieldsFromCurrentBlock, CompletionItemKind.Field),
isIncomplete: false,
}
}
}
return {
items: toCompletionItems(fieldsFromCurrentBlock, CompletionItemKind.Field),
isIncomplete: false,
}
}
// "@@" block attributes
let blockAtrributeArguments: CompletionItem[] = []
if (attribute === '@@unique') {
blockAtrributeArguments = givenBlockAttributeParams({
blockAttribute: '@@unique',
wordBeforePosition,
datasourceProvider,
previewFeatures,
})
} else if (attribute === '@@id') {
blockAtrributeArguments = givenBlockAttributeParams({
blockAttribute: '@@id',
wordBeforePosition,
datasourceProvider,
previewFeatures,
})
} else if (attribute === '@@index') {
blockAtrributeArguments = givenBlockAttributeParams({
blockAttribute: '@@index',
wordBeforePosition,
datasourceProvider,
previewFeatures,
})
} else if (attribute === '@@fulltext') {
blockAtrributeArguments = givenBlockAttributeParams({
blockAttribute: '@@fulltext',
wordBeforePosition,
datasourceProvider,
previewFeatures,
})
}
if (blockAtrributeArguments.length) {
suggestions = blockAtrributeArguments
} else {
// "@" field attributes
let fieldAtrributeArguments: CompletionItem[] = []
if (attribute === '@unique') {
fieldAtrributeArguments = givenFieldAttributeParams(
'@unique',
previewFeatures,
datasourceProvider,
wordBeforePosition,
)
} else if (attribute === '@id') {
fieldAtrributeArguments = givenFieldAttributeParams(
'@id',
previewFeatures,
datasourceProvider,
wordBeforePosition,
)
}
suggestions = fieldAtrributeArguments
}
}
// Check which attributes are already present
// so we can filter them out from the suggestions
const attributesFound: Set<string> = new Set()
for (const word of wordsBeforePosition) {
if (word.includes('references')) {
attributesFound.add('references')
}
if (word.includes('fields')) {
attributesFound.add('fields')
}
if (word.includes('onUpdate')) {
attributesFound.add('onUpdate')
}
if (word.includes('onDelete')) {
attributesFound.add('onDelete')
}
if (word.includes('map')) {
attributesFound.add('map')
}
if (word.includes('name') || /".*"/.exec(word)) {
attributesFound.add('name')
attributesFound.add('""')
}
if (word.includes('type')) {
attributesFound.add('type')
}
}
// now filter them out of the suggestions as they are already present
const filteredSuggestions: CompletionItem[] = suggestions.reduce(
(accumulator: CompletionItem[] & unknown[], sugg) => {
let suggestionMatch = false
for (const attribute of attributesFound) {
if (sugg.label.includes(attribute)) {
suggestionMatch = true
}
}
if (!suggestionMatch) {
accumulator.push(sugg)
}
return accumulator
},
[],
)
// nothing to present any more, return
if (filteredSuggestions.length === 0) {
return
}
return {
items: filteredSuggestions,
isIncomplete: false,
}
}
export function getSuggestionsForInsideRoundBrackets(
untrimmedCurrentLine: string,
lines: string[],
document: TextDocument,
position: Position,