@memberjunction/installer 6.2.0-edge.2 → 6.2.0-edge.4

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.
Files changed (38) hide show
  1. package/dist/adapters/PostgresAdapter.d.ts +132 -0
  2. package/dist/adapters/PostgresAdapter.d.ts.map +1 -0
  3. package/dist/adapters/PostgresAdapter.js +210 -0
  4. package/dist/adapters/PostgresAdapter.js.map +1 -0
  5. package/dist/adapters/ProcessRunner.d.ts +2 -1
  6. package/dist/adapters/ProcessRunner.d.ts.map +1 -1
  7. package/dist/adapters/ProcessRunner.js +6 -2
  8. package/dist/adapters/ProcessRunner.js.map +1 -1
  9. package/dist/adapters/SqlServerAdapter.d.ts +52 -2
  10. package/dist/adapters/SqlServerAdapter.d.ts.map +1 -1
  11. package/dist/adapters/SqlServerAdapter.js +87 -2
  12. package/dist/adapters/SqlServerAdapter.js.map +1 -1
  13. package/dist/events/InstallerEvents.d.ts +2 -2
  14. package/dist/events/InstallerEvents.d.ts.map +1 -1
  15. package/dist/index.d.ts +2 -1
  16. package/dist/index.d.ts.map +1 -1
  17. package/dist/index.js +2 -1
  18. package/dist/index.js.map +1 -1
  19. package/dist/logging/ReportGenerator.d.ts.map +1 -1
  20. package/dist/logging/ReportGenerator.js +2 -0
  21. package/dist/logging/ReportGenerator.js.map +1 -1
  22. package/dist/models/InstallConfig.d.ts +30 -3
  23. package/dist/models/InstallConfig.d.ts.map +1 -1
  24. package/dist/models/InstallConfig.js +22 -2
  25. package/dist/models/InstallConfig.js.map +1 -1
  26. package/dist/phases/ConfigurePhase.d.ts +8 -0
  27. package/dist/phases/ConfigurePhase.d.ts.map +1 -1
  28. package/dist/phases/ConfigurePhase.js +56 -8
  29. package/dist/phases/ConfigurePhase.js.map +1 -1
  30. package/dist/phases/DatabaseProvisionPhase.d.ts +151 -21
  31. package/dist/phases/DatabaseProvisionPhase.d.ts.map +1 -1
  32. package/dist/phases/DatabaseProvisionPhase.js +513 -84
  33. package/dist/phases/DatabaseProvisionPhase.js.map +1 -1
  34. package/dist/phases/PreflightPhase.d.ts +4 -2
  35. package/dist/phases/PreflightPhase.d.ts.map +1 -1
  36. package/dist/phases/PreflightPhase.js +17 -10
  37. package/dist/phases/PreflightPhase.js.map +1 -1
  38. package/package.json +5 -1
@@ -1,29 +1,264 @@
1
1
  /**
2
2
  * Phase C — Database Provisioning
3
3
  *
4
- * Generates idempotent SQL scripts for database setup and prompts the user
5
- * to execute them manually in SSMS or Azure Data Studio. Then validates
6
- * that SQL Server is reachable at the configured host:port.
4
+ * Makes sure the database exists and the CodeGen and API logins can use it, so
5
+ * the migrate phase that follows has somewhere to run. Works on SQL Server and
6
+ * PostgreSQL (`DatabasePlatform`).
7
7
  *
8
- * Two scripts are generated:
9
- * 1. **`mj-db-setup.sql`** — Creates the database (if not exists), `__mj` schema,
10
- * SQL logins, database users, and role grants. All statements are idempotent
11
- * (safe to run multiple times).
12
- * 2. **`mj-db-validate.sql`** — Verifies the schema, users, and roles exist.
13
- * Run this to confirm the setup script was executed correctly.
14
- *
15
- * The phase does **not** execute SQL directly — it generates scripts and asks
16
- * the user to run them. This design avoids requiring a SQL driver dependency
17
- * in the installer and gives users full visibility into what's being executed.
8
+ * 1. Generates two idempotent scripts and saves them in the install folder:
9
+ * - **`mj-db-setup.sql`** — creates the database (if missing), the `__mj`
10
+ * schema, the logins (PostgreSQL: login roles), and the grants. On
11
+ * SQL Server it is a `GO`-separated script; on PostgreSQL it is a `psql`
12
+ * script rendered from the same ordered statements the installer runs.
13
+ * - **`mj-db-validate.sql`** — checks that the schema and logins exist.
14
+ * 2. Checks that the server is reachable (a TCP check; no credentials are sent).
15
+ * 3. Signs in as the CodeGen and API logins. If both work, the database is
16
+ * already set up and nothing else happens.
17
+ * 4. Otherwise it runs the setup itself, signed in with an administrator
18
+ * login (`DatabaseAdminUser` / `DatabaseAdminPassword`, or
19
+ * `MJ_INSTALL_DB_ADMIN_USER` / `MJ_INSTALL_DB_ADMIN_PASSWORD`). Interactive
20
+ * installs ask for that login, and can still choose to run the script by hand.
21
+ * The administrator login is used only here and is never saved.
22
+ * 5. Signs in as both logins again to confirm the setup worked.
18
23
  *
19
24
  * @module phases/DatabaseProvisionPhase
20
- * @see SqlServerAdapter — used for TCP connectivity validation.
25
+ * @see SqlServerAdapter — SQL Server TCP check, sign-in check, and script execution.
26
+ * @see PostgresAdapter — PostgreSQL TCP check, sign-in check, and step execution.
21
27
  * @see ConfigurePhase — provides the database credentials used in script generation.
22
28
  */
23
29
  import path from 'node:path';
24
30
  import { InstallerError } from '../errors/InstallerError.js';
25
31
  import { FileSystemAdapter } from '../adapters/FileSystemAdapter.js';
26
- import { SqlServerAdapter } from '../adapters/SqlServerAdapter.js';
32
+ import { SqlServerAdapter, SqlBatchError } from '../adapters/SqlServerAdapter.js';
33
+ import { PostgresAdapter, PgStepError } from '../adapters/PostgresAdapter.js';
34
+ /** How many times an interactive install asks again after the administrator login is refused. */
35
+ const ADMIN_LOGIN_ATTEMPTS = 3;
36
+ /**
37
+ * Wrap a name as a T-SQL identifier, doubling any `]` so that no database or
38
+ * login name can break out of the brackets.
39
+ */
40
+ export function QuoteSqlIdentifier(name) {
41
+ return `[${name.replace(/]/g, ']]')}]`;
42
+ }
43
+ /**
44
+ * Escape text for use inside a T-SQL `'...'` literal by doubling `'`. The
45
+ * caller supplies the surrounding quotes.
46
+ */
47
+ export function EscapeSqlString(text) {
48
+ return text.replace(/'/g, "''");
49
+ }
50
+ /**
51
+ * Split a script into batches on lines that contain only `GO`, the way SSMS
52
+ * and `sqlcmd` do. Batches with nothing but comments and blank lines are dropped.
53
+ */
54
+ export function SplitSqlBatches(script) {
55
+ return script
56
+ .split(/^[ \t]*GO[ \t]*$/im)
57
+ .map((batch) => batch.trim())
58
+ .filter((batch) => batch.split(/\r?\n/).some((line) => line.trim() !== '' && !line.trim().startsWith('--')));
59
+ }
60
+ const PLATFORM_LABELS = {
61
+ sqlserver: {
62
+ Server: 'SQL Server',
63
+ DefaultPort: 1433,
64
+ MaintenanceDatabase: 'master',
65
+ DefaultAdminUser: 'sa',
66
+ AdminArticle: 'a SQL administrator',
67
+ AdminRequirement: 'a SQL login that can create databases and logins (such as sa)',
68
+ AdminExample: 'a SQL admin login such as sa',
69
+ AdminPrompt: 'SQL admin login (needs rights to create databases and logins):',
70
+ ManualTool: 'in SSMS or Azure Data Studio',
71
+ },
72
+ postgresql: {
73
+ Server: 'PostgreSQL',
74
+ DefaultPort: 5432,
75
+ MaintenanceDatabase: 'postgres',
76
+ DefaultAdminUser: 'postgres',
77
+ AdminArticle: 'a PostgreSQL superuser',
78
+ AdminRequirement: 'a PostgreSQL superuser (such as postgres)',
79
+ AdminExample: 'a PostgreSQL superuser such as postgres',
80
+ AdminPrompt: 'PostgreSQL admin role (a superuser, such as postgres):',
81
+ ManualTool: 'with psql',
82
+ },
83
+ };
84
+ /**
85
+ * Wrap a name as a PostgreSQL identifier, doubling any `"` so that no database
86
+ * or role name can break out of the quotes. Quoted names keep their case, which
87
+ * matches how the `pg` driver passes the user and database names when connecting.
88
+ */
89
+ export function QuotePgIdentifier(name) {
90
+ return `"${name.replace(/"/g, '""')}"`;
91
+ }
92
+ /**
93
+ * Wrap text as a PostgreSQL string literal, doubling any `'`. The setup runs
94
+ * `SET standard_conforming_strings = on` first, so backslashes stay literal.
95
+ */
96
+ export function QuotePgLiteral(text) {
97
+ return `'${text.replace(/'/g, "''")}'`;
98
+ }
99
+ /**
100
+ * Group roles that MJ's PostgreSQL migrations and CodeGen grant object
101
+ * permissions to. The newest baselines `GRANT ... TO "cdp_*"` without creating
102
+ * the roles (MJ's own CI creates them first, as a superuser), and older
103
+ * baselines create them only when missing. Creating them here, as `NOLOGIN`
104
+ * roles, means the CodeGen login never needs `CREATEROLE`.
105
+ */
106
+ export const POSTGRES_MJ_GROUP_ROLES = Object.freeze([
107
+ 'cdp_BI',
108
+ 'cdp_CodeGen',
109
+ 'cdp_Developer',
110
+ 'cdp_Integration',
111
+ 'cdp_UI',
112
+ ]);
113
+ /** Extensions MJ's PostgreSQL migrations require (they run `CREATE EXTENSION IF NOT EXISTS`). */
114
+ export const POSTGRES_MJ_EXTENSIONS = Object.freeze(['pgcrypto', 'uuid-ossp']);
115
+ /** The PostgreSQL maintenance database the setup connects to before the MJ database exists. */
116
+ const POSTGRES_MAINTENANCE_DB = 'postgres';
117
+ /**
118
+ * Build the ordered PostgreSQL setup statements. The installer runs exactly
119
+ * these (one statement per query, never a split script), and
120
+ * {@link RenderPostgresSetupScript} writes the same list as a `psql` script.
121
+ *
122
+ * Privileges (least privilege; mirrors `db_owner` vs. read/write/execute on SQL Server):
123
+ * - **CodeGen login** — `LOGIN` only (no `CREATEDB`, `CREATEROLE`, or superuser).
124
+ * Owns the `__mj` schema, so `mj migrate` and CodeGen can create, alter, and
125
+ * replace the tables, views, functions, and triggers in it and grant on them;
126
+ * `CONNECT, CREATE, TEMPORARY` on the database, because Skyway runs
127
+ * `CREATE SCHEMA IF NOT EXISTS` before migrating (PostgreSQL checks the
128
+ * database `CREATE` privilege even when the schema exists) and Open Apps add schemas.
129
+ * - **API login** — `LOGIN` only. `CONNECT, TEMPORARY` on the database,
130
+ * `USAGE` on `__mj`, `SELECT/INSERT/UPDATE/DELETE` on its tables,
131
+ * `USAGE, SELECT` on its sequences, `EXECUTE` on its routines — for what is
132
+ * there now and, through default privileges, for everything the CodeGen
133
+ * login creates later (including schemas it adds).
134
+ * - **Administrator** (this setup only) — creates the database, the roles, and
135
+ * the `pgcrypto` / `uuid-ossp` extensions.
136
+ *
137
+ * @param config - Install config with the database name and both logins.
138
+ * @returns The ordered steps.
139
+ */
140
+ export function BuildPostgresSetupSteps(config) {
141
+ const dbName = config.DatabaseName ?? 'MemberJunction';
142
+ const codeGenUser = config.CodeGenUser ?? 'MJ_CodeGen';
143
+ const codeGenPassword = config.CodeGenPassword ?? 'CHANGE_ME';
144
+ const apiUser = config.APIUser ?? 'MJ_Connect';
145
+ const apiPassword = config.APIPassword ?? 'CHANGE_ME';
146
+ const db = QuotePgIdentifier(dbName);
147
+ const codeGen = QuotePgIdentifier(codeGenUser);
148
+ const api = QuotePgIdentifier(apiUser);
149
+ const schema = QuotePgIdentifier('__mj');
150
+ const maintenance = POSTGRES_MAINTENANCE_DB;
151
+ const roleExists = 'SELECT 1 FROM pg_catalog.pg_roles WHERE rolname = $1';
152
+ const steps = [
153
+ // (a) Server level, connected to the maintenance database.
154
+ {
155
+ Database: maintenance,
156
+ Description: 'Treat backslashes in string literals literally',
157
+ Sql: 'SET standard_conforming_strings = on',
158
+ },
159
+ {
160
+ Database: maintenance,
161
+ Description: `Create database ${dbName}`,
162
+ Sql: `CREATE DATABASE ${db}`,
163
+ SkipIf: { Sql: 'SELECT 1 FROM pg_catalog.pg_database WHERE datname = $1', Param: dbName },
164
+ },
165
+ // (b) Roles. Existing roles are left as they are (their passwords are not changed).
166
+ ...POSTGRES_MJ_GROUP_ROLES.map((role) => ({
167
+ Database: maintenance,
168
+ Description: `Create group role ${role}`,
169
+ Sql: `CREATE ROLE ${QuotePgIdentifier(role)} NOLOGIN`,
170
+ SkipIf: { Sql: roleExists, Param: role },
171
+ })),
172
+ {
173
+ Database: maintenance,
174
+ Description: `Create CodeGen login role ${codeGenUser}`,
175
+ Sql: `CREATE ROLE ${codeGen} LOGIN PASSWORD ${QuotePgLiteral(codeGenPassword)}`,
176
+ SkipIf: { Sql: roleExists, Param: codeGenUser },
177
+ },
178
+ {
179
+ Database: maintenance,
180
+ Description: `Create API login role ${apiUser}`,
181
+ Sql: `CREATE ROLE ${api} LOGIN PASSWORD ${QuotePgLiteral(apiPassword)}`,
182
+ SkipIf: { Sql: roleExists, Param: apiUser },
183
+ },
184
+ ];
185
+ // (c) Inside the MJ database.
186
+ const inDb = (Description, Sql) => ({ Database: dbName, Description, Sql });
187
+ steps.push(...POSTGRES_MJ_EXTENSIONS.map((ext) => inDb(`Create extension ${ext}`, `CREATE EXTENSION IF NOT EXISTS ${QuotePgIdentifier(ext)}`)), inDb(`Let ${codeGenUser} connect and create schemas`, `GRANT CONNECT, CREATE, TEMPORARY ON DATABASE ${db} TO ${codeGen}`), inDb(`Let ${apiUser} connect`, `GRANT CONNECT, TEMPORARY ON DATABASE ${db} TO ${api}`), inDb(`Create schema __mj owned by ${codeGenUser}`, `CREATE SCHEMA IF NOT EXISTS ${schema} AUTHORIZATION ${codeGen}`), inDb(`Make ${codeGenUser} the owner of schema __mj`, `ALTER SCHEMA ${schema} OWNER TO ${codeGen}`), inDb(`Let ${apiUser} use schema __mj`, `GRANT USAGE ON SCHEMA ${schema} TO ${api}`), inDb(`Let ${apiUser} read and write existing __mj tables`, `GRANT SELECT, INSERT, UPDATE, DELETE ON ALL TABLES IN SCHEMA ${schema} TO ${api}`), inDb(`Let ${apiUser} use existing __mj sequences`, `GRANT USAGE, SELECT ON ALL SEQUENCES IN SCHEMA ${schema} TO ${api}`), inDb(`Let ${apiUser} execute existing __mj routines`, `GRANT EXECUTE ON ALL ROUTINES IN SCHEMA ${schema} TO ${api}`), inDb(`Let ${apiUser} read and write tables ${codeGenUser} creates`, `ALTER DEFAULT PRIVILEGES FOR ROLE ${codeGen} GRANT SELECT, INSERT, UPDATE, DELETE ON TABLES TO ${api}`), inDb(`Let ${apiUser} use sequences ${codeGenUser} creates`, `ALTER DEFAULT PRIVILEGES FOR ROLE ${codeGen} GRANT USAGE, SELECT ON SEQUENCES TO ${api}`), inDb(`Let ${apiUser} execute routines ${codeGenUser} creates`, `ALTER DEFAULT PRIVILEGES FOR ROLE ${codeGen} GRANT EXECUTE ON ROUTINES TO ${api}`), inDb(`Let ${apiUser} use schemas ${codeGenUser} creates`, `ALTER DEFAULT PRIVILEGES FOR ROLE ${codeGen} GRANT USAGE ON SCHEMAS TO ${api}`));
188
+ return steps;
189
+ }
190
+ /**
191
+ * Render the setup steps as a `psql` script for people who run the setup by
192
+ * hand. `\connect` and `\gexec` are psql meta-commands; they appear only in
193
+ * this file, never in what the installer sends to the server.
194
+ *
195
+ * @param config - Install config (for the header).
196
+ * @param steps - Steps from {@link BuildPostgresSetupSteps}.
197
+ * @returns The script text.
198
+ */
199
+ export function RenderPostgresSetupScript(config, steps) {
200
+ const dbName = config.DatabaseName ?? 'MemberJunction';
201
+ const lines = [
202
+ '-- MemberJunction Database Setup Script (PostgreSQL)',
203
+ '-- Generated by MJ Installer',
204
+ '-- This script is idempotent (safe to run multiple times)',
205
+ '--',
206
+ '-- Run it with psql as a PostgreSQL superuser, for example:',
207
+ `-- psql -h <host> -p <port> -U postgres -d ${POSTGRES_MAINTENANCE_DB} -f mj-db-setup.sql`,
208
+ `-- It creates the database ${dbName}, the CodeGen and API login roles, the MJ`,
209
+ '-- group roles, the required extensions, the __mj schema, and the grants.',
210
+ '',
211
+ '\\set ON_ERROR_STOP on',
212
+ ];
213
+ let currentDatabase = null;
214
+ steps.forEach((step, index) => {
215
+ if (step.Database !== currentDatabase) {
216
+ lines.push('', `\\connect ${QuotePgIdentifier(step.Database)}`);
217
+ currentDatabase = step.Database;
218
+ }
219
+ lines.push('', `-- ${index + 1}. ${step.Description}`);
220
+ if (step.SkipIf) {
221
+ // psql's \gexec runs the statement only when the existence check finds nothing.
222
+ const check = step.SkipIf.Sql.replace('$1', QuotePgLiteral(step.SkipIf.Param));
223
+ lines.push(`SELECT ${QuotePgLiteral(step.Sql)} WHERE NOT EXISTS (${check})\\gexec`);
224
+ }
225
+ else {
226
+ lines.push(`${step.Sql};`);
227
+ }
228
+ });
229
+ lines.push('', "\\echo '=== MemberJunction database setup complete ==='", '');
230
+ return lines.join('\n');
231
+ }
232
+ /**
233
+ * Generate the PostgreSQL validation script: one `[PASS]` / `[FAIL]` row per check.
234
+ *
235
+ * @param config - Install config with the database name and both logins.
236
+ * @returns The script text (`psql`).
237
+ */
238
+ export function GeneratePostgresValidateScript(config) {
239
+ const dbName = config.DatabaseName ?? 'MemberJunction';
240
+ const codeGenUser = config.CodeGenUser ?? 'MJ_CodeGen';
241
+ const apiUser = config.APIUser ?? 'MJ_Connect';
242
+ const check = (condition, label) => `SELECT CASE WHEN ${condition} THEN ${QuotePgLiteral(`[PASS] ${label}`)} ELSE ${QuotePgLiteral(`[FAIL] ${label}`)} END AS "Check"`;
243
+ const roleCheck = (role, label) => check(`EXISTS (SELECT 1 FROM pg_catalog.pg_roles WHERE rolname = ${QuotePgLiteral(role)} AND rolcanlogin)`, label);
244
+ return [
245
+ '-- MemberJunction Database Validation Script (PostgreSQL)',
246
+ '-- Generated by MJ Installer',
247
+ '-- Run this with psql to verify the database setup is correct.',
248
+ '',
249
+ `\\connect ${QuotePgIdentifier(dbName)}`,
250
+ '',
251
+ [
252
+ check(`EXISTS (SELECT 1 FROM pg_catalog.pg_namespace WHERE nspname = '__mj')`, '__mj schema exists'),
253
+ roleCheck(codeGenUser, `CodeGen login ${codeGenUser} exists`),
254
+ roleCheck(apiUser, `API login ${apiUser} exists`),
255
+ check(`(CASE WHEN EXISTS (SELECT 1 FROM pg_catalog.pg_roles WHERE rolname = ${QuotePgLiteral(apiUser)}) `
256
+ + `AND EXISTS (SELECT 1 FROM pg_catalog.pg_namespace WHERE nspname = '__mj') `
257
+ + `THEN has_schema_privilege(${QuotePgLiteral(apiUser)}, '__mj', 'USAGE') ELSE false END)`, `API login ${apiUser} can use schema __mj`),
258
+ ].join('\nUNION ALL\n') + ';',
259
+ '',
260
+ ].join('\n');
261
+ }
27
262
  /**
28
263
  * Phase C — Generates SQL provisioning scripts and validates database connectivity.
29
264
  *
@@ -43,71 +278,263 @@ export class DatabaseProvisionPhase {
43
278
  constructor() {
44
279
  this.fileSystem = new FileSystemAdapter();
45
280
  this.sqlAdapter = new SqlServerAdapter();
281
+ this.pgAdapter = new PostgresAdapter();
46
282
  }
47
283
  /**
48
- * Execute the database provisioning phase: generate scripts, prompt user,
49
- * and validate connectivity.
284
+ * Execute the database provisioning phase: generate the scripts, make sure
285
+ * the database server is reachable, and set the database up if it is not already.
50
286
  *
51
287
  * @param context - Database provision input with directory, config, mode, and emitter.
52
- * @returns Script paths and validation result.
53
- * @throws {InstallerError} With code `DB_UNREACHABLE` if SQL Server connectivity fails after script execution.
288
+ * @returns Script paths, whether setup was confirmed, and whether the script ran.
289
+ * @throws {InstallerError} `DB_UNREACHABLE` when the server cannot be reached;
290
+ * `DB_NOT_SET_UP` when the database is not set up and no administrator login
291
+ * was given (or the user chose to run the script and it still is not);
292
+ * `DB_ADMIN_LOGIN_FAILED` when the administrator login is refused;
293
+ * `DB_SETUP_FAILED` when the setup script fails or leaves a login unable to sign in.
54
294
  */
55
295
  async Run(context) {
56
296
  const { Config: config, Emitter: emitter } = context;
297
+ const platform = config.DatabasePlatform ?? 'sqlserver';
298
+ const labels = PLATFORM_LABELS[platform];
57
299
  // Step 1: Generate SQL scripts
58
300
  emitter.Emit('step:progress', {
59
301
  Type: 'step:progress',
60
302
  Phase: 'database',
61
303
  Message: 'Generating database setup scripts...',
62
304
  });
63
- const scripts = this.generateSetupScript(config);
305
+ const pgSteps = platform === 'postgresql' ? BuildPostgresSetupSteps(config) : [];
306
+ const setupScript = platform === 'postgresql' ? RenderPostgresSetupScript(config, pgSteps) : this.generateSetupScript(config);
64
307
  const scriptPath = path.join(context.Dir, 'mj-db-setup.sql');
65
- await this.fileSystem.WriteText(scriptPath, scripts);
66
- const validateScript = this.generateValidateScript(config);
308
+ await this.fileSystem.WriteText(scriptPath, setupScript);
309
+ const validateScript = platform === 'postgresql' ? GeneratePostgresValidateScript(config) : this.generateValidateScript(config);
67
310
  const validatePath = path.join(context.Dir, 'mj-db-validate.sql');
68
311
  await this.fileSystem.WriteText(validatePath, validateScript);
312
+ const scriptsGenerated = [scriptPath, validatePath];
69
313
  emitter.Emit('log', {
70
314
  Type: 'log',
71
- Level: 'info',
315
+ Level: 'verbose',
72
316
  Message: `SQL scripts saved to:\n - ${scriptPath}\n - ${validatePath}`,
73
317
  });
74
- // Step 2: Prompt user to execute the script
75
- if (!context.Yes) {
76
- await this.promptForScriptExecution(emitter, scriptPath);
77
- }
78
- else {
79
- emitter.Emit('warn', {
80
- Type: 'warn',
81
- Phase: 'database',
82
- Message: 'Non-interactive mode: skipping SQL script execution prompt. Run mj-db-setup.sql manually if needed.',
83
- });
84
- }
85
- // Step 3: Validate connectivity
318
+ // Step 2: Make sure the server is reachable (a TCP check; no credentials are sent).
319
+ // Resolution order matches PreflightPhase.checkSqlConnectivity:
320
+ // 1. .env in context.Dir (when present) — this is what the app will actually use.
321
+ // 2. Explicit config.DatabaseHost / DatabasePort.
322
+ // 3. Defaults (localhost and the platform's default port).
86
323
  emitter.Emit('step:progress', {
87
324
  Type: 'step:progress',
88
325
  Phase: 'database',
89
326
  Message: 'Validating database connectivity...',
90
327
  });
91
- // Resolution order matches PreflightPhase.checkSqlConnectivity:
92
- // 1. .env in context.Dir (when present) — this is what the app will actually use.
93
- // 2. Explicit config.DatabaseHost / DatabasePort.
94
- // 3. Defaults (localhost:1433).
95
328
  const envValues = await this.readEnvDbTarget(context.Dir);
96
329
  const host = envValues?.host ?? config.DatabaseHost ?? 'localhost';
97
- const port = envValues?.port ?? config.DatabasePort ?? 1433;
98
- const connectivity = await this.sqlAdapter.CheckConnectivity(host, port);
330
+ const port = envValues?.port ?? config.DatabasePort ?? labels.DefaultPort;
331
+ const connectivity = platform === 'postgresql'
332
+ ? await this.pgAdapter.CheckConnectivity(host, port)
333
+ : await this.sqlAdapter.CheckConnectivity(host, port);
99
334
  if (!connectivity.Reachable) {
100
- throw new InstallerError('database', 'DB_UNREACHABLE', `Cannot connect to SQL Server at ${host}:${port}. ${connectivity.ErrorMessage ?? ''}`, `Ensure SQL Server is running and accessible. Then run the setup script: ${scriptPath}`);
335
+ throw new InstallerError('database', 'DB_UNREACHABLE', `Cannot connect to ${labels.Server} at ${host}:${port}. ${connectivity.ErrorMessage ?? ''}`, `Ensure ${labels.Server} is running and reachable from this machine, then run the install again.`);
336
+ }
337
+ emitter.Emit('log', {
338
+ Type: 'log',
339
+ Level: 'verbose',
340
+ Message: `${labels.Server} reachable at ${host}:${port} (${connectivity.LatencyMs}ms).`,
341
+ });
342
+ // Step 3: Is the database already set up?
343
+ const server = { Platform: platform, Host: host, Port: port, TrustServerCertificate: config.DatabaseTrustCert ?? false };
344
+ const dbName = config.DatabaseName ?? 'MemberJunction';
345
+ const before = await this.checkProvisioned(server, config);
346
+ if (before.Status === 'ready') {
347
+ emitter.Emit('log', {
348
+ Type: 'log',
349
+ Level: 'info',
350
+ Message: `Database "${dbName}" is already set up; the CodeGen and API logins both sign in.`,
351
+ });
352
+ return { ScriptsGenerated: scriptsGenerated, ValidationPassed: true, SetupScriptExecuted: false };
353
+ }
354
+ if (before.Status === 'unknown') {
355
+ emitter.Emit('warn', {
356
+ Type: 'warn',
357
+ Phase: 'database',
358
+ Message: `Could not check whether database "${dbName}" is set up: ${before.Detail}. Continuing; if it is not set up, run ${scriptPath} as ${labels.AdminArticle}.`,
359
+ });
360
+ return { ScriptsGenerated: scriptsGenerated, ValidationPassed: false, SetupScriptExecuted: false };
101
361
  }
362
+ // Step 4: Set it up — automatically with an administrator login, or by hand.
363
+ emitter.Emit('log', {
364
+ Type: 'log',
365
+ Level: 'verbose',
366
+ Message: `Database "${dbName}" is not set up yet: ${before.Detail}.`,
367
+ });
368
+ const admin = await this.resolveAdminCredentials(context, server, dbName, scriptPath);
369
+ if (admin) {
370
+ if (platform === 'postgresql') {
371
+ await this.runPostgresSetup(server, admin, pgSteps, scriptPath, emitter);
372
+ }
373
+ else {
374
+ await this.runSetupScript(server, admin, setupScript, scriptPath, emitter);
375
+ }
376
+ }
377
+ else if (context.Yes) {
378
+ throw new InstallerError('database', 'DB_NOT_SET_UP', `Database "${dbName}" is not set up: ${before.Detail}.`, `Set MJ_INSTALL_DB_ADMIN_USER and MJ_INSTALL_DB_ADMIN_PASSWORD to ${labels.AdminRequirement} and the installer will set it up, or run ${scriptPath} as ${labels.AdminArticle}. Then run the install again.`);
379
+ }
380
+ else {
381
+ await this.promptForScriptExecution(emitter, scriptPath, labels);
382
+ }
383
+ // Step 5: Confirm both logins now work.
384
+ const after = await this.checkProvisioned(server, config);
385
+ if (after.Status === 'ready') {
386
+ emitter.Emit('log', {
387
+ Type: 'log',
388
+ Level: 'info',
389
+ Message: `Database "${dbName}" is set up; the CodeGen and API logins both sign in.`,
390
+ });
391
+ return { ScriptsGenerated: scriptsGenerated, ValidationPassed: true, SetupScriptExecuted: admin !== null };
392
+ }
393
+ if (after.Status === 'unknown') {
394
+ emitter.Emit('warn', {
395
+ Type: 'warn',
396
+ Phase: 'database',
397
+ Message: `Could not confirm the database setup: ${after.Detail}. Continuing.`,
398
+ });
399
+ return { ScriptsGenerated: scriptsGenerated, ValidationPassed: false, SetupScriptExecuted: admin !== null };
400
+ }
401
+ throw new InstallerError('database', admin ? 'DB_SETUP_FAILED' : 'DB_NOT_SET_UP', `Database "${dbName}" is still not usable after setup: ${after.Detail}.`, `Check the output of ${scriptPath} (run it ${labels.ManualTool} as ${labels.AdminArticle}), then run the install again.`);
402
+ }
403
+ // ---------------------------------------------------------------------------
404
+ // Setup check and execution
405
+ // ---------------------------------------------------------------------------
406
+ /**
407
+ * Sign in once with the platform's adapter. SQL Server results are passed
408
+ * through unchanged; PostgreSQL results are mapped to the same shape.
409
+ */
410
+ async tryLogin(server, database, user, password) {
411
+ if (server.Platform === 'postgresql') {
412
+ const result = await this.pgAdapter.TryLogin({ Host: server.Host, Port: server.Port, Database: database, User: user, Password: password });
413
+ return { Ok: result.Ok, LoginRejected: result.LoginRejected, ErrorMessage: result.ErrorMessage };
414
+ }
415
+ return this.sqlAdapter.TryLogin({
416
+ Host: server.Host,
417
+ Port: server.Port,
418
+ TrustServerCertificate: server.TrustServerCertificate,
419
+ Database: database,
420
+ User: user,
421
+ Password: password,
422
+ });
423
+ }
424
+ /**
425
+ * Sign in to the target database as the CodeGen login and then the API login.
426
+ * A login the server refuses means setup has not run; any other failure means
427
+ * the check could not tell.
428
+ */
429
+ async checkProvisioned(server, config) {
430
+ const database = config.DatabaseName ?? 'MemberJunction';
431
+ const logins = [
432
+ { Role: 'CodeGen', User: config.CodeGenUser ?? 'MJ_CodeGen', Password: config.CodeGenPassword ?? '' },
433
+ { Role: 'API', User: config.APIUser ?? 'MJ_Connect', Password: config.APIPassword ?? '' },
434
+ ];
435
+ for (const login of logins) {
436
+ const result = await this.tryLogin(server, database, login.User, login.Password);
437
+ if (result.Ok)
438
+ continue;
439
+ const detail = `the ${login.Role} login "${login.User}" cannot sign in to "${database}" (${result.ErrorMessage ?? 'no detail'})`;
440
+ return result.LoginRejected ? { Status: 'not-set-up', Detail: detail } : { Status: 'unknown', Detail: detail };
441
+ }
442
+ return { Status: 'ready' };
443
+ }
444
+ /**
445
+ * Find an administrator login to run the setup script with: from config or
446
+ * `MJ_INSTALL_DB_ADMIN_*` first; otherwise, interactively, by asking. The login
447
+ * is checked against the server's maintenance database (`master` / `postgres`)
448
+ * before it is used. Returns `null` when the user chooses to run the script
449
+ * themselves, or when nothing is configured in non-interactive mode.
450
+ */
451
+ async resolveAdminCredentials(context, server, dbName, scriptPath) {
452
+ const { Config: config, Emitter: emitter } = context;
453
+ const labels = PLATFORM_LABELS[server.Platform];
454
+ if (config.DatabaseAdminUser && config.DatabaseAdminPassword !== undefined) {
455
+ const configured = { User: config.DatabaseAdminUser, Password: config.DatabaseAdminPassword };
456
+ const result = await this.tryLogin(server, labels.MaintenanceDatabase, configured.User, configured.Password);
457
+ if (result.Ok)
458
+ return configured;
459
+ throw new InstallerError('database', 'DB_ADMIN_LOGIN_FAILED', `The administrator login "${configured.User}" could not sign in: ${result.ErrorMessage ?? 'no detail'}.`, `Check DatabaseAdminUser / DatabaseAdminPassword (or MJ_INSTALL_DB_ADMIN_USER / MJ_INSTALL_DB_ADMIN_PASSWORD), or run ${scriptPath} as ${labels.AdminArticle}.`);
460
+ }
461
+ if (context.Yes)
462
+ return null;
463
+ const method = await this.prompt(emitter, {
464
+ PromptId: 'db-setup-method',
465
+ PromptType: 'select',
466
+ Message: `Database "${dbName}" is not set up yet. How should it be set up?`,
467
+ Choices: [
468
+ { Label: `Set it up now (you will be asked for ${labels.AdminExample})`, Value: 'auto' },
469
+ { Label: `I'll run ${path.basename(scriptPath)} myself`, Value: 'manual' },
470
+ ],
471
+ Default: 'auto',
472
+ });
473
+ if (method !== 'auto')
474
+ return null;
475
+ for (let attempt = 1; attempt <= ADMIN_LOGIN_ATTEMPTS; attempt++) {
476
+ const user = await this.prompt(emitter, {
477
+ PromptId: 'db-admin-user',
478
+ PromptType: 'input',
479
+ Message: labels.AdminPrompt,
480
+ Default: config.DatabaseAdminUser ?? labels.DefaultAdminUser,
481
+ });
482
+ const password = await this.prompt(emitter, {
483
+ PromptId: 'db-admin-password',
484
+ PromptType: 'password',
485
+ Message: `Password for ${user}:`,
486
+ });
487
+ const result = await this.tryLogin(server, labels.MaintenanceDatabase, user, password);
488
+ if (result.Ok)
489
+ return { User: user, Password: password };
490
+ emitter.Emit('warn', {
491
+ Type: 'warn',
492
+ Phase: 'database',
493
+ Message: `"${user}" could not sign in: ${result.ErrorMessage ?? 'no detail'}`,
494
+ });
495
+ }
496
+ throw new InstallerError('database', 'DB_ADMIN_LOGIN_FAILED', `No administrator login could sign in after ${ADMIN_LOGIN_ATTEMPTS} attempts.`, `Run ${scriptPath} as ${labels.AdminArticle}, then run the install again.`);
497
+ }
498
+ /** Run the SQL Server setup script batch by batch as the administrator login. */
499
+ async runSetupScript(server, admin, setupScript, scriptPath, emitter) {
500
+ emitter.Emit('log', {
501
+ Type: 'log',
502
+ Level: 'info',
503
+ Message: `Setting up the database as "${admin.User}" (running ${path.basename(scriptPath)})...`,
504
+ });
505
+ try {
506
+ await this.sqlAdapter.ExecuteBatches({
507
+ Host: server.Host,
508
+ Port: server.Port,
509
+ TrustServerCertificate: server.TrustServerCertificate,
510
+ Database: 'master',
511
+ User: admin.User,
512
+ Password: admin.Password,
513
+ }, SplitSqlBatches(setupScript), (message) => emitter.Emit('log', { Type: 'log', Level: 'verbose', Message: ` ${message}` }));
514
+ }
515
+ catch (err) {
516
+ const where = err instanceof SqlBatchError ? ` (batch ${err.BatchNumber})` : '';
517
+ throw new InstallerError('database', 'DB_SETUP_FAILED', `${path.basename(scriptPath)} failed${where}: ${err instanceof Error ? err.message : String(err)}`, `Make sure "${admin.User}" can create databases and logins, or run ${scriptPath} yourself as a SQL administrator. Then run the install again.`);
518
+ }
519
+ }
520
+ /**
521
+ * Run the PostgreSQL setup as the administrator login: the same ordered
522
+ * statements written to `mj-db-setup.sql`, each sent on its own (never a
523
+ * split script), in the maintenance database first and then in the MJ database.
524
+ */
525
+ async runPostgresSetup(server, admin, steps, scriptPath, emitter) {
102
526
  emitter.Emit('log', {
103
527
  Type: 'log',
104
528
  Level: 'info',
105
- Message: `SQL Server reachable at ${host}:${port} (${connectivity.LatencyMs}ms). This is a TCP check only — credentials and TLS are first exercised by the migrate phase.`,
529
+ Message: `Setting up the database as "${admin.User}" (running the statements in ${path.basename(scriptPath)})...`,
106
530
  });
107
- return {
108
- ScriptsGenerated: [scriptPath, validatePath],
109
- ValidationPassed: true,
110
- };
531
+ try {
532
+ await this.pgAdapter.ExecuteSteps({ Host: server.Host, Port: server.Port, User: admin.User, Password: admin.Password }, steps, (message) => emitter.Emit('log', { Type: 'log', Level: 'verbose', Message: ` ${message}` }));
533
+ }
534
+ catch (err) {
535
+ const where = err instanceof PgStepError ? ` (step ${err.StepNumber}: ${err.StepDescription})` : '';
536
+ throw new InstallerError('database', 'DB_SETUP_FAILED', `${path.basename(scriptPath)} failed${where}: ${err instanceof Error ? err.message : String(err)}`, `Make sure "${admin.User}" is a PostgreSQL superuser (or can create databases and roles), or run ${scriptPath} yourself with psql as a PostgreSQL superuser. Then run the install again.`);
537
+ }
111
538
  }
112
539
  // ---------------------------------------------------------------------------
113
540
  // SQL script generation
@@ -132,13 +559,13 @@ export class DatabaseProvisionPhase {
132
559
  loginBlock(user, password) {
133
560
  if (this.isBuiltInSysadmin(user)) {
134
561
  return `-- Skipping CREATE LOGIN [${user}] — sa is a built-in sysadmin and already exists in every SQL Server instance.
135
- PRINT 'Skipped CREATE LOGIN: ${user} (built-in sysadmin)';
562
+ PRINT 'Skipped CREATE LOGIN: ${EscapeSqlString(user)} (built-in sysadmin)';
136
563
  GO`;
137
564
  }
138
- return `IF NOT EXISTS (SELECT 1 FROM sys.server_principals WHERE name = '${user}')
565
+ return `IF NOT EXISTS (SELECT 1 FROM sys.server_principals WHERE name = '${EscapeSqlString(user)}')
139
566
  BEGIN
140
- CREATE LOGIN [${user}] WITH PASSWORD = '${password}';
141
- PRINT 'Created login: ${user}';
567
+ CREATE LOGIN ${QuoteSqlIdentifier(user)} WITH PASSWORD = N'${EscapeSqlString(password)}';
568
+ PRINT 'Created login: ${EscapeSqlString(user)}';
142
569
  END
143
570
  GO`;
144
571
  }
@@ -147,13 +574,13 @@ GO`;
147
574
  if (this.isBuiltInSysadmin(user)) {
148
575
  return `-- Skipping CREATE USER [${user}] — SQL Server rejects \`CREATE USER FOR LOGIN [sa]\` with Msg 15405 (special principal).
149
576
  -- sa already has implicit sysadmin permissions in every database; no user-mapping is required.
150
- PRINT 'Skipped CREATE USER: ${user} (built-in sysadmin)';
577
+ PRINT 'Skipped CREATE USER: ${EscapeSqlString(user)} (built-in sysadmin)';
151
578
  GO`;
152
579
  }
153
- return `IF NOT EXISTS (SELECT 1 FROM sys.database_principals WHERE name = '${user}')
580
+ return `IF NOT EXISTS (SELECT 1 FROM sys.database_principals WHERE name = '${EscapeSqlString(user)}')
154
581
  BEGIN
155
- CREATE USER [${user}] FOR LOGIN [${user}];
156
- PRINT 'Created user: ${user}';
582
+ CREATE USER ${QuoteSqlIdentifier(user)} FOR LOGIN ${QuoteSqlIdentifier(user)};
583
+ PRINT 'Created user: ${EscapeSqlString(user)}';
157
584
  END
158
585
  GO`;
159
586
  }
@@ -166,10 +593,10 @@ GO`;
166
593
  return `IF NOT EXISTS (SELECT 1 FROM sys.database_role_members rm
167
594
  JOIN sys.database_principals rp ON rm.role_principal_id = rp.principal_id
168
595
  JOIN sys.database_principals mp ON rm.member_principal_id = mp.principal_id
169
- WHERE rp.name = '${role}' AND mp.name = '${user}')
596
+ WHERE rp.name = '${role}' AND mp.name = '${EscapeSqlString(user)}')
170
597
  BEGIN
171
- ALTER ROLE ${role} ADD MEMBER [${user}];
172
- PRINT 'Granted ${role} to ${user}';
598
+ ALTER ROLE ${role} ADD MEMBER ${QuoteSqlIdentifier(user)};
599
+ PRINT 'Granted ${role} to ${EscapeSqlString(user)}';
173
600
  END
174
601
  GO`;
175
602
  }
@@ -179,7 +606,7 @@ GO`;
179
606
  return `-- Skipping GRANT EXECUTE TO [${user}] — sa is sysadmin and has EXECUTE permission implicitly.
180
607
  GO`;
181
608
  }
182
- return `GRANT EXECUTE TO [${user}];
609
+ return `GRANT EXECUTE TO ${QuoteSqlIdentifier(user)};
183
610
  GO`;
184
611
  }
185
612
  /**
@@ -193,12 +620,12 @@ GO`;
193
620
  */
194
621
  validateUserBlock(user) {
195
622
  if (this.isBuiltInSysadmin(user)) {
196
- return `PRINT '[PASS] User ${user} is a built-in sysadmin (maps to dbo; no database principal expected)';`;
623
+ return `PRINT '[PASS] User ${EscapeSqlString(user)} is a built-in sysadmin (maps to dbo; no database principal expected)';`;
197
624
  }
198
- return `IF EXISTS (SELECT 1 FROM sys.database_principals WHERE name = '${user}')
199
- PRINT '[PASS] User ${user} exists';
625
+ return `IF EXISTS (SELECT 1 FROM sys.database_principals WHERE name = '${EscapeSqlString(user)}')
626
+ PRINT '[PASS] User ${EscapeSqlString(user)} exists';
200
627
  ELSE
201
- PRINT '[FAIL] User ${user} NOT found';`;
628
+ PRINT '[FAIL] User ${EscapeSqlString(user)} NOT found';`;
202
629
  }
203
630
  generateSetupScript(config) {
204
631
  const dbName = config.DatabaseName ?? 'MemberJunction';
@@ -216,16 +643,16 @@ ELSE
216
643
  --============================================================================
217
644
  -- 1. Create database (if not exists)
218
645
  --============================================================================
219
- IF NOT EXISTS (SELECT 1 FROM sys.databases WHERE name = '${dbName}')
646
+ IF NOT EXISTS (SELECT 1 FROM sys.databases WHERE name = '${EscapeSqlString(dbName)}')
220
647
  BEGIN
221
- CREATE DATABASE [${dbName}];
222
- PRINT 'Created database: ${dbName}';
648
+ CREATE DATABASE ${QuoteSqlIdentifier(dbName)};
649
+ PRINT 'Created database: ${EscapeSqlString(dbName)}';
223
650
  END
224
651
  ELSE
225
- PRINT 'Database already exists: ${dbName}';
652
+ PRINT 'Database already exists: ${EscapeSqlString(dbName)}';
226
653
  GO
227
654
 
228
- USE [${dbName}];
655
+ USE ${QuoteSqlIdentifier(dbName)};
229
656
  GO
230
657
 
231
658
  --============================================================================
@@ -251,7 +678,7 @@ ${this.loginBlock(apiUser, apiPassword)}
251
678
  --============================================================================
252
679
  -- 4. Create database users
253
680
  --============================================================================
254
- USE [${dbName}];
681
+ USE ${QuoteSqlIdentifier(dbName)};
255
682
  GO
256
683
 
257
684
  ${this.userBlock(codeGenUser)}
@@ -273,9 +700,9 @@ ${this.grantExecuteBlock(apiUser)}
273
700
 
274
701
  PRINT '';
275
702
  PRINT '=== MemberJunction database setup complete ===';
276
- PRINT 'Database: ${dbName}';
277
- PRINT 'CodeGen user: ${codeGenUser}';
278
- PRINT 'API user: ${apiUser}';
703
+ PRINT 'Database: ${EscapeSqlString(dbName)}';
704
+ PRINT 'CodeGen user: ${EscapeSqlString(codeGenUser)}';
705
+ PRINT 'API user: ${EscapeSqlString(apiUser)}';
279
706
  `;
280
707
  }
281
708
  generateValidateScript(config) {
@@ -286,10 +713,10 @@ PRINT 'API user: ${apiUser}';
286
713
  -- Generated by MJ Installer
287
714
  -- Run this to verify the database setup is correct.
288
715
 
289
- USE [${dbName}];
716
+ USE ${QuoteSqlIdentifier(dbName)};
290
717
  GO
291
718
 
292
- PRINT 'Checking database: ${dbName}';
719
+ PRINT 'Checking database: ${EscapeSqlString(dbName)}';
293
720
  PRINT '';
294
721
 
295
722
  -- Check __mj schema
@@ -310,16 +737,18 @@ PRINT '=== Validation complete ===';
310
737
  // ---------------------------------------------------------------------------
311
738
  // Prompt helper
312
739
  // ---------------------------------------------------------------------------
313
- async promptForScriptExecution(emitter, scriptPath) {
314
- await new Promise((resolve) => {
315
- emitter.Emit('prompt', {
316
- Type: 'prompt',
317
- PromptId: 'run-db-script',
318
- PromptType: 'confirm',
319
- Message: `Please run "${scriptPath}" in SSMS or Azure Data Studio, then confirm to continue.`,
320
- Default: 'yes',
321
- Resolve: resolve,
322
- });
740
+ async promptForScriptExecution(emitter, scriptPath, labels) {
741
+ await this.prompt(emitter, {
742
+ PromptId: 'run-db-script',
743
+ PromptType: 'confirm',
744
+ Message: `Please run "${scriptPath}" ${labels.ManualTool} as ${labels.AdminArticle}, then confirm to continue.`,
745
+ Default: 'yes',
746
+ });
747
+ }
748
+ /** Emit a prompt event and wait for the frontend's answer. */
749
+ prompt(emitter, prompt) {
750
+ return new Promise((resolve) => {
751
+ emitter.Emit('prompt', { Type: 'prompt', ...prompt, Resolve: resolve });
323
752
  });
324
753
  }
325
754
  /**