Loopback 4, querying with SQLQuery with postgres connector

2.1k views Asked by At

This is how I have defined my repository following very generic example given at loopback documentation:-

import {DefaultCrudRepository, juggler} from '@loopback/repository';
import {AModel} from '../models';
import {TimeseriesDataSource} from '../datasources';
import {inject} from '@loopback/core';

export class AModelRepository extends DefaultCrudRepository<
  AModel,
  typeof AModel.prototype.id
> {
  constructor(
    @inject('datasources.timeseries') dataSource: TimeseriesDataSource,
  ) {
    super(AModel, dataSource);
  }
}

I was hoping that if do AModelRepository.execute(sql, null, cb) it would work. But its giving error - Error: Not implemented

Any help is highly appreciated.

3

There are 3 answers

0
VISHAL DAGA On

Somehow I got it working by injecting the datasource like this

    export class SomeController {
      constructor(
        @repository(SomeRepository) public someRepository: SomeRepository,
        @inject('datasources.timeseries') public dataSource: timeseriesDataSource,
      ) {}
      someMethod(){
         this.dataSource.connector.execute(sql, params, cb)
       }

I will edit if I find any better approach. Please feel free to correct this answer.

0
Miroslav Bajtoš On

LoopBack 4 does not support execute action yet. We have recently discussed this limitation in issue #2053. See my comment for some ideas on how to work around the current limitations. I opened a pull request to add a promise-based dataSource.execute API to loopback-datasource-juggler, see https://github.com/strongloop/loopback-datasource-juggler/pull/1671. Once that change is landed and released, implementing DefaultCrudRepository.prototype.execute() will be trivial.

We are welcoming community contributions, it would be great if you could contribute the execute implementation to loopback-next yourself. See our Contributing Guide to get started.

0
Vitaliy On

In Loopback 4 as of now, the answer above from @Miroslav is working.

I use it like this:

export class SomeDataSource extends juggler.DataSource {
  constructor(
    @inject('DATA_CONFIG_SOURCE') private dsConfig: object
  ) {
    super(dsConfig);
  }
}
//in tests
const datasource = new SomeDataSource(postgresConfig);
dataSource.execute(sqlStatement);

//at the end of the tests
await dbDataSource.disconnect();