Skip to content

Commit

Permalink
fix: types, methods
Browse files Browse the repository at this point in the history
  • Loading branch information
Elin Angelow committed Dec 19, 2023
1 parent 720bfb8 commit fdbf17d
Show file tree
Hide file tree
Showing 8 changed files with 87 additions and 29 deletions.
7 changes: 6 additions & 1 deletion README.md
Original file line number Diff line number Diff line change
@@ -1,8 +1,13 @@
# Expose sql methods as nodejs methods

## arguments

- every method that is called should consist on only 1 argument
of type object, in it should be passed every argument of sql function,procedure ... etc

- mssql: ok
- mysql: pending
- postgres: pending
- postgres: wip
- sqlite: pending

[![Build Status](https://travis-ci.com/zetxx/expose-sql-methods.svg?branch=master)](https://travis-ci.com/zetxx/expose-sql-methods)
2 changes: 1 addition & 1 deletion examples/mssql/example.config.js
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,6 @@ module.exports = {
},
link: {
gluePrefix: '.',
schema: ['a', 'b'] // schemas allowed
schemas: ['a', 'b'] // schemas allowed
}
};
2 changes: 1 addition & 1 deletion examples/postgres/example.config.js
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,6 @@ module.exports = {
},
link: {
gluePrefix: '.',
schema: ['public'] // schemas allowed
schemas: ['public'] // schemas allowed
}
};
22 changes: 17 additions & 5 deletions examples/postgres/example.sql
Original file line number Diff line number Diff line change
@@ -1,21 +1,33 @@
CREATE TABLE "some-test-example"."exsschema"."tx" (
CREATE TABLE "exsschema"."tx" (
tag serial PRIMARY KEY,
device VARCHAR (100) NOT NULL,
created BIGINT DEFAULT extract(epoch from now())
);
---------------------------------------------------------------
CREATE FUNCTION "some-test-example"."exsschema"."fnLastTx"(pDevice VARCHAR (100))
INSERT INTO "exsschema".tx (device,created) VALUES
('34987a479f90',1702857600),
('ec62608a3368',1702857600),
('34987a479f90',1702894599),
('ec62608a3368',1702894609),
('34987a479f90',1702894784),
('ec62608a3368',1702894804),
('34987a479f90',1702894968),
('ec62608a3368',1702894988),
('34987a479f90',1702895168),
('ec62608a3368',1702895182);
---------------------------------------------------------------
CREATE FUNCTION "exsschema"."fnLastTx"("pDevice" VARCHAR (100))
RETURNS table (tag integer, created BIGINT)
AS
$$
SELECT tag, created FROM "some-test-example"."exsschema"."tx" WHERE tag = (SELECT MAX(tag) AS tag FROM "some-test-example"."exsschema"."tx" WHERE device = pDevice);
SELECT tag, created FROM "exsschema"."tx" WHERE tag = (SELECT MAX(tag) AS tag FROM "exsschema"."tx" WHERE device = "pDevice");
$$
LANGUAGE sql;
---------------------------------------------------------------
CREATE FUNCTION "some-test-example"."exsschema"."fnNewTx"(pDevice VARCHAR (100), pCreated BIGINT)
CREATE FUNCTION "fnNewTx"(pDevice VARCHAR (100), pCreated BIGINT)
RETURNS table (tag integer, created BIGINT)
AS
$$
INSERT INTO "some-test-example"."exsschema"."tx" (device, created) VALUES (pDevice, pCreated) RETURNING tag, created;
SELECT 1 tag, 2 created RETURNING tag, created;
$$
LANGUAGE sql;
4 changes: 2 additions & 2 deletions examples/postgres/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -3,8 +3,8 @@
const methods = await require('../../lib/postgres')(
require('./config')
);
if (methods['some-test-example/exsschema/fnLastTx"'])
await methods['some-test-example/exsschema/fnLastTx"']({ParLessonType: [{LessonId: 100, LessonName: 'example lesson'}]});
if (methods && methods['exsschema/fnLastTx'])
await methods['exsschema/fnLastTx']({pDevice: '34987a479f90'});
} catch (e) {
console.error(e);
}
Expand Down
6 changes: 2 additions & 4 deletions lib/mssql/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -62,7 +62,7 @@ const Link = async(config) => {


module.exports = async(config) => {
const {gluePrefix = '.'} = config;
const {link: {gluePrefix = '.', schemas} = {}} = config;
const link = await Link(config.connect);

const predefinedQuery = async(key) => {
Expand Down Expand Up @@ -231,8 +231,6 @@ module.exports = async(config) => {
}

const build = async(tableTypes) => {
const linkOnly = [].concat(config.link.schema);

const qr = await predefinedQuery('internalMethod');

const procList = qr.recordset.reduce((procedures, {
Expand All @@ -248,7 +246,7 @@ module.exports = async(config) => {
isNullable,
isOutput
}) => {
if (isOutput || linkOnly.indexOf(schema) < 0) {
if (isOutput || schemas.indexOf(schema) < 0) {
return procedures;
}
const pn = [schema, name].join(gluePrefix);
Expand Down
63 changes: 49 additions & 14 deletions lib/postgres/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -21,22 +21,13 @@ const conn = (() => {
const Link = async(config) => {
const sql = await conn(config);
return {
request: async(q) => {
try {
return await sql(['select 123']);
} catch (e) {
console.warn(q);
console.error(e);
throw e;
}
},
sql
};
};


module.exports = async(config) => {
const {gluePrefix = '.'} = config;
const {link: {gluePrefix = '.', schemas} = {}} = config;
const link = await Link(config.connect);

const predefinedQuery = async(key) => {
Expand Down Expand Up @@ -68,13 +59,57 @@ module.exports = async(config) => {
return cache;
};
})();
// https://www.postgresql.org/docs/current/catalog-pg-proc.html
const buildArgs = (argnames, argmodes) => {
return argnames
.reduce((args, arg, idx) => {
const mode = (argmodes && argmodes[idx]) || 'i';
const gm = (mode === 'i' && 'input') || 'other';
const argRdy = {name: arg, mode};
return {
...args,
[gm]: (args[gm] || []).concat([argRdy]),
all: args.all.concat([argRdy])
};
}, {input: [], other: [], all: []});
};

const build = async() => {
const allTypes = await types();
(await predefinedQuery('methods'))
.map((method) => {
console.log(method);
});
return (await predefinedQuery('methods'))
.filter(({schema}) => schemas.indexOf(schema) > -1)
.reduce((methods, {
schema,
name,
ninargs, // number of input args
nargdefaults, // number of args with default value
rettype, // return type
inargtypes, // An array of the data types of the function arguments. This includes only input arguments (including INOUT and VARIADIC arguments), and thus represents the call signature of the function.
allargtypes, // An array of the data types of the function arguments. This includes all arguments (including OUT and INOUT arguments); however, if all the arguments are IN arguments, this field will be null. Note that subscripting is 1-based, whereas for historical reasons proargtypes is subscripted from 0.
argnames, // An array of the names of the function arguments. Arguments without a name are set to empty strings in the array. If none of the arguments have a name, this field will be null. Note that subscripts correspond to positions of proallargtypes not proargtypes.
argmodes // An array of the modes of the function arguments, encoded as i for IN arguments, o for OUT arguments, b for INOUT arguments, v for VARIADIC arguments, t for TABLE arguments. If all the arguments are IN arguments, this field will be null. Note that subscripts correspond to positions of proallargtypes not proargtypes.
}) => {
const jsName = [schema, name].join(gluePrefix);
const sqlName = [`${schema}`, `${name}`].join('.');
const args = buildArgs(argnames, argmodes);
return {
...methods,
[jsName]: async(arguments) => {
const dynArgs = args.input.map(({name}) => {
if (!arguments[name]) {
throw SqlSe.create(
'argumentNotFound',
{fn: jsName, argument: name}
);
}
return `'${arguments[name]}'`;
});
// const res = await link.sql`select * from ${link.sql(sqlName)}('abc')`
const res = await link.sql`select * from ${link.sql(sqlName)}(${link.sql(arguments)})`
return await res;
}
};
}, {});
};
return await build();
};
10 changes: 9 additions & 1 deletion lib/postgres/sqls/methods.sql
Original file line number Diff line number Diff line change
@@ -1,5 +1,13 @@
SELECT
*
nspname "schema",
proname "name",
pronargs ninargs,
pronargdefaults nargdefaults,
prorettype rettype,
proargtypes inargtypes,
proallargtypes allargtypes,
proargnames argnames,
proargmodes argmodes
FROM
pg_catalog.pg_namespace n
JOIN
Expand Down

0 comments on commit fdbf17d

Please sign in to comment.