@coffre/db 0.5.0 → 0.5.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/dist/migrate.d.ts +41 -4
- package/dist/migrate.js +95 -8
- package/package.json +2 -2
- package/src/migrate.ts +111 -6
package/dist/migrate.d.ts
CHANGED
|
@@ -3,6 +3,40 @@ import { PoolClient } from "pg";
|
|
|
3
3
|
//#region src/migrate.d.ts
|
|
4
4
|
/** Reassert database privileges that pg_dump and CREATE DATABASE TEMPLATE do not carry. */
|
|
5
5
|
export declare function restrictDatabase(client: Pick<PoolClient, 'query'>): Promise<void>;
|
|
6
|
+
/** An owner of coffre's objects whose privileges the login lacks: not a member of it, or one that does not inherit them. */
|
|
7
|
+
export type ForeignOwner = {
|
|
8
|
+
name: string;
|
|
9
|
+
member: boolean;
|
|
10
|
+
};
|
|
11
|
+
/**
|
|
12
|
+
* The login cannot change coffre's objects, the ledger's schema, the tables
|
|
13
|
+
* and the functions: their owners are roles whose privileges it does not
|
|
14
|
+
* have, as neither one of them nor a member of one that inherits them.
|
|
15
|
+
* Postgres would refuse the first migration that touches one, "permission
|
|
16
|
+
* denied for schema drizzle"; this says whose login migrates, or what makes
|
|
17
|
+
* this one able to: on Postgres 16 and later, a membership that inherits,
|
|
18
|
+
* which each one's GRANT says; before, a membership, and a login that
|
|
19
|
+
* inherits (`ALTER ROLE … INHERIT`).
|
|
20
|
+
*/
|
|
21
|
+
export declare class NotOwner extends Error {
|
|
22
|
+
readonly login: string;
|
|
23
|
+
readonly owners: ForeignOwner[];
|
|
24
|
+
constructor(login: string, owners: ForeignOwner[], { grantsInherit, inherits }: {
|
|
25
|
+
grantsInherit: boolean;
|
|
26
|
+
inherits: boolean;
|
|
27
|
+
});
|
|
28
|
+
}
|
|
29
|
+
/** What coffre's migrations make and so change later: relations and functions, by name, in public. */
|
|
30
|
+
type Managed = {
|
|
31
|
+
relations: string[];
|
|
32
|
+
functions: string[];
|
|
33
|
+
};
|
|
34
|
+
/**
|
|
35
|
+
* The names a migration's SQL makes: CREATE TABLE, VIEW, MATERIALIZED VIEW
|
|
36
|
+
* and SEQUENCE, and CREATE FUNCTION, in public. Unquoted, a name is folded
|
|
37
|
+
* to lower case, as Postgres folds it.
|
|
38
|
+
*/
|
|
39
|
+
export declare function managedObjects(sqlTexts: readonly string[]): Managed;
|
|
6
40
|
/**
|
|
7
41
|
* Beside this module: src/migrations in the workspace, and dist/migrations
|
|
8
42
|
* in the built package, where the build copies them.
|
|
@@ -35,17 +69,20 @@ export type MigrationPlan = {
|
|
|
35
69
|
};
|
|
36
70
|
/**
|
|
37
71
|
* Which of this version's migrations a database has applied, and which it
|
|
38
|
-
* has not, without changing it or waiting on a migration under way
|
|
39
|
-
*
|
|
40
|
-
*
|
|
72
|
+
* has not, without changing it or waiting on a migration under way; and
|
|
73
|
+
* whether this login could apply them (`notOwner`), as `migrateDatabase`
|
|
74
|
+
* requires: thrown, when it cannot read which. A history that is not a
|
|
75
|
+
* prefix of this version's is refused, as `migrateDatabase` refuses it.
|
|
41
76
|
*/
|
|
42
77
|
export declare function migrationStatus(url: string): Promise<{
|
|
43
78
|
applied: string[];
|
|
44
79
|
pending: string[];
|
|
80
|
+
notOwner: NotOwner | null;
|
|
45
81
|
}>;
|
|
46
82
|
/**
|
|
47
83
|
* Apply missing migrations, check their history and reassert database
|
|
48
|
-
* privileges
|
|
84
|
+
* privileges, as a login that can change coffre's objects: another is
|
|
85
|
+
* refused, NotOwner, before anything changes. `onPlan` hears what there is to apply before it is, under
|
|
49
86
|
* the migration lock, and may stop the run by throwing: all of it then goes
|
|
50
87
|
* in one call, with no word of each.
|
|
51
88
|
*/
|
package/dist/migrate.js
CHANGED
|
@@ -25,6 +25,71 @@ async function restrictDatabase(client) {
|
|
|
25
25
|
END $$`);
|
|
26
26
|
}
|
|
27
27
|
/**
|
|
28
|
+
* The login cannot change coffre's objects, the ledger's schema, the tables
|
|
29
|
+
* and the functions: their owners are roles whose privileges it does not
|
|
30
|
+
* have, as neither one of them nor a member of one that inherits them.
|
|
31
|
+
* Postgres would refuse the first migration that touches one, "permission
|
|
32
|
+
* denied for schema drizzle"; this says whose login migrates, or what makes
|
|
33
|
+
* this one able to: on Postgres 16 and later, a membership that inherits,
|
|
34
|
+
* which each one's GRANT says; before, a membership, and a login that
|
|
35
|
+
* inherits (`ALTER ROLE … INHERIT`).
|
|
36
|
+
*/
|
|
37
|
+
var NotOwner = class extends Error {
|
|
38
|
+
login;
|
|
39
|
+
owners;
|
|
40
|
+
constructor(login, owners, { grantsInherit, inherits }) {
|
|
41
|
+
const one = owners.length === 1;
|
|
42
|
+
const members = owners.every((owner) => owner.member);
|
|
43
|
+
const fixes = [...owners.filter((owner) => grantsInherit || !owner.member).map((owner) => `GRANT ${identifier(owner.name)} TO ${identifier(login)}${grantsInherit ? " WITH INHERIT TRUE" : ""}`), ...grantsInherit || inherits ? [] : [`ALTER ROLE ${identifier(login)} INHERIT`]];
|
|
44
|
+
super(`coffre's tables are owned by ${owners.map((owner) => owner.name).join(" and ")}, and this login, ${login}, ` + (members ? `is a member of ${one ? "it" : "them"} but does not inherit ${one ? "its" : "their"} privileges: ` : `is neither ${one ? "it nor a member of it" : "one nor a member of one"}: `) + `migrate with ${one ? `${owners[0].name}'s` : "their"} connection string, or, as a role that administers ${one ? "it" : "them"}, run ${fixes.join("; ")}`);
|
|
45
|
+
this.name = "NotOwner";
|
|
46
|
+
this.login = login;
|
|
47
|
+
this.owners = owners;
|
|
48
|
+
}
|
|
49
|
+
};
|
|
50
|
+
/** A role's name as SQL takes it: always quoted, as a keyword such as `user` must be. */
|
|
51
|
+
function identifier(name) {
|
|
52
|
+
return `"${name.replace(/"/g, "\"\"")}"`;
|
|
53
|
+
}
|
|
54
|
+
/**
|
|
55
|
+
* The names a migration's SQL makes: CREATE TABLE, VIEW, MATERIALIZED VIEW
|
|
56
|
+
* and SEQUENCE, and CREATE FUNCTION, in public. Unquoted, a name is folded
|
|
57
|
+
* to lower case, as Postgres folds it.
|
|
58
|
+
*/
|
|
59
|
+
function managedObjects(sqlTexts) {
|
|
60
|
+
const name = String.raw`(?:"?public"?\.)?(?:"((?:[^"]|"")+)"|([A-Za-z_][A-Za-z0-9_$]*))`;
|
|
61
|
+
const relation = new RegExp(String.raw`\bCREATE\s+(?:OR\s+REPLACE\s+)?(?:UNLOGGED\s+)?(?:TABLE|VIEW|MATERIALIZED\s+VIEW|SEQUENCE)\s+(?:IF\s+NOT\s+EXISTS\s+)?${name}`, "gi");
|
|
62
|
+
const fn = new RegExp(String.raw`\bCREATE\s+(?:OR\s+REPLACE\s+)?FUNCTION\s+${name}\s*\(`, "gi");
|
|
63
|
+
const names = (pattern) => [...new Set(sqlTexts.flatMap((text) => [...text.matchAll(pattern)].map(([, quoted, bare]) => quoted !== void 0 ? quoted.replace(/""/g, "\"") : bare.toLowerCase())))];
|
|
64
|
+
return {
|
|
65
|
+
relations: names(relation),
|
|
66
|
+
functions: names(fn)
|
|
67
|
+
};
|
|
68
|
+
}
|
|
69
|
+
/**
|
|
70
|
+
* The owners of what migrations change, whose privileges the login lacks:
|
|
71
|
+
* the drizzle schema and everything in it, and in public the relations and
|
|
72
|
+
* functions coffre's migrations make ($1, $2), and nothing else of public,
|
|
73
|
+
* which may hold a database's other tables. A superuser has every role's.
|
|
74
|
+
*/
|
|
75
|
+
const FOREIGN_OWNERS = `
|
|
76
|
+
WITH owned AS (
|
|
77
|
+
SELECT nspowner AS owner FROM pg_namespace WHERE nspname = 'drizzle'
|
|
78
|
+
UNION ALL
|
|
79
|
+
SELECT c.relowner FROM pg_class c JOIN pg_namespace n ON n.oid = c.relnamespace
|
|
80
|
+
WHERE c.relkind IN ('r', 'p', 'v', 'm', 'S', 'f')
|
|
81
|
+
AND (n.nspname = 'drizzle' OR (n.nspname = 'public' AND c.relname = ANY($1::text[])))
|
|
82
|
+
UNION ALL
|
|
83
|
+
SELECT p.proowner FROM pg_proc p JOIN pg_namespace n ON n.oid = p.pronamespace
|
|
84
|
+
WHERE n.nspname = 'public' AND p.proname = ANY($2::text[])
|
|
85
|
+
)
|
|
86
|
+
SELECT DISTINCT r.rolname AS owner, pg_has_role(owned.owner, 'MEMBER') AS member, current_user AS login,
|
|
87
|
+
current_setting('server_version_num')::int >= 160000 AS grants_inherit,
|
|
88
|
+
(SELECT rolinherit FROM pg_roles WHERE rolname = current_user) AS inherits
|
|
89
|
+
FROM owned JOIN pg_roles r ON r.oid = owned.owner
|
|
90
|
+
WHERE NOT pg_has_role(owned.owner, 'USAGE')
|
|
91
|
+
ORDER BY r.rolname`;
|
|
92
|
+
/**
|
|
28
93
|
* Beside this module: src/migrations in the workspace, and dist/migrations
|
|
29
94
|
* in the built package, where the build copies them.
|
|
30
95
|
*/
|
|
@@ -41,7 +106,8 @@ async function expectedMigrations(engine) {
|
|
|
41
106
|
return {
|
|
42
107
|
createdAt: String(entry.when),
|
|
43
108
|
hash: createHash("sha256").update(sqlText).digest("hex"),
|
|
44
|
-
tag: entry.tag
|
|
109
|
+
tag: entry.tag,
|
|
110
|
+
sql: sqlText
|
|
45
111
|
};
|
|
46
112
|
}));
|
|
47
113
|
for (let index = 1; index < expected.length; index += 1) if (BigInt(expected[index - 1].createdAt) >= BigInt(expected[index].createdAt)) throw new Error("Drizzle migration journal timestamps must be strictly increasing");
|
|
@@ -106,6 +172,18 @@ async function postgresMigrator(url) {
|
|
|
106
172
|
},
|
|
107
173
|
migrate: (migrationsFolder) => migrate(drizzle(client), { migrationsFolder }),
|
|
108
174
|
restrict: () => restrictDatabase(client),
|
|
175
|
+
async notOwner({ relations, functions }) {
|
|
176
|
+
const { rows } = await client.query(FOREIGN_OWNERS, [relations, functions]);
|
|
177
|
+
if (rows.length === 0) return null;
|
|
178
|
+
const [{ login, grants_inherit: grantsInherit, inherits }] = rows;
|
|
179
|
+
return new NotOwner(login, rows.map(({ owner, member }) => ({
|
|
180
|
+
name: owner,
|
|
181
|
+
member
|
|
182
|
+
})), {
|
|
183
|
+
grantsInherit,
|
|
184
|
+
inherits
|
|
185
|
+
});
|
|
186
|
+
},
|
|
109
187
|
async close() {
|
|
110
188
|
client.release();
|
|
111
189
|
await pool.end();
|
|
@@ -125,14 +203,16 @@ async function sqliteMigrator(url) {
|
|
|
125
203
|
async unlock() {},
|
|
126
204
|
migrate: (migrationsFolder) => migrate(sqlite, { migrationsFolder }),
|
|
127
205
|
async restrict() {},
|
|
206
|
+
notOwner: async () => null,
|
|
128
207
|
close
|
|
129
208
|
};
|
|
130
209
|
}
|
|
131
210
|
/**
|
|
132
211
|
* Which of this version's migrations a database has applied, and which it
|
|
133
|
-
* has not, without changing it or waiting on a migration under way
|
|
134
|
-
*
|
|
135
|
-
*
|
|
212
|
+
* has not, without changing it or waiting on a migration under way; and
|
|
213
|
+
* whether this login could apply them (`notOwner`), as `migrateDatabase`
|
|
214
|
+
* requires: thrown, when it cannot read which. A history that is not a
|
|
215
|
+
* prefix of this version's is refused, as `migrateDatabase` refuses it.
|
|
136
216
|
*/
|
|
137
217
|
async function migrationStatus(url) {
|
|
138
218
|
const engine = engineOfUrl(url);
|
|
@@ -142,12 +222,16 @@ async function migrationStatus(url) {
|
|
|
142
222
|
sqlite: sqliteMigrator
|
|
143
223
|
}[engine](url);
|
|
144
224
|
try {
|
|
145
|
-
const
|
|
225
|
+
const notOwner = await migrator.notOwner(managedObjects(expected.map((entry) => entry.sql)));
|
|
226
|
+
const history = await migrator.applied().catch((error) => {
|
|
227
|
+
throw notOwner ?? error;
|
|
228
|
+
});
|
|
146
229
|
verifyHistory(expected, history, false);
|
|
147
230
|
const applied = history?.length ?? 0;
|
|
148
231
|
return {
|
|
149
232
|
applied: expected.slice(0, applied).map((entry) => entry.tag),
|
|
150
|
-
pending: expected.slice(applied).map((entry) => entry.tag)
|
|
233
|
+
pending: expected.slice(applied).map((entry) => entry.tag),
|
|
234
|
+
notOwner
|
|
151
235
|
};
|
|
152
236
|
} finally {
|
|
153
237
|
await migrator.close();
|
|
@@ -155,7 +239,8 @@ async function migrationStatus(url) {
|
|
|
155
239
|
}
|
|
156
240
|
/**
|
|
157
241
|
* Apply missing migrations, check their history and reassert database
|
|
158
|
-
* privileges
|
|
242
|
+
* privileges, as a login that can change coffre's objects: another is
|
|
243
|
+
* refused, NotOwner, before anything changes. `onPlan` hears what there is to apply before it is, under
|
|
159
244
|
* the migration lock, and may stop the run by throwing: all of it then goes
|
|
160
245
|
* in one call, with no word of each.
|
|
161
246
|
*/
|
|
@@ -170,6 +255,8 @@ async function migrateDatabase(url, onPlan) {
|
|
|
170
255
|
try {
|
|
171
256
|
await migrator.lock();
|
|
172
257
|
locked = true;
|
|
258
|
+
const notOwner = await migrator.notOwner(managedObjects(expected.map((entry) => entry.sql)));
|
|
259
|
+
if (notOwner !== null) throw notOwner;
|
|
173
260
|
const applied = await migrator.applied();
|
|
174
261
|
verifyHistory(expected, applied, false);
|
|
175
262
|
const done = applied?.length ?? 0;
|
|
@@ -190,4 +277,4 @@ async function migrateDatabase(url, onPlan) {
|
|
|
190
277
|
}
|
|
191
278
|
}
|
|
192
279
|
//#endregion
|
|
193
|
-
export { DatabaseAhead, migrateDatabase, migrationStatus, migrationsFolder, restrictDatabase };
|
|
280
|
+
export { DatabaseAhead, NotOwner, managedObjects, migrateDatabase, migrationStatus, migrationsFolder, restrictDatabase };
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@coffre/db",
|
|
3
|
-
"version": "0.5.
|
|
3
|
+
"version": "0.5.1",
|
|
4
4
|
"description": "coffre's database: the schema, its migrations and the connections, on Postgres or SQLite.",
|
|
5
5
|
"license": "MIT",
|
|
6
6
|
"repository": {
|
|
@@ -79,7 +79,7 @@
|
|
|
79
79
|
"drizzle-orm": "0.45.2",
|
|
80
80
|
"pg": "8.16.3",
|
|
81
81
|
"pg-connection-string": "2.14.0",
|
|
82
|
-
"@coffre/core": "0.5.
|
|
82
|
+
"@coffre/core": "0.5.1"
|
|
83
83
|
},
|
|
84
84
|
"devDependencies": {
|
|
85
85
|
"@types/node": "26.1.1",
|
package/src/migrate.ts
CHANGED
|
@@ -40,6 +40,7 @@ interface ExpectedMigration {
|
|
|
40
40
|
createdAt: string;
|
|
41
41
|
hash: string;
|
|
42
42
|
tag: string;
|
|
43
|
+
sql: string;
|
|
43
44
|
}
|
|
44
45
|
|
|
45
46
|
interface AppliedMigration {
|
|
@@ -56,9 +57,95 @@ interface Migrator {
|
|
|
56
57
|
migrate(migrationsFolder: string): Promise<void>;
|
|
57
58
|
/** Reassert privileges a one-database backup does not carry. */
|
|
58
59
|
restrict(): Promise<void>;
|
|
60
|
+
/** Why this login cannot change the objects migrations change, `managed` among them, or null when it can. */
|
|
61
|
+
notOwner(managed: Managed): Promise<NotOwner | null>;
|
|
59
62
|
close(): Promise<void>;
|
|
60
63
|
}
|
|
61
64
|
|
|
65
|
+
/** An owner of coffre's objects whose privileges the login lacks: not a member of it, or one that does not inherit them. */
|
|
66
|
+
export type ForeignOwner = { name: string; member: boolean };
|
|
67
|
+
|
|
68
|
+
/**
|
|
69
|
+
* The login cannot change coffre's objects, the ledger's schema, the tables
|
|
70
|
+
* and the functions: their owners are roles whose privileges it does not
|
|
71
|
+
* have, as neither one of them nor a member of one that inherits them.
|
|
72
|
+
* Postgres would refuse the first migration that touches one, "permission
|
|
73
|
+
* denied for schema drizzle"; this says whose login migrates, or what makes
|
|
74
|
+
* this one able to: on Postgres 16 and later, a membership that inherits,
|
|
75
|
+
* which each one's GRANT says; before, a membership, and a login that
|
|
76
|
+
* inherits (`ALTER ROLE … INHERIT`).
|
|
77
|
+
*/
|
|
78
|
+
export class NotOwner extends Error {
|
|
79
|
+
readonly login: string;
|
|
80
|
+
readonly owners: ForeignOwner[];
|
|
81
|
+
|
|
82
|
+
constructor(login: string, owners: ForeignOwner[], { grantsInherit, inherits }: { grantsInherit: boolean; inherits: boolean }) {
|
|
83
|
+
const one = owners.length === 1;
|
|
84
|
+
const members = owners.every((owner) => owner.member);
|
|
85
|
+
const fixes = [
|
|
86
|
+
...owners.filter((owner) => grantsInherit || !owner.member).map((owner) => `GRANT ${identifier(owner.name)} TO ${identifier(login)}${grantsInherit ? ' WITH INHERIT TRUE' : ''}`),
|
|
87
|
+
...(grantsInherit || inherits ? [] : [`ALTER ROLE ${identifier(login)} INHERIT`]),
|
|
88
|
+
];
|
|
89
|
+
super(
|
|
90
|
+
`coffre's tables are owned by ${owners.map((owner) => owner.name).join(' and ')}, and this login, ${login}, ` +
|
|
91
|
+
(members
|
|
92
|
+
? `is a member of ${one ? 'it' : 'them'} but does not inherit ${one ? 'its' : 'their'} privileges: `
|
|
93
|
+
: `is neither ${one ? 'it nor a member of it' : 'one nor a member of one'}: `) +
|
|
94
|
+
`migrate with ${one ? `${owners[0]!.name}'s` : 'their'} connection string, or, as a role that administers ${one ? 'it' : 'them'}, run ${fixes.join('; ')}`,
|
|
95
|
+
);
|
|
96
|
+
this.name = 'NotOwner';
|
|
97
|
+
this.login = login;
|
|
98
|
+
this.owners = owners;
|
|
99
|
+
}
|
|
100
|
+
}
|
|
101
|
+
|
|
102
|
+
/** A role's name as SQL takes it: always quoted, as a keyword such as `user` must be. */
|
|
103
|
+
function identifier(name: string): string {
|
|
104
|
+
return `"${name.replace(/"/g, '""')}"`;
|
|
105
|
+
}
|
|
106
|
+
|
|
107
|
+
/** What coffre's migrations make and so change later: relations and functions, by name, in public. */
|
|
108
|
+
type Managed = { relations: string[]; functions: string[] };
|
|
109
|
+
|
|
110
|
+
/**
|
|
111
|
+
* The names a migration's SQL makes: CREATE TABLE, VIEW, MATERIALIZED VIEW
|
|
112
|
+
* and SEQUENCE, and CREATE FUNCTION, in public. Unquoted, a name is folded
|
|
113
|
+
* to lower case, as Postgres folds it.
|
|
114
|
+
*/
|
|
115
|
+
export function managedObjects(sqlTexts: readonly string[]): Managed {
|
|
116
|
+
const name = String.raw`(?:"?public"?\.)?(?:"((?:[^"]|"")+)"|([A-Za-z_][A-Za-z0-9_$]*))`;
|
|
117
|
+
const relation = new RegExp(String.raw`\bCREATE\s+(?:OR\s+REPLACE\s+)?(?:UNLOGGED\s+)?(?:TABLE|VIEW|MATERIALIZED\s+VIEW|SEQUENCE)\s+(?:IF\s+NOT\s+EXISTS\s+)?${name}`, 'gi');
|
|
118
|
+
const fn = new RegExp(String.raw`\bCREATE\s+(?:OR\s+REPLACE\s+)?FUNCTION\s+${name}\s*\(`, 'gi');
|
|
119
|
+
const names = (pattern: RegExp) => [
|
|
120
|
+
...new Set(sqlTexts.flatMap((text) => [...text.matchAll(pattern)].map(([, quoted, bare]) => (quoted !== undefined ? quoted.replace(/""/g, '"') : bare!.toLowerCase())))),
|
|
121
|
+
];
|
|
122
|
+
return { relations: names(relation), functions: names(fn) };
|
|
123
|
+
}
|
|
124
|
+
|
|
125
|
+
/**
|
|
126
|
+
* The owners of what migrations change, whose privileges the login lacks:
|
|
127
|
+
* the drizzle schema and everything in it, and in public the relations and
|
|
128
|
+
* functions coffre's migrations make ($1, $2), and nothing else of public,
|
|
129
|
+
* which may hold a database's other tables. A superuser has every role's.
|
|
130
|
+
*/
|
|
131
|
+
const FOREIGN_OWNERS = `
|
|
132
|
+
WITH owned AS (
|
|
133
|
+
SELECT nspowner AS owner FROM pg_namespace WHERE nspname = 'drizzle'
|
|
134
|
+
UNION ALL
|
|
135
|
+
SELECT c.relowner FROM pg_class c JOIN pg_namespace n ON n.oid = c.relnamespace
|
|
136
|
+
WHERE c.relkind IN ('r', 'p', 'v', 'm', 'S', 'f')
|
|
137
|
+
AND (n.nspname = 'drizzle' OR (n.nspname = 'public' AND c.relname = ANY($1::text[])))
|
|
138
|
+
UNION ALL
|
|
139
|
+
SELECT p.proowner FROM pg_proc p JOIN pg_namespace n ON n.oid = p.pronamespace
|
|
140
|
+
WHERE n.nspname = 'public' AND p.proname = ANY($2::text[])
|
|
141
|
+
)
|
|
142
|
+
SELECT DISTINCT r.rolname AS owner, pg_has_role(owned.owner, 'MEMBER') AS member, current_user AS login,
|
|
143
|
+
current_setting('server_version_num')::int >= 160000 AS grants_inherit,
|
|
144
|
+
(SELECT rolinherit FROM pg_roles WHERE rolname = current_user) AS inherits
|
|
145
|
+
FROM owned JOIN pg_roles r ON r.oid = owned.owner
|
|
146
|
+
WHERE NOT pg_has_role(owned.owner, 'USAGE')
|
|
147
|
+
ORDER BY r.rolname`;
|
|
148
|
+
|
|
62
149
|
/**
|
|
63
150
|
* Beside this module: src/migrations in the workspace, and dist/migrations
|
|
64
151
|
* in the built package, where the build copies them.
|
|
@@ -89,6 +176,7 @@ async function expectedMigrations(engine: Engine): Promise<ExpectedMigration[]>
|
|
|
89
176
|
createdAt: String(entry.when),
|
|
90
177
|
hash: createHash('sha256').update(sqlText).digest('hex'),
|
|
91
178
|
tag: entry.tag,
|
|
179
|
+
sql: sqlText,
|
|
92
180
|
};
|
|
93
181
|
}),
|
|
94
182
|
);
|
|
@@ -177,6 +265,12 @@ async function postgresMigrator(url: string): Promise<Migrator> {
|
|
|
177
265
|
},
|
|
178
266
|
migrate: (migrationsFolder) => migrate(drizzle(client), { migrationsFolder }),
|
|
179
267
|
restrict: () => restrictDatabase(client),
|
|
268
|
+
async notOwner({ relations, functions }) {
|
|
269
|
+
const { rows } = await client.query<{ owner: string; member: boolean; login: string; grants_inherit: boolean; inherits: boolean }>(FOREIGN_OWNERS, [relations, functions]);
|
|
270
|
+
if (rows.length === 0) return null;
|
|
271
|
+
const [{ login, grants_inherit: grantsInherit, inherits }] = rows as [(typeof rows)[number]];
|
|
272
|
+
return new NotOwner(login, rows.map(({ owner, member }) => ({ name: owner, member })), { grantsInherit, inherits });
|
|
273
|
+
},
|
|
180
274
|
async close() {
|
|
181
275
|
client.release();
|
|
182
276
|
await pool.end();
|
|
@@ -206,6 +300,8 @@ async function sqliteMigrator(url: string): Promise<Migrator> {
|
|
|
206
300
|
async unlock() {},
|
|
207
301
|
migrate: (migrationsFolder) => migrate(sqlite, { migrationsFolder }),
|
|
208
302
|
async restrict() {},
|
|
303
|
+
// One file, which whoever opens it may change.
|
|
304
|
+
notOwner: async () => null,
|
|
209
305
|
close,
|
|
210
306
|
};
|
|
211
307
|
}
|
|
@@ -218,21 +314,27 @@ export type MigrationPlan = { applied: number; total: number; pending: string[]
|
|
|
218
314
|
|
|
219
315
|
/**
|
|
220
316
|
* Which of this version's migrations a database has applied, and which it
|
|
221
|
-
* has not, without changing it or waiting on a migration under way
|
|
222
|
-
*
|
|
223
|
-
*
|
|
317
|
+
* has not, without changing it or waiting on a migration under way; and
|
|
318
|
+
* whether this login could apply them (`notOwner`), as `migrateDatabase`
|
|
319
|
+
* requires: thrown, when it cannot read which. A history that is not a
|
|
320
|
+
* prefix of this version's is refused, as `migrateDatabase` refuses it.
|
|
224
321
|
*/
|
|
225
|
-
export async function migrationStatus(url: string): Promise<{ applied: string[]; pending: string[] }> {
|
|
322
|
+
export async function migrationStatus(url: string): Promise<{ applied: string[]; pending: string[]; notOwner: NotOwner | null }> {
|
|
226
323
|
const engine = engineOfUrl(url);
|
|
227
324
|
const expected = await expectedMigrations(engine);
|
|
228
325
|
const migrator = await { postgres: postgresMigrator, sqlite: sqliteMigrator }[engine](url);
|
|
229
326
|
try {
|
|
230
|
-
const
|
|
327
|
+
const notOwner = await migrator.notOwner(managedObjects(expected.map((entry) => entry.sql)));
|
|
328
|
+
// A login that may not even read the ledger is told why.
|
|
329
|
+
const history = await migrator.applied().catch((error: unknown) => {
|
|
330
|
+
throw notOwner ?? error;
|
|
331
|
+
});
|
|
231
332
|
verifyHistory(expected, history, false);
|
|
232
333
|
const applied = history?.length ?? 0;
|
|
233
334
|
return {
|
|
234
335
|
applied: expected.slice(0, applied).map((entry) => entry.tag),
|
|
235
336
|
pending: expected.slice(applied).map((entry) => entry.tag),
|
|
337
|
+
notOwner,
|
|
236
338
|
};
|
|
237
339
|
} finally {
|
|
238
340
|
await migrator.close();
|
|
@@ -241,7 +343,8 @@ export async function migrationStatus(url: string): Promise<{ applied: string[];
|
|
|
241
343
|
|
|
242
344
|
/**
|
|
243
345
|
* Apply missing migrations, check their history and reassert database
|
|
244
|
-
* privileges
|
|
346
|
+
* privileges, as a login that can change coffre's objects: another is
|
|
347
|
+
* refused, NotOwner, before anything changes. `onPlan` hears what there is to apply before it is, under
|
|
245
348
|
* the migration lock, and may stop the run by throwing: all of it then goes
|
|
246
349
|
* in one call, with no word of each.
|
|
247
350
|
*/
|
|
@@ -258,6 +361,8 @@ export async function migrateDatabase(
|
|
|
258
361
|
await migrator.lock();
|
|
259
362
|
locked = true;
|
|
260
363
|
|
|
364
|
+
const notOwner = await migrator.notOwner(managedObjects(expected.map((entry) => entry.sql)));
|
|
365
|
+
if (notOwner !== null) throw notOwner;
|
|
261
366
|
const applied = await migrator.applied();
|
|
262
367
|
verifyHistory(expected, applied, false);
|
|
263
368
|
const done = applied?.length ?? 0;
|