-
Notifications
You must be signed in to change notification settings - Fork 4
Expand file tree
/
Copy pathguess-model.js
More file actions
276 lines (243 loc) · 7.17 KB
/
Copy pathguess-model.js
File metadata and controls
276 lines (243 loc) · 7.17 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
/**
* Guess model from column data
*/
// Dependencies
const _ = require('lodash');
const moment = require('moment-timezone');
const Sequelize = require('sequelize');
const utils = require('./utils-data');
const dbUtils = require('./utils-db');
// Guess model from data from rows of data
//
// And should return a model object
// {
// fields: {
// columnA: {
// tablesInputColumn: "Column From CSV",
// field: "db_column_name",
// type: Sequelize.INTEGER
// // sequelize options
// // http://docs.sequelizejs.com/manual/models-definition.html
// }
// },
// // Options for Sequelize models
// options: {
// // http://docs.sequelizejs.com/manual/models-definition.html
// indexes [
// { fields: ["db_column_name"] }
// ]
// }
// }
function guessModel(data, tablesOptions = {}, sequlizeInstance) {
let fields = {};
let modelName = tablesOptions.tableName
? _.camelCase(tablesOptions.tableName)
: 'tablesImport';
let modelOptions = {
sequelize: sequlizeInstance,
indexes: [],
timestamps: false,
underscored: true,
freezeTableName: true,
tableName: dbUtils.sqlName(modelName)
};
// Go through each column
_.each(data[0], (v, columnName) => {
let fieldName = _.camelCase(columnName);
let sqlName = dbUtils.sqlName(columnName);
let columnData = _.map(data, columnName);
let field = {};
// Set tables-specific property
field.tablesInputColumn = columnName;
// set specific SQL column name
field.field = sqlName;
// Guess type
field.type = dataToType(columnData, columnName, tablesOptions);
// Allow null by default
field.allowNull = true;
// Attach to fields
fields[fieldName] = field;
// Make indexes based on column name
if (shouldIndex(columnName, tablesOptions) && field.type != 'TEXT') {
// Index needs to use SQL name, not Sequelize name
// By default index name will be [table]_[fields]
modelOptions.indexes.push({ name: `ix_${sqlName}`, fields: [sqlName] });
}
});
// If key is provided, use as primary key
if (tablesOptions.key) {
let keyFields = _.isArray(tablesOptions.key)
? tablesOptions.key
: [tablesOptions.key];
let keyFieldsCased = _.map(keyFields, _.camelCase);
keyFieldsCased.forEach((f, fi) => {
if (!fields[f]) {
throw new Error(`Field "${keyFields[fi]}" specified as key but could not be found.`);
}
fields[f].primaryKey = true;
fields[f].allowNull = false;
});
}
else {
// Add a primary key
fields.tablesPrimaryKey = {
type: Sequelize.INTEGER,
autoIncrement: true,
primaryKey: true
};
}
class TablesAutoModel extends Sequelize.Model {}
TablesAutoModel.init(fields, modelOptions);
// Attached so that we can reference it later
TablesAutoModel.modelName = modelName;
return TablesAutoModel;
}
// Data to type
function dataToType(data, name, tablesOptions = {}) {
let knownID = /(^|\s|_|-)(zip|phone|id)(_|\s|-|$)/i;
// Otherise go through each value and see what is found
data = _.map(data, function(d) {
d = standardize(d);
return {
value: d,
length: d && d.toString ? d.toString().length : null,
kind: pickle(d, tablesOptions)
};
});
// Filter out any empty values
data = _.filter(data, 'length');
let counted = _.countBy(data, 'kind');
let top = _.sortBy(
_.map(counted, function(d, di) {
return { kind: di, count: d };
}),
'count'
).reverse()[0];
let maxLength = _.maxBy(data, d => (d && d.length ? d.length : 0));
maxLength = maxLength ? maxLength.length : maxLength;
let kind;
// If none, then just assume string
if (_.size(data) === 0) {
return Sequelize.STRING;
}
// If there is only one kind, stick with that
else if (_.size(counted) === 1) {
kind = top.kind;
}
// If there is a string, use string
else if (counted.STRING) {
kind = 'STRING';
}
// If there is an integer and a float, use float
else if (counted.INTEGER && counted.FLOAT) {
kind = 'FLOAT';
}
else {
kind = top.kind;
}
// Check for long strings. Max string (in MySQL) is 255
if (kind === 'STRING' && maxLength * 2 < 240) {
return new Sequelize.STRING(Math.max(2, maxLength * 2));
}
// Otherwise add length
else if (kind === 'STRING') {
return Sequelize.TEXT;
}
// Known not numbers
else if ((kind === 'INTEGER' || kind === 'FLOAT') && knownID.test(name)) {
return new Sequelize.STRING(Math.floor(maxLength * 2));
}
// Check for long integers
else if (kind === 'INTEGER' && maxLength > 8) {
return Sequelize.BIGINT;
}
else {
return Sequelize[kind];
}
}
// Convert value a bit, but keep as string if needed
function standardize(value) {
let isString = _.isString(value);
value = utils.standardizeInput(value);
return isString && value === null ? '' : value;
}
// Determine if should index based on name
function shouldIndex(name, options = {}) {
let c = options.fieldsToIndex;
let nameTest = _.isRegExp(c)
? c
: _.isString(c)
? new RegExp(c, 'i')
: /(^|_)(id|name|key|amount|amt)($|_)/g;
return nameTest.test(_.snakeCase(name));
}
// Find type. Should return base Sequelize type
function pickle(value, options = {}) {
// Tests
let floatTest = /^[-+]?(\d{1,3}(,\d{3})*|\d+)\.\d+$/g;
let intTest = /^[-+]?(\d{1,3}(,\d{3})*|\d+)$/g;
let booleanTest = /^(true|false|y|n|yes|no)$/gi;
let dateTest = /^\d{1,2}\/\d{1,2}\/\d{2,4}$/g;
let datetimeTest = /^\d{1,2}\/\d{1,2}\/\d{2,4}\s+\d{1,2}:\d{1,2}(:\d{1,2}|)(\s+|)(am|pm|)$/gi;
// Test values
if (_.isArray(value) || _.isPlainObject(value)) {
// TODO: Maybe handle JSON data type
return 'TEXT';
}
// TODO: Non-strict mode of parsing dates will end up parsing
// simple numbers like '42'
// Strict mode dates
if (options.dateStrictMode) {
if (
_.isDate(value) ||
(options.datetimeFormat &&
moment(value, options.datetimeFormat, options.dateStrictMode).isValid()) ||
datetimeTest.test(value)
) {
return 'DATE';
}
if (
(options.dateFormat && moment(value, options.dateFormat, options.dateStrictMode).isValid()) ||
dateTest.test(value)
) {
return 'DATEONLY';
}
}
// Numbers
if (_.isInteger(value) || intTest.test(value)) {
return 'INTEGER';
}
if ((_.isFinite(value) && !_.isInteger(value)) || floatTest.test(value)) {
return 'FLOAT';
}
// Booleans
if (_.isBoolean(value) || booleanTest.test(value)) {
return 'BOOLEAN';
}
// Non-strict mode dates
if (!options.dateStrictMode) {
if (
_.isDate(value) ||
(options.datetimeFormat &&
moment(value, options.datetimeFormat, options.dateStrictMode).isValid()) ||
datetimeTest.test(value)
) {
return 'DATE';
}
if (
(options.dateFormat && moment(value, options.dateFormat, options.dateStrictMode).isValid()) ||
dateTest.test(value)
) {
return 'DATEONLY';
}
}
// Default to string
return 'STRING';
}
// Attach other functions for testing
guessModel.dataToType = dataToType;
guessModel.standardize = standardize;
guessModel.shouldIndex = shouldIndex;
guessModel.pickle = pickle;
// Export
module.exports = guessModel;