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',
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 )) {
160 var groups = key_file.get_groups();
161 groups.forEach(function(g) {
164 var keys = key_file.get_keys(g);
165 if (!keys) { return; }
166 keys.forEach(function(k) {
167 ini[g][k] = key_file.get_value(g,k);
172 if (File.isFile(cfg.INI)) {
173 if (cfg.INI.match(/links\.ini$/)) {
176 readIni(cfg.INI.replace(/\.ini$/, ".links.ini"));
181 if (File.isDirectory(cfg.INI)) {
184 //--- load ini files..
185 // this is very specific.
187 var dirs = File.list( cfg.INI + '/Pman').filter(
189 if (!File.isDirectory(cfg.INI + '/Pman/' + e + '/DataObjects')) {
197 dirs.forEach(function(d) {
198 // this currently misses the web.*/Pman/XXXX/DataObjects..
199 var path = cfg.INI + '/Pman/' + d + '/DataObjects';
201 if (!File.isDirectory(path)) {
204 var inis = File.list(path).filter(
205 function(e) { return e.match(/\.links\.ini$/); }
211 inis.forEach(function(i) {
212 readIni(path + '/' + i);
217 // look at web.XXXX/Pman/XXX/DataObjects/*.ini
218 var inis = File.list(cfg.INI).filter(
219 function(e) { return e.match(/\.links\.ini$/); }
222 inis.forEach(function(i) {
223 readIni(path + '/' + i);
229 //print(JSON.stringify(ini, null,4));
235 //GLib.key_file_load_from_file (key_file, String file, KeyFileFlags flags) : Boolean
240 query_tables = "SHOW TABLES";
241 query_describe_table = "DESCRIBE `%s`";
245 query_tables = "select c.relname FROM pg_catalog.pg_class c " +
246 "LEFT JOIN pg_catalog.pg_namespace n ON n.oid = c.relnamespace " +
247 "WHERE c.relkind IN ('r','') AND n.nspname NOT IN ('pg_catalog', 'pg_toast')" +
248 "AND pg_catalog.pg_table_is_visible(c.oid) ";
249 query_describe_table =
251 "f.attnum AS number, " +
252 "f.attname AS Field, " +
254 "CASE WHEN f.attnotnull = 't' THEN 'NO' ELSE 'YES' END AS isNull, " +
255 "pg_catalog.format_type(f.atttypid,f.atttypmod) AS Type, " +
256 "CASE WHEN p.contype = 'p' THEN 't' ELSE 'f' END AS primarykey, " +
257 "CASE WHEN p.contype = 'u' THEN 't' ELSE 'f' END AS uniquekey, " +
258 "CASE WHEN p.contype = 'f' THEN g.relname END AS foreignkey, " +
259 "CASE WHEN p.contype = 'f' THEN p.confkey END AS foreignkey_fieldnum, " +
260 "CASE WHEN p.contype = 'f' THEN g.relname END AS foreignkey, " +
261 "CASE WHEN p.contype = 'f' THEN p.conkey END AS foreignkey_connnum, " +
262 "CASE WHEN f.atthasdef = 't' THEN d.adsrc END AS default " +
263 "FROM pg_attribute f JOIN pg_class c ON c.oid = f.attrelid " +
264 " JOIN pg_type t ON t.oid = f.atttypid " +
265 " LEFT JOIN pg_attrdef d ON d.adrelid = c.oid AND d.adnum = f.attnum " +
266 " LEFT JOIN pg_namespace n ON n.oid = c.relnamespace " +
267 " LEFT JOIN pg_constraint p ON p.conrelid = c.oid AND f.attnum = ANY ( p.conkey ) " +
268 " LEFT JOIN pg_class AS g ON p.confrelid = g.oid " +
269 "WHERE c.relkind = 'r'::char AND n.nspname = '%n' " +
270 "AND c.relname = '%s' AND f.attnum > 0 ORDER BY number";
276 throw new Exception("Invalid data base type " + cfg.DBTYPE + " should be MySQL or PostgreSQL";
280 "Type": "varchar(255)",
281 "Null": "NO", << or is null
291 var tables = Gda.execute_select_command(cnc, query_tables).fetchAll();
292 print(JSON.stringify(tables));
295 tables.forEach(function(table) {
297 var schema = Gda.execute_select_command(cnc,
298 query_describe_table.replace(/%s/, table).replace(/%n/,'public')
304 var combofields= [ { name : 'id', type: 'int' } ]; // technically the primary key..
308 var firstTxtCol = '';
310 //print(JSON.stringify(schema, null,4)); Seed.quit();
312 schema.forEach(function(e) {
316 var type = e.Type.match(/([^(]+)\(([^\)]+)\)/);
328 if (typeof(map[e.Type]) == 'undefined') {
331 name: "ArgumentError",
332 message: "Unknown mapping for type : " + e.Type
335 row.type = map[e.Type];
337 if (row.type == 'string' && !firstTxtCol.length) {
338 firstTxtCol = row.name;
341 if (row.type == 'date') {
342 row.dateFormat = 'Y-m-d';
346 if (combofields.length == 1 && row.type == 'string') {
347 combofields.push(row);
351 var title = row.name.replace(/_id/, '').replace(/_/g, ' ');
352 title = title[0].toUpperCase() + title.substring(1);
355 "xtype": "ColumnModel",
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
363 "*prop": "colModel[]"
365 var xtype = 'TextField';
368 if (row.type == 'number') {
369 xtype = 'NumberField';
371 if (row.type == 'date') {
374 if (e.Type == 'text') {
377 if (row.name == 'id') {
380 // what about booleans.. -> checkboxes..
387 width : row.type == 'string' ? 200 : 75,
391 if (xtype == 'DateField') {
392 form[row.name].format = 'Y-m-d';
393 form[row.name].width = 100;
396 if (xtype == 'TextArea') {
397 form[row.name].height = 100;
399 if (xtype == 'Hidden') {
400 delete form[row.name].fieldLabel;
401 delete form[row.name].width;
411 emptyText : 'Select ' + table,
412 forceSelection : true,
414 loadingText: 'Searching...',
417 qtip: 'Select ' + table,
419 triggerAction : 'all',
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
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
440 '|sortInfo' : '{ direction : \'ASC\', field: \'id\' }',
442 '|beforeload' : 'function (_self, o)' +
444 " o.params = o.params || {};\n" +
445 " // set more here\n" +
451 'xtype' : 'HttpProxy',
454 '|url' : "baseURL + '/Roo/" + table + ".php'",
459 'xtype' : 'JsonReader',
463 'totalProperty' : 'total',
464 '|fields' : JSON.stringify(combofields)
475 //print(JSON.stringify(reader,null,4));
479 combofields : combofields,
481 oreader : JSON.parse(JSON.stringify(reader)), // dupe it..
483 firstTxtCol : firstTxtCol,
487 //console.dump(schema );
494 // merge in the linked tables..
495 readers.forEach(function(reader) {
496 if (typeof(ini[reader.table]) == 'undefined') {
500 print("OVERLAY - " + reader.table);
502 for (var col in ini[reader.table]) {
503 var kv = ini[reader.table][col].split(':');
506 var add = readers.filter(function(r) { return r.table == kv[0] })[0];
510 // merge in data (eg. project_id => project_id_*****
512 add.oreader.forEach(function(or) {
514 name : col + '_' + or.name,
519 // col is mapped to something..
520 var combofields = add.combofields;
521 if (add.combofields.length < 2) {
524 if (typeof(reader.form[col]) == 'undefined') {
525 print (JSON.stringify(reader.form, null,4));
526 print("missing linked column " + col);
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
546 //readers.forEach(function(reader) {
547 // delete reader.oreader;
554 //print(JSON.stringify(readers, null, 4));
556 readers.forEach(function(reader) {
559 var dir = GLib.get_home_dir() + '/.Builder/Roo.data.JsonReader';
560 if (!File.isDirectory(dir)) {
561 print("mkdir " + dir);
566 print("WRITE: " + dir + '/' + cfg.DBNAME + '_' + reader.table + '.json');
571 xtype : "JsonReader",
572 totalProperty : "total",
575 id : 'id', // maybe no..
577 '|fields' : JSON.stringify(reader.reader, null,4).replace(/"/g,"'")
581 dir + '/' + cfg.DBNAME + '_' + reader.table + '.json',
582 JSON.stringify(jreader, null, 4)
587 dir = GLib.get_home_dir() + '/.Builder/Roo.GridPanel';
588 if (!File.isDirectory(dir)) {
589 print("mkdir " + dir);
594 print("WRITE: " + dir + '/' + cfg.DBNAME + '_' + reader.table + '.json');
597 dir + '/' + cfg.DBNAME + '_' + reader.table + '.json',
603 "title": reader.table,
605 "fitContainer": true,
606 "tableName": reader.table,
610 "|activate": "function() {\n _this.panel = this;\n if (_this.grid) {\n _this.grid.footer.onClick('first');\n }\n}"
616 "autoExpandColumn": reader.firstTxtCol,
619 "|render": "function() \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" +
627 "|rowdblclick": "function (_self, rowIndex, e)\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" +
639 "*prop": "dataSource",
642 '|sortInfo' : "{ field : '" + reader.firstTxtCol + "', direction: 'ASC' }",
648 "xtype": "HttpProxy",
650 "|url": "baseURL + '/Roo/" + reader.table + ".php'",
658 "xtype": "PagingToolbar",
661 "displayMsg": "Displaying " + reader.table + "{0} - {1} of {2}",
662 "emptyMsg": "No " + reader.table + " found",
673 "cls": "x-btn-text-icon",
674 "|icon": "Roo.rootURL + 'images/default/dd/drop-add.gif'",
676 "|click": "function()\n"+
678 " if (!_this.dialog) return;\n" +
679 " _this.dialog.show( { id : 0 } , function() {\n"+
680 " _this.grid.footer.onClick('first');\n"+
684 "|xns": "Roo.Toolbar"
689 "cls": "x-btn-text-icon",
690 "|icon": "Roo.rootURL + 'images/default/tree/leaf.gif'",
692 "|click": "function()\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"+
699 " if (!_this.dialog) return;\n" +
700 " _this.dialog.show(s[0].data, function() {\n"+
701 " _this.grid.footer.onClick('first');\n"+
707 "|xns": "Roo.Toolbar"
711 "cls": "x-btn-text-icon",
712 "|icon": "rootURL + '/Pman/templates/images/trash.gif'",
715 "|click": "function()\n"+
717 " Pman.genericDelete(_this, '" + reader.table + "'); \n"+
721 "|xns": "Roo.Toolbar"
725 ].concat( reader.colmodel)
735 dir = GLib.get_home_dir() + '/.Builder/Roo.form.Form';
736 if (!File.isDirectory(dir)) {
737 print("mkdir " + dir);
740 var formElements = [];
742 for (var k in reader.form) {
743 if (k == 'id') { // should really do primary key testing..
746 formHeight += reader.form[k].xtype == 'TextArea' ? 100 : 30;
748 formElements.push(reader.form[k]);
750 if (reader.form['id']) {
751 formElements.push(reader.form['id']);
755 print("WRITE: " + dir + '/' + cfg.DBNAME + '_' + reader.table + '.json');
761 "|actioncomplete" : "function(_self,action)\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"+
768 " if (action.type == 'load') {\n"+
769 " _this.dialog.el.unmask();\n"+
772 " if (action.type =='submit') {\n"+
774 " _this.dialog.el.unmask();\n"+
775 " _this.dialog.hide();\n"+
777 " if (_this.callback) {\n"+
778 " _this.callback.call(_this, _this.form.getValues());\n"+
780 " _this.form.reset();\n"+
785 "|rendered" : "function (form)\n"+
787 " _this.form= form;\n"+
791 style : "margin:10px;",
792 "|url" : "baseURL + '/Roo/" + reader.table + ".php'",
798 dir + '/' + cfg.DBNAME + '_' + reader.table + '.json',
801 JSON.stringify( frmCfg, null, 4)
810 dir = GLib.get_home_dir() + '/.Builder/Roo.form.ComboBox';
811 if (!File.isDirectory(dir)) {
812 print("mkdir " + dir);
816 print("WRITE: " + dir + '/' + cfg.DBNAME + '_' + reader.table + '.json');
819 dir + '/' + cfg.DBNAME + '_' + reader.table + '.json',
822 JSON.stringify(reader.combo, null, 4)
833 dir = GLib.get_home_dir() + '/.Builder/Roo.LayoutDialog';
834 if (!File.isDirectory(dir)) {
835 print("mkdir " + dir);
838 var formElements = [];
839 for (var k in reader.form) {
840 if (k == 'id') { // should really do primary key testing..
843 formElements.push(reader.form[k]);
845 formElements.push(reader.form['id']);
847 print("WRITE: " + dir + '/' + cfg.DBNAME + '_' + reader.table + '.json');
850 dir + '/' + cfg.DBNAME + '_' + reader.table + '.json',
856 "collapsible": false,
857 "height": formHeight,
859 "title": "Edit / Create " + reader.table,
862 "xtype": "LayoutDialog",
867 "xtype": "LayoutRegion",
872 "xtype": "ContentPanel",
881 "click": "function (_self, e)\n{\n _this.dialog.hide();\n}"
883 "*prop": "buttons[]",
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}"
892 "*prop": "buttons[]",