подкорректировать WebSQL запрос
ребят подскажите пожалуйста, балуюсь с WebSQL, и так как в БД пока не силён, напортачил с запросом. По факту есть массив с объектами по умолчанию "valuesArr". Значения этих объектов записываются в БД WebSQL, тем самым заполняют строки таблицы. При необходимости пользователь может добавить строки изменить или удалить строки, но минуя массив значений по умолчанию. Пользователь работает только с БД. Или я не из того места запускаю метод - “DataBase.prototype.push” который генерирует строки по умолчанию. Или мне нужно изменить каким-то образом сам запрос в WebSQL.(по типу “create table if not exists”), только “insert....” В данный момент код ведёт себя следующим образом: При запуске таблица пустая, строки по умолчанию не генерирует, создаёт их только после пары обновлений страницы. При последующих обновлениях страницы продолжает генерировать строки по умолчанию. Хотелось бы что-бы при запуске, автоматически генерировались значения по умолчанию и при обновлениях страницы они не добавлялись снова и снова. Заранее благодарен)
function DataBase(name) {
this.dbName = name;
this.ucDbName = this.dbName = this.dbName[0].toUpperCase() + this.dbName.substring(1);
this.db = openDatabase(this.dbName, '1.0', this.ucDbName, 100 * 1024 * 1024);
}
DataBase.prototype.create = function(name) {
let strFields = '';
let fields = {
date: 'TEXT',
nameOfProvider: 'TEXT',
warehouse: 'TEXT',
nameOfProduct: 'TEXT',
quantity: 'TEXT',
total: 'TEXT'
}
for (const key in fields) {
strFields += ", " + key + ' ' + fields[key];
}
this.db.transaction(function (tx) {
tx.executeSql('create table if not exists ' + name + '(id integer primary key autoincrement' + strFields + ')');
});
};
DataBase.prototype.add = function(name) {
let q = new Array();
let vars = new Array();
let vals = new Array();
let values = {
date: document.getElementById('add-date').value,
nameOfProvider: document.getElementById('add-nameOfProvider').value,
warehouse: document.getElementById('add-warehouse').value,
nameOfProduct: document.getElementById('add-nameOfProduct').value,
quantity: document.getElementById('add-quantity').value,
total: document.getElementById('add-total').value
}
for (let i = 0; i < Object.keys(values).length; i++) {
q.push('?');
}
for (const key in values) {
vars.push(key);
}
for (const key in values) {
vals.push(values[key]);
}
this.db.transaction(function (tx) {
tx.executeSql('insert into ' + name + '(' + vars.join(", ") + ') values(' + q.join(", ") + ')', vals);
});
};
DataBase.prototype.push = function(name) {
let valuesArr = [
{
date: "2021.12.09",
nameOfProvider: "BMW",
warehouse: "Основной",
nameOfProduct: "Двигатель",
quantity: "1",
total: "50000"
},
{
date: "2020.10.11",
nameOfProvider: "Audi",
warehouse: "Запасной",
nameOfProduct: "Свечи",
quantity: "6",
total: "3000"
},
{
date: "2021.09.03",
nameOfProvider: "Lada",
warehouse: "Основной",
nameOfProduct: "Катушка",
quantity: "3",
total: "1500"
}
];
for (let values of valuesArr ){
console.log(values);
let q = new Array();
let vars = new Array();
let vals = new Array();
for (let i = 0; i < Object.values(values).length; i++) {
q.push('?');
console.log(q);
}
for (const key in values) {
vars.push(key);
console.log(vars);
}
for (const key in values) {
vals.push(values[key]);
console.log(vals);
}
this.db.transaction(function (tx) {
tx.executeSql('insert into ' + name + '(' + vars.join(", ") + ') values(' + q.join(", ") + ')', vals);
});
}
};
DataBase.prototype.load = function(name) {
console.log('werwer');
let sql = `select * from ${name}`;
document.querySelector('.table').innerHTML = '';
this.db.transaction(function(tx) {
tx.executeSql(sql, [], function(tx, result) {
let n = result.rows.length;
for(let i = 0; i < n; i++) {
let work = result.rows.item(i);
let tbl_block = document.querySelector('.table');
let cell_id = document.createElement('div');
let cell_date = document.createElement('div');
let cell_del_btn = document.createElement('div');
let del_btn = document.createElement('button');
cell_date.setAttribute('class', 'cell-table');
cell_date.setAttribute('data-id', work.id);
let cell_nameOfProvider = cell_date.cloneNode(true);
let cell_warehouse = cell_date.cloneNode(true);
let cell_nameOfProduct = cell_date.cloneNode(true);
let cell_quantity = cell_date.cloneNode(true);
let cell_total = cell_date.cloneNode(true);
cell_id = cell_date.cloneNode(true);
cell_id.setAttribute('data-field', 'id');
cell_date.setAttribute('data-field', 'date');
cell_nameOfProvider.setAttribute('data-field', 'nameOfProvider');
cell_warehouse.setAttribute('data-field', 'warehouse');
cell_nameOfProduct.setAttribute('data-field', 'nameOfProduct');
cell_quantity.setAttribute('data-field', 'quantity');
cell_total.setAttribute('data-field', 'total');
cell_del_btn.setAttribute('class', 'cell-table');
cell_del_btn.setAttribute('data-id', work.id);
del_btn.setAttribute('class', 'cell-table');
del_btn.setAttribute('data-id', work.id);
cell_id.innerText = work.id;
cell_date.innerText = work.date;
cell_nameOfProvider.innerText = work.nameOfProvider;
cell_warehouse.innerText = work.warehouse;
cell_nameOfProduct.innerText = work.nameOfProduct;
cell_quantity.innerText = work.quantity;
cell_total.innerText = work.total;
del_btn.innerHTML = '×';
cell_del_btn.appendChild(del_btn);
tbl_block.appendChild(cell_id);
tbl_block.appendChild(cell_date);
tbl_block.appendChild(cell_nameOfProvider);
tbl_block.appendChild(cell_warehouse);
tbl_block.appendChild(cell_nameOfProduct);
tbl_block.appendChild(cell_quantity);
tbl_block.appendChild(cell_total);
tbl_block.appendChild(cell_del_btn);
}
});
});
};
DataBase.prototype.update = function(name, field, value, id) {
let sql = `update ${name} set ${field} = '${value}' WHERE id = ${id}`;
console.log(sql);
this.db.transaction(function (tx) {
tx.executeSql(sql);
});
};
DataBase.prototype.del = function(name, id) {
let sql = `DELETE FROM ${name} WHERE id = ` + id;
this.db.transaction((tx) => {
tx.executeSql(sql);
});
};
DataBase.prototype.clear = function(name) {
let sql = `DROP TABLE ${name}`;
this.db.transaction(function (tx) {
tx.executeSql(sql);
});
document.querySelector('.table').innerHTML = '';
};
function App(baseName, tableName) {
this.db = new DataBase(baseName);
this.tbl = tableName;
this.fields = {
adddate: document.querySelector('#add-date'),
addnameOfProvider: document.querySelector('#add-nameOfProvider'),
addwarehouse: document.querySelector('#add-warehouse'),
addnameOfProduct: document.querySelector('#add-nameOfProduct'),
addquantity: document.querySelector('#add-quantity'),
addtotal: document.querySelector('#add-total')
};
this.btn = {
add: document.querySelector('#add'),
clear: document.querySelector('#btnClear'),
del: document.querySelector('.table')
};
};
App.prototype.create = function() {
this.db.create(this.tbl);
this.db.push(this.tbl);
this.btn.add.addEventListener('click', e => {
if(e.target.tagName == 'INPUT') {
if (this.fields.adddate != '' && this.fields.addnameOfProvider != '' && this.fields.addwarehouse != '' && this.fields.addnameOfProduct !='' && this.fields.addquantity !=''&& this.fields.addtotal !='') {
this.db.add(this.tbl);
this.db.load(this.tbl);
}
for(const key in this.fields) {
this.fields[key].value = '';
}
}
});
this.btn.clear.addEventListener('click', e => {
if (e.target.tagName == 'BUTTON') {
this.db.clear(this.tbl);
}
});
this.btn.del.addEventListener('click', e => {
if(e.target.tagName == 'BUTTON') {
this.db.del(this.tbl, parseInt(e.target.getAttribute('data-id')));
this.db.load(this.tbl);
}
});
this.btn.del.addEventListener('dblclick', e => {
if(e.target.tagName == 'DIV') {
e.target.setAttribute('contenteditable', 'true');
e.target.focus();
}
});
this.btn.del.addEventListener('keydown', e => {
if (e.target.tagName == 'DIV' && e.target.getAttribute('contenteditable') == 'true') {
if(e.keyCode == 13) {
e.target.setAttribute('contenteditable', 'false');
let fld = e.target.getAttribute('data-field');
let vle = e.target.innerText;
let id = parseInt(e.target.getAttribute('data-id'));
this.db.update(this.tbl, fld, vle, id);
}
}
});
};
window.addEventListener('load', () => {
let app = new App('dbusr', 'users');
app.db.load(app.tbl);
app.create();
});
function tableSearch() {
var phrase = document.getElementById('search-text');
let items = document.getElementsByClassName("cell-table");
for (let i = 0; i < items.length; i++) {
for (let item of items) {
let atribute = item.getAttribute("data-field");
if(atribute){
console.log(item.innerHTML);
}
}
}
for (let i = 0; i < items.length; i++) {
for (let item of items) {
if (item.innerHTML.toLowerCase().split('').slice(0, phrase.value.length).join('') !== phrase.value.toLowerCase()|| phrase.value == "") {
item.style = 'background-color: #f3e6e6';
} else if (item.style !== 'background-color: lightgreen') {
item.style = 'background-color: lightgreen';
console.log(item);
}
}
}
}
let filter_select_el = document.getElementById('filter');
// var items_el = document.getElementsByClassName('cell-table');
filter_select_el.onchange = function() {
console.log(this.value);
let items = document.getElementsByClassName('cell-table');
let id = "";
for (let i = 0; i < items.length; i++) {
for (let item of items) {
if (item.innerHTML.toLowerCase() !== this.value.toLowerCase()) {
item.style.display = 'none';
} else if (item.style.display !== 'inline') {
item.style.display = 'inline';
id = item.getAttribute("data-id");
console.log(item.getAttribute("data-id"));
}
for(let currentItem of items){
if (currentItem.getAttribute("data-id") === id){
currentItem.style.display = 'inline';
}
}
}
}
};