-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathDBView.js
More file actions
1042 lines (820 loc) · 30.4 KB
/
DBView.js
File metadata and controls
1042 lines (820 loc) · 30.4 KB
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
if(!javaxt) var javaxt={};
if(!javaxt.express) javaxt.express={};
//******************************************************************************
//** DBView
//******************************************************************************
/**
* Component used to compile queries and view results in a table. The
* component consists of three elements: a list of tables on the left, a
* query editor in the center, and a table/grid on the bottom (below the
* editor). Queries are executed on the server via REST web services. The
* queries are queued by the server and executed asynchronously. The server
* provides web methods to submit jobs, check job status, and pick up
* completed jobs. See the javaxt.express.services.QueryService class for
* more information.
*
******************************************************************************/
javaxt.express.DBView = function(parent, config) {
this.className = "javaxt.express.DBView";
var me = this;
var defaultConfig = {
/** If the CodeMirror library is available, it will be used as the query
* editor (vs default textarea). You can specify a coding language to
* use with CodeMirror (e.g. sql, cypher, etc). Default is sql.
*/
queryLanguage: "sql",
/** Path to REST endpoint used to create, get, and delete query jobs.
* This path may be overridden via the createJob, getJob, and cancelJob
* config.
*/
queryService: "sql/job/",
/** Path to REST endpoint that returns a list of tables. Alternatively,
* you can provide a function with a callback.
*/
getTables: "sql/tables/",
/** Path to REST endpoint used to create a query job. Alternatively, you
* can provide a function that executes a "POST" request.
*/
createJob: "sql/job/",
/** Path to REST endpoint used to delete/cancel a query job. Note that
* the "{jobID}" will be replaced with an actual id. Alternatively, you
* can provide a function that executes a "DELETE" request. The function
* should return an XHR request.
*/
cancelJob: "sql/job/{jobID}",
/** Path to REST endpoint that returns results of a query job. Note that
* the "{jobID}" will be replaced with an actual id. Alternatively, you
* can provide a function that executes a "GET" request. The function
* should return an XHR request.
*/
getJob: "sql/job/{jobID}",
/** Used to specify the page size (i.e. the maximum number records to
* fetch from the server at a time)
*/
pageSize: 50,
/** Used to specify the response format for the query results. Options
* include "json", "csv", "tsv, and "jsv"
*/
format: "json",
/** Style for individual elements within the component. Note that you can
* provide CSS class names instead of individual style definitions.
*/
style:{
container: {
width: "100%",
height: "100%"
},
border: "1px solid #383b41",
leftPanel: {
backgroundColor: "#272a31",
borderRight: "1px solid #383b41",
color: "#bfc0c3"
},
rightPanel: {
},
bottomPanel: {
backgroundColor: "#e4e4e4",
borderTop: "1px solid #b5b5b5"
/*
fontFamily: '"Consolas", "Bitstream Vera Sans Mono", "Courier New", Courier, monospace';
color: "#97989c";
*/
},
toolbar: "panel-toolbar",
toolbarButton: {}, //javaxt.dhtml.style.default.toolbarButton
toolbarIcons: {
run: "run-icon",
cancel: "stop-icon"
},
editor: {
height: "240px",
fontFamily: '"Consolas", "Bitstream Vera Sans Mono", "Courier New", Courier, monospace'
},
table: {}, //javaxt.dhtml.style.default.table
tree: {
padding: "7px 0 7px 0px",
backgroundColor: "",
li: "tree-node"
},
error: {
fontFamily: '"Consolas", "Bitstream Vera Sans Mono", "Courier New", Courier, monospace',
color: "#6c6c6c",
padding: "10px"
}
},
/** By default, when a user clicks on a node in the tree, the query editor
* is updated with a default query statement for the node. You can update
* this default behaviour by providing a custom function.
*/
onTreeClick: function(item){
var tableName = item.name;
if (item.node){
var schema = item.node.schema;
if (schema && schema!=="public"){
tableName = schema + "." + tableName;
}
}
editor.setValue("select * from " + tableName);
}
};
var tree, toolbar, editor, grid, gridContainer, waitmask;
var runButton, cancelButton;
var jobID;
var border;
//**************************************************************************
//** Constructor
//**************************************************************************
var init = function(){
if (typeof parent === "string"){
parent = document.getElementById(parent);
}
if (!parent) return;
//Clone the config so we don't modify the original config object
config = clone(config);
//Merge clone with default config
config = merge(config, defaultConfig);
//Get waitmask
waitmask = config.waitmask;
border = config.border;
//Create main div
var div = createElement('div', parent, config.style.container);
div.classList.add('javaxt-db-view');
me.el = div;
addShowHide(me);
//Create table with 2 columns
var table = createTable(div);
var tr = table.addRow();
//Left column
var td = tr.addColumn(config.style.leftPanel);
td.style.height = "100%";
var target = createTableView(td);
//Right column
var td = tr.addColumn(config.style.rightPanel);
td.style.width = "100%";
td.style.height = "100%";
var hr = addHorizontalResizer(td, target);
createQueryView(hr);
onRender(me.el, function(){
if (waitmask) waitmask.show(500);
var getTables = config.getTables;
if (typeof getTables === "string"){
get(getTables, {
success: function(text){
if (waitmask) waitmask.hide();
//Parse response
var tables = JSON.parse(text).tables;
//Add nodes to the tree
tree.addNodes(tables);
},
failure: function(request){
if (waitmask) waitmask.hide();
alert(request);
}
});
}
else if (typeof getTables === "function") {
getTables.apply(me, [tree]);
}
});
};
//**************************************************************************
//** setQuery
//**************************************************************************
/** Used to update the query in the query editor. Will clear records in the
* table from any previous query.
*/
this.setQuery = function(query){
if (query){
if (query===editor.getValue()){
//Do nothing
}
else{
editor.setValue(query);
me.clearResults();
}
}
else{
me.clear();
}
};
//**************************************************************************
//** getQuery
//**************************************************************************
/** Returns text from the query editor
*/
this.getQuery = function(){
return editor.getValue();
};
//**************************************************************************
//** executeQuery
//**************************************************************************
/** Used to execute a query by submitting whatever is in the query editor to
* the server. Note that there is no client-side validation.
*/
this.executeQuery = function(){
//Cancel current query (if running)
cancel();
//Show waitmask
if (waitmask) waitmask.show(500);
//Clear current grid
me.clearResults();
grid = null;
//Set parameters for the query service
var payload = {
query: editor.getValue(),
limit: config.pageSize,
format: config.format
};
//Execute query and render results
getResponse(payload, function(request){
cancelButton.disable();
var data = parseResponse(request.responseText);
render(data.records, data.columns);
if (waitmask) waitmask.hide();
});
};
//**************************************************************************
//** clear
//**************************************************************************
/** Used to remove text from the query editor and clear the results table.
*/
this.clear = function(){
editor.setValue("");
me.clearResults();
};
//**************************************************************************
//** clearResults
//**************************************************************************
/** Used to clear the results table.
*/
this.clearResults = function(){
if (grid){
try{
grid.clear();
destroy(grid);
}
catch(e){}
}
gridContainer.innerHTML = "";
};
//**************************************************************************
//** getComponents
//**************************************************************************
/** Returns a json object with individual components that make up this
* component.
* <ul>
* <li>tree: javaxt.dhtml.Tree used to render table names</li>
* <li>grid: javaxt.dhtml.DataGrid used to render query results</li>
* <li>editor: the component used edit queries</li>
* <li>toolbar: DOM object (table) with buttons</li>
* </ul>
*/
this.getComponents = function(){
return {
tree: tree,
grid: grid,
editor: editor,
toolbar: toolbar
};
};
//**************************************************************************
//** createTableView
//**************************************************************************
/** Creates a panel used to render a list of tables in the database. Tables
* are rendered in a tree view.
*/
var createTableView = function(parent){
var outerDiv = createElement("div", parent, {
position: "relative",
height: "100%",
width: "210px",
overflow: "auto"
});
var div = createElement("div", outerDiv, {
position: "absolute",
width: "100%"
});
//Create tree
tree = new javaxt.dhtml.Tree(div, {
style: config.style.tree
});
tree.onClick = function(item){
config.onTreeClick.apply(me, [item]);
};
return outerDiv;
};
//**************************************************************************
//** createQueryView
//**************************************************************************
var createQueryView = function(parent){
//Create panel
var panel = new javaxt.dhtml.Panel(parent, {
style: {
toolbar: config.style.toolbar
}
});
//Create toolbar
toolbar = panel.getToolbar();
addButtons(toolbar);
//Create editor
var table = createTable(panel.getBody());
var td = table.addRow().addColumn(config.style.editor);
td.style.borderBottom = border;
var target = td;
if (typeof CodeMirror !== 'undefined'){
var outerDiv = createElement("div", td, {
height: "100%",
position: "relative"
});
var innerDiv = createElement("div", outerDiv, {
width: "100%",
height: "100%",
position: "absolute",
overflow: "hidden",
overflowX: "auto"
});
editor = CodeMirror(innerDiv, {
value: "",
mode: config.queryLanguage,
lineNumbers: true,
indentUnit: 4
});
td.childNodes[0].style.height = "100%";
editor.setValue = function(str){
var doc = this.getDoc();
doc.setValue(str);
doc.clearHistory();
var cm = this;
setTimeout(function() {
cm.refresh();
},200);
};
editor.getValue = function(){
return this.getDoc().getValue();
};
}
else{
editor = createElement('textarea', td, {
width: "100%",
height: "100%",
resize: "none",
border: "0 none",
padding: "10px",
boxSizing: "border-box", //this is critical if you want padding
fontFamily: "inherit",
fontSize: "inherit"
});
editor.spellcheck = false;
editor.getValue = function(){
return this.value;
};
editor.setValue = function(str){
this.value = str;
};
}
//Create results table
td = table.addRow().addColumn(config.style.bottomPanel);
td.style.height = "100%";
td.style.verticalAlign = "top";
//Add vertical resizer
addVerticalResizer(td, target);
//Add div for the grid
gridContainer = createElement("div", td, {
height: "100%"
});
};
//**************************************************************************
//** addVerticalResizer
//**************************************************************************
/** Inserts a resize handle into the parent. Assumes target is above the
* parent.
*/
var addVerticalResizer = function(parent, target){
var div = createElement("div", parent, {
position: "relative"
});
var resizeHandle = createElement("div", div, {
position: "absolute",
width: "100%",
height: "10px",
top: "-5px",
cursor: "ns-resize",
zIndex: 2
});
javaxt.dhtml.utils.initDrag(resizeHandle, {
onDragStart: function(x,y){
var div = this;
div.yOffset = y;
div.initialHeight = target.offsetHeight;
},
onDrag: function(x,y){
var div = this;
var top = (div.yOffset-y);
var height = div.initialHeight-top;
target.style.height = height + "px";
},
onDragEnd: function(){
}
});
};
//**************************************************************************
//** addHorizontalResizer
//**************************************************************************
/** Inserts a resize handle into the parent. Assumes target is to the left
* of the parent parent.
*/
var addHorizontalResizer = function(parent, target){
var div = createElement("div", parent, {
position: "relative",
height: "100%"
});
var resizeHandle = createElement("div", div, {
position: "absolute",
height: "100%",
width: "10px",
left: "-5px",
cursor: "ew-resize",
zIndex: 2
});
javaxt.dhtml.utils.initDrag(resizeHandle, {
onDragStart: function(x,y){
var div = this;
div.xOffset = x;
div.initialWidth = target.offsetWidth;
},
onDrag: function(x,y){
var div = this;
var left = (div.xOffset-x);
var width = div.initialWidth-left;
target.style.width = width + "px";
},
onDragEnd: function(){
}
});
return div;
};
//**************************************************************************
//** addButtons
//**************************************************************************
/** Adds buttons to the toolbar
*/
var addButtons = function(toolbar){
//Add button
runButton = createButton(toolbar, {
label: "Run",
//menu: true,
icon: config.style.toolbarIcons.run,
disabled: false
});
runButton.onClick = function(){
me.executeQuery();
};
//Cancel button
cancelButton = createButton(toolbar, {
label: "Cancel",
icon: config.style.toolbarIcons.cancel,
disabled: true
});
cancelButton.onClick = function(){
cancel(function(){
if (waitmask) waitmask.hide();
});
};
};
//**************************************************************************
//** cancel
//**************************************************************************
/** Used to cancel the current query
*/
var cancel = function(callback){
if (jobID){
var request;
var requestConfig = {
success : function(){
cancelButton.disable();
if (callback) callback.apply(null,[]);
},
failure: function(request){
cancelButton.disable();
if (callback) callback.apply(null,[]);
if (request.status!==404){
showError(request);
}
}
};
var cancelJob = config.cancelJob;
if (!cancelJob) cancelJob = config.queryService + jobID;
if (typeof cancelJob === "string"){
var url = cancelJob.replace("{jobID}",jobID);
request = javaxt.dhtml.utils.delete(url, requestConfig);
}
else if (typeof cancelJob === "function") {
request = cancelJob.apply(me, [jobID, requestConfig]);
}
}
else{
if (callback) callback.apply(null,[]);
}
jobID = null;
};
//**************************************************************************
//** showError
//**************************************************************************
/** Used to render error messages returned from the server
*/
var showError = function(msg){
cancelButton.disable();
//Update message
if (msg && msg.responseText){
msg = (msg.responseText.length>0 ? msg.responseText : msg.statusText);
}
if (msg) msg = msg.replaceAll("\n","<br>");
//Populate the bottom panel
gridContainer.innerHTML = "";
var outerDiv = createElement("div", gridContainer, {
width: "100%",
height: "100%",
position: "relative",
overflow: "auto"
});
var innerDiv = createElement("div", outerDiv, {
width: "100%",
height: "100%",
position: "absolute"
});
var div = createElement("div", innerDiv, config.style.error);
div.innerHTML = msg;
//Hide waitmask
if (waitmask) waitmask.hide();
};
//**************************************************************************
//** getResponse
//**************************************************************************
/** Used to execute a sql api request and get a response. Note that queries
* are executed asynchronously. This method will pool the sql api until
* the query is complete.
*/
var getResponse = function(payload, callback){
var requestConfig = {
success : function(text){
jobID = JSON.parse(text).job_id;
cancelButton.enable();
//Periodically check job status
var timer;
var checkStatus = function(){
if (jobID){
var request;
var requestConfig = {
success : function(text){
if (text==="pending" || text==="running"){
timer = setTimeout(checkStatus, 250);
}
else{
clearTimeout(timer);
callback.apply(me, [request]);
}
},
failure: function(response){
clearTimeout(timer);
showError(response);
}
};
var getJob = config.getJob;
if (!getJob) getJob = config.queryService + jobID;
if (typeof getJob === "string"){
var url = getJob.replace("{jobID}",jobID);
request = get(url, requestConfig);
}
else if (typeof getJob === "function") {
request = getJob.apply(me, [jobID, requestConfig]);
}
}
else{
clearTimeout(timer);
}
};
timer = setTimeout(checkStatus, 250);
},
failure: function(response){
//mainMask.hide();
showError(response);
}
};
var createJob = config.createJob;
if (!createJob) createJob = config.queryService;
if (typeof createJob === "string"){
post(createJob, JSON.stringify(payload), requestConfig);
}
else if (typeof createJob === "function") {
createJob.apply(me, [payload, requestConfig]);
}
};
//**************************************************************************
//** parseResponse
//**************************************************************************
/** Used to parse the query response from the sql api
*/
var parseResponse = function(obj){
var records = [];
var columns = [];
if (javaxt.dhtml.utils.isString(obj)){
var s = obj.substring(0,1);
if (s=="{" || s=="["){
obj = JSON.parse(obj);
}
}
if (obj.cols && obj.rows){ //standard response from javaxt-express QueryService (aka jsv format)
records = obj.rows;
columns = obj.cols;
}
else{
if (config.format==="json"){
if (obj.rows){ //response from javaxt-express QueryService
var rows = obj.rows;
//Generate list of columns
var record = rows[0];
for (var key in record) {
if (record.hasOwnProperty(key)) {
columns.push(key);
}
}
//Generate records
for (var i=0; i<rows.length; i++){
var record = [];
var row = rows[i];
for (var j=0; j<columns.length; j++){
var key = columns[j];
var val = row[key];
record.push(val);
}
records.push(record);
}
}
}
else{
//csv or tsv?
}
}
return {
columns: columns,
records: records
};
};
//**************************************************************************
//** render
//**************************************************************************
/** Used to render query results in a grid
*/
var render = function(records, columns){
if (!columns || columns.length===0){
showError("No records");
return;
}
//mainMask.hide();
//Create divs
var outerDiv = createElement("div", gridContainer, {
position: "relative",
height: "100%"
});
var innerDiv = createElement("div", outerDiv, {
position: "absolute",
width: "100%",
height: "100%",
overflow: "hidden",
overflowX: "auto"
});
var overflowDiv = createElement("div", innerDiv, {
position: "absolute",
width: "100%",
height: "100%"
});
//Create grid after the divs are rendered
onRender(innerDiv, function(){
var rect = javaxt.dhtml.utils.getRect(innerDiv);
//Compute column widths
var widths = [];
var minWidths = [];
var headerWidth = 0;
var pixelsPerChar = 10;
if (columns.length>1){
var arr = [];
arr.push(columns);
arr.push(...records);
var o = getSuggestedColumnWidths(arr, pixelsPerChar, rect.width);
widths = o.suggestedWidths;
headerWidth = o.headerWidth;
for (var i=0; i<columns.length; i++){
var minWidth = columns[i].length*pixelsPerChar;
if (minWidth<150) minWidth = 150;
minWidths.push(minWidth);
}
}
else{
widths.push("100%");
minWidths.push(null);
}
//Generate column definitions
var arr = [];
for (var i=0; i<columns.length; i++){
arr.push({
header: columns[i],
width: widths[i],
minWidth: minWidths[i],
sortable: false
});
}
//Adjust width of the overflowDiv as needed
if (rect.width<headerWidth){
overflowDiv.style.width = headerWidth + "px";
}
//Create grid
grid = new javaxt.dhtml.DataGrid(overflowDiv, {
columns: arr,
style: config.style.table,
url: config.queryService,
limit: config.pageSize,
getResponse: function(url, payload, callback){
payload = {
query: editor.getValue(),
page: grid.getCurrPage(),
limit: config.pageSize,
format: config.format
};
getResponse(payload, callback);
},
parseResponse: function(request){
return parseResponse(request.responseText).records;
},
update: function(row, record){
for (var i=0; i<record.length; i++){
var val = record[i];
if (val === null || val === undefined){
val = "";
}
else{
if (val.constructor === arrayConstructor ||
val.constructor === objectConstructor) {
val = JSON.stringify(val);
}
}
row.set(i, val);
}
}
});
grid.beforeLoad = function(page){
//mainMask.show();
//cancelButton.disable();
};
grid.afterLoad = function(){
//mainMask.hide();
cancelButton.disable();
};
grid.onSelectionChange = function(){
};
grid.getColumns = function(){
return columns;
};
grid.getConfig = function(){
return {
columns: arr
};
};
grid.load(records, 1);
});
};
//**************************************************************************
//** createButton
//**************************************************************************