Skip to content

Commit d7e5c87

Browse files
authored
Breaking changes to codegen (#1371)
1 parent 75d1671 commit d7e5c87

File tree

21 files changed

+279
-508
lines changed

21 files changed

+279
-508
lines changed

cli/src/base.ts

Lines changed: 3 additions & 11 deletions
Original file line numberDiff line numberDiff line change
@@ -1,13 +1,5 @@
11
import { Command, Flags, Interfaces } from '@oclif/core';
2-
import {
3-
buildClient,
4-
getAPIKey,
5-
getBranch,
6-
getHostUrl,
7-
parseWorkspacesUrlParts,
8-
Schemas,
9-
XataApiPlugin
10-
} from '@xata.io/client';
2+
import { buildClient, getHostUrl, parseWorkspacesUrlParts, Schemas, XataApiPlugin } from '@xata.io/client';
113
import { XataImportPlugin } from '@xata.io/importer';
124
import ansiRegex from 'ansi-regex';
135
import chalk from 'chalk';
@@ -192,7 +184,7 @@ export abstract class BaseCommand<T extends typeof Command> extends Command {
192184
const { flags } = await this.parseCommand();
193185
const profileName = flags.profile || getEnvProfileName();
194186

195-
const apiKey = getAPIKey();
187+
const apiKey = process.env.XATA_API_KEY;
196188
const useEnv = !ignoreEnv || profileName === 'default';
197189
if (useEnv && apiKey) return buildProfile({ name: 'default', apiKey });
198190

@@ -531,7 +523,7 @@ export abstract class BaseCommand<T extends typeof Command> extends Command {
531523
}
532524

533525
getCurrentBranchName() {
534-
return getBranch() ?? 'main';
526+
return process.env.XATA_BRANCH ?? 'main';
535527
}
536528

537529
async updateConfig() {

cli/src/commands/codegen/index.ts

Lines changed: 5 additions & 18 deletions
Original file line numberDiff line numberDiff line change
@@ -1,11 +1,12 @@
11
import { Flags } from '@oclif/core';
22
import { generate, isValidJavascriptTarget, javascriptTargets } from '@xata.io/codegen';
33
import chalk from 'chalk';
4-
import { mkdir, readFile, writeFile } from 'fs/promises';
4+
import { mkdir, writeFile } from 'fs/promises';
55
import path, { dirname, extname, relative } from 'path';
66
import { BaseCommand } from '../../base.js';
77
import { ProjectConfig } from '../../config.js';
88
import { getBranchDetailsWithPgRoll } from '../../migrations/pgroll.js';
9+
import { safeReadFile } from '../../utils/files.js';
910

1011
export const languages: Record<string, 'javascript' | 'typescript'> = {
1112
'.js': 'javascript',
@@ -46,9 +47,6 @@ export default class Codegen extends BaseCommand<typeof Codegen> {
4647
}),
4748
'worker-id': Flags.string({
4849
description: 'Xata worker deployment id'
49-
}),
50-
'experimental-incremental-build': Flags.boolean({
51-
description: 'Experimental: Keep the source code in the generated file and only update the parts that changed'
5250
})
5351
};
5452

@@ -84,27 +82,16 @@ export default class Codegen extends BaseCommand<typeof Codegen> {
8482
}
8583

8684
const xata = await this.getXataClient();
87-
const { workspace, region, database, branch, databaseURL } = await this.getParsedDatabaseURLWithBranch(
88-
flags.db,
89-
flags.branch
90-
);
85+
const { workspace, region, database, branch } = await this.getParsedDatabaseURLWithBranch(flags.db, flags.branch);
9186
const { schema } = await getBranchDetailsWithPgRoll(xata, { workspace, region, database, branch });
92-
93-
const codegenBranch = flags['inject-branch'] ? branch : undefined;
94-
95-
// Experimental: Keep the source code in the generated file and only update the parts that changed
96-
const incrementalBuild =
97-
flags['experimental-incremental-build'] ?? this.projectConfig?.experimental?.incrementalBuild ?? false;
98-
const existingCode = incrementalBuild ? await readFile(output, 'utf8').catch(() => undefined) : undefined;
87+
const existingCode = await safeReadFile(output);
9988

10089
const result = await generate({
10190
schema,
102-
databaseURL,
10391
language,
10492
moduleType,
10593
javascriptTarget,
106-
branch: codegenBranch,
107-
existingCode
94+
existingCode: existingCode ?? ''
10895
});
10996

11097
const { typescript, javascript, types } = result;

cli/src/commands/init/index.test.ts

Lines changed: 59 additions & 64 deletions
Original file line numberDiff line numberDiff line change
@@ -157,8 +157,7 @@ describe('xata init', () => {
157157
}",
158158
"package.json": "{"name":"test","version":"1.0.0"}",
159159
"readme.md": "",
160-
"xataCustom.ts": "// Generated by Xata Codegen 0.29.4. Please do not edit.
161-
import { buildClient } from "@xata.io/client";
160+
"xataCustom.ts": "import { buildClient, getDeployPreviewBranch } from "@xata.io/client";
162161
import type {
163162
BaseClientOptions,
164163
SchemaInference,
@@ -181,24 +180,23 @@ describe('xata init', () => {
181180
182181
const DatabaseClient = buildClient();
183182
184-
const defaultOptions = {
185-
databaseURL: "https://test-1234.us-east-1.xata.sh/db/db1",
186-
};
187-
188183
export class XataClient extends DatabaseClient<DatabaseSchema> {
189184
constructor(options?: BaseClientOptions) {
190-
super({ ...defaultOptions, ...options }, tables);
185+
super(
186+
{
187+
apiKey: process.env.XATA_API_KEY,
188+
databaseURL: process.env.XATA_DATABASE_URL,
189+
// Use deploy preview branch if available, otherwise use branch from environment
190+
branch:
191+
getDeployPreviewBranch(process.env) ??
192+
process.env.XATA_BRANCH ??
193+
"main",
194+
...options,
195+
},
196+
tables
197+
);
191198
}
192199
}
193-
194-
let instance: XataClient | undefined = undefined;
195-
196-
export const getXataClient = () => {
197-
if (instance) return instance;
198-
199-
instance = new XataClient();
200-
return instance;
201-
};
202200
",
203201
}
204202
`);
@@ -242,8 +240,7 @@ describe('xata init', () => {
242240
}
243241
}",
244242
"readme.md": "",
245-
"xataCustom.ts": "// Generated by Xata Codegen 0.29.4. Please do not edit.
246-
import { buildClient } from "@xata.io/client";
243+
"xataCustom.ts": "import { buildClient, getDeployPreviewBranch } from "@xata.io/client";
247244
import type {
248245
BaseClientOptions,
249246
SchemaInference,
@@ -266,24 +263,23 @@ describe('xata init', () => {
266263
267264
const DatabaseClient = buildClient();
268265
269-
const defaultOptions = {
270-
databaseURL: "https://test-1234.us-east-1.xata.sh/db/db1",
271-
};
272-
273266
export class XataClient extends DatabaseClient<DatabaseSchema> {
274267
constructor(options?: BaseClientOptions) {
275-
super({ ...defaultOptions, ...options }, tables);
268+
super(
269+
{
270+
apiKey: process.env.XATA_API_KEY,
271+
databaseURL: process.env.XATA_DATABASE_URL,
272+
// Use deploy preview branch if available, otherwise use branch from environment
273+
branch:
274+
getDeployPreviewBranch(process.env) ??
275+
process.env.XATA_BRANCH ??
276+
"main",
277+
...options,
278+
},
279+
tables
280+
);
276281
}
277282
}
278-
279-
let instance: XataClient | undefined = undefined;
280-
281-
export const getXataClient = () => {
282-
if (instance) return instance;
283-
284-
instance = new XataClient();
285-
return instance;
286-
};
287283
",
288284
}
289285
`);
@@ -319,8 +315,10 @@ describe('xata init', () => {
319315
}
320316
}",
321317
"readme.md": "",
322-
"xataCustom.ts": "// Generated by Xata Codegen 0.29.4. Please do not edit.
323-
import { buildClient } from "npm:@xata.io/client@latest";
318+
"xataCustom.ts": "import {
319+
buildClient,
320+
getDeployPreviewBranch,
321+
} from "npm:@xata.io/client@latest";
324322
import type {
325323
BaseClientOptions,
326324
SchemaInference,
@@ -343,24 +341,23 @@ describe('xata init', () => {
343341
344342
const DatabaseClient = buildClient();
345343
346-
const defaultOptions = {
347-
databaseURL: "https://test-1234.us-east-1.xata.sh/db/db1",
348-
};
349-
350344
export class XataClient extends DatabaseClient<DatabaseSchema> {
351345
constructor(options?: BaseClientOptions) {
352-
super({ ...defaultOptions, ...options }, tables);
346+
super(
347+
{
348+
apiKey: Deno.env.get("XATA_API_KEY"),
349+
databaseURL: Deno.env.get("XATA_DATABASE_URL"),
350+
// Use deploy preview branch if available, otherwise use branch from environment
351+
branch:
352+
getDeployPreviewBranch(Deno.env.get) ??
353+
Deno.env.get("XATA_BRANCH") ??
354+
"main",
355+
...options,
356+
},
357+
tables
358+
);
353359
}
354360
}
355-
356-
let instance: XataClient | undefined = undefined;
357-
358-
export const getXataClient = () => {
359-
if (instance) return instance;
360-
361-
instance = new XataClient();
362-
return instance;
363-
};
364361
",
365362
}
366363
`);
@@ -400,8 +397,7 @@ describe('xata init', () => {
400397
"package.json": "{"name":"test","version":"1.0.0"}",
401398
"pnpm-lock.yaml": "lockfileVersion: '6.0'",
402399
"readme.md": "",
403-
"xataCustom.ts": "// Generated by Xata Codegen 0.29.4. Please do not edit.
404-
import { buildClient } from "@xata.io/client";
400+
"xataCustom.ts": "import { buildClient, getDeployPreviewBranch } from "@xata.io/client";
405401
import type {
406402
BaseClientOptions,
407403
SchemaInference,
@@ -424,24 +420,23 @@ describe('xata init', () => {
424420
425421
const DatabaseClient = buildClient();
426422
427-
const defaultOptions = {
428-
databaseURL: "https://test-1234.us-east-1.xata.sh/db/db1",
429-
};
430-
431423
export class XataClient extends DatabaseClient<DatabaseSchema> {
432424
constructor(options?: BaseClientOptions) {
433-
super({ ...defaultOptions, ...options }, tables);
425+
super(
426+
{
427+
apiKey: process.env.XATA_API_KEY,
428+
databaseURL: process.env.XATA_DATABASE_URL,
429+
// Use deploy preview branch if available, otherwise use branch from environment
430+
branch:
431+
getDeployPreviewBranch(process.env) ??
432+
process.env.XATA_BRANCH ??
433+
"main",
434+
...options,
435+
},
436+
tables
437+
);
434438
}
435439
}
436-
437-
let instance: XataClient | undefined = undefined;
438-
439-
export const getXataClient = () => {
440-
if (instance) return instance;
441-
442-
instance = new XataClient();
443-
return instance;
444-
};
445440
",
446441
}
447442
`);

cli/src/commands/shell/index.ts

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -49,7 +49,7 @@ export default class Shell extends BaseCommand<typeof Shell> {
4949
const branchDetails = await getBranchDetailsWithPgRoll(xata, { workspace, region, database, branch });
5050
const { schema } = branchDetails;
5151

52-
const { javascript } = await generate({ language: 'javascript', databaseURL, schema });
52+
const { javascript } = await generate({ language: 'javascript', schema });
5353
await fs.writeFile(tempFile, javascript);
5454
} catch (err) {
5555
const message = err instanceof Error ? err.message : String(err);

cli/src/config.ts

Lines changed: 1 addition & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -5,7 +5,7 @@ export const projectConfigSchema = z.object({
55
databaseURL: z.string(),
66
codegen: z.object({
77
output: z.string(),
8-
moduleType: z.enum(['cjs', 'esm', 'deno']),
8+
moduleType: z.enum(['cjs', 'esm', 'deno', 'vite']),
99
declarations: z.boolean(),
1010
javascriptTarget: z.enum([
1111
'es5',
@@ -21,7 +21,6 @@ export const projectConfigSchema = z.object({
2121
])
2222
}),
2323
experimental: z.object({
24-
incrementalBuild: z.boolean(),
2524
workflow: z.boolean()
2625
})
2726
});

cli/src/migrations/pgroll.ts

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1,13 +1,13 @@
11
import { Schemas, XataApiClient } from '@xata.io/client';
22
import { Column } from '@xata.io/codegen';
3+
import { OpRawSQL, OpRenameConstraint, PgRollOperation } from '@xata.io/pgroll';
34
import path from 'path';
45
import z from 'zod';
56
import { XataClient } from '../base.js';
7+
import { BranchSchemaFormatted } from '../commands/schema/types.js';
68
import { safeJSONParse, safeReadFile } from '../utils/files.js';
79
import { migrationsDir, readMigrationsDir } from './files.js';
810
import { MigrationFilePgroll, migrationFilePgroll } from './schema.js';
9-
import { OpRawSQL, OpRenameConstraint, PgRollOperation } from '@xata.io/pgroll';
10-
import { BranchSchemaFormatted } from '../commands/schema/types.js';
1111

1212
export const isBranchPgRollEnabled = (details: Schemas.DBBranch) => {
1313
// @ts-expect-error TODO: Fix this when api is finalized

packages/client/src/api/client.ts

Lines changed: 1 addition & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,4 @@
11
import { defaultTrace, TraceFunction } from '../schema/tracing';
2-
import { getAPIKey } from '../util/environment';
32
import { FetchImpl, getFetchImplementation } from '../util/fetch';
43
import { RequiredKeys } from '../util/types';
54
import { generateUUID } from '../util/uuid';
@@ -40,7 +39,7 @@ const buildApiClient = () =>
4039
class {
4140
constructor(options: XataApiClientOptions = {}) {
4241
const provider = options.host ?? 'production';
43-
const apiKey = options.apiKey ?? getAPIKey();
42+
const apiKey = options.apiKey;
4443
const trace = options.trace ?? defaultTrace;
4544
const clientID = generateUUID();
4645

packages/client/src/client.ts

Lines changed: 6 additions & 23 deletions
Original file line numberDiff line numberDiff line change
@@ -6,7 +6,6 @@ import { defaultTrace, TraceFunction } from './schema/tracing';
66
import { SearchPlugin, SearchPluginResult } from './search';
77
import { SQLPlugin, SQLPluginResult } from './sql';
88
import { TransactionPlugin, TransactionPluginResult } from './transaction';
9-
import { getAPIKey, getBranch, getDatabaseURL, getEnableBrowserVariable, getPreviewBranch } from './util/environment';
109
import { FetchImpl, getFetchImplementation } from './util/fetch';
1110
import { AllRequired, StringKeys } from './util/types';
1211
import { generateUUID } from './util/uuid';
@@ -83,7 +82,7 @@ export const buildClient = <Plugins extends Record<string, XataPlugin> = {}>(plu
8382

8483
#parseOptions(options?: BaseClientOptions): SafeOptions {
8584
// If is running from the browser and the user didn't pass `enableBrowser` we throw an error
86-
const enableBrowser = options?.enableBrowser ?? getEnableBrowserVariable() ?? false;
85+
const enableBrowser = options?.enableBrowser ?? false;
8786
// @ts-ignore Window, Deno are not globals
8887
const isBrowser = typeof window !== 'undefined' && typeof Deno === 'undefined';
8988
if (isBrowser && !enableBrowser) {
@@ -93,8 +92,9 @@ export const buildClient = <Plugins extends Record<string, XataPlugin> = {}>(plu
9392
}
9493

9594
const fetch = getFetchImplementation(options?.fetch);
96-
const databaseURL = options?.databaseURL || getDatabaseURL();
97-
const apiKey = options?.apiKey || getAPIKey();
95+
const databaseURL = options?.databaseURL;
96+
const apiKey = options?.apiKey;
97+
const branch = options?.branch;
9898
const trace = options?.trace ?? defaultTrace;
9999
const clientName = options?.clientName;
100100
const host = options?.host ?? 'production';
@@ -108,25 +108,8 @@ export const buildClient = <Plugins extends Record<string, XataPlugin> = {}>(plu
108108
throw new Error('Option databaseURL is required');
109109
}
110110

111-
const envBranch = getBranch();
112-
const previewBranch = getPreviewBranch();
113-
const branch = options?.branch || previewBranch || envBranch || 'main';
114-
if (!!previewBranch && branch !== previewBranch) {
115-
console.warn(
116-
`Ignoring preview branch ${previewBranch} because branch option was passed to the client constructor with value ${branch}`
117-
);
118-
} else if (!!envBranch && branch !== envBranch) {
119-
console.warn(
120-
`Ignoring branch ${envBranch} because branch option was passed to the client constructor with value ${branch}`
121-
);
122-
} else if (!!previewBranch && !!envBranch && previewBranch !== envBranch) {
123-
console.warn(
124-
`Ignoring preview branch ${previewBranch} and branch ${envBranch} because branch option was passed to the client constructor with value ${branch}`
125-
);
126-
} else if (!previewBranch && !envBranch && options?.branch === undefined) {
127-
console.warn(
128-
`No branch was passed to the client constructor. Using default branch ${branch}. You can set the branch with the environment variable XATA_BRANCH or by passing the branch option to the client constructor.`
129-
);
111+
if (!branch) {
112+
throw new Error('Option branch is required');
130113
}
131114

132115
return {

0 commit comments

Comments
 (0)