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