Skip to content

Instantly share code, notes, and snippets.

@ezzabuzaid
Last active December 1, 2020 16:55
Show Gist options
  • Save ezzabuzaid/61dd4a3198f2d99beedd1f900d87adf0 to your computer and use it in GitHub Desktop.
Save ezzabuzaid/61dd4a3198f2d99beedd1f900d87adf0 to your computer and use it in GitHub Desktop.
create sql query using a function
const schema = {
id: {
type: 'int UNSIGNED',
value: 'AUTO_INCREMENT',
key: 'PRIMARY KEY'
},
title: {
type: 'VARCHAR(255)',
value: 'NOT NULL'
},
body: {
type: 'VARCHAR(255)',
value: 'NOT NULL'
}
};
function creataTable(tableName, columns) {
const columnsNames = Object.keys(columns);
const statement = columnsNames.reduce((statment, column, index) => {
const { type, value, key = '' } = columns[column];
let _statment = `${column} ${type} ${value} ${key}`;
_statment = _statment.trim();
if ((index + 1) !== columnsNames.length) {
_statment += ', ';
}
return `${statment}${_statment}`;
}, '');
return `CREATE TABLE ${tableName} (${statement})`;
}
const table = creataTable('MyTable', schema);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment