graphile-many-to-many 1.0.3

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/LICENSE ADDED
@@ -0,0 +1,23 @@
1
+ The MIT License (MIT)
2
+
3
+ Copyright (c) 2025 Dan Lynch <pyramation@gmail.com>
4
+ Copyright (c) 2025 Constructive <developers@constructive.io>
5
+ Copyright (c) 2020-present, Interweb, Inc.
6
+
7
+ Permission is hereby granted, free of charge, to any person obtaining a copy
8
+ of this software and associated documentation files (the "Software"), to deal
9
+ in the Software without restriction, including without limitation the rights
10
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
11
+ copies of the Software, and to permit persons to whom the Software is
12
+ furnished to do so, subject to the following conditions:
13
+
14
+ The above copyright notice and this permission notice shall be included in all
15
+ copies or substantial portions of the Software.
16
+
17
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
18
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
19
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
20
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
21
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
22
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
23
+ SOFTWARE.
@@ -0,0 +1,3 @@
1
+ import type { Plugin } from 'graphile-build';
2
+ declare const PgManyToManyRelationEdgeColumnsPlugin: Plugin;
3
+ export default PgManyToManyRelationEdgeColumnsPlugin;
@@ -0,0 +1,60 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ const PgManyToManyRelationEdgeColumnsPlugin = (builder) => {
4
+ builder.hook('GraphQLObjectType:fields', (fields, build, context) => {
5
+ const { extend, pgGetGqlTypeByTypeIdAndModifier, pgSql: sql, pg2gql, graphql: { GraphQLString, GraphQLNonNull }, pgColumnFilter, inflection, pgOmit: omit, pgGetSelectValueForFieldAndTypeAndModifier: getSelectValueForFieldAndTypeAndModifier, describePgEntity } = build;
6
+ const { scope: { isPgManyToManyEdgeType, pgManyToManyRelationship }, fieldWithHooks } = context;
7
+ const nullableIf = (condition, Type) => condition ? Type : new GraphQLNonNull(Type);
8
+ if (!isPgManyToManyEdgeType || !pgManyToManyRelationship) {
9
+ return fields;
10
+ }
11
+ const { leftKeyAttributes, junctionTable, junctionLeftKeyAttributes, junctionRightKeyAttributes, rightKeyAttributes, allowsMultipleEdgesToNode } = pgManyToManyRelationship;
12
+ if (allowsMultipleEdgesToNode) {
13
+ return fields;
14
+ }
15
+ return extend(fields, junctionTable.attributes.reduce((memo, attr) => {
16
+ if (!pgColumnFilter(attr, build, context))
17
+ return memo;
18
+ if (omit(attr, 'read'))
19
+ return memo;
20
+ // Skip left and right key attributes
21
+ if (junctionLeftKeyAttributes.map((a) => a.name).includes(attr.name))
22
+ return memo;
23
+ if (junctionRightKeyAttributes.map((a) => a.name).includes(attr.name))
24
+ return memo;
25
+ const fieldName = inflection.column(attr);
26
+ const ReturnType = pgGetGqlTypeByTypeIdAndModifier(attr.typeId, attr.typeModifier) || GraphQLString;
27
+ // Since we're ignoring multi-column keys, we can simplify here
28
+ const leftKeyAttribute = leftKeyAttributes[0];
29
+ const junctionLeftKeyAttribute = junctionLeftKeyAttributes[0];
30
+ const junctionRightKeyAttribute = junctionRightKeyAttributes[0];
31
+ const rightKeyAttribute = rightKeyAttributes[0];
32
+ const sqlSelectFrom = sql.fragment `select ${sql.identifier(attr.name)} from ${sql.identifier(junctionTable.namespace.name, junctionTable.name)}`;
33
+ const fieldConfig = fieldWithHooks(fieldName, (fieldContext) => {
34
+ const { type, typeModifier } = attr;
35
+ const { addDataGenerator } = fieldContext;
36
+ addDataGenerator((parsedResolveInfoFragment) => {
37
+ return {
38
+ pgQuery: (queryBuilder) => {
39
+ queryBuilder.select(getSelectValueForFieldAndTypeAndModifier(ReturnType, fieldContext, parsedResolveInfoFragment, sql.fragment `(${sqlSelectFrom} where ${sql.identifier(junctionRightKeyAttribute.name)} = ${queryBuilder.getTableAlias()}.${sql.identifier(rightKeyAttribute.name)} and ${sql.identifier(junctionLeftKeyAttribute.name)} = ${queryBuilder.parentQueryBuilder.parentQueryBuilder.getTableAlias()}.${sql.identifier(leftKeyAttribute.name)})`, type, typeModifier), fieldName);
40
+ }
41
+ };
42
+ });
43
+ return {
44
+ description: attr.description,
45
+ type: nullableIf(!attr.isNotNull && !attr.type.domainIsNotNull && !attr.tags.notNull, ReturnType),
46
+ resolve: (data) => {
47
+ return pg2gql(data[fieldName], attr.type);
48
+ }
49
+ };
50
+ }, {
51
+ isPgManyToManyRelationEdgeColumnField: true,
52
+ pgFieldIntrospection: attr
53
+ });
54
+ return extend(memo, {
55
+ [fieldName]: fieldConfig
56
+ }, `Adding field for ${describePgEntity(attr)}.`);
57
+ }, {}), `Adding columns to '${describePgEntity(junctionTable)}'`);
58
+ }, ['PgManyToManyRelationEdgeColumns']);
59
+ };
60
+ exports.default = PgManyToManyRelationEdgeColumnsPlugin;
@@ -0,0 +1,3 @@
1
+ import type { Plugin } from 'graphile-build';
2
+ declare const PgManyToManyRelationEdgeTablePlugin: Plugin;
3
+ export default PgManyToManyRelationEdgeTablePlugin;
@@ -0,0 +1,107 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ const PgManyToManyRelationEdgeTablePlugin = (builder, { pgSimpleCollections }) => {
4
+ builder.hook('GraphQLObjectType:fields', (fields, build, context) => {
5
+ const { extend, getTypeByName, pgGetGqlTypeByTypeIdAndModifier, graphql: { GraphQLNonNull, GraphQLList }, inflection, getSafeAliasFromResolveInfo, getSafeAliasFromAlias, pgQueryFromResolveData: queryFromResolveData, pgAddStartEndCursor: addStartEndCursor, pgSql: sql, describePgEntity } = build;
6
+ const { scope: { isPgManyToManyEdgeType, pgManyToManyRelationship }, fieldWithHooks, Self } = context;
7
+ if (!isPgManyToManyEdgeType || !pgManyToManyRelationship) {
8
+ return fields;
9
+ }
10
+ const { leftKeyAttributes, junctionLeftKeyAttributes, rightTable, rightKeyAttributes, junctionRightKeyAttributes, junctionTable, junctionRightConstraint, allowsMultipleEdgesToNode } = pgManyToManyRelationship;
11
+ if (!allowsMultipleEdgesToNode) {
12
+ return fields;
13
+ }
14
+ const JunctionTableType = pgGetGqlTypeByTypeIdAndModifier(junctionTable.type.id, null);
15
+ if (!JunctionTableType) {
16
+ throw new Error(`Could not determine type for table with id ${junctionTable.type.id}`);
17
+ }
18
+ const JunctionTableConnectionType = getTypeByName(inflection.connection(JunctionTableType.name));
19
+ const buildFields = (isConnection) => {
20
+ const fieldName = isConnection
21
+ ? inflection.manyRelationByKeys(junctionRightKeyAttributes, junctionTable, rightTable, junctionRightConstraint)
22
+ : inflection.manyRelationByKeysSimple(junctionRightKeyAttributes, junctionTable, rightTable, junctionRightConstraint);
23
+ const Type = isConnection ? JunctionTableConnectionType : JunctionTableType;
24
+ if (!Type) {
25
+ return undefined;
26
+ }
27
+ return {
28
+ [fieldName]: fieldWithHooks(fieldName, ({ getDataFromParsedResolveInfoFragment, addDataGenerator }) => {
29
+ const sqlFrom = sql.identifier(junctionTable.namespace.name, junctionTable.name);
30
+ const queryOptions = {
31
+ useAsterisk: junctionTable.canUseAsterisk,
32
+ withPagination: isConnection,
33
+ withPaginationAsFields: false,
34
+ asJsonAggregate: !isConnection
35
+ };
36
+ addDataGenerator((parsedResolveInfoFragment) => {
37
+ return {
38
+ pgQuery: (queryBuilder) => {
39
+ queryBuilder.select(() => {
40
+ const resolveData = getDataFromParsedResolveInfoFragment(parsedResolveInfoFragment, Type);
41
+ const junctionTableAlias = sql.identifier(Symbol());
42
+ const rightTableAlias = queryBuilder.getTableAlias();
43
+ const leftTableAlias = queryBuilder.parentQueryBuilder.parentQueryBuilder.getTableAlias();
44
+ const query = queryFromResolveData(sqlFrom, junctionTableAlias, resolveData, queryOptions, (innerQueryBuilder) => {
45
+ innerQueryBuilder.parentQueryBuilder = queryBuilder;
46
+ const junctionPrimaryKeyConstraint = junctionTable.primaryKeyConstraint;
47
+ const junctionPrimaryKeyAttributes = junctionPrimaryKeyConstraint && junctionPrimaryKeyConstraint.keyAttributes;
48
+ if (junctionPrimaryKeyAttributes) {
49
+ innerQueryBuilder.beforeLock('orderBy', () => {
50
+ // append order by primary key to the list of orders
51
+ if (!innerQueryBuilder.isOrderUnique(false)) {
52
+ innerQueryBuilder.data.cursorPrefix = ['primary_key_asc'];
53
+ junctionPrimaryKeyAttributes.forEach((attr) => {
54
+ innerQueryBuilder.orderBy(sql.fragment `${innerQueryBuilder.getTableAlias()}.${sql.identifier(attr.name)}`, true);
55
+ });
56
+ innerQueryBuilder.setOrderIsUnique();
57
+ }
58
+ });
59
+ }
60
+ junctionRightKeyAttributes.forEach((attr, i) => {
61
+ innerQueryBuilder.where(sql.fragment `${junctionTableAlias}.${sql.identifier(attr.name)} = ${rightTableAlias}.${sql.identifier(rightKeyAttributes[i].name)}`);
62
+ });
63
+ junctionLeftKeyAttributes.forEach((attr, i) => {
64
+ innerQueryBuilder.where(sql.fragment `${junctionTableAlias}.${sql.identifier(attr.name)} = ${leftTableAlias}.${sql.identifier(leftKeyAttributes[i].name)}`);
65
+ });
66
+ }, queryBuilder.context, queryBuilder.rootValue);
67
+ return sql.fragment `(${query})`;
68
+ }, getSafeAliasFromAlias(parsedResolveInfoFragment.alias));
69
+ }
70
+ };
71
+ });
72
+ return {
73
+ description: `Reads and enables pagination through a set of \`${JunctionTableType.name}\`.`,
74
+ type: isConnection
75
+ ? new GraphQLNonNull(JunctionTableConnectionType)
76
+ : new GraphQLNonNull(new GraphQLList(new GraphQLNonNull(JunctionTableType))),
77
+ args: {},
78
+ resolve: (data, _args, _context, resolveInfo) => {
79
+ const safeAlias = getSafeAliasFromResolveInfo(resolveInfo);
80
+ if (isConnection) {
81
+ return addStartEndCursor(data[safeAlias]);
82
+ }
83
+ return data[safeAlias];
84
+ }
85
+ };
86
+ }, {
87
+ isPgFieldConnection: isConnection,
88
+ isPgFieldSimpleCollection: !isConnection,
89
+ isPgManyToManyRelationEdgeTableField: true,
90
+ pgFieldIntrospection: junctionTable
91
+ })
92
+ };
93
+ };
94
+ const simpleCollections = junctionRightConstraint.tags.simpleCollections ||
95
+ junctionTable.tags.simpleCollections ||
96
+ pgSimpleCollections;
97
+ const hasConnections = simpleCollections !== 'only';
98
+ const hasSimpleCollections = simpleCollections === 'only' || simpleCollections === 'both';
99
+ const connectionFields = hasConnections ? buildFields(true) : undefined;
100
+ const simpleCollectionFields = hasSimpleCollections ? buildFields(false) : undefined;
101
+ return extend(fields, {
102
+ ...(connectionFields || {}),
103
+ ...(simpleCollectionFields || {})
104
+ }, `Many-to-many relation edge table (${hasConnections ? 'connection' : 'simple collection'}) on ${Self.name} type for ${describePgEntity(junctionRightConstraint)}.`);
105
+ });
106
+ };
107
+ exports.default = PgManyToManyRelationEdgeTablePlugin;
@@ -0,0 +1,3 @@
1
+ import type { Plugin } from 'graphile-build';
2
+ declare const PgManyToManyRelationInflectionPlugin: Plugin;
3
+ export default PgManyToManyRelationInflectionPlugin;
@@ -0,0 +1,41 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ const PgManyToManyRelationInflectionPlugin = (builder) => {
4
+ builder.hook('inflection', (inflection) => {
5
+ const manyToManyRelationByKeys = function manyToManyRelationByKeys(_leftKeyAttributes, junctionLeftKeyAttributes, junctionRightKeyAttributes, _rightKeyAttributes, junctionTable, rightTable, _junctionLeftConstraint, junctionRightConstraint) {
6
+ if (junctionRightConstraint.tags.manyToManyFieldName) {
7
+ return junctionRightConstraint.tags.manyToManyFieldName;
8
+ }
9
+ return this.camelCase(`${this.pluralize(this._singularizedTableName(rightTable))}-by-${this._singularizedTableName(junctionTable)}-${[...junctionLeftKeyAttributes, ...junctionRightKeyAttributes]
10
+ .map((attr) => this.column(attr))
11
+ .join('-and-')}`);
12
+ };
13
+ const manyToManyRelationByKeysSimple = function manyToManyRelationByKeysSimple(_leftKeyAttributes, junctionLeftKeyAttributes, junctionRightKeyAttributes, _rightKeyAttributes, junctionTable, rightTable, _junctionLeftConstraint, junctionRightConstraint) {
14
+ if (junctionRightConstraint.tags.manyToManySimpleFieldName) {
15
+ return junctionRightConstraint.tags.manyToManySimpleFieldName;
16
+ }
17
+ return this.camelCase(`${this.pluralize(this._singularizedTableName(rightTable))}-by-${this._singularizedTableName(junctionTable)}-${[...junctionLeftKeyAttributes, ...junctionRightKeyAttributes]
18
+ .map((attr) => this.column(attr))
19
+ .join('-and-')}-list`);
20
+ };
21
+ const manyToManyRelationEdge = function manyToManyRelationEdge(leftKeyAttributes, junctionLeftKeyAttributes, junctionRightKeyAttributes, rightKeyAttributes, junctionTable, rightTable, junctionLeftConstraint, junctionRightConstraint, leftTableTypeName) {
22
+ const relationName = inflection.manyToManyRelationByKeys(leftKeyAttributes, junctionLeftKeyAttributes, junctionRightKeyAttributes, rightKeyAttributes, junctionTable, rightTable, junctionLeftConstraint, junctionRightConstraint);
23
+ return this.upperCamelCase(`${leftTableTypeName}-${relationName}-many-to-many-edge`);
24
+ };
25
+ const manyToManyRelationConnection = function manyToManyRelationConnection(leftKeyAttributes, junctionLeftKeyAttributes, junctionRightKeyAttributes, rightKeyAttributes, junctionTable, rightTable, junctionLeftConstraint, junctionRightConstraint, leftTableTypeName) {
26
+ const relationName = inflection.manyToManyRelationByKeys(leftKeyAttributes, junctionLeftKeyAttributes, junctionRightKeyAttributes, rightKeyAttributes, junctionTable, rightTable, junctionLeftConstraint, junctionRightConstraint, leftTableTypeName);
27
+ return this.upperCamelCase(`${leftTableTypeName}-${relationName}-many-to-many-connection`);
28
+ };
29
+ const manyToManyRelationSubqueryName = function manyToManyRelationSubqueryName(_leftKeyAttributes, _junctionLeftKeyAttributes, _junctionRightKeyAttributes, _rightKeyAttributes, junctionTable) {
30
+ return `many-to-many-subquery-by-${this._singularizedTableName(junctionTable)}`;
31
+ };
32
+ return Object.assign(inflection, {
33
+ manyToManyRelationByKeys,
34
+ manyToManyRelationByKeysSimple,
35
+ manyToManyRelationEdge,
36
+ manyToManyRelationConnection,
37
+ manyToManyRelationSubqueryName
38
+ });
39
+ });
40
+ };
41
+ exports.default = PgManyToManyRelationInflectionPlugin;
@@ -0,0 +1,3 @@
1
+ import type { Plugin } from 'graphile-build';
2
+ declare const PgManyToManyRelationPlugin: Plugin;
3
+ export default PgManyToManyRelationPlugin;
@@ -0,0 +1,114 @@
1
+ "use strict";
2
+ var __importDefault = (this && this.__importDefault) || function (mod) {
3
+ return (mod && mod.__esModule) ? mod : { "default": mod };
4
+ };
5
+ Object.defineProperty(exports, "__esModule", { value: true });
6
+ const createManyToManyConnectionType_1 = __importDefault(require("./createManyToManyConnectionType"));
7
+ const manyToManyRelationships_1 = __importDefault(require("./manyToManyRelationships"));
8
+ const PgManyToManyRelationPlugin = (builder, options = {}) => {
9
+ const { pgSimpleCollections } = options;
10
+ builder.hook('GraphQLObjectType:fields', (fields, build, context) => {
11
+ const { extend, pgGetGqlTypeByTypeIdAndModifier, pgSql: sql, getSafeAliasFromResolveInfo, getSafeAliasFromAlias, graphql: { GraphQLNonNull, GraphQLList }, inflection, pgQueryFromResolveData: queryFromResolveData, pgAddStartEndCursor: addStartEndCursor, describePgEntity } = build;
12
+ const { scope: { isPgRowType, pgIntrospection: leftTable }, fieldWithHooks, Self } = context;
13
+ if (!isPgRowType || !leftTable || leftTable.kind !== 'class') {
14
+ return fields;
15
+ }
16
+ const relationships = (0, manyToManyRelationships_1.default)(leftTable, build);
17
+ const relatedFields = relationships.reduce((memo, relationship) => {
18
+ const { leftKeyAttributes, junctionLeftKeyAttributes, junctionRightKeyAttributes, rightKeyAttributes, junctionTable, rightTable, junctionLeftConstraint, junctionRightConstraint } = relationship;
19
+ const RightTableType = pgGetGqlTypeByTypeIdAndModifier(rightTable.type.id, null);
20
+ if (!RightTableType) {
21
+ throw new Error(`Could not determine type for table with id ${rightTable.type.id}`);
22
+ }
23
+ const RightTableConnectionType = (0, createManyToManyConnectionType_1.default)(relationship, build, options, leftTable);
24
+ // Since we're ignoring multi-column keys, we can simplify here
25
+ const leftKeyAttribute = leftKeyAttributes[0];
26
+ const junctionLeftKeyAttribute = junctionLeftKeyAttributes[0];
27
+ const junctionRightKeyAttribute = junctionRightKeyAttributes[0];
28
+ const rightKeyAttribute = rightKeyAttributes[0];
29
+ let memoWithRelations = memo;
30
+ const makeFields = (isConnection) => {
31
+ const manyRelationFieldName = isConnection
32
+ ? inflection.manyToManyRelationByKeys(leftKeyAttributes, junctionLeftKeyAttributes, junctionRightKeyAttributes, rightKeyAttributes, junctionTable, rightTable, junctionLeftConstraint, junctionRightConstraint)
33
+ : inflection.manyToManyRelationByKeysSimple(leftKeyAttributes, junctionLeftKeyAttributes, junctionRightKeyAttributes, rightKeyAttributes, junctionTable, rightTable, junctionLeftConstraint, junctionRightConstraint);
34
+ memoWithRelations = extend(memoWithRelations, {
35
+ [manyRelationFieldName]: fieldWithHooks(manyRelationFieldName, ({ getDataFromParsedResolveInfoFragment, addDataGenerator }) => {
36
+ const sqlFrom = sql.identifier(rightTable.namespace.name, rightTable.name);
37
+ const queryOptions = {
38
+ useAsterisk: rightTable.canUseAsterisk,
39
+ withPagination: isConnection,
40
+ withPaginationAsFields: false,
41
+ asJsonAggregate: !isConnection
42
+ };
43
+ addDataGenerator((parsedResolveInfoFragment) => {
44
+ return {
45
+ pgQuery: (queryBuilder) => {
46
+ queryBuilder.select(() => {
47
+ const resolveData = getDataFromParsedResolveInfoFragment(parsedResolveInfoFragment, isConnection ? RightTableConnectionType : RightTableType);
48
+ const rightTableAlias = sql.identifier(Symbol());
49
+ const leftTableAlias = queryBuilder.getTableAlias();
50
+ const query = queryFromResolveData(sqlFrom, rightTableAlias, resolveData, queryOptions, (innerQueryBuilder) => {
51
+ innerQueryBuilder.parentQueryBuilder = queryBuilder;
52
+ const rightPrimaryKeyConstraint = rightTable.primaryKeyConstraint;
53
+ const rightPrimaryKeyAttributes = rightPrimaryKeyConstraint && rightPrimaryKeyConstraint.keyAttributes;
54
+ if (rightPrimaryKeyAttributes) {
55
+ innerQueryBuilder.beforeLock('orderBy', () => {
56
+ // append order by primary key to the list of orders
57
+ if (!innerQueryBuilder.isOrderUnique(false)) {
58
+ innerQueryBuilder.data.cursorPrefix = ['primary_key_asc'];
59
+ rightPrimaryKeyAttributes.forEach((attr) => {
60
+ innerQueryBuilder.orderBy(sql.fragment `${innerQueryBuilder.getTableAlias()}.${sql.identifier(attr.name)}`, true);
61
+ });
62
+ innerQueryBuilder.setOrderIsUnique();
63
+ }
64
+ });
65
+ }
66
+ const subqueryName = inflection.manyToManyRelationSubqueryName(leftKeyAttributes, junctionLeftKeyAttributes, junctionRightKeyAttributes, rightKeyAttributes, junctionTable, rightTable, junctionLeftConstraint, junctionRightConstraint);
67
+ const subqueryBuilder = innerQueryBuilder.buildNamedChildSelecting(subqueryName, sql.identifier(junctionTable.namespace.name, junctionTable.name), sql.identifier(junctionRightKeyAttribute.name));
68
+ subqueryBuilder.where(sql.fragment `${sql.identifier(junctionLeftKeyAttribute.name)} = ${leftTableAlias}.${sql.identifier(leftKeyAttribute.name)}`);
69
+ innerQueryBuilder.where(() => sql.fragment `${rightTableAlias}.${sql.identifier(rightKeyAttribute.name)} in (${subqueryBuilder.build()})`);
70
+ }, queryBuilder.context, queryBuilder.rootValue);
71
+ return sql.fragment `(${query})`;
72
+ }, getSafeAliasFromAlias(parsedResolveInfoFragment.alias));
73
+ }
74
+ };
75
+ });
76
+ return {
77
+ description: `Reads and enables pagination through a set of \`${RightTableType.name}\`.`,
78
+ type: isConnection
79
+ ? new GraphQLNonNull(RightTableConnectionType)
80
+ : new GraphQLNonNull(new GraphQLList(new GraphQLNonNull(RightTableType))),
81
+ args: {},
82
+ resolve: (data, _args, _context, resolveInfo) => {
83
+ const safeAlias = getSafeAliasFromResolveInfo(resolveInfo);
84
+ if (isConnection) {
85
+ return addStartEndCursor(data[safeAlias]);
86
+ }
87
+ return data[safeAlias];
88
+ }
89
+ };
90
+ }, {
91
+ isPgFieldConnection: isConnection,
92
+ isPgFieldSimpleCollection: !isConnection,
93
+ isPgManyToManyRelationField: true,
94
+ pgFieldIntrospection: rightTable
95
+ })
96
+ }, `Many-to-many relation field (${isConnection ? 'connection' : 'simple collection'}) on ${Self.name} type for ${describePgEntity(junctionLeftConstraint)} and ${describePgEntity(junctionRightConstraint)}.`);
97
+ };
98
+ const simpleCollections = junctionRightConstraint.tags.simpleCollections ||
99
+ rightTable.tags.simpleCollections ||
100
+ pgSimpleCollections;
101
+ const hasConnections = simpleCollections !== 'only';
102
+ const hasSimpleCollections = simpleCollections === 'only' || simpleCollections === 'both';
103
+ if (hasConnections) {
104
+ makeFields(true);
105
+ }
106
+ if (hasSimpleCollections) {
107
+ makeFields(false);
108
+ }
109
+ return memoWithRelations;
110
+ }, {});
111
+ return extend(fields, relatedFields, `Adding many-to-many relations for ${Self.name}`);
112
+ });
113
+ };
114
+ exports.default = PgManyToManyRelationPlugin;
package/README.md ADDED
@@ -0,0 +1,236 @@
1
+ # graphile-many-to-many
2
+
3
+ <p align="center" width="100%">
4
+ <img height="250" src="https://raw.githubusercontent.com/constructive-io/constructive/refs/heads/main/assets/outline-logo.svg" />
5
+ </p>
6
+
7
+ <p align="center" width="100%">
8
+ <a href="https://github.com/constructive-io/constructive/actions/workflows/run-tests.yaml">
9
+ <img height="20" src="https://github.com/constructive-io/constructive/actions/workflows/run-tests.yaml/badge.svg" />
10
+ </a>
11
+ <a href="https://github.com/constructive-io/constructive/blob/main/LICENSE">
12
+ <img height="20" src="https://img.shields.io/badge/license-MIT-blue.svg"/>
13
+ </a>
14
+ <a href="https://www.npmjs.com/package/graphile-many-to-many">
15
+ <img height="20" src="https://img.shields.io/github/package-json/v/launchql/launchql?filename=graphile%2Fgraphile-many-to-many%2Fpackage.json"/>
16
+ </a>
17
+ </p>
18
+
19
+ **`graphile-many-to-many`** adds connection fields for many-to-many relations in PostGraphile v4 / Graphile Engine schemas so join tables automatically expose relay-friendly collections. Requires `postgraphile@^4.5.0` or `graphile-build-pg@^4.5.0`.
20
+
21
+ ## 🚀 Installation
22
+
23
+ ```bash
24
+ pnpm add graphile-many-to-many
25
+ ```
26
+
27
+ ## ✨ Features
28
+
29
+ - Generates many-to-many connection and simple collection fields from junction tables
30
+ - Works with PostGraphile CLI and library usage
31
+ - Smart comments (`@omit manyToMany`) to suppress specific relations
32
+ - Configurable field names via inflectors or smart comments
33
+
34
+ ## 📦 Usage
35
+
36
+ Append the plugin and the fields will be added to your schema.
37
+
38
+ ### PostGraphile CLI
39
+
40
+ ```bash
41
+ pnpm add postgraphile graphile-many-to-many
42
+ npx postgraphile --append-plugins graphile-many-to-many
43
+ ```
44
+
45
+ ### Library
46
+
47
+ ```js
48
+ const express = require("express");
49
+ const { postgraphile } = require("postgraphile");
50
+ const PgManyToManyPlugin = require("graphile-many-to-many");
51
+
52
+ const app = express();
53
+
54
+ app.use(
55
+ postgraphile(process.env.DATABASE_URL, "app_public", {
56
+ appendPlugins: [PgManyToManyPlugin],
57
+ graphiql: true,
58
+ })
59
+ );
60
+
61
+ app.listen(5000);
62
+ ```
63
+
64
+ Example query:
65
+
66
+ ```graphql
67
+ {
68
+ allPeople {
69
+ nodes {
70
+ personName
71
+ teamsByTeamMemberPersonIdAndTeamId {
72
+ nodes {
73
+ teamName
74
+ }
75
+ }
76
+ }
77
+ }
78
+ }
79
+ ```
80
+
81
+ ## 🙅‍♀️ Excluding Fields
82
+
83
+ Use `@omit manyToMany` [smart comments](https://www.graphile.org/postgraphile/smart-comments/) on constraints or tables to prevent fields from being generated.
84
+
85
+ ```sql
86
+ -- omit a relation by constraint
87
+ comment on constraint qux_bar_id_fkey on p.qux is E'@omit manyToMany';
88
+
89
+ -- or omit the junction table entirely
90
+ comment on table p.corge is E'@omit manyToMany';
91
+ ```
92
+
93
+ ## 📝 Field Naming
94
+
95
+ Field names are verbose by default (e.g. `teamsByTeamMemberTeamId`) to avoid collisions. You can override them with an inflector plugin or smart comments.
96
+
97
+ ### Custom inflector
98
+
99
+ > Warning: Short names can collide when a junction table references the same target multiple times—customize accordingly.
100
+
101
+ ```js
102
+ const { makeAddInflectorsPlugin } = require("graphile-utils");
103
+
104
+ module.exports = makeAddInflectorsPlugin(
105
+ {
106
+ manyToManyRelationByKeys(
107
+ _leftKeyAttributes,
108
+ _junctionLeftKeyAttributes,
109
+ _junctionRightKeyAttributes,
110
+ _rightKeyAttributes,
111
+ _junctionTable,
112
+ rightTable,
113
+ _junctionLeftConstraint,
114
+ junctionRightConstraint
115
+ ) {
116
+ if (junctionRightConstraint.tags.manyToManyFieldName) {
117
+ return junctionRightConstraint.tags.manyToManyFieldName;
118
+ }
119
+ return this.camelCase(
120
+ `${this.pluralize(this._singularizedTableName(rightTable))}`
121
+ );
122
+ },
123
+ manyToManyRelationByKeysSimple(
124
+ _leftKeyAttributes,
125
+ _junctionLeftKeyAttributes,
126
+ _junctionRightKeyAttributes,
127
+ _rightKeyAttributes,
128
+ _junctionTable,
129
+ rightTable,
130
+ _junctionLeftConstraint,
131
+ junctionRightConstraint
132
+ ) {
133
+ if (junctionRightConstraint.tags.manyToManySimpleFieldName) {
134
+ return junctionRightConstraint.tags.manyToManySimpleFieldName;
135
+ }
136
+ return this.camelCase(
137
+ `${this.pluralize(this._singularizedTableName(rightTable))}-list`
138
+ );
139
+ },
140
+ },
141
+ true // Passing true here allows the plugin to overwrite existing inflectors.
142
+ );
143
+ ```
144
+
145
+ ### Smart comments
146
+
147
+ ```sql
148
+ -- rename the Connection field
149
+ comment on constraint membership_team_id_fkey on p.membership is E'@manyToManyFieldName teams';
150
+
151
+ -- rename both Connection and simple collection fields (when simple collections are enabled)
152
+ comment on constraint membership_team_id_fkey on p.membership is E'@manyToManyFieldName teams\n@manyToManySimpleFieldName teamsList';
153
+ ```
154
+
155
+ ## 🧪 Testing
156
+
157
+ ```sh
158
+ # requires a local Postgres available (defaults to postgres/password@localhost:5432)
159
+ pnpm --filter graphile-many-to-many test
160
+ ```
161
+
162
+ ---
163
+
164
+ ## Education and Tutorials
165
+
166
+ 1. 🚀 [Quickstart: Getting Up and Running](https://constructive.io/learn/quickstart)
167
+ Get started with modular databases in minutes. Install prerequisites and deploy your first module.
168
+
169
+ 2. 📦 [Modular PostgreSQL Development with Database Packages](https://constructive.io/learn/modular-postgres)
170
+ Learn to organize PostgreSQL projects with pgpm workspaces and reusable database modules.
171
+
172
+ 3. ✏️ [Authoring Database Changes](https://constructive.io/learn/authoring-database-changes)
173
+ Master the workflow for adding, organizing, and managing database changes with pgpm.
174
+
175
+ 4. 🧪 [End-to-End PostgreSQL Testing with TypeScript](https://constructive.io/learn/e2e-postgres-testing)
176
+ Master end-to-end PostgreSQL testing with ephemeral databases, RLS testing, and CI/CD automation.
177
+
178
+ 5. ⚡ [Supabase Testing](https://constructive.io/learn/supabase)
179
+ Use TypeScript-first tools to test Supabase projects with realistic RLS, policies, and auth contexts.
180
+
181
+ 6. 💧 [Drizzle ORM Testing](https://constructive.io/learn/drizzle-testing)
182
+ Run full-stack tests with Drizzle ORM, including database setup, teardown, and RLS enforcement.
183
+
184
+ 7. 🔧 [Troubleshooting](https://constructive.io/learn/troubleshooting)
185
+ Common issues and solutions for pgpm, PostgreSQL, and testing.
186
+
187
+ ## Related Constructive Tooling
188
+
189
+ ### 🧪 Testing
190
+
191
+ * [pgsql-test](https://github.com/constructive-io/constructive/tree/main/packages/pgsql-test): **📊 Isolated testing environments** with per-test transaction rollbacks—ideal for integration tests, complex migrations, and RLS simulation.
192
+ * [supabase-test](https://github.com/constructive-io/constructive/tree/main/packages/supabase-test): **🧪 Supabase-native test harness** preconfigured for the local Supabase stack—per-test rollbacks, JWT/role context helpers, and CI/GitHub Actions ready.
193
+ * [graphile-test](https://github.com/constructive-io/constructive/tree/main/packages/graphile-test): **🔐 Authentication mocking** for Graphile-focused test helpers and emulating row-level security contexts.
194
+ * [pg-query-context](https://github.com/constructive-io/constructive/tree/main/packages/pg-query-context): **🔒 Session context injection** to add session-local context (e.g., `SET LOCAL`) into queries—ideal for setting `role`, `jwt.claims`, and other session settings.
195
+
196
+ ### 🧠 Parsing & AST
197
+
198
+ * [pgsql-parser](https://www.npmjs.com/package/pgsql-parser): **🔄 SQL conversion engine** that interprets and converts PostgreSQL syntax.
199
+ * [libpg-query-node](https://www.npmjs.com/package/libpg-query): **🌉 Node.js bindings** for `libpg_query`, converting SQL into parse trees.
200
+ * [pg-proto-parser](https://www.npmjs.com/package/pg-proto-parser): **📦 Protobuf parser** for parsing PostgreSQL Protocol Buffers definitions to generate TypeScript interfaces, utility functions, and JSON mappings for enums.
201
+ * [@pgsql/enums](https://www.npmjs.com/package/@pgsql/enums): **🏷️ TypeScript enums** for PostgreSQL AST for safe and ergonomic parsing logic.
202
+ * [@pgsql/types](https://www.npmjs.com/package/@pgsql/types): **📝 Type definitions** for PostgreSQL AST nodes in TypeScript.
203
+ * [@pgsql/utils](https://www.npmjs.com/package/@pgsql/utils): **🛠️ AST utilities** for constructing and transforming PostgreSQL syntax trees.
204
+ * [pg-ast](https://www.npmjs.com/package/pg-ast): **🔍 Low-level AST tools** and transformations for Postgres query structures.
205
+
206
+ ### 🚀 API & Dev Tools
207
+
208
+ * [launchql/server](https://github.com/constructive-io/constructive/tree/main/packages/server): **⚡ Express-based API server** powered by PostGraphile to expose a secure, scalable GraphQL API over your Postgres database.
209
+ * [launchql/explorer](https://github.com/constructive-io/constructive/tree/main/packages/explorer): **🔎 Visual API explorer** with GraphiQL for browsing across all databases and schemas—useful for debugging, documentation, and API prototyping.
210
+
211
+ ### 🔁 Streaming & Uploads
212
+
213
+ * [launchql/s3-streamer](https://github.com/constructive-io/constructive/tree/main/packages/s3-streamer): **📤 Direct S3 streaming** for large files with support for metadata injection and content validation.
214
+ * [launchql/etag-hash](https://github.com/constructive-io/constructive/tree/main/packages/etag-hash): **🏷️ S3-compatible ETags** created by streaming and hashing file uploads in chunks.
215
+ * [launchql/etag-stream](https://github.com/constructive-io/constructive/tree/main/packages/etag-stream): **🔄 ETag computation** via Node stream transformer during upload or transfer.
216
+ * [launchql/uuid-hash](https://github.com/constructive-io/constructive/tree/main/packages/uuid-hash): **🆔 Deterministic UUIDs** generated from hashed content, great for deduplication and asset referencing.
217
+ * [launchql/uuid-stream](https://github.com/constructive-io/constructive/tree/main/packages/uuid-stream): **🌊 Streaming UUID generation** based on piped file content—ideal for upload pipelines.
218
+ * [launchql/upload-names](https://github.com/constructive-io/constructive/tree/main/packages/upload-names): **📂 Collision-resistant filenames** utility for structured and unique file names for uploads.
219
+
220
+ ### 🧰 CLI & Codegen
221
+
222
+ * [pgpm](https://github.com/constructive-io/constructive/tree/main/packages/pgpm): **🖥️ PostgreSQL Package Manager** for modular Postgres development. Works with database workspaces, scaffolding, migrations, seeding, and installing database packages.
223
+ * [@launchql/cli](https://github.com/constructive-io/constructive/tree/main/packages/cli): **🖥️ Command-line toolkit** for managing LaunchQL projects—supports database scaffolding, migrations, seeding, code generation, and automation.
224
+ * [constructive-io/constructive-gen](https://github.com/constructive-io/constructive/tree/main/packages/launchql-gen): **✨ Auto-generated GraphQL** mutations and queries dynamically built from introspected schema data.
225
+ * [@launchql/query-builder](https://github.com/constructive-io/constructive/tree/main/packages/query-builder): **🏗️ SQL constructor** providing a robust TypeScript-based query builder for dynamic generation of `SELECT`, `INSERT`, `UPDATE`, `DELETE`, and stored procedure calls—supports advanced SQL features like `JOIN`, `GROUP BY`, and schema-qualified queries.
226
+ * [@launchql/query](https://github.com/constructive-io/constructive/tree/main/packages/query): **🧩 Fluent GraphQL builder** for PostGraphile schemas. ⚡ Schema-aware via introspection, 🧩 composable and ergonomic for building deeply nested queries.
227
+
228
+ ## Credits
229
+
230
+ **🛠 Built by the [Constructive](https://constructive.io) team — creators of modular Postgres tooling for secure, composable backends. If you like our work, contribute on [GitHub](https://github.com/constructive-io).**
231
+
232
+ ## Disclaimer
233
+
234
+ AS DESCRIBED IN THE LICENSES, THE SOFTWARE IS PROVIDED "AS IS", AT YOUR OWN RISK, AND WITHOUT WARRANTIES OF ANY KIND.
235
+
236
+ No developer or entity involved in creating this software will be liable for any claims or damages whatsoever associated with your use, inability to use, or your interaction with other users of the code, including any direct, indirect, incidental, special, exemplary, punitive or consequential damages, or loss of profits, cryptocurrencies, tokens, or anything else of value.
@@ -0,0 +1,16 @@
1
+ import type { Build } from 'graphile-build';
2
+ import type { PgClass } from 'graphile-build-pg';
3
+ import type { GraphQLObjectType, GraphQLResolveInfo, GraphQLType } from 'graphql';
4
+ import type { ManyToManyRelationship, PgManyToManyOptions } from './types';
5
+ type PgConnectionBuild = Build & {
6
+ newWithHooks: any;
7
+ inflection: any;
8
+ graphql: typeof import('graphql');
9
+ getTypeByName: (name: string) => GraphQLType | undefined;
10
+ pgGetGqlTypeByTypeIdAndModifier: (typeId: string | number, modifier: number | null) => GraphQLType;
11
+ pgField: any;
12
+ getSafeAliasFromResolveInfo: (info: GraphQLResolveInfo) => string;
13
+ describePgEntity: (entity: any) => string;
14
+ };
15
+ declare const createManyToManyConnectionType: (relationship: ManyToManyRelationship, build: PgConnectionBuild, options: PgManyToManyOptions, leftTable: PgClass) => GraphQLObjectType;
16
+ export default createManyToManyConnectionType;