felixmosh / knex-mock-client

A mock client for knex which allows you to write unit tests with DB interactions

Geek Repo:Geek Repo

Github PK Tool:Github PK Tool

Doesn't support onConflict

chrisharrison opened this issue · comments

Given this code:

describe("on conflict", () => {
  const mockedKnex = knex({ client: MockClient, dialect: "pg" });
  let tracker: Tracker;

  beforeAll(() => {
    tracker = getTracker();
  });

  afterEach(() => {
    tracker.reset();
  });

  test("it mocks correct on conflict SQL", async () => {
    await knex("a_table")
      .insert({id: 1234, created_at: "2022-05-10", updated_at: "2022-05-10"})
      .onConflict("id")
      .merge(["id", "created_at"]);
  });

  console.log(tracker.history.insert);
});

The SQL logged is:
insert into "a_table" ("created_at", "id", "updated_at") values (?, ?, ?)

It should be something along the lines of:
insert into "a_table" ("created_at", "id", "updated_at") values (?, ?, ?) on conflict ("id") do update set "id" = ? "updated_at" = ?

Thank you for submitting this issue, I'll review it asap.

I've tested it, and it works for me.
This is what I get

[
  {
    method: 'insert',
    options: {},
    timeout: false,
    cancelOnTimeout: false,
    bindings: ['2022-05-10', 1234, '2022-05-10'],
    __knexQueryUid: 'Aq0oFojeAAX0hQJ6zb_r5',
    sql: 'insert into "table_name" ("created_at", "id", "updated_at") values (?, ?, ?) on conflict ("id") do update set "id" = excluded."id", "created_at" = excluded."created_at"',
    returning: undefined,
    queryContext: undefined,
  },
]

Check the test that I've added for onConflict.

Just a heads up I have exactly the same issue as @chrisharrison for an insert/on conflict/merge.

Just a heads up I have exactly the same issue as @chrisharrison for an insert/on conflict/merge.

Can you share a query?

const result = await this.knex
  .insert({
    id: user.id,
    name: user.name,
  })
  .into("user")
  .onConflict("id")
  .merge(["name"])
  .returning([
    "id",
    "name",
  ]);

I can see that the query works correctly in production but the mock only produces insert ... values ..., without on conflict ....

Did you checked my comment link?
You need to specify the dialect since onConflict is relevant only to postgress.
Hope this solves your issue.

My bad, I missed that you had specified the dialect. Thanks for your help 😄