Skip to content

Commit

Permalink
Merge pull request #2960 from mephmanx/adding_d1_support
Browse files Browse the repository at this point in the history
adding_d1_support
  • Loading branch information
jacobbednarz authored Dec 27, 2023
2 parents 32014eb + d8c476d commit f361f1b
Show file tree
Hide file tree
Showing 5 changed files with 56 additions and 2 deletions.
3 changes: 3 additions & 0 deletions .changelog/2960.txt
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
```release-note:enhancement
resource/cloudflare_worker_script: adds D1 binding support
```
6 changes: 6 additions & 0 deletions internal/framework/service/d1/resource_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -34,6 +34,12 @@ func init() {
}

for _, database := range databases {
// hardcoded D1 identifier until we can solve the cyclic import
// issues and automatically create this resource.
if database.UUID == "ce8b95dc-b376-4ff8-9b9e-1801ed6d745d" {
continue
}

err := client.DeleteD1Database(ctx, cloudflare.AccountIdentifier(accountID), database.UUID)
if err != nil {
return fmt.Errorf("failed to delete D1 database %q: %w", database.Name, err)
Expand Down
18 changes: 18 additions & 0 deletions internal/sdkv2provider/resource_cloudflare_workers_script.go
Original file line number Diff line number Diff line change
Expand Up @@ -129,6 +129,14 @@ func parseWorkerBindings(d *schema.ResourceData, bindings ScriptBindings) {
Queue: data["queue"].(string),
}
}

for _, rawData := range d.Get("d1_database_binding").(*schema.Set).List() {
data := rawData.(map[string]interface{})

bindings[data["name"].(string)] = cloudflare.WorkerD1DatabaseBinding{
DatabaseID: data["database_id"].(string),
}
}
}

func getPlacement(d *schema.ResourceData) cloudflare.Placement {
Expand Down Expand Up @@ -239,6 +247,7 @@ func resourceCloudflareWorkerScriptRead(ctx context.Context, d *schema.ResourceD
r2BucketBindings := &schema.Set{F: schema.HashResource(r2BucketBindingResource)}
analyticsEngineBindings := &schema.Set{F: schema.HashResource(analyticsEngineBindingResource)}
queueBindings := &schema.Set{F: schema.HashResource(queueBindingResource)}
d1DatabaseBindings := &schema.Set{F: schema.HashResource(d1BindingResource)}

for name, binding := range bindings {
switch v := binding.(type) {
Expand Down Expand Up @@ -292,6 +301,11 @@ func resourceCloudflareWorkerScriptRead(ctx context.Context, d *schema.ResourceD
"binding": name,
"queue": v.Queue,
})
case cloudflare.WorkerD1DatabaseBinding:
d1DatabaseBindings.Add(map[string]interface{}{
"name": name,
"database_id": v.DatabaseID,
})
}
}

Expand Down Expand Up @@ -331,6 +345,10 @@ func resourceCloudflareWorkerScriptRead(ctx context.Context, d *schema.ResourceD
return diag.FromErr(fmt.Errorf("cannot set queue bindings (%s): %w", d.Id(), err))
}

if err := d.Set("d1_database_binding", d1DatabaseBindings); err != nil {
return diag.FromErr(fmt.Errorf("cannot set d1 database bindings (%s): %w", d.Id(), err))
}

d.SetId(scriptData.ID)

return nil
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -22,6 +22,7 @@ const (
moduleContent = `export default { fetch() { return new Response('Hello world'); }, };`
encodedWasm = "AGFzbQEAAAAGgYCAgAAA" // wat source: `(module)`, so literally just an empty wasm module
compatibilityDate = "2023-03-19"
d1DatabaseID = "ce8b95dc-b376-4ff8-9b9e-1801ed6d745d"
)

var (
Expand Down Expand Up @@ -94,7 +95,7 @@ func TestAccCloudflareWorkerScript_ModuleUpload(t *testing.T) {
{
Config: testAccCheckCloudflareWorkerScriptUploadModule(rnd, accountID, r2AccesKeyID, r2AccesKeySecret),
Check: resource.ComposeTestCheckFunc(
testAccCheckCloudflareWorkerScriptExists(name, &script, nil),
testAccCheckCloudflareWorkerScriptExists(name, &script, []string{"MY_DATABASE"}),
resource.TestCheckResourceAttr(name, "name", rnd),
resource.TestCheckResourceAttr(name, "content", moduleContent),
resource.TestCheckResourceAttr(name, "compatibility_date", compatibilityDate),
Expand Down Expand Up @@ -139,6 +140,7 @@ func testAccCheckCloudflareWorkerScriptCreateBucket(t *testing.T, rnd string) {
cfg, err := config.LoadDefaultConfig(context.TODO(),
config.WithEndpointResolverWithOptions(r2Resolver),
config.WithCredentialsProvider(credentials.NewStaticCredentialsProvider(accessKeyId, accessKeySecret, "")),
config.WithDefaultRegion("auto"),
)
if err != nil {
t.Error(err)
Expand Down Expand Up @@ -272,8 +274,13 @@ resource "cloudflare_worker_script" "%[1]s" {
mode = "smart"
}
d1_database_binding {
name = "MY_DATABASE"
database_id = "%[8]s"
}
depends_on = [cloudflare_logpush_job.%[1]s]
}`, rnd, moduleContent, accountID, compatibilityDate, strings.Join(compatibilityFlags, `","`), r2AccessKeyID, r2AccessKeySecret)
}`, rnd, moduleContent, accountID, compatibilityDate, strings.Join(compatibilityFlags, `","`), r2AccessKeyID, r2AccessKeySecret, d1DatabaseID)
}

func testAccCheckCloudflareWorkerScriptExists(n string, script *cloudflare.WorkerScript, bindings []string) resource.TestCheckFunc {
Expand Down
20 changes: 20 additions & 0 deletions internal/sdkv2provider/schema_cloudflare_workers_script.go
Original file line number Diff line number Diff line change
Expand Up @@ -134,6 +134,21 @@ var queueBindingResource = &schema.Resource{
},
}

var d1BindingResource = &schema.Resource{
Schema: map[string]*schema.Schema{
"name": {
Type: schema.TypeString,
Required: true,
Description: "The global variable for the binding in your Worker code.",
},
"database_id": {
Type: schema.TypeString,
Required: true,
Description: "Database ID of D1 database to use.",
},
},
}

var placementResource = &schema.Resource{
Schema: map[string]*schema.Schema{
"mode": {
Expand Down Expand Up @@ -232,5 +247,10 @@ func resourceCloudflareWorkerScriptSchema() map[string]*schema.Schema {
Optional: true,
Elem: queueBindingResource,
},
"d1_database_binding": {
Type: schema.TypeSet,
Optional: true,
Elem: d1BindingResource,
},
}
}

0 comments on commit f361f1b

Please sign in to comment.