@odatano/core 2.0.0-rc.5 → 2.0.0-rc.51
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/@cds-models/CardanoAgentService/index.d.ts +99 -51
- package/@cds-models/CardanoAgentService/index.js +15 -0
- package/@cds-models/CardanoBackendService/index.d.ts +358 -0
- package/@cds-models/CardanoBackendService/index.js +41 -0
- package/@cds-models/CardanoIndexerService/index.d.ts +594 -11
- package/@cds-models/CardanoIndexerService/index.js +74 -0
- package/@cds-models/CardanoODataService/index.d.ts +417 -57
- package/@cds-models/CardanoODataService/index.js +42 -0
- package/@cds-models/CardanoSignService/index.d.ts +45 -19
- package/@cds-models/CardanoSignService/index.js +4 -0
- package/@cds-models/CardanoTransactionService/index.d.ts +70 -44
- package/@cds-models/CardanoTransactionService/index.js +5 -0
- package/@cds-models/CardanoWorkerService/index.d.ts +35 -22
- package/@cds-models/CardanoWorkerService/index.js +2 -0
- package/@cds-models/index.d.ts +114 -4
- package/@cds-models/index.js +20 -4
- package/@cds-models/odatano/cardano/index.d.ts +451 -32
- package/@cds-models/odatano/cardano/index.js +48 -0
- package/README.md +103 -167
- package/db/schema.cds +2455 -1705
- package/db/types.cds +456 -295
- package/package.json +41 -53
- package/scripts/deploy-schema.mjs +113 -0
- package/scripts/migrate-schema.mjs +528 -0
- package/scripts/migrate-slot-leader.mjs +96 -0
- package/src/index.d.ts +20 -21
- package/src/index.js +45 -31
- package/src/plugin.js +17 -35
- package/srv/blockchain/asset-decimals.d.ts +7 -0
- package/srv/blockchain/asset-decimals.js +91 -0
- package/srv/blockchain/backends/blockfrost-backend.d.ts +25 -137
- package/srv/blockchain/backends/blockfrost-backend.js +125 -215
- package/srv/blockchain/backends/call-signal.d.ts +7 -0
- package/srv/blockchain/backends/call-signal.js +22 -0
- package/srv/blockchain/backends/cardano-backend.d.ts +100 -189
- package/srv/blockchain/backends/cardano-backend.js +29 -5
- package/srv/blockchain/backends/koios-backend.d.ts +108 -170
- package/srv/blockchain/backends/koios-backend.js +488 -482
- package/srv/blockchain/backends/odatano-backend.d.ts +55 -0
- package/srv/blockchain/backends/odatano-backend.js +211 -0
- package/srv/blockchain/backends/ogmios-backend.d.ts +122 -190
- package/srv/blockchain/backends/ogmios-backend.js +683 -327
- package/srv/blockchain/backends/ogmios-frame-guard.d.ts +14 -0
- package/srv/blockchain/backends/ogmios-frame-guard.js +89 -0
- package/srv/blockchain/cardano-client.d.ts +71 -241
- package/srv/blockchain/cardano-client.js +354 -322
- package/srv/blockchain/cardano-indexer.d.ts +295 -283
- package/srv/blockchain/cardano-indexer.js +1690 -502
- package/srv/blockchain/cardano-tx-builder.d.ts +25 -89
- package/srv/blockchain/cardano-tx-builder.js +164 -140
- package/srv/blockchain/circuit-breaker.d.ts +2 -13
- package/srv/blockchain/circuit-breaker.js +11 -15
- package/srv/blockchain/crawler/account-snapshots.d.ts +29 -0
- package/srv/blockchain/crawler/account-snapshots.js +173 -0
- package/srv/blockchain/crawler/asset-decimals-backfill.d.ts +17 -0
- package/srv/blockchain/crawler/asset-decimals-backfill.js +56 -0
- package/srv/blockchain/crawler/asset-registry-backfill.d.ts +46 -0
- package/srv/blockchain/crawler/asset-registry-backfill.js +157 -0
- package/srv/blockchain/crawler/asset-slice-backfill.d.ts +35 -0
- package/srv/blockchain/crawler/asset-slice-backfill.js +149 -0
- package/srv/blockchain/crawler/certificate-backfill.d.ts +56 -0
- package/srv/blockchain/crawler/certificate-backfill.js +174 -0
- package/srv/blockchain/crawler/crawler.d.ts +125 -81
- package/srv/blockchain/crawler/crawler.js +738 -167
- package/srv/blockchain/crawler/credential-backfill.d.ts +30 -0
- package/srv/blockchain/crawler/credential-backfill.js +101 -0
- package/srv/blockchain/crawler/hooks.d.ts +2 -17
- package/srv/blockchain/crawler/index.d.ts +1 -8
- package/srv/blockchain/crawler/index.js +31 -17
- package/srv/blockchain/crawler/input-asset-copies.d.ts +34 -0
- package/srv/blockchain/crawler/input-asset-copies.js +161 -0
- package/srv/blockchain/crawler/key-pages.d.ts +12 -0
- package/srv/blockchain/crawler/key-pages.js +48 -0
- package/srv/blockchain/crawler/metadata-position-backfill.d.ts +22 -0
- package/srv/blockchain/crawler/metadata-position-backfill.js +59 -0
- package/srv/blockchain/crawler/output-datum-backfill.d.ts +41 -0
- package/srv/blockchain/crawler/output-datum-backfill.js +100 -0
- package/srv/blockchain/crawler/sync-state.d.ts +31 -47
- package/srv/blockchain/crawler/sync-state.js +135 -128
- package/srv/blockchain/crawler/transaction-backfill.d.ts +46 -0
- package/srv/blockchain/crawler/transaction-backfill.js +271 -0
- package/srv/blockchain/crawler/utxo-set-import.d.ts +66 -0
- package/srv/blockchain/crawler/utxo-set-import.js +399 -0
- package/srv/blockchain/crawler/window-plan.d.ts +31 -0
- package/srv/blockchain/crawler/window-plan.js +59 -0
- package/srv/blockchain/ledger-state.d.ts +62 -0
- package/srv/blockchain/ledger-state.js +521 -0
- package/srv/blockchain/pending-spends.d.ts +16 -0
- package/srv/blockchain/pending-spends.js +81 -0
- package/srv/blockchain/pool-metadata.d.ts +15 -0
- package/srv/blockchain/pool-metadata.js +132 -0
- package/srv/blockchain/request-coalescer.d.ts +2 -16
- package/srv/blockchain/request-coalescer.js +2 -16
- package/srv/blockchain/signing/cose-verifier.d.ts +3 -17
- package/srv/blockchain/signing/cose-verifier.js +146 -70
- package/srv/blockchain/signing/external-signer.d.ts +15 -115
- package/srv/blockchain/signing/external-signer.js +22 -131
- package/srv/blockchain/signing/failed-recheck.d.ts +17 -0
- package/srv/blockchain/signing/failed-recheck.js +135 -0
- package/srv/blockchain/signing/hsm-signer.d.ts +10 -54
- package/srv/blockchain/signing/hsm-signer.js +28 -79
- package/srv/blockchain/signing/landing-proof.d.ts +60 -0
- package/srv/blockchain/signing/landing-proof.js +224 -0
- package/srv/blockchain/signing/signature-verifier.d.ts +9 -47
- package/srv/blockchain/signing/signature-verifier.js +71 -87
- package/srv/blockchain/signing/submission-finalizer.d.ts +37 -45
- package/srv/blockchain/signing/submission-finalizer.js +280 -86
- package/srv/blockchain/stored-chain.d.ts +19 -0
- package/srv/blockchain/stored-chain.js +258 -0
- package/srv/blockchain/transaction-building/buildooor-tx.d.ts +31 -229
- package/srv/blockchain/transaction-building/buildooor-tx.js +663 -421
- package/srv/blockchain/transaction-building/cardano-tx.d.ts +9 -37
- package/srv/blockchain/transaction-presence.d.ts +12 -0
- package/srv/blockchain/transaction-presence.js +29 -0
- package/srv/blockchain/transaction-rows.d.ts +12 -0
- package/srv/blockchain/transaction-rows.js +44 -0
- package/srv/blockchain/wallet-worker/build-request.d.ts +8 -23
- package/srv/blockchain/wallet-worker/build-request.js +40 -353
- package/srv/blockchain/wallet-worker/confirmation-tracker.d.ts +27 -47
- package/srv/blockchain/wallet-worker/confirmation-tracker.js +158 -61
- package/srv/blockchain/wallet-worker/index.d.ts +1 -1
- package/srv/blockchain/wallet-worker/index.js +3 -11
- package/srv/blockchain/wallet-worker/invalidation.d.ts +35 -0
- package/srv/blockchain/wallet-worker/invalidation.js +128 -0
- package/srv/blockchain/wallet-worker/job-store.d.ts +58 -150
- package/srv/blockchain/wallet-worker/job-store.js +200 -273
- package/srv/blockchain/wallet-worker/lease-heartbeat.d.ts +2 -26
- package/srv/blockchain/wallet-worker/lease-heartbeat.js +6 -28
- package/srv/blockchain/wallet-worker/signers.d.ts +5 -24
- package/srv/blockchain/wallet-worker/signers.js +4 -12
- package/srv/blockchain/wallet-worker/wallet-worker.d.ts +29 -82
- package/srv/blockchain/wallet-worker/wallet-worker.js +334 -198
- package/srv/cardano-agent-service.cds +122 -84
- package/srv/cardano-agent-service.js +12 -9
- package/srv/cardano-backend-service.cds +81 -0
- package/srv/cardano-backend-service.d.ts +2 -0
- package/srv/cardano-backend-service.js +259 -0
- package/srv/cardano-indexer-service.cds +393 -18
- package/srv/cardano-indexer-service.d.ts +5 -1
- package/srv/cardano-indexer-service.js +477 -16
- package/srv/cardano-service.cds +426 -269
- package/srv/cardano-service.js +640 -217
- package/srv/cardano-sign-service.cds +211 -180
- package/srv/cardano-sign-service.js +210 -287
- package/srv/cardano-tx-service.cds +462 -370
- package/srv/cardano-tx-service.js +283 -800
- package/srv/cardano-ui.cds +16 -16
- package/srv/cardano-worker-service.cds +141 -125
- package/srv/cardano-worker-service.js +104 -61
- package/srv/cbor/cip68.d.ts +13 -0
- package/srv/cbor/cip68.js +56 -0
- package/srv/cbor/index.d.ts +3 -1
- package/srv/cbor/index.js +9 -1
- package/srv/cbor/parse.d.ts +30 -18
- package/srv/cbor/parse.js +44 -9
- package/srv/cbor/plutus-data-json.d.ts +20 -0
- package/srv/cbor/plutus-data-json.js +32 -0
- package/srv/config.d.ts +117 -0
- package/srv/config.js +419 -0
- package/srv/server.d.ts +15 -110
- package/srv/server.js +83 -405
- package/srv/utils/agent-access.d.ts +11 -0
- package/srv/utils/agent-access.js +86 -0
- package/srv/utils/agent-grants-config.d.ts +0 -46
- package/srv/utils/agent-grants-config.js +17 -85
- package/srv/utils/agent-grants.d.ts +106 -122
- package/srv/utils/agent-grants.js +538 -237
- package/srv/utils/agent-token-auth.d.ts +4 -99
- package/srv/utils/agent-token-auth.js +62 -186
- package/srv/utils/backend-request-handler.d.ts +3 -17
- package/srv/utils/backend-request-handler.js +3 -18
- package/srv/utils/build-request.d.ts +52 -0
- package/srv/utils/build-request.js +487 -0
- package/srv/utils/collections.d.ts +4 -10
- package/srv/utils/collections.js +14 -10
- package/srv/utils/const.d.ts +32 -75
- package/srv/utils/const.js +40 -80
- package/srv/utils/crypto.d.ts +3 -12
- package/srv/utils/crypto.js +11 -25
- package/srv/utils/db-indexes.d.ts +31 -0
- package/srv/utils/db-indexes.js +185 -0
- package/srv/utils/db-kind.d.ts +23 -0
- package/srv/utils/db-kind.js +42 -0
- package/srv/utils/db-sanitize.d.ts +20 -0
- package/srv/utils/db-sanitize.js +80 -0
- package/srv/utils/deep-json.d.ts +6 -0
- package/srv/utils/deep-json.js +240 -0
- package/srv/utils/detached-run.d.ts +41 -0
- package/srv/utils/detached-run.js +101 -0
- package/srv/utils/epoch-slots.d.ts +14 -0
- package/srv/utils/epoch-slots.js +45 -0
- package/srv/utils/error-codes.d.ts +26 -75
- package/srv/utils/error-codes.js +27 -72
- package/srv/utils/errors.d.ts +55 -187
- package/srv/utils/errors.js +161 -235
- package/srv/utils/lease.d.ts +20 -0
- package/srv/utils/lease.js +62 -0
- package/srv/utils/liveness.d.ts +12 -0
- package/srv/utils/liveness.js +35 -0
- package/srv/utils/mappers.d.ts +111 -223
- package/srv/utils/mappers.js +432 -371
- package/srv/utils/navigation.d.ts +17 -0
- package/srv/utils/navigation.js +52 -0
- package/srv/utils/network-context.d.ts +0 -1
- package/srv/utils/network-context.js +9 -15
- package/srv/utils/paging.d.ts +31 -0
- package/srv/utils/paging.js +43 -0
- package/srv/utils/pg-inline-json.d.ts +8 -0
- package/srv/utils/pg-inline-json.js +58 -0
- package/srv/utils/pg-order-nulls.d.ts +14 -0
- package/srv/utils/pg-order-nulls.js +54 -0
- package/srv/utils/plutus-placeholders.d.ts +16 -22
- package/srv/utils/plutus-placeholders.js +62 -33
- package/srv/utils/rate-limiter.d.ts +2 -21
- package/srv/utils/rate-limiter.js +5 -17
- package/srv/utils/readiness.d.ts +12 -0
- package/srv/utils/readiness.js +29 -0
- package/srv/utils/reference-script.d.ts +19 -0
- package/srv/utils/reference-script.js +84 -0
- package/srv/utils/resolution.d.ts +13 -0
- package/srv/utils/resolution.js +47 -0
- package/srv/utils/result-numbers.d.ts +15 -0
- package/srv/utils/result-numbers.js +61 -0
- package/srv/utils/row-values.d.ts +7 -0
- package/srv/utils/row-values.js +27 -0
- package/srv/utils/service-events.d.ts +0 -24
- package/srv/utils/service-events.js +3 -25
- package/srv/utils/signing-helper.d.ts +3 -20
- package/srv/utils/signing-helper.js +35 -64
- package/srv/utils/tx-build-helper.d.ts +25 -105
- package/srv/utils/tx-build-helper.js +108 -156
- package/srv/utils/tx-request-parsers.d.ts +82 -33
- package/srv/utils/tx-request-parsers.js +401 -49
- package/srv/utils/tx-utils.d.ts +3 -27
- package/srv/utils/tx-utils.js +32 -50
- package/srv/utils/types.d.ts +294 -232
- package/srv/utils/types.js +2 -22
- package/srv/utils/validators.d.ts +22 -92
- package/srv/utils/validators.js +60 -170
|
@@ -0,0 +1,528 @@
|
|
|
1
|
+
#!/usr/bin/env node
|
|
2
|
+
// Applies the schema changes the additive schema deploy refuses: a changed key, a changed column
|
|
3
|
+
// type, a dropped column, a renamed table. Every step runs only where it is still due.
|
|
4
|
+
// Run with ODATANO stopped, before the schema deploy. --dry-run only reports.
|
|
5
|
+
import cds from '@sap/cds';
|
|
6
|
+
|
|
7
|
+
const T = (name) => `odatano_cardano_${name}`;
|
|
8
|
+
const E = (name) => `odatano.cardano.${name}`;
|
|
9
|
+
const TX_SEQ_SLOT_FACTOR = 65536;
|
|
10
|
+
/** Column type the schema deploy creates for a timestamp, per database. */
|
|
11
|
+
const TIMESTAMP = { postgres: 'TIMESTAMP', sqlite: 'TIMESTAMP_TEXT' };
|
|
12
|
+
|
|
13
|
+
/** Column names of a table with their declared types, both lower-cased. Empty when the table is missing. */
|
|
14
|
+
export async function columnsOf(db, table) {
|
|
15
|
+
const rows = db.kind === 'postgres'
|
|
16
|
+
? await db.run(`SELECT column_name AS name, data_type AS type FROM information_schema.columns WHERE table_schema = current_schema() AND table_name = '${table.toLowerCase()}'`)
|
|
17
|
+
: await db.run(`SELECT name, type FROM pragma_table_info('${table}')`);
|
|
18
|
+
return new Map(rows.map(r => [String(r.name).toLowerCase(), String(r.type).toLowerCase()]));
|
|
19
|
+
}
|
|
20
|
+
|
|
21
|
+
/** 'table', 'view' or null for a name in the current schema. */
|
|
22
|
+
export async function relationKind(db, name) {
|
|
23
|
+
const rows = db.kind === 'postgres'
|
|
24
|
+
? await db.run(`SELECT CASE c.relkind WHEN 'v' THEN 'view' ELSE 'table' END AS kind FROM pg_class c JOIN pg_namespace n ON n.oid = c.relnamespace
|
|
25
|
+
WHERE n.nspname = current_schema() AND c.relkind IN ('r', 'p', 'v') AND c.relname = '${name.toLowerCase()}'`)
|
|
26
|
+
: await db.run(`SELECT type AS kind FROM sqlite_schema WHERE type IN ('table', 'view') AND lower(name) = '${name.toLowerCase()}'`);
|
|
27
|
+
return rows[0]?.kind ?? null;
|
|
28
|
+
}
|
|
29
|
+
|
|
30
|
+
/** True for a declared type that holds a time as plain text. */
|
|
31
|
+
export function isTextType(type) {
|
|
32
|
+
return /char|text|string/.test(type) && !type.includes('timestamp');
|
|
33
|
+
}
|
|
34
|
+
|
|
35
|
+
/** Counts the blocks whose time is not a UTC timestamp in ISO 8601 form. */
|
|
36
|
+
export function unparsableSql(kind) {
|
|
37
|
+
const pattern = kind === 'postgres'
|
|
38
|
+
? `time !~ '^[0-9]{4}-[0-9]{2}-[0-9]{2}T[0-9]{2}:[0-9]{2}:[0-9]{2}([.][0-9]+)?Z$'`
|
|
39
|
+
: `time NOT GLOB '[0-9][0-9][0-9][0-9]-[0-9][0-9]-[0-9][0-9]T[0-9][0-9]:[0-9][0-9]:[0-9][0-9]*Z'`;
|
|
40
|
+
return `SELECT count(*) AS n FROM ${T('Blocks')} WHERE time IS NOT NULL AND ${pattern}`;
|
|
41
|
+
}
|
|
42
|
+
|
|
43
|
+
/** CREATE TABLE statement of a SQLite table under a new name, with `time` declared as a timestamp. */
|
|
44
|
+
export function rebuiltTableSql(createSql, table, newName) {
|
|
45
|
+
const retyped = createSql.replace(/(\btime\s+)N?VARCHAR\s*\(\s*\d+\s*\)/i, `$1${TIMESTAMP.sqlite}`);
|
|
46
|
+
if (retyped === createSql) throw new Error(`${table}: no text column time in its table definition`);
|
|
47
|
+
return retyped.replace(new RegExp(`^(\\s*CREATE TABLE\\s+)"?${table}"?`, 'i'), `$1${newName}`);
|
|
48
|
+
}
|
|
49
|
+
|
|
50
|
+
// What a SAP HANA user does instead: an HDI container takes no DDL from the runtime user.
|
|
51
|
+
export const HANA_UPGRADE = 'SAP HANA: this script cannot migrate an HDI container. Deploy this version into a new HDI container '
|
|
52
|
+
+ 'and point the application at it. The chain data is read again on demand; the records of your own transactions stay in the '
|
|
53
|
+
+ 'old container. docs/guides/UPGRADE_2.0.md has the steps.';
|
|
54
|
+
|
|
55
|
+
// Tables that moved from the transaction hash to Transactions.txSeq as their key.
|
|
56
|
+
// `to` is the entity that holds the rows in the model of this version.
|
|
57
|
+
const TX_SEQ_TABLES = [
|
|
58
|
+
{ from: 'TransactionInputs', to: 'TransactionInputs', hashKey: 'tx_hash', seqKey: 'txSeq', order: 'inputIndex' },
|
|
59
|
+
{ from: 'TransactionOutputs', to: 'TransactionOutputs', hashKey: 'tx_hash', seqKey: 'txSeq', order: 'outputIndex' },
|
|
60
|
+
{ from: 'TransactionInputAssets', to: 'TransactionInputAssetCopies', hashKey: 'input_tx_hash', seqKey: 'input_txSeq', order: 'input_inputIndex, unit' },
|
|
61
|
+
{ from: 'TransactionOutputAssets', to: 'TransactionOutputAssets', hashKey: 'output_tx_hash', seqKey: 'output_txSeq', order: 'output_outputIndex, unit' },
|
|
62
|
+
];
|
|
63
|
+
|
|
64
|
+
/** Copy statement: the given columns of the old table, the new key from Transactions. */
|
|
65
|
+
export function copySql(spec, columns, target) {
|
|
66
|
+
const others = columns.filter(c => c !== spec.hashKey.toLowerCase());
|
|
67
|
+
const into = [spec.seqKey, ...others].join(', ');
|
|
68
|
+
const source = ['t.txSeq', ...others.map(c => `x.${c}`)].join(', ');
|
|
69
|
+
const order = ['t.txSeq', ...spec.order.split(',').map(c => `x.${c.trim()}`)].join(', ');
|
|
70
|
+
return `INSERT INTO ${target} (${into}) SELECT ${source} FROM ${T(spec.from)} x `
|
|
71
|
+
+ `JOIN ${T('Transactions')} t ON t.hash = x.${spec.hashKey} ORDER BY ${order}`;
|
|
72
|
+
}
|
|
73
|
+
|
|
74
|
+
async function count(tx, table) {
|
|
75
|
+
const [row] = await tx.run(`SELECT count(*) AS n FROM ${table}`);
|
|
76
|
+
return Number(row.n);
|
|
77
|
+
}
|
|
78
|
+
|
|
79
|
+
/** Name of the unique constraint that holds one idempotency key per job. */
|
|
80
|
+
const WALLET_JOBS_DEDUP = 'odatano_cardano_CardanoWalletJobs_dedup';
|
|
81
|
+
|
|
82
|
+
/** An allow list as stored: a JSON array of names, anything else is empty. */
|
|
83
|
+
function grantList(raw) {
|
|
84
|
+
try {
|
|
85
|
+
const list = JSON.parse(String(raw ?? '[]'));
|
|
86
|
+
return Array.isArray(list) ? list.filter(n => typeof n === 'string') : [];
|
|
87
|
+
} catch {
|
|
88
|
+
return [];
|
|
89
|
+
}
|
|
90
|
+
}
|
|
91
|
+
|
|
92
|
+
/** The grantable operations of a model, `Service.operation`, by their name without the service. */
|
|
93
|
+
export function grantableByName(model) {
|
|
94
|
+
const definitions = Object.entries(model?.definitions ?? {});
|
|
95
|
+
const services = definitions.filter(([, def]) => def.kind === 'service').map(([name]) => name);
|
|
96
|
+
const byName = new Map();
|
|
97
|
+
const add = (service, operation, def) => {
|
|
98
|
+
if (def?.['@odatano.agent'] !== 'grant') return;
|
|
99
|
+
byName.set(operation, [...(byName.get(operation) ?? []), `${service}.${operation}`]);
|
|
100
|
+
};
|
|
101
|
+
for (const [name, def] of definitions) {
|
|
102
|
+
const service = services.find(s => name.startsWith(`${s}.`));
|
|
103
|
+
if (!service) continue;
|
|
104
|
+
if (def.kind === 'action' || def.kind === 'function') add(service, name.slice(service.length + 1), def);
|
|
105
|
+
for (const [bound, action] of Object.entries(def.actions ?? {})) add(service, bound, action);
|
|
106
|
+
}
|
|
107
|
+
return byName;
|
|
108
|
+
}
|
|
109
|
+
|
|
110
|
+
// A stored allow list with every name qualified. A name without a service allowed the operation of
|
|
111
|
+
// that name in every service, so it becomes all of them; a name nothing declares any more is dropped.
|
|
112
|
+
export function qualifiedGrantList(list, byName) {
|
|
113
|
+
const grantable = new Set([...byName.values()].flat());
|
|
114
|
+
const out = list.flatMap(name => (name.includes('.') ? (grantable.has(name) ? [name] : []) : (byName.get(name) ?? [])));
|
|
115
|
+
return [...new Set(out)];
|
|
116
|
+
}
|
|
117
|
+
|
|
118
|
+
/** Lower-cased columns of a unique constraint, in order; null when the table or the constraint is missing. */
|
|
119
|
+
// Where one idempotency key is held by several jobs, every job but one releases it: a job still in
|
|
120
|
+
// flight keeps it, else the newest. createdAt, then ID, break a tie the same way on every database.
|
|
121
|
+
export function releaseSharedClaimsSql(table) {
|
|
122
|
+
const flight = (alias) => `CASE WHEN ${alias}.status IN ('submitting', 'submitted') THEN 1 ELSE 0 END`;
|
|
123
|
+
return `UPDATE ${table} SET dedupKey = ID WHERE dedupKey <> ID AND EXISTS (`
|
|
124
|
+
+ `SELECT 1 FROM ${table} o WHERE o.dedupKey = ${table}.dedupKey AND o.ID <> ${table}.ID AND (`
|
|
125
|
+
+ `${flight('o')} > ${flight(table)} OR (${flight('o')} = ${flight(table)} AND (`
|
|
126
|
+
+ `o.createdAt > ${table}.createdAt OR (o.createdAt = ${table}.createdAt AND o.ID > ${table}.ID)))))`;
|
|
127
|
+
}
|
|
128
|
+
|
|
129
|
+
export async function uniqueColumns(db, table, constraint) {
|
|
130
|
+
if (db.kind === 'postgres') {
|
|
131
|
+
const rows = await db.run(`SELECT a.attname AS name FROM pg_constraint c JOIN pg_namespace n ON n.oid = c.connamespace
|
|
132
|
+
JOIN unnest(c.conkey) WITH ORDINALITY k(attnum, pos) ON true
|
|
133
|
+
JOIN pg_attribute a ON a.attrelid = c.conrelid AND a.attnum = k.attnum
|
|
134
|
+
WHERE n.nspname = current_schema() AND c.conname = '${constraint.toLowerCase()}' ORDER BY k.pos`);
|
|
135
|
+
return rows.length ? rows.map(r => String(r.name).toLowerCase()) : null;
|
|
136
|
+
}
|
|
137
|
+
const [stored] = await db.run(`SELECT sql FROM sqlite_schema WHERE type = 'table' AND name = '${table}'`);
|
|
138
|
+
const match = String(stored?.sql ?? '').match(new RegExp(`CONSTRAINT\\s+"?${constraint}"?\\s+UNIQUE\\s*\\(([^)]*)\\)`, 'i'));
|
|
139
|
+
return match ? match[1].split(',').map(c => c.trim().replace(/"/g, '').toLowerCase()) : null;
|
|
140
|
+
}
|
|
141
|
+
|
|
142
|
+
// The steps, oldest first. `due` says whether the database still needs the step (`pending` names the
|
|
143
|
+
// earlier steps that are due), `apply` changes the database, `model` makes the stored model say the same.
|
|
144
|
+
export const STEPS = [
|
|
145
|
+
{
|
|
146
|
+
name: 'transaction inputs and outputs keyed by txSeq',
|
|
147
|
+
async due(db) {
|
|
148
|
+
if (!(await columnsOf(db, T('TransactionInputs'))).has('tx_hash')) return false;
|
|
149
|
+
const open = Number((await db.run(`SELECT count(*) AS n FROM ${T('Transactions')} WHERE slot IS NULL OR txIndex IS NULL`))[0].n);
|
|
150
|
+
if (open > 0) throw new Error(`${open} transactions have no slot or txIndex; their txSeq cannot be derived`);
|
|
151
|
+
return true;
|
|
152
|
+
},
|
|
153
|
+
async apply(tx, { ddl, log }) {
|
|
154
|
+
if (!(await columnsOf(tx, T('Transactions'))).has('txseq')) await tx.run(`ALTER TABLE ${T('Transactions')} ADD COLUMN txSeq BIGINT`);
|
|
155
|
+
await tx.run(`UPDATE ${T('Transactions')} SET txSeq = slot * ${TX_SEQ_SLOT_FACTOR} + txIndex`);
|
|
156
|
+
await tx.run(`CREATE INDEX IF NOT EXISTS odatano_cardano_transactions_txseq ON ${T('Transactions')} (txSeq)`);
|
|
157
|
+
|
|
158
|
+
for (const spec of TX_SEQ_TABLES) {
|
|
159
|
+
const from = T(spec.from);
|
|
160
|
+
const to = T(spec.to);
|
|
161
|
+
const rebuilt = `${to}_txseq_new`;
|
|
162
|
+
const rows = await count(tx, from);
|
|
163
|
+
await tx.run(ddl(spec.to).replace(new RegExp(`^(\\s*CREATE TABLE )${to}\\b`, 'i'), `$1${rebuilt}`));
|
|
164
|
+
// only columns both layouts have: a column this version dropped stays behind
|
|
165
|
+
const kept = new Set((await columnsOf(tx, rebuilt)).keys());
|
|
166
|
+
const columns = [...(await columnsOf(tx, from)).keys()].filter(c => c === spec.hashKey.toLowerCase() || kept.has(c));
|
|
167
|
+
await tx.run(copySql(spec, columns, rebuilt));
|
|
168
|
+
const copied = await count(tx, rebuilt);
|
|
169
|
+
if (copied !== rows) throw new Error(`${from}: ${rows} rows, ${copied} copied (rows without a Transactions row?)`);
|
|
170
|
+
await tx.run(`DROP TABLE ${from}`);
|
|
171
|
+
await tx.run(`ALTER TABLE ${rebuilt} RENAME TO ${to}`);
|
|
172
|
+
if (tx.kind === 'postgres') {
|
|
173
|
+
await tx.run(`ALTER TABLE ${to} RENAME CONSTRAINT ${rebuilt.toLowerCase()}_pkey TO ${to.toLowerCase()}_pkey`);
|
|
174
|
+
}
|
|
175
|
+
log(`${to}: ${copied} rows`);
|
|
176
|
+
}
|
|
177
|
+
// fresh planner statistics: without them the rebuilt tables are read by sequential scans
|
|
178
|
+
for (const name of ['Transactions', ...TX_SEQ_TABLES.map(t => t.to)]) await tx.run(`ANALYZE ${T(name)}`);
|
|
179
|
+
},
|
|
180
|
+
model(definitions, image) {
|
|
181
|
+
delete definitions[E('TransactionInputAssets')];
|
|
182
|
+
for (const spec of TX_SEQ_TABLES) definitions[E(spec.to)] = image[E(spec.to)];
|
|
183
|
+
const transactions = definitions[E('Transactions')];
|
|
184
|
+
const current = image[E('Transactions')].elements;
|
|
185
|
+
if (!transactions?.elements) return;
|
|
186
|
+
transactions.elements.txSeq = current.txSeq;
|
|
187
|
+
// the compositions into the rebuilt tables join on txSeq now; a stale join makes the
|
|
188
|
+
// deploy emit an empty statement for them
|
|
189
|
+
const rebuilt = new Set(TX_SEQ_TABLES.map(t => E(t.to)));
|
|
190
|
+
for (const [name, element] of Object.entries(current)) {
|
|
191
|
+
if (element.target && rebuilt.has(element.target)) transactions.elements[name] = element;
|
|
192
|
+
}
|
|
193
|
+
},
|
|
194
|
+
},
|
|
195
|
+
{
|
|
196
|
+
name: 'Blocks.time: text -> timestamp',
|
|
197
|
+
async due(db) {
|
|
198
|
+
const type = (await columnsOf(db, T('Blocks'))).get('time');
|
|
199
|
+
if (type === undefined || !isTextType(type)) return false;
|
|
200
|
+
const unparsable = Number((await db.run(unparsableSql(db.kind)))[0].n);
|
|
201
|
+
if (unparsable > 0) throw new Error(`${unparsable} blocks hold a time that is no ISO 8601 UTC timestamp`);
|
|
202
|
+
return `${await count(db, T('Blocks'))} rows`;
|
|
203
|
+
},
|
|
204
|
+
async apply(tx) {
|
|
205
|
+
const table = T('Blocks');
|
|
206
|
+
if (tx.kind === 'postgres') {
|
|
207
|
+
await tx.run(`ALTER TABLE ${table} ALTER COLUMN time TYPE ${TIMESTAMP.postgres} USING (time::timestamptz AT TIME ZONE 'UTC')`);
|
|
208
|
+
return;
|
|
209
|
+
}
|
|
210
|
+
// SQLite cannot change a column's type: the table is rebuilt with the same rows
|
|
211
|
+
const rebuilt = `${table}_time_new`;
|
|
212
|
+
const rows = await count(tx, table);
|
|
213
|
+
const [stored] = await tx.run(`SELECT sql FROM sqlite_schema WHERE type = 'table' AND name = '${table}'`);
|
|
214
|
+
await tx.run(rebuiltTableSql(stored.sql, table, rebuilt));
|
|
215
|
+
await tx.run(`INSERT INTO ${rebuilt} SELECT * FROM ${table}`);
|
|
216
|
+
const copied = await count(tx, rebuilt);
|
|
217
|
+
if (copied !== rows) throw new Error(`${table}: ${rows} rows, ${copied} copied`);
|
|
218
|
+
await tx.run(`DROP TABLE ${table}`);
|
|
219
|
+
await tx.run(`ALTER TABLE ${rebuilt} RENAME TO ${table}`);
|
|
220
|
+
},
|
|
221
|
+
model(definitions, image) {
|
|
222
|
+
const stored = definitions[E('Blocks')];
|
|
223
|
+
if (stored?.elements?.time) stored.elements.time = image[E('Blocks')].elements.time;
|
|
224
|
+
},
|
|
225
|
+
},
|
|
226
|
+
{
|
|
227
|
+
name: 'CardanoAgentGrants: columns walletId and allowedJobKinds removed',
|
|
228
|
+
async due(db) {
|
|
229
|
+
const columns = await columnsOf(db, T('CardanoAgentGrants'));
|
|
230
|
+
return columns.has('walletid') || columns.has('allowedjobkinds');
|
|
231
|
+
},
|
|
232
|
+
async apply(tx) {
|
|
233
|
+
const columns = await columnsOf(tx, T('CardanoAgentGrants'));
|
|
234
|
+
for (const column of ['walletId', 'allowedJobKinds']) {
|
|
235
|
+
if (columns.has(column.toLowerCase())) await tx.run(`ALTER TABLE ${T('CardanoAgentGrants')} DROP COLUMN ${column}`);
|
|
236
|
+
}
|
|
237
|
+
},
|
|
238
|
+
model(definitions) {
|
|
239
|
+
const elements = definitions[E('CardanoAgentGrants')]?.elements ?? {};
|
|
240
|
+
delete elements.walletId;
|
|
241
|
+
delete elements.allowedJobKinds;
|
|
242
|
+
},
|
|
243
|
+
},
|
|
244
|
+
{
|
|
245
|
+
name: 'TransactionInputAssets: table renamed to TransactionInputAssetCopies',
|
|
246
|
+
async due(db, pending) {
|
|
247
|
+
// the txSeq step builds the table under its new name already
|
|
248
|
+
if (pending.includes(STEPS[0].name)) return false;
|
|
249
|
+
if (await relationKind(db, T('TransactionInputAssets')) !== 'table') return false;
|
|
250
|
+
if (await relationKind(db, T('TransactionInputAssetCopies'))) {
|
|
251
|
+
throw new Error(`${T('TransactionInputAssets')} and ${T('TransactionInputAssetCopies')} both exist as tables`);
|
|
252
|
+
}
|
|
253
|
+
return true;
|
|
254
|
+
},
|
|
255
|
+
async apply(tx) {
|
|
256
|
+
const from = T('TransactionInputAssets');
|
|
257
|
+
const to = T('TransactionInputAssetCopies');
|
|
258
|
+
await tx.run(`ALTER TABLE ${from} RENAME TO ${to}`);
|
|
259
|
+
if (tx.kind !== 'postgres') return;
|
|
260
|
+
const [key] = await tx.run(`SELECT 1 AS x FROM pg_constraint WHERE conname = '${from.toLowerCase()}_pkey' AND connamespace = current_schema()::regnamespace`);
|
|
261
|
+
if (key) await tx.run(`ALTER TABLE ${to} RENAME CONSTRAINT ${from.toLowerCase()}_pkey TO ${to.toLowerCase()}_pkey`);
|
|
262
|
+
},
|
|
263
|
+
model(definitions, image) {
|
|
264
|
+
delete definitions[E('TransactionInputAssets')];
|
|
265
|
+
definitions[E('TransactionInputAssetCopies')] = image[E('TransactionInputAssetCopies')];
|
|
266
|
+
// the deploy adds the association to the view again; it has no column
|
|
267
|
+
delete definitions[E('TransactionInputs')]?.elements?.assets;
|
|
268
|
+
},
|
|
269
|
+
},
|
|
270
|
+
{
|
|
271
|
+
name: 'CardanoWalletJobs: one idempotency key per user across wallets and kinds',
|
|
272
|
+
async due(db) {
|
|
273
|
+
const columns = await uniqueColumns(db, T('CardanoWalletJobs'), WALLET_JOBS_DEDUP);
|
|
274
|
+
return columns !== null && columns.join(',') !== 'dedupkey';
|
|
275
|
+
},
|
|
276
|
+
async apply(tx) {
|
|
277
|
+
const table = T('CardanoWalletJobs');
|
|
278
|
+
await tx.run(releaseSharedClaimsSql(table));
|
|
279
|
+
if (tx.kind === 'postgres') {
|
|
280
|
+
await tx.run(`ALTER TABLE ${table} DROP CONSTRAINT ${WALLET_JOBS_DEDUP}`);
|
|
281
|
+
await tx.run(`ALTER TABLE ${table} ADD CONSTRAINT ${WALLET_JOBS_DEDUP} UNIQUE (dedupKey)`);
|
|
282
|
+
return;
|
|
283
|
+
}
|
|
284
|
+
// SQLite cannot change a table constraint: the table is rebuilt with the same rows
|
|
285
|
+
const rebuilt = `${table}_dedup_new`;
|
|
286
|
+
const rows = await count(tx, table);
|
|
287
|
+
const [stored] = await tx.run(`SELECT sql FROM sqlite_schema WHERE type = 'table' AND name = '${table}'`);
|
|
288
|
+
const createSql = String(stored.sql).replace(/(CONSTRAINT\s+"?\w+_dedup"?\s+UNIQUE\s*)\([^)]*\)/i, '$1(dedupKey)');
|
|
289
|
+
if (createSql === stored.sql) throw new Error(`${table}: no constraint ${WALLET_JOBS_DEDUP} in its table definition`);
|
|
290
|
+
await tx.run(createSql.replace(new RegExp(`^(\\s*CREATE TABLE\\s+)"?${table}"?`, 'i'), `$1${rebuilt}`));
|
|
291
|
+
await tx.run(`INSERT INTO ${rebuilt} SELECT * FROM ${table}`);
|
|
292
|
+
const copied = await count(tx, rebuilt);
|
|
293
|
+
if (copied !== rows) throw new Error(`${table}: ${rows} rows, ${copied} copied`);
|
|
294
|
+
await tx.run(`DROP TABLE ${table}`);
|
|
295
|
+
await tx.run(`ALTER TABLE ${rebuilt} RENAME TO ${table}`);
|
|
296
|
+
},
|
|
297
|
+
model(definitions, image) {
|
|
298
|
+
const stored = definitions[E('CardanoWalletJobs')];
|
|
299
|
+
if (stored) stored['@assert.unique.dedup'] = image[E('CardanoWalletJobs')]['@assert.unique.dedup'];
|
|
300
|
+
},
|
|
301
|
+
},
|
|
302
|
+
{
|
|
303
|
+
name: 'CardanoAgentGrants: allow lists name Service.operation',
|
|
304
|
+
async due(db) {
|
|
305
|
+
if (!(await columnsOf(db, T('CardanoAgentGrants'))).has('allowedactions')) return false;
|
|
306
|
+
const rows = await db.run(`SELECT allowedActions AS actions FROM ${T('CardanoAgentGrants')}`);
|
|
307
|
+
const open = rows.filter(r => grantList(r.actions).some(name => !name.includes('.'))).length;
|
|
308
|
+
return open ? `${open} grants` : false;
|
|
309
|
+
},
|
|
310
|
+
async apply(tx, { model }) {
|
|
311
|
+
const byName = grantableByName(model);
|
|
312
|
+
const table = T('CardanoAgentGrants');
|
|
313
|
+
const update = tx.kind === 'postgres'
|
|
314
|
+
? `UPDATE ${table} SET allowedActions = $1 WHERE ID = $2`
|
|
315
|
+
: `UPDATE ${table} SET allowedActions = ? WHERE ID = ?`;
|
|
316
|
+
for (const row of await tx.run(`SELECT ID AS id, allowedActions AS actions FROM ${table}`)) {
|
|
317
|
+
const list = grantList(row.actions);
|
|
318
|
+
if (!list.some(name => !name.includes('.'))) continue;
|
|
319
|
+
await tx.run(update, [JSON.stringify(qualifiedGrantList(list, byName)), row.id]);
|
|
320
|
+
}
|
|
321
|
+
},
|
|
322
|
+
model() {},
|
|
323
|
+
},
|
|
324
|
+
];
|
|
325
|
+
|
|
326
|
+
/** Names of all views of the schema, the ones created last first. */
|
|
327
|
+
async function viewNames(db) {
|
|
328
|
+
const rows = db.kind === 'postgres'
|
|
329
|
+
? await db.run(`SELECT c.relname AS name FROM pg_class c JOIN pg_namespace n ON n.oid = c.relnamespace
|
|
330
|
+
WHERE c.relkind = 'v' AND n.nspname = current_schema() ORDER BY c.oid DESC`)
|
|
331
|
+
: await db.run(`SELECT name FROM sqlite_schema WHERE type = 'view' ORDER BY rowid DESC`);
|
|
332
|
+
return rows.map(r => r.name);
|
|
333
|
+
}
|
|
334
|
+
|
|
335
|
+
/** Database names of the views the models define, lower-cased. */
|
|
336
|
+
export function modelViewNames(...models) {
|
|
337
|
+
const names = new Set();
|
|
338
|
+
for (const model of models) {
|
|
339
|
+
for (const [name, def] of Object.entries(model?.definitions ?? {})) {
|
|
340
|
+
if (def.kind === 'entity' && isView(def)) names.add(name.replace(/\./g, '_').toLowerCase());
|
|
341
|
+
}
|
|
342
|
+
}
|
|
343
|
+
return names;
|
|
344
|
+
}
|
|
345
|
+
|
|
346
|
+
async function hasModelTable(db) {
|
|
347
|
+
const [found] = await db.run(db.kind === 'postgres'
|
|
348
|
+
? `SELECT 1 AS x FROM pg_tables WHERE tablename = 'cds_model' AND schemaname = current_schema()`
|
|
349
|
+
: `SELECT 1 AS x FROM sqlite_schema WHERE name = 'cds_model'`);
|
|
350
|
+
return Boolean(found);
|
|
351
|
+
}
|
|
352
|
+
|
|
353
|
+
/** The model of this version as the schema deploy stores it, and the CREATE TABLE statement of an entity. */
|
|
354
|
+
async function modelOfThisVersion(db) {
|
|
355
|
+
const model = await cds.load('*').then(cds.minify);
|
|
356
|
+
cds.deploy.exclude_external_entities_in(model);
|
|
357
|
+
const options = { ...db.options };
|
|
358
|
+
const statements = cds.compile.to.sql(model, options);
|
|
359
|
+
const ddl = (name) => {
|
|
360
|
+
const found = statements.find(s => new RegExp(`^CREATE TABLE ${T(name)} \\(`, 'i').test(s.trim()));
|
|
361
|
+
if (!found) throw new Error(`the model has no table ${T(name)}`);
|
|
362
|
+
return found;
|
|
363
|
+
};
|
|
364
|
+
return { model, options, image: cds.compile.to.sql.delta(model, options).afterImage, ddl };
|
|
365
|
+
}
|
|
366
|
+
|
|
367
|
+
const isView = (def) => Boolean(def.query || def.projection);
|
|
368
|
+
|
|
369
|
+
/** PostgreSQL columns of a table with length, precision and scale, by lower-cased name. */
|
|
370
|
+
async function columnSizes(db, table) {
|
|
371
|
+
const rows = await db.run(`SELECT column_name AS name, character_maximum_length AS length, numeric_precision AS precision, numeric_scale AS scale
|
|
372
|
+
FROM information_schema.columns WHERE table_schema = current_schema() AND table_name = '${table.toLowerCase()}'`);
|
|
373
|
+
return new Map(rows.map(r => [String(r.name).toLowerCase(), r]));
|
|
374
|
+
}
|
|
375
|
+
|
|
376
|
+
/** `element` with the length, precision and scale its PostgreSQL column has. */
|
|
377
|
+
export function sizedAsStored(element, column) {
|
|
378
|
+
if (!column) return element;
|
|
379
|
+
const sized = { ...element };
|
|
380
|
+
if (element.type === 'cds.Decimal' && column.precision != null) {
|
|
381
|
+
sized.precision = Number(column.precision);
|
|
382
|
+
sized.scale = Number(column.scale ?? 0);
|
|
383
|
+
}
|
|
384
|
+
if (element.type === 'cds.String' && column.length != null) sized.length = Number(column.length);
|
|
385
|
+
return sized;
|
|
386
|
+
}
|
|
387
|
+
|
|
388
|
+
// The model of this version cut down to what the database holds: its tables and their columns,
|
|
389
|
+
// no views. On PostgreSQL the sizes are the stored ones, so the deploy widens what this version widened.
|
|
390
|
+
export async function modelOfDatabase(db, image) {
|
|
391
|
+
const definitions = {};
|
|
392
|
+
for (const [name, def] of Object.entries(image.definitions)) {
|
|
393
|
+
if (def.kind !== 'entity') { definitions[name] = def; continue; }
|
|
394
|
+
if (isView(def)) continue;
|
|
395
|
+
const table = name.replace(/\./g, '_');
|
|
396
|
+
const columns = await columnsOf(db, table);
|
|
397
|
+
if (!columns.size) continue;
|
|
398
|
+
const sizes = db.kind === 'postgres' ? await columnSizes(db, table) : new Map();
|
|
399
|
+
const elements = {};
|
|
400
|
+
for (const [elementName, element] of Object.entries(def.elements ?? {})) {
|
|
401
|
+
const column = element['@cds.persistence.name'];
|
|
402
|
+
if (column !== undefined && !columns.has(String(column).toLowerCase())) continue;
|
|
403
|
+
elements[elementName] = column === undefined ? element : sizedAsStored(element, sizes.get(String(column).toLowerCase()));
|
|
404
|
+
}
|
|
405
|
+
definitions[name] = { ...def, elements };
|
|
406
|
+
}
|
|
407
|
+
return { ...image, definitions };
|
|
408
|
+
}
|
|
409
|
+
|
|
410
|
+
/** Waits for the first connection, which can take longer than the pool waits for one. */
|
|
411
|
+
async function connected(db) {
|
|
412
|
+
for (let attempt = 1; ; attempt++) {
|
|
413
|
+
try {
|
|
414
|
+
return await db.run('SELECT 1 AS x');
|
|
415
|
+
} catch (err) {
|
|
416
|
+
if (attempt === 15) throw err;
|
|
417
|
+
await new Promise(resolve => setTimeout(resolve, Math.min(500 * attempt, 5000)));
|
|
418
|
+
}
|
|
419
|
+
}
|
|
420
|
+
}
|
|
421
|
+
|
|
422
|
+
// Statements of the deploy from `prior` to this version that render as nothing. @cap-js/postgres
|
|
423
|
+
// names a statement by the hash of its text, so two empty ones collide and the deploy fails.
|
|
424
|
+
// SQLite runs an empty statement as a no-op, so only PostgreSQL counts.
|
|
425
|
+
export function emptyDeltaStatements(model, options, prior) {
|
|
426
|
+
if (options.kind !== 'postgres') return 0;
|
|
427
|
+
const { drops, createsAndAlters } = cds.compile.to.sql.delta(model, options, prior);
|
|
428
|
+
return [...drops, ...createsAndAlters].filter(sql => !String(sql).trim()).length;
|
|
429
|
+
}
|
|
430
|
+
|
|
431
|
+
/** Refuses a stored model the deploy cannot take, before the deploy changes anything. */
|
|
432
|
+
export async function assertDeployable(db) {
|
|
433
|
+
if (db.kind !== 'postgres') return;
|
|
434
|
+
if (!(await hasModelTable(db))) return;
|
|
435
|
+
const prior = JSON.parse((await db.run('SELECT csn FROM cds_model'))[0].csn);
|
|
436
|
+
const { model, options } = await modelOfThisVersion(db);
|
|
437
|
+
const empty = emptyDeltaStatements(model, options, prior);
|
|
438
|
+
if (empty) {
|
|
439
|
+
throw new Error(`the deploy from the stored model (cds_model) would run ${empty} empty statements, which the database refuses. `
|
|
440
|
+
+ 'The stored model holds a change the migration steps do not cover. Nothing was changed.');
|
|
441
|
+
}
|
|
442
|
+
}
|
|
443
|
+
|
|
444
|
+
/** The steps the database still needs, with what `due` reported for each. */
|
|
445
|
+
async function dueSteps(db) {
|
|
446
|
+
const due = [];
|
|
447
|
+
for (const step of STEPS) {
|
|
448
|
+
const detail = await step.due(db, due.map(d => d.step.name));
|
|
449
|
+
if (detail) due.push({ step, detail });
|
|
450
|
+
}
|
|
451
|
+
return due;
|
|
452
|
+
}
|
|
453
|
+
|
|
454
|
+
// Brings an existing database to the point where the additive schema deploy can take over, and
|
|
455
|
+
// returns the names of the steps it ran. A database without a stored model gets one here.
|
|
456
|
+
// Whenever it changes something the views are gone afterwards; the deploy creates them.
|
|
457
|
+
export async function migrateSchema(db, { dryRun = false, log = console.log } = {}) {
|
|
458
|
+
if (db.kind === 'hana') throw new Error(HANA_UPGRADE);
|
|
459
|
+
if (db.kind !== 'postgres' && db.kind !== 'sqlite') throw new Error(`unsupported database kind ${db.kind}: PostgreSQL and SQLite are migrated`);
|
|
460
|
+
await connected(db);
|
|
461
|
+
|
|
462
|
+
const due = await dueSteps(db);
|
|
463
|
+
const stored = await hasModelTable(db);
|
|
464
|
+
// a database that holds none of our tables is new: the deploy creates it
|
|
465
|
+
const adopt = !stored && (await columnsOf(db, T('Blocks'))).size > 0;
|
|
466
|
+
if (!due.length && !adopt) return [];
|
|
467
|
+
|
|
468
|
+
const [lease] = await db.run(`SELECT leaseUntil FROM ${T('CardanoSyncState')}`).catch(() => []);
|
|
469
|
+
const leaseUntil = lease?.leaseUntil ?? lease?.leaseuntil;
|
|
470
|
+
if (leaseUntil && Date.parse(leaseUntil) > Date.now()) {
|
|
471
|
+
throw new Error(`the crawler lease is held until ${leaseUntil}: stop ODATANO first`);
|
|
472
|
+
}
|
|
473
|
+
|
|
474
|
+
for (const { step, detail } of due) log(`due: ${step.name}${detail === true ? '' : ` (${detail})`}`);
|
|
475
|
+
if (adopt) log('due: the database has no stored model (cds_model), it is written from its tables');
|
|
476
|
+
const names = due.map(d => d.step.name);
|
|
477
|
+
if (dryRun) { log('dry run: nothing changed'); return names; }
|
|
478
|
+
|
|
479
|
+
const { model: current, options, image, ddl } = await modelOfThisVersion(db);
|
|
480
|
+
await db.tx(async (tx) => {
|
|
481
|
+
const started = Date.now();
|
|
482
|
+
const done = (msg) => log(`[${Math.round((Date.now() - started) / 1000)}s] ${msg}`);
|
|
483
|
+
|
|
484
|
+
const model = stored ? JSON.parse((await tx.run('SELECT csn FROM cds_model'))[0].csn) : null;
|
|
485
|
+
// only views of the models: any other view stays, and one that depends on ours makes the drop fail
|
|
486
|
+
const ours = modelViewNames(model, image);
|
|
487
|
+
const views = (await viewNames(tx)).filter(name => ours.has(String(name).toLowerCase()));
|
|
488
|
+
for (const name of views) await tx.run(`DROP VIEW IF EXISTS "${name}"`);
|
|
489
|
+
done(`${views.length} views dropped`);
|
|
490
|
+
|
|
491
|
+
for (const { step } of due) {
|
|
492
|
+
await step.apply(tx, { ddl, log: done, model: current });
|
|
493
|
+
if (model) step.model(model.definitions, image.definitions);
|
|
494
|
+
done(step.name);
|
|
495
|
+
}
|
|
496
|
+
|
|
497
|
+
if (model) {
|
|
498
|
+
// the stored model lists no view any more, so the deploy creates every view of this version
|
|
499
|
+
for (const [name, def] of Object.entries(model.definitions)) {
|
|
500
|
+
if (isView(def)) delete model.definitions[name];
|
|
501
|
+
}
|
|
502
|
+
const empty = emptyDeltaStatements(current, options, model);
|
|
503
|
+
if (empty) throw new Error(`after the steps the deploy would run ${empty} empty statements; nothing was changed`);
|
|
504
|
+
await tx.run(db.kind === 'postgres' ? 'UPDATE cds_model SET csn = $1' : 'UPDATE cds_model SET csn = ?', [JSON.stringify(model)]);
|
|
505
|
+
} else {
|
|
506
|
+
const adopted = await modelOfDatabase(tx, image);
|
|
507
|
+
const empty = emptyDeltaStatements(current, options, adopted);
|
|
508
|
+
if (empty) throw new Error(`for the stored model written from the tables the deploy would run ${empty} empty statements; nothing was changed`);
|
|
509
|
+
const csn = JSON.stringify(adopted);
|
|
510
|
+
await tx.run(`CREATE TABLE cds_model (csn ${db.kind === 'postgres' ? 'TEXT' : 'CLOB'})`);
|
|
511
|
+
await tx.run(db.kind === 'postgres' ? 'INSERT INTO cds_model VALUES ($1)' : 'INSERT INTO cds_model VALUES (?)', [csn]);
|
|
512
|
+
}
|
|
513
|
+
done(`cds_model ${model ? 'updated' : 'written'}`);
|
|
514
|
+
});
|
|
515
|
+
return adopt ? [...names, 'stored model written'] : names;
|
|
516
|
+
}
|
|
517
|
+
|
|
518
|
+
async function main() {
|
|
519
|
+
const db = await cds.connect.to('db');
|
|
520
|
+
const dryRun = process.argv.includes('--dry-run');
|
|
521
|
+
const ran = await migrateSchema(db, { dryRun });
|
|
522
|
+
if (!ran.length) console.log('The schema needs no migration.');
|
|
523
|
+
else if (!dryRun) console.log('Migrated. Deploy the schema now; it creates the views again.');
|
|
524
|
+
}
|
|
525
|
+
|
|
526
|
+
if (process.argv[1] && import.meta.url === (await import('node:url')).pathToFileURL(process.argv[1]).href) {
|
|
527
|
+
main().then(() => process.exit(0), (err) => { console.error(`FAILED: ${err.message}`); process.exit(1); });
|
|
528
|
+
}
|
|
@@ -0,0 +1,96 @@
|
|
|
1
|
+
#!/usr/bin/env node
|
|
2
|
+
// Reads old Blocks.slotLeader values on stdin and prints SQL that rewrites them to bech32 pool ids.
|
|
3
|
+
// Issuer keys are hashed. VRF keys are matched via --stake-pools. Unmapped values go to stderr.
|
|
4
|
+
// --extra-map supplies those as "<old value> <pool id>" lines. The database is not touched.
|
|
5
|
+
import fs from 'node:fs';
|
|
6
|
+
import { pathToFileURL } from 'node:url';
|
|
7
|
+
import { bech32 } from 'bech32';
|
|
8
|
+
import { blake2b_224, blake2b_256 } from '@harmoniclabs/crypto';
|
|
9
|
+
|
|
10
|
+
const toHex = (bytes) => Buffer.from(bytes).toString('hex');
|
|
11
|
+
const lines = (text) => text.split(/\r?\n/).map(l => l.trim()).filter(Boolean);
|
|
12
|
+
|
|
13
|
+
/** VRF key hash (hex) -> pool id, from an Ogmios stakePools response (whole JSON-RPC reply or its result). */
|
|
14
|
+
export function vrfMapFromStakePools(response) {
|
|
15
|
+
const pools = response?.result ?? response ?? {};
|
|
16
|
+
const map = new Map();
|
|
17
|
+
for (const [id, pool] of Object.entries(pools)) {
|
|
18
|
+
const vrf = pool?.vrfVerificationKeyHash;
|
|
19
|
+
if (typeof vrf === 'string') map.set(vrf.toLowerCase(), pool.id ?? id);
|
|
20
|
+
}
|
|
21
|
+
return map;
|
|
22
|
+
}
|
|
23
|
+
|
|
24
|
+
/** "<old value> <pool id>" lines to a Map; lines starting with # are skipped. */
|
|
25
|
+
export function parseExtraMap(text) {
|
|
26
|
+
const map = new Map();
|
|
27
|
+
for (const line of lines(text)) {
|
|
28
|
+
if (line.startsWith('#')) continue;
|
|
29
|
+
const [from, to] = line.split(/\s+/);
|
|
30
|
+
if (!to?.startsWith('pool1')) throw new Error(`extra map: no pool id for ${from}`);
|
|
31
|
+
map.set(from, to);
|
|
32
|
+
}
|
|
33
|
+
return map;
|
|
34
|
+
}
|
|
35
|
+
|
|
36
|
+
/** Bech32 pool id for an old slotLeader value, or null when it cannot be derived. */
|
|
37
|
+
export function slotLeaderToPoolId(value, vrfMap = new Map()) {
|
|
38
|
+
if (typeof value !== 'string') return null;
|
|
39
|
+
const v = value.trim();
|
|
40
|
+
if (/^[0-9a-f]{64}$/i.test(v)) {
|
|
41
|
+
return bech32.encode('pool', bech32.toWords(blake2b_224(Uint8Array.from(Buffer.from(v, 'hex')))));
|
|
42
|
+
}
|
|
43
|
+
if (v.startsWith('vrf_vk1')) {
|
|
44
|
+
const { words } = bech32.decode(v, 120);
|
|
45
|
+
const vrfHash = toHex(blake2b_256(Uint8Array.from(bech32.fromWords(words))));
|
|
46
|
+
return vrfMap.get(vrfHash) ?? null;
|
|
47
|
+
}
|
|
48
|
+
return null;
|
|
49
|
+
}
|
|
50
|
+
|
|
51
|
+
const sqlString = (s) => `'${s.replace(/'/g, "''")}'`;
|
|
52
|
+
|
|
53
|
+
/** SQL that rewrites every mapped value in one UPDATE; empty string when nothing maps. */
|
|
54
|
+
export function migrationSql(mapping) {
|
|
55
|
+
if (mapping.size === 0) return '';
|
|
56
|
+
const rows = [...mapping].map(([from, to]) => ` (${sqlString(from)}, ${sqlString(to)})`);
|
|
57
|
+
return [
|
|
58
|
+
'BEGIN;',
|
|
59
|
+
'CREATE TEMPORARY TABLE slot_leader_map (old_value VARCHAR(200) PRIMARY KEY, new_value VARCHAR(120) NOT NULL);',
|
|
60
|
+
`INSERT INTO slot_leader_map (old_value, new_value) VALUES\n${rows.join(',\n')};`,
|
|
61
|
+
'UPDATE odatano_cardano_Blocks',
|
|
62
|
+
' SET slotLeader = (SELECT m.new_value FROM slot_leader_map m WHERE m.old_value = odatano_cardano_Blocks.slotLeader)',
|
|
63
|
+
' WHERE slotLeader IN (SELECT old_value FROM slot_leader_map);',
|
|
64
|
+
'DROP TABLE slot_leader_map;',
|
|
65
|
+
'COMMIT;',
|
|
66
|
+
'',
|
|
67
|
+
].join('\n');
|
|
68
|
+
}
|
|
69
|
+
|
|
70
|
+
function argValue(name) {
|
|
71
|
+
const i = process.argv.indexOf(name);
|
|
72
|
+
return i >= 0 ? process.argv[i + 1] : undefined;
|
|
73
|
+
}
|
|
74
|
+
|
|
75
|
+
function main() {
|
|
76
|
+
const stakePoolsFile = argValue('--stake-pools');
|
|
77
|
+
const extraMapFile = argValue('--extra-map');
|
|
78
|
+
const vrfMap = stakePoolsFile ? vrfMapFromStakePools(JSON.parse(fs.readFileSync(stakePoolsFile, 'utf8'))) : new Map();
|
|
79
|
+
const extraMap = extraMapFile ? parseExtraMap(fs.readFileSync(extraMapFile, 'utf8')) : new Map();
|
|
80
|
+
|
|
81
|
+
const values = [...new Set(lines(fs.readFileSync(0, 'utf8')))];
|
|
82
|
+
const mapping = new Map();
|
|
83
|
+
const unmapped = [];
|
|
84
|
+
for (const v of values) {
|
|
85
|
+
if (v.startsWith('pool1')) continue;
|
|
86
|
+
const poolId = extraMap.get(v) ?? slotLeaderToPoolId(v, vrfMap);
|
|
87
|
+
if (poolId) mapping.set(v, poolId);
|
|
88
|
+
else unmapped.push(v);
|
|
89
|
+
}
|
|
90
|
+
|
|
91
|
+
process.stdout.write(migrationSql(mapping));
|
|
92
|
+
console.error(`slotLeader values: ${values.length} read, ${mapping.size} mapped, ${unmapped.length} left unchanged`);
|
|
93
|
+
for (const v of unmapped) console.error(` unmapped: ${v}`);
|
|
94
|
+
}
|
|
95
|
+
|
|
96
|
+
if (process.argv[1] && import.meta.url === pathToFileURL(process.argv[1]).href) main();
|