loutilities 3.12.2.dev1__tar.gz → 3.12.4.dev1__tar.gz

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (115) hide show
  1. {loutilities-3.12.2.dev1/loutilities.egg-info → loutilities-3.12.4.dev1}/PKG-INFO +2 -1
  2. loutilities-3.12.4.dev1/loutilities/anonymize_db.py +573 -0
  3. {loutilities-3.12.2.dev1 → loutilities-3.12.4.dev1}/loutilities/tables-assets/static/datatables.js +11 -1
  4. {loutilities-3.12.2.dev1 → loutilities-3.12.4.dev1}/loutilities/tables-assets/static/editor.displayController.onPage.js +12 -8
  5. {loutilities-3.12.2.dev1 → loutilities-3.12.4.dev1}/loutilities/version.py +1 -1
  6. {loutilities-3.12.2.dev1 → loutilities-3.12.4.dev1/loutilities.egg-info}/PKG-INFO +2 -1
  7. {loutilities-3.12.2.dev1 → loutilities-3.12.4.dev1}/loutilities.egg-info/SOURCES.txt +1 -0
  8. {loutilities-3.12.2.dev1 → loutilities-3.12.4.dev1}/loutilities.egg-info/entry_points.txt +1 -0
  9. {loutilities-3.12.2.dev1 → loutilities-3.12.4.dev1}/loutilities.egg-info/requires.txt +1 -0
  10. {loutilities-3.12.2.dev1 → loutilities-3.12.4.dev1}/setup.py +3 -0
  11. {loutilities-3.12.2.dev1 → loutilities-3.12.4.dev1}/.gitattributes +0 -0
  12. {loutilities-3.12.2.dev1 → loutilities-3.12.4.dev1}/.gitignore +0 -0
  13. {loutilities-3.12.2.dev1 → loutilities-3.12.4.dev1}/README.md +0 -0
  14. {loutilities-3.12.2.dev1 → loutilities-3.12.4.dev1}/loutilities/__init__.py +0 -0
  15. {loutilities-3.12.2.dev1 → loutilities-3.12.4.dev1}/loutilities/agegrade.py +0 -0
  16. {loutilities-3.12.2.dev1 → loutilities-3.12.4.dev1}/loutilities/apikey.py +0 -0
  17. {loutilities-3.12.2.dev1 → loutilities-3.12.4.dev1}/loutilities/applytemplate.py +0 -0
  18. {loutilities-3.12.2.dev1 → loutilities-3.12.4.dev1}/loutilities/bfile.py +0 -0
  19. {loutilities-3.12.2.dev1 → loutilities-3.12.4.dev1}/loutilities/boolexpr.py +0 -0
  20. {loutilities-3.12.2.dev1 → loutilities-3.12.4.dev1}/loutilities/config.py +0 -0
  21. {loutilities-3.12.2.dev1 → loutilities-3.12.4.dev1}/loutilities/configparser.py +0 -0
  22. {loutilities-3.12.2.dev1 → loutilities-3.12.4.dev1}/loutilities/csvu.py +0 -0
  23. {loutilities-3.12.2.dev1 → loutilities-3.12.4.dev1}/loutilities/csvwt.py +0 -0
  24. {loutilities-3.12.2.dev1 → loutilities-3.12.4.dev1}/loutilities/extconfigparser.py +0 -0
  25. {loutilities-3.12.2.dev1 → loutilities-3.12.4.dev1}/loutilities/filetrigger.py +0 -0
  26. {loutilities-3.12.2.dev1 → loutilities-3.12.4.dev1}/loutilities/filtercsv.py +0 -0
  27. {loutilities-3.12.2.dev1 → loutilities-3.12.4.dev1}/loutilities/filters.py +0 -0
  28. {loutilities-3.12.2.dev1 → loutilities-3.12.4.dev1}/loutilities/flask/__init__.py +0 -0
  29. {loutilities-3.12.2.dev1 → loutilities-3.12.4.dev1}/loutilities/flask/user/__init__.py +0 -0
  30. {loutilities-3.12.2.dev1 → loutilities-3.12.4.dev1}/loutilities/flask/user/views.py +0 -0
  31. {loutilities-3.12.2.dev1 → loutilities-3.12.4.dev1}/loutilities/flask_helpers/__init__.py +0 -0
  32. {loutilities-3.12.2.dev1 → loutilities-3.12.4.dev1}/loutilities/flask_helpers/as_blueprint.py +0 -0
  33. {loutilities-3.12.2.dev1 → loutilities-3.12.4.dev1}/loutilities/flask_helpers/blueprints.py +0 -0
  34. {loutilities-3.12.2.dev1 → loutilities-3.12.4.dev1}/loutilities/flask_helpers/decorators.py +0 -0
  35. {loutilities-3.12.2.dev1 → loutilities-3.12.4.dev1}/loutilities/flask_helpers/mailer.py +0 -0
  36. {loutilities-3.12.2.dev1 → loutilities-3.12.4.dev1}/loutilities/geo.py +0 -0
  37. {loutilities-3.12.2.dev1 → loutilities-3.12.4.dev1}/loutilities/googleauth.py +0 -0
  38. {loutilities-3.12.2.dev1 → loutilities-3.12.4.dev1}/loutilities/kmlutils.py +0 -0
  39. {loutilities-3.12.2.dev1 → loutilities-3.12.4.dev1}/loutilities/makerst.py +0 -0
  40. {loutilities-3.12.2.dev1 → loutilities-3.12.4.dev1}/loutilities/namesplitter.py +0 -0
  41. {loutilities-3.12.2.dev1 → loutilities-3.12.4.dev1}/loutilities/nesteddict.py +0 -0
  42. {loutilities-3.12.2.dev1 → loutilities-3.12.4.dev1}/loutilities/nicknames.csv +0 -0
  43. {loutilities-3.12.2.dev1 → loutilities-3.12.4.dev1}/loutilities/nicknames.py +0 -0
  44. {loutilities-3.12.2.dev1 → loutilities-3.12.4.dev1}/loutilities/renderrun.py +0 -0
  45. {loutilities-3.12.2.dev1 → loutilities-3.12.4.dev1}/loutilities/sqlalchemy_helpers.py +0 -0
  46. {loutilities-3.12.2.dev1 → loutilities-3.12.4.dev1}/loutilities/tables-assets/readme.md +0 -0
  47. {loutilities-3.12.2.dev1 → loutilities-3.12.4.dev1}/loutilities/tables-assets/static/background-post-data-manager.js +0 -0
  48. {loutilities-3.12.2.dev1 → loutilities-3.12.4.dev1}/loutilities/tables-assets/static/branding.css +0 -0
  49. {loutilities-3.12.2.dev1 → loutilities-3.12.4.dev1}/loutilities/tables-assets/static/buttons.colvis.js +0 -0
  50. {loutilities-3.12.2.dev1 → loutilities-3.12.4.dev1}/loutilities/tables-assets/static/charts.css +0 -0
  51. {loutilities-3.12.2.dev1 → loutilities-3.12.4.dev1}/loutilities/tables-assets/static/charts.js +0 -0
  52. {loutilities-3.12.2.dev1 → loutilities-3.12.4.dev1}/loutilities/tables-assets/static/datatables-childrow.js +0 -0
  53. {loutilities-3.12.2.dev1 → loutilities-3.12.4.dev1}/loutilities/tables-assets/static/datatables.css +0 -0
  54. {loutilities-3.12.2.dev1 → loutilities-3.12.4.dev1}/loutilities/tables-assets/static/datatables.dataRender.datetime.js +0 -0
  55. {loutilities-3.12.2.dev1 → loutilities-3.12.4.dev1}/loutilities/tables-assets/static/datatables.dataRender.ellipsis.js +0 -0
  56. {loutilities-3.12.2.dev1 → loutilities-3.12.4.dev1}/loutilities/tables-assets/static/datatables.dataRender.googledoc.js +0 -0
  57. {loutilities-3.12.2.dev1 → loutilities-3.12.4.dev1}/loutilities/tables-assets/static/editor-saeditor.js +0 -0
  58. {loutilities-3.12.2.dev1 → loutilities-3.12.4.dev1}/loutilities/tables-assets/static/editor.buttons.editchildrowrefresh.js +0 -0
  59. {loutilities-3.12.2.dev1 → loutilities-3.12.4.dev1}/loutilities/tables-assets/static/editor.buttons.editrefresh.js +0 -0
  60. {loutilities-3.12.2.dev1 → loutilities-3.12.4.dev1}/loutilities/tables-assets/static/editor.buttons.separator.js +0 -0
  61. {loutilities-3.12.2.dev1 → loutilities-3.12.4.dev1}/loutilities/tables-assets/static/editor.ckeditor5.js +0 -0
  62. {loutilities-3.12.2.dev1 → loutilities-3.12.4.dev1}/loutilities/tables-assets/static/editor.css +0 -0
  63. {loutilities-3.12.2.dev1 → loutilities-3.12.4.dev1}/loutilities/tables-assets/static/editor.fieldType.display.js +0 -0
  64. {loutilities-3.12.2.dev1 → loutilities-3.12.4.dev1}/loutilities/tables-assets/static/editor.googledoc.js +0 -0
  65. {loutilities-3.12.2.dev1 → loutilities-3.12.4.dev1}/loutilities/tables-assets/static/editor.select2.mymethods.js +0 -0
  66. {loutilities-3.12.2.dev1 → loutilities-3.12.4.dev1}/loutilities/tables-assets/static/eventscalendar.css +0 -0
  67. {loutilities-3.12.2.dev1 → loutilities-3.12.4.dev1}/loutilities/tables-assets/static/filters.css +0 -0
  68. {loutilities-3.12.2.dev1 → loutilities-3.12.4.dev1}/loutilities/tables-assets/static/filters.js +0 -0
  69. {loutilities-3.12.2.dev1 → loutilities-3.12.4.dev1}/loutilities/tables-assets/static/jquery.ui.dialog-clickoutside.js +0 -0
  70. {loutilities-3.12.2.dev1 → loutilities-3.12.4.dev1}/loutilities/tables-assets/static/jqueryui.theme.adjust.css +0 -0
  71. {loutilities-3.12.2.dev1 → loutilities-3.12.4.dev1}/loutilities/tables-assets/static/legend.js +0 -0
  72. {loutilities-3.12.2.dev1 → loutilities-3.12.4.dev1}/loutilities/tables-assets/static/mutex-promise.js +0 -0
  73. {loutilities-3.12.2.dev1 → loutilities-3.12.4.dev1}/loutilities/tables-assets/static/user/admin/beforedatatables.js +0 -0
  74. {loutilities-3.12.2.dev1 → loutilities-3.12.4.dev1}/loutilities/tables-assets/static/user/admin/groups.js +0 -0
  75. {loutilities-3.12.2.dev1 → loutilities-3.12.4.dev1}/loutilities/tables-assets/static/utils.js +0 -0
  76. {loutilities-3.12.2.dev1 → loutilities-3.12.4.dev1}/loutilities/tables-assets/templates/bare-layout.jinja2 +0 -0
  77. {loutilities-3.12.2.dev1 → loutilities-3.12.4.dev1}/loutilities/tables-assets/templates/datatables.html +0 -0
  78. {loutilities-3.12.2.dev1 → loutilities-3.12.4.dev1}/loutilities/tables-assets/templates/datatables.jinja2 +0 -0
  79. {loutilities-3.12.2.dev1 → loutilities-3.12.4.dev1}/loutilities/tables-assets/templates/layout-base.jinja2 +0 -0
  80. {loutilities-3.12.2.dev1 → loutilities-3.12.4.dev1}/loutilities/tables-assets/templates/layout.html +0 -0
  81. {loutilities-3.12.2.dev1 → loutilities-3.12.4.dev1}/loutilities/tables-assets/templates/layout.jinja2 +0 -0
  82. {loutilities-3.12.2.dev1 → loutilities-3.12.4.dev1}/loutilities/tables-assets/templates/security/change_password.jinja2 +0 -0
  83. {loutilities-3.12.2.dev1 → loutilities-3.12.4.dev1}/loutilities/tables-assets/templates/security/email/reset_instructions.html +0 -0
  84. {loutilities-3.12.2.dev1 → loutilities-3.12.4.dev1}/loutilities/tables-assets/templates/security/email/reset_instructions.txt +0 -0
  85. {loutilities-3.12.2.dev1 → loutilities-3.12.4.dev1}/loutilities/tables-assets/templates/security/forgot_password.jinja2 +0 -0
  86. {loutilities-3.12.2.dev1 → loutilities-3.12.4.dev1}/loutilities/tables-assets/templates/security/login_user.jinja2 +0 -0
  87. {loutilities-3.12.2.dev1 → loutilities-3.12.4.dev1}/loutilities/tables-assets/templates/security/reset_password.jinja2 +0 -0
  88. {loutilities-3.12.2.dev1 → loutilities-3.12.4.dev1}/loutilities/tables-assets/templates/select-view.jinja2 +0 -0
  89. {loutilities-3.12.2.dev1 → loutilities-3.12.4.dev1}/loutilities/tables.py +0 -0
  90. {loutilities-3.12.2.dev1 → loutilities-3.12.4.dev1}/loutilities/textreader.py +0 -0
  91. {loutilities-3.12.2.dev1 → loutilities-3.12.4.dev1}/loutilities/timeu.py +0 -0
  92. {loutilities-3.12.2.dev1 → loutilities-3.12.4.dev1}/loutilities/transform.py +0 -0
  93. {loutilities-3.12.2.dev1 → loutilities-3.12.4.dev1}/loutilities/user/__init__.py +0 -0
  94. {loutilities-3.12.2.dev1 → loutilities-3.12.4.dev1}/loutilities/user/applogging.py +0 -0
  95. {loutilities-3.12.2.dev1 → loutilities-3.12.4.dev1}/loutilities/user/audit_mixin.py +0 -0
  96. {loutilities-3.12.2.dev1 → loutilities-3.12.4.dev1}/loutilities/user/model.py +0 -0
  97. {loutilities-3.12.2.dev1 → loutilities-3.12.4.dev1}/loutilities/user/roles.py +0 -0
  98. {loutilities-3.12.2.dev1 → loutilities-3.12.4.dev1}/loutilities/user/scripts/__init__.py +0 -0
  99. {loutilities-3.12.2.dev1 → loutilities-3.12.4.dev1}/loutilities/user/scripts/users_init.py +0 -0
  100. {loutilities-3.12.2.dev1 → loutilities-3.12.4.dev1}/loutilities/user/settings.py +0 -0
  101. {loutilities-3.12.2.dev1 → loutilities-3.12.4.dev1}/loutilities/user/tablefiles.py +0 -0
  102. {loutilities-3.12.2.dev1 → loutilities-3.12.4.dev1}/loutilities/user/tables.py +0 -0
  103. {loutilities-3.12.2.dev1 → loutilities-3.12.4.dev1}/loutilities/user/views/__init__.py +0 -0
  104. {loutilities-3.12.2.dev1 → loutilities-3.12.4.dev1}/loutilities/user/views/userrole.py +0 -0
  105. {loutilities-3.12.2.dev1 → loutilities-3.12.4.dev1}/loutilities/wxextensions.py +0 -0
  106. {loutilities-3.12.2.dev1 → loutilities-3.12.4.dev1}/loutilities/xmldict.py +0 -0
  107. {loutilities-3.12.2.dev1 → loutilities-3.12.4.dev1}/loutilities.egg-info/dependency_links.txt +0 -0
  108. {loutilities-3.12.2.dev1 → loutilities-3.12.4.dev1}/loutilities.egg-info/not-zip-safe +0 -0
  109. {loutilities-3.12.2.dev1 → loutilities-3.12.4.dev1}/loutilities.egg-info/top_level.txt +0 -0
  110. {loutilities-3.12.2.dev1 → loutilities-3.12.4.dev1}/setup.cfg +0 -0
  111. {loutilities-3.12.2.dev1 → loutilities-3.12.4.dev1}/tests/__init__.py +0 -0
  112. {loutilities-3.12.2.dev1 → loutilities-3.12.4.dev1}/tests/models.py +0 -0
  113. {loutilities-3.12.2.dev1 → loutilities-3.12.4.dev1}/tests/test_sqlalchemy_helpers.py +0 -0
  114. {loutilities-3.12.2.dev1 → loutilities-3.12.4.dev1}/tests/test_tables.py +0 -0
  115. {loutilities-3.12.2.dev1 → loutilities-3.12.4.dev1}/tests/test_user_tables.py +0 -0
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.4
2
2
  Name: loutilities
3
- Version: 3.12.2.dev1
3
+ Version: 3.12.4.dev1
4
4
  Summary: some hopefully useful utilities
5
5
  Home-page: http://github.com/louking/loutilities
6
6
  Author: Lou King
@@ -8,6 +8,7 @@ Author-email: lking@pobox.com
8
8
  License: Apache License, Version 2.0
9
9
  Requires-Dist: flask-security-too>=5.5.0
10
10
  Requires-Dist: flask-sqlalchemy>=3.0.5
11
+ Requires-Dist: pyyaml
11
12
  Dynamic: author
12
13
  Dynamic: author-email
13
14
  Dynamic: description
@@ -0,0 +1,573 @@
1
+ #!/usr/bin/env python
2
+ """
3
+ anonymize_db.py - anonymize PII fields in mysqldump files
4
+
5
+ Reads one or more mysqldump SQL files and replaces configured PII columns with
6
+ synthetic values, leaving all other data intact. Processes files sequentially so
7
+ that sync relationships (e.g. localuser mirrors user) are resolved correctly —
8
+ pass the users DB dump before the members DB dump.
9
+
10
+ Each app supplies its own YAML config describing which tables and columns to
11
+ scrub; the script itself contains no app-specific logic.
12
+
13
+ Usage:
14
+ # Single file to stdout:
15
+ anonymize_db -c anonymize_members.yaml users.sql > users_anon.sql
16
+
17
+ # Multiple files to an output directory (same filenames):
18
+ anonymize_db -c anonymize_members.yaml --output-dir ./anon/ users.sql members.sql
19
+ """
20
+
21
+ import argparse
22
+ import os
23
+ import random
24
+ import re
25
+ import sys
26
+ from datetime import date, timedelta
27
+
28
+ import yaml
29
+
30
+
31
+ # ---------------------------------------------------------------------------
32
+ # SQL value tokenizer
33
+ # ---------------------------------------------------------------------------
34
+
35
+ def _split_insert_rows(values_str):
36
+ """
37
+ Split the VALUES clause of an INSERT statement into per-row content strings
38
+ (without the surrounding parentheses). Handles strings containing commas
39
+ and parentheses correctly.
40
+ """
41
+ rows = []
42
+ i = 0
43
+ n = len(values_str)
44
+
45
+ while i < n:
46
+ # Advance to opening paren of next row
47
+ while i < n and values_str[i] != '(':
48
+ i += 1
49
+ if i >= n:
50
+ break
51
+
52
+ i += 1 # skip '('
53
+ start = i
54
+ depth = 1
55
+
56
+ while i < n and depth > 0:
57
+ c = values_str[i]
58
+ if c == "'": # string literal
59
+ i += 1
60
+ while i < n:
61
+ if values_str[i] == '\\':
62
+ i += 2 # skip escape sequence
63
+ elif values_str[i] == "'":
64
+ i += 1
65
+ break
66
+ else:
67
+ i += 1
68
+ elif c == '(':
69
+ depth += 1
70
+ i += 1
71
+ elif c == ')':
72
+ depth -= 1
73
+ if depth == 0:
74
+ rows.append(values_str[start:i])
75
+ i += 1 # skip ')'
76
+ else:
77
+ i += 1
78
+ else:
79
+ i += 1
80
+
81
+ return rows
82
+
83
+
84
+ def _tokenize_row(s):
85
+ """
86
+ Split a row's value string (content between the outer parens) into a list
87
+ of raw SQL tokens, one per column. Tokens preserve original quoting so
88
+ un-modified columns are written back verbatim.
89
+ """
90
+ tokens = []
91
+ i = 0
92
+ n = len(s)
93
+
94
+ while i < n:
95
+ while i < n and s[i] in ' \t':
96
+ i += 1
97
+ if i >= n:
98
+ break
99
+
100
+ start = i
101
+
102
+ if s[i] == "'":
103
+ # String literal — scan to closing unescaped quote
104
+ i += 1
105
+ while i < n:
106
+ if s[i] == '\\':
107
+ i += 2
108
+ elif s[i] == "'":
109
+ i += 1
110
+ break
111
+ else:
112
+ i += 1
113
+ token = s[start:i]
114
+ elif s[i:i+4] == 'NULL' and (i + 4 >= n or s[i + 4] in (',', ' ', '\t')):
115
+ token = 'NULL'
116
+ i += 4
117
+ elif s[i] == '0' and i + 1 < n and s[i + 1] in 'xX':
118
+ # Hex literal
119
+ i += 2
120
+ while i < n and s[i] in '0123456789abcdefABCDEF':
121
+ i += 1
122
+ token = s[start:i]
123
+ else:
124
+ # Unquoted number or other literal
125
+ while i < n and s[i] not in (',', ' ', '\t'):
126
+ i += 1
127
+ token = s[start:i]
128
+
129
+ tokens.append(token)
130
+
131
+ while i < n and s[i] in ' \t':
132
+ i += 1
133
+ if i < n and s[i] == ',':
134
+ i += 1
135
+
136
+ return tokens
137
+
138
+
139
+ def _sql_to_python(token):
140
+ """Convert a raw SQL token to a Python string, or None for NULL."""
141
+ if token == 'NULL':
142
+ return None
143
+ if token.startswith("'") and token.endswith("'"):
144
+ s = token[1:-1]
145
+ result = []
146
+ i = 0
147
+ escape_map = {
148
+ 'n': '\n', 'r': '\r', 't': '\t', '0': '\0',
149
+ "'": "'", '\\': '\\', '"': '"', 'b': '\b', 'Z': '\x1a',
150
+ }
151
+ while i < len(s):
152
+ if s[i] == '\\' and i + 1 < len(s):
153
+ result.append(escape_map.get(s[i + 1], s[i + 1]))
154
+ i += 2
155
+ else:
156
+ result.append(s[i])
157
+ i += 1
158
+ return ''.join(result)
159
+ return token # number or hex literal — return as-is
160
+
161
+
162
+ def _python_to_sql(value):
163
+ """Convert a Python string (or None) to a SQL token."""
164
+ if value is None:
165
+ return 'NULL'
166
+ s = (str(value)
167
+ .replace('\\', '\\\\')
168
+ .replace("'", "\\'")
169
+ .replace('\n', '\\n')
170
+ .replace('\r', '\\r')
171
+ .replace('\t', '\\t')
172
+ .replace('\0', '\\0'))
173
+ return f"'{s}'"
174
+
175
+
176
+ # ---------------------------------------------------------------------------
177
+ # Anonymization generators
178
+ # ---------------------------------------------------------------------------
179
+
180
+ def _anon_email(row_id):
181
+ return f'user{row_id}@example.com'
182
+
183
+
184
+ def _anon_fullname(row_id):
185
+ return f'Firstname{row_id} Lastname{row_id}'
186
+
187
+
188
+ def _anon_firstname(row_id):
189
+ return f'Firstname{row_id}'
190
+
191
+
192
+ def _anon_lastname(row_id):
193
+ return f'Lastname{row_id}'
194
+
195
+
196
+ def _anon_date_shift(date_str, row_id):
197
+ """Shift a date by a deterministic random offset seeded on row_id."""
198
+ if date_str is None:
199
+ return None
200
+ try:
201
+ d = date.fromisoformat(date_str)
202
+ rng = random.Random(int(row_id) * 97 + 31337)
203
+ d = d + timedelta(days=rng.randint(-1095, 1095)) # ±3 years
204
+ return str(d)
205
+ except (ValueError, TypeError, AttributeError):
206
+ return date_str
207
+
208
+
209
+ # Map type name → lambda(row_id, original_python_value) → new python value
210
+ _GENERATORS = {
211
+ 'email': lambda rid, _v: _anon_email(rid),
212
+ 'fullname': lambda rid, _v: _anon_fullname(rid),
213
+ 'firstname': lambda rid, _v: _anon_firstname(rid),
214
+ 'lastname': lambda rid, _v: _anon_lastname(rid),
215
+ 'date_shift': lambda rid, v: _anon_date_shift(v, rid),
216
+ 'ip': lambda _r, _v: '127.0.0.1',
217
+ 'text': lambda _r, _v: 'anonymized',
218
+ 'city': lambda _r, _v: 'Anytown',
219
+ }
220
+
221
+
222
+ # ---------------------------------------------------------------------------
223
+ # Main processor
224
+ # ---------------------------------------------------------------------------
225
+
226
+ _CREATE_TABLE_RE = re.compile(r'^CREATE TABLE `(\w+)`')
227
+ _COLUMN_DEF_RE = re.compile(r'^\s+`(\w+)`\s')
228
+
229
+
230
+ class DumpAnonymizer:
231
+ """Stream-processes mysqldump files, replacing configured PII columns."""
232
+
233
+ def __init__(self, config):
234
+ self._tables_cfg = config.get('tables', {})
235
+ self._table_columns = {} # table_name -> [col, ...]
236
+ # sync_maps[source_table][source_pk_value] = {field_name: anon_value}
237
+ self._sync_maps = {}
238
+
239
+ # Precompute which fields of which tables need to be stored for sync
240
+ # sync_sources[source_table] = {source_field, ...}
241
+ self._sync_sources = {}
242
+ for _tgt, tgt_cfg in self._tables_cfg.items():
243
+ for field, fcfg in tgt_cfg.get('fields', {}).items():
244
+ if fcfg.get('type') == 'sync':
245
+ src_table = fcfg['source_table']
246
+ src_field = fcfg.get('source_field', field)
247
+ self._sync_sources.setdefault(src_table, set()).add(src_field)
248
+
249
+ # ------------------------------------------------------------------
250
+ # CREATE TABLE parsing
251
+ # ------------------------------------------------------------------
252
+
253
+ def _parse_create_table(self, block):
254
+ """Return (table_name, [col_name, ...]) from a buffered CREATE TABLE block."""
255
+ first_line = block.split('\n')[0]
256
+ m = _CREATE_TABLE_RE.match(first_line)
257
+ if not m:
258
+ return None, []
259
+ table_name = m.group(1)
260
+ columns = []
261
+ for line in block.split('\n')[1:]:
262
+ stripped = line.strip()
263
+ # Skip constraint lines and the closing ) line
264
+ if not stripped or any(stripped.startswith(kw) for kw in
265
+ ('PRIMARY', 'KEY', 'UNIQUE', 'CONSTRAINT', ')', 'CHECK')):
266
+ continue
267
+ cm = _COLUMN_DEF_RE.match(line)
268
+ if cm:
269
+ columns.append(cm.group(1))
270
+ return table_name, columns
271
+
272
+ # ------------------------------------------------------------------
273
+ # Value generation
274
+ # ------------------------------------------------------------------
275
+
276
+ def _generate(self, field_cfg, row_id, original_val, columns, tokens):
277
+ """
278
+ Compute the anonymized Python value for one field.
279
+ Returns the original value unchanged if the type is unknown.
280
+ """
281
+ ftype = field_cfg.get('type', 'text')
282
+
283
+ # NULL preservation: keep NULL for every type except 'fixed'
284
+ if original_val is None and ftype not in ('fixed', 'sync'):
285
+ return None
286
+
287
+ if ftype == 'sync':
288
+ src_table = field_cfg['source_table']
289
+ src_field = field_cfg.get('source_field') # caller sets this
290
+ join_field = field_cfg['join_field']
291
+
292
+ join_val = None
293
+ if join_field in columns:
294
+ join_val = _sql_to_python(tokens[columns.index(join_field)])
295
+
296
+ return (self._sync_maps
297
+ .get(src_table, {})
298
+ .get(join_val, {})
299
+ .get(src_field, original_val))
300
+
301
+ if ftype == 'fixed':
302
+ return field_cfg.get('value', 'anonymized')
303
+
304
+ generator = _GENERATORS.get(ftype)
305
+ if generator is None:
306
+ return original_val
307
+
308
+ try:
309
+ rid = int(row_id) if row_id is not None else 0
310
+ except (ValueError, TypeError):
311
+ rid = abs(hash(str(row_id))) % 1_000_000
312
+
313
+ return generator(rid, original_val)
314
+
315
+ # ------------------------------------------------------------------
316
+ # Sync map population
317
+ # ------------------------------------------------------------------
318
+
319
+ def _populate_sync_map(self, table_name, columns, row_id, tokens):
320
+ """
321
+ If table_name is a sync source, compute and store the anonymized
322
+ values for fields that downstream tables will need.
323
+ """
324
+ needed_fields = self._sync_sources.get(table_name)
325
+ if not needed_fields:
326
+ return
327
+
328
+ table_cfg = self._tables_cfg.get(table_name, {})
329
+ fields_cfg = table_cfg.get('fields', {})
330
+
331
+ for src_field in needed_fields:
332
+ fcfg = fields_cfg.get(src_field)
333
+ if not fcfg or src_field not in columns:
334
+ continue
335
+ original_val = _sql_to_python(tokens[columns.index(src_field)])
336
+ anon_val = self._generate(fcfg, row_id, original_val, columns, tokens)
337
+
338
+ (self._sync_maps
339
+ .setdefault(table_name, {})
340
+ .setdefault(row_id, {})[src_field]) = anon_val
341
+
342
+ # ------------------------------------------------------------------
343
+ # Row anonymization
344
+ # ------------------------------------------------------------------
345
+
346
+ def _anonymize_row(self, table_name, columns, tokens):
347
+ """Return a new token list with PII columns replaced."""
348
+ table_cfg = self._tables_cfg.get(table_name, {})
349
+ fields_cfg = table_cfg.get('fields', {})
350
+ if not fields_cfg:
351
+ return tokens
352
+
353
+ # Row primary key for deterministic value generation
354
+ pk_field = table_cfg.get('pk', 'id')
355
+ row_id = None
356
+ if pk_field in columns:
357
+ row_id = _sql_to_python(tokens[columns.index(pk_field)])
358
+
359
+ # Store sync values before modifying tokens
360
+ self._populate_sync_map(table_name, columns, row_id, tokens)
361
+
362
+ result = list(tokens)
363
+ for field_name, fcfg in fields_cfg.items():
364
+ if field_name not in columns:
365
+ continue
366
+ idx = columns.index(field_name)
367
+ original_val = _sql_to_python(tokens[idx])
368
+
369
+ # For sync fields, inject source_field so _generate can look it up
370
+ if fcfg.get('type') == 'sync' and 'source_field' not in fcfg:
371
+ fcfg = dict(fcfg, source_field=field_name)
372
+
373
+ anon_val = self._generate(fcfg, row_id, original_val, columns, tokens)
374
+
375
+ if anon_val is None:
376
+ result[idx] = 'NULL'
377
+ elif anon_val != original_val:
378
+ result[idx] = _python_to_sql(str(anon_val))
379
+
380
+ return result
381
+
382
+ # ------------------------------------------------------------------
383
+ # INSERT line processing
384
+ # ------------------------------------------------------------------
385
+
386
+ def _process_insert(self, line):
387
+ """Parse, anonymize, and re-serialise an INSERT line."""
388
+ if not line.startswith('INSERT INTO `'):
389
+ return line
390
+
391
+ i = 13 # len('INSERT INTO `')
392
+ j = line.index('`', i)
393
+ table_name = line[i:j]
394
+
395
+ if table_name not in self._tables_cfg:
396
+ return line
397
+
398
+ rest = line[j + 1:].lstrip() # text after closing backtick
399
+
400
+ # Optional explicit column list: (col1, col2, ...)
401
+ col_list_str = None
402
+ if rest.startswith('('):
403
+ col_end = rest.index(')')
404
+ col_list_str = rest[1:col_end]
405
+ columns = [c.strip().strip('`') for c in col_list_str.split(',')]
406
+ rest = rest[col_end + 1:].lstrip()
407
+ else:
408
+ columns = self._table_columns.get(table_name, [])
409
+
410
+ if not columns:
411
+ return line
412
+
413
+ if not rest.upper().startswith('VALUES'):
414
+ return line
415
+
416
+ # Preserve output line format: detect newline between VALUES and first row
417
+ values_tail = rest[6:] # text after 'VALUES'
418
+ multiline = '\n' in values_tail.lstrip(' \t')
419
+ rest = values_tail.lstrip() # strip whitespace including newline
420
+ rest = rest.rstrip()
421
+ if rest.endswith(';'):
422
+ rest = rest[:-1]
423
+
424
+ row_strings = _split_insert_rows(rest)
425
+ new_rows = []
426
+ for row_str in row_strings:
427
+ tokens = _tokenize_row(row_str)
428
+ if len(tokens) != len(columns):
429
+ # Column count mismatch — emit unchanged to avoid corruption
430
+ new_rows.append(f'({row_str})')
431
+ else:
432
+ new_tokens = self._anonymize_row(table_name, columns, tokens)
433
+ new_rows.append('(' + ','.join(new_tokens) + ')')
434
+
435
+ if multiline:
436
+ rows_str = ',\n'.join(new_rows)
437
+ if col_list_str:
438
+ return f'INSERT INTO `{table_name}` ({col_list_str}) VALUES\n{rows_str};\n'
439
+ return f'INSERT INTO `{table_name}` VALUES\n{rows_str};\n'
440
+ else:
441
+ if col_list_str:
442
+ return f'INSERT INTO `{table_name}` ({col_list_str}) VALUES {",".join(new_rows)};\n'
443
+ return f'INSERT INTO `{table_name}` VALUES {",".join(new_rows)};\n'
444
+
445
+ # ------------------------------------------------------------------
446
+ # File processing
447
+ # ------------------------------------------------------------------
448
+
449
+ def process_file(self, infile, outfile):
450
+ """Stream one mysqldump file from infile to outfile."""
451
+ in_create = False
452
+ create_buffer = []
453
+ insert_buffer = [] # multi-line INSERT that needs anonymizing
454
+ insert_passthru = False # multi-line INSERT whose table is not in config
455
+
456
+ for line in infile:
457
+ # Multi-line INSERT — pass-through (table not in config)
458
+ if insert_passthru:
459
+ outfile.write(line)
460
+ if line.rstrip('\n').rstrip().endswith(';'):
461
+ insert_passthru = False
462
+ continue
463
+
464
+ # Multi-line INSERT — buffer until terminating semicolon
465
+ if insert_buffer:
466
+ insert_buffer.append(line)
467
+ if line.rstrip('\n').rstrip().endswith(';'):
468
+ outfile.write(self._process_insert(''.join(insert_buffer)))
469
+ insert_buffer = []
470
+ continue
471
+
472
+ # CREATE TABLE block
473
+ if in_create:
474
+ create_buffer.append(line.rstrip('\n'))
475
+ outfile.write(line)
476
+ if line.startswith(')'):
477
+ block = '\n'.join(create_buffer)
478
+ tname, cols = self._parse_create_table(block)
479
+ if tname and cols:
480
+ self._table_columns[tname] = cols
481
+ in_create = False
482
+ create_buffer = []
483
+ continue
484
+
485
+ if _CREATE_TABLE_RE.match(line):
486
+ in_create = True
487
+ create_buffer = [line.rstrip('\n')]
488
+ outfile.write(line)
489
+ continue
490
+
491
+ # INSERT line
492
+ if line.startswith('INSERT INTO `'):
493
+ if line.rstrip('\n').rstrip().endswith(';'):
494
+ # Entire INSERT on one line
495
+ outfile.write(self._process_insert(line))
496
+ else:
497
+ # Multi-line INSERT — peek at table name to choose mode
498
+ i = 13 # len('INSERT INTO `')
499
+ j = line.index('`', i)
500
+ if line[i:j] in self._tables_cfg:
501
+ insert_buffer = [line]
502
+ else:
503
+ insert_passthru = True
504
+ outfile.write(line)
505
+ continue
506
+
507
+ outfile.write(line)
508
+
509
+ def process_files(self, file_pairs):
510
+ """
511
+ Process (input_path, output_path_or_None) pairs in order.
512
+ Pass None as output_path to write to stdout.
513
+ """
514
+ for inpath, outpath in file_pairs:
515
+ print(f'Processing {inpath} ...', file=sys.stderr)
516
+ with open(inpath, 'r', encoding='utf-8', errors='replace') as inf:
517
+ if outpath:
518
+ with open(outpath, 'w', encoding='utf-8') as outf:
519
+ self.process_file(inf, outf)
520
+ print(f' -> {outpath}', file=sys.stderr)
521
+ else:
522
+ self.process_file(inf, sys.stdout)
523
+
524
+
525
+ # ---------------------------------------------------------------------------
526
+ # CLI entry point
527
+ # ---------------------------------------------------------------------------
528
+
529
+ def main():
530
+ parser = argparse.ArgumentParser(
531
+ description='Anonymize PII fields in mysqldump files using a YAML config.',
532
+ epilog=(
533
+ 'When using sync relationships (e.g. localuser mirrors user), '
534
+ 'pass the source DB dump first so the sync map is populated before '
535
+ 'the target DB dump is processed.'
536
+ ),
537
+ )
538
+ parser.add_argument(
539
+ '-c', '--config', required=True, metavar='CONFIG',
540
+ help='YAML configuration file describing which tables/columns to anonymize',
541
+ )
542
+ parser.add_argument(
543
+ '--output-dir', metavar='DIR',
544
+ help='Write output files here, using the same filenames as the inputs. '
545
+ 'Required when more than one input file is given.',
546
+ )
547
+ parser.add_argument(
548
+ 'inputs', nargs='+', metavar='DUMP_FILE',
549
+ help='Input mysqldump SQL file(s)',
550
+ )
551
+ args = parser.parse_args()
552
+
553
+ with open(args.config) as f:
554
+ config = yaml.safe_load(f)
555
+
556
+ anonymizer = DumpAnonymizer(config)
557
+
558
+ if args.output_dir:
559
+ os.makedirs(args.output_dir, exist_ok=True)
560
+ file_pairs = [
561
+ (inp, os.path.join(args.output_dir, os.path.basename(inp)))
562
+ for inp in args.inputs
563
+ ]
564
+ else:
565
+ if len(args.inputs) > 1:
566
+ parser.error('Multiple input files require --output-dir.')
567
+ file_pairs = [(args.inputs[0], None)]
568
+
569
+ anonymizer.process_files(file_pairs)
570
+
571
+
572
+ if __name__ == '__main__':
573
+ main()
@@ -221,9 +221,10 @@ function render_select_as_tags () {
221
221
  */
222
222
  function get_button_options(buttons, editor) {
223
223
  var button_options = [];
224
+ var editor_actions = ['create', 'edit', 'editRefresh', 'editChildRowRefresh', 'remove'];
224
225
  for (i=0; i<buttons.length; i++) {
225
226
  button = buttons[i];
226
- if ($.inArray(button, ['create', 'edit', 'editRefresh', 'editChildRowRefresh', 'remove']) >= 0) {
227
+ if ($.inArray(button, editor_actions) >= 0) {
227
228
  button_options.push({extend:button, editor:editor});
228
229
  } else {
229
230
  // convert button actions to javascript, // kludge for conversion from python
@@ -231,6 +232,15 @@ function get_button_options(buttons, editor) {
231
232
  button.action = eval(button.action)
232
233
  }
233
234
 
235
+ // a button configuration object which extends one of the standard editor actions
236
+ // (e.g., {extend:'create', enabled:false} to render a disabled create button) still
237
+ // needs the shared editor annotated, same as the plain string form above -- unless it
238
+ // already brings its own editor (e.g., a custom saeditor for a 'selected' extend)
239
+ if (button.hasOwnProperty('extend') && $.inArray(button.extend, editor_actions) >= 0
240
+ && !button.hasOwnProperty('editor')) {
241
+ button.editor = editor;
242
+ }
243
+
234
244
  button_options.push(button);
235
245
  }
236
246
  }
@@ -19,7 +19,7 @@ function onPageDisplay ( elm ) {
19
19
  var emptyInfo;
20
20
  // jqueryui standalone display controller
21
21
  var sadisplay = Editor.display.jqueryui;
22
-
22
+
23
23
  Editor.display[name] = $.extend( true, {}, Editor.models.display, {
24
24
  // Create the HTML mark-up needed the display controller
25
25
  init: function ( editor ) {
@@ -29,7 +29,7 @@ function onPageDisplay ( elm ) {
29
29
  // emptyInfo = $(elm).html();
30
30
  return Editor.display[name];
31
31
  },
32
-
32
+
33
33
  // Show the form
34
34
  open: function ( editor, form, callback ) {
35
35
  if (editor.mode() == 'create') {
@@ -42,13 +42,13 @@ function onPageDisplay ( elm ) {
42
42
  } else {
43
43
  $(elm).children().detach();
44
44
  $(elm).append( form );
45
-
46
- if ( callback ) {
47
- callback();
45
+
46
+ if ( callback ) {
47
+ callback();
48
48
  }
49
49
  }
50
50
  },
51
-
51
+
52
52
  // Hide the form
53
53
  close: function ( editor, callback ) {
54
54
  // close jqueryui if it's open
@@ -56,12 +56,16 @@ function onPageDisplay ( elm ) {
56
56
 
57
57
  $(elm).children().detach();
58
58
  // $(elm).html( emptyInfo );
59
-
59
+
60
60
  if ( callback ) {
61
61
  callback();
62
62
  }
63
+ },
64
+
65
+ node: function () {
66
+ return elm;
63
67
  }
64
68
  } );
65
-
69
+
66
70
  return name;
67
71
  }
@@ -1,2 +1,2 @@
1
1
  # this string is used for the version string in the documentation, as well as the egg
2
- __version__ = '3.12.2.dev1'
2
+ __version__ = '3.12.4.dev1'
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.4
2
2
  Name: loutilities
3
- Version: 3.12.2.dev1
3
+ Version: 3.12.4.dev1
4
4
  Summary: some hopefully useful utilities
5
5
  Home-page: http://github.com/louking/loutilities
6
6
  Author: Lou King
@@ -8,6 +8,7 @@ Author-email: lking@pobox.com
8
8
  License: Apache License, Version 2.0
9
9
  Requires-Dist: flask-security-too>=5.5.0
10
10
  Requires-Dist: flask-sqlalchemy>=3.0.5
11
+ Requires-Dist: pyyaml
11
12
  Dynamic: author
12
13
  Dynamic: author-email
13
14
  Dynamic: description
@@ -4,6 +4,7 @@ README.md
4
4
  setup.py
5
5
  loutilities/__init__.py
6
6
  loutilities/agegrade.py
7
+ loutilities/anonymize_db.py
7
8
  loutilities/apikey.py
8
9
  loutilities/applytemplate.py
9
10
  loutilities/bfile.py
@@ -1,5 +1,6 @@
1
1
  [console_scripts]
2
2
  agegrade = loutilities.agegrade:main
3
+ anonymize_db = loutilities.anonymize_db:main
3
4
  apikey = loutilities.apikey:main
4
5
  applytemplate = loutilities.applytemplate:main
5
6
  filtercsv = loutilities.filtercsv:main
@@ -1,2 +1,3 @@
1
1
  flask-security-too>=5.5.0
2
2
  flask-sqlalchemy>=3.0.5
3
+ pyyaml
@@ -29,6 +29,7 @@ setup(
29
29
  # include_package_data = True,
30
30
  scripts = [
31
31
  'loutilities/agegrade.py',
32
+ 'loutilities/anonymize_db.py',
32
33
  'loutilities/apikey.py',
33
34
  'loutilities/applytemplate.py',
34
35
  'loutilities/filtercsv.py',
@@ -41,6 +42,7 @@ setup(
41
42
  # 'unicodecsv>=0.13.0',
42
43
  'flask-security-too>=5.5.0',
43
44
  'flask-sqlalchemy>=3.0.5',
45
+ 'pyyaml',
44
46
  ],
45
47
 
46
48
  # include data files as appropriate
@@ -59,6 +61,7 @@ setup(
59
61
  entry_points = {
60
62
  'console_scripts': [
61
63
  'agegrade = loutilities.agegrade:main',
64
+ 'anonymize_db = loutilities.anonymize_db:main',
62
65
  'apikey = loutilities.apikey:main',
63
66
  'applytemplate = loutilities.applytemplate:main',
64
67
  'filtercsv = loutilities.filtercsv:main',