Laravel Go✓ Human-reviewed

Bounded CSV exports in Laravel Go

Replace a single FastExcel CSV export with encoding/csv, fixed columns, tenant-scoped bounded iteration and private staged artifacts; exclude workbook and import features.

Approved 2026-12-04T13:20:42.346885Z · Submission 61

Bounded CSV exports in Laravel Go

Scope and provenance

Replace one FastExcel CSV export with application-owned row selection, projection and Go's encoding/csv. This is not an XLSX/ODS writer, spreadsheet importer, style engine, multi-sheet API or general FastExcel port. Inventory the actual calls first: if the app needs Excel cell types, formulas, workbook styles or import callbacks, keep a suitable library instead. The refs this recipe was checked against are in its metadata; reconcile them with the target application's toolchain/framework first.

FastExcel by Raphaël Huchet is MIT licensed. Read src/FastExcel.php, src/Exportable.php and tests/FastExcelTest.php, preserving its notices if adapting source/fixtures. Its writer delegates file encoding to OpenSpout. This inline CSV path uses the Go standard library and does not copy that engine. No target-app conversion is claimed.

At the time of writing, the Package Port catalog listed Go as needing a port; check get-recipe's current port catalog. A Go workbook library may be preferable for real workbook requirements, but changing a filename to .xlsx cannot turn CSV bytes into a workbook.

Upstream semantics and deliberate differences

If the installed FastExcel has the inspected implementation, it chooses the writer from the filename, derives headers from the first mapped row, accepts arrays/collections/traversables, and can skip callback rows returning null/false. CSV configuration controls delimiter, enclosure and BOM. Generator export avoids materializing the whole result, whereas a previously loaded collection is already in memory. Transposition is not bounded row streaming.

The application contract here is one fixed ordered schema: ID,Name,JoinedAt, comma-separated UTF-8, CRLF record endings, no BOM, and a header even for an empty result. Rows always have all three cells; null name becomes an empty string; IDs are decimal strings and times are explicitly formatted in UTC. These choices differ from automatic first-row inference and must be accepted by the consumer. CSV cannot guarantee that spreadsheet software preserves leading zeros or long numeric strings as text.

Implement the export job

  1. Authorize the export and establish tenant/user scope before reading data. Select only public export columns, never model serialization or request-provided column names. Generate a trusted server-side filename and enforce maximum rows, cell bytes, total bytes and job duration.
  2. Use a private staged file, not a publicly visible partial download. Create it exclusively beneath a trusted private directory; complete and close it before marking the export ready. Query/writer/cancellation failures delete the partial artifact and do not produce a successful download record. Keep the file until the response has finished reading; a deferred deletion in a job that merely schedules a response is too early.
  3. Iterate with stable keyset pagination or a proven bounded cursor. Include a deterministic unique key and decide whether the export is a point-in-time snapshot or a documented live scan. A high-water ID prevents later inserts above that ID, but does not freeze updates/deletes. Scope every chunk and avoid loading all rows or N+1 relations.
  4. Write each projected row with the standard writer, not string concatenation. Inside the operation owning file and a fallible query loop:
writer := csv.NewWriter(file)
writer.UseCRLF = true
if err := writer.Write([]string{"ID", "Name", "JoinedAt"}); err != nil {
    return err
}
// For each authorized row: validate policy, then writer.Write([]string{...}).
// Return any query, projection or Write error immediately.
writer.Flush()
if err := writer.Error(); err != nil {
    return err
}
// Check file.Close() before promoting the completed artifact.

Imports include encoding/csv; the surrounding job supplies its file lifecycle and query. Flush errors are not optional: buffering can defer disk failures until flush. UseCRLF also normalizes embedded newlines and can discard lone carriage returns; if byte-preserving fields matter, use LF records instead and approve that dialect explicitly.

  1. Choose a spreadsheet-input policy independently of CSV escaping. Quoting a cell does not prevent formula execution. For this bounded human-viewed export, reject untrusted text beginning with =, +, - or @ after trimming leading whitespace/control characters, and reject leading tab/CR/LF controls before serialization. Do not alter trusted generated numeric fields. This intentionally rejects some legitimate names; document the restriction. If lossless arbitrary text and safe spreadsheet opening are both required, use a typed workbook format and test the actual spreadsheet client instead of claiming CSV quoting solves it.
  2. Serve completed files only after fresh authorization, with text/csv; charset=utf-8, a fixed safe attachment filename and private caching. Never put sensitive exports in public storage. Expiry and cleanup must cover failed jobs and finished downloads; retries must not expose another user's artifact.

Acceptance trial

Parse the generated bytes with an independent CSV reader and compare exact header order and rows, not just line counts. Include commas, quotes, Unicode, embedded LF/CRLF and lone CR, nulls, empty result, leading-zero IDs and large IDs. Approve documented newline/consumer coercion differences.

  • Formula-looking text and leading controls follow rejection policy; no partial artifact becomes downloadable after rejection.
  • Distinct tenants exporting concurrently get only their own rows/files. All chunks retain authorization filters.
  • More than two query chunks produce every expected ID once; concurrent insert/update/delete behavior matches the declared consistency contract.
  • Simulated disk-full/short write, query failure, cancellation and file-close failure leave no ready record or leaked partial file.
  • Peak memory stays bounded as row count grows; enforce limits with a dataset large enough to reveal accidental Get/slice accumulation.

Run the target app's go test ./..., go test -race ./..., go vet ./... and gofmt. Record Go/framework versions, dialect, real database/filesystem, memory measurement and result bytes with the change.