# Export catalog data to S3 (checklist)

Read before any `UNLOAD`, or `SELECT` whose purpose is to put data in S3. Ask one step at a time;
take values already stated in the conversation, `use_case_spec.md`, or the active project instead
of re-asking. On any failure or a "no", follow
[Failure handling](overview.md#failure-handling) in overview.md.

## Consent steps

1. **Scope** — whole table, or a subset (row filter, first N rows, partition range)?
2. **Fields** — list the readable columns (from the preview), all pre-selected; the user keeps
   or removes. Columns marked "not readable with your permissions" cannot be exported.
3. **Destination** — the S3 prefix (and KMS key, if any). Suggest one the user can accept or
   change: `s3://sagemaker-<region>-<account-id>/data-discovery/exports/<table>/<UTC timestamp>/`
   when `aws s3api head-bucket --bucket sagemaker-<region>-<account-id>` succeeds (a new
   timestamped prefix is empty); otherwise ask for one. For a general (`UNLOAD`) export the
   prefix must be **empty** (`aws s3api list-objects-v2 --bucket <bucket> --prefix <prefix>
   --max-items 1`); if it has objects, ask for a new prefix. The DataSet branch writes one
   uniquely named `.csv`, so its destination does not need to be empty. A KMS key is applied
   through the query's result configuration, not the SQL. `--result-configuration` is one
   structure, so pass both parts together:
   `--result-configuration OutputLocation=<path>,EncryptionConfiguration={EncryptionOption=SSE_KMS,KmsKey=<key-arn>}`
   (for `UNLOAD`, `<path>` is the workgroup result location that receives its manifest).
   On an enforced workgroup the workgroup's encryption applies instead; say so in the summary.
4. **Purpose and format**
   - **Register as a SageMaker AI DataSet** → single CSV (DataSet branch below); do not ask format.
   - **Otherwise** → ask; default **Parquet**, JSONL or CSV on request. `UNLOAD` format values:
     Parquet → `format = 'PARQUET'`; JSONL → `format = 'JSON'`; CSV →
     `format = 'TEXTFILE', field_delimiter = ','` (no header row). `UNLOAD` has no `CSV` format.
5. **Summary, then explicit yes** — show source table, columns, filter, destination, format, and
   workgroup, and state: *the export contains only the rows and columns you are permitted to read*
   (Lake Formation column grants and row filters are applied silently). Also state the cost and
   reversibility: Athena bills for the data the query scans, the written objects incur S3 storage
   until deleted, and the export can be undone by deleting the written objects.

## Gotchas (check before running)

- **Enforced workgroups** (see [overview.md](overview.md) step 2) silently replace a `SELECT`'s
  output location; say so before running. For the DataSet branch see below; for a general export
  use `UNLOAD`, which writes to the prefix it names.
- **`UNLOAD` output shape.** One or more part files under the prefix, without `.parquet`/`.jsonl`
  extensions (JSON and TEXTFILE/CSV are gzip `.gz` by default — add `compression = 'NONE'` for
  uncompressed); its manifest goes to the workgroup result location,
  not the prefix. Tell the user this when reporting.
- **S3 Tables** use the `Catalog=` addressing in [overview.md](overview.md) step 3.
- **Third-party (`uai::`) tables** cannot be exported through Athena — stop and say so.

## Run and verify

- **General export.** Write the confirmed `UNLOAD` statement to `export.sql` with a quoted heredoc
  and pass it as `file://` (see overview.md). Not enforced — pass the result configuration from
  step 3 (add
  `,EncryptionConfiguration={EncryptionOption=SSE_KMS,KmsKey=<key-arn>}` only if a KMS key was
  chosen):

  ```bash
  cat > export.sql <<'SQL'
  UNLOAD (SELECT <confirmed columns> FROM … [WHERE …]) TO '<prefix>' WITH (format = …)
  SQL
  aws athena start-query-execution --work-group <workgroup> --query-execution-context Database=<database> \
    --query-string file://export.sql \
    --result-configuration OutputLocation=<workgroup result location>
  rm -f export.sql
  ```

  Enforced — the workgroup's location and encryption apply, so omit `--result-configuration`:

  ```bash
  cat > export.sql <<'SQL'
  UNLOAD (SELECT <confirmed columns> FROM … [WHERE …]) TO '<prefix>' WITH (format = …)
  SQL
  aws athena start-query-execution --work-group <workgroup> --query-execution-context Database=<database> \
    --query-string file://export.sql
  rm -f export.sql
  ```

  Verify with `aws s3api list-objects-v2 --bucket <bucket> --prefix <prefix>`; report the prefix and
  file list.
- **DataSet branch:** `dataset-import` needs one `.csv` file, which only a `SELECT` result
  produces (`UNLOAD` part files have no extension). Pick the location before running:
  - **Workgroup not enforced** → `SELECT <confirmed columns> FROM … [WHERE …]` (via `file://`,
    removed after submit, as above) with
    `--result-configuration OutputLocation=<prefix>`.
  - **Workgroup enforced** → the CSV can only land in the workgroup's output location. Offer: keep
    it there (show that location and confirm it as the destination), or switch to a workgroup that
    is not enforced (confirm the switch). Do not fall back to `UNLOAD` for this branch.

  The `SELECT` writes one uncompressed `.csv` (plus a `.csv.metadata`). Read
  `ResultConfiguration.OutputLocation` back from
  `aws athena get-query-execution --query-execution-id <id>`, confirm it is under the confirmed
  prefix (Athena reports the full `<prefix><query-execution-id>.csv` URI), then `aws s3api head-object --bucket <bucket> --key <key>`. Hand off to
  [../dataset-import/overview.md](../dataset-import/overview.md) with Path=`<that .csv URI>` and
  Format=`Custom`; it runs its own confirmation. Note that a `Custom` CSV DataSet may need
  conversion before fine-tuning.
