jsonschema2ddl
Version:
Convert JSON Schema to DDL
45 lines • 1.59 kB
JavaScript
import { ValidationError } from 'jsonschema';
import { COLUMNS_TYPES_PREFERENCE } from './types';
const camelToSnakeCase = (str) => {
return str
.replace(/[A-Z]/g, (char) => `_${char.toLowerCase()}`)
.replace(/^_/, '');
};
export function db_table_name(table_name, schema_name) {
table_name = camelToSnakeCase(table_name);
if (!schema_name) {
return `${table_name}`;
}
return `"${schema_name}"."${table_name}"`;
}
export function db_column_name(col_name) {
return camelToSnakeCase(col_name);
}
/**
* Get one schema from a list of 'allOf', 'anyOf', 'oneOf'.
*
* @param object_schema
* @returns
*/
export function get_one_schema(object_schema) {
const types = object_schema["allOf"] || object_schema["anyOf"] || object_schema["oneOf"] || [];
if (!types.length) {
throw new ValidationError("Neither 'type', 'allOf', 'anyOf', 'oneOf' defined for field. Aborting!");
}
function get_type_preference(type_definition) {
let schema_type = type_definition["type"];
if ("format" in type_definition && type_definition["format"] in COLUMNS_TYPES_PREFERENCE) {
schema_type = type_definition["format"];
}
return [type_definition, COLUMNS_TYPES_PREFERENCE[schema_type]];
}
const types_with_preference = types.map(get_type_preference);
const max_preference_type = types_with_preference.reduce((a, x) => {
if (x[1] > a[1]) {
a = x;
}
return a;
}, [null, -Infinity]);
return max_preference_type[0];
}
//# sourceMappingURL=utils.js.map