Drupal 6 to Drupal 7 image_attach to imagefield migration

The old table structure

image_attach → image → files

becomes

field_data_field_image → file_managed

Assuming that the database name is test, imagefield is named field_image. file access type is public and the files folder is located in DRUPAL_ROOT,

fill the field_data_field_image table:

INSERT INTO file_managed (fid, uid, filename, uri, filemime, filesize, status, timestamp)
SELECT DISTINCT f.fid fid, f.uid uid, REPLACE(f.filepath, 'files/images/', '') filename, REPLACE(f.filepath, 'files/images/', 'public://') uri,
f.filemime filemime, f.filesize filesize, f.status status, f.timestamp timestamp
FROM image_attach ia, image i, files f WHERE ia.iid=i.nid AND i.fid=f.fid AND f.filename='_original' AND;

then, fill the file_managed table:

INSERT INTO field_data_field_image (entity_type, bundle, deleted, entity_id, revision_id, language, delta, field_image_fid, field_image_alt, field_image_title, field_image_width, field_image_height)
SELECT DISTINCT 'node' node, 'event' bundle, 0 deleted, ia.nid entity_id, n.vid revision_id, 'und' language, 0 delta, f.fid field_image_fid, '' field_image_alt, '' field_image_title, NULL field_image_width, NULL field_image_height
FROM image_attach ia, image i, files f, node n WHERE n.nid = ia.nid AND ia.iid=i.nid AND i.fid=f.fid AND f.filename='_original';

As the default location of uploaded images changed, we should move files

$ echo "SELECT REPLACE(f.filepath, 'files/images/', '') FROM image_attach ia, image i, files f, node n WHERE n.nid = ia.nid AND ia.iid=i.nid AND i.fid=f.fid AND f.filename='_original' AND NOT f.filepath LIKE '%baden baden.jpg';"|\
mysql -s rib | while read i do; cp "files/images/$i" "files/$i"; done