@cumulus/db 10.1.0 → 10.1.1-alpha.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.
Files changed (62) hide show
  1. package/dist/config.d.ts +0 -1
  2. package/dist/config.js +2 -4
  3. package/dist/connection.js +8 -29
  4. package/dist/index.d.ts +13 -8
  5. package/dist/index.js +28 -11
  6. package/dist/lib/QuerySearchClient.d.ts +36 -0
  7. package/dist/lib/QuerySearchClient.js +51 -0
  8. package/dist/lib/collection.d.ts +10 -0
  9. package/dist/lib/collection.js +21 -0
  10. package/dist/lib/errors.d.ts +6 -0
  11. package/dist/lib/errors.js +8 -0
  12. package/dist/lib/execution.d.ts +21 -0
  13. package/dist/lib/execution.js +28 -1
  14. package/dist/lib/file.d.ts +33 -0
  15. package/dist/lib/file.js +61 -0
  16. package/dist/lib/granule.d.ts +35 -3
  17. package/dist/lib/granule.js +104 -8
  18. package/dist/migrations/{20220126172008_files_granule_id_index.d.ts → 20210914051414_add_type_to_files.d.ts} +1 -1
  19. package/dist/migrations/{20220126172008_files_granule_id_index.js → 20210914051414_add_type_to_files.js} +5 -3
  20. package/dist/models/base.d.ts +49 -9
  21. package/dist/models/base.js +75 -7
  22. package/dist/models/collection.d.ts +4 -3
  23. package/dist/models/collection.js +4 -1
  24. package/dist/models/execution.d.ts +1 -0
  25. package/dist/models/execution.js +5 -2
  26. package/dist/models/file.d.ts +2 -2
  27. package/dist/models/file.js +2 -1
  28. package/dist/models/granule.d.ts +2 -0
  29. package/dist/models/granule.js +8 -2
  30. package/dist/models/pdr.js +2 -2
  31. package/dist/test-utils.js +3 -0
  32. package/dist/translate/async_operations.d.ts +13 -0
  33. package/dist/translate/async_operations.js +56 -2
  34. package/dist/translate/collections.d.ts +13 -2
  35. package/dist/translate/collections.js +31 -2
  36. package/dist/translate/executions.js +2 -2
  37. package/dist/translate/file.js +3 -1
  38. package/dist/translate/granules.d.ts +15 -4
  39. package/dist/translate/granules.js +38 -14
  40. package/dist/translate/pdr.d.ts +29 -0
  41. package/dist/translate/pdr.js +82 -0
  42. package/dist/translate/providers.d.ts +2 -1
  43. package/dist/translate/providers.js +24 -1
  44. package/dist/translate/rules.d.ts +2 -1
  45. package/dist/translate/rules.js +36 -2
  46. package/dist/types/base.d.ts +5 -0
  47. package/dist/types/base.js +3 -0
  48. package/dist/types/collection.d.ts +6 -4
  49. package/dist/types/file.d.ts +3 -1
  50. package/dist/types/granule.d.ts +2 -1
  51. package/dist/types/pdr.d.ts +2 -1
  52. package/dist/types/provider.d.ts +1 -1
  53. package/dist/types/provider.js +6 -0
  54. package/dist/types/query.d.ts +10 -0
  55. package/dist/types/query.js +3 -0
  56. package/dist/types/record.d.ts +5 -0
  57. package/dist/types/record.js +3 -0
  58. package/dist/types/rule.d.ts +3 -2
  59. package/package.json +8 -9
  60. package/LICENSE +0 -60
  61. package/dist/translate/pdrs.d.ts +0 -19
  62. package/dist/translate/pdrs.js +0 -44
@@ -1,10 +1,22 @@
1
1
  "use strict";
2
+ var __importDefault = (this && this.__importDefault) || function (mod) {
3
+ return (mod && mod.__esModule) ? mod : { "default": mod };
4
+ };
2
5
  Object.defineProperty(exports, "__esModule", { value: true });
3
- exports.getApiGranuleExecutionCumulusIds = exports.getApiGranuleCumulusIds = exports.upsertGranuleWithExecutionJoinRecord = void 0;
6
+ exports.getGranulesByApiPropertiesQuery = exports.getApiGranuleExecutionCumulusIds = exports.getUniqueGranuleByGranuleId = exports.getApiGranuleCumulusIds = exports.upsertGranuleWithExecutionJoinRecord = exports.getGranuleCollectionId = void 0;
7
+ const Collections_1 = require("@cumulus/message/Collections");
8
+ const errors_1 = require("@cumulus/errors");
9
+ const logger_1 = __importDefault(require("@cumulus/logger"));
4
10
  const collection_1 = require("../models/collection");
5
11
  const granule_1 = require("../models/granule");
6
12
  const granules_executions_1 = require("../models/granules-executions");
7
- const { deconstructCollectionId } = require('@cumulus/message/Collections');
13
+ const { TableNames } = require('../tables');
14
+ const getGranuleCollectionId = async (knexOrTransaction, granule) => {
15
+ const collectionPgModel = new collection_1.CollectionPgModel();
16
+ const collection = await collectionPgModel.get(knexOrTransaction, { cumulus_id: granule.collection_cumulus_id });
17
+ return (0, Collections_1.constructCollectionId)(collection.name, collection.version);
18
+ };
19
+ exports.getGranuleCollectionId = getGranuleCollectionId;
8
20
  /**
9
21
  * Upsert a granule and a record in the granules/executions join table.
10
22
  *
@@ -14,24 +26,24 @@ const { deconstructCollectionId } = require('@cumulus/message/Collections');
14
26
  * @param {Object} [granulePgModel] - Granule PG model class instance
15
27
  * @param {Object} [granulesExecutionsPgModel]
16
28
  * Granules/executions PG model class instance
17
- * @returns {Promise<number[]>}
29
+ * @returns {Promise<PostgresGranuleRecord[]>}
18
30
  */
19
31
  const upsertGranuleWithExecutionJoinRecord = async (knexTransaction, granule, executionCumulusId, granulePgModel = new granule_1.GranulePgModel(), granulesExecutionsPgModel = new granules_executions_1.GranulesExecutionsPgModel()) => {
20
- const [granuleCumulusId] = await granulePgModel.upsert(knexTransaction, granule, executionCumulusId);
32
+ const [pgGranule] = await granulePgModel.upsert(knexTransaction, granule, executionCumulusId);
21
33
  // granuleCumulusId could be undefined if the upsert affected no rows due to its
22
34
  // conditional logic. In that case, we assume that the execution history for the
23
35
  // granule was already written and return early. Execution history cannot be written
24
36
  // without granuleCumulusId regardless.
25
- if (!granuleCumulusId) {
37
+ if (!pgGranule) {
26
38
  return [];
27
39
  }
28
40
  if (executionCumulusId) {
29
41
  await granulesExecutionsPgModel.upsert(knexTransaction, {
30
- granule_cumulus_id: granuleCumulusId,
42
+ granule_cumulus_id: pgGranule.cumulus_id,
31
43
  execution_cumulus_id: executionCumulusId,
32
44
  });
33
45
  }
34
- return [granuleCumulusId];
46
+ return [pgGranule];
35
47
  };
36
48
  exports.upsertGranuleWithExecutionJoinRecord = upsertGranuleWithExecutionJoinRecord;
37
49
  /**
@@ -50,7 +62,7 @@ const getApiGranuleCumulusIds = async (knexOrTransaction, granules, collectionPg
50
62
  const { collectionId } = granule;
51
63
  let collectionCumulusId = collectionMap[collectionId];
52
64
  if (!collectionCumulusId) {
53
- const { name, version } = deconstructCollectionId(collectionId);
65
+ const { name, version } = (0, Collections_1.deconstructCollectionId)(collectionId);
54
66
  collectionCumulusId = await collectionPgModel.getRecordCumulusId(knexOrTransaction, { name, version });
55
67
  collectionMap[collectionId] = collectionCumulusId;
56
68
  }
@@ -62,6 +74,30 @@ const getApiGranuleCumulusIds = async (knexOrTransaction, granules, collectionPg
62
74
  return [...new Set(granuleCumulusIds)];
63
75
  };
64
76
  exports.getApiGranuleCumulusIds = getApiGranuleCumulusIds;
77
+ /**
78
+ * Get one Granule for a granule_id. If more than one or none are found, throw an error
79
+ *
80
+ * @param {Knex | Knex.Transaction} knexOrTransaction -
81
+ * DB client or transaction
82
+ * @param {string} granuleId - a Granule ID
83
+ * @param {GranulePgModel} granulePgModel - Granule PG model class instance
84
+ * @returns {Promise<PostgresGranuleRecord>}
85
+ */
86
+ const getUniqueGranuleByGranuleId = async (knexOrTransaction, granuleId, granulePgModel = new granule_1.GranulePgModel()) => {
87
+ const logger = new logger_1.default({ sender: '@cumulus/api/granules' });
88
+ const PgGranuleRecords = await granulePgModel.search(knexOrTransaction, {
89
+ granule_id: granuleId,
90
+ });
91
+ if (PgGranuleRecords.length > 1) {
92
+ logger.warn(`Granule ID ${granuleId} is not unique across collections, cannot make an update action based on granule Id alone`);
93
+ throw new Error(`Failed to write ${granuleId} due to granuleId duplication on postgres granule record`);
94
+ }
95
+ if (PgGranuleRecords.length === 0) {
96
+ throw new errors_1.RecordDoesNotExist(`Granule ${granuleId} does not exist or was already deleted`);
97
+ }
98
+ return PgGranuleRecords[0];
99
+ };
100
+ exports.getUniqueGranuleByGranuleId = getUniqueGranuleByGranuleId;
65
101
  /**
66
102
  * Get cumulus IDs for all executions associated to a set of granules
67
103
  *
@@ -81,4 +117,64 @@ const getApiGranuleExecutionCumulusIds = async (knexOrTransaction, granules, col
81
117
  return executionCumulusIds;
82
118
  };
83
119
  exports.getApiGranuleExecutionCumulusIds = getApiGranuleExecutionCumulusIds;
120
+ /**
121
+ * Helper to build a query to search granules by various API granule record properties.
122
+ *
123
+ * @param {Knex} knex - DB client
124
+ * @param {Object} searchParams
125
+ * @param {string | Array<string>} [searchParams.collectionIds] - Collection ID
126
+ * @param {string | Array<string>} [searchParams.granuleIds] - array of granule IDs
127
+ * @param {string} [searchParams.providerName] - Provider name
128
+ * @param {UpdatedAtRange} [searchParams.updatedAtRange] - Date range for updated_at column
129
+ * @param {string} [searchParams.status] - Granule status to search by
130
+ * @param {string | Array<string>} [sortByFields] - Field(s) to sort by
131
+ * @returns {Knex.QueryBuilder}
132
+ */
133
+ const getGranulesByApiPropertiesQuery = (knex, { collectionIds, granuleIds, providerNames, updatedAtRange = {}, status, }, sortByFields) => {
134
+ const { granules: granulesTable, collections: collectionsTable, providers: providersTable, } = TableNames;
135
+ return knex(granulesTable)
136
+ .select(`${granulesTable}.*`)
137
+ .select({
138
+ providerName: `${providersTable}.name`,
139
+ collectionName: `${collectionsTable}.name`,
140
+ collectionVersion: `${collectionsTable}.version`,
141
+ })
142
+ .innerJoin(collectionsTable, `${granulesTable}.collection_cumulus_id`, `${collectionsTable}.cumulus_id`)
143
+ .leftJoin(providersTable, `${granulesTable}.provider_cumulus_id`, `${providersTable}.cumulus_id`)
144
+ .modify((queryBuilder) => {
145
+ if (collectionIds) {
146
+ const collectionIdFilters = [collectionIds].flat();
147
+ const collectionIdConcatField = `(${collectionsTable}.name || '${Collections_1.collectionIdSeparator}' || ${collectionsTable}.version)`;
148
+ const collectionIdInClause = collectionIdFilters.map(() => '?').join(',');
149
+ queryBuilder.whereRaw(`${collectionIdConcatField} IN (${collectionIdInClause})`, collectionIdFilters);
150
+ }
151
+ if (granuleIds) {
152
+ const granuleIdFilters = [granuleIds].flat();
153
+ queryBuilder.where((nestedQueryBuilder) => {
154
+ granuleIdFilters.forEach((granuleId) => {
155
+ nestedQueryBuilder.orWhere(`${granulesTable}.granule_id`, 'LIKE', `%${granuleId}%`);
156
+ });
157
+ });
158
+ }
159
+ if (providerNames) {
160
+ queryBuilder.whereIn(`${providersTable}.name`, providerNames);
161
+ }
162
+ if (updatedAtRange.updatedAtFrom) {
163
+ queryBuilder.where(`${granulesTable}.updated_at`, '>=', updatedAtRange.updatedAtFrom);
164
+ }
165
+ if (updatedAtRange.updatedAtTo) {
166
+ queryBuilder.where(`${granulesTable}.updated_at`, '<=', updatedAtRange.updatedAtTo);
167
+ }
168
+ if (status) {
169
+ queryBuilder.where(`${granulesTable}.status`, status);
170
+ }
171
+ if (sortByFields) {
172
+ queryBuilder.orderBy([sortByFields].flat());
173
+ }
174
+ })
175
+ .groupBy(`${granulesTable}.cumulus_id`)
176
+ .groupBy(`${collectionsTable}.cumulus_id`)
177
+ .groupBy(`${providersTable}.cumulus_id`);
178
+ };
179
+ exports.getGranulesByApiPropertiesQuery = getGranulesByApiPropertiesQuery;
84
180
  //# sourceMappingURL=granule.js.map
@@ -1,4 +1,4 @@
1
1
  import { Knex } from 'knex';
2
2
  export declare const up: (knex: Knex) => Promise<void>;
3
3
  export declare const down: (knex: Knex) => Promise<void>;
4
- //# sourceMappingURL=20220126172008_files_granule_id_index.d.ts.map
4
+ //# sourceMappingURL=20210914051414_add_type_to_files.d.ts.map
@@ -3,14 +3,16 @@ Object.defineProperty(exports, "__esModule", { value: true });
3
3
  exports.down = exports.up = void 0;
4
4
  const up = async (knex) => {
5
5
  await knex.schema.table('files', (table) => {
6
- table.index('granule_cumulus_id');
6
+ table
7
+ .text('type')
8
+ .comment('file "type"');
7
9
  });
8
10
  };
9
11
  exports.up = up;
10
12
  const down = async (knex) => {
11
13
  await knex.schema.table('files', (table) => {
12
- table.dropIndex('granule_cumulus_id');
14
+ table.dropColumn('type');
13
15
  });
14
16
  };
15
17
  exports.down = down;
16
- //# sourceMappingURL=20220126172008_files_granule_id_index.js.map
18
+ //# sourceMappingURL=20210914051414_add_type_to_files.js.map
@@ -1,12 +1,21 @@
1
1
  import { Knex } from 'knex';
2
+ import { UpdatedAtRange } from '../types/record';
3
+ import { BaseRecord } from '../types/base';
2
4
  import { TableNames } from '../tables';
3
- declare class BasePgModel<ItemType, RecordType extends {
4
- cumulus_id: number;
5
- }> {
5
+ declare class BasePgModel<ItemType, RecordType extends BaseRecord> {
6
6
  readonly tableName: TableNames;
7
7
  constructor({ tableName, }: {
8
8
  tableName: TableNames;
9
9
  });
10
+ /**
11
+ * Fetches multiple items from Postgres
12
+ *
13
+ * @param {Knex | Knex.Transaction} knexOrTransaction - DB client or transaction
14
+ * @param {Partial<RecordType>} params - An object or any portion of an object of type RecordType
15
+ * @param {UpdatedAtRange} updatedAtParams - An object with Date search bounds for updatedAt
16
+ * @returns {Promise<PostgresCollectionRecord[]>} List of returned records
17
+ */
18
+ searchWithUpdatedAtRange(knexOrTransaction: Knex | Knex.Transaction, params: Partial<RecordType>, updatedAtParams: UpdatedAtRange): Promise<RecordType[]>;
10
19
  count(knexOrTransaction: Knex | Knex.Transaction, params: ([string, string, string] | [Partial<RecordType>])[]): Promise<{
11
20
  [k: string]: string | number;
12
21
  }[]>;
@@ -18,11 +27,13 @@ declare class BasePgModel<ItemType, RecordType extends {
18
27
  * @returns {Promise<RecordType>} The returned record
19
28
  */
20
29
  get(knexOrTransaction: Knex | Knex.Transaction, params: Partial<RecordType>): Promise<RecordType>;
30
+ getMaxCumulusId(knexOrTransaction: Knex | Knex.Transaction): Promise<number>;
31
+ paginateByCumulusId(knexOrTransaction: Knex | Knex.Transaction, startId?: number, pageSize?: number): Promise<RecordType[]>;
21
32
  /**
22
33
  * Fetches multiple items from Postgres
23
34
  *
24
35
  * @param {Knex | Knex.Transaction} knexOrTransaction - DB client or transaction
25
- * @param {Object} params - An object or any portion of an object of type RecordType
36
+ * @param {Partial<RecordType>} params - An object or any portion of an object of type RecordType
26
37
  * @returns {Promise<RecordType[]>} List of returned records
27
38
  */
28
39
  search(knexOrTransaction: Knex | Knex.Transaction, params: Partial<RecordType>): Promise<RecordType[]>;
@@ -39,11 +50,11 @@ declare class BasePgModel<ItemType, RecordType extends {
39
50
  /**
40
51
  * Get cumulus_id column value for multiple records in Postgres
41
52
  *
42
- * @param {Knex | Knex.Transaction} knexOrTransaction -
53
+ * @param {Knex | Knex.Transaction} knexOrTransaction
43
54
  * DB client or transaction
44
55
  * @param {Array<string>} columnNames - column names for whereIn query
45
- * @param {Array<string>} values - record values for whereIn query
46
- * @returns {Promise<Array<number>>} An array of cumulus_ids for the returned records
56
+ * @param {Array<any>} values - record values for whereIn query
57
+ * @returns {Promise<Array>} An array of cumulus_ids for the returned records
47
58
  */
48
59
  getRecordsCumulusIds(knexOrTransaction: Knex | Knex.Transaction, columnNames: Array<keyof RecordType>, values: Array<any>): Promise<Array<number>>;
49
60
  /**
@@ -59,9 +70,23 @@ declare class BasePgModel<ItemType, RecordType extends {
59
70
  *
60
71
  * @param {Knex | Knex.Transaction} knexOrTransaction - DB client or transaction
61
72
  * @param {ItemType} item - A record to insert into the DB
62
- * @returns {Promise<number[]>} List of IDs of the inserted records
73
+ * @param {string | Array<string>} returningFields - A string or array of strings
74
+ * of columns to return. Defaults to 'cumulus_id'.
75
+ * @returns {Promise<unknown[] | Object[]>} Returns an array of objects or an
76
+ * array of values from the specified column(s) from returningFields.
77
+ */
78
+ create(knexOrTransaction: Knex | Knex.Transaction, item: ItemType, returningFields?: string | string[]): Promise<unknown[] | Object[]>;
79
+ /**
80
+ * Creates multiple items in Postgres
81
+ *
82
+ * @param {Knex | Knex.Transaction} knexOrTransaction - DB client or transaction
83
+ * @param {ItemType[]} items - Records to insert into the DB
84
+ * @param {string | Array<string>} returningFields - A string or array of strings
85
+ * of columns to return. Defaults to 'cumulus_id'.
86
+ * @returns {Promise<unknown[] | Object[]>} Returns an array of objects or an
87
+ * array of values from the specified column(s) from returningFields.
63
88
  */
64
- create(knexOrTransaction: Knex | Knex.Transaction, item: ItemType): Promise<number[]>;
89
+ insert(knexOrTransaction: Knex | Knex.Transaction, items: ItemType[], returningFields?: string | string[]): Promise<unknown[] | Object[]>;
65
90
  /**
66
91
  * Deletes the item from Postgres
67
92
  *
@@ -80,6 +105,21 @@ declare class BasePgModel<ItemType, RecordType extends {
80
105
  * @returns {Promise<RecordType[]>} List of returned records
81
106
  */
82
107
  update(knexOrTransaction: Knex | Knex.Transaction, whereClause: Partial<RecordType>, updateParams: Partial<RecordType>, returning?: Array<string>): Promise<any[]>;
108
+ /**
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
+ */
118
+ deleteExcluding({ knexOrTransaction, excludeCumulusIds, queryParams, }: {
119
+ knexOrTransaction: Knex | Knex.Transaction;
120
+ excludeCumulusIds: Number[];
121
+ queryParams: Partial<RecordType>;
122
+ }): Promise<number>;
83
123
  }
84
124
  export { BasePgModel };
85
125
  //# sourceMappingURL=base.d.ts.map
@@ -7,6 +7,28 @@ class BasePgModel {
7
7
  constructor({ tableName, }) {
8
8
  this.tableName = tableName;
9
9
  }
10
+ /**
11
+ * Fetches multiple items from Postgres
12
+ *
13
+ * @param {Knex | Knex.Transaction} knexOrTransaction - DB client or transaction
14
+ * @param {Partial<RecordType>} params - An object or any portion of an object of type RecordType
15
+ * @param {UpdatedAtRange} updatedAtParams - An object with Date search bounds for updatedAt
16
+ * @returns {Promise<PostgresCollectionRecord[]>} List of returned records
17
+ */
18
+ async searchWithUpdatedAtRange(knexOrTransaction, params, updatedAtParams) {
19
+ const records = await knexOrTransaction(this.tableName)
20
+ .where((builder) => {
21
+ var _a, _b;
22
+ builder.where(params);
23
+ if (updatedAtParams.updatedAtFrom || updatedAtParams.updatedAtTo) {
24
+ builder.whereBetween('updated_at', [
25
+ (_a = updatedAtParams === null || updatedAtParams === void 0 ? void 0 : updatedAtParams.updatedAtFrom) !== null && _a !== void 0 ? _a : new Date(0),
26
+ (_b = updatedAtParams === null || updatedAtParams === void 0 ? void 0 : updatedAtParams.updatedAtTo) !== null && _b !== void 0 ? _b : new Date(),
27
+ ]);
28
+ }
29
+ });
30
+ return records;
31
+ }
10
32
  async count(knexOrTransaction, params) {
11
33
  const query = knexOrTransaction(this.tableName).where((builder) => {
12
34
  params.forEach((param) => {
@@ -36,11 +58,23 @@ class BasePgModel {
36
58
  }
37
59
  return record;
38
60
  }
61
+ async getMaxCumulusId(knexOrTransaction) {
62
+ const result = await knexOrTransaction(this.tableName).max('cumulus_id').first();
63
+ if (!result) {
64
+ throw new Error(`Invalid .max "cumulus_id" query on ${this.tableName}, MAX cumulus_id cannot be returned`);
65
+ }
66
+ return Number(result.max);
67
+ }
68
+ async paginateByCumulusId(knexOrTransaction, startId = 0, pageSize = 100) {
69
+ return await knexOrTransaction.select()
70
+ .from(this.tableName)
71
+ .whereBetween('cumulus_id', [startId, startId + pageSize - 1]);
72
+ }
39
73
  /**
40
74
  * Fetches multiple items from Postgres
41
75
  *
42
76
  * @param {Knex | Knex.Transaction} knexOrTransaction - DB client or transaction
43
- * @param {Object} params - An object or any portion of an object of type RecordType
77
+ * @param {Partial<RecordType>} params - An object or any portion of an object of type RecordType
44
78
  * @returns {Promise<RecordType[]>} List of returned records
45
79
  */
46
80
  async search(knexOrTransaction, params) {
@@ -70,11 +104,11 @@ class BasePgModel {
70
104
  /**
71
105
  * Get cumulus_id column value for multiple records in Postgres
72
106
  *
73
- * @param {Knex | Knex.Transaction} knexOrTransaction -
107
+ * @param {Knex | Knex.Transaction} knexOrTransaction
74
108
  * DB client or transaction
75
109
  * @param {Array<string>} columnNames - column names for whereIn query
76
- * @param {Array<string>} values - record values for whereIn query
77
- * @returns {Promise<Array<number>>} An array of cumulus_ids for the returned records
110
+ * @param {Array<any>} values - record values for whereIn query
111
+ * @returns {Promise<Array>} An array of cumulus_ids for the returned records
78
112
  */
79
113
  async getRecordsCumulusIds(knexOrTransaction, columnNames, values) {
80
114
  const records = await knexOrTransaction(this.tableName)
@@ -106,12 +140,30 @@ class BasePgModel {
106
140
  *
107
141
  * @param {Knex | Knex.Transaction} knexOrTransaction - DB client or transaction
108
142
  * @param {ItemType} item - A record to insert into the DB
109
- * @returns {Promise<number[]>} List of IDs of the inserted records
143
+ * @param {string | Array<string>} returningFields - A string or array of strings
144
+ * of columns to return. Defaults to 'cumulus_id'.
145
+ * @returns {Promise<unknown[] | Object[]>} Returns an array of objects or an
146
+ * array of values from the specified column(s) from returningFields.
110
147
  */
111
- async create(knexOrTransaction, item) {
148
+ async create(knexOrTransaction, item, returningFields = 'cumulus_id') {
112
149
  return await knexOrTransaction(this.tableName)
113
150
  .insert(item)
114
- .returning('cumulus_id');
151
+ .returning(returningFields);
152
+ }
153
+ /**
154
+ * Creates multiple items in Postgres
155
+ *
156
+ * @param {Knex | Knex.Transaction} knexOrTransaction - DB client or transaction
157
+ * @param {ItemType[]} items - Records to insert into the DB
158
+ * @param {string | Array<string>} returningFields - A string or array of strings
159
+ * of columns to return. Defaults to 'cumulus_id'.
160
+ * @returns {Promise<unknown[] | Object[]>} Returns an array of objects or an
161
+ * array of values from the specified column(s) from returningFields.
162
+ */
163
+ async insert(knexOrTransaction, items, returningFields = 'cumulus_id') {
164
+ return await knexOrTransaction(this.tableName)
165
+ .insert(items)
166
+ .returning(returningFields);
115
167
  }
116
168
  /**
117
169
  * Deletes the item from Postgres
@@ -139,6 +191,22 @@ class BasePgModel {
139
191
  .where(whereClause)
140
192
  .update(updateParams, returning);
141
193
  }
194
+ /**
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
+ */
204
+ async deleteExcluding({ knexOrTransaction, excludeCumulusIds = [], queryParams, }) {
205
+ return await knexOrTransaction(this.tableName)
206
+ .where(queryParams)
207
+ .whereNotIn('cumulus_id', excludeCumulusIds)
208
+ .del();
209
+ }
142
210
  }
143
211
  exports.BasePgModel = BasePgModel;
144
212
  //# sourceMappingURL=base.js.map
@@ -3,12 +3,13 @@ import { BasePgModel } from './base';
3
3
  import { PostgresCollection, PostgresCollectionRecord } from '../types/collection';
4
4
  declare class CollectionPgModel extends BasePgModel<PostgresCollection, PostgresCollectionRecord> {
5
5
  constructor();
6
+ create(knexOrTransaction: Knex | Knex.Transaction, item: PostgresCollection): Promise<Object[] | unknown[]>;
6
7
  upsert(knexOrTransaction: Knex | Knex.Transaction, collection: PostgresCollection): Knex.QueryBuilder<any, {
7
8
  _base: any;
8
- _hasSelection: true;
9
- _keys: "name" | "version" | "cumulus_id";
9
+ _hasSelection: false;
10
+ _keys: never;
10
11
  _aliases: {};
11
- _single: true;
12
+ _single: false;
12
13
  _intersectProps: {};
13
14
  _unionProps: never;
14
15
  }[]>;
@@ -9,12 +9,15 @@ class CollectionPgModel extends base_1.BasePgModel {
9
9
  tableName: tables_1.TableNames.collections,
10
10
  });
11
11
  }
12
+ create(knexOrTransaction, item) {
13
+ return super.create(knexOrTransaction, item, '*');
14
+ }
12
15
  upsert(knexOrTransaction, collection) {
13
16
  return knexOrTransaction(this.tableName)
14
17
  .insert(collection)
15
18
  .onConflict(['name', 'version'])
16
19
  .merge()
17
- .returning('cumulus_id');
20
+ .returning('*');
18
21
  }
19
22
  }
20
23
  exports.CollectionPgModel = CollectionPgModel;
@@ -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
+ create(knexOrTransaction: Knex | Knex.Transaction, item: PostgresExecution): Promise<Object[] | unknown[]>;
6
7
  upsert(knexOrTrx: Knex | Knex.Transaction, execution: PostgresExecution): Promise<any[]>;
7
8
  /**
8
9
  * Get executions from the execution cumulus_id
@@ -10,6 +10,9 @@ class ExecutionPgModel extends base_1.BasePgModel {
10
10
  tableName: tables_1.TableNames.executions,
11
11
  });
12
12
  }
13
+ create(knexOrTransaction, item) {
14
+ return super.create(knexOrTransaction, item, '*');
15
+ }
13
16
  async upsert(knexOrTrx, execution) {
14
17
  if (execution.status === 'running') {
15
18
  return await knexOrTrx(this.tableName)
@@ -21,13 +24,13 @@ class ExecutionPgModel extends base_1.BasePgModel {
21
24
  timestamp: execution.timestamp,
22
25
  original_payload: execution.original_payload,
23
26
  })
24
- .returning('cumulus_id');
27
+ .returning('*');
25
28
  }
26
29
  return await knexOrTrx(this.tableName)
27
30
  .insert(execution)
28
31
  .onConflict('arn')
29
32
  .merge()
30
- .returning('cumulus_id');
33
+ .returning('*');
31
34
  }
32
35
  /**
33
36
  * Get executions from the execution cumulus_id
@@ -5,8 +5,8 @@ declare class FilePgModel extends BasePgModel<PostgresFile, PostgresFileRecord>
5
5
  constructor();
6
6
  upsert(knexOrTrx: Knex | Knex.Transaction, file: PostgresFile): Knex.QueryBuilder<any, {
7
7
  _base: any;
8
- _hasSelection: true;
9
- _keys: "key" | "bucket";
8
+ _hasSelection: false;
9
+ _keys: never;
10
10
  _aliases: {};
11
11
  _single: false;
12
12
  _intersectProps: {};
@@ -13,7 +13,8 @@ class FilePgModel extends base_1.BasePgModel {
13
13
  return knexOrTrx(this.tableName)
14
14
  .insert(file)
15
15
  .onConflict(['bucket', 'key'])
16
- .merge();
16
+ .merge()
17
+ .returning('*');
17
18
  }
18
19
  }
19
20
  exports.FilePgModel = FilePgModel;
@@ -7,6 +7,7 @@ interface RecordSelect {
7
7
  }
8
8
  export default class GranulePgModel extends BasePgModel<PostgresGranule, PostgresGranuleRecord> {
9
9
  constructor();
10
+ create(knexOrTransaction: Knex | Knex.Transaction, item: PostgresGranule): Promise<Object[] | unknown[]>;
10
11
  /**
11
12
  * Deletes the item from Postgres
12
13
  *
@@ -17,6 +18,7 @@ export default class GranulePgModel extends BasePgModel<PostgresGranule, Postgre
17
18
  delete(knexOrTransaction: Knex | Knex.Transaction, params: PostgresGranuleUniqueColumns | {
18
19
  cumulus_id: number;
19
20
  }): Promise<number>;
21
+ deleteExcluding(): Promise<never>;
20
22
  /**
21
23
  * Checks if a granule is present in PostgreSQL
22
24
  *
@@ -16,6 +16,9 @@ class GranulePgModel extends base_1.BasePgModel {
16
16
  tableName: tables_1.TableNames.granules,
17
17
  });
18
18
  }
19
+ create(knexOrTransaction, item) {
20
+ return super.create(knexOrTransaction, item, '*');
21
+ }
19
22
  /**
20
23
  * Deletes the item from Postgres
21
24
  *
@@ -28,6 +31,9 @@ class GranulePgModel extends base_1.BasePgModel {
28
31
  .where(params)
29
32
  .del();
30
33
  }
34
+ async deleteExcluding() {
35
+ throw new Error('deleteExcluding not implemented on granule class');
36
+ }
31
37
  /**
32
38
  * Checks if a granule is present in PostgreSQL
33
39
  *
@@ -88,7 +94,7 @@ class GranulePgModel extends base_1.BasePgModel {
88
94
  // will not affect any rows.
89
95
  upsertQuery.whereNotExists(granulesExecutionsPgModel.search(knexOrTrx, { execution_cumulus_id: executionCumulusId }));
90
96
  }
91
- upsertQuery.returning('cumulus_id');
97
+ upsertQuery.returning('*');
92
98
  return await upsertQuery;
93
99
  }
94
100
  return await knexOrTrx(this.tableName)
@@ -96,7 +102,7 @@ class GranulePgModel extends base_1.BasePgModel {
96
102
  .onConflict(['granule_id', 'collection_cumulus_id'])
97
103
  .merge()
98
104
  .where(knexOrTrx.raw(`${this.tableName}.created_at <= to_timestamp(${(0, timestamp_1.translateDateToUTC)(granule.created_at)})`))
99
- .returning('cumulus_id');
105
+ .returning('*');
100
106
  }
101
107
  /**
102
108
  * Get granules from the granule cumulus_id
@@ -26,14 +26,14 @@ class PdrPgModel extends base_1.BasePgModel {
26
26
  qb.where(knexOrTrx.raw(`${this.tableName}.execution_cumulus_id != EXCLUDED.execution_cumulus_id`))
27
27
  .orWhere(knexOrTrx.raw(`${this.tableName}.progress < EXCLUDED.progress`));
28
28
  })
29
- .returning('cumulus_id');
29
+ .returning('*');
30
30
  }
31
31
  return await knexOrTrx(this.tableName)
32
32
  .insert(pdr)
33
33
  .onConflict('name')
34
34
  .merge()
35
35
  .where(knexOrTrx.raw(`${this.tableName}.created_at <= to_timestamp(${(0, timestamp_1.translateDateToUTC)(pdr.created_at)})`))
36
- .returning('cumulus_id');
36
+ .returning('*');
37
37
  }
38
38
  }
39
39
  exports.default = PdrPgModel;
@@ -58,6 +58,9 @@ const fakeCollectionRecordFactory = (params) => ({
58
58
  regex: 'fake-regex',
59
59
  sampleFileName: 'file.txt',
60
60
  }]),
61
+ meta: { foo: 'bar' },
62
+ created_at: new Date(),
63
+ updated_at: new Date(),
61
64
  ...params,
62
65
  });
63
66
  exports.fakeCollectionRecordFactory = fakeCollectionRecordFactory;
@@ -1,4 +1,17 @@
1
1
  import { ApiAsyncOperation } from '@cumulus/types/api/async_operations';
2
2
  import { PostgresAsyncOperation } from '../types/async_operation';
3
+ /**
4
+ * Generate a PostgreSQL Async Operation record from an API record.
5
+ *
6
+ * @param {Object} record - An API Async Operation record
7
+ * @returns {Object} A PostgreSQL Async Operation record
8
+ */
3
9
  export declare const translateApiAsyncOperationToPostgresAsyncOperation: (record: ApiAsyncOperation) => PostgresAsyncOperation;
10
+ /**
11
+ * Generate an API Async Operation record from a PostgreSQL record.
12
+ *
13
+ * @param {Object} pgAsyncOperation - A PostgreSQL async operation record
14
+ * @returns {Object} An Async Operation API record
15
+ */
16
+ export declare const translatePostgresAsyncOperationToApiAsyncOperation: (pgAsyncOperation: PostgresAsyncOperation) => ApiAsyncOperation;
4
17
  //# sourceMappingURL=async_operations.d.ts.map