poad 2.76.1 → 2.76.3
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/package.json +1 -1
- package/project/deploy.js +23 -8
- package/project/migrate.js +1 -1
- package/project/ref/index.js +2 -2
- package/project/ref/load.js +58 -18
- package/project/ref/ls.js +14 -4
- package/project/source.js +6 -0
- package/project/upgrade.js +1 -1
- package/test/api-exposure.test.js +40 -0
- package/test/project-sync.test.js +1 -1
- package/test/redirectors.test.js +23 -0
- package/test/reference-reload.test.js +94 -4
- package/utils/api-exposure/api-exposure.sql +11 -2
- package/utils/api-exposure/index.js +33 -11
- package/utils/help-details.js +4 -2
- package/utils/migrate-run.js +1 -1
- package/utils/project-sync/run.js +39 -26
- package/utils/redirectors.js +48 -0
- package/utils/reference-store.js +93 -23
- package/utils/reference.js +87 -4
- package/utils/seed/apply.js +68 -4
- package/utils/seed/run.js +62 -2
package/utils/seed/apply.js
CHANGED
|
@@ -72,7 +72,7 @@ const SEQUENCES = ` for s in select a.attname::text as col, pg_get_serial_seque
|
|
|
72
72
|
end loop;`;
|
|
73
73
|
|
|
74
74
|
/** Fin du script (après les lignes de données) */
|
|
75
|
-
function tail(target, columns) {
|
|
75
|
+
function tail(target, columns, sha256) {
|
|
76
76
|
const arr = columns && columns.length ? `array[${columns.map(quoteLiteral).join(', ')}]::text[]` : 'null::text[]';
|
|
77
77
|
const reg = `${quoteLiteral(sqlName(target))}::regclass`;
|
|
78
78
|
return `\\.
|
|
@@ -113,8 +113,10 @@ begin
|
|
|
113
113
|
get diagnostics d = row_count;
|
|
114
114
|
execute format('insert into %s (%s) overriding system value select %s from _poad_seed', t, collist, collist);
|
|
115
115
|
else
|
|
116
|
+
-- Clé primaire : jamais nulle, « = » suffit et permet une anti-jointure par hachage (« is not distinct
|
|
117
|
+
-- from » forçait une boucle imbriquée : 132 s pour recharger 260 000 lignes sur 100 000)
|
|
116
118
|
execute format('delete from %s x where not exists (select 1 from _poad_seed s where %s)', t,
|
|
117
|
-
(select string_agg(format('s.%1$I
|
|
119
|
+
(select string_agg(format('s.%1$I = x.%1$I', c), ' and ') from unnest(pk) c));
|
|
118
120
|
get diagnostics d = row_count;
|
|
119
121
|
setlist := (select string_agg(format('%1$I = excluded.%1$I', c), ', ') from unnest(cols) c where c <> all (pk));
|
|
120
122
|
execute format('insert into %s (%s) overriding system value select %s from _poad_seed on conflict (%s) do %s', t, collist, collist,
|
|
@@ -127,7 +129,7 @@ ${SEQUENCES}
|
|
|
127
129
|
end
|
|
128
130
|
$poad$;
|
|
129
131
|
\\endif
|
|
130
|
-
commit;
|
|
132
|
+
${sha256 ? markSql(target, sha256) : ''}commit;
|
|
131
133
|
`;
|
|
132
134
|
}
|
|
133
135
|
|
|
@@ -137,6 +139,68 @@ function parseNotice(text) {
|
|
|
137
139
|
return m ? { table: m[1], written: Number(m[2]), deleted: Number(m[3]) } : null;
|
|
138
140
|
}
|
|
139
141
|
|
|
142
|
+
// --- État réel d'une table de référence dans la base (CLI 2.76.2) ---------------------------------
|
|
143
|
+
// La marque est posée dans la base du projet, dans la transaction du chargement : _poad.reference_loads
|
|
144
|
+
// (table, empreinte sha256 du contenu chargé, nombre de lignes après chargement). Un volume recréé vide ou
|
|
145
|
+
// une base remise à zéro la perdent avec les lignes : la table redevient « à charger ». Le registre du
|
|
146
|
+
// plan de contrôle (seed_applied) et poad/data du CLI ne sont qu'un cache de cet état.
|
|
147
|
+
|
|
148
|
+
const SHA_RE = /^[0-9a-f]{64}$/;
|
|
149
|
+
|
|
150
|
+
/** Instructions qui posent la marque (dans une transaction ouverte) ; la table de marques est créée au besoin */
|
|
151
|
+
function markSql(target, sha256) {
|
|
152
|
+
if (!SHA_RE.test(String(sha256))) throw new Error('empreinte sha256 attendue');
|
|
153
|
+
return `create schema if not exists _poad;
|
|
154
|
+
create table if not exists _poad.reference_loads (target text primary key, sha256 text not null, rows bigint not null, loaded_at timestamptz not null default now());
|
|
155
|
+
revoke all on _poad.reference_loads from public;
|
|
156
|
+
insert into _poad.reference_loads (target, sha256, rows) select ${quoteLiteral(target)}, ${quoteLiteral(sha256)}, count(*) from ${sqlName(target)}
|
|
157
|
+
on conflict (target) do update set sha256 = excluded.sha256, rows = excluded.rows, loaded_at = now();
|
|
158
|
+
`;
|
|
159
|
+
}
|
|
160
|
+
|
|
161
|
+
/**
|
|
162
|
+
* Une requête (une ligne JSON) : pour chaque table, existe-t-elle, est-elle vide, sa marque (empreinte, lignes
|
|
163
|
+
* à la pose) et, si elle est marquée, son nombre de lignes. Lecture seule ; marche aussi sans la table de marques
|
|
164
|
+
* (engine jamais chargé) et sans la table elle-même (migration non appliquée).
|
|
165
|
+
*/
|
|
166
|
+
function stateSql(targets) {
|
|
167
|
+
const rows = targets.map((t) => `(${quoteLiteral(t)}, ${quoteLiteral(sqlName(t))})`).join(', ');
|
|
168
|
+
const xp = (path, x, type) => `(xpath('${path}/text()', ${x}))[1]::text${type ? `::${type}` : ''}`;
|
|
169
|
+
return `select coalesce(json_agg(json_build_object('target', target, 'exists', rel is not null, 'empty', empty, 'sha256', ${xp('/row/s', 'mark')}, 'mark_rows', ${xp('/row/r', 'mark', 'bigint')}, 'loaded_at', ${xp('/row/l', 'mark')}, ` +
|
|
170
|
+
`'rows', case when rel is not null and ${xp('/row/s', 'mark')} is not null then ${xp('/row/n', "query_to_xml(format('select count(*) as n from %s', rel), false, true, '')", 'bigint')} end) order by target), '[]')::text from (` +
|
|
171
|
+
`select w.target, w.rel, case when w.rel is null then null else ${xp('/row/e', "query_to_xml(format('select not exists (select 1 from %s) as e', w.rel), false, true, '')", 'boolean')} end as empty, ` +
|
|
172
|
+
`case when to_regclass('_poad.reference_loads') is not null then nullif(query_to_xml(format('select sha256 as s, rows as r, loaded_at as l from _poad.reference_loads where target = %L', w.target), false, true, '')::text, '')::xml end as mark ` +
|
|
173
|
+
`from (select v.target, to_regclass(v.name) as rel from (values ${rows}) v(target, name)) w) y`;
|
|
174
|
+
}
|
|
175
|
+
|
|
176
|
+
/**
|
|
177
|
+
* Verdict pour une table : loaded (marque à l'empreinte attendue, autant de lignes qu'à la pose ou plus),
|
|
178
|
+
* sinon à charger : empty (vide, sans marque), unmarked (des lignes, pas de marque), outdated (autre
|
|
179
|
+
* empreinte), incomplete (moins de lignes qu'à la pose), no_table (pas encore créée) ; unknown : base illisible.
|
|
180
|
+
* expected : une empreinte ou une liste d'empreintes acceptées.
|
|
181
|
+
*/
|
|
182
|
+
function referenceState(expected, st) {
|
|
183
|
+
if (!st) return 'unknown';
|
|
184
|
+
if (!st.exists) return 'no_table';
|
|
185
|
+
if (!st.sha256) return st.empty ? 'empty' : 'unmarked';
|
|
186
|
+
const ok = (Array.isArray(expected) ? expected : [expected]).filter(Boolean);
|
|
187
|
+
if (ok.length && !ok.includes(st.sha256)) return 'outdated';
|
|
188
|
+
if (st.rows === null || st.rows === undefined || Number(st.rows) < Number(st.mark_rows || 0)) return 'incomplete';
|
|
189
|
+
return 'loaded';
|
|
190
|
+
}
|
|
191
|
+
|
|
192
|
+
/** Sortie de stateSql (dernière ligne non vide) → { target: état brut } ; null si illisible */
|
|
193
|
+
function parseState(text) {
|
|
194
|
+
const line = String(text || '').trim().split('\n').filter(Boolean).pop();
|
|
195
|
+
try {
|
|
196
|
+
const list = JSON.parse(line);
|
|
197
|
+
if (!Array.isArray(list)) return null;
|
|
198
|
+
return Object.fromEntries(list.map((x) => [x.target, { ...x, rows: x.rows === null ? null : Number(x.rows), mark_rows: x.mark_rows === null ? null : Number(x.mark_rows) }]));
|
|
199
|
+
} catch {
|
|
200
|
+
return null;
|
|
201
|
+
}
|
|
202
|
+
}
|
|
203
|
+
|
|
140
204
|
/** Requête des dépendances (clés étrangères) entre tables, pour l'ordre de chargement */
|
|
141
205
|
const FK_SQL = "select conrelid::regclass::text || '|' || confrelid::regclass::text from pg_constraint where contype = 'f' and conrelid <> confrelid";
|
|
142
206
|
|
|
@@ -164,4 +228,4 @@ function loadOrder(targets, edges) {
|
|
|
164
228
|
return out;
|
|
165
229
|
}
|
|
166
230
|
|
|
167
|
-
module.exports = { head, tail, parseNotice, sqlName, quoteIdent, loadOrder, FK_SQL };
|
|
231
|
+
module.exports = { head, tail, parseNotice, sqlName, quoteIdent, loadOrder, FK_SQL, markSql, stateSql, referenceState, parseState };
|
package/utils/seed/run.js
CHANGED
|
@@ -188,7 +188,7 @@ async function loadLocal(container, d, { database } = {}) {
|
|
|
188
188
|
// psql peut s'arrêter avant la fin (ON_ERROR_STOP) : c'est alors son message qui compte, pas l'écriture coupée
|
|
189
189
|
let streamErr = null;
|
|
190
190
|
await pipeline(Readable.fromWeb(res.body), decryptStream(Buffer.from(d.key, 'base64')), zlib.createGunzip(), c.stdin, { end: false })
|
|
191
|
-
.then(() => c.stdin.end(A.tail(d.target, d.columns)))
|
|
191
|
+
.then(() => c.stdin.end(A.tail(d.target, d.columns, d.sha256)))
|
|
192
192
|
.catch((e) => {
|
|
193
193
|
streamErr = e;
|
|
194
194
|
c.stdin.destroy();
|
|
@@ -206,6 +206,66 @@ async function loadLocal(container, d, { database } = {}) {
|
|
|
206
206
|
}
|
|
207
207
|
|
|
208
208
|
/** Dépendances entre tables de l'engine local (ordre de chargement) */
|
|
209
|
+
/**
|
|
210
|
+
* Contenu converti (convertFile : COPY en gzip) chargé dans l'engine local, avec la marque de son empreinte (la
|
|
211
|
+
* même que sur poad.io pour le même fichier) ; { written, deleted, warnings }
|
|
212
|
+
*/
|
|
213
|
+
async function loadLocalFile(container, t, { database } = {}) {
|
|
214
|
+
const c = localPsql(container, [], database);
|
|
215
|
+
let out = '';
|
|
216
|
+
c.stdout.on('data', (x) => (out = (out + x).slice(-20000)));
|
|
217
|
+
c.stderr.on('data', (x) => (out = (out + x).slice(-20000)));
|
|
218
|
+
const closed = new Promise((r) => c.on('close', r));
|
|
219
|
+
c.stdin.on('error', () => {});
|
|
220
|
+
c.stdin.write(A.head(t.target, t.columns));
|
|
221
|
+
let streamErr = null;
|
|
222
|
+
await pipeline(fs.createReadStream(t.file), zlib.createGunzip(), c.stdin, { end: false })
|
|
223
|
+
.then(() => c.stdin.end(A.tail(t.target, t.columns, t.sha256)))
|
|
224
|
+
.catch((e) => {
|
|
225
|
+
streamErr = e;
|
|
226
|
+
c.stdin.destroy();
|
|
227
|
+
});
|
|
228
|
+
const code = await closed;
|
|
229
|
+
if (code === 0 && streamErr) throw new api.CloudError(`${t.target}: ${streamErr.message}`, { code: 'seed_load_failed' });
|
|
230
|
+
if (code !== 0) {
|
|
231
|
+
const lines = out.split('\n');
|
|
232
|
+
const e = (lines.find((l) => /ERROR:/.test(l)) || lines.filter(Boolean).pop() || `psql ${code}`).replace(/^psql:[^E]*/, '').replace(/^ERROR:\s+([0-9A-Z]{5}:\s+)?/, '');
|
|
233
|
+
throw new api.CloudError(`${t.target}: ${e}`, { code: 'seed_load_failed' });
|
|
234
|
+
}
|
|
235
|
+
const warnings = out.split('\n').filter((l) => /WARNING:.*poad-seed/.test(l)).map((l) => l.replace(/^.*WARNING:\s+([0-9A-Z]{5}:\s+)?poad-seed\s+/, ''));
|
|
236
|
+
return { ...(A.parseNotice(out) || { written: null, deleted: null }), warnings };
|
|
237
|
+
}
|
|
238
|
+
|
|
239
|
+
/** État réel des tables dans la base locale (marque posée au chargement, lignes) ; null : illisible */
|
|
240
|
+
function localState(container, targets) {
|
|
241
|
+
if (!targets.length) return Promise.resolve({});
|
|
242
|
+
return new Promise((resolve) => {
|
|
243
|
+
const c = localPsql(container, ['-tA', '-c', A.stateSql(targets)]);
|
|
244
|
+
let out = '';
|
|
245
|
+
c.stdout.on('data', (x) => (out += x));
|
|
246
|
+
c.on('error', () => resolve(null));
|
|
247
|
+
c.on('close', (code) => resolve(code === 0 ? A.parseState(out) : null));
|
|
248
|
+
c.stdin.end();
|
|
249
|
+
});
|
|
250
|
+
}
|
|
251
|
+
|
|
252
|
+
/**
|
|
253
|
+
* Lignes du puits de logs local (service cli) : event=reference_state (une par table vérifiée) ou reference_load ;
|
|
254
|
+
* noms, états, nombres de lignes, empreintes courtes ; jamais une valeur des données.
|
|
255
|
+
*/
|
|
256
|
+
function localLog(container, entries) {
|
|
257
|
+
if (!entries.length) return Promise.resolve();
|
|
258
|
+
const lit = (v) => `'${String(v).replace(/'/g, "''")}'`;
|
|
259
|
+
const values = entries.map((e) => `(${lit(e.level || 'info')}, ${lit(e.msg)}, ${lit(JSON.stringify(e.attrs))})`).join(', ');
|
|
260
|
+
const sql = `insert into _logs.entries (ts, level, service, msg, attrs) select now(), l, 'cli', m, a::jsonb from (values ${values}) v(l, m, a) where to_regclass('_logs.entries') is not null`;
|
|
261
|
+
return new Promise((resolve) => {
|
|
262
|
+
const c = localPsql(container, ['-tA', '-c', sql]);
|
|
263
|
+
c.on('error', () => resolve());
|
|
264
|
+
c.on('close', () => resolve());
|
|
265
|
+
c.stdin.end();
|
|
266
|
+
});
|
|
267
|
+
}
|
|
268
|
+
|
|
209
269
|
function localEdges(container) {
|
|
210
270
|
return new Promise((resolve) => {
|
|
211
271
|
const c = localPsql(container, ['-tA', '-c', A.FK_SQL]);
|
|
@@ -216,4 +276,4 @@ function localEdges(container) {
|
|
|
216
276
|
});
|
|
217
277
|
}
|
|
218
278
|
|
|
219
|
-
module.exports = { convertFile, pushTable, waitLoad, loadLocal, localEdges, fmt, tmpDir };
|
|
279
|
+
module.exports = { convertFile, pushTable, waitLoad, loadLocal, loadLocalFile, localState, localLog, localEdges, fmt, tmpDir };
|