Skip to content

Commit

Permalink
fix: apply potential dedupe alias on normalized query also on pk filter
Browse files Browse the repository at this point in the history
  • Loading branch information
psteinroe committed Mar 12, 2024
1 parent 45ae9d2 commit 819bfb5
Show file tree
Hide file tree
Showing 5 changed files with 86 additions and 6 deletions.
5 changes: 5 additions & 0 deletions .changeset/calm-mirrors-study.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
---
"@supabase-cache-helpers/postgrest-core": patch
---

fix: apply dedupe aliased to pk filters if there are any
35 changes: 35 additions & 0 deletions packages/postgrest-core/__tests__/delete-fetcher.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@ import { createClient, SupabaseClient } from '@supabase/supabase-js';
import { Database } from './database.types';
import { buildDeleteFetcher } from '../src/delete-fetcher';
import './utils';
import { PostgrestParser } from '../dist';

Check warning on line 6 in packages/postgrest-core/__tests__/delete-fetcher.spec.ts

View workflow job for this annotation

GitHub Actions / ESLint Report Analysis

packages/postgrest-core/__tests__/delete-fetcher.spec.ts#L6

[import/order] `../dist` import should occur before import of `../src/delete-fetcher`

Check warning on line 6 in packages/postgrest-core/__tests__/delete-fetcher.spec.ts

View workflow job for this annotation

GitHub Actions / ESLint Report Analysis

packages/postgrest-core/__tests__/delete-fetcher.spec.ts#L6

[import/order] `../dist` import should occur before import of `../src/delete-fetcher`

Check warning on line 6 in packages/postgrest-core/__tests__/delete-fetcher.spec.ts

View workflow job for this annotation

GitHub Actions / ESLint Report Analysis

packages/postgrest-core/__tests__/delete-fetcher.spec.ts#L6

[import/order] `../dist` import should occur before import of `../src/delete-fetcher`

const TEST_PREFIX = 'postgrest-fetcher-delete-';

Expand Down Expand Up @@ -139,4 +140,38 @@ describe('delete', () => {

expect(data).toEqual([]);
});

it('should use alias if there is one on the pks', async () => {
const { data: contact } = await client
.from('contact')
.insert({ username: `${testRunPrefix}-test`, ticket_number: 1234 })
.select('id')
.throwOnError()
.single();
expect(contact?.id).toBeDefined();

const q = client
.from('contact')
.select('test:id,username')
.eq('test', contact!.id);

const result = await buildDeleteFetcher(client.from('contact'), ['id'], {
query: 'ticket_number',
queriesForTable: () => [new PostgrestParser(q)],
})([
{
id: contact?.id,
},
]);
expect(result).toEqual([
{
normalizedData: {
id: contact?.id,
ticket_number: 1234,
username: `${testRunPrefix}-test`,
},
userQueryData: { ticket_number: 1234 },
},
]);
});
});
30 changes: 30 additions & 0 deletions packages/postgrest-core/__tests__/update-fetcher.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@ import { createClient, SupabaseClient } from '@supabase/supabase-js';
import { Database } from './database.types';

Check warning on line 3 in packages/postgrest-core/__tests__/update-fetcher.spec.ts

View workflow job for this annotation

GitHub Actions / ESLint Report Analysis

packages/postgrest-core/__tests__/update-fetcher.spec.ts#L3

[import/order] There should be no empty line within import group

Check warning on line 3 in packages/postgrest-core/__tests__/update-fetcher.spec.ts

View workflow job for this annotation

GitHub Actions / ESLint Report Analysis

packages/postgrest-core/__tests__/update-fetcher.spec.ts#L3

[import/order] There should be no empty line within import group

Check warning on line 3 in packages/postgrest-core/__tests__/update-fetcher.spec.ts

View workflow job for this annotation

GitHub Actions / ESLint Report Analysis

packages/postgrest-core/__tests__/update-fetcher.spec.ts#L3

[import/order] There should be no empty line within import group
import './utils';

import { PostgrestParser } from '../dist';
import { buildUpdateFetcher } from '../src/update-fetcher';

const TEST_PREFIX = 'postgrest-fetcher-update-';
Expand Down Expand Up @@ -79,4 +80,33 @@ describe('update', () => {
},
});
});

it('should use alias if there is one on the pks', async () => {
const q = client
.from('contact')
.select('test:id,username')
.eq('test', contact!.id);

const updatedContact = await buildUpdateFetcher(
client.from('contact'),
['id'],
{ queriesForTable: () => [new PostgrestParser(q)] },
)({
id: contact?.id,
username: `${testRunPrefix}-username-4`,
});
expect(updatedContact).toEqual({
normalizedData: {
id: expect.anything(),
username: `${testRunPrefix}-username-4`,
},
});
const { data } = await client
.from('contact')
.select('*')
.eq('id', contact?.id ?? '')
.throwOnError()
.maybeSingle();
expect(data?.username).toEqual(`${testRunPrefix}-username-4`);
});
});
12 changes: 8 additions & 4 deletions packages/postgrest-core/src/delete-fetcher.ts
Original file line number Diff line number Diff line change
Expand Up @@ -42,10 +42,15 @@ export const buildDeleteFetcher =
): Promise<MutationFetcherResponse<R>[] | null> => {
let filterBuilder = qb.delete(opts);

const query = buildNormalizedQuery<Q>(opts);

const pkAlias = (path: string): string =>
query?.paths.find((p) => p.path === path)?.alias || path;

if (primaryKeys.length === 1) {
const primaryKey = primaryKeys[0];
const primaryKey = primaryKeys[0] as string;
filterBuilder.in(
primaryKey as string,
pkAlias(primaryKey),
input.map((i) => {
const v = i[primaryKey];
if (!v) {
Expand All @@ -68,7 +73,7 @@ export const buildDeleteFetcher =
`Missing value for primary key ${c as string}`,
);
}
return `${c as string}.eq.${v}`;
return `${pkAlias(c as string)}.eq.${v}`;
})})`,
)
.join(','),
Expand All @@ -84,7 +89,6 @@ export const buildDeleteFetcher =
}, {} as R),
);

const query = buildNormalizedQuery<Q>(opts);
if (query) {
const { selectQuery, userQueryPaths, paths } = query;
// make sure that primary keys are included in the select query
Expand Down
10 changes: 8 additions & 2 deletions packages/postgrest-core/src/update-fetcher.ts
Original file line number Diff line number Diff line change
Expand Up @@ -41,13 +41,19 @@ export const buildUpdateFetcher =
input: Partial<T['Row']>,
): Promise<MutationFetcherResponse<R> | null> => {
let filterBuilder = qb.update(input as any, opts); // todo fix type;

const query = buildNormalizedQuery<Q>(opts);

const pkAlias = (path: string): string =>
query?.paths.find((p) => p.path === path)?.alias || path;

for (const key of primaryKeys) {
const value = input[key];
if (!value)
throw new Error(`Missing value for primary key ${String(key)}`);
filterBuilder = filterBuilder.eq(key as string, value);
filterBuilder = filterBuilder.eq(pkAlias(key as string), value);
}
const query = buildNormalizedQuery<Q>(opts);

if (query) {
const { selectQuery, userQueryPaths, paths } = query;
const { data } = await filterBuilder
Expand Down

0 comments on commit 819bfb5

Please sign in to comment.