-
Notifications
You must be signed in to change notification settings - Fork 69
Expand file tree
/
Copy pathsample_db_export.py
More file actions
1714 lines (1576 loc) · 61.4 KB
/
Copy pathsample_db_export.py
File metadata and controls
1714 lines (1576 loc) · 61.4 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
'''
Anonymized development database sample export.
Sample about ``ratio`` of ``generic.User`` rows (fixed seed), cascade related
records, rewrite identity fields to category+index labels, and write an
INSERT-only SQL dump suitable for import after ``migrate``.
'''
from __future__ import annotations
import random
from dataclasses import dataclass, field
from datetime import date, datetime, time, timedelta
from decimal import Decimal
from pathlib import Path
from typing import Any, Callable, Iterable, Sequence
from django.db import connection
from generic.models import User
__all__ = [
'SAMPLE_PASSWORD_HASH',
'SAMPLE_PASSWORD_PLAINTEXT',
'export_sample_database',
]
# Django pbkdf2 hash of the plaintext password "test" (development samples only).
SAMPLE_PASSWORD_HASH = (
'pbkdf2_sha256$1000000$dGQo0oBkjKFUB7JeCtrtky$'
'cj/291X3R/f1+HqppYf/fF8L6EvdsLfHZmY6caZU9Ag='
)
SAMPLE_PASSWORD_PLAINTEXT = 'test'
REDACTED = '[redacted]'
USAGE_SAMPLE = '样例'
BATCH_SIZE = 100
# Tables exported fully (configuration / reference data).
FULL_TABLES: list[str] = [
'semester_semestertype',
'semester_semester',
'app_organizationtag',
'app_organizationtype',
'Appointment_room',
'dormitory_dormitory',
# feedback_feedbacktype: written separately to null dangling org defaults.
'app_academictag',
'achievement_achievementtype',
'achievement_achievement',
'app_help',
]
@dataclass
class UserAlias:
'''Anonymized fields for one retained User row.'''
old_id: int
old_username: str
new_username: str
new_name: str
pinyin: str
acronym: str
utype: str
email: str
@dataclass
class SampleContext:
'''Mutable export state: selected keys and username remapping.'''
ratio: float
seed: int
user_by_id: dict[int, UserAlias] = field(default_factory=dict)
username_map: dict[str, str] = field(default_factory=dict)
person_ids: set[int] = field(default_factory=set)
org_ids: set[int] = field(default_factory=set)
participant_usernames: set[str] = field(default_factory=set)
activity_ids: set[int] = field(default_factory=set)
commentbase_ids: set[int] = field(default_factory=set)
course_ids: set[int] = field(default_factory=set)
coursetime_ids: set[int] = field(default_factory=set)
pool_ids: set[int] = field(default_factory=set)
poolitem_ids: set[int] = field(default_factory=set)
appoint_ids: set[int] = field(default_factory=set)
survey_ids: set[int] = field(default_factory=set)
question_ids: set[int] = field(default_factory=set)
answersheet_ids: set[int] = field(default_factory=set)
reader_ids: set[int] = field(default_factory=set)
book_ids: set[int] = field(default_factory=set)
freshman_ids: set[int] = field(default_factory=set)
feedback_ids: set[int] = field(default_factory=set)
position_ids: set[int] = field(default_factory=set)
@property
def user_ids(self) -> set[int]:
return set(self.user_by_id)
@property
def new_usernames(self) -> set[str]:
return set(self.username_map.values())
def export_sample_database(
outfile: Path,
*,
ratio: float = 0.1,
seed: int = 42,
) -> dict[str, Any]:
'''
Export an anonymized sample dump to ``outfile``.
:return: Summary dict with ratio, seed, user count, and output path.
'''
if not 0 < ratio <= 1:
raise ValueError('ratio must be in (0, 1]')
ctx = SampleContext(ratio=ratio, seed=seed)
_sample_users(ctx)
_expand_and_collect(ctx)
outfile.parent.mkdir(parents=True, exist_ok=True)
with outfile.open('w', encoding='utf-8', newline='\n') as fh:
fh.write('-- YPPF anonymized sample dump for development\n')
fh.write(
f'-- ratio={ratio} seed={seed} users={len(ctx.user_by_id)}\n'
)
fh.write('-- Import after: CREATE DATABASE + migrate\n')
fh.write('SET NAMES utf8mb4;\n')
fh.write('SET FOREIGN_KEY_CHECKS=0;\n')
fh.write('SET UNIQUE_CHECKS=0;\n')
fh.write('\n')
_write_all_tables(fh, ctx)
fh.write('\n')
fh.write('SET UNIQUE_CHECKS=1;\n')
fh.write('SET FOREIGN_KEY_CHECKS=1;\n')
return {
'ratio': ratio,
'seed': seed,
'users': len(ctx.user_by_id),
'path': str(outfile),
}
def _sample_users(ctx: SampleContext) -> None:
rows = list(
User.objects.order_by('pk').values_list('id', 'username', 'utype')
)
if not rows:
raise RuntimeError('No users in database; nothing to sample')
rng = random.Random(ctx.seed)
count = max(1, int(len(rows) * ctx.ratio))
count = min(count, len(rows))
chosen = rng.sample(rows, count)
_assign_aliases(ctx, chosen)
def _assign_aliases(
ctx: SampleContext,
users: Sequence[tuple[int, str, str]],
) -> None:
'''Build anonymized usernames/names for the given users.'''
counters = {
User.Type.STUDENT: 0,
User.Type.ORG: 0,
User.Type.PERSON: 0,
User.Type.TEACHER: 0,
User.Type.UNAUTHORIZED: 0,
User.Type.SPECIAL: 0,
'': 0,
}
# Stable order by old id so remapping is deterministic given the set.
for old_id, old_username, utype in sorted(users, key=lambda x: x[0]):
utype = utype or ''
if utype == User.Type.STUDENT:
counters[User.Type.STUDENT] += 1
n = counters[User.Type.STUDENT]
new_username = f'S{n:06d}'
new_name = f'学生{n}'
pinyin = f'xuesheng{n}'
acronym = f'xs{str(n)[0]}'
elif utype == User.Type.ORG:
counters[User.Type.ORG] += 1
n = counters[User.Type.ORG]
new_username = f'O{n:06d}'
new_name = f'组织{n}'
pinyin = f'zuzhi{n}'
acronym = f'zz{str(n)[0]}'
elif utype in (User.Type.PERSON, User.Type.TEACHER):
# Match existing sample: Person/Teacher share P/用户 series.
counters[User.Type.PERSON] += 1
n = counters[User.Type.PERSON]
new_username = f'P{n:06d}'
new_name = f'用户{n}'
pinyin = f'yonghu{n}'
acronym = f'yh{str(n)[0]}'
else:
counters[User.Type.SPECIAL] += 1
n = counters[User.Type.SPECIAL]
new_username = f'X{n:06d}'
new_name = f'账号{n}'
pinyin = f'zhanghao{n}'
acronym = f'zh{str(n)[0]}'
alias = UserAlias(
old_id=old_id,
old_username=old_username,
new_username=new_username,
new_name=new_name,
pinyin=pinyin,
acronym=acronym[:32],
utype=utype,
email=f'{new_username.lower()}@example.com',
)
ctx.user_by_id[old_id] = alias
ctx.username_map[old_username] = new_username
def _ensure_user_ids(ctx: SampleContext, user_ids: Iterable[int]) -> None:
'''Force-include users referenced by retained rows (FK closure).'''
missing = [
uid for uid in set(user_ids)
if uid is not None and int(uid) not in ctx.user_by_id
]
if not missing:
return
rows = list(
User.objects.filter(pk__in=missing).values_list(
'id', 'username', 'utype'
)
)
if not rows:
return
existing = [
(alias.old_id, alias.old_username, alias.utype)
for alias in ctx.user_by_id.values()
]
ctx.user_by_id.clear()
ctx.username_map.clear()
_assign_aliases(ctx, existing + rows)
def _expand_and_collect(ctx: SampleContext) -> None:
'''
Collect related primary keys for the sampled users.
Referenced-but-missing users (e.g. examine teachers) are added as leaf
identities only: their User/NaturalPerson rows are exported, but they do
not trigger another round of appointment/position/notification expansion.
'''
_collect_profiles(ctx)
_collect_positions_and_courses(ctx)
_collect_activities(ctx)
_collect_appointments(ctx)
# Leaf users required by activity teachers / appoint majors already added.
_collect_profiles(ctx)
_collect_feedback_comments_notifications(ctx)
_collect_pools_academic_achievements(ctx)
_collect_questionnaire(ctx)
_collect_library_dorm_logs(ctx)
_collect_freshmen(ctx)
# Ensure orgtype incharge persons exist as leaf rows (or null at write).
_collect_orgtype_incharge_leaf(ctx)
_collect_profiles(ctx)
def _fetch_ids(sql: str, params: Sequence[Any] | None = None) -> set[Any]:
with connection.cursor() as cursor:
cursor.execute(sql, params or [])
return {row[0] for row in cursor.fetchall() if row[0] is not None}
def _in_clause(ids: Sequence[Any]) -> tuple[str, list[Any]]:
if not ids:
return 'NULL', []
placeholders = ','.join(['%s'] * len(ids))
return placeholders, list(ids)
def _collect_profiles(ctx: SampleContext) -> None:
uids = list(ctx.user_ids)
if not uids:
return
ph, params = _in_clause(uids)
ctx.person_ids |= _fetch_ids(
f'SELECT id FROM app_naturalperson WHERE person_id_id IN ({ph})',
params,
)
ctx.org_ids |= _fetch_ids(
f'SELECT id FROM app_organization WHERE organization_id_id IN ({ph})',
params,
)
# Participants keyed by username.
unames = list(ctx.username_map)
if unames:
ph, params = _in_clause(unames)
ctx.participant_usernames |= _fetch_ids(
f'SELECT Sid_id FROM Appointment_participant WHERE Sid_id IN ({ph})',
params,
)
def _collect_orgtype_incharge_leaf(ctx: SampleContext) -> None:
'''Include incharge persons only when their org type is used by sample orgs.'''
if not ctx.org_ids:
return
ph, params = _in_clause(list(ctx.org_ids))
otypes = _fetch_ids(
f'SELECT DISTINCT otype_id FROM app_organization WHERE id IN ({ph})',
params,
)
if not otypes:
return
ph2, params2 = _in_clause(list(otypes))
incharge_users = _fetch_ids(
'SELECT np.person_id_id FROM app_organizationtype ot '
'JOIN app_naturalperson np ON np.id = ot.incharge_id '
f'WHERE ot.otype_id IN ({ph2}) AND ot.incharge_id IS NOT NULL',
params2,
)
_ensure_user_ids(ctx, incharge_users)
def _collect_positions_and_courses(ctx: SampleContext) -> None:
# Only positions fully inside the sampled person/org sets.
if ctx.person_ids and ctx.org_ids:
ph_p, params_p = _in_clause(list(ctx.person_ids))
ph_o, params_o = _in_clause(list(ctx.org_ids))
ctx.position_ids |= _fetch_ids(
f'SELECT id FROM app_position '
f'WHERE person_id IN ({ph_p}) AND org_id IN ({ph_o})',
list(params_p) + list(params_o),
)
# Courses owned by sampled orgs.
if ctx.org_ids:
ph, params = _in_clause(list(ctx.org_ids))
ctx.course_ids |= _fetch_ids(
f'SELECT id FROM app_course WHERE organization_id IN ({ph})',
params,
)
if ctx.course_ids:
ph, params = _in_clause(list(ctx.course_ids))
ctx.coursetime_ids |= _fetch_ids(
f'SELECT id FROM app_coursetime WHERE course_id IN ({ph})',
params,
)
# Pending org/position applications tied to sampled users/persons.
if ctx.user_ids and _table_exists('app_modifyorganization'):
ph, params = _in_clause(list(ctx.user_ids))
ctx.commentbase_ids |= _fetch_ids(
f'SELECT commentbase_ptr_id FROM app_modifyorganization '
f'WHERE pos_id IN ({ph})',
params,
)
if ctx.person_ids and ctx.org_ids and _table_exists('app_modifyposition'):
ph_p, params_p = _in_clause(list(ctx.person_ids))
ph_o, params_o = _in_clause(list(ctx.org_ids))
ctx.commentbase_ids |= _fetch_ids(
f'SELECT commentbase_ptr_id FROM app_modifyposition '
f'WHERE person_id IN ({ph_p}) AND org_id IN ({ph_o})',
list(params_p) + list(params_o),
)
def _collect_activities(ctx: SampleContext) -> None:
if ctx.org_ids:
ph, params = _in_clause(list(ctx.org_ids))
ctx.activity_ids |= _fetch_ids(
f'SELECT commentbase_ptr_id FROM app_activity '
f'WHERE organization_id_id IN ({ph})',
params,
)
if ctx.activity_ids:
ph, params = _in_clause(list(ctx.activity_ids))
ctx.commentbase_ids |= set(ctx.activity_ids)
# Leaf-include examine teachers so FK rows remain valid.
teacher_persons = _fetch_ids(
f'SELECT examine_teacher_id FROM app_activity '
f'WHERE commentbase_ptr_id IN ({ph}) '
f'AND examine_teacher_id IS NOT NULL',
params,
)
if teacher_persons:
ctx.person_ids |= teacher_persons
ph2, params2 = _in_clause(list(teacher_persons))
_ensure_user_ids(
ctx,
_fetch_ids(
f'SELECT person_id_id FROM app_naturalperson '
f'WHERE id IN ({ph2})',
params2,
),
)
ctx.coursetime_ids |= _fetch_ids(
f'SELECT course_time_id FROM app_activity '
f'WHERE commentbase_ptr_id IN ({ph}) '
f'AND course_time_id IS NOT NULL',
params,
)
if ctx.coursetime_ids:
ph2, params2 = _in_clause(list(ctx.coursetime_ids))
ctx.course_ids |= _fetch_ids(
f'SELECT course_id FROM app_coursetime WHERE id IN ({ph2})',
params2,
)
def _collect_appointments(ctx: SampleContext) -> None:
unames = list(ctx.username_map)
if unames:
ph, params = _in_clause(unames)
ctx.participant_usernames |= _fetch_ids(
f'SELECT Sid_id FROM Appointment_participant '
f'WHERE Sid_id IN ({ph})',
params,
)
if not ctx.participant_usernames:
return
ph, params = _in_clause(list(ctx.participant_usernames))
# Appointments owned by sampled participants.
ctx.appoint_ids |= _fetch_ids(
f'SELECT Aid FROM Appointment_appoint '
f'WHERE major_student_id IN ({ph})',
params,
)
if not ctx.appoint_ids:
return
ph_a, params_a = _in_clause(list(ctx.appoint_ids))
# Leaf-include other students listed on those appointments.
student_ids = _fetch_ids(
f'SELECT participant_id FROM Appointment_appoint_students '
f'WHERE appoint_id IN ({ph_a})',
params_a,
)
ctx.participant_usernames |= student_ids
_ensure_user_ids(
ctx,
User.objects.filter(username__in=student_ids).values_list(
'id', flat=True
),
)
def _collect_feedback_comments_notifications(ctx: SampleContext) -> None:
if ctx.person_ids:
ph, params = _in_clause(list(ctx.person_ids))
ctx.feedback_ids |= _fetch_ids(
f'SELECT commentbase_ptr_id FROM feedback_feedback '
f'WHERE person_id IN ({ph})',
params,
)
if ctx.org_ids:
ph, params = _in_clause(list(ctx.org_ids))
ctx.feedback_ids |= _fetch_ids(
f'SELECT commentbase_ptr_id FROM feedback_feedback '
f'WHERE org_id IN ({ph})',
params,
)
# Org-sourced feedback may reference persons outside the user sample.
# Leaf-include those persons (and their User rows) so person_id FKs stay
# valid; Feedback.person is NOT NULL and cannot be nulled at write time.
if ctx.feedback_ids and _table_exists('feedback_feedback'):
ph, params = _in_clause(list(ctx.feedback_ids))
feedback_persons = _fetch_ids(
f'SELECT DISTINCT person_id FROM feedback_feedback '
f'WHERE commentbase_ptr_id IN ({ph})',
params,
)
if feedback_persons:
ctx.person_ids |= feedback_persons
ph2, params2 = _in_clause(list(feedback_persons))
_ensure_user_ids(
ctx,
_fetch_ids(
f'SELECT person_id_id FROM app_naturalperson '
f'WHERE id IN ({ph2})',
params2,
),
)
# Drop feedback whose person still cannot be exported.
if ctx.person_ids:
ph_p, params_p = _in_clause(list(ctx.person_ids))
valid = _fetch_ids(
f'SELECT commentbase_ptr_id FROM feedback_feedback '
f'WHERE commentbase_ptr_id IN ({ph}) '
f'AND person_id IN ({ph_p})',
params + params_p,
)
else:
valid = set()
drop = ctx.feedback_ids - valid
ctx.feedback_ids -= drop
ctx.commentbase_ids |= ctx.feedback_ids
# Notifications are not exported (content often still contains PII).
def _collect_pools_academic_achievements(ctx: SampleContext) -> None:
if ctx.user_ids:
ph, params = _in_clause(list(ctx.user_ids))
ctx.pool_ids |= _fetch_ids(
f'SELECT DISTINCT pool_id FROM app_poolrecord '
f'WHERE user_id IN ({ph})',
params,
)
# Also include pools linked to sampled activities.
if ctx.activity_ids and _table_exists('app_pool'):
ph, params = _in_clause(list(ctx.activity_ids))
ctx.pool_ids |= _fetch_ids(
f'SELECT id FROM app_pool '
f'WHERE activity_id IN ({ph})',
params,
)
if ctx.pool_ids:
ph, params = _in_clause(list(ctx.pool_ids))
ctx.poolitem_ids |= _fetch_ids(
f'SELECT id FROM app_poolitem WHERE pool_id IN ({ph})',
params,
)
def _collect_questionnaire(ctx: SampleContext) -> None:
if not ctx.user_ids:
return
ph, params = _in_clause(list(ctx.user_ids))
ctx.survey_ids |= _fetch_ids(
f'SELECT id FROM questionnaire_survey WHERE creator_id IN ({ph})',
params,
)
ctx.answersheet_ids |= _fetch_ids(
f'SELECT id FROM questionnaire_answersheet WHERE creator_id IN ({ph})',
params,
)
if ctx.answersheet_ids:
ph2, params2 = _in_clause(list(ctx.answersheet_ids))
ctx.survey_ids |= _fetch_ids(
f'SELECT DISTINCT survey_id FROM questionnaire_answersheet '
f'WHERE id IN ({ph2})',
params2,
)
creators = _fetch_ids(
f'SELECT DISTINCT creator_id FROM questionnaire_answersheet '
f'WHERE id IN ({ph2})',
params2,
)
_ensure_user_ids(ctx, creators)
if ctx.survey_ids:
ph2, params2 = _in_clause(list(ctx.survey_ids))
ctx.question_ids |= _fetch_ids(
f'SELECT id FROM questionnaire_question WHERE survey_id IN ({ph2})',
params2,
)
_ensure_user_ids(
ctx,
_fetch_ids(
f'SELECT creator_id FROM questionnaire_survey '
f'WHERE id IN ({ph2})',
params2,
),
)
def _collect_library_dorm_logs(ctx: SampleContext) -> None:
# Readers whose student_id matches old usernames in sample.
unames = list(ctx.username_map)
if unames:
ph, params = _in_clause(unames)
ctx.reader_ids |= _fetch_ids(
f'SELECT id FROM yp_library_reader WHERE student_id IN ({ph})',
params,
)
if ctx.reader_ids:
ph, params = _in_clause(list(ctx.reader_ids))
ctx.book_ids |= _fetch_ids(
f'SELECT DISTINCT book_id_id FROM yp_library_lendrecord '
f'WHERE reader_id_id IN ({ph}) AND book_id_id IS NOT NULL',
params,
)
def _collect_freshmen(ctx: SampleContext) -> None:
ids = list(_fetch_ids('SELECT id FROM app_freshman'))
if not ids:
return
rng = random.Random(ctx.seed + 1)
count = max(1, int(len(ids) * ctx.ratio)) if len(ids) > 1 else len(ids)
count = min(count, len(ids))
ctx.freshman_ids = set(rng.sample(ids, count))
def _sql_literal(value: Any) -> str:
if value is None:
return 'NULL'
if isinstance(value, bool):
return '1' if value else '0'
if isinstance(value, int) and not isinstance(value, bool):
return str(value)
if isinstance(value, float):
return repr(value)
if isinstance(value, Decimal):
return format(value, 'f')
if isinstance(value, datetime):
return f"'{value.strftime('%Y-%m-%d %H:%M:%S.%f')}'"
if isinstance(value, date):
return f"'{value.isoformat()}'"
if isinstance(value, time):
return f"'{value.strftime('%H:%M:%S')}'"
if isinstance(value, timedelta):
total = int(value.total_seconds())
hours, rem = divmod(abs(total), 3600)
minutes, seconds = divmod(rem, 60)
sign = '-' if total < 0 else ''
return f"'{sign}{hours}:{minutes:02d}:{seconds:02d}'"
if isinstance(value, (bytes, bytearray, memoryview)):
return 'NULL'
text = str(value)
text = text.replace('\\', '\\\\').replace("'", "\\'")
text = text.replace('\n', '\\n').replace('\r', '\\r')
return f"'{text}'"
def _quote_ident(name: str) -> str:
return f'`{name}`'
def _table_columns(table: str) -> list[str]:
with connection.cursor() as cursor:
cursor.execute(f'SELECT * FROM {_quote_ident(table)} LIMIT 0')
return [col[0] for col in cursor.description]
def _fetch_rows(
table: str,
columns: Sequence[str],
where_sql: str | None = None,
params: Sequence[Any] | None = None,
) -> list[tuple[Any, ...]]:
col_sql = ', '.join(_quote_ident(c) for c in columns)
sql = f'SELECT {col_sql} FROM {_quote_ident(table)}'
if where_sql:
sql += f' WHERE {where_sql}'
with connection.cursor() as cursor:
cursor.execute(sql, params or [])
return list(cursor.fetchall())
def _write_inserts(
fh,
table: str,
columns: Sequence[str],
rows: Sequence[Sequence[Any]],
) -> None:
if not rows:
return
col_list = ', '.join(_quote_ident(c) for c in columns)
for start in range(0, len(rows), BATCH_SIZE):
batch = rows[start:start + BATCH_SIZE]
fh.write(
f'INSERT INTO {_quote_ident(table)} ({col_list}) VALUES\n'
)
values_lines = []
for row in batch:
rendered = ', '.join(_sql_literal(v) for v in row)
values_lines.append(f'({rendered})')
fh.write(',\n'.join(values_lines))
fh.write(';\n')
def _transform_user_row(
ctx: SampleContext,
columns: Sequence[str],
row: Sequence[Any],
) -> tuple[Any, ...] | None:
data = dict(zip(columns, row))
alias = ctx.user_by_id.get(int(data['id']))
if alias is None:
return None
data['password'] = SAMPLE_PASSWORD_HASH
data['username'] = alias.new_username
data['first_name'] = ''
data['last_name'] = ''
data['email'] = alias.email
data['name'] = alias.new_name
data['pinyin'] = alias.pinyin
data['acronym'] = alias.acronym
# Avoid first-login password-change redirect when using the sample password.
if 'is_newuser' in data:
data['is_newuser'] = 0
return tuple(data[c] for c in columns)
def _transform_naturalperson(
ctx: SampleContext,
columns: Sequence[str],
row: Sequence[Any],
) -> tuple[Any, ...] | None:
data = dict(zip(columns, row))
alias = ctx.user_by_id.get(int(data['person_id_id']))
if alias is None:
return None
data['stu_id_dbonly'] = alias.new_username
data['name'] = alias.new_name
data['nickname'] = alias.new_name
data['birthday'] = None
data['email'] = alias.email
data['telephone'] = None
data['biography'] = REDACTED
data['avatar'] = ''
data['wallpaper'] = ''
data['QRcode'] = ''
data['stu_dorm'] = None
if data.get('stu_major') not in (None, ''):
data['stu_major'] = REDACTED
# stu_class is CharField(max_length=5); keep a short marker.
if data.get('stu_class') not in (None, ''):
data['stu_class'] = 'R'
return tuple(data[c] for c in columns)
def _transform_organization(
ctx: SampleContext,
columns: Sequence[str],
row: Sequence[Any],
) -> tuple[Any, ...] | None:
data = dict(zip(columns, row))
alias = ctx.user_by_id.get(int(data['organization_id_id']))
if alias is None:
return None
# Prefer org series name from alias.
data['oname'] = alias.new_name
data['introduction'] = REDACTED
data['avatar'] = ''
data['QRcode'] = ''
data['wallpaper'] = ''
return tuple(data[c] for c in columns)
def _transform_freshman(
ctx: SampleContext,
columns: Sequence[str],
row: Sequence[Any],
index_map: dict[int, int],
) -> tuple[Any, ...] | None:
data = dict(zip(columns, row))
pk = int(data['id'])
if pk not in index_map:
return None
n = index_map[pk]
data['sid'] = f'F{n:06d}'
data['name'] = f'新生{n}'
data['birthday'] = date(2000, 1, 1)
data['place'] = '其它'
return tuple(data[c] for c in columns)
def _transform_participant(
ctx: SampleContext,
columns: Sequence[str],
row: Sequence[Any],
) -> tuple[Any, ...] | None:
data = dict(zip(columns, row))
new_sid = ctx.username_map.get(str(data['Sid_id']))
if new_sid is None:
return None
data['Sid_id'] = new_sid
return tuple(data[c] for c in columns)
def _transform_appoint(
ctx: SampleContext,
columns: Sequence[str],
row: Sequence[Any],
) -> tuple[Any, ...] | None:
data = dict(zip(columns, row))
major = ctx.username_map.get(str(data['major_student_id']))
if major is None:
return None
data['major_student_id'] = major
data['Ausage'] = USAGE_SAMPLE
data['Aannouncement'] = ''
return tuple(data[c] for c in columns)
def _generic_username_fields_transform(
ctx: SampleContext,
columns: Sequence[str],
row: Sequence[Any],
username_fields: Sequence[str],
redact_fields: Sequence[str] = (),
empty_fields: Sequence[str] = (),
) -> tuple[Any, ...] | None:
data = dict(zip(columns, row))
for field_name in username_fields:
if field_name not in data:
continue
old = data[field_name]
if old is None:
continue
mapped = ctx.username_map.get(str(old))
if mapped is None:
return None
data[field_name] = mapped
for field_name in redact_fields:
if field_name in data and data[field_name] not in (None, ''):
data[field_name] = REDACTED
for field_name in empty_fields:
if field_name in data:
data[field_name] = '' if data[field_name] is not None else None
return tuple(data[c] for c in columns)
def _write_full_table(fh, table: str) -> None:
columns = _table_columns(table)
rows = _fetch_rows(table, columns)
# OrganizationType.incharge may reference persons outside sample; null out
# missing incharge when exporting full orgtype after persons are known.
_write_inserts(fh, table, columns, rows)
def _write_filtered(
fh,
table: str,
where_sql: str,
params: Sequence[Any],
transform: Callable[
[Sequence[str], Sequence[Any]],
tuple[Any, ...] | None,
],
) -> None:
columns = _table_columns(table)
raw_rows = _fetch_rows(table, columns, where_sql, params)
out_rows = []
for row in raw_rows:
transformed = transform(columns, row)
if transformed is not None:
out_rows.append(transformed)
_write_inserts(fh, table, columns, out_rows)
def _write_all_tables(fh, ctx: SampleContext) -> None:
# 1) Full configuration tables (fix orgtype incharge after persons exist:
# write orgtype later with adjusted incharge).
for table in FULL_TABLES:
if table == 'app_organizationtype':
continue
if not _table_exists(table):
continue
_write_full_table(fh, table)
# Organization types with incharge restricted to sampled persons.
if _table_exists('app_organizationtype'):
columns = _table_columns('app_organizationtype')
rows = _fetch_rows('app_organizationtype', columns)
out = []
for row in rows:
data = dict(zip(columns, row))
incharge = data.get('incharge_id')
if incharge is not None and int(incharge) not in ctx.person_ids:
# Keep row; point incharge to NULL if person not retained.
# But person_ids should include all incharge after expansion.
if int(incharge) not in ctx.person_ids:
data['incharge_id'] = None
out.append(tuple(data[c] for c in columns))
# Re-fetch person_ids after expansion should include incharge; if still
# missing, null them.
fixed = []
for row in out:
data = dict(zip(columns, row))
incharge = data.get('incharge_id')
if incharge is not None and int(incharge) not in ctx.person_ids:
data['incharge_id'] = None
fixed.append(tuple(data[c] for c in columns))
_write_inserts(fh, 'app_organizationtype', columns, fixed)
# Feedback types: keep all rows, but null org defaults not in the sample.
if _table_exists('feedback_feedbacktype'):
columns = _table_columns('feedback_feedbacktype')
rows = _fetch_rows('feedback_feedbacktype', columns)
out = []
for row in rows:
data = dict(zip(columns, row))
org_id = data.get('org_id')
if org_id is not None and int(org_id) not in ctx.org_ids:
data['org_id'] = None
# ALL_DEFAULT(2) claims both org and org_type defaults.
if int(data.get('flexible') or 0) == 2:
if data.get('org_type_id') is not None:
data['flexible'] = 1 # ORG_TYPE_DEFAULT
else:
data['flexible'] = 0 # NO_DEFAULT
out.append(tuple(data[c] for c in columns))
_write_inserts(fh, 'feedback_feedbacktype', columns, out)
# College announcements: keep rows, redact message body.
if _table_exists('Appointment_college_announcement'):
columns = _table_columns('Appointment_college_announcement')
rows = _fetch_rows('Appointment_college_announcement', columns)
out = []
for row in rows:
data = dict(zip(columns, row))
if data.get('announcement') not in (None, ''):
data['announcement'] = REDACTED
out.append(tuple(data[c] for c in columns))
_write_inserts(fh, 'Appointment_college_announcement', columns, out)
# Books referenced by sample lend records (plus full if none).
if _table_exists('yp_library_book'):
columns = _table_columns('yp_library_book')
if ctx.book_ids:
ph, params = _in_clause(list(ctx.book_ids))
rows = _fetch_rows(
'yp_library_book', columns, f'id IN ({ph})', params
)
else:
rows = []
book_index = {
int(dict(zip(columns, row))['id']): i
for i, row in enumerate(
sorted(rows, key=lambda r: int(dict(zip(columns, r))['id'])),
start=1,
)
}
out = []
for row in rows:
data = dict(zip(columns, row))
n = book_index[int(data['id'])]
data['title'] = f'书本{n}'
if 'identity_code' in data:
data['identity_code'] = f'B{n:06d}'
if 'author' in data and data['author'] not in (None, ''):
data['author'] = REDACTED
if 'publisher' in data and data['publisher'] not in (None, ''):
data['publisher'] = REDACTED
out.append(tuple(data[c] for c in columns))
_write_inserts(fh, 'yp_library_book', columns, out)
# Users and profiles
if ctx.user_ids:
ph, params = _in_clause(list(ctx.user_ids))
_write_filtered(
fh,
'generic_user',
f'id IN ({ph})',
params,
lambda cols, row: _transform_user_row(ctx, cols, row),
)
if ctx.person_ids:
ph, params = _in_clause(list(ctx.person_ids))
_write_filtered(
fh,
'app_naturalperson',
f'id IN ({ph})',
params,
lambda cols, row: _transform_naturalperson(ctx, cols, row),
)
if ctx.org_ids:
ph, params = _in_clause(list(ctx.org_ids))
_write_filtered(
fh,
'app_organization',
f'id IN ({ph})',
params,
lambda cols, row: _transform_organization(ctx, cols, row),
)
# Freshmen
if ctx.freshman_ids and _table_exists('app_freshman'):
ordered = sorted(ctx.freshman_ids)
index_map = {pk: i for i, pk in enumerate(ordered, start=1)}
ph, params = _in_clause(ordered)
_write_filtered(
fh,
'app_freshman',
f'id IN ({ph})',
params,
lambda cols, row: _transform_freshman(ctx, cols, row, index_map),
)
# Participants
if ctx.participant_usernames:
ph, params = _in_clause(list(ctx.participant_usernames))
_write_filtered(
fh,
'Appointment_participant',
f'Sid_id IN ({ph})',
params,
lambda cols, row: _transform_participant(ctx, cols, row),
)
# Credit / YQPoint by username; redact free-text source labels.
for table, user_col in (
('generic_creditrecord', 'user_id'),
('generic_yqpointrecord', 'user_id'),
):
if not _table_exists(table) or not ctx.username_map: