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 'time' : 'string', //bogus
133 'character' : 'string',
135 'varchar' : 'string',
137 'longtext' : 'string',
138 'tinytext' : 'string',
139 'mediumtext' : 'string',
141 'timestamp' : 'number',
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 )) {
158 var groups = key_file.get_groups();
159 groups.forEach(function(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);
170 if (File.isFile(cfg.INI)) {
171 if (cfg.INI.match(/links\.ini$/)) {
174 readIni(cfg.INI.replace(/\.ini$/, ".links.ini"));
179 if (File.isDirectory(cfg.INI)) {
182 //--- load ini files..
183 // this is very specific.
185 var dirs = File.list( cfg.INI + '/Pman').filter(
187 if (!File.isDirectory(cfg.INI + '/Pman/' + e + '/DataObjects')) {
195 dirs.forEach(function(d) {
196 // this currently misses the web.*/Pman/XXXX/DataObjects..
197 var path = cfg.INI + '/Pman/' + d + '/DataObjects';
199 if (!File.isDirectory(path)) {
202 var inis = File.list(path).filter(
203 function(e) { return e.match(/\.links\.ini$/); }
209 inis.forEach(function(i) {
210 readIni(path + '/' + i);
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$/); }
220 inis.forEach(function(i) {
221 readIni(path + '/' + i);
227 //print(JSON.stringify(ini, null,4));
233 //GLib.key_file_load_from_file (key_file, String file, KeyFileFlags flags) : Boolean
238 query_tables = "SHOW TABLES";
239 query_describe_table = "DESCRIBE `%s`";
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 =
249 "f.attnum AS number, " +
250 "f.attname AS Field, " +
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";
275 "Type": "varchar(255)",
276 "Null": "NO", << or is null
286 var tables = Gda.execute_select_command(cnc, query_tables).fetchAll();
287 print(JSON.stringify(tables));
290 tables.forEach(function(table) {
292 var schema = Gda.execute_select_command(cnc,
293 query_describe_table.replace(/%s/, table).replace(/%n/,'public')
299 var combofields= [ { name : 'id', type: 'int' } ]; // technically the primary key..
303 var firstTxtCol = '';
305 //print(JSON.stringify(schema, null,4)); Seed.quit();
307 schema.forEach(function(e) {
311 var type = e.Type.match(/([^(]+)\(([^\)]+)\)/);
323 if (typeof(map[e.Type]) == 'undefined') {
326 name: "ArgumentError",
327 message: "Unknown mapping for type : " + e.Type
330 row.type = map[e.Type];
332 if (row.type == 'string' && !firstTxtCol.length) {
333 firstTxtCol = row.name;
336 if (row.type == 'date') {
337 row.dateFormat = 'Y-m-d';
341 if (combofields.length == 1 && row.type == 'string') {
342 combofields.push(row);
346 var title = row.name.replace(/_id/, '').replace(/_/g, ' ');
347 title = title[0].toUpperCase() + title.substring(1);
350 "xtype": "ColumnModel",
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
358 "*prop": "colModel[]"
360 var xtype = 'TextField';
363 if (row.type == 'number') {
364 xtype = 'NumberField';
366 if (row.type == 'date') {
369 if (e.Type == 'text') {
372 if (row.name == 'id') {
375 // what about booleans.. -> checkboxes..
382 width : row.type == 'string' ? 200 : 75,
386 if (xtype == 'TextArea') {
387 form[row.name].height = 100;
389 if (xtype == 'Hidden') {
390 delete form[row.name].fieldLabel;
391 delete form[row.name].width;
399 allowBlank : 'false',
401 emptyText : 'Select ' + table,
402 forceSelection : true,
404 loadingText: 'Searching...',
407 qtip: 'Select ' + table,
409 triggerAction : 'all',
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
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
430 '|sortInfo' : '{ direction : \'ASC\', field: \'id\' }',
432 '|beforeload' : 'function (_self, o)' +
434 " o.params = o.params || {};\n" +
435 " // set more here\n" +
441 'xtype' : 'HttpProxy',
444 '|url' : "baseURL + '/Roo/" + table + ".php'",
449 'xtype' : 'JsonReader',
453 'totalProperty' : 'total',
454 '|fields' : JSON.stringify(combofields)
465 //print(JSON.stringify(reader,null,4));
469 combofields : combofields,
471 oreader : JSON.parse(JSON.stringify(reader)), // dupe it..
473 firstTxtCol : firstTxtCol,
477 //console.dump(schema );
484 // merge in the linked tables..
485 readers.forEach(function(reader) {
486 if (typeof(ini[reader.table]) == 'undefined') {
490 print("OVERLAY - " + reader.table);
492 for (var col in ini[reader.table]) {
493 var kv = ini[reader.table][col].split(':');
496 var add = readers.filter(function(r) { return r.table == kv[0] })[0];
500 // merge in data (eg. project_id => project_id_*****
502 add.oreader.forEach(function(or) {
504 name : col + '_' + or.name,
509 // col is mapped to something..
510 var combofields = add.combofields;
511 if (add.combofields.length < 2) {
514 if (typeof(reader.form[col]) == 'undefined') {
515 print (JSON.stringify(reader.form, null,4));
516 print("missing linked column " + col);
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
536 //readers.forEach(function(reader) {
537 // delete reader.oreader;
544 //print(JSON.stringify(readers, null, 4));
546 readers.forEach(function(reader) {
549 var dir = GLib.get_home_dir() + '/.Builder/Roo.data.JsonReader';
550 if (!File.isDirectory(dir)) {
551 print("mkdir " + dir);
556 print("WRITE: " + dir + '/' + cfg.DBNAME + '_' + reader.table + '.json');
561 xtype : "JsonReader",
562 totalProperty : "total",
565 id : 'id', // maybe no..
567 '|fields' : JSON.stringify(reader.reader, null,4).replace(/"/g,"'")
571 dir + '/' + cfg.DBNAME + '_' + reader.table + '.json',
572 JSON.stringify(jreader, null, 4)
577 dir = GLib.get_home_dir() + '/.Builder/Roo.GridPanel';
578 if (!File.isDirectory(dir)) {
579 print("mkdir " + dir);
584 print("WRITE: " + dir + '/' + cfg.DBNAME + '_' + reader.table + '.json');
587 dir + '/' + cfg.DBNAME + '_' + reader.table + '.json',
593 "title": reader.table,
595 "fitContainer": true,
596 "tableName": reader.table,
600 "|activate": "function() {\n _this.panel = this;\n if (_this.grid) {\n _this.grid.footer.onClick('first');\n }\n}"
606 "autoExpandColumn": reader.firstTxtCol,
609 "|render": "function() \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" +
617 "|rowdblclick": "function (_self, rowIndex, e)\n" +
619 " if (!_this.dialog) return;\n" +
620 " _this.dialog.show( this.getDataSource().getAt(rowIndex), function() {\n" +
621 " _this.grid.footer.onClick('first');\n" +
629 "*prop": "dataSource",
632 '|sortInfo' : "{ field : '" + reader.firstTxtCol + "', direction: 'ASC' }",
638 "xtype": "HttpProxy",
640 "|url": "baseURL + '/Roo/" + reader.table + ".php'",
648 "xtype": "PagingToolbar",
651 "displayMsg": "Displaying " + reader.table + "{0} - {1} of {2}",
652 "emptyMsg": "No " + reader.table + " found",
663 "cls": "x-btn-text-icon",
664 "|icon": "Roo.rootURL + 'images/default/dd/drop-add.gif'",
666 "|click": "function()\n"+
668 " if (!_this.dialog) return;\n" +
669 " _this.dialog.show( { id : 0 } , function() {\n"+
670 " _this.grid.footer.onClick('first');\n"+
674 "|xns": "Roo.Toolbar"
679 "cls": "x-btn-text-icon",
680 "|icon": "Roo.rootURL + 'images/default/tree/leaf.gif'",
682 "|click": "function()\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"+
689 " if (!_this.dialog) return;\n" +
690 " _this.dialog.show(s[0].data, function() {\n"+
691 " _this.grid.footer.onClick('first');\n"+
697 "|xns": "Roo.Toolbar"
701 "cls": "x-btn-text-icon",
702 "|icon": "rootURL + '/Pman/templates/images/trash.gif'",
705 "|click": "function()\n"+
707 " Pman.genericDelete(_this, '" + reader.table + "'); \n"+
711 "|xns": "Roo.Toolbar"
715 ].concat( reader.colmodel)
725 dir = GLib.get_home_dir() + '/.Builder/Roo.form.Form';
726 if (!File.isDirectory(dir)) {
727 print("mkdir " + dir);
730 var formElements = [];
732 for (var k in reader.form) {
733 if (k == 'id') { // should really do primary key testing..
736 formHeight += reader.form[k].xtype == 'TextArea' ? 100 : 30;
738 formElements.push(reader.form[k]);
740 if (reader.form['id']) {
741 formElements.push(reader.form['id']);
745 print("WRITE: " + dir + '/' + cfg.DBNAME + '_' + reader.table + '.json');
751 "|actioncomplete" : "function(_self,action)\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"+
758 " if (action.type == 'load') {\n"+
759 " _this.dialog.el.unmask();\n"+
762 " if (action.type =='submit') {\n"+
764 " _this.dialog.el.unmask();\n"+
765 " _this.dialog.hide();\n"+
767 " if (_this.callback) {\n"+
768 " _this.callback.call(_this, _this.form.getValues());\n"+
770 " _this.form.reset();\n"+
775 "|rendered" : "function (form)\n"+
777 " _this.form= form;\n"+
781 style : "margin:10px;",
782 "|url" : "baseURL + '/Roo/" + reader.table + ".php'",
788 dir + '/' + cfg.DBNAME + '_' + reader.table + '.json',
791 JSON.stringify( frmCfg, null, 4)
800 dir = GLib.get_home_dir() + '/.Builder/Roo.form.ComboBox';
801 if (!File.isDirectory(dir)) {
802 print("mkdir " + dir);
806 print("WRITE: " + dir + '/' + cfg.DBNAME + '_' + reader.table + '.json');
809 dir + '/' + cfg.DBNAME + '_' + reader.table + '.json',
812 JSON.stringify(reader.combo, null, 4)
823 dir = GLib.get_home_dir() + '/.Builder/Roo.LayoutDialog';
824 if (!File.isDirectory(dir)) {
825 print("mkdir " + dir);
828 var formElements = [];
829 for (var k in reader.form) {
830 if (k == 'id') { // should really do primary key testing..
833 formElements.push(reader.form[k]);
835 formElements.push(reader.form['id']);
837 print("WRITE: " + dir + '/' + cfg.DBNAME + '_' + reader.table + '.json');
840 dir + '/' + cfg.DBNAME + '_' + reader.table + '.json',
846 "collapsible": false,
847 "height": formHeight,
849 "title": "Edit / Create " + reader.table,
851 "xtype": "LayoutDialog",
856 "xtype": "LayoutRegion",
861 "xtype": "ContentPanel",
870 "click": "function (_self, e)\n{\n _this.dialog.hide();\n}"
872 "*prop": "buttons[]",
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}"
881 "*prop": "buttons[]",