question-mark
Stuck on an issue?

Lightrun Answers was designed to reduce the constant googling that comes with debugging 3rd party libraries. It collects links to all the places you might be looking at while hunting down a tough bug.

And, if you’re still stuck at the end, we’re happy to hop on a call to see how we can help out.

QueryFailed error when trying to synchronise

See original GitHub issue

I’m currently in the process of testing a typescript app using Typeorm. Tried to create a few simple examples at first but it seems that pg-mem is throwing an error when trying to write the test. Application code works fine. Have I implemented wrong/is there a simple fix?

Thanks!

Stack trace

QueryFailedError: column "columns.table_name" does not exist

    🐜 This seems to be an execution error, which means that your request syntax seems okay,
    but the resulting statement cannot be executed → Probably not a pg-mem error.

    *️⃣ Failed SQL statement: SELECT columns.*, pg_catalog.col_description(('"' || table_catalog || '"."' || table_schema || '"."' || table_name || '"')::regclass::oid, ordinal_position) AS description, ('"' || "udt_schema" || '"."' || "udt_name" || '"')::"regtype" AS "regtype", pg_catalog.format_type("col_attr"."atttypid", "col_attr"."atttypmod") AS "format_type" FROM "information_schema"."columns" LEFT JOIN "pg_catalog"."pg_attribute" AS "col_attr" ON "col_attr"."attname" = "columns"."column_name" AND "col_attr"."attrelid" = ( SELECT "cls"."oid" FROM "pg_catalog"."pg_class" AS "cls" LEFT JOIN "pg_catalog"."pg_namespace" AS "ns" ON "ns"."oid" = "cls"."relnamespace" WHERE "cls"."relname" = "columns"."table_name" AND "ns"."nspname" = "columns"."table_schema" ) WHERE ("table_schema" = 'public' AND "table_name" = 'address');

    👉 You can file an issue at https://github.com/oguimbal/pg-mem along with a way to reproduce this error (if you can), and  the stacktrace

Typeorm entity:

 @Entity()
export class Address {
  @PrimaryGeneratedColumn('uuid')
  id: number;

  @Column()
  number: string;

  @Column()
  line1: string;

  @Column()
  line2: string;

  @Column()
  city: string;

  @Column()
  postcode: string;

  @Column()
  country: string;
}

Test

describe('address model', () => {
  let connection: Connection;
  beforeEach( async () => {
    const db = newDb();
    console.log('creating connection');
    connection = await db.adapters.createTypeormConnection({
        type: 'postgres',
        entities: [ Address ]
    });

    console.log('sync?')
    await connection.synchronize();
  });
  it('should be created', () => {
    console.log('hi')
    const addressRepository = connection.getRepository(Address);
    const address = addressRepository.create({
      number: '30',
      line1: 'Main Street', 
      city: 'London',
      postcode: 'N113SE',
    });

    expect(address.number).toEqual('30');
  });
});

Issue Analytics

  • State:open
  • Created 2 years ago
  • Reactions:3
  • Comments:9 (3 by maintainers)

github_iconTop GitHub Comments

9reactions
TylerSustarecommented, Aug 21, 2021

I was able to fix the issue by using the registerFunction for my use case (TypeORM with NestJS) I was getting the error like others in this thread.

    QueryFailedError: ERROR: function current_database() does not exist
    HINT: 🔨 Please note that pg-mem implements very few native functions.

                👉 You can specify the functions you would like to use via "db.public.registerFunction(...)"

    🐜 This seems to be an execution error, which means that your request syntax seems okay,
    but the resulting statement cannot be executed → Probably not a pg-mem error.

    *️⃣ Failed SQL statement: SELECT * FROM current_database();

    👉 You can file an issue...

But by setting up my tests like the following, everything is working splendidly on Node v14.15.0 and "pg-mem": "^1.9.17"

import { Test, TestingModule } from '@nestjs/testing';
import { IMemoryDb, newDb } from 'pg-mem';
import { Connection, Repository } from 'typeorm';
import { UsersService } from './users.service';
import { User } from './users.entity';
import { usersFixtures } from './fixtures';

describe('UsersService', () => {
  let db: IMemoryDb;
  let got: Connection;
  let users: Repository<User>;
  let service: UsersService;

  beforeAll(async () => {
    //==== create a memory db
    db = newDb({
      autoCreateForeignKeyIndices: true,
    });

    //==== define current_database
    db.public.registerFunction({
      implementation: () => 'test',
      name: 'current_database',
    });

    //==== create a Typeorm connection
    got = await db.adapters.createTypeormConnection({
      type: 'postgres',
      entities: [User],
    });
    //==== create tables
    await got.synchronize();
    users = got.getRepository(User);

    //==== create entities
    for (const user of usersFixtures()) {
      const u = users.create(user);
      await users.save(u);
    }
  });

  afterAll(async () => {
    await got.close();
  });

  const mockFindOne = jest.fn((id) => users.findOne(id));

  const fakeUserService: Partial<UsersService> = {
    findOne: mockFindOne,
  };

  beforeEach(async () => {
    const module: TestingModule = await Test.createTestingModule({
      providers: [{ provide: UsersService, useValue: fakeUserService }],
    }).compile();

    service = module.get<UsersService>(UsersService);
  });

  afterEach(() => {
    mockFindOne.mockClear();
  });

  it('should be defined', () => {
    expect(service).toBeDefined();
  });

  describe('find', () => {
    it('should find one', async () => {
      const user = await service.findOne(1);

      expect(user).toMatchObject({
        email: 'a',
        password: 'b',
      });

      const user2 = await service.findOne(2);
      expect(user2).toMatchObject({
        email: 'bono',
        password: 'u2sux',
      });
      expect(mockFindOne).toBeCalledTimes(2);
    });
  });
});

1reaction
adolfo-fcommented, Aug 18, 2021

+1 I’m seeing exactly the same issue but updating to the latest node did not help. I get the error when running the example here https://github.com/oguimbal/pg-mem/blob/master/samples/typeorm/simple.ts. Thanks a lot.

Read more comments on GitHub >

github_iconTop Results From Across the Web

How to solve "Query failed" error in drush sql-sync output?
I had the same error "Query failed" using drush sql-sync. Finally I found a solution. Make sure your database user privileges include LOCK...
Read more >
Windows Time service won't synchronize - Microsoft Q&A
Everytime we try to make a w32tm /resync, we have this error : "The computer did not resync because no time data was...
Read more >
Getting 'Query failed' while executing blt:drupal:sync:db ...
I want to... sync local database with the remote It's not working because... Executing blt:drupal:sync:db command results in Query failed error.
Read more >
Error while performing a subscription re-sync: Failed to ... - Plesk
Resolution · 1. Log into the destination server · 2. Navigate to Tools & Settings > Migration & Transfer Manager and select the...
Read more >
SQL Database Synchronization Failure Alert - Forum
If a database on one server fails or goes offline and is unable to sync to the ... reply.. i tried the query...
Read more >

github_iconTop Related Medium Post

No results found

github_iconTop Related StackOverflow Question

No results found

github_iconTroubleshoot Live Code

Lightrun enables developers to add logs, metrics and snapshots to live code - no restarts or redeploys required.
Start Free

github_iconTop Related Reddit Thread

No results found

github_iconTop Related Hackernoon Post

No results found

github_iconTop Related Tweet

No results found

github_iconTop Related Dev.to Post

No results found

github_iconTop Related Hashnode Post

No results found