CloudflareD1.NET.Migrations
1.0.0
See the version list below for details.
dotnet add package CloudflareD1.NET.Migrations --version 1.0.0
NuGet\Install-Package CloudflareD1.NET.Migrations -Version 1.0.0
<PackageReference Include="CloudflareD1.NET.Migrations" Version="1.0.0" />
<PackageVersion Include="CloudflareD1.NET.Migrations" Version="1.0.0" />
<PackageReference Include="CloudflareD1.NET.Migrations" />
paket add CloudflareD1.NET.Migrations --version 1.0.0
#r "nuget: CloudflareD1.NET.Migrations, 1.0.0"
#:package CloudflareD1.NET.Migrations@1.0.0
#addin nuget:?package=CloudflareD1.NET.Migrations&version=1.0.0
#tool nuget:?package=CloudflareD1.NET.Migrations&version=1.0.0
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.
๐ฆ Packages
| Package | Description | Install |
|---|---|---|
| CloudflareD1.NET | Core package with raw SQL support | dotnet add package CloudflareD1.NET |
| CloudflareD1.NET.Linq | LINQ queries and object mapping | dotnet add package CloudflareD1.NET.Linq |
| CloudflareD1.NET.Migrations | Database migrations and schema management | dotnet add package CloudflareD1.NET.Migrations |
| dotnet-d1 | CLI tool for managing migrations | dotnet tool install -g dotnet-d1 |
โจ Features
Core Package (CloudflareD1.NET)
- ๐ 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
LINQ Package (CloudflareD1.NET.Linq)
- โจ IQueryable<T> Support - Standard LINQ with deferred execution (v1.3.0+)
- ๐ Join Operations - INNER JOIN and LEFT JOIN support (v1.6.0)
- ๐ GroupBy & Having - Group results with aggregate filters (v1.5.0+)
- ๐ฏ Select() Projections - Project to DTOs with computed properties (v1.4.0)
- ๐ Distinct() - Remove duplicate rows (v1.7.0)
- ๐ Contains()/IN Clause - Collection filtering support (v1.7.0)
- ๐ Set Operations - Union, UnionAll, Intersect, Except (NEW in v1.8.0-beta)
- ๐ฏ Type-Safe Queries -
QueryAsync<T>()with automatic entity mapping - ๐บ๏ธ Automatic Mapping - Snake_case columns to PascalCase properties
- ๐ช Strongly Typed - Compile-time type checking for queries
- โก High Performance - Reflection caching for minimal overhead
- ๐จ Custom Mappers - Implement
IEntityMapperfor custom logic - ๐ LINQ Methods - QueryFirstOrDefaultAsync, QuerySingleAsync, etc.
Migrations Package (CloudflareD1.NET.Migrations)
- ๐ Version Control - Track database schema changes over time
- ๐ Fluent API - Intuitive builder for creating tables and indexes
- โฌ๏ธ Up/Down Migrations - Forward and rollback support
- ๐ Migration History - Automatic tracking of applied migrations
- ๐ ๏ธ CLI Tool - dotnet-d1 command-line tool for migration management
- ๐ฏ Type-Safe - Strongly typed schema definitions
- ๐ง Schema Operations - CREATE/DROP tables, ADD/DROP columns, indexes
- ๐ Constraints - Primary keys, foreign keys, unique, check constraints
- ๐ฆ Programmatic API - Apply migrations from code
- โ Well Tested - Comprehensive unit test coverage
๐ฆ Installation
Core Package
dotnet add package CloudflareD1.NET
With LINQ Support
dotnet add package CloudflareD1.NET.Linq
With Migrations Support
# Install the migrations package
dotnet add package CloudflareD1.NET.Migrations
# Install the CLI tool globally
dotnet tool install -g dotnet-d1
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
๏ฟฝ Database Migrations
CloudflareD1.NET.Migrations provides a complete database migration system for managing schema changes over time.
Quick Start with Migrations
# Install the CLI tool
dotnet tool install -g dotnet-d1
# Create a new migration
dotnet d1 migrations add CreateUsersTable
# Apply migrations
dotnet d1 database update
# Rollback last migration
dotnet d1 database rollback
Creating Migrations
Migrations use a fluent API for defining schema changes:
using CloudflareD1.NET.Migrations;
public class CreateUsersTable_20241027120000 : Migration
{
public override string Id => "20241027120000";
public override string Name => "CreateUsersTable";
public override void Up(MigrationBuilder builder)
{
builder.CreateTable("users", t =>
{
t.Integer("id").PrimaryKey().AutoIncrement();
t.Text("name").NotNull();
t.Text("email").NotNull().Unique();
t.Integer("age");
t.Text("created_at").Default("CURRENT_TIMESTAMP");
});
builder.CreateIndex("idx_users_email", "users", new[] { "email" }, unique: true);
}
public override void Down(MigrationBuilder builder)
{
builder.DropIndex("idx_users_email");
builder.DropTable("users");
}
}
Programmatic Usage
using CloudflareD1.NET.Migrations;
// Get migrations from assembly
var migrations = Assembly.GetExecutingAssembly()
.GetTypes()
.Where(t => t.IsSubclassOf(typeof(Migration)) && !t.IsAbstract)
.Select(t => (Migration)Activator.CreateInstance(t)!)
.ToList();
// Create migration runner
var runner = new MigrationRunner(client, migrations);
// Apply all pending migrations
var applied = await runner.MigrateAsync();
// Rollback last migration
var rolledBack = await runner.RollbackAsync();
Features
- โ Fluent API - Intuitive builder for schema changes
- โ Up/Down Migrations - Full rollback support
- โ
Migration History - Automatic tracking in
__migrationstable - โ
CLI Tool -
dotnet-d1for managing migrations - โ Type-Safe - Strongly typed schema definitions
- โ Schema Operations - CREATE/DROP tables, ADD/DROP columns, indexes
- โ Constraints - Primary keys, foreign keys, unique, check constraints
For complete documentation, see the Migrations Guide.
๏ฟฝ๐ฎ Future Enhancements
The following features are planned for future releases, pending Cloudflare D1 REST API support:
Transactions (Pending Cloudflare API)
- ITransaction Interface - Explicit transaction control with Begin/Commit/Rollback
- Atomic Operations - Multiple operations within a single transaction
- Auto-rollback - Automatic rollback on dispose if not committed
Note: Cloudflare D1 currently only supports transactions in the Workers environment. Once transaction support is added to the REST API, we will implement these features.
Batch Operations (Pending Cloudflare API)
- BatchInsertAsync - Bulk insert multiple entities efficiently
- BatchUpdateAsync - Bulk update with automatic property mapping
- BatchDeleteAsync - Bulk delete operations
- UpsertAsync - Insert or update based on existence
Note: While basic batch execution is supported via BatchAsync(), advanced batch operations with automatic entity mapping require transaction support from Cloudflare's REST API.
๐ค 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
- CloudflareD1.NET (>= 1.11.1)
NuGet packages (1)
Showing the top 1 NuGet packages that depend on CloudflareD1.NET.Migrations:
| Package | Downloads |
|---|---|
|
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. |
GitHub repositories
This package is not used by any popular GitHub repositories.
v1.0.0: Initial release with migration support, fluent MigrationBuilder API, history tracking, and rollback capabilities.