OK, I've given up trying to do it in raw SQL due to the intricate referential integrity of the Drupal datamodel (OK, I admit defeat!! :)
The following code bootstraps drupal, then moves files from an input directory to the private-files folder on the local drive and uses the Drupal file_save() API to create the Drupal file registers, then updates the user profile custom field (in my case called "field_attachments").
hope it helps anyone trying to do the same. (I created a standalone PHP file called "importuserfiles.php" in the root of the drupal folder using the code below)
<?php
define('DRUPAL_ROOT', getcwd());
$_SERVER['REMOTE_ADDR'] = "localhost"; // Necessary if running from command line
require_once DRUPAL_ROOT . '/includes/bootstrap.inc';
drupal_bootstrap(DRUPAL_BOOTSTRAP_FULL);
$local_from_path = 'c:\\inputfiles'; // root folder of your input folders.
$drupal_private_base = 'c:\\website-files'; // root location of Drupal's private website files.
$di = new RecursiveDirectoryIterator($local_from_path);
foreach (new RecursiveIteratorIterator($di) as $filename => $file) {
$user_id = explode('-', $di); // the userid is held in the folder name (userfiles-uid)
$uid = $user_id[1]; // so pull the second value from the array (after userfiles-)
echo $filename . ' - ' . $file->getSize() . ' bytes. Attaching to user: ' . $uid . '<br/>';
$local_to_path = $drupal_private_base . '\\userfiles-' . $uid . '\\' . basename($filename); // the destination folder on the local file system for this user.
$drupal_to_path = "private://userfiles-" . $uid.'/'.basename($filename); // the private files folder URI for this user.
echo "Moving file: " . $filename . " To: " . $local_to_path . '</br>';
mkdir($drupal_private_base . '\\userfiles-' . $uid); // make the destination folder in case it doesn't exist.
//move the file to the new location
if (!rename($filename, $local_to_path)) {
echo "failed to move $file.. </br>";
break;
}
$user = user_load($uid); // load the user object
// create the file object for Drupal...
$filetosave = new stdClass();
$filetosave->filename = basename($filename);
$filetosave->filepath = $filename;
$filetosave->uri = $drupal_to_path;
$filetosave->filemime = file_get_mimetype($filename);
$filetosave->filesize = filesize($filename);
$filetosave->display = 1;
$filetosave->description = basename($filename); // just use the filename as the description
$filetosave->uid = $uid;
$filetosave->status = FILE_STATUS_PERMANENT;
file_save($filetosave); // save the file so Drupal registers it.
$user->field_attachments['und'][] = (array)$filetosave; // add the file to the file field called "field_attachments"
user_save($user);
?>