You cannot select more than 25 topics
Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
120 lines
6.1 KiB
Python
120 lines
6.1 KiB
Python
|
1 month ago
|
"""Move built-in steps 5/6 and duplicate questionnaire metadata into their own columns.
|
||
|
|
|
||
|
|
Dry run by default. --apply requires a new backup file; unexpected conflicts abort.
|
||
|
|
Custom dynamic steps, scores, submission states and timestamps are preserved.
|
||
|
|
"""
|
||
|
|
import argparse
|
||
|
|
import datetime
|
||
|
|
import json
|
||
|
|
from pathlib import Path
|
||
|
|
import re
|
||
|
|
|
||
|
|
from migrate_training_step_answers import ROOT, connect
|
||
|
|
|
||
|
|
TASK_STEPS = {'market-opportunity-selection': (5, 6), 'product-pricing': (5,), 'category-optimization': (5,)}
|
||
|
|
QUESTIONNAIRE_ROW = 'f0874dba-d859-4489-af2f-017c2bbe1b29'
|
||
|
|
|
||
|
|
|
||
|
|
def dump(value):
|
||
|
|
return json.dumps(value, ensure_ascii=False, separators=(',', ':'))
|
||
|
|
|
||
|
|
|
||
|
|
def plan_row(row):
|
||
|
|
changes = {}
|
||
|
|
dynamic = json.loads(row.get('dynamic_step_answers') or '{}')
|
||
|
|
for step in TASK_STEPS.get(row['task_key'], ()):
|
||
|
|
key = 'step%d' % step
|
||
|
|
if key not in dynamic:
|
||
|
|
continue
|
||
|
|
column = key + '_answer'
|
||
|
|
existing = json.loads(row.get(column) or '{}')
|
||
|
|
if existing and existing != dynamic[key]:
|
||
|
|
raise ValueError('Conflicting %s on %s' % (column, row['id']))
|
||
|
|
changes[column] = dump(dynamic.pop(key))
|
||
|
|
if changes:
|
||
|
|
changes['dynamic_step_answers'] = dump(dynamic)
|
||
|
|
if row['id'] == QUESTIONNAIRE_ROW:
|
||
|
|
three = json.loads(row['step3_answer'] or '{}')
|
||
|
|
four = json.loads(row['step4_answer'] or '{}')
|
||
|
|
url = four.get('questionnaireFileUrl')
|
||
|
|
if url:
|
||
|
|
if url != three.get('importedDocumentUrl'):
|
||
|
|
raise ValueError('Questionnaire URL differs from step 3')
|
||
|
|
for key in ('questionnaireFileName', 'questionnaireFileUrl'):
|
||
|
|
if key in four:
|
||
|
|
if key in three and three[key] != four[key]:
|
||
|
|
raise ValueError('Conflicting questionnaire metadata: ' + key)
|
||
|
|
three[key] = four.pop(key)
|
||
|
|
changes.update(step3_answer=dump(three), step4_answer=dump(four))
|
||
|
|
return changes
|
||
|
|
|
||
|
|
|
||
|
|
def synchronize_step(cursor, row, column, raw):
|
||
|
|
step = int(re.search(r'\d+', column)[0])
|
||
|
|
cursor.execute('INSERT INTO student_training_step_answer '
|
||
|
|
'(id,progress_id,student_user_id,teaching_class_id,task_id,task_key,step_no,step_name,answer_json,create_time,update_time) '
|
||
|
|
'VALUES (%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s) ON DUPLICATE KEY UPDATE answer_json=VALUES(answer_json)',
|
||
|
|
['s%d-%s' % (step, row['id']), 'p-' + row['id'], row['student_user_id'], row['teaching_class_id'],
|
||
|
|
row['task_id'], row['task_key'], step, 'Step %d' % step, raw, row['create_time'], row['update_time']])
|
||
|
|
for url in set(re.findall(r'(?:https?://[^\s\"\']+)?/file/[^\s\"\']+', raw.replace('\\/', '/'))):
|
||
|
|
cursor.execute('UPDATE training_knowledge_file SET step_no=%s WHERE student_user_id=%s AND task_key=%s AND file_url=%s',
|
||
|
|
[step, row['student_user_id'], row['task_key'], url])
|
||
|
|
cursor.execute('UPDATE training_knowledge_chunk SET step_no=%s WHERE knowledge_file_id IN '
|
||
|
|
'(SELECT id FROM training_knowledge_file WHERE student_user_id=%s AND task_key=%s AND file_url=%s)',
|
||
|
|
[step, row['student_user_id'], row['task_key'], url])
|
||
|
|
|
||
|
|
|
||
|
|
def main():
|
||
|
|
parser = argparse.ArgumentParser(description=__doc__)
|
||
|
|
parser.add_argument('--apply', action='store_true')
|
||
|
|
parser.add_argument('--backup', type=Path)
|
||
|
|
args = parser.parse_args()
|
||
|
|
if args.apply and not args.backup:
|
||
|
|
parser.error('--apply requires --backup')
|
||
|
|
conn = connect(ROOT / 'src/main/resources/application-dev.yml')
|
||
|
|
try:
|
||
|
|
with conn.cursor() as cursor:
|
||
|
|
cursor.execute('START TRANSACTION' if args.apply else 'START TRANSACTION READ ONLY')
|
||
|
|
cursor.execute('SELECT * FROM student_training_answer WHERE task_key IN (%s,%s,%s) OR id=%s' +
|
||
|
|
(' FOR UPDATE' if args.apply else ''), list(TASK_STEPS) + [QUESTIONNAIRE_ROW])
|
||
|
|
plans = [(row, plan_row(row)) for row in cursor.fetchall()]
|
||
|
|
plans = [(row, changes) for row, changes in plans if changes]
|
||
|
|
print(dump({'mode': 'apply' if args.apply else 'dry-run', 'rows': len(plans),
|
||
|
|
'changes': {row['id']: list(changes) for row, changes in plans}}))
|
||
|
|
if not args.apply:
|
||
|
|
return
|
||
|
|
backup = {'answers': [row for row, _ in plans], 'details': [], 'files': [], 'chunks': []}
|
||
|
|
for row, _ in plans:
|
||
|
|
for table, key in [('student_training_step_answer', 'details'), ('training_knowledge_file', 'files'), ('training_knowledge_chunk', 'chunks')]:
|
||
|
|
cursor.execute('SELECT * FROM ' + table + ' WHERE student_user_id=%s AND task_key=%s',
|
||
|
|
[row['student_user_id'], row['task_key']])
|
||
|
|
backup[key].extend(cursor.fetchall())
|
||
|
|
def encode(value):
|
||
|
|
if isinstance(value, (datetime.datetime, datetime.date)):
|
||
|
|
return value.isoformat()
|
||
|
|
if isinstance(value, bytes):
|
||
|
|
return {'bytes_hex': value.hex()}
|
||
|
|
return str(value)
|
||
|
|
with args.backup.open('x', encoding='utf-8') as output:
|
||
|
|
json.dump(backup, output, ensure_ascii=False, default=encode, indent=2)
|
||
|
|
for row, changes in plans:
|
||
|
|
cursor.execute('UPDATE student_training_answer SET ' + ','.join(key + '=%s' for key in changes) + ' WHERE id=%s',
|
||
|
|
list(changes.values()) + [row['id']])
|
||
|
|
for column, raw in changes.items():
|
||
|
|
if column.startswith('step'):
|
||
|
|
synchronize_step(cursor, row, column, raw)
|
||
|
|
cursor.execute('SELECT * FROM student_training_answer WHERE id=%s', [row['id']])
|
||
|
|
actual = cursor.fetchone()
|
||
|
|
for key, value in row.items():
|
||
|
|
if actual[key] != changes.get(key, value):
|
||
|
|
raise ValueError('Post-write verification failed: ' + row['id'] + ' / ' + key)
|
||
|
|
conn.commit()
|
||
|
|
print(dump({'repaired_rows': len(plans), 'backup': str(args.backup)}))
|
||
|
|
finally:
|
||
|
|
conn.rollback()
|
||
|
|
conn.close()
|
||
|
|
|
||
|
|
|
||
|
|
if __name__ == '__main__':
|
||
|
|
main()
|