Socket
Socket
Sign inDemoInstall

@databases/pg-schema-introspect

Package Overview
Dependencies
79
Maintainers
1
Versions
8
Alerts
File Explorer

Advanced tools

Install Socket

Detect and block malicious and high-risk dependencies

Install

Comparing version 4.1.0 to 4.2.0-canary-2649

lib/tsconfig.tsbuildinfo

36

lib/__tests__/getAttributes.test.pg.js
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
Object.defineProperty(exports, "__esModule", { value: true });
const pg_1 = require("@databases/pg");
const getAttributes_1 = require("../getAttributes");
const db = pg_1.default({
bigIntMode: 'number'
});
const db = (0, pg_1.default)({ bigIntMode: 'number' });
test('getAttributes', async () => {
await db.query(pg_1.sql`CREATE SCHEMA getattributes`);
await db.query(pg_1.sql`
await db.query((0, pg_1.sql) `CREATE SCHEMA getattributes`);
await db.query((0, pg_1.sql) `
CREATE TYPE getattributes.kind AS ENUM('FirstKind', 'SecondKind');

@@ -30,10 +22,11 @@ COMMENT ON TYPE getattributes.kind IS 'There are two kinds of thing';

`);
expect((await getAttributes_1.default(db, {
className: 'table',
schemaName: 'getattributes'
})).map(c => ({ ...c,
schemaID: typeof c.schemaID === 'number' ? '<oid>' : c.schemaID,
classID: typeof c.classID === 'number' ? '<oid>' : c.classID,
typeID: typeof c.typeID === 'number' ? '<oid>' : c.typeID
}))).toMatchInlineSnapshot(`
expect((await (0, getAttributes_1.default)(db, {
className: 'table',
schemaName: 'getattributes',
})).map((c) => ({
...c,
schemaID: typeof c.schemaID === 'number' ? '<oid>' : c.schemaID,
classID: typeof c.classID === 'number' ? '<oid>' : c.classID,
typeID: typeof c.typeID === 'number' ? '<oid>' : c.typeID,
}))).toMatchInlineSnapshot(`
Array [

@@ -112,2 +105,3 @@ Object {

`);
});
});
//# sourceMappingURL=getAttributes.test.pg.js.map
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
Object.defineProperty(exports, "__esModule", { value: true });
const pg_1 = require("@databases/pg");
const getClasses_1 = require("../getClasses");
const ClassKind_1 = require("../enums/ClassKind");
const db = pg_1.default({
bigIntMode: 'number'
});
const db = (0, pg_1.default)({ bigIntMode: 'number' });
test('getClasses', async () => {
await db.query(pg_1.sql`CREATE SCHEMA getclasses`);
await db.query(pg_1.sql`
await db.query((0, pg_1.sql) `CREATE SCHEMA getclasses`);
await db.query((0, pg_1.sql) `
CREATE TABLE getclasses.table_a (id BIGSERIAL NOT NULL PRIMARY KEY);

@@ -24,15 +15,52 @@ CREATE TABLE getclasses.table_b (id BIGSERIAL NOT NULL PRIMARY KEY);

CREATE TABLE getclasses.partitioned (
id INT NOT NULL,
create_date DATE NOT NULL
) PARTITION BY RANGE (create_date);
CREATE TABLE getclasses.partitioned_p0 PARTITION OF getclasses.partitioned FOR VALUES FROM ('1900-01-01') TO ('1999-12-31');
CREATE TABLE getclasses.partitioned_p1 PARTITION OF getclasses.partitioned FOR VALUES FROM ('2000-01-01') TO ('2100-12-31');
COMMENT ON TABLE getclasses.table_b IS 'This is a great table';
COMMENT ON VIEW getclasses.view_b IS 'This is a great view';
`);
expect((await getClasses_1.default(db, {
schemaName: 'getclasses',
kind: [ClassKind_1.default.OrdinaryTable, ClassKind_1.default.View, ClassKind_1.default.MaterializedView]
})).map(t => ({ ...t,
classID: typeof t.classID === 'number' ? '<oid>' : t.classID,
schemaID: typeof t.schemaID === 'number' ? '<oid>' : t.schemaID
}))).toMatchInlineSnapshot(`
expect((await (0, getClasses_1.default)(db, {
schemaName: 'getclasses',
kind: [
ClassKind_1.default.OrdinaryTable,
ClassKind_1.default.PartitionedTable,
ClassKind_1.default.View,
ClassKind_1.default.MaterializedView,
],
})).map((t) => ({
...t,
classID: typeof t.classID === 'number' ? '<oid>' : t.classID,
schemaID: typeof t.schemaID === 'number' ? '<oid>' : t.schemaID,
}))).toMatchInlineSnapshot(`
Array [
Object {
"classID": "<oid>",
"className": "partitioned",
"comment": null,
"kind": "p",
"schemaID": "<oid>",
"schemaName": "getclasses",
},
Object {
"classID": "<oid>",
"className": "partitioned_p0",
"comment": null,
"kind": "r",
"schemaID": "<oid>",
"schemaName": "getclasses",
},
Object {
"classID": "<oid>",
"className": "partitioned_p1",
"comment": null,
"kind": "r",
"schemaID": "<oid>",
"schemaName": "getclasses",
},
Object {
"classID": "<oid>",
"className": "table_a",

@@ -70,2 +98,3 @@ "comment": null,

`);
});
});
//# sourceMappingURL=getClasses.test.pg.js.map
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
Object.defineProperty(exports, "__esModule", { value: true });
const pg_1 = require("@databases/pg");
const getConstraints_1 = require("../getConstraints");
const db = pg_1.default({
bigIntMode: 'number'
});
const db = (0, pg_1.default)({ bigIntMode: 'number' });
test('getConstraints', async () => {
await db.query(pg_1.sql`CREATE SCHEMA getconstraints`);
await db.query(pg_1.sql`
await db.query((0, pg_1.sql) `CREATE SCHEMA getconstraints`);
await db.query((0, pg_1.sql) `
CREATE TABLE getconstraints.table_a (

@@ -31,8 +23,10 @@ id BIGSERIAL NOT NULL PRIMARY KEY

`);
expect((await getConstraints_1.default(db, {
schemaName: 'getconstraints'
})).map(t => ({ ...t,
classID: typeof t.classID === 'number' ? '<oid>' : t.classID,
referencedClassID: typeof t.referencedClassID === 'number' ? '<oid>' : t.referencedClassID
}))).toMatchInlineSnapshot(`
expect((await (0, getConstraints_1.default)(db, {
schemaName: 'getconstraints',
// kind: [ClassKind.OrdinaryTable, ClassKind.View],
})).map((t) => ({
...t,
classID: typeof t.classID === 'number' ? '<oid>' : t.classID,
referencedClassID: typeof t.referencedClassID === 'number' ? '<oid>' : t.referencedClassID,
}))).toMatchInlineSnapshot(`
Array [

@@ -100,2 +94,3 @@ Object {

`);
});
});
//# sourceMappingURL=getConstraints.test.pg.js.map
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
Object.defineProperty(exports, "__esModule", { value: true });
const pg_1 = require("@databases/pg");
const getEnumValues_1 = require("../getEnumValues");
const db = pg_1.default({
bigIntMode: 'number'
});
const db = (0, pg_1.default)({ bigIntMode: 'number' });
test('get custom types', async () => {
await db.query(pg_1.sql`CREATE SCHEMA getenumvalues`);
await db.query(pg_1.sql`
await db.query((0, pg_1.sql) `CREATE SCHEMA getenumvalues`);
await db.query((0, pg_1.sql) `
CREATE TYPE getenumvalues.kind AS ENUM('FirstKind', 'SecondKind');
COMMENT ON TYPE getenumvalues.kind IS 'There are two kinds of thing';
`);
expect((await getEnumValues_1.default(db, {
schemaName: 'getenumvalues'
})).map(v => ({ ...v,
schemaID: typeof v.schemaID === 'number' ? '<oid>' : v.schemaID,
typeID: typeof v.typeID === 'number' ? '<oid>' : v.typeID
}))).toMatchInlineSnapshot(`
expect((await (0, getEnumValues_1.default)(db, { schemaName: 'getenumvalues' })).map((v) => ({
...v,
schemaID: typeof v.schemaID === 'number' ? '<oid>' : v.schemaID,
typeID: typeof v.typeID === 'number' ? '<oid>' : v.typeID,
}))).toMatchInlineSnapshot(`
Array [

@@ -43,2 +34,3 @@ Object {

`);
});
});
//# sourceMappingURL=getEnumValues.test.pg.js.map
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
Object.defineProperty(exports, "__esModule", { value: true });
const pg_1 = require("@databases/pg");
const getSearchPath_1 = require("../getSearchPath");
const db = pg_1.default({
bigIntMode: 'number'
});
const db = (0, pg_1.default)({ bigIntMode: 'number' });
test('getSearchPath', async () => {
expect(await getSearchPath_1.default(db)).toMatchInlineSnapshot(`
expect(await (0, getSearchPath_1.default)(db)).toMatchInlineSnapshot(`
Array [

@@ -20,5 +12,4 @@ "public",

`);
expect(await getSearchPath_1.default(db, {
includeNonExistantSchemas: true
})).toMatchInlineSnapshot(`
expect(await (0, getSearchPath_1.default)(db, { includeNonExistantSchemas: true }))
.toMatchInlineSnapshot(`
Array [

@@ -29,4 +20,4 @@ "test-user",

`);
await db.query(pg_1.sql`CREATE SCHEMA "test-user"`);
expect(await getSearchPath_1.default(db)).toMatchInlineSnapshot(`
await db.query((0, pg_1.sql) `CREATE SCHEMA "test-user"`);
expect(await (0, getSearchPath_1.default)(db)).toMatchInlineSnapshot(`
Array [

@@ -37,2 +28,3 @@ "test-user",

`);
});
});
//# sourceMappingURL=getSearchPath.test.pg.js.map
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
Object.defineProperty(exports, "__esModule", { value: true });
const pg_1 = require("@databases/pg");
const getTypes_1 = require("../getTypes");
const TypeCategory_1 = require("../enums/TypeCategory");
const fs_1 = require("fs");
const TypeKind_1 = require("../enums/TypeKind");
const prettier = require('prettier');
jest.setTimeout(30000);
const db = pg_1.default({
bigIntMode: 'number'
});
const db = (0, pg_1.default)({ bigIntMode: 'number' });
afterAll(async () => {
await db.dispose();
await db.dispose();
});
const PG_DATA_TYPE_FILENAME = `${__dirname}/../../../pg-data-type-id/src/index.ts`;
const DEFAULT_TYPESCRIPT_MAPPING_FILENAME = `${__dirname}/../../../pg-schema-print-types/src/DefaultTypeScriptMapping.ts`; // int8 default for pg-promise is string
const DEFAULT_TYPESCRIPT_MAPPING_FILENAME = `${__dirname}/../../../pg-schema-print-types/src/DefaultTypeScriptMapping.ts`;
// int8 default for pg-promise is string
// but @databases/pg uses number
const INTERVAL = '{years: number,months: number,days: number,hours: number,minutes: number,seconds: number,milliseconds: number, toPostgres: () => string, toISO: () => string}';
const typeMappings = {
[pg_1.DataTypeID.bool]: 'boolean',
[pg_1.DataTypeID.bytea]: 'Buffer',
[pg_1.DataTypeID.circle]: '{x: number, y: number, radius: number}',
[pg_1.DataTypeID.float4]: 'number',
[pg_1.DataTypeID.int2]: 'number',
[pg_1.DataTypeID.int8]: 'number',
[pg_1.DataTypeID.interval]: INTERVAL,
[pg_1.DataTypeID.json]: 'any',
[pg_1.DataTypeID.jsonb]: 'any',
[pg_1.DataTypeID.point]: '{x: number, y: number}',
[pg_1.DataTypeID.timestamp]: 'Date',
[pg_1.DataTypeID._bool]: 'Array<boolean | nul>',
[pg_1.DataTypeID._bytea]: 'Array<Buffer | null>',
[pg_1.DataTypeID._int2]: 'Array<number | null>',
[pg_1.DataTypeID._int8]: 'Array<number | null>',
[pg_1.DataTypeID._interval]: `Array<${INTERVAL} | null>`,
[pg_1.DataTypeID._json]: 'Array<any | null>',
[pg_1.DataTypeID._numeric]: 'Array<number | null>',
[pg_1.DataTypeID._point]: 'Array<{x: number, y: number} | null>',
[pg_1.DataTypeID._text]: 'Array<string | null>',
[pg_1.DataTypeID._timestamp]: 'Array<Date | null>'
[pg_1.DataTypeID.bool]: 'boolean',
[pg_1.DataTypeID.bytea]: 'Buffer',
[pg_1.DataTypeID.circle]: '{x: number, y: number, radius: number}',
[pg_1.DataTypeID.float4]: 'number',
[pg_1.DataTypeID.int2]: 'number',
[pg_1.DataTypeID.int8]: 'number',
[pg_1.DataTypeID.interval]: INTERVAL,
[pg_1.DataTypeID.json]: 'any',
[pg_1.DataTypeID.jsonb]: 'any',
[pg_1.DataTypeID.point]: '{x: number, y: number}',
[pg_1.DataTypeID.timestamp]: 'Date',
[pg_1.DataTypeID._bool]: 'Array<boolean | nul>',
[pg_1.DataTypeID._bytea]: 'Array<Buffer | null>',
[pg_1.DataTypeID._int2]: 'Array<number | null>',
[pg_1.DataTypeID._int8]: 'Array<number | null>',
[pg_1.DataTypeID._interval]: `Array<${INTERVAL} | null>`,
[pg_1.DataTypeID._json]: 'Array<any | null>',
[pg_1.DataTypeID._numeric]: 'Array<number | null>',
[pg_1.DataTypeID._point]: 'Array<{x: number, y: number} | null>',
[pg_1.DataTypeID._text]: 'Array<string | null>',
[pg_1.DataTypeID._timestamp]: 'Array<Date | null>',
};
async function writeIfDifferent(filename, content) {
const prettierOptions = (await prettier.resolveConfig(filename)) || {};
prettierOptions.parser = 'typescript';
const formatted = prettier.format(content, prettierOptions);
let currentContent = '';
try {
currentContent = fs_1.readFileSync(filename, 'utf8');
if (currentContent === formatted) {
return;
const prettierOptions = (await prettier.resolveConfig(filename)) || {};
prettierOptions.parser = 'typescript';
const formatted = prettier.format(content, prettierOptions);
let currentContent = '';
try {
currentContent = (0, fs_1.readFileSync)(filename, 'utf8');
if (currentContent === formatted) {
return;
}
}
} catch (ex) {
if (ex.code !== 'ENOENT') throw ex;
}
if (process.env.CI) {
expect(formatted).toEqual(currentContent);
}
fs_1.writeFileSync(filename, formatted);
catch (ex) {
if (ex.code !== 'ENOENT')
throw ex;
}
if (process.env.CI) {
expect(formatted).toEqual(currentContent);
}
(0, fs_1.writeFileSync)(filename, formatted);
}
async function writeJsonIfDifferent(filename, content) {
const formatted = JSON.stringify(content, null, ' ');
let currentContent = '';
try {
currentContent = fs_1.readFileSync(filename, 'utf8');
if (currentContent === formatted) {
return;
const formatted = JSON.stringify(content, null, ' ');
let currentContent = '';
try {
currentContent = (0, fs_1.readFileSync)(filename, 'utf8');
if (currentContent === formatted) {
return;
}
}
} catch (ex) {
if (ex.code !== 'ENOENT') throw ex;
}
if (process.env.CI) {
expect(formatted).toEqual(currentContent);
}
fs_1.writeFileSync(filename, formatted);
catch (ex) {
if (ex.code !== 'ENOENT')
throw ex;
}
if (process.env.CI) {
expect(formatted).toEqual(currentContent);
}
(0, fs_1.writeFileSync)(filename, formatted);
}
test('get built in types', async () => {
const pgVersion = await getPgVersion();
const builtInTypesFromPg = (await getTypes_1.default(db, {
schemaName: 'pg_catalog'
})).filter(t => t.kind !== TypeKind_1.default.Composite).map(t => ({
pgVersion,
kind: t.kind,
typeID: t.typeID,
typeName: t.typeName,
category: t.category,
comment: t.comment,
...('subtypeName' in t ? {
subtypeName: t.subtypeName
} : {})
}));
const oldState = JSON.parse(fs_1.readFileSync(`${__dirname}/builtinTypes.json`, 'utf8'));
let {
types: builtInTypesFromFile
} = oldState;
const {
ambiguousTypes
} = oldState;
for (const typeFromPg of builtInTypesFromPg) {
const ambiguousType = ambiguousTypes[typeFromPg.typeName] || [];
if (process.env.CI) {
if (!ambiguousType.length) {
const typeFromFile = builtInTypesFromFile.find(typeFromFile => typeFromFile.typeID === typeFromPg.typeID);
if (typeFromFile) {
if (typeFromPg.pgVersion[0] >= typeFromFile.pgVersion[0]) {
expect(typeFromFile).toEqual(typeFromPg);
}
} else {
expect(builtInTypesFromFile).toContainEqual(typeFromPg);
const pgVersion = await getPgVersion();
const builtInTypesFromPg = (await (0, getTypes_1.default)(db, { schemaName: 'pg_catalog' }))
.filter((t) => t.kind !== TypeKind_1.default.Composite)
.map((t) => ({
pgVersion,
kind: t.kind,
typeID: t.typeID,
typeName: t.typeName,
category: t.category,
comment: t.comment,
...('subtypeName' in t ? { subtypeName: t.subtypeName } : {}),
}));
const oldState = JSON.parse((0, fs_1.readFileSync)(`${__dirname}/builtinTypes.json`, 'utf8'));
let { types: builtInTypesFromFile } = oldState;
const { ambiguousTypes } = oldState;
for (const typeFromPg of builtInTypesFromPg) {
const ambiguousType = ambiguousTypes[typeFromPg.typeName] || [];
if (process.env.CI) {
if (!ambiguousType.length) {
const typeFromFile = builtInTypesFromFile.find((typeFromFile) => typeFromFile.typeID === typeFromPg.typeID);
if (typeFromFile) {
if (typeFromPg.pgVersion[0] >= typeFromFile.pgVersion[0]) {
expect(typeFromFile).toEqual(typeFromPg);
}
}
else {
expect(builtInTypesFromFile).toContainEqual(typeFromPg);
}
}
}
}
} else if (ambiguousType.length) {
let found = false;
const existingTypes = ambiguousType.filter(t => {
if (t.typeID === typeFromPg.typeID) {
if (lte(t.pgVersion, typeFromPg.pgVersion)) {
return false;
} else {
found = true;
}
else if (ambiguousType.length) {
let found = false;
const existingTypes = ambiguousType.filter((t) => {
if (t.typeID === typeFromPg.typeID) {
if (lte(t.pgVersion, typeFromPg.pgVersion)) {
return false;
}
else {
found = true;
}
}
return true;
});
if (!found) {
ambiguousTypes[typeFromPg.typeName] = sortByPostgresVersion([
...existingTypes,
typeFromPg,
]);
}
}
return true;
});
if (!found) {
ambiguousTypes[typeFromPg.typeName] = sortByPostgresVersion([...existingTypes, typeFromPg]);
}
} else {
// if there are missing types, you can add them by running
// with PG_TEST_IMAGE=postgres:10.14-alpine (replacing with the relevant version)
let found = false;
builtInTypesFromFile = builtInTypesFromFile.filter(typeFromFile => {
if (typeFromFile.typeName === typeFromPg.typeName) {
if (typeFromFile.typeID !== typeFromPg.typeID) {
found = true;
ambiguousTypes[typeFromFile.typeName] = sortByPostgresVersion([typeFromFile, typeFromPg]);
return false;
} else if (lte(typeFromFile.pgVersion, typeFromPg.pgVersion)) {
return false;
} else {
found = true;
}
else {
// if there are missing types, you can add them by running
// with PG_TEST_IMAGE=postgres:10.14-alpine (replacing with the relevant version)
let found = false;
builtInTypesFromFile = builtInTypesFromFile.filter((typeFromFile) => {
if (typeFromFile.typeName === typeFromPg.typeName) {
if (typeFromFile.typeID !== typeFromPg.typeID) {
found = true;
ambiguousTypes[typeFromFile.typeName] = sortByPostgresVersion([
typeFromFile,
typeFromPg,
]);
return false;
}
else if (lte(typeFromFile.pgVersion, typeFromPg.pgVersion)) {
return false;
}
else {
found = true;
}
}
return true;
});
if (!found) {
builtInTypesFromFile.push(typeFromPg);
}
}
return true;
});
if (!found) {
builtInTypesFromFile.push(typeFromPg);
}
}
}
builtInTypesFromFile.sort((a, b) => a.typeName > b.typeName ? 1 : -1);
await writeJsonIfDifferent(`${__dirname}/builtinTypes.json`, {
ambiguousTypes,
types: builtInTypesFromFile
});
const groupedTypes = builtInTypesFromFile.reduce((result, ty) => {
const category = Object.keys(TypeCategory_1.default).find(c => TypeCategory_1.default[c] === ty.category);
result[category] = (result[category] || []).concat([ty]);
return result;
}, {});
expect(Object.keys(groupedTypes).sort().reduce((result, key) => {
return { ...result,
[key]: groupedTypes[key].map(ty => `${ty.typeID} = ${ty.typeName}` + ('subtypeName' in ty && ty.subtypeName ? `<${ty.subtypeName}>` : ''))
};
}, {})).toMatchSnapshot();
const PgDataTypeIDsEnum = ['// auto generated by test suite of pg-schema-introspect', '', 'enum PgDataTypeID {'];
Object.keys(groupedTypes).forEach((groupName, i) => {
if (i !== 0) PgDataTypeIDsEnum.push('');
PgDataTypeIDsEnum.push(` // === ${groupName} ===`);
groupedTypes[groupName].forEach(type => {
PgDataTypeIDsEnum.push('');
const commentLines = [];
if (type.comment) {
commentLines.push(type.comment);
}
if (type.kind === TypeKind_1.default.Array) {
commentLines.push(`Array<${type.subtypeName}>`);
}
if (commentLines.length) {
PgDataTypeIDsEnum.push(` /**`);
commentLines.forEach((commentLine, j) => {
if (j !== 0) {
PgDataTypeIDsEnum.push(` *`);
}
PgDataTypeIDsEnum.push(` * ${commentLine}`);
builtInTypesFromFile.sort((a, b) => (a.typeName > b.typeName ? 1 : -1));
await writeJsonIfDifferent(`${__dirname}/builtinTypes.json`, {
ambiguousTypes,
types: builtInTypesFromFile,
});
const groupedTypes = builtInTypesFromFile.reduce((result, ty) => {
const category = Object.keys(TypeCategory_1.default).find((c) => TypeCategory_1.default[c] === ty.category);
result[category] = (result[category] || []).concat([ty]);
return result;
}, {});
expect(Object.keys(groupedTypes)
.sort()
.reduce((result, key) => {
return {
...result,
[key]: groupedTypes[key].map((ty) => `${ty.typeID} = ${ty.typeName}` +
('subtypeName' in ty && ty.subtypeName
? `<${ty.subtypeName}>`
: '')),
};
}, {})).toMatchSnapshot();
const PgDataTypeIDsEnum = [
'// auto generated by test suite of pg-schema-introspect',
'',
'enum PgDataTypeID {',
];
Object.keys(groupedTypes).forEach((groupName, i) => {
if (i !== 0)
PgDataTypeIDsEnum.push('');
PgDataTypeIDsEnum.push(` // === ${groupName} ===`);
groupedTypes[groupName].forEach((type) => {
PgDataTypeIDsEnum.push('');
const commentLines = [];
if (type.comment) {
commentLines.push(type.comment);
}
if (type.kind === TypeKind_1.default.Array) {
commentLines.push(`Array<${type.subtypeName}>`);
}
if (commentLines.length) {
PgDataTypeIDsEnum.push(` /**`);
commentLines.forEach((commentLine, j) => {
if (j !== 0) {
PgDataTypeIDsEnum.push(` *`);
}
PgDataTypeIDsEnum.push(` * ${commentLine}`);
});
PgDataTypeIDsEnum.push(` */`);
}
PgDataTypeIDsEnum.push(` ${type.typeName} = ${type.typeID},`);
});
PgDataTypeIDsEnum.push(` */`);
}
PgDataTypeIDsEnum.push(` ${type.typeName} = ${type.typeID},`);
});
});
PgDataTypeIDsEnum.push(`}`);
PgDataTypeIDsEnum.push(``);
PgDataTypeIDsEnum.push(`export default PgDataTypeID;`);
PgDataTypeIDsEnum.push(`module.exports = PgDataTypeID;`);
PgDataTypeIDsEnum.push(`module.exports.default = PgDataTypeID;`);
PgDataTypeIDsEnum.push(``);
await writeIfDifferent(PG_DATA_TYPE_FILENAME, PgDataTypeIDsEnum.join('\n'));
const pgTypes = require('pg-types/lib/textParsers');
const mapping = new Map();
const reverseMapping = new Map();
pgTypes.init((id, parser) => {
mapping.set(id, parser);
const m = reverseMapping.get(parser) || [];
reverseMapping.set(parser, [...m, id]);
});
const typeMappingLines = [];
mapping.forEach((parser, id) => {
const allIDs = reverseMapping.get(parser) || [];
const idsWithMapping = allIDs.filter(typeID => typeID in typeMappings);
if (idsWithMapping.length === 0) {
throw new Error('There is no mapping for: ' + allIDs.map(typeID => pg_1.DataTypeID[typeID]).join(', '));
}
if (idsWithMapping.length > 1) {
throw new Error('There is ambiguity between: ' + idsWithMapping.map(typeID => pg_1.DataTypeID[typeID]).join(', '));
}
typeMappingLines.push(` [DataTypeID.${pg_1.DataTypeID[id]}, '${typeMappings[idsWithMapping[0]]}'],`);
});
const DefaultTypeScriptMapping = ['// auto generated by test suite of pg-schema-introspect', ``, `import DataTypeID from '@databases/pg-data-type-id';`, ``, `const DefaultTypeScriptMapping = new Map([`, ...typeMappingLines.sort(), `]);`, ``, `export default DefaultTypeScriptMapping;`];
await writeIfDifferent(DEFAULT_TYPESCRIPT_MAPPING_FILENAME, DefaultTypeScriptMapping.join('\n'));
PgDataTypeIDsEnum.push(`}`);
PgDataTypeIDsEnum.push(``);
PgDataTypeIDsEnum.push(`export default PgDataTypeID;`);
PgDataTypeIDsEnum.push(`module.exports = PgDataTypeID;`);
PgDataTypeIDsEnum.push(`module.exports.default = PgDataTypeID;`);
PgDataTypeIDsEnum.push(``);
await writeIfDifferent(PG_DATA_TYPE_FILENAME, PgDataTypeIDsEnum.join('\n'));
const pgTypes = require('pg-types/lib/textParsers');
const mapping = new Map();
const reverseMapping = new Map();
pgTypes.init((id, parser) => {
mapping.set(id, parser);
const m = reverseMapping.get(parser) || [];
reverseMapping.set(parser, [...m, id]);
});
const typeMappingLines = [];
mapping.forEach((parser, id) => {
const allIDs = reverseMapping.get(parser) || [];
const idsWithMapping = allIDs.filter((typeID) => typeID in typeMappings);
if (idsWithMapping.length === 0) {
throw new Error('There is no mapping for: ' +
allIDs.map((typeID) => pg_1.DataTypeID[typeID]).join(', '));
}
if (idsWithMapping.length > 1) {
throw new Error('There is ambiguity between: ' +
idsWithMapping.map((typeID) => pg_1.DataTypeID[typeID]).join(', '));
}
typeMappingLines.push(` [DataTypeID.${pg_1.DataTypeID[id]}, '${typeMappings[idsWithMapping[0]]}'],`);
});
const DefaultTypeScriptMapping = [
'// auto generated by test suite of pg-schema-introspect',
``,
`import DataTypeID from '@databases/pg-data-type-id';`,
``,
`const DefaultTypeScriptMapping = new Map([`,
...typeMappingLines.sort(),
`]);`,
``,
`export default DefaultTypeScriptMapping;`,
];
await writeIfDifferent(DEFAULT_TYPESCRIPT_MAPPING_FILENAME, DefaultTypeScriptMapping.join('\n'));
});
test('get custom types', async () => {
await db.query(pg_1.sql`CREATE SCHEMA gettypes`);
await db.query(pg_1.sql`
await db.query((0, pg_1.sql) `CREATE SCHEMA gettypes`);
await db.query((0, pg_1.sql) `
CREATE TYPE gettypes.currency AS ENUM('USD', 'GBP');

@@ -276,3 +268,3 @@ COMMENT ON TYPE gettypes.currency IS 'Three character currency code';

`);
await db.query(pg_1.sql`
await db.query((0, pg_1.sql) `
CREATE TABLE gettypes.tab (

@@ -283,6 +275,7 @@ email gettypes.email NOT NULL PRIMARY KEY,

`);
await db.query(pg_1.sql`
await db.query((0, pg_1.sql) `
INSERT INTO gettypes.tab (email, money) VALUES (${'forbes@lindesay.co.uk'}, ROW (${10}, 'USD'))
`);
expect(await db.query(pg_1.sql`SELECT * FROM gettypes.tab`)).toMatchInlineSnapshot(`
expect(await db.query((0, pg_1.sql) `SELECT * FROM gettypes.tab`))
.toMatchInlineSnapshot(`
Array [

@@ -295,36 +288,33 @@ Object {

`);
expect((await getTypes_1.default(db, {
schemaName: 'gettypes'
})).map(t => {
const result = { ...t,
schemaID: typeof t.schemaID === 'number' ? '<oid>' : t.schemaID,
typeID: typeof t.typeID === 'number' ? '<oid>' : t.typeID
};
if ('subtypeID' in result && typeof result.subtypeID === 'number') {
result.subtypeID = '<oid>';
}
if ('basetypeID' in result && typeof result.basetypeID === 'number') {
result.basetypeID = '<oid>';
}
if ('classID' in result && typeof result.classID === 'number') {
result.classID = '<oid>';
}
if ('attributes' in result) {
result.attributes = result.attributes.map(a => ({ ...a,
classID: typeof a.classID === 'number' ? '<oid>' : a.classID,
schemaID: typeof a.schemaID === 'number' ? '<oid>' : a.schemaID,
typeID: typeof a.typeID === 'number' ? '<oid>' : a.typeID
}));
}
return result;
}).filter(t => {
// newer versions of postgres include this, but we need the tests to continue
// passing on postgres 10.14 for now.
return t.typeName !== '_email';
})).toMatchInlineSnapshot(`
expect((await (0, getTypes_1.default)(db, { schemaName: 'gettypes' }))
.map((t) => {
const result = {
...t,
schemaID: typeof t.schemaID === 'number' ? '<oid>' : t.schemaID,
typeID: typeof t.typeID === 'number' ? '<oid>' : t.typeID,
};
if ('subtypeID' in result && typeof result.subtypeID === 'number') {
result.subtypeID = '<oid>';
}
if ('basetypeID' in result && typeof result.basetypeID === 'number') {
result.basetypeID = '<oid>';
}
if ('classID' in result && typeof result.classID === 'number') {
result.classID = '<oid>';
}
if ('attributes' in result) {
result.attributes = result.attributes.map((a) => ({
...a,
classID: typeof a.classID === 'number' ? '<oid>' : a.classID,
schemaID: typeof a.schemaID === 'number' ? '<oid>' : a.schemaID,
typeID: typeof a.typeID === 'number' ? '<oid>' : a.typeID,
}));
}
return result;
})
.filter((t) => {
// newer versions of postgres include this, but we need the tests to continue
// passing on postgres 10.14 for now.
return t.typeName !== '_email';
})).toMatchInlineSnapshot(`
Array [

@@ -471,24 +461,20 @@ Object {

});
async function getPgVersion() {
// e.g. PostgreSQL 10.1 on x86_64-apple-darwin16.7.0, compiled by Apple LLVM version 9.0.0 (clang-900.0.38), 64-bit
const [{
version: sqlVersionString
}] = await db.query(db.sql`SELECT version();`);
const match = /PostgreSQL (\d+).(\d+)/.exec(sqlVersionString);
if (match) {
const [, major, minor] = match;
return [parseInt(major, 10), parseInt(minor, 10)];
}
return [0, 0];
// e.g. PostgreSQL 10.1 on x86_64-apple-darwin16.7.0, compiled by Apple LLVM version 9.0.0 (clang-900.0.38), 64-bit
const [{ version: sqlVersionString }] = await db.query(db.sql `SELECT version();`);
const match = /PostgreSQL (\d+).(\d+)/.exec(sqlVersionString);
if (match) {
const [, major, minor] = match;
return [parseInt(major, 10), parseInt(minor, 10)];
}
return [0, 0];
}
function lte(a, b) {
return a[0] < b[0] || a[0] === b[0] && (a[1] === b[1] || a[1] < b[1]);
return a[0] < b[0] || (a[0] === b[0] && (a[1] === b[1] || a[1] < b[1]));
}
function sortByPostgresVersion(records) {
return records.slice().sort((a, b) => a.pgVersion[0] - b.pgVersion[0] || a.pgVersion[1] - b.pgVersion[1]);
}
return records
.slice()
.sort((a, b) => a.pgVersion[0] - b.pgVersion[0] || a.pgVersion[1] - b.pgVersion[1]);
}
//# sourceMappingURL=getTypes.test.pg.js.map

@@ -8,2 +8,3 @@ declare enum ClassKind {

CompositeType = "c",
PartitionedTable = "p",
ToastTable = "t",

@@ -10,0 +11,0 @@ ForeignTable = "f"

"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
Object.defineProperty(exports, "__esModule", { value: true });
var ClassKind;
(function (ClassKind) {
ClassKind["OrdinaryTable"] = "r";
ClassKind["Index"] = "i";
ClassKind["Sequence"] = "S";
ClassKind["View"] = "v";
ClassKind["MaterializedView"] = "m";
ClassKind["CompositeType"] = "c";
ClassKind["ToastTable"] = "t";
ClassKind["ForeignTable"] = "f";
ClassKind["OrdinaryTable"] = "r";
ClassKind["Index"] = "i";
ClassKind["Sequence"] = "S";
ClassKind["View"] = "v";
ClassKind["MaterializedView"] = "m";
ClassKind["CompositeType"] = "c";
ClassKind["PartitionedTable"] = "p";
ClassKind["ToastTable"] = "t";
ClassKind["ForeignTable"] = "f";
})(ClassKind || (ClassKind = {}));
exports.default = ClassKind;
exports.default = ClassKind;
//# sourceMappingURL=ClassKind.js.map
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
Object.defineProperty(exports, "__esModule", { value: true });
var ConstraintType;
(function (ConstraintType) {
ConstraintType["Check"] = "c";
ConstraintType["ForeignKey"] = "f";
ConstraintType["PrimaryKey"] = "p";
ConstraintType["Unique"] = "u";
ConstraintType["ConstraintTrigger"] = "t";
ConstraintType["Exclusion"] = "x";
ConstraintType["Check"] = "c";
ConstraintType["ForeignKey"] = "f";
ConstraintType["PrimaryKey"] = "p";
ConstraintType["Unique"] = "u";
ConstraintType["ConstraintTrigger"] = "t";
ConstraintType["Exclusion"] = "x";
})(ConstraintType || (ConstraintType = {}));
exports.default = ConstraintType;
exports.default = ConstraintType;
//# sourceMappingURL=ConstraintType.js.map
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
Object.defineProperty(exports, "__esModule", { value: true });
var ForeignKeyAction;
(function (ForeignKeyAction) {
ForeignKeyAction["NoAction"] = "a";
ForeignKeyAction["Restrict"] = "r";
ForeignKeyAction["Cascade"] = "c";
ForeignKeyAction["SetNull"] = "n";
ForeignKeyAction["SetDefault"] = "d";
ForeignKeyAction["NoAction"] = "a";
ForeignKeyAction["Restrict"] = "r";
ForeignKeyAction["Cascade"] = "c";
ForeignKeyAction["SetNull"] = "n";
ForeignKeyAction["SetDefault"] = "d";
})(ForeignKeyAction || (ForeignKeyAction = {}));
exports.default = ForeignKeyAction;
exports.default = ForeignKeyAction;
//# sourceMappingURL=ForeginKeyAction.js.map
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
Object.defineProperty(exports, "__esModule", { value: true });
var ForeignKeyMatchType;
(function (ForeignKeyMatchType) {
ForeignKeyMatchType["Full"] = "f";
ForeignKeyMatchType["Partial"] = "p";
ForeignKeyMatchType["Simple"] = "u";
ForeignKeyMatchType["Full"] = "f";
ForeignKeyMatchType["Partial"] = "p";
ForeignKeyMatchType["Simple"] = "u";
})(ForeignKeyMatchType || (ForeignKeyMatchType = {}));
exports.default = ForeignKeyMatchType;
exports.default = ForeignKeyMatchType;
//# sourceMappingURL=ForeignKeyMatchType.js.map
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
Object.defineProperty(exports, "__esModule", { value: true });
var TypeCateogry;
(function (TypeCateogry) {
TypeCateogry["Array"] = "A";
TypeCateogry["Boolean"] = "B";
TypeCateogry["Composite"] = "C";
TypeCateogry["DateTime"] = "D";
TypeCateogry["Enum"] = "E";
TypeCateogry["Geometric"] = "G";
TypeCateogry["NetworkAddress"] = "I";
TypeCateogry["Numeric"] = "N";
TypeCateogry["PseudoTypes"] = "P";
TypeCateogry["Range"] = "R";
TypeCateogry["String"] = "S";
TypeCateogry["Timespan"] = "T";
TypeCateogry["UserDefined"] = "U";
TypeCateogry["BitString"] = "V";
TypeCateogry["Unknown"] = "X";
TypeCateogry["Array"] = "A";
TypeCateogry["Boolean"] = "B";
TypeCateogry["Composite"] = "C";
TypeCateogry["DateTime"] = "D";
TypeCateogry["Enum"] = "E";
TypeCateogry["Geometric"] = "G";
TypeCateogry["NetworkAddress"] = "I";
TypeCateogry["Numeric"] = "N";
TypeCateogry["PseudoTypes"] = "P";
TypeCateogry["Range"] = "R";
TypeCateogry["String"] = "S";
TypeCateogry["Timespan"] = "T";
TypeCateogry["UserDefined"] = "U";
TypeCateogry["BitString"] = "V";
TypeCateogry["Unknown"] = "X";
})(TypeCateogry || (TypeCateogry = {}));
exports.default = TypeCateogry;
exports.default = TypeCateogry;
//# sourceMappingURL=TypeCategory.js.map
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
Object.defineProperty(exports, "__esModule", { value: true });
var TypeKind;
(function (TypeKind) {
// N.B. Array is not really a type in postgres,
// instead Array is just a special kind of base
// type
TypeKind["Array"] = "array";
TypeKind["Base"] = "b"; // (e.g., a table's row type)
TypeKind["Composite"] = "c"; // domains alias other types, with optional constraints
TypeKind["Domain"] = "d";
TypeKind["Enum"] = "e";
TypeKind["Pseudo"] = "p";
// N.B. Array is not really a type in postgres,
// instead Array is just a special kind of base
// type
TypeKind["Array"] = "array";
TypeKind["Base"] = "b";
// (e.g., a table's row type)
TypeKind["Composite"] = "c";
// domains alias other types, with optional constraints
TypeKind["Domain"] = "d";
TypeKind["Enum"] = "e";
TypeKind["Pseudo"] = "p";
})(TypeKind || (TypeKind = {}));
exports.default = TypeKind;
exports.default = TypeKind;
//# sourceMappingURL=TypeKind.js.map
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
Object.defineProperty(exports, "__esModule", { value: true });
const pg_1 = require("@databases/pg");
const getClasses_1 = require("./getClasses");
async function getAttributes(connection, query) {
const conditions = getClasses_1.classQuery(query);
if (query.column) {
conditions.push(pg_1.sql`a.attname = ${query.column}`);
}
if (!query.column && !query.includeSystemColumns) {
conditions.push(pg_1.sql`a.attnum > 0`);
}
conditions.push(pg_1.sql`a.attisdropped = false`);
const attributes = await connection.query(pg_1.sql`
const conditions = (0, getClasses_1.classQuery)(query);
if (query.column) {
conditions.push((0, pg_1.sql) `a.attname = ${query.column}`);
}
if (!query.column && !query.includeSystemColumns) {
conditions.push((0, pg_1.sql) `a.attnum > 0`);
}
conditions.push((0, pg_1.sql) `a.attisdropped = false`);
const attributes = await connection.query((0, pg_1.sql) `
SELECT

@@ -46,8 +37,8 @@ ns.oid AS "schemaID",

ON (def.adrelid = cls.oid AND def.adnum = a.attnum)
${conditions.length ? pg_1.sql`WHERE ${pg_1.sql.join(conditions, pg_1.sql` AND `)}` : pg_1.sql``}
${conditions.length ? (0, pg_1.sql) `WHERE ${pg_1.sql.join(conditions, (0, pg_1.sql) ` AND `)}` : (0, pg_1.sql) ``}
ORDER BY ns.nspname ASC, cls.relname ASC, a.attname ASC;
`);
return attributes;
return attributes;
}
exports.default = getAttributes;
exports.default = getAttributes;
//# sourceMappingURL=getAttributes.js.map
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
Object.defineProperty(exports, "__esModule", { value: true });
exports.classQuery = void 0;
const pg_1 = require("@databases/pg");
async function getClasses(connection, query) {
const conditions = classQuery(query);
const tables = await connection.query(pg_1.sql`
const conditions = classQuery(query);
const tables = await connection.query((0, pg_1.sql) `
SELECT

@@ -23,40 +18,33 @@ ns.oid as "schemaID",

ON (cls.relnamespace = ns.oid)
${conditions.length ? pg_1.sql`WHERE ${pg_1.sql.join(conditions, pg_1.sql` AND `)}` : pg_1.sql``}
${conditions.length ? (0, pg_1.sql) `WHERE ${pg_1.sql.join(conditions, (0, pg_1.sql) ` AND `)}` : (0, pg_1.sql) ``}
ORDER BY ns.nspname ASC, cls.relname ASC;
`);
return tables;
return tables;
}
exports.default = getClasses;
function classQuery(query) {
const conditions = [];
if (query.kind) {
if (Array.isArray(query.kind)) {
conditions.push(pg_1.sql`cls.relkind IN (${pg_1.sql.join(query.kind.map(k => pg_1.sql`${k}`), pg_1.sql`, `)})`);
} else {
conditions.push(pg_1.sql`cls.relkind = ${query.kind}`);
const conditions = [];
if (query.kind) {
if (Array.isArray(query.kind)) {
conditions.push((0, pg_1.sql) `cls.relkind IN (${pg_1.sql.join(query.kind.map((k) => (0, pg_1.sql) `${k}`), (0, pg_1.sql) `, `)})`);
}
else {
conditions.push((0, pg_1.sql) `cls.relkind = ${query.kind}`);
}
}
}
if (query.schemaName) {
conditions.push(pg_1.sql`ns.nspname = ${query.schemaName}`);
}
if (query.schemaID) {
conditions.push(pg_1.sql`ns.oid = ${query.schemaID}`);
}
if (query.className) {
conditions.push(pg_1.sql`cls.relname = ${query.className}`);
}
if (query.classID) {
conditions.push(pg_1.sql`cls.oid = ${query.classID}`);
}
return conditions;
if (query.schemaName) {
conditions.push((0, pg_1.sql) `ns.nspname = ${query.schemaName}`);
}
if (query.schemaID) {
conditions.push((0, pg_1.sql) `ns.oid = ${query.schemaID}`);
}
if (query.className) {
conditions.push((0, pg_1.sql) `cls.relname = ${query.className}`);
}
if (query.classID) {
conditions.push((0, pg_1.sql) `cls.oid = ${query.classID}`);
}
return conditions;
}
exports.classQuery = classQuery;
exports.classQuery = classQuery;
//# sourceMappingURL=getClasses.js.map
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
Object.defineProperty(exports, "__esModule", { value: true });
const pg_1 = require("@databases/pg");
const getClasses_1 = require("./getClasses");
async function getConstraints(connection, query) {
const conditions = getClasses_1.classQuery(query);
const constraints = await connection.query(pg_1.sql`
const conditions = (0, getClasses_1.classQuery)(query);
const constraints = await connection.query((0, pg_1.sql) `
SELECT

@@ -30,8 +24,8 @@ conname AS "constraintName",

ON (c.connamespace = ns.oid)
${conditions.length ? pg_1.sql`WHERE ${pg_1.sql.join(conditions, pg_1.sql` AND `)}` : pg_1.sql``}
${conditions.length ? (0, pg_1.sql) `WHERE ${pg_1.sql.join(conditions, (0, pg_1.sql) ` AND `)}` : (0, pg_1.sql) ``}
ORDER BY ns.nspname ASC, c.conname ASC
`);
return constraints;
return constraints;
}
exports.default = getConstraints;
exports.default = getConstraints;
//# sourceMappingURL=getConstraints.js.map
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
Object.defineProperty(exports, "__esModule", { value: true });
const pg_1 = require("@databases/pg");
const getTypes_1 = require("./getTypes");
async function getEnumValues(connection, query) {
const conditions = getTypes_1.typeQuery(query);
const enumValues = await connection.query(pg_1.sql`
const conditions = (0, getTypes_1.typeQuery)(query);
const enumValues = await connection.query((0, pg_1.sql) `
SELECT

@@ -27,8 +21,8 @@ ns.oid AS "schemaID",

ON (ty.typelem = subt.oid)
${conditions.length ? pg_1.sql`WHERE ${pg_1.sql.join(conditions, pg_1.sql` AND `)}` : pg_1.sql``}
${conditions.length ? (0, pg_1.sql) `WHERE ${pg_1.sql.join(conditions, (0, pg_1.sql) ` AND `)}` : (0, pg_1.sql) ``}
ORDER BY ns.nspname ASC, ty.typname ASC, e.enumlabel ASC
`);
return enumValues;
return enumValues;
}
exports.default = getEnumValues;
exports.default = getEnumValues;
//# sourceMappingURL=getEnumValues.js.map
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
Object.defineProperty(exports, "__esModule", { value: true });
exports.sql = exports.connect = void 0;
const pg_1 = require("@databases/pg");
exports.connect = pg_1.default;
Object.defineProperty(exports, "sql", {
enumerable: true,
get: function () {
return pg_1.sql;
}
});
Object.defineProperty(exports, "sql", { enumerable: true, get: function () { return pg_1.sql; } });
const ClassKind_1 = require("./enums/ClassKind");
const getAttributes_1 = require("./getAttributes");
const getClasses_1 = require("./getClasses");
const getConstraints_1 = require("./getConstraints");
const getSchemaName_1 = require("./getSchemaName");
const getSearchPath_1 = require("./getSearchPath");
const getTypes_1 = require("./getTypes");
async function getSchema(connection, query = {}) {
const schemaName = query.schemaName ? query.schemaName : query.schemaID ? await getSchemaName_1.default(connection, query.schemaID) : (await getSearchPath_1.default(connection))[0];
if (!schemaName) {
throw new Error('No schema found');
}
const [types, classes, allAttributes, allConstraints] = await Promise.all([getTypes_1.default(connection, {
schemaName
}), getClasses_1.default(connection, {
schemaName,
kind: [ClassKind_1.default.OrdinaryTable, ClassKind_1.default.View, ClassKind_1.default.MaterializedView]
}), getAttributes_1.default(connection, {
schemaName
}), getConstraints_1.default(connection, {
schemaName
})]);
return {
types,
classes: classes.map(cls => ({ ...cls,
attributes: allAttributes.filter(att => att.classID === cls.classID),
constraints: allConstraints.filter(con => con.classID === cls.classID)
}))
};
const schemaName = query.schemaName
? query.schemaName
: query.schemaID
? await (0, getSchemaName_1.default)(connection, query.schemaID)
: (await (0, getSearchPath_1.default)(connection))[0];
if (!schemaName) {
throw new Error('No schema found');
}
const [types, classes, allAttributes, allConstraints] = await Promise.all([
(0, getTypes_1.default)(connection, { schemaName }),
(0, getClasses_1.default)(connection, {
schemaName,
kind: [
ClassKind_1.default.OrdinaryTable,
ClassKind_1.default.PartitionedTable,
ClassKind_1.default.View,
ClassKind_1.default.MaterializedView,
],
}),
(0, getAttributes_1.default)(connection, { schemaName }),
(0, getConstraints_1.default)(connection, { schemaName }),
]);
return {
types,
classes: classes.map((cls) => ({
...cls,
attributes: allAttributes.filter((att) => att.classID === cls.classID),
constraints: allConstraints.filter((con) => con.classID === cls.classID),
})),
};
}
exports.default = getSchema;
exports.default = getSchema;
//# sourceMappingURL=getSchema.js.map
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
Object.defineProperty(exports, "__esModule", { value: true });
const pg_1 = require("@databases/pg");
async function getSchemaName(connection, schemaID) {
const namespaces = await connection.query(pg_1.sql`SELECT nspname FROM pg_catalog.pg_namespace WHERE oid = ${schemaID}`);
if (namespaces.length !== 1) {
throw new Error(`Could not find schema with oid ${schemaID}`);
}
return namespaces[0].nspname;
const namespaces = (await connection.query((0, pg_1.sql) `SELECT nspname FROM pg_catalog.pg_namespace WHERE oid = ${schemaID}`));
if (namespaces.length !== 1) {
throw new Error(`Could not find schema with oid ${schemaID}`);
}
return namespaces[0].nspname;
}
exports.default = getSchemaName;
exports.default = getSchemaName;
//# sourceMappingURL=getSchemaName.js.map
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
Object.defineProperty(exports, "__esModule", { value: true });
const pg_1 = require("@databases/pg");
async function getSearchPath(connection, options = {}) {
const [[{
current_user
}], [{
search_path
}], namespaces] = await Promise.all([connection.query(pg_1.sql`SELECT current_user;`), connection.query(pg_1.sql`SHOW search_path;`), options.includeNonExistantSchemas ? Promise.resolve(null) : connection.query(pg_1.sql`SELECT nspname FROM pg_catalog.pg_namespace`)]);
const schemaNames = namespaces && namespaces.map(n => n.nspname);
const searchPath = search_path.split(',').map(p => p.trim()).map(p => p[0] === '"' ? JSON.parse(p) : p).map(p => p === '$user' ? current_user : p).filter(p => !schemaNames || schemaNames.includes(p));
return searchPath;
const [[{ current_user }], [{ search_path }], namespaces] = await Promise.all([
connection.query((0, pg_1.sql) `SELECT current_user;`),
connection.query((0, pg_1.sql) `SHOW search_path;`),
options.includeNonExistantSchemas
? Promise.resolve(null)
: connection.query((0, pg_1.sql) `SELECT nspname FROM pg_catalog.pg_namespace`),
]);
const schemaNames = namespaces && namespaces.map((n) => n.nspname);
const searchPath = search_path
.split(',')
.map((p) => p.trim())
.map((p) => (p[0] === '"' ? JSON.parse(p) : p))
.map((p) => (p === '$user' ? current_user : p))
.filter((p) => !schemaNames || schemaNames.includes(p));
return searchPath;
}
exports.default = getSearchPath;
exports.default = getSearchPath;
//# sourceMappingURL=getSearchPath.js.map
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
Object.defineProperty(exports, "__esModule", { value: true });
const getTypes_1 = require("./getTypes");
const getSearchPath_1 = require("./getSearchPath");
async function getTypeID(connection, query) {
const types = await getTypes_1.default(connection, query);
const fullTypeName = query.schemaName ? `${query.schemaName}.${query.typeName}` : query.typeName;
if (types.length === 0) {
throw new Error(`Could not find type: ${fullTypeName}`);
}
if (types.length === 1) {
return types[0].typeID;
}
const searchPath = await getSearchPath_1.default(connection, {
includeNonExistantSchemas: true
});
for (const schemaName of searchPath) {
const type = types.find(ty => ty.schemaName === schemaName);
if (type) {
return type.typeID;
const types = await (0, getTypes_1.default)(connection, query);
const fullTypeName = query.schemaName
? `${query.schemaName}.${query.typeName}`
: query.typeName;
if (types.length === 0) {
throw new Error(`Could not find type: ${fullTypeName}`);
}
}
throw new Error(`Could not find type: ${fullTypeName}. It could be any of: ${types.map(t => `${t.schemaName}.${t.typeName}`).join(', ')}`);
if (types.length === 1) {
return types[0].typeID;
}
const searchPath = await (0, getSearchPath_1.default)(connection, {
includeNonExistantSchemas: true,
});
for (const schemaName of searchPath) {
const type = types.find((ty) => ty.schemaName === schemaName);
if (type) {
return type.typeID;
}
}
throw new Error(`Could not find type: ${fullTypeName}. It could be any of: ${types
.map((t) => `${t.schemaName}.${t.typeName}`)
.join(', ')}`);
}
exports.default = getTypeID;
exports.default = getTypeID;
//# sourceMappingURL=getTypeID.js.map

@@ -65,4 +65,4 @@ import { Queryable } from '@databases/pg';

}
export declare type Type = ArrayType | BaseType | CompositeType | DomainType | EnumType | PseudoType;
export type Type = ArrayType | BaseType | CompositeType | DomainType | EnumType | PseudoType;
export default function getTypes(connection: Queryable, query?: TypeQuery): Promise<Type[]>;
export declare function typeQuery(query: TypeQuery): import("@databases/sql/lib/web").SQLQuery[];
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
Object.defineProperty(exports, "__esModule", { value: true });
exports.typeQuery = void 0;
const pg_1 = require("@databases/pg");
const TypeCategory_1 = require("./enums/TypeCategory");
const TypeKind_1 = require("./enums/TypeKind");
const getAttributes_1 = require("./getAttributes");
const getEnumValues_1 = require("./getEnumValues");
async function getTypes(connection, query = {}) {
const conditions = typeQuery(query);
const typeRecords = await connection.query(pg_1.sql`
const conditions = typeQuery(query);
const typeRecords = (await connection.query((0, pg_1.sql) `
SELECT

@@ -42,99 +33,93 @@ ns.oid AS "schemaID",

ON (ty.typbasetype = baset.oid)
${conditions.length ? pg_1.sql`WHERE ${pg_1.sql.join(conditions, pg_1.sql` AND `)}` : pg_1.sql``}
${conditions.length ? (0, pg_1.sql) `WHERE ${pg_1.sql.join(conditions, (0, pg_1.sql) ` AND `)}` : (0, pg_1.sql) ``}
ORDER BY ns.nspname ASC, ty.typname ASC, subt.typname ASC, baset.typname ASC
`);
return Promise.all(typeRecords.map(async tr => {
const base = {
schemaID: tr.schemaID,
schemaName: tr.schemaName,
typeID: tr.typeID,
typeName: tr.typeName,
kind: tr.kind,
category: tr.category,
comment: tr.comment
};
switch (base.kind) {
case TypeKind_1.default.Array:
case TypeKind_1.default.Base:
if (tr.category === TypeCategory_1.default.Array) {
return { ...base,
kind: TypeKind_1.default.Array,
subtypeID: tr.subtypeID,
subtypeName: tr.subtypeName
};
} else {
return { ...base,
kind: TypeKind_1.default.Base,
subtypeID: tr.subtypeID,
subtypeName: tr.subtypeName
};
`));
return Promise.all(typeRecords.map(async (tr) => {
const base = {
schemaID: tr.schemaID,
schemaName: tr.schemaName,
typeID: tr.typeID,
typeName: tr.typeName,
kind: tr.kind,
category: tr.category,
comment: tr.comment,
};
switch (base.kind) {
case TypeKind_1.default.Array:
case TypeKind_1.default.Base:
if (tr.category === TypeCategory_1.default.Array) {
return {
...base,
kind: TypeKind_1.default.Array,
subtypeID: tr.subtypeID,
subtypeName: tr.subtypeName,
};
}
else {
return {
...base,
kind: TypeKind_1.default.Base,
subtypeID: tr.subtypeID,
subtypeName: tr.subtypeName,
};
}
case TypeKind_1.default.Composite:
return {
...base,
kind: TypeKind_1.default.Composite,
classID: tr.classID,
attributes: await (0, getAttributes_1.default)(connection, {
classID: tr.classID,
}),
};
case TypeKind_1.default.Domain:
return {
...base,
kind: TypeKind_1.default.Domain,
basetypeID: tr.basetypeID,
basetypeName: tr.basetypeName,
};
case TypeKind_1.default.Enum:
return {
...base,
kind: TypeKind_1.default.Enum,
values: (await (0, getEnumValues_1.default)(connection, {
typeID: tr.typeID,
})).map((v) => v.value),
};
case TypeKind_1.default.Pseudo:
return {
...base,
kind: TypeKind_1.default.Pseudo,
};
default:
const kind = base.kind;
return {
...base,
kind,
};
}
case TypeKind_1.default.Composite:
return { ...base,
kind: TypeKind_1.default.Composite,
classID: tr.classID,
attributes: await getAttributes_1.default(connection, {
classID: tr.classID
})
};
case TypeKind_1.default.Domain:
return { ...base,
kind: TypeKind_1.default.Domain,
basetypeID: tr.basetypeID,
basetypeName: tr.basetypeName
};
case TypeKind_1.default.Enum:
return { ...base,
kind: TypeKind_1.default.Enum,
values: (await getEnumValues_1.default(connection, {
typeID: tr.typeID
})).map(v => v.value)
};
case TypeKind_1.default.Pseudo:
return { ...base,
kind: TypeKind_1.default.Pseudo
};
default:
const kind = base.kind;
return { ...base,
kind
};
}
}));
}));
}
exports.default = getTypes;
function typeQuery(query) {
const conditions = [];
if (query.schemaID) {
conditions.push(pg_1.sql`ns.oid = ${query.schemaID}`);
}
if (query.schemaName) {
conditions.push(pg_1.sql`ns.nspname = ${query.schemaName}`);
}
if (query.typeID) {
conditions.push(pg_1.sql`ty.oid = ${query.typeID}`);
}
if (query.typeName) {
conditions.push(pg_1.sql`ty.typname = ${query.typeName}`);
}
if (query.category) {
conditions.push(pg_1.sql`ty.typcategory = ${query.category}`);
}
return conditions;
const conditions = [];
if (query.schemaID) {
conditions.push((0, pg_1.sql) `ns.oid = ${query.schemaID}`);
}
if (query.schemaName) {
conditions.push((0, pg_1.sql) `ns.nspname = ${query.schemaName}`);
}
if (query.typeID) {
conditions.push((0, pg_1.sql) `ty.oid = ${query.typeID}`);
}
if (query.typeName) {
conditions.push((0, pg_1.sql) `ty.typname = ${query.typeName}`);
}
if (query.category) {
conditions.push((0, pg_1.sql) `ty.typcategory = ${query.category}`);
}
return conditions;
}
exports.typeQuery = typeQuery;
exports.typeQuery = typeQuery;
//# sourceMappingURL=getTypes.js.map
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
Object.defineProperty(exports, "__esModule", { value: true });
exports.sql = exports.connect = exports.default = exports.TypeKind = exports.TypeCategory = exports.ForeignKeyMatchType = exports.ForeignKeyAction = exports.ConstraintType = exports.ClassKind = void 0;
var ClassKind_1 = require("./enums/ClassKind");
Object.defineProperty(exports, "ClassKind", {
enumerable: true,
get: function () {
return ClassKind_1.default;
}
});
Object.defineProperty(exports, "ClassKind", { enumerable: true, get: function () { return ClassKind_1.default; } });
var ConstraintType_1 = require("./enums/ConstraintType");
Object.defineProperty(exports, "ConstraintType", {
enumerable: true,
get: function () {
return ConstraintType_1.default;
}
});
Object.defineProperty(exports, "ConstraintType", { enumerable: true, get: function () { return ConstraintType_1.default; } });
var ForeginKeyAction_1 = require("./enums/ForeginKeyAction");
Object.defineProperty(exports, "ForeignKeyAction", {
enumerable: true,
get: function () {
return ForeginKeyAction_1.default;
}
});
Object.defineProperty(exports, "ForeignKeyAction", { enumerable: true, get: function () { return ForeginKeyAction_1.default; } });
var ForeignKeyMatchType_1 = require("./enums/ForeignKeyMatchType");
Object.defineProperty(exports, "ForeignKeyMatchType", {
enumerable: true,
get: function () {
return ForeignKeyMatchType_1.default;
}
});
Object.defineProperty(exports, "ForeignKeyMatchType", { enumerable: true, get: function () { return ForeignKeyMatchType_1.default; } });
var TypeCategory_1 = require("./enums/TypeCategory");
Object.defineProperty(exports, "TypeCategory", {
enumerable: true,
get: function () {
return TypeCategory_1.default;
}
});
Object.defineProperty(exports, "TypeCategory", { enumerable: true, get: function () { return TypeCategory_1.default; } });
var TypeKind_1 = require("./enums/TypeKind");
Object.defineProperty(exports, "TypeKind", {
enumerable: true,
get: function () {
return TypeKind_1.default;
}
});
Object.defineProperty(exports, "TypeKind", { enumerable: true, get: function () { return TypeKind_1.default; } });
var getSchema_1 = require("./getSchema");
Object.defineProperty(exports, "default", {
enumerable: true,
get: function () {
return getSchema_1.default;
}
});
Object.defineProperty(exports, "connect", {
enumerable: true,
get: function () {
return getSchema_1.connect;
}
});
Object.defineProperty(exports, "sql", {
enumerable: true,
get: function () {
return getSchema_1.sql;
}
});
Object.defineProperty(exports, "default", { enumerable: true, get: function () { return getSchema_1.default; } });
Object.defineProperty(exports, "connect", { enumerable: true, get: function () { return getSchema_1.connect; } });
Object.defineProperty(exports, "sql", { enumerable: true, get: function () { return getSchema_1.sql; } });
//# sourceMappingURL=index.js.map
{
"name": "@databases/pg-schema-introspect",
"version": "4.1.0",
"version": "4.2.0-canary-2649",
"description": "",

@@ -8,3 +8,3 @@ "main": "./lib/index.js",

"dependencies": {
"@databases/pg": "^5.0.0"
"@databases/pg": "5.5.0"
},

@@ -11,0 +11,0 @@ "devDependencies": {

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

SocketSocket SOC 2 Logo

Product

  • Package Alerts
  • Integrations
  • Docs
  • Pricing
  • FAQ
  • Roadmap

Stay in touch

Get open source security insights delivered straight into your inbox.


  • Terms
  • Privacy
  • Security

Made with ⚡️ by Socket Inc