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