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