-
-
Notifications
You must be signed in to change notification settings - Fork 145
Expand file tree
/
Copy pathpull.test.ts
More file actions
1444 lines (1210 loc) · 51.5 KB
/
pull.test.ts
File metadata and controls
1444 lines (1210 loc) · 51.5 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
import fs from 'node:fs';
import path from 'node:path';
import { describe, expect, it } from 'vitest';
import { createProject, getDefaultPrelude, getTestDbName, getTestDbUrl, runCli } from '../utils';
import { formatDocument } from '@zenstackhq/language';
import { getTestDbProvider } from '@zenstackhq/testtools';
const getSchema = (workDir: string) => fs.readFileSync(path.join(workDir, 'zenstack/schema.zmodel')).toString();
describe('DB pull - Common features (all providers)', () => {
describe('Pull from zero - restore complete schema from database', () => {
it('should restore basic schema with all supported types', async () => {
const { workDir, schema } = await createProject(
`model User {
id Int @id @default(autoincrement())
email String @unique
name String?
age Int @default(0)
balance Decimal @default(0.00)
isActive Boolean @default(true)
bigCounter BigInt @default(0)
score Float @default(0.0)
bio String?
avatar Bytes?
metadata Json?
createdAt DateTime @default(now())
updatedAt DateTime @updatedAt
}`,
);
runCli('db push', workDir);
// Store the schema after db push (this is what provider names will be)
const schemaFile = path.join(workDir, 'zenstack/schema.zmodel');
// Remove schema content to simulate restoration from zero
fs.writeFileSync(schemaFile, getDefaultPrelude());
// Pull should fully restore the schema
runCli('db pull --indent 4', workDir);
const restoredSchema = getSchema(workDir);
expect(restoredSchema).toEqual(schema);
});
it('should restore schema with relations', async () => {
const { workDir, schema } = await createProject(
`model Post {
id Int @id @default(autoincrement())
title String
author User @relation(fields: [authorId], references: [id], onDelete: Cascade)
authorId Int
}
model User {
id Int @id @default(autoincrement())
email String @unique
posts Post[]
}`,
);
runCli('db push', workDir);
const schemaFile = path.join(workDir, 'zenstack/schema.zmodel');
fs.writeFileSync(schemaFile, getDefaultPrelude());
runCli('db pull --indent 4', workDir);
const restoredSchema = getSchema(workDir);
expect(restoredSchema).toEqual(schema);
});
it('should restore schema with many-to-many relations', async () => {
const { workDir, schema } = await createProject(
`model Post {
id Int @id @default(autoincrement())
title String
postTags PostTag[]
}
model PostTag {
post Post @relation(fields: [postId], references: [id], onDelete: Cascade)
postId Int
tag Tag @relation(fields: [tagId], references: [id], onDelete: Cascade)
tagId Int
@@id([postId, tagId])
}
model Tag {
id Int @id @default(autoincrement())
name String @unique
postTags PostTag[]
}`,
);
runCli('db push', workDir);
const schemaFile = path.join(workDir, 'zenstack/schema.zmodel');
fs.writeFileSync(schemaFile, getDefaultPrelude());
runCli('db pull --indent 4', workDir);
const restoredSchema = getSchema(workDir);
expect(restoredSchema).toEqual(schema);
});
it('should restore self-referencing model with multiple FK columns without duplicate fields', async () => {
const { workDir, schema } = await createProject(
`model Category {
id Int @id @default(autoincrement())
categoryParentId Category? @relation('Category_parentIdToCategory', fields: [parentId], references: [id])
parentId Int?
categoryBuddyId Category? @relation('Category_buddyIdToCategory', fields: [buddyId], references: [id])
buddyId Int?
categoryMentorId Category? @relation('Category_mentorIdToCategory', fields: [mentorId], references: [id])
mentorId Int?
categoryParentIdToCategoryId Category[] @relation('Category_parentIdToCategory')
categoryBuddyIdToCategoryId Category[] @relation('Category_buddyIdToCategory')
categoryMentorIdToCategoryId Category[] @relation('Category_mentorIdToCategory')
}`,
);
runCli('db push', workDir);
const schemaFile = path.join(workDir, 'zenstack/schema.zmodel');
fs.writeFileSync(schemaFile, getDefaultPrelude());
runCli('db pull --indent 4', workDir);
const restoredSchema = getSchema(workDir);
expect(restoredSchema).toEqual(schema);
});
it('should preserve self-referencing model with multiple FK columns', async () => {
const { workDir, schema } = await createProject(
`model Category {
id Int @id @default(autoincrement())
category Category? @relation('Category_parentIdToCategory', fields: [parentId], references: [id])
parentId Int?
buddy Category? @relation('Category_buddyIdToCategory', fields: [buddyId], references: [id])
buddyId Int?
mentor Category? @relation('Category_mentorIdToCategory', fields: [mentorId], references: [id])
mentorId Int?
categories Category[] @relation('Category_parentIdToCategory')
buddys Category[] @relation('Category_buddyIdToCategory')
mentees Category[] @relation('Category_mentorIdToCategory')
}`,
);
runCli('db push', workDir);
runCli('db pull --indent 4', workDir);
const restoredSchema = getSchema(workDir);
expect(restoredSchema).toEqual(schema);
});
it('should restore opposite relation fields when multiple models have FKs to the same target', async () => {
const { workDir, schema } = await createProject(
`model Comment {
id Int @id @default(autoincrement())
text String
commentCreatedBy User? @relation('Comment_createdByToUser', fields: [createdBy], references: [id])
createdBy Int?
commentUpdatedBy User? @relation('Comment_updatedByToUser', fields: [updatedBy], references: [id])
updatedBy Int?
}
model Post {
id Int @id @default(autoincrement())
title String
postCreatedBy User? @relation('Post_createdByToUser', fields: [createdBy], references: [id])
createdBy Int?
postUpdatedBy User? @relation('Post_updatedByToUser', fields: [updatedBy], references: [id])
updatedBy Int?
}
model User {
id Int @id @default(autoincrement())
email String @unique
commentCreatedBy Comment[] @relation('Comment_createdByToUser')
commentUpdatedBy Comment[] @relation('Comment_updatedByToUser')
postCreatedBy Post[] @relation('Post_createdByToUser')
postUpdatedBy Post[] @relation('Post_updatedByToUser')
}`,
);
runCli('db push', workDir);
const schemaFile = path.join(workDir, 'zenstack/schema.zmodel');
fs.writeFileSync(schemaFile, getDefaultPrelude());
runCli('db pull --indent 4', workDir);
const restoredSchema = getSchema(workDir);
expect(restoredSchema).toEqual(schema);
});
it('should preserve opposite relation fields when multiple models have FKs to the same target', async () => {
const { workDir, schema } = await createProject(
`model Comment {
id Int @id @default(autoincrement())
text String
commentCreatedBy User? @relation('Comment_createdByToUser', fields: [createdBy], references: [id])
createdBy Int?
commentUpdatedBy User? @relation('Comment_updatedByToUser', fields: [updatedBy], references: [id])
updatedBy Int?
}
model Post {
id Int @id @default(autoincrement())
title String
postCreatedBy User? @relation('Post_createdByToUser', fields: [createdBy], references: [id])
createdBy Int?
postUpdatedBy User? @relation('Post_updatedByToUser', fields: [updatedBy], references: [id])
updatedBy Int?
}
model User {
id Int @id @default(autoincrement())
email String @unique
commentCreatedBy Comment[] @relation('Comment_createdByToUser')
commentUpdatedBy Comment[] @relation('Comment_updatedByToUser')
postCreatedBy Post[] @relation('Post_createdByToUser')
postUpdatedBy Post[] @relation('Post_updatedByToUser')
}`,
);
runCli('db push', workDir);
runCli('db pull --indent 4', workDir);
const restoredSchema = getSchema(workDir);
expect(restoredSchema).toEqual(schema);
});
it('should restore one-to-one relation when FK is the single-column primary key', async () => {
const { workDir, schema } = await createProject(
`model Profile {
user User @relation(fields: [id], references: [id], onDelete: Cascade)
id Int @id @default(autoincrement())
bio String?
}
model User {
id Int @id @default(autoincrement())
email String @unique
profile Profile?
}`,
);
runCli('db push', workDir);
const schemaFile = path.join(workDir, 'zenstack/schema.zmodel');
fs.writeFileSync(schemaFile, getDefaultPrelude());
runCli('db pull --indent 4', workDir);
const restoredSchema = getSchema(workDir);
expect(restoredSchema).toEqual(schema);
});
it('should restore schema with indexes and unique constraints', async () => {
const { workDir, schema } = await createProject(
`model User {
id Int @id @default(autoincrement())
email String @unique
username String
firstName String
lastName String
role String
@@unique([username, email])
@@index([role])
@@index([firstName, lastName])
@@index([email, username, role])
}`,
);
runCli('db push', workDir);
const schemaFile = path.join(workDir, 'zenstack/schema.zmodel');
fs.writeFileSync(schemaFile, getDefaultPrelude());
runCli('db pull --indent 4', workDir);
const restoredSchema = getSchema(workDir);
expect(restoredSchema).toEqual(schema);
});
it('should restore schema with composite primary keys', async () => {
const { workDir, schema } = await createProject(
`model UserRole {
userId String
role String
grantedAt DateTime @default(now())
@@id([userId, role])
}`,
);
runCli('db push', workDir);
const schemaFile = path.join(workDir, 'zenstack/schema.zmodel');
fs.writeFileSync(schemaFile, getDefaultPrelude());
runCli('db pull --indent 4', workDir);
const restoredSchema = getSchema(workDir);
expect(restoredSchema).toEqual(schema);
});
it('should preserve Decimal and Float default value precision', async () => {
const { workDir, schema } = await createProject(
`model Product {
id Int @id @default(autoincrement())
price Decimal @default(99.99)
discount Decimal @default(0.50)
taxRate Decimal @default(7.00)
weight Float @default(1.5)
rating Float @default(4.0)
temperature Float @default(98.6)
}`,
);
runCli('db push', workDir);
const schemaFile = path.join(workDir, 'zenstack/schema.zmodel');
fs.writeFileSync(schemaFile, getDefaultPrelude());
runCli('db pull --indent 4', workDir);
const restoredSchema = getSchema(workDir);
expect(restoredSchema).toEqual(schema);
});
});
describe('Pull with existing schema - preserve schema features', () => {
it('should preserve field and table mappings', async () => {
const { workDir, schema } = await createProject(
`model User {
id Int @id @default(autoincrement())
email String @unique @map('email_address')
firstName String @map('first_name')
lastName String @map('last_name')
@@map('users')
}`,
);
runCli('db push', workDir);
runCli('db pull --indent 4', workDir);
expect(getSchema(workDir)).toEqual(schema);
});
it('should not modify a comprehensive schema with all features', async () => {
const { workDir, schema } = await createProject(`model User {
id Int @id @default(autoincrement())
email String @unique @map('email_address')
name String? @default('Anonymous')
role Role @default(USER)
profile Profile?
shared_profile Profile? @relation('shared')
posts Post[]
createdAt DateTime @default(now())
updatedAt DateTime @updatedAt
jsonData Json?
balance Decimal @default(0.00)
isActive Boolean @default(true)
bigCounter BigInt @default(0)
bytes Bytes?
@@index([role])
@@map('users')
}
model Profile {
id Int @id @default(autoincrement())
user User @relation(fields: [userId], references: [id], onDelete: Cascade)
userId Int @unique
user_shared User @relation('shared', fields: [shared_userId], references: [id], onDelete: Cascade)
shared_userId Int @unique
bio String?
avatarUrl String?
@@map('profiles')
}
model Post {
id Int @id @default(autoincrement())
author User @relation(fields: [authorId], references: [id], onDelete: Cascade)
authorId Int
title String
content String?
published Boolean @default(false)
tags PostTag[]
createdAt DateTime @default(now())
updatedAt DateTime @updatedAt
slug String
score Float @default(0.0)
metadata Json?
@@unique([authorId, slug])
@@index([authorId, published])
@@map('posts')
}
model Tag {
id Int @id @default(autoincrement())
name String @unique
posts PostTag[]
createdAt DateTime @default(now())
@@index([name], name: 'tag_name_idx')
@@map('tags')
}
model PostTag {
post Post @relation(fields: [postId], references: [id], onDelete: Cascade)
postId Int
tag Tag @relation(fields: [tagId], references: [id], onDelete: Cascade)
tagId Int
assignedAt DateTime @default(now())
note String? @default('initial')
@@id([postId, tagId])
@@map('post_tags')
}
enum Role {
USER
ADMIN
MODERATOR
}`,
// When using MySQL, the introspection simply overrides the enum and cannot detect if it exists with the same name because it only stores the values.
// TODO: Create a better way to handle this, possibly by finding enums by their values as well if the schema exists.
);
runCli('db push', workDir);
runCli('db pull --indent 4', workDir);
expect(getSchema(workDir)).toEqual(schema);
});
it('should preserve imports when pulling with multi-file schema', async () => {
const { workDir } = await createProject('', { customPrelude: true });
const schemaPath = path.join(workDir, 'zenstack/schema.zmodel');
const modelsDir = path.join(workDir, 'zenstack/models');
fs.mkdirSync(modelsDir, { recursive: true });
// Create main schema with imports
const mainSchema = await formatDocument(`import './models/user'
import './models/post'
${getDefaultPrelude()}`);
fs.writeFileSync(schemaPath, mainSchema);
// Create user model
const userModel = await formatDocument(`import './post'
model User {
id Int @id @default(autoincrement())
email String @unique
name String?
posts Post[]
createdAt DateTime @default(now())
}`);
fs.writeFileSync(path.join(modelsDir, 'user.zmodel'), userModel);
// Create post model
const postModel = await formatDocument(`import './user'
model Post {
id Int @id @default(autoincrement())
title String
content String?
author User @relation(fields: [authorId], references: [id], onDelete: Cascade)
authorId Int
createdAt DateTime @default(now())
}`);
fs.writeFileSync(path.join(modelsDir, 'post.zmodel'), postModel);
runCli('db push', workDir);
// Pull and verify imports are preserved
runCli('db pull --indent 4', workDir);
const pulledMainSchema = fs.readFileSync(schemaPath).toString();
const pulledUserSchema = fs.readFileSync(path.join(modelsDir, 'user.zmodel')).toString();
const pulledPostSchema = fs.readFileSync(path.join(modelsDir, 'post.zmodel')).toString();
expect(pulledMainSchema).toEqual(mainSchema);
expect(pulledUserSchema).toEqual(userModel);
expect(pulledPostSchema).toEqual(postModel);
});
});
describe('Pull should preserve enum declaration order', () => {
it('should preserve interleaved enum and model ordering', async () => {
const { workDir, schema } = await createProject(
`enum Role {
USER
ADMIN
}
model User {
id Int @id @default(autoincrement())
email String @unique
role Role @default(USER)
status Status @default(ACTIVE)
}
enum Status {
ACTIVE
INACTIVE
SUSPENDED
}`,
);
runCli('db push', workDir);
runCli('db pull --indent 4', workDir);
// Enum-model-enum ordering should be preserved
expect(getSchema(workDir)).toEqual(schema);
});
});
describe('Pull should consolidate shared enums', () => {
it('should consolidate per-column enums back to the original shared enum', async () => {
const { workDir, schema } = await createProject(
`enum Status {
ACTIVE
INACTIVE
SUSPENDED
}
model User {
id Int @id @default(autoincrement())
status Status @default(ACTIVE)
}
model Group {
id Int @id @default(autoincrement())
status Status @default(ACTIVE)
}`,
);
runCli('db push', workDir);
runCli('db pull --indent 4', workDir);
// MySQL creates per-column enums (UserStatus, GroupStatus) but
// consolidation should map them back to the original shared Status enum
expect(getSchema(workDir)).toEqual(schema);
});
it('should consolidate per-column enums with --always-map without stale @@map', async () => {
// This test targets a bug where consolidateEnums renames keepEnum.name
// to oldEnum.name but leaves the synthetic @@map attribute added by
// syncEnums, so getDbName(keepEnum) still returns the old mapped name
// (e.g., 'UserStatus') instead of the consolidated name ('Status'),
// preventing matching in the downstream delete/add enum logic.
const { workDir } = await createProject(
`enum Status {
ACTIVE
INACTIVE
SUSPENDED
}
model User {
id Int @id @default(autoincrement())
status Status @default(ACTIVE)
}
model Group {
id Int @id @default(autoincrement())
status Status @default(ACTIVE)
}`,
);
runCli('db push', workDir);
runCli('db pull --indent 4 --always-map', workDir);
const pulledSchema = getSchema(workDir);
// The consolidated enum should be named Status, not UserStatus/GroupStatus
expect(pulledSchema).toContain('enum Status');
expect(pulledSchema).not.toContain('enum UserStatus');
expect(pulledSchema).not.toContain('enum GroupStatus');
// There should be no stale @@map referencing the synthetic per-column name
expect(pulledSchema).not.toMatch(/@@map\(['"]UserStatus['"]\)/);
expect(pulledSchema).not.toMatch(/@@map\(['"]GroupStatus['"]\)/);
});
});
describe('Pull should preserve triple-slash comments on enums', () => {
it('should preserve triple-slash comments on enum declarations and fields', async () => {
const { workDir, schema } = await createProject(
`model User {
id Int @id @default(autoincrement())
status Status @default(ACTIVE)
}
/// User account status
/// ACTIVE - user can log in
/// INACTIVE - user is disabled
enum Status {
/// User can log in
ACTIVE
/// User is disabled
INACTIVE
/// User is suspended
SUSPENDED
}`,
);
runCli('db push', workDir);
runCli('db pull --indent 4', workDir);
expect(getSchema(workDir)).toEqual(schema);
});
});
describe('Pull should preserve data validation attributes', () => {
it('should preserve field-level validation attributes after db pull', async () => {
const { workDir, schema } = await createProject(
`model User {
id Int @id @default(autoincrement())
email String @unique @email
phone String @phone
name String @length(min: 2, max: 100)
website String? @url
code String? @regex('^[A-Z]+$')
age Int @gt(0)
score Float @gte(0.0)
rating Decimal @lt(10)
rank BigInt @lte(999)
}`,
);
runCli('db push', workDir);
// Pull should preserve all validation attributes
runCli('db pull --indent 4', workDir);
expect(getSchema(workDir)).toEqual(schema);
});
it('should preserve string transformation attributes after db pull', async () => {
const { workDir, schema } = await createProject(
`model Setting {
id Int @id @default(autoincrement())
key String @trim @lower
value String @trim @upper
}`,
);
runCli('db push', workDir);
runCli('db pull --indent 4', workDir);
expect(getSchema(workDir)).toEqual(schema);
});
it('should preserve model-level @@validate attribute after db pull', async () => {
const { workDir, schema } = await createProject(
`model Product {
id Int @id @default(autoincrement())
minPrice Decimal @default(0.00)
maxPrice Decimal @default(100.00)
@@validate(minPrice < maxPrice, 'minPrice must be less than maxPrice')
}`,
);
runCli('db push', workDir);
runCli('db pull --indent 4', workDir);
expect(getSchema(workDir)).toEqual(schema);
});
});
describe('Pull should update existing field definitions when database changes', () => {
it('should update field type when database column type changes', async () => {
// Step 1: Create initial schema with String field
const { workDir } = await createProject(
`model User {
id Int @id @default(autoincrement())
email String @unique
age String
}`,
);
runCli('db push', workDir);
// Step 2: Modify schema to change age from String to Int
const schemaFile = path.join(workDir, 'zenstack/schema.zmodel');
const updatedSchema = await formatDocument(`${getDefaultPrelude()}
model User {
id Int @id @default(autoincrement())
email String @unique
age Int
}`);
fs.writeFileSync(schemaFile, updatedSchema);
runCli('db push', workDir);
// Step 3: Revert schema back to original (with String type)
const originalSchema = await formatDocument(`${getDefaultPrelude()}
model User {
id Int @id @default(autoincrement())
email String @unique
age String
}`);
fs.writeFileSync(schemaFile, originalSchema);
// Step 4: Pull from database - should detect that age is now Int
runCli('db pull --indent 4', workDir);
// Step 5: Verify that pulled schema has Int type (matching database)
const pulledSchema = getSchema(workDir);
expect(pulledSchema).toEqual(updatedSchema);
});
it('should update field optionality when database column nullability changes', async () => {
// Step 1: Create initial schema with required field
const { workDir } = await createProject(
`model User {
id Int @id @default(autoincrement())
email String @unique
name String
}`,
);
runCli('db push', workDir);
// Step 2: Modify schema to make name optional
const schemaFile = path.join(workDir, 'zenstack/schema.zmodel');
const updatedSchema = await formatDocument(`${getDefaultPrelude()}
model User {
id Int @id @default(autoincrement())
email String @unique
name String?
}`);
fs.writeFileSync(schemaFile, updatedSchema);
runCli('db push', workDir);
// Step 3: Revert schema back to original (with required name)
const originalSchema = await formatDocument(`${getDefaultPrelude()}
model User {
id Int @id @default(autoincrement())
email String @unique
name String
}`);
fs.writeFileSync(schemaFile, originalSchema);
// Step 4: Pull from database - should detect that name is now optional
runCli('db pull --indent 4', workDir);
// Step 5: Verify that pulled schema has optional name (matching database)
const pulledSchema = getSchema(workDir);
expect(pulledSchema).toEqual(updatedSchema);
});
it('should update default value when database default changes', async () => {
// Step 1: Create initial schema with default value
const { workDir } = await createProject(
`model User {
id Int @id @default(autoincrement())
email String @unique
status String @default('active')
}`,
);
runCli('db push', workDir);
// Step 2: Modify schema to change default value
const schemaFile = path.join(workDir, 'zenstack/schema.zmodel');
const updatedSchema = await formatDocument(`${getDefaultPrelude()}
model User {
id Int @id @default(autoincrement())
email String @unique
status String @default('pending')
}`);
fs.writeFileSync(schemaFile, updatedSchema);
runCli('db push', workDir);
// Step 3: Revert schema back to original default
const originalSchema = await formatDocument(`${getDefaultPrelude()}
model User {
id Int @id @default(autoincrement())
email String @unique
status String @default('active')
}`);
fs.writeFileSync(schemaFile, originalSchema);
// Step 4: Pull from database - should detect that default changed
runCli('db pull --indent 4', workDir);
// Step 5: Verify that pulled schema has updated default (matching database)
const pulledSchema = getSchema(workDir);
expect(pulledSchema).toEqual(updatedSchema);
});
});
});
describe('DB pull - PostgreSQL specific features', () => {
it('should restore schema with multiple database schemas', async ({ skip }) => {
const provider = getTestDbProvider();
if (provider !== 'postgresql') {
skip();
return;
}
const { workDir, schema } = await createProject(
`model User {
id Int @id @default(autoincrement())
email String @unique
posts Post[]
@@schema('auth')
}
model Post {
id Int @id @default(autoincrement())
title String
author User @relation(fields: [authorId], references: [id], onDelete: Cascade)
authorId Int
@@schema('content')
}`,
{ provider: 'postgresql', datasourceFields:{ schemas: ['public', 'content', 'auth'] } },
);
runCli('db push', workDir);
const schemaFile = path.join(workDir, 'zenstack/schema.zmodel');
fs.writeFileSync(schemaFile, getDefaultPrelude({ provider: 'postgresql', datasourceFields:{ schemas: ['public', 'content', 'auth']} }));
runCli('db pull --indent 4', workDir);
const restoredSchema = getSchema(workDir);
expect(restoredSchema).toEqual(schema);
});
it('should preserve native PostgreSQL enums when schema exists', async ({ skip }) => {
const provider = getTestDbProvider();
if (provider !== 'postgresql') {
skip();
return;
}
const { workDir, schema } = await createProject(
`model User {
id Int @id @default(autoincrement())
email String @unique
status Status @default(ACTIVE)
role Role @default(USER)
}
enum Status {
ACTIVE
INACTIVE
SUSPENDED
}
enum Role {
USER
ADMIN
MODERATOR
}`,
{ provider: 'postgresql' },
);
runCli('db push', workDir);
runCli('db pull --indent 4', workDir);
const pulledSchema = getSchema(workDir);
expect(pulledSchema).toEqual(schema);
});
it('should not modify schema with PostgreSQL-specific features', async ({ skip }) => {
const provider = getTestDbProvider();
if (provider !== 'postgresql') {
skip();
return;
}
const { workDir, schema } = await createProject(
`model User {
id Int @id @default(autoincrement())
email String @unique
status Status @default(ACTIVE)
posts Post[]
metadata Json?
@@schema('auth')
@@index([status])
}
model Post {
id Int @id @default(autoincrement())
title String
author User @relation(fields: [authorId], references: [id], onDelete: Cascade)
authorId Int
tags String[]
@@schema('content')
@@index([authorId])
}
enum Status {
ACTIVE
INACTIVE
SUSPENDED
}`,
{ provider: 'postgresql', datasourceFields:{ schemas: ['public', 'content', 'auth'] } },
);
runCli('db push', workDir);
runCli('db pull --indent 4', workDir);
expect(getSchema(workDir)).toEqual(schema);
});
it('should restore native type attributes from PostgreSQL typnames', async ({ skip }) => {
const provider = getTestDbProvider();
if (provider !== 'postgresql') {
skip();
return;
}
// PostgreSQL introspection returns typnames like 'int2', 'float8', 'bpchar',
// but Prisma/ZenStack attributes are named @db.SmallInt, @db.DoublePrecision, @db.Char, etc.
// This test verifies the mapping works correctly.
// Note: Default native types (jsonb for Json, bytea for Bytes) are not added when pulling from zero
// because they match the default database type for that field type.
const { workDir } = await createProject(
`model TypeTest {
id Int @id @default(autoincrement())
smallNumber Int @db.SmallInt()
realNumber Float @db.Real()
doubleNum Float @db.DoublePrecision()
fixedChar String @db.Char(10)
uuid String @db.Uuid()
jsonData Json @db.Json()
jsonbData Json @db.JsonB()
binaryData Bytes @db.ByteA()
}`,
{ provider: 'postgresql' },
);
runCli('db push', workDir);
const schemaFile = path.join(workDir, 'zenstack/schema.zmodel');
// Remove schema content to simulate restoration from zero
fs.writeFileSync(schemaFile, getDefaultPrelude({ provider: 'postgresql' }));
// Pull should restore non-default native type attributes
// Default types (jsonb for Json, bytea for Bytes) are not added
runCli('db pull --indent 4', workDir);
const restoredSchema = getSchema(workDir);
// Verify key native type mappings are restored correctly:
// - @db.SmallInt for int2 (non-default for Int which defaults to integer/int4)
// - @db.Real for float4 (non-default for Float which defaults to double precision/float8)
// - @db.Char(10) for bpchar with length (non-default for String which defaults to text)
// - @db.Uuid for uuid (non-default for String which defaults to text)
// - @db.Json for json (non-default for Json which defaults to jsonb)
expect(restoredSchema).toContain('@db.SmallInt');
expect(restoredSchema).toContain('@db.Real');
expect(restoredSchema).toContain('@db.Char(10)');
expect(restoredSchema).toContain('@db.Uuid');
expect(restoredSchema).toContain('@db.Json');
// Default types should NOT be added when pulling from zero
expect(restoredSchema).not.toContain('@db.Integer'); // integer is default for Int
expect(restoredSchema).not.toContain('@db.DoublePrecision'); // double precision is default for Float
expect(restoredSchema).not.toContain('@db.JsonB'); // jsonb is default for Json
expect(restoredSchema).not.toContain('@db.ByteA'); // bytea is default for Bytes
});
it('should correctly map composite foreign key columns by position', async ({ skip }) => {
const provider = getTestDbProvider();
if (provider !== 'postgresql') {
skip();
return;
}
// Composite FK: (tenantId, authorId) REFERENCES Tenant(tenantId, userId)
// The introspection must correlate by position, not match each source column
// to every target column. Without the fix, tenantId would incorrectly map to
// both tenantId AND userId in the target table.
const { workDir, schema } = await createProject(
`model Post {
id Int @id @default(autoincrement())
title String
tenant Tenant @relation(fields: [tenantId, authorId], references: [tenantId, userId], onDelete: Cascade)
tenantId Int
authorId Int
@@index([tenantId, authorId])
}
model Tenant {
tenantId Int
userId Int
name String
posts Post[]
@@id([tenantId, userId])
}`,
{ provider: 'postgresql' },