dbgenerate.js
[app.Builder.js] / dbgenerate.js
1 //<script type="text/javascript">
2
3 /**
4  * This is a hacky generator to generate element definitions for the Roo version from the database
5  * 
6  * Let's see if libgda can be used to generate our Readers for roo...
7  * 
8  * Concept - conect to database..
9  * 
10  * list tables
11  * 
12  * extra schemas..
13  * 
14  * write readers..
15  * 
16  * usage: seed generate.js
17  *
18  *
19  *
20  *
21  *Hack needed to latest GLib-2.0.gir 
22  *
23  * <record name="KeyFile" c:type="GKeyFile" disguised="1">
24         <constructor name="new" c:identifier="g_key_file_new">
25         <return-value transfer-ownership="full">
26           <type name="KeyFile" c:type="GKeyFile*"/>
27         </return-value>
28       </constructor>
29  *
30  *
31  * remove introspectable =0 from g_key_file_get_groups
32  *   and add transfer-owneership = none to return value
33  * remove introspectable =0 from g_key_file_get_keys
34  *   and add transfer-owneership = none to return value* 
35  * 
36  */
37 Gda  = imports.gi.Gda;
38 GObject = imports.gi.GObject;
39
40 GLib = imports.gi.GLib;
41
42 console = imports.console;
43 File = imports.File.File;
44 Options = imports.Options.Options;
45
46 //Gda.init();
47
48 var prov = Gda.Config.list_providers ();
49 //print(prov.dump_as_string());
50
51 var o = new Options({
52     help_description : 'Element builder for App Builder based on database schema',
53     
54     options:  [
55         { arg_long : 'DBTYPE' , arg_short : 't', description : 'Database Type (eg. MySQL or PostgreSQL ' },
56         { arg_long : 'DBNAME' , arg_short : 'd', description : 'Database Name' },
57         { arg_long : 'USERNAME' , arg_short : 'u', description : 'Username'},
58         { arg_long : 'PASSWORD' , arg_short : 'p', description : '' , arg_default :'' },
59         { arg_long : 'INI' , arg_short : 'I', description :
60                     'Either base directory which has Pman/***/DataObjects/***.links.ini or location of ini file.' },
61     ]
62            
63 })
64
65
66
67 var cfg = o.parse(Seed.argv);
68 print(JSON.stringify(cfg, null,4));
69
70 var   cnc = Gda.Connection.open_from_string (cfg.DBTYPE,
71          "DB_NAME=" + cfg.DBNAME, 
72         "USERNAME=" + cfg.USERNAME + ';PASSWORD=' + cfg.PASSWORD,
73         Gda.ConnectionOptions.NONE, null);
74
75
76
77                                               
78
79  
80 Gda.DataSelect.prototype.fetchAll = function()
81 {
82     var cols = [];
83     
84     for (var i =0;i < this.get_n_columns(); i++) {
85         cols.push(this.get_column_name(i));
86     }
87     //print(JSON.stringify(cols, null,4));
88     var iter = this.create_iter();
89     var res = [];
90     //print(this.get_n_rows());
91     var _this = this;
92     for (var r = 0; r < this.get_n_rows(); r++) {
93         
94         // single clo..
95         //print("GOT ROW");
96         if (cols.length == 1) {
97             res.push(this.get_value_at(0,r).get_string());
98             continue;
99         }
100         var add = { };
101         
102         cols.forEach(function(n,i) {
103             var val = _this.get_value_at(i,r);
104             var type = GObject.type_name(val.g_type) ;
105             var vs = ['GdaBinary', 'GdaBlob' ].indexOf(type) > -1 ? val.value.to_string(1024) : val.value;
106             //print(n + " : TYPE: " + GObject.type_name(val.g_type) + " : " + vs);
107             //print (n + '=' + iter.get_value_at(i).value);
108             add[n] = vs;
109         });
110         
111         res.push(add);
112         
113     }
114     return res;
115
116 }
117
118 var map = {
119     'date' : 'date',
120     'datetime' : 'date',
121     'timestamp with time zone' : 'date',
122     'time' : 'string', //bogus
123     'int' : 'int',
124     'integer' : 'int',
125     'bigint' : 'int',
126     'double' : 'float',
127     'tinyint' : 'int',
128     'smallint' : 'int',
129     'decimal' : 'float',
130     'float' : 'float',
131     'numeric' : 'float',
132     'char' : 'string',
133     'character' : 'string',
134     'character varying' : 'string',
135     'varchar' : 'string',
136     'text' : 'string',
137     'longtext' : 'string',
138     'tinytext' : 'string',
139     'mediumtext' : 'string',
140     'enum' : 'string',
141     'timestamp' : 'number',
142     'blob' : 'text',
143     'bytea' : 'text',
144     'boolean' : 'int',
145     
146 }
147
148 var ini = { }
149
150 function readIni(fn)
151 {
152     print('Read INI : ' + fn);
153     var key_file = new GLib.KeyFile.c_new();
154     if (!key_file.load_from_file (fn , GLib.KeyFileFlags.NONE )) {
155         return;
156     }
157    
158     var groups = key_file.get_groups();
159     groups.forEach(function(g) {
160         ini[g] = {}
161            print("KEY:"+g);
162         var keys = key_file.get_keys(g);
163         if (!keys) { return; }
164          keys.forEach(function(k) {
165             ini[g][k] = key_file.get_value(g,k);
166         })
167     })
168     
169 }
170 if (File.isFile(cfg.INI)) {
171     if (cfg.INI.match(/links\.ini$/)) {
172         readIni(cfg.INI);
173     } else {
174         readIni(cfg.INI.replace(/\.ini$/, ".links.ini"));
175     }
176 }
177
178
179 if (File.isDirectory(cfg.INI)) {
180         
181
182     //--- load ini files..
183     // this is very specific.
184     
185     var dirs = File.list( cfg.INI + '/Pman').filter( 
186         function(e) { 
187             if (!File.isDirectory(cfg.INI + '/Pman/' + e + '/DataObjects')) {
188                 return false;
189             }
190             return true;
191         }
192     );
193     
194      
195     dirs.forEach(function(d) {
196         // this currently misses the web.*/Pman/XXXX/DataObjects..
197         var path = cfg.INI + '/Pman/' + d + '/DataObjects';
198          
199         if (!File.isDirectory(path)) {
200             return; //skip
201         }
202         var inis = File.list(path).filter(
203             function(e) { return e.match(/\.links\.ini$/); }
204         );
205         if (!inis.length) {
206             return;
207         }
208         
209         inis.forEach(function(i) {
210             readIni(path + '/' + i); 
211             
212         })
213  
214     });
215     // look at web.XXXX/Pman/XXX/DataObjects/*.ini
216     var inis = File.list(cfg.INI).filter(
217         function(e) { return e.match(/\.links\.ini$/); }
218     )
219     
220      inis.forEach(function(i) {
221         readIni(path + '/' + i); 
222         
223     })
224     
225     
226 }
227 //print(JSON.stringify(ini, null,4));
228  //console.dump(ini);
229
230
231  //Seed.quit();
232
233 //GLib.key_file_load_from_file (key_file, String file, KeyFileFlags flags) : Boolean
234
235
236 switch(cfg.DBTYPE) {
237     case "MySQL":
238         query_tables = "SHOW TABLES";
239         query_describe_table = "DESCRIBE `%s`";
240         break;
241     
242     case 'PostgreSQL':
243         query_tables = "select c.relname FROM pg_catalog.pg_class c " + 
244             "LEFT JOIN pg_catalog.pg_namespace n ON n.oid = c.relnamespace " + 
245             "WHERE c.relkind IN ('r','') AND n.nspname NOT IN ('pg_catalog', 'pg_toast')" +
246             "AND pg_catalog.pg_table_is_visible(c.oid) ";
247          query_describe_table =  
248                 "SELECT " +
249                 "f.attnum AS number, " +
250                 "f.attname AS Field, " +
251                 "f.attnum, " +
252                 "CASE WHEN f.attnotnull = 't' THEN 'NO' ELSE 'YES' END AS isNull, " + 
253                 "pg_catalog.format_type(f.atttypid,f.atttypmod) AS Type, " +
254                 "CASE WHEN p.contype = 'p' THEN 't' ELSE 'f' END AS primarykey, " +
255                 "CASE WHEN p.contype = 'u' THEN 't' ELSE 'f' END AS uniquekey, " +
256                 "CASE WHEN p.contype = 'f' THEN g.relname END AS foreignkey, " +
257                 "CASE WHEN p.contype = 'f' THEN p.confkey END AS foreignkey_fieldnum, " +
258                 "CASE WHEN p.contype = 'f' THEN g.relname END AS foreignkey, " +
259                 "CASE WHEN p.contype = 'f' THEN p.conkey END AS foreignkey_connnum, " +
260                 "CASE WHEN f.atthasdef = 't' THEN d.adsrc END AS default " +
261                 "FROM pg_attribute f JOIN pg_class c ON c.oid = f.attrelid " +
262                 "        JOIN pg_type t ON t.oid = f.atttypid " +
263                 "        LEFT JOIN pg_attrdef d ON d.adrelid = c.oid AND d.adnum = f.attnum " +
264                 "        LEFT JOIN pg_namespace n ON n.oid = c.relnamespace " +
265                 "        LEFT JOIN pg_constraint p ON p.conrelid = c.oid AND f.attnum = ANY ( p.conkey ) " +
266                 "        LEFT JOIN pg_class AS g ON p.confrelid = g.oid " +
267                 "WHERE c.relkind = 'r'::char AND n.nspname = '%n' " +
268                 "AND c.relname = '%s' AND f.attnum > 0 ORDER BY number";
269                 
270                 
271                 
272         break;
273 /*
274            "Field": "province",
275         "Type": "varchar(255)",
276         "Null": "NO", << or is null
277         "Key": null,
278         "Default": null,
279         "Extra": 
280 */  
281 }
282
283
284  
285
286 var tables = Gda.execute_select_command(cnc, query_tables).fetchAll();
287 print(JSON.stringify(tables));
288
289 var readers = [];
290 tables.forEach(function(table) {
291     //print(table);
292     var schema = Gda.execute_select_command(cnc,
293             query_describe_table.replace(/%s/, table).replace(/%n/,'public')
294             ).fetchAll();
295     
296     
297     var reader = []; 
298     var colmodel = []; 
299     var combofields= [ { name : 'id', type: 'int' } ]; // technically the primary key..
300          
301     var form = {}
302        
303     var firstTxtCol = '';
304     
305     //print(JSON.stringify(schema, null,4));    Seed.quit();
306     
307     schema.forEach(function(e)  {
308         e.Type = e.type;
309         e.Field = e.field;
310          
311         var type = e.Type.match(/([^(]+)\(([^\)]+)\)/);
312         var row  = { }; 
313         if (type) {
314             e.Type = type[1];
315             e.Size = type[2];
316         }
317         
318         
319         
320         row.name = e.Field;
321         
322         
323         if (typeof(map[e.Type]) == 'undefined') {
324            console.dump(e);
325            throw {
326                 name: "ArgumentError", 
327                 message: "Unknown mapping for type : " + e.Type
328             };
329         }
330         row.type = map[e.Type];
331         
332         if (row.type == 'string' && !firstTxtCol.length) {
333             firstTxtCol = row.name;
334         }
335         
336         if (row.type == 'date') {
337             row.dateFormat = 'Y-m-d';
338         }
339         reader.push(row);
340         
341         if (combofields.length == 1 && row.type == 'string') {
342             combofields.push(row);
343         }
344         
345         
346         var title = row.name.replace(/_id/, '').replace(/_/g, ' ');
347         title  = title[0].toUpperCase() + title.substring(1);
348         
349         colmodel.push({
350             "xtype": "ColumnModel",
351             "header": title,
352             "width":  row.type == 'string' ? 200 : 75,
353             "dataIndex": row.name,
354             "|renderer": row.type != 'date' ? 
355                     "function(v) { return String.format('{0}', v); }" :
356                     "function(v) { return String.format('{0}', v ? v.format('d/M/Y') : ''); }" , // special for date
357             "|xns": "Roo.grid",
358             "*prop": "colModel[]"
359         });
360         var xtype = 'TextField';
361         
362         
363         if (row.type == 'number') {
364             xtype = 'NumberField';
365         }
366         if (row.type == 'date') {
367             xtype = 'DateField';
368         }
369         if (e.Type == 'text') {
370             xtype = 'TextArea';
371         }
372         if (row.name == 'id') {
373             xtype = 'Hidden';
374         } 
375         // what about booleans.. -> checkboxes..
376         
377         
378         
379         form[row.name] = {
380             fieldLabel : title,
381             name : row.name,
382             width : row.type == 'string' ? 200 : 75,
383             '|xns' : 'Roo.form',
384             xtype : xtype
385         }
386         if (xtype == 'TextArea') {
387             form[row.name].height = 100;
388         }
389         if (xtype == 'Hidden') {
390             delete form[row.name].fieldLabel;
391             delete form[row.name].width;
392         }
393         
394     });
395     
396     var combo = {
397         '|xns' : 'Roo.form',
398         xtype: 'ComboBox',
399         allowBlank : 'false',
400         editable : 'false',
401         emptyText : 'Select ' + table,
402         forceSelection : true,
403         listWidth : 400,
404         loadingText: 'Searching...',
405         minChars : 2,
406         pageSize : 20,
407         qtip: 'Select ' + table,
408         selectOnFocus: true,
409         triggerAction : 'all',
410         typeAhead: true,
411         
412         width: 300,
413         
414         
415         
416         tpl : '<div class="x-grid-cell-text x-btn button"><b>{name}</b> </div>', // SET WHEN USED
417         queryParam : '',// SET WHEN USED
418         fieldLabel : table,  // SET WHEN USED
419         valueField : 'id',
420         displayField : '', // SET WHEN USED eg. project_id_name
421         hiddenName : '', // SET WHEN USED eg. project_id
422         name : '', // SET WHEN USED eg. project_id_name
423         items : [
424             {
425                     
426                 '*prop' : 'store',
427                 'xtype' : 'Store',
428                 '|xns' : 'Roo.data',
429                 'remoteSort' : true,
430                 '|sortInfo' : '{ direction : \'ASC\', field: \'id\' }',
431                 listeners : {
432                     '|beforeload' : 'function (_self, o)' +
433                     "{\n" +
434                     "    o.params = o.params || {};\n" +
435                     "    // set more here\n" +
436                     "}\n"
437                 },
438                 items : [
439                     {
440                         '*prop' : 'proxy',
441                         'xtype' : 'HttpProxy',
442                         'method' : 'GET',
443                         '|xns' : 'Roo.data',
444                         '|url' : "baseURL + '/Roo/" + table + ".php'",
445                     },
446                     
447                     {
448                         '*prop' : 'reader',
449                         'xtype' : 'JsonReader',
450                         '|xns' : 'Roo.data',
451                         'id' : 'id',
452                         'root' : 'data',
453                         'totalProperty' : 'total',
454                         '|fields' : JSON.stringify(combofields)
455                         
456                     }
457                 ]
458             }
459         ]
460     }
461     
462     
463     
464     
465     //print(JSON.stringify(reader,null,4));
466     readers.push({
467         table : table ,
468         combo : combo,
469         combofields : combofields,
470         reader :  reader,
471         oreader : JSON.parse(JSON.stringify(reader)), // dupe it..
472         colmodel : colmodel,
473         firstTxtCol : firstTxtCol,
474         form : form
475     });
476     
477     //console.dump(schema );
478     
479      
480 });
481
482
483
484 // merge in the linked tables..
485 readers.forEach(function(reader) {
486     if (typeof(ini[reader.table]) == 'undefined') {
487      
488         return;
489     }
490     print("OVERLAY - " + reader.table);
491     // we have a map..
492     for (var col in ini[reader.table]) {
493         var kv = ini[reader.table][col].split(':');
494         
495         
496         var add = readers.filter(function(r) { return r.table == kv[0] })[0];
497         if (!add) {
498             continue;
499         }
500         // merge in data (eg. project_id => project_id_*****
501      
502         add.oreader.forEach(function(or) {
503             reader.reader.push({
504                 name : col + '_' + or.name,
505                 type : or.type
506             });
507         });
508         
509         // col is mapped to something..
510         var combofields = add.combofields;
511         if (add.combofields.length < 2) {
512             continue;
513         }
514         if (typeof(reader.form[col]) == 'undefined') {
515             print (JSON.stringify(reader.form, null,4));
516             print("missing linked column " + col);
517             continue;
518         }
519         
520         var combofields_name = add.combofields[1].name;
521         var old =   reader.form[col];
522         reader.form[col] = JSON.parse(JSON.stringify(add.combo)); // clone
523         reader.form[col].queryParam  = 'query[' + combofields_name + ']';// SET WHEN USED
524         reader.form[col].fieldLabel = old.fieldLabel;  // SET WHEN USED
525         reader.form[col].hiddenName = old.name; // SET WHEN USED eg. project_id
526         reader.form[col].displayField = combofields_name; // SET WHEN USED eg. project_id
527         reader.form[col].name  = old.name + '_' + combofields_name; // SET WHEN USED eg. project_id_name
528         reader.form[col].tpl = '<div class="x-grid-cell-text x-btn button"><b>{' + combofields_name +'}</b> </div>'; // SET WHEN USED
529         
530              
531     };
532     
533     
534 });
535
536 //readers.forEach(function(reader) {
537 //    delete reader.oreader;
538 //});
539
540  
541
542
543
544 //print(JSON.stringify(readers, null, 4));
545
546 readers.forEach(function(reader) {
547     
548
549     var dir = GLib.get_home_dir() + '/.Builder/Roo.data.JsonReader'; 
550     if (!File.isDirectory(dir)) {
551         print("mkdir " + dir);
552         File.mkdir(dir);
553     }
554     
555     // READERS
556     print("WRITE: " +  dir + '/' + cfg.DBNAME + '_' + reader.table + '.json');
557     
558                 
559     var jreader = {
560         '|xns' : 'Roo.data',
561         xtype : "JsonReader",
562         totalProperty : "total",
563         root : "data",
564         '*prop' : "reader",
565         id : 'id', // maybe no..
566        
567         '|fields' :  JSON.stringify(reader.reader, null,4).replace(/"/g,"'")
568     };
569     
570     File.write(
571         dir + '/' + cfg.DBNAME + '_' + reader.table + '.json',
572         JSON.stringify(jreader, null, 4)
573     )
574     
575     
576     // GRIDS
577     dir = GLib.get_home_dir() + '/.Builder/Roo.GridPanel'; 
578     if (!File.isDirectory(dir)) {
579         print("mkdir " + dir);
580         File.mkdir(dir);
581     }
582     
583
584     print("WRITE: " +  dir + '/' + cfg.DBNAME + '_' + reader.table + '.json');
585     
586     File.write(
587         dir + '/' + cfg.DBNAME + '_' + reader.table + '.json',
588             
589        
590         JSON.stringify({
591             '|xns' : 'Roo',
592             xtype : "GridPanel",
593             "title": reader.table,
594             "fitToframe": true,
595             "fitContainer": true,
596             "tableName": reader.table,
597             "background": true,
598             "region" : 'center',
599             "listeners": {
600                 "|activate": "function() {\n    _this.panel = this;\n    if (_this.grid) {\n        _this.grid.footer.onClick('first');\n    }\n}"
601             },
602             "items": [
603                 {
604                     "*prop": "grid",
605                     "xtype": "Grid",
606                     "autoExpandColumn": reader.firstTxtCol,
607                     "loadMask": true,
608                     "listeners": {
609                         "|render": "function() \n" +
610                             "{\n" +
611                             "    _this.grid = this; \n" +
612                             "    //_this.dialog = Pman.Dialog.FILL_IN\n" +
613                             "    if (_this.panel.active) {\n" +
614                             "       this.footer.onClick('first');\n" +
615                             "    }\n" +
616                             "}",
617                         "|rowdblclick": "function (_self, rowIndex, e)\n" + 
618                             "{\n" + 
619                             "    if (!_this.dialog) return;\n" + 
620                             "    _this.dialog.show( this.getDataSource().getAt(rowIndex), function() {\n" + 
621                             "        _this.grid.footer.onClick('first');\n" + 
622                             "    }); \n" + 
623                             "}\n"
624                     },
625                     "|xns": "Roo.grid",
626
627                     "items": [
628                         {
629                             "*prop": "dataSource",
630                             "xtype": "Store",
631                              remoteSort : true,
632                             '|sortInfo' : "{ field : '" + reader.firstTxtCol  +  "', direction: 'ASC' }", 
633                             "|xns": "Roo.data",
634                             "items": [
635                                 
636                                 {
637                                     "*prop": "proxy",
638                                     "xtype": "HttpProxy",
639                                     "method": "GET",
640                                     "|url": "baseURL + '/Roo/" + reader.table + ".php'",
641                                     "|xns": "Roo.data"
642                                 },
643                                 jreader
644                             ]
645                         },
646                         {
647                             "*prop": "footer",
648                             "xtype": "PagingToolbar",
649                             "pageSize": 25,
650                             "displayInfo": true,
651                             "displayMsg": "Displaying " + reader.table + "{0} - {1} of {2}",
652                             "emptyMsg": "No " + reader.table + " found",
653                             "|xns": "Roo"
654                         },
655                         {
656                             "*prop": "toolbar",
657                             "xtype": "Toolbar",
658                             "|xns": "Roo",
659                             "items": [
660                                 {
661                                     "text": "Add",
662                                     "xtype": "Button",
663                                     "cls": "x-btn-text-icon",
664                                     "|icon": "Roo.rootURL + 'images/default/dd/drop-add.gif'",
665                                     "listeners": {
666                                         "|click": "function()\n"+
667                                             "{\n"+
668                                             "    if (!_this.dialog) return;\n" +
669                                             "    _this.dialog.show( { id : 0 } , function() {\n"+
670                                             "        _this.grid.footer.onClick('first');\n"+
671                                             "   }); \n"+
672                                             "}\n"
673                                     },
674                                     "|xns": "Roo.Toolbar"
675                                 },
676                                 {
677                                     "text": "Edit",
678                                     "xtype": "Button",
679                                     "cls": "x-btn-text-icon",
680                                     "|icon": "Roo.rootURL + 'images/default/tree/leaf.gif'",
681                                     "listeners": {
682                                         "|click": "function()\n"+
683                                             "{\n"+
684                                             "    var s = _this.grid.getSelectionModel().getSelections();\n"+
685                                             "    if (!s.length || (s.length > 1))  {\n"+
686                                             "        Roo.MessageBox.alert(\"Error\", s.length ? \"Select only one Row\" : \"Select a Row\");\n"+
687                                             "        return;\n"+
688                                             "    }\n"+
689                                             "    if (!_this.dialog) return;\n" +
690                                             "    _this.dialog.show(s[0].data, function() {\n"+
691                                             "        _this.grid.footer.onClick('first');\n"+
692                                             "    }); \n"+
693                                             "    \n"+
694                                             "}\n" 
695                                         
696                                     },
697                                     "|xns": "Roo.Toolbar"
698                                 },
699                                 {
700                                     "text": "Delete",
701                                     "cls": "x-btn-text-icon",
702                                     "|icon": "rootURL + '/Pman/templates/images/trash.gif'",
703                                     "xtype": "Button",
704                                     "listeners": {
705                                         "|click": "function()\n"+
706                                             "{\n"+
707                                             "     Pman.genericDelete(_this, '" + reader.table + "'); \n"+
708                                             "}\n"+
709                                             "        "
710                                     },
711                                     "|xns": "Roo.Toolbar"
712                                 }
713                             ]
714                         }, // end toolbar
715                     ].concat( reader.colmodel)
716                 }
717             ]
718             
719             
720         }, null, 4)
721     )
722     
723     /// FORMS..
724     
725     dir = GLib.get_home_dir() + '/.Builder/Roo.form.Form'; 
726     if (!File.isDirectory(dir)) {
727         print("mkdir " + dir);
728         File.mkdir(dir);
729     }
730     var formElements = [];
731     var formHeight = 50;
732     for (var k in reader.form) {
733         if (k == 'id') { // should really do primary key testing..
734             continue;
735         }
736         formHeight += reader.form[k].xtype == 'TextArea' ? 100 : 30;
737         
738         formElements.push(reader.form[k]);
739     }
740     if (reader.form['id']) {
741         formElements.push(reader.form['id']);
742     }
743     
744
745     print("WRITE: " +  dir + '/' + cfg.DBNAME + '_' + reader.table + '.json');
746     var frmCfg = 
747     {
748         '|xns' : 'Roo.form',
749         xtype : "Form",
750         listeners : {
751             "|actioncomplete" : "function(_self,action)\n"+
752                 "{\n"+
753                 "    if (action.type == 'setdata') {\n"+
754                 "       //_this.dialog.el.mask(\"Loading\");\n"+
755                 "       //this.load({ method: 'GET', params: { '_id' : _this.data.id }});\n"+
756                 "       return;\n"+
757                 "    }\n"+
758                 "    if (action.type == 'load') {\n"+
759                 "        _this.dialog.el.unmask();\n"+
760                 "        return;\n"+
761                 "    }\n"+
762                 "    if (action.type =='submit') {\n"+
763                 "    \n"+
764                 "        _this.dialog.el.unmask();\n"+
765                 "        _this.dialog.hide();\n"+
766                 "    \n"+
767                 "         if (_this.callback) {\n"+
768                 "            _this.callback.call(_this, _this.form.getValues());\n"+
769                 "         }\n"+
770                 "         _this.form.reset();\n"+
771                 "         return;\n"+
772                 "    }\n"+
773                 "}\n",
774             
775             "|rendered" : "function (form)\n"+
776                 "{\n"+
777                 "    _this.form= form;\n"+
778                 "}\n"
779         },
780         method : "POST",
781         style : "margin:10px;",
782         "|url" : "baseURL + '/Roo/" + reader.table + ".php'",
783         items : formElements
784     };
785     
786     
787     File.write(
788         dir + '/' + cfg.DBNAME + '_' + reader.table + '.json',
789             
790        
791         JSON.stringify( frmCfg, null, 4)
792     );
793             
794             
795    
796    
797    
798      /// COMBO..
799     
800     dir = GLib.get_home_dir() + '/.Builder/Roo.form.ComboBox'; 
801     if (!File.isDirectory(dir)) {
802         print("mkdir " + dir);
803         File.mkdir(dir);
804     }
805    
806     print("WRITE: " +  dir + '/' + cfg.DBNAME + '_' + reader.table + '.json');
807     
808     File.write(
809         dir + '/' + cfg.DBNAME + '_' + reader.table + '.json',
810             
811        
812         JSON.stringify(reader.combo, null, 4)
813     );
814             
815    
816    
817    
818    
819    
820     // DIALOG.
821    
822    
823     dir = GLib.get_home_dir() + '/.Builder/Roo.LayoutDialog'; 
824     if (!File.isDirectory(dir)) {
825         print("mkdir " + dir);
826         File.mkdir(dir);
827     }
828     var formElements = [];
829     for (var k in reader.form) {
830         if (k == 'id') { // should really do primary key testing..
831             continue;
832         }
833         formElements.push(reader.form[k]);
834     }
835     formElements.push(reader.form['id']);
836
837     print("WRITE: " +  dir + '/' + cfg.DBNAME + '_' + reader.table + '.json');
838     
839     File.write(
840         dir + '/' + cfg.DBNAME + '_' + reader.table + '.json',
841             
842        
843         JSON.stringify({
844        
845             "closable": false,
846             "collapsible": false,
847             "height": formHeight,
848             "resizable": false,
849             "title": "Edit / Create " + reader.table,
850             "width": 400,
851             "xtype": "LayoutDialog",
852             "|xns": "Roo",
853             "items": [
854                 {
855                     "|xns": "Roo",
856                     "xtype": "LayoutRegion",
857                     "*prop": "center"
858                 },
859                 {
860                     "region": "center",
861                     "xtype": "ContentPanel",
862                     "|xns": "Roo",
863                     "items": [
864                         frmCfg
865                     ]
866                 },
867                 
868                 {
869                     "listeners": {
870                         "click": "function (_self, e)\n{\n    _this.dialog.hide();\n}"
871                     },
872                     "*prop": "buttons[]",
873                     "text": "Cancel",
874                     "xtype": "Button",
875                     "|xns": "Roo"
876                 },
877                 {
878                     "listeners": {
879                         "click": "function (_self, e)\n{\n    // do some checks?\n     \n    \n    _this.dialog.el.mask(\"Saving\");\n    _this.form.doAction(\"submit\");\n\n}"
880                     },
881                     "*prop": "buttons[]",
882                     "text": "Save",
883                     "xtype": "Button",
884                     "|xns": "Roo"
885                 }
886             ]
887         }, null,4)
888     );
889    
890    
891    
892 });
893
894