@cumulus/db 10.1.1-alpha.0 → 11.0.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/LICENSE ADDED
@@ -0,0 +1,60 @@
1
+ Copyright © 2020 United States Government as represented by the Administrator of the National Aeronautics and Space Administration. All Rights Reserved.
2
+
3
+ Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License.
4
+ You may obtain a copy of the License at
5
+
6
+ http://www.apache.org/licenses/LICE NSE-2.0
7
+
8
+ Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS,
9
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License.
10
+
11
+ ---
12
+
13
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
14
+
15
+ 1. Definitions.
16
+
17
+ "License" shall mean the terms and conditions for use, reproduction, and distribution as defined by Sections 1 through 9 of this document.
18
+
19
+ "Licensor" shall mean the copyright owner or entity authorized by the copyright owner that is granting the License.
20
+
21
+ "Legal Entity" shall mean the union of the acting entity and all other entities that control, are controlled by, or are under common control with that entity. For the purposes of this definition, "control" means (i) the power, direct or indirect, to cause the direction or management of such entity, whether by contract or otherwise, or (ii) ownership of fifty percent (50%) or more of the outstanding shares, or (iii) beneficial ownership of such entity.
22
+
23
+ "You" (or "Your") shall mean an individual or Legal Entity exercising permissions granted by this License.
24
+
25
+ "Source" form shall mean the preferred form for making modifications, including but not limited to software source code, documentation source, and configuration files.
26
+
27
+ "Object" form shall mean any form resulting from mechanical transformation or translation of a Source form, including but not limited to compiled object code, generated documentation, and conversions to other media types.
28
+
29
+ "Work" shall mean the work of authorship, whether in Source or Object form, made available under the License, as indicated by a copyright notice that is included in or attached to the work (an example is provided in the Appendix below).
30
+
31
+ "Derivative Works" shall mean any work, whether in Source or Object form, that is based on (or derived from) the Work and for which the editorial revisions, annotations, elaborations, or other modifications represent, as a whole, an original work of authorship. For the purposes of this License, Derivative Works shall not include works that remain separable from, or merely link (or bind by name) to the interfaces of, the Work and Derivative Works thereof.
32
+
33
+ "Contribution" shall mean any work of authorship, including the original version of the Work and any modifications or additions to that Work or Derivative Works thereof, that is intentionally submitted to Licensor for inclusion in the Work by the copyright owner or by an individual or Legal Entity authorized to submit on behalf of the copyright owner. For the purposes of this definition, "submitted" means any form of electronic, verbal, or written communication sent to the Licensor or its representatives, including but not limited to communication on electronic mailing lists, source code control systems, and issue tracking systems that are managed by, or on behalf of, the Licensor for the purpose of discussing and improving the Work, but excluding communication that is conspicuously marked or otherwise designated in writing by the copyright owner as "Not a Contribution."
34
+
35
+ "Contributor" shall mean Licensor and any individual or Legal Entity on behalf of whom a Contribution has been received by Licensor and subsequently incorporated within the Work.
36
+
37
+ 2. Grant of Copyright License. Subject to the terms and conditions of this License, each Contributor hereby grants to You a perpetual, worldwide, non-exclusive, no-charge, royalty-free, irrevocable copyright license to reproduce, prepare Derivative Works of, publicly display, publicly perform, sublicense, and distribute the Work and such Derivative Works in Source or Object form.
38
+
39
+ 3. Grant of Patent License. Subject to the terms and conditions of this License, each Contributor hereby grants to You a perpetual, worldwide, non-exclusive, no-charge, royalty-free, irrevocable (except as stated in this section) patent license to make, have made, use, offer to sell, sell, import, and otherwise transfer the Work, where such license applies only to those patent claims licensable by such Contributor that are necessarily infringed by their Contribution(s) alone or by combination of their Contribution(s) with the Work to which such Contribution(s) was submitted. If You institute patent litigation against any entity (including a cross-claim or counterclaim in a lawsuit) alleging that the Work or a Contribution incorporated within the Work constitutes direct or contributory patent infringement, then any patent licenses granted to You under this License for that Work shall terminate as of the date such litigation is filed.
40
+
41
+ 4. Redistribution. You may reproduce and distribute copies of the Work or Derivative Works thereof in any medium, with or without modifications, and in Source or Object form, provided that You meet the following conditions:
42
+
43
+ You must give any other recipients of the Work or Derivative Works a copy of this License; and
44
+ You must cause any modified files to carry prominent notices stating that You changed the files; and
45
+ You must retain, in the Source form of any Derivative Works that You distribute, all copyright, patent, trademark, and attribution notices from the Source form of the Work, excluding those notices that do not pertain to any part of the Derivative Works; and
46
+ If the Work includes a "NOTICE" text file as part of its distribution, then any Derivative Works that You distribute must include a readable copy of the attribution notices contained within such NOTICE file, excluding those notices that do not pertain to any part of the Derivative Works, in at least one of the following places: within a NOTICE text file distributed as part of the Derivative Works; within the Source form or documentation, if provided along with the Derivative Works; or, within a display generated by the Derivative Works, if and wherever such third-party notices normally appear. The contents of the NOTICE file are for informational purposes only and do not modify the License. You may add Your own attribution notices within Derivative Works that You distribute, alongside or as an addendum to the NOTICE text from the Work, provided that such additional attribution notices cannot be construed as modifying the License.
47
+
48
+ You may add Your own copyright statement to Your modifications and may provide additional or different license terms and conditions for use, reproduction, or distribution of Your modifications, or for any such Derivative Works as a whole, provided Your use, reproduction, and distribution of the Work otherwise complies with the conditions stated in this License.
49
+
50
+ 5. Submission of Contributions. Unless You explicitly state otherwise, any Contribution intentionally submitted for inclusion in the Work by You to the Licensor shall be under the terms and conditions of this License, without any additional terms or conditions. Notwithstanding the above, nothing herein shall supersede or modify the terms of any separate license agreement you may have executed with Licensor regarding such Contributions.
51
+
52
+ 6. Trademarks. This License does not grant permission to use the trade names, trademarks, service marks, or product names of the Licensor, except as required for reasonable and customary use in describing the origin of the Work and reproducing the content of the NOTICE file.
53
+
54
+ 7. Disclaimer of Warranty. Unless required by applicable law or agreed to in writing, Licensor provides the Work (and each Contributor provides its Contributions) on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied, including, without limitation, any warranties or conditions of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A PARTICULAR PURPOSE. You are solely responsible for determining the appropriateness of using or redistributing the Work and assume any risks associated with Your exercise of permissions under this License.
55
+
56
+ 8. Limitation of Liability. In no event and under no legal theory, whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or agreed to in writing, shall any Contributor be liable to You for damages, including any direct, indirect, special, incidental, or consequential damages of any character arising as a result of this License or out of the use or inability to use the Work (including but not limited to damages for loss of goodwill, work stoppage, computer failure or malfunction, or any and all other commercial damages or losses), even if such Contributor has been advised of the possibility of such damages.
57
+
58
+ 9. Accepting Warranty or Additional Liability. While redistributing the Work or Derivative Works thereof, You may choose to offer, and charge a fee for, acceptance of support, warranty, indemnity, or other liability obligations and/or rights consistent with this License. However, in accepting such obligations, You may act only on Your own behalf and on Your sole responsibility, not on behalf of any other Contributor, and only if You agree to indemnify, defend, and hold each Contributor harmless for any liability incurred by, or claims asserted against, such Contributor by reason of your accepting any such warranty or additional liability.
59
+
60
+ END OF TERMS AND CONDITIONS
package/dist/config.d.ts CHANGED
@@ -8,6 +8,7 @@ export declare const localStackConnectionEnv: {
8
8
  PG_DATABASE: string;
9
9
  PG_PORT: string;
10
10
  };
11
+ export declare const isKnexDebugEnabled: (env?: NodeJS.ProcessEnv) => boolean;
11
12
  export declare const getSecretConnectionConfig: (SecretId: string, secretsManager: AWS.SecretsManager) => Promise<Knex.PgConnectionConfig>;
12
13
  export declare const getConnectionConfigEnv: (env: NodeJS.ProcessEnv) => Knex.PgConnectionConfig;
13
14
  /**
package/dist/config.js CHANGED
@@ -3,7 +3,7 @@ var __importDefault = (this && this.__importDefault) || function (mod) {
3
3
  return (mod && mod.__esModule) ? mod : { "default": mod };
4
4
  };
5
5
  Object.defineProperty(exports, "__esModule", { value: true });
6
- exports.getKnexConfig = exports.getConnectionConfig = exports.getConnectionConfigEnv = exports.getSecretConnectionConfig = exports.localStackConnectionEnv = void 0;
6
+ exports.getKnexConfig = exports.getConnectionConfig = exports.getConnectionConfigEnv = exports.getSecretConnectionConfig = exports.isKnexDebugEnabled = exports.localStackConnectionEnv = void 0;
7
7
  const aws_sdk_1 = __importDefault(require("aws-sdk"));
8
8
  const common_1 = require("@cumulus/common");
9
9
  exports.localStackConnectionEnv = {
@@ -13,6 +13,8 @@ exports.localStackConnectionEnv = {
13
13
  PG_DATABASE: 'postgres',
14
14
  PG_PORT: '5432',
15
15
  };
16
+ const isKnexDebugEnabled = (env = {}) => env.KNEX_DEBUG === 'true';
17
+ exports.isKnexDebugEnabled = isKnexDebugEnabled;
16
18
  const getSecretConnectionConfig = async (SecretId, secretsManager) => {
17
19
  var _a;
18
20
  const response = await secretsManager.getSecretValue({ SecretId }).promise();
@@ -110,7 +112,7 @@ const getKnexConfig = async ({ env = process.env, secretsManager = new aws_sdk_1
110
112
  const knexConfig = {
111
113
  client: 'pg',
112
114
  connection: await (0, exports.getConnectionConfig)({ env, secretsManager }),
113
- debug: env.KNEX_DEBUG === 'true',
115
+ debug: (0, exports.isKnexDebugEnabled)(env),
114
116
  asyncStackTraces: env.KNEX_ASYNC_STACK_TRACES === 'true',
115
117
  pool: {
116
118
  min: 0,
@@ -44,16 +44,37 @@ const log = new logger_1.default({ sender: '@cumulus/db/connection' });
44
44
  * @returns {Promise<Knex>} a Knex configuration object that has returned at least one query
45
45
  */
46
46
  const getKnexClient = async ({ env = process.env, secretsManager = new aws_sdk_1.default.SecretsManager(), knexLogger = log, } = {}) => {
47
+ if ((0, config_1.isKnexDebugEnabled)(env)) {
48
+ knexLogger.info('Initializing connection pool...');
49
+ }
47
50
  const knexConfig = await (0, config_1.getKnexConfig)({ env, secretsManager });
48
51
  const knexClient = (0, knex_1.knex)(knexConfig);
49
- //@ts-ignore
50
- // context is an internal object that isn't typed
51
- // this is needed to force tarn to log per-retry failures
52
- // and allow propagateCreateError to be set `false`
53
- knexClient.context.client.pool.on('createFail', (_, error) => {
54
- knexLogger.warn('knex failed on attempted connection', error);
55
- throw error;
56
- });
52
+ if ((0, config_1.isKnexDebugEnabled)(env)) {
53
+ //@ts-ignore
54
+ // context is an internal object that isn't typed
55
+ // this is needed to force tarn to log per-retry failures
56
+ // and allow propagateCreateError to be set `false`
57
+ knexClient.context.client.pool.on('createFail', (_, error) => {
58
+ knexLogger.warn('knex failed on attempted connection', error);
59
+ throw error;
60
+ });
61
+ //@ts-ignore
62
+ knexClient.context.client.pool.on('createSuccess', (_, resource) => {
63
+ knexLogger.info(`added connection to pool: ${JSON.stringify(resource)}`);
64
+ });
65
+ //@ts-ignore
66
+ knexClient.context.client.pool.on('acquireSuccess', (_, resource) => {
67
+ knexLogger.info(`acquired connection from pool: ${JSON.stringify(resource)}`);
68
+ });
69
+ //@ts-ignore
70
+ knexClient.context.client.pool.on('release', (resource) => {
71
+ knexLogger.info(`released connection from pool: ${JSON.stringify(resource)}`);
72
+ });
73
+ //@ts-ignore
74
+ knexClient.context.client.pool.on('poolDestroySuccess', () => {
75
+ knexLogger.info('pool is destroyed');
76
+ });
77
+ }
57
78
  return knexClient;
58
79
  };
59
80
  exports.getKnexClient = getKnexClient;
package/dist/index.d.ts CHANGED
@@ -20,7 +20,7 @@ export { translateApiAsyncOperationToPostgresAsyncOperation, translatePostgresAs
20
20
  export { translateApiFiletoPostgresFile, translatePostgresFileToApiFile, } from './translate/file';
21
21
  export { translateApiCollectionToPostgresCollection, translatePostgresCollectionToApiCollection, } from './translate/collections';
22
22
  export { translateApiProviderToPostgresProvider, translatePostgresProviderToApiProvider, } from './translate/providers';
23
- export { translateApiRuleToPostgresRule, translatePostgresRuleToApiRule, } from './translate/rules';
23
+ export { translatePostgresRuleToApiRule, translateApiRuleToPostgresRule, translateApiRuleToPostgresRuleRaw, } from './translate/rules';
24
24
  export { translateApiExecutionToPostgresExecution, translatePostgresExecutionToApiExecution, } from './translate/executions';
25
25
  export { translateApiGranuleToPostgresGranule, translatePostgresGranuleToApiGranule, translatePostgresGranuleResultToApiGranule, } from './translate/granules';
26
26
  export { translateApiPdrToPostgresPdr, translatePostgresPdrToApiPdr, } from './translate/pdr';
package/dist/index.js CHANGED
@@ -1,7 +1,11 @@
1
1
  "use strict";
2
2
  var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
3
3
  if (k2 === undefined) k2 = k;
4
- Object.defineProperty(o, k2, { enumerable: true, get: function() { return m[k]; } });
4
+ var desc = Object.getOwnPropertyDescriptor(m, k);
5
+ if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
6
+ desc = { enumerable: true, get: function() { return m[k]; } };
7
+ }
8
+ Object.defineProperty(o, k2, desc);
5
9
  }) : (function(o, m, k, k2) {
6
10
  if (k2 === undefined) k2 = k;
7
11
  o[k2] = m[k];
@@ -19,8 +23,8 @@ var __importStar = (this && this.__importStar) || function (mod) {
19
23
  return result;
20
24
  };
21
25
  Object.defineProperty(exports, "__esModule", { value: true });
22
- exports.getGranuleCollectionId = exports.getApiGranuleExecutionCumulusIds = exports.getApiGranuleCumulusIds = exports.getFilesAndGranuleInfoQuery = exports.getExecutionInfoByGranuleCumulusId = exports.getApiGranuleExecutionCumulusIdsByExecution = exports.getApiExecutionCumulusIds = exports.getWorkflowNameIntersectFromGranuleIds = exports.newestExecutionArnFromGranuleIdWorkflowName = exports.executionArnsFromGranuleIdsAndWorkflowNames = exports.getCollectionsByGranuleIds = exports.translatePostgresPdrToApiPdr = exports.translateApiPdrToPostgresPdr = exports.translatePostgresGranuleResultToApiGranule = exports.translatePostgresGranuleToApiGranule = exports.translateApiGranuleToPostgresGranule = exports.translatePostgresExecutionToApiExecution = exports.translateApiExecutionToPostgresExecution = exports.translatePostgresRuleToApiRule = exports.translateApiRuleToPostgresRule = exports.translatePostgresProviderToApiProvider = exports.translateApiProviderToPostgresProvider = exports.translatePostgresCollectionToApiCollection = exports.translateApiCollectionToPostgresCollection = exports.translatePostgresFileToApiFile = exports.translateApiFiletoPostgresFile = exports.translatePostgresAsyncOperationToApiAsyncOperation = exports.translateApiAsyncOperationToPostgresAsyncOperation = exports.nullifyUndefinedProviderValues = exports.validateProviderHost = exports.migrationDir = exports.TableNames = exports.createRejectableTransaction = exports.localStackConnectionEnv = exports.getKnexConfig = exports.getKnexClient = exports.isCollisionError = exports.generateLocalTestDb = exports.fakeRuleRecordFactory = exports.fakeProviderRecordFactory = exports.fakePdrRecordFactory = exports.fakeGranuleRecordFactory = exports.fakeFileRecordFactory = exports.fakeExecutionRecordFactory = exports.fakeCollectionRecordFactory = exports.fakeAsyncOperationRecordFactory = exports.destroyLocalTestDb = exports.deleteTestDatabase = exports.createTestDatabase = exports.Knex = void 0;
23
- exports.RulePgModel = exports.ProviderPgModel = exports.PdrPgModel = exports.GranulesExecutionsPgModel = exports.GranulePgModel = exports.FilePgModel = exports.ExecutionPgModel = exports.CollectionPgModel = exports.BasePgModel = exports.AsyncOperationPgModel = exports.QuerySearchClient = exports.getGranulesByApiPropertiesQuery = exports.upsertGranuleWithExecutionJoinRecord = exports.getUniqueGranuleByGranuleId = void 0;
26
+ exports.getApiGranuleExecutionCumulusIds = exports.getApiGranuleCumulusIds = exports.getFilesAndGranuleInfoQuery = exports.getExecutionInfoByGranuleCumulusId = exports.getApiGranuleExecutionCumulusIdsByExecution = exports.getApiExecutionCumulusIds = exports.getWorkflowNameIntersectFromGranuleIds = exports.newestExecutionArnFromGranuleIdWorkflowName = exports.executionArnsFromGranuleIdsAndWorkflowNames = exports.getCollectionsByGranuleIds = exports.translatePostgresPdrToApiPdr = exports.translateApiPdrToPostgresPdr = exports.translatePostgresGranuleResultToApiGranule = exports.translatePostgresGranuleToApiGranule = exports.translateApiGranuleToPostgresGranule = exports.translatePostgresExecutionToApiExecution = exports.translateApiExecutionToPostgresExecution = exports.translateApiRuleToPostgresRuleRaw = exports.translateApiRuleToPostgresRule = exports.translatePostgresRuleToApiRule = exports.translatePostgresProviderToApiProvider = exports.translateApiProviderToPostgresProvider = exports.translatePostgresCollectionToApiCollection = exports.translateApiCollectionToPostgresCollection = exports.translatePostgresFileToApiFile = exports.translateApiFiletoPostgresFile = exports.translatePostgresAsyncOperationToApiAsyncOperation = exports.translateApiAsyncOperationToPostgresAsyncOperation = exports.nullifyUndefinedProviderValues = exports.validateProviderHost = exports.migrationDir = exports.TableNames = exports.createRejectableTransaction = exports.localStackConnectionEnv = exports.getKnexConfig = exports.getKnexClient = exports.isCollisionError = exports.generateLocalTestDb = exports.fakeRuleRecordFactory = exports.fakeProviderRecordFactory = exports.fakePdrRecordFactory = exports.fakeGranuleRecordFactory = exports.fakeFileRecordFactory = exports.fakeExecutionRecordFactory = exports.fakeCollectionRecordFactory = exports.fakeAsyncOperationRecordFactory = exports.destroyLocalTestDb = exports.deleteTestDatabase = exports.createTestDatabase = exports.Knex = void 0;
27
+ exports.RulePgModel = exports.ProviderPgModel = exports.PdrPgModel = exports.GranulesExecutionsPgModel = exports.GranulePgModel = exports.FilePgModel = exports.ExecutionPgModel = exports.CollectionPgModel = exports.BasePgModel = exports.AsyncOperationPgModel = exports.QuerySearchClient = exports.getGranulesByApiPropertiesQuery = exports.upsertGranuleWithExecutionJoinRecord = exports.getUniqueGranuleByGranuleId = exports.getGranuleCollectionId = void 0;
24
28
  const path = __importStar(require("path"));
25
29
  var knex_1 = require("knex");
26
30
  Object.defineProperty(exports, "Knex", { enumerable: true, get: function () { return knex_1.Knex; } });
@@ -65,8 +69,9 @@ var providers_1 = require("./translate/providers");
65
69
  Object.defineProperty(exports, "translateApiProviderToPostgresProvider", { enumerable: true, get: function () { return providers_1.translateApiProviderToPostgresProvider; } });
66
70
  Object.defineProperty(exports, "translatePostgresProviderToApiProvider", { enumerable: true, get: function () { return providers_1.translatePostgresProviderToApiProvider; } });
67
71
  var rules_1 = require("./translate/rules");
68
- Object.defineProperty(exports, "translateApiRuleToPostgresRule", { enumerable: true, get: function () { return rules_1.translateApiRuleToPostgresRule; } });
69
72
  Object.defineProperty(exports, "translatePostgresRuleToApiRule", { enumerable: true, get: function () { return rules_1.translatePostgresRuleToApiRule; } });
73
+ Object.defineProperty(exports, "translateApiRuleToPostgresRule", { enumerable: true, get: function () { return rules_1.translateApiRuleToPostgresRule; } });
74
+ Object.defineProperty(exports, "translateApiRuleToPostgresRuleRaw", { enumerable: true, get: function () { return rules_1.translateApiRuleToPostgresRuleRaw; } });
70
75
  var executions_1 = require("./translate/executions");
71
76
  Object.defineProperty(exports, "translateApiExecutionToPostgresExecution", { enumerable: true, get: function () { return executions_1.translateApiExecutionToPostgresExecution; } });
72
77
  Object.defineProperty(exports, "translatePostgresExecutionToApiExecution", { enumerable: true, get: function () { return executions_1.translatePostgresExecutionToApiExecution; } });
@@ -0,0 +1,4 @@
1
+ import { Knex } from 'knex';
2
+ export declare const up: (knex: Knex) => Promise<void>;
3
+ export declare const down: (knex: Knex) => Promise<void>;
4
+ //# sourceMappingURL=20220126172008_files_granule_id_index.d.ts.map
@@ -0,0 +1,16 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.down = exports.up = void 0;
4
+ const up = async (knex) => {
5
+ await knex.schema.table('files', (table) => {
6
+ table.index('granule_cumulus_id');
7
+ });
8
+ };
9
+ exports.up = up;
10
+ const down = async (knex) => {
11
+ await knex.schema.table('files', (table) => {
12
+ table.dropIndex('granule_cumulus_id');
13
+ });
14
+ };
15
+ exports.down = down;
16
+ //# sourceMappingURL=20220126172008_files_granule_id_index.js.map
@@ -4,7 +4,7 @@ import { BaseRecord } from '../types/base';
4
4
  import { TableNames } from '../tables';
5
5
  declare class BasePgModel<ItemType, RecordType extends BaseRecord> {
6
6
  readonly tableName: TableNames;
7
- constructor({ tableName, }: {
7
+ constructor({ tableName }: {
8
8
  tableName: TableNames;
9
9
  });
10
10
  /**
@@ -29,11 +29,27 @@ declare class BasePgModel<ItemType, RecordType extends BaseRecord> {
29
29
  get(knexOrTransaction: Knex | Knex.Transaction, params: Partial<RecordType>): Promise<RecordType>;
30
30
  getMaxCumulusId(knexOrTransaction: Knex | Knex.Transaction): Promise<number>;
31
31
  paginateByCumulusId(knexOrTransaction: Knex | Knex.Transaction, startId?: number, pageSize?: number): Promise<RecordType[]>;
32
+ /**
33
+ * Builds query to fetch mulitple items from postgres
34
+ *
35
+ * @param {Knex | Knex.Transaction} knexOrTransaction - DB client or transaction
36
+ * @param {Object} params - An object or any portion of an object of type RecordType
37
+ * @returns {Object} - Knex querybuilder object
38
+ */
39
+ queryBuilderSearch(knexOrTransaction: Knex | Knex.Transaction, params: Partial<RecordType>): Knex.QueryBuilder<any, {
40
+ _base: any;
41
+ _hasSelection: false;
42
+ _keys: never;
43
+ _aliases: {};
44
+ _single: false;
45
+ _intersectProps: {};
46
+ _unionProps: never;
47
+ }[]>;
32
48
  /**
33
49
  * Fetches multiple items from Postgres
34
50
  *
35
51
  * @param {Knex | Knex.Transaction} knexOrTransaction - DB client or transaction
36
- * @param {Partial<RecordType>} params - An object or any portion of an object of type RecordType
52
+ * @param {Object} params - An object or any portion of an object of type RecordType
37
53
  * @returns {Promise<RecordType[]>} List of returned records
38
54
  */
39
55
  search(knexOrTransaction: Knex | Knex.Transaction, params: Partial<RecordType>): Promise<RecordType[]>;
@@ -106,15 +122,15 @@ declare class BasePgModel<ItemType, RecordType extends BaseRecord> {
106
122
  */
107
123
  update(knexOrTransaction: Knex | Knex.Transaction, whereClause: Partial<RecordType>, updateParams: Partial<RecordType>, returning?: Array<string>): Promise<any[]>;
108
124
  /**
109
- * Deletes items from postgres based on params, excluding any cumulus_ids in the excludeCumulusIds
110
- * @param {Object} params
111
- * @param {Knex | Knex.Transaction} params.knexOrTransaction - DB client or transaction
112
- * @param {Partial<RecordType>} params.queryParams - An object or any portion
113
- * of an object of type RecordType
114
- * @param {[number]} params.excludeCumulusIds - A list of cumulus_ids to exclude from the deletion
115
- * request
116
- * @returns {Promise<number>} The number of rows deleted
117
- */
125
+ * Deletes items from postgres based on params, excluding any cumulus_ids in the excludeCumulusIds
126
+ * @param {Object} params
127
+ * @param {Knex | Knex.Transaction} params.knexOrTransaction - DB client or transaction
128
+ * @param {Partial<RecordType>} params.queryParams - An object or any portion
129
+ * of an object of type RecordType
130
+ * @param {[number]} params.excludeCumulusIds - A list of cumulus_ids to exclude from the deletion
131
+ * request
132
+ * @returns {Promise<number>} The number of rows deleted
133
+ */
118
134
  deleteExcluding({ knexOrTransaction, excludeCumulusIds, queryParams, }: {
119
135
  knexOrTransaction: Knex | Knex.Transaction;
120
136
  excludeCumulusIds: Number[];
@@ -4,7 +4,7 @@ exports.BasePgModel = void 0;
4
4
  const errors_1 = require("@cumulus/errors");
5
5
  const database_1 = require("../database");
6
6
  class BasePgModel {
7
- constructor({ tableName, }) {
7
+ constructor({ tableName }) {
8
8
  this.tableName = tableName;
9
9
  }
10
10
  /**
@@ -16,8 +16,7 @@ class BasePgModel {
16
16
  * @returns {Promise<PostgresCollectionRecord[]>} List of returned records
17
17
  */
18
18
  async searchWithUpdatedAtRange(knexOrTransaction, params, updatedAtParams) {
19
- const records = await knexOrTransaction(this.tableName)
20
- .where((builder) => {
19
+ const records = await knexOrTransaction(this.tableName).where((builder) => {
21
20
  var _a, _b;
22
21
  builder.where(params);
23
22
  if (updatedAtParams.updatedAtFrom || updatedAtParams.updatedAtTo) {
@@ -30,7 +29,8 @@ class BasePgModel {
30
29
  return records;
31
30
  }
32
31
  async count(knexOrTransaction, params) {
33
- const query = knexOrTransaction(this.tableName).where((builder) => {
32
+ const query = knexOrTransaction(this.tableName)
33
+ .where((builder) => {
34
34
  params.forEach((param) => {
35
35
  if (param.length === 3) {
36
36
  builder.where(...param);
@@ -39,7 +39,8 @@ class BasePgModel {
39
39
  builder.where(param[0]);
40
40
  }
41
41
  });
42
- }).count();
42
+ })
43
+ .count();
43
44
  return await query;
44
45
  }
45
46
  /**
@@ -59,27 +60,39 @@ class BasePgModel {
59
60
  return record;
60
61
  }
61
62
  async getMaxCumulusId(knexOrTransaction) {
62
- const result = await knexOrTransaction(this.tableName).max('cumulus_id').first();
63
+ const result = await knexOrTransaction(this.tableName)
64
+ .max('cumulus_id')
65
+ .first();
63
66
  if (!result) {
64
67
  throw new Error(`Invalid .max "cumulus_id" query on ${this.tableName}, MAX cumulus_id cannot be returned`);
65
68
  }
66
69
  return Number(result.max);
67
70
  }
68
71
  async paginateByCumulusId(knexOrTransaction, startId = 0, pageSize = 100) {
69
- return await knexOrTransaction.select()
72
+ return await knexOrTransaction
73
+ .select()
70
74
  .from(this.tableName)
71
75
  .whereBetween('cumulus_id', [startId, startId + pageSize - 1]);
72
76
  }
77
+ /**
78
+ * Builds query to fetch mulitple items from postgres
79
+ *
80
+ * @param {Knex | Knex.Transaction} knexOrTransaction - DB client or transaction
81
+ * @param {Object} params - An object or any portion of an object of type RecordType
82
+ * @returns {Object} - Knex querybuilder object
83
+ */
84
+ queryBuilderSearch(knexOrTransaction, params) {
85
+ return knexOrTransaction(this.tableName).where(params);
86
+ }
73
87
  /**
74
88
  * Fetches multiple items from Postgres
75
89
  *
76
90
  * @param {Knex | Knex.Transaction} knexOrTransaction - DB client or transaction
77
- * @param {Partial<RecordType>} params - An object or any portion of an object of type RecordType
91
+ * @param {Object} params - An object or any portion of an object of type RecordType
78
92
  * @returns {Promise<RecordType[]>} List of returned records
79
93
  */
80
94
  async search(knexOrTransaction, params) {
81
- const records = await knexOrTransaction(this.tableName)
82
- .where(params);
95
+ const records = await this.queryBuilderSearch(knexOrTransaction, params);
83
96
  return records;
84
97
  }
85
98
  /**
@@ -173,9 +186,7 @@ class BasePgModel {
173
186
  * @returns {Promise<number>} The number of rows deleted
174
187
  */
175
188
  async delete(knexOrTransaction, params) {
176
- return await knexOrTransaction(this.tableName)
177
- .where(params)
178
- .del();
189
+ return await knexOrTransaction(this.tableName).where(params).del();
179
190
  }
180
191
  /**
181
192
  * Updates the item or items in Postgres
@@ -192,15 +203,15 @@ class BasePgModel {
192
203
  .update(updateParams, returning);
193
204
  }
194
205
  /**
195
- * Deletes items from postgres based on params, excluding any cumulus_ids in the excludeCumulusIds
196
- * @param {Object} params
197
- * @param {Knex | Knex.Transaction} params.knexOrTransaction - DB client or transaction
198
- * @param {Partial<RecordType>} params.queryParams - An object or any portion
199
- * of an object of type RecordType
200
- * @param {[number]} params.excludeCumulusIds - A list of cumulus_ids to exclude from the deletion
201
- * request
202
- * @returns {Promise<number>} The number of rows deleted
203
- */
206
+ * Deletes items from postgres based on params, excluding any cumulus_ids in the excludeCumulusIds
207
+ * @param {Object} params
208
+ * @param {Knex | Knex.Transaction} params.knexOrTransaction - DB client or transaction
209
+ * @param {Partial<RecordType>} params.queryParams - An object or any portion
210
+ * of an object of type RecordType
211
+ * @param {[number]} params.excludeCumulusIds - A list of cumulus_ids to exclude from the deletion
212
+ * request
213
+ * @returns {Promise<number>} The number of rows deleted
214
+ */
204
215
  async deleteExcluding({ knexOrTransaction, excludeCumulusIds = [], queryParams, }) {
205
216
  return await knexOrTransaction(this.tableName)
206
217
  .where(queryParams)
@@ -3,6 +3,7 @@ import { BasePgModel } from './base';
3
3
  import { PostgresExecution, PostgresExecutionRecord } from '../types/execution';
4
4
  declare class ExecutionPgModel extends BasePgModel<PostgresExecution, PostgresExecutionRecord> {
5
5
  constructor();
6
+ static nonActiveStatuses: string[];
6
7
  create(knexOrTransaction: Knex | Knex.Transaction, item: PostgresExecution): Promise<Object[] | unknown[]>;
7
8
  upsert(knexOrTrx: Knex | Knex.Transaction, execution: PostgresExecution): Promise<any[]>;
8
9
  /**
@@ -67,4 +67,5 @@ class ExecutionPgModel extends base_1.BasePgModel {
67
67
  }
68
68
  }
69
69
  exports.ExecutionPgModel = ExecutionPgModel;
70
+ ExecutionPgModel.nonActiveStatuses = ['completed', 'failed', 'unknown'];
70
71
  //# sourceMappingURL=execution.js.map
@@ -1,7 +1,7 @@
1
1
  import { Knex } from 'knex';
2
2
  import { PostgresGranule, PostgresGranuleRecord, PostgresGranuleUniqueColumns } from '../types/granule';
3
3
  import { BasePgModel } from './base';
4
- import { GranulesExecutionsPgModel } from './granules-executions';
4
+ import { ExecutionPgModel } from './execution';
5
5
  interface RecordSelect {
6
6
  cumulus_id: number;
7
7
  }
@@ -37,7 +37,16 @@ export default class GranulePgModel extends BasePgModel<PostgresGranule, Postgre
37
37
  * @returns {Promise<PostgresGranuleRecord>} The returned record
38
38
  */
39
39
  get(knexOrTransaction: Knex | Knex.Transaction, params: PostgresGranuleUniqueColumns | RecordSelect): Promise<PostgresGranuleRecord>;
40
- upsert(knexOrTrx: Knex | Knex.Transaction, granule: PostgresGranule, executionCumulusId?: number, granulesExecutionsPgModel?: GranulesExecutionsPgModel): Promise<any[]>;
40
+ _buildExclusionClause(executionPgModel: ExecutionPgModel, executionCumulusId: number, knexOrTrx: Knex | Knex.Transaction, status: 'queued' | 'running'): Knex.QueryBuilder<any, {
41
+ _base: any;
42
+ _hasSelection: false;
43
+ _keys: never;
44
+ _aliases: {};
45
+ _single: false;
46
+ _intersectProps: {};
47
+ _unionProps: never;
48
+ }[]>;
49
+ upsert(knexOrTrx: Knex | Knex.Transaction, granule: PostgresGranule, executionCumulusId?: number, executionPgModel?: ExecutionPgModel): Promise<any[]>;
41
50
  /**
42
51
  * Get granules from the granule cumulus_id
43
52
  *
@@ -4,7 +4,7 @@ exports.GranulePgModel = void 0;
4
4
  const errors_1 = require("@cumulus/errors");
5
5
  const tables_1 = require("../tables");
6
6
  const base_1 = require("./base");
7
- const granules_executions_1 = require("./granules-executions");
7
+ const execution_1 = require("./execution");
8
8
  const timestamp_1 = require("../lib/timestamp");
9
9
  const sort_1 = require("../lib/sort");
10
10
  function isRecordSelect(param) {
@@ -27,9 +27,7 @@ class GranulePgModel extends base_1.BasePgModel {
27
27
  * @returns {Promise<number>} The number of rows deleted
28
28
  */
29
29
  async delete(knexOrTransaction, params) {
30
- return await knexOrTransaction(this.tableName)
31
- .where(params)
32
- .del();
30
+ return await knexOrTransaction(this.tableName).where(params).del();
33
31
  }
34
32
  async deleteExcluding() {
35
33
  throw new Error('deleteExcluding not implemented on granule class');
@@ -70,7 +68,16 @@ class GranulePgModel extends base_1.BasePgModel {
70
68
  }
71
69
  return super.get(knexOrTransaction, params);
72
70
  }
73
- async upsert(knexOrTrx, granule, executionCumulusId, granulesExecutionsPgModel = new granules_executions_1.GranulesExecutionsPgModel()) {
71
+ _buildExclusionClause(executionPgModel, executionCumulusId, knexOrTrx, status) {
72
+ const queryBuilder = executionPgModel.queryBuilderSearch(knexOrTrx, {
73
+ cumulus_id: executionCumulusId,
74
+ });
75
+ if (status === 'running') {
76
+ queryBuilder.whereIn('status', execution_1.ExecutionPgModel.nonActiveStatuses);
77
+ }
78
+ return queryBuilder;
79
+ }
80
+ async upsert(knexOrTrx, granule, executionCumulusId, executionPgModel = new execution_1.ExecutionPgModel()) {
74
81
  if (!granule.created_at) {
75
82
  throw new Error(`To upsert granule record must have 'created_at' set: ${JSON.stringify(granule)}`);
76
83
  }
@@ -86,13 +93,14 @@ class GranulePgModel extends base_1.BasePgModel {
86
93
  })
87
94
  .where(knexOrTrx.raw(`${this.tableName}.created_at <= to_timestamp(${(0, timestamp_1.translateDateToUTC)(granule.created_at)})`));
88
95
  // In reality, the only place where executionCumulusId should be
89
- // undefined is from the data migrations
96
+ // undefined is from the data migrations OR a queued granule from reingest
90
97
  if (executionCumulusId) {
91
- // Only do the upsert if there IS NOT already a record associating
92
- // the granule to this execution. If there IS already a record
93
- // linking this granule to this execution, then this upsert query
94
- // will not affect any rows.
95
- upsertQuery.whereNotExists(granulesExecutionsPgModel.search(knexOrTrx, { execution_cumulus_id: executionCumulusId }));
98
+ const exclusionClause = this._buildExclusionClause(executionPgModel, executionCumulusId, knexOrTrx, granule.status);
99
+ // Only do the upsert if there is no execution that matches the exclusionClause
100
+ // For running granules, this means the execution does not exist in a state other
101
+ // than 'running'. For queued granules, this means that the execution does not
102
+ // exist at all
103
+ upsertQuery.whereNotExists(exclusionClause);
96
104
  }
97
105
  upsertQuery.returning('*');
98
106
  return await upsertQuery;
@@ -95,8 +95,8 @@ const translateApiExecutionToPostgresExecution = async (dynamoRecord, knex, coll
95
95
  updated_at: dynamoRecord.updatedAt ? new Date(dynamoRecord.updatedAt) : undefined,
96
96
  };
97
97
  if (dynamoRecord.collectionId !== undefined) {
98
- const collectionNameVersionArray = dynamoRecord.collectionId.split('___');
99
- translatedRecord.collection_cumulus_id = await collectionPgModel.getRecordCumulusId(knex, { name: collectionNameVersionArray[0], version: collectionNameVersionArray[1] });
98
+ const { name, version } = (0, Collections_1.deconstructCollectionId)(dynamoRecord.collectionId);
99
+ translatedRecord.collection_cumulus_id = await collectionPgModel.getRecordCumulusId(knex, { name, version });
100
100
  }
101
101
  // If we have a parentArn, try a lookup in Postgres. If there's a match, set the parent_cumulus_id
102
102
  if (dynamoRecord.parentArn !== undefined) {
@@ -22,7 +22,7 @@ const translatePostgresProviderToApiProvider = (record) => {
22
22
  createdAt: record.created_at.getTime(),
23
23
  updatedAt: record.updated_at.getTime(),
24
24
  username: record.username,
25
- password: record.username,
25
+ password: record.password,
26
26
  allowedRedirects: record.allowed_redirects,
27
27
  };
28
28
  if (record.username || record.password) {
@@ -13,5 +13,15 @@ export declare const translatePostgresRuleToApiRule: (pgRule: PostgresRuleRecord
13
13
  * @param {Object} providerPgModel - Instance of the provider database model
14
14
  * @returns {Object} A rule record
15
15
  */
16
+ export declare const translateApiRuleToPostgresRuleRaw: (record: RuleRecord, dbClient: Knex, collectionPgModel?: CollectionPgModel, providerPgModel?: ProviderPgModel) => Promise<PostgresRule>;
17
+ /**
18
+ * Generate a Postgres rule record from a DynamoDB record and remove nil properties.
19
+ *
20
+ * @param {Object} record - A rule
21
+ * @param {Object} dbClient - Knex client for reading from RDS database
22
+ * @param {Object} collectionPgModel - Instance of the collection database model
23
+ * @param {Object} providerPgModel - Instance of the provider database model
24
+ * @returns {Object} A rule record
25
+ */
16
26
  export declare const translateApiRuleToPostgresRule: (record: RuleRecord, dbClient: Knex, collectionPgModel?: CollectionPgModel, providerPgModel?: ProviderPgModel) => Promise<PostgresRule>;
17
27
  //# sourceMappingURL=rules.d.ts.map
@@ -1,6 +1,6 @@
1
1
  "use strict";
2
2
  Object.defineProperty(exports, "__esModule", { value: true });
3
- exports.translateApiRuleToPostgresRule = exports.translatePostgresRuleToApiRule = void 0;
3
+ exports.translateApiRuleToPostgresRule = exports.translateApiRuleToPostgresRuleRaw = exports.translatePostgresRuleToApiRule = void 0;
4
4
  const util_1 = require("@cumulus/common/util");
5
5
  const collection_1 = require("../models/collection");
6
6
  const provider_1 = require("../models/provider");
@@ -46,25 +46,36 @@ exports.translatePostgresRuleToApiRule = translatePostgresRuleToApiRule;
46
46
  * @param {Object} providerPgModel - Instance of the provider database model
47
47
  * @returns {Object} A rule record
48
48
  */
49
+ const translateApiRuleToPostgresRuleRaw = async (record, dbClient, collectionPgModel = new collection_1.CollectionPgModel(), providerPgModel = new provider_1.ProviderPgModel()) => ({
50
+ name: record.name,
51
+ workflow: record.workflow,
52
+ provider_cumulus_id: record.provider ? await providerPgModel.getRecordCumulusId(dbClient, { name: record.provider }) : undefined,
53
+ collection_cumulus_id: record.collection ? await collectionPgModel.getRecordCumulusId(dbClient, { name: record.collection.name, version: record.collection.version }) : undefined,
54
+ meta: record.meta,
55
+ payload: record.payload,
56
+ queue_url: record.queueUrl,
57
+ arn: record.rule.arn,
58
+ type: record.rule.type,
59
+ value: record.rule.value,
60
+ log_event_arn: record.rule.logEventArn,
61
+ enabled: (record.state === undefined) || (record.state === 'ENABLED'),
62
+ tags: (record.tags ? JSON.stringify(record.tags) : undefined),
63
+ execution_name_prefix: record.executionNamePrefix,
64
+ created_at: (record.createdAt ? new Date(record.createdAt) : undefined),
65
+ updated_at: (record.updatedAt ? new Date(record.updatedAt) : undefined),
66
+ });
67
+ exports.translateApiRuleToPostgresRuleRaw = translateApiRuleToPostgresRuleRaw;
68
+ /**
69
+ * Generate a Postgres rule record from a DynamoDB record and remove nil properties.
70
+ *
71
+ * @param {Object} record - A rule
72
+ * @param {Object} dbClient - Knex client for reading from RDS database
73
+ * @param {Object} collectionPgModel - Instance of the collection database model
74
+ * @param {Object} providerPgModel - Instance of the provider database model
75
+ * @returns {Object} A rule record
76
+ */
49
77
  const translateApiRuleToPostgresRule = async (record, dbClient, collectionPgModel = new collection_1.CollectionPgModel(), providerPgModel = new provider_1.ProviderPgModel()) => {
50
- const ruleRecord = {
51
- name: record.name,
52
- workflow: record.workflow,
53
- provider_cumulus_id: record.provider ? await providerPgModel.getRecordCumulusId(dbClient, { name: record.provider }) : undefined,
54
- collection_cumulus_id: record.collection ? await collectionPgModel.getRecordCumulusId(dbClient, { name: record.collection.name, version: record.collection.version }) : undefined,
55
- meta: record.meta,
56
- payload: record.payload,
57
- queue_url: record.queueUrl,
58
- arn: record.rule.arn,
59
- type: record.rule.type,
60
- value: record.rule.value,
61
- log_event_arn: record.rule.logEventArn,
62
- enabled: (record.state === undefined) || (record.state === 'ENABLED'),
63
- tags: (record.tags ? JSON.stringify(record.tags) : undefined),
64
- execution_name_prefix: record.executionNamePrefix,
65
- created_at: (record.createdAt ? new Date(record.createdAt) : undefined),
66
- updated_at: (record.updatedAt ? new Date(record.updatedAt) : undefined),
67
- };
78
+ const ruleRecord = await (0, exports.translateApiRuleToPostgresRuleRaw)(record, dbClient, collectionPgModel, providerPgModel);
68
79
  return (0, util_1.removeNilProperties)(ruleRecord);
69
80
  };
70
81
  exports.translateApiRuleToPostgresRule = translateApiRuleToPostgresRule;
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@cumulus/db",
3
- "version": "10.1.1-alpha.0",
3
+ "version": "11.0.0",
4
4
  "description": "Utilities for working with the Cumulus DB",
5
5
  "license": "Apache-2.0",
6
6
  "main": "./dist/index.js",
@@ -29,21 +29,22 @@
29
29
  "node": ">=12.18.0"
30
30
  },
31
31
  "dependencies": {
32
- "@cumulus/aws-client": "10.0.0",
33
- "@cumulus/common": "10.0.0",
34
- "@cumulus/errors": "10.0.0",
35
- "@cumulus/logger": "10.0.0",
36
- "@cumulus/message": "10.0.0",
37
- "@cumulus/types": "10.0.0",
32
+ "@cumulus/aws-client": "11.0.0",
33
+ "@cumulus/common": "11.0.0",
34
+ "@cumulus/errors": "11.0.0",
35
+ "@cumulus/logger": "11.0.0",
36
+ "@cumulus/message": "11.0.0",
37
+ "@cumulus/types": "11.0.0",
38
38
  "crypto-random-string": "^3.2.0",
39
39
  "is-valid-hostname": "0.0.1",
40
40
  "knex": "0.95.15",
41
- "lodash": "^4.17.20",
41
+ "lodash": "^4.17.21",
42
42
  "pg": "^8.3.0",
43
43
  "snake-camel": "^1.0.6",
44
44
  "uuid": "8.3.2"
45
45
  },
46
46
  "devDependencies": {
47
47
  "@types/uuid": "^8.0.0"
48
- }
48
+ },
49
+ "gitHead": "e922ad12fd94affa6cd60a97a184a465a756c50b"
49
50
  }