Aller au contenu principal

try_copy_file function

Applies to: check marked yes Databricks SQL check marked yes Databricks Runtime 18 LTS and above

Beta

This feature is in Beta. Workspace admins can control access to this feature from the Previews page. See Manage Databricks previews.

Copies a file to a destination path and returns a FILE reference, or NULL if the source file doesn't exist or is inaccessible. Omit destination to copy the file into Unity Catalog-managed storage, which converts a FILE EXTERNAL reference to a FILE MANAGED reference.

Syntax

try_copy_file(file => file
[, destination => destination ]
[, if_file_exists_mode => mode ])

You can pass arguments positionally or by name. After you pass an argument by name, all following arguments must also be passed by name. For more information, see named parameter invocation.

Arguments

  • file: A FILE value to copy.
  • destination: An optional STRING with the full destination file path, not just a directory. When omitted, the file is copied into Unity Catalog-managed storage, converting a FILE EXTERNAL reference to a FILE MANAGED reference.
  • if_file_exists_mode: An optional STRING that sets the behavior when a file already exists at the destination path. Applies only when using the destination argument. Accepted values (case insensitive) are:
    • 'error': Raises an error. This is the default value.
    • 'overwrite': Overwrites the existing file.
    • 'skip': Skips copying and returns a FILE reference to the existing file.

Returns

A FILE value that references the copied file, or NULL if the source file doesn't exist or is inaccessible.

Notes

  • This function is the error-tolerant version of copy_file function. Use it to ignore errors when converting a FILE EXTERNAL reference to a FILE MANAGED reference, whether the conversion is explicit (omitting destination) or automatic (inserting a FILE EXTERNAL value into a FILE MANAGED column).
  • If a file already exists at the destination path, Databricks raises an error by default unless you set if_file_exists_mode to overwrite or skip.

Common error conditions

  • COPY_FILE_ERROR.FILE_ALREADY_EXISTS
  • COPY_FILE_AUTHORIZATION_ERROR.WRITE_UNAUTHORIZED

For more information, see Error conditions in Databricks.

Examples

If the source file doesn't exist, try_copy_file returns NULL:

SQL
SELECT try_copy_file(deleted_file, destination => '/Volumes/archive/reports/report.pdf');
Text
NULL

To copy a file into Unity Catalog-managed storage, converting a FILE EXTERNAL reference to a FILE MANAGED reference, omit the destination:

SQL
SELECT try_copy_file(to_file('/Volumes/source/data/input.csv'));

To copy a file and overwrite any existing destination file:

SQL
SELECT try_copy_file(
to_file('/Volumes/source/reports/report.pdf'),
destination => '/Volumes/archive/reports/report.pdf',
if_file_exists_mode => 'overwrite'
);