CloudflareD1.NET.Migrations 1.0.0

There is a newer version of this package available.
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
                    
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.Migrations" Version="1.0.0" />
                    
For projects that support PackageReference, copy this XML node into the project file to reference the package.
<PackageVersion Include="CloudflareD1.NET.Migrations" Version="1.0.0" />
                    
Directory.Packages.props
<PackageReference Include="CloudflareD1.NET.Migrations" />
                    
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.Migrations --version 1.0.0
                    
#r "nuget: CloudflareD1.NET.Migrations, 1.0.0"
                    
#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.Migrations@1.0.0
                    
#: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.Migrations&version=1.0.0
                    
Install as a Cake Addin
#tool nuget:?package=CloudflareD1.NET.Migrations&version=1.0.0
                    
Install as a Cake Tool

CloudflareD1.NET

NuGet NuGet - Linq 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.

๐Ÿ“ฆ 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 IEntityMapper for 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

  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

๏ฟฝ 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 __migrations table
  • โœ… CLI Tool - dotnet-d1 for 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.

  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 (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.

Version Downloads Last Updated
1.1.0 197 10/28/2025
1.0.1 260 10/27/2025
1.0.0 168 10/27/2025

v1.0.0: Initial release with migration support, fluent MigrationBuilder API, history tracking, and rollback capabilities.