2
0
mirror of https://github.com/frappe/books.git synced 2024-12-24 11:55:46 +00:00
books/backends/sqlite.js

249 lines
7.6 KiB
JavaScript
Raw Normal View History

2018-01-16 06:09:17 +00:00
const frappe = require('frappejs');
2018-01-12 12:25:07 +00:00
const sqlite3 = require('sqlite3').verbose();
const Database = require('./database');
2018-02-07 13:23:52 +00:00
const debug = false;
2018-01-12 12:25:07 +00:00
module.exports = class sqliteDatabase extends Database {
constructor({ dbPath }) {
super();
this.dbPath = dbPath;
2018-01-31 13:04:46 +00:00
}
connect(dbPath) {
if (dbPath) {
this.dbPath = dbPath;
2018-01-31 13:04:46 +00:00
}
return new Promise(resolve => {
this.conn = new sqlite3.Database(this.dbPath, () => {
2018-01-31 13:04:46 +00:00
if (debug) {
this.conn.on('trace', (trace) => console.log(trace));
}
2018-02-20 09:53:38 +00:00
this.run('PRAGMA foreign_keys=ON').then(resolve);
2018-01-31 13:04:46 +00:00
});
});
}
async tableExists(table) {
const name = await this.sql(`SELECT name FROM sqlite_master WHERE type='table' AND name='${table}'`);
return (name && name.length) ? true : false;
2018-01-31 13:04:46 +00:00
}
2018-02-23 16:17:55 +00:00
async addForeignKeys(doctype, newForeignKeys) {
2018-02-20 09:53:38 +00:00
await this.run('PRAGMA foreign_keys=OFF');
await this.run('BEGIN TRANSACTION');
2018-03-05 16:45:21 +00:00
const tempName = 'TEMP' + doctype
2018-02-20 09:53:38 +00:00
// create temp table
2018-03-05 16:45:21 +00:00
await this.createTable(doctype, tempName);
const columns = (await this.getTableColumns(tempName)).join(', ');
2018-02-20 09:53:38 +00:00
// copy from old to new table
2018-03-05 16:45:21 +00:00
await this.run(`INSERT INTO ${tempName} (${columns}) SELECT ${columns} from ${doctype}`);
2018-02-20 09:53:38 +00:00
// drop old table
await this.run(`DROP TABLE ${doctype}`);
// rename new table
2018-03-05 16:45:21 +00:00
await this.run(`ALTER TABLE ${tempName} RENAME TO ${doctype}`);
2018-02-20 09:53:38 +00:00
await this.run('COMMIT');
await this.run('PRAGMA foreign_keys=ON');
}
2018-03-05 16:45:21 +00:00
removeColumns() {
// pass
}
2018-02-20 09:53:38 +00:00
async runCreateTableQuery(doctype, columns, indexes) {
const query = `CREATE TABLE IF NOT EXISTS ${doctype} (
2018-02-20 09:53:38 +00:00
${columns.join(", ")} ${indexes.length ? (", " + indexes.join(", ")) : ''})`;
2018-01-12 12:25:07 +00:00
2018-02-20 09:53:38 +00:00
return await this.run(query);
2018-01-31 13:04:46 +00:00
}
2018-02-20 09:53:38 +00:00
updateColumnDefinition(field, columns, indexes) {
2018-02-23 16:17:55 +00:00
let def = this.getColumnDefinition(field);
columns.push(def);
if (field.fieldtype==='Link' && field.target) {
2018-03-07 10:37:58 +00:00
indexes.push(`FOREIGN KEY (${field.fieldname}) REFERENCES ${field.target} ON UPDATE CASCADE ON DELETE RESTRICT`);
2018-02-23 16:17:55 +00:00
}
}
getColumnDefinition(field) {
let def = [
field.fieldname,
this.typeMap[field.fieldtype],
field.fieldname === 'name' ? 'PRIMARY KEY NOT NULL' : '',
field.required ? 'NOT NULL' : '',
field.default ? `DEFAULT ${field.default}` : ''
].join(' ');
2018-02-23 16:17:55 +00:00
return def;
2018-01-31 13:04:46 +00:00
}
async getTableColumns(doctype) {
return (await this.sql(`PRAGMA table_info(${doctype})`)).map(d => d.name);
2018-01-31 13:04:46 +00:00
}
2018-02-20 09:53:38 +00:00
async getForeignKeys(doctype) {
return (await this.sql(`PRAGMA foreign_key_list(${doctype})`)).map(d => d.from);
}
async runAddColumnQuery(doctype, field, values) {
await this.run(`ALTER TABLE ${doctype} ADD COLUMN ${this.getColumnDefinition(field)}`, values);
2018-01-31 13:04:46 +00:00
}
getOne(doctype, name, fields = '*') {
fields = this.prepareFields(fields);
2018-01-31 13:04:46 +00:00
return new Promise((resolve, reject) => {
this.conn.get(`select ${fields} from ${doctype}
2018-01-12 12:25:07 +00:00
where name = ?`, name,
2018-01-31 13:04:46 +00:00
(err, row) => {
resolve(row || {});
});
});
}
async insertOne(doctype, doc) {
let fields = this.getKeys(doctype);
2018-01-31 13:04:46 +00:00
let placeholders = fields.map(d => '?').join(', ');
2018-02-01 11:07:36 +00:00
if (!doc.name) {
2018-03-05 16:45:21 +00:00
doc.name = frappe.getRandomString();
2018-02-01 11:07:36 +00:00
}
return await this.run(`insert into ${doctype}
2018-02-01 11:07:36 +00:00
(${fields.map(field => field.fieldname).join(", ")})
values (${placeholders})`, this.getFormattedValues(fields, doc));
2018-01-31 13:04:46 +00:00
}
2018-01-12 12:25:07 +00:00
async updateOne(doctype, doc) {
let fields = this.getKeys(doctype);
2018-01-31 13:04:46 +00:00
let assigns = fields.map(field => `${field.fieldname} = ?`);
let values = this.getFormattedValues(fields, doc);
2018-01-31 12:56:21 +00:00
2018-01-31 13:04:46 +00:00
// additional name for where clause
values.push(doc.name);
2018-01-31 12:56:21 +00:00
return await this.run(`update ${doctype}
2018-01-12 12:25:07 +00:00
set ${assigns.join(", ")} where name=?`, values);
2018-01-31 13:04:46 +00:00
}
async runDeleteOtherChildren(field, added) {
// delete other children
// `delete from doctype where parent = ? and name not in (?, ?, ?)}`
await this.run(`delete from ${field.childtype}
where
parent = ? and
name not in (${added.slice(1).map(d => '?').join(', ')})`, added);
2018-01-31 13:04:46 +00:00
}
async deleteOne(doctype, name) {
return await this.run(`delete from ${doctype} where name=?`, name);
2018-02-01 11:07:36 +00:00
}
async deleteChildren(parenttype, parent) {
2018-02-12 12:01:31 +00:00
await this.run(`delete from ${parenttype} where parent=?`, parent);
}
async deleteSingleValues(name) {
await frappe.db.run('delete from SingleValue where parent=?', name)
2018-02-01 11:07:36 +00:00
}
2018-04-29 09:07:04 +00:00
getAll({ doctype, fields, filters, start, limit, orderBy = 'modified', groupBy, order = 'desc' } = {}) {
2018-01-31 13:04:46 +00:00
if (!fields) {
fields = frappe.getMeta(doctype).getKeywordFields();
2018-01-31 13:04:46 +00:00
}
2018-03-05 16:45:21 +00:00
if (typeof fields === 'string') {
fields = [fields];
}
2018-04-26 10:19:53 +00:00
2018-01-31 13:04:46 +00:00
return new Promise((resolve, reject) => {
let conditions = this.getFilterConditions(filters);
2018-02-12 12:01:31 +00:00
let query = `select ${fields.join(", ")}
from ${doctype}
2018-01-12 12:25:07 +00:00
${conditions.conditions ? "where" : ""} ${conditions.conditions}
2018-04-29 09:07:04 +00:00
${groupBy ? ("group by " + groupBy.join(', ')) : ""}
2018-04-26 10:19:53 +00:00
${orderBy ? ("order by " + orderBy) : ""} ${orderBy ? (order || "asc") : ""}
2018-02-12 12:01:31 +00:00
${limit ? ("limit " + limit) : ""} ${start ? ("offset " + start) : ""}`;
this.conn.all(query, conditions.values,
2018-01-31 13:04:46 +00:00
(err, rows) => {
if (err) {
2018-04-26 10:19:53 +00:00
console.error(err);
2018-01-31 13:04:46 +00:00
reject(err);
} else {
resolve(rows);
}
});
});
}
run(query, params) {
return new Promise((resolve, reject) => {
this.conn.run(query, params, (err) => {
if (err) {
2018-04-26 10:19:53 +00:00
console.error(err);
2018-01-31 13:04:46 +00:00
reject(err);
} else {
resolve();
}
});
});
}
sql(query, params) {
return new Promise((resolve) => {
this.conn.all(query, params, (err, rows) => {
resolve(rows);
});
});
}
async commit() {
try {
await this.run('commit');
} catch (e) {
if (e.errno !== 1) {
throw e;
}
}
}
initTypeMap() {
this.typeMap = {
2018-03-30 16:56:30 +00:00
'Autocomplete': 'text'
, 'Currency': 'real'
2018-01-31 13:04:46 +00:00
, 'Int': 'integer'
, 'Float': 'real'
, 'Percent': 'real'
, 'Check': 'integer'
, 'Small Text': 'text'
, 'Long Text': 'text'
, 'Code': 'text'
, 'Text Editor': 'text'
, 'Date': 'text'
, 'Datetime': 'text'
, 'Time': 'text'
, 'Text': 'text'
, 'Data': 'text'
, 'Link': 'text'
2018-03-27 04:20:42 +00:00
, 'DynamicLink': 'text'
2018-01-31 13:04:46 +00:00
, 'Password': 'text'
, 'Select': 'text'
, 'Read Only': 'text'
2018-03-29 18:51:24 +00:00
, 'File': 'text'
2018-01-31 13:04:46 +00:00
, 'Attach': 'text'
, 'Attach Image': 'text'
, 'Signature': 'text'
, 'Color': 'text'
, 'Barcode': 'text'
, 'Geolocation': 'text'
}
}
2018-01-12 12:25:07 +00:00
}