-
-
Notifications
You must be signed in to change notification settings - Fork 495
/
EntityManager.mysql.test.ts
1988 lines (1715 loc) · 86.1 KB
/
EntityManager.mysql.test.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 { v4 } from 'uuid';
import chalk from 'chalk';
import {
Collection, Configuration, EntityManager, LockMode, MikroORM, QueryOrder, Reference, Utils, Logger, ValidationError, wrap,
UniqueConstraintViolationException, TableNotFoundException, NotNullConstraintViolationException, TableExistsException, SyntaxErrorException,
NonUniqueFieldNameException, InvalidFieldNameException,
} from '@mikro-orm/core';
import { MySqlDriver, MySqlConnection } from '@mikro-orm/mysql';
import { Author2, Book2, BookTag2, FooBar2, FooBaz2, Publisher2, PublisherType, Test2 } from './entities-sql';
import { initORMMySql, wipeDatabaseMySql } from './bootstrap';
describe('EntityManagerMySql', () => {
let orm: MikroORM<MySqlDriver>;
beforeAll(async () => orm = await initORMMySql());
beforeEach(async () => wipeDatabaseMySql(orm.em));
test('isConnected()', async () => {
expect(await orm.isConnected()).toBe(true);
await orm.close(true);
expect(await orm.isConnected()).toBe(false);
await orm.connect();
expect(await orm.isConnected()).toBe(true);
});
test('getConnectionOptions()', async () => {
const config = new Configuration({
type: 'mysql',
clientUrl: 'mysql://root@127.0.0.1:3308/db_name',
host: '127.0.0.10',
password: 'secret',
user: 'user',
logger: jest.fn(),
forceUtcTimezone: true,
} as any, false);
const driver = new MySqlDriver(config);
expect(driver.getConnection().getConnectionOptions()).toEqual({
database: 'db_name',
host: '127.0.0.10',
password: 'secret',
port: 3308,
user: 'user',
timezone: 'Z',
supportBigNumbers: true,
});
});
test('should return mysql driver', async () => {
const driver = orm.em.getDriver();
expect(driver).toBeInstanceOf(MySqlDriver);
await expect(driver.findOne(Book2.name, { title: 'bar' })).resolves.toBeNull();
const author = await driver.nativeInsert(Author2.name, { name: 'author', email: 'email' });
const tag = await driver.nativeInsert(BookTag2.name, { name: 'tag name' });
expect((await driver.nativeInsert(Book2.name, { uuid: v4(), author: author.insertId, tags: [tag.insertId] })).insertId).not.toBeNull();
await expect(driver.getConnection().execute('select 1 as count')).resolves.toEqual([{ count: 1 }]);
await expect(driver.getConnection().execute('select 1 as count', [], 'get')).resolves.toEqual({ count: 1 });
await expect(driver.getConnection().execute('select 1 as count', [], 'run')).resolves.toEqual([{ count: 1 }]);
await expect(driver.getConnection().execute('insert into test2 (name) values (?)', ['test'], 'run')).resolves.toEqual({
affectedRows: 1,
insertId: 1,
});
await expect(driver.getConnection().execute('update test2 set name = ? where name = ?', ['test 2', 'test'], 'run')).resolves.toEqual({
affectedRows: 1,
insertId: 0,
});
await expect(driver.getConnection().execute('delete from test2 where name = ?', ['test 2'], 'run')).resolves.toEqual({
affectedRows: 1,
insertId: 0,
});
expect(driver.getPlatform().usesImplicitTransactions()).toBe(true);
expect(driver.getPlatform().denormalizePrimaryKey(1)).toBe(1);
expect(driver.getPlatform().denormalizePrimaryKey('1')).toBe('1');
await expect(driver.find(BookTag2.name, { books: { $in: [1] } })).resolves.not.toBeNull();
await expect(driver.ensureIndexes()).rejects.toThrowError('MySqlDriver does not use ensureIndexes');
const conn = driver.getConnection();
await conn.transactional(async tx => {
await conn.execute('select 1', [], 'all', tx);
await conn.execute(orm.em.getKnex().raw('select 1'), [], 'all', tx);
await conn.execute(orm.em.getRepository(Author2).getKnex().raw('select 1'), [], 'all', tx);
});
});
test('driver appends errored query', async () => {
const driver = orm.em.getDriver();
const err1 = `insert into \`not_existing\` (\`foo\`) values ('bar') - Table 'mikro_orm_test.not_existing' doesn't exist`;
await expect(driver.nativeInsert('not_existing', { foo: 'bar' })).rejects.toThrowError(err1);
const err2 = `delete from \`not_existing\` - Table 'mikro_orm_test.not_existing' doesn't exist`;
await expect(driver.nativeDelete('not_existing', {})).rejects.toThrowError(err2);
});
test('connection returns correct URL', async () => {
const conn1 = new MySqlConnection(new Configuration({
type: 'mysql',
clientUrl: 'mysql://example.host.com',
port: 1234,
user: 'usr',
password: 'pw',
} as any, false));
await expect(conn1.getClientUrl()).toBe('mysql://usr:*****@example.host.com:1234');
const conn2 = new MySqlConnection(new Configuration({ type: 'mysql', port: 3307 } as any, false));
await expect(conn2.getClientUrl()).toBe('mysql://root@127.0.0.1:3307');
});
test('should convert entity to PK when trying to search by entity', async () => {
const repo = orm.em.getRepository(Author2);
const author = new Author2('name', 'email');
author.termsAccepted = true;
author.favouriteAuthor = author;
await repo.persistAndFlush(author);
const a = await repo.findOne(author);
const authors = await repo.find({ favouriteAuthor: author });
expect(a).toBe(author);
expect(authors[0]).toBe(author);
expect(await repo.findOne({ termsAccepted: false })).toBeNull();
});
test('should allow shadow properties in EM.create()', async () => {
const repo = orm.em.getRepository(Author2);
const author = repo.create({ name: 'name', email: 'email', version: 123 });
await expect(author.version).toBe(123);
});
test('should create UUID value when using EM.create()', async () => {
const repo = orm.em.getRepository(Book2);
const book = repo.create({ title: 'name', author: 123 });
expect(book.uuid).toBeDefined();
});
test('manual mapping of raw DB results to entities vie EM.map()', async () => {
const repo = orm.em.getRepository(Book2);
const book = repo.map({
uuid_pk: '123-dsa',
title: 'name',
created_at: '2019-06-09T07:50:25.722Z',
author_id: 123,
publisher_id: 321,
tags: ['1', '2', '3'],
})!;
expect(book.uuid).toBe('123-dsa');
expect(book.title).toBe('name');
expect(book.createdAt).toBeInstanceOf(Date);
expect(book.author).toBeInstanceOf(Author2);
expect(book.author.id).toBe(123);
expect(book.publisher).toBeInstanceOf(Reference);
expect(book.publisher!.unwrap()).toBeInstanceOf(Publisher2);
expect(book.publisher!.id).toBe(321);
expect(book.tags.length).toBe(3);
expect(book.tags[0]).toBeInstanceOf(BookTag2);
expect(book.tags[0].id).toBe('1'); // bigint as string
expect(book.tags[1].id).toBe('2');
expect(book.tags[2].id).toBe('3');
expect(repo.getReference(book.uuid)).toBe(book);
});
test('should work with boolean values', async () => {
const repo = orm.em.getRepository(Author2);
const author = new Author2('name', 'email');
await repo.persistAndFlush(author);
expect(author.termsAccepted).toBe(false);
author.termsAccepted = true;
await repo.persistAndFlush(author);
expect(author.termsAccepted).toBe(true);
orm.em.clear();
const a1 = await repo.findOne({ termsAccepted: false });
expect(a1).toBeNull();
const a2 = (await repo.findOne({ termsAccepted: true }))!;
expect(a2).not.toBeNull();
a2.termsAccepted = false;
await repo.persistAndFlush(a2);
orm.em.clear();
const a3 = (await repo.findOne({ termsAccepted: false }))!;
expect(a3).not.toBeNull();
expect(a3.termsAccepted).toBe(false);
const a4 = await repo.findOne({ termsAccepted: true });
expect(a4).toBeNull();
});
test(`populating inverse side of 1:1 also back-links inverse side's owner`, async () => {
const bar = FooBar2.create('fb');
bar.baz = new FooBaz2('fz');
await orm.em.persistAndFlush(bar);
orm.em.clear();
const repo = orm.em.getRepository(FooBar2);
const a = await repo.findOne(bar.id, ['baz']);
expect(wrap(a!.baz).isInitialized()).toBe(true);
expect(wrap(a!.baz!.bar).isInitialized()).toBe(true);
});
test('factory should support a primary key value of 0', async () => {
const factory = orm.em.getEntityFactory();
const p1 = new Publisher2(); // calls constructor, so uses default name
expect(p1.name).toBe('asd');
expect(p1).toBeInstanceOf(Publisher2);
expect(p1.books).toBeInstanceOf(Collection);
expect(p1.tests).toBeInstanceOf(Collection);
const p2 = factory.create(Publisher2, { id: 0 }); // shouldn't call constructor
expect(p2).toBeInstanceOf(Publisher2);
expect(p2.name).toBeUndefined();
expect(p2.books).toBeInstanceOf(Collection);
expect(p2.tests).toBeInstanceOf(Collection);
});
test(`1:1 relationships with an inverse side primary key of 0 should link`, async () => {
// Set up static data with id of 0
const driver = orm.em.getDriver();
const response = await driver.getConnection().execute('SET sql_mode = \'NO_AUTO_VALUE_ON_ZERO\';insert into foo_baz2 (id, name) values (?, ?)', [0, 'testBaz'], 'run');
expect(response[1]).toMatchObject({
affectedRows: 1,
insertId: 0,
});
const fooBazRef = orm.em.getReference<FooBaz2>(FooBaz2, 0);
const fooBar = FooBar2.create('testBar');
fooBar.baz = Reference.create(fooBazRef);
await orm.em.persistAndFlush(fooBar);
orm.em.clear();
const repo = orm.em.getRepository(FooBar2);
const a = await repo.findOne(fooBar.id, ['baz']);
expect(wrap(a!.baz).isInitialized()).toBe(true);
expect(a!.baz!.id).toBe(0);
expect(a!.baz!.name).toBe('testBaz');
});
test('inverse side of 1:1 is ignored in change set', async () => {
const bar = FooBar2.create('fb');
bar.baz = new FooBaz2('fz 1');
await orm.em.persistAndFlush(bar);
bar.baz = new FooBaz2('fz 2');
await orm.em.flush();
});
test('transactions', async () => {
const god1 = new Author2('God1', 'hello@heaven1.god');
try {
await orm.em.transactional(async em => {
await em.persistAndFlush(god1);
throw new Error(); // rollback the transaction
});
} catch { }
const res1 = await orm.em.findOne(Author2, { name: 'God1' });
expect(res1).toBeNull();
const ret = await orm.em.transactional(async em => {
const god2 = new Author2('God2', 'hello@heaven2.god');
await em.persist(god2);
return true;
});
const res2 = await orm.em.findOne(Author2, { name: 'God2' });
expect(res2).not.toBeNull();
expect(ret).toBe(true);
const err = new Error('Test');
try {
await orm.em.transactional(async em => {
const god3 = new Author2('God4', 'hello@heaven4.god');
await em.persist(god3);
throw err;
});
} catch (e) {
expect(e).toBe(err);
const res3 = await orm.em.findOne(Author2, { name: 'God4' });
expect(res3).toBeNull();
}
});
test('nested transactions with save-points', async () => {
await orm.em.transactional(async em => {
const god1 = new Author2('God1', 'hello1@heaven.god');
try {
await em.transactional(async em2 => {
await em2.persist(god1);
throw new Error(); // rollback the transaction
});
} catch { }
const res1 = await em.findOne(Author2, { name: 'God1' });
expect(res1).toBeNull();
await em.transactional(async em2 => {
const god2 = new Author2('God2', 'hello2@heaven.god');
em2.persist(god2);
});
const res2 = await em.findOne(Author2, { name: 'God2' });
expect(res2).not.toBeNull();
});
});
test('nested transaction rollback with save-points will commit the outer one', async () => {
const mock = jest.fn();
const logger = new Logger(mock, true);
Object.assign(orm.em.config, { logger });
// start outer transaction
const transaction = orm.em.transactional(async em => {
// do stuff inside inner transaction and rollback
try {
await em.transactional(async em2 => {
await em2.persistAndFlush(new Author2('God', 'hello@heaven.god'));
throw new Error(); // rollback the transaction
});
} catch { }
await em.persist(new Author2('God Persisted!', 'hello-persisted@heaven.god'));
});
// try to commit the outer transaction
await expect(transaction).resolves.toBeUndefined();
expect(mock.mock.calls.length).toBe(6);
expect(mock.mock.calls[0][0]).toMatch('begin');
expect(mock.mock.calls[1][0]).toMatch('savepoint trx');
expect(mock.mock.calls[2][0]).toMatch('insert into `author2` (`created_at`, `email`, `name`, `terms_accepted`, `updated_at`) values (?, ?, ?, ?, ?)');
expect(mock.mock.calls[3][0]).toMatch('rollback to savepoint trx');
expect(mock.mock.calls[4][0]).toMatch('insert into `author2` (`created_at`, `email`, `name`, `terms_accepted`, `updated_at`) values (?, ?, ?, ?, ?)');
expect(mock.mock.calls[5][0]).toMatch('commit');
await expect(orm.em.findOne(Author2, { name: 'God Persisted!' })).resolves.not.toBeNull();
});
test('should load entities', async () => {
expect(orm).toBeInstanceOf(MikroORM);
expect(orm.em).toBeInstanceOf(EntityManager);
const god = new Author2('God', 'hello@heaven.god');
const bible = new Book2('Bible', god);
await orm.em.persistAndFlush(bible);
const author = new Author2('Jon Snow', 'snow@wall.st');
author.born = new Date('1990-03-23');
author.bornTime = '00:23:59';
author.favouriteBook = bible;
const publisher = new Publisher2('7K publisher', PublisherType.GLOBAL);
// as we order by Book.createdAt when populating collection, we need to make sure values will be sequential
const book1 = new Book2('My Life on The Wall, part 1', author);
book1.createdAt = new Date(Date.now() + 1);
book1.publisher = wrap(publisher).toReference();
const book2 = new Book2('My Life on The Wall, part 2', author);
book2.createdAt = new Date(Date.now() + 2);
book2.publisher = wrap(publisher).toReference();
const book3 = new Book2('My Life on The Wall, part 3', author);
book3.createdAt = new Date(Date.now() + 3);
book3.publisher = wrap(publisher).toReference();
const repo = orm.em.getRepository(Book2);
repo.persist(book1);
repo.persist(book2);
repo.persist(book3);
await repo.flush();
orm.em.clear();
const publisher7k = (await orm.em.getRepository(Publisher2).findOne({ name: '7K publisher' }))!;
expect(publisher7k).not.toBeNull();
expect(publisher7k.tests).toBeInstanceOf(Collection);
expect(publisher7k.tests.isInitialized()).toBe(false);
orm.em.clear();
const authorRepository = orm.em.getRepository(Author2);
const booksRepository = orm.em.getRepository(Book2);
const books = await booksRepository.findAll(['author']);
expect(wrap(books[0].author).isInitialized()).toBe(true);
expect(await authorRepository.findOne({ favouriteBook: bible.uuid })).not.toBe(null);
orm.em.clear();
const noBooks = await booksRepository.find({ title: 'not existing' }, ['author']);
expect(noBooks.length).toBe(0);
orm.em.clear();
const jon = (await authorRepository.findOne({ name: 'Jon Snow' }))!;
await orm.em.populate(jon, ['books', 'favouriteBook']);
const authors = await authorRepository.findAll();
await orm.em.populate(authors, ['books', 'favouriteBook']);
expect(await authorRepository.findOne({ email: 'not existing' })).toBeNull();
await expect(orm.em.populate([], ['books', 'favouriteBook'])).resolves.toEqual([]);
// count test
const count = await authorRepository.count();
expect(count).toBe(authors.length);
const count2 = await orm.em.count(Author2);
expect(count2).toBe(authors.length);
// identity map test
authors.shift(); // shift the god away, as that entity is detached from IM
expect(jon).toBe(authors[0]);
expect(jon).toBe(await authorRepository.findOne(jon.id));
// serialization test
const o = wrap(jon).toJSON();
expect(o).toMatchObject({
id: jon.id,
createdAt: jon.createdAt,
updatedAt: jon.updatedAt,
books: [
{ author: jon.id, publisher: publisher.id, title: 'My Life on The Wall, part 1' },
{ author: jon.id, publisher: publisher.id, title: 'My Life on The Wall, part 2' },
{ author: jon.id, publisher: publisher.id, title: 'My Life on The Wall, part 3' },
],
favouriteBook: { author: god.id, title: 'Bible' },
born: '1990-03-23',
bornTime: '00:23:59',
email: 'snow@wall.st',
name: 'Jon Snow',
});
expect(wrap(jon).toJSON()).toEqual(o);
expect(jon.books.getIdentifiers()).toBeInstanceOf(Array);
expect(typeof jon.books.getIdentifiers()[0]).toBe('string');
for (const author of authors) {
expect(author.books).toBeInstanceOf(Collection);
expect(author.books.isInitialized()).toBe(true);
// iterator test
for (const book of author.books) {
expect(book.title).toMatch(/My Life on The Wall, part \d/);
expect(book.author).toBeInstanceOf(Author2);
expect(wrap(book.author).isInitialized()).toBe(true);
expect(book.publisher).toBeInstanceOf(Reference);
expect(book.publisher!.unwrap()).toBeInstanceOf(Publisher2);
expect(wrap(book.publisher).isInitialized()).toBe(false);
}
}
const booksByTitleAsc = await booksRepository.find({ author: jon.id }, [], { title: QueryOrder.ASC });
expect(booksByTitleAsc[0].title).toBe('My Life on The Wall, part 1');
expect(booksByTitleAsc[1].title).toBe('My Life on The Wall, part 2');
expect(booksByTitleAsc[2].title).toBe('My Life on The Wall, part 3');
const booksByTitleDesc = await booksRepository.find({ author: jon.id }, [], { title: QueryOrder.DESC });
expect(booksByTitleDesc[0].title).toBe('My Life on The Wall, part 3');
expect(booksByTitleDesc[1].title).toBe('My Life on The Wall, part 2');
expect(booksByTitleDesc[2].title).toBe('My Life on The Wall, part 1');
const twoBooks = await booksRepository.find({ author: jon.id }, [], { title: QueryOrder.DESC }, 2);
expect(twoBooks.length).toBe(2);
expect(twoBooks[0].title).toBe('My Life on The Wall, part 3');
expect(twoBooks[1].title).toBe('My Life on The Wall, part 2');
const lastBook = await booksRepository.find({ author: jon.id }, ['author'], { title: QueryOrder.DESC }, 2, 2);
expect(lastBook.length).toBe(1);
expect(lastBook[0].title).toBe('My Life on The Wall, part 1');
expect(lastBook[0].author).toBeInstanceOf(Author2);
expect(wrap(lastBook[0].author).isInitialized()).toBe(true);
await orm.em.getRepository(Book2).remove(lastBook[0].uuid);
});
test('json properties', async () => {
const god = new Author2('God', 'hello@heaven.god');
god.identities = ['fb-123', 'pw-231', 'tw-321'];
const bible = new Book2('Bible', god);
bible.meta = { category: 'god like', items: 3 };
await orm.em.persistAndFlush(bible);
orm.em.clear();
const g = (await orm.em.findOne(Author2, god.id, ['books']))!;
expect(Array.isArray(g.identities)).toBe(true);
expect(g.identities).toEqual(['fb-123', 'pw-231', 'tw-321']);
expect(typeof g.books[0].meta).toBe('object');
expect(g.books[0].meta).toEqual({ category: 'god like', items: 3 });
});
test('findOne should initialize entity that is already in IM', async () => {
const god = new Author2('God', 'hello@heaven.god');
const bible = new Book2('Bible', god);
await orm.em.persistAndFlush(bible);
orm.em.clear();
const ref = orm.em.getReference(Author2, god.id);
expect(wrap(ref).isInitialized()).toBe(false);
const newGod = await orm.em.findOne(Author2, god.id);
expect(ref).toBe(newGod);
expect(wrap(ref).isInitialized()).toBe(true);
});
test('findOne supports regexps', async () => {
const author1 = new Author2('Author 1', 'a1@example.com');
const author2 = new Author2('Author 2', 'a2@example.com');
const author3 = new Author2('Author 3', 'a3@example.com');
await orm.em.persistAndFlush([author1, author2, author3]);
orm.em.clear();
const authors = await orm.em.find(Author2, { email: /exa.*le\.c.m$/ });
expect(authors.length).toBe(3);
expect(authors[0].name).toBe('Author 1');
expect(authors[1].name).toBe('Author 2');
expect(authors[2].name).toBe('Author 3');
orm.em.clear();
const authors2 = await orm.em.find(Author2, { email: { $re: 'exa.*le.c.m$' } });
expect(authors2.length).toBe(3);
expect(authors2[0].name).toBe('Author 1');
expect(authors2[1].name).toBe('Author 2');
expect(authors2[2].name).toBe('Author 3');
});
test('findOne supports optimistic locking [testMultipleFlushesDoIncrementalUpdates]', async () => {
const test = new Test2();
for (let i = 0; i < 5; i++) {
test.name = 'test' + i;
await orm.em.persistAndFlush(test);
expect(typeof test.version).toBe('number');
expect(test.version).toBe(i + 1);
}
});
test('findOne supports optimistic locking [testStandardFailureThrowsException]', async () => {
const test = new Test2();
test.name = 'test';
await orm.em.persistAndFlush(test);
expect(typeof test.version).toBe('number');
expect(test.version).toBe(1);
orm.em.clear();
const test2 = await orm.em.findOne(Test2, test.id);
await orm.em.nativeUpdate(Test2, { id: test.id }, { name: 'Changed!' }); // simulate concurrent update
test2!.name = 'WHATT???';
try {
await orm.em.flush();
expect(1).toBe('should be unreachable');
} catch (e) {
expect(e).toBeInstanceOf(ValidationError);
expect(e.message).toBe(`The optimistic lock on entity Test2 failed`);
expect((e as ValidationError).getEntity()).toBe(test2);
}
});
test('findOne supports optimistic locking [versioned proxy]', async () => {
const test = new Test2();
test.name = 'test';
await orm.em.persistAndFlush(test);
orm.em.clear();
const proxy = orm.em.getReference(Test2, test.id);
await orm.em.lock(proxy, LockMode.OPTIMISTIC, 1);
expect(wrap(proxy).isInitialized()).toBe(true);
});
test('findOne supports optimistic locking [versioned entity]', async () => {
const test = new Test2();
test.name = 'test';
await orm.em.persistAndFlush(test);
orm.em.clear();
const test2 = await orm.em.findOne(Test2, test.id, { lockMode: LockMode.OPTIMISTIC, lockVersion: test.version });
await orm.em.lock(test2!, LockMode.OPTIMISTIC, test.version);
const test3 = await orm.em.findOne(Test2, test.id, { lockMode: LockMode.OPTIMISTIC, lockVersion: test.version });
expect(test3).toBe(test2);
});
test('findOne supports optimistic locking [testOptimisticTimestampLockFailureThrowsException]', async () => {
const bar = FooBar2.create('Testing');
expect(bar.version).toBeUndefined();
await orm.em.persistAndFlush(bar);
expect(bar.version).toBeInstanceOf(Date);
orm.em.clear();
const bar2 = (await orm.em.findOne(FooBar2, bar.id))!;
expect(bar2.version).toBeInstanceOf(Date);
try {
// Try to lock the record with an older timestamp and it should throw an exception
const expectedVersionExpired = new Date(+bar2.version - 3600);
await orm.em.lock(bar2, LockMode.OPTIMISTIC, expectedVersionExpired);
expect(1).toBe('should be unreachable');
} catch (e) {
expect((e as ValidationError).getEntity()).toBe(bar2);
}
});
test('findOne supports optimistic locking [unversioned entity]', async () => {
const author = new Author2('name', 'email');
await orm.em.persistAndFlush(author);
await expect(orm.em.lock(author, LockMode.OPTIMISTIC)).rejects.toThrowError('Cannot obtain optimistic lock on unversioned entity Author2');
await expect(orm.em.findOne(Author2, author.id, { lockMode: LockMode.OPTIMISTIC })).rejects.toThrowError('Cannot obtain optimistic lock on unversioned entity Author2');
});
test('lock supports optimistic locking [versioned entity]', async () => {
const test = new Test2();
test.name = 'test';
await orm.em.persistAndFlush(test);
await orm.em.lock(test, undefined!);
await orm.em.lock(test, LockMode.OPTIMISTIC);
await orm.em.lock(test, LockMode.OPTIMISTIC, test.version);
});
test('lock supports optimistic locking [version mismatch]', async () => {
const test = new Test2();
test.name = 'test';
await orm.em.persistAndFlush(test);
await expect(orm.em.lock(test, LockMode.OPTIMISTIC, test.version + 1)).rejects.toThrowError('The optimistic lock failed, version 2 was expected, but is actually 1');
});
test('lock supports optimistic locking [testLockUnmanagedEntityThrowsException]', async () => {
const test = new Test2();
test.name = 'test';
await expect(orm.em.lock(test, LockMode.OPTIMISTIC)).rejects.toThrowError('Entity Test2 is not managed. An entity is managed if its fetched from the database or registered as new through EntityManager.persist()');
});
test('pessimistic locking requires active transaction', async () => {
const test = Test2.create('Lock test');
await orm.em.persistAndFlush(test);
await expect(orm.em.findOne(Test2, test.id, { lockMode: LockMode.PESSIMISTIC_READ })).rejects.toThrowError('An open transaction is required for this operation');
await expect(orm.em.findOne(Test2, test.id, { lockMode: LockMode.PESSIMISTIC_WRITE })).rejects.toThrowError('An open transaction is required for this operation');
await expect(orm.em.lock(test, LockMode.PESSIMISTIC_READ)).rejects.toThrowError('An open transaction is required for this operation');
await expect(orm.em.lock(test, LockMode.PESSIMISTIC_WRITE)).rejects.toThrowError('An open transaction is required for this operation');
});
test('lock supports pessimistic locking [pessimistic write]', async () => {
const author = new Author2('name', 'email');
await orm.em.persistAndFlush(author);
const mock = jest.fn();
const logger = new Logger(mock, true);
Object.assign(orm.em.config, { logger });
await orm.em.transactional(async em => {
await em.lock(author, LockMode.PESSIMISTIC_WRITE);
});
expect(mock.mock.calls.length).toBe(3);
expect(mock.mock.calls[0][0]).toMatch('begin');
expect(mock.mock.calls[1][0]).toMatch('select 1 from `author2` as `e0` where `e0`.`id` = ? for update');
expect(mock.mock.calls[2][0]).toMatch('commit');
});
test('lock supports pessimistic locking [pessimistic read]', async () => {
const author = new Author2('name', 'email');
await orm.em.persistAndFlush(author);
const mock = jest.fn();
const logger = new Logger(mock, true);
Object.assign(orm.em.config, { logger });
await orm.em.transactional(async em => {
await em.lock(author, LockMode.PESSIMISTIC_READ);
});
expect(mock.mock.calls.length).toBe(3);
expect(mock.mock.calls[0][0]).toMatch('begin');
expect(mock.mock.calls[1][0]).toMatch('select 1 from `author2` as `e0` where `e0`.`id` = ? lock in share mode');
expect(mock.mock.calls[2][0]).toMatch('commit');
});
test('custom query expressions via query builder', async () => {
const god = new Author2('God', 'hello@heaven.god');
const bible = new Book2('Bible', god);
bible.meta = { category: 'foo', items: 1 };
await orm.em.persistAndFlush(bible);
orm.em.clear();
const qb1 = orm.em.createQueryBuilder(Book2);
const res1 = await qb1.select('*').where({ 'JSON_CONTAINS(`e0`.`meta`, ?)': [{ foo: 'bar' }, false] }).execute('get');
expect(res1.createdAt).toBeDefined();
expect(res1.created_at).not.toBeDefined();
expect(res1.meta).toEqual({ category: 'foo', items: 1 });
const qb2 = orm.em.createQueryBuilder(Book2);
const res2 = await qb2.select('*').where({ 'JSON_CONTAINS(meta, ?)': [{ category: 'foo' }, true] }).execute('get', false);
expect(res2.createdAt).not.toBeDefined();
expect(res2.created_at).toBeDefined();
expect(res2.meta).toEqual({ category: 'foo', items: 1 });
const res3 = (await orm.em.findOne(Book2, { 'JSON_CONTAINS(meta, ?)': [{ items: 1 }, true] } as any))!;
expect(res3).toBeInstanceOf(Book2);
expect(res3.createdAt).toBeDefined();
expect(res3.meta).toEqual({ category: 'foo', items: 1 });
});
test('query builder getResult() and getSingleResult() return entities', async () => {
const god = new Author2('God', 'hello@heaven.god');
const bible = new Book2('Bible', god);
bible.meta = { category: 'foo', items: 1 };
await orm.em.persistAndFlush(bible);
orm.em.clear();
const qb1 = orm.em.createQueryBuilder(Book2);
const res1 = await qb1.select('*').getSingleResult();
expect(res1).toBeInstanceOf(Book2);
expect(res1!.createdAt).toBeDefined();
expect((res1 as any).created_at).not.toBeDefined();
expect(res1!.meta).toEqual({ category: 'foo', items: 1 });
expect(wrap(res1).isInitialized()).toBe(true);
const qb2 = orm.em.createQueryBuilder(Book2);
const res2 = await qb2.select('*').where({ title: 'not exists' }).getSingleResult();
expect(res2).toBeNull();
});
test('stable results of serialization', async () => {
const god = new Author2('God', 'hello@heaven.god');
const bible = new Book2('Bible', god);
const bible2 = new Book2('Bible pt. 2', god);
const bible3 = new Book2('Bible pt. 3', new Author2('Lol', 'lol@lol.lol'));
await orm.em.persistAndFlush([bible, bible2, bible3]);
orm.em.clear();
const newGod = (await orm.em.findOne(Author2, god.id))!;
const books = await orm.em.find(Book2, {});
await wrap(newGod).init(false);
for (const book of books) {
expect(wrap(book).toJSON()).toMatchObject({
author: book.author.id,
});
}
});
test('stable results of serialization (collection)', async () => {
const pub = new Publisher2('Publisher2');
await orm.em.persistAndFlush(pub);
const god = new Author2('God', 'hello@heaven.god');
const bible = new Book2('Bible', god);
bible.publisher = wrap(pub).toReference();
const bible2 = new Book2('Bible pt. 2', god);
bible2.publisher = wrap(pub).toReference();
const bible3 = new Book2('Bible pt. 3', new Author2('Lol', 'lol@lol.lol'));
bible3.publisher = wrap(pub).toReference();
await orm.em.persistAndFlush([bible, bible2, bible3]);
orm.em.clear();
const newGod = orm.em.getReference(Author2, god.id);
const publisher = (await orm.em.findOne(Publisher2, pub.id, ['books']))!;
await wrap(newGod).init();
const json = wrap(publisher).toJSON().books;
for (const book of publisher.books) {
expect(json.find((b: Book2) => b.uuid === book.uuid)).toMatchObject({
author: book.author.id,
});
}
});
test('findOne by id', async () => {
const authorRepository = orm.em.getRepository(Author2);
const jon = new Author2('Jon Snow', 'snow@wall.st');
await authorRepository.persistAndFlush(jon);
orm.em.clear();
let author = (await authorRepository.findOne(jon.id))!;
expect(author).not.toBeNull();
expect(author.name).toBe('Jon Snow');
orm.em.clear();
author = (await authorRepository.findOne({ id: jon.id }))!;
expect(author).not.toBeNull();
expect(author.name).toBe('Jon Snow');
});
test('populate ManyToOne relation', async () => {
const authorRepository = orm.em.getRepository(Author2);
const god = new Author2('God', 'hello@heaven.god');
const bible = new Book2('Bible', god);
await orm.em.persistAndFlush(bible);
let jon = new Author2('Jon Snow', 'snow@wall.st');
jon.born = new Date();
jon.favouriteBook = bible;
await orm.em.persistAndFlush(jon);
orm.em.clear();
jon = (await authorRepository.findOne(jon.id))!;
expect(jon).not.toBeNull();
expect(jon.name).toBe('Jon Snow');
expect(jon.favouriteBook).toBeInstanceOf(Book2);
expect(wrap(jon.favouriteBook).isInitialized()).toBe(false);
await wrap(jon.favouriteBook).init();
expect(jon.favouriteBook).toBeInstanceOf(Book2);
expect(wrap(jon.favouriteBook).isInitialized()).toBe(true);
expect(jon.favouriteBook!.title).toBe('Bible');
});
test('populate OneToOne relation', async () => {
const bar = FooBar2.create('bar');
const baz = new FooBaz2('baz');
bar.baz = baz;
await orm.em.persistAndFlush(bar);
orm.em.clear();
const b1 = (await orm.em.findOne(FooBar2, { id: bar.id }, ['baz']))!;
expect(b1.baz).toBeInstanceOf(FooBaz2);
expect(b1.baz!.id).toBe(baz.id);
expect(wrap(b1).toJSON()).toMatchObject({ baz: wrap(baz).toJSON() });
});
test('populate OneToOne relation on inverse side', async () => {
const bar = FooBar2.create('bar');
const baz = new FooBaz2('baz');
bar.baz = baz;
await orm.em.persistAndFlush(bar);
orm.em.clear();
const mock = jest.fn();
const logger = new Logger(mock, true);
Object.assign(orm.em.config, { logger });
const b0 = (await orm.em.findOne(FooBaz2, { id: baz.id }))!;
expect(mock.mock.calls[0][0]).toMatch('select `e0`.*, `e1`.`id` as `bar_id` from `foo_baz2` as `e0` left join `foo_bar2` as `e1` on `e0`.`id` = `e1`.`baz_id` where `e0`.`id` = ? limit ?');
expect(b0.bar).toBeDefined();
expect(b0.bar).toBeInstanceOf(FooBar2);
expect(wrap(b0.bar).isInitialized()).toBe(false);
orm.em.clear();
const b1 = (await orm.em.findOne(FooBaz2, { id: baz.id }, ['bar']))!;
expect(mock.mock.calls[1][0]).toMatch('select `e0`.*, `e1`.`id` as `bar_id` from `foo_baz2` as `e0` left join `foo_bar2` as `e1` on `e0`.`id` = `e1`.`baz_id` where `e0`.`id` = ? limit ?');
expect(mock.mock.calls[2][0]).toMatch('select `e0`.* from `foo_bar2` as `e0` where `e0`.`id` in (?) order by `e0`.`id` asc');
expect(b1.bar).toBeInstanceOf(FooBar2);
expect(b1.bar!.id).toBe(bar.id);
expect(wrap(b1).toJSON()).toMatchObject({ bar: wrap(bar).toJSON() });
orm.em.clear();
const b2 = (await orm.em.findOne(FooBaz2, { bar: bar.id }, ['bar']))!;
expect(mock.mock.calls[3][0]).toMatch('select `e0`.*, `e1`.`id` as `bar_id` from `foo_baz2` as `e0` left join `foo_bar2` as `e1` on `e0`.`id` = `e1`.`baz_id` where `e1`.`id` = ? limit ?');
expect(mock.mock.calls[4][0]).toMatch('select `e0`.* from `foo_bar2` as `e0` where `e0`.`id` in (?) order by `e0`.`id` asc');
expect(b2.bar).toBeInstanceOf(FooBar2);
expect(b2.bar!.id).toBe(bar.id);
expect(wrap(b2).toJSON()).toMatchObject({ bar: wrap(bar).toJSON() });
});
test('populate OneToOne relation with uuid PK', async () => {
const author = new Author2('name', 'email');
const book = new Book2('b1', author);
const test = Test2.create('t');
test.book = book;
await orm.em.persistAndFlush(test);
orm.em.clear();
const b1 = (await orm.em.findOne(Book2, { test: test.id }, ['test.config']))!;
expect(b1.uuid).not.toBeNull();
expect(wrap(b1).toJSON()).toMatchObject({ test: wrap(test).toJSON() });
});
test('populate passes nested where and orderBy', async () => {
const author = new Author2('name', 'email');
const b1 = new Book2('b1', author);
const b2 = new Book2('b2', author);
const b3 = new Book2('b3', author);
const b4 = new Book2('b4', author);
const b5 = new Book2('b5', author);
const tag1 = new BookTag2('silly');
const tag2 = new BookTag2('funny');
const tag3 = new BookTag2('sick');
const tag4 = new BookTag2('strange');
const tag5 = new BookTag2('sexy');
b1.tags.add(tag1, tag3);
b2.tags.add(tag1, tag2, tag5);
b3.tags.add(tag5);
b4.tags.add(tag2, tag4, tag5);
b5.tags.add(tag5);
author.books.add(b1, b2, b3, b4, b5);
await orm.em.persistAndFlush(author);
orm.em.clear();
const a1 = await orm.em.find(Author2, author, ['books'], { books: { title: QueryOrder.DESC } });
expect(a1[0].books.getItems().map(b => b.title)).toEqual(['b5', 'b4', 'b3', 'b2', 'b1']);
orm.em.clear();
const a2 = await orm.em.findOneOrFail(Author2, author, ['books'], { books: { title: QueryOrder.DESC } });
expect(a2.books.getItems().map(b => b.title)).toEqual(['b5', 'b4', 'b3', 'b2', 'b1']);
orm.em.clear();
const a3 = await orm.em.findOneOrFail(Author2, { books: { tags: { name: { $in: ['silly', 'strange'] } } } }, ['books.tags'], { books: { tags: { name: QueryOrder.DESC }, title: QueryOrder.ASC } });
expect(a3.books.getItems().map(b => b.title)).toEqual(['b4', 'b1', 'b2']); // first strange tag (desc), then silly by name (asc)
});
test('many to many relation', async () => {
const author = new Author2('Jon Snow', 'snow@wall.st');
const book1 = new Book2('My Life on The Wall, part 1', author);
const book2 = new Book2('My Life on The Wall, part 2', author);
const book3 = new Book2('My Life on The Wall, part 3', author);
const tag1 = new BookTag2('silly');
const tag2 = new BookTag2('funny');
const tag3 = new BookTag2('sick');
const tag4 = new BookTag2('strange');
const tag5 = new BookTag2('sexy');
book1.tags.add(tag1, tag3);
book2.tags.add(tag1, tag2, tag5);
book3.tags.add(tag2, tag4, tag5);
orm.em.persist(book1);
orm.em.persist(book2);
await orm.em.persistAndFlush(book3);
expect(typeof tag1.id).toBe('string');
expect(typeof tag2.id).toBe('string');
expect(typeof tag3.id).toBe('string');
expect(typeof tag4.id).toBe('string');
expect(typeof tag5.id).toBe('string');
// test inverse side
const tagRepository = orm.em.getRepository(BookTag2);
let tags = await tagRepository.findAll();
expect(tags).toBeInstanceOf(Array);
expect(tags.length).toBe(5);
expect(tags[0]).toBeInstanceOf(BookTag2);
expect(tags[0].name).toBe('silly');
expect(tags[0].books).toBeInstanceOf(Collection);
expect(tags[0].books.isInitialized()).toBe(true);
expect(tags[0].books.isDirty()).toBe(false);
expect(tags[0].books.count()).toBe(2);
expect(tags[0].books.length).toBe(2);
orm.em.clear();
tags = await orm.em.find(BookTag2, {});
expect(tags[0].books.isInitialized()).toBe(false);
expect(tags[0].books.isDirty()).toBe(false);
expect(() => tags[0].books.getItems()).toThrowError(/Collection<Book2> of entity BookTag2\[\d+] not initialized/);
expect(() => tags[0].books.remove(book1, book2)).toThrowError(/Collection<Book2> of entity BookTag2\[\d+] not initialized/);
expect(() => tags[0].books.removeAll()).toThrowError(/Collection<Book2> of entity BookTag2\[\d+] not initialized/);
expect(() => tags[0].books.contains(book1)).toThrowError(/Collection<Book2> of entity BookTag2\[\d+] not initialized/);
// test M:N lazy load
orm.em.clear();
tags = await tagRepository.findAll();
await tags[0].books.init();
expect(tags[0].books.count()).toBe(2);
expect(tags[0].books.getItems()[0]).toBeInstanceOf(Book2);
expect(tags[0].books.getItems()[0].uuid).toBeDefined();
expect(wrap(tags[0].books.getItems()[0]).isInitialized()).toBe(true);
expect(tags[0].books.isInitialized()).toBe(true);
const old = tags[0];
expect(tags[1].books.isInitialized()).toBe(false);
tags = await tagRepository.findAll(['books']);
expect(tags[1].books.isInitialized()).toBe(true);
expect(tags[0].id).toBe(old.id);
expect(tags[0]).toBe(old);
expect(tags[0].books).toBe(old.books);
// test M:N lazy load
orm.em.clear();
let book = (await orm.em.findOne(Book2, book1.uuid))!;
expect(book.tags.isInitialized()).toBe(false);
await book.tags.init();
expect(book.tags.isInitialized()).toBe(true);
expect(book.tags.count()).toBe(2);
expect(book.tags.getItems()[0]).toBeInstanceOf(BookTag2);
expect(book.tags.getItems()[0].id).toBeDefined();
expect(wrap(book.tags.getItems()[0]).isInitialized()).toBe(true);
// test collection CRUD
// remove
expect(book.tags.count()).toBe(2);
book.tags.remove(tag1);
await orm.em.persistAndFlush(book);
orm.em.clear();
book = (await orm.em.findOne(Book2, book.uuid, ['tags']))!;
expect(book.tags.count()).toBe(1);
// add
book.tags.add(tagRepository.getReference(tag1.id)); // we need to get reference as tag1 is detached from current EM
book.tags.add(new BookTag2('fresh'));
await orm.em.persistAndFlush(book);
orm.em.clear();
book = (await orm.em.findOne(Book2, book.uuid, ['tags']))!;
expect(book.tags.count()).toBe(3);
// contains
expect(book.tags.contains(tag1)).toBe(true);
expect(book.tags.contains(tag2)).toBe(false);
expect(book.tags.contains(tag3)).toBe(true);
expect(book.tags.contains(tag4)).toBe(false);
expect(book.tags.contains(tag5)).toBe(false);
// removeAll
book.tags.removeAll();
await orm.em.persistAndFlush(book);
orm.em.clear();
book = (await orm.em.findOne(Book2, book.uuid, ['tags']))!;
expect(book.tags.count()).toBe(0);
});
test('bigint support', async () => {
const t = new BookTag2('test');
t.id = '9223372036854775807';
await orm.em.persistAndFlush(t);
expect(t.id).toBe('9223372036854775807');
orm.em.clear();
const t2 = await orm.em.findOneOrFail(BookTag2, t.id);
expect(t2.id).toBe('9223372036854775807');
});
test('many to many working with inverse side', async () => {
const author = new Author2('Jon Snow', 'snow@wall.st');
const book1 = new Book2('My Life on The Wall, part 1', author);
const book2 = new Book2('My Life on The Wall, part 2', author);