-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathindex.js
1597 lines (1324 loc) · 60.3 KB
/
index.js
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
/*
*
* This script generates a specific testing dataset for comparison of PostgreSQL and MongoDB database systems
* The generated data is an interpretation of actual data stored as rewritten Vital Records
* analyzed from "Moravský zemský archiv (MZA) v Brně: fond E67 - Sbírka matrik"
*
* Author: Marek Pakes, xpakes00@stud.fit.vutbr.cz
* Created for Bachelor's thesis on topic "Porovnání relačních a dokumentových databázových systémů pro genealogické účely"
* Year: 2019
*
*/
const startedGeneratingAt = new Date();
console.log('Started at: ', startedGeneratingAt);
// Files from ./data -> Most common names, surnames, villages, occupations in Czech republic
// extracted from freely available data
// *_TITLES & DEATH_CAUSES extracted from provided documents from MZA
const VILLAGES = require('./data/towns.cz');
const NAMES_MEN = require('./data/names.men');
const NAMES_WOMEN = require('./data/names.women');
const SURNAMES_MEN = require('./data/surnames.men');
const SURNAMES_WOMEN = require('./data/surnames.women');
const PERSON_OCCUPATIONS = require('./data/occupations');
const DIRECTOR_TITLES = require('./data/director.titles');
const CELEBRANT_TITLES = require('./data/celebrant.titles');
const OFFICIANT_TITLES = require('./data/officiant.titles');
const DEATH_CAUSES = require('./data/death.causes');
const POSTGRES_CREDENTIALS = require('./postgres/credentials');
// Node.js File System (to write into output files)
// https://nodejs.org/api/fs.html
const fs = require('fs');
// Package for generating random names for Users + street & descr numbers for Persons
// https://www.npmjs.com/package/faker
const faker = require('faker');
// Library for working with dates (adding, subtracting)
// https://date-fns.org/
const dateFns = require('date-fns');
// MongoDB Node.JS Driver
// http://mongodb.github.io/node-mongodb-native/3.1/api/
const MongoClient = require('mongodb').MongoClient;
const assert = require('assert'); // for testing connections
const usersCount = 2; // number of users ("User" table)
// Registers count = archivesCount * fondsCount * signaturesCount ("Register" table entities count)
const archivesCount = 3; // number of generated unique archives
const fondsCount = 5; // number of generated unique fonds inside an archive
const signaturesCount = 15; // number of generated unique signatures inside of an archive fond
const directorsCount = 3; // number of unique funeral directors ("Director" table entities count)
const celebrantsCount = 3; // number of unique funeral celebrants ("Celebrant" table entities count)
const officiantsCount = 3; // number of unique marriage officiants ("Officiant" table entities count)
const villagesCount = Math.min(VILLAGES.length, 15);
/*** Parse args ***/
let recordsCount = 1000; // ("Death" table + "Marriage" table entities count)
let createIndexes = true;
const args = require('minimist')(process.argv.slice(2));
Object.keys(args).map(key => {
if (key === 'createIndexes') {
createIndexes = args['createIndexes'];
}
if (key === 'recordsCount') {
recordsCount = args['recordsCount'];
}
});
const computedMarriageRecordsCount = Math.floor(recordsCount / 3); // ("Marriage" table entities count)
/***
* IMPORTANT NOTE: ALL PERSONS -> not only brides, grooms (+ these will eventually be deceased).
* Counting also parents and kids
* ***/
// Number of unique persons
// Due to randomness of generated kids + generating parents ratio of deaths & marriages to persons varies!
// Ratio of persons to deaths is approx. 4:1
// Ratio of persons to marriages is approx. 8:1
// can get to +2 to +6 due to kids and parents
const recordPersonsCount = computedMarriageRecordsCount * 8; // ("Person" table entities count)
const occupationsCount = Math.min(PERSON_OCCUPATIONS.length, 50); // number of unique occupations ("Occupation" table entities count)
const SQL_OUTPUT_FILE = 'output/inserts.sql'; // Usable for any SQL database
const POSTGRES_TABLES = createIndexes === false || createIndexes === 'false' // For tables to create on db connect
? 'postgres/postgres.tables-noindex.sql' // Create without indexes
: 'postgres/postgres.tables.sql'; // Create with indexes
faker.locale = 'cz'; // set locale of helper package for generating streets of persons and names of users
// Rewrite old output file
fs.writeFileSync(SQL_OUTPUT_FILE, '');
// String used for later PostgreSQL connection
let sqlInserts = '';
// Creates a SQL INSERT command to fill Postgres database
// AND
// Creates output file with these - SQL_OUTPUT_FILE
function sqlInsert(entityName, entity) {
let columns = Object.keys(entity);
let values = Object.values(entity).map(value => isNaN(value) ? `'${value}'` : value);
// create inserts for PostgreSQL connection
sqlInserts += `INSERT INTO "${entityName}" (${columns}) VALUES (${values});\n`;
// create reusable output file for other potential SQL database usage
fs.appendFileSync(
SQL_OUTPUT_FILE,
`INSERT INTO "${entityName}" (${columns}) VALUES (${values});\n`
);
}
// A random index iterator (remembers used values)
// <iteratorInstance>.next() -> pushes next value to iterator
// <iteratorInstance>.next().value -> picks next value (random index number)
// Usage:
// const desiredRandomIndices = randomIndexFrom(myArray.length); -> create iterator
// let newRandomIndex = desiredRandomIndices.next().value;
function* randomIndexFrom(length) {
const indices = Array.from({length}, (_, i) => i)
.sort(() => Math.random() - 0.5);
// returns an index from randomly sorted indices until length is reached (no duplicity)
for (const index of indices) {
yield index;
}
// if the length was reached, continues to return random index (random duplicity)
while (true) {
yield indices[Math.floor(Math.random() * length)];
}
}
// Generate random date between startDate and endDate)
function randomDate(startDate, endDate) {
if (!(startDate instanceof Date)) return;
if (!endDate) {
endDate = new Date();
} else {
if (!(endDate instanceof Date)) return;
}
return new Date(startDate.getTime() + Math.random() * (endDate.getTime() - startDate.getTime()));
}
// create new output file if doesn't exist or rewrite to empty
// fs.writeFileSync(SQL_OUTPUT_FILE, '');
// create User table inserts
let users = [];
for (let i = 0; i < usersCount; i++) {
const User = {
_id_user: i,
name: faker.fake("{{name.firstName}} {{name.lastName}}"),
};
users = [...users, User];
sqlInsert('User', User);
}
// create Register table inserts
let registers = [];
for (let i = 0; i < archivesCount; i++) {
for (let j = 0; j < fondsCount; j++) {
for (let k = 0; k < signaturesCount; k++) {
const Register = {
_id_register: i * fondsCount * signaturesCount + j * signaturesCount + k,
archive: `ARCH${i}`,
fond: `FOND${j}`,
signature: k,
};
registers = [...registers, Register];
sqlInsert('Register', Register);
}
}
}
// create Name table inserts
let menNames = [];
let womenNames = [];
for (let i = 0; i < NAMES_MEN.length; i++) {
const ManName = {
_id_name: i,
name: NAMES_MEN[i],
};
menNames = [...menNames, ManName];
sqlInsert('Name', ManName);
}
for (let i = 0; i < NAMES_WOMEN.length; i++) {
const WomanName = {
_id_name: i + NAMES_MEN.length,
name: NAMES_WOMEN[i],
};
womenNames = [...womenNames, WomanName];
sqlInsert('Name', WomanName);
}
const allNames = [...menNames, ...womenNames];
// create Occupation table inserts
let occupations = [];
for (let i = 0; i < occupationsCount; i++) {
const Occupation = {
_id_occup: i,
name: PERSON_OCCUPATIONS.map(occ => occ).sort(() => Math.random() - 0.5)[i],
};
occupations = [...occupations, Occupation];
sqlInsert('Occupation', Occupation);
}
// create Director table inserts
let directors = [];
const directorTitleIndices = randomIndexFrom(DIRECTOR_TITLES.length);
const directorSurnames = SURNAMES_MEN.map(sur => sur).sort(() => Math.random() - 0.5).slice(0, directorsCount);
for (let i = 0; i < directorsCount; i++) {
const Director = {
_id_director: i,
surname: directorSurnames[i],
title: DIRECTOR_TITLES[directorTitleIndices.next().value],
};
directors = [...directors, Director];
sqlInsert('Director', Director);
}
// create DirectorName table inserts
let directorNames = [];
const directorNameIndices = randomIndexFrom(NAMES_MEN.length);
for (let i = 0; i < directorsCount; i++) {
const DirectorName = {
director_id: i,
name_id: directorNameIndices.next().value,
};
directorNames = [...directorNames, DirectorName];
sqlInsert('DirectorName', DirectorName);
}
// create Celebrant table inserts
let celebrants = [];
const celebrantTitleIndices = randomIndexFrom(CELEBRANT_TITLES.length);
const celebrantSurnames = SURNAMES_MEN.map(sur => sur).sort(() => Math.random() - 0.5).slice(0, celebrantsCount);
for (let i = 0; i < celebrantsCount; i++) {
const Celebrant = {
_id_celebrant: i,
surname: celebrantSurnames[i],
title_occup: CELEBRANT_TITLES[celebrantTitleIndices.next().value],
};
celebrants = [...celebrants, Celebrant];
sqlInsert('Celebrant', Celebrant);
}
// create CelebrantName table inserts
let celebrantNames = [];
const celebrantNameIndices = randomIndexFrom(NAMES_MEN.length);
for (let i = 0; i < celebrantsCount; i++) {
const CelebrantName = {
celebrant_id: i,
name_id: celebrantNameIndices.next().value,
};
celebrantNames = [...celebrantNames, CelebrantName];
sqlInsert('CelebrantName', CelebrantName);
}
// create Officiant table inserts
let officiants = [];
const officiantTitleIndices = randomIndexFrom(OFFICIANT_TITLES.length);
const officiantSurnames = SURNAMES_MEN.map(sur => sur).sort(() => Math.random() - 0.5).slice(0, officiantsCount);
for (let i = 0; i < officiantsCount; i++) {
const Officiant = {
_id_officiant: i,
surname: officiantSurnames[i],
title: OFFICIANT_TITLES[officiantTitleIndices.next().value],
};
officiants = [...officiants, Officiant];
sqlInsert('Officiant', Officiant);
}
// create OfficiantName table inserts
let officiantNames = [];
const officiantNameIndices = randomIndexFrom(NAMES_MEN.length);
for (let i = 0; i < officiantsCount; i++) {
const OfficiantName = {
officiant_id: i,
name_id: officiantNameIndices.next().value,
};
officiantNames = [...officiantNames, OfficiantName];
sqlInsert('OfficiantName', OfficiantName);
}
// create Person table inserts
const personManSurnames = SURNAMES_MEN.map(sur => sur).sort(() => Math.random() - 0.5);
const personManIndices = randomIndexFrom(personManSurnames.length);
const personWomanSurnames = SURNAMES_WOMEN.map(sur => sur).sort(() => Math.random() - 0.5);
const personWomanIndices = randomIndexFrom(personWomanSurnames.length);
let persons = [];
console.log('Person entities', new Date());
const personVillageIndices = randomIndexFrom(villagesCount);
for (let i = 0; i < recordPersonsCount;) { // incrementing takes place inside cycle for each person
const [descr, street] = faker.fake("{{address.streetAddress}}").split(' ');
const personSex = Math.random() > 0.5 ? 'muž' : 'žena';
const surname = personSex === 'muž'
? personManSurnames[personManIndices.next().value]
: personWomanSurnames[personWomanIndices.next().value];
const personVillage = VILLAGES[personVillageIndices.next().value];
const randomReligion = Math.random() > 0.5 ? 'nepokřtěn' : Math.random() > 0.2 ? 'katolík' : 'evangelík';
const religionFather = Math.random() > 0.7 ? 'nepokřtěn' : Math.random() > 0.2 ? 'katolík' : 'evangelík';
const religionMother = Math.random() > 0.2 ? religionFather : randomReligion;
const religionPerson = Math.random() > 0.5 ? religionFather : religionMother;
const motherSurname = personSex === 'muž' ? `${surname}ová` : surname;
const fatherSurname = personSex === 'muž' ? surname : surname.slice(0, surname.indexOf('ová'));
const Mother = {
_id_person: i,
surname: motherSurname,
village: personVillage,
street: street,
descr: descr,
birth: dateFns.format(randomDate(new Date('1800-01-01'), new Date('1810-01-01')), 'YYYY-MM-DD'),
sex: 'žena',
religion: religionMother,
// father_id: 99999, // FIXME? is this needed? - would have to generate another person. If so, add some randomness?
};
i++; // increment for each person
persons = [...persons, Mother];
sqlInsert('Person', Mother);
const Father = {
_id_person: i,
surname: fatherSurname,
village: personVillage,
street: street,
descr: descr,
birth: dateFns.format(randomDate(new Date('1800-01-01'), new Date('1810-01-01')), 'YYYY-MM-DD'),
sex: 'muž',
religion: religionFather,
};
i++; // increment for each person
persons = [...persons, Father];
sqlInsert('Person', Father);
const Person = {
_id_person: i,
surname: surname,
village: personVillage,
street: street,
descr: descr,
birth: dateFns.format(randomDate(new Date('1825-01-01'), new Date('1840-01-01')), 'YYYY-MM-DD'),
sex: personSex,
religion: religionPerson,
mother_id: Mother._id_person,
father_id: Father._id_person,
};
i++; // increment for each person
persons = [...persons, Person];
sqlInsert('Person', Person);
if (Math.random() > 0.5) { // 50% persons will have randomly 1 - 4 kids (for Death records)
const personKidsCount = Math.floor(Math.random() * 4 + 1);
for (let j = 0; j < personKidsCount; j++) {
const kidSex = Math.random() > 0.5 ? 'muž' : 'žena';
const kidSameAddress = Math.random() > 0.2; // 20% kids have different address
const kidStreet = faker.fake("{{address.streetAddress}}").split(' ')[1];
const kidDescr = faker.fake("{{address.streetAddress}}").split(' ')[0];
let kidSurname = Person.surname;
if (kidSex !== personSex) {
kidSurname = kidSex === 'žena' ? `${Person.surname}ová` : Person.surname.slice(0, surname.indexOf('ová'));
}
let PersonKid = {
_id_person: i,
surname: kidSurname,
village: kidSameAddress ? personVillage : VILLAGES[Math.floor(Math.random() * 20)],
street: kidStreet,
descr: kidDescr,
birth: dateFns.format(randomDate(new Date('1855-01-01'), new Date('1870-01-01')), 'YYYY-MM-DD'),
sex: kidSex,
religion: Math.random() > 0.2 ? religionPerson : 'nepokřtěn', // 80% same religion as parent or 20% not baptised
};
// connect kid to its mother or father
// one of them is enough because it is needed only for Death records where dead_person is either of them (Person)
Person.sex === 'žena' ? PersonKid.mother_id = Person._id_person : PersonKid.father_id = Person._id_person;
i++; // increment cycle index for each kid
persons = [...persons, PersonKid];
sqlInsert('Person', PersonKid);
}
}
}
console.log('PersonName entities', new Date());
// create PersonName table inserts
let personNames = [];
const menNameIndices = randomIndexFrom(NAMES_MEN.length);
const womenNameIndices = randomIndexFrom(NAMES_WOMEN.length);
for (let i = 0; i < persons.length; i++) {
const isMan = persons[i].sex === 'muž';
const PersonName = {
person_id: i,
name_id: isMan ? menNameIndices.next().value : NAMES_MEN.length + womenNameIndices.next().value
};
// 30% of men will have 2 names
if (isMan && Math.random() > 0.7) {
const SecondName = {
person_id: i,
name_id: menNameIndices.next().value
};
personNames = [...personNames, SecondName];
sqlInsert('PersonName', SecondName);
}
personNames = [...personNames, PersonName];
sqlInsert('PersonName', PersonName);
}
console.log('PersonOccupation entities', new Date());
// create PersonOccupation table inserts
let personOccupations = [];
for (let i = 0; i < persons.length; i++) {
// 80% will have 1 - 3 occupations
if (Math.random() > 0.2) {
const occupationIndices = randomIndexFrom(occupationsCount);
const personOccupsCount = Math.floor(Math.random() * 3 + 1);
for (let j = 0; j < personOccupsCount; j++) {
const PersonOccupation = {
person_id: i,
occup_id: occupationIndices.next().value,
};
personOccupations = [...personOccupations, PersonOccupation];
sqlInsert('PersonOccupation', PersonOccupation);
}
}
}
// create Marriage table inserts
let marriages = [];
let witnesses = [];
const officiantsIndices = randomIndexFrom(officiants.length);
const marriageRegistersIndices = randomIndexFrom(registers.length);
const marriageUsersIndices = randomIndexFrom(users.length);
console.log('grooms', new Date());
const grooms = persons
.filter(person => person.sex === 'muž' && person.mother_id && person.father_id)
.sort(() => Math.random() - 0.5);
console.log('brides', new Date());
const brides = persons
.filter(person => person.sex === 'žena' && person.mother_id && person.father_id)
.sort(() => Math.random() - 0.5);
const groomIndices = randomIndexFrom(grooms.length);
const brideIndices = randomIndexFrom(brides.length);
console.log('Marriage entities', new Date());
// added 20% so some people will have more than 1 wedding records
for (let i = 0; i < Math.floor(brides.length * 1.2); i++) {
const marriageVillageIndices = randomIndexFrom(villagesCount);
const groom = grooms[groomIndices.next().value];
const bride = brides[brideIndices.next().value];
// random date between couple's age of 15 to 35
const marriageDate = dateFns.format(
randomDate(
dateFns.addYears(new Date(groom.birth), Math.floor(Math.random() * 20 + 15)),
dateFns.addYears(new Date(bride.birth), Math.floor(Math.random() * 20 + 15))),
'YYYY-MM-DD'
);
const groomDateDiffDays = dateFns.differenceInDays(new Date(marriageDate), new Date(groom.birth));
const groom_y = Math.floor(groomDateDiffDays / 365);
const groom_m = Math.floor((groomDateDiffDays - groom_y * 365) / 30);
const groom_d = Math.floor((groomDateDiffDays - groom_y * 365 - groom_m * 30));
const brideDateDiffDays = dateFns.differenceInDays(new Date(marriageDate), new Date(bride.birth));
const bride_y = Math.floor(brideDateDiffDays / 365);
const bride_m = Math.floor((brideDateDiffDays - bride_y * 365) / 30);
const bride_d = Math.floor((brideDateDiffDays - bride_y * 365 - bride_m * 30));
const marriageVillage = Math.random() > 0.5
? VILLAGES[marriageVillageIndices.next().value]
: Math.random() > 0.5 ? groom.village : bride.village;
const relatives = Math.floor(Math.random() * 100);
let relationship = 'ne';
switch (relatives) { // 5% of marriages will be between relatives
case 95:
relationship = 'strýc-neteř';
break;
case 96:
relationship = 'sourozenci';
break;
case 97:
relationship = 'bratranec-sestřenice 1. stupně';
break;
case 98:
relationship = 'bratranec-sestřenice 2. stupně';
break;
case 99:
relationship = 'polosourozenci';
break;
default:
relationship = 'ne';
break;
}
const Marriage = {
_id_marriage: i,
rec_ready: Math.random() > 0.2, // insignificant data - random
rec_order: Math.floor(Math.random() * 1000), // insignificant data - random
scan_order: Math.floor(Math.random() * 1000), // insignificant data - random
scan_layout: Math.random() < 0.5 ? 'C' : Math.random() > 0.7 ? 'L' : 'P', // layout values according to provided data
date: marriageDate,
village: marriageVillage,
groom_y: groom_y, // age is computed data - can be also queried, but it seems simpler to have inside table
groom_m: groom_m,
groom_d: groom_d,
bride_y: bride_y,
bride_m: bride_m,
bride_d: bride_d,
groom_adult: groom_y >= 18, // computed data - can be also queried TODO
bride_adult: bride_y >= 18,
relationship: relationship,
groom_id: groom._id_person, // connected groom entity
bride_id: bride._id_person, // connected bride entity
user_id: users[marriageUsersIndices.next().value]._id_user, // randomly connected user entity
register_id: registers[marriageRegistersIndices.next().value]._id_register, // randomly connected register entity
officiant_id: officiants[officiantsIndices.next().value]._id_officiant, // randomly connected officiant entity
};
// add banns dates to some marriage records - for simplicity only storing dates of banns w/o text (would need another entity)
if (Math.random() > 0.5) {
Marriage.banns_1 = dateFns.format(dateFns.subDays(new Date(marriageDate), 7), 'YYYY-MM-DD');
if (Math.random() > 0.5) {
Marriage.banns_2 = dateFns.format(dateFns.subDays(new Date(marriageDate), 14), 'YYYY-MM-DD');
if (Math.random() > 0.5) {
Marriage.banns_3 = dateFns.format(dateFns.subDays(new Date(marriageDate), 21), 'YYYY-MM-DD');
}
}
}
marriages = [...marriages, Marriage];
sqlInsert('Marriage', Marriage);
// Create Witness table inserts
// Generating witnesses for each marriage inside of its cycle
const marriageWitnesses = persons
.filter(person => person._id_person !== groom._id_person && person._id_person !== bride._id_person)
.sort(() => Math.random() - 0.5).slice(0, 4);
for (let j = 0; j < 4; j++) {
const Witness = {
person_id: marriageWitnesses[j]._id_person, // randomly connected to person entity
marriage_id: i, // connected to marriage entity which is now generated
side: j > 1 ? 'nevěsty' : 'ženicha', // to distinguish whether is related / acquainted to bride or groom
relationship: Math.random() > 0.6 ? 'sourozenec' : Math.random() < 0.3 ? 'přítel': 'jiné', // 3 cases should be suitable for testing
};
witnesses = [...witnesses, Witness];
sqlInsert('Witness', Witness);
}
}
// create Death table inserts
const celebrantsIndices = randomIndexFrom(celebrants.length);
const directorsIndices = randomIndexFrom(directors.length);
const deathRegistersIndices = randomIndexFrom(registers.length);
const deathUsersIndices = randomIndexFrom(users.length);
const deathCausesIndices = randomIndexFrom(DEATH_CAUSES.length);
let deaths = [];
console.log('deadpersons', new Date());
// create a buffer to .pop() from, so no person has more than 1 death record
const deadPersons = persons.filter(person => person.mother_id && person.father_id);
console.log('Death entities', new Date());
// for (let i = Math.min(deathsCount, deadPersons.length); i > 0; i--) {
for (let i = deadPersons.length; i > 0; i--) {
const deathVillageIndices = randomIndexFrom(villagesCount);
const person = deadPersons[deadPersons.length - 1];
const deathVillage = Math.random() > 0.5 ? VILLAGES[deathVillageIndices.next().value] : person.village;
const deathDate = dateFns.format(dateFns.addYears(new Date(person.birth), Math.floor(Math.random() * 100)), 'YYYY-MM-DD');
const ageDiffDays = dateFns.differenceInDays(new Date(deathDate), new Date(person.birth));
const age_y = Math.floor(ageDiffDays / 365);
const age_m = Math.floor((ageDiffDays - age_y * 365) / 30);
const age_d = Math.floor((ageDiffDays - age_y * 365 - age_m * 30));
const age_h = Math.floor(Math.random() * 24);
let [descr, street] = faker.fake("{{address.streetAddress}}").split(' ');
let Death = {
_id_death: i,
rec_ready: Math.random() > 0.2, // insignificant data - random
rec_order: Math.floor(Math.random() * 1000), // insignificant data - random
scan_order: Math.floor(Math.random() * 1000), // insignificant data - random
scan_layout: Math.random() < 0.5 ? 'C' : Math.random() > 0.7 ? 'L' : 'P', // layout values according to provided data
death_village: deathVillage,
death_street: deathVillage === person.village ? person.street : street,
death_descr: deathVillage === person.village ? person.descr : descr,
place_funeral: person.village,
widowed: Math.random() > 0.7, // computed data - can be also queried TODO
age_y: age_y, // age is computed data - can be also queried, but it seems simpler to have inside table
age_m: age_m,
age_d: age_d,
age_h: age_h,
inspection: Math.random() > 0.7,
person_id: person._id_person, // connected to person entity
user_id: users[deathUsersIndices.next().value]._id_user, // randomly connected user entity
register_id: registers[deathRegistersIndices.next().value]._id_register, // randomly connected register entity
director_id: directors[directorsIndices.next().value]._id_director, // randomly connected director entity
celebrant_id: celebrants[celebrantsIndices.next().value]._id_celebrant, // randomly connected celebrant entity
};
const placeProb = Math.random();
// every 20th record has death place filled
if (placeProb > 0.8) {
if (placeProb > 0.9) {
Death.place_death = 'v řece Svitavě u Bilovic';
} else {
Death.place_death = 'nemocnice';
}
} // could be enriched with JSON data (more cases), but wouldn't affect testing
// every 2nd record has death cause filled
const causeProb = Math.random();
if (causeProb > 0.5) {
if (causeProb > 0.9) {
Death.death_cause = 'osýpky'; // one of most frequent
} else if (causeProb > 0.7) {
Death.death_cause = 'souchotiny'; // one of most frequent
} else {
Death.death_cause = DEATH_CAUSES[deathCausesIndices.next().value];
}
}
// every 10th record has notes filled
const notesProb = Math.random();
if (notesProb > 0.9) {
Death.notes = 'chyba zápisu, prohozené rubriky';
if (notesProb > 0.95) {
Death.notes = 'poznámky...';
}
}
// records either have death & funeral date or provision date
if (Math.random() > 0.7) {
Death.provision_date = deathDate;
} else {
Death.death_date = deathDate;
Death.funeral_date = dateFns.format(dateFns.addDays(new Date(deathDate), 2), 'YYYY-MM-DD');
}
if (Death.inspection) {
Death.inspection_by = Math.random() > 0.6 ? 'Dr. Hrachovina' : 'Dr. Nováček';
}
deadPersons.pop(); // pop last person who has record
deaths = [...deaths, Death];
sqlInsert('Death', Death);
}
/**********************Generate Marriage document collection for MongoDB**********************/
let marriageDocuments = [];
console.log('Marriages map', new Date());
marriages.map(marriageRecord => {
/********* Death Record attributes *********/
let marriageDoc = {...marriageRecord};
/********* ENTITIES connected to Death Record *********/
/********* Register *********/
marriageDoc.register = {...registers.find(reg => reg._id_register === marriageRecord.register_id)};
/********* User *********/
marriageDoc.user = {...users.find(usr => usr._id_user === marriageRecord.user_id)};
/********* Officiant *********/
marriageDoc.officiant = {...officiants.find(dir => dir._id_officiant === marriageRecord.officiant_id)};
const officiantNameRefs = officiantNames
.filter(officiantName => officiantName.officiant_id === marriageRecord.officiant_id)
.map(officiantName => officiantName.name_id);
if (officiantNameRefs.length > 0) {
marriageDoc.officiant.name = [];
officiantNameRefs.map(ref => {
const officiantName = allNames.find(name => name._id_name === ref);
marriageDoc.officiant.name = [...marriageDoc.officiant.name, officiantName.name];
});
}
/********* Witnesses *********/
const marriageWitnesses = witnesses
.filter(witness => witness.marriage_id === marriageRecord._id_marriage);
if (marriageWitnesses.length > 0) {
marriageDoc.witnesses = [];
// Fill each witness entity (object) into array
marriageWitnesses.map(witness => {
const witnessNameRefs = personNames
.filter(personName => personName.person_id === witness.person_id)
.map(personName => personName.name_id);
if (witnessNameRefs.length > 0) {
witness.name = [];
witnessNameRefs.map(ref => {
const witnessName = allNames.find(name => name._id_name === ref);
witness.name = [...witness.name, witnessName.name];
});
}
// Witness occupations entities
const witnessOccupRefs = personOccupations
.filter(personOccup => personOccup.person_id === witness.person_id)
.map(personOccup => personOccup.occup_id);
if (witnessOccupRefs.length > 0) {
witness.occupations = [];
witnessOccupRefs.map(ref => {
const witnessOccupation = occupations.find(occup => occup._id_occup === ref);
witness.occupations = [...witness.occupations, witnessOccupation.name];
});
}
const witnessPersonEntity = {...persons.find(person => person._id_person === witness.person_id)};
// Remove redundant ids used for Relational db foreign keys
delete witnessPersonEntity['father_id'];
delete witnessPersonEntity['mother_id'];
delete witness['marriage_id'];
delete witness['person_id'];
witness = {...witness, ...witnessPersonEntity}; // attributes from Witness entity + Person entity
marriageDoc.witnesses = [...marriageDoc.witnesses, witness];
});
}
/********* Groom & connected entities (parents) *********/
marriageDoc.groom = {...persons.find(person => person._id_person === marriageRecord.groom_id)};
const groomNameRefs = personNames
.filter(personName => personName.person_id === marriageRecord.groom_id)
.map(personName => personName.name_id);
if (groomNameRefs.length > 0) {
marriageDoc.groom.name = [];
groomNameRefs.map(ref => {
const groomName = allNames.find(name => name._id_name === ref);
marriageDoc.groom.name = [...marriageDoc.groom.name, groomName.name];
});
}
// Person occupations entities
const groomOccupRefs = personOccupations
.filter(personOccup => personOccup.person_id === marriageRecord.groom_id)
.map(personOccup => personOccup.occup_id);
if (groomOccupRefs.length > 0) {
marriageDoc.groom.occupations = [];
groomOccupRefs.map(ref => {
const occupation = occupations.find(occup => occup._id_occup === ref);
marriageDoc.groom.occupations = [...marriageDoc.groom.occupations, occupation.name];
});
}
/********* Groom's Father *********/
if (marriageDoc.groom && marriageDoc.groom.father_id) {
marriageDoc.groom.father = {...persons.find(person => person._id_person === marriageDoc.groom.father_id)};
if (marriageDoc.groom.father) {
const groomFatherNameRefs = personNames
.filter(personName => personName.person_id === marriageDoc.groom.father._id_person)
.map(personName => personName.name_id);
if (groomFatherNameRefs.length > 0) {
marriageDoc.groom.father.name = [];
groomFatherNameRefs.map(ref => {
const groomFatherName = allNames.find(name => name._id_name === ref);
marriageDoc.groom.father.name = [...marriageDoc.groom.father.name, groomFatherName.name];
});
}
// Father occupations entities
const fatherOccupRefs = personOccupations
.filter(personOccup => personOccup.person_id === marriageDoc.groom.father._id_person)
.map(personOccup => personOccup.occup_id);
if (fatherOccupRefs.length > 0) {
marriageDoc.groom.father.occupations = [];
fatherOccupRefs.map(ref => {
const occupation = occupations.find(occup => occup._id_occup === ref);
marriageDoc.groom.father.occupations = [...marriageDoc.groom.father.occupations, occupation.name];
});
}
}
}
/********* Groom's Mother *********/
if (marriageDoc.groom && marriageDoc.groom.mother_id) {
marriageDoc.groom.mother = {...persons.find(person => person._id_person === marriageDoc.groom.mother_id)};
if (marriageDoc.groom.mother) {
const groomMotherNameRefs = personNames
.filter(personName => personName.person_id === marriageDoc.groom.mother._id_person)
.map(personName => personName.name_id);
if (groomMotherNameRefs.length > 0) {
marriageDoc.groom.mother.name = [];
groomMotherNameRefs.map(ref => {
const groomMotherName = allNames.find(name => name._id_name === ref);
marriageDoc.groom.mother.name = [...marriageDoc.groom.mother.name, groomMotherName.name];
});
}
// Father occupations entities
const motherOccupRefs = personOccupations
.filter(personOccup => personOccup.person_id === marriageDoc.groom.mother._id_person)
.map(personOccup => personOccup.occup_id);
if (motherOccupRefs.length > 0) {
marriageDoc.groom.mother.occupations = [];
motherOccupRefs.map(ref => {
const occupation = occupations.find(occup => occup._id_occup === ref);
marriageDoc.groom.mother.occupations = [...marriageDoc.groom.mother.occupations, occupation.name];
});
}
}
}
/********* Bride & connected entities (parents) *********/
marriageDoc.bride = {...persons.find(person => person._id_person === marriageRecord.bride_id)};
const brideNameRefs = personNames
.filter(personName => personName.person_id === marriageRecord.bride_id)
.map(personName => personName.name_id);
if (brideNameRefs.length > 0) {
marriageDoc.bride.name = [];
brideNameRefs.map(ref => {
const brideName = allNames.find(name => name._id_name === ref);
marriageDoc.bride.name = [...marriageDoc.bride.name, brideName.name];
});
}
// Person occupations entities
const brideOccupRefs = personOccupations
.filter(personOccup => personOccup.person_id === marriageRecord.bride_id)
.map(personOccup => personOccup.occup_id);
if (brideOccupRefs.length > 0) {
marriageDoc.bride.occupations = [];
brideOccupRefs.map(ref => {
const occupation = occupations.find(occup => occup._id_occup === ref);
marriageDoc.bride.occupations = [...marriageDoc.bride.occupations, occupation.name];
});
}
/********* Bride's Father *********/
if (marriageDoc.bride && marriageDoc.bride.father_id) {
marriageDoc.bride.father = {...persons.find(person => person._id_person === marriageDoc.bride.father_id)};
if (marriageDoc.bride.father) {
const brideFatherNameRefs = personNames
.filter(personName => personName.person_id === marriageDoc.bride.father._id_person)
.map(personName => personName.name_id);
if (brideFatherNameRefs.length > 0) {
marriageDoc.bride.father.name = [];
brideFatherNameRefs.map(ref => {
const brideFatherName = allNames.find(name => name._id_name === ref);
marriageDoc.bride.father.name = [...marriageDoc.bride.father.name, brideFatherName.name];
});
}
// Father occupations entities
const fatherOccupRefs = personOccupations
.filter(personOccup => personOccup.person_id === marriageDoc.bride.father._id_person)
.map(personOccup => personOccup.occup_id);
if (fatherOccupRefs.length > 0) {
marriageDoc.bride.father.occupations = [];
fatherOccupRefs.map(ref => {
const occupation = occupations.find(occup => occup._id_occup === ref);
marriageDoc.bride.father.occupations = [...marriageDoc.bride.father.occupations, occupation.name];
});
}
}
}
/********* Bride's Mother *********/
if (marriageDoc.mother && marriageDoc.mother.mother_id) {
marriageDoc.bride.mother = {...persons.find(person => person._id_person === marriageDoc.mother.mother_id)};
if (marriageDoc.bride.mother) {
const brideMotherNameRefs = personNames
.filter(personName => personName.person_id === marriageDoc.bride.mother._id_person)
.map(personName => personName.name_id);
if (brideMotherNameRefs.length > 0) {
marriageDoc.bride.mother.name = [];
brideMotherNameRefs.map(ref => {
const brideMotherName = allNames.find(name => name._id_name === ref);
marriageDoc.bride.mother.name = [...marriageDoc.bride.mother.name, brideMotherName.name];
});
}
// Mother occupations entities
const motherOccupRefs = personOccupations
.filter(personOccup => personOccup.person_id === marriageDoc.bride.mother._id_person)
.map(personOccup => personOccup.occup_id);
if (motherOccupRefs.length > 0) {
marriageDoc.bride.mother.occupations = [];
motherOccupRefs.map(ref => {
const occupation = occupations.find(occup => occup._id_occup === ref);
marriageDoc.bride.mother.occupations = [...marriageDoc.bride.mother.occupations, occupation.name];
});
}
}
}
// Remove redundant ids used for Relational db foreign keys
// and _id_marriage because it will be replaced by _id index (ObjectId) in MongoDB
delete marriageDoc['_id_marriage'];
delete marriageDoc['groom_id'];
delete marriageDoc['bride_id'];