try_copy_file function
Applies to: Databricks SQL
Databricks Runtime 18 LTS and above
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: AFILEvalue to copy.destination: An optionalSTRINGwith the full destination file path, not just a directory. When omitted, the file is copied into Unity Catalog-managed storage, converting aFILE EXTERNALreference to aFILE MANAGEDreference.if_file_exists_mode: An optionalSTRINGthat sets the behavior when a file already exists at the destination path. Applies only when using thedestinationargument. Accepted values (case insensitive) are:'error': Raises an error. This is the default value.'overwrite': Overwrites the existing file.'skip': Skips copying and returns aFILEreference 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_filefunction. Use it to ignore errors when converting aFILE EXTERNALreference to aFILE MANAGEDreference, whether the conversion is explicit (omittingdestination) or automatic (inserting aFILE EXTERNALvalue into aFILE MANAGEDcolumn). - If a file already exists at the destination path, Databricks raises an error by default unless you set
if_file_exists_modetooverwriteorskip.
Common error conditions
COPY_FILE_ERROR.FILE_ALREADY_EXISTSCOPY_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:
SELECT try_copy_file(deleted_file, destination => '/Volumes/archive/reports/report.pdf');
NULL
To copy a file into Unity Catalog-managed storage, converting a FILE EXTERNAL reference to a FILE MANAGED reference, omit the destination:
SELECT try_copy_file(to_file('/Volumes/source/data/input.csv'));
To copy a file and overwrite any existing destination file:
SELECT try_copy_file(
to_file('/Volumes/source/reports/report.pdf'),
destination => '/Volumes/archive/reports/report.pdf',
if_file_exists_mode => 'overwrite'
);