Skip to content

API Reference

Temp edited this page Nov 27, 2025 · 8 revisions

API Reference

Complete API endpoint documentation for D1 Database Manager.

Base URL

Production: https://d1.yourdomain.com
Local Dev:  http://localhost:8787

Authentication

All API requests require authentication via Cloudflare Access JWT.

Headers:

Cookie: CF_Authorization=<jwt-token>

Local development bypasses authentication automatically.

Response Format

Success Response

{
  "result": { ... },
  "success": true
}

Error Response

{
  "error": "Error message",
  "success": false
}

Database Endpoints

List Databases

Get all D1 databases in the account.

GET /api/databases

Response:

{
  "result": [
    {
      "uuid": "a1b2c3d4-...",
      "name": "my-database",
      "version": "production",
      "created_at": "2024-11-02T12:00:00.000Z",
      "file_size": 2457600,
      "num_tables": 12
    }
  ],
  "success": true
}

Get Database Info

Get detailed information about a specific database.

GET /api/databases/:dbId/info

Parameters:

  • dbId (path) - Database UUID

Response:

{
  "result": {
    "uuid": "a1b2c3d4-...",
    "name": "my-database",
    "version": "production",
    "created_at": "2024-11-02T12:00:00.000Z",
    "file_size": 2457600,
    "num_tables": 12
  },
  "success": true
}

Create Database

Create a new D1 database.

POST /api/databases
Content-Type: application/json

Body:

{
  "name": "my-database"
}

Response:

{
  "result": {
    "uuid": "new-uuid-...",
    "name": "my-database",
    "version": "production",
    "created_at": "2024-11-03T10:30:00.000Z"
  },
  "success": true
}

Rename Database

Rename a database using migration-based approach.

POST /api/databases/:dbId/rename
Content-Type: application/json

Parameters:

  • dbId (path) - Database UUID

Body:

{
  "newName": "new-database-name"
}

Process:

  1. Creates new database
  2. Exports data
  3. Imports to new database
  4. Deletes original

Response:

{
  "result": {
    "newDatabaseId": "new-uuid-...",
    "name": "new-database-name"
  },
  "success": true
}

Delete Database

Delete a D1 database permanently.

DELETE /api/databases/:dbId

Parameters:

  • dbId (path) - Database UUID

Response:

{
  "result": {
    "message": "Database deleted successfully"
  },
  "success": true
}

Bulk Export Databases

Export multiple databases as SQL dumps.

POST /api/databases/export
Content-Type: application/json

Body:

{
  "databases": [
    {"uuid": "uuid-1", "name": "db1"},
    {"uuid": "uuid-2", "name": "db2"}
  ]
}

Response: Returns SQL content for each database to be zipped client-side.

{
  "result": {
    "db1.sql": "CREATE TABLE ...",
    "db2.sql": "CREATE TABLE ..."
  },
  "success": true
}

Import Database

Import SQL file to create new or update existing database.

POST /api/databases/import
Content-Type: multipart/form-data

Body:

  • file (file) - SQL file to import
  • createNew (boolean) - Create new database if true
  • databaseName (string) - Name for new database (if createNew)
  • targetDatabaseId (string) - Target database UUID (if !createNew)

Response:

{
  "result": {
    "message": "Database imported successfully",
    "databaseId": "uuid-..."
  },
  "success": true
}

Optimize Databases

Run ANALYZE on databases to update query statistics.

POST /api/databases/optimize
Content-Type: application/json

Body:

{
  "databaseIds": ["uuid-1", "uuid-2", "uuid-3"]
}

Response:

{
  "result": {
    "succeeded": ["uuid-1", "uuid-2"],
    "failed": [
      {
        "id": "uuid-3",
        "error": "Error message"
      }
    ]
  },
  "success": true
}

Table Endpoints

List Tables

Get all tables in a database.

GET /api/tables/:dbId/list

Parameters:

  • dbId (path) - Database UUID

Response:

{
  "result": [
    {
      "name": "users",
      "type": "table",
      "ncol": 5,
      "wr": 0,
      "strict": 0
    }
  ],
  "success": true
}

Get Table Schema

Get column definitions for a table.

GET /api/tables/:dbId/schema/:tableName

Parameters:

  • dbId (path) - Database UUID
  • tableName (path) - Table name

Response:

{
  "result": [
    {
      "cid": 0,
      "name": "id",
      "type": "INTEGER",
      "notnull": 1,
      "dflt_value": null,
      "pk": 1
    },
    {
      "cid": 1,
      "name": "name",
      "type": "TEXT",
      "notnull": 1,
      "dflt_value": null,
      "pk": 0
    }
  ],
  "success": true
}

Get Table Data

Get rows from a table with pagination and filtering.

GET /api/tables/:dbId/data/:tableName?limit=50&offset=0

Parameters:

  • dbId (path) - Database UUID
  • tableName (path) - Table name
  • limit (query) - Number of rows per page (default: 50)
  • offset (query) - Number of rows to skip (default: 0)
  • filter_<column> (query) - Filter type for column
  • filterValue_<column> (query) - Filter value for column

Filter Types:

  • contains - TEXT contains value
  • equals - Exact match
  • notEquals - Not equal to value
  • gt - Greater than (numeric)
  • gte - Greater than or equal (numeric)
  • lt - Less than (numeric)
  • lte - Less than or equal (numeric)
  • isNull - IS NULL
  • isNotNull - IS NOT NULL
  • startsWith - TEXT starts with value
  • endsWith - TEXT ends with value

Example:

GET /api/tables/:dbId/data/users?limit=50&offset=0&filter_email=contains&filterValue_email=gmail

Response:

{
  "result": [
    {
      "id": 1,
      "name": "Alice",
      "email": "alice@gmail.com",
      "created_at": "2024-11-01T00:00:00.000Z"
    }
  ],
  "meta": {
    "total": 1,
    "limit": 50,
    "offset": 0
  },
  "success": true
}

Get Table Indexes

Get indexes for a table.

GET /api/tables/:dbId/indexes/:tableName

Parameters:

  • dbId (path) - Database UUID
  • tableName (path) - Table name

Response:

{
  "result": [
    {
      "seq": 0,
      "name": "idx_users_email",
      "unique": 1,
      "origin": "c",
      "partial": 0
    }
  ],
  "success": true
}

Get Table Dependencies

Get foreign key dependencies for tables.

GET /api/tables/:dbId/dependencies?tables=users,posts

Parameters:

  • dbId (path) - Database UUID
  • tables (query) - Comma-separated list of table names

Response:

{
  "result": {
    "users": {
      "outbound": [],
      "inbound": [
        {
          "table": "posts",
          "column": "user_id",
          "onDelete": "CASCADE",
          "onUpdate": "NO ACTION",
          "rowCount": 152
        }
      ]
    },
    "posts": {
      "outbound": [
        {
          "table": "users",
          "column": "user_id",
          "onDelete": "CASCADE",
          "onUpdate": "NO ACTION",
          "rowCount": 0
        }
      ],
      "inbound": []
    }
  },
  "success": true
}

Simulate Cascade Impact

Preview the cascade impact of deleting rows or tables.

POST /api/tables/:dbId/simulate-cascade
Content-Type: application/json

Parameters:

  • dbId (path) - Database UUID

Body:

{
  "targetTable": "posts",
  "whereClause": "id = 42"
}
  • targetTable (required) - Table name being deleted from
  • whereClause (optional) - WHERE clause for row deletion (omit for table deletion)

Response:

{
  "result": {
    "targetTable": "posts",
    "whereClause": "id = 42",
    "totalAffectedRows": 103,
    "maxDepth": 2,
    "cascadePaths": [
      {
        "id": "path-1",
        "sourceTable": "posts",
        "targetTable": "comments",
        "action": "CASCADE",
        "depth": 1,
        "affectedRows": 87,
        "column": "post_id"
      },
      {
        "id": "path-2",
        "sourceTable": "posts",
        "targetTable": "likes",
        "action": "CASCADE",
        "depth": 1,
        "affectedRows": 15,
        "column": "post_id"
      }
    ],
    "affectedTables": [
      {
        "tableName": "posts",
        "action": "DELETE",
        "rowsBefore": 1,
        "rowsAfter": 0,
        "depth": 0
      },
      {
        "tableName": "comments",
        "action": "CASCADE",
        "rowsBefore": 87,
        "rowsAfter": 0,
        "depth": 1
      },
      {
        "tableName": "likes",
        "action": "CASCADE",
        "rowsBefore": 15,
        "rowsAfter": 0,
        "depth": 1
      }
    ],
    "warnings": [
      {
        "type": "high_impact",
        "message": "Deletion will cascade to 102 additional rows across 2 tables",
        "severity": "high"
      }
    ],
    "constraints": [],
    "circularDependencies": []
  },
  "success": true
}

Use Cases:

  • Row deletion from TableView - provides whereClause to simulate specific row(s)
  • Table deletion from DatabaseView - omit whereClause to simulate entire table deletion
  • Impact analysis before destructive operations

See Also: Cascade Impact Simulator for the full feature documentation.

Create Table

Create a new table.

POST /api/tables/:dbId/create
Content-Type: application/json

Parameters:

  • dbId (path) - Database UUID

Body:

{
  "tableName": "users",
  "columns": [
    {
      "name": "id",
      "type": "INTEGER",
      "primaryKey": true,
      "notNull": true
    },
    {
      "name": "name",
      "type": "TEXT",
      "notNull": true
    },
    {
      "name": "email",
      "type": "TEXT",
      "notNull": true,
      "unique": true
    }
  ]
}

Response:

{
  "result": {
    "message": "Table created successfully"
  },
  "success": true
}

Rename Table

Rename a table.

PATCH /api/tables/:dbId/:tableName/rename
Content-Type: application/json

Parameters:

  • dbId (path) - Database UUID
  • tableName (path) - Current table name

Body:

{
  "newName": "customers"
}

Response:

{
  "result": {
    "message": "Table renamed successfully"
  },
  "success": true
}

Clone Table

Clone a table (structure + data + indexes).

POST /api/tables/:dbId/:tableName/clone
Content-Type: application/json

Parameters:

  • dbId (path) - Database UUID
  • tableName (path) - Table name to clone

Body:

{
  "newTableName": "users_copy"
}

Response:

{
  "result": {
    "message": "Table cloned successfully",
    "newTableName": "users_copy"
  },
  "success": true
}

Export Table

Export table as SQL or CSV.

GET /api/tables/:dbId/:tableName/export?format=sql

Parameters:

  • dbId (path) - Database UUID
  • tableName (path) - Table name
  • format (query) - Export format: sql or csv

Response: Returns file content directly.

SQL Format:

CREATE TABLE users (...);
INSERT INTO users VALUES (...);

CSV Format:

id,name,email
1,Alice,alice@example.com

Delete Table

Delete a table.

DELETE /api/tables/:dbId/:tableName

Parameters:

  • dbId (path) - Database UUID
  • tableName (path) - Table name

Response:

{
  "result": {
    "message": "Table deleted successfully"
  },
  "success": true
}

Constraint Validation Endpoints

Validate Full Database

Run constraint validation on all tables in the database.

POST /api/constraints/:dbId/validate

Parameters:

  • dbId (path) - Database UUID

Response:

{
  "result": {
    "database": "my-database",
    "timestamp": "2025-11-04T19:30:00.000Z",
    "totalViolations": 3,
    "violationsByType": {
      "foreign_key": 2,
      "not_null": 1,
      "unique": 0
    },
    "violations": [
      {
        "id": "fk-posts-user_id-0",
        "type": "foreign_key",
        "severity": "warning",
        "table": "posts",
        "column": "user_id",
        "affectedRows": 5,
        "details": "5 orphaned records reference non-existent users",
        "fixable": true,
        "fixStrategies": ["delete", "set_null"],
        "metadata": {
          "parentTable": "users",
          "parentColumn": "id",
          "fkId": 0
        }
      },
      {
        "id": "nn-users-email",
        "type": "not_null",
        "severity": "critical",
        "table": "users",
        "column": "email",
        "affectedRows": 1,
        "details": "1 row has NULL value in NOT NULL column \"email\"",
        "fixable": false,
        "fixStrategies": ["manual"]
      }
    ],
    "isHealthy": false
  },
  "success": true
}

Constraint Types Validated:

  • Foreign Key - Orphaned records with broken references
  • NOT NULL - NULL values in NOT NULL columns
  • UNIQUE - Duplicate values in unique columns

Severity Levels:

  • critical - Major violation (>50 rows or NOT NULL)
  • warning - Moderate violation (10-50 rows)
  • info - Minor violation (<10 rows)

Validate Table

Run constraint validation on a specific table.

POST /api/constraints/:dbId/validate-table
Content-Type: application/json

Parameters:

  • dbId (path) - Database UUID

Body:

{
  "tableName": "posts"
}

Response: Same format as full validation, but limited to specified table.

Apply Fixes

Apply fixes to detected constraint violations.

POST /api/constraints/:dbId/fix
Content-Type: application/json

Parameters:

  • dbId (path) - Database UUID

Body:

{
  "violations": ["fk-posts-user_id-0", "fk-comments-post_id-0"],
  "fixStrategy": "delete"
}

Required Fields:

  • violations - Array of violation IDs to fix
  • fixStrategy - Fix method: delete or set_null

Fix Strategies:

delete - Delete orphaned records

DELETE FROM table WHERE fk_column NOT IN (SELECT pk FROM parent_table)

set_null - Set foreign keys to NULL (requires nullable column)

UPDATE table SET fk_column = NULL WHERE fk_column NOT IN (SELECT pk FROM parent_table)

Response:

{
  "result": [
    {
      "violationId": "fk-posts-user_id-0",
      "success": true,
      "rowsAffected": 5
    },
    {
      "violationId": "fk-comments-post_id-0",
      "success": true,
      "rowsAffected": 12
    }
  ],
  "success": true
}

Note: Only Foreign Key violations are automatically fixable. NOT NULL and UNIQUE violations require manual intervention.

Foreign Key Endpoints

Get All Foreign Keys

Get all foreign keys for a database as graph structure.

GET /api/tables/:dbId/foreign-keys

Parameters:

  • dbId (path) - Database UUID

Response:

{
  "result": {
    "nodes": [
      {
        "id": "users",
        "label": "users",
        "columns": [
          {"name": "id", "type": "INTEGER", "isPK": true},
          {"name": "name", "type": "TEXT", "isPK": false}
        ],
        "rowCount": 152
      },
      {
        "id": "posts",
        "label": "posts",
        "columns": [
          {"name": "id", "type": "INTEGER", "isPK": true},
          {"name": "user_id", "type": "INTEGER", "isPK": false}
        ],
        "rowCount": 487
      }
    ],
    "edges": [
      {
        "id": "fk_posts_user_id_users_id",
        "source": "posts",
        "target": "users",
        "sourceColumn": "user_id",
        "targetColumn": "id",
        "onDelete": "CASCADE",
        "onUpdate": "NO ACTION"
      }
    ]
  },
  "success": true
}

Add Foreign Key

Add a new foreign key constraint.

POST /api/tables/:dbId/foreign-keys/add
Content-Type: application/json

Parameters:

  • dbId (path) - Database UUID

Body:

{
  "sourceTable": "posts",
  "sourceColumn": "user_id",
  "targetTable": "users",
  "targetColumn": "id",
  "onDelete": "CASCADE",
  "onUpdate": "NO ACTION",
  "constraintName": "fk_posts_user_id"
}

Required Fields:

  • sourceTable - Table containing the foreign key
  • sourceColumn - Column with foreign key
  • targetTable - Referenced table
  • targetColumn - Referenced column
  • onDelete - ON DELETE action (CASCADE, RESTRICT, SET NULL, SET DEFAULT, NO ACTION)
  • onUpdate - ON UPDATE action (CASCADE, RESTRICT, SET NULL, SET DEFAULT, NO ACTION)

Optional Fields:

  • constraintName - Custom constraint name (auto-generated if omitted)

Validation:

  • Column types must be compatible
  • Target column must be PRIMARY KEY or have UNIQUE constraint
  • No orphaned rows in source table

Response:

{
  "result": {
    "message": "Foreign key constraint added successfully"
  },
  "success": true
}

Error Response:

{
  "error": "Column type mismatch (INTEGER vs TEXT)",
  "success": false
}

Modify Foreign Key

Modify ON DELETE/ON UPDATE behavior of existing foreign key.

PATCH /api/tables/:dbId/foreign-keys/:constraintName
Content-Type: application/json

Parameters:

  • dbId (path) - Database UUID
  • constraintName (path) - Foreign key constraint name

Body:

{
  "onDelete": "RESTRICT",
  "onUpdate": "NO ACTION"
}

Note: Source/target tables and columns cannot be changed. Delete and recreate the constraint if needed.

Response:

{
  "result": {
    "message": "Foreign key constraint modified successfully"
  },
  "success": true
}

Delete Foreign Key

Remove a foreign key constraint.

DELETE /api/tables/:dbId/foreign-keys/:constraintName

Parameters:

  • dbId (path) - Database UUID
  • constraintName (path) - Foreign key constraint name (e.g., fk_posts_user_id_users_id)

Response:

{
  "result": {
    "message": "Foreign key constraint deleted successfully"
  },
  "success": true
}

Warning: Referential integrity will no longer be enforced after deletion.

See Also: Foreign Key Visualizer for the visual interface to these endpoints.

Index Analyzer Endpoint

Analyze Indexes

Analyze database schema and query patterns to recommend optimal indexes.

GET /api/indexes/:dbId/analyze

Parameters:

  • dbId (path) - Database UUID

Response:

{
  "recommendations": [
    {
      "tableName": "posts",
      "columnName": "user_id",
      "indexType": "single",
      "priority": "high",
      "rationale": "Foreign key column referencing users.id. Indexes on foreign keys significantly improve JOIN performance.",
      "estimatedImpact": "High - Foreign key lookups will be much faster, especially for JOINs",
      "suggestedSQL": "CREATE INDEX idx_posts_user_id ON posts(user_id);"
    }
  ],
  "existingIndexes": [
    {
      "tableName": "users",
      "indexes": [
        {
          "name": "sqlite_autoindex_users_1",
          "columns": ["id"],
          "unique": true
        }
      ]
    }
  ],
  "statistics": {
    "totalRecommendations": 4,
    "tablesWithoutIndexes": 2,
    "averageQueryEfficiency": 0.65
  },
  "success": true
}

Analysis Approach:

  1. Schema Analysis - Detects foreign keys, unique constraints, and commonly queried column types
  2. Query Pattern Detection - Analyzes last 100 queries to find frequently filtered/joined columns
  3. Priority Scoring - Weights recommendations by query frequency and relationship importance

Priority Levels:

  • high - Critical for performance (foreign keys, frequently queried columns)
  • medium - Moderate impact (occasionally queried columns, sort columns)
  • low - Optional improvements (rarely queried columns)

See Also: Index Analyzer for detailed usage guide and best practices.

Column Endpoints

Add Column

Add a new column to a table.

POST /api/tables/:dbId/:tableName/columns/add
Content-Type: application/json

Parameters:

  • dbId (path) - Database UUID
  • tableName (path) - Table name

Body:

{
  "columnName": "phone",
  "columnType": "TEXT",
  "notNull": false,
  "defaultValue": null
}

Response:

{
  "result": {
    "message": "Column added successfully"
  },
  "success": true
}

Rename Column

Rename a column.

PATCH /api/tables/:dbId/:tableName/columns/:columnName/rename
Content-Type: application/json

Parameters:

  • dbId (path) - Database UUID
  • tableName (path) - Table name
  • columnName (path) - Current column name

Body:

{
  "newName": "full_name"
}

Response:

{
  "result": {
    "message": "Column renamed successfully"
  },
  "success": true
}

Modify Column

Modify column type or constraints.

PATCH /api/tables/:dbId/:tableName/columns/:columnName/modify
Content-Type: application/json

Parameters:

  • dbId (path) - Database UUID
  • tableName (path) - Table name
  • columnName (path) - Column name

Body:

{
  "newType": "REAL",
  "notNull": true,
  "defaultValue": "0.0"
}

Response:

{
  "result": {
    "message": "Column modified successfully"
  },
  "success": true
}

Drop Column

Remove a column from a table.

DELETE /api/tables/:dbId/:tableName/columns/:columnName

Parameters:

  • dbId (path) - Database UUID
  • tableName (path) - Table name
  • columnName (path) - Column name

Response:

{
  "result": {
    "message": "Column dropped successfully"
  },
  "success": true
}

Query Endpoints

Execute Query

Execute a SQL query.

POST /api/query/:dbId/execute
Content-Type: application/json

Parameters:

  • dbId (path) - Database UUID

Body:

{
  "query": "SELECT * FROM users WHERE id = 1;",
  "skipValidation": false
}

Response:

{
  "results": [
    {
      "id": 1,
      "name": "Alice",
      "email": "alice@example.com"
    }
  ],
  "meta": {
    "duration": 15,
    "rows_read": 1,
    "rows_written": 0,
    "changes": 0
  },
  "success": true
}

Execute Batch Queries

Execute multiple queries in a batch.

POST /api/query/:dbId/batch
Content-Type: application/json

Parameters:

  • dbId (path) - Database UUID

Body:

{
  "queries": [
    "INSERT INTO users (name, email) VALUES ('Alice', 'alice@example.com');",
    "INSERT INTO users (name, email) VALUES ('Bob', 'bob@example.com');"
  ]
}

Response:

{
  "results": [
    {
      "success": true,
      "meta": {
        "changes": 1,
        "last_row_id": 1
      }
    },
    {
      "success": true,
      "meta": {
        "changes": 1,
        "last_row_id": 2
      }
    }
  ],
  "success": true
}

Get Query History

Get query execution history for a database.

GET /api/query/:dbId/history?limit=100

Parameters:

  • dbId (path) - Database UUID
  • limit (query) - Number of history entries (default: 100)

Response:

{
  "result": [
    {
      "id": 1,
      "database_id": "uuid-...",
      "query": "SELECT * FROM users;",
      "executed_at": "2024-11-03T10:30:00.000Z",
      "duration_ms": 15,
      "rows_affected": 10,
      "error": null,
      "user_email": "user@example.com"
    }
  ],
  "success": true
}

Saved Queries Endpoints

List Saved Queries

Get all saved queries for current user.

GET /api/saved-queries?dbId=:dbId

Parameters:

  • dbId (query, optional) - Filter by database UUID

Response:

{
  "result": [
    {
      "id": 1,
      "name": "Active Users",
      "description": "Users active in last 30 days",
      "database_id": "uuid-...",
      "query": "SELECT * FROM users WHERE last_login > date('now', '-30 days');",
      "created_at": "2024-11-01T00:00:00.000Z",
      "updated_at": "2024-11-01T00:00:00.000Z",
      "user_email": "user@example.com"
    }
  ],
  "success": true
}

Save Query

Save a query for reuse.

POST /api/saved-queries
Content-Type: application/json

Body:

{
  "name": "Active Users",
  "description": "Users active in last 30 days",
  "database_id": "uuid-...",
  "query": "SELECT * FROM users WHERE last_login > date('now', '-30 days');"
}

Response:

{
  "result": {
    "id": 1,
    "message": "Query saved successfully"
  },
  "success": true
}

Update Saved Query

Update an existing saved query.

PATCH /api/saved-queries/:queryId
Content-Type: application/json

Parameters:

  • queryId (path) - Saved query ID

Body:

{
  "name": "Active Users (Updated)",
  "description": "New description",
  "query": "SELECT * FROM users WHERE last_login > date('now', '-7 days');"
}

Response:

{
  "result": {
    "message": "Query updated successfully"
  },
  "success": true
}

Delete Saved Query

Delete a saved query.

DELETE /api/saved-queries/:queryId

Parameters:

  • queryId (path) - Saved query ID

Response:

{
  "result": {
    "message": "Query deleted successfully"
  },
  "success": true
}

Undo Endpoints

Get Undo History

Get undo/rollback history for a database.

GET /api/undo/:dbId/history

Parameters:

  • dbId (path) - Database UUID

Response:

{
  "success": true,
  "history": [
    {
      "id": 1,
      "database_id": "uuid-...",
      "operation_type": "DROP_TABLE",
      "target_table": "users",
      "target_column": null,
      "description": "Dropped table 'users' with 152 rows",
      "snapshot_data": "{...}",
      "executed_at": "2025-11-04T14:30:00.000Z",
      "user_email": "user@example.com"
    },
    {
      "id": 2,
      "database_id": "uuid-...",
      "operation_type": "DROP_COLUMN",
      "target_table": "posts",
      "target_column": "author",
      "description": "Dropped column 'author' from table 'posts'",
      "snapshot_data": "{...}",
      "executed_at": "2025-11-04T13:15:00.000Z",
      "user_email": "user@example.com"
    },
    {
      "id": 3,
      "database_id": "uuid-...",
      "operation_type": "DELETE_ROW",
      "target_table": "comments",
      "target_column": null,
      "description": "Deleted 5 rows from 'comments'",
      "snapshot_data": "{...}",
      "executed_at": "2025-11-04T12:00:00.000Z",
      "user_email": "user@example.com"
    }
  ]
}

Operation Types:

  • DROP_TABLE - Table deletion with full snapshot
  • DROP_COLUMN - Column deletion with data snapshot
  • DELETE_ROW - Row deletion with data snapshot

Limit: Returns last 10 operations per database.

Restore Undo Operation

Restore a specific undo operation.

POST /api/undo/:dbId/restore/:undoId

Parameters:

  • dbId (path) - Database UUID
  • undoId (path) - Undo history entry ID

Response (Success):

{
  "success": true,
  "message": "Operation restored successfully",
  "details": {
    "operation_type": "DROP_TABLE",
    "target_table": "users",
    "rows_restored": 152
  }
}

Response (Conflict):

{
  "success": false,
  "error": "Restore operation failed",
  "message": "Table 'users' already exists. Cannot restore."
}

Response (Not Found):

{
  "success": false,
  "error": "Undo entry not found",
  "message": "The requested undo operation does not exist."
}

Restoration Behavior:

DROP_TABLE:

  • Recreates table with original schema
  • Restores all indexes
  • Restores all data rows
  • Fails if table name already exists

DROP_COLUMN:

  • Adds column back to table
  • Restores column data for all rows
  • Fails if column name already exists

DELETE_ROW:

  • Re-inserts deleted rows
  • Uses original WHERE clause for reference
  • May fail if primary key conflicts exist

Clear Undo History

Clear all undo history for a database.

DELETE /api/undo/:dbId/clear

Parameters:

  • dbId (path) - Database UUID

Response:

{
  "success": true,
  "cleared": 10
}

Notes:

  • Permanently deletes all undo snapshots for the database
  • Cannot be undone
  • Frees up space in metadata database

Delete Rows with Undo

Delete rows from a table with automatic snapshot capture.

POST /api/tables/:dbId/:tableName/rows/delete
Content-Type: application/json

Parameters:

  • dbId (path) - Database UUID
  • tableName (path) - Table name

Body:

{
  "whereClause": "id = 42"
}

Response:

{
  "result": {
    "message": "Rows deleted successfully",
    "changes": 1,
    "undoId": 123
  },
  "success": true
}

Process:

  1. Captures snapshot of rows matching WHERE clause
  2. Saves snapshot to undo history
  3. Executes DELETE operation
  4. Returns undo ID for reference

See Also: Undo Rollback for complete documentation.

Job History Endpoints

List Jobs

Get a paginated list of bulk operation jobs.

GET /api/jobs

Query Parameters:

Parameter Type Description
status string Filter by status (queued, running, completed, failed, cancelled)
operation string Filter by operation type (database_export, database_import, etc.)
databaseId string Filter by database UUID
startDate string Filter by start date (ISO 8601)
endDate string Filter by end date (ISO 8601)
jobId string Search by job ID
minErrors number Minimum error count
sortBy string Sort field (started_at, completed_at, total_items, error_count)
sortOrder string Sort direction (asc, desc)
limit number Results per page (default: 20)
offset number Pagination offset

Response:

{
  "success": true,
  "result": {
    "jobs": [
      {
        "job_id": "database_export-abc123-xyz789",
        "database_id": "uuid-...",
        "operation_type": "database_export",
        "status": "completed",
        "total_items": 4,
        "processed_items": 3,
        "error_count": 1,
        "percentage": 100,
        "started_at": "2025-11-26T15:30:00.000Z",
        "completed_at": "2025-11-26T15:30:15.000Z",
        "user_email": "user@example.com",
        "metadata": null
      }
    ],
    "total": 25,
    "limit": 20,
    "offset": 0
  }
}

Get Job Details

Get details for a specific job.

GET /api/jobs/:jobId

Parameters:

  • jobId (path) - Job ID

Response:

{
  "success": true,
  "result": {
    "job_id": "database_export-abc123-xyz789",
    "database_id": "uuid-...",
    "operation_type": "database_export",
    "status": "completed",
    "total_items": 4,
    "processed_items": 3,
    "error_count": 1,
    "percentage": 100,
    "started_at": "2025-11-26T15:30:00.000Z",
    "completed_at": "2025-11-26T15:30:15.000Z",
    "user_email": "user@example.com",
    "metadata": null
  }
}

Get Job Events

Get the event timeline for a specific job.

GET /api/jobs/:jobId/events

Parameters:

  • jobId (path) - Job ID

Response:

{
  "success": true,
  "result": {
    "events": [
      {
        "id": 1,
        "job_id": "database_export-abc123-xyz789",
        "event_type": "started",
        "user_email": "user@example.com",
        "timestamp": "2025-11-26T15:30:00.000Z",
        "details": { "message": "Processing 4 databases" }
      },
      {
        "id": 2,
        "job_id": "database_export-abc123-xyz789",
        "event_type": "progress_25",
        "user_email": "user@example.com",
        "timestamp": "2025-11-26T15:30:05.000Z",
        "details": { "processed": 1, "database": "tt-1" }
      },
      {
        "id": 3,
        "job_id": "database_export-abc123-xyz789",
        "event_type": "failed",
        "user_email": "user@example.com",
        "timestamp": "2025-11-26T15:30:10.000Z",
        "details": { "error": "FTS5 tables not supported", "database": "test-new" }
      },
      {
        "id": 4,
        "job_id": "database_export-abc123-xyz789",
        "event_type": "completed",
        "user_email": "user@example.com",
        "timestamp": "2025-11-26T15:30:15.000Z",
        "details": { "processed": 3, "errors": 1 }
      }
    ]
  }
}

Event Types:

Type Description
started Job began processing
progress_25 25% complete milestone
progress_50 50% complete milestone
progress_75 75% complete milestone
completed Job finished successfully
failed Job encountered an error
cancelled Job was cancelled

See Also: Job History for complete documentation.

Time Travel Endpoints

Get Current Bookmark

Get the current bookmark (point-in-time state) for a database.

GET /api/time-travel/:dbId/bookmark

Parameters:

  • dbId (path) - Database UUID

Response:

{
  "success": true,
  "result": {
    "bookmark": "00000085-0000024c-00004c6d-8e611177d83f7fb2f0396d0847be2cc62eaa94debb2f65eae0a58c44c4cf6a74",
    "capturedAt": "2025-11-27T10:30:00.000Z",
    "databaseId": "uuid-...",
    "databaseName": "my-database",
    "restoreCommand": "wrangler d1 time-travel restore my-database --bookmark=00000085-..."
  }
}

Note: The bookmark is fetched from the D1 Export API (at_bookmark field).

Get Checkpoint History

Get stored checkpoint history for a database.

GET /api/time-travel/:dbId/history?limit=50

Parameters:

  • dbId (path) - Database UUID
  • limit (query, optional) - Maximum entries to return (default: 50)

Response:

{
  "success": true,
  "result": [
    {
      "id": 1,
      "database_id": "uuid-...",
      "database_name": "my-database",
      "bookmark": "00000085-0000024c-...",
      "operation_type": "pre_drop_table",
      "description": "Before dropping table: users",
      "captured_at": "2025-11-27T10:00:00.000Z",
      "user_email": "user@example.com",
      "restoreCommand": "wrangler d1 time-travel restore my-database --bookmark=..."
    }
  ]
}

Operation Types:

Type Description
manual User-initiated checkpoint
pre_drop_table Before DROP TABLE
pre_drop_column Before DROP COLUMN
pre_delete_rows Before DELETE rows

Capture Manual Checkpoint

Create a manual checkpoint for a database.

POST /api/time-travel/:dbId/capture
Content-Type: application/json

Parameters:

  • dbId (path) - Database UUID

Body:

{
  "description": "Before schema migration"
}

Response:

{
  "success": true,
  "result": {
    "bookmark": "00000085-0000024c-...",
    "capturedAt": "2025-11-27T10:30:00.000Z",
    "databaseId": "uuid-...",
    "databaseName": "my-database",
    "restoreCommand": "wrangler d1 time-travel restore my-database --bookmark=..."
  }
}

Delete Checkpoint

Delete a checkpoint from history.

DELETE /api/time-travel/:dbId/history/:id

Parameters:

  • dbId (path) - Database UUID
  • id (path) - Checkpoint history entry ID

Response:

{
  "success": true,
  "deleted": true
}

Note: This only removes the checkpoint record, not the actual database state. Time Travel recovery remains available until the retention period expires.

See Also: Time Travel for complete documentation.

Error Codes

Status Code Description
200 Success
400 Bad Request - Invalid parameters
401 Unauthorized - Authentication required
403 Forbidden - Insufficient permissions
404 Not Found - Resource doesn't exist
500 Internal Server Error

Rate Limiting

Cloudflare Workers have built-in rate limiting:

  • Free Plan: 100,000 requests/day
  • Paid Plan: Unlimited requests

No custom rate limiting implemented in D1 Manager.

CORS

CORS is configured to allow requests from:

  • Same origin (production)
  • http://localhost:5173 (local development)
  • http://localhost:8787 (local Worker)

Custom origins can be added in worker/utils/cors.ts.

Next Steps


Need Help? See Troubleshooting or open an issue.

Clone this wiki locally