Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
23 changes: 23 additions & 0 deletions graphile/graphile-search-plugin/LICENSE
Original file line number Diff line number Diff line change
@@ -0,0 +1,23 @@
The MIT License (MIT)

Copyright (c) 2025 Dan Lynch <pyramation@gmail.com>
Copyright (c) 2025 Constructive <developers@constructive.io>
Copyright (c) 2020-present, Interweb, Inc.

Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
81 changes: 81 additions & 0 deletions graphile/graphile-search-plugin/README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,81 @@
# graphile-search-plugin

<p align="center" width="100%">
<img height="250" src="https://raw.githubusercontent.com/constructive-io/constructive/refs/heads/main/assets/outline-logo.svg" />
</p>

<p align="center" width="100%">
<a href="https://github.com/constructive-io/constructive/actions/workflows/run-tests.yaml">
<img height="20" src="https://github.com/constructive-io/constructive/actions/workflows/run-tests.yaml/badge.svg" />
</a>
<a href="https://github.com/constructive-io/constructive/blob/main/LICENSE">
<img height="20" src="https://img.shields.io/badge/license-MIT-blue.svg"/>
</a>
<a href="https://www.npmjs.com/package/graphile-search-plugin">
<img height="20" src="https://img.shields.io/github/package-json/v/constructive-io/constructive?filename=graphile%2Fgraphile-search-plugin%2Fpackage.json"/>
</a>
</p>

**`graphile-search-plugin`** enables auto-generated full-text search condition fields for all `tsvector` columns in PostGraphile v5 schemas.

## Installation

```sh
npm install graphile-search-plugin
```

## Features

- Adds full-text search condition fields for `tsvector` columns
- Uses `websearch_to_tsquery` for natural search syntax
- Automatic `ORDER BY ts_rank(column, tsquery) DESC` relevance ordering (matching V4 behavior)
- Cursor-based pagination remains stable — PostGraphile re-appends unique key columns after the relevance sort
- Works with PostGraphile v5 preset/plugin pipeline

## Usage

### With Preset (Recommended)

```typescript
import { PgSearchPreset } from 'graphile-search-plugin';

const preset = {
extends: [
// ... your other presets
PgSearchPreset({ pgSearchPrefix: 'fullText' }),
],
};
```

### With Plugin Directly

```typescript
import { PgSearchPlugin } from 'graphile-search-plugin';

const preset = {
plugins: [
PgSearchPlugin({ pgSearchPrefix: 'fullText' }),
],
};
```

### GraphQL Query

```graphql
query SearchGoals($search: String!) {
goals(condition: { fullTextTsv: $search }) {
nodes {
id
title
description
}
}
}
```

## Testing

```sh
# requires a local Postgres available (defaults to postgres/password@localhost:5432)
pnpm --filter graphile-search-plugin test
```
Original file line number Diff line number Diff line change
@@ -0,0 +1,39 @@
// Jest Snapshot v1, https://jestjs.io/docs/snapshot-testing

exports[`PgSearchPlugin condition-based search on stsv column returns only title-matched rows for fullTextStsv condition 1`] = `
{
"allGoals": {
"nodes": [
{
"description": "Second in years female given. Us firmament. She'd kind there let moved thing evening saying set whales a fowl heaven.",
"rowId": 6,
"title": "green fowl",
},
],
},
}
`;

exports[`PgSearchPlugin condition-based search on tsv column returns matching rows ordered by relevance (ts_rank DESC) 1`] = `
{
"allGoals": {
"nodes": [
{
"description": "Second in years female given. Us firmament. She'd kind there let moved thing evening saying set whales a fowl heaven.",
"rowId": 6,
"title": "green fowl",
},
{
"description": "Appear evening that gathered saying. Sea subdue so fill stars. Bring is man divided behold fish their. Also won't fowl.",
"rowId": 2,
"title": "evenings",
},
{
"description": "Heaven. Tree creeping was. Gathered living dominion us likeness first subdue fill. Fowl him moveth fly also the is created.",
"rowId": 3,
"title": "heaven",
},
],
},
}
`;
180 changes: 180 additions & 0 deletions graphile/graphile-search-plugin/__tests__/plugin.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,180 @@
import { join } from 'path';
import { getConnections, seed, snapshot } from 'graphile-test';
import type { GraphQLResponse } from 'graphile-test';
import type { PgTestClient } from 'pgsql-test';
import { PgSearchPreset } from '../src';

const SCHEMA = 'app_public';
const sqlFile = (f: string) => join(__dirname, '../sql', f);

interface GoalsResult {
allGoals: {
nodes: Array<{
rowId: number;
title: string;
description: string;
}>;
};
}

type QueryFn = <TResult = unknown>(
query: string,
variables?: Record<string, unknown>
) => Promise<GraphQLResponse<TResult>>;

describe('PgSearchPlugin', () => {
let db: PgTestClient;
let teardown: () => Promise<void>;
let query: QueryFn;

beforeAll(async () => {
const testPreset = {
extends: [
PgSearchPreset({ pgSearchPrefix: 'fullText' }),
],
};

const connections = await getConnections(
{
schemas: [SCHEMA],
preset: testPreset,
useRoot: true,
},
[seed.sqlfile([sqlFile('test.sql')])]
);

db = connections.db;
teardown = connections.teardown;
query = connections.query;

// Start a transaction for savepoint-based test isolation
await db.client.query('BEGIN');
});

afterAll(async () => {
if (db) {
try {
await db.client.query('ROLLBACK');
} catch {
// Ignore rollback errors
}
}

if (teardown) {
await teardown();
}
});

beforeEach(async () => {
await db.beforeEach();
});

afterEach(async () => {
await db.afterEach();
});

describe('condition-based search on tsv column', () => {
it('returns matching rows ordered by relevance (ts_rank DESC)', async () => {
const result = await query<GoalsResult>(
`
query GoalsSearchViaCondition($search: String!) {
allGoals(condition: { fullTextTsv: $search }) {
nodes {
rowId
title
description
}
}
}
`,
{ search: 'fowl' }
);

expect(result.errors).toBeUndefined();
expect(snapshot(result.data)).toMatchSnapshot();
});

it('returns no rows when search term does not match', async () => {
const result = await query<GoalsResult>(
`
query GoalsSearchViaCondition($search: String!) {
allGoals(condition: { fullTextTsv: $search }) {
nodes {
rowId
title
}
}
}
`,
{ search: 'xylophone' }
);

expect(result.errors).toBeUndefined();
expect(result.data?.allGoals.nodes).toHaveLength(0);
});
});

describe('condition-based search on stsv column', () => {
it('returns only title-matched rows for fullTextStsv condition', async () => {
const result = await query<GoalsResult>(
`
query GoalsSearchViaCondition2($search: String!) {
allGoals(condition: { fullTextStsv: $search }) {
nodes {
rowId
title
description
}
}
}
`,
{ search: 'fowl' }
);

expect(result.errors).toBeUndefined();
expect(snapshot(result.data)).toMatchSnapshot();
});
});

describe('edge cases', () => {
it('handles empty search string gracefully', async () => {
const result = await query<GoalsResult>(
`
query GoalsSearchViaCondition($search: String!) {
allGoals(condition: { fullTextTsv: $search }) {
nodes {
rowId
title
}
}
}
`,
{ search: '' }
);

// Empty string may return all or no results depending on PostgreSQL behavior
expect(result.errors).toBeUndefined();
expect(result.data?.allGoals).toBeDefined();
});

it('works with multi-word search terms', async () => {
const result = await query<GoalsResult>(
`
query GoalsSearchViaCondition($search: String!) {
allGoals(condition: { fullTextTsv: $search }) {
nodes {
rowId
title
}
}
}
`,
{ search: 'green fowl' }
);

expect(result.errors).toBeUndefined();
expect(result.data?.allGoals).toBeDefined();
expect(result.data?.allGoals.nodes.length).toBeGreaterThan(0);
});
});
});
18 changes: 18 additions & 0 deletions graphile/graphile-search-plugin/jest.config.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,18 @@
/** @type {import('ts-jest').JestConfigWithTsJest} */
module.exports = {
preset: 'ts-jest',
testEnvironment: 'node',
transform: {
'^.+\\.tsx?$': [
'ts-jest',
{
babelConfig: false,
tsconfig: 'tsconfig.json'
}
]
},
transformIgnorePatterns: [`/node_modules/*`],
testRegex: '(/__tests__/.*|(\\.|/)(test|spec))\\.(jsx?|tsx?)$',
moduleFileExtensions: ['ts', 'tsx', 'js', 'jsx', 'json', 'node'],
modulePathIgnorePatterns: ['dist/*']
};
Loading