CloudflareD1.NET
1.0.1
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
<PackageReference Include="CloudflareD1.NET" Version="1.0.1" />
<PackageVersion Include="CloudflareD1.NET" Version="1.0.1" />
<PackageReference Include="CloudflareD1.NET" />
paket add CloudflareD1.NET --version 1.0.1
#r "nuget: CloudflareD1.NET, 1.0.1"
#:package CloudflareD1.NET@1.0.1
#addin nuget:?package=CloudflareD1.NET&version=1.0.1
#tool nuget:?package=CloudflareD1.NET&version=1.0.1
CloudflareD1.NET
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
API Token (Recommended)
- Go to Cloudflare Dashboard
- Create API Token with D1 Edit permissions
- 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.
- Fork the repository
- Create your feature branch (
git checkout -b feature/AmazingFeature) - Commit your changes (
git commit -m 'Add some AmazingFeature') - Push to the branch (
git push origin feature/AmazingFeature) - 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
- ๐ซ Open an issue on GitHub Issues
- ๐ฌ Start a discussion on GitHub Discussions
๐ Links
Made with โค๏ธ by the .NET and Cloudflare communities
| Product | Versions 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. |
-
.NETStandard 2.1
- Microsoft.Data.Sqlite (>= 9.0.10)
- Microsoft.Extensions.Configuration.Abstractions (>= 9.0.10)
- Microsoft.Extensions.Configuration.Binder (>= 9.0.10)
- Microsoft.Extensions.DependencyInjection.Abstractions (>= 9.0.10)
- Microsoft.Extensions.Http (>= 9.0.10)
- Microsoft.Extensions.Logging.Abstractions (>= 9.0.10)
- Microsoft.Extensions.Options (>= 9.0.10)
- Microsoft.Extensions.Options.ConfigurationExtensions (>= 9.0.10)
- System.Text.Json (>= 9.0.10)
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.