Skip to content
Merged
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
2 changes: 2 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,8 @@ The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.1.0/),
and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0.html).

## [Unreleased]
### Changed
- Update postgraphile dependencies to beta.48 (#23)

## [0.2.2] - 2025-05-21
### Fixed
Expand Down
4 changes: 2 additions & 2 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -20,13 +20,13 @@
"prepare": "husky"
},
"dependencies": {
"@graphile/simplify-inflection": "^8.0.0-beta.5",
"@graphile/simplify-inflection": "^8.0.0-beta.8",
"@subql/utils": "^2.14.0",
"@types/yargs": "^17.0.33",
"dotenv": "^16.4.5",
"eslint": "^8.8.0",
"express": "^4.21.1",
"postgraphile": "^5.0.0-beta.28",
"postgraphile": "^5.0.0-beta.48",
"yargs": "latest"
},
"devDependencies": {
Expand Down
2 changes: 1 addition & 1 deletion src/config/graphile.config.ts
Original file line number Diff line number Diff line change
Expand Up @@ -38,7 +38,7 @@ export function genPreset(args: ArgsInterface): GraphileConfig.Preset {

const SchemaSmartTagsPlugin = CreateSchemaSmartTagsPlugin(pgSchema);
const metadataPlugin = CreateMetadataPlugin(pgSchema);
const subqueryMetadataPlugin = CreateSubqueryMetadataPlugin(pgSchema, args);
const subqueryMetadataPlugin = CreateSubqueryMetadataPlugin(pgSchema);
const preset: GraphileConfig.Preset = {
extends: [PostGraphileAmberPreset, PgSimplifyInflectionPreset],
grafserv: {
Expand Down
27 changes: 12 additions & 15 deletions src/plugins/GetMetadataPlugin.ts
Original file line number Diff line number Diff line change
@@ -1,8 +1,8 @@
// Copyright 2020-2024 SubQuery Pte Ltd authors & contributors
// SPDX-License-Identifier: GPL-3.0

import { makeExtendSchemaPlugin, gql } from 'graphile-utils';
import { withPgClientTransaction } from 'postgraphile/@dataplan/pg';
import { gql, extendSchema } from 'graphile-utils';
import { loadOneWithPgClient } from 'postgraphile/@dataplan/pg';

const METADATA_TYPES = {
deployments: 'string',
Expand All @@ -27,8 +27,8 @@ type MetaType = number | string | boolean | object;

type MetaEntry = { key: string; value: MetaType };

export function CreateMetadataPlugin(schemaName: string) {
return makeExtendSchemaPlugin((build) => {
export function CreateMetadataPlugin(schemaName: string): GraphileConfig.Plugin {
return extendSchema((build) => {
// TODO Only handled the single-chain scenario, multi-chains may have unexpected results.
const metadata = build.input.pgRegistry.pgResources._metadata;

Expand All @@ -49,14 +49,12 @@ export function CreateMetadataPlugin(schemaName: string) {
_meta: MetadataPayload
}
`,
plans: {
objects: {
Query: {
_meta() {
const $executorContext = metadata.executor.context();
const $metadataResult = withPgClientTransaction(
metadata.executor,
$executorContext,
async (client, data) => {
plans: {
_meta() {
const $executorContext = metadata.executor.context();
return loadOneWithPgClient(metadata.executor, $executorContext, async (client) => {
const { rows } = await client.query<MetaEntry>({
text: `select * from "${schemaName}"."_metadata" WHERE key = ANY ($1)`,
values: [METADATA_KEYS],
Expand Down Expand Up @@ -85,10 +83,9 @@ export function CreateMetadataPlugin(schemaName: string) {
result.block.number = Number(row.value);
}
}
return result;
}
);
return $metadataResult;
return [result];
});
},
},
},
},
Expand Down
155 changes: 77 additions & 78 deletions src/plugins/GetSubqueryMetadataPlugin.ts
Original file line number Diff line number Diff line change
Expand Up @@ -8,10 +8,9 @@
MULTI_METADATA_REGEX,
TableEstimate,
} from '@subql/utils';
import { makeExtendSchemaPlugin, gql, ExtensionDefinition } from 'graphile-utils';
import { PgClient, withPgClientTransaction } from 'postgraphile/@dataplan/pg';
import { constant } from 'postgraphile/grafast';
import { ArgsInterface } from '../config/yargs';
import { gql, ExtensionDefinition, extendSchema } from 'graphile-utils';
import { loadOneWithPgClient, PgClient } from 'postgraphile/@dataplan/pg';
import { constant, FieldArgs, Step } from 'postgraphile/grafast';

const extensionsTypeDefs: ExtensionDefinition['typeDefs'] = gql`
type TableEstimate {
Expand Down Expand Up @@ -56,7 +55,7 @@
nodes?: Partial<MetaData>[];
};

const { version: packageVersion } = require('../../package.json');

Check warning on line 58 in src/plugins/GetSubqueryMetadataPlugin.ts

View workflow job for this annotation

GitHub Actions / code-style

Require statement not part of import statement
const META_JSON_FIELDS = ['deployments'];

function matchMetadataTableName(name: string): boolean {
Expand All @@ -66,17 +65,17 @@
async function getTableEstimate(schemaName: string, pgClient: PgClient) {
const { rows } = await pgClient.query<TableEstimate>({
text: `select relname as table , reltuples::bigint as estimate from pg_class
where
where
relnamespace in (select oid from pg_namespace where nspname = $1)
and
and
relname in (select table_name from information_schema.tables where table_schema = $1)`,
values: [schemaName],
});
return rows;
}

export function CreateSubqueryMetadataPlugin(schemaName: string, args: ArgsInterface): GraphileConfig.Plugin {
return makeExtendSchemaPlugin((build) => {
export function CreateSubqueryMetadataPlugin(schemaName: string): GraphileConfig.Plugin {
return extendSchema((build) => {
// Find all metadata table
const pgResources = build.input.pgRegistry.pgResources;
const metadataTables = Object.keys(build.input.pgRegistry.pgResources).filter((tableName) =>
Expand All @@ -92,83 +91,83 @@

return {
typeDefs: extensionsTypeDefs,

plans: {
objects: {
Query: {
_metadata($parent, { $chainId }, ...args) {
const totalCountInput = $parent.get('totalCount');
if ($chainId === undefined) {
return;
}

const chainId = $chainId.eval();
const metadataTableName = chainId ? getMetadataTableName(chainId) : '_metadata';
const $metadata = metadataPgResource[metadataTableName];
if (!$metadata) throw new Error(`Not Found Metadata, chainId: ${chainId}`);
const $metadataResult = withPgClientTransaction(
$metadata.executor,
$chainId,
async (pgClient, input): Promise<Partial<MetaData>> => {
const rowCountEstimate = await getTableEstimate(schemaName, pgClient);
const { rows } = await pgClient.query<MetaEntry>({
text: `select value, key from "${schemaName}"."${metadataTableName}"`,
});
const result: Record<string, unknown> = {};
rows.forEach((item) => {
if (META_JSON_FIELDS.includes(item.key)) {
result[item.key] = JSON.parse(item.value as string);
} else {
result[item.key] = item.value;
}
});

result.rowCountEstimate = rowCountEstimate;
result.queryNodeVersion = packageVersion;
result.queryNodeStyle = 'subgraph';
return result;
plans: {
_metadata($parent: Step, { $chainId }: FieldArgs) {
if ($chainId === undefined) {
return;
}
);

return $metadataResult;
},
_metadatas(_, $input) {
const totalCount = Object.keys(metadataPgResource).length;
const pgTable = metadataPgResource[metadataTables[0]];
if (!totalCount || !pgTable) {
return constant({ totalCount: 0, nodes: [] });
}
const chainId = ($chainId as any).eval();

Check warning on line 102 in src/plugins/GetSubqueryMetadataPlugin.ts

View workflow job for this annotation

GitHub Actions / code-style

Unexpected any. Specify a different type
const metadataTableName = chainId ? getMetadataTableName(chainId) : '_metadata';
const $metadata = metadataPgResource[metadataTableName];
if (!$metadata) throw new Error(`Not Found Metadata, chainId: ${chainId}`);

const $metadataResult = withPgClientTransaction(
pgTable.executor,
$input.getRaw(''),
async (pgClient, input): Promise<MetadatasConnection> => {
const rowCountEstimate = await getTableEstimate(schemaName, pgClient);
const nodes = await Promise.all(
metadataTables.map(async (tableName): Promise<Partial<MetaData>> => {
const { rows } = await pgClient.query({
text: `select value, key from "${schemaName}"."${tableName}"`,
});
const result: Record<string, unknown> = {};
rows.forEach((item: any) => {
if (META_JSON_FIELDS.includes(item.key)) {
result[item.key] = JSON.parse(item.value);
} else {
result[item.key] = item.value;
}
});
return loadOneWithPgClient(
$metadata.executor,
$chainId,
async (
pgClient /*, [chainId]: readonly string[] */
): Promise<[MetadatasConnection]> => {
const rowCountEstimate = await getTableEstimate(schemaName, pgClient);
const { rows } = await pgClient.query<MetaEntry>({
text: `select value, key from "${schemaName}"."${metadataTableName}"`,
});
const result: Record<string, unknown> = {};
rows.forEach((item) => {
if (META_JSON_FIELDS.includes(item.key)) {
result[item.key] = JSON.parse(item.value as string);
} else {
result[item.key] = item.value;
}
});

result.rowCountEstimate = rowCountEstimate;
result.queryNodeVersion = packageVersion;
result.queryNodeStyle = 'subgraph';
return result;
})
);

return { totalCount, nodes };
result.rowCountEstimate = rowCountEstimate;
result.queryNodeVersion = packageVersion;
result.queryNodeStyle = 'subgraph';
return [result];
}
);
},
// NOTE there are no tests for this
_metadatas(_: Step, $input: FieldArgs) {
const totalCount = Object.keys(metadataPgResource).length;
const pgTable = metadataPgResource[metadataTables[0]];
if (!totalCount || !pgTable) {
return constant({ totalCount: 0, nodes: [] });
}
);

return $metadataResult;
return loadOneWithPgClient(
pgTable.executor,
$input.getRaw(''),
async (pgClient): Promise<[MetadatasConnection]> => {
const rowCountEstimate = await getTableEstimate(schemaName, pgClient);
const nodes = await Promise.all(
metadataTables.map(async (tableName): Promise<Partial<MetaData>> => {
const { rows } = await pgClient.query<{ key: string; value: string }>({
text: `select value, key from "${schemaName}"."${tableName}"`,
});
const result: Record<string, unknown> = {};
rows.forEach((item) => {
if (META_JSON_FIELDS.includes(item.key)) {
result[item.key] = JSON.parse(item.value);
} else {
result[item.key] = item.value;
}
});

result.rowCountEstimate = rowCountEstimate;
result.queryNodeVersion = packageVersion;
result.queryNodeStyle = 'subgraph';
return result;
})
);

return [{ totalCount, nodes }];
}
);
},
},
},
},
Expand Down
2 changes: 1 addition & 1 deletion src/plugins/PgRowByVirtualIdPlugin.ts
Original file line number Diff line number Diff line change
Expand Up @@ -24,7 +24,7 @@
this: Inflection,
details: {
unique: PgResourceUnique;
resource: PgResource<any, any, any, any, any>;

Check warning on line 27 in src/plugins/PgRowByVirtualIdPlugin.ts

View workflow job for this annotation

GitHub Actions / code-style

Unexpected any. Specify a different type

Check warning on line 27 in src/plugins/PgRowByVirtualIdPlugin.ts

View workflow job for this annotation

GitHub Actions / code-style

Unexpected any. Specify a different type

Check warning on line 27 in src/plugins/PgRowByVirtualIdPlugin.ts

View workflow job for this annotation

GitHub Actions / code-style

Unexpected any. Specify a different type

Check warning on line 27 in src/plugins/PgRowByVirtualIdPlugin.ts

View workflow job for this annotation

GitHub Actions / code-style

Unexpected any. Specify a different type

Check warning on line 27 in src/plugins/PgRowByVirtualIdPlugin.ts

View workflow job for this annotation

GitHub Actions / code-style

Unexpected any. Specify a different type
}
): string;
}
Expand Down Expand Up @@ -163,7 +163,7 @@
function plan(_$root: any, args: FieldArgs) {
const spec = Object.create(null);
for (const attributeName in detailsByAttributeName) {
spec[attributeName] = args.get(
spec[attributeName] = args.getRaw(
detailsByAttributeName[attributeName].graphqlName
);
}
Expand Down
26 changes: 12 additions & 14 deletions src/plugins/filter/ArgFilterAttributesPlugin.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,8 +2,8 @@
// SPDX-License-Identifier: GPL-3.0

// refer https://github.com/graphile-contrib/postgraphile-plugin-connection-filter/blob/375f125/src/PgConnectionArgFilterAttributesPlugin.ts
import type { PgConditionStep } from '@dataplan/pg';
import { getFieldDefine, getSupportOperators, Operators } from './utils';
import type { PgCondition } from '@dataplan/pg';
import { getFieldDefine, getSupportOperators, isEmpty, Operators } from './utils';

export const ArgFilterAttributesPlugin: GraphileConfig.Plugin = {
name: 'ArgFilterAttributesPlugin',
Expand Down Expand Up @@ -56,23 +56,21 @@ export const ArgFilterAttributesPlugin: GraphileConfig.Plugin = {
{
type: fieldDefine.type,
description: 'filter condition field',
inputPlan: EXPORTABLE(
(escapeLikeWildcards) => (input) => {
return `%${escapeLikeWildcards(input)}%` as any;
},
[escapeLikeWildcards]
),
// TODO unable to find migration for this
// inputPlan: EXPORTABLE(
// (escapeLikeWildcards) => (input: unknown) => {
// return `%${escapeLikeWildcards(input)}%` as any;
// },
// [escapeLikeWildcards]
// ),
// eslint-disable-next-line complexity
applyPlan: EXPORTABLE(
apply: EXPORTABLE(
() =>
/* eslint-disable complexity */
function ($where: PgConditionStep<any>, fieldArgs) {
const $input = fieldArgs.getRaw();
if ($input.evalIs(undefined)) {
function ($where: PgCondition<any>, inputValue: any) {
if (isEmpty(inputValue)) {
return;
}

let inputValue = $input.eval();
switch (operator) {
case Operators.CONTAINS:
case Operators.NOT_CONTAINS:
Expand Down
Loading
Loading