Builder/Provider/Database/generate.js
[app.Builder.js] / Builder / Provider / Database / generate.js
1 //<script type="text/javascript">
2
3 /**
4  * 
5  * Let's see if libgda can be used to generate our Readers for roo...
6  * 
7  * Concept - conect to database..
8  * 
9  * list tables
10  * 
11  * extra schemas..
12  * 
13  * write readers..
14  * 
15  * usage: seed generate.js 
16  * 
17  */
18 Gda  = imports.gi.Gda;
19 GObject = imports.gi.GObject;
20
21 GLib = imports.gi.GLib;
22
23 console = imports['../../../console.js'];
24 File = imports['../../../File.js'].File;
25 Gda.init();
26
27 var prov = Gda.Config.list_providers ();
28 //print(prov.dump_as_string());
29 var args = Array.prototype.slice.call(Seed.argv);
30 args.shift();args.shift();// remove first 2
31 print(args.length );
32 if (args.length < 1) {
33     var sample = {
34         DB_NAME : "XXX",
35         USERNAME : "YYY",
36         PASSWORD: "ZZZ",
37         INI : "/path/to/mydb.ini",
38     }
39     print("Usage : seed generate.js  '" + JSON.stringify(sample) +"'");
40     Seed.quit();
41 }
42 var cfg = JSON.parse(args[0]);
43
44 var   cnc = Gda.Connection.open_from_string ("MySQL", "DB_NAME=" + cfg.DB_NAME, 
45                                               "USERNAME=" + cfg.USERNAME + ';PASSWORD=' + cfg.PASSWORD,
46                                               Gda.ConnectionOptions.NONE, null);
47
48
49
50                                               
51
52  
53 Gda.DataSelect.prototype.fetchAll = function()
54 {
55     var cols = [];
56     
57     for (var i =0;i < this.get_n_columns(); i++) {
58         cols.push(this.get_column_name(i));
59     }
60     //console.dump(cols);
61     var iter = this.create_iter();
62     var res = [];
63     while (iter.move_next()) {
64         if (cols.length == 1) {
65             res.push(iter.get_value_at(0).get_string());
66             continue;
67         }
68         var add = { };
69         
70         cols.forEach(function(n,i) {
71            var val = iter.get_value_at(i);
72            var type = GObject.type_name(val.g_type) ;
73            var vs = type == 'GdaBlob' ? val.value.to_string(1024) : val.value;
74          //  print(n + " : TYPE: " + GObject.type_name(val.g_type) + " : " + vs);
75             //print (n + '=' + iter.get_value_at(i).value);
76             add[n] = vs;
77         });
78         
79         res.push(add);
80         
81     }
82     return res;
83
84 }
85
86 var map = {
87     'date' : 'date',
88     'datetime' : 'string',
89     'int' : 'int',
90     'bigint' : 'int',
91     'char' : 'int',
92     'tinyint' : 'int',
93     'decimal' : 'float',
94     'float' : 'float',
95     'varchar' : 'string',
96     'text' : 'string',
97     'longtext' : 'string',
98     'mediumtext' : 'string',
99     'enum' : 'string',
100     
101     
102 }
103
104 var ini = { }
105
106 function readIni(fn)
107 {
108     var key_file = GLib.key_file_new();
109     if (!GLib.key_file_load_from_file (key_file, fn , GLib.KeyFileFlags.NONE )) {
110         return;
111     }
112    
113     var groups = GLib.key_file_get_groups(key_file);
114     groups.forEach(function(g) {
115         ini[g] = {}
116            
117         var keys = GLib.key_file_get_keys(key_file,g);
118         keys.forEach(function(k) {
119             ini[g][k] = GLib.key_file_get_value(key_file,g,k);
120         })
121     })
122     
123 }
124 if (File.isFile(cfg.INI)) {
125     if (cfg.INI.match(/links\.ini$/)) {
126         readIni(cfg.INI);
127     } else {
128         readIni(cfg.INI.replace(/\.ini$/, ".links.ini"));
129     }
130 }
131
132 if (File.isDirectory(cfg.INI)) {
133         
134
135     //--- load ini files..
136     // this is very specific.
137     var dirs = File.list( GLib.get_home_dir() + '/gitlive').filter( 
138         function(e) { return e.match(/^Pman/); }
139     );
140     
141     dirs.forEach(function(d) {
142         // this currently misses the web.*/Pman/XXXX/DataObjects..
143         var path = GLib.get_home_dir() + '/gitlive/' + d + '/DataObjects';
144         if (!File.isDirectory(path)) {
145             path = GLib.get_home_dir() + '/gitlive/' + d + '/Pman/DataObjects';
146         }
147         if (!File.isDirectory(path)) {
148             return; //skip
149         }
150         var inis = File.list(path).filter(
151             function(e) { return e.match(/\.links\.ini$/); }
152         );
153         if (!inis.length) {
154             return;
155         }
156         
157         inis.forEach(function(i) {
158             readIni(path + '/' + i); 
159             
160         })
161
162         
163         
164     });
165 }
166 print(JSON.stringify(ini, null,4));
167  //console.dump(ini);
168
169
170  //Seed.quit();
171
172 //GLib.key_file_load_from_file (key_file, String file, KeyFileFlags flags) : Boolean
173
174
175
176  
177
178 var tables = Gda.execute_select_command(cnc, "SHOW TABLES").fetchAll();
179 var readers = [];
180 tables.forEach(function(table) {
181     //print(table);
182     var schema = Gda.execute_select_command(cnc, "DESCRIBE `" + table+'`').fetchAll();
183     var reader = []; 
184     var colmodel = []; 
185     var combofields= [ { name : 'id', type: 'int' } ]; // technically the primary key..
186          
187     var form = {}
188        
189     var firstTxtCol = '';
190     
191     
192     
193     schema.forEach(function(e)  {
194         var type = e.Type.match(/([^(]+)\(([^\)]+)\)/);
195         var row  = { }; 
196         if (type) {
197             e.Type = type[1];
198             e.Size = type[2];
199         }
200         
201         
202         
203         row.name = e.Field;
204         
205         
206         if (typeof(map[e.Type]) == 'undefined') {
207            console.dump(e);
208            throw {
209                 name: "ArgumentError", 
210                 message: "Unknown mapping for type : " + e.Type
211             };
212         }
213         row.type = map[e.Type];
214         
215         if (row.type == 'string' && !firstTxtCol.length) {
216             firstTxtCol = row.name;
217         }
218         
219         if (row.type == 'date') {
220             row.dateFormat = 'Y-m-d';
221         }
222         reader.push(row);
223         
224         if (combofields.length == 1 && row.type == 'string') {
225             combofields.push(row);
226         }
227         
228         
229         var title = row.name.replace(/_id/, '').replace(/_/g, ' ');
230         title  = title[0].toUpperCase() + title.substring(1);
231         
232         colmodel.push({
233             "xtype": "ColumnModel",
234             "header": title,
235             "width":  row.type == 'string' ? 200 : 75,
236             "dataIndex": row.name,
237             "|renderer": row.type != 'date' ? 
238                     "function(v) { return String.format('{0}', v); }" :
239                     "function(v) { return String.format('{0}', v ? v.format('d/M/Y') : ''); }" , // special for date
240             "|xns": "Roo.grid",
241             "*prop": "colModel[]"
242         });
243         var xtype = 'TextField';
244         if (row.type == 'number') {
245             xtype = 'NumberField';
246         }
247         if (row.type == 'date') {
248             xtype = 'DateField';
249         }
250         if (e.Type == 'text') {
251             xtype = 'TextArea';
252         }
253         
254         // what about booleans.. -> checkboxes..
255         
256         
257         
258         form[row.name] = {
259             fieldLabel : title,
260             name : row.name,
261             width : row.type == 'string' ? 200 : 75,
262             '|xns' : 'Roo.form',
263             xtype : xtype
264         }
265         if (xtype == 'TextArea') {
266             form[row.name].height = 100;
267         }
268         
269         
270     });
271     
272     var combo = {
273         '|xns' : 'Roo.form',
274         xtype: 'ComboBox',
275         allowBlank : 'false',
276         editable : 'false',
277         emptyText : 'Select ' + table,
278         forceSelection : true,
279         listWidth : 400,
280         loadingText: 'Searching...',
281         minChars : 2,
282         pageSize : 20,
283         qtip: 'Select ' + table,
284         selectOnFocus: true,
285         tirggerAction : all,
286         typeAhead: true,
287         valueField : id,
288         width: 300,
289         tpl : '<div class="x-grid-cell-text x-btn button"><b>{name}</b> </div>', // SET WHEN USED
290         queryParam : '',// SET WHEN USED
291         fieldLabel : table,  // SET WHEN USED
292         hiddenName : '', // SET WHEN USED eg. project_id
293         name : '', // SET WHEN USED eg. project_id_name
294         items : [
295             {
296                     
297                 '*prop' : 'store',
298                 'xtype' : 'Store',
299                 '|xns' : 'Roo.data',
300                 listeners : {
301                     '|beforeload' : 'function (_self, o)' +
302                     "{\n" +
303                     "    o.params = o.params || {};\n" +
304                     "    // set more here\n" +
305                     "}\n"
306                 },
307                 items : [
308                     {
309                         '*prop' : 'proxy',
310                         'xtype' : 'HttpProxy',
311                         'method' : 'GET',
312                         '|xns' : 'Roo.data',
313                         '|url' : "baseURL + '/Roo/" + table + ".php'",
314                     },
315                     
316                     {
317                         '*prop' : 'reader',
318                         'xtype' : 'JsonReader',
319                         '|xns' : 'Roo.data',
320                         'id' : 'id',
321                         'root' : 'data',
322                         'totalProperty' : 'total',
323                         '|fields' : JSON.stringify(combofields)
324                         
325                     }
326                 ]
327             }
328         ]
329     }
330     
331     
332     
333     
334     //print(JSON.stringify(reader,null,4));
335     readers.push({
336         table : table ,
337         combo : combo,
338         combofields : combofields,
339         reader :  reader,
340         oreader : JSON.parse(JSON.stringify(reader)), // dupe it..
341         colmodel : colmodel,
342         firstTxtCol : firstTxtCol,
343         form : form
344     });
345     
346     //console.dump(schema );
347     
348      
349 });
350
351
352
353 // merge in the linked tables..
354 readers.forEach(function(reader) {
355     if (typeof(ini[reader.table]) == 'undefined') {
356      
357         return;
358     }
359     print("OVERLAY - " + reader.table);
360     // we have a map..
361     for (var col in ini[reader.table]) {
362         var kv = ini[reader.table][col].split(':');
363         var add = readers.filter(function(r) { return r.table == kv[0] })[0];
364         
365         // merge in data (eg. project_id => project_id_*****
366      
367         add.oreader.forEach(function(or) {
368            
369             
370             
371             reader.reader.push({
372                 name : col + '_' + or.name,
373                 type : or.type
374             });
375         });
376         
377         // col is mapped to something..
378         var combofields = add.combofields;
379         var combofields_name = add.combofields[1].name;
380         var old =   reader.form[col];
381         reader.form[col] = JSON.parse(JSON.stringify(add.combo)); // clone
382         reader.form[col].queryParam  = 'query[' + combofields_name + ']';// SET WHEN USED
383         reader.form[col].fieldLabel = old.fieldLabel;  // SET WHEN USED
384         reader.form[col].hiddenName : old.name; // SET WHEN USED eg. project_id
385         reader.form[col].name : old.name + '_' + combofields_name; // SET WHEN USED eg. project_id_name
386         reader.form[col].tpl = '<div class="x-grid-cell-text x-btn button"><b>{' + combofields_name +'}</b> </div>'; // SET WHEN USED
387         
388              
389     };
390     
391     
392 });
393
394 //readers.forEach(function(reader) {
395 //    delete reader.oreader;
396 //});
397
398  
399
400
401
402 //print(JSON.stringify(readers, null, 4));
403
404 readers.forEach(function(reader) {
405     
406
407     var dir = GLib.get_home_dir() + '/.Builder/Roo.data.JsonReader'; 
408     if (!File.isDirectory(dir)) {
409         File.mkdir(dir);
410     }
411     
412     // READERS
413     print("WRITE: " +  dir + '/' + cfg.DB_NAME + '_' + reader.table + '.json');
414     
415                 
416     var jreader = {
417         '|xns' : 'Roo.data',
418         xtype : "JsonReader",
419         totalProperty : "total",
420         root : "data",
421         '*prop' : "reader",
422         id : 'id', // maybe no..
423         '|fields' :  JSON.stringify(reader.reader, null,4)
424     };
425     
426     File.write(
427         dir + '/' + cfg.DB_NAME + '_' + reader.table + '.json',
428         JSON.stringify(jreader, null, 4)
429     )
430     
431     
432     // GRIDS
433     dir = GLib.get_home_dir() + '/.Builder/Roo.GridPanel'; 
434     if (!File.isDirectory(dir)) {
435         File.mkdir(dir);
436     }
437     
438
439     print("WRITE: " +  dir + '/' + cfg.DB_NAME + '_' + reader.table + '.json');
440     
441     File.write(
442         dir + '/' + cfg.DB_NAME + '_' + reader.table + '.json',
443             
444        
445         JSON.stringify({
446             '|xns' : 'Roo',
447             xtype : "GridPanel",
448             "title": reader.table,
449             "fitToframe": true,
450             "fitContainer": true,
451             "tableName": reader.table,
452             "background": true,
453             "listeners": {
454                 "|activate": "function() {\n    _this.panel = this;\n    if (_this.grid) {\n        _this.grid.footer.onClick('first');\n    }\n}"
455             },
456             "items": [
457                 {
458                     "*prop": "grid",
459                     "xtype": "Grid",
460                     "autoExpandColumn": reader.firstTxtCol,
461                     "loadMask": true,
462                     "listeners": {
463                         "|render": "function() \n" +
464                             "{\n" +
465                             "   _this.grid = this; \n" +
466                             "    //_this.dialog = Pman.Dialog.FILL_IN\n" +
467                             "    if (_this.panel.active) {\n" +
468                             "       this.footer.onClick('first');\n" +
469                             "    }\n" +
470                             "}"
471                     },
472                     "|xns": "Roo.grid",
473
474                     "items": [
475                         {
476                             "*prop": "dataSource",
477                             "xtype": "Store",
478                             
479                             "|xns": "Roo.data",
480                             "items": [
481                                 
482                                 {
483                                     "*prop": "proxy",
484                                     "xtype": "HttpProxy",
485                                     "method": "GET",
486                                     "|url": "baseURL + '/Roo/" + reader.table + ".php'",
487                                     "|xns": "Roo.data"
488                                 },
489                                 jreader
490                             ]
491                         },
492                         {
493                             "*prop": "footer",
494                             "xtype": "PagingToolbar",
495                             "pageSize": 25,
496                             "displayInfo": true,
497                             "displayMsg": "Displaying " + reader.table + "{0} - {1} of {2}",
498                             "emptyMsg": "No " + reader.table + " found",
499                             "|xns": "Roo"
500                         },
501                         {
502                             "*prop": "toolbar",
503                             "xtype": "Toolbar",
504                             "|xns": "Roo",
505                             "items": [
506                                 {
507                                     "text": "Add",
508                                     "xtype": "Button",
509                                     "cls": "x-btn-text-icon",
510                                     "|icon": "Roo.rootURL + 'images/default/dd/drop-add.gif'",
511                                     "listeners": {
512                                         "|click": "function()\n"+
513                                             "{\n"+
514                                             "   //yourdialog.show( { id : 0 } , function() {\n"+
515                                             "   //  _this.grid.footer.onClick('first');\n"+
516                                             "   //}); \n"+
517                                             "}\n"
518                                     },
519                                     "|xns": "Roo"
520                                 },
521                                 {
522                                     "text": "Edit",
523                                     "xtype": "Button",
524                                     "cls": "x-btn-text-icon",
525                                     "|icon": "Roo.rootURL + 'images/default/tree/leaf.gif'",
526                                     "listeners": {
527                                         "|click": "function()\n"+
528                                             "{\n"+
529                                             "    var s = _this.grid.getSelectionModel().getSelections();\n"+
530                                             "    if (!s.length || (s.length > 1))  {\n"+
531                                             "        Roo.MessageBox.alert(\"Error\", s.length ? \"Select only one Row\" : \"Select a Row\");\n"+
532                                             "        return;\n"+
533                                             "    }\n"+
534                                             "    \n"+
535                                             "    //_this.dialog.show(s[0].data, function() {\n"+
536                                             "    //    _this.grid.footer.onClick('first');\n"+
537                                             "    //   }); \n"+
538                                             "    \n"+
539                                             "}\n" 
540                                         
541                                     },
542                                     "|xns": "Roo"
543                                 },
544                                 {
545                                     "text": "Delete",
546                                     "cls": "x-btn-text-icon",
547                                     "|icon": "rootURL + '/Pman/templates/images/trash.gif'",
548                                     "xtype": "Button",
549                                     "listeners": {
550                                         "|click": "function()\n"+
551                                             "{\n"+
552                                             "   //Pman.genericDelete(_this, _this.grid.tableName); \n"+
553                                             "}\n"+
554                                             "        "
555                                     },
556                                     "|xns": "Roo"
557                                 }
558                             ]
559                         }, // end toolbar
560                     ].concat( reader.colmodel)
561                 }
562             ]
563             
564             
565         }, null, 4)
566     )
567     
568     /// FORMS..
569     
570     dir = GLib.get_home_dir() + '/.Builder/Roo.form.Form'; 
571     if (!File.isDirectory(dir)) {
572         File.mkdir(dir);
573     }
574     formElements = [];
575     for (var k in reader.form) {
576         if (k == 'id') { // should really do primary key testing..
577             continue;
578            }
579         formElements.push(reader.form[k]);
580     }
581
582     print("WRITE: " +  dir + '/' + cfg.DB_NAME + '_' + reader.table + '.json');
583     
584     File.write(
585         dir + '/' + cfg.DB_NAME + '_' + reader.table + '.json',
586             
587        
588         JSON.stringify({
589             '|xns' : 'Roo.form',
590             xtype : "Form",
591             listeners : {
592                 "|actioncomplete" : "function(_self,action)\n"+
593                     "{\n"+
594                     "    if (action.type == 'setdata') {\n"+
595                     "       //_this.dialog.el.mask(\"Loading\");\n"+
596                     "       //this.load({ method: 'GET', params: { '_id' : _this.data.id }});\n"+
597                     "       return;\n"+
598                     "    }
599                     "    if (action.type == 'load') {\n"+
600                     "        _this.dialog.el.unmask();\n"+
601                     "        return;\n"+
602                     "    }\n"+
603                     "    if (action.type =='submit') {\n"+
604                     "    \n"+
605                     "        _this.dialog.el.unmask();\n"+
606                     "        _this.dialog.hide();\n"+
607                     "    \n"+
608                     "         if (_this.callback) {\n"+
609                     "            _this.callback.call(_this, _this.form.getValues());\n"+
610                     "         }\n"+
611                     "         _this.form.reset();\n"+
612                     "         return;"\n"+
613                     "    }\n"+
614                     "}\n",
615                 
616                 "|rendered" : "function (form)\n"+
617                     "{\n"+
618                     "    _this.form= form;
619                     "}\n"
620             }
621             method : "POST",
622             style : "margin:10px;",
623             "|url" : "baseURL + '/Roo/" + reader.table + ".php'",
624             items : formElements
625         })
626     );
627             
628             
629                    
630 });              
631
632
633
634