Skip to content

Commit

Permalink
Revert "chore(capabilities): define native query connection capabilit…
Browse files Browse the repository at this point in the history
…ies (#1211)"

This reverts commit c9e964c.
  • Loading branch information
DayTF authored Nov 27, 2024
1 parent 891d520 commit 8230d09
Show file tree
Hide file tree
Showing 19 changed files with 13 additions and 323 deletions.
3 changes: 0 additions & 3 deletions packages/agent/src/routes/capabilities.ts
Original file line number Diff line number Diff line change
Expand Up @@ -31,9 +31,6 @@ export default class Capabilities extends BaseRoute {
);

context.response.body = {
nativeQueryConnections: Object.keys(this.dataSource.nativeQueryConnections).map(
connectionName => ({ name: connectionName }),
),
collections:
collections?.map(collection => ({
name: collection.name,
Expand Down
24 changes: 0 additions & 24 deletions packages/agent/test/routes/capabilities.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -52,27 +52,6 @@ describe('Capabilities', () => {
route = new Capabilities(services, options, dataSource);
});

describe('when datasource has nativeQueryConnections registered', () => {
it('should return the available connection names', async () => {
const context = createMockContext({
...defaultContext,
requestBody: { collectionNames: [] },
});
// eslint-disable-next-line @typescript-eslint/ban-ts-comment
// @ts-ignore
jest.replaceProperty(route.dataSource, 'nativeQueryConnections', { main: {}, replica: {} });

// eslint-disable-next-line @typescript-eslint/ban-ts-comment
// @ts-ignore
await route.fetchCapabilities(context);

expect(context.response.body).toEqual({
nativeQueryConnections: [{ name: 'main' }, { name: 'replica' }],
collections: [],
});
});
});

describe('when request body does not list any collection name', () => {
test('should return nothing', async () => {
const context = createMockContext({
Expand All @@ -85,7 +64,6 @@ describe('Capabilities', () => {
await route.fetchCapabilities(context);

expect(context.response.body).toEqual({
nativeQueryConnections: [],
collections: [],
});
});
Expand All @@ -101,7 +79,6 @@ describe('Capabilities', () => {
await route.fetchCapabilities(context);

expect(context.response.body).toEqual({
nativeQueryConnections: [],
collections: [],
});
});
Expand All @@ -119,7 +96,6 @@ describe('Capabilities', () => {
await route.fetchCapabilities(context);

expect(context.response.body).toEqual({
nativeQueryConnections: [],
collections: [
{
name: 'books',
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -12,13 +12,6 @@ export default class CompositeDatasource<T extends Collection = Collection>
{
private dataSources: DataSource[] = [];

get nativeQueryConnections(): Record<string, unknown> {
return this.dataSources.reduce(
(acc, current) => ({ ...acc, ...current.nativeQueryConnections }),
{},
);
}

get schema(): DataSourceSchema {
return { charts: this.dataSources.flatMap(dataSource => dataSource.schema.charts) };
}
Expand Down Expand Up @@ -57,12 +50,6 @@ export default class CompositeDatasource<T extends Collection = Collection>
}
}

for (const nativeQueryConnection of Object.keys(dataSource.nativeQueryConnections || {})) {
if (this.nativeQueryConnections[nativeQueryConnection]) {
throw new Error(`Native Query connection '${nativeQueryConnection}' is already defined`);
}
}

this.dataSources.push(dataSource);
}

Expand All @@ -75,18 +62,4 @@ export default class CompositeDatasource<T extends Collection = Collection>

throw new Error(`Chart '${name}' is not defined in the dataSource.`);
}

async executeNativeQuery(
connectionName: string,
query: string,
contextVariables = {},
): Promise<unknown> {
if (!this.nativeQueryConnections[connectionName]) {
throw new Error(`Unknown connection name '${connectionName}'`);
}

return this.dataSources
.find(datasource => Boolean(datasource.nativeQueryConnections[connectionName]))
.executeNativeQuery(connectionName, query, contextVariables);
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -38,7 +38,7 @@ describe('CompositeDataSource', () => {
expect(compositeDataSource.schema.charts).toEqual(['chart1', 'chart2', 'chart3', 'chart4']);
});

it('should throw with collection name conflict', () => {
it('should throw with collectio name conflict', () => {
const aDataSource = factories.dataSource.buildWithCollection(
factories.collection.build({ name: 'collection1' }),
);
Expand All @@ -64,17 +64,6 @@ describe('CompositeDataSource', () => {
"Chart 'chart1' is already defined in datasource.",
);
});

it('should throw an error if native query connection name already defined', () => {
const compositeDataSource = new CompositeDataSource<Collection>();
const aDataSource = factories.dataSource.buildWithNativeQueryConnections({ main: {} });
const otherDataSource = factories.dataSource.buildWithNativeQueryConnections({ main: {} });
compositeDataSource.addDataSource(aDataSource);

expect(() => compositeDataSource.addDataSource(otherDataSource)).toThrow(
`Native Query connection 'main' is already defined`,
);
});
});

describe('getCollection', () => {
Expand All @@ -94,21 +83,6 @@ describe('CompositeDataSource', () => {
});
});

describe('nativeQueryConnections', () => {
it('should throw an error when the collection does not exist', () => {
const compositeDataSource = new CompositeDataSource<Collection>();
const aDataSource = factories.dataSource.buildWithNativeQueryConnections({ main: {} });
const otherDataSource = factories.dataSource.buildWithNativeQueryConnections({ second: {} });
compositeDataSource.addDataSource(aDataSource);
compositeDataSource.addDataSource(otherDataSource);

expect(compositeDataSource.nativeQueryConnections).toEqual({
main: {},
second: {},
});
});
});

describe('renderChart', () => {
it('should not throw error when the chart exists', async () => {
const compositeDataSource = new CompositeDataSource<Collection>();
Expand All @@ -132,29 +106,4 @@ describe('CompositeDataSource', () => {
).rejects.toThrow("Chart 'chart1' is not defined in the dataSource.");
});
});

describe('executeNativeQuery', () => {
describe('when no connection name is found for given name', () => {
it('should throw an error', async () => {
const compositeDataSource = new CompositeDataSource<Collection>();

await expect(compositeDataSource.executeNativeQuery('main', 'query')).rejects.toThrow(
new Error(`Unknown connection name 'main'`),
);
});
});

it('should execute the query on the child datasource', async () => {
const compositeDataSource = new CompositeDataSource<Collection>();
const aDataSource = factories.dataSource.buildWithNativeQueryConnections({ main: {} });
compositeDataSource.addDataSource(aDataSource);

const spyExecute = jest.spyOn(aDataSource, 'executeNativeQuery');

await compositeDataSource.executeNativeQuery('main', 'query', {});

expect(spyExecute).toHaveBeenCalledOnce();
expect(spyExecute).toHaveBeenCalledWith('main', 'query', {});
});
});
});
Original file line number Diff line number Diff line change
Expand Up @@ -10,8 +10,6 @@ function makeMockDataSource(): jest.Mocked<DataSource> {
charts: [] as string[],
},
collections: [],
nativeQueryConnections: {},
executeNativeQuery: jest.fn(),
getCollection: jest.fn(),
renderChart: jest.fn(),
};
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -10,8 +10,6 @@ function makeMockDataSource(): jest.Mocked<DataSource> {
charts: [] as string[],
},
collections: [],
nativeQueryConnections: {},
executeNativeQuery: jest.fn(),
getCollection: jest.fn(),
renderChart: jest.fn(),
};
Expand Down
32 changes: 2 additions & 30 deletions packages/datasource-sequelize/src/datasource.ts
Original file line number Diff line number Diff line change
@@ -1,12 +1,7 @@
import { BaseDataSource, Logger } from '@forestadmin/datasource-toolkit';
import { QueryTypes, Sequelize } from 'sequelize';
import { Sequelize } from 'sequelize';

import SequelizeCollection from './collection';
import { SequelizeDatasourceOptions } from './types';

interface NativeQueryConnection {
instance: Sequelize;
}

export default class SequelizeDataSource extends BaseDataSource<SequelizeCollection> {
/**
Expand All @@ -17,7 +12,7 @@ export default class SequelizeDataSource extends BaseDataSource<SequelizeCollect
*/
protected sequelize: Sequelize = null;

constructor(sequelize: Sequelize, logger?: Logger, options?: SequelizeDatasourceOptions) {
constructor(sequelize: Sequelize, logger?: Logger) {
super();

if (!sequelize) throw new Error('Invalid (null) Sequelize instance.');
Expand All @@ -26,10 +21,6 @@ export default class SequelizeDataSource extends BaseDataSource<SequelizeCollect
this.sequelize = sequelize;

this.createCollections(this.sequelize.models, logger);

if (options?.liveQueryConnections) {
this.addNativeQueryConnection(options.liveQueryConnections, { instance: this.sequelize });
}
}

async close(): Promise<void> {
Expand All @@ -45,23 +36,4 @@ export default class SequelizeDataSource extends BaseDataSource<SequelizeCollect
this.addCollection(collection);
});
}

override async executeNativeQuery<R extends object>(
connectionName: string,
query: string,
contextVariables = {},
): Promise<R[]> {
if (!this.nativeQueryConnections[connectionName]) {
throw new Error(`Unknown connection name '${connectionName}'`);
}

return (this.nativeQueryConnections[connectionName] as NativeQueryConnection).instance.query<R>(
query,
{
bind: contextVariables,
type: QueryTypes.SELECT,
raw: true,
},
);
}
}
8 changes: 2 additions & 6 deletions packages/datasource-sequelize/src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,15 +2,11 @@ import { DataSourceFactory, Logger } from '@forestadmin/datasource-toolkit';
import { Sequelize } from 'sequelize';

import SequelizeDataSource from './datasource';
import { SequelizeDatasourceOptions } from './types';

export { default as SequelizeCollection } from './collection';
export { default as SequelizeDataSource } from './datasource';
export { default as TypeConverter } from './utils/type-converter';

export function createSequelizeDataSource(
connection: Sequelize,
options?: SequelizeDatasourceOptions,
): DataSourceFactory {
return async (logger: Logger) => new SequelizeDataSource(connection, logger, options);
export function createSequelizeDataSource(connection: Sequelize): DataSourceFactory {
return async (logger: Logger) => new SequelizeDataSource(connection, logger);
}
3 changes: 0 additions & 3 deletions packages/datasource-sequelize/src/types.ts

This file was deleted.

61 changes: 2 additions & 59 deletions packages/datasource-sequelize/test/datasource.unit.test.ts
Original file line number Diff line number Diff line change
@@ -1,12 +1,10 @@
import { QueryTypes, Sequelize } from 'sequelize';
import { Sequelize } from 'sequelize';

import { SequelizeCollection, SequelizeDataSource } from '../src';

describe('SequelizeDataSource', () => {
it('should fail to instantiate without a Sequelize instance', () => {
expect(() => new SequelizeDataSource(null as unknown as Sequelize)).toThrow(
'Invalid (null) Sequelize instance.',
);
expect(() => new SequelizeDataSource(null)).toThrow('Invalid (null) Sequelize instance.');
});

it('should fail to instantiate without a Sequelize models defined', () => {
Expand All @@ -21,12 +19,6 @@ describe('SequelizeDataSource', () => {
).toBeArrayOfSize(0);
});

it('should have no predefined nativeQueryConnection', () => {
expect(
new SequelizeDataSource({ models: {} } as unknown as Sequelize).nativeQueryConnections,
).toEqual({});
});

it('should create collection based on models', () => {
const sequelize = new Sequelize({ dialect: 'postgres' });
sequelize.define('cars', {});
Expand All @@ -52,53 +44,4 @@ describe('SequelizeDataSource', () => {

expect(firstCollectionNames).toStrictEqual(secondCollectionNames);
});

it('should register nativeQueryConnection', () => {
const sequelize = new Sequelize({ dialect: 'postgres' });
sequelize.define('cars', {});
const logger = jest.fn();
const dataSource = new SequelizeDataSource(sequelize, logger, {
liveQueryConnections: 'main',
});

expect(dataSource.nativeQueryConnections).toEqual({ main: { instance: sequelize } });
});

describe('executeNativeQuery', () => {
it('should execute the given query on the correct connection', async () => {
const sequelize = new Sequelize({ dialect: 'postgres' });
sequelize.define('cars', {});
const logger = jest.fn();
const spyQuery = jest.spyOn(sequelize, 'query').mockImplementation();
const dataSource = new SequelizeDataSource(sequelize, logger, {
liveQueryConnections: 'main',
});

await dataSource.executeNativeQuery('main', 'query', { something: 'value' });

expect(spyQuery).toHaveBeenCalled();
expect(spyQuery).toHaveBeenCalledWith('query', {
bind: { something: 'value' },
type: QueryTypes.SELECT,
raw: true,
});
});

describe('when giving an unknown connection name', () => {
it('should throw an error', async () => {
const sequelize = new Sequelize({ dialect: 'postgres' });
sequelize.define('cars', {});
const logger = jest.fn();
const spyQuery = jest.spyOn(sequelize, 'query').mockImplementation();
const dataSource = new SequelizeDataSource(sequelize, logger, {
liveQueryConnections: 'main',
});

await expect(
dataSource.executeNativeQuery('production', 'query', { something: 'value' }),
).rejects.toThrow(new Error(`Unknown connection name 'production'`));
expect(spyQuery).not.toHaveBeenCalled();
});
});
});
});
7 changes: 1 addition & 6 deletions packages/datasource-sql/src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -101,12 +101,7 @@ export function createSqlDataSource(
options?.displaySoftDeleted,
);

return new SqlDatasource(
new SequelizeDataSource(sequelize, logger, {
liveQueryConnections: options?.liveQueryConnections,
}),
latestIntrospection.views,
);
return new SqlDatasource(new SequelizeDataSource(sequelize, logger), latestIntrospection.views);
};
}

Expand Down
1 change: 0 additions & 1 deletion packages/datasource-sql/src/types.ts
Original file line number Diff line number Diff line change
Expand Up @@ -50,5 +50,4 @@ export type SslMode = 'preferred' | 'disabled' | 'required' | 'verify' | 'manual
export type SqlDatasourceOptions = {
introspection?: SupportedIntrospection;
displaySoftDeleted?: string[] | true;
liveQueryConnections?: string;
};
Loading

0 comments on commit 8230d09

Please sign in to comment.