forest-cli 3.0.11 → 3.0.12-beta.1
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/bin/run +1 -1
- package/oclif.manifest.json +1 -1
- package/package.json +17 -8
- package/src/abstract-authenticated-command.js +0 -46
- package/src/abstract-command.js +0 -27
- package/src/commands/branch.js +0 -136
- package/src/commands/deploy.js +0 -90
- package/src/commands/environments/copy-layout.js +0 -116
- package/src/commands/environments/create.js +0 -62
- package/src/commands/environments/delete.js +0 -81
- package/src/commands/environments/get.js +0 -48
- package/src/commands/environments/reset.js +0 -76
- package/src/commands/environments/update.js +0 -46
- package/src/commands/environments.js +0 -41
- package/src/commands/init.js +0 -169
- package/src/commands/login.js +0 -34
- package/src/commands/logout.js +0 -18
- package/src/commands/projects/create.js +0 -262
- package/src/commands/projects/get.js +0 -53
- package/src/commands/projects.js +0 -36
- package/src/commands/push.js +0 -75
- package/src/commands/schema/apply.js +0 -140
- package/src/commands/schema/update.js +0 -70
- package/src/commands/set-origin.js +0 -59
- package/src/commands/switch.js +0 -117
- package/src/commands/user.js +0 -44
- package/src/context/command-project-create-plan.js +0 -11
- package/src/context/command-projects-common-plan.js +0 -65
- package/src/context/command-schema-update-command-plan.js +0 -4
- package/src/context/dependencies-plan.js +0 -21
- package/src/context/env-plan.js +0 -27
- package/src/context/plan.js +0 -12
- package/src/context/process-plan.js +0 -3
- package/src/context/renderers-plan.js +0 -7
- package/src/context/serializers-plan.js +0 -8
- package/src/context/services-plan.js +0 -8
- package/src/context/static.js +0 -19
- package/src/context/utils-plan.js +0 -7
- package/src/deserializers/api-error.js +0 -21
- package/src/deserializers/application-token.js +0 -15
- package/src/deserializers/branch.js +0 -8
- package/src/deserializers/environment.js +0 -5
- package/src/deserializers/job.js +0 -5
- package/src/deserializers/project.js +0 -11
- package/src/errors/application-error.js +0 -9
- package/src/errors/application-token/unable-to-create-application-token-error.js +0 -16
- package/src/errors/database/empty-database-error.js +0 -5
- package/src/errors/dumper/incompatible-liana-for-update-error.js +0 -16
- package/src/errors/dumper/invalid-forest-cli-project-structure-error.js +0 -16
- package/src/errors/forest-cli-error.js +0 -32
- package/src/index.js +0 -1
- package/src/renderers/branches.js +0 -45
- package/src/renderers/defaults.js +0 -19
- package/src/renderers/environment.js +0 -51
- package/src/renderers/environments.js +0 -51
- package/src/renderers/project.js +0 -45
- package/src/renderers/projects.js +0 -45
- package/src/serializers/application-token.js +0 -11
- package/src/serializers/deployment-request.js +0 -5
- package/src/serializers/environment.js +0 -20
- package/src/serializers/job.js +0 -5
- package/src/serializers/project.js +0 -17
- package/src/serializers/schema.js +0 -116
- package/src/services/api.js +0 -110
- package/src/services/apimap-sorter.js +0 -104
- package/src/services/application-token.js +0 -56
- package/src/services/ask-for-environment.js +0 -24
- package/src/services/authenticator.js +0 -187
- package/src/services/branch-manager.js +0 -169
- package/src/services/dumper/dumper.js +0 -503
- package/src/services/dumper/handlebars/helpers/equal.js +0 -3
- package/src/services/dumper/handlebars/helpers/indent.js +0 -3
- package/src/services/dumper/handlebars/helpers/is-array.js +0 -3
- package/src/services/dumper/handlebars/helpers/is-object.js +0 -3
- package/src/services/dumper/handlebars/helpers/sum.js +0 -3
- package/src/services/dumper/handlebars/helpers/wrap-quotes.js +0 -7
- package/src/services/dumper/handlebars/loader.js +0 -10
- package/src/services/dumper/handlebars/partials/render-nested.js +0 -27
- package/src/services/dumper/templates/app/Dockerfile.hbs +0 -6
- package/src/services/dumper/templates/app/app.hbs +0 -79
- package/src/services/dumper/templates/app/config/databases.hbs +0 -49
- package/src/services/dumper/templates/app/docker-compose.hbs +0 -33
- package/src/services/dumper/templates/app/dockerignore.hbs +0 -3
- package/src/services/dumper/templates/app/env.hbs +0 -20
- package/src/services/dumper/templates/app/forest/collection.hbs +0 -13
- package/src/services/dumper/templates/app/gitignore.hbs +0 -3
- package/src/services/dumper/templates/app/middlewares/forestadmin.hbs +0 -21
- package/src/services/dumper/templates/app/middlewares/welcome.hbs +0 -7
- package/src/services/dumper/templates/app/models/index.hbs +0 -56
- package/src/services/dumper/templates/app/models/mongo-model.hbs +0 -16
- package/src/services/dumper/templates/app/models/sequelize-model.hbs +0 -48
- package/src/services/dumper/templates/app/public/favicon.png +0 -0
- package/src/services/dumper/templates/app/routes/route.hbs +0 -61
- package/src/services/dumper/templates/app/server.hbs +0 -56
- package/src/services/dumper/templates/app/views/index.hbs +0 -73
- package/src/services/environment-manager.js +0 -139
- package/src/services/init-manager.js +0 -183
- package/src/services/job-state-checker.js +0 -57
- package/src/services/logger.js +0 -125
- package/src/services/oidc/authenticator.js +0 -109
- package/src/services/oidc/error.js +0 -32
- package/src/services/project-manager.js +0 -89
- package/src/services/projects/create/command-generate-config-getter.js +0 -61
- package/src/services/projects/create/project-creator.js +0 -89
- package/src/services/prompter/abstract-prompter.js +0 -13
- package/src/services/prompter/application-prompts.js +0 -63
- package/src/services/prompter/database-prompts.js +0 -208
- package/src/services/prompter/general-prompter.js +0 -61
- package/src/services/prompter/project-prompts.js +0 -47
- package/src/services/prompter/prompter-error.js +0 -10
- package/src/services/schema/schema-service.js +0 -154
- package/src/services/schema/update/analyzer/database-analyzer.js +0 -64
- package/src/services/schema/update/analyzer/mongo-collections-analyzer.js +0 -344
- package/src/services/schema/update/analyzer/mongo-embedded-analyzer.js +0 -226
- package/src/services/schema/update/analyzer/mongo-hasmany-analyzer.js +0 -55
- package/src/services/schema/update/analyzer/mongo-references-analyzer.js +0 -51
- package/src/services/schema/update/analyzer/mysql-table-constraints-getter.js +0 -59
- package/src/services/schema/update/analyzer/sequelize-column-type-getter.js +0 -147
- package/src/services/schema/update/analyzer/sequelize-default-value.js +0 -122
- package/src/services/schema/update/analyzer/sequelize-table-constraints-getter.js +0 -298
- package/src/services/schema/update/analyzer/sequelize-tables-analyzer.js +0 -529
- package/src/services/schema/update/database.js +0 -160
- package/src/services/schema-sender.js +0 -55
- package/src/services/spinner.js +0 -130
- package/src/services/with-current-project.js +0 -41
- package/src/utils/database-url.js +0 -33
- package/src/utils/directory-existence-checker.js +0 -17
- package/src/utils/error-handler.js +0 -63
- package/src/utils/error.js +0 -21
- package/src/utils/event-sender.js +0 -80
- package/src/utils/fields.js +0 -14
- package/src/utils/key-generator.js +0 -18
- package/src/utils/messages.js +0 -7
- package/src/utils/mongo-collections.js +0 -35
- package/src/utils/mongo-primitive-type.js +0 -44
- package/src/utils/strings.js +0 -49
- package/src/utils/terminator.js +0 -38
- package/src/utils/to-valid-package-name.js +0 -24
|
@@ -1,529 +0,0 @@
|
|
|
1
|
-
const { inject } = require('@forestadmin/context');
|
|
2
|
-
const P = require('bluebird');
|
|
3
|
-
const _ = require('lodash');
|
|
4
|
-
const { plural, singular } = require('pluralize');
|
|
5
|
-
const ColumnTypeGetter = require('./sequelize-column-type-getter');
|
|
6
|
-
const DefaultValueExpression = require('./sequelize-default-value');
|
|
7
|
-
const TableConstraintsGetter = require('./sequelize-table-constraints-getter');
|
|
8
|
-
const EmptyDatabaseError = require('../../../../errors/database/empty-database-error');
|
|
9
|
-
const stringUtils = require('../../../../utils/strings');
|
|
10
|
-
const { isUnderscored } = require('../../../../utils/fields');
|
|
11
|
-
|
|
12
|
-
const ASSOCIATION_TYPE_BELONGS_TO = 'belongsTo';
|
|
13
|
-
const ASSOCIATION_TYPE_BELONGS_TO_MANY = 'belongsToMany';
|
|
14
|
-
const ASSOCIATION_TYPE_HAS_MANY = 'hasMany';
|
|
15
|
-
const ASSOCIATION_TYPE_HAS_ONE = 'hasOne';
|
|
16
|
-
|
|
17
|
-
const FOREIGN_KEY = 'FOREIGN KEY';
|
|
18
|
-
|
|
19
|
-
/** Queries database for default schema name */
|
|
20
|
-
async function getDefaultSchema(connection, userProvidedSchema) {
|
|
21
|
-
if (userProvidedSchema) {
|
|
22
|
-
return userProvidedSchema;
|
|
23
|
-
}
|
|
24
|
-
|
|
25
|
-
const dialect = connection.getDialect();
|
|
26
|
-
const queries = {
|
|
27
|
-
mssql: 'SELECT SCHEMA_NAME() AS default_schema',
|
|
28
|
-
mysql: 'SELECT DATABASE() AS default_schema',
|
|
29
|
-
mariadb: 'SELECT DATABASE() AS default_schema',
|
|
30
|
-
postgres: 'SELECT CURRENT_SCHEMA() AS default_schema',
|
|
31
|
-
};
|
|
32
|
-
|
|
33
|
-
if (queries[dialect]) {
|
|
34
|
-
const rows = await connection.query(
|
|
35
|
-
queries[dialect],
|
|
36
|
-
{ type: connection.QueryTypes.SELECT },
|
|
37
|
-
);
|
|
38
|
-
|
|
39
|
-
return rows.length && rows[0].default_schema
|
|
40
|
-
? rows[0].default_schema : 'public';
|
|
41
|
-
}
|
|
42
|
-
|
|
43
|
-
return 'public';
|
|
44
|
-
}
|
|
45
|
-
|
|
46
|
-
/** Retrieve the description of the fields in a given table. */
|
|
47
|
-
async function analyzeFields(queryInterface, tableName, config) {
|
|
48
|
-
const dialect = queryInterface.sequelize.getDialect();
|
|
49
|
-
let columnsByName;
|
|
50
|
-
|
|
51
|
-
// Workaround bug in sequelize/dialects/mysql/query-generator#describe
|
|
52
|
-
// => Don't provide the schema when using mysql/mariadb
|
|
53
|
-
if (['mysql', 'mariadb'].includes(dialect)) {
|
|
54
|
-
columnsByName = await queryInterface.describeTable(tableName, {});
|
|
55
|
-
} else {
|
|
56
|
-
columnsByName = await queryInterface.describeTable(tableName, { schema: config.dbSchema });
|
|
57
|
-
}
|
|
58
|
-
|
|
59
|
-
// Workaround bug in sequelize/dialects/(postgres|mssql)/query.js#run()
|
|
60
|
-
// => Fetch the unmodified default value from the information schema
|
|
61
|
-
if (dialect === 'postgres' || dialect === 'mssql') {
|
|
62
|
-
const getDefaultsQuery = `
|
|
63
|
-
SELECT column_name as colname, column_default as coldefault
|
|
64
|
-
FROM information_schema.columns
|
|
65
|
-
WHERE table_schema = ? AND table_name = ?
|
|
66
|
-
`;
|
|
67
|
-
|
|
68
|
-
const rows = await queryInterface.sequelize.query(getDefaultsQuery, {
|
|
69
|
-
type: queryInterface.sequelize.QueryTypes.SELECT,
|
|
70
|
-
replacements: [config.dbSchema, tableName],
|
|
71
|
-
});
|
|
72
|
-
rows.forEach((row) => {
|
|
73
|
-
columnsByName[row.colname].defaultValue = row.coldefault;
|
|
74
|
-
});
|
|
75
|
-
}
|
|
76
|
-
|
|
77
|
-
Object.values(columnsByName).forEach((column) => {
|
|
78
|
-
const defaultValue = new DefaultValueExpression(dialect, column.type, column.defaultValue);
|
|
79
|
-
// eslint-disable-next-line no-param-reassign
|
|
80
|
-
column.defaultValue = defaultValue.parse();
|
|
81
|
-
});
|
|
82
|
-
|
|
83
|
-
return columnsByName;
|
|
84
|
-
}
|
|
85
|
-
|
|
86
|
-
async function analyzePrimaryKeys(schema) {
|
|
87
|
-
return Object.keys(schema).filter((column) => schema[column].primaryKey);
|
|
88
|
-
}
|
|
89
|
-
|
|
90
|
-
/** Retrieve table names from the provided schema. */
|
|
91
|
-
async function showAllTables(queryInterface, databaseConnection, schema) {
|
|
92
|
-
const dbDialect = databaseConnection.getDialect();
|
|
93
|
-
|
|
94
|
-
if (['mysql', 'mariadb'].includes(dbDialect)) {
|
|
95
|
-
return queryInterface.showAllTables();
|
|
96
|
-
}
|
|
97
|
-
|
|
98
|
-
const tables = await queryInterface.sequelize.query(
|
|
99
|
-
'SELECT table_name as table_name FROM INFORMATION_SCHEMA.TABLES WHERE table_schema = ? AND table_type LIKE \'%TABLE\' AND table_name != \'spatial_ref_sys\'',
|
|
100
|
-
{ type: queryInterface.sequelize.QueryTypes.SELECT, replacements: [schema] },
|
|
101
|
-
);
|
|
102
|
-
|
|
103
|
-
return tables.map((table) => table.table_name);
|
|
104
|
-
}
|
|
105
|
-
|
|
106
|
-
function hasTimestamps(fields) {
|
|
107
|
-
let hasCreatedAt = false;
|
|
108
|
-
let hasUpdatedAt = false;
|
|
109
|
-
|
|
110
|
-
fields.forEach((field) => {
|
|
111
|
-
if (field.name === 'createdAt') {
|
|
112
|
-
hasCreatedAt = true;
|
|
113
|
-
}
|
|
114
|
-
|
|
115
|
-
if (field.name === 'updatedAt') {
|
|
116
|
-
hasUpdatedAt = true;
|
|
117
|
-
}
|
|
118
|
-
});
|
|
119
|
-
|
|
120
|
-
return hasCreatedAt && hasUpdatedAt;
|
|
121
|
-
}
|
|
122
|
-
|
|
123
|
-
function formatAliasName(columnName) {
|
|
124
|
-
const alias = _.camelCase(columnName);
|
|
125
|
-
if (alias.endsWith('Id') && alias.length > 2) {
|
|
126
|
-
return alias.substring(0, alias.length - 2);
|
|
127
|
-
}
|
|
128
|
-
if (alias.endsWith('Uuid') && alias.length > 4) {
|
|
129
|
-
return alias.substring(0, alias.length - 4);
|
|
130
|
-
}
|
|
131
|
-
return alias;
|
|
132
|
-
}
|
|
133
|
-
|
|
134
|
-
// NOTICE: Look for the id column in both fields and primary keys.
|
|
135
|
-
function hasIdColumn(fields, primaryKeys) {
|
|
136
|
-
return fields.some((field) => field.name === 'id' || field.nameColumn === 'id')
|
|
137
|
-
|| _.includes(primaryKeys, 'id');
|
|
138
|
-
}
|
|
139
|
-
|
|
140
|
-
function isTechnicalTimestamp({ type, name }) {
|
|
141
|
-
// NOTICE: Ignore technical timestamp fields.
|
|
142
|
-
const FIELDS_TO_IGNORE = [
|
|
143
|
-
'createdAt', 'updatedAt', 'deletedAt',
|
|
144
|
-
'createDate', 'updateDate', 'deleteDate',
|
|
145
|
-
'creationDate', 'deletionDate',
|
|
146
|
-
];
|
|
147
|
-
|
|
148
|
-
return type === 'DATE' && FIELDS_TO_IGNORE.includes(name);
|
|
149
|
-
}
|
|
150
|
-
|
|
151
|
-
function isJunctionTable(fields, constraints) {
|
|
152
|
-
for (let index = 0; index < fields.length; index += 1) {
|
|
153
|
-
const field = fields[index];
|
|
154
|
-
|
|
155
|
-
// NOTICE: The only fields accepted are primary keys, technical timestamps and foreignKeys
|
|
156
|
-
if (!isTechnicalTimestamp(field) && !field.primaryKey) {
|
|
157
|
-
return false;
|
|
158
|
-
}
|
|
159
|
-
}
|
|
160
|
-
|
|
161
|
-
const foreignKeys = constraints.filter((constraint) => constraint.foreignTableName
|
|
162
|
-
&& constraint.columnName
|
|
163
|
-
&& constraint.columnType === FOREIGN_KEY);
|
|
164
|
-
// NOTICE: To be a junction table it means you have 2 foreignKeys, no more no less
|
|
165
|
-
return foreignKeys.length === 2;
|
|
166
|
-
}
|
|
167
|
-
|
|
168
|
-
// NOTICE: Check the foreign key's reference unicity
|
|
169
|
-
function checkUnicity(primaryKeys, uniqueIndexes, columnName) {
|
|
170
|
-
const isUnique = uniqueIndexes !== null
|
|
171
|
-
&& uniqueIndexes.find((indexColumnName) =>
|
|
172
|
-
indexColumnName.length === 1 && indexColumnName.includes(columnName));
|
|
173
|
-
|
|
174
|
-
const isPrimary = _.isEqual([columnName], primaryKeys);
|
|
175
|
-
|
|
176
|
-
return isPrimary || isUnique;
|
|
177
|
-
}
|
|
178
|
-
|
|
179
|
-
function associationNameAlreadyExists(existingReferences, newReference) {
|
|
180
|
-
return existingReferences.some((reference) => reference && reference.as === newReference.as);
|
|
181
|
-
}
|
|
182
|
-
|
|
183
|
-
function referenceAlreadyExists(existingReferences, newReference) {
|
|
184
|
-
return existingReferences.some((reference) => (
|
|
185
|
-
reference
|
|
186
|
-
&& reference.ref === newReference.ref
|
|
187
|
-
&& reference.association === newReference.association
|
|
188
|
-
&& reference.foreignKey === newReference.foreignKey
|
|
189
|
-
));
|
|
190
|
-
}
|
|
191
|
-
|
|
192
|
-
// NOTICE: Format the references depending on the type of the association
|
|
193
|
-
function createReference(
|
|
194
|
-
tableName,
|
|
195
|
-
existingsReferences,
|
|
196
|
-
association,
|
|
197
|
-
foreignKey,
|
|
198
|
-
manyToManyForeignKey,
|
|
199
|
-
) {
|
|
200
|
-
const foreignKeyName = _.camelCase(foreignKey.columnName);
|
|
201
|
-
const reference = {
|
|
202
|
-
foreignKey: foreignKey.columnName,
|
|
203
|
-
foreignKeyName: `${foreignKeyName}Key`,
|
|
204
|
-
association,
|
|
205
|
-
};
|
|
206
|
-
|
|
207
|
-
if (association === ASSOCIATION_TYPE_BELONGS_TO) {
|
|
208
|
-
reference.ref = foreignKey.foreignTableName;
|
|
209
|
-
reference.as = formatAliasName(foreignKey.columnName);
|
|
210
|
-
if (foreignKey.foreignColumnName !== 'id') {
|
|
211
|
-
reference.targetKey = foreignKey.foreignColumnName;
|
|
212
|
-
}
|
|
213
|
-
} else if (association === ASSOCIATION_TYPE_BELONGS_TO_MANY) {
|
|
214
|
-
reference.ref = manyToManyForeignKey.foreignTableName;
|
|
215
|
-
reference.otherKey = manyToManyForeignKey.columnName;
|
|
216
|
-
reference.through = stringUtils.camelCase(
|
|
217
|
-
stringUtils.transformToSafeString(foreignKey.tableName),
|
|
218
|
-
);
|
|
219
|
-
reference.as = _.camelCase(plural(`${manyToManyForeignKey.foreignTableName}_through_${foreignKey.tableName}`));
|
|
220
|
-
} else {
|
|
221
|
-
reference.ref = foreignKey.tableName;
|
|
222
|
-
|
|
223
|
-
const formater = association === ASSOCIATION_TYPE_HAS_MANY ? plural : singular;
|
|
224
|
-
const prefix = (singular(tableName) === formatAliasName(foreignKeyName))
|
|
225
|
-
? ''
|
|
226
|
-
: `${formatAliasName(foreignKeyName)}_`;
|
|
227
|
-
|
|
228
|
-
if (foreignKey.foreignColumnName !== 'id') {
|
|
229
|
-
reference.sourceKey = foreignKey.foreignColumnName;
|
|
230
|
-
}
|
|
231
|
-
reference.as = _.camelCase(formater(`${prefix}${foreignKey.tableName}`));
|
|
232
|
-
}
|
|
233
|
-
|
|
234
|
-
if (referenceAlreadyExists(existingsReferences, reference)) return null;
|
|
235
|
-
|
|
236
|
-
if (associationNameAlreadyExists(existingsReferences, reference)) {
|
|
237
|
-
reference.as = _.camelCase(`${reference.as} ${reference.foreignKey}`);
|
|
238
|
-
}
|
|
239
|
-
|
|
240
|
-
return reference;
|
|
241
|
-
}
|
|
242
|
-
|
|
243
|
-
async function analyzeTable(queryInterface, tableConstraintsGetter, table, config) {
|
|
244
|
-
const schema = await analyzeFields(queryInterface, table, config);
|
|
245
|
-
|
|
246
|
-
return {
|
|
247
|
-
schema,
|
|
248
|
-
constraints: await tableConstraintsGetter.perform(table),
|
|
249
|
-
primaryKeys: await analyzePrimaryKeys(schema),
|
|
250
|
-
};
|
|
251
|
-
}
|
|
252
|
-
|
|
253
|
-
function createBelongsToReference(referenceTable, tableReferences, constraint) {
|
|
254
|
-
const referenceColumnName = constraint.foreignColumnName;
|
|
255
|
-
const referencePrimaryKeys = referenceTable.primaryKeys;
|
|
256
|
-
const referenceUniqueConstraint = referenceTable.constraints
|
|
257
|
-
.find(({ columnType }) => ['UNIQUE', 'PRIMARY KEY'].includes(columnType));
|
|
258
|
-
const referenceUniqueIndexes = referenceUniqueConstraint
|
|
259
|
-
? referenceUniqueConstraint.uniqueIndexes
|
|
260
|
-
: null;
|
|
261
|
-
const isReferencePrimaryOrUnique = checkUnicity(
|
|
262
|
-
referencePrimaryKeys,
|
|
263
|
-
referenceUniqueIndexes,
|
|
264
|
-
referenceColumnName,
|
|
265
|
-
);
|
|
266
|
-
|
|
267
|
-
if (isReferencePrimaryOrUnique) {
|
|
268
|
-
return createReference(
|
|
269
|
-
null,
|
|
270
|
-
tableReferences,
|
|
271
|
-
ASSOCIATION_TYPE_BELONGS_TO,
|
|
272
|
-
constraint,
|
|
273
|
-
);
|
|
274
|
-
}
|
|
275
|
-
return null;
|
|
276
|
-
}
|
|
277
|
-
|
|
278
|
-
// NOTICE: Use the foreign key and reference properties to determine the associations
|
|
279
|
-
// and push them as references of the table.
|
|
280
|
-
function createAllReferences(databaseSchema, schemaGenerated) {
|
|
281
|
-
const references = {};
|
|
282
|
-
Object.keys(databaseSchema).forEach((tableName) => { references[tableName] = []; });
|
|
283
|
-
|
|
284
|
-
Object.keys(databaseSchema).forEach((tableName) => {
|
|
285
|
-
const table = databaseSchema[tableName];
|
|
286
|
-
const { constraints, primaryKeys } = table;
|
|
287
|
-
const { isJunction } = schemaGenerated[tableName].options;
|
|
288
|
-
|
|
289
|
-
const foreignKeysWithExistingTable = constraints
|
|
290
|
-
.filter((constraint) => constraint.columnType === FOREIGN_KEY
|
|
291
|
-
&& databaseSchema[constraint.foreignTableName]);
|
|
292
|
-
|
|
293
|
-
foreignKeysWithExistingTable.forEach((constraint) => {
|
|
294
|
-
const { columnName } = constraint;
|
|
295
|
-
const uniqueIndexes = constraint.uniqueIndexes || null;
|
|
296
|
-
|
|
297
|
-
const isPrimaryOrUnique = checkUnicity(primaryKeys, uniqueIndexes, columnName);
|
|
298
|
-
|
|
299
|
-
const referenceTableName = constraint.foreignTableName;
|
|
300
|
-
|
|
301
|
-
if (isJunction) {
|
|
302
|
-
const manyToManyKeys = foreignKeysWithExistingTable
|
|
303
|
-
.filter((otherKey) => otherKey.columnName !== constraint.columnName);
|
|
304
|
-
|
|
305
|
-
manyToManyKeys.forEach((manyToManyKey) => {
|
|
306
|
-
references[referenceTableName].push(
|
|
307
|
-
createReference(
|
|
308
|
-
referenceTableName,
|
|
309
|
-
references[referenceTableName],
|
|
310
|
-
ASSOCIATION_TYPE_BELONGS_TO_MANY,
|
|
311
|
-
constraint,
|
|
312
|
-
manyToManyKey,
|
|
313
|
-
),
|
|
314
|
-
);
|
|
315
|
-
});
|
|
316
|
-
} else {
|
|
317
|
-
references[referenceTableName].push(
|
|
318
|
-
createReference(
|
|
319
|
-
referenceTableName,
|
|
320
|
-
references[referenceTableName],
|
|
321
|
-
isPrimaryOrUnique ? ASSOCIATION_TYPE_HAS_ONE : ASSOCIATION_TYPE_HAS_MANY,
|
|
322
|
-
constraint,
|
|
323
|
-
),
|
|
324
|
-
);
|
|
325
|
-
}
|
|
326
|
-
|
|
327
|
-
references[tableName].push(
|
|
328
|
-
createBelongsToReference(
|
|
329
|
-
databaseSchema[referenceTableName],
|
|
330
|
-
references[tableName],
|
|
331
|
-
constraint,
|
|
332
|
-
),
|
|
333
|
-
);
|
|
334
|
-
});
|
|
335
|
-
});
|
|
336
|
-
|
|
337
|
-
// remove null references
|
|
338
|
-
return Object.entries(references)
|
|
339
|
-
.reduce(
|
|
340
|
-
(accumulator, [tableName, tableReferences]) => {
|
|
341
|
-
accumulator[tableName] = tableReferences.filter(Boolean);
|
|
342
|
-
return accumulator;
|
|
343
|
-
},
|
|
344
|
-
{},
|
|
345
|
-
);
|
|
346
|
-
}
|
|
347
|
-
|
|
348
|
-
function isOnlyJoinTableWithId(schema, constraints) {
|
|
349
|
-
const idColumn = Object.keys(schema).find((columnName) => columnName === 'id');
|
|
350
|
-
|
|
351
|
-
if (!idColumn) return false;
|
|
352
|
-
|
|
353
|
-
const possibleForeignColumnNames = Object.keys(schema)
|
|
354
|
-
.filter((columnName) => !isTechnicalTimestamp(schema[columnName]) && columnName !== 'id');
|
|
355
|
-
|
|
356
|
-
const columnWithoutForeignKey = possibleForeignColumnNames
|
|
357
|
-
.find((columnName) => !_.find(constraints, { columnName, columnType: FOREIGN_KEY }));
|
|
358
|
-
|
|
359
|
-
return !columnWithoutForeignKey;
|
|
360
|
-
}
|
|
361
|
-
|
|
362
|
-
async function createTableSchema(columnTypeGetter, {
|
|
363
|
-
schema,
|
|
364
|
-
constraints,
|
|
365
|
-
primaryKeys,
|
|
366
|
-
}, tableName) {
|
|
367
|
-
const fields = [];
|
|
368
|
-
|
|
369
|
-
await P.each(Object.keys(schema), async (columnName) => {
|
|
370
|
-
const columnInfo = schema[columnName];
|
|
371
|
-
const type = await columnTypeGetter.perform(columnInfo, columnName, tableName);
|
|
372
|
-
const foreignKey = _.find(constraints, { columnName, columnType: FOREIGN_KEY });
|
|
373
|
-
const isValidField = type && (!foreignKey
|
|
374
|
-
|| !foreignKey.foreignTableName
|
|
375
|
-
|| !foreignKey.columnName || columnInfo.primaryKey);
|
|
376
|
-
// NOTICE: If the column is of integer type, named "id" and primary, Sequelize will handle it
|
|
377
|
-
// automatically without necessary declaration.
|
|
378
|
-
const isIdIntegerPrimaryColumn = columnName === 'id'
|
|
379
|
-
&& ['INTEGER', 'BIGINT'].includes(type)
|
|
380
|
-
&& columnInfo.primaryKey;
|
|
381
|
-
// NOTICE: But in some cases we want to force the id to be still generated.
|
|
382
|
-
// For example, Sequelize will not use a default id field on a model
|
|
383
|
-
// that has only foreign keys, so if the id primary key is present, we need to force it.
|
|
384
|
-
const forceIdColumn = isIdIntegerPrimaryColumn && isOnlyJoinTableWithId(schema, constraints);
|
|
385
|
-
|
|
386
|
-
if (isValidField && (!isIdIntegerPrimaryColumn || forceIdColumn)) {
|
|
387
|
-
// NOTICE: sequelize considers column name with parenthesis as raw Attributes
|
|
388
|
-
// do not try to camelCase the name for avoiding sequelize issues
|
|
389
|
-
const hasParenthesis = columnName.includes('(') || columnName.includes(')');
|
|
390
|
-
const name = hasParenthesis ? columnName : _.camelCase(columnName);
|
|
391
|
-
let isRequired = !columnInfo.allowNull;
|
|
392
|
-
if (isTechnicalTimestamp({ name, type })) {
|
|
393
|
-
isRequired = false;
|
|
394
|
-
}
|
|
395
|
-
|
|
396
|
-
const field = {
|
|
397
|
-
name,
|
|
398
|
-
nameColumn: columnName,
|
|
399
|
-
type,
|
|
400
|
-
primaryKey: columnInfo.primaryKey,
|
|
401
|
-
defaultValue: columnInfo.defaultValue,
|
|
402
|
-
isRequired,
|
|
403
|
-
};
|
|
404
|
-
|
|
405
|
-
fields.push(field);
|
|
406
|
-
}
|
|
407
|
-
});
|
|
408
|
-
|
|
409
|
-
const options = {
|
|
410
|
-
underscored: isUnderscored(fields),
|
|
411
|
-
timestamps: hasTimestamps(fields),
|
|
412
|
-
hasIdColumn: hasIdColumn(fields, primaryKeys),
|
|
413
|
-
hasPrimaryKeys: !_.isEmpty(primaryKeys),
|
|
414
|
-
isJunction: isJunctionTable(fields, constraints),
|
|
415
|
-
};
|
|
416
|
-
|
|
417
|
-
return {
|
|
418
|
-
fields,
|
|
419
|
-
primaryKeys,
|
|
420
|
-
options,
|
|
421
|
-
};
|
|
422
|
-
}
|
|
423
|
-
|
|
424
|
-
// NOTICE: This detects two generated fields (regular or reference's alias) with the same name
|
|
425
|
-
// and rename reference's alias as `Linked${collectionReferenced}` to prevent Sequelize
|
|
426
|
-
// from crashing at startup.
|
|
427
|
-
function fixAliasConflicts(wholeSchema) {
|
|
428
|
-
const tablesName = Object.keys(wholeSchema);
|
|
429
|
-
|
|
430
|
-
if (!tablesName.length) { return; }
|
|
431
|
-
|
|
432
|
-
tablesName.forEach((tableName) => {
|
|
433
|
-
const table = wholeSchema[tableName];
|
|
434
|
-
|
|
435
|
-
if (table.references.length && table.fields.length) {
|
|
436
|
-
const fieldNames = table.fields.map((field) => field.name);
|
|
437
|
-
|
|
438
|
-
table.references.forEach((reference, index) => {
|
|
439
|
-
if (fieldNames.includes(reference.as)) {
|
|
440
|
-
table.references[index].as = `linked${_.upperFirst(reference.as)}`;
|
|
441
|
-
}
|
|
442
|
-
});
|
|
443
|
-
}
|
|
444
|
-
});
|
|
445
|
-
}
|
|
446
|
-
|
|
447
|
-
async function analyzeSequelizeTables(connection, config, allowWarning) {
|
|
448
|
-
// User provided a schema, check if it exists
|
|
449
|
-
if (config.dbSchema) {
|
|
450
|
-
const schemas = await connection.query(
|
|
451
|
-
'SELECT SCHEMA_NAME FROM INFORMATION_SCHEMA.SCHEMATA WHERE SCHEMA_NAME = ?;',
|
|
452
|
-
{ type: connection.QueryTypes.SELECT, replacements: [config.dbSchema] },
|
|
453
|
-
);
|
|
454
|
-
|
|
455
|
-
if (!schemas.length) {
|
|
456
|
-
const message = 'This schema does not exists.';
|
|
457
|
-
|
|
458
|
-
return inject().terminator.terminate(1, {
|
|
459
|
-
errorCode: 'database_authentication_error',
|
|
460
|
-
errorMessage: message,
|
|
461
|
-
logs: [message],
|
|
462
|
-
});
|
|
463
|
-
}
|
|
464
|
-
}
|
|
465
|
-
|
|
466
|
-
// If dbSchema was not provided by user, get default one.
|
|
467
|
-
const configWithSchema = {
|
|
468
|
-
...config,
|
|
469
|
-
dbSchema: await getDefaultSchema(connection, config.dbSchema),
|
|
470
|
-
};
|
|
471
|
-
|
|
472
|
-
// Build the db schema.
|
|
473
|
-
const schemaAllTables = {};
|
|
474
|
-
const queryInterface = connection.getQueryInterface();
|
|
475
|
-
const databaseSchema = {};
|
|
476
|
-
const tableNames = await showAllTables(queryInterface, connection, configWithSchema.dbSchema);
|
|
477
|
-
const constraintsGetter = new TableConstraintsGetter(connection, configWithSchema.dbSchema);
|
|
478
|
-
|
|
479
|
-
await P.each(tableNames, async (tableName) => {
|
|
480
|
-
const {
|
|
481
|
-
schema,
|
|
482
|
-
constraints,
|
|
483
|
-
primaryKeys,
|
|
484
|
-
} = await analyzeTable(queryInterface, constraintsGetter, tableName, configWithSchema);
|
|
485
|
-
databaseSchema[tableName] = {
|
|
486
|
-
schema, constraints, primaryKeys, references: [],
|
|
487
|
-
};
|
|
488
|
-
});
|
|
489
|
-
|
|
490
|
-
const columnTypeGetter = new ColumnTypeGetter(
|
|
491
|
-
connection, configWithSchema.dbSchema, allowWarning,
|
|
492
|
-
);
|
|
493
|
-
|
|
494
|
-
await P.each(tableNames, async (tableName) => {
|
|
495
|
-
schemaAllTables[tableName] = await createTableSchema(
|
|
496
|
-
columnTypeGetter,
|
|
497
|
-
databaseSchema[tableName],
|
|
498
|
-
tableName,
|
|
499
|
-
);
|
|
500
|
-
});
|
|
501
|
-
|
|
502
|
-
// NOTICE: Fill the references field for each table schema
|
|
503
|
-
const referencesPerTable = createAllReferences(databaseSchema, schemaAllTables);
|
|
504
|
-
Object.keys(referencesPerTable).forEach((tableName) => {
|
|
505
|
-
schemaAllTables[tableName].references = _.sortBy(referencesPerTable[tableName], 'association');
|
|
506
|
-
|
|
507
|
-
// NOTE: When a table contains no field, it will be considered camelCased
|
|
508
|
-
// by default, so we need to check its references to ensure whether
|
|
509
|
-
// it is camelCased or not.
|
|
510
|
-
if (!schemaAllTables[tableName].fields.length) {
|
|
511
|
-
schemaAllTables[tableName].options.underscored = isUnderscored(
|
|
512
|
-
schemaAllTables[tableName].references.map(({ foreignKey }) => ({ nameColumn: foreignKey })),
|
|
513
|
-
);
|
|
514
|
-
}
|
|
515
|
-
});
|
|
516
|
-
|
|
517
|
-
if (_.isEmpty(schemaAllTables)) {
|
|
518
|
-
throw new EmptyDatabaseError('no tables found', {
|
|
519
|
-
orm: 'sequelize',
|
|
520
|
-
dialect: connection.getDialect(),
|
|
521
|
-
});
|
|
522
|
-
}
|
|
523
|
-
|
|
524
|
-
fixAliasConflicts(schemaAllTables);
|
|
525
|
-
|
|
526
|
-
return schemaAllTables;
|
|
527
|
-
}
|
|
528
|
-
|
|
529
|
-
module.exports = analyzeSequelizeTables;
|
|
@@ -1,160 +0,0 @@
|
|
|
1
|
-
class Database {
|
|
2
|
-
constructor({
|
|
3
|
-
assertPresent,
|
|
4
|
-
mongodb,
|
|
5
|
-
Sequelize,
|
|
6
|
-
terminator,
|
|
7
|
-
}) {
|
|
8
|
-
assertPresent({
|
|
9
|
-
mongodb,
|
|
10
|
-
Sequelize,
|
|
11
|
-
terminator,
|
|
12
|
-
});
|
|
13
|
-
this.mongodb = mongodb;
|
|
14
|
-
this.Sequelize = Sequelize;
|
|
15
|
-
this.terminator = terminator;
|
|
16
|
-
}
|
|
17
|
-
|
|
18
|
-
async handleAuthenticationError(error) {
|
|
19
|
-
return this.terminator.terminate(1, {
|
|
20
|
-
logs: [
|
|
21
|
-
'Cannot connect to the database due to the following error:',
|
|
22
|
-
error,
|
|
23
|
-
],
|
|
24
|
-
errorCode: 'database_authentication_error',
|
|
25
|
-
errorMessage: error.message,
|
|
26
|
-
});
|
|
27
|
-
}
|
|
28
|
-
|
|
29
|
-
sequelizeAuthenticate(connection) {
|
|
30
|
-
return connection.authenticate()
|
|
31
|
-
.then(() => connection)
|
|
32
|
-
.catch((error) => this.handleAuthenticationError(error));
|
|
33
|
-
}
|
|
34
|
-
|
|
35
|
-
// eslint-disable-next-line class-methods-use-this
|
|
36
|
-
getDialect(dbConnectionUrl, dbDialect) {
|
|
37
|
-
if (dbConnectionUrl) {
|
|
38
|
-
if (dbConnectionUrl.startsWith('postgres://')) { return 'postgres'; }
|
|
39
|
-
if (dbConnectionUrl.startsWith('mysql://')) { return 'mysql'; }
|
|
40
|
-
if (dbConnectionUrl.startsWith('mssql://')) { return 'mssql'; }
|
|
41
|
-
// NOTICE: For MongoDB can be "mongodb://" or "mongodb+srv://"
|
|
42
|
-
if (dbConnectionUrl.startsWith('mongodb')) { return 'mongodb'; }
|
|
43
|
-
}
|
|
44
|
-
return dbDialect;
|
|
45
|
-
}
|
|
46
|
-
|
|
47
|
-
connectToMongodb(options, isSSL) {
|
|
48
|
-
let connectionOptionsMongoClient = options.connectionOptions;
|
|
49
|
-
if (!connectionOptionsMongoClient) {
|
|
50
|
-
connectionOptionsMongoClient = {
|
|
51
|
-
useNewUrlParser: true,
|
|
52
|
-
useUnifiedTopology: true,
|
|
53
|
-
};
|
|
54
|
-
if (isSSL) { connectionOptionsMongoClient.ssl = true; }
|
|
55
|
-
}
|
|
56
|
-
|
|
57
|
-
let connectionUrl = options.dbConnectionUrl;
|
|
58
|
-
if (!connectionUrl) {
|
|
59
|
-
connectionUrl = 'mongodb';
|
|
60
|
-
if (options.mongodbSrv) { connectionUrl += '+srv'; }
|
|
61
|
-
connectionUrl += '://';
|
|
62
|
-
if (options.dbUser) { connectionUrl += options.dbUser; }
|
|
63
|
-
if (options.dbPassword) { connectionUrl += `:${options.dbPassword}`; }
|
|
64
|
-
connectionUrl += `@${options.dbHostname}`;
|
|
65
|
-
if (!options.mongodbSrv) { connectionUrl += `:${options.dbPort}`; }
|
|
66
|
-
connectionUrl += `/${options.dbName}`;
|
|
67
|
-
}
|
|
68
|
-
|
|
69
|
-
return this.mongodb.MongoClient.connect(connectionUrl, connectionOptionsMongoClient)
|
|
70
|
-
.catch((error) => this.handleAuthenticationError(error));
|
|
71
|
-
}
|
|
72
|
-
|
|
73
|
-
connectToSequelize(databaseDialect, options, isSSL) {
|
|
74
|
-
let connectionOptionsSequelize = options.connectionOptions;
|
|
75
|
-
if (!connectionOptionsSequelize) {
|
|
76
|
-
connectionOptionsSequelize = {};
|
|
77
|
-
|
|
78
|
-
if (databaseDialect === 'mssql') {
|
|
79
|
-
connectionOptionsSequelize.dialectOptions = { options: { encrypt: isSSL } };
|
|
80
|
-
} else if (isSSL) {
|
|
81
|
-
// Add SSL options only if the user selected SSL mode.
|
|
82
|
-
// SSL Cerificate is always trusted during `forest projects:create` command
|
|
83
|
-
// to ease their onboarding.
|
|
84
|
-
connectionOptionsSequelize.dialectOptions = { ssl: { rejectUnauthorized: false } };
|
|
85
|
-
}
|
|
86
|
-
}
|
|
87
|
-
|
|
88
|
-
connectionOptionsSequelize.logging = false;
|
|
89
|
-
|
|
90
|
-
let connection;
|
|
91
|
-
if (options.dbConnectionUrl) {
|
|
92
|
-
connection = new this.Sequelize(options.dbConnectionUrl, connectionOptionsSequelize);
|
|
93
|
-
} else {
|
|
94
|
-
connectionOptionsSequelize.host = options.dbHostname;
|
|
95
|
-
connectionOptionsSequelize.port = options.dbPort;
|
|
96
|
-
connectionOptionsSequelize.dialect = databaseDialect;
|
|
97
|
-
|
|
98
|
-
connection = new this.Sequelize(
|
|
99
|
-
options.dbName, options.dbUser,
|
|
100
|
-
options.dbPassword, connectionOptionsSequelize,
|
|
101
|
-
);
|
|
102
|
-
}
|
|
103
|
-
|
|
104
|
-
return this.sequelizeAuthenticate(connection);
|
|
105
|
-
}
|
|
106
|
-
|
|
107
|
-
async connect(options) {
|
|
108
|
-
const isSSL = options.dbSSL || options.ssl;
|
|
109
|
-
const databaseDialect = this.getDialect(options.dbConnectionUrl, options.dbDialect);
|
|
110
|
-
|
|
111
|
-
if (databaseDialect === 'mongodb') {
|
|
112
|
-
return this.connectToMongodb(options, isSSL);
|
|
113
|
-
}
|
|
114
|
-
|
|
115
|
-
return this.connectToSequelize(databaseDialect, options, isSSL);
|
|
116
|
-
}
|
|
117
|
-
|
|
118
|
-
connectFromDatabasesConfig(databasesConfig) {
|
|
119
|
-
return Promise.all(
|
|
120
|
-
databasesConfig.map(async (databaseConfig) => {
|
|
121
|
-
const connectionOptions = { ...databaseConfig.connection.options };
|
|
122
|
-
|
|
123
|
-
const connectionInstance = await this.connect({
|
|
124
|
-
dbConnectionUrl: databaseConfig.connection.url,
|
|
125
|
-
connectionOptions,
|
|
126
|
-
});
|
|
127
|
-
|
|
128
|
-
return {
|
|
129
|
-
...databaseConfig,
|
|
130
|
-
connectionInstance,
|
|
131
|
-
};
|
|
132
|
-
}),
|
|
133
|
-
);
|
|
134
|
-
}
|
|
135
|
-
|
|
136
|
-
// eslint-disable-next-line class-methods-use-this
|
|
137
|
-
disconnectFromDatabases(databaseConnections) {
|
|
138
|
-
return Promise.all(
|
|
139
|
-
databaseConnections.map((connection) => this.disconnect(connection.connectionInstance)),
|
|
140
|
-
);
|
|
141
|
-
}
|
|
142
|
-
|
|
143
|
-
// eslint-disable-next-line class-methods-use-this
|
|
144
|
-
async disconnect(connection) {
|
|
145
|
-
return connection.close();
|
|
146
|
-
}
|
|
147
|
-
|
|
148
|
-
areAllDatabasesOfTheSameType(databasesConfig) {
|
|
149
|
-
const databasesDialect = databasesConfig.map(
|
|
150
|
-
(databaseConfig) => this.getDialect(databaseConfig.connection.url),
|
|
151
|
-
);
|
|
152
|
-
|
|
153
|
-
const hasMongoDb = databasesDialect.some((dialect) => dialect === 'mongodb');
|
|
154
|
-
const hasAnotherDbType = databasesDialect.some((dialect) => dialect !== 'mongodb');
|
|
155
|
-
|
|
156
|
-
return !(hasMongoDb && hasAnotherDbType);
|
|
157
|
-
}
|
|
158
|
-
}
|
|
159
|
-
|
|
160
|
-
module.exports = Database;
|