graphile-postgis 0.1.0 → 0.1.1

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.
Files changed (79) hide show
  1. package/LICENSE +3 -1
  2. package/PostgisExtensionDetectionPlugin.d.ts +3 -0
  3. package/PostgisExtensionDetectionPlugin.js +28 -0
  4. package/PostgisInflectionPlugin.d.ts +3 -0
  5. package/PostgisInflectionPlugin.js +36 -0
  6. package/PostgisRegisterTypesPlugin.d.ts +3 -0
  7. package/PostgisRegisterTypesPlugin.js +232 -0
  8. package/PostgisVersionPlugin.d.ts +3 -0
  9. package/PostgisVersionPlugin.js +23 -0
  10. package/Postgis_GeometryCollection_GeometriesPlugin.d.ts +3 -0
  11. package/Postgis_GeometryCollection_GeometriesPlugin.js +43 -0
  12. package/Postgis_LineString_PointsPlugin.d.ts +3 -0
  13. package/Postgis_LineString_PointsPlugin.js +40 -0
  14. package/Postgis_MultiLineString_LineStringsPlugin.d.ts +3 -0
  15. package/Postgis_MultiLineString_LineStringsPlugin.js +38 -0
  16. package/Postgis_MultiPoint_PointsPlugin.d.ts +3 -0
  17. package/Postgis_MultiPoint_PointsPlugin.js +38 -0
  18. package/Postgis_MultiPolygon_PolygonsPlugin.d.ts +3 -0
  19. package/Postgis_MultiPolygon_PolygonsPlugin.js +38 -0
  20. package/Postgis_Point_LatitudeLongitudePlugin.d.ts +3 -0
  21. package/Postgis_Point_LatitudeLongitudePlugin.js +43 -0
  22. package/Postgis_Polygon_RingsPlugin.d.ts +3 -0
  23. package/Postgis_Polygon_RingsPlugin.js +49 -0
  24. package/README.md +125 -5
  25. package/constants.d.ts +12 -0
  26. package/constants.js +34 -0
  27. package/esm/PostgisExtensionDetectionPlugin.js +26 -0
  28. package/esm/PostgisInflectionPlugin.js +34 -0
  29. package/esm/PostgisRegisterTypesPlugin.js +227 -0
  30. package/esm/PostgisVersionPlugin.js +21 -0
  31. package/esm/Postgis_GeometryCollection_GeometriesPlugin.js +41 -0
  32. package/esm/Postgis_LineString_PointsPlugin.js +38 -0
  33. package/esm/Postgis_MultiLineString_LineStringsPlugin.js +36 -0
  34. package/esm/Postgis_MultiPoint_PointsPlugin.js +36 -0
  35. package/esm/Postgis_MultiPolygon_PolygonsPlugin.js +36 -0
  36. package/esm/Postgis_Point_LatitudeLongitudePlugin.js +41 -0
  37. package/esm/Postgis_Polygon_RingsPlugin.js +47 -0
  38. package/esm/constants.js +31 -0
  39. package/esm/index.js +33 -0
  40. package/esm/makeGeoJSONType.js +39 -0
  41. package/esm/types.js +1 -0
  42. package/esm/utils.js +47 -0
  43. package/index.d.ts +15 -0
  44. package/index.js +49 -0
  45. package/makeGeoJSONType.d.ts +1 -0
  46. package/makeGeoJSONType.js +42 -0
  47. package/package.json +37 -52
  48. package/types.d.ts +59 -0
  49. package/types.js +2 -0
  50. package/utils.d.ts +5 -0
  51. package/utils.js +53 -0
  52. package/main/PostgisExtensionDetectionPlugin.js +0 -43
  53. package/main/PostgisInflectionPlugin.js +0 -51
  54. package/main/PostgisRegisterTypesPlugin.js +0 -347
  55. package/main/Postgis_GeometryCollection_GeometriesPlugin.js +0 -55
  56. package/main/Postgis_LineString_PointsPlugin.js +0 -51
  57. package/main/Postgis_MultiLineString_LineStringsPlugin.js +0 -51
  58. package/main/Postgis_MultiPoint_PointsPlugin.js +0 -51
  59. package/main/Postgis_MultiPolygon_PolygonsPlugin.js +0 -51
  60. package/main/Postgis_Point_LatitudeLongitudePlugin.js +0 -59
  61. package/main/Postgis_Polygon_RingsPlugin.js +0 -64
  62. package/main/constants.js +0 -39
  63. package/main/index.js +0 -93
  64. package/main/makeGeoJSONType.js +0 -89
  65. package/main/utils.js +0 -56
  66. package/module/PostgisExtensionDetectionPlugin.js +0 -31
  67. package/module/PostgisInflectionPlugin.js +0 -44
  68. package/module/PostgisRegisterTypesPlugin.js +0 -267
  69. package/module/Postgis_GeometryCollection_GeometriesPlugin.js +0 -57
  70. package/module/Postgis_LineString_PointsPlugin.js +0 -53
  71. package/module/Postgis_MultiLineString_LineStringsPlugin.js +0 -51
  72. package/module/Postgis_MultiPoint_PointsPlugin.js +0 -51
  73. package/module/Postgis_MultiPolygon_PolygonsPlugin.js +0 -51
  74. package/module/Postgis_Point_LatitudeLongitudePlugin.js +0 -64
  75. package/module/Postgis_Polygon_RingsPlugin.js +0 -66
  76. package/module/constants.js +0 -30
  77. package/module/index.js +0 -32
  78. package/module/makeGeoJSONType.js +0 -79
  79. package/module/utils.js +0 -40
@@ -0,0 +1,49 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ const constants_1 = require("./constants");
4
+ const utils_1 = require("./utils");
5
+ const PostgisPolygonRingsPlugin = (builder) => {
6
+ builder.hook('GraphQLObjectType:fields', (fields, build, context) => {
7
+ const { scope: { isPgGISType, pgGISType, pgGISTypeDetails } } = context;
8
+ if (!isPgGISType || !pgGISType || !pgGISTypeDetails || pgGISTypeDetails.subtype !== constants_1.GisSubtype.Polygon) {
9
+ return fields;
10
+ }
11
+ const { extend, getPostgisTypeByGeometryType, graphql: { GraphQLList } } = build;
12
+ const { hasZ, hasM, srid } = pgGISTypeDetails;
13
+ const LineStringType = getPostgisTypeByGeometryType(pgGISType, constants_1.GisSubtype.LineString, hasZ, hasM, srid);
14
+ if (!LineStringType) {
15
+ return fields;
16
+ }
17
+ return extend(fields, {
18
+ exterior: {
19
+ type: LineStringType,
20
+ resolve(data) {
21
+ const polygon = data.__geojson;
22
+ return {
23
+ __gisType: (0, utils_1.getGISTypeName)(constants_1.GisSubtype.LineString, hasZ, hasM),
24
+ __srid: data.__srid,
25
+ __geojson: {
26
+ type: 'LineString',
27
+ coordinates: polygon.coordinates[0]
28
+ }
29
+ };
30
+ }
31
+ },
32
+ interiors: {
33
+ type: new GraphQLList(LineStringType),
34
+ resolve(data) {
35
+ const polygon = data.__geojson;
36
+ return polygon.coordinates.slice(1).map((coord) => ({
37
+ __gisType: (0, utils_1.getGISTypeName)(constants_1.GisSubtype.LineString, hasZ, hasM),
38
+ __srid: data.__srid,
39
+ __geojson: {
40
+ type: 'LineString',
41
+ coordinates: coord
42
+ }
43
+ }));
44
+ }
45
+ }
46
+ });
47
+ });
48
+ };
49
+ exports.default = PostgisPolygonRingsPlugin;
package/README.md CHANGED
@@ -1,9 +1,129 @@
1
1
  # graphile-postgis
2
2
 
3
+ <p align="center" width="100%">
4
+ <img height="250" src="https://raw.githubusercontent.com/launchql/launchql/refs/heads/main/assets/outline-logo.svg" />
5
+ </p>
6
+
7
+ <p align="center" width="100%">
8
+ <a href="https://github.com/launchql/launchql/actions/workflows/run-tests.yaml">
9
+ <img height="20" src="https://github.com/launchql/launchql/actions/workflows/run-tests.yaml/badge.svg" />
10
+ </a>
11
+ <a href="https://github.com/launchql/launchql/blob/main/LICENSE"><img height="20" src="https://img.shields.io/badge/license-MIT-blue.svg"/></a>
12
+ <a href="https://www.npmjs.com/package/graphile-postgis"><img height="20" src="https://img.shields.io/github/package-json/v/launchql/launchql?filename=graphile%2Fgraphile-postgis%2Fpackage.json"/></a>
13
+ </p>
14
+
15
+ PostGIS helpers for PostGraphile/Graphile. This plugin registers GeoJSON scalars, PostGIS
16
+ geometry/geography GraphQL types, and convenience fields for common spatial types.
17
+
18
+ ## Install
3
19
 
4
20
  ```sh
5
- createdb graphile_test
6
- psql graphile_test -f __tests__/schema.sql
7
- export TEST_DATABASE_URL=postgres://localhost:5432/graphile_test
8
- yarn test:watch
9
- ```
21
+ pnpm add graphile-postgis
22
+ ```
23
+
24
+ ## Usage
25
+
26
+ ### CLI
27
+
28
+ ```sh
29
+ postgraphile --append-plugins graphile-postgis
30
+ ```
31
+
32
+ Make sure your database has the `postgis` extension enabled so the plugin can expose the spatial types.
33
+
34
+ ### Library
35
+
36
+ ```ts
37
+ import PostgisPlugin from 'graphile-postgis';
38
+
39
+ const options = {
40
+ appendPlugins: [PostgisPlugin]
41
+ };
42
+ ```
43
+
44
+ ## Testing
45
+
46
+ Tests run against a real Postgres/PostGIS instance using the `graphile-test` and
47
+ `pgsql-test` harnesses. The suite seeds the database from `sql/schema.sql`.
48
+
49
+ ```sh
50
+ psql -U postgres -f sql/schema.sql postgres
51
+ pnpm test --filter graphile-postgis
52
+ ```
53
+
54
+ ---
55
+
56
+ ## Education and Tutorials
57
+
58
+ 1. 🚀 [Quickstart: Getting Up and Running](https://launchql.com/learn/quickstart)
59
+ Get started with modular databases in minutes. Install prerequisites and deploy your first module.
60
+
61
+ 2. 📦 [Modular PostgreSQL Development with Database Packages](https://launchql.com/learn/modular-postgres)
62
+ Learn to organize PostgreSQL projects with pgpm workspaces and reusable database modules.
63
+
64
+ 3. ✏️ [Authoring Database Changes](https://launchql.com/learn/authoring-database-changes)
65
+ Master the workflow for adding, organizing, and managing database changes with pgpm.
66
+
67
+ 4. 🧪 [End-to-End PostgreSQL Testing with TypeScript](https://launchql.com/learn/e2e-postgres-testing)
68
+ Master end-to-end PostgreSQL testing with ephemeral databases, RLS testing, and CI/CD automation.
69
+
70
+ 5. ⚡ [Supabase Testing](https://launchql.com/learn/supabase)
71
+ Use TypeScript-first tools to test Supabase projects with realistic RLS, policies, and auth contexts.
72
+
73
+ 6. 💧 [Drizzle ORM Testing](https://launchql.com/learn/drizzle-testing)
74
+ Run full-stack tests with Drizzle ORM, including database setup, teardown, and RLS enforcement.
75
+
76
+ 7. 🔧 [Troubleshooting](https://launchql.com/learn/troubleshooting)
77
+ Common issues and solutions for pgpm, PostgreSQL, and testing.
78
+
79
+ ## Related LaunchQL Tooling
80
+
81
+ ### 🧪 Testing
82
+
83
+ * [launchql/pgsql-test](https://github.com/launchql/launchql/tree/main/packages/pgsql-test): **📊 Isolated testing environments** with per-test transaction rollbacks—ideal for integration tests, complex migrations, and RLS simulation.
84
+ * [launchql/supabase-test](https://github.com/launchql/launchql/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.
85
+ * [launchql/graphile-test](https://github.com/launchql/launchql/tree/main/packages/graphile-test): **🔐 Authentication mocking** for Graphile-focused test helpers and emulating row-level security contexts.
86
+ * [launchql/pg-query-context](https://github.com/launchql/launchql/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.
87
+
88
+ ### 🧠 Parsing & AST
89
+
90
+ * [launchql/pgsql-parser](https://github.com/launchql/pgsql-parser): **🔄 SQL conversion engine** that interprets and converts PostgreSQL syntax.
91
+ * [launchql/libpg-query-node](https://github.com/launchql/libpg-query-node): **🌉 Node.js bindings** for `libpg_query`, converting SQL into parse trees.
92
+ * [launchql/pg-proto-parser](https://github.com/launchql/pg-proto-parser): **📦 Protobuf parser** for parsing PostgreSQL Protocol Buffers definitions to generate TypeScript interfaces, utility functions, and JSON mappings for enums.
93
+ * [@pgsql/enums](https://github.com/launchql/pgsql-parser/tree/main/packages/enums): **🏷️ TypeScript enums** for PostgreSQL AST for safe and ergonomic parsing logic.
94
+ * [@pgsql/types](https://github.com/launchql/pgsql-parser/tree/main/packages/types): **📝 Type definitions** for PostgreSQL AST nodes in TypeScript.
95
+ * [@pgsql/utils](https://github.com/launchql/pgsql-parser/tree/main/packages/utils): **🛠️ AST utilities** for constructing and transforming PostgreSQL syntax trees.
96
+ * [launchql/pg-ast](https://github.com/launchql/launchql/tree/main/packages/pg-ast): **🔍 Low-level AST tools** and transformations for Postgres query structures.
97
+
98
+ ### 🚀 API & Dev Tools
99
+
100
+ * [launchql/server](https://github.com/launchql/launchql/tree/main/packages/server): **⚡ Express-based API server** powered by PostGraphile to expose a secure, scalable GraphQL API over your Postgres database.
101
+ * [launchql/explorer](https://github.com/launchql/launchql/tree/main/packages/explorer): **🔎 Visual API explorer** with GraphiQL for browsing across all databases and schemas—useful for debugging, documentation, and API prototyping.
102
+
103
+ ### 🔁 Streaming & Uploads
104
+
105
+ * [launchql/s3-streamer](https://github.com/launchql/launchql/tree/main/packages/s3-streamer): **📤 Direct S3 streaming** for large files with support for metadata injection and content validation.
106
+ * [launchql/etag-hash](https://github.com/launchql/launchql/tree/main/packages/etag-hash): **🏷️ S3-compatible ETags** created by streaming and hashing file uploads in chunks.
107
+ * [launchql/etag-stream](https://github.com/launchql/launchql/tree/main/packages/etag-stream): **🔄 ETag computation** via Node stream transformer during upload or transfer.
108
+ * [launchql/uuid-hash](https://github.com/launchql/launchql/tree/main/packages/uuid-hash): **🆔 Deterministic UUIDs** generated from hashed content, great for deduplication and asset referencing.
109
+ * [launchql/uuid-stream](https://github.com/launchql/launchql/tree/main/packages/uuid-stream): **🌊 Streaming UUID generation** based on piped file content—ideal for upload pipelines.
110
+ * [launchql/upload-names](https://github.com/launchql/launchql/tree/main/packages/upload-names): **📂 Collision-resistant filenames** utility for structured and unique file names for uploads.
111
+
112
+ ### 🧰 CLI & Codegen
113
+
114
+ * [pgpm](https://github.com/launchql/launchql/tree/main/packages/pgpm): **🖥️ PostgreSQL Package Manager** for modular Postgres development. Works with database workspaces, scaffolding, migrations, seeding, and installing database packages.
115
+ * [@launchql/cli](https://github.com/launchql/launchql/tree/main/packages/cli): **🖥️ Command-line toolkit** for managing LaunchQL projects—supports database scaffolding, migrations, seeding, code generation, and automation.
116
+ * [launchql/launchql-gen](https://github.com/launchql/launchql/tree/main/packages/launchql-gen): **✨ Auto-generated GraphQL** mutations and queries dynamically built from introspected schema data.
117
+ * [@launchql/query-builder](https://github.com/launchql/launchql/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.
118
+ * [@launchql/query](https://github.com/launchql/launchql/tree/main/packages/query): **🧩 Fluent GraphQL builder** for PostGraphile schemas. ⚡ Schema-aware via introspection, 🧩 composable and ergonomic for building deeply nested queries.
119
+
120
+ ## Credits
121
+
122
+ 🛠 Built by LaunchQL — if you like our tools, please checkout and contribute to [our github ⚛️](https://github.com/launchql)
123
+
124
+
125
+ ## Disclaimer
126
+
127
+ AS DESCRIBED IN THE LICENSES, THE SOFTWARE IS PROVIDED "AS IS", AT YOUR OWN RISK, AND WITHOUT WARRANTIES OF ANY KIND.
128
+
129
+ 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.
package/constants.d.ts ADDED
@@ -0,0 +1,12 @@
1
+ export declare enum GisSubtype {
2
+ Geometry = 0,
3
+ Point = 1,
4
+ LineString = 2,
5
+ Polygon = 3,
6
+ MultiPoint = 4,
7
+ MultiLineString = 5,
8
+ MultiPolygon = 6,
9
+ GeometryCollection = 7
10
+ }
11
+ export declare const SUBTYPE_STRING_BY_SUBTYPE: Record<GisSubtype, string>;
12
+ export declare const GIS_SUBTYPE_NAME: Record<GisSubtype, string>;
package/constants.js ADDED
@@ -0,0 +1,34 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.GIS_SUBTYPE_NAME = exports.SUBTYPE_STRING_BY_SUBTYPE = exports.GisSubtype = void 0;
4
+ var GisSubtype;
5
+ (function (GisSubtype) {
6
+ GisSubtype[GisSubtype["Geometry"] = 0] = "Geometry";
7
+ GisSubtype[GisSubtype["Point"] = 1] = "Point";
8
+ GisSubtype[GisSubtype["LineString"] = 2] = "LineString";
9
+ GisSubtype[GisSubtype["Polygon"] = 3] = "Polygon";
10
+ GisSubtype[GisSubtype["MultiPoint"] = 4] = "MultiPoint";
11
+ GisSubtype[GisSubtype["MultiLineString"] = 5] = "MultiLineString";
12
+ GisSubtype[GisSubtype["MultiPolygon"] = 6] = "MultiPolygon";
13
+ GisSubtype[GisSubtype["GeometryCollection"] = 7] = "GeometryCollection";
14
+ })(GisSubtype || (exports.GisSubtype = GisSubtype = {}));
15
+ exports.SUBTYPE_STRING_BY_SUBTYPE = {
16
+ [GisSubtype.Geometry]: 'geometry',
17
+ [GisSubtype.Point]: 'point',
18
+ [GisSubtype.LineString]: 'line-string',
19
+ [GisSubtype.Polygon]: 'polygon',
20
+ [GisSubtype.MultiPoint]: 'multi-point',
21
+ [GisSubtype.MultiLineString]: 'multi-line-string',
22
+ [GisSubtype.MultiPolygon]: 'multi-polygon',
23
+ [GisSubtype.GeometryCollection]: 'geometry-collection'
24
+ };
25
+ exports.GIS_SUBTYPE_NAME = {
26
+ [GisSubtype.Geometry]: 'Geometry',
27
+ [GisSubtype.Point]: 'Point',
28
+ [GisSubtype.LineString]: 'LineString',
29
+ [GisSubtype.Polygon]: 'Polygon',
30
+ [GisSubtype.MultiPoint]: 'MultiPoint',
31
+ [GisSubtype.MultiLineString]: 'MultiLineString',
32
+ [GisSubtype.MultiPolygon]: 'MultiPolygon',
33
+ [GisSubtype.GeometryCollection]: 'GeometryCollection'
34
+ };
@@ -0,0 +1,26 @@
1
+ const PostgisExtensionDetectionPlugin = (builder) => {
2
+ builder.hook('build', (build) => {
3
+ const postgisBuild = build;
4
+ const { pgIntrospectionResultsByKind: introspectionResultsByKind } = postgisBuild;
5
+ const pgGISExtension = introspectionResultsByKind.extension.find((extension) => extension.name === 'postgis');
6
+ // Check we have the postgis extension
7
+ if (!pgGISExtension) {
8
+ console.warn('PostGIS extension not found in database; skipping');
9
+ return postgisBuild;
10
+ }
11
+ // Extract the geography and geometry types
12
+ const pgGISGeometryType = introspectionResultsByKind.type.find((type) => type.name === 'geometry' && type.namespaceId === pgGISExtension.namespaceId);
13
+ const pgGISGeographyType = introspectionResultsByKind.type.find((type) => type.name === 'geography' && type.namespaceId === pgGISExtension.namespaceId);
14
+ if (!pgGISGeographyType || !pgGISGeometryType) {
15
+ throw new Error("PostGIS is installed, but we couldn't find the geometry/geography types!");
16
+ }
17
+ return postgisBuild.extend(postgisBuild, {
18
+ pgGISGraphQLTypesByTypeAndSubtype: {},
19
+ pgGISGraphQLInterfaceTypesByType: {},
20
+ pgGISGeometryType,
21
+ pgGISGeographyType,
22
+ pgGISExtension
23
+ });
24
+ });
25
+ };
26
+ export default PostgisExtensionDetectionPlugin;
@@ -0,0 +1,34 @@
1
+ import { GisSubtype, SUBTYPE_STRING_BY_SUBTYPE } from './constants';
2
+ const PostgisInflectionPlugin = (builder) => {
3
+ builder.hook('inflection', (inflection) => {
4
+ return {
5
+ ...inflection,
6
+ gisType(type, subtype, hasZ, hasM, _srid) {
7
+ return this.upperCamelCase([type.name, SUBTYPE_STRING_BY_SUBTYPE[subtype], hasZ ? 'z' : null, hasM ? 'm' : null]
8
+ .filter(Boolean)
9
+ .join('-'));
10
+ },
11
+ gisInterfaceName(type) {
12
+ return this.upperCamelCase(`${type.name}-interface`);
13
+ },
14
+ gisDimensionInterfaceName(type, hasZ, hasM) {
15
+ return this.upperCamelCase([type.name, SUBTYPE_STRING_BY_SUBTYPE[GisSubtype.Geometry], hasZ ? 'z' : null, hasM ? 'm' : null]
16
+ .filter(Boolean)
17
+ .join('-'));
18
+ },
19
+ geojsonFieldName() {
20
+ return 'geojson';
21
+ },
22
+ gisXFieldName(_type) {
23
+ return _type.name === 'geography' ? 'longitude' : 'x';
24
+ },
25
+ gisYFieldName(_type) {
26
+ return _type.name === 'geography' ? 'latitude' : 'y';
27
+ },
28
+ gisZFieldName(_type) {
29
+ return _type.name === 'geography' ? 'height' : 'z';
30
+ }
31
+ };
32
+ });
33
+ };
34
+ export default PostgisInflectionPlugin;
@@ -0,0 +1,227 @@
1
+ import { GisSubtype } from './constants';
2
+ import makeGeoJSONType from './makeGeoJSONType';
3
+ import { getGISTypeDetails, getGISTypeModifier, getGISTypeName } from './utils';
4
+ const SUBTYPES = [
5
+ GisSubtype.Point,
6
+ GisSubtype.LineString,
7
+ GisSubtype.Polygon,
8
+ GisSubtype.MultiPoint,
9
+ GisSubtype.MultiLineString,
10
+ GisSubtype.MultiPolygon,
11
+ GisSubtype.GeometryCollection
12
+ ];
13
+ const identity = (input) => input;
14
+ const PostgisRegisterTypesPlugin = (builder) => {
15
+ builder.hook('build', (build) => {
16
+ const rawBuild = build;
17
+ const GeoJSON = makeGeoJSONType(rawBuild.graphql, rawBuild.inflection.builtin('GeoJSON'));
18
+ rawBuild.addType(GeoJSON);
19
+ return rawBuild.extend(rawBuild, {
20
+ getPostgisTypeByGeometryType(pgGISType, subtype, hasZ = false, hasM = false, srid = 0) {
21
+ const typeModifier = getGISTypeModifier(subtype, hasZ, hasM, srid);
22
+ return this.pgGetGqlTypeByTypeIdAndModifier(pgGISType.id, typeModifier);
23
+ },
24
+ pgGISIncludedTypes: [],
25
+ pgGISIncludeType(Type) {
26
+ this.pgGISIncludedTypes.push(Type);
27
+ }
28
+ });
29
+ });
30
+ builder.hook('init', (input, build) => {
31
+ const rawBuild = build;
32
+ const { newWithHooks, pgIntrospectionResultsByKind: introspectionResultsByKind, graphql: { GraphQLInt, GraphQLNonNull, GraphQLInterfaceType, GraphQLObjectType }, pgRegisterGqlTypeByTypeId, pgRegisterGqlInputTypeByTypeId, pgTweaksByTypeIdAndModifer, getTypeByName, pgSql: sql, pg2gql, pg2GqlMapper, inflection, pgGISGraphQLTypesByTypeAndSubtype: constructedTypes, pgGISGraphQLInterfaceTypesByType: interfacesMap, pgGISGeometryType: GEOMETRY_TYPE, pgGISGeographyType: GEOGRAPHY_TYPE, pgGISExtension: POSTGIS, pgGISIncludeType: includeType } = rawBuild;
33
+ if (!GEOMETRY_TYPE || !GEOGRAPHY_TYPE) {
34
+ return input;
35
+ }
36
+ console.warn('PostGIS plugin enabled');
37
+ const GeoJSON = getTypeByName(inflection.builtin('GeoJSON'));
38
+ if (!GeoJSON) {
39
+ throw new Error('GeoJSON type was not registered on the build');
40
+ }
41
+ const geojsonFieldName = inflection.geojsonFieldName();
42
+ const ensureInterfaceStore = (type) => {
43
+ if (!interfacesMap[type.id]) {
44
+ interfacesMap[type.id] = {};
45
+ }
46
+ };
47
+ const getGisInterface = (type) => {
48
+ const zmflag = -1; // no dimensional constraint; could be xy/xyz/xym/xyzm
49
+ ensureInterfaceStore(type);
50
+ if (!interfacesMap[type.id][zmflag]) {
51
+ interfacesMap[type.id][zmflag] = newWithHooks(GraphQLInterfaceType, {
52
+ name: inflection.gisInterfaceName(type),
53
+ fields: {
54
+ [geojsonFieldName]: {
55
+ type: GeoJSON,
56
+ description: 'Converts the object to GeoJSON'
57
+ },
58
+ srid: {
59
+ type: new GraphQLNonNull(GraphQLInt),
60
+ description: 'Spatial reference identifier (SRID)'
61
+ }
62
+ },
63
+ resolveType(value) {
64
+ const Type = constructedTypes[type.id]?.[value.__gisType];
65
+ return Type instanceof GraphQLObjectType ? Type : undefined;
66
+ },
67
+ description: `All ${type.name} types implement this interface`
68
+ }, {
69
+ isPgGISInterface: true,
70
+ pgGISType: type,
71
+ pgGISZMFlag: zmflag
72
+ });
73
+ for (const subtype of SUBTYPES) {
74
+ for (const hasZ of [false, true]) {
75
+ for (const hasM of [false, true]) {
76
+ const typeModifier = getGISTypeModifier(subtype, hasZ, hasM, 0);
77
+ const Type = getGisType(type, typeModifier);
78
+ includeType(Type);
79
+ }
80
+ }
81
+ }
82
+ }
83
+ return interfacesMap[type.id][zmflag];
84
+ };
85
+ const getGisDimensionInterface = (type, hasZ, hasM) => {
86
+ const zmflag = (hasZ ? 2 : 0) + (hasM ? 1 : 0); // Equivalent to ST_Zmflag: https://postgis.net/docs/ST_Zmflag.html
87
+ const coords = { 0: 'XY', 1: 'XYM', 2: 'XYZ', 3: 'XYZM' };
88
+ ensureInterfaceStore(type);
89
+ if (!interfacesMap[type.id][zmflag]) {
90
+ interfacesMap[type.id][zmflag] = newWithHooks(GraphQLInterfaceType, {
91
+ name: inflection.gisDimensionInterfaceName(type, hasZ, hasM),
92
+ fields: {
93
+ [geojsonFieldName]: {
94
+ type: GeoJSON,
95
+ description: 'Converts the object to GeoJSON'
96
+ },
97
+ srid: {
98
+ type: new GraphQLNonNull(GraphQLInt),
99
+ description: 'Spatial reference identifier (SRID)'
100
+ }
101
+ },
102
+ resolveType(value) {
103
+ const Type = constructedTypes[type.id]?.[value.__gisType];
104
+ return Type instanceof GraphQLObjectType ? Type : undefined;
105
+ },
106
+ description: `All ${type.name} ${coords[zmflag]} types implement this interface`
107
+ }, {
108
+ isPgGISDimensionInterface: true,
109
+ pgGISType: type,
110
+ pgGISZMFlag: zmflag
111
+ });
112
+ for (const subtype of SUBTYPES) {
113
+ const typeModifier = getGISTypeModifier(subtype, hasZ, hasM, 0);
114
+ const Type = getGisType(type, typeModifier);
115
+ includeType(Type);
116
+ }
117
+ }
118
+ return interfacesMap[type.id][zmflag];
119
+ };
120
+ const getGisType = (type, typeModifier) => {
121
+ const typeId = type.id;
122
+ const typeDetails = getGISTypeDetails(typeModifier);
123
+ const { subtype, hasZ, hasM, srid } = typeDetails;
124
+ console.warn(`Getting ${type.name} type ${type.id}|${typeModifier}|${subtype}|${hasZ}|${hasM}|${srid}`);
125
+ if (!constructedTypes[typeId]) {
126
+ constructedTypes[typeId] = {};
127
+ }
128
+ const typeModifierKey = typeModifier ?? -1;
129
+ if (!pgTweaksByTypeIdAndModifer[typeId]) {
130
+ pgTweaksByTypeIdAndModifer[typeId] = {};
131
+ }
132
+ if (!pgTweaksByTypeIdAndModifer[typeId][typeModifierKey]) {
133
+ pgTweaksByTypeIdAndModifer[typeId][typeModifierKey] = (fragment) => {
134
+ const params = [
135
+ sql.literal('__gisType'),
136
+ sql.fragment `${sql.identifier(POSTGIS?.namespaceName || 'public', 'postgis_type_name' // MUST be lowercase!
137
+ )}(
138
+ ${sql.identifier(POSTGIS?.namespaceName || 'public', 'geometrytype' // MUST be lowercase!
139
+ )}(${fragment}),
140
+ ${sql.identifier(POSTGIS?.namespaceName || 'public', 'st_coorddim' // MUST be lowercase!
141
+ )}(${fragment}::text)
142
+ )`,
143
+ sql.literal('__srid'),
144
+ sql.fragment `${sql.identifier(POSTGIS?.namespaceName || 'public', 'st_srid' // MUST be lowercase!
145
+ )}(${fragment})`,
146
+ sql.literal('__geojson'),
147
+ sql.fragment `${sql.identifier(POSTGIS?.namespaceName || 'public', 'st_asgeojson' // MUST be lowercase!
148
+ )}(${fragment})::JSON`
149
+ ];
150
+ return sql.fragment `(case when ${fragment} is null then null else json_build_object(
151
+ ${sql.join(params, ', ')}
152
+ ) end)`;
153
+ };
154
+ }
155
+ const gisTypeKey = typeModifier != null ? getGISTypeName(subtype, hasZ, hasM) : -1;
156
+ if (!constructedTypes[typeId][gisTypeKey]) {
157
+ if (typeModifierKey === -1) {
158
+ constructedTypes[typeId][gisTypeKey] = getGisInterface(type);
159
+ }
160
+ else if (subtype === GisSubtype.Geometry) {
161
+ constructedTypes[typeId][gisTypeKey] = getGisDimensionInterface(type, hasZ, hasM);
162
+ }
163
+ else {
164
+ const intType = introspectionResultsByKind.type.find((introspectionType) => introspectionType.name === 'int4' && introspectionType.namespaceName === 'pg_catalog');
165
+ const jsonType = introspectionResultsByKind.type.find((introspectionType) => introspectionType.name === 'json' && introspectionType.namespaceName === 'pg_catalog');
166
+ if (!intType || !jsonType) {
167
+ throw new Error('Unable to locate built-in int4/json types');
168
+ }
169
+ constructedTypes[typeId][gisTypeKey] = newWithHooks(GraphQLObjectType, {
170
+ name: inflection.gisType(type, subtype, hasZ, hasM, srid),
171
+ interfaces: () => [
172
+ getGisInterface(type),
173
+ getGisDimensionInterface(type, hasZ, hasM)
174
+ ],
175
+ fields: {
176
+ [geojsonFieldName]: {
177
+ type: GeoJSON,
178
+ resolve: (data) => {
179
+ return pg2gql(data.__geojson, jsonType);
180
+ }
181
+ },
182
+ srid: {
183
+ type: new GraphQLNonNull(GraphQLInt),
184
+ resolve: (data) => {
185
+ return pg2gql(data.__srid, intType);
186
+ }
187
+ }
188
+ }
189
+ }, {
190
+ isPgGISType: true,
191
+ pgGISType: type,
192
+ pgGISTypeDetails: typeDetails
193
+ });
194
+ }
195
+ }
196
+ return constructedTypes[typeId][gisTypeKey];
197
+ };
198
+ console.warn(`Registering handler for ${GEOGRAPHY_TYPE.id}`);
199
+ pgRegisterGqlInputTypeByTypeId(GEOGRAPHY_TYPE.id, () => GeoJSON);
200
+ pg2GqlMapper[GEOGRAPHY_TYPE.id] = {
201
+ map: identity,
202
+ unmap: (o) => sql.fragment `st_geomfromgeojson(${sql.value(JSON.stringify(o))}::text)::${sql.identifier(POSTGIS?.namespaceName || 'public', 'geography')}`
203
+ };
204
+ pgRegisterGqlTypeByTypeId(GEOGRAPHY_TYPE.id, (_set, typeModifier) => {
205
+ return getGisType(GEOGRAPHY_TYPE, typeModifier);
206
+ });
207
+ console.warn(`Registering handler for ${GEOMETRY_TYPE.id}`);
208
+ pgRegisterGqlInputTypeByTypeId(GEOMETRY_TYPE.id, () => GeoJSON);
209
+ pg2GqlMapper[GEOMETRY_TYPE.id] = {
210
+ map: identity,
211
+ unmap: (o) => sql.fragment `st_geomfromgeojson(${sql.value(JSON.stringify(o))}::text)`
212
+ };
213
+ pgRegisterGqlTypeByTypeId(GEOMETRY_TYPE.id, (_set, typeModifier) => {
214
+ return getGisType(GEOMETRY_TYPE, typeModifier);
215
+ });
216
+ return input;
217
+ }, ['PostgisTypes'], ['PgTables'], ['PgTypes']);
218
+ builder.hook('GraphQLSchema', (schemaConfig, build) => {
219
+ const postgisBuild = build;
220
+ const existingTypes = schemaConfig.types ?? [];
221
+ return {
222
+ ...schemaConfig,
223
+ types: [...existingTypes, ...postgisBuild.pgGISIncludedTypes]
224
+ };
225
+ });
226
+ };
227
+ export default PostgisRegisterTypesPlugin;
@@ -0,0 +1,21 @@
1
+ const plugin = (builder) => {
2
+ builder.hook('build', (build) => {
3
+ const pkg = require('../package.json');
4
+ // Check dependencies
5
+ if (!build.versions) {
6
+ throw new Error(`Plugin ${pkg.name}@${pkg.version} requires graphile-build@^4.1.0 in order to check dependencies (current version: ${build.graphileBuildVersion})`);
7
+ }
8
+ const depends = (name, range) => {
9
+ if (!build.hasVersion(name, range)) {
10
+ throw new Error(`Plugin ${pkg.name}@${pkg.version} requires ${name}@${range} (${build.versions[name]
11
+ ? `current version: ${build.versions[name]}`
12
+ : 'not found'})`);
13
+ }
14
+ };
15
+ depends('graphile-build-pg', '^4.4.0');
16
+ // Register this plugin
17
+ build.versions = build.extend(build.versions, { [pkg.name]: pkg.version });
18
+ return build;
19
+ });
20
+ };
21
+ export default plugin;
@@ -0,0 +1,41 @@
1
+ import { GisSubtype } from './constants';
2
+ import { getGISTypeName } from './utils';
3
+ const PostgisGeometryCollectionGeometriesPlugin = (builder) => {
4
+ builder.hook('GraphQLObjectType:fields', function AddGeometriesToGeometryCollection(fields, build, context) {
5
+ const { scope: { isPgGISType, pgGISType, pgGISTypeDetails } } = context;
6
+ if (!isPgGISType ||
7
+ !pgGISType ||
8
+ !pgGISTypeDetails ||
9
+ pgGISTypeDetails.subtype !== GisSubtype.GeometryCollection) {
10
+ return fields;
11
+ }
12
+ const { extend, pgGISGraphQLInterfaceTypesByType, graphql: { GraphQLList } } = build;
13
+ const { hasZ, hasM } = pgGISTypeDetails;
14
+ const zmflag = (hasZ ? 2 : 0) + (hasM ? 1 : 0); // Equivalent to ST_Zmflag: https://postgis.net/docs/ST_Zmflag.html
15
+ const Interface = pgGISGraphQLInterfaceTypesByType[pgGISType.id][zmflag];
16
+ if (!Interface) {
17
+ console.warn("Unexpectedly couldn't find the interface");
18
+ return fields;
19
+ }
20
+ return extend(fields, {
21
+ geometries: {
22
+ type: new GraphQLList(Interface),
23
+ resolve(data) {
24
+ const geometryCollection = data.__geojson;
25
+ return geometryCollection.geometries.map((geom) => {
26
+ const subtype = GisSubtype[geom.type];
27
+ if (subtype === undefined) {
28
+ throw new Error(`Unsupported geometry subtype ${geom.type}`);
29
+ }
30
+ return {
31
+ __gisType: getGISTypeName(subtype, hasZ, hasM),
32
+ __srid: data.__srid,
33
+ __geojson: geom
34
+ };
35
+ });
36
+ }
37
+ }
38
+ });
39
+ });
40
+ };
41
+ export default PostgisGeometryCollectionGeometriesPlugin;
@@ -0,0 +1,38 @@
1
+ import { GisSubtype } from './constants';
2
+ import { getGISTypeName } from './utils';
3
+ const PostgisLineStringPointsPlugin = (builder) => {
4
+ builder.hook('GraphQLObjectType:fields', (fields, build, context) => {
5
+ const { scope: { isPgGISType, pgGISType, pgGISTypeDetails } } = context;
6
+ if (!isPgGISType ||
7
+ !pgGISType ||
8
+ !pgGISTypeDetails ||
9
+ pgGISTypeDetails.subtype !== GisSubtype.LineString) {
10
+ return fields;
11
+ }
12
+ const { extend, getPostgisTypeByGeometryType, graphql: { GraphQLList } } = build;
13
+ const { hasZ, hasM, srid } = pgGISTypeDetails;
14
+ const Point = getPostgisTypeByGeometryType(pgGISType, GisSubtype.Point, hasZ, hasM, srid);
15
+ if (!Point) {
16
+ return fields;
17
+ }
18
+ return extend(fields, {
19
+ points: {
20
+ type: new GraphQLList(Point),
21
+ resolve(data) {
22
+ const lineString = data.__geojson;
23
+ return lineString.coordinates.map((coord) => {
24
+ return {
25
+ __gisType: getGISTypeName(GisSubtype.Point, hasZ, hasM),
26
+ __srid: data.__srid,
27
+ __geojson: {
28
+ type: 'Point',
29
+ coordinates: coord
30
+ }
31
+ };
32
+ });
33
+ }
34
+ }
35
+ });
36
+ });
37
+ };
38
+ export default PostgisLineStringPointsPlugin;