Skip to content

Commit 87ed74f

Browse files
committed
Use new D1 API
1 parent 67bb4dd commit 87ed74f

File tree

10 files changed

+70
-58
lines changed

10 files changed

+70
-58
lines changed

packages/wrangler/src/__tests__/provision.test.ts

Lines changed: 17 additions & 15 deletions
Original file line numberDiff line numberDiff line change
@@ -481,6 +481,7 @@ describe("--x-provision", () => {
481481
);
482482
})
483483
);
484+
mockGetD1Database("prefilled-d1-name", {}, true);
484485

485486
// no name prompt
486487
mockCreateD1Database({
@@ -597,6 +598,7 @@ describe("--x-provision", () => {
597598
);
598599
})
599600
);
601+
mockGetD1Database("new-d1-name", {}, true);
600602

601603
mockGetD1Database("old-d1-id", { name: "old-d1-name" });
602604

@@ -784,18 +786,10 @@ describe("--x-provision", () => {
784786
});
785787
mockGetSettings();
786788

787-
msw.use(
788-
http.get("*/accounts/:accountId/d1/database", async () => {
789-
return HttpResponse.json(
790-
createFetchResult([
791-
{
792-
name: "existing-db-name",
793-
uuid: "existing-d1-id",
794-
},
795-
])
796-
);
797-
})
798-
);
789+
mockGetD1Database("existing-db-name", {
790+
name: "existing-db-name",
791+
uuid: "existing-d1-id",
792+
});
799793

800794
mockUploadWorkerRequest({
801795
expectedBindings: [
@@ -1030,14 +1024,22 @@ function mockGetR2Bucket(bucketName: string, missing: boolean = false) {
10301024
}
10311025

10321026
function mockGetD1Database(
1033-
databaseId: string,
1034-
databaseInfo: Partial<DatabaseInfo>
1027+
databaseIdOrName: string,
1028+
databaseInfo: Partial<DatabaseInfo>,
1029+
missing: boolean = false
10351030
) {
10361031
msw.use(
10371032
http.get(
10381033
`*/accounts/:accountId/d1/database/:database_id`,
10391034
({ params }) => {
1040-
expect(params.database_id).toEqual(databaseId);
1035+
expect(params.database_id).toEqual(databaseIdOrName);
1036+
if (missing) {
1037+
return HttpResponse.json(
1038+
createFetchResult(null, false, [
1039+
{ code: 7404, message: "database not found" },
1040+
])
1041+
);
1042+
}
10411043
return HttpResponse.json(createFetchResult(databaseInfo));
10421044
},
10431045
{ once: true }

packages/wrangler/src/d1/info.ts

Lines changed: 5 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -4,7 +4,10 @@ import { withConfig } from "../config";
44
import { logger } from "../logger";
55
import { requireAuth } from "../user";
66
import { printWranglerBanner } from "../wrangler-banner";
7-
import { getDatabaseByNameOrBinding, getDatabaseInfoFromId } from "./utils";
7+
import {
8+
getDatabaseByNameOrBinding,
9+
getDatabaseInfoFromIdOrName,
10+
} from "./utils";
811
import type {
912
CommonYargsArgv,
1013
StrictYargsOptionsToInterface,
@@ -35,7 +38,7 @@ export const Handler = withConfig<HandlerOptions>(
3538
name
3639
);
3740

38-
const result = await getDatabaseInfoFromId(accountId, db.uuid);
41+
const result = await getDatabaseInfoFromIdOrName(accountId, db.uuid);
3942

4043
const output: Record<string, string | number> = { ...result };
4144
if (output["file_size"]) {

packages/wrangler/src/d1/insights.ts

Lines changed: 5 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -3,7 +3,10 @@ import { withConfig } from "../config";
33
import { logger } from "../logger";
44
import { requireAuth } from "../user";
55
import { printWranglerBanner } from "../wrangler-banner";
6-
import { getDatabaseByNameOrBinding, getDatabaseInfoFromId } from "./utils";
6+
import {
7+
getDatabaseByNameOrBinding,
8+
getDatabaseInfoFromIdOrName,
9+
} from "./utils";
710
import type {
811
CommonYargsArgv,
912
StrictYargsOptionsToInterface,
@@ -114,7 +117,7 @@ export const Handler = withConfig<HandlerOptions>(
114117
name
115118
);
116119

117-
const result = await getDatabaseInfoFromId(accountId, db.uuid);
120+
const result = await getDatabaseInfoFromIdOrName(accountId, db.uuid);
118121

119122
const output: Record<string, string | number>[] = [];
120123

packages/wrangler/src/d1/migrations/apply.ts

Lines changed: 8 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -11,7 +11,10 @@ import { printWranglerBanner } from "../../wrangler-banner";
1111
import { createBackup } from "../backups";
1212
import { DEFAULT_MIGRATION_PATH, DEFAULT_MIGRATION_TABLE } from "../constants";
1313
import { executeSql } from "../execute";
14-
import { getDatabaseInfoFromConfig, getDatabaseInfoFromId } from "../utils";
14+
import {
15+
getDatabaseInfoFromConfig,
16+
getDatabaseInfoFromIdOrName,
17+
} from "../utils";
1518
import {
1619
getMigrationsPath,
1720
getUnappliedMigrations,
@@ -130,7 +133,10 @@ Your database may not be available to serve requests during the migration, conti
130133
"In non-local mode `databaseInfo` should be defined."
131134
);
132135
const accountId = await requireAuth(config);
133-
const dbInfo = await getDatabaseInfoFromId(accountId, databaseInfo?.uuid);
136+
const dbInfo = await getDatabaseInfoFromIdOrName(
137+
accountId,
138+
databaseInfo?.uuid
139+
);
134140
if (dbInfo.version === "alpha") {
135141
logger.log("🕒 Creating backup...");
136142
await createBackup(accountId, databaseInfo.uuid);

packages/wrangler/src/d1/timeTravel/utils.ts

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,6 @@
11
import { fetchResult } from "../../cfetch";
22
import { UserError } from "../../errors";
3-
import { getDatabaseInfoFromId } from "../utils";
3+
import { getDatabaseInfoFromIdOrName } from "../utils";
44
import type { BookmarkResponse } from "./types";
55

66
/**
@@ -36,7 +36,7 @@ export const throwIfDatabaseIsAlpha = async (
3636
accountId: string,
3737
databaseId: string
3838
): Promise<void> => {
39-
const dbInfo = await getDatabaseInfoFromId(accountId, databaseId);
39+
const dbInfo = await getDatabaseInfoFromIdOrName(accountId, databaseId);
4040
if (dbInfo.version === "alpha") {
4141
throw new UserError(
4242
"Time travel is not available for alpha D1 databases. You will need to migrate to a new database for access to this feature."

packages/wrangler/src/d1/utils.ts

Lines changed: 4 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -46,20 +46,20 @@ export const getDatabaseByNameOrBinding = async (
4646
return dbFromConfig;
4747
}
4848

49-
const allDBs = await listDatabases(accountId, true);
49+
const allDBs = await listDatabases(accountId);
5050
const matchingDB = allDBs.find((db) => db.name === name);
5151
if (!matchingDB) {
5252
throw new UserError(`Couldn't find DB with name '${name}'`);
5353
}
5454
return matchingDB;
5555
};
5656

57-
export const getDatabaseInfoFromId = async (
57+
export const getDatabaseInfoFromIdOrName = async (
5858
accountId: string,
59-
databaseId: string
59+
databaseIdOrName: string
6060
): Promise<DatabaseInfo> => {
6161
return await fetchResult<DatabaseInfo>(
62-
`/accounts/${accountId}/d1/database/${databaseId}`,
62+
`/accounts/${accountId}/d1/database/${databaseIdOrName}`,
6363
{
6464
headers: {
6565
"Content-Type": "application/json",

packages/wrangler/src/deploy/deploy.ts

Lines changed: 9 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -800,15 +800,15 @@ See https://developers.cloudflare.com/workers/platform/compatibility-dates for m
800800
} else {
801801
assert(accountId, "Missing accountId");
802802

803-
getFlag("RESOURCES_PROVISION")
804-
? await provisionBindings(
805-
bindings,
806-
accountId,
807-
scriptName,
808-
props.experimentalAutoCreate,
809-
props.config
810-
)
811-
: null;
803+
if (getFlag("RESOURCES_PROVISION")) {
804+
await provisionBindings(
805+
bindings,
806+
accountId,
807+
scriptName,
808+
props.experimentalAutoCreate,
809+
props.config
810+
);
811+
}
812812
await ensureQueuesExistByConfig(config);
813813
let bindingsPrinted = false;
814814

packages/wrangler/src/deployment-bundle/bindings.ts

Lines changed: 8 additions & 11 deletions
Original file line numberDiff line numberDiff line change
@@ -2,7 +2,10 @@ import assert from "node:assert";
22
import { fetchResult } from "../cfetch";
33
import { createD1Database } from "../d1/create";
44
import { listDatabases } from "../d1/list";
5-
import { getDatabaseByNameOrBinding, getDatabaseInfoFromId } from "../d1/utils";
5+
import {
6+
getDatabaseByNameOrBinding,
7+
getDatabaseInfoFromIdOrName,
8+
} from "../d1/utils";
69
import { prompt, select } from "../dialogs";
710
import { UserError } from "../errors";
811
import { createKVNamespace, listKVNamespaces } from "../kv/helpers";
@@ -251,7 +254,7 @@ class D1Handler extends ProvisionResourceHandler<"d1", CfD1Database> {
251254

252255
// ...and the user HAS specified a name in their config, so we need to check if the database_name they provided
253256
// matches the database_name of the existing binding (which isn't present in settings, so we'll need to make an API call to check)
254-
const dbFromId = await getDatabaseInfoFromId(
257+
const dbFromId = await getDatabaseInfoFromIdOrName(
255258
this.accountId,
256259
maybeInherited.id
257260
);
@@ -269,21 +272,15 @@ class D1Handler extends ProvisionResourceHandler<"d1", CfD1Database> {
269272
return false;
270273
}
271274
try {
272-
// TODO: Use https://jira.cfdata.org/browse/CFSQL-1180 once ready
273-
const db = await getDatabaseByNameOrBinding(
274-
{ d1_databases: [] } as unknown as Config,
275+
const db = await getDatabaseInfoFromIdOrName(
275276
this.accountId,
276277
this.binding.database_name
277278
);
279+
278280
// This database_name exists! We don't need to provision it
279281
return db.uuid;
280282
} catch (e) {
281-
if (
282-
!(
283-
e instanceof Error &&
284-
e.message.startsWith("Couldn't find DB with name")
285-
)
286-
) {
283+
if (!(e instanceof APIError && e.code === 7404)) {
287284
// this is an error that is not "database not found", so we do want to throw
288285
throw e;
289286
}

packages/wrangler/src/init.ts

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -9,7 +9,7 @@ import { assertNever } from "./api/startDevWorker/utils";
99
import { fetchResult } from "./cfetch";
1010
import { fetchWorker } from "./cfetch/internal";
1111
import { readConfig } from "./config";
12-
import { getDatabaseInfoFromId } from "./d1/utils";
12+
import { getDatabaseInfoFromIdOrName } from "./d1/utils";
1313
import { confirm, select } from "./dialogs";
1414
import { getC3CommandFromEnv } from "./environment-variables/misc-variables";
1515
import { CommandLineArgsError, FatalError, UserError } from "./errors";
@@ -993,7 +993,7 @@ export async function mapBindings(
993993
bindings
994994
.filter((binding) => binding.type === "d1")
995995
.map(async (binding) => {
996-
const dbInfo = await getDatabaseInfoFromId(accountId, binding.id);
996+
const dbInfo = await getDatabaseInfoFromIdOrName(accountId, binding.id);
997997
d1BindingsWithInfo[binding.id] = dbInfo;
998998
})
999999
);

packages/wrangler/src/versions/upload.ts

Lines changed: 10 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -749,15 +749,16 @@ See https://developers.cloudflare.com/workers/platform/compatibility-dates for m
749749
printBindings({ ...bindings, vars: maskedVars });
750750
} else {
751751
assert(accountId, "Missing accountId");
752-
getFlag("RESOURCES_PROVISION")
753-
? await provisionBindings(
754-
bindings,
755-
accountId,
756-
scriptName,
757-
props.experimentalAutoCreate,
758-
props.config
759-
)
760-
: null;
752+
if (getFlag("RESOURCES_PROVISION")) {
753+
await provisionBindings(
754+
bindings,
755+
accountId,
756+
scriptName,
757+
props.experimentalAutoCreate,
758+
props.config
759+
);
760+
}
761+
761762
await ensureQueuesExistByConfig(config);
762763
let bindingsPrinted = false;
763764

0 commit comments

Comments
 (0)