- Categories:
File functions (AI Functions)
TO_FILE¶
Constructs a value of type FILE from a file location or from metadata.
Syntax¶
Use one of the following:
TO_FILE( <stage_name>, <relative_path> ) TO_FILE( <file_url> ) TO_FILE( <metadata> )
Arguments¶
Specify the file by providing:
Both
stage_nameandrelative_pathfile_urlmetadata
Only one of these methods can be used at a time.
stage_nameThe name of the stage where the file is located, as a string, in the form
'@stage_name'.relative_pathThe path to the file on the stage specified by
stage_nameas a string.file_urlA valid stage or scoped file URL as a string.
metadataAn OBJECT containing the required FILE attributes. A FILE must have CONTENT_TYPE, SIZE, ETAG, and LAST_MODIFIED fields. It must also specify the file’s location in one of the following ways:
Both STAGE and RELATIVE_PATH
STAGE_FILE_URL
SCOPED_FILE_URL
Returns¶
A FILE that represents the staged file.
Usage notes¶
Raises an error when:
The supplied URL is not valid.
The file is on a stage that the user lacks privileges to access.
The supplied metadata doesn’t contain the required FILE fields.
Examples¶
Creating FILE objects using TO_FILE¶
A simple use of the TO_FILE function with a stage name and relative path:
Result:
A simple use of the TO_FILE function with a staged file URL:
Result:
Or use the FILE_URL from a file in the directory of your stage:
This example uses TO_FILE function directly with a scoped file URL:
This shows an example of constructing a FILE from an object containing the required metadata:
Adding FILE to a table¶
The following example demonstrates how to create FILE and store it in a table, then perform various operations using that column, including saving and loading from Parquet, SnowPipe, datasets, materialized views, dynamic tables, and cloning with time travel.
Creating a table with a FILE column:
To write a table containing a FILE column to a stage as a Parquet file and load it back:
Create a dataset from a Parquet file:
Copy Parquet files into a table:
Create a Snowpipe:
Create a materialized view or a dynamic table from the table:
Store files in an array in a table column:
Examples of errors¶
These examples illustrate common mistakes in using TO_FILE that result in the function raising an error.
The following example constructs a FILE from a metadata object but omits a required field:
The following example is similar, but omits the ETAG field, which is requred.
The following example shows attempts to GROUP BY, ORDER BY, and CLUSTER BY a FILE column, which is not supported because FILE values cannot be compared.
This final example uses an incorrect stage name, specifically a slash at the end of the stage name. Snowflake already adds a slash between the stage name and relative path, so this results in two slashes, and the combined stage path does not specify any file.
Known limitations¶
TO_FILE cannot be used in INSERT INTO TABLE <t> VALUES clause. Use INSERT INTO TABLE <t> SELECT instead.