firebase-tools-with-isolate 13.9.0 → 13.11.2

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 (35) hide show
  1. package/lib/commands/dataconnect-sdk-generate.js +15 -9
  2. package/lib/commands/dataconnect-services-list.js +1 -7
  3. package/lib/commands/dataconnect-sql-migrate.js +0 -1
  4. package/lib/crashlytics/buildToolsJarHelper.js +2 -1
  5. package/lib/dataconnect/build.js +1 -9
  6. package/lib/dataconnect/client.js +14 -22
  7. package/lib/dataconnect/errors.js +17 -9
  8. package/lib/dataconnect/graphqlError.js +6 -3
  9. package/lib/dataconnect/names.js +21 -1
  10. package/lib/dataconnect/provisionCloudSql.js +37 -20
  11. package/lib/dataconnect/schemaMigration.js +98 -66
  12. package/lib/deploy/dataconnect/deploy.js +1 -0
  13. package/lib/deploy/dataconnect/release.js +0 -1
  14. package/lib/deploy/functions/prepare.js +1 -1
  15. package/lib/deploy/functions/runtimes/discovery/index.js +2 -1
  16. package/lib/deploy/functions/runtimes/supported/types.js +6 -0
  17. package/lib/emulator/controller.js +4 -3
  18. package/lib/emulator/dataconnectEmulator.js +69 -27
  19. package/lib/emulator/download.js +4 -0
  20. package/lib/emulator/downloadableEmulators.js +51 -24
  21. package/lib/emulator/portUtils.js +11 -2
  22. package/lib/emulator/storage/rules/runtime.js +1 -1
  23. package/lib/frameworks/angular/utils.js +8 -3
  24. package/lib/frameworks/next/utils.js +0 -1
  25. package/lib/gcp/cloudsql/cloudsqladmin.js +15 -2
  26. package/lib/gcp/cloudsql/connect.js +6 -6
  27. package/lib/init/features/dataconnect/index.js +171 -109
  28. package/lib/rc.js +1 -3
  29. package/lib/requireAuth.js +3 -0
  30. package/lib/track.js +29 -2
  31. package/package.json +3 -3
  32. package/schema/firebase-config.json +2 -0
  33. package/templates/init/dataconnect/dataconnect.yaml +1 -1
  34. package/templates/init/dataconnect/mutations.gql +1 -1
  35. package/templates/init/dataconnect/queries.gql +6 -6
@@ -20,16 +20,22 @@ exports.command = new command_1.Command("dataconnect:sdk:generate")
20
20
  configDir = path.resolve(path.join(cwd), configDir);
21
21
  }
22
22
  const serviceInfo = await (0, load_1.load)(projectId, service.location, configDir);
23
- const args = {
24
- projectId,
25
- configDir,
26
- auto_download: true,
27
- rc: options.rc,
28
- locationId: service.location,
29
- };
30
- const dataconnectEmulator = new dataconnectEmulator_1.DataConnectEmulator(args);
23
+ const hasGeneratables = serviceInfo.connectorInfo.some((c) => {
24
+ return (c.connectorYaml.generate?.javascriptSdk ||
25
+ c.connectorYaml.generate?.kotlinSdk ||
26
+ c.connectorYaml.generate?.swiftSdk);
27
+ });
28
+ if (!hasGeneratables) {
29
+ logger_1.logger.warn("No generated SDKs have been declared in connector.yaml files.");
30
+ logger_1.logger.warn("See https://firebase.google.com/docs/data-connect/quickstart#configure-sdk-outputs for examples of how to configure generated SDKs.");
31
+ return;
32
+ }
31
33
  for (const conn of serviceInfo.connectorInfo) {
32
- const output = await dataconnectEmulator.generate(conn.connectorYaml.connectorId);
34
+ const output = await dataconnectEmulator_1.DataConnectEmulator.generate({
35
+ configDir,
36
+ locationId: service.location,
37
+ connectorId: conn.connectorYaml.connectorId,
38
+ });
33
39
  logger_1.logger.info(output);
34
40
  logger_1.logger.info(`Generated SDKs for ${conn.connectorYaml.connectorId}`);
35
41
  }
@@ -33,17 +33,11 @@ exports.command = new command_1.Command("dataconnect:services:list")
33
33
  });
34
34
  const jsonOutput = { services: [] };
35
35
  for (const service of services) {
36
- let schema = {
36
+ const schema = (await client.getSchema(service.name)) ?? {
37
37
  name: "",
38
38
  primaryDatasource: {},
39
39
  source: { files: [] },
40
40
  };
41
- try {
42
- schema = await client.getSchema(service.name);
43
- }
44
- catch (err) {
45
- logger_1.logger.debug(`Error fetching schema: ${err}`);
46
- }
47
41
  const connectors = await client.listConnectors(service.name);
48
42
  const serviceName = names.parseServiceName(service.name);
49
43
  const instanceName = schema?.primaryDatasource.postgresql?.cloudSql.instance ?? "";
@@ -32,7 +32,6 @@ exports.command = new command_1.Command("dataconnect:sql:migrate [serviceId]")
32
32
  const diffs = await (0, schemaMigration_1.migrateSchema)({
33
33
  options,
34
34
  schema: serviceInfo.schema,
35
- allowNonInteractiveMigration: true,
36
35
  validateOnly: true,
37
36
  });
38
37
  if (diffs.length) {
@@ -12,10 +12,11 @@ const rimraf = require("rimraf");
12
12
  const utils = require("../utils");
13
13
  const JAR_CACHE_DIR = process.env.FIREBASE_CRASHLYTICS_BUILDTOOLS_PATH ||
14
14
  path.join(os.homedir(), ".cache", "firebase", "crashlytics", "buildtools");
15
- const JAR_VERSION = "2.9.2";
15
+ const JAR_VERSION = "3.0.0";
16
16
  const JAR_URL = `https://dl.google.com/android/maven2/com/google/firebase/firebase-crashlytics-buildtools/${JAR_VERSION}/firebase-crashlytics-buildtools-${JAR_VERSION}.jar`;
17
17
  async function fetchBuildtoolsJar() {
18
18
  if (process.env.CRASHLYTICS_LOCAL_JAR) {
19
+ logger_1.logger.debug(`Using local Crashlytics Jar override at ${process.env.CRASHLYTICS_LOCAL_JAR}`);
19
20
  return process.env.CRASHLYTICS_LOCAL_JAR;
20
21
  }
21
22
  const jarPath = path.join(JAR_CACHE_DIR, `crashlytics-buildtools-${JAR_VERSION}.jar`);
@@ -5,15 +5,7 @@ const dataconnectEmulator_1 = require("../emulator/dataconnectEmulator");
5
5
  const error_1 = require("../error");
6
6
  const graphqlError_1 = require("./graphqlError");
7
7
  async function build(options, configDir) {
8
- const projectId = options.project ?? "demo-test";
9
- const args = {
10
- projectId,
11
- configDir,
12
- auto_download: true,
13
- rc: options.rc,
14
- };
15
- const dataconnectEmulator = new dataconnectEmulator_1.DataConnectEmulator(args);
16
- const buildResult = await dataconnectEmulator.build();
8
+ const buildResult = await dataconnectEmulator_1.DataConnectEmulator.build({ configDir });
17
9
  if (buildResult?.errors?.length) {
18
10
  throw new error_1.FirebaseError(`There are errors in your schema and connector files:\n${buildResult.errors.map(graphqlError_1.prettify).join("\n")}`);
19
11
  }
@@ -1,11 +1,10 @@
1
1
  "use strict";
2
2
  Object.defineProperty(exports, "__esModule", { value: true });
3
- exports.upsertConnector = exports.listConnectors = exports.deleteConnector = exports.getConnector = exports.upsertSchema = exports.getSchema = exports.deleteService = exports.createService = exports.listServices = exports.listAllServices = exports.listLocations = void 0;
3
+ exports.upsertConnector = exports.listConnectors = exports.deleteConnector = exports.getConnector = exports.upsertSchema = exports.getSchema = exports.deleteService = exports.createService = exports.listAllServices = exports.listLocations = void 0;
4
4
  const api_1 = require("../api");
5
5
  const apiv2_1 = require("../apiv2");
6
6
  const operationPoller = require("../operation-poller");
7
7
  const types = require("./types");
8
- const logger_1 = require("../logger");
9
8
  const DATACONNECT_API_VERSION = "v1alpha";
10
9
  const dataconnectClient = () => new apiv2_1.Client({
11
10
  urlPrefix: (0, api_1.dataconnectOrigin)(),
@@ -18,25 +17,10 @@ async function listLocations(projectId) {
18
17
  }
19
18
  exports.listLocations = listLocations;
20
19
  async function listAllServices(projectId) {
21
- const locations = await listLocations(projectId);
22
- let services = [];
23
- await Promise.all(locations.map(async (l) => {
24
- try {
25
- const locationServices = await listServices(projectId, l);
26
- services = services.concat(locationServices);
27
- }
28
- catch (err) {
29
- logger_1.logger.debug(`Unable to listServices in ${l}: ${err}`);
30
- }
31
- }));
32
- return services;
33
- }
34
- exports.listAllServices = listAllServices;
35
- async function listServices(projectId, locationId) {
36
- const res = await dataconnectClient().get(`/projects/${projectId}/locations/${locationId}/services`);
20
+ const res = await dataconnectClient().get(`/projects/${projectId}/locations/-/services`);
37
21
  return res.body.services ?? [];
38
22
  }
39
- exports.listServices = listServices;
23
+ exports.listAllServices = listAllServices;
40
24
  async function createService(projectId, locationId, serviceId) {
41
25
  const op = await dataconnectClient().post(`/projects/${projectId}/locations/${locationId}/services`, {
42
26
  name: `projects/${projectId}/locations/${locationId}/services/${serviceId}`,
@@ -54,7 +38,7 @@ async function createService(projectId, locationId, serviceId) {
54
38
  }
55
39
  exports.createService = createService;
56
40
  async function deleteService(projectId, locationId, serviceId) {
57
- const op = await dataconnectClient().delete(`projects/${projectId}/locations/${locationId}/services/${serviceId}?force=true`);
41
+ const op = await dataconnectClient().delete(`projects/${projectId}/locations/${locationId}/services/${serviceId}`);
58
42
  const pollRes = await operationPoller.pollOperation({
59
43
  apiOrigin: (0, api_1.dataconnectOrigin)(),
60
44
  apiVersion: DATACONNECT_API_VERSION,
@@ -64,8 +48,16 @@ async function deleteService(projectId, locationId, serviceId) {
64
48
  }
65
49
  exports.deleteService = deleteService;
66
50
  async function getSchema(serviceName) {
67
- const res = await dataconnectClient().get(`${serviceName}/schemas/${types.SCHEMA_ID}`);
68
- return res.body;
51
+ try {
52
+ const res = await dataconnectClient().get(`${serviceName}/schemas/${types.SCHEMA_ID}`);
53
+ return res.body;
54
+ }
55
+ catch (err) {
56
+ if (err.status !== 404) {
57
+ throw err;
58
+ }
59
+ return undefined;
60
+ }
69
61
  }
70
62
  exports.getSchema = getSchema;
71
63
  async function upsertSchema(schema, validateOnly = false) {
@@ -5,20 +5,23 @@ const INCOMPATIBLE_SCHEMA_ERROR_TYPESTRING = "IncompatibleSqlSchemaError";
5
5
  const PRECONDITION_ERROR_TYPESTRING = "type.googleapis.com/google.rpc.PreconditionFailure";
6
6
  const INCOMPATIBLE_CONNECTOR_TYPE = "INCOMPATIBLE_CONNECTOR";
7
7
  function getIncompatibleSchemaError(err) {
8
- const original = err.context?.body?.error || err.orignal;
9
- if (!original) {
10
- throw err;
8
+ const incompatibles = errorDetails(err, INCOMPATIBLE_SCHEMA_ERROR_TYPESTRING);
9
+ if (incompatibles.length === 0) {
10
+ return undefined;
11
11
  }
12
- const details = original.details;
13
- const incompatibles = details.filter((d) => d["@type"]?.includes(INCOMPATIBLE_SCHEMA_ERROR_TYPESTRING));
14
- return incompatibles[0];
12
+ const incompatible = incompatibles[0];
13
+ const preconditionErrs = errorDetails(err, PRECONDITION_ERROR_TYPESTRING);
14
+ const violationTypes = (incompatible.violationType = preconditionErrs
15
+ .flatMap((preCondErr) => preCondErr.violations)
16
+ .flatMap((viol) => viol.type)
17
+ .filter((type) => type === "INACCESSIBLE_SCHEMA" || type === "INCOMPATIBLE_SCHEMA"));
18
+ incompatible.violationType = violationTypes[0];
19
+ return incompatible;
15
20
  }
16
21
  exports.getIncompatibleSchemaError = getIncompatibleSchemaError;
17
22
  function getInvalidConnectors(err) {
23
+ const preconditionErrs = errorDetails(err, PRECONDITION_ERROR_TYPESTRING);
18
24
  const invalidConns = [];
19
- const original = err.context?.body?.error || err?.orignal;
20
- const details = original?.details;
21
- const preconditionErrs = details?.filter((d) => d["@type"]?.includes(PRECONDITION_ERROR_TYPESTRING));
22
25
  for (const preconditionErr of preconditionErrs) {
23
26
  const incompatibleConnViolation = preconditionErr?.violations?.filter((v) => v.type === INCOMPATIBLE_CONNECTOR_TYPE);
24
27
  const newConns = incompatibleConnViolation?.map((i) => i.subject) ?? [];
@@ -27,3 +30,8 @@ function getInvalidConnectors(err) {
27
30
  return invalidConns;
28
31
  }
29
32
  exports.getInvalidConnectors = getInvalidConnectors;
33
+ function errorDetails(err, ofType) {
34
+ const original = err.context?.body?.error || err?.original;
35
+ const details = original?.details;
36
+ return details?.filter((d) => d["@type"]?.includes(ofType)) || [];
37
+ }
@@ -3,9 +3,12 @@ Object.defineProperty(exports, "__esModule", { value: true });
3
3
  exports.prettify = void 0;
4
4
  function prettify(err) {
5
5
  const message = err.message;
6
- let header = err.extensions.file ?? "";
7
- if (err.locations) {
8
- header += `:${err.locations[0].line}`;
6
+ let header = err.extensions?.file ?? "";
7
+ if (err.locations && err.locations.length) {
8
+ const line = err.locations[0]?.line ?? "";
9
+ if (line) {
10
+ header += `:${line}`;
11
+ }
9
12
  }
10
13
  return header.length ? `${header}: ${message}` : message;
11
14
  }
@@ -1,6 +1,6 @@
1
1
  "use strict";
2
2
  Object.defineProperty(exports, "__esModule", { value: true });
3
- exports.parseConnectorName = exports.parseServiceName = void 0;
3
+ exports.parseCloudSQLInstanceName = exports.parseConnectorName = exports.parseServiceName = void 0;
4
4
  const error_1 = require("../error");
5
5
  const serviceNameRegex = /projects\/(?<projectId>[^\/]+)\/locations\/(?<location>[^\/]+)\/services\/(?<serviceId>[^\/]+)/;
6
6
  function parseServiceName(serviceName) {
@@ -44,3 +44,23 @@ function parseConnectorName(connectorName) {
44
44
  };
45
45
  }
46
46
  exports.parseConnectorName = parseConnectorName;
47
+ const cloudSQLInstanceNameRegex = /projects\/(?<projectId>[^\/]+)\/locations\/(?<location>[^\/]+)\/instances\/(?<instanceId>[^\/]+)/;
48
+ function parseCloudSQLInstanceName(cloudSQLInstanceName) {
49
+ const res = cloudSQLInstanceNameRegex.exec(cloudSQLInstanceName);
50
+ const projectId = res?.groups?.projectId;
51
+ const location = res?.groups?.location;
52
+ const instanceId = res?.groups?.instanceId;
53
+ if (!projectId || !location || !instanceId) {
54
+ throw new error_1.FirebaseError(`${cloudSQLInstanceName} is not a valid cloudSQL instance name`);
55
+ }
56
+ const toString = () => {
57
+ return `projects/${projectId}/locations/${location}/services/${instanceId}`;
58
+ };
59
+ return {
60
+ projectId,
61
+ location,
62
+ instanceId,
63
+ toString,
64
+ };
65
+ }
66
+ exports.parseCloudSQLInstanceName = parseCloudSQLInstanceName;
@@ -1,6 +1,6 @@
1
1
  "use strict";
2
2
  Object.defineProperty(exports, "__esModule", { value: true });
3
- exports.checkInstanceConfig = exports.provisionCloudSql = void 0;
3
+ exports.getUpdateReason = exports.provisionCloudSql = void 0;
4
4
  const cloudSqlAdminClient = require("../gcp/cloudsql/cloudsqladmin");
5
5
  const utils = require("../utils");
6
6
  const checkIam_1 = require("./checkIam");
@@ -9,16 +9,18 @@ const GOOGLE_ML_INTEGRATION_ROLE = "roles/aiplatform.user";
9
9
  const freeTrial_1 = require("./freeTrial");
10
10
  const error_1 = require("../error");
11
11
  async function provisionCloudSql(args) {
12
- let connectionName;
13
- const { projectId, locationId, instanceId, databaseId, enableGoogleMlIntegration, silent } = args;
12
+ let connectionName = "";
13
+ const { projectId, locationId, instanceId, databaseId, enableGoogleMlIntegration, waitForCreation, silent, } = args;
14
14
  try {
15
15
  const existingInstance = await cloudSqlAdminClient.getInstance(projectId, instanceId);
16
16
  silent || utils.logLabeledBullet("dataconnect", `Found existing instance ${instanceId}.`);
17
17
  connectionName = existingInstance?.connectionName || "";
18
- if (!checkInstanceConfig(existingInstance, enableGoogleMlIntegration)) {
18
+ const why = getUpdateReason(existingInstance, enableGoogleMlIntegration);
19
+ if (why) {
19
20
  silent ||
20
21
  utils.logLabeledBullet("dataconnect", `Instance ${instanceId} settings not compatible with Firebase Data Connect. ` +
21
- `Updating instance to enable Cloud IAM authentication and public IP. This may take a few minutes...`);
22
+ `Updating instance. This may take a few minutes...` +
23
+ why);
22
24
  await (0, utils_1.promiseWithSpinner)(() => cloudSqlAdminClient.updateInstanceForDataConnect(existingInstance, enableGoogleMlIntegration), "Updating your instance...");
23
25
  silent || utils.logLabeledBullet("dataconnect", "Instance updated");
24
26
  }
@@ -33,21 +35,32 @@ async function provisionCloudSql(args) {
33
35
  throw new error_1.FirebaseError("Free trial unavailable.");
34
36
  }
35
37
  silent ||
36
- utils.logLabeledBullet("dataconnect", `CloudSQL instance '${instanceId}' not found, creating it. This instance is provided under the terms of the Data Connect free trial ${(0, freeTrial_1.freeTrialTermsLink)()}`);
37
- silent || utils.logLabeledBullet("dataconnect", `This may take while...`);
38
- const newInstance = await (0, utils_1.promiseWithSpinner)(() => cloudSqlAdminClient.createInstance(projectId, locationId, instanceId, enableGoogleMlIntegration), "Creating your instance...");
39
- silent || utils.logLabeledBullet("dataconnect", "Instance created");
40
- connectionName = newInstance?.connectionName || "";
38
+ utils.logLabeledBullet("dataconnect", `CloudSQL instance '${instanceId}' not found, creating it.` +
39
+ `\nThis instance is provided under the terms of the Data Connect free trial ${(0, freeTrial_1.freeTrialTermsLink)()}` +
40
+ `\nMonitor the progress at ${cloudSqlAdminClient.instanceConsoleLink(projectId, instanceId)}`);
41
+ const newInstance = await (0, utils_1.promiseWithSpinner)(() => cloudSqlAdminClient.createInstance(projectId, locationId, instanceId, enableGoogleMlIntegration, waitForCreation), "Creating your instance...");
42
+ if (newInstance) {
43
+ silent || utils.logLabeledBullet("dataconnect", "Instance created");
44
+ connectionName = newInstance?.connectionName || "";
45
+ }
46
+ else {
47
+ silent || utils.logLabeledBullet("dataconnect", "Instance creation process started");
48
+ }
41
49
  }
42
50
  try {
43
51
  await cloudSqlAdminClient.getDatabase(projectId, instanceId, databaseId);
44
52
  silent || utils.logLabeledBullet("dataconnect", `Found existing database ${databaseId}.`);
45
53
  }
46
54
  catch (err) {
47
- silent ||
48
- utils.logLabeledBullet("dataconnect", `Database ${databaseId} not found, creating it now...`);
49
- await cloudSqlAdminClient.createDatabase(projectId, instanceId, databaseId);
50
- silent || utils.logLabeledBullet("dataconnect", `Database ${databaseId} created.`);
55
+ if (err.status === 404) {
56
+ silent ||
57
+ utils.logLabeledBullet("dataconnect", `Database ${databaseId} not found, creating it now...`);
58
+ await cloudSqlAdminClient.createDatabase(projectId, instanceId, databaseId);
59
+ silent || utils.logLabeledBullet("dataconnect", `Database ${databaseId} created.`);
60
+ }
61
+ else {
62
+ silent || utils.logLabeledWarning("dataconnect", `Database ${databaseId} is not accessible.`);
63
+ }
51
64
  }
52
65
  if (enableGoogleMlIntegration) {
53
66
  await (0, checkIam_1.grantRolesToCloudSqlServiceAccount)(projectId, instanceId, [GOOGLE_ML_INTEGRATION_ROLE]);
@@ -55,20 +68,24 @@ async function provisionCloudSql(args) {
55
68
  return connectionName;
56
69
  }
57
70
  exports.provisionCloudSql = provisionCloudSql;
58
- function checkInstanceConfig(instance, requireGoogleMlIntegration) {
71
+ function getUpdateReason(instance, requireGoogleMlIntegration) {
72
+ let reason = "";
59
73
  const settings = instance.settings;
60
74
  if (!settings.ipConfiguration?.ipv4Enabled) {
61
- return false;
75
+ reason += "\n - to enable public IP.";
62
76
  }
63
77
  if (requireGoogleMlIntegration) {
64
78
  if (!settings.enableGoogleMlIntegration) {
65
- return false;
79
+ reason += "\n - to enable Google ML integration.";
66
80
  }
67
81
  if (!settings.databaseFlags?.some((f) => f.name === "cloudsql.enable_google_ml_integration" && f.value === "on")) {
68
- return false;
82
+ reason += "\n - to enable Google ML integration database flag.";
69
83
  }
70
84
  }
71
85
  const isIamEnabled = settings.databaseFlags?.some((f) => f.name === "cloudsql.iam_authentication" && f.value === "on") ?? false;
72
- return isIamEnabled;
86
+ if (!isIamEnabled) {
87
+ reason += "\n - to enable IAM authentication database flag.";
88
+ }
89
+ return reason;
73
90
  }
74
- exports.checkInstanceConfig = checkInstanceConfig;
91
+ exports.getUpdateReason = getUpdateReason;
@@ -14,50 +14,50 @@ const utils_1 = require("../utils");
14
14
  const errors = require("./errors");
15
15
  async function diffSchema(schema) {
16
16
  const { serviceName, instanceName, databaseId } = getIdentifiers(schema);
17
- await ensureServiceIsConnectedToCloudSql(serviceName, instanceName, databaseId);
17
+ await ensureServiceIsConnectedToCloudSql(serviceName, instanceName, databaseId, false);
18
18
  try {
19
19
  await (0, client_1.upsertSchema)(schema, true);
20
+ (0, utils_1.logLabeledSuccess)("dataconnect", `Database schema is up to date.`);
20
21
  }
21
22
  catch (err) {
23
+ if (err.status !== 400) {
24
+ throw err;
25
+ }
22
26
  const invalidConnectors = errors.getInvalidConnectors(err);
27
+ const incompatible = errors.getIncompatibleSchemaError(err);
28
+ if (!incompatible && !invalidConnectors.length) {
29
+ throw err;
30
+ }
23
31
  if (invalidConnectors.length) {
24
32
  displayInvalidConnectors(invalidConnectors);
25
33
  }
26
- const incompatible = errors.getIncompatibleSchemaError(err);
27
34
  if (incompatible) {
28
35
  displaySchemaChanges(incompatible);
29
36
  return incompatible.diffs;
30
37
  }
31
38
  }
32
- (0, utils_1.logLabeledSuccess)("dataconnect", `Database schema is up to date.`);
33
39
  return [];
34
40
  }
35
41
  exports.diffSchema = diffSchema;
36
42
  async function migrateSchema(args) {
37
- const { options, schema, allowNonInteractiveMigration, validateOnly } = args;
43
+ const { options, schema, validateOnly } = args;
38
44
  const { serviceName, instanceId, instanceName, databaseId } = getIdentifiers(schema);
39
- await ensureServiceIsConnectedToCloudSql(serviceName, instanceName, databaseId);
45
+ await ensureServiceIsConnectedToCloudSql(serviceName, instanceName, databaseId, true);
40
46
  try {
41
47
  await (0, client_1.upsertSchema)(schema, validateOnly);
42
48
  logger_1.logger.debug(`Database schema was up to date for ${instanceId}:${databaseId}`);
43
49
  }
44
50
  catch (err) {
51
+ if (err.status !== 400) {
52
+ throw err;
53
+ }
45
54
  const incompatible = errors.getIncompatibleSchemaError(err);
46
55
  const invalidConnectors = errors.getInvalidConnectors(err);
47
56
  if (!incompatible && !invalidConnectors.length) {
48
57
  throw err;
49
58
  }
50
- const shouldDeleteInvalidConnectors = await promptForInvalidConnectorError(options, invalidConnectors, validateOnly);
51
- if (!shouldDeleteInvalidConnectors && invalidConnectors.length) {
52
- const cmd = suggestedCommand(serviceName, invalidConnectors);
53
- throw new error_1.FirebaseError(`Command aborted. Try deploying compatible connectors first with ${clc.bold(cmd)}`);
54
- }
55
- const migrationMode = incompatible
56
- ? await promptForSchemaMigration(options, databaseId, incompatible, allowNonInteractiveMigration)
57
- : "none";
58
- if (migrationMode === "none" && incompatible) {
59
- throw new error_1.FirebaseError("Command aborted.");
60
- }
59
+ const migrationMode = await promptForSchemaMigration(options, databaseId, incompatible, validateOnly);
60
+ const shouldDeleteInvalidConnectors = await promptForInvalidConnectorError(options, serviceName, invalidConnectors, validateOnly);
61
61
  let diffs = [];
62
62
  if (incompatible) {
63
63
  diffs = await handleIncompatibleSchemaError({
@@ -68,10 +68,12 @@ async function migrateSchema(args) {
68
68
  choice: migrationMode,
69
69
  });
70
70
  }
71
- if (invalidConnectors.length) {
71
+ if (shouldDeleteInvalidConnectors) {
72
72
  await deleteInvalidConnectors(invalidConnectors);
73
73
  }
74
- await (0, client_1.upsertSchema)(schema, validateOnly);
74
+ if (!validateOnly) {
75
+ await (0, client_1.upsertSchema)(schema, validateOnly);
76
+ }
75
77
  return diffs;
76
78
  }
77
79
  return [];
@@ -135,16 +137,22 @@ async function handleIncompatibleSchemaError(args) {
135
137
  }
136
138
  return [];
137
139
  }
138
- async function promptForSchemaMigration(options, databaseName, err, allowNonInteractiveMigration) {
140
+ async function promptForSchemaMigration(options, databaseName, err, validateOnly) {
141
+ if (!err) {
142
+ return "none";
143
+ }
139
144
  displaySchemaChanges(err);
140
145
  if (!options.nonInteractive) {
146
+ if (validateOnly && options.force) {
147
+ return "all";
148
+ }
141
149
  const choices = err.destructive
142
150
  ? [
143
151
  { name: "Execute all changes (including destructive changes)", value: "all" },
144
152
  { name: "Abort changes", value: "none" },
145
153
  ]
146
154
  : [
147
- { name: "Execute changes", value: "safe" },
155
+ { name: "Execute changes", value: "all" },
148
156
  { name: "Abort changes", value: "none" },
149
157
  ];
150
158
  return await (0, prompt_1.promptOnce)({
@@ -153,38 +161,42 @@ async function promptForSchemaMigration(options, databaseName, err, allowNonInte
153
161
  choices,
154
162
  });
155
163
  }
156
- else if (!allowNonInteractiveMigration) {
157
- logger_1.logger.error("Your database schema is incompatible with your Data Connect schema. Run `firebase dataconnect:sql:migrate` to migrate your database schema");
158
- return "none";
164
+ if (!validateOnly) {
165
+ throw new error_1.FirebaseError("Command aborted. Your database schema is incompatible with your Data Connect schema. Run `firebase dataconnect:sql:migrate` to migrate your database schema");
159
166
  }
160
167
  else if (options.force) {
161
168
  return "all";
162
169
  }
163
170
  else if (!err.destructive) {
164
- return "safe";
171
+ return "all";
165
172
  }
166
173
  else {
167
- logger_1.logger.error("This schema migration includes potentially destructive changes. If you'd like to execute it anyway, rerun this command with --force");
168
- return "none";
174
+ throw new error_1.FirebaseError("Command aborted. This schema migration includes potentially destructive changes. If you'd like to execute it anyway, rerun this command with --force");
169
175
  }
170
176
  }
171
- async function promptForInvalidConnectorError(options, invalidConnectors, validateOnly) {
177
+ async function promptForInvalidConnectorError(options, serviceName, invalidConnectors, validateOnly) {
172
178
  if (!invalidConnectors.length) {
173
179
  return false;
174
180
  }
175
181
  displayInvalidConnectors(invalidConnectors);
176
182
  if (validateOnly) {
177
- return false;
183
+ if (options.force) {
184
+ return false;
185
+ }
186
+ throw new error_1.FirebaseError(`Command aborted. If you'd like to migrate it anyway, you may override with --force.`);
178
187
  }
179
- else if (options.force ||
180
- (!options.nonInteractive &&
181
- (await (0, prompt_1.confirm)({
182
- ...options,
183
- message: "Would you like to delete and recreate these connectors?",
184
- })))) {
188
+ if (options.force) {
185
189
  return true;
186
190
  }
187
- return false;
191
+ if (!options.nonInteractive &&
192
+ (await (0, prompt_1.confirm)({
193
+ ...options,
194
+ message: `Would you like to delete and recreate these connectors? This will cause ${clc.red(`downtime.`)}.`,
195
+ }))) {
196
+ return true;
197
+ }
198
+ const cmd = suggestedCommand(serviceName, invalidConnectors);
199
+ throw new error_1.FirebaseError(`Command aborted. Try deploying those connectors first with ${clc.bold(cmd)}`);
188
200
  }
189
201
  async function deleteInvalidConnectors(invalidConnectors) {
190
202
  return Promise.all(invalidConnectors.map(client_1.deleteConnector));
@@ -192,39 +204,42 @@ async function deleteInvalidConnectors(invalidConnectors) {
192
204
  function displayInvalidConnectors(invalidConnectors) {
193
205
  const connectorIds = invalidConnectors.map((i) => i.split("/").pop()).join(", ");
194
206
  (0, utils_1.logLabeledWarning)("dataconnect", `The schema you are deploying is incompatible with the following existing connectors: ${connectorIds}.`);
195
- (0, utils_1.logLabeledWarning)("dataconnect", `This is a ${clc.red("breaking")} change and will cause a brief downtime.`);
207
+ (0, utils_1.logLabeledWarning)("dataconnect", `This is a ${clc.red("breaking")} change and may break existing apps.`);
196
208
  }
197
- async function ensureServiceIsConnectedToCloudSql(serviceName, instanceId, databaseId) {
198
- let currentSchema;
199
- try {
200
- currentSchema = await (0, client_1.getSchema)(serviceName);
201
- }
202
- catch (err) {
203
- if (err.status === 404) {
204
- currentSchema = {
205
- name: `${serviceName}/schemas/${types_1.SCHEMA_ID}`,
206
- source: {
207
- files: [],
208
- },
209
- primaryDatasource: {
210
- postgresql: {
211
- database: databaseId,
212
- cloudSql: {
213
- instance: instanceId,
214
- },
209
+ async function ensureServiceIsConnectedToCloudSql(serviceName, instanceId, databaseId, linkIfNotConnected) {
210
+ let currentSchema = await (0, client_1.getSchema)(serviceName);
211
+ if (!currentSchema) {
212
+ if (!linkIfNotConnected) {
213
+ (0, utils_1.logLabeledWarning)("dataconnect", `Not yet linked to the Cloud SQL instance.`);
214
+ return;
215
+ }
216
+ (0, utils_1.logLabeledBullet)("dataconnect", `Linking the Cloud SQL instance...`);
217
+ currentSchema = {
218
+ name: `${serviceName}/schemas/${types_1.SCHEMA_ID}`,
219
+ source: {
220
+ files: [],
221
+ },
222
+ primaryDatasource: {
223
+ postgresql: {
224
+ database: databaseId,
225
+ cloudSql: {
226
+ instance: instanceId,
215
227
  },
216
228
  },
217
- };
218
- }
219
- else {
220
- throw err;
221
- }
229
+ },
230
+ };
231
+ }
232
+ const postgresql = currentSchema.primaryDatasource.postgresql;
233
+ if (postgresql?.cloudSql.instance !== instanceId) {
234
+ (0, utils_1.logLabeledWarning)("dataconnect", `Switching connected Cloud SQL instance\nFrom ${postgresql?.cloudSql.instance}\nTo ${instanceId}`);
222
235
  }
223
- if (!currentSchema.primaryDatasource.postgresql ||
224
- currentSchema.primaryDatasource.postgresql.schemaValidation === "STRICT") {
236
+ if (postgresql?.database !== databaseId) {
237
+ (0, utils_1.logLabeledWarning)("dataconnect", `Switching connected Postgres database from ${postgresql?.database} to ${databaseId}`);
238
+ }
239
+ if (!postgresql || postgresql.schemaValidation === "STRICT") {
225
240
  return;
226
241
  }
227
- currentSchema.primaryDatasource.postgresql.schemaValidation = "STRICT";
242
+ postgresql.schemaValidation = "STRICT";
228
243
  try {
229
244
  await (0, client_1.upsertSchema)(currentSchema, false);
230
245
  }
@@ -236,10 +251,27 @@ async function ensureServiceIsConnectedToCloudSql(serviceName, instanceId, datab
236
251
  }
237
252
  }
238
253
  function displaySchemaChanges(error) {
239
- const message = "Your new schema is incompatible with the schema of your CloudSQL database. " +
240
- "The following SQL statements will migrate your database schema to match your new Data Connect schema.\n" +
241
- error.diffs.map(toString).join("\n");
242
- (0, utils_1.logLabeledWarning)("dataconnect", message);
254
+ switch (error.violationType) {
255
+ case "INCOMPATIBLE_SCHEMA":
256
+ {
257
+ const message = "Your new schema is incompatible with the schema of your CloudSQL database. " +
258
+ "The following SQL statements will migrate your database schema to match your new Data Connect schema.\n" +
259
+ error.diffs.map(toString).join("\n");
260
+ (0, utils_1.logLabeledWarning)("dataconnect", message);
261
+ }
262
+ break;
263
+ case "INACCESSIBLE_SCHEMA":
264
+ {
265
+ const message = "Cannot access your CloudSQL database to validate schema. " +
266
+ "The following SQL statements can setup a new database schema.\n" +
267
+ error.diffs.map(toString).join("\n");
268
+ (0, utils_1.logLabeledWarning)("dataconnect", message);
269
+ (0, utils_1.logLabeledWarning)("dataconnect", "Some SQL resources may already exist.");
270
+ }
271
+ break;
272
+ default:
273
+ throw new error_1.FirebaseError(`Unknown schema violation type: ${error.violationType}, IncompatibleSqlSchemaError: ${error}`);
274
+ }
243
275
  }
244
276
  function toString(diff) {
245
277
  return `\/** ${diff.destructive ? clc.red("Destructive: ") : ""}${diff.description}*\/\n${(0, sql_formatter_1.format)(diff.sql, { language: "postgresql" })}`;
@@ -57,6 +57,7 @@ async function default_1(context, options) {
57
57
  instanceId,
58
58
  databaseId,
59
59
  enableGoogleMlIntegration,
60
+ waitForCreation: true,
60
61
  });
61
62
  }));
62
63
  return;
@@ -21,7 +21,6 @@ async function default_1(context, options) {
21
21
  await (0, schemaMigration_1.migrateSchema)({
22
22
  options,
23
23
  schema: s,
24
- allowNonInteractiveMigration: false,
25
24
  validateOnly: false,
26
25
  });
27
26
  }