2019-12-11 14:01:01 +00:00
|
|
|
const UserError = require('vn-loopback/util/user-error');
|
|
|
|
|
2018-10-15 09:43:57 +00:00
|
|
|
module.exports = Self => {
|
|
|
|
/**
|
|
|
|
* Returns a set of allowed values defined on table scheme
|
|
|
|
* @param {String} column - Model or Table column name
|
|
|
|
* @return {Array} - Array of set values
|
|
|
|
*/
|
|
|
|
Self.getSetValues = async function(column) {
|
|
|
|
let model = this.app.models[this.modelName].definition;
|
|
|
|
let properties = model.properties;
|
2018-12-19 07:42:07 +00:00
|
|
|
let tableName = this.modelName;
|
|
|
|
let schema = null;
|
2018-10-15 09:43:57 +00:00
|
|
|
|
2018-12-19 07:42:07 +00:00
|
|
|
if (model.settings && model.settings.mysql) {
|
|
|
|
let tableSplit = model.settings.mysql.table.split('.');
|
|
|
|
tableName = tableSplit.pop();
|
|
|
|
schema = tableSplit.pop() || null;
|
|
|
|
}
|
2018-10-15 09:43:57 +00:00
|
|
|
|
2019-12-11 14:01:01 +00:00
|
|
|
let property = properties[column];
|
2018-10-15 09:43:57 +00:00
|
|
|
|
2019-12-11 14:01:01 +00:00
|
|
|
if (!property)
|
|
|
|
throw new UserError(`Column does not exist`);
|
2018-10-15 09:43:57 +00:00
|
|
|
|
2019-12-11 14:01:01 +00:00
|
|
|
let columnName = property.mysql
|
|
|
|
? property.mysql.columnName
|
|
|
|
: column;
|
2018-10-15 09:43:57 +00:00
|
|
|
|
2019-12-11 14:01:01 +00:00
|
|
|
let columnInfo = await this.rawSql(
|
|
|
|
`SELECT column_type columnType
|
|
|
|
FROM information_schema.columns
|
2018-10-15 09:43:57 +00:00
|
|
|
WHERE table_name = ?
|
2018-12-19 07:42:07 +00:00
|
|
|
AND table_schema = IFNULL(?, DATABASE())
|
|
|
|
AND column_name = ?`,
|
|
|
|
[tableName, schema, columnName]
|
|
|
|
);
|
2018-10-15 09:43:57 +00:00
|
|
|
|
2019-12-11 14:01:01 +00:00
|
|
|
if (!columnInfo || !columnInfo[0])
|
|
|
|
throw new UserError(`Cannot fetch column values`);
|
2018-10-15 09:43:57 +00:00
|
|
|
|
|
|
|
let setValues;
|
2019-12-11 14:01:01 +00:00
|
|
|
setValues = columnInfo[0].columnType
|
|
|
|
.replace(/^set\((.*)\)$/i, '$1')
|
|
|
|
.replace(/'/g, '')
|
|
|
|
.match(new RegExp(/(\w+)+/, 'ig'));
|
2018-10-15 09:43:57 +00:00
|
|
|
|
|
|
|
let values = [];
|
|
|
|
setValues.forEach(setValue => {
|
|
|
|
values.push({value: setValue});
|
|
|
|
});
|
|
|
|
|
|
|
|
return values;
|
|
|
|
};
|
|
|
|
};
|