- session.add(row)
-
- session.commit()
- print 'loaded'
-
- # Shouldn't matter since this is usually the end of the program and thus
- # the connection too, but let's change this back just in case
- if 'mysql' in engine_uri:
- session.execute('SET FOREIGN_KEY_CHECKS = 1')
-
-
-def csvexport(engine_uri, directory='.'):
+ try:
+ session.add(row)
+ session.flush()
+ except IntegrityError as e:
+ failed_rows.append(row)
+
+ # Loop over the failed rows and keep trying to insert them. If a loop
+ # doesn't manage to insert any rows, bail.
+ do_another_loop = True
+ while failed_rows and do_another_loop:
+ do_another_loop = False
+
+ for i, row in enumerate(failed_rows):
+ try:
+ session.add(row)
+ session.flush()
+
+ # Success!
+ del failed_rows[i]
+ do_another_loop = True
+ except IntegrityError as e:
+ pass
+
+ if failed_rows:
+ print len(failed_rows), "rows failed"
+ else:
+ print 'loaded'
+
+def command_csvexport(engine_uri, directory='.'):