Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

[Experimental] Support for prisma #1220

Draft
wants to merge 13 commits into
base: main
Choose a base branch
from
11 changes: 7 additions & 4 deletions packages/client/src/client.ts
Original file line number Diff line number Diff line change
Expand Up @@ -37,29 +37,32 @@ export const buildClient = <Plugins extends Record<string, XataPlugin> = {}>(plu
class {
#options: SafeOptions;

schema: Schemas.Schema;
db: SchemaPluginResult<any>;
search: SearchPluginResult<any>;
transactions: TransactionPluginResult<any>;
sql: SQLPluginResult;
files: FilesPluginResult<any>;

constructor(options: BaseClientOptions = {}, schemaTables?: Schemas.Table[]) {
constructor(options: BaseClientOptions = {}, tables: Schemas.Table[]) {
const safeOptions = this.#parseOptions(options);
this.#options = safeOptions;

const pluginOptions: XataPluginOptions = {
...this.#getFetchProps(safeOptions),
cache: safeOptions.cache,
host: safeOptions.host
host: safeOptions.host,
tables
};

const db = new SchemaPlugin(schemaTables).build(pluginOptions);
const search = new SearchPlugin(db, schemaTables).build(pluginOptions);
const db = new SchemaPlugin().build(pluginOptions);
const search = new SearchPlugin(db).build(pluginOptions);
const transactions = new TransactionPlugin().build(pluginOptions);
const sql = new SQLPlugin().build(pluginOptions);
const files = new FilesPlugin().build(pluginOptions);

// We assign the namespaces after creating in case the user overrides the db plugin
this.schema = { tables };
this.db = db;
this.search = search;
this.transactions = transactions;
Expand Down
3 changes: 2 additions & 1 deletion packages/client/src/plugins.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
import { ApiExtraProps, HostProvider } from './api';
import { ApiExtraProps, HostProvider, Schemas } from './api';
import { CacheImpl } from './schema/cache';

export abstract class XataPlugin {
Expand All @@ -8,4 +8,5 @@ export abstract class XataPlugin {
export type XataPluginOptions = ApiExtraProps & {
cache: CacheImpl;
host: HostProvider;
tables: Schemas.Table[];
};
6 changes: 3 additions & 3 deletions packages/client/src/schema/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -29,13 +29,13 @@ export class SchemaPlugin<Schemas extends Record<string, XataRecord>> extends Xa
#tables: Record<string, Repository<any>> = {};
#schemaTables?: Table[];

constructor(schemaTables?: Table[]) {
constructor() {
super();

this.#schemaTables = schemaTables;
}

build(pluginOptions: XataPluginOptions): SchemaPluginResult<Schemas> {
this.#schemaTables = pluginOptions.tables;

const db: any = new Proxy(
{},
{
Expand Down
5 changes: 3 additions & 2 deletions packages/client/src/search/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -67,12 +67,13 @@ export type SearchPluginResult<Schemas extends Record<string, BaseData>> = {
export class SearchPlugin<Schemas extends Record<string, XataRecord>> extends XataPlugin {
#schemaTables?: Table[];

constructor(private db: SchemaPluginResult<Schemas>, schemaTables?: Table[]) {
constructor(private db: SchemaPluginResult<Schemas>) {
super();
this.#schemaTables = schemaTables;
}

build(pluginOptions: XataPluginOptions): SearchPluginResult<Schemas> {
this.#schemaTables = pluginOptions.tables;

return {
all: async <Tables extends StringKeys<Schemas>>(query: string, options: SearchOptions<Schemas, Tables> = {}) => {
const { records, totalCount } = await this.#search(query, options, pluginOptions);
Expand Down
5 changes: 5 additions & 0 deletions packages/plugin-client-prisma/.npmignore
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
src
tsconfig.json
rollup.config.mjs
.eslintrc.cjs
.gitignore
1 change: 1 addition & 0 deletions packages/plugin-client-prisma/README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
# @xata.io/prisma
33 changes: 33 additions & 0 deletions packages/plugin-client-prisma/package.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,33 @@
{
"name": "@xata.io/prisma",
"version": "0.0.1",
"description": "",
"main": "./dist/index.cjs",
"module": "./dist/index.mjs",
"types": "./dist/index.d.ts",
"exports": {
".": {
"import": "./dist/index.mjs",
"require": "./dist/index.cjs",
"types": "./dist/index.d.ts"
}
},
"scripts": {
"build": "rimraf dist && rollup -c",
"tsc": "tsc --noEmit"
},
"author": "",
"license": "Apache-2.0",
"bugs": {
"url": "https://github.com/xataio/client-ts/issues"
},
"dependencies": {
"@prisma/driver-adapter-utils": "^5.4.2",
"@xata.io/client": "workspace:*"
},
"devDependencies": {
"@prisma/client": "^5.6.0",
"prisma": "^5.6.0",
"superjson": "^2.2.1"
}
}
29 changes: 29 additions & 0 deletions packages/plugin-client-prisma/rollup.config.mjs
Original file line number Diff line number Diff line change
@@ -0,0 +1,29 @@
import dts from 'rollup-plugin-dts';
import esbuild from 'rollup-plugin-esbuild';

export default [
{
input: 'src/index.ts',
plugins: [esbuild()],
output: [
{
file: `dist/index.cjs`,
format: 'cjs',
sourcemap: true
},
{
file: `dist/index.mjs`,
format: 'es',
sourcemap: true
}
]
},
{
input: 'src/index.ts',
plugins: [dts()],
output: {
file: `dist/index.d.ts`,
format: 'es'
}
}
];
128 changes: 128 additions & 0 deletions packages/plugin-client-prisma/src/conversion.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,128 @@
import { type ColumnType, ColumnTypeEnum } from '@prisma/driver-adapter-utils';

export function fieldToColumnType(fieldType: string): ColumnType {
switch (fieldType) {
case 'bool':
return ColumnTypeEnum.Boolean;
case 'bytea':
return ColumnTypeEnum.Bytes;
case 'char':
return ColumnTypeEnum.Text;
case 'int8':
return ColumnTypeEnum.Int64;
case 'int2':
return ColumnTypeEnum.Int32;
case 'int4':
return ColumnTypeEnum.Int32;
case 'regproc':
return ColumnTypeEnum.Text;
case 'text':
return ColumnTypeEnum.Text;
case 'oid':
return ColumnTypeEnum.Int64;
case 'tid':
return ColumnTypeEnum.Text;
case 'xid':
return ColumnTypeEnum.Text;
case 'cid':
return ColumnTypeEnum.Text;
case 'json':
return ColumnTypeEnum.Json;
case 'xml':
return ColumnTypeEnum.Text;
case 'pg_node_tree':
return ColumnTypeEnum.Text;
case 'smgr':
return ColumnTypeEnum.Text;
case 'path':
return ColumnTypeEnum.Text;
case 'polygon':
return ColumnTypeEnum.Text;
case 'cidr':
return ColumnTypeEnum.Text;
case 'float4':
return ColumnTypeEnum.Float;
case 'float8':
return ColumnTypeEnum.Double;
case 'abstime':
return ColumnTypeEnum.Text;
case 'reltime':
return ColumnTypeEnum.Text;
case 'tinterval':
return ColumnTypeEnum.Text;
case 'circle':
return ColumnTypeEnum.Text;
case 'macaddr8':
return ColumnTypeEnum.Text;
case 'money':
return ColumnTypeEnum.Numeric;
case 'macaddr':
return ColumnTypeEnum.Text;
case 'inet':
return ColumnTypeEnum.Text;
case 'aclitem':
return ColumnTypeEnum.Text;
case 'bpchar':
return ColumnTypeEnum.Text;
case 'varchar':
return ColumnTypeEnum.Text;
case 'date':
return ColumnTypeEnum.Date;
case 'time':
return ColumnTypeEnum.Time;
case 'timestamp':
return ColumnTypeEnum.DateTime;
case 'timestamptz':
return ColumnTypeEnum.DateTime;
case 'interval':
return ColumnTypeEnum.Text;
case 'timetz':
return ColumnTypeEnum.Time;
case 'bit':
return ColumnTypeEnum.Text;
case 'varbit':
return ColumnTypeEnum.Text;
case 'numeric':
return ColumnTypeEnum.Numeric;
case 'refcursor':
return ColumnTypeEnum.Text;
case 'regprocedure':
return ColumnTypeEnum.Text;
case 'regoper':
return ColumnTypeEnum.Text;
case 'regoperator':
return ColumnTypeEnum.Text;
case 'regclass':
return ColumnTypeEnum.Text;
case 'regtype':
return ColumnTypeEnum.Text;
case 'uuid':
return ColumnTypeEnum.Uuid;
case 'txid_snapshot':
return ColumnTypeEnum.Text;
case 'pg_lsn':
return ColumnTypeEnum.Text;
case 'pg_ndistinct':
return ColumnTypeEnum.Text;
case 'pg_dependencies':
return ColumnTypeEnum.Text;
case 'tsvector':
return ColumnTypeEnum.Text;
case 'tsquery':
return ColumnTypeEnum.Text;
case 'gtsvector':
return ColumnTypeEnum.Text;
case 'regconfig':
return ColumnTypeEnum.Text;
case 'regdictionary':
return ColumnTypeEnum.Text;
case 'jsonb':
return ColumnTypeEnum.Json;
case 'regnamespace':
return ColumnTypeEnum.Text;
case 'regrole':
return ColumnTypeEnum.Text;
default:
return ColumnTypeEnum.Text;
}
}
76 changes: 76 additions & 0 deletions packages/plugin-client-prisma/src/driver.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,76 @@
/* eslint-disable @typescript-eslint/require-await */
import type {
ColumnType,
DriverAdapter,
Query,
Queryable,
Result,
ResultSet,
Transaction
} from '@prisma/driver-adapter-utils';
import { Debug, err, ok } from '@prisma/driver-adapter-utils';
import { Responses, SQLPluginResult } from '@xata.io/client';
import { fieldToColumnType } from './conversion';

const debug = Debug('prisma:driver-adapter:xata');

type PerformIOResult = Responses.SQLResponse;

abstract class XataQueryable implements Queryable {
readonly flavour = 'postgres';

async queryRaw(query: Query): Promise<Result<ResultSet>> {
const tag = '[js::query_raw]';
debug(`${tag} %O`, query);

const res = await this.performIO(query);

if (!res.ok) {
return err(res.error);
}

const { records, columns = {}, warning } = res.value;
if (warning) debug(`${tag} %O`, warning);

const [columnNames, columnTypes] = Object.fromEntries(columns as any).reduce(
([names, types]: [string[], ColumnType[]], [name, { type_name }]: [string, { type_name: string }]) => {
names.push(name);
types.push(fieldToColumnType(type_name));
return [names, types];
},
[[], []] as [string[], ColumnType[]]
);
Comment on lines +35 to +42
Copy link
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

TODO: Improve this


return ok({ columnNames, columnTypes, rows: records as any[] });
}

async executeRaw(query: Query): Promise<Result<number>> {
const tag = '[js::execute_raw]';
debug(`${tag} %O`, query);

return (await this.performIO(query)).map((r) => r.total ?? 0);
}

abstract performIO(query: Query): Promise<Result<PerformIOResult>>;
}

type XataClient = { sql: SQLPluginResult };

export class PrismaXataHTTP extends XataQueryable implements DriverAdapter {
constructor(private xata: XataClient) {
super();
}

override async performIO(query: Query): Promise<Result<PerformIOResult>> {
const { sql, args: values } = query;
return ok(await this.xata.sql(sql, values));
}

startTransaction(): Promise<Result<Transaction>> {
return Promise.reject(new Error('Transactions are not supported in HTTP mode'));
}

async close() {
return ok(undefined);
}
}
12 changes: 12 additions & 0 deletions packages/plugin-client-prisma/src/index.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,12 @@
import { SQLPlugin, XataPlugin, XataPluginOptions } from '@xata.io/client';
import { PrismaXataHTTP } from './driver';

export class PrismaPlugin extends XataPlugin {
build(pluginOptions: XataPluginOptions) {
const xata = { schema: { tables: pluginOptions.tables }, sql: new SQLPlugin().build(pluginOptions) };

return new PrismaXataHTTP(xata, pluginOptions.tables);
}
}

export * from './driver';
13 changes: 13 additions & 0 deletions packages/plugin-client-prisma/test/plugin.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,13 @@
import { describe, test } from 'vitest';
import { PrismaXataHTTP } from '../src/driver';
import { smokeTest } from './smoke';
import { BaseClient } from '../../client/src';

describe.skip('@xata.io/prisma plugin', () => {
test('run smoke tests', async () => {
const xata = new BaseClient();
const adapter = new PrismaXataHTTP(xata);

await smokeTest(adapter);
});
});
Loading
Loading