usqlite.js 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704
  1. /**
  2. * 对 SQLite 的 ORM 的封装处理
  3. * @time 2023-04-06
  4. * @version 2.0.0
  5. *
  6. * @by wzx
  7. */
  8. let config = {
  9. deBug: true,
  10. isConnect: false
  11. }
  12. class Response {
  13. constructor(code, msg, data) {
  14. this.code = code;
  15. this.msg = msg;
  16. this.data = data;
  17. }
  18. toString() {
  19. return JSON.stringify(this);
  20. }
  21. }
  22. class Utils {
  23. static modelSql(name, options) {
  24. let sql;
  25. let sqlArr = [];
  26. let primaryKeyArr = [];
  27. Utils.log('[modelSql] options:' + options);
  28. for (const key in options) {
  29. if (Object.hasOwnProperty.call(options, key)) {
  30. const option = options[key];
  31. sqlArr.push(Utils.restrain(key, option));
  32. if (option.primaryKey == true) {
  33. primaryKeyArr.push(key.toString());
  34. Utils.log(`${key} is primary key${primaryKeyArr.length}`);
  35. }
  36. }
  37. }
  38. Utils.log(primaryKeyArr.length);
  39. if (primaryKeyArr.length>1) {
  40. sql = `CREATE TABLE '${name}' (${sqlArr.join(', ').replaceAll(' PRIMARY KEY','')}, PRIMARY KEY (${primaryKeyArr.join()}))`;
  41. }
  42. else{
  43. sql = `CREATE TABLE '${name}' (${sqlArr.join(', ')})`;
  44. }
  45. Utils.log(`[modelSql] ${sql}`);
  46. return sql;
  47. }
  48. static restrain(key, options) {
  49. let restrainArray = [];
  50. restrainArray.push(`'${key}'`);
  51. // 如果是 String 拦截处理
  52. if (options.constructor != Object) {
  53. restrainArray.push(Utils.toType(options));
  54. return restrainArray.join(' ');
  55. }
  56. restrainArray.push(Utils.toType(options.type));
  57. // 主键
  58. if (options.primaryKey == true) {
  59. if(options.autoIncrement != true){
  60. restrainArray.push('PRIMARY KEY');
  61. }
  62. }
  63. // 自增
  64. if (Utils.isNumber(options.type)&&options.autoIncrement == true) {
  65. restrainArray.pop();
  66. restrainArray.push('INTEGER');
  67. restrainArray.push('PRIMARY KEY');
  68. restrainArray.push('AUTOINCREMENT');
  69. }
  70. // 非空
  71. if (options.notNull == true) {
  72. restrainArray.push('NOT NULL');
  73. }
  74. // 默认值
  75. if (options.default) {
  76. restrainArray.push(`DEFAULT ${options.default}`);
  77. }
  78. // 是否是不同的值
  79. if (options.unique == true) {
  80. restrainArray.push('UNIQUE');
  81. }
  82. // 检查
  83. if (options.check) {
  84. restrainArray.push(`CHECK(${THIS_VALUE.check})`);
  85. }
  86. return restrainArray.join(' ');
  87. }
  88. static toType(jsType) {
  89. let sqliteType = '';
  90. if (Utils.isNumber(jsType)) {
  91. sqliteType = 'numeric';
  92. } else if (Utils.isDate(jsType)) {
  93. sqliteType = 'timestamp';
  94. } else if (Utils.isArrayBuffer(jsType)) {
  95. sqliteType = 'blob';
  96. } else {
  97. sqliteType = 'varchar';
  98. }
  99. console.log('[toType]', jsType, sqliteType)
  100. return sqliteType;
  101. }
  102. static log() {
  103. if (config.deBug) {
  104. console.log.apply(null, arguments);
  105. }
  106. }
  107. static warn() {
  108. if (config.deBug) {
  109. console.warn.apply(null, arguments);
  110. }
  111. }
  112. static error() {
  113. console.error.apply(null, arguments);
  114. }
  115. static isArray(value){ return Object.prototype.toString.call(value) === '[object Array]'}
  116. static isObject(value){ return Object.prototype.toString.call(value) === '[object Object]'}
  117. static isString(value){ return Object.prototype.toString.call(value) === '[object String]'}
  118. static isFunction(value){ return (value === Function || Object.prototype.toString.call(value) === '[object Function]')}
  119. static isNumber(value){ return (value === Number || Object.prototype.toString.call(value) === '[object Number]')}
  120. static isNaN(value){ return (Object.prototype.toString.call(value) === '[object Number]' && isNaN(value))}
  121. static isBoolean(value){ return Object.prototype.toString.call(value) === '[object Boolean]'}
  122. static isUndefined(value){ return Object.prototype.toString.call(value) === '[object Undefined]'}
  123. static isModel(value){ return Object.prototype.toString.call(value) === '[object Model]'}
  124. static isDate(value){ return (value === Date||Object.prototype.toString.call(value) === '[object Date]')}
  125. static isArrayBuffer(value){
  126. console.log('isArrayBuffer', Object.prototype.toString.call(value))
  127. return Object.prototype.toString.call(value) === '[object ArrayBuffer]'}
  128. }
  129. /**
  130. * Model 对象内部public方法全部 return this;
  131. */
  132. class Model {
  133. /**
  134. * @constructor
  135. * @param {String} name 数据库表名
  136. * @param {} options 数据表列对象
  137. * @returns
  138. */
  139. constructor(name, options) {
  140. let self = this;
  141. self.name = name;
  142. self.options = options;
  143. if (config.isConnect) {
  144. self.repair();
  145. } else {
  146. if(!config.name||!config.path){
  147. console.error('"config.name" or "config.path" is empty');
  148. }
  149. usqlite.connect(config);
  150. }
  151. }
  152. /**
  153. * @description 查询表数据
  154. * @param {String|Array} options
  155. * - String WHERE 内容
  156. * - Array 需要查询的列
  157. * @returns
  158. */
  159. find(options='') {
  160. let sql = '';
  161. // let self = this;
  162. // self.repair();
  163. if(!(Utils.isString(options)||Utils.isArray(options)||Utils.isFunction(options))) {
  164. Utils.error('The first parameter of Model.find should be "Array", "String" or "Function" (when there is only one parameter).')
  165. }
  166. if (options == '') {
  167. sql = `SELECT * FROM '${this.name}'`; // 查找全部
  168. } else if (Utils.isArray(options)) {
  169. sql = `SELECT ${options.join()} FROM '${this.name}'`; // 查找制定列
  170. } else if (Utils.isString(options)) {
  171. sql = `SELECT * FROM '${this.name}' WHERE ${options}`; // 制定条件查询
  172. }
  173. Utils.log(`[find]: ${sql}`);
  174. return new Promise((resolve, reject) => {
  175. plus.sqlite.selectSql({
  176. name: config.name,
  177. sql: sql,
  178. success(res) {
  179. console.log('[find] res:', res)
  180. resolve(res)
  181. },
  182. fail(err) {
  183. console.error('[find] err:', err)
  184. reject(err)
  185. }
  186. });
  187. });
  188. }
  189. /**
  190. * @description 分页查询
  191. * @param {Object} options : { where:查询条件, number: 当前页数 , count : 每页数量 }
  192. * @return
  193. */
  194. limit(options) {
  195. let sql = '';
  196. // let self = this;
  197. // self.repair();
  198. if(!Utils.isObject(options)){
  199. Utils.error('The first parameter of Model.limit should be "Object".')
  200. }
  201. if (!options.where) {
  202. // 不存在 where
  203. sql =
  204. `SELECT * FROM '${this.name}' LIMIT ${options.count} OFFSET ${(options.number - 1) * options.count}`
  205. } else {
  206. // 存在 where
  207. sql =
  208. `SELECT * FROM '${this.name}' WHERE ${options.where} LIMIT ${options.count} OFFSET ${(options.number - 1) * options.count}`;
  209. };
  210. Utils.log(`[limit]: ${sql}`);
  211. return new Promise((resolve, reject) => {
  212. plus.sqlite.selectSql({
  213. name: config.name,
  214. sql: sql,
  215. success(res) {
  216. console.log('[limit] res:', res)
  217. resolve(res)
  218. },
  219. fail(err) {
  220. console.error('[limit] err:', err)
  221. reject(err)
  222. }
  223. });
  224. });
  225. }
  226. /**
  227. * @description 插入数据
  228. * @param {Object|Array} data: 需要插入的单个或者多个数据
  229. */
  230. async insert(data) {
  231. // let self = this;
  232. // self.repair();
  233. if(!(Utils.isObject(data)||Util.isArray(data))){
  234. Utils.error('The first parameter of Model.insert should be "Object" or "Array".')
  235. }
  236. if (config.isConnect) {
  237. if (Utils.isArray(data)) {
  238. for (var i = 0; i < data.length; i++) {
  239. await this.insert(data[i]);
  240. }
  241. } else if (Utils.isObject(data)) {
  242. let keys = [];
  243. let values = [];
  244. // let index = arguments[3]??null;
  245. for (var key in data) {
  246. keys.push(key);
  247. values.push(`'${data[key]}'`);
  248. }
  249. let sql = `INSERT INTO '${this.name}' (${keys.join()}) VALUES (${values.join()})`;
  250. Utils.log(`[insert]: ${sql}`);
  251. return new Promise((resolve, reject) => {
  252. plus.sqlite.executeSql({
  253. name: config.name,
  254. sql: sql,
  255. success(res) {
  256. console.log('[insert] res:', res)
  257. resolve(res)
  258. },
  259. fail(err) {
  260. console.error('[insert] err:', err)
  261. reject(err)
  262. }
  263. })
  264. });
  265. }
  266. }
  267. }
  268. /**
  269. * @description 更新数据
  270. * @param {Object} data: 修改后的数据
  271. * @param {String} options:可选参数 更新条件
  272. */
  273. update(data, options='') {
  274. // let self = this;
  275. // self.repair();
  276. let sql = '';
  277. let items = [];
  278. if(!(Utils.isObject(data))){
  279. Utils.error('The first parameter of Model.update should be "Objrct".')
  280. }
  281. if(!(Utils.isObject(options)||Utils.isString(options))){
  282. Utils.error('The second parameter of Model.update should be "Object" or "String".')
  283. }
  284. for (var key in data) {
  285. items.push(`${key}='${data[key]}'`);
  286. };
  287. if (options == '') {
  288. sql = `UPDATE '${this.name}' SET ${items.join()}`;
  289. } else {
  290. sql = `UPDATE ${this.name} SET ${items.join()} WHERE ${options}`;
  291. };
  292. Utils.log(`[update]: ${sql}`);
  293. return new Promise((resolve, reject) => {
  294. plus.sqlite.executeSql({
  295. name: config.name,
  296. sql: sql,
  297. success(res) {
  298. console.log('[update] res:', res)
  299. resolve(res)
  300. },
  301. fail(err) {
  302. console.error('[update] err:', err)
  303. reject(err)
  304. }
  305. });
  306. });
  307. }
  308. /**
  309. * @description 删除数据
  310. * @param {String} options :可选参数 删除条件
  311. */
  312. delete(options='') {
  313. // let self = this;
  314. // self.repair();
  315. var sql = '';
  316. if(!(Utils.isString(options)||Utils.isFunction(options))){
  317. Utils.error('The first parameter of Model.delete should be "Object" or "Function".')
  318. }
  319. if (options == '') {
  320. sql = `DELETE FROM '${this.name}'`;
  321. } else {
  322. sql = `DELETE FROM '${this.name}' WHERE ${options}`;
  323. };
  324. Utils.log(`[delete]: ${sql}`);
  325. return new Promise((resolve, reject) => {
  326. plus.sqlite.executeSql({
  327. name: config.name,
  328. sql: sql,
  329. success(res) {
  330. console.log('[delete] res:', res)
  331. resolve(res)
  332. },
  333. fail(err) {
  334. console.error('[delete] err:', err)
  335. reject(err)
  336. }
  337. });
  338. });
  339. }
  340. /**
  341. * @description 重命名或者新增列
  342. * @param {Object|Array|String} options 参数 数组为新增多列 对象为新增单列{aa} 字符串重命名
  343. * @return:
  344. */
  345. async alter(options) {
  346. let self = this;
  347. // self.repair();
  348. let sql = '';
  349. if(!(Utils.isObject(options)||Utils.isArray(options)||Utils.isString(options))){
  350. Utils.error('The first parameter of Model.alter should be "Object", "Array" or "String".')
  351. }
  352. if (Utils.isArray(options)) { // 新增多列
  353. for (let i = 0; i < options.length; i++) {
  354. await this.alter(options[i]);
  355. }
  356. } else if (Utils.isObject(options)) { // 新增单列
  357. let column = Utils.restrain(options.name, options.option);
  358. sql = `ALTER TABLE '${this.name}' ADD COLUMN ${column}`
  359. } else if (options.constructor == String) { // 重命名
  360. sql = `ALTER TABLE '${this.name}' RENAME TO '${options}'`
  361. }
  362. Utils.log(`[alter]: ${sql}`);
  363. return new Promise((resolve, reject) => {
  364. plus.sqlite.selectSql({
  365. name: config.name,
  366. sql: sql,
  367. success(res) {
  368. if (options.constructor == String) { // 重命名
  369. self.name = options;
  370. }
  371. console.log('[alter] res:', res)
  372. resolve(res)
  373. },
  374. fail(err) {
  375. console.error('[alter] err:', err)
  376. reject(err)
  377. }
  378. });
  379. });
  380. }
  381. /**
  382. * @description
  383. * @param {Model} model 右 Model
  384. * @param {Object} options
  385. * @returns
  386. */
  387. join(model, options) {
  388. // let self = this;
  389. // self.repair();
  390. if (!model) {
  391. Utils.error('"model" cannot be empty.');
  392. }
  393. if (!Utils.isObject(options)) {
  394. Utils.error('The type of "options" is wrong, it should be "Object".');
  395. }
  396. if (!options.type || !options.predicate) {
  397. Utils.error('Missing required parameters');
  398. }
  399. let leftName = this.name;
  400. let rightName = model.name;
  401. let leftValue = options.predicate.left;
  402. let rightValue = options.predicate.right;
  403. let cols = ['*'];
  404. const SQL_MAP = {
  405. cross: `SELECT ${cols.join()} FROM ${leftName} CROSS JOIN ${rightName};`,
  406. inner: [`SELECT ${cols.join()} FROM ${leftName} NATURAL JOIN ${rightName}`,
  407. `SELECT ${cols.join()} FROM ${leftName} INNER JOIN ${rightName} ON ${leftName}.${leftValue} = ${rightName}.${rightValue}`
  408. ],
  409. outer: `SELECT ${cols.join()} FROM ${leftName} OUTER JOIN ${rightName} ON ${leftName}.${leftValue} = ${rightName}.${rightValue}`
  410. }
  411. let sql = '';
  412. if (options.type == inner && !options.predicate) {
  413. sql = SQL_MAP[options.type][0];
  414. } else if (options.type == inner && !options.predicate) {
  415. sql = SQL_MAP[options.type][1];
  416. } else {
  417. sql = SQL_MAP[options.type];
  418. }
  419. Utils.log(`[join]: ${sql}`);
  420. return new Promise((resolve, reject) => {
  421. plus.sqlite.selectSql({
  422. name: config.name,
  423. sql: sql,
  424. success(res) {
  425. console.log('[join] res:', res)
  426. resolve(res)
  427. },
  428. fail(err) {
  429. console.error('[join] err:', err)
  430. reject(err)
  431. }
  432. });
  433. });
  434. }
  435. /**
  436. * @description 执行sql语句
  437. * @param {String} sql : sql语句
  438. */
  439. sql(sql) {
  440. if (!Utils.isString(sql)) {
  441. Utils.error('"The type of "sql" is wrong, it should be "String".');
  442. }
  443. // let self = this;
  444. // self.repair();
  445. Utils.log(`[sql]: ${sql}`);
  446. return new Promise((resolve, reject) => {
  447. plus.sqlite.selectSql({
  448. name: config.name,
  449. sql: sql,
  450. success(res) {
  451. console.log('[sql] res:', res)
  452. resolve(res)
  453. },
  454. fail(err) {
  455. console.error('[sql] err:', err)
  456. reject(err)
  457. }
  458. });
  459. });
  460. }
  461. /**
  462. * @description 判断表是否存在
  463. */
  464. isExist() {
  465. let sql = `SELECT count(*) AS isExist FROM sqlite_master WHERE type='table' AND name='${this.name}'`;
  466. Utils.log(`[isExist] Table: ${config.name}`);
  467. // Utils.log(`[isExist] ${sql}`);
  468. return new Promise((resolve, reject) => {
  469. plus.sqlite.selectSql({
  470. name: config.name,
  471. sql: sql,
  472. success(res) {
  473. console.log('[isExist] res:', res)
  474. resolve(res)
  475. },
  476. fail(err) {
  477. console.error('[isExist] err:', err)
  478. reject(err)
  479. }
  480. });
  481. });
  482. }
  483. /**
  484. * @description 删除数据表 **不推荐**
  485. */
  486. drop() {
  487. var sql = `DROP TABLE '${this.name}'`;
  488. // let self = this;
  489. // self.repair();
  490. Utils.log(`[drop]: ${sql}`);
  491. return new Promise((resolve, reject) => {
  492. plus.sqlite.selectSql({
  493. name: config.name,
  494. sql: sql,
  495. success(res) {
  496. console.log('[drop] res:', res)
  497. resolve(res)
  498. },
  499. fail(err) {
  500. console.error('[drop] err:', err)
  501. reject(err)
  502. }
  503. });
  504. });
  505. }
  506. /**
  507. * @description 创建数据表 **不推荐**
  508. */
  509. create() {
  510. // let self = this;
  511. let sql = Utils.modelSql(this.name, this.options);
  512. Utils.log(`[create]: ${sql}`);
  513. return new Promise((resolve, reject) => {
  514. plus.sqlite.selectSql({
  515. name: config.name,
  516. sql: sql,
  517. success(res) {
  518. console.log('[create] res:', res)
  519. resolve(res)
  520. },
  521. fail(err) {
  522. console.error('[create] err:', err)
  523. reject(err)
  524. }
  525. });
  526. });
  527. }
  528. toString() {
  529. return `[${this.name} Model]`;
  530. }
  531. async repair() {
  532. let self = this;
  533. try {
  534. let res = await self.isExist()
  535. if (!res[0].isExist) {
  536. await self.create();
  537. }
  538. } catch(e) {
  539. console.error(e);
  540. }
  541. }
  542. }
  543. // 单例模式
  544. export class usqlite {
  545. /**
  546. * 构造函数
  547. * @param {Object} options 数据库配置信息 *
  548. * {name: 'demo', path: '_doc/demo.db'}
  549. * - name 数据库名称*
  550. * - path 数据库路径
  551. */
  552. constructor(options) {
  553. console.warn('No instantiation');
  554. }
  555. /**
  556. * @description 链接数据库
  557. * @param {Object} options 数据库配置信息 *
  558. * {name: 'demo', path: '_doc/demo.db'}
  559. * - name 数据库名称*
  560. * - path 数据库路径
  561. */
  562. static connect(options) {
  563. config.name = options.name; // 数据库名称*
  564. config.path = options.path; // 数据库名称*
  565. return new Promise((resolve, reject) => {
  566. plus.sqlite.openDatabase({
  567. name: config.name, //数据库名称
  568. path: config.path, //数据库地址
  569. success(res) {
  570. config.isConnect = true;
  571. // console.log('[connect] res:', res)
  572. resolve(res)
  573. },
  574. fail(err) {
  575. if (e.code == -1402) {
  576. config.isConnect = true;
  577. console.warn('[connect] warn:', err)
  578. } else {
  579. config.isConnect = false;
  580. console.error('[connect] err:', err)
  581. }
  582. reject(err)
  583. }
  584. });
  585. });
  586. }
  587. /**
  588. * @description 断开数据库
  589. * @param {*} callback
  590. */
  591. static close() {
  592. return new Promise((resolve, reject) => {
  593. plus.sqlite.closeDatabase({
  594. name: config.name, //数据库名称
  595. path: config.path, //数据库地址
  596. success(res) {
  597. config.isConnect = false;
  598. // console.log('[close] res:', res)
  599. resolve(res)
  600. },
  601. fail(err) {
  602. console.error('[close] err:', err)
  603. reject(err)
  604. }
  605. });
  606. });
  607. }
  608. /**
  609. * @description 创建 Model 对象
  610. * @example
  611. * usqlite.model('demo',
  612. * {
  613. * id: {
  614. * type: Number
  615. * },
  616. * content: String
  617. * })
  618. * @param {String} name 数据表名称 *
  619. * @param {String} options 参数配置 *
  620. * @returns 返回 Model 对象
  621. */
  622. static model(name, options) {
  623. Utils.log(config);
  624. return new Model(name, options);
  625. }
  626. }