poad 2.50.0 → 2.52.0
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/global/start.js +13 -2
- package/package.json +1 -1
- package/project/cli.js +8 -0
- package/project/logs.js +2 -0
- package/project/seed/index.js +17 -0
- package/project/seed/load.js +50 -0
- package/project/seed/ls.js +27 -0
- package/project/seed/mode.js +14 -0
- package/project/seed/push.js +103 -0
- package/project/seed/rm.js +14 -0
- package/test/fronts.test.js +173 -0
- package/test/seed.test.js +133 -0
- package/utils/fronts.js +213 -0
- package/utils/logline.js +2 -2
- package/utils/report.js +12 -0
- package/utils/seed/apply.js +124 -0
- package/utils/seed/convert.js +673 -0
- package/utils/seed/pack.js +179 -0
- package/utils/seed/run.js +193 -0
- package/utils/tomlfile.js +3 -2
package/utils/fronts.js
ADDED
|
@@ -0,0 +1,213 @@
|
|
|
1
|
+
// Fronts dessinés dans poad (engine 0.46.0+) : un port de cette machine par
|
|
2
|
+
// front, comme sur poad.io un sous-domaine par front (<id>.app.poad.io). Même
|
|
3
|
+
// origine isolée en local qu'en ligne : cookies, stockage et service workers
|
|
4
|
+
// propres au front, et des adresses de pages identiques (pas de /apps/<nom>).
|
|
5
|
+
//
|
|
6
|
+
// poad/config.toml :
|
|
7
|
+
// [fronts]
|
|
8
|
+
// spare_ports = [41001, 41002] réservés d'avance, publiés à chaque poad start
|
|
9
|
+
// [fronts.k3x9q2m7a1bc]
|
|
10
|
+
// port = 41003
|
|
11
|
+
//
|
|
12
|
+
// Chaque port est publié sur le port 8100 du conteneur (second écouteur de la
|
|
13
|
+
// passerelle de l'engine) ; l'engine reconnaît le front à l'hôte d'arrivée
|
|
14
|
+
// (localhost:<port>). Un port ne s'ajoute pas à un conteneur qui tourne :
|
|
15
|
+
// la réserve permet à la console de créer un front pendant que le projet
|
|
16
|
+
// tourne, joignable aussitôt. Réserve vide : le front attend le prochain
|
|
17
|
+
// poad start (la console le dit).
|
|
18
|
+
const SPARE = 2;
|
|
19
|
+
const CONTAINER_PORT = '8100/tcp';
|
|
20
|
+
const ID_RE = /^[a-z][a-z0-9]{11}$/;
|
|
21
|
+
|
|
22
|
+
/** Engine 0.46.0 et plus : fronts servis par l'engine */
|
|
23
|
+
const supportsFronts = (config) => {
|
|
24
|
+
const [major, minor] = String(config.engine || '').split('.').map(Number);
|
|
25
|
+
return major > 0 || minor >= 46;
|
|
26
|
+
};
|
|
27
|
+
|
|
28
|
+
const portOk = (p) => Number.isInteger(p) && p > 0 && p < 65536;
|
|
29
|
+
|
|
30
|
+
/** { fronts: [{ id, port }], spare: [port…] } d'après config.fronts */
|
|
31
|
+
const read = (config) => {
|
|
32
|
+
const section = (config && config.fronts) || {};
|
|
33
|
+
const fronts = [];
|
|
34
|
+
for (const [id, v] of Object.entries(section)) {
|
|
35
|
+
if (!ID_RE.test(id) || !v || typeof v !== 'object' || Array.isArray(v)) continue;
|
|
36
|
+
const port = Number(v.port);
|
|
37
|
+
if (portOk(port)) fronts.push({ id, port });
|
|
38
|
+
}
|
|
39
|
+
const taken = new Set(fronts.map((f) => f.port));
|
|
40
|
+
const spare = [...new Set((Array.isArray(section.spare_ports) ? section.spare_ports : []).map(Number))].filter((p) => portOk(p) && !taken.has(p));
|
|
41
|
+
return { fronts, spare };
|
|
42
|
+
};
|
|
43
|
+
|
|
44
|
+
/** Ports du projet hors fronts (base, API, Mailpit, collecteur…) : jamais pris pour un front */
|
|
45
|
+
const projectPorts = (config) =>
|
|
46
|
+
[config.db && config.db.port, config.web && config.web.port, config.mail && config.mail.port, config.logs && config.logs.gelf_port, config.valkey && config.valkey.port]
|
|
47
|
+
.map(Number)
|
|
48
|
+
.filter(Boolean);
|
|
49
|
+
|
|
50
|
+
/** Écrit la réserve, et les sections [fronts.<id>] données ({ id: port | null }) */
|
|
51
|
+
const write = (root, { spare, fronts = {} }) => {
|
|
52
|
+
const { setKeys, removeSection } = require('./tomlfile');
|
|
53
|
+
if (spare) setKeys(root, 'fronts', { spare_ports: spare });
|
|
54
|
+
for (const [id, port] of Object.entries(fronts)) {
|
|
55
|
+
if (!ID_RE.test(id)) continue;
|
|
56
|
+
if (port === null) removeSection(root, `fronts.${id}`);
|
|
57
|
+
else setKeys(root, `fronts.${id}`, { port });
|
|
58
|
+
}
|
|
59
|
+
};
|
|
60
|
+
|
|
61
|
+
/** Met config.fronts à jour sur place d'après un état { fronts, spare } */
|
|
62
|
+
const apply = (config, state) => {
|
|
63
|
+
const section = { spare_ports: state.spare };
|
|
64
|
+
for (const f of state.fronts) section[f.id] = { port: f.port };
|
|
65
|
+
config.fronts = section;
|
|
66
|
+
};
|
|
67
|
+
|
|
68
|
+
/**
|
|
69
|
+
* Réserve complétée à SPARE ports libres (avant poad start). Renvoie les ports
|
|
70
|
+
* ajoutés. deps.findFreePorts et deps.isPortFree pour les tests.
|
|
71
|
+
*/
|
|
72
|
+
const ensureSpare = async (root, config, deps = {}) => {
|
|
73
|
+
const ports = require('./ports');
|
|
74
|
+
const findFreePorts = deps.findFreePorts || ports.findFreePorts;
|
|
75
|
+
const isPortFree = deps.isPortFree || ports.isPortFree;
|
|
76
|
+
const state = read(config);
|
|
77
|
+
const used = new Set([...projectPorts(config), ...state.fronts.map((f) => f.port), ...state.spare]);
|
|
78
|
+
const added = [];
|
|
79
|
+
// Ports de réserve pris sur cette machine par autre chose : remplacés
|
|
80
|
+
const spare = [];
|
|
81
|
+
for (const p of state.spare) if (await isPortFree(p)) spare.push(p);
|
|
82
|
+
while (spare.length < SPARE) {
|
|
83
|
+
const [p] = await findFreePorts(1, 20000, 60000);
|
|
84
|
+
if (used.has(p)) continue;
|
|
85
|
+
used.add(p);
|
|
86
|
+
spare.push(p);
|
|
87
|
+
added.push(p);
|
|
88
|
+
}
|
|
89
|
+
if (added.length || spare.length !== state.spare.length || (config.fronts || {}).spare_ports === undefined) write(root, { spare });
|
|
90
|
+
apply(config, { ...state, spare });
|
|
91
|
+
return added;
|
|
92
|
+
};
|
|
93
|
+
|
|
94
|
+
/** Entrées pour ports.reassignBusyPorts : le port de chaque front (section fronts.<id>) */
|
|
95
|
+
const busyEntries = (config) =>
|
|
96
|
+
read(config).fronts.map((f) => {
|
|
97
|
+
// reassignBusyPorts lit config[section][key] : alias à plat, replié par foldMoved
|
|
98
|
+
config[`fronts.${f.id}`] = { port: f.port };
|
|
99
|
+
return { section: `fronts.${f.id}`, key: 'port', label: `Front ${f.id}` };
|
|
100
|
+
});
|
|
101
|
+
|
|
102
|
+
/**
|
|
103
|
+
* Après reassignBusyPorts, config['fronts.<id>'] porte le port déplacé : le
|
|
104
|
+
* ramener dans config.fronts.<id>
|
|
105
|
+
*/
|
|
106
|
+
const foldMoved = (config) => {
|
|
107
|
+
for (const key of Object.keys(config)) {
|
|
108
|
+
const m = /^fronts\.([a-z][a-z0-9]{11})$/.exec(key);
|
|
109
|
+
if (!m) continue;
|
|
110
|
+
config.fronts = config.fronts || {};
|
|
111
|
+
config.fronts[m[1]] = { ...(config.fronts[m[1]] || {}), ...config[key] };
|
|
112
|
+
delete config[key];
|
|
113
|
+
}
|
|
114
|
+
};
|
|
115
|
+
|
|
116
|
+
/** Variables de l'engine : fronts connus, réserve, nom du projet */
|
|
117
|
+
const engineEnv = (config) => {
|
|
118
|
+
const { fronts, spare } = read(config);
|
|
119
|
+
return [
|
|
120
|
+
`POAD_FRONT_PORTS=${fronts.map((f) => `${f.id}=${f.port}`).join(',')}`,
|
|
121
|
+
`POAD_FRONT_SPARE_PORTS=${spare.join(',')}`,
|
|
122
|
+
`POAD_PROJECT_NAME=${projectName(config)}`,
|
|
123
|
+
];
|
|
124
|
+
};
|
|
125
|
+
|
|
126
|
+
/** Nom du projet (project_id de config.toml, celui que montre poad projects) */
|
|
127
|
+
const projectName = (config) => String((config && (config.project_id || config.project_uuid)) || 'poad').replace(/[\r\n]/g, ' ').slice(0, 80);
|
|
128
|
+
|
|
129
|
+
/** Ports publiés : tous sur 8100/tcp du conteneur, à la même interface que les autres ports */
|
|
130
|
+
const bindings = (config) => {
|
|
131
|
+
const { fronts, spare } = read(config);
|
|
132
|
+
const all = [...fronts.map((f) => f.port), ...spare];
|
|
133
|
+
if (!all.length) return { exposed: {}, bindings: {} };
|
|
134
|
+
const HostIp = require('./ports').hostIp(config);
|
|
135
|
+
return { exposed: { [CONTAINER_PORT]: {} }, bindings: { [CONTAINER_PORT]: all.map((p) => ({ HostIp, HostPort: String(p) })) } };
|
|
136
|
+
};
|
|
137
|
+
|
|
138
|
+
/** Fronts de l'engine (GET /meta/v1/fronts) ; null si meta ne répond pas ou ne les connaît pas */
|
|
139
|
+
// attempts : juste après poad start, meta peut ne pas répondre encore (passerelle pas encore ouverte, 502) :
|
|
140
|
+
// nouvel essai toutes les 1,5 s ; 404 (engine sans fronts) ou réponse illisible : abandon tout de suite
|
|
141
|
+
const fetchFronts = async (config, fetchFn = globalThis.fetch, { attempts = 1, delayMs = 1500 } = {}) => {
|
|
142
|
+
for (let i = 0; i < attempts; i++) {
|
|
143
|
+
if (i) await new Promise((r) => setTimeout(r, delayMs));
|
|
144
|
+
try {
|
|
145
|
+
const res = await fetchFn(`http://localhost:${config.web.port}/meta/v1/fronts`, {
|
|
146
|
+
headers: { apikey: config.auth.service, authorization: `Bearer ${config.auth.service}` },
|
|
147
|
+
signal: AbortSignal.timeout(8000),
|
|
148
|
+
});
|
|
149
|
+
if (res.status >= 502 && res.status <= 504) continue;
|
|
150
|
+
if (!res.ok) return null;
|
|
151
|
+
const list = await res.json();
|
|
152
|
+
return Array.isArray(list) ? list.filter((f) => f && typeof f.id === 'string' && ID_RE.test(f.id)) : null;
|
|
153
|
+
} catch {
|
|
154
|
+
/* pas encore joignable : essai suivant */
|
|
155
|
+
}
|
|
156
|
+
}
|
|
157
|
+
return null;
|
|
158
|
+
};
|
|
159
|
+
|
|
160
|
+
/** Port local d'une adresse http://localhost:<port> (ou 127.0.0.1) */
|
|
161
|
+
const portOf = (address) => {
|
|
162
|
+
const m = /^http:\/\/(?:localhost|127\.0\.0\.1):(\d{1,5})\/?$/.exec(String(address || ''));
|
|
163
|
+
return m && portOk(Number(m[1])) ? Number(m[1]) : null;
|
|
164
|
+
};
|
|
165
|
+
|
|
166
|
+
/**
|
|
167
|
+
* Après le démarrage : config.toml suit les fronts de l'engine. Un front qui a
|
|
168
|
+
* pris un port de réserve reçoit sa section, et ce port quitte la réserve ;
|
|
169
|
+
* la section d'un front supprimé part. Ne fait rien si meta ne répond pas.
|
|
170
|
+
* Renvoie { fronts: [{ id, name, address, port_pending }] } ou null.
|
|
171
|
+
*/
|
|
172
|
+
const sync = async (root, config, fetchFn, options) => {
|
|
173
|
+
const list = await fetchFronts(config, fetchFn, options);
|
|
174
|
+
if (!list) return null;
|
|
175
|
+
const state = read(config);
|
|
176
|
+
const known = new Map(state.fronts.map((f) => [f.id, f.port]));
|
|
177
|
+
const changes = {};
|
|
178
|
+
let spare = state.spare;
|
|
179
|
+
for (const f of list) {
|
|
180
|
+
const port = portOf(f.address);
|
|
181
|
+
if (port && known.get(f.id) !== port) {
|
|
182
|
+
changes[f.id] = port;
|
|
183
|
+
spare = spare.filter((p) => p !== port);
|
|
184
|
+
}
|
|
185
|
+
}
|
|
186
|
+
const ids = new Set(list.map((f) => f.id));
|
|
187
|
+
for (const f of state.fronts) if (!ids.has(f.id)) changes[f.id] = null;
|
|
188
|
+
if (Object.keys(changes).length || spare.length !== state.spare.length) {
|
|
189
|
+
write(root, { spare, fronts: changes });
|
|
190
|
+
const fronts = state.fronts.filter((f) => changes[f.id] !== null).map((f) => (changes[f.id] ? { id: f.id, port: changes[f.id] } : f));
|
|
191
|
+
for (const [id, port] of Object.entries(changes)) if (port && !known.has(id)) fronts.push({ id, port });
|
|
192
|
+
apply(config, { fronts, spare });
|
|
193
|
+
}
|
|
194
|
+
return { fronts: list.map((f) => ({ id: f.id, name: typeof f.name === 'string' ? f.name : f.id, address: f.address || null, port_pending: f.port_pending === true })) };
|
|
195
|
+
};
|
|
196
|
+
|
|
197
|
+
/** Lignes d'affichage (poad start, poad info) */
|
|
198
|
+
const describe = (config, synced, chalk) => {
|
|
199
|
+
const lines = [];
|
|
200
|
+
const { fronts, spare } = read(config);
|
|
201
|
+
if (synced) {
|
|
202
|
+
for (const f of synced.fronts) {
|
|
203
|
+
if (f.address) lines.push(`Front ${f.name} : ${chalk.bold.cyanBright(f.address)}`);
|
|
204
|
+
else lines.push(`Front ${f.name} : ${chalk.yellowBright('no port yet, restart the project (poad stop, then poad start)')}`);
|
|
205
|
+
}
|
|
206
|
+
} else {
|
|
207
|
+
for (const f of fronts) lines.push(`Front ${f.id} : ${chalk.bold.cyanBright(`http://localhost:${f.port}`)}`);
|
|
208
|
+
}
|
|
209
|
+
if (spare.length) lines.push(chalk.grey(`Spare front ports: ${spare.join(', ')} (for fronts created from the console)`));
|
|
210
|
+
return lines;
|
|
211
|
+
};
|
|
212
|
+
|
|
213
|
+
module.exports = { SPARE, CONTAINER_PORT, supportsFronts, read, write, ensureSpare, busyEntries, foldMoved, engineEnv, projectName, bindings, fetchFronts, portOf, sync, describe };
|
package/utils/logline.js
CHANGED
|
@@ -5,8 +5,8 @@ const LEVELS = ['debug', 'info', 'warn', 'error', 'fatal'];
|
|
|
5
5
|
|
|
6
6
|
// Options de filtre → attribut de la ligne (attrs). Mêmes noms et même sens
|
|
7
7
|
// que les paramètres de /logs/v1 (services/logs/src/api.ts de l'infra).
|
|
8
|
-
const ATTR_OPTIONS = { flow: 'flow', step: 'step', function: 'function', tool: 'tool', outcome: 'outcome', provider: 'provider', model: 'model', event: 'event', table: 'table', channel: 'channel' };
|
|
9
|
-
const EXAMPLES = { flow: 'demo-flux', step: 'appel', function: 'demo-stats', tool: 'select_rows', outcome: 'refused', provider: 'anthropic', model: 'claude-opus-5-5', event: 'ai_default_model_changed', table: 'notes', channel: 'notes' };
|
|
8
|
+
const ATTR_OPTIONS = { flow: 'flow', step: 'step', function: 'function', tool: 'tool', outcome: 'outcome', provider: 'provider', model: 'model', event: 'event', table: 'table', channel: 'channel', front: 'front', page: 'page' };
|
|
9
|
+
const EXAMPLES = { flow: 'demo-flux', step: 'appel', function: 'demo-stats', tool: 'select_rows', outcome: 'refused', provider: 'anthropic', model: 'claude-opus-5-5', event: 'ai_default_model_changed', table: 'notes', channel: 'notes', front: 'k3x9q2m7a1bc', page: 'accueil' };
|
|
10
10
|
// Identifiant d'exécution (UUID) entier, ou son début : 8 caractères au moins
|
|
11
11
|
const RUN_RE = /^[0-9a-f-]{8,36}$/;
|
|
12
12
|
|
package/utils/report.js
CHANGED
|
@@ -71,6 +71,18 @@ async function printProject(root, config, opts = {}) {
|
|
|
71
71
|
const line = await migrationsLine(root, config);
|
|
72
72
|
if (line) info.Migrations = line;
|
|
73
73
|
console.log(prettyoutput(info));
|
|
74
|
+
// Fronts dessinés dans poad (engine 0.46.0+) : config.toml suit l'engine (port pris dans la réserve), puis une ligne par front
|
|
75
|
+
const fronts = require('./fronts');
|
|
76
|
+
if (fronts.supportsFronts(config)) {
|
|
77
|
+
// Juste après poad start (opts.justStarted) : meta peut mettre quelques secondes à répondre
|
|
78
|
+
const synced = opts.offline ? null : await fronts.sync(root, config, undefined, opts.justStarted ? { attempts: 20 } : undefined);
|
|
79
|
+
const lines = fronts.describe(config, synced, chalk);
|
|
80
|
+
if (lines.length) {
|
|
81
|
+
console.log(chalk.bold('Fronts'));
|
|
82
|
+
lines.forEach((l) => console.log(` ${l}`));
|
|
83
|
+
console.log(' ');
|
|
84
|
+
}
|
|
85
|
+
}
|
|
74
86
|
}
|
|
75
87
|
|
|
76
88
|
async function printServices(root, config, opts = {}) {
|
|
@@ -0,0 +1,124 @@
|
|
|
1
|
+
// Script psql qui charge le contenu COPY d'une table dans sa table cible.
|
|
2
|
+
// Même texte que deploy/cloud/control/seed-apply.mjs de poad-site (chargement
|
|
3
|
+
// des projets hébergés) : à garder identiques.
|
|
4
|
+
//
|
|
5
|
+
// En une transaction : table temporaire du même type, COPY, puis
|
|
6
|
+
// - avec clé primaire : les lignes absentes du contenu sont supprimées, les
|
|
7
|
+
// autres insérées ou mises à jour (ON CONFLICT) : les lignes des autres
|
|
8
|
+
// tables qui y renvoient restent valides ;
|
|
9
|
+
// - sans clé primaire : la table est vidée puis remplie ;
|
|
10
|
+
// - les séquences (serial, identity) repartent après le plus grand identifiant.
|
|
11
|
+
// Une suppression refusée par une clé étrangère annule tout, avec le message de
|
|
12
|
+
// PostgreSQL : rien n'est chargé à moitié.
|
|
13
|
+
'use strict';
|
|
14
|
+
|
|
15
|
+
const quoteIdent = (s) => `"${String(s).replace(/"/g, '""')}"`;
|
|
16
|
+
const quoteLiteral = (s) => `'${String(s).replace(/'/g, "''")}'`;
|
|
17
|
+
|
|
18
|
+
/** « schéma.table » du registre vers un nom SQL entre guillemets */
|
|
19
|
+
function sqlName(target) {
|
|
20
|
+
const i = target.indexOf('.');
|
|
21
|
+
return `${quoteIdent(target.slice(0, i))}.${quoteIdent(target.slice(i + 1))}`;
|
|
22
|
+
}
|
|
23
|
+
|
|
24
|
+
/** Début du script (avant les lignes de données) */
|
|
25
|
+
function head(target, columns) {
|
|
26
|
+
const t = sqlName(target);
|
|
27
|
+
const cols = columns && columns.length ? columns.map(quoteIdent).join(', ') : '*';
|
|
28
|
+
const copyCols = columns && columns.length ? ` (${columns.map(quoteIdent).join(', ')})` : '';
|
|
29
|
+
return [
|
|
30
|
+
'\\set ON_ERROR_STOP on',
|
|
31
|
+
'set client_min_messages = notice;',
|
|
32
|
+
'begin;',
|
|
33
|
+
"set local statement_timeout = 0;",
|
|
34
|
+
"set local lock_timeout = '60s';",
|
|
35
|
+
`create temp table _poad_seed on commit drop as select ${cols} from ${t} with no data;`,
|
|
36
|
+
`copy _poad_seed${copyCols} from stdin;`,
|
|
37
|
+
'',
|
|
38
|
+
].join('\n');
|
|
39
|
+
}
|
|
40
|
+
|
|
41
|
+
/** Fin du script (après les lignes de données) */
|
|
42
|
+
function tail(target, columns) {
|
|
43
|
+
const arr = columns && columns.length ? `array[${columns.map(quoteLiteral).join(', ')}]::text[]` : 'null::text[]';
|
|
44
|
+
return `\\.
|
|
45
|
+
do $poad$
|
|
46
|
+
declare
|
|
47
|
+
t regclass := ${quoteLiteral(sqlName(target))}::regclass;
|
|
48
|
+
cols text[] := ${arr};
|
|
49
|
+
pk text[];
|
|
50
|
+
collist text;
|
|
51
|
+
setlist text;
|
|
52
|
+
n bigint := 0;
|
|
53
|
+
d bigint := 0;
|
|
54
|
+
s record;
|
|
55
|
+
begin
|
|
56
|
+
if cols is null then
|
|
57
|
+
select array_agg(attname::text order by attnum) into cols
|
|
58
|
+
from pg_attribute where attrelid = '_poad_seed'::regclass and attnum > 0 and not attisdropped;
|
|
59
|
+
end if;
|
|
60
|
+
select array_agg(a.attname::text order by array_position(i.indkey::int2[], a.attnum)) into pk
|
|
61
|
+
from pg_index i join pg_attribute a on a.attrelid = i.indrelid and a.attnum = any(i.indkey)
|
|
62
|
+
where i.indrelid = t and i.indisprimary;
|
|
63
|
+
collist := (select string_agg(quote_ident(c), ', ') from unnest(cols) c);
|
|
64
|
+
if pk is null or not (pk <@ cols) then
|
|
65
|
+
execute format('delete from %s', t);
|
|
66
|
+
get diagnostics d = row_count;
|
|
67
|
+
execute format('insert into %s (%s) overriding system value select %s from _poad_seed', t, collist, collist);
|
|
68
|
+
else
|
|
69
|
+
execute format('delete from %s x where not exists (select 1 from _poad_seed s where %s)', t,
|
|
70
|
+
(select string_agg(format('s.%1$I is not distinct from x.%1$I', c), ' and ') from unnest(pk) c));
|
|
71
|
+
get diagnostics d = row_count;
|
|
72
|
+
setlist := (select string_agg(format('%1$I = excluded.%1$I', c), ', ') from unnest(cols) c where c <> all (pk));
|
|
73
|
+
execute format('insert into %s (%s) overriding system value select %s from _poad_seed on conflict (%s) do %s', t, collist, collist,
|
|
74
|
+
(select string_agg(quote_ident(c), ', ') from unnest(pk) c),
|
|
75
|
+
case when setlist is null then 'nothing' else 'update set ' || setlist end);
|
|
76
|
+
end if;
|
|
77
|
+
get diagnostics n = row_count;
|
|
78
|
+
for s in select a.attname::text as col, pg_get_serial_sequence(t::text, a.attname) as seq
|
|
79
|
+
from pg_attribute a where a.attrelid = t and a.attnum > 0 and not a.attisdropped loop
|
|
80
|
+
if s.seq is not null then
|
|
81
|
+
execute format('select setval(%L, coalesce((select max(%I) from %s), 0) + 1, false)', s.seq, s.col, t);
|
|
82
|
+
end if;
|
|
83
|
+
end loop;
|
|
84
|
+
raise notice 'poad-seed % written=% deleted=%', t, n, d;
|
|
85
|
+
end
|
|
86
|
+
$poad$;
|
|
87
|
+
commit;
|
|
88
|
+
`;
|
|
89
|
+
}
|
|
90
|
+
|
|
91
|
+
/** Ligne « poad-seed … written=N deleted=M » de la sortie de psql */
|
|
92
|
+
function parseNotice(text) {
|
|
93
|
+
const m = /poad-seed (\S+) written=(\d+) deleted=(\d+)/.exec(String(text || ''));
|
|
94
|
+
return m ? { table: m[1], written: Number(m[2]), deleted: Number(m[3]) } : null;
|
|
95
|
+
}
|
|
96
|
+
|
|
97
|
+
/** Requête des dépendances (clés étrangères) entre tables, pour l'ordre de chargement */
|
|
98
|
+
const FK_SQL = "select conrelid::regclass::text || '|' || confrelid::regclass::text from pg_constraint where contype = 'f' and conrelid <> confrelid";
|
|
99
|
+
|
|
100
|
+
/** Ordre de chargement : une table après celles qu'elle référence (registre : schéma.table) */
|
|
101
|
+
function loadOrder(targets, edges) {
|
|
102
|
+
const norm = (s) => s.replace(/"/g, '');
|
|
103
|
+
const key = (t) => (t.includes('.') ? t : `public.${t}`);
|
|
104
|
+
const set = new Set(targets);
|
|
105
|
+
const deps = new Map(targets.map((t) => [t, new Set()]));
|
|
106
|
+
for (const line of edges) {
|
|
107
|
+
const [from, to] = String(line).split('|').map((x) => key(norm(x.trim())));
|
|
108
|
+
if (set.has(from) && set.has(to)) deps.get(from).add(to);
|
|
109
|
+
}
|
|
110
|
+
const out = [];
|
|
111
|
+
const state = new Map();
|
|
112
|
+
const visit = (t) => {
|
|
113
|
+
if (state.get(t) === 2) return;
|
|
114
|
+
if (state.get(t) === 1) return; // cycle : l'ordre donné l'emporte
|
|
115
|
+
state.set(t, 1);
|
|
116
|
+
for (const d of deps.get(t)) visit(d);
|
|
117
|
+
state.set(t, 2);
|
|
118
|
+
out.push(t);
|
|
119
|
+
};
|
|
120
|
+
for (const t of targets) visit(t);
|
|
121
|
+
return out;
|
|
122
|
+
}
|
|
123
|
+
|
|
124
|
+
module.exports = { head, tail, parseNotice, sqlName, quoteIdent, loadOrder, FK_SQL };
|