graphile-function-source 0.0.0-stage → 0.2.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.
- package/LICENSE +23 -0
- package/README.md +111 -2
- package/esm/function-from-source.d.ts +50 -0
- package/esm/function-from-source.js +289 -0
- package/esm/index.d.ts +2 -0
- package/esm/index.js +1 -0
- package/function-from-source.d.ts +50 -0
- package/function-from-source.js +293 -0
- package/index.d.ts +2 -0
- package/index.js +9 -0
- package/package.json +56 -4
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.
|
package/README.md
CHANGED
|
@@ -1,3 +1,112 @@
|
|
|
1
|
-
#
|
|
1
|
+
# graphile-function-source
|
|
2
2
|
|
|
3
|
-
|
|
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"><img height="20" src="https://img.shields.io/badge/license-MIT-blue.svg"/></a>
|
|
12
|
+
<a href="https://www.npmjs.com/package/graphile-function-source"><img height="20" src="https://img.shields.io/github/package-json/v/constructive-io/constructive?filename=graphile%2Fgraphile-function-source%2Fpackage.json"/></a>
|
|
13
|
+
</p>
|
|
14
|
+
|
|
15
|
+
Author PostgreSQL functions from `CREATE FUNCTION` source text in PostGraphile v5.
|
|
16
|
+
|
|
17
|
+
Adds two mutations over the `metaschema_public.function` table:
|
|
18
|
+
|
|
19
|
+
- `createFunctionFromSource(input: { databaseId, schemaId, source, apiExposed })`, when the table is insertable — the same insert as `createFunction`.
|
|
20
|
+
- `updateFunctionFromSource(input: { id, source })`, when the table is updatable — the same update as `updateFunction`. It rewrites only the definition columns; `databaseId`, `schemaId` and `apiExposed` are unchanged.
|
|
21
|
+
|
|
22
|
+
Both take the same text: one plain `CREATE FUNCTION` statement. `CREATE OR REPLACE` is refused by both — replacing is what `updateFunctionFromSource` means.
|
|
23
|
+
|
|
24
|
+
The server parses `source` with [`plpgsql-parser`](https://www.npmjs.com/package/plpgsql-parser), maps it onto the table's columns (`name`, `kind`, `arguments`, `returns`, `volatility`, `is_strict`, `security_invoker`, and the hydrated `body_ast`), and writes the same row `createFunction` / `updateFunction` would, on the request's own client. The database decides whether a definition is allowed; the plugin only parses and writes. Deleting needs no source: use the generated `deleteFunction`.
|
|
25
|
+
|
|
26
|
+
Parse failures are GraphQL errors with `extensions.code = 'FUNCTION_SOURCE_PARSE_ERROR'` and, when the parser reports one, `extensions.position` (0-based offset into `source`). Constructs the table cannot represent are refused with `FUNCTION_SOURCE_UNSUPPORTED`.
|
|
27
|
+
|
|
28
|
+
## Usage
|
|
29
|
+
|
|
30
|
+
```ts
|
|
31
|
+
import { FunctionFromSourcePreset } from 'graphile-function-source';
|
|
32
|
+
|
|
33
|
+
const preset = {
|
|
34
|
+
extends: [FunctionFromSourcePreset]
|
|
35
|
+
};
|
|
36
|
+
```
|
|
37
|
+
|
|
38
|
+
`parseFunctionSource(source)` is exported for parsing without GraphQL.
|
|
39
|
+
|
|
40
|
+
---
|
|
41
|
+
|
|
42
|
+
## Education and Tutorials
|
|
43
|
+
|
|
44
|
+
1. 🚀 [Quickstart: Getting Up and Running](https://constructive.io/learn/quickstart)
|
|
45
|
+
Get started with modular databases in minutes. Install prerequisites and deploy your first module.
|
|
46
|
+
|
|
47
|
+
2. 📦 [Modular PostgreSQL Development with Database Packages](https://constructive.io/learn/modular-postgres)
|
|
48
|
+
Learn to organize PostgreSQL projects with pgpm workspaces and reusable database modules.
|
|
49
|
+
|
|
50
|
+
3. ✏️ [Authoring Database Changes](https://constructive.io/learn/authoring-database-changes)
|
|
51
|
+
Master the workflow for adding, organizing, and managing database changes with pgpm.
|
|
52
|
+
|
|
53
|
+
4. 🧪 [End-to-End PostgreSQL Testing with TypeScript](https://constructive.io/learn/e2e-postgres-testing)
|
|
54
|
+
Master end-to-end PostgreSQL testing with ephemeral databases, RLS testing, and CI/CD automation.
|
|
55
|
+
|
|
56
|
+
5. ⚡ [Supabase Testing](https://constructive.io/learn/supabase)
|
|
57
|
+
Use TypeScript-first tools to test Supabase projects with realistic RLS, policies, and auth contexts.
|
|
58
|
+
|
|
59
|
+
6. 💧 [Drizzle ORM Testing](https://constructive.io/learn/drizzle-testing)
|
|
60
|
+
Run full-stack tests with Drizzle ORM, including database setup, teardown, and RLS enforcement.
|
|
61
|
+
|
|
62
|
+
7. 🔧 [Troubleshooting](https://constructive.io/learn/troubleshooting)
|
|
63
|
+
Common issues and solutions for pgpm, PostgreSQL, and testing.
|
|
64
|
+
|
|
65
|
+
## Related Constructive Tooling
|
|
66
|
+
|
|
67
|
+
### 📦 Package Management
|
|
68
|
+
|
|
69
|
+
* [pgpm](https://github.com/constructive-io/constructive/tree/main/pgpm/pgpm): **🖥️ PostgreSQL Package Manager** for modular Postgres development. Works with database workspaces, scaffolding, migrations, seeding, and installing database packages.
|
|
70
|
+
|
|
71
|
+
### 🧪 Testing
|
|
72
|
+
|
|
73
|
+
* [pgsql-test](https://github.com/constructive-io/constructive/tree/main/postgres/pgsql-test): **📊 Isolated testing environments** with per-test transaction rollbacks—ideal for integration tests, complex migrations, and RLS simulation.
|
|
74
|
+
* [pglite-test](https://github.com/constructive-io/constructive/tree/main/postgres/pglite-test): **🪶 Drop-in pgsql-test replacement backed by PGlite** — in-process Postgres, no server required, instance-per-suite isolation.
|
|
75
|
+
* [pgsql-seed](https://github.com/constructive-io/constructive/tree/main/postgres/pgsql-seed): **🌱 PostgreSQL seeding utilities** for CSV, JSON, SQL data loading, and pgpm deployment.
|
|
76
|
+
* [supabase-test](https://github.com/constructive-io/constructive/tree/main/postgres/supabase-test): **🧪 Supabase-native test harness** preconfigured for the local Supabase stack—per-test rollbacks, JWT/role context helpers, and CI/GitHub Actions ready.
|
|
77
|
+
* [graphile-test](https://github.com/constructive-io/constructive/tree/main/graphile/graphile-test): **🔐 Authentication mocking** for Graphile-focused test helpers and emulating row-level security contexts.
|
|
78
|
+
* [pg-query-context](https://github.com/constructive-io/constructive/tree/main/postgres/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.
|
|
79
|
+
|
|
80
|
+
### 🧠 Parsing & AST
|
|
81
|
+
|
|
82
|
+
* [pgsql-parser](https://www.npmjs.com/package/pgsql-parser): **🔄 SQL conversion engine** that interprets and converts PostgreSQL syntax.
|
|
83
|
+
* [libpg-query-node](https://www.npmjs.com/package/libpg-query): **🌉 Node.js bindings** for `libpg_query`, converting SQL into parse trees.
|
|
84
|
+
* [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.
|
|
85
|
+
* [@pgsql/enums](https://www.npmjs.com/package/@pgsql/enums): **🏷️ TypeScript enums** for PostgreSQL AST for safe and ergonomic parsing logic.
|
|
86
|
+
* [@pgsql/types](https://www.npmjs.com/package/@pgsql/types): **📝 Type definitions** for PostgreSQL AST nodes in TypeScript.
|
|
87
|
+
* [@pgsql/utils](https://www.npmjs.com/package/@pgsql/utils): **🛠️ AST utilities** for constructing and transforming PostgreSQL syntax trees.
|
|
88
|
+
|
|
89
|
+
### 📚 Documentation & Skills
|
|
90
|
+
|
|
91
|
+
* [constructive-skills](https://github.com/constructive-io/constructive-skills): **📖 Platform documentation and AI agent skills** — feature catalog, blueprint reference, SDK guides (i18n, billing, limits, events, uploads, security, entities, search, AI), and deployment guides.
|
|
92
|
+
|
|
93
|
+
Install skills for AI coding agents:
|
|
94
|
+
|
|
95
|
+
```bash
|
|
96
|
+
# All platform skills (security, blueprints, codegen, billing, etc.)
|
|
97
|
+
npx skills add constructive-io/constructive-skills
|
|
98
|
+
|
|
99
|
+
# Individual repo skills (pgpm, testing, CLI, search, etc.)
|
|
100
|
+
npx skills add https://github.com/constructive-io/constructive --skill pgpm
|
|
101
|
+
npx skills add https://github.com/constructive-io/constructive --skill constructive-testing
|
|
102
|
+
```
|
|
103
|
+
|
|
104
|
+
## Credits
|
|
105
|
+
|
|
106
|
+
**🛠 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).**
|
|
107
|
+
|
|
108
|
+
## Disclaimer
|
|
109
|
+
|
|
110
|
+
AS DESCRIBED IN THE LICENSES, THE SOFTWARE IS PROVIDED "AS IS", AT YOUR OWN RISK, AND WITHOUT WARRANTIES OF ANY KIND.
|
|
111
|
+
|
|
112
|
+
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,50 @@
|
|
|
1
|
+
import 'graphile-build';
|
|
2
|
+
import 'graphile-build-pg';
|
|
3
|
+
import type { GraphileConfig } from 'graphile-config';
|
|
4
|
+
type AstNode = Record<string, any>;
|
|
5
|
+
interface FieldType {
|
|
6
|
+
name: string;
|
|
7
|
+
schema?: string;
|
|
8
|
+
args?: (number | string)[];
|
|
9
|
+
array_dimensions?: number;
|
|
10
|
+
}
|
|
11
|
+
export interface FunctionDefinition {
|
|
12
|
+
name: string;
|
|
13
|
+
kind: 'sql' | 'plpgsql' | 'trigger';
|
|
14
|
+
arguments: {
|
|
15
|
+
name?: string;
|
|
16
|
+
type: FieldType;
|
|
17
|
+
mode?: string;
|
|
18
|
+
}[];
|
|
19
|
+
returns: {
|
|
20
|
+
type: FieldType;
|
|
21
|
+
setof?: boolean;
|
|
22
|
+
} | {
|
|
23
|
+
table: {
|
|
24
|
+
name: string;
|
|
25
|
+
type: FieldType;
|
|
26
|
+
}[];
|
|
27
|
+
};
|
|
28
|
+
volatility: 'IMMUTABLE' | 'STABLE' | 'VOLATILE';
|
|
29
|
+
is_strict: boolean;
|
|
30
|
+
security_invoker: boolean;
|
|
31
|
+
body_ast: AstNode;
|
|
32
|
+
}
|
|
33
|
+
export declare const FUNCTION_SOURCE_PARSE_ERROR = "FUNCTION_SOURCE_PARSE_ERROR";
|
|
34
|
+
export declare const FUNCTION_SOURCE_UNSUPPORTED = "FUNCTION_SOURCE_UNSUPPORTED";
|
|
35
|
+
/**
|
|
36
|
+
* Maps one `CREATE FUNCTION` statement onto the columns `metaschema_public.function`
|
|
37
|
+
* accepts. Anything those columns cannot carry is refused rather than dropped; whether
|
|
38
|
+
* the definition is *allowed* is left to the database.
|
|
39
|
+
* Create and update take the same text: replacing is chosen by the mutation, not the source.
|
|
40
|
+
*/
|
|
41
|
+
export declare const parseFunctionSource: (source: string) => Promise<FunctionDefinition>;
|
|
42
|
+
/**
|
|
43
|
+
* `createFunctionFromSource` / `updateFunctionFromSource`: author or replace a customer
|
|
44
|
+
* function from SQL text. The server parses (the database never parses strings) and
|
|
45
|
+
* performs the same `pgInsertSingle` / `pgUpdateSingle` as `createFunction` /
|
|
46
|
+
* `updateFunction`, on the request's own client.
|
|
47
|
+
*/
|
|
48
|
+
export declare const FunctionFromSourcePlugin: GraphileConfig.Plugin;
|
|
49
|
+
export declare const FunctionFromSourcePreset: GraphileConfig.Preset;
|
|
50
|
+
export {};
|
|
@@ -0,0 +1,289 @@
|
|
|
1
|
+
import 'graphile-build';
|
|
2
|
+
import 'graphile-build-pg';
|
|
3
|
+
import { pgInsertSingle, pgUpdateSingle } from '@dataplan/pg';
|
|
4
|
+
import { access, lambda, object } from 'grafast';
|
|
5
|
+
import { GraphQLError } from 'graphql';
|
|
6
|
+
import { loadModule, parseSql, parseSync } from 'plpgsql-parser';
|
|
7
|
+
export const FUNCTION_SOURCE_PARSE_ERROR = 'FUNCTION_SOURCE_PARSE_ERROR';
|
|
8
|
+
export const FUNCTION_SOURCE_UNSUPPORTED = 'FUNCTION_SOURCE_UNSUPPORTED';
|
|
9
|
+
/** `position` is the parser's 0-based offset into the submitted source. */
|
|
10
|
+
const sourceError = (code, message, position) => new GraphQLError(message, {
|
|
11
|
+
extensions: position === undefined ? { code } : { code, position }
|
|
12
|
+
});
|
|
13
|
+
const unsupported = (message, position) => sourceError(FUNCTION_SOURCE_UNSUPPORTED, message, position);
|
|
14
|
+
/** Rethrows anything that is not a parser syntax error. */
|
|
15
|
+
const asParseError = (err, offset) => {
|
|
16
|
+
const details = err.sqlDetails;
|
|
17
|
+
if (!details)
|
|
18
|
+
throw err;
|
|
19
|
+
return sourceError(FUNCTION_SOURCE_PARSE_ERROR, details.message, offset === undefined ? undefined : offset + details.cursorPosition);
|
|
20
|
+
};
|
|
21
|
+
const sval = (node) => node.String.sval;
|
|
22
|
+
const MODES = {
|
|
23
|
+
FUNC_PARAM_DEFAULT: undefined,
|
|
24
|
+
FUNC_PARAM_IN: 'in',
|
|
25
|
+
FUNC_PARAM_OUT: 'out',
|
|
26
|
+
FUNC_PARAM_INOUT: 'inout',
|
|
27
|
+
FUNC_PARAM_VARIADIC: 'variadic'
|
|
28
|
+
};
|
|
29
|
+
const fieldType = (typeName) => {
|
|
30
|
+
if (typeName.pct_type)
|
|
31
|
+
throw unsupported('%TYPE references are not supported', typeName.location);
|
|
32
|
+
if (typeName.setof)
|
|
33
|
+
throw unsupported('SETOF is only supported as the return type', typeName.location);
|
|
34
|
+
const names = typeName.names.map(sval);
|
|
35
|
+
if (names.length > 2)
|
|
36
|
+
throw unsupported('type names take at most a schema qualifier', typeName.location);
|
|
37
|
+
const name = names[names.length - 1];
|
|
38
|
+
const type = { name };
|
|
39
|
+
if (names.length === 2 && names[0] !== 'pg_catalog')
|
|
40
|
+
type.schema = names[0];
|
|
41
|
+
if (typeName.typmods) {
|
|
42
|
+
if (name === 'interval')
|
|
43
|
+
throw unsupported('interval field qualifiers are not supported', typeName.location);
|
|
44
|
+
type.args = typeName.typmods.map((mod) => {
|
|
45
|
+
const value = mod.A_Const?.ival?.ival ?? mod.A_Const?.sval?.sval;
|
|
46
|
+
if (value === undefined)
|
|
47
|
+
throw unsupported('type modifiers must be constants', typeName.location);
|
|
48
|
+
return value;
|
|
49
|
+
});
|
|
50
|
+
}
|
|
51
|
+
if (typeName.arrayBounds)
|
|
52
|
+
type.array_dimensions = typeName.arrayBounds.length;
|
|
53
|
+
return type;
|
|
54
|
+
};
|
|
55
|
+
/**
|
|
56
|
+
* Maps one `CREATE FUNCTION` statement onto the columns `metaschema_public.function`
|
|
57
|
+
* accepts. Anything those columns cannot carry is refused rather than dropped; whether
|
|
58
|
+
* the definition is *allowed* is left to the database.
|
|
59
|
+
* Create and update take the same text: replacing is chosen by the mutation, not the source.
|
|
60
|
+
*/
|
|
61
|
+
export const parseFunctionSource = async (source) => {
|
|
62
|
+
await loadModule();
|
|
63
|
+
let parsed;
|
|
64
|
+
try {
|
|
65
|
+
parsed = parseSync(source);
|
|
66
|
+
}
|
|
67
|
+
catch (err) {
|
|
68
|
+
throw asParseError(err, 0);
|
|
69
|
+
}
|
|
70
|
+
const stmts = parsed.sql.stmts ?? [];
|
|
71
|
+
if (stmts.length !== 1 || !stmts[0].stmt.CreateFunctionStmt) {
|
|
72
|
+
throw unsupported('source must be exactly one CREATE FUNCTION statement', stmts[1]?.stmt_location);
|
|
73
|
+
}
|
|
74
|
+
const stmt = stmts[0].stmt.CreateFunctionStmt;
|
|
75
|
+
if (stmt.is_procedure)
|
|
76
|
+
throw unsupported('procedures are not supported');
|
|
77
|
+
if (stmt.replace) {
|
|
78
|
+
throw unsupported('CREATE OR REPLACE is not supported; to replace a function, send CREATE FUNCTION to updateFunctionFromSource with its id');
|
|
79
|
+
}
|
|
80
|
+
if (stmt.sql_body)
|
|
81
|
+
throw unsupported('write the body as a string literal (AS $$ ... $$)');
|
|
82
|
+
if (stmt.funcname.length !== 1) {
|
|
83
|
+
throw unsupported('the function name must be unqualified; schemaId chooses its schema');
|
|
84
|
+
}
|
|
85
|
+
let language;
|
|
86
|
+
let body;
|
|
87
|
+
let bodyLocation;
|
|
88
|
+
let volatility = 'VOLATILE';
|
|
89
|
+
let isStrict = false;
|
|
90
|
+
let securityInvoker = true;
|
|
91
|
+
for (const { DefElem: opt } of stmt.options ?? []) {
|
|
92
|
+
switch (opt.defname) {
|
|
93
|
+
case 'language':
|
|
94
|
+
language = sval(opt.arg).toLowerCase();
|
|
95
|
+
break;
|
|
96
|
+
case 'as':
|
|
97
|
+
if (opt.arg.List.items.length !== 1)
|
|
98
|
+
throw unsupported('AS takes a single body string', opt.location);
|
|
99
|
+
body = sval(opt.arg.List.items[0]);
|
|
100
|
+
bodyLocation = opt.location;
|
|
101
|
+
break;
|
|
102
|
+
case 'volatility':
|
|
103
|
+
volatility = sval(opt.arg).toUpperCase();
|
|
104
|
+
break;
|
|
105
|
+
case 'strict':
|
|
106
|
+
isStrict = Boolean(opt.arg.Boolean.boolval);
|
|
107
|
+
break;
|
|
108
|
+
case 'security':
|
|
109
|
+
securityInvoker = !opt.arg.Boolean.boolval;
|
|
110
|
+
break;
|
|
111
|
+
default:
|
|
112
|
+
throw unsupported(`${opt.defname.toUpperCase()} is not supported`, opt.location);
|
|
113
|
+
}
|
|
114
|
+
}
|
|
115
|
+
if (body === undefined)
|
|
116
|
+
throw unsupported('the function has no body (AS $$ ... $$)');
|
|
117
|
+
const args = [];
|
|
118
|
+
const table = [];
|
|
119
|
+
for (const { FunctionParameter: param } of stmt.parameters ?? []) {
|
|
120
|
+
if (param.defexpr)
|
|
121
|
+
throw unsupported('argument defaults are not supported', param.location);
|
|
122
|
+
if (param.mode === 'FUNC_PARAM_TABLE') {
|
|
123
|
+
table.push({ name: param.name, type: fieldType(param.argType) });
|
|
124
|
+
continue;
|
|
125
|
+
}
|
|
126
|
+
if (!(param.mode in MODES))
|
|
127
|
+
throw unsupported(`argument mode ${param.mode} is not supported`, param.location);
|
|
128
|
+
const mode = MODES[param.mode];
|
|
129
|
+
args.push({
|
|
130
|
+
...(param.name ? { name: param.name } : {}),
|
|
131
|
+
type: fieldType(param.argType),
|
|
132
|
+
...(mode ? { mode } : {})
|
|
133
|
+
});
|
|
134
|
+
}
|
|
135
|
+
const returnType = stmt.returnType;
|
|
136
|
+
if (!returnType)
|
|
137
|
+
throw unsupported('the function must declare RETURNS');
|
|
138
|
+
const returns = table.length
|
|
139
|
+
? { table }
|
|
140
|
+
: { type: fieldType({ ...returnType, setof: false }), ...(returnType.setof ? { setof: true } : {}) };
|
|
141
|
+
const common = {
|
|
142
|
+
name: sval(stmt.funcname[0]),
|
|
143
|
+
arguments: args,
|
|
144
|
+
returns,
|
|
145
|
+
volatility,
|
|
146
|
+
is_strict: isStrict,
|
|
147
|
+
security_invoker: securityInvoker
|
|
148
|
+
};
|
|
149
|
+
if (language === 'sql') {
|
|
150
|
+
// Body offsets map onto the source only when the body appears verbatim (dollar-quoted).
|
|
151
|
+
const bodyStart = source.indexOf(body, bodyLocation);
|
|
152
|
+
let bodyAst;
|
|
153
|
+
try {
|
|
154
|
+
bodyAst = parseSql(body);
|
|
155
|
+
}
|
|
156
|
+
catch (err) {
|
|
157
|
+
throw asParseError(err, bodyStart < 0 ? undefined : bodyStart);
|
|
158
|
+
}
|
|
159
|
+
return { ...common, kind: 'sql', body_ast: bodyAst };
|
|
160
|
+
}
|
|
161
|
+
if (language === 'plpgsql') {
|
|
162
|
+
const [bodyError] = parsed.errors;
|
|
163
|
+
if (bodyError)
|
|
164
|
+
throw sourceError(FUNCTION_SOURCE_PARSE_ERROR, bodyError.message);
|
|
165
|
+
const fn = parsed.functions[0];
|
|
166
|
+
const [hydrationError] = fn.plpgsql.errors;
|
|
167
|
+
if (hydrationError)
|
|
168
|
+
throw sourceError(FUNCTION_SOURCE_PARSE_ERROR, hydrationError.error);
|
|
169
|
+
const kind = 'type' in returns && returns.type.name === 'trigger' ? 'trigger' : 'plpgsql';
|
|
170
|
+
return { ...common, kind, body_ast: fn.plpgsql.hydrated.plpgsql_funcs[0] };
|
|
171
|
+
}
|
|
172
|
+
throw unsupported(`LANGUAGE ${language ?? '(none)'} is not supported; use plpgsql or sql`);
|
|
173
|
+
};
|
|
174
|
+
const isFunctionTable = (resource) => {
|
|
175
|
+
const pg = resource.codec.extensions?.pg;
|
|
176
|
+
return !resource.parameters && pg?.schemaName === 'metaschema_public' && pg?.name === 'function';
|
|
177
|
+
};
|
|
178
|
+
/** `updateFunctionFromSource` addresses the row the way `updateFunction` does: by `id`. */
|
|
179
|
+
const isIdPrimaryKey = (unique) => Boolean(unique.isPrimary) && unique.attributes.length === 1 && unique.attributes[0] === 'id';
|
|
180
|
+
const findFunctionResource = (build, behavior) => Object.values(build.pgResources).find((resource) => isFunctionTable(resource) &&
|
|
181
|
+
(behavior === 'resource:insert' || resource.uniques.some(isIdPrimaryKey)) &&
|
|
182
|
+
build.behavior.pgResourceMatches(resource, behavior) === true);
|
|
183
|
+
const CREATE_INPUT = 'CreateFunctionFromSourceInput';
|
|
184
|
+
const UPDATE_INPUT = 'UpdateFunctionFromSourceInput';
|
|
185
|
+
/** The columns the source text decides; create and update write exactly these. */
|
|
186
|
+
const definitionColumns = ($input) => {
|
|
187
|
+
const $definition = lambda(access($input, 'source'), (source) => parseFunctionSource(source));
|
|
188
|
+
return {
|
|
189
|
+
name: access($definition, 'name'),
|
|
190
|
+
kind: access($definition, 'kind'),
|
|
191
|
+
arguments: access($definition, 'arguments'),
|
|
192
|
+
returns: access($definition, 'returns'),
|
|
193
|
+
volatility: access($definition, 'volatility'),
|
|
194
|
+
is_strict: access($definition, 'is_strict'),
|
|
195
|
+
security_invoker: access($definition, 'security_invoker'),
|
|
196
|
+
body_ast: access($definition, 'body_ast')
|
|
197
|
+
};
|
|
198
|
+
};
|
|
199
|
+
/**
|
|
200
|
+
* `createFunctionFromSource` / `updateFunctionFromSource`: author or replace a customer
|
|
201
|
+
* function from SQL text. The server parses (the database never parses strings) and
|
|
202
|
+
* performs the same `pgInsertSingle` / `pgUpdateSingle` as `createFunction` /
|
|
203
|
+
* `updateFunction`, on the request's own client.
|
|
204
|
+
*/
|
|
205
|
+
export const FunctionFromSourcePlugin = {
|
|
206
|
+
name: 'FunctionFromSourcePlugin',
|
|
207
|
+
version: '1.0.0',
|
|
208
|
+
after: ['PgMutationCreatePlugin', 'PgMutationUpdateDeletePlugin', 'PgMutationPayloadEdgePlugin'],
|
|
209
|
+
schema: {
|
|
210
|
+
hooks: {
|
|
211
|
+
init(_, build) {
|
|
212
|
+
const { GraphQLBoolean, GraphQLNonNull, GraphQLString } = build.graphql;
|
|
213
|
+
const register = (name, description, fields) => build.registerInputObjectType(name, { isMutationInput: true }, () => ({
|
|
214
|
+
description,
|
|
215
|
+
fields: () => ({
|
|
216
|
+
clientMutationId: {
|
|
217
|
+
type: GraphQLString,
|
|
218
|
+
apply(qb, val) {
|
|
219
|
+
qb.setMeta('clientMutationId', val);
|
|
220
|
+
}
|
|
221
|
+
},
|
|
222
|
+
...fields(build.getInputTypeByName('UUID')),
|
|
223
|
+
source: {
|
|
224
|
+
type: new GraphQLNonNull(GraphQLString),
|
|
225
|
+
description: 'One `CREATE FUNCTION` statement (LANGUAGE plpgsql or sql).'
|
|
226
|
+
}
|
|
227
|
+
})
|
|
228
|
+
}), 'FunctionFromSourcePlugin input');
|
|
229
|
+
if (findFunctionResource(build, 'resource:insert')) {
|
|
230
|
+
register(CREATE_INPUT, 'Author a function from its `CREATE FUNCTION` source text.', (uuid) => ({
|
|
231
|
+
databaseId: { type: new GraphQLNonNull(uuid) },
|
|
232
|
+
schemaId: { type: new GraphQLNonNull(uuid) },
|
|
233
|
+
apiExposed: { type: GraphQLBoolean, defaultValue: false }
|
|
234
|
+
}));
|
|
235
|
+
}
|
|
236
|
+
if (findFunctionResource(build, 'resource:update')) {
|
|
237
|
+
register(UPDATE_INPUT, 'Replace a function\'s definition from its `CREATE FUNCTION` source text.', (uuid) => ({ id: { type: new GraphQLNonNull(uuid) } }));
|
|
238
|
+
}
|
|
239
|
+
return _;
|
|
240
|
+
},
|
|
241
|
+
GraphQLObjectType_fields(fields, build, context) {
|
|
242
|
+
if (!context.scope.isRootMutation)
|
|
243
|
+
return fields;
|
|
244
|
+
const { GraphQLNonNull } = build.graphql;
|
|
245
|
+
const field = (fieldName, description, payloadType, inputType, plan) => context.fieldWithHooks({ fieldName }, {
|
|
246
|
+
description,
|
|
247
|
+
type: build.getOutputTypeByName(payloadType),
|
|
248
|
+
args: {
|
|
249
|
+
input: {
|
|
250
|
+
type: new GraphQLNonNull(build.getInputTypeByName(inputType)),
|
|
251
|
+
applyPlan(_, $mutation) {
|
|
252
|
+
return $mutation;
|
|
253
|
+
}
|
|
254
|
+
}
|
|
255
|
+
},
|
|
256
|
+
plan(_$root, fieldArgs) {
|
|
257
|
+
const $mutation = plan(fieldArgs);
|
|
258
|
+
fieldArgs.apply($mutation);
|
|
259
|
+
return object({ result: $mutation });
|
|
260
|
+
}
|
|
261
|
+
});
|
|
262
|
+
const added = {};
|
|
263
|
+
const insertable = findFunctionResource(build, 'resource:insert');
|
|
264
|
+
if (insertable) {
|
|
265
|
+
added.createFunctionFromSource = field('createFunctionFromSource', 'Creates a `Function` from its `CREATE FUNCTION` source text.', build.inflection.createPayloadType(insertable), CREATE_INPUT, (fieldArgs) => {
|
|
266
|
+
const $input = fieldArgs.getRaw('input');
|
|
267
|
+
return pgInsertSingle(insertable, {
|
|
268
|
+
database_id: access($input, 'databaseId'),
|
|
269
|
+
schema_id: access($input, 'schemaId'),
|
|
270
|
+
api_exposed: access($input, 'apiExposed'),
|
|
271
|
+
...definitionColumns($input)
|
|
272
|
+
});
|
|
273
|
+
});
|
|
274
|
+
}
|
|
275
|
+
const updatable = findFunctionResource(build, 'resource:update');
|
|
276
|
+
if (updatable) {
|
|
277
|
+
added.updateFunctionFromSource = field('updateFunctionFromSource', 'Replaces a `Function`\'s definition from its source text; its database, schema and exposure are unchanged.', build.inflection.updatePayloadType({ resource: updatable }), UPDATE_INPUT, (fieldArgs) => {
|
|
278
|
+
const $input = fieldArgs.getRaw('input');
|
|
279
|
+
return pgUpdateSingle(updatable, { id: access($input, 'id') }, definitionColumns($input));
|
|
280
|
+
});
|
|
281
|
+
}
|
|
282
|
+
return build.extend(fields, added, 'Adding FunctionFromSource mutations');
|
|
283
|
+
}
|
|
284
|
+
}
|
|
285
|
+
}
|
|
286
|
+
};
|
|
287
|
+
export const FunctionFromSourcePreset = {
|
|
288
|
+
plugins: [FunctionFromSourcePlugin]
|
|
289
|
+
};
|
package/esm/index.d.ts
ADDED
package/esm/index.js
ADDED
|
@@ -0,0 +1 @@
|
|
|
1
|
+
export { FUNCTION_SOURCE_PARSE_ERROR, FUNCTION_SOURCE_UNSUPPORTED, FunctionFromSourcePlugin, FunctionFromSourcePreset, parseFunctionSource } from './function-from-source';
|
|
@@ -0,0 +1,50 @@
|
|
|
1
|
+
import 'graphile-build';
|
|
2
|
+
import 'graphile-build-pg';
|
|
3
|
+
import type { GraphileConfig } from 'graphile-config';
|
|
4
|
+
type AstNode = Record<string, any>;
|
|
5
|
+
interface FieldType {
|
|
6
|
+
name: string;
|
|
7
|
+
schema?: string;
|
|
8
|
+
args?: (number | string)[];
|
|
9
|
+
array_dimensions?: number;
|
|
10
|
+
}
|
|
11
|
+
export interface FunctionDefinition {
|
|
12
|
+
name: string;
|
|
13
|
+
kind: 'sql' | 'plpgsql' | 'trigger';
|
|
14
|
+
arguments: {
|
|
15
|
+
name?: string;
|
|
16
|
+
type: FieldType;
|
|
17
|
+
mode?: string;
|
|
18
|
+
}[];
|
|
19
|
+
returns: {
|
|
20
|
+
type: FieldType;
|
|
21
|
+
setof?: boolean;
|
|
22
|
+
} | {
|
|
23
|
+
table: {
|
|
24
|
+
name: string;
|
|
25
|
+
type: FieldType;
|
|
26
|
+
}[];
|
|
27
|
+
};
|
|
28
|
+
volatility: 'IMMUTABLE' | 'STABLE' | 'VOLATILE';
|
|
29
|
+
is_strict: boolean;
|
|
30
|
+
security_invoker: boolean;
|
|
31
|
+
body_ast: AstNode;
|
|
32
|
+
}
|
|
33
|
+
export declare const FUNCTION_SOURCE_PARSE_ERROR = "FUNCTION_SOURCE_PARSE_ERROR";
|
|
34
|
+
export declare const FUNCTION_SOURCE_UNSUPPORTED = "FUNCTION_SOURCE_UNSUPPORTED";
|
|
35
|
+
/**
|
|
36
|
+
* Maps one `CREATE FUNCTION` statement onto the columns `metaschema_public.function`
|
|
37
|
+
* accepts. Anything those columns cannot carry is refused rather than dropped; whether
|
|
38
|
+
* the definition is *allowed* is left to the database.
|
|
39
|
+
* Create and update take the same text: replacing is chosen by the mutation, not the source.
|
|
40
|
+
*/
|
|
41
|
+
export declare const parseFunctionSource: (source: string) => Promise<FunctionDefinition>;
|
|
42
|
+
/**
|
|
43
|
+
* `createFunctionFromSource` / `updateFunctionFromSource`: author or replace a customer
|
|
44
|
+
* function from SQL text. The server parses (the database never parses strings) and
|
|
45
|
+
* performs the same `pgInsertSingle` / `pgUpdateSingle` as `createFunction` /
|
|
46
|
+
* `updateFunction`, on the request's own client.
|
|
47
|
+
*/
|
|
48
|
+
export declare const FunctionFromSourcePlugin: GraphileConfig.Plugin;
|
|
49
|
+
export declare const FunctionFromSourcePreset: GraphileConfig.Preset;
|
|
50
|
+
export {};
|
|
@@ -0,0 +1,293 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
Object.defineProperty(exports, "__esModule", { value: true });
|
|
3
|
+
exports.FunctionFromSourcePreset = exports.FunctionFromSourcePlugin = exports.parseFunctionSource = exports.FUNCTION_SOURCE_UNSUPPORTED = exports.FUNCTION_SOURCE_PARSE_ERROR = void 0;
|
|
4
|
+
require("graphile-build");
|
|
5
|
+
require("graphile-build-pg");
|
|
6
|
+
const pg_1 = require("@dataplan/pg");
|
|
7
|
+
const grafast_1 = require("grafast");
|
|
8
|
+
const graphql_1 = require("graphql");
|
|
9
|
+
const plpgsql_parser_1 = require("plpgsql-parser");
|
|
10
|
+
exports.FUNCTION_SOURCE_PARSE_ERROR = 'FUNCTION_SOURCE_PARSE_ERROR';
|
|
11
|
+
exports.FUNCTION_SOURCE_UNSUPPORTED = 'FUNCTION_SOURCE_UNSUPPORTED';
|
|
12
|
+
/** `position` is the parser's 0-based offset into the submitted source. */
|
|
13
|
+
const sourceError = (code, message, position) => new graphql_1.GraphQLError(message, {
|
|
14
|
+
extensions: position === undefined ? { code } : { code, position }
|
|
15
|
+
});
|
|
16
|
+
const unsupported = (message, position) => sourceError(exports.FUNCTION_SOURCE_UNSUPPORTED, message, position);
|
|
17
|
+
/** Rethrows anything that is not a parser syntax error. */
|
|
18
|
+
const asParseError = (err, offset) => {
|
|
19
|
+
const details = err.sqlDetails;
|
|
20
|
+
if (!details)
|
|
21
|
+
throw err;
|
|
22
|
+
return sourceError(exports.FUNCTION_SOURCE_PARSE_ERROR, details.message, offset === undefined ? undefined : offset + details.cursorPosition);
|
|
23
|
+
};
|
|
24
|
+
const sval = (node) => node.String.sval;
|
|
25
|
+
const MODES = {
|
|
26
|
+
FUNC_PARAM_DEFAULT: undefined,
|
|
27
|
+
FUNC_PARAM_IN: 'in',
|
|
28
|
+
FUNC_PARAM_OUT: 'out',
|
|
29
|
+
FUNC_PARAM_INOUT: 'inout',
|
|
30
|
+
FUNC_PARAM_VARIADIC: 'variadic'
|
|
31
|
+
};
|
|
32
|
+
const fieldType = (typeName) => {
|
|
33
|
+
if (typeName.pct_type)
|
|
34
|
+
throw unsupported('%TYPE references are not supported', typeName.location);
|
|
35
|
+
if (typeName.setof)
|
|
36
|
+
throw unsupported('SETOF is only supported as the return type', typeName.location);
|
|
37
|
+
const names = typeName.names.map(sval);
|
|
38
|
+
if (names.length > 2)
|
|
39
|
+
throw unsupported('type names take at most a schema qualifier', typeName.location);
|
|
40
|
+
const name = names[names.length - 1];
|
|
41
|
+
const type = { name };
|
|
42
|
+
if (names.length === 2 && names[0] !== 'pg_catalog')
|
|
43
|
+
type.schema = names[0];
|
|
44
|
+
if (typeName.typmods) {
|
|
45
|
+
if (name === 'interval')
|
|
46
|
+
throw unsupported('interval field qualifiers are not supported', typeName.location);
|
|
47
|
+
type.args = typeName.typmods.map((mod) => {
|
|
48
|
+
const value = mod.A_Const?.ival?.ival ?? mod.A_Const?.sval?.sval;
|
|
49
|
+
if (value === undefined)
|
|
50
|
+
throw unsupported('type modifiers must be constants', typeName.location);
|
|
51
|
+
return value;
|
|
52
|
+
});
|
|
53
|
+
}
|
|
54
|
+
if (typeName.arrayBounds)
|
|
55
|
+
type.array_dimensions = typeName.arrayBounds.length;
|
|
56
|
+
return type;
|
|
57
|
+
};
|
|
58
|
+
/**
|
|
59
|
+
* Maps one `CREATE FUNCTION` statement onto the columns `metaschema_public.function`
|
|
60
|
+
* accepts. Anything those columns cannot carry is refused rather than dropped; whether
|
|
61
|
+
* the definition is *allowed* is left to the database.
|
|
62
|
+
* Create and update take the same text: replacing is chosen by the mutation, not the source.
|
|
63
|
+
*/
|
|
64
|
+
const parseFunctionSource = async (source) => {
|
|
65
|
+
await (0, plpgsql_parser_1.loadModule)();
|
|
66
|
+
let parsed;
|
|
67
|
+
try {
|
|
68
|
+
parsed = (0, plpgsql_parser_1.parseSync)(source);
|
|
69
|
+
}
|
|
70
|
+
catch (err) {
|
|
71
|
+
throw asParseError(err, 0);
|
|
72
|
+
}
|
|
73
|
+
const stmts = parsed.sql.stmts ?? [];
|
|
74
|
+
if (stmts.length !== 1 || !stmts[0].stmt.CreateFunctionStmt) {
|
|
75
|
+
throw unsupported('source must be exactly one CREATE FUNCTION statement', stmts[1]?.stmt_location);
|
|
76
|
+
}
|
|
77
|
+
const stmt = stmts[0].stmt.CreateFunctionStmt;
|
|
78
|
+
if (stmt.is_procedure)
|
|
79
|
+
throw unsupported('procedures are not supported');
|
|
80
|
+
if (stmt.replace) {
|
|
81
|
+
throw unsupported('CREATE OR REPLACE is not supported; to replace a function, send CREATE FUNCTION to updateFunctionFromSource with its id');
|
|
82
|
+
}
|
|
83
|
+
if (stmt.sql_body)
|
|
84
|
+
throw unsupported('write the body as a string literal (AS $$ ... $$)');
|
|
85
|
+
if (stmt.funcname.length !== 1) {
|
|
86
|
+
throw unsupported('the function name must be unqualified; schemaId chooses its schema');
|
|
87
|
+
}
|
|
88
|
+
let language;
|
|
89
|
+
let body;
|
|
90
|
+
let bodyLocation;
|
|
91
|
+
let volatility = 'VOLATILE';
|
|
92
|
+
let isStrict = false;
|
|
93
|
+
let securityInvoker = true;
|
|
94
|
+
for (const { DefElem: opt } of stmt.options ?? []) {
|
|
95
|
+
switch (opt.defname) {
|
|
96
|
+
case 'language':
|
|
97
|
+
language = sval(opt.arg).toLowerCase();
|
|
98
|
+
break;
|
|
99
|
+
case 'as':
|
|
100
|
+
if (opt.arg.List.items.length !== 1)
|
|
101
|
+
throw unsupported('AS takes a single body string', opt.location);
|
|
102
|
+
body = sval(opt.arg.List.items[0]);
|
|
103
|
+
bodyLocation = opt.location;
|
|
104
|
+
break;
|
|
105
|
+
case 'volatility':
|
|
106
|
+
volatility = sval(opt.arg).toUpperCase();
|
|
107
|
+
break;
|
|
108
|
+
case 'strict':
|
|
109
|
+
isStrict = Boolean(opt.arg.Boolean.boolval);
|
|
110
|
+
break;
|
|
111
|
+
case 'security':
|
|
112
|
+
securityInvoker = !opt.arg.Boolean.boolval;
|
|
113
|
+
break;
|
|
114
|
+
default:
|
|
115
|
+
throw unsupported(`${opt.defname.toUpperCase()} is not supported`, opt.location);
|
|
116
|
+
}
|
|
117
|
+
}
|
|
118
|
+
if (body === undefined)
|
|
119
|
+
throw unsupported('the function has no body (AS $$ ... $$)');
|
|
120
|
+
const args = [];
|
|
121
|
+
const table = [];
|
|
122
|
+
for (const { FunctionParameter: param } of stmt.parameters ?? []) {
|
|
123
|
+
if (param.defexpr)
|
|
124
|
+
throw unsupported('argument defaults are not supported', param.location);
|
|
125
|
+
if (param.mode === 'FUNC_PARAM_TABLE') {
|
|
126
|
+
table.push({ name: param.name, type: fieldType(param.argType) });
|
|
127
|
+
continue;
|
|
128
|
+
}
|
|
129
|
+
if (!(param.mode in MODES))
|
|
130
|
+
throw unsupported(`argument mode ${param.mode} is not supported`, param.location);
|
|
131
|
+
const mode = MODES[param.mode];
|
|
132
|
+
args.push({
|
|
133
|
+
...(param.name ? { name: param.name } : {}),
|
|
134
|
+
type: fieldType(param.argType),
|
|
135
|
+
...(mode ? { mode } : {})
|
|
136
|
+
});
|
|
137
|
+
}
|
|
138
|
+
const returnType = stmt.returnType;
|
|
139
|
+
if (!returnType)
|
|
140
|
+
throw unsupported('the function must declare RETURNS');
|
|
141
|
+
const returns = table.length
|
|
142
|
+
? { table }
|
|
143
|
+
: { type: fieldType({ ...returnType, setof: false }), ...(returnType.setof ? { setof: true } : {}) };
|
|
144
|
+
const common = {
|
|
145
|
+
name: sval(stmt.funcname[0]),
|
|
146
|
+
arguments: args,
|
|
147
|
+
returns,
|
|
148
|
+
volatility,
|
|
149
|
+
is_strict: isStrict,
|
|
150
|
+
security_invoker: securityInvoker
|
|
151
|
+
};
|
|
152
|
+
if (language === 'sql') {
|
|
153
|
+
// Body offsets map onto the source only when the body appears verbatim (dollar-quoted).
|
|
154
|
+
const bodyStart = source.indexOf(body, bodyLocation);
|
|
155
|
+
let bodyAst;
|
|
156
|
+
try {
|
|
157
|
+
bodyAst = (0, plpgsql_parser_1.parseSql)(body);
|
|
158
|
+
}
|
|
159
|
+
catch (err) {
|
|
160
|
+
throw asParseError(err, bodyStart < 0 ? undefined : bodyStart);
|
|
161
|
+
}
|
|
162
|
+
return { ...common, kind: 'sql', body_ast: bodyAst };
|
|
163
|
+
}
|
|
164
|
+
if (language === 'plpgsql') {
|
|
165
|
+
const [bodyError] = parsed.errors;
|
|
166
|
+
if (bodyError)
|
|
167
|
+
throw sourceError(exports.FUNCTION_SOURCE_PARSE_ERROR, bodyError.message);
|
|
168
|
+
const fn = parsed.functions[0];
|
|
169
|
+
const [hydrationError] = fn.plpgsql.errors;
|
|
170
|
+
if (hydrationError)
|
|
171
|
+
throw sourceError(exports.FUNCTION_SOURCE_PARSE_ERROR, hydrationError.error);
|
|
172
|
+
const kind = 'type' in returns && returns.type.name === 'trigger' ? 'trigger' : 'plpgsql';
|
|
173
|
+
return { ...common, kind, body_ast: fn.plpgsql.hydrated.plpgsql_funcs[0] };
|
|
174
|
+
}
|
|
175
|
+
throw unsupported(`LANGUAGE ${language ?? '(none)'} is not supported; use plpgsql or sql`);
|
|
176
|
+
};
|
|
177
|
+
exports.parseFunctionSource = parseFunctionSource;
|
|
178
|
+
const isFunctionTable = (resource) => {
|
|
179
|
+
const pg = resource.codec.extensions?.pg;
|
|
180
|
+
return !resource.parameters && pg?.schemaName === 'metaschema_public' && pg?.name === 'function';
|
|
181
|
+
};
|
|
182
|
+
/** `updateFunctionFromSource` addresses the row the way `updateFunction` does: by `id`. */
|
|
183
|
+
const isIdPrimaryKey = (unique) => Boolean(unique.isPrimary) && unique.attributes.length === 1 && unique.attributes[0] === 'id';
|
|
184
|
+
const findFunctionResource = (build, behavior) => Object.values(build.pgResources).find((resource) => isFunctionTable(resource) &&
|
|
185
|
+
(behavior === 'resource:insert' || resource.uniques.some(isIdPrimaryKey)) &&
|
|
186
|
+
build.behavior.pgResourceMatches(resource, behavior) === true);
|
|
187
|
+
const CREATE_INPUT = 'CreateFunctionFromSourceInput';
|
|
188
|
+
const UPDATE_INPUT = 'UpdateFunctionFromSourceInput';
|
|
189
|
+
/** The columns the source text decides; create and update write exactly these. */
|
|
190
|
+
const definitionColumns = ($input) => {
|
|
191
|
+
const $definition = (0, grafast_1.lambda)((0, grafast_1.access)($input, 'source'), (source) => (0, exports.parseFunctionSource)(source));
|
|
192
|
+
return {
|
|
193
|
+
name: (0, grafast_1.access)($definition, 'name'),
|
|
194
|
+
kind: (0, grafast_1.access)($definition, 'kind'),
|
|
195
|
+
arguments: (0, grafast_1.access)($definition, 'arguments'),
|
|
196
|
+
returns: (0, grafast_1.access)($definition, 'returns'),
|
|
197
|
+
volatility: (0, grafast_1.access)($definition, 'volatility'),
|
|
198
|
+
is_strict: (0, grafast_1.access)($definition, 'is_strict'),
|
|
199
|
+
security_invoker: (0, grafast_1.access)($definition, 'security_invoker'),
|
|
200
|
+
body_ast: (0, grafast_1.access)($definition, 'body_ast')
|
|
201
|
+
};
|
|
202
|
+
};
|
|
203
|
+
/**
|
|
204
|
+
* `createFunctionFromSource` / `updateFunctionFromSource`: author or replace a customer
|
|
205
|
+
* function from SQL text. The server parses (the database never parses strings) and
|
|
206
|
+
* performs the same `pgInsertSingle` / `pgUpdateSingle` as `createFunction` /
|
|
207
|
+
* `updateFunction`, on the request's own client.
|
|
208
|
+
*/
|
|
209
|
+
exports.FunctionFromSourcePlugin = {
|
|
210
|
+
name: 'FunctionFromSourcePlugin',
|
|
211
|
+
version: '1.0.0',
|
|
212
|
+
after: ['PgMutationCreatePlugin', 'PgMutationUpdateDeletePlugin', 'PgMutationPayloadEdgePlugin'],
|
|
213
|
+
schema: {
|
|
214
|
+
hooks: {
|
|
215
|
+
init(_, build) {
|
|
216
|
+
const { GraphQLBoolean, GraphQLNonNull, GraphQLString } = build.graphql;
|
|
217
|
+
const register = (name, description, fields) => build.registerInputObjectType(name, { isMutationInput: true }, () => ({
|
|
218
|
+
description,
|
|
219
|
+
fields: () => ({
|
|
220
|
+
clientMutationId: {
|
|
221
|
+
type: GraphQLString,
|
|
222
|
+
apply(qb, val) {
|
|
223
|
+
qb.setMeta('clientMutationId', val);
|
|
224
|
+
}
|
|
225
|
+
},
|
|
226
|
+
...fields(build.getInputTypeByName('UUID')),
|
|
227
|
+
source: {
|
|
228
|
+
type: new GraphQLNonNull(GraphQLString),
|
|
229
|
+
description: 'One `CREATE FUNCTION` statement (LANGUAGE plpgsql or sql).'
|
|
230
|
+
}
|
|
231
|
+
})
|
|
232
|
+
}), 'FunctionFromSourcePlugin input');
|
|
233
|
+
if (findFunctionResource(build, 'resource:insert')) {
|
|
234
|
+
register(CREATE_INPUT, 'Author a function from its `CREATE FUNCTION` source text.', (uuid) => ({
|
|
235
|
+
databaseId: { type: new GraphQLNonNull(uuid) },
|
|
236
|
+
schemaId: { type: new GraphQLNonNull(uuid) },
|
|
237
|
+
apiExposed: { type: GraphQLBoolean, defaultValue: false }
|
|
238
|
+
}));
|
|
239
|
+
}
|
|
240
|
+
if (findFunctionResource(build, 'resource:update')) {
|
|
241
|
+
register(UPDATE_INPUT, 'Replace a function\'s definition from its `CREATE FUNCTION` source text.', (uuid) => ({ id: { type: new GraphQLNonNull(uuid) } }));
|
|
242
|
+
}
|
|
243
|
+
return _;
|
|
244
|
+
},
|
|
245
|
+
GraphQLObjectType_fields(fields, build, context) {
|
|
246
|
+
if (!context.scope.isRootMutation)
|
|
247
|
+
return fields;
|
|
248
|
+
const { GraphQLNonNull } = build.graphql;
|
|
249
|
+
const field = (fieldName, description, payloadType, inputType, plan) => context.fieldWithHooks({ fieldName }, {
|
|
250
|
+
description,
|
|
251
|
+
type: build.getOutputTypeByName(payloadType),
|
|
252
|
+
args: {
|
|
253
|
+
input: {
|
|
254
|
+
type: new GraphQLNonNull(build.getInputTypeByName(inputType)),
|
|
255
|
+
applyPlan(_, $mutation) {
|
|
256
|
+
return $mutation;
|
|
257
|
+
}
|
|
258
|
+
}
|
|
259
|
+
},
|
|
260
|
+
plan(_$root, fieldArgs) {
|
|
261
|
+
const $mutation = plan(fieldArgs);
|
|
262
|
+
fieldArgs.apply($mutation);
|
|
263
|
+
return (0, grafast_1.object)({ result: $mutation });
|
|
264
|
+
}
|
|
265
|
+
});
|
|
266
|
+
const added = {};
|
|
267
|
+
const insertable = findFunctionResource(build, 'resource:insert');
|
|
268
|
+
if (insertable) {
|
|
269
|
+
added.createFunctionFromSource = field('createFunctionFromSource', 'Creates a `Function` from its `CREATE FUNCTION` source text.', build.inflection.createPayloadType(insertable), CREATE_INPUT, (fieldArgs) => {
|
|
270
|
+
const $input = fieldArgs.getRaw('input');
|
|
271
|
+
return (0, pg_1.pgInsertSingle)(insertable, {
|
|
272
|
+
database_id: (0, grafast_1.access)($input, 'databaseId'),
|
|
273
|
+
schema_id: (0, grafast_1.access)($input, 'schemaId'),
|
|
274
|
+
api_exposed: (0, grafast_1.access)($input, 'apiExposed'),
|
|
275
|
+
...definitionColumns($input)
|
|
276
|
+
});
|
|
277
|
+
});
|
|
278
|
+
}
|
|
279
|
+
const updatable = findFunctionResource(build, 'resource:update');
|
|
280
|
+
if (updatable) {
|
|
281
|
+
added.updateFunctionFromSource = field('updateFunctionFromSource', 'Replaces a `Function`\'s definition from its source text; its database, schema and exposure are unchanged.', build.inflection.updatePayloadType({ resource: updatable }), UPDATE_INPUT, (fieldArgs) => {
|
|
282
|
+
const $input = fieldArgs.getRaw('input');
|
|
283
|
+
return (0, pg_1.pgUpdateSingle)(updatable, { id: (0, grafast_1.access)($input, 'id') }, definitionColumns($input));
|
|
284
|
+
});
|
|
285
|
+
}
|
|
286
|
+
return build.extend(fields, added, 'Adding FunctionFromSource mutations');
|
|
287
|
+
}
|
|
288
|
+
}
|
|
289
|
+
}
|
|
290
|
+
};
|
|
291
|
+
exports.FunctionFromSourcePreset = {
|
|
292
|
+
plugins: [exports.FunctionFromSourcePlugin]
|
|
293
|
+
};
|
package/index.d.ts
ADDED
package/index.js
ADDED
|
@@ -0,0 +1,9 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
Object.defineProperty(exports, "__esModule", { value: true });
|
|
3
|
+
exports.parseFunctionSource = exports.FunctionFromSourcePreset = exports.FunctionFromSourcePlugin = exports.FUNCTION_SOURCE_UNSUPPORTED = exports.FUNCTION_SOURCE_PARSE_ERROR = void 0;
|
|
4
|
+
var function_from_source_1 = require("./function-from-source");
|
|
5
|
+
Object.defineProperty(exports, "FUNCTION_SOURCE_PARSE_ERROR", { enumerable: true, get: function () { return function_from_source_1.FUNCTION_SOURCE_PARSE_ERROR; } });
|
|
6
|
+
Object.defineProperty(exports, "FUNCTION_SOURCE_UNSUPPORTED", { enumerable: true, get: function () { return function_from_source_1.FUNCTION_SOURCE_UNSUPPORTED; } });
|
|
7
|
+
Object.defineProperty(exports, "FunctionFromSourcePlugin", { enumerable: true, get: function () { return function_from_source_1.FunctionFromSourcePlugin; } });
|
|
8
|
+
Object.defineProperty(exports, "FunctionFromSourcePreset", { enumerable: true, get: function () { return function_from_source_1.FunctionFromSourcePreset; } });
|
|
9
|
+
Object.defineProperty(exports, "parseFunctionSource", { enumerable: true, get: function () { return function_from_source_1.parseFunctionSource; } });
|
package/package.json
CHANGED
|
@@ -1,6 +1,58 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "graphile-function-source",
|
|
3
|
-
"version": "0.
|
|
4
|
-
"
|
|
5
|
-
"
|
|
6
|
-
|
|
3
|
+
"version": "0.2.1",
|
|
4
|
+
"description": "Author PostgreSQL functions from CREATE FUNCTION source text in PostGraphile v5",
|
|
5
|
+
"author": "Constructive <developers@constructive.io>",
|
|
6
|
+
"homepage": "https://github.com/constructive-io/constructive",
|
|
7
|
+
"license": "MIT",
|
|
8
|
+
"main": "index.js",
|
|
9
|
+
"module": "esm/index.js",
|
|
10
|
+
"types": "index.d.ts",
|
|
11
|
+
"scripts": {
|
|
12
|
+
"clean": "makage clean",
|
|
13
|
+
"prepack": "npm run build",
|
|
14
|
+
"build": "makage build",
|
|
15
|
+
"build:dev": "makage build --dev",
|
|
16
|
+
"lint": "eslint . --fix",
|
|
17
|
+
"test": "jest"
|
|
18
|
+
},
|
|
19
|
+
"publishConfig": {
|
|
20
|
+
"access": "public",
|
|
21
|
+
"directory": "dist"
|
|
22
|
+
},
|
|
23
|
+
"repository": {
|
|
24
|
+
"type": "git",
|
|
25
|
+
"url": "https://github.com/constructive-io/constructive"
|
|
26
|
+
},
|
|
27
|
+
"keywords": [
|
|
28
|
+
"postgraphile",
|
|
29
|
+
"graphile",
|
|
30
|
+
"constructive",
|
|
31
|
+
"plugin",
|
|
32
|
+
"postgres",
|
|
33
|
+
"graphql",
|
|
34
|
+
"plpgsql",
|
|
35
|
+
"functions"
|
|
36
|
+
],
|
|
37
|
+
"bugs": {
|
|
38
|
+
"url": "https://github.com/constructive-io/constructive/issues"
|
|
39
|
+
},
|
|
40
|
+
"dependencies": {
|
|
41
|
+
"plpgsql-parser": "^18.5.14"
|
|
42
|
+
},
|
|
43
|
+
"peerDependencies": {
|
|
44
|
+
"@dataplan/pg": "^1.1.1",
|
|
45
|
+
"grafast": "^1.1.2",
|
|
46
|
+
"graphile-build": "^5.1.1",
|
|
47
|
+
"graphile-build-pg": "^5.1.3",
|
|
48
|
+
"graphile-config": "^1.1.0",
|
|
49
|
+
"graphql": "^16.9.0",
|
|
50
|
+
"postgraphile": "^5.1.3"
|
|
51
|
+
},
|
|
52
|
+
"devDependencies": {
|
|
53
|
+
"@types/node": "^22.19.11",
|
|
54
|
+
"graphile-test": "^5.18.3",
|
|
55
|
+
"makage": "^0.8.0"
|
|
56
|
+
},
|
|
57
|
+
"gitHead": "0b8a4fa54f658bf3b3a8776b98cc5fb373103ce8"
|
|
58
|
+
}
|