1 //<script type="text/javascript">
4 * This is a hacky generator to generate element definitions for the Roo version from the database
6 * Let's see if libgda can be used to generate our Readers for roo...
8 * Concept - conect to database..
16 * usage: seed generate.js
21 *Hack needed to latest GLib-2.0.gir
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*"/>
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*
38 GObject = imports.gi.GObject;
40 GLib = imports.gi.GLib;
42 console = imports.console;
43 File = imports.File.File;
44 Options = imports.Options.Options;
48 var prov = Gda.Config.list_providers ();
49 //print(prov.dump_as_string());
52 help_description : 'Element builder for App Builder based on database schema',
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.' },
67 var cfg = o.parse(Seed.argv);
68 print(JSON.stringify(cfg, null,4));
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);
80 Gda.DataSelect.prototype.fetchAll = function()
84 for (var i =0;i < this.get_n_columns(); i++) {
85 cols.push(this.get_column_name(i));
87 //print(JSON.stringify(cols, null,4));
88 var iter = this.create_iter();
90 //print(this.get_n_rows());
92 for (var r = 0; r < this.get_n_rows(); r++) {
96 if (cols.length == 1) {
97 res.push(this.get_value_at(0,r).get_string());
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);
121 'timestamp with time zone' : 'date',
122 'timestamp without time zone' : 'date',
123 'time' : 'string', //bogus
134 'character' : 'string',
135 'character varying' : 'string',
136 'varchar' : 'string',
138 'longtext' : 'string',
139 'tinytext' : 'string',
140 'mediumtext' : 'string',
142 'timestamp' : 'number',
153 print('Read INI : ' + fn);
154 var key_file = new GLib.KeyFile.c_new();
155 if (!key_file.load_from_file (fn , GLib.KeyFileFlags.NONE )) {
159 var groups = key_file.get_groups();
160 groups.forEach(function(g) {
163 var keys = key_file.get_keys(g);
164 if (!keys) { return; }
165 keys.forEach(function(k) {
166 ini[g][k] = key_file.get_value(g,k);
171 if (File.isFile(cfg.INI)) {
172 if (cfg.INI.match(/links\.ini$/)) {
175 readIni(cfg.INI.replace(/\.ini$/, ".links.ini"));
180 if (File.isDirectory(cfg.INI)) {
183 //--- load ini files..
184 // this is very specific.
186 var dirs = File.list( cfg.INI + '/Pman').filter(
188 if (!File.isDirectory(cfg.INI + '/Pman/' + e + '/DataObjects')) {
196 dirs.forEach(function(d) {
197 // this currently misses the web.*/Pman/XXXX/DataObjects..
198 var path = cfg.INI + '/Pman/' + d + '/DataObjects';
200 if (!File.isDirectory(path)) {
203 var inis = File.list(path).filter(
204 function(e) { return e.match(/\.links\.ini$/); }
210 inis.forEach(function(i) {
211 readIni(path + '/' + i);
216 // look at web.XXXX/Pman/XXX/DataObjects/*.ini
217 var inis = File.list(cfg.INI).filter(
218 function(e) { return e.match(/\.links\.ini$/); }
221 inis.forEach(function(i) {
222 readIni(path + '/' + i);
228 //print(JSON.stringify(ini, null,4));
234 //GLib.key_file_load_from_file (key_file, String file, KeyFileFlags flags) : Boolean
239 query_tables = "SHOW TABLES";
240 query_describe_table = "DESCRIBE `%s`";
244 query_tables = "select c.relname FROM pg_catalog.pg_class c " +
245 "LEFT JOIN pg_catalog.pg_namespace n ON n.oid = c.relnamespace " +
246 "WHERE c.relkind IN ('r','') AND n.nspname NOT IN ('pg_catalog', 'pg_toast')" +
247 "AND pg_catalog.pg_table_is_visible(c.oid) ";
248 query_describe_table =
250 "f.attnum AS number, " +
251 "f.attname AS Field, " +
253 "CASE WHEN f.attnotnull = 't' THEN 'NO' ELSE 'YES' END AS isNull, " +
254 "pg_catalog.format_type(f.atttypid,f.atttypmod) AS Type, " +
255 "CASE WHEN p.contype = 'p' THEN 't' ELSE 'f' END AS primarykey, " +
256 "CASE WHEN p.contype = 'u' THEN 't' ELSE 'f' END AS uniquekey, " +
257 "CASE WHEN p.contype = 'f' THEN g.relname END AS foreignkey, " +
258 "CASE WHEN p.contype = 'f' THEN p.confkey END AS foreignkey_fieldnum, " +
259 "CASE WHEN p.contype = 'f' THEN g.relname END AS foreignkey, " +
260 "CASE WHEN p.contype = 'f' THEN p.conkey END AS foreignkey_connnum, " +
261 "CASE WHEN f.atthasdef = 't' THEN d.adsrc END AS default " +
262 "FROM pg_attribute f JOIN pg_class c ON c.oid = f.attrelid " +
263 " JOIN pg_type t ON t.oid = f.atttypid " +
264 " LEFT JOIN pg_attrdef d ON d.adrelid = c.oid AND d.adnum = f.attnum " +
265 " LEFT JOIN pg_namespace n ON n.oid = c.relnamespace " +
266 " LEFT JOIN pg_constraint p ON p.conrelid = c.oid AND f.attnum = ANY ( p.conkey ) " +
267 " LEFT JOIN pg_class AS g ON p.confrelid = g.oid " +
268 "WHERE c.relkind = 'r'::char AND n.nspname = '%n' " +
269 "AND c.relname = '%s' AND f.attnum > 0 ORDER BY number";
276 "Type": "varchar(255)",
277 "Null": "NO", << or is null
287 var tables = Gda.execute_select_command(cnc, query_tables).fetchAll();
288 print(JSON.stringify(tables));
291 tables.forEach(function(table) {
293 var schema = Gda.execute_select_command(cnc,
294 query_describe_table.replace(/%s/, table).replace(/%n/,'public')
300 var combofields= [ { name : 'id', type: 'int' } ]; // technically the primary key..
304 var firstTxtCol = '';
306 //print(JSON.stringify(schema, null,4)); Seed.quit();
308 schema.forEach(function(e) {
312 var type = e.Type.match(/([^(]+)\(([^\)]+)\)/);
324 if (typeof(map[e.Type]) == 'undefined') {
327 name: "ArgumentError",
328 message: "Unknown mapping for type : " + e.Type
331 row.type = map[e.Type];
333 if (row.type == 'string' && !firstTxtCol.length) {
334 firstTxtCol = row.name;
337 if (row.type == 'date') {
338 row.dateFormat = 'Y-m-d';
342 if (combofields.length == 1 && row.type == 'string') {
343 combofields.push(row);
347 var title = row.name.replace(/_id/, '').replace(/_/g, ' ');
348 title = title[0].toUpperCase() + title.substring(1);
351 "xtype": "ColumnModel",
353 "width": row.type == 'string' ? 200 : 75,
354 "dataIndex": row.name,
355 "|renderer": row.type != 'date' ?
356 "function(v) { return String.format('{0}', v); }" :
357 "function(v) { return String.format('{0}', v ? v.format('d/M/Y') : ''); }" , // special for date
359 "*prop": "colModel[]"
361 var xtype = 'TextField';
364 if (row.type == 'number') {
365 xtype = 'NumberField';
367 if (row.type == 'date') {
370 if (e.Type == 'text') {
373 if (row.name == 'id') {
376 // what about booleans.. -> checkboxes..
383 width : row.type == 'string' ? 200 : 75,
387 if (xtype == 'TextArea') {
388 form[row.name].height = 100;
390 if (xtype == 'Hidden') {
391 delete form[row.name].fieldLabel;
392 delete form[row.name].width;
400 allowBlank : 'false',
402 emptyText : 'Select ' + table,
403 forceSelection : true,
405 loadingText: 'Searching...',
408 qtip: 'Select ' + table,
410 triggerAction : 'all',
417 tpl : '<div class="x-grid-cell-text x-btn button"><b>{name}</b> </div>', // SET WHEN USED
418 queryParam : '',// SET WHEN USED
419 fieldLabel : table, // SET WHEN USED
421 displayField : '', // SET WHEN USED eg. project_id_name
422 hiddenName : '', // SET WHEN USED eg. project_id
423 name : '', // SET WHEN USED eg. project_id_name
431 '|sortInfo' : '{ direction : \'ASC\', field: \'id\' }',
433 '|beforeload' : 'function (_self, o)' +
435 " o.params = o.params || {};\n" +
436 " // set more here\n" +
442 'xtype' : 'HttpProxy',
445 '|url' : "baseURL + '/Roo/" + table + ".php'",
450 'xtype' : 'JsonReader',
454 'totalProperty' : 'total',
455 '|fields' : JSON.stringify(combofields)
466 //print(JSON.stringify(reader,null,4));
470 combofields : combofields,
472 oreader : JSON.parse(JSON.stringify(reader)), // dupe it..
474 firstTxtCol : firstTxtCol,
478 //console.dump(schema );
485 // merge in the linked tables..
486 readers.forEach(function(reader) {
487 if (typeof(ini[reader.table]) == 'undefined') {
491 print("OVERLAY - " + reader.table);
493 for (var col in ini[reader.table]) {
494 var kv = ini[reader.table][col].split(':');
497 var add = readers.filter(function(r) { return r.table == kv[0] })[0];
501 // merge in data (eg. project_id => project_id_*****
503 add.oreader.forEach(function(or) {
505 name : col + '_' + or.name,
510 // col is mapped to something..
511 var combofields = add.combofields;
512 if (add.combofields.length < 2) {
515 if (typeof(reader.form[col]) == 'undefined') {
516 print (JSON.stringify(reader.form, null,4));
517 print("missing linked column " + col);
521 var combofields_name = add.combofields[1].name;
522 var old = reader.form[col];
523 reader.form[col] = JSON.parse(JSON.stringify(add.combo)); // clone
524 reader.form[col].queryParam = 'query[' + combofields_name + ']';// SET WHEN USED
525 reader.form[col].fieldLabel = old.fieldLabel; // SET WHEN USED
526 reader.form[col].hiddenName = old.name; // SET WHEN USED eg. project_id
527 reader.form[col].displayField = combofields_name; // SET WHEN USED eg. project_id
528 reader.form[col].name = old.name + '_' + combofields_name; // SET WHEN USED eg. project_id_name
529 reader.form[col].tpl = '<div class="x-grid-cell-text x-btn button"><b>{' + combofields_name +'}</b> </div>'; // SET WHEN USED
537 //readers.forEach(function(reader) {
538 // delete reader.oreader;
545 //print(JSON.stringify(readers, null, 4));
547 readers.forEach(function(reader) {
550 var dir = GLib.get_home_dir() + '/.Builder/Roo.data.JsonReader';
551 if (!File.isDirectory(dir)) {
552 print("mkdir " + dir);
557 print("WRITE: " + dir + '/' + cfg.DBNAME + '_' + reader.table + '.json');
562 xtype : "JsonReader",
563 totalProperty : "total",
566 id : 'id', // maybe no..
568 '|fields' : JSON.stringify(reader.reader, null,4).replace(/"/g,"'")
572 dir + '/' + cfg.DBNAME + '_' + reader.table + '.json',
573 JSON.stringify(jreader, null, 4)
578 dir = GLib.get_home_dir() + '/.Builder/Roo.GridPanel';
579 if (!File.isDirectory(dir)) {
580 print("mkdir " + dir);
585 print("WRITE: " + dir + '/' + cfg.DBNAME + '_' + reader.table + '.json');
588 dir + '/' + cfg.DBNAME + '_' + reader.table + '.json',
594 "title": reader.table,
596 "fitContainer": true,
597 "tableName": reader.table,
601 "|activate": "function() {\n _this.panel = this;\n if (_this.grid) {\n _this.grid.footer.onClick('first');\n }\n}"
607 "autoExpandColumn": reader.firstTxtCol,
610 "|render": "function() \n" +
612 " _this.grid = this; \n" +
613 " //_this.dialog = Pman.Dialog.FILL_IN\n" +
614 " if (_this.panel.active) {\n" +
615 " this.footer.onClick('first');\n" +
618 "|rowdblclick": "function (_self, rowIndex, e)\n" +
620 " if (!_this.dialog) return;\n" +
621 " _this.dialog.show( this.getDataSource().getAt(rowIndex), function() {\n" +
622 " _this.grid.footer.onClick('first');\n" +
630 "*prop": "dataSource",
633 '|sortInfo' : "{ field : '" + reader.firstTxtCol + "', direction: 'ASC' }",
639 "xtype": "HttpProxy",
641 "|url": "baseURL + '/Roo/" + reader.table + ".php'",
649 "xtype": "PagingToolbar",
652 "displayMsg": "Displaying " + reader.table + "{0} - {1} of {2}",
653 "emptyMsg": "No " + reader.table + " found",
664 "cls": "x-btn-text-icon",
665 "|icon": "Roo.rootURL + 'images/default/dd/drop-add.gif'",
667 "|click": "function()\n"+
669 " if (!_this.dialog) return;\n" +
670 " _this.dialog.show( { id : 0 } , function() {\n"+
671 " _this.grid.footer.onClick('first');\n"+
675 "|xns": "Roo.Toolbar"
680 "cls": "x-btn-text-icon",
681 "|icon": "Roo.rootURL + 'images/default/tree/leaf.gif'",
683 "|click": "function()\n"+
685 " var s = _this.grid.getSelectionModel().getSelections();\n"+
686 " if (!s.length || (s.length > 1)) {\n"+
687 " Roo.MessageBox.alert(\"Error\", s.length ? \"Select only one Row\" : \"Select a Row\");\n"+
690 " if (!_this.dialog) return;\n" +
691 " _this.dialog.show(s[0].data, function() {\n"+
692 " _this.grid.footer.onClick('first');\n"+
698 "|xns": "Roo.Toolbar"
702 "cls": "x-btn-text-icon",
703 "|icon": "rootURL + '/Pman/templates/images/trash.gif'",
706 "|click": "function()\n"+
708 " Pman.genericDelete(_this, '" + reader.table + "'); \n"+
712 "|xns": "Roo.Toolbar"
716 ].concat( reader.colmodel)
726 dir = GLib.get_home_dir() + '/.Builder/Roo.form.Form';
727 if (!File.isDirectory(dir)) {
728 print("mkdir " + dir);
731 var formElements = [];
733 for (var k in reader.form) {
734 if (k == 'id') { // should really do primary key testing..
737 formHeight += reader.form[k].xtype == 'TextArea' ? 100 : 30;
739 formElements.push(reader.form[k]);
741 if (reader.form['id']) {
742 formElements.push(reader.form['id']);
746 print("WRITE: " + dir + '/' + cfg.DBNAME + '_' + reader.table + '.json');
752 "|actioncomplete" : "function(_self,action)\n"+
754 " if (action.type == 'setdata') {\n"+
755 " //_this.dialog.el.mask(\"Loading\");\n"+
756 " //this.load({ method: 'GET', params: { '_id' : _this.data.id }});\n"+
759 " if (action.type == 'load') {\n"+
760 " _this.dialog.el.unmask();\n"+
763 " if (action.type =='submit') {\n"+
765 " _this.dialog.el.unmask();\n"+
766 " _this.dialog.hide();\n"+
768 " if (_this.callback) {\n"+
769 " _this.callback.call(_this, _this.form.getValues());\n"+
771 " _this.form.reset();\n"+
776 "|rendered" : "function (form)\n"+
778 " _this.form= form;\n"+
782 style : "margin:10px;",
783 "|url" : "baseURL + '/Roo/" + reader.table + ".php'",
789 dir + '/' + cfg.DBNAME + '_' + reader.table + '.json',
792 JSON.stringify( frmCfg, null, 4)
801 dir = GLib.get_home_dir() + '/.Builder/Roo.form.ComboBox';
802 if (!File.isDirectory(dir)) {
803 print("mkdir " + dir);
807 print("WRITE: " + dir + '/' + cfg.DBNAME + '_' + reader.table + '.json');
810 dir + '/' + cfg.DBNAME + '_' + reader.table + '.json',
813 JSON.stringify(reader.combo, null, 4)
824 dir = GLib.get_home_dir() + '/.Builder/Roo.LayoutDialog';
825 if (!File.isDirectory(dir)) {
826 print("mkdir " + dir);
829 var formElements = [];
830 for (var k in reader.form) {
831 if (k == 'id') { // should really do primary key testing..
834 formElements.push(reader.form[k]);
836 formElements.push(reader.form['id']);
838 print("WRITE: " + dir + '/' + cfg.DBNAME + '_' + reader.table + '.json');
841 dir + '/' + cfg.DBNAME + '_' + reader.table + '.json',
847 "collapsible": false,
848 "height": formHeight,
850 "title": "Edit / Create " + reader.table,
852 "xtype": "LayoutDialog",
857 "xtype": "LayoutRegion",
862 "xtype": "ContentPanel",
871 "click": "function (_self, e)\n{\n _this.dialog.hide();\n}"
873 "*prop": "buttons[]",
880 "click": "function (_self, e)\n{\n // do some checks?\n \n \n _this.dialog.el.mask(\"Saving\");\n _this.form.doAction(\"submit\");\n\n}"
882 "*prop": "buttons[]",