├── LICENSE ├── README.md ├── example └── index.html └── lib └── jsonDB.js /LICENSE: -------------------------------------------------------------------------------- 1 | Apache License 2 | Version 2.0, January 2004 3 | http://www.apache.org/licenses/ 4 | 5 | TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION 6 | 7 | 1. Definitions. 8 | 9 | "License" shall mean the terms and conditions for use, reproduction, 10 | and distribution as defined by Sections 1 through 9 of this document. 11 | 12 | "Licensor" shall mean the copyright owner or entity authorized by 13 | the copyright owner that is granting the License. 14 | 15 | "Legal Entity" shall mean the union of the acting entity and all 16 | other entities that control, are controlled by, or are under common 17 | control with that entity. For the purposes of this definition, 18 | "control" means (i) the power, direct or indirect, to cause the 19 | direction or management of such entity, whether by contract or 20 | otherwise, or (ii) ownership of fifty percent (50%) or more of the 21 | outstanding shares, or (iii) beneficial ownership of such entity. 22 | 23 | "You" (or "Your") shall mean an individual or Legal Entity 24 | exercising permissions granted by this License. 25 | 26 | "Source" form shall mean the preferred form for making modifications, 27 | including but not limited to software source code, documentation 28 | source, and configuration files. 29 | 30 | "Object" form shall mean any form resulting from mechanical 31 | transformation or translation of a Source form, including but 32 | not limited to compiled object code, generated documentation, 33 | and conversions to other media types. 34 | 35 | "Work" shall mean the work of authorship, whether in Source or 36 | Object form, made available under the License, as indicated by a 37 | copyright notice that is included in or attached to the work 38 | (an example is provided in the Appendix below). 39 | 40 | "Derivative Works" shall mean any work, whether in Source or Object 41 | form, that is based on (or derived from) the Work and for which the 42 | editorial revisions, annotations, elaborations, or other modifications 43 | represent, as a whole, an original work of authorship. For the purposes 44 | of this License, Derivative Works shall not include works that remain 45 | separable from, or merely link (or bind by name) to the interfaces of, 46 | the Work and Derivative Works thereof. 47 | 48 | "Contribution" shall mean any work of authorship, including 49 | the original version of the Work and any modifications or additions 50 | to that Work or Derivative Works thereof, that is intentionally 51 | submitted to Licensor for inclusion in the Work by the copyright owner 52 | or by an individual or Legal Entity authorized to submit on behalf of 53 | the copyright owner. For the purposes of this definition, "submitted" 54 | means any form of electronic, verbal, or written communication sent 55 | to the Licensor or its representatives, including but not limited to 56 | communication on electronic mailing lists, source code control systems, 57 | and issue tracking systems that are managed by, or on behalf of, the 58 | Licensor for the purpose of discussing and improving the Work, but 59 | excluding communication that is conspicuously marked or otherwise 60 | designated in writing by the copyright owner as "Not a Contribution." 61 | 62 | "Contributor" shall mean Licensor and any individual or Legal Entity 63 | on behalf of whom a Contribution has been received by Licensor and 64 | subsequently incorporated within the Work. 65 | 66 | 2. Grant of Copyright License. Subject to the terms and conditions of 67 | this License, each Contributor hereby grants to You a perpetual, 68 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 69 | copyright license to reproduce, prepare Derivative Works of, 70 | publicly display, publicly perform, sublicense, and distribute the 71 | Work and such Derivative Works in Source or Object form. 72 | 73 | 3. Grant of Patent License. Subject to the terms and conditions of 74 | this License, each Contributor hereby grants to You a perpetual, 75 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 76 | (except as stated in this section) patent license to make, have made, 77 | use, offer to sell, sell, import, and otherwise transfer the Work, 78 | where such license applies only to those patent claims licensable 79 | by such Contributor that are necessarily infringed by their 80 | Contribution(s) alone or by combination of their Contribution(s) 81 | with the Work to which such Contribution(s) was submitted. If You 82 | institute patent litigation against any entity (including a 83 | cross-claim or counterclaim in a lawsuit) alleging that the Work 84 | or a Contribution incorporated within the Work constitutes direct 85 | or contributory patent infringement, then any patent licenses 86 | granted to You under this License for that Work shall terminate 87 | as of the date such litigation is filed. 88 | 89 | 4. Redistribution. You may reproduce and distribute copies of the 90 | Work or Derivative Works thereof in any medium, with or without 91 | modifications, and in Source or Object form, provided that You 92 | meet the following conditions: 93 | 94 | (a) You must give any other recipients of the Work or 95 | Derivative Works a copy of this License; and 96 | 97 | (b) You must cause any modified files to carry prominent notices 98 | stating that You changed the files; and 99 | 100 | (c) You must retain, in the Source form of any Derivative Works 101 | that You distribute, all copyright, patent, trademark, and 102 | attribution notices from the Source form of the Work, 103 | excluding those notices that do not pertain to any part of 104 | the Derivative Works; and 105 | 106 | (d) If the Work includes a "NOTICE" text file as part of its 107 | distribution, then any Derivative Works that You distribute must 108 | include a readable copy of the attribution notices contained 109 | within such NOTICE file, excluding those notices that do not 110 | pertain to any part of the Derivative Works, in at least one 111 | of the following places: within a NOTICE text file distributed 112 | as part of the Derivative Works; within the Source form or 113 | documentation, if provided along with the Derivative Works; or, 114 | within a display generated by the Derivative Works, if and 115 | wherever such third-party notices normally appear. The contents 116 | of the NOTICE file are for informational purposes only and 117 | do not modify the License. You may add Your own attribution 118 | notices within Derivative Works that You distribute, alongside 119 | or as an addendum to the NOTICE text from the Work, provided 120 | that such additional attribution notices cannot be construed 121 | as modifying the License. 122 | 123 | You may add Your own copyright statement to Your modifications and 124 | may provide additional or different license terms and conditions 125 | for use, reproduction, or distribution of Your modifications, or 126 | for any such Derivative Works as a whole, provided Your use, 127 | reproduction, and distribution of the Work otherwise complies with 128 | the conditions stated in this License. 129 | 130 | 5. Submission of Contributions. Unless You explicitly state otherwise, 131 | any Contribution intentionally submitted for inclusion in the Work 132 | by You to the Licensor shall be under the terms and conditions of 133 | this License, without any additional terms or conditions. 134 | Notwithstanding the above, nothing herein shall supersede or modify 135 | the terms of any separate license agreement you may have executed 136 | with Licensor regarding such Contributions. 137 | 138 | 6. Trademarks. This License does not grant permission to use the trade 139 | names, trademarks, service marks, or product names of the Licensor, 140 | except as required for reasonable and customary use in describing the 141 | origin of the Work and reproducing the content of the NOTICE file. 142 | 143 | 7. Disclaimer of Warranty. Unless required by applicable law or 144 | agreed to in writing, Licensor provides the Work (and each 145 | Contributor provides its Contributions) on an "AS IS" BASIS, 146 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or 147 | implied, including, without limitation, any warranties or conditions 148 | of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A 149 | PARTICULAR PURPOSE. You are solely responsible for determining the 150 | appropriateness of using or redistributing the Work and assume any 151 | risks associated with Your exercise of permissions under this License. 152 | 153 | 8. Limitation of Liability. In no event and under no legal theory, 154 | whether in tort (including negligence), contract, or otherwise, 155 | unless required by applicable law (such as deliberate and grossly 156 | negligent acts) or agreed to in writing, shall any Contributor be 157 | liable to You for damages, including any direct, indirect, special, 158 | incidental, or consequential damages of any character arising as a 159 | result of this License or out of the use or inability to use the 160 | Work (including but not limited to damages for loss of goodwill, 161 | work stoppage, computer failure or malfunction, or any and all 162 | other commercial damages or losses), even if such Contributor 163 | has been advised of the possibility of such damages. 164 | 165 | 9. Accepting Warranty or Additional Liability. While redistributing 166 | the Work or Derivative Works thereof, You may choose to offer, 167 | and charge a fee for, acceptance of support, warranty, indemnity, 168 | or other liability obligations and/or rights consistent with this 169 | License. However, in accepting such obligations, You may act only 170 | on Your own behalf and on Your sole responsibility, not on behalf 171 | of any other Contributor, and only if You agree to indemnify, 172 | defend, and hold each Contributor harmless for any liability 173 | incurred by, or claims asserted against, such Contributor by reason 174 | of your accepting any such warranty or additional liability. 175 | 176 | END OF TERMS AND CONDITIONS 177 | 178 | APPENDIX: How to apply the Apache License to your work. 179 | 180 | To apply the Apache License to your work, attach the following 181 | boilerplate notice, with the fields enclosed by brackets "{}" 182 | replaced with your own identifying information. (Don't include 183 | the brackets!) The text should be enclosed in the appropriate 184 | comment syntax for the file format. We also recommend that a 185 | file or class name and description of purpose be included on the 186 | same "printed page" as the copyright notice for easier 187 | identification within third-party archives. 188 | 189 | Copyright {yyyy} {name of copyright owner} 190 | 191 | Licensed under the Apache License, Version 2.0 (the "License"); 192 | you may not use this file except in compliance with the License. 193 | You may obtain a copy of the License at 194 | 195 | http://www.apache.org/licenses/LICENSE-2.0 196 | 197 | Unless required by applicable law or agreed to in writing, software 198 | distributed under the License is distributed on an "AS IS" BASIS, 199 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 200 | See the License for the specific language governing permissions and 201 | limitations under the License. 202 | 203 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | ###jsonDB 2 | 3 | jsonDB是js的一个类库,实现使用SQL语句对json数据增删改查。
4 | jsonDB的构建源自于HTML5本地存储的一个应用需求,可以通过sql对json数据进行增删改查,同时该类库提供强大的where检索条件,数据排序,limit查询条件限制等数据库基本功能。
5 | 通过jsonDB可以轻松维护一个库/表或多个库/表,而无需额外实现json的数据的维护等,在该类库完善以后为简化sql操作,基于jsonDB核心模块扩展了连贯操作模型,简化对jsonDB的操作以及sql语句出错的概率。 6 | 7 | 当前版本的不足: 8 | ------------------- 9 | 1.无法支持查询字段运算 10 | 2.不支持对没有选取的查询字段排序 11 | 3.只支持单个字段排序,无法进行组合排序操作 12 | 4.update、delete语句不支持order by子句,导致limit子句功能弱化 13 | 5.编写where条件是必须使用()包含where条件 14 | 6.无法选取深层次的字段作为返回字段 15 | 7.没有错误或异常解决方案 16 | 8.不支持外部扩展 17 | 18 | jsonDB基础应用示例: 19 | ------------------- 20 | ```javascript 21 | //创建一张user数据表,并定义一个DB的jsonDB别名 22 | var data = [{username:'张三',sex:'男',birthday:{year:2000,month:6,day:18}},{username:'李红',sex:'女',birthday:{year:1986,month:9,day:22}}]; 23 | //以下方法可以通过两种方式获取别名,一个是通过init方法获取(推荐),一个是获取jsonDB()方法的返回值 24 | //以后示例中都将使用init()方法创建的别名操作数据 25 | var jDB = jsonDB(data,'user').init('DB'); 26 | 27 | //插入一条新的数据 28 | data = {username:'李想',sex:'男',birthday:{year:1990,month:2,day:15}}; 29 | DB.insert(data,'user'); 30 | 31 | //查询姓名为李红的性别,where条件必须加()否者会出现错误 32 | var result =DB.query('select sex from user where (username="李红")'); 33 | //结果:[{"sex":"女"}] 34 | 35 | //查询2000年之前出生的且按出生年先后排序 36 | var result =DB.query('select * from user where (birthday.year<2000) order by birthday.year asc'); 37 | //结果:[{"username":"李红","sex":"女","birthday":{"year":1986,"month":9,"day":22}},{"username":"李想","sex":"男","birthday":{"year":1990,"month":2,"day":15}}] 38 | 39 | //查询年龄最小的两个人 40 | var result =DB.query('select * from user order by birthday.year desc limit 2'); 41 | //查询结果:[{"username":"张三","sex":"男","birthday":{"year":2000,"month":6,"day":18}},{"username":"李想","sex":"男","birthday":{"year":1990,"month":2,"day":15}}] 42 | 43 | //修改李红的出生日期 44 | var result =DB.query('update user set birthday.year=1991 where (username="李红") limit 1'); 45 | //影响条数为一条,可以通过DB.findAll('user')获取全部数据查看是否被修改成功 46 | 47 | //删除姓名为李想的数据 48 | var result =DB.query('delete from user where (username="李想") limit 1'); 49 | //影响条数为一条,可以通过DB.findAll('user')获取全部数据查看是否被删除成功 50 | 51 | //数据库中所有数据 52 | //[{"username":"张三","sex":"男","birthday":{"year":2000,"month":6,"day":18}},{"username":"李红","sex":"女","birthday":{"year":1991,"month":9,"day":22}}] 53 | ``` 54 | 55 | jsonDB的高级应用示例: 56 | ------------------- 57 | ```javascript 58 | //向数据表插入一条数据 59 | DB.table('user').add({username:'王帅',sex:'男',birthday:{year:1995,month:10,day:23}}); 60 | 61 | //查询所有人出生日期,并按出生年排序,由于之前使用table('user')定义为user表,所以可以省略,table方法定义是一直有效的,除非是重新设定了 62 | var result = DB.field('username,birthday').order('birthday.year').select(); 63 | //查询结果 [{"username":"李红","birthday":{"year":1991,"month":9,"day":22}},{"username":"王帅","birthday":{"year":1995,"month":10,"day":23}},{"username":"张三","birthday":{"year":2000,"month":6,"day":18}}] 64 | 65 | //先插入一些数据,方便后面的检索操作 66 | DB.table('user').add({username:'李亨',sex:'男',birthday:{year:2008,month:8,day:8}}) 67 | .add({username:'张琦',sex:'男',birthday:{year:1990,month:10,day:23}}) 68 | .add({username:'李媛芳',sex:'女',birthday:{year:1985,month:2,day:28}}) 69 | .add({username:'李果果',sex:'女',birthday:{year:2002,month:3,day:15}}) 70 | .add({username:'张源',sex:'男',birthday:{year:2005,month:12,day:5}}) 71 | .add({username:'王丽娜',sex:'女',birthday:{year:1992,month:5,day:12}}); 72 | 73 | //高级查询之模糊搜索 74 | //查询所有李姓成员(正则查找法) 75 | var result = DB.field(["username"]).where('username.match(/^李/)').select(); 76 | //查询结果[{"username":"李红"},{"username":"李亨"},{"username":"李媛芳"},{"username":"李果果"}] 77 | 78 | //查询所有李姓成员(字符串搜索法) 79 | var result = DB.field(["username"]).where('username.indexOf("李")=0').select(); 80 | //查询结果[{"username":"李红"},{"username":"李亨"},{"username":"李媛芳"},{"username":"李果果"}] 81 | 82 | //查询所有在1990年到1995年出生的人 83 | var result = DB.field(["username","birthday"]).where('birthday.year>=1990 and birthday.year<=1995').order('birthday.year').select(); 84 | //查询结果:[{"username":"张琦","birthday":{"year":1990,"month":10,"day":23}},{"username":"李红","birthday":{"year":1991,"month":9,"day":22}},{"username":"王丽娜","birthday":{"year":1992,"month":5,"day":12}},{"username":"王帅","birthday":{"year":1995,"month":10,"day":23}}] 85 | ``` 86 | -------------------------------------------------------------------------------- /example/index.html: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | jsonDB使用示例 6 | 7 | 74 | 75 | 76 | 77 | 78 | -------------------------------------------------------------------------------- /lib/jsonDB.js: -------------------------------------------------------------------------------- 1 | /** 2 | +----------------------------------------- 3 | * jsonDB 基于json数据格式构建的数据模型 4 | +----------------------------------------- 5 | * @description 对json数据检索,删除,查询和更新 6 | * @author 戚银(web程序猿) thinkercode.china@gamil.com 7 | * @date 2014年6月28日 8 | * @version 0.1 9 | * @blog http://blog.csdn.net/thinkercode/ 10 | +----------------------------------------- 11 | * 简介: 12 | * jsonDB是js的一个类库,是基于json数据格式构建的数据 13 | * 模型实现对json数据增删改查。jsonDB的构建源自于HTML5 14 | * 本地存储的一个应用需求,可以通过sql对json数据进行增 15 | * 删改查,同时该类库提供强大的where检索条件,数据排序, 16 | * limit查询条件限制等数据库基本功能。通过jsonDB可以轻 17 | * 松维护一个库/表或多个库/表,而无需额外实现json的数据 18 | * 的维护等,在该类库完善以后为简化sql操作,基于jsonDB核 19 | * 心模块扩展了连贯操作模型,简化对jsonDB的操作以及sql语 20 | * 句出错的概率。 21 | +----------------------------------------- 22 | * 当前版本的不足: 23 | * 1.无法支持查询字段运算 24 | * 2.不支持对没有选取的查询字段排序 25 | * 3.只支持单个字段排序,无法进行组合排序操作 26 | * 4.update、delete语句不支持order by子句,导致limit子句功能弱化 27 | * 5.编写where条件是必须使用()包含where条件 28 | * 6.无法选取深层次的字段作为返回字段 29 | * 7.没有错误或异常解决方案 30 | * 8.不支持外部扩展 31 | +----------------------------------------- 32 | * jsonDB的使用: 33 | * jsonDB会提供一个详细的使用手册,其中包含大量示例 34 | * jsonDB还有很多可以使用的技巧并没有一一包含在手册中 35 | * 期望强大的网友一起挖掘jsonDB的潜在使用技巧,并分享给大家 36 | * 如果使用中发现问题可以随时发送邮件,或者通过博客留言等方式一起探讨 37 | * 同时鉴于自己实力有限,期望发动网友一起扩展jsonDB, 38 | * 能在未来前端应用中奉献一份力量 39 | +----------------------------------------- 40 | */ 41 | (function(window,undefined){ 42 | _jsonDB = window.jsonDB, 43 | _history = null, 44 | DBCore = {}, 45 | Database = {}, 46 | DBExpand = {}; 47 | 48 | 49 | /** 50 | * [jsonDB 初始化模型,支持定义本地数据库和数据表] 51 | * @param mixed data 数据 52 | * @param string dbName 数据库名字 53 | * @return jsonDB 54 | */ 55 | var jsonDB = function(data,dbName){ 56 | 57 | //创建数据库或者数据表 58 | if(data){ 59 | dbName = dbName || 'json_db'; 60 | eval('Database.'+ dbName +'= data'); 61 | } 62 | 63 | return jsonDB.fn.init(); 64 | } 65 | 66 | jsonDB.fn = jsonDB.prototype = { 67 | //初始化插件 68 | init : function (alias){ 69 | if(alias){ 70 | _history = window[alias]; 71 | window[alias] = jsonDB(); 72 | } 73 | return this; 74 | }, 75 | 76 | query : function(sql){ 77 | var type = sql.match(/^(\w+)/); 78 | switch(type[0]){ 79 | case 'select' : 80 | case 'delete' : 81 | case 'update' : 82 | return eval('DBCore.fn.'+ type[0] +'(sql+" ")'); 83 | break; 84 | default : 85 | return false; 86 | break; 87 | } 88 | }, 89 | 90 | insert : function(data,dbName){ 91 | if(data){ 92 | dbName = dbName || 'json_db'; 93 | eval('Database.'+ dbName +'.push(data)'); 94 | } 95 | return this; 96 | }, 97 | 98 | findAll : function(dbName){ 99 | if(dbName){ 100 | return eval('Database.'+ dbName); 101 | } 102 | return Database; 103 | } 104 | }; 105 | 106 | /** 107 | * [DBExpand 数据库核心功能扩展] 108 | */ 109 | DBExpand = DBExpand.prototype = { 110 | sqlParam : { 111 | fields : '*', 112 | table : 'json_db', 113 | where : null, 114 | order : null, 115 | limit : null, 116 | }, 117 | 118 | add : function(data){ 119 | return this.insert(data,this.sqlParam.table); 120 | }, 121 | 122 | select : function(){ 123 | var sql = 'select '+this.sqlParam.fields+' from '+this.sqlParam.table; 124 | if(this.sqlParam.where){ 125 | sql += ' where '+this.sqlParam.where; 126 | } 127 | if(this.sqlParam.order){ 128 | sql += ' order by '+this.sqlParam.order; 129 | } 130 | if(this.sqlParam.limit){ 131 | sql += ' limit '+this.sqlParam.limit; 132 | } 133 | 134 | this.clear(); 135 | return this.query(sql); 136 | }, 137 | 138 | update : function(data){ 139 | if(data.length<1){ 140 | return false; 141 | } 142 | 143 | var sql = 'update '+this.sqlParam.table+' set '+data; 144 | if(this.sqlParam.where){ 145 | sql += ' where '+this.sqlParam.where; 146 | } 147 | if(this.sqlParam.limit){ 148 | sql += ' limit '+this.sqlParam.limit; 149 | } 150 | this.clear(); 151 | return this.query(sql); 152 | }, 153 | 154 | delete : function(){ 155 | if(this.sqlParam.where.length<1){ 156 | return false; 157 | } 158 | 159 | var sql = 'delete from '+this.sqlParam.table; 160 | if(this.sqlParam.where){ 161 | sql += ' where '+this.sqlParam.where; 162 | } 163 | if(this.sqlParam.limit){ 164 | sql += ' limit '+this.sqlParam.limit; 165 | } 166 | this.clear(); 167 | return this.query(sql); 168 | }, 169 | 170 | drop : function(dbName){ 171 | //创建数据库或者数据表 172 | if(data){ 173 | dbName = dbName || 'json_db'; 174 | eval('Database.'+ dbName +'= null'); 175 | } 176 | return this; 177 | }, 178 | 179 | field : function(fields){ 180 | if(typeof fields == 'object'){ 181 | this.sqlParam.fields = fields.join(','); 182 | }else{ 183 | this.sqlParam.fields = fields; 184 | } 185 | return this; 186 | }, 187 | 188 | table : function(table){ 189 | this.sqlParam.table = table; 190 | return this; 191 | }, 192 | 193 | where : function(where){ 194 | this.sqlParam.where = '('+where+')'; 195 | return this; 196 | }, 197 | 198 | order : function(order){ 199 | this.sqlParam.order = order; 200 | return this; 201 | }, 202 | 203 | limit : function(limit){ 204 | this.sqlParam.limit = limit; 205 | return this; 206 | }, 207 | 208 | clear : function(){ 209 | this.sqlParam.fields = '*'; 210 | this.sqlParam.where = null; 211 | this.sqlParam.order = null; 212 | this.sqlParam.limit = null; 213 | } 214 | } 215 | 216 | /** 217 | * [DBCore 数据库核心] 218 | */ 219 | DBCore.fn = DBCore.prototype = { 220 | SqlRegExp : { 221 | fields: '([a-z0-9_\\,\\.\\s\\*]*?\\s+)', 222 | from : '(from\\s+([a-z0-9_\\.]+)\\s*)?', 223 | where : '(?:where\\s+(\\(.*\\))\\s*)?', 224 | order : '(?:order\\s+by\\s+([a-z0-9_\\,\\.]+))?\\s+(asc|desc|ascnum|descnum)?\\s*', 225 | limit : '(?:limit\\s+([0-9\\,]+))?', 226 | set : '(set\\s+(.*?)\\s+)', 227 | table : '(([a-z0-9_\\.]*?)\\s*)?', 228 | }, 229 | 230 | select : function(sql){ 231 | var params = {fields:["*"], from:"json_db", where:"", orderby:[], order: "asc", limit:[]}, 232 | SqlRegExp = this.SqlRegExp, 233 | reg = '^(select)\\s+'+SqlRegExp.fields + SqlRegExp.from + SqlRegExp.where + SqlRegExp.order + SqlRegExp.limit, 234 | sqlReg = new RegExp(reg,'i'), 235 | sqlFields = sql.match(sqlReg), 236 | options = { 237 | fields: sqlFields[2].replace(' ','').split(','), 238 | from: (sqlFields[4] == undefined) ? 'json_db' : sqlFields[4], 239 | where: (sqlFields[5] == undefined) ? "true" : sqlFields[5].replace(/([^\>\<\!\=])=([^\>\<\!\=])/gi,'$1 == $2').replace(/\sand\s/gi,' && ').replace(/\sor\s/gi,' || ').replace(/`/gi,''), 240 | orderby: (sqlFields[6] == undefined) ? []:sqlFields[6].replace(' ','').split(','), 241 | order: (sqlFields[7] == undefined) ? "asc" : sqlFields[7], 242 | limit: (sqlFields[8] == undefined) ? [] : sqlFields[8].replace(' ','').split(',') 243 | }; 244 | 245 | for(i in options){ 246 | params[i] = options[i]; 247 | } 248 | 249 | var result = []; 250 | result = this.filter(params,function(data){ 251 | if(options.fields.length == 0 || options.fields[0] == "*"){ 252 | return data; 253 | } 254 | 255 | var result = {}; 256 | for(var i in options.fields){ 257 | result[options.fields[i]] = data[options.fields[i]]; 258 | } 259 | return result; 260 | }); 261 | result = this.orderBy(result,options); 262 | result = this.limit(result,options); 263 | return result; 264 | }, 265 | 266 | update : function(sql){ 267 | var params = {from:"json_db", where:"", limit:[], set:[]}, 268 | SqlRegExp = this.SqlRegExp, 269 | reg = '^(update)\\s+'+ SqlRegExp.table + SqlRegExp.set + SqlRegExp.where + SqlRegExp.limit, 270 | sqlReg = new RegExp(reg,'i'), 271 | sqlFields = sql.match(sqlReg), 272 | options = { 273 | from: (sqlFields[3] == undefined) ? 'json_db' : sqlFields[3], 274 | set: (sqlFields[5] == undefined) ? [] : sqlFields[5].replace(' ','').split(','), 275 | where: (sqlFields[6] == undefined) ? "true" : sqlFields[6].replace(/([^\>\<\!\=])=([^\>\<\!\=])/gi,'$1 == $2').replace(/\sand\s/gi,' && ').replace(/\sor\s/gi,' || ').replace(/`/gi,''), 276 | limit: (sqlFields[7] == undefined) ? [] : sqlFields[7].replace(' ','').split(',') 277 | }; 278 | 279 | for(i in options){ 280 | params[i] = options[i]; 281 | } 282 | var jsonData = eval('Database.' + options.from), 283 | tally = 0, 284 | extent = this.extent(params), 285 | setLen = options.set.length, 286 | affected_rows = 0; 287 | 288 | if(setLen<1){ 289 | return false; 290 | } 291 | 292 | options.where = options.where || "true"; 293 | for(var i in jsonData){ 294 | with(jsonData[i]){ 295 | if(eval(options.where)){ 296 | if(affected_rows >= extent.start && tally < extent.stop){ 297 | for(var j=0;j\<\!\=])=([^\>\<\!\=])/gi,'$1 == $2').replace(/\sand\s/gi,' && ').replace(/\sor\s/gi,' || ').replace(/`/gi,''), 320 | limit: (sqlFields[5] == undefined) ? [] : sqlFields[5].replace(' ','').split(',') 321 | }; 322 | 323 | for(i in options){ 324 | params[i] = options[i]; 325 | } 326 | 327 | var jsonData = eval('Database.' + options.from + '.concat()'), 328 | tally = 0, 329 | extent = this.extent(params), 330 | affected_rows = 0; 331 | 332 | options.where = options.where || "true"; 333 | for(var i in jsonData){ 334 | with(jsonData[i]){ 335 | if(eval(options.where)){ 336 | if(affected_rows >= extent.start && tally < extent.stop){ 337 | eval('Database.'+options.from+'.splice(i-tally,1)'); 338 | ++tally; 339 | }else if(tally == extent.stop){ 340 | return tally; 341 | } 342 | ++affected_rows; 343 | } 344 | } 345 | } 346 | return tally; 347 | }, 348 | 349 | filter : function(options, callback){ 350 | var jsonData = eval('Database.' + options.from), 351 | result = [], 352 | index = 0; 353 | 354 | options.where = options.where || "true"; 355 | for(var i in jsonData){ 356 | with(jsonData[i]){ 357 | if(eval(options.where)){ 358 | if(callback){ 359 | result[index++] = callback(jsonData[i]); 360 | }else{ 361 | result[index++] = jsonData[i]; 362 | } 363 | } 364 | } 365 | } 366 | 367 | return result; 368 | }, 369 | 370 | orderBy : function(result,options){ 371 | if(options.orderby.length == 0){ 372 | return result; 373 | } 374 | 375 | result.sort(function(a,b){ 376 | switch(options.order.toLowerCase()){ 377 | case "desc": return (eval('a.'+ options.orderby[0] +' < b.'+ options.orderby[0]))? 1:-1; 378 | case "asc": return (eval('a.'+ options.orderby[0] +' > b.'+ options.orderby[0]))? 1:-1; 379 | case "descnum": return (eval('a.'+ options.orderby[0] +' - b.'+ options.orderby[0])); 380 | case "ascnum": return (eval('b.'+ options.orderby[0] +' - a.'+ options.orderby[0])); 381 | } 382 | }); 383 | 384 | return result; 385 | }, 386 | 387 | limit : function(result,options){ 388 | switch(options.limit.length){ 389 | case 0: 390 | return result; 391 | case 1: 392 | return result.splice(0,options.limit[0]); 393 | case 2: 394 | return result.splice(options.limit[0],options.limit[1]); 395 | } 396 | }, 397 | 398 | extent : function(options){ 399 | switch(options.limit.length){ 400 | case 0: 401 | return {start:0, stop:9e+99}; 402 | case 1: 403 | return {start:0, stop:options.limit[0]}; 404 | case 2: 405 | return {start:options.limit[0], stop:options.limit[1]}; 406 | } 407 | } 408 | } 409 | 410 | window.jsonDB = jsonDB; 411 | 412 | //追加扩展功能 413 | jsonDB.fn = jsonDB.prototype =extend(jsonDB.fn,DBExpand); 414 | 415 | //合并对象方法 416 | function extend(){ 417 | var paramsLen = arguments.length; 418 | if(paramsLen<1){ 419 | return false; 420 | } 421 | 422 | var target = arguments[0]; 423 | for(var i=1;i