CloudflareD1.NET 1.0.1

There is a newer version of this package available.
See the version list below for details.
dotnet add package CloudflareD1.NET --version 1.0.1
                    
NuGet\Install-Package CloudflareD1.NET -Version 1.0.1
                    
This command is intended to be used within the Package Manager Console in Visual Studio, as it uses the NuGet module's version of Install-Package.
<PackageReference Include="CloudflareD1.NET" Version="1.0.1" />
                    
For projects that support PackageReference, copy this XML node into the project file to reference the package.
<PackageVersion Include="CloudflareD1.NET" Version="1.0.1" />
                    
Directory.Packages.props
<PackageReference Include="CloudflareD1.NET" />
                    
Project file
For projects that support Central Package Management (CPM), copy this XML node into the solution Directory.Packages.props file to version the package.
paket add CloudflareD1.NET --version 1.0.1
                    
#r "nuget: CloudflareD1.NET, 1.0.1"
                    
#r directive can be used in F# Interactive and Polyglot Notebooks. Copy this into the interactive tool or source code of the script to reference the package.
#:package CloudflareD1.NET@1.0.1
                    
#:package directive can be used in C# file-based apps starting in .NET 10 preview 4. Copy this into a .cs file before any lines of code to reference the package.
#addin nuget:?package=CloudflareD1.NET&version=1.0.1
                    
Install as a Cake Addin
#tool nuget:?package=CloudflareD1.NET&version=1.0.1
                    
Install as a Cake Tool

CloudflareD1.NET

NuGet License: MIT

A complete .NET adapter for Cloudflare D1 - the serverless SQL database running on Cloudflare's edge network. This library provides seamless integration with Cloudflare's D1 database, supporting both local SQLite development and remote D1 production deployments.

โœจ Features

  • ๐Ÿš€ Full D1 API Support - Complete implementation of Cloudflare D1 REST API
  • ๐Ÿ  Local Development Mode - Use local SQLite for development without any setup
  • ๐Ÿ”„ Seamless Switching - Easy toggle between local and remote modes
  • ๐Ÿ“ฆ Batch Operations - Execute multiple queries as a single transaction
  • โฑ๏ธ Time Travel Queries - Query historical data (D1 feature)
  • ๐Ÿ› ๏ธ Database Management - Create, list, and delete D1 databases programmatically
  • ๐Ÿ’‰ Dependency Injection - Full ASP.NET Core DI integration
  • ๐Ÿ” Flexible Authentication - Support for API Token and API Key authentication
  • ๐Ÿ“ Comprehensive Logging - Built-in logging with ILogger support
  • ๐ŸŽฏ Type-Safe - Strongly typed with full XML documentation
  • โšก Async/Await - Modern async patterns throughout
  • ๐Ÿงช Well Tested - Comprehensive test coverage

๐Ÿ“ฆ Installation

Install via NuGet Package Manager:

dotnet add package CloudflareD1.NET

Or via Package Manager Console:

Install-Package CloudflareD1.NET

๐Ÿš€ Quick Start

Local Development Mode (Default)

Perfect for development and testing without needing Cloudflare credentials:

using CloudflareD1.NET;
using CloudflareD1.NET.Configuration;
using Microsoft.Extensions.Options;
using Microsoft.Extensions.Logging;

// Configure for local SQLite mode
var options = Options.Create(new D1Options
{
    UseLocalMode = true,
    LocalDatabasePath = "myapp.db"
});

var logger = loggerFactory.CreateLogger<D1Client>();

// Create client
using var client = new D1Client(options, logger);

// Create table
await client.ExecuteAsync(@"
    CREATE TABLE users (
        id INTEGER PRIMARY KEY AUTOINCREMENT,
        name TEXT NOT NULL,
        email TEXT UNIQUE NOT NULL
    )
");

// Insert data
await client.ExecuteAsync(
    "INSERT INTO users (name, email) VALUES (@name, @email)",
    new { name = "John Doe", email = "john@example.com" }
);

// Query data
var result = await client.QueryAsync("SELECT * FROM users");
foreach (var row in result.Results)
{
    Console.WriteLine($"{row["name"]}: {row["email"]}");
}

Remote Cloudflare D1 Mode

For production with actual Cloudflare D1 databases:

var options = Options.Create(new D1Options
{
    UseLocalMode = false,
    AccountId = "your-cloudflare-account-id",
    DatabaseId = "your-d1-database-id",
    ApiToken = "your-cloudflare-api-token"
});

using var client = new D1Client(options, logger);

// Same API as local mode!
var result = await client.QueryAsync("SELECT * FROM users WHERE name = @name", 
    new { name = "John" });

๐Ÿ”ง ASP.NET Core Integration

With Configuration

In appsettings.json:

{
  "CloudflareD1": {
    "UseLocalMode": true,
    "LocalDatabasePath": "myapp.db"
  }
}

In Program.cs or Startup.cs:

using CloudflareD1.NET.Extensions;

// Add D1 services
builder.Services.AddCloudflareD1(builder.Configuration.GetSection("CloudflareD1"));

// Or configure directly
builder.Services.AddCloudflareD1(options =>
{
    options.UseLocalMode = true;
    options.LocalDatabasePath = "myapp.db";
});

Using in Controllers

using CloudflareD1.NET;
using Microsoft.AspNetCore.Mvc;

[ApiController]
[Route("api/[controller]")]
public class UsersController : ControllerBase
{
    private readonly ID1Client _d1Client;

    public UsersController(ID1Client d1Client)
    {
        _d1Client = d1Client;
    }

    [HttpGet]
    public async Task<IActionResult> GetUsers()
    {
        var result = await _d1Client.QueryAsync("SELECT * FROM users");
        return Ok(result.Results);
    }

    [HttpPost]
    public async Task<IActionResult> CreateUser([FromBody] User user)
    {
        var result = await _d1Client.ExecuteAsync(
            "INSERT INTO users (name, email) VALUES (@name, @email)",
            user
        );
        
        return CreatedAtAction(nameof(GetUsers), new { id = result.Meta?.LastRowId });
    }
}

๐Ÿ“š Advanced Usage

Batch Operations (Transactions)

Execute multiple statements as a single atomic transaction:

using CloudflareD1.NET.Models;

var statements = new List<D1Statement>
{
    new() { 
        Sql = "INSERT INTO users (name, email) VALUES (@name, @email)", 
        Params = new { name = "Alice", email = "alice@example.com" } 
    },
    new() { 
        Sql = "INSERT INTO orders (user_id, total) VALUES (@userId, @total)", 
        Params = new { userId = 1, total = 99.99 } 
    },
    new() { 
        Sql = "UPDATE stats SET user_count = user_count + 1" 
    }
};

var results = await client.BatchAsync(statements);
// All succeed or all fail together

Time Travel Queries (Cloudflare D1 Only)

Query your database at a specific point in time:

using CloudflareD1.NET;

var managementClient = (ID1ManagementClient)client;

// Query data as it was 24 hours ago
var timestamp = DateTime.UtcNow.AddDays(-1).ToString("o");
var historicalData = await managementClient.QueryAtTimestampAsync(
    "SELECT * FROM users",
    timestamp
);

Database Management

using CloudflareD1.NET;

var managementClient = (ID1ManagementClient)client;

// List all databases
var databases = await managementClient.ListDatabasesAsync();

// Create a new database
var newDb = await managementClient.CreateDatabaseAsync("my-new-database");

// Get database info
var dbInfo = await managementClient.GetDatabaseAsync("database-id");

// Delete a database
await managementClient.DeleteDatabaseAsync("database-id");

๐ŸŽฏ Configuration Options

Option Type Default Description
UseLocalMode bool true Use local SQLite instead of Cloudflare D1
LocalDatabasePath string "local.db" Path to local SQLite database file
AccountId string null Cloudflare Account ID (required for remote)
DatabaseId string null D1 Database ID (required for remote)
ApiToken string null Cloudflare API Token for authentication
ApiKey string null Cloudflare API Key (legacy auth)
Email string null Email for API Key authentication
ApiBaseUrl string https://api.cloudflare.com/client/v4 Cloudflare API base URL
TimeoutSeconds int 30 HTTP request timeout

๐Ÿ” Authentication

  1. Go to Cloudflare Dashboard
  2. Create API Token with D1 Edit permissions
  3. Use in configuration:
options.ApiToken = "your-api-token";

API Key (Legacy)

options.ApiKey = "your-api-key";
options.Email = "your-email@example.com";

๐Ÿ“– Documentation

Full documentation is available at https://your-docs-site.com (coming soon)

๐Ÿงช Testing

The library includes a comprehensive test suite. Run tests with:

dotnet test

๐Ÿค Contributing

Contributions are welcome! Please feel free to submit a Pull Request.

  1. Fork the repository
  2. Create your feature branch (git checkout -b feature/AmazingFeature)
  3. Commit your changes (git commit -m 'Add some AmazingFeature')
  4. Push to the branch (git push origin feature/AmazingFeature)
  5. Open a Pull Request

๐Ÿ“ License

This project is licensed under the MIT License - see the LICENSE file for details.

๐Ÿ™ Acknowledgments

  • Cloudflare for the amazing D1 database platform
  • The .NET community for excellent tooling and support

๐Ÿ“ฎ Support


Made with โค๏ธ by the .NET and Cloudflare communities

Product Compatible and additional computed target framework versions.
.NET net5.0 was computed.  net5.0-windows was computed.  net6.0 was computed.  net6.0-android was computed.  net6.0-ios was computed.  net6.0-maccatalyst was computed.  net6.0-macos was computed.  net6.0-tvos was computed.  net6.0-windows was computed.  net7.0 was computed.  net7.0-android was computed.  net7.0-ios was computed.  net7.0-maccatalyst was computed.  net7.0-macos was computed.  net7.0-tvos was computed.  net7.0-windows was computed.  net8.0 was computed.  net8.0-android was computed.  net8.0-browser was computed.  net8.0-ios was computed.  net8.0-maccatalyst was computed.  net8.0-macos was computed.  net8.0-tvos was computed.  net8.0-windows was computed.  net9.0 was computed.  net9.0-android was computed.  net9.0-browser was computed.  net9.0-ios was computed.  net9.0-maccatalyst was computed.  net9.0-macos was computed.  net9.0-tvos was computed.  net9.0-windows was computed.  net10.0 was computed.  net10.0-android was computed.  net10.0-browser was computed.  net10.0-ios was computed.  net10.0-maccatalyst was computed.  net10.0-macos was computed.  net10.0-tvos was computed.  net10.0-windows was computed. 
.NET Core netcoreapp3.0 was computed.  netcoreapp3.1 was computed. 
.NET Standard netstandard2.1 is compatible. 
MonoAndroid monoandroid was computed. 
MonoMac monomac was computed. 
MonoTouch monotouch was computed. 
Tizen tizen60 was computed. 
Xamarin.iOS xamarinios was computed. 
Xamarin.Mac xamarinmac was computed. 
Xamarin.TVOS xamarintvos was computed. 
Xamarin.WatchOS xamarinwatchos was computed. 
Compatible target framework(s)
Included target framework(s) (in package)
Learn more about Target Frameworks and .NET Standard.

NuGet packages (3)

Showing the top 3 NuGet packages that depend on CloudflareD1.NET:

Package Downloads
CloudflareD1.NET.Linq

LINQ query builder and object mapping extensions for CloudflareD1.NET. Provides CompiledQuery for 95% faster repeated query execution with automatic expression tree caching, IQueryable<T> with deferred execution, async streaming with IAsyncEnumerable<T> for memory-efficient result processing, Set Operations (Union, UnionAll, Intersect, Except), Distinct() for removing duplicates, Contains()/IN clause for collection filtering, Join operations (INNER JOIN, LEFT JOIN), Having clause for filtered aggregations, GroupBy with aggregations (Count, Sum, Average, Min, Max), type-safe query construction with expression trees, Select() projection with computed properties, entity mapping, and fluent API for building SQL queries using lambda expressions. All query methods support CancellationToken.

CloudflareD1.NET.CodeFirst

Code-First ORM for CloudflareD1.NET. Define your database schema using C# classes and attributes, with automatic migration generation. Includes DbContext pattern, entity relationships, and model-driven development similar to Entity Framework Core but optimized for Cloudflare D1 and SQLite.

CloudflareD1.NET.Migrations

Database migration support for CloudflareD1.NET. Provides schema versioning, migration tracking, and fluent API for defining database changes. Works with both local SQLite and remote Cloudflare D1 databases.

GitHub repositories

This package is not used by any popular GitHub repositories.

Version Downloads Last Updated
1.12.0 261 10/28/2025
1.11.3 169 10/28/2025
1.11.2 326 10/27/2025
1.11.1 203 10/27/2025
1.0.2 731 10/26/2025
1.0.2-beta 155 10/26/2025
1.0.1 125 10/25/2025