Sub topic 8
Casting columns and capturing source file metadata while loading
This chapter assumes you can write a basic COPY INTO statement, know how FORMAT_OPTIONS control CSV parsing, and understand how the target table's schema is set. You should also know that COPY INTO skips files it has already loaded.
Why transform during the load
Files rarely arrive with the types you want. A CSV file has no type information, so every column is a string unless you let COPY INTO infer types. Inference guesses, and a guess can change from one batch to the next. A column that looks like an integer today may contain a code like A17 tomorrow.
COPY INTO accepts a SELECT statement in place of a plain path. The query runs on each file as it is read, before the rows reach the table. You can use it to:
- Cast columns to the exact types the target table expects.
- Rename columns or compute new ones.
- Add file metadata, such as the path of the file each row came from.
A SELECT source
COPY INTO main.sales.orders
FROM (
SELECT
CAST(order_id AS BIGINT) AS order_id,
CAST(amount AS DECIMAL(10, 2)) AS amount,
CAST(order_ts AS TIMESTAMP) AS order_ts,
_metadata.file_path AS source_file
FROM '/Volumes/main/sales/landing/orders/'
)
FILEFORMAT = CSV
FORMAT_OPTIONS ('header' = 'true');The FROM clause inside the parentheses holds the source path. The FILEFORMAT and FORMAT_OPTIONS stay outside, after the closing parenthesis. The SELECT runs against the columns the parser finds in the files, so the names in your CAST calls must match the CSV header.
The target table must have columns that line up with the query's output. Here the table needs order_id, amount, order_ts and source_file.
Capturing file metadata
Every file read by COPY INTO exposes a hidden _metadata column. It is not part of the file's data, and you only see it if you select it by name. Useful fields include:
| Field | Contents |
|---|---|
| `_metadata.file_path` | Full path of the source file |
| `_metadata.file_name` | File name without the directory |
| `_metadata.file_size` | Size of the file in bytes |
| `_metadata.file_modification_time` | Last modified time of the file |
Storing file_path gives you lineage. When a bad row shows up, you can find the file that produced it. It also helps when you want to delete and reload one file's rows after the source is corrected.
Because _metadata is hidden, SELECT * never returns it. List it explicitly, as the example does with _metadata.file_path AS source_file.
How the load flows
Common errors
- Cast failures. If a value cannot convert, such as
N/Acast toDECIMAL, the load can fail or produce nulls, depending on your Spark ANSI mode setting. Run the statement withVALIDATEfirst to see problem rows before anything is written. - Column mismatch. If the query's output columns don't match the table's columns, the load fails with a schema error. Use
ASaliases so names match exactly. - Putting options in the wrong place.
FILEFORMATandFORMAT_OPTIONSgo after the closing parenthesis, not inside the subquery. - Expecting the transform to rerun. Files that were already loaded are skipped, even if you change the
SELECT. Changing the query does not reprocess old files unless you use theforceoption, which is covered in a later chapter.
Exercise
You want each loaded row to record the file it came from, and you want SELECT * to be unnecessary. What do you add to the SELECT source, and why won't SELECT * return it automatically?
Show answer
Add _metadata.file_path AS source_file (or another _metadata field) to the SELECT list, and make sure the target table has a source_file column. SELECT * does not return it because _metadata is a hidden column that must be selected by name.
Exercise
You edit the CAST in your SELECT source to fix a wrong type, then re-run COPY INTO on the same folder. No rows change. Why?
Show answer
COPY INTO tracks which files it has loaded and skips them on later runs, regardless of the query. To reprocess those files you would need the force option, after deciding how to handle the rows already in the table.