Hi

I am uploading a file using managed file. the function is working well for new files. but when I upload a file with the same name ,for some files it is not working.
and it is throwing an error
as below

PDOException: SQLSTATE[23000]: Integrity constraint violation: 1062 Duplicate entry 'cloudinary.Assets://default_3.png' for key 'uri': UPDATE {file_managed} SET uid=:db_update_placeholder_0, filename=:db_update_placeholder_1, uri=:db_update_placeholder_2, filemime=:db_update_placeholder_3, filesize=:db_update_placeholder_4, status=:db_update_placeholder_5, timestamp=:db_update_placeholder_6 WHERE (fid = :db_condition_placeholder_0) ; Array ( [:db_update_placeholder_0] => 1 [:db_update_placeholder_1] => default.png [:db_update_placeholder_2] => cloudinary.Assets://default_3.png [:db_update_placeholder_3] => image/png [:db_update_placeholder_4] => 821 [:db_update_placeholder_5] => 1 [:db_update_placeholder_6] => 1496125623 [:db_condition_placeholder_0] => 4461 ) in drupal_write_record() (line 7362 of /home/pp7/www/includes/common.inc).

I tried clearing the tabel with filename = default.png. but error comes for the default_1.png after the upload. Yes i know that in my table i have upto default_54.png. So should i delete all the default_* files?

the code i am using here is

/**
 * form creation
 * @param unknown $form
 * @param unknown $form_state
 * @return array $form
 */
function ctools_singleasset_upload_manage_form($form, &$form_state){
  $field_instance = field_info_instance('node', 'field_asset_file', 'asset');
  $form['field_asset_file'] = array(
      '#type' => 'managed_file',
      '#title' => t('Upload File'),
      '#upload_validators' => array(
          'file_validate_extensions' => array(
              $field_instance['settings']['file_extensions']
          )
      ),
      '#required' => TRUE,
      '#progress_indicator' => 'bar'
  );
  $form['field_submit'] = array(
      '#type' => 'submit',
      '#value' => t('Save'),
      '#attributes' => array(
          'class' => array(
              'btn-default btn-primary'
          )
      )
  );
  $form['#submit'][] = 'ctools_singleasset_upload_manage';
  return $form;
}
/**
 * Submit function
 */
function ctools_singleasset_upload_manage($form, &$form_state){
  if ($form_state['values']['field_asset_file'] != 0){
    $root_folder = variable_get('cloudinary_root_folder', FALSE);
    $cloudinary_path = 'cloudinary.' . $root_folder . '://';
    $upload_max_size = 50;
    $file_direc = variable_get('cloudinary_file_directory', FALSE);
    $file = file_load($form_state['values']['field_asset_file']);
    $file->status = FILE_STATUS_PERMANENT;
    if ($file_direc){
      $directory = $cloudinary_path . $file_direc;
    } else{
      $directory = $cloudinary_path;
    }
    file_prepare_directory($directory, FILE_CREATE_DIRECTORY);
    $file->uri = file_unmanaged_copy($file->uri, $directory, FILE_EXISTS_REPLACE);
    drupal_chmod($file->uri);
    file_save($file);
    global $user;
    $newnode = ( object ) NULL;
    $newnode->type = 'asset';
    $newnode->uid = $user->uid;
    $newnode->created = strtotime("now");
    $newnode->changed = strtotime("now");
    $newnode->status = 1;
    $newnode->language = 'und';
    node_object_prepare($newnode);
    if ($file){
      $file->status = FILE_STATUS_PERMANENT;
      file_save($file);
      $newnode->field_asset_file['und'][0] = array(
        'uid' => $file->uid,
        'status' => 1,
        'filename' => $file->filename,
        'uri' => $file->uri,
        'filemime' => $file->filemime,
        'filesize' => $file->filesize,
        'display' => 1,
        'description' => '',
        'fid' => $file->fid,
        'rdf_mapping' => array(),
        'timestamp' => time() 
      );
      if (isset($file->destination)){
        $newnode->field_asset_file['und'][0]['destination'] = $file->destination;
      }
      
      if ($file->fid){
        $newnode->title = $file->filename;
        $metadata = get_asset_file_metadata($file->fid);
        $jsonmetadata = json_encode(unserialize($metadata));
        $newnode->field_asset_metadata['und'][0]['value'] = $jsonmetadata;
        $jsonmetadata = unserialize($metadata);
        if (isset($jsonmetadata) && ! isset($jsonmetadata['format'])){
          $ext = ! empty($jsonmetadata['url']) ? pathinfo($jsonmetadata['url'], PATHINFO_EXTENSION) : '';
          $jsonmetadata['format'] = $ext;
        }
        
        $newnode->field_metadata_public_id['und'][0]['value'] = $jsonmetadata['public_id'];
        $newnode->field_metadata_version['und'][0]['value'] = $jsonmetadata['version'];
        $newnode->field_metadata_bytes['und'][0]['value'] = $jsonmetadata['bytes'];
        $newnode->field_metadata_format['und'][0]['value'] = $jsonmetadata['format'];
        $newnode->field_metadata_created_at['und'][0]['value'] = $jsonmetadata['created_at'];
        $newnode->field_metadata_tags['und'][0]['value'] = $jsonmetadata['tags'][0];
        $newnode->field_metadata_url['und'][0]['value'] = $jsonmetadata['url'];
        $newnode->field_metadata_resource_type['und'][0]['value'] = $jsonmetadata['resource_type'];
        
        if (isset($jsonmetadata['color'])){
          $newnode->field_metadata_color['und'][0]['value'] = $jsonmetadata['color'];
        }
        
        if ($jsonmetadata['resource_type'] == 'image'){
          $newnode->field_metadata_width['und'][0]['value'] = isset($jsonmetadata['width']) ? $jsonmetadata['width'] : '';
          $newnode->field_metadata_height['und'][0]['value'] = isset($jsonmetadata['height']) ? $jsonmetadata['height'] : '';
          if ($jsonmetadata['width'] == $jsonmetadata['height']){
            $newnode->field_orientation['und'][0]['value'] = 'square';
          } else if ($jsonmetadata['width'] > $jsonmetadata['height']){
            $newnode->field_orientation['und'][0]['value'] = 'landscape';
          } else if ($jsonmetadata['width'] < $jsonmetadata['height']){
            $newnode->field_orientation['und'][0]['value'] = 'portrait';
          }
          // /Checking Size fieldand set the value
          if ($jsonmetadata['width'] >= 800){
            $newnode->field_size_asset['und'][0]['value'] = 'large';
          } else if ($jsonmetadata['width'] >= 200 && $jsonmetadata['width'] <= 799){
            $newnode->field_size_asset['und'][0]['value'] = 'medium';
          } else if ($jsonmetadata['width'] >= 1 && $jsonmetadata['width'] <= 199){
            $newnode->field_size_asset['und'][0]['value'] = 'small';
          }
        }
        node_save($newnode);
             
      }
      drupal_set_message(t('Asset uploaded successfully.'), 'status', FALSE);
    }
  } else{
    drupal_set_message(t('Please select file to upload asset.'), 'error');
  }
}

What i am missing here? .. thanks in advance

Comments

lipinponmala007’s picture

it took a long time to find the root cause.

The database row and the physical file should be actually in sync. That means if in the file_managed table is having sample.pdf in URI then sample.pdf should be there in the file uploaded location as well.

Let us see how this is possible to have the table and location mismatch

1) database is taken from another instance and the "files" folder is not copied.

2)manually moved some of the files from server. but corresponding data is there in databse table.

More insights:

Consider the a file "sample.pdf" is uploaded.

then

Drupal will check if the file is already there in a physical location. if existing asccording to the setting file can get replaced or overwritten or operation got allowed. if "rename" is in the settings "sample_0.pdf" will be used and the corresponding uri will be stored in the database.

consider id sample.pdf is not present in the uploading location,physically in the next file upload. 

In this case, Drupal could not find the file the suggestion for the uri will be "sample.pdf"  to save for the database. Since the database table, "file_managed" already have sample.pdf in URI column the database error will be coming. 

Solution

try

If the database is was taken from another instance. take the files directory as well.

Avoid manual deleting of files in the Drupal file system.

-