D1 · OData v4 Gateway

The easiest way to expose D1 via OData

Bridge Google AppSheet, Power BI, Excel, and enterprise tools directly to Cloudflare D1 SQLite databases—with zero servers, sub-10ms edge latency, and full read/write CRUD.

5M / day Free D1 Reads
0 Servers No IPs or Firewalls
Full CRUD GET, POST, PATCH, DELETE

Spreadsheets

Great for prototyping, but Google Sheets slows down past a few thousand rows and lacks real relational constraints.

  • Slow syncs on large tables
  • No foreign keys or ACID transactions
  • API rate limits under concurrent users

Traditional SQL Servers

PostgreSQL or SQL Server require always-on VMs, connection pools, static IPs, and firewall rules opened to external clouds.

  • Monthly fixed server costs even when idle
  • Complex VPC, SSL & IP allowlist setup
  • Single-region latency spikes
Under The Hood

Built for Edge-Native OData

Timing-Safe Authentication

Validates HTTP Basic Auth headers via SHA-256 constant-time XOR comparison, preventing credential length and timing side-channel leaks.

AST Query Parser

Tokenizes $filter, $select, and $orderby into a strict Abstract Syntax Tree, validating table and column names against safe alphanumeric rules.

Parameterized SQL Compiler

Compiles every literal value into bound ? SQLite parameters—100% immune to SQL injection attacks.

D1 Execution & OData Envelope

Executes directly on Cloudflare D1 via Worker bindings and formats standard OData v4 JSON with @odata.context and @odata.nextLink.

From query to SQLite

OData to SQLite Translator

Select a preset or edit the OData query path to inspect how D1Sheet compiles requests into parameterized D1 queries.

GET
CONFIG

Configure wrangler.toml & Secrets

Everything is controlled cleanly through wrangler.toml bindings, [vars], and encrypted Cloudflare Secrets.

Security rule: Never put BASIC_AUTH_PASS in wrangler.toml. Always use npx wrangler secret put BASIC_AUTH_PASS for production and .dev.vars locally.
wrangler.toml
name = "d1sheet"
main = "src/index.ts"
compatibility_date = "2024-09-23"

[[d1_databases]]
binding = "DB"
database_name = "d1sheet-db"
database_id = "YOUR_D1_DATABASE_ID"

[vars]
ODATA_SERVICE_ROOT = "/odata"
DEFAULT_PAGE_SIZE = "100"
MAX_PAGE_SIZE = "1000"
BASIC_AUTH_USER = "admin"
Variable / Binding Purpose Default
DB Cloudflare D1 database binding referenced in Worker code as env.DB DB
ODATA_SERVICE_ROOT Base URL route prefix for all OData endpoints /odata
DEFAULT_PAGE_SIZE Records per page when the client omits $top 100
MAX_PAGE_SIZE Hard ceiling for $top to safeguard Worker memory and D1 reads 1000
BASIC_AUTH_USER Username checked by the HTTP Basic Auth middleware admin
BASIC_AUTH_PASS Encrypted secret stored in Cloudflare (or .dev.vars locally)—never commit to Git. Secret
Zero to Live in 5 Minutes

Step-by-Step Worker Deployment

Follow these six commands from a clean terminal to launch your production OData gateway on Cloudflare Edge.

Node.js 18+ installed
Git CLI
01

Clone the Repository & Install Dependencies

Pull the D1Sheet source from GitHub and install Hono, TypeScript, and Wrangler CLI.

git clone https://github.com/vieirafabiog/D1Sheet.git
cd D1Sheet
npm install
02

Authenticate & Create Your Cloudflare D1 Database

Log into Cloudflare via Wrangler (once) and provision a new serverless SQLite database. Wrangler will print a [[d1_databases]] block with your unique database_id.

npx wrangler login
npx wrangler d1 create d1sheet-db
Wrangler CLI Output Example
[[d1_databases]]
binding = "DB"
database_name = "d1sheet-db"
database_id = "a1b2c3d4-e5f6-7890-abcd-ef1234567890"
03

Bind the Database in wrangler.toml

Open wrangler.toml and paste the database_name and database_id generated in Step 2. Adjust BASIC_AUTH_USER or page size limits if desired.

wrangler.toml
[[d1_databases]]
binding = "DB"
database_name = "d1sheet-db"
database_id = "a1b2c3d4-e5f6-7890-abcd-ef1234567890"
04

Create Tables & Seed Sample Data (Optional)

Use the included schema.sql (Customers, Products, Orders) to populate your remote D1 right away, or run your own SQL migration file.

npm run db:init:remote
# Or with your own schema file:
# npx wrangler d1 execute DB --remote --file=your_schema.sql
05

Set Your Encrypted Production Password

Store BASIC_AUTH_PASS inside Cloudflare encrypted Secrets. Wrangler will prompt you securely in the terminal.

npx wrangler secret put BASIC_AUTH_PASS
06

Deploy to Cloudflare Workers & Verify

Publish your gateway globally in seconds. Wrangler outputs your live URL—test it immediately with cURL or Power BI.

npm run deploy
# Live Service Root: https://d1sheet.<your-subdomain>.workers.dev/odata
Protocol Specification

Endpoints & Query Options

Full OData v4 read/write capabilities paired with automatic SQLite schema reflection.

Method Endpoint Behavior
GET /odata OData Service Document listing all D1 tables for Power BI & AppSheet auto-discovery
GET /odata/$metadata Dynamic EDMX XML schema inspected live via sqlite_master & PRAGMA table_info
GET /odata/{TableName} Query entity collection with $filter, $select, $orderby, $top, $skip, $count & @odata.nextLink
GET /odata/{Table}({id}) Fetch single entity by primary key (supports Table(1), Table(Id=1), or Table/1)
GET /odata/{Table}/$count Return plain-text integer record count matching optional $filter
POST /odata/{TableName} Insert new row using SQLite RETURNING * and return 201 Created + Location header
PATCH / PUT /odata/{Table}({id}) Partial or full update of existing row returning 200 OK + updated entity
DELETE /odata/{Table}({id}) Delete record by primary key and return 204 No Content
OData Query Option Example SQLite Translation
$select ?$select=Id,Name,Balance SELECT "Id", "Name", "Balance" FROM ...
$filter (Relational) ?$filter=Balance ge 1000 and IsVip eq true WHERE ("Balance" >= ? AND "IsVip" = ?)
$filter (Contains) ?$filter=contains(Email, '@corp.com') WHERE (INSTR("Email", ?) > 0)
$filter (Prefix/Suffix) ?$filter=startswith(Name, 'Dr.') WHERE (INSTR("Name", ?) = 1) / LIKE ('%' || ?)
$filter (Nulls) ?$filter=Email ne null and City eq null WHERE ("Email" IS NOT NULL AND "City" IS NULL)
$filter (Functions) ?$filter=tolower(City) eq 'london' LOWER("City"), UPPER(...), LENGTH(...)
$orderby ?$orderby=Balance desc, Name asc ORDER BY "Balance" DESC, "Name" ASC
$top & $skip ?$top=20&$skip=40 LIMIT ? OFFSET ? (with @odata.nextLink)
$count ?$count=true SELECT COUNT(*) AS count ... → "@odata.count"
Develop & Test Offline

Local Development Workflow

Run the full Worker + local SQLite D1 emulator and all 33 automated tests right on your machine.

1. Configure .dev.vars

Create .dev.vars from the example file for your local Basic Auth password.

cp .dev.vars.example .dev.vars

2. Seed Local D1 SQLite

Initialize .wrangler/state/v3/d1 locally using schema.sql.

npm run db:init:local

3. Run Automated Tests (33/33)

Execute auth, SQL translator, CRUD, and metadata integration tests.

npm test && npm run typecheck

4. Start Local Dev Server

Launch Wrangler local gateway at http://localhost:8787/odata.

npm run dev
Plug & Play Clients

Connect Anywhere via OData v4

Built for Google AppSheet, compatible with every OData v4 consumer.

1

Open Sources in AppSheet

Go to My Account → Sources → + New Data Source and select OData.

2

Enter Your Worker Root URL

Set OData Version to 4.0 and paste https://d1sheet.<subdomain>.workers.dev/odata.

3

Basic Authentication

Use your BASIC_AUTH_USER (e.g. admin) and BASIC_AUTH_PASS secret.

4

Full Bidirectional Sync

AppSheet automatically discovers tables, Primary Keys, types, and uses POST / PATCH / DELETE.

AppSheet Modeling Pro-Tips: Ensure every D1 table has an explicit Primary Key (e.g. Id INTEGER PRIMARY KEY AUTOINCREMENT or TEXT UUID) and avoid spaces in column names.
# AppSheet Connection Settings
OData Version : 4.0
Root URL      : https://d1sheet.<you>.workers.dev/odata
Auth Type     : Basic
Username      : admin
Password      : <BASIC_AUTH_PASS>
SAP Gateway   : false
CSRF Required : false
1

Get Data → OData Feed

Open Power BI Desktop, click Get Data and select OData feed.

2

Paste Service Root

Enter https://d1sheet.<you>.workers.dev/odata in Basic mode.

3

Authenticate & Load

Select Basic credentials, sign in, and load any table from the Navigator.

// Power Query (M) Generated Connection
let
    Source = OData.Feed(
        "https://d1sheet.<you>.workers.dev/odata",
        null,
        [Implementation="2.0"]
    ),
    Customers_table = Source{[Name="Customers",Signature="table"]}[Data]
in
    Customers_table
1

Data → Get Data → From Other Sources

Choose From OData Feed inside Excel's Data ribbon.

2

Connect with Basic Auth

Paste your Worker /odata endpoint, provide Basic Auth credentials, and refresh live anytime.

# Live Refreshable Excel Data
URL: https://d1sheet.<you>.workers.dev/odata
Auth: Basic (Username + Secret)
Features: Query Folding ($filter, $select, $top)
1

Standard HTTP + JSON / XML

Query or mutate D1 rows from any language, webhook, Zapier, or Make scenario.

# List tables
curl -u admin:secret https://d1sheet.<you>.workers.dev/odata

# Insert record
curl -X POST -u admin:secret \
  -H "Content-Type: application/json" \
  -d '{"Name":"Alice","Balance":500}' \
  https://d1sheet.<you>.workers.dev/odata/Customers