Serverless SQL-to-CSV Report Engine
A serverless function that turns one signed JSON request into a multi-section CSV report, uploads it to Cloudflare R2 and can email the link.
- PHP 8.2
- DigitalOcean Functions
- MySQL
- Cloudflare R2
- SMTP
Why I built it
Report requests change all the time: a new column, another total, a different grouping, or data from another project. Instead of writing a new export endpoint for every report, one request describes the whole report and the function does the rest.
What a request can describe
- Datasets: SQL queries with their values passed separately as bindings (prepared statements, never string-built SQL).
- Sections: detailed tables, or group summaries that group rows and add up columns. Several sections go into one CSV file, and one dataset can feed more than one section.
- Columns: rename fields, fall back to another field when empty, map stored codes to labels, multiply, add or subtract fields, and pull nested values out of JSON or PHP-serialized data.
- Summary rows: labels, sums and row counts.
- Email: recipients, subject and an HTML body with the download link.
- Project: choose which database to read from, from an allow-list of connections.
Technical highlights
- Low memory on large reports: rows are read with unbuffered queries and written to the CSV as they arrive, instead of loading everything into memory.
- Security before anything else: the caller's IP must be allowed, the request must carry a valid HMAC-SHA256 signature over a timestamp and the sorted JSON body, and old timestamps are rejected. All of this is checked before a database connection is opened.
- Cloud delivery: the finished file is uploaded to Cloudflare R2 and the response returns its public URL plus row counts per dataset.
- Deployed as a DigitalOcean Functions web action on the PHP 8.2 runtime.