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 | @attribution.command()
@click.option(
'--limit', help='Process n packages at a time (best for testing/debugging).'
)
@click.option('--dry-run', help="Don't save anything to the database.", is_flag=True)
@click.option(
'--search-api/--no-search-api',
help='Search external APIs (e.g. ORCID) for details.',
default=True,
)
def migratedb(limit, dry_run, search_api):
"""
Semi-manual migration script that attempts to extract individual contributors from
'author' and 'contributor' fields (if present) in order to create Agent and
ContributionActivity records for them.
"""
if not dry_run:
click.secho(
'Attempting to migrate contributors. It is HIGHLY recommended that you back up your '
'database before running this.',
fg='red',
)
click.confirm('Continue?', default=False, abort=True)
converted_packages = [r.package_id for r in PackageContributionActivityQuery.all()]
unconverted_packages = PackageQuery.search(
~PackageQuery.m.id.in_(converted_packages)
)
contribution_extras = {
p.id: Session.query(PackageExtra)
.filter(PackageExtra.package_id == p.id, PackageExtra.key == 'contributors')
.first()
for p in unconverted_packages
}
total = len(unconverted_packages)
limit = int(limit or total)
parser = migration.Parser()
for i, pkg in enumerate(unconverted_packages[:limit]):
click.echo('Processing package {0} of {1}.\n'.format(i + 1, total))
parser.run(pkg.author, pkg.id, 'author')
if contribution_extras.get(pkg.id) is not None:
extras = contribution_extras.get(pkg.id).value
if not isinstance(extras, str):
parser.run(extras, pkg.id, 'contributor')
combiner = migration.Combiner(parser)
combined = combiner.run()
if search_api:
api_updater = migration.APISearch()
for agnt in combined:
api_updater.update(agnt)
click.echo(f'\n\n{len(combined)} contributors found.')
if dry_run:
click.echo('Exiting before saving to the database.')
return
agent_lookup = {}
agent_create = toolkit.get_action('agent_create')
contribution_activity_create = toolkit.get_action('contribution_activity_create')
agent_affiliation_create = toolkit.get_action('agent_affiliation_create')
remove_keys = ['packages', 'affiliations', 'key', 'all_names']
for a in combined:
try:
# create the agent (check it doesn't exist first)
agent_dict = {**{k: v for k, v in a.items() if k not in remove_keys}}
if a['agent_type'] == 'person':
filters = [
and_(
AgentQuery.m.family_name == a['family_name'],
AgentQuery.m.given_names == a['given_names'],
)
]
else:
filters = [AgentQuery.m.name == a['name']]
if a.get('external_id'):
filters.append(AgentQuery.m.external_id == a.get('external_id'))
matches = AgentQuery.search(or_(*filters))
if len(matches) == 1:
new_agent = matches[0].as_dict()
click.echo(f'MATCHED "{a["key"]}"')
elif len(matches) > 1:
choice_ix = migration.multi_choice(
f'Does "{a["key"]}" match any of these existing agents?',
[m.display_name for m in matches] + ['None of these'],
)
if choice_ix == len(matches):
del a['external_id']
del a['external_id_scheme']
new_agent = agent_create({'ignore_auth': True}, agent_dict)
click.echo(f'CREATED "{a["key"]}"')
else:
new_agent = matches[choice_ix].as_dict()
click.echo(f'MATCHED "{a["key"]}"')
else:
new_agent = agent_create({'ignore_auth': True}, agent_dict)
click.echo(f'CREATED "{a["key"]}"')
agent_lookup[a['key']] = new_agent['id']
# then activities
for pkg, order in a['packages'].get('author', []):
# create citation
contribution_activity_create(
{'ignore_auth': True},
{
'activity': '[citation]',
'scheme': 'internal',
'order': order,
'package_id': pkg,
'agent_id': new_agent['id'],
},
)
# then the actual activity
contribution_activity_create(
{'ignore_auth': True},
{
'activity': 'Unspecified',
'scheme': 'internal',
'package_id': pkg,
'agent_id': new_agent['id'],
},
)
for pkg, _ in a['packages'].get('contributor', []):
# just the activity for this one
contribution_activity_create(
{'ignore_auth': True},
{
'activity': 'Unspecified',
'scheme': 'internal',
'package_id': pkg,
'agent_id': new_agent['id'],
},
)
except Exception as e:
# very broad catch just so it doesn't ruin everything if one thing breaks
click.echo(f'Skipping {a["key"]} due to error: {e}', err=True)
# finally, the affiliations
for pkg, pairs in combiner.affiliations.items():
for agent_a, agent_b in pairs:
try:
agent_affiliation_create(
{'ignore_auth': True},
{
'agent_a_id': agent_lookup[agent_a],
'agent_b_id': agent_lookup[agent_b],
'package_id': pkg,
},
)
except Exception as e:
# very broad catch just so it doesn't ruin everything if one thing breaks
click.echo(
f'Skipping {agent_a} + {agent_b} affiliation due to error: {e}',
err=True,
)
# finally finally, update the package author strings
for pkg in unconverted_packages[:limit]:
try:
authors = get_author_string(package_id=pkg.id)
PackageQuery.update(pkg.id, author=authors)
except Exception as e:
# very broad catch just so it doesn't ruin everything if one thing breaks
click.echo(f'Skipping {pkg.id} due to error: {e}', err=True)
|