planner-sql-plugin.c 31.8 KB
Newer Older
Richard Hult's avatar
Richard Hult committed
1 2
/* -*- Mode: C; tab-width: 8; indent-tabs-mode: t; c-basic-offset: 8 -*- */
/*
Richard Hult's avatar
Richard Hult committed
3
 * Copyright (C) 2003-2004 Imendio HB
Richard Hult's avatar
Richard Hult committed
4 5 6
 * Copyright (C) 2003 CodeFactory AB
 * Copyright (C) 2003 Richard Hult <richard@imendio.com>
 * Copyright (C) 2003 Mikael Hallendal <micke@imendio.com>
7
 * Copyright (C) 2003 Alvaro del Castillo <acs@barrapunto.com>
Richard Hult's avatar
Richard Hult committed
8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32
 *
 * This program is free software; you can redistribute it and/or
 * modify it under the terms of the GNU General Public License as
 * published by the Free Software Foundation; either version 2 of the
 * License, or (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 * General Public License for more details.
 *
 * You should have received a copy of the GNU General Public
 * License along with this program; if not, write to the
 * Free Software Foundation, Inc., 59 Temple Place - Suite 330,
 * Boston, MA 02111-1307, USA.
 */
#include <config.h>
#include <math.h>
#include <string.h>
#include <stdlib.h>
#include <glib.h>
#include <libgnome/gnome-i18n.h>
#include <libgnomeui/gnome-entry.h>
#include <glade/glade.h>
#include <gtk/gtk.h>
33
#include <libgda/libgda.h>
Richard Hult's avatar
Richard Hult committed
34
#include "planner-window.h"
Richard Hult's avatar
Richard Hult committed
35
#include "planner-application.h"
Richard Hult's avatar
Richard Hult committed
36 37 38 39 40 41 42 43 44 45 46
#include "planner-plugin.h"

#define d(x)

#define SERVER     "sql-plugin-server"
#define DATABASE   "sql-plugin-database"
#define REVISION   "sql-plugin-revision"
#define LOGIN      "sql-plugin-login"
#define PASSWORD   "sql-plugin-password"
#define PROJECT_ID "sql-plugin-project-id"

Richard Hult's avatar
Richard Hult committed
47
#define GCONF_PATH "/apps/planner/plugins/sql"
Richard Hult's avatar
Richard Hult committed
48

49 50
#define STOP_ON_ERR GDA_COMMAND_OPTION_STOP_ON_ERRORS

Richard Hult's avatar
Richard Hult committed
51 52 53 54
typedef struct {
	GtkWidget *open_dialog;
} SQLPluginPriv; 

55
static gint     sql_plugin_retrieve_project_id (PlannerPlugin      *plugin,
Richard Hult's avatar
Richard Hult committed
56 57 58 59 60
						gchar              *server,
						gchar              *port,
						gchar              *database,
						gchar              *login,
						gchar              *password);
61
static gboolean sql_plugin_retrieve_db_values  (PlannerPlugin      *plugin,
Richard Hult's avatar
Richard Hult committed
62 63 64 65 66 67
						const gchar        *title,
						gchar             **server,
						gchar             **port,
						gchar             **db,
						gchar             **user,
						gchar             **password);
68 69 70 71
static void     sql_plugin_open                (GtkAction          *action,
						gpointer            user_data);
static void     sql_plugin_save                (GtkAction          *action,
						gpointer            user_data);
72 73 74
static GdaDataModel * 
                sql_execute_query              (GdaConnection      *con, 
					        gchar              *query);
75 76 77 78

/* FIXME: The same in mrp-sql.c. Create a SQL API in libplanner? */ 
static const gchar * sql_get_last_error        (GdaConnection      *connection);

79 80
void            plugin_init                    (PlannerPlugin      *plugin,
						PlannerWindow      *main_window);
Richard Hult's avatar
Richard Hult committed
81 82 83 84 85 86
void            plugin_exit                    (void);



enum {
	COL_ID,
87 88 89
	COL_NAME,
	COL_PHASE,
	COL_REVISION
Richard Hult's avatar
Richard Hult committed
90 91
};

92
static GtkActionEntry entries[] = {
Richard Hult's avatar
Richard Hult committed
93 94
	{ "Open",  NULL,  N_("Open from Database..."), NULL, N_("Open a project from a database"), G_CALLBACK (sql_plugin_open) },
	{ "Save",  NULL,  N_("Save to Database"), NULL, N_("Save the current project to a database"), G_CALLBACK (sql_plugin_save) },
Richard Hult's avatar
Richard Hult committed
95 96
};

Richard Hult's avatar
Richard Hult committed
97
static guint n_entries = G_N_ELEMENTS (entries);
98

99 100 101 102 103 104 105 106 107 108 109 110 111

/**
 * Helper to execute a SQL query using GDA
 */
static GdaDataModel *
sql_execute_query (GdaConnection *con, gchar *query)
{
	GdaCommand   *cmd;
	GdaDataModel *res;

	cmd = gda_command_new (query, GDA_COMMAND_TYPE_SQL, STOP_ON_ERR);
	res = gda_connection_execute_single_command  (con, cmd, NULL);
	gda_command_free (cmd);
Richard Hult's avatar
Richard Hult committed
112
	
113 114 115
	return res;
}

116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136
static const gchar *
sql_get_last_error (GdaConnection *connection)
{
	GList       *list;
	GdaError    *error;
	const gchar *error_txt;

	list = (GList *) gda_connection_get_errors (connection);

	if (list == NULL) {
		return _("No errors reported.");
	}

	error = (GdaError *) g_list_last (list)->data;
      
	/* FIXME: Poor user, she won't get localized messages */
	error_txt = gda_error_get_description (error);

	return error_txt;
}

137

Richard Hult's avatar
Richard Hult committed
138 139 140 141
/**
 * Helper to get an int.
 */
static gint
142
get_int (GdaDataModel *res, gint row, gint column)
Richard Hult's avatar
Richard Hult committed
143
{
Richard Hult's avatar
Richard Hult committed
144 145 146
	gchar    *str;
	GdaValue *value;
	gint      i;
147 148 149 150 151 152 153 154

	value = (GdaValue *) gda_data_model_get_value_at (res, column, row);
	if (value == NULL) {
		g_warning ("Failed to get a value: (%d,%d)", column, row);
		return INT_MAX;
	}
	
	str = gda_value_stringify (value);
Richard Hult's avatar
Richard Hult committed
155 156 157 158
	i = strtol (str, NULL, 10);
	g_free (str);

	return i;
Richard Hult's avatar
Richard Hult committed
159 160 161 162 163 164
}

/**
 * Helper to get an UTF-8 string.
 */
static gchar *
165
get_string (GdaDataModel *res, gint row, gint column)
Richard Hult's avatar
Richard Hult committed
166
{
Richard Hult's avatar
Richard Hult committed
167 168 169 170
	gchar    *str;
	gchar    *ret;
	gsize     len;
	GdaValue *value;
Richard Hult's avatar
Richard Hult committed
171
	
172 173 174 175 176 177 178
	value = (GdaValue *) gda_data_model_get_value_at (res, column, row);
	if (value == NULL) {
		g_warning ("Failed to get a value: (%d,%d)", column, row);
		return "";
	}
	
	str = gda_value_stringify (value);
Richard Hult's avatar
Richard Hult committed
179 180 181
	len = strlen (str);
	
	if (g_utf8_validate (str, len, NULL)) {
Richard Hult's avatar
Richard Hult committed
182
		return str;
Richard Hult's avatar
Richard Hult committed
183 184 185 186 187 188 189 190 191 192 193 194 195 196
	}

	/* First, try to convert to UTF-8 from the current locale. */
	ret = g_locale_to_utf8 (str, len, NULL, NULL, NULL);

	if (!ret) {
		/* If that fails, try to convert to UTF-8 from ISO-8859-1. */
		ret = g_convert (str, len, "UTF-8", "ISO-8859-1", NULL, NULL, NULL);
	}

	if (!ret) {
		/* Give up. */
		ret = g_strdup (_("Invalid Unicode"));
	}
Richard Hult's avatar
Richard Hult committed
197 198

	g_free (str);
Richard Hult's avatar
Richard Hult committed
199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275
	
	return ret;
}

/**
 * Helper that copies a string or returns NULL for strings only containing
 * whitespace.
 */
static gchar *
strdup_null_if_empty (const gchar *str)
{
	gchar *tmp;

	if (!str) {
		return NULL;
	}

	tmp = g_strstrip (g_strdup (str));
	if (tmp[0] == 0) {
		g_free (tmp);
		return NULL;
	}
		
	return tmp;
}

/**
 * Creates an SQL URI.
 */
static gchar *
create_sql_uri (const gchar *server,
		const gchar *port,
		const gchar *database,
		const gchar *login,
		const gchar *password,
		gint         project_id)
{
	GString *string;
	gchar   *str;

	string = g_string_new ("sql://");
	
	if (server) {
		if (login) {
			g_string_append (string, login);
			
			if (password) {
				g_string_append_c (string, ':');
				g_string_append (string, password);
			}
			
			g_string_append_c (string, '@');
		}
		
		g_string_append (string, server);
		
		if (port) {
			g_string_append_c (string, ':');
			g_string_append (string, port);
		}
	}

	g_string_append_c (string, '#');

	g_string_append_printf (string, "db=%s", database);
	
	if (project_id != -1) {
		g_string_append_printf (string, "&id=%d", project_id);
	}
	
	str = string->str;
	g_string_free (string, FALSE);
	
	return str;
}

static void
276 277
show_error_dialog (PlannerPlugin *plugin,
		   const gchar   *str)
Richard Hult's avatar
Richard Hult committed
278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306
{
	GtkWindow *window;
	GtkWidget *dialog;
	gint       response;

	window = GTK_WINDOW (plugin->main_window);
	
	dialog = gtk_message_dialog_new (window,
					 GTK_DIALOG_DESTROY_WITH_PARENT,
					 GTK_MESSAGE_ERROR,
					 GTK_BUTTONS_CLOSE,
					 str);

	response = gtk_dialog_run (GTK_DIALOG (dialog));
	gtk_widget_destroy (dialog);
}

static void
selection_changed_cb (GtkTreeSelection *selection, GtkWidget *ok_button)
{
	gboolean sensitive = FALSE;
	
	if (gtk_tree_selection_count_selected_rows (selection) > 0) {
		sensitive = TRUE;
	}
	
	gtk_widget_set_sensitive (ok_button, sensitive);
}

307 308 309 310 311 312 313 314 315
static void
row_activated_cb (GtkWidget         *tree_view,
		  GtkTreePath       *path,
		  GtkTreeViewColumn *column,
		  GtkWidget         *ok_button)
{
	gtk_widget_activate (ok_button);
}

316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683
/* Planner versions:
   1.x is always lower than 2.x.
   0.6 is lower than 0.11 
   If 0.11.90 we don't look ".90".
*/
static gboolean
is_newer_version (const gchar *version_new_txt, 
		  const gchar *version_old_txt)
{
	guint   subversion_old, subversion_new;
	guint   version_old, version_new;
	gchar **versionv_new, **versionv_old;

	g_return_val_if_fail (version_new_txt != NULL && 
			      version_old_txt != NULL, FALSE);
	
	version_old = g_ascii_strtod (version_old_txt, NULL);
	version_new = g_ascii_strtod (version_new_txt, NULL);

	if (version_new > version_old) {
		return TRUE;
	}
	else if (version_old > version_new) {
		return FALSE;
	}
	
	/* Need to check subversion */
	versionv_old = g_strsplit (version_old_txt,".",-1);
	versionv_new = g_strsplit (version_new_txt,".",-1);

	subversion_old = g_ascii_strtod (versionv_old[1], NULL);
	subversion_new = g_ascii_strtod (versionv_new[1], NULL);

	g_strfreev (versionv_new);
	g_strfreev (versionv_old);

	if (subversion_new > subversion_old) {
		return TRUE;
	}
	return FALSE;
}

static gboolean
check_database_tables (GdaConnection *conn,
		       PlannerPlugin *plugin)
{
	GtkWindow    *window;
	GdaDataModel *res;
	GtkWidget    *dialog;
	gint          result;
	GDir*         dir;
	const gchar  *name;
	gboolean      upgradable = FALSE;
	gboolean      create_tables;
	gboolean      can_create_tables = FALSE;
	gchar        *max_version_database;
	gchar        *max_version_upgrade;
	gchar        *upgrade_file = NULL;
	gchar        *database_file = NULL;
	gchar        *database_version = VERSION;
	const gchar  *database_name;
	gboolean      retval = FALSE;

	max_version_database = g_strdup ("0.0");
	max_version_upgrade = g_strdup ("0.0");
	database_name = gda_connection_get_database (conn);

	window = GTK_WINDOW (plugin->main_window);

	/* Try to get the database version */
	res = sql_execute_query (conn, "SELECT value FROM property_global WHERE prop_name='database_version'");		
	if (res == NULL) {
		create_tables = TRUE;
	} else {
		create_tables = FALSE;
		database_version = get_string (res, 0, 0);
		g_message ("Database version : %s", database_version);
		if (database_version == NULL) {
			database_version = VERSION;
		}
		g_object_unref (res);
	}

	/* Check for tables */
	dir = g_dir_open (SQL_DIR, 0, NULL);
	while ((name = g_dir_read_name (dir)) != NULL) {
		gchar **namev = NULL, **versionv = NULL;
		gchar  *version;
		gchar  *sql_file = g_build_filename (SQL_DIR, name, NULL);

		if (strncmp (name + strlen (name) - 4, ".sql", 4) != 0) {
			g_warning ("Strange file in SQL data Planner directory: %s%s", 
				   SQL_DIR, name);
			continue;
		}

		/* Find version between "-" and ".sql" */
		namev = g_strsplit (sql_file,"-",-1);
		/* Upgrade: 2 versions in file */
		if (namev[1] && namev[2]) {
			versionv = g_strsplit (namev[2],".sql",-1);
			if (is_newer_version (versionv[0], namev[1])) {
				if (!strcmp (namev[1], database_version)) {
					upgradable = TRUE;
					if (is_newer_version (versionv[0], 
							      max_version_upgrade)) {
						if (upgrade_file) {
							g_free (upgrade_file);
						}
						upgrade_file = g_strdup (sql_file);
						g_free (max_version_upgrade);
						max_version_upgrade = g_strdup (versionv[0]);
					}
				}
			} else {
				g_warning ("Incorrect upgrade file name: %s", sql_file);
			}
		}
		/* Create tables */
		else if (namev[1]) {
			versionv = g_strsplit (namev[1],".sql",-1);
			if (is_newer_version (versionv[0], max_version_database)) {
				if (database_file) {
					g_free (database_file);
				}
				database_file = g_strdup (sql_file);
				g_free (max_version_database);
				max_version_database = g_strdup (versionv[0]);
			}
			
			can_create_tables = TRUE;
			version = g_strdup (versionv[0]);
			g_free (version);
			
		} else {
			if (!database_file) {
				database_file = g_strdup (sql_file);
			}
			g_warning ("File with no version: %s", sql_file);
			can_create_tables = TRUE;
		}
		if (versionv) {
			g_strfreev (versionv);
		}
		if (namev) {
			g_strfreev (namev);
		}
		g_free (sql_file);
	}

	/* With each database change we need the new complete database description
	   and the upgrades files from different versions */
	if ((is_newer_version (max_version_upgrade, max_version_database) ||
	    is_newer_version (max_version_database, max_version_upgrade))
	    && 
	    (upgradable || create_tables)) {
		g_warning ("Database file version %s (%s) is different from upgrade file version %s (%s)",
			   max_version_database,
			   database_file,
			   max_version_upgrade,
			   upgrade_file);
		retval = FALSE;
		upgradable = FALSE;
		can_create_tables = FALSE;		
	}

	if (!upgradable && !create_tables) {
		retval = TRUE;
	}
	else if (upgradable && !create_tables) {
		gchar *contents;

		dialog = gtk_message_dialog_new (window,
						 GTK_DIALOG_DESTROY_WITH_PARENT,
						 GTK_MESSAGE_QUESTION,
						 GTK_BUTTONS_NONE,
						 _("Database %s needs to be upgraded "
						   "from version %s to version %s.\n"
						   "Please backup database before the upgrade."),
						 database_name, database_version, 
						 max_version_upgrade);
		gtk_dialog_add_buttons ((GtkDialog *) dialog, 
					GTK_STOCK_CANCEL, GTK_RESPONSE_CANCEL, 
					_("Upgrade"), GTK_RESPONSE_YES,  
					NULL);						 
		
		result = gtk_dialog_run (GTK_DIALOG (dialog));
		gtk_widget_destroy (dialog);
		if (result == GTK_RESPONSE_YES) {
			g_file_get_contents (upgrade_file, &contents, NULL, NULL);
			res = sql_execute_query (conn, contents);
			g_free (contents);
			if (res == NULL) {
				dialog = gtk_message_dialog_new (window,
								 GTK_DIALOG_DESTROY_WITH_PARENT,
								 GTK_MESSAGE_WARNING,
								 GTK_BUTTONS_CLOSE,
								 _("Could not upgrade database %s.\n Upgrade file used: %s."
								   "\n\nDatabase error: \n%s"),
								 database_name, upgrade_file,
								 sql_get_last_error (conn));
				
				gtk_dialog_run (GTK_DIALOG (dialog));
				gtk_widget_destroy (dialog);
				retval = FALSE;
			} else {
				gchar *query;

				sql_execute_query (conn, "DELETE * FROM property_global WHERE prop_name='database_version'");
				query = g_strdup_printf ("INSERT INTO property_global (prop_name, value) VALUES ('database_version','%s')", max_version_upgrade); 

				sql_execute_query (conn, query);
				g_free (query);
				g_free (res);
				retval = TRUE;
			}
		} else {
			retval = FALSE;
		}
		g_free (upgrade_file);
	}

	else if (create_tables && !can_create_tables) {
		g_warning ("Need to create tables but no database file");
		retval = FALSE;
	}

	else if (create_tables && can_create_tables) {
		gchar  *contents;

		g_file_get_contents (database_file, &contents, NULL, NULL);
		res = sql_execute_query (conn, contents);
		g_free (contents);
		if (res == NULL) {
			dialog = gtk_message_dialog_new (window,
							 GTK_DIALOG_DESTROY_WITH_PARENT,
							 GTK_MESSAGE_WARNING,
							 GTK_BUTTONS_CLOSE,
							 _("Can't create tables in database %s"),
							 database_name);
			
			result = gtk_dialog_run (GTK_DIALOG (dialog));
			gtk_widget_destroy (dialog);
			retval = FALSE;
		} else {
			gchar *query;
			
			query = g_strdup_printf ("INSERT INTO property_global (prop_name, value) VALUES ('database_version','%s')", max_version_database); 
			
			sql_execute_query (conn, query);
			g_free (query);
			g_free (res);
			retval = TRUE;
		}
		g_free (database_file);
	}
	
	g_free (max_version_upgrade);
	g_free (max_version_database);
	return retval;
}

/* Try to create the database */
static gboolean
create_database (const gchar   *dsn_name,
		 const gchar   *db_name,
		 PlannerPlugin *plugin)
{
	GtkWidget         *dialog;
	GtkWindow         *window;
	guint              result;
	gboolean           retval;
	GdaConnection     *conn;
	GdaClient         *client;
	GdaDataSourceInfo *dsn;
	gchar             *cnc_string_orig;
	/* FIXME: In postgresql we use template1 as the connection database */
	gchar             *init_database = "template1";
	gchar             *query;

	dsn = gda_config_find_data_source (dsn_name);
	cnc_string_orig = dsn->cnc_string;
	retval = FALSE;

	window = GTK_WINDOW (plugin->main_window);

	/* Use same data but changing the database */
	dsn->cnc_string = g_strdup_printf ("DATABASE=%s", init_database); 
	gda_config_save_data_source_info (dsn);

	client = gda_client_new ();
	conn = gda_client_open_connection (client, dsn_name, NULL, NULL, 0);
	if (conn == NULL) {
		g_warning ("Can't connect to database server in order to check/create the database: %s", cnc_string_orig);
	} else {
		dialog = gtk_message_dialog_new (window,
						 GTK_DIALOG_DESTROY_WITH_PARENT,
						 GTK_MESSAGE_QUESTION,
						 GTK_BUTTONS_YES_NO,
						 _("Database %s is not setup for Planner. "
						   "Do you want to do that?"),
						 db_name);
		
		result = gtk_dialog_run (GTK_DIALOG (dialog));
		gtk_widget_destroy (dialog);
		
		if (result == GTK_RESPONSE_YES) {
			query = g_strdup_printf ("CREATE DATABASE %s WITH ENCODING = 'UTF8'", 
						 db_name); 
			sql_execute_query (conn, query);
			g_free (query);
			/* FIXME: Tables will need the group: dirty relation between 
			   code and tables definitions in sql file.*/
			query = g_strdup_printf ("CREATE GROUP planner WITH USER %s", 
						 gda_connection_get_username (conn));
			sql_execute_query (conn, query);
			g_free (query);
			retval = TRUE;
		} else {
			retval = FALSE;
		}
		gda_connection_close (conn);
		g_object_unref (client);
	}
	g_free (dsn->cnc_string);
	dsn->cnc_string = cnc_string_orig;
	gda_config_save_data_source_info (dsn);

	return retval;
}

/* Test database status: database exists, correct tables, correct version */
static GdaConnection *
sql_get_tested_connection (const gchar   *dsn_name,
			   const gchar   *db_name,
			   GdaClient     *client,
			   PlannerPlugin *plugin) 
{
	GdaConnection *conn;
	gchar         *str;

	conn = gda_client_open_connection (client, dsn_name, NULL, NULL, 0);

	if (conn == NULL) {
		if (!create_database (dsn_name, db_name, plugin)) {
			str = g_strdup_printf (_("Connection to database '%s' failed."), 
					       db_name);
			show_error_dialog (plugin, str);
			conn = NULL;
		} else {
			conn = gda_client_open_connection (client, dsn_name, NULL, NULL, 0);
		}
	}

	if (conn != NULL) {
		if (!check_database_tables (conn, plugin)) {		
			str = g_strdup_printf (_("Test to tables in database '%s' failed."), db_name);
			show_error_dialog (plugin, str);
			g_free (str);
			gda_connection_close (conn);
			conn = NULL;	
		}
	}

	/* g_object_unref (client); */
	return conn;
}

Richard Hult's avatar
Richard Hult committed
684 685 686 687 688
/**
 * Display a list with projects and let the user select one. Returns the project
 * id of the selected one.
 */
static gint
Richard Hult's avatar
Richard Hult committed
689
sql_plugin_retrieve_project_id (PlannerPlugin *plugin,
690 691 692 693 694
				gchar         *server,
				gchar         *port,
				gchar         *database,
				gchar         *login,
				gchar         *password)
Richard Hult's avatar
Richard Hult committed
695
{
696 697 698
	GdaConnection     *conn;
	GdaDataModel      *res;
	GdaClient         *client;
Richard Hult's avatar
Richard Hult committed
699 700 701 702 703 704 705 706 707 708 709 710
	GladeXML          *gui;
	GtkWidget         *dialog;
	GtkWidget         *treeview;
	GtkWidget         *ok_button;
	GtkListStore      *liststore;
	GtkCellRenderer   *cell;
	GtkTreeViewColumn *col;
	gint               i;
	gint               response;
	gint               project_id;
	GtkTreeSelection  *selection;
	GtkTreeIter        iter;
711
	gchar             *db_txt;
712 713
	const gchar       *dsn_name = "planner-auto";
	const gchar       *provider = "PostgreSQL";
714 715 716

	db_txt = g_strdup_printf ("DATABASE=%s",database);
	gda_config_save_data_source (dsn_name, 
717
                                     provider, 
718
                                     db_txt,
719
                                     "planner project", login, password);
720 721 722
	g_free (db_txt);

	client = gda_client_new ();
723
	conn = sql_get_tested_connection (dsn_name, database, client, plugin);
Richard Hult's avatar
Richard Hult committed
724

725
	if (conn == NULL) {
Richard Hult's avatar
Richard Hult committed
726 727 728
		return -1;
	}

729 730
	res = sql_execute_query (conn, "BEGIN");
	if (res == NULL) {
Richard Hult's avatar
Richard Hult committed
731 732 733
		g_warning ("BEGIN command failed.");
		return -1;
	}
734
	g_object_unref (res);
Richard Hult's avatar
Richard Hult committed
735

736
	res = sql_execute_query (conn,
737 738
				 "DECLARE mycursor CURSOR FOR SELECT proj_id, name,"
				 "phase, revision FROM project ORDER by proj_id ASC");
Richard Hult's avatar
Richard Hult committed
739

740 741
	if (res == NULL) {
		g_warning ("DECLARE CURSOR command failed (project).");
Richard Hult's avatar
Richard Hult committed
742 743
		return -1;
	}
744 745 746 747
	g_object_unref (res);
	

	res = sql_execute_query (conn, "FETCH ALL in mycursor");
Richard Hult's avatar
Richard Hult committed
748

749
	if (res == NULL) {
Richard Hult's avatar
Richard Hult committed
750 751 752 753 754 755 756 757 758 759 760
		g_warning ("FETCH ALL failed.");
		return -1;
	}

	gui = glade_xml_new (GLADEDIR"/sql.glade", "select_dialog", NULL);
	dialog = glade_xml_get_widget (gui, "select_dialog");
	treeview = glade_xml_get_widget (gui, "project_treeview");
	ok_button = glade_xml_get_widget (gui, "ok_button");

	g_object_unref (gui);
	
761
	liststore = gtk_list_store_new (4, G_TYPE_INT, G_TYPE_STRING, G_TYPE_STRING, G_TYPE_INT);
Richard Hult's avatar
Richard Hult committed
762 763
	gtk_tree_view_set_model (GTK_TREE_VIEW (treeview), GTK_TREE_MODEL (liststore));

764 765 766 767 768 769 770 771
	cell = gtk_cell_renderer_text_new ();
	col = gtk_tree_view_column_new_with_attributes (_("ID"),
							cell,
							"text", COL_ID,
							NULL);
	gtk_tree_view_column_set_resizable (col, TRUE);
	gtk_tree_view_append_column (GTK_TREE_VIEW (treeview), col);
	
Richard Hult's avatar
Richard Hult committed
772 773 774 775 776
	cell = gtk_cell_renderer_text_new ();
	col = gtk_tree_view_column_new_with_attributes (_("Project"),
							cell,
							"text", COL_NAME,
							NULL);
777
	gtk_tree_view_column_set_resizable (col, TRUE);
Richard Hult's avatar
Richard Hult committed
778
	gtk_tree_view_append_column (GTK_TREE_VIEW (treeview), col);
779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797
	
	cell = gtk_cell_renderer_text_new ();
	col = gtk_tree_view_column_new_with_attributes (_("Phase"),
							cell,
							"text", COL_PHASE,
							NULL);
	gtk_tree_view_column_set_resizable (col, TRUE);
	gtk_tree_view_append_column (GTK_TREE_VIEW (treeview), col);
	
	cell = gtk_cell_renderer_text_new ();
	col = gtk_tree_view_column_new_with_attributes (_("Revision"),
							cell,
							"text", COL_REVISION,
							NULL);
	gtk_tree_view_column_set_resizable (col, TRUE);
	gtk_tree_view_append_column (GTK_TREE_VIEW (treeview), col);
	
	gtk_tree_view_columns_autosize (GTK_TREE_VIEW (treeview));
	
Richard Hult's avatar
Richard Hult committed
798 799 800
	selection = gtk_tree_view_get_selection (GTK_TREE_VIEW (treeview));
	gtk_tree_selection_set_mode (selection, GTK_SELECTION_SINGLE); 
	
801 802
	g_signal_connect (selection,
			  "changed",
Richard Hult's avatar
Richard Hult committed
803 804
			  G_CALLBACK (selection_changed_cb),
			  ok_button);
805 806 807 808 809

	g_signal_connect (treeview,
			  "row_activated",
			  G_CALLBACK (row_activated_cb),
			  ok_button);
Richard Hult's avatar
Richard Hult committed
810
	
811
	for (i = 0; i < gda_data_model_get_n_rows (res); i++) {
Richard Hult's avatar
Richard Hult committed
812 813
		gint   id;
		gchar *name;
814 815
		gchar *phase;
		gint   revision;
Richard Hult's avatar
Richard Hult committed
816 817 818
		
		id = get_int (res, i, 0);
		name = get_string (res, i, 1);
819 820
		phase = get_string (res, i, 2);
		revision = get_int (res, i, 3);
Richard Hult's avatar
Richard Hult committed
821

822 823 824 825 826 827
		/* FIXME: needs fixing in the database backend. */
		if (strcmp (phase, "NULL") == 0) {
			g_free (phase);
			phase = g_strdup ("");
		}
		
Richard Hult's avatar
Richard Hult committed
828 829 830 831 832
		gtk_list_store_append (GTK_LIST_STORE (liststore), &iter);
		gtk_list_store_set (GTK_LIST_STORE (liststore), 
				    &iter,
				    COL_ID, id,
				    COL_NAME, name,
833 834
				    COL_PHASE, phase,
			            COL_REVISION, revision,
Richard Hult's avatar
Richard Hult committed
835 836 837
				    -1);

		g_free (name);
838
		g_free (phase);
Richard Hult's avatar
Richard Hult committed
839 840
	}

841
	if (gda_data_model_get_n_columns (res) == 0) {
Richard Hult's avatar
Richard Hult committed
842 843 844
		gtk_widget_set_sensitive (ok_button, FALSE);
	}
	
845
	g_object_unref (res);
Richard Hult's avatar
Richard Hult committed
846

847
	res = sql_execute_query (conn,"CLOSE mycursor");
848 849
	
	g_object_unref (res);
Richard Hult's avatar
Richard Hult committed
850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878
	
	gtk_widget_show_all (dialog);
	response = gtk_dialog_run (GTK_DIALOG (dialog));

	project_id = -1;
	
	switch (response) {
	case GTK_RESPONSE_CANCEL:
	case GTK_RESPONSE_DELETE_EVENT:
		break;
	case GTK_RESPONSE_OK:
		if (!gtk_tree_selection_get_selected (selection, NULL, &iter)) {
			break;
		}

		gtk_tree_model_get (GTK_TREE_MODEL (liststore),
				    &iter, 
				    COL_ID, &project_id,
				    -1);
		
		break;
	};

	gtk_widget_destroy (dialog);

	return project_id;
}

static gboolean
879 880 881 882 883 884 885
sql_plugin_retrieve_db_values (PlannerPlugin  *plugin,
			       const gchar    *title,
			       gchar         **server,
			       gchar         **port,
			       gchar         **database,
			       gchar         **login,
			       gchar         **password)
Richard Hult's avatar
Richard Hult committed
886
{
887 888 889 890 891 892 893 894 895
	GladeXML           *gui;
	GtkWidget          *dialog;
	gchar              *str;
	gint                response;
	GtkWidget          *server_entry;
	GtkWidget          *db_entry;
	GtkWidget          *user_entry;
	GtkWidget          *password_entry;
	gboolean            ret;
Richard Hult's avatar
Richard Hult committed
896
	PlannerApplication *application;
897
	GConfClient        *gconf_client;
Richard Hult's avatar
Richard Hult committed
898

Richard Hult's avatar
Richard Hult committed
899
	application = planner_window_get_application (plugin->main_window);
Richard Hult's avatar
Richard Hult committed
900
	
901
	gconf_client = planner_application_get_gconf_client ();
Richard Hult's avatar
Richard Hult committed
902 903 904 905 906 907 908 909 910 911 912 913 914 915

	gui = glade_xml_new (GLADEDIR"/sql.glade", "open_dialog" , NULL);
	dialog = glade_xml_get_widget (gui, "open_dialog");

	gtk_window_set_title (GTK_WINDOW (dialog), title);

	server_entry = gnome_entry_gtk_entry (
		GNOME_ENTRY (glade_xml_get_widget (gui, "server_entry")));
	db_entry = gnome_entry_gtk_entry (
		GNOME_ENTRY (glade_xml_get_widget (gui, "db_entry")));
	user_entry = gnome_entry_gtk_entry (
		GNOME_ENTRY (glade_xml_get_widget (gui, "user_entry")));
	password_entry = glade_xml_get_widget (gui, "password_entry");

Richard Hult's avatar
Richard Hult committed
916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933
	str = gconf_client_get_string (gconf_client, GCONF_PATH "/server", NULL);
	if (str) {
		gtk_entry_set_text (GTK_ENTRY (server_entry), str);
		g_free (str);
	}

	str = gconf_client_get_string (gconf_client, GCONF_PATH "/database", NULL);
	if (str) {
		gtk_entry_set_text (GTK_ENTRY (db_entry), str);
		g_free (str);
	}

	str = gconf_client_get_string (gconf_client, GCONF_PATH "/username", NULL);
	if (str) {
		gtk_entry_set_text (GTK_ENTRY (user_entry), str);
		g_free (str);
	}
	
Richard Hult's avatar
Richard Hult committed
934 935 936 937 938 939 940 941 942 943 944 945
	g_object_unref (gui);

	response = gtk_dialog_run (GTK_DIALOG (dialog));

	switch (response) {
	case GTK_RESPONSE_OK:
		*server = strdup_null_if_empty (gtk_entry_get_text (GTK_ENTRY (server_entry)));
		*port = NULL;
		*database = strdup_null_if_empty (gtk_entry_get_text (GTK_ENTRY (db_entry)));
		*login = strdup_null_if_empty (gtk_entry_get_text (GTK_ENTRY (user_entry)));
		*password = strdup_null_if_empty (gtk_entry_get_text (GTK_ENTRY (password_entry)));

Richard Hult's avatar
Richard Hult committed
946 947 948 949 950 951 952 953 954
		gconf_client_set_string (gconf_client,
					 GCONF_PATH "/server", *server ? *server : "",
					 NULL);
		gconf_client_set_string (gconf_client,
					 GCONF_PATH "/database", *database ? *database : "",
					 NULL);
		gconf_client_set_string (gconf_client,
					 GCONF_PATH "/username", *login ? *login : "",
					 NULL);
Richard Hult's avatar
Richard Hult committed
955 956 957 958 959 960 961 962 963 964 965 966 967 968
		ret = TRUE;
		break;

	default:
		ret = FALSE;
		break;
	}

	gtk_widget_destroy (dialog);
		
	return ret;
}

static void
969 970
sql_plugin_open (GtkAction *action,
		 gpointer   user_data)
Richard Hult's avatar
Richard Hult committed
971
{
Richard Hult's avatar
Richard Hult committed
972 973
	PlannerPlugin      *plugin = user_data;
	PlannerApplication *application;
974 975 976 977 978 979 980 981 982 983
	GtkWidget          *window;
	MrpProject         *project;
	gchar              *server = NULL;
	gchar              *port = NULL;
	gchar              *database = NULL;
	gchar              *login = NULL;
	gchar              *password = NULL;
	gint                project_id = -1;
	gchar              *uri = NULL;
	GError             *error = NULL;
Richard Hult's avatar
Richard Hult committed
984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010

	if (!sql_plugin_retrieve_db_values (plugin,
					    _("Open from Database"),
					    &server,
					    &port,
					    &database,
					    &login,
					    &password)) {
		return;
	}
	
	project_id = sql_plugin_retrieve_project_id (plugin,
						     server,
						     port,
						     database,
						     login,
						     password);
	if (project_id == -1) {
		goto fail;
	}
	
	/* Note: The project can change or disappear between the call above and
	 * below. We handle that case though.
	 */

	uri = create_sql_uri (server, port, database, login, password, project_id);

Richard Hult's avatar
Richard Hult committed
1011
	project = planner_window_get_project (plugin->main_window);
Richard Hult's avatar
Richard Hult committed
1012
	window = GTK_WIDGET (plugin->main_window);
Richard Hult's avatar
Richard Hult committed
1013
	application = planner_window_get_application (plugin->main_window);
Richard Hult's avatar
Richard Hult committed
1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036
	
	if (mrp_project_is_empty (project)) {
		GObject *object = G_OBJECT (window);
		
		if (!mrp_project_load (project, uri, &error)) {
			show_error_dialog (plugin, error->message);
			g_clear_error (&error);
			goto fail;
		}

		/* Note: Those aren't used for anything right now. */
		g_object_set_data_full (object, SERVER, server, g_free);
		g_object_set_data_full (object, DATABASE, database, g_free);
		g_object_set_data_full (object, LOGIN, login, g_free);
		g_object_set_data_full (object, PASSWORD, password, g_free);

		g_free (uri);
		
		return;
	} else {
		GObject *object;
		
		window = planner_application_new_window (application);
Richard Hult's avatar
Richard Hult committed
1037
		project = planner_window_get_project (PLANNER_WINDOW (window));
Richard Hult's avatar
Richard Hult committed
1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074
		
		object = G_OBJECT (window);
		
		/* We must get the new plugin object for the new window,
		 * otherwise we'll pass the wrong window around... a bit
		 * hackish.
		 */
		plugin = g_object_get_data (G_OBJECT (window), "sql-plugin");
		
		if (!mrp_project_load (project, uri, &error)) {
			g_warning ("Error: %s", error->message);
			g_clear_error (&error);
			gtk_widget_destroy (window);
			goto fail;
		}
		
		g_object_set_data_full (object, SERVER, server, g_free);
		g_object_set_data_full (object, DATABASE, database, g_free);
		g_object_set_data_full (object, LOGIN, login, g_free);
		g_object_set_data_full (object, PASSWORD, password, g_free);

		g_free (uri);

		gtk_widget_show_all (window);
		return;
	}

 fail:
	g_free (server);
	g_free (port);
	g_free (database);
	g_free (login);
	g_free (password);
	g_free (uri);
}

static void
1075 1076
sql_plugin_save (GtkAction *action,
		 gpointer   user_data)
Richard Hult's avatar
Richard Hult committed
1077
{
1078 1079 1080
	GdaClient     *client;
	GdaConnection *conn;
	PlannerPlugin *plugin   = user_data;
1081 1082
	MrpProject    *project;
	GObject       *object;
1083 1084
	gchar         *server   = NULL;
	gchar         *port     = NULL;
1085
	gchar         *database = NULL;
1086
	gchar         *login    = NULL;
1087
	gchar         *password = NULL;
1088 1089 1090 1091 1092 1093
	gchar         *uri      = NULL;
	const gchar   *uri_plan = NULL;
	GError        *error    = NULL;
	gchar         *db_txt;
	const gchar   *dsn_name = "planner-auto";
	const gchar   *provider = "PostgreSQL";
Richard Hult's avatar
Richard Hult committed
1094
		
Richard Hult's avatar
Richard Hult committed
1095
	project = planner_window_get_project (plugin->main_window);
Richard Hult's avatar
Richard Hult committed
1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106

	if (!sql_plugin_retrieve_db_values (plugin,
					    _("Save to Database"),
					    &server,
					    &port,
					    &database,
					    &login,
					    &password)) {
		return;
	}

1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121
	db_txt = g_strdup_printf ("DATABASE=%s",database);
	gda_config_save_data_source (dsn_name, 
                                     provider, 
                                     db_txt,
                                     "planner project", login, password);
	g_free (db_txt);
	client = gda_client_new ();
	conn = sql_get_tested_connection (dsn_name, database, client, plugin);
	if (conn == NULL) {
		g_object_unref (client);
		return;
	}
	gda_connection_close (conn);
	g_object_unref (client);

Richard Hult's avatar
Richard Hult committed
1122 1123 1124 1125
	/* This code is prepared for getting support for selecting a project to
	 * save over. Needs finishing though. Pass project id -1 for now (always
	 * create a new project).
	 */
1126
	uri_plan = mrp_project_get_uri (project);
Richard Hult's avatar
Richard Hult committed
1127

1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 1144 1145 1146 1147 1148 1149 1150 1151 1152 1153 1154 1155
	/* First time project */
	if (uri_plan == NULL) {
		uri = create_sql_uri (server, port, database, login, password, -1);	
		if (!mrp_project_save_as (project, uri, FALSE, &error)) { 
			show_error_dialog (plugin, error->message);
			g_clear_error (&error);
			goto fail;
		}
		g_free (uri);
		
	} 
	/* Project was in database */
	else if (strncmp (uri_plan, "sql://", 6) == 0) {
		if (!mrp_project_save (project, FALSE, &error)) { 
			show_error_dialog (plugin, error->message);
			g_clear_error (&error);
			goto fail;
		}
	} 
	/* Project wasn't in database */
	else {
		uri = create_sql_uri (server, port, database, login, password, -1);	
		if (!mrp_project_save_as (project, uri, FALSE, &error)) { 
			show_error_dialog (plugin, error->message);
			g_clear_error (&error);
			goto fail;
		}
		g_free (uri);
Richard Hult's avatar
Richard Hult committed
1156 1157 1158 1159 1160 1161 1162 1163 1164 1165 1166 1167 1168 1169 1170 1171 1172 1173 1174 1175 1176 1177 1178 1179 1180 1181
	}
		
	object = G_OBJECT (plugin->main_window);
	
	g_object_set_data_full (object, SERVER, server, g_free);
	g_object_set_data_full (object, DATABASE, database, g_free);
	g_object_set_data_full (object, LOGIN, login, g_free);
	g_object_set_data_full (object, PASSWORD, password, g_free);
	
	return;

fail:
	g_free (server);
	g_free (port);
	g_free (database);
	g_free (login);
	g_free (password);
	g_free (uri);
}

G_MODULE_EXPORT void 
plugin_exit (void) 
{
}

G_MODULE_EXPORT void 
1182
plugin_init (PlannerPlugin *plugin,
Richard Hult's avatar
Richard Hult committed
1183
	     PlannerWindow *main_window)
Richard Hult's avatar
Richard Hult committed
1184
{
Richard Hult's avatar
Richard Hult committed
1185 1186 1187 1188 1189
	SQLPluginPriv  *priv;
	GtkActionGroup *actions;
	GtkUIManager   *ui;
	gint            i = -1;
	GError         *error = NULL;
Richard Hult's avatar
Richard Hult committed
1190 1191 1192 1193 1194 1195 1196 1197 1198 1199 1200 1201 1202
	
	priv = g_new0 (SQLPluginPriv, 1);

	g_object_set_data (G_OBJECT (main_window), 
			   PROJECT_ID,
			   GINT_TO_POINTER (i));
	g_object_set_data (G_OBJECT (main_window), 
			   "sql-plugin-revision",
			   GINT_TO_POINTER (i));

	g_object_set_data (G_OBJECT (main_window), 
			   "sql-plugin",
			   plugin);
1203 1204 1205 1206 1207 1208 1209 1210 1211 1212 1213 1214 1215 1216 1217

	/* Create the actions, get the ui manager and merge the whole */
	actions = gtk_action_group_new ("SQL plugin actions");
	gtk_action_group_set_translation_domain (actions, GETTEXT_PACKAGE);

	gtk_action_group_add_actions (actions, entries, n_entries, plugin);

	ui = planner_window_get_ui_manager (main_window);
	gtk_ui_manager_insert_action_group (ui, actions, 0);

	if (!gtk_ui_manager_add_ui_from_file (ui, DATADIR"/planner/ui/sql-plugin.ui", &error)) {
		g_message ("Building menu failed: %s", error->message);
		g_message ("Couldn't load: %s",DATADIR"/planner/ui/sql-plugin.ui");
		g_error_free (error);
	}
Richard Hult's avatar
Richard Hult committed
1218 1219
	
	gtk_ui_manager_ensure_update (ui);
Richard Hult's avatar
Richard Hult committed
1220 1221
}