| 1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101 | 2
2
2
2
2
2
2
9
8
8
8
2
2
2
8
8
8
1
2
219
219
219
13
2
335
313
335
3
335
335
3
332
153
933
712
221
221
221
4
221
221
221
595
590
5
5
5
5
474
219
219
219
474
434
434
8
8
434
224
210
210
210
3
3
207
207
205
205
2
205
211
211
209
209
209
1325
1325
1325
187
187
169
1138
158
209
209
8
6
2
2
2
1
273
157
17
17
16
140
22
15
7
7
7
8
3
5
1
1
5
1
5
5
5
1
5
22
22
19
19
198
36
162
5
162
162
34
5
29
17
34
34
34
9
2
7
7
10
1
9
7
9
9
23
1
22
20
22
2
20
22
6
6
6
329
329
1
328
329
329
329
329
329
8
329
328
1
328
329
329
328
151
151
164
164
164
148
75
16
2
326
3
3
3
21
4
17
326
327
128
128
47
81
6
75
1
128
57
57
57
53
65
65
2
63
47
57
3
4
4
2
2
3
57
57
58
16
15
17
1
1
17
17
17
2
15
15
15
15
15
15
15
15
15
14
14
14
5
2
2
5
5
5
3
3
2
2
22
4
18
1
1
18
18
18
18
14
14
14
14
14
14
14
13
13
13
35
31
36
36
36
2
34
34
34
34
34
34
34
34
34
34
34
9
5
5
4
25
30
30
30
30
7
4
3
3
4
3
19
19
1
18
19
7
7
8
8
6
4
4
4
4
1
3
4
6
29
28
28
28
28
28
28
156
157
157
157
155
155
155
2
2
2
1
2
2
2
9
3
3
9
9
9
9
9
9
9
9
9
9
3
2
3
9
9
1
9
9
9
30
30
30
2
28
24
30
30
30
3
3
3
6
3
19
38
2
36
19
3
27
164
27
1
1
4
1
4
4
4
4
4
4
1
4
4
17
4
13
1
17
17
17
17
17
8
17
2
2
2
1
1
4
1
3
1
3
3
10
1
9
9
2
2
1
1
2
2
2
16
42
42
2
4
4
3
4
2
10
21
21
2
2
8
8
1
2
2
3
1
3
2
4
| var util = require('util');
var querystring = require('querystring');
var Db = thinkRequire('Db');
//数据库实例化对象
var dbInstances = {};
//数据表的字段信息
var tableFieldsCache = {};
/**
* Model类
* @type {[type]}
*/
var Model = module.exports = Class(function(){
'use strict';
//解析page参数
var parsePage = function(options){
if ('page' in options) {
var page = options.page + '';
var num = 0;
if (page.indexOf(',') > -1) {
page = page.split(',');
num = parseInt(page[1], 10);
page = page[0];
}
num = num || C('db_nums_per_page');
page = parseInt(page, 10) || 1;
return {
page: page,
num: num
};
}
return {
page: 1,
num: C('db_nums_per_page')
};
};
/**
* 字符串命名风格转换
* @param {[type]} name [description]
* @param {[type]} type [description]
* @return {[type]} [description]
*/
var parseName = function(name){
name = name.trim();
//首字母如果是大写,不转义为_x
name = name[0].toLowerCase() + name.substr(1);
return name.replace(/[A-Z]/g, function(a){
return '_' + a;
});
};
return {
// 当前数据库操作对象
db: null,
// 主键名称
pk: 'id',
// 数据库配置信息
config: null,
// 配置信息key
configKey: '',
// 模型名称
name: '',
// 数据表前缀
tablePrefix: '',
// 数据表名(不包含表前缀)
tableName: '',
// 实际数据表名(包含表前缀)
trueTableName: '',
// 数据表字段信息
fields: {},
// 数据信息
_data: {},
// 参数
_options: {},
/**
* 初始化
* @access public
* @param string $name 模型名称
* @param mixed config 数据库连接信息
*/
init: function(name, config){
// 获取模型名称
if (name) {
this.name = name;
}
if (isString(config)) {
config = {db_prefix: config};
}
this.config = config || '';
//数据表前缀
if (this.config.db_prefix) {
this.tablePrefix = this.config.db_prefix;
}else if(!this.tablePrefix) {
this.tablePrefix = C('db_prefix');
}
},
/**
* 初始化数据库连接
* @return {[type]} [description]
*/
initDb: function(){
if (this.db) {
return this.db;
}
var config = this.config;
var configKey = md5(JSON.stringify(config));
if (!dbInstances[configKey]) {
dbInstances[configKey] = Db.getInstance(config);
}
this.db = dbInstances[configKey];
this.configKey = configKey;
return this.db;
},
/**
* 获取模型名
* @access public
* @return string
*/
getModelName: function(){
if (this.name) {
return this.name;
}
var filename = this.__filename || __filename;
var last = filename.lastIndexOf('/');
this.name = filename.substr(last + 1, filename.length - last - 9);
return this.name;
},
/**
* 获取表名
* @return {[type]} [description]
*/
getTableName: function(){
if (!this.trueTableName) {
var tableName = this.tablePrefix || '';
tableName += this.tableName || parseName(this.getModelName());
this.trueTableName = tableName.toLowerCase();
}
return this.trueTableName;
},
/**
* 获取数据表信息
* @access protected
* @return Promise
*/
getTableFields: function(table, all){
this.initDb();
if (table === true) {
table = undefined;
all = true;
}
if (!isEmpty(this.fields)) {
return getPromise(all ? this.fields : this.fields._field);
}
var tableName = table || this.getTableName();
var fields = tableFieldsCache[tableName];
if (!isEmpty(fields)) {
this.fields = fields;
return getPromise(all ? fields : fields._field);
}
var self = this;
//从数据表里查询字段信息
return this.flushFields(tableName).then(function(fields){
self.fields = fields;
if (C('db_fields_cache')) {
tableFieldsCache[tableName] = fields;
}
return getPromise(all ? fields : fields._field);
});
},
/**
* 获取数据表信息
* @param {[type]} table [description]
* @return Promise [description]
*/
flushFields: function(table){
table = table || this.getTableName();
return this.initDb().getFields(table).then(function(data){
var fields = {
'_field': Object.keys(data),
'_autoinc': false,
'_unique': []
};
var types = {};
for(var key in data){
var val = data[key];
types[key] = val.type;
if (val.primary) {
fields._pk = key;
if (val.autoinc) {
fields._autoinc = true;
}
}else if (val.unique) {
fields._unique.push(key);
}
}
fields._type = types;
return fields;
})
},
/**
* 根据数据获取类型为唯一的字段
* @return {[type]} [description]
*/
getUniqueField: function(data){
if (!data) {
return this.fields._unique[0];
}
var fields = this.fields._unique;
for(var i = 0, length = fields.length; i < length; i++){
if (data[fields[i]]) {
return fields[i];
}
}
},
/**
* 获取上一次操作的sql
* @return {[type]} [description]
*/
getLastSql: function(){
return this.initDb().getLastSql();
},
/**
* 获取主键名称
* @access public
* @return string
*/
getPk: function(){
//如果fields为空,那么异步去获取
if (isEmpty(this.fields)) {
var self = this;
return this.getTableFields().then(function(){
return self.fields._pk || self.pk;
})
}
return this.fields._pk || this.pk;
},
/**
* 缓存
* @param {[type]} key [description]
* @param {[type]} expire [description]
* @param {[type]} type [description]
* @return {[type]} [description]
*/
cache: function(key, timeout){
if (key === undefined) {
return this;
}
var options = this._getCacheOptions(key, timeout);
this._options.cache = options;
return this;
},
/**
* 获取缓存的选项
* @param {[type]} key [description]
* @param {[type]} timeout [description]
* @return {[type]} [description]
*/
_getCacheOptions: function(key, timeout, type){
if (isObject(key)) {
return key;
}
if (isNumber(key)) {
timeout = key;
key = '';
}
//如果key为true,那么使用sql的md5值
if (key === true) {
key = '';
}
var cacheType = type === undefined ? C('db_cache_type') : type;
var options = {
key: key,
timeout: timeout || C('db_cache_timeout'),
type: cacheType,
gcType: 'dbCache'
}
if (cacheType === 'File') {
options.cache_path = C('db_cache_path');
}
return options;
},
/**
* 指定查询数量
* @param {[type]} offset [description]
* @param {[type]} length [description]
* @return {[type]} [description]
*/
limit: function(offset, length){
this._options.limit = length === undefined ? offset : offset + ',' + length;
return this;
},
/**
* 指定分页
* @return {[type]} [description]
*/
page: function(page, listRows){
this._options.page = listRows === undefined ? page : page + ',' + listRows;
return this;
},
/**
* where条件
* @return {[type]} [description]
*/
where: function(where){
if (!where) {
return this;
}
if (isString(where)) {
where = {_string: where};
}
this._options.where = extend(this._options.where || {}, where);
return this;
},
/**
* 要查询的字段
* @param {[type]} field [description]
* @param {[type]} reverse [description]
* @return {[type]} [description]
*/
field: function(field, reverse){
if (isArray(field)) {
field = field.join(',');
}else if (!field) {
field = '*';
}
this._options.field = field;
this._options.fieldReverse = reverse;
return this;
},
/**
* 设置表名
* @param {[type]} table [description]
* @return {[type]} [description]
*/
table: function(table, hasPrefix){
if (!table) {
return this;
}
this._options.table = hasPrefix ? table : this.tablePrefix + table;
return this;
},
/**
* 联合查询
* @return {[type]} [description]
*/
union: function(union, all){
if (!union) {
return this;
}
if (!this._options.union) {
this._options.union = [];
}
this._options.union.push({
union: union,
all: all
});
return this;
},
/**
* .join({
* 'xxx': {
* join: 'left',
* as: 'c',
* on: ['id', 'cid']
* }
* })
* 联合查询
* @param {[type]} join [description]
* @return {[type]} [description]
*/
join: function(join){
if (!join) {
return this;
}
if (!this._options.join) {
this._options.join = [];
}
if (isArray(join)) {
this._options.join = this._options.join.concat(join);
}else{
this._options.join.push(join);
}
return this;
},
/**
* 生成查询SQL 可用于子查询
* @param {[type]} options [description]
* @return {[type]} [description]
*/
buildSql: function(options){
var self = this;
return this.parseOptions(options).then(function(options){
return '( ' + self.db.buildSelectSql(options).trim() + ' )';
});
},
/**
* 解析参数
* @param {[type]} options [description]
* @return promise [description]
*/
parseOptions: function(oriOpts, extraOptions){
var options;
if (isScalar(oriOpts)) {
options = extend({}, this._options);
}else{
options = extend({}, this._options, oriOpts, extraOptions);
}
//查询过后清空sql表达式组装 避免影响下次查询
this._options = {};
//获取表名
options.table = options.table || this.getTableName();
//表前缀,Db里会使用
options.tablePrefix = this.tablePrefix;
options.model = this.getModelName();
//数据表别名
if (options.alias) {
options.table += ' AS ' + options.alias;
}
var promise = this.getTableFields(options.table).then(function(fields){
if (isScalar(oriOpts)) {
options = extend(options, self.parseWhereOptions(oriOpts), extraOptions);
}
return fields;
})
var self = this;
return promise.then(function(fields){
// 字段类型验证
if (isObject(options.where) && !isEmpty(fields)) {
var keyReg = /[\.\|\&]/;
// 对数组查询条件进行字段类型检查
for(var key in options.where){
var val = options.where[key];
key = key.trim();
if (fields.indexOf(key) > -1) {
if (isScalar(val)) {
options.where[key] = self.parseType(options.where, key)[key];
}
}else if(key[0] !== '_' && !keyReg.test(key)){ //字段名不合法,报错
return getPromise(new Error('field `' + key + '` in where condition is not valid'), true);
}
}
}
//field反选
if (options.field && options.fieldReverse) {
//fieldReverse设置为false
options.fieldReverse = false;
var optionsField = options.field.split(',');
options.field = fields.filter(function(item){
if (optionsField.indexOf(item) > -1) {
return;
}
return item;
}).join(',');
}
return self._optionsFilter(options, fields);
});
},
/**
* 选项过滤器
* 具体的Model类里进行实现
* @param {[type]} options [description]
* @return {[type]} [description]
*/
_optionsFilter: function(options){
return options;
},
/**
* 数据类型检测
* @param {[type]} data [description]
* @param {[type]} key [description]
* @return {[type]} [description]
*/
parseType: function(data, key){
var fieldType = this.fields._type[key] || '';
if (fieldType.indexOf('bigint') === -1 && fieldType.indexOf('int') > -1) {
data[key] = parseInt(data[key], 10) || 0;
}else if(fieldType.indexOf('double') > -1 || fieldType.indexOf('float') > -1){
data[key] = parseFloat(data[key]) || 0.0;
}else if(fieldType.indexOf('bool') > -1){
data[key] = !! data[key];
}
return data;
},
/**
* 对插入到数据库中的数据进行处理,要在parseOptions后执行
* @param {[type]} data [description]
* @return {[type]} [description]
*/
parseData: function(data){
//因为会对data进行修改,所以这里需要深度拷贝
data = extend({}, data);
var key;
if (!isEmpty(this.fields)) {
for(key in data){
var val = data[key];
if (this.fields._field.indexOf(key) === -1) {
delete data[key];
}else if(isScalar(val)){
data = this.parseType(data, key);
}
}
}
//安全过滤
if (isFunction(this._options.filter)) {
for(key in data){
var ret = this._options.filter.call(this, key, data[key]);
if (ret === undefined) {
delete data[key];
}else{
data[key] = ret;
}
}
delete this._options.filter;
}
data = this._dataFilter(data);
return data;
},
/**
* 数据过滤器
* 具体的Model类里进行实现
* @param {[type]} data [description]
* @return {[type]} [description]
*/
_dataFilter: function(data){
return data;
},
/**
* 数据插入之前操作,可以返回一个promise
* @param {[type]} data [description]
* @param {[type]} options [description]
* @return {[type]} [description]
*/
_beforeAdd: function(data){
return data;
},
/**
* 数据插入之后操作,可以返回一个promise
* @param {[type]} data [description]
* @param {[type]} options [description]
* @return {[type]} [description]
*/
_afterAdd: function(data){
return data;
},
/**
* 添加一条数据
* @param {[type]} data [description]
* @param {[type]} options [description]
* @param int 返回插入的id
*/
add: function(data, options, replace){
if (options === true) {
replace = true;
options = {};
}
//copy data
data = extend({}, this._data, data);
this._data = {};
if (isEmpty(data)) {
return getPromise(new Error('_DATA_TYPE_INVALID_'), true);
}
var self = this;
//解析后的选项
var parsedOptions = {};
//解析后的数据
var parsedData = {};
return this.parseOptions(options).then(function(options){
parsedOptions = options;
return self._beforeAdd(data, parsedOptions);
}).then(function(data){
parsedData = data;
data = self.parseData(data);
return self.db.insert(data, parsedOptions, replace);
}).then(function(){
parsedData[self.getPk()] = self.db.getLastInsertId();
return self._afterAdd(parsedData, parsedOptions);
}).then(function(){
return parsedData[self.getPk()];
});
},
/**
* 如果当前条件的数据不存在,才添加
* @param {[type]} data 要插入的数据
* @param {[type]} where where条件
* @param boolean returnType 返回值是否包含type
* @return {[type]} promise
*/
thenAdd: function(data, where, returnType){
if (where === true) {
returnType = true;
where = '';
}
var self = this;
return this.where(where).find().then(function(findData){
if (!isEmpty(findData)) {
var idValue = findData[self.getPk()];
return returnType ? {id: idValue, type: 'exist'} : idValue;
}
return self.add(data).then(function(insertId){
return returnType ? {id: insertId, type: 'add'} : insertId;
});
});
},
/**
* 插入多条数据
* @param {[type]} data [description]
* @param {[type]} options [description]
* @param {[type]} replace [description]
*/
addAll: function(data, options, replace){
if (!isArray(data) || !isObject(data[0])) {
return getPromise(new Error('_DATA_TYPE_INVALID_'), true);
}
if (options === true) {
replace = true;
options = {};
}
var self = this;
return this.parseOptions(options).then(function(options){
return self.db.insertAll(data, options, replace);
}).then(function(){
return self.db.getLastInsertId();
});
},
/**
* 删除后续操作
* @return {[type]} [description]
*/
_afterDelete: function(data){
return data;
},
/**
* 删除数据
* @return {[type]} [description]
*/
delete: function(options){
var self = this;
var parsedOptions = {};
var affectedRows = 0;
return this.parseOptions(options).then(function(options){
parsedOptions = options;
return self.db.delete(options);
}).then(function(rows){
affectedRows = rows;
return self._afterDelete(parsedOptions.where || {}, parsedOptions);
}).then(function(){
return affectedRows;
})
},
/**
* 更新前置操作
* @param {[type]} data [description]
* @param {[type]} options [description]
* @return {[type]} [description]
*/
_beforeUpdate: function(data){
return data;
},
/**
* 更新后置操作
* @param {[type]} data [description]
* @param {[type]} options [description]
* @return {[type]} [description]
*/
_afterUpdate: function(data){
return data;
},
/**
* 更新数据
* @return {[type]} [description]
*/
update: function(data, options){
data = extend({}, this._data, data);
this._data = {};
if (isEmpty(data)) {
return getPromise(new Error('_DATA_TYPE_INVALID_'), true);
}
var self = this;
var parsedOptions = {};
var parsedData = {};
var affectedRows = 0;
return this.parseOptions(options).then(function(options){
parsedOptions = options;
return self._beforeUpdate(data, options);
}).then(function(data){
var pk = self.getPk();
parsedData = data;
data = self.parseData(data);
if (isEmpty(parsedOptions.where)) {
// 如果存在主键数据 则自动作为更新条件
if (!isEmpty(data[pk])) {
parsedOptions.where = getObject(pk, data[pk]);
delete data[pk];
}else{
return getPromise(new Error('_OPERATION_WRONG_'), true);
}
}else{
parsedData[pk] = parsedOptions.where[pk];
}
return self.db.update(data, parsedOptions);
}).then(function(rows){
affectedRows = rows;
return self._afterUpdate(parsedData, parsedOptions);
}).then(function(){
return affectedRows;
});
},
/**
* 更新多个数据,自动用主键作为查询条件
* @param {[type]} dataList [description]
* @return {[type]} [description]
*/
updateAll: function(dataList){
if (!isArray(dataList) || !isObject(dataList[0])) {
return getPromise(new Error('_DATA_TYPE_INVALID_'), true);
}
var self = this;
var promises = dataList.map(function(data){
return self.update(data);
});
return Promise.all(promises);
},
/**
* 更新某个字段的值
* @param {[type]} field [description]
* @param {[type]} value [description]
* @return {[type]} [description]
*/
updateField: function(field, value){
var data = {};
if (isObject(field)) {
data = field;
}else{
data[field] = value;
}
return this.update(data);
},
/**
* 字段值增长
* @return {[type]} [description]
*/
updateInc: function(field, step){
step = parseInt(step, 10) || 1;
return this.updateField(field, ['exp', field + '+' + step]);
},
/**
* 字段值减少
* @return {[type]} [description]
*/
updateDec: function(field, step){
step = parseInt(step, 10) || 1;
return this.updateField(field, ['exp', field + '-' + step]);
},
/**
* 解析options中简洁的where条件
* @return {[type]} [description]
*/
parseWhereOptions: function(options){
if (isNumber(options) || isString(options)) {
var pk = this.getPk();
options += '';
var where = {};
if (options.indexOf(',') > -1) {
where[pk] = ['IN', options];
}else{
where[pk] = options;
}
options = {
where: where
};
}
return options || {};
},
/**
* find查询后置操作
* @return {[type]} [description]
*/
_afterFind: function(result){
return result;
},
/**
* 查询一条数据
* @return 返回一个promise
*/
find: function(options){
var self = this;
var parsedOptions = {};
return this.parseOptions(options, {limit: 1}).then(function(options){
parsedOptions = options;
return self.db.select(options);
}).then(function(data){
return self._afterFind(data[0] || {}, parsedOptions);
});
},
/**
* 查询后置操作
* @param {[type]} result [description]
* @param {[type]} options [description]
* @return {[type]} [description]
*/
_afterSelect: function(result){
return result;
},
/**
* 查询数据
* @return 返回一个promise
*/
select: function(options){
var self = this;
var parsedOptions = {};
return this.parseOptions(options).then(function(options){
parsedOptions = options;
return self.db.select(options);
}).then(function(result){
return self._afterSelect(result, parsedOptions);
});
},
/**
* 查询添加
* @param {[type]} options [description]
* @return {[type]} [description]
*/
selectAdd: function(options){
var self = this;
var promise = getPromise(options);
if (options instanceof Model) {
promise = options.parseOptions();
}
return Promise.all([this.parseOptions(), promise]).then(function(data){
var fields = data[0].field || self.fields._field;
return self.db.selectAdd(fields, data[0].table, data[1]);
});
},
/**
* 返回数据里含有count信息的查询
* @param options 查询选项
* @param pageFlag 当页面不合法时的处理方式,true为获取第一页,false为获取最后一页,undefined获取为空
* @return promise
*/
countSelect: function(options, pageFlag){
if (isBoolean(options)) {
pageFlag = options;
options = {};
}
var self = this;
//解析后的options
var parsedOptions = {};
var result = {};
return this.parseOptions(options).then(function(options){
delete options.table;
parsedOptions = options;
return self.options({
where: options.where,
cache: options.cache,
join: options.join,
alias: options.alias
}).count((options.alias || self.getTableName()) + '.' + self.getPk());
}).then(function(count){
var pageOptions = parsePage(parsedOptions);
var totalPage = Math.ceil(count / pageOptions.num);
if (isBoolean(pageFlag)) {
if (pageOptions.page > totalPage) {
pageOptions.page = pageFlag === true ? 1 : totalPage;
}
parsedOptions.page = pageOptions.page + ',' + pageOptions.num;
}
result = extend({count: count, total: totalPage}, pageOptions);
if (!parsedOptions.page) {
parsedOptions.page = pageOptions.page;
}
return self.select(parsedOptions);
}).then(function(data){
result.data = data;
return result;
});
},
/**
* 获取某个字段下的记录
* @return {[type]} [description]
*/
getField: function(field, one){
var self = this;
return this.parseOptions({'field': field}).then(function(options){
if (isNumber(one)) {
options.limit = one;
}else if (one === true) {
options.limit = 1;
}
return self.db.select(options);
}).then(function(data){
var multi = field.indexOf(',') > -1;
if (multi) {
var fields = field.split(/\s*,\s*/);
var result = {};
fields.forEach(function(item){
result[item] = [];
})
data.every(function(item){
fields.forEach(function(fItem){
if (one === true) {
result[fItem] = item[fItem];
}else{
result[fItem].push(item[fItem]);
}
})
return one !== true;
})
return result;
}else{
data = data.map(function(item){
return Object.values(item)[0];
})
return one === true ? data[0] : data;
}
});
},
/**
* 根据某个字段值获取一条数据
* @param {[type]} name [description]
* @param {[type]} value [description]
* @return {[type]} [description]
*/
getBy: function(name, value){
var where = getObject(name, value);
return this.where(where).find();
},
/**
* SQL查询
* @return {[type]} [description]
*/
query: function(sql, parse){
if (parse !== undefined && !isBoolean(parse) && !isArray(parse)) {
parse = [].slice.call(arguments, 1);
}
var self = this;
sql = this.parseSql(sql, parse);
return this.initDb().select(sql, this._options.cache).then(function(data){
self._options = {};
return data;
});
},
/**
* 执行SQL语法,非查询类的SQL语句,返回值为影响的行数
* @param {[type]} sql [description]
* @param {[type]} parse [description]
* @return {[type]} [description]
*/
execute: function(sql, parse){
if (parse !== undefined && !isBoolean(parse) && !isArray(parse)) {
parse = [].slice.call(arguments, 1);
}
sql = this.parseSql(sql, parse);
return this.initDb().execute(sql);
},
/**
* 解析SQL语句
* @return promise [description]
*/
parseSql: function(sql, parse){
if (parse === undefined) {
parse = [];
}else if(!isArray(parse)){
parse = [parse];
}
parse.unshift(sql);
sql = util.format.apply(null, parse);
var map = {
'__TABLE__': '`' + this.getTableName() + '`'
};
var self = this;
sql = sql.replace(/__([A-Z]+)__/g, function(a, b){
return map[a] || ('`' + self.tablePrefix + b.toLowerCase() + '`');
});
return sql;
},
/**
* 启动事务
* @return {[type]} [description]
*/
startTrans: function(){
var self = this;
return this.initDb().commit().then(function(){
return self.db.startTrans();
});
},
/**
* 提交事务
* @return {[type]} [description]
*/
commit: function(){
return this.initDb().commit();
},
/**
* 回滚事务
* @return {[type]} [description]
*/
rollback: function(){
return this.initDb().rollback();
},
/**
* 设置数据对象值
* @return {[type]} [description]
*/
data: function(data){
if (data === true) {
return this._data;
}
if (isString(data)) {
data = querystring.parse(data);
}
this._data = data;
return this;
},
/**
* 设置操作选项
* @param {[type]} options [description]
* @return {[type]} [description]
*/
options: function(options){
if (options === true) {
return this._options;
}
this._options = options;
return this;
},
/**
* 关闭数据库连接
* @return {[type]} [description]
*/
close: function(){
delete dbInstances[this.configKey];
if (this.db) {
this.db.close();
this.db = null;
}
}
};
}).extend(function(){
'use strict';
//追加的方法
var methods = {};
// 链操作方法列表
var methodNameList = [
'order','alias','having','group',
'lock','auto','filter','validate'
];
methodNameList.forEach(function(item){
methods[item] = function(data){
this._options[item] = data;
return this;
};
});
methods.distinct = function(data){
this._options.distinct = data;
//如果传过来一个字段,则映射到field上
if (isString(data)) {
this._options.field = data;
}
return this;
};
['count','sum','min','max','avg'].forEach(function(item){
methods[item] = function(field){
field = field || this.pk;
return this.getField(item.toUpperCase() + '(' + field + ') AS thinkjs_' + item, true);
};
});
//方法别名
var aliasMethodMap = {
update: 'save',
updateField: 'setField',
updateInc: 'setInc',
updateDec: 'setDec'
};
Object.keys(aliasMethodMap).forEach(function(key){
var value = aliasMethodMap[key];
methods[value] = function(){
return this[key].apply(this, arguments);
};
});
return methods;
});
/**
* 关闭所有的数据库连接
* @return {[type]} [description]
*/
Model.close = function(){
'use strict';
for(var key in dbInstances) {
dbInstances[key].close();
}
dbInstances = {};
};
/**
* 清除数据表字段缓存
* @return {[type]} [description]
*/
Model.clearTableFieldsCache = function(){
'use strict';
tableFieldsCache = {};
} |