Skip to content

Commit

Permalink
Use new D1 API
Browse files Browse the repository at this point in the history
  • Loading branch information
penalosa committed Jan 28, 2025
1 parent 67bb4dd commit 87ed74f
Show file tree
Hide file tree
Showing 10 changed files with 70 additions and 58 deletions.
32 changes: 17 additions & 15 deletions packages/wrangler/src/__tests__/provision.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -481,6 +481,7 @@ describe("--x-provision", () => {
);
})
);
mockGetD1Database("prefilled-d1-name", {}, true);

// no name prompt
mockCreateD1Database({
Expand Down Expand Up @@ -597,6 +598,7 @@ describe("--x-provision", () => {
);
})
);
mockGetD1Database("new-d1-name", {}, true);

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

Expand Down Expand Up @@ -784,18 +786,10 @@ describe("--x-provision", () => {
});
mockGetSettings();

msw.use(
http.get("*/accounts/:accountId/d1/database", async () => {
return HttpResponse.json(
createFetchResult([
{
name: "existing-db-name",
uuid: "existing-d1-id",
},
])
);
})
);
mockGetD1Database("existing-db-name", {
name: "existing-db-name",
uuid: "existing-d1-id",
});

mockUploadWorkerRequest({
expectedBindings: [
Expand Down Expand Up @@ -1030,14 +1024,22 @@ function mockGetR2Bucket(bucketName: string, missing: boolean = false) {
}

function mockGetD1Database(
databaseId: string,
databaseInfo: Partial<DatabaseInfo>
databaseIdOrName: string,
databaseInfo: Partial<DatabaseInfo>,
missing: boolean = false
) {
msw.use(
http.get(
`*/accounts/:accountId/d1/database/:database_id`,
({ params }) => {
expect(params.database_id).toEqual(databaseId);
expect(params.database_id).toEqual(databaseIdOrName);
if (missing) {
return HttpResponse.json(
createFetchResult(null, false, [
{ code: 7404, message: "database not found" },
])
);
}
return HttpResponse.json(createFetchResult(databaseInfo));
},
{ once: true }
Expand Down
7 changes: 5 additions & 2 deletions packages/wrangler/src/d1/info.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,10 @@ import { withConfig } from "../config";
import { logger } from "../logger";
import { requireAuth } from "../user";
import { printWranglerBanner } from "../wrangler-banner";
import { getDatabaseByNameOrBinding, getDatabaseInfoFromId } from "./utils";
import {
getDatabaseByNameOrBinding,
getDatabaseInfoFromIdOrName,
} from "./utils";
import type {
CommonYargsArgv,
StrictYargsOptionsToInterface,
Expand Down Expand Up @@ -35,7 +38,7 @@ export const Handler = withConfig<HandlerOptions>(
name
);

const result = await getDatabaseInfoFromId(accountId, db.uuid);
const result = await getDatabaseInfoFromIdOrName(accountId, db.uuid);

const output: Record<string, string | number> = { ...result };
if (output["file_size"]) {
Expand Down
7 changes: 5 additions & 2 deletions packages/wrangler/src/d1/insights.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,10 @@ import { withConfig } from "../config";
import { logger } from "../logger";
import { requireAuth } from "../user";
import { printWranglerBanner } from "../wrangler-banner";
import { getDatabaseByNameOrBinding, getDatabaseInfoFromId } from "./utils";
import {
getDatabaseByNameOrBinding,
getDatabaseInfoFromIdOrName,
} from "./utils";
import type {
CommonYargsArgv,
StrictYargsOptionsToInterface,
Expand Down Expand Up @@ -114,7 +117,7 @@ export const Handler = withConfig<HandlerOptions>(
name
);

const result = await getDatabaseInfoFromId(accountId, db.uuid);
const result = await getDatabaseInfoFromIdOrName(accountId, db.uuid);

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

Expand Down
10 changes: 8 additions & 2 deletions packages/wrangler/src/d1/migrations/apply.ts
Original file line number Diff line number Diff line change
Expand Up @@ -11,7 +11,10 @@ import { printWranglerBanner } from "../../wrangler-banner";
import { createBackup } from "../backups";
import { DEFAULT_MIGRATION_PATH, DEFAULT_MIGRATION_TABLE } from "../constants";
import { executeSql } from "../execute";
import { getDatabaseInfoFromConfig, getDatabaseInfoFromId } from "../utils";
import {
getDatabaseInfoFromConfig,
getDatabaseInfoFromIdOrName,
} from "../utils";
import {
getMigrationsPath,
getUnappliedMigrations,
Expand Down Expand Up @@ -130,7 +133,10 @@ Your database may not be available to serve requests during the migration, conti
"In non-local mode `databaseInfo` should be defined."
);
const accountId = await requireAuth(config);
const dbInfo = await getDatabaseInfoFromId(accountId, databaseInfo?.uuid);
const dbInfo = await getDatabaseInfoFromIdOrName(
accountId,
databaseInfo?.uuid
);
if (dbInfo.version === "alpha") {
logger.log("🕒 Creating backup...");
await createBackup(accountId, databaseInfo.uuid);
Expand Down
4 changes: 2 additions & 2 deletions packages/wrangler/src/d1/timeTravel/utils.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
import { fetchResult } from "../../cfetch";
import { UserError } from "../../errors";
import { getDatabaseInfoFromId } from "../utils";
import { getDatabaseInfoFromIdOrName } from "../utils";
import type { BookmarkResponse } from "./types";

/**
Expand Down Expand Up @@ -36,7 +36,7 @@ export const throwIfDatabaseIsAlpha = async (
accountId: string,
databaseId: string
): Promise<void> => {
const dbInfo = await getDatabaseInfoFromId(accountId, databaseId);
const dbInfo = await getDatabaseInfoFromIdOrName(accountId, databaseId);
if (dbInfo.version === "alpha") {
throw new UserError(
"Time travel is not available for alpha D1 databases. You will need to migrate to a new database for access to this feature."
Expand Down
8 changes: 4 additions & 4 deletions packages/wrangler/src/d1/utils.ts
Original file line number Diff line number Diff line change
Expand Up @@ -46,20 +46,20 @@ export const getDatabaseByNameOrBinding = async (
return dbFromConfig;
}

const allDBs = await listDatabases(accountId, true);
const allDBs = await listDatabases(accountId);
const matchingDB = allDBs.find((db) => db.name === name);
if (!matchingDB) {
throw new UserError(`Couldn't find DB with name '${name}'`);
}
return matchingDB;
};

export const getDatabaseInfoFromId = async (
export const getDatabaseInfoFromIdOrName = async (
accountId: string,
databaseId: string
databaseIdOrName: string
): Promise<DatabaseInfo> => {
return await fetchResult<DatabaseInfo>(
`/accounts/${accountId}/d1/database/${databaseId}`,
`/accounts/${accountId}/d1/database/${databaseIdOrName}`,
{
headers: {
"Content-Type": "application/json",
Expand Down
18 changes: 9 additions & 9 deletions packages/wrangler/src/deploy/deploy.ts
Original file line number Diff line number Diff line change
Expand Up @@ -800,15 +800,15 @@ See https://developers.cloudflare.com/workers/platform/compatibility-dates for m
} else {
assert(accountId, "Missing accountId");

getFlag("RESOURCES_PROVISION")
? await provisionBindings(
bindings,
accountId,
scriptName,
props.experimentalAutoCreate,
props.config
)
: null;
if (getFlag("RESOURCES_PROVISION")) {
await provisionBindings(
bindings,
accountId,
scriptName,
props.experimentalAutoCreate,
props.config
);
}
await ensureQueuesExistByConfig(config);
let bindingsPrinted = false;

Expand Down
19 changes: 8 additions & 11 deletions packages/wrangler/src/deployment-bundle/bindings.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,10 @@ import assert from "node:assert";
import { fetchResult } from "../cfetch";
import { createD1Database } from "../d1/create";
import { listDatabases } from "../d1/list";
import { getDatabaseByNameOrBinding, getDatabaseInfoFromId } from "../d1/utils";
import {
getDatabaseByNameOrBinding,
getDatabaseInfoFromIdOrName,
} from "../d1/utils";
import { prompt, select } from "../dialogs";
import { UserError } from "../errors";
import { createKVNamespace, listKVNamespaces } from "../kv/helpers";
Expand Down Expand Up @@ -251,7 +254,7 @@ class D1Handler extends ProvisionResourceHandler<"d1", CfD1Database> {

// ...and the user HAS specified a name in their config, so we need to check if the database_name they provided
// 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)
const dbFromId = await getDatabaseInfoFromId(
const dbFromId = await getDatabaseInfoFromIdOrName(
this.accountId,
maybeInherited.id
);
Expand All @@ -269,21 +272,15 @@ class D1Handler extends ProvisionResourceHandler<"d1", CfD1Database> {
return false;
}
try {
// TODO: Use https://jira.cfdata.org/browse/CFSQL-1180 once ready
const db = await getDatabaseByNameOrBinding(
{ d1_databases: [] } as unknown as Config,
const db = await getDatabaseInfoFromIdOrName(
this.accountId,
this.binding.database_name
);

// This database_name exists! We don't need to provision it
return db.uuid;
} catch (e) {
if (
!(
e instanceof Error &&
e.message.startsWith("Couldn't find DB with name")
)
) {
if (!(e instanceof APIError && e.code === 7404)) {
// this is an error that is not "database not found", so we do want to throw
throw e;
}
Expand Down
4 changes: 2 additions & 2 deletions packages/wrangler/src/init.ts
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,7 @@ import { assertNever } from "./api/startDevWorker/utils";
import { fetchResult } from "./cfetch";
import { fetchWorker } from "./cfetch/internal";
import { readConfig } from "./config";
import { getDatabaseInfoFromId } from "./d1/utils";
import { getDatabaseInfoFromIdOrName } from "./d1/utils";
import { confirm, select } from "./dialogs";
import { getC3CommandFromEnv } from "./environment-variables/misc-variables";
import { CommandLineArgsError, FatalError, UserError } from "./errors";
Expand Down Expand Up @@ -993,7 +993,7 @@ export async function mapBindings(
bindings
.filter((binding) => binding.type === "d1")
.map(async (binding) => {
const dbInfo = await getDatabaseInfoFromId(accountId, binding.id);
const dbInfo = await getDatabaseInfoFromIdOrName(accountId, binding.id);
d1BindingsWithInfo[binding.id] = dbInfo;
})
);
Expand Down
19 changes: 10 additions & 9 deletions packages/wrangler/src/versions/upload.ts
Original file line number Diff line number Diff line change
Expand Up @@ -749,15 +749,16 @@ See https://developers.cloudflare.com/workers/platform/compatibility-dates for m
printBindings({ ...bindings, vars: maskedVars });
} else {
assert(accountId, "Missing accountId");
getFlag("RESOURCES_PROVISION")
? await provisionBindings(
bindings,
accountId,
scriptName,
props.experimentalAutoCreate,
props.config
)
: null;
if (getFlag("RESOURCES_PROVISION")) {
await provisionBindings(
bindings,
accountId,
scriptName,
props.experimentalAutoCreate,
props.config
);
}

await ensureQueuesExistByConfig(config);
let bindingsPrinted = false;

Expand Down

0 comments on commit 87ed74f

Please sign in to comment.