gda-statement.c 69.6 KB
Newer Older
1
/*
2
 * Copyright (C) 2008 Bas Driessen <bas.driessen@xobas.com>
3
 * Copyright (C) 2008 - 2011 Murray Cumming <murrayc@murrayc.com>
4
 * Copyright (C) 2008 - 2014 Vivien Malerba <malerba@gnome-db.org>
5 6
 * Copyright (C) 2010 David King <davidk@openismus.com>
 * Copyright (C) 2010 Jonh Wendell <jwendell@gnome.org>
7
 * Copyright (C) 2017-2018 Daniel Espinosa <esodan@gmail.com>
8
 *
9 10 11 12
 * This library is free software; you can redistribute it and/or
 * modify it under the terms of the GNU Lesser General Public
 * License as published by the Free Software Foundation; either
 * version 2 of the License, or (at your option) any later version.
13
 *
14
 * This library is distributed in the hope that it will be useful,
15 16
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
17
 * Lesser General Public License for more details.
18
 *
19 20 21 22
 * You should have received a copy of the GNU Lesser General Public
 * License along with this library; if not, write to the
 * Free Software Foundation, Inc., 51 Franklin St, Fifth Floor,
 * Boston, MA  02110-1301, USA.
23 24
 */

25
#undef GDA_DISABLE_DEPRECATED
26 27 28 29 30 31 32 33 34 35 36 37 38
#include <string.h>
#include <glib/gi18n-lib.h>
#include <libgda/gda-statement.h>
#include <libgda/gda-debug-macros.h>
#include <libgda/sql-parser/gda-statement-struct-util.h>
#include <libgda/sql-parser/gda-statement-struct-parts.h>
#include <libgda/sql-parser/gda-statement-struct-unknown.h>
#include <libgda/sql-parser/gda-statement-struct-insert.h>
#include <libgda/sql-parser/gda-statement-struct-delete.h>
#include <libgda/sql-parser/gda-statement-struct-update.h>
#include <libgda/sql-parser/gda-statement-struct-compound.h>
#include <libgda/sql-parser/gda-statement-struct-select.h>
#include <libgda/gda-marshal.h>
39
#include <libgda/gda-data-handler.h>
40
#include <libgda/gda-server-provider-private.h>
41 42 43
#include <libgda/gda-statement-extra.h>
#include <libgda/gda-holder.h>
#include <libgda/gda-set.h>
44
#include <libgda/gda-meta-store.h>
45 46
#include <libgda/gda-connection.h>
#include <libgda/gda-util.h>
47
#include <libgda/libgda.h>
48 49 50 51 52 53 54 55 56 57 58 59 60 61 62

/* 
 * Main static functions 
 */
static void gda_statement_dispose (GObject *object);

static void gda_statement_set_property (GObject *object,
					guint param_id,
					const GValue *value,
					GParamSpec *pspec);
static void gda_statement_get_property (GObject *object,
					guint param_id,
					GValue *value,
					GParamSpec *pspec);

63
typedef struct {
64
	GdaSqlStatement *internal_struct;
65
	GType           *requested_types;
66
} GdaStatementPrivate;
67 68

G_DEFINE_TYPE_WITH_PRIVATE (GdaStatement, gda_statement, G_TYPE_OBJECT)
69 70 71 72
/* signals */
enum
{
	RESET,
73
	CHECKED,
74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99
	LAST_SIGNAL
};

static gint gda_statement_signals[LAST_SIGNAL] = { 0, 0 };

/* properties */
enum
{
	PROP_0,
	PROP_STRUCTURE
};

/* module error */
GQuark gda_statement_error_quark (void)
{
	static GQuark quark;
	if (!quark)
		quark = g_quark_from_static_string ("gda_statement_error");
	return quark;
}


static void
gda_statement_class_init (GdaStatementClass * klass)
{
	GObjectClass   *object_class = G_OBJECT_CLASS (klass);
100

101
	/**
102
	 * GdaStatement::reset:
103 104 105 106
	 * @stmt: the #GdaStatement object
	 *
	 * Gets emitted whenever the @stmt has changed
	 */
107 108 109 110 111 112 113 114
	gda_statement_signals[RESET] =
		g_signal_new ("reset",
			      G_TYPE_FROM_CLASS (object_class),
			      G_SIGNAL_RUN_FIRST,
			      G_STRUCT_OFFSET (GdaStatementClass, reset),
			      NULL, NULL,
			      g_cclosure_marshal_VOID__VOID, G_TYPE_NONE,
			      0);
115
	/**
116
	 * GdaStatement::checked:
117
	 * @stmt: the #GdaStatement object
118 119
	 * @cnc: a #GdaConnection
	 * @checked: whether @stmt have been verified
120 121 122 123
	 *
	 * Gets emitted whenever the structure and contents
	 * of @stmt have been verified (emitted after gda_statement_check_validity()).
	 */
124 125
	gda_statement_signals[CHECKED] =
		g_signal_new ("checked",
126 127
			      G_TYPE_FROM_CLASS (object_class),
			      G_SIGNAL_RUN_FIRST,
128
			      G_STRUCT_OFFSET (GdaStatementClass, checked),
129
			      NULL, NULL,
130
			      _gda_marshal_VOID__OBJECT_BOOLEAN, G_TYPE_NONE,
131
			      2, GDA_TYPE_CONNECTION, G_TYPE_BOOLEAN);
132 133

	klass->reset = NULL;
134
	klass->checked = NULL;
135 136 137 138 139 140 141 142 143 144 145 146 147 148

	object_class->dispose = gda_statement_dispose;

	/* Properties */
	object_class->set_property = gda_statement_set_property;
	object_class->get_property = gda_statement_get_property;
	g_object_class_install_property (object_class, PROP_STRUCTURE,
					 g_param_spec_pointer ("structure", NULL, NULL, 
							       G_PARAM_WRITABLE | G_PARAM_READABLE));
}

static void
gda_statement_init (GdaStatement * stmt)
{
149 150 151
	GdaStatementPrivate *priv = gda_statement_get_instance_private (stmt);
	priv->internal_struct = NULL;
	priv->requested_types = NULL;
152 153 154
}

/**
155
 * gda_statement_new:
156 157 158 159 160 161 162 163 164 165 166 167 168 169
 *
 * Creates a new #GdaStatement object
 *
 * Returns: the new object
 */
GdaStatement*
gda_statement_new (void)
{
	GObject *obj;

	obj = g_object_new (GDA_TYPE_STATEMENT, NULL);
	return GDA_STATEMENT (obj);
}

170
GdaSqlStatement *
Vivien Malerba's avatar
Vivien Malerba committed
171 172
_gda_statement_get_internal_struct (GdaStatement *stmt)
{
173 174 175
	g_return_val_if_fail (GDA_IS_STATEMENT (stmt), NULL);
	GdaStatementPrivate *priv = gda_statement_get_instance_private (stmt);
	return priv->internal_struct;
Vivien Malerba's avatar
Vivien Malerba committed
176
}
177 178

/**
179
 * gda_statement_copy:
180 181 182 183
 * @orig: a #GdaStatement to make a copy of
 * 
 * Copy constructor
 *
Jonh Wendell's avatar
Jonh Wendell committed
184
 * Returns: (transfer full): a the new copy of @orig
185 186
 */
GdaStatement *
187
gda_statement_copy (GdaStatement *orig)
188 189 190 191
{
	GObject *obj;

	g_return_val_if_fail (GDA_IS_STATEMENT (orig), NULL);
192
	GdaStatementPrivate *priv = gda_statement_get_instance_private (orig);
193

194
	obj = g_object_new (GDA_TYPE_STATEMENT, "structure", priv->internal_struct, NULL);
195 196 197 198 199 200 201 202 203 204 205
	return GDA_STATEMENT (obj);
}

static void
gda_statement_dispose (GObject *object)
{
	GdaStatement *stmt;

	g_return_if_fail (object != NULL);
	g_return_if_fail (GDA_IS_STATEMENT (object));
	stmt = GDA_STATEMENT (object);
206 207 208 209 210 211 212 213 214
	GdaStatementPrivate *priv = gda_statement_get_instance_private (stmt);

	if (priv->requested_types) {
		g_free (priv->requested_types);
		priv->requested_types = NULL;
	}
	if (priv->internal_struct) {
		gda_sql_statement_free (priv->internal_struct);
		priv->internal_struct = NULL;
215 216 217
	}

	/* parent class */
218
	G_OBJECT_CLASS (gda_statement_parent_class)->dispose (object);
219 220 221 222 223 224 225 226 227 228 229
}

static void
gda_statement_set_property (GObject *object,
			     guint param_id,
			     const GValue *value,
			     GParamSpec *pspec)
{
	GdaStatement *stmt;

	stmt = GDA_STATEMENT (object);
230
	GdaStatementPrivate *priv = gda_statement_get_instance_private (stmt);
231
	switch (param_id) {
232
		case PROP_STRUCTURE:
233 234 235
			if (priv->internal_struct) {
				gda_sql_statement_free (priv->internal_struct);
				priv->internal_struct = NULL;
236
			}
237 238 239
			if (priv->requested_types) {
				g_free (priv->requested_types);
				priv->requested_types = NULL;
240
			}
241
			priv->internal_struct = gda_sql_statement_copy (g_value_get_pointer (value));
242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257
			g_signal_emit (stmt, gda_statement_signals [RESET], 0);
			break;
		default:
			G_OBJECT_WARN_INVALID_PROPERTY_ID (object, param_id, pspec);
			break;
	}
}

static void
gda_statement_get_property (GObject *object,
			     guint param_id,
			     GValue *value,
			     GParamSpec *pspec)
{
	GdaStatement *stmt;
	stmt = GDA_STATEMENT (object);
258
	GdaStatementPrivate *priv = gda_statement_get_instance_private (stmt);
259 260

	switch (param_id) {
261
		case PROP_STRUCTURE:
262
			g_value_set_pointer (value, gda_sql_statement_copy (priv->internal_struct));
263 264 265 266 267 268 269 270
			break;
		default:
			G_OBJECT_WARN_INVALID_PROPERTY_ID (object, param_id, pspec);
			break;
	}
}

/**
271
 * gda_statement_get_statement_type:
272 273 274 275 276
 * @stmt: a #GdaStatement object
 *
 * Get the type of statement held by @stmt. It returns GDA_SQL_STATEMENT_NONE if
 * @stmt does not hold any statement
 *
277
 * Returns: (transfer none): the statement type
278 279 280 281
 */
GdaSqlStatementType
gda_statement_get_statement_type (GdaStatement *stmt)
{
282
	g_return_val_if_fail (stmt != NULL, GDA_SQL_STATEMENT_NONE);
283
	g_return_val_if_fail (GDA_IS_STATEMENT (stmt), GDA_SQL_STATEMENT_NONE);
284 285
	GdaStatementPrivate *priv = gda_statement_get_instance_private (stmt);
	g_return_val_if_fail (priv, GDA_SQL_STATEMENT_NONE);
286

287 288 289 290
	if (priv->internal_struct)
		return priv->internal_struct->stmt_type;

	return GDA_SQL_STATEMENT_NONE;
291 292 293
}

/**
294
 * gda_statement_is_useless:
295 296 297 298 299 300 301 302 303 304 305
 * @stmt: a #GdaStatement object
 *
 * Tells if @stmt is composed only of spaces (that is it has no real SQL code), and is completely
 * useless as such.
 *
 * Returns: TRUE if executing @stmt does nothing
 */
gboolean
gda_statement_is_useless (GdaStatement *stmt)
{
	g_return_val_if_fail (GDA_IS_STATEMENT (stmt), FALSE);
306 307
	GdaStatementPrivate *priv = gda_statement_get_instance_private (stmt);
	g_return_val_if_fail (priv, FALSE);
308

309 310
	if (priv->internal_struct &&
	    priv->internal_struct->stmt_type == GDA_SQL_STATEMENT_UNKNOWN) {
311 312
		GSList *list;
		GdaSqlStatementUnknown *unknown;
313
		unknown = (GdaSqlStatementUnknown*) priv->internal_struct->contents;
314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338
		for (list = unknown->expressions; list; list = list->next) {
			GdaSqlExpr *expr = (GdaSqlExpr *) list->data;
			if (expr->param_spec)
				return FALSE;
			if (expr->value) {
				if (G_VALUE_TYPE (expr->value) == G_TYPE_STRING) {
					const gchar *str;
					for (str = g_value_get_string (expr->value); 
					     (*str == ' ') || (*str == '\t') || (*str == '\n') || 
						     (*str == '\f') || (*str == '\r'); str++);
					if (*str)
						return FALSE;
				}
				else {
					TO_IMPLEMENT;
					return FALSE;
				}
			}
		}
		return TRUE;
	}
	return FALSE;
}

/**
339
 * gda_statement_check_structure:
340 341 342 343 344 345 346 347 348 349 350
 * @stmt: a #GdaStatement object
 * @error: a place to store errors, or %NULL
 * 
 * Checks that @stmt's structure is correct.
 *
 * Returns: TRUE if @stmt's structure is correct
 */
gboolean
gda_statement_check_structure (GdaStatement *stmt, GError **error)
{
	g_return_val_if_fail (GDA_IS_STATEMENT (stmt), FALSE);
351
	GdaStatementPrivate *priv = gda_statement_get_instance_private (stmt);
352

353
	return gda_sql_statement_check_structure (priv->internal_struct, error);
354 355 356
}

/**
357
 * gda_statement_check_validity:
358
 * @stmt: a #GdaStatement object
359
 * @cnc: (nullable): a #GdaConnection object, or %NULL
360 361
 * @error: a place to store errors, or %NULL
 *
362 363
 * If @cnc is not %NULL then checks that every object (table, field, function) used in @stmt 
 * actually exists in @cnc's database
364
 *
365
 * If @cnc is %NULL, then cleans anything related to @cnc in @stmt.
366
 *
367 368
 * See gda_sql_statement_check_validity() for more information.
 *
369
 * Returns: TRUE if every object actually exists in @cnc's database
370 371
 */
gboolean
372
gda_statement_check_validity (GdaStatement *stmt, GdaConnection *cnc, GError **error)
373 374 375
{
	gboolean retval;
	g_return_val_if_fail (GDA_IS_STATEMENT (stmt), FALSE);
376
	GdaStatementPrivate *priv = gda_statement_get_instance_private (stmt);
377
	g_return_val_if_fail (!cnc || GDA_IS_CONNECTION (cnc), FALSE);
378

379
	retval = gda_sql_statement_check_validity (priv->internal_struct, cnc, error);
380
	g_signal_emit (stmt, gda_statement_signals [CHECKED], 0, cnc, retval);
381 382 383 384

	return retval;
}

385
/**
386
 * gda_statement_normalize:
387 388 389 390 391 392 393 394 395 396 397 398 399 400
 * @stmt: a #GdaStatement object
 * @cnc: a #GdaConnection object
 * @error: a place to store errors, or %NULL
 *
 * "Normalizes" some parts of @stmt, see gda_sql_statement_normalize() for more
 * information.
 *
 * Returns: TRUE if no error occurred
 */
gboolean
gda_statement_normalize (GdaStatement *stmt, GdaConnection *cnc, GError **error)
{
	g_return_val_if_fail (GDA_IS_STATEMENT (stmt), FALSE);
	g_return_val_if_fail (GDA_IS_CONNECTION (cnc), FALSE);
401
	GdaStatementPrivate *priv = gda_statement_get_instance_private (stmt);
402

403
	return gda_sql_statement_normalize (priv->internal_struct, cnc, error);
404 405
}

406
/**
407
 * gda_statement_serialize:
408 409 410 411 412 413 414 415 416 417 418 419
 * @stmt: a #GdaStatement object
 *
 * Creates a string representing the contents of @stmt.
 *
 * Returns: a string containing the serialized version of @stmt
 */
gchar *
gda_statement_serialize (GdaStatement *stmt)
{
	gchar *str;
	GString *string;
	g_return_val_if_fail (GDA_IS_STATEMENT (stmt), NULL);
420
	GdaStatementPrivate *priv = gda_statement_get_instance_private (stmt);
421 422 423

	string = g_string_new ("{");
	g_string_append (string, "\"statement\":");
424
	str = gda_sql_statement_serialize (priv->internal_struct);
425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447
	if (str) {
		g_string_append (string, str);
		g_free (str);
	}
	else
		g_string_append (string, "null");
	g_string_append_c (string, '}');

	str = string->str;
	g_string_free (string, FALSE);
	return str;
}

static gboolean
get_params_foreach_func (GdaSqlAnyPart *node, GdaSet **params, GError **error)
{
	GdaSqlParamSpec *pspec;
	if (!node) return TRUE;

	if ((node->type == GDA_SQL_ANY_EXPR) &&
	    (pspec = ((GdaSqlExpr*) node)->param_spec)) {
		GdaHolder *h;

448
		if (pspec->g_type == GDA_TYPE_NULL) {
449 450 451 452 453 454 455
			g_set_error (error, GDA_STATEMENT_ERROR, GDA_STATEMENT_PARAM_TYPE_ERROR,
				     _("Could not determine GType for parameter '%s'"),
				     pspec->name ? pspec->name : _("Unnamed"));
			return FALSE;
		}
		if (!*params) 
			*params = gda_set_new (NULL);
456 457
		h = gda_holder_new (pspec->g_type, pspec->name);
		g_object_set (G_OBJECT (h), "name", pspec->name,
458 459 460
			      "description", pspec->descr, NULL);
		gda_holder_set_not_null (h, ! pspec->nullok);
		if (((GdaSqlExpr*) node)->value) {
461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477
			/* Expr's value is "SQL encoded" => we need to convert it to a real value */
			GValue *evalue;
			evalue = ((GdaSqlExpr*) node)->value;
			if (G_VALUE_TYPE (evalue) == G_TYPE_STRING) {
				GdaDataHandler *dh;
				GValue *value;
				dh = gda_data_handler_get_default (pspec->g_type);
				if (!dh) {
					g_set_error (error, GDA_STATEMENT_ERROR, GDA_STATEMENT_PARAM_TYPE_ERROR,
						     _("Can't handle default value of type '%s'"),
						     gda_g_type_to_string (pspec->g_type));
					g_object_unref (h);
					return FALSE;
				}
				value = gda_data_handler_get_value_from_sql (dh,
									     g_value_get_string (evalue),
									     pspec->g_type);
478 479 480 481
				if (!value)
					value = gda_value_new_default (g_value_get_string (evalue));
				gda_holder_set_default_value (h, value);
				gda_value_free (value);
482 483 484
			}
			else
				gda_holder_set_default_value (h, ((GdaSqlExpr*) node)->value);
485 486 487 488 489 490 491 492 493
			gda_holder_set_value_to_default (h);
		}
		gda_set_add_holder (*params, h);
		g_object_unref (h);
	}
	return TRUE;
}

/**
494
 * gda_statement_get_parameters:
495
 * @stmt: a #GdaStatement object
496
 * @out_params: (out) (nullable) (transfer full): a place to store a new #GdaSet object, or %NULL
497 498 499 500 501
 * @error: a place to store errors, or %NULL
 *
 * Get a new #GdaSet object which groups all the execution parameters
 * which @stmt needs. This new object is returned though @out_params.
 *
502 503
 * Note that if @stmt does not need any parameter, then @out_params is set to %NULL.
 *
504 505 506 507 508 509 510
 * Returns: TRUE if no error occurred.
 */
gboolean
gda_statement_get_parameters (GdaStatement *stmt, GdaSet **out_params, GError **error)
{
	GdaSet *set = NULL;
	g_return_val_if_fail (GDA_IS_STATEMENT (stmt), FALSE);
511
	GdaStatementPrivate *priv = gda_statement_get_instance_private (stmt);
512 513 514 515

	if (out_params)
		*out_params = NULL;

516
	if (!gda_sql_any_part_foreach (GDA_SQL_ANY_PART (priv->internal_struct->contents),
517 518 519 520 521 522 523 524 525 526 527 528 529 530 531
				       (GdaSqlForeachFunc) get_params_foreach_func, &set, error)) {
		if (set) {
			g_object_unref (set);
			set = NULL;
		}
		return FALSE;
	}
	
	if (out_params)
		*out_params = set;
	else
		g_object_unref (set);
	return TRUE;
}

532 533 534 535 536 537 538 539 540
/*
 * _gda_statement_get_requested_types:
 * @stmt: a #GdaStatement
 *
 * Returns: a new #GType, suitable to use with gda_connection_statement_execute_select_full(), or %NULL
 */
const GType *
_gda_statement_get_requested_types (GdaStatement *stmt)
{
541 542 543
	g_return_val_if_fail (GDA_IS_STATEMENT (stmt), NULL);
	GdaStatementPrivate *priv = gda_statement_get_instance_private (stmt);
	if (! priv->internal_struct)
544
		return NULL;
545 546 547
	if (priv->requested_types)
		return priv->requested_types;
	if (priv->internal_struct->stmt_type != GDA_SQL_STATEMENT_SELECT)
548 549 550 551 552 553
		return NULL;

	GdaSqlStatementSelect *selst;
	GSList *list;
	GArray *array = NULL;
 rewind:
554
	selst = (GdaSqlStatementSelect*) priv->internal_struct->contents;
555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576
	for (list = selst->expr_list; list; list = list->next) {
		GdaSqlExpr *expr;
		GType type = G_TYPE_INVALID;
		expr = ((GdaSqlSelectField*) list->data)->expr;
		if (expr->cast_as && *expr->cast_as)
			type = gda_g_type_from_string (expr->cast_as);
		if (array) {
			if (type == G_TYPE_INVALID)
				type = 0;
			g_array_append_val (array, type);
		}
		else if (type != G_TYPE_INVALID) {
			array = g_array_new (TRUE, FALSE, sizeof (GType));
			goto rewind;
		}
	}
	if (array) {
		GType *retval;
		guint len;
		len = array->len;
		retval = (GType*) g_array_free (array, FALSE);
		retval [len] = G_TYPE_NONE;
577
		priv->requested_types = retval;
578 579 580 581 582 583 584
		return retval;
	}
	else
		return NULL;
}


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
/*
 * SQL rendering
 */
static gchar *default_render_value (const GValue *value, GdaSqlRenderingContext *context, GError **error);
static gchar *default_render_param_spec (GdaSqlParamSpec *pspec, GdaSqlExpr *expr, GdaSqlRenderingContext *context, 
					 gboolean *is_default, gboolean *is_null, GError **error);

static gchar *default_render_unknown (GdaSqlStatementUnknown *stmt, GdaSqlRenderingContext *context, GError **error);
static gchar *default_render_select (GdaSqlStatementSelect *stmt, GdaSqlRenderingContext *context, GError **error);
static gchar *default_render_insert (GdaSqlStatementInsert *stmt, GdaSqlRenderingContext *context, GError **error);
static gchar *default_render_delete (GdaSqlStatementDelete *stmt, GdaSqlRenderingContext *context, GError **error);
static gchar *default_render_update (GdaSqlStatementUpdate *stmt, GdaSqlRenderingContext *context, GError **error);
static gchar *default_render_compound (GdaSqlStatementCompound *stmt, GdaSqlRenderingContext *context, GError **error);

static gchar *default_render_expr (GdaSqlExpr *expr, GdaSqlRenderingContext *context, 
				   gboolean *is_default, gboolean *is_null, GError **error);
static gchar *default_render_table (GdaSqlTable *table, GdaSqlRenderingContext *context, GError **error);
static gchar *default_render_field (GdaSqlField *field, GdaSqlRenderingContext *context, GError **error);
static gchar *default_render_function (GdaSqlFunction *func, GdaSqlRenderingContext *context, GError **error);
static gchar *default_render_operation (GdaSqlOperation *op, GdaSqlRenderingContext *context, GError **error);
static gchar *default_render_case (GdaSqlCase *case_s, GdaSqlRenderingContext *context, GError **error);
static gchar *default_render_select_field (GdaSqlSelectField *field, GdaSqlRenderingContext *context, GError **error);
static gchar *default_render_select_target (GdaSqlSelectTarget *target, GdaSqlRenderingContext *context, GError **error);
static gchar *default_render_select_join (GdaSqlSelectJoin *join, GdaSqlRenderingContext *context, GError **error);
static gchar *default_render_select_from (GdaSqlSelectFrom *from, GdaSqlRenderingContext *context, GError **error);
static gchar *default_render_select_order (GdaSqlSelectOrder *order, GdaSqlRenderingContext *context, GError **error);
611
static gchar *default_render_distinct (GdaSqlStatementSelect *select, GdaSqlRenderingContext *context, GError **error);
612

613
/**
614
 * gda_statement_to_sql_real:
615 616 617 618 619 620 621 622 623 624 625
 * @stmt: a #GdaStatement object
 * @context: a #GdaSqlRenderingContext context
 * @error: a place to store errors, or %NULL
 *
 * Renders @stmt to its SQL representation, using @context to specify how each part of @stmt must
 * be rendered. This function is mainly used by database provider's implementations which require
 * to specialize some aspects of SQL rendering to be adapted to the database,'s own SQL dialect
 * (for example SQLite rewrites the 'FALSE' and 'TRUE' literals as '0' and 'NOT 0').
 * 
 * Returns: a new string, or %NULL if an error occurred
 */
626 627 628 629 630
gchar *
gda_statement_to_sql_real (GdaStatement *stmt, GdaSqlRenderingContext *context, GError **error)
{
	GdaSqlStatementContentsInfo *cinfo;
	g_return_val_if_fail (GDA_IS_STATEMENT (stmt), NULL);
631
	GdaStatementPrivate *priv = gda_statement_get_instance_private (stmt);
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

	if (!context->render_value) 
		context->render_value = default_render_value;
	if (!context->render_param_spec) 
		context->render_param_spec = default_render_param_spec;
	if (!context->render_expr) 
		context->render_expr = default_render_expr;

	if (!context->render_unknown) 
		context->render_unknown = (GdaSqlRenderingFunc) default_render_unknown;
	if (!context->render_select) 
		context->render_select = (GdaSqlRenderingFunc) default_render_select;
	if (!context->render_insert) 
		context->render_insert = (GdaSqlRenderingFunc) default_render_insert;
	if (!context->render_delete) 
		context->render_delete = (GdaSqlRenderingFunc) default_render_delete;
	if (!context->render_update) 
		context->render_update = (GdaSqlRenderingFunc) default_render_update;
	if (!context->render_compound) 
		context->render_compound = (GdaSqlRenderingFunc) default_render_compound;

	if (!context->render_table) 
		context->render_table = (GdaSqlRenderingFunc) default_render_table;
	if (!context->render_field) 
		context->render_field = (GdaSqlRenderingFunc) default_render_field;
	if (!context->render_function) 
		context->render_function = (GdaSqlRenderingFunc) default_render_function;
	if (!context->render_operation) 
		context->render_operation = (GdaSqlRenderingFunc) default_render_operation;
	if (!context->render_case) 
		context->render_case = (GdaSqlRenderingFunc) default_render_case;
	if (!context->render_select_field)
		context->render_select_field = (GdaSqlRenderingFunc) default_render_select_field;
	if (!context->render_select_target)
		context->render_select_target = (GdaSqlRenderingFunc) default_render_select_target;
	if (!context->render_select_join)
		context->render_select_join = (GdaSqlRenderingFunc) default_render_select_join;
	if (!context->render_select_from)
		context->render_select_from = (GdaSqlRenderingFunc) default_render_select_from;
	if (!context->render_select_order)
		context->render_select_order = (GdaSqlRenderingFunc) default_render_select_order;
673 674
	if (!context->render_distinct)
		context->render_distinct = (GdaSqlRenderingFunc) default_render_distinct;
675

676 677
	cinfo = gda_sql_statement_get_contents_infos (priv->internal_struct->stmt_type);
	if (cinfo->check_structure_func && !cinfo->check_structure_func (GDA_SQL_ANY_PART (priv->internal_struct->contents),
678 679 680
									 NULL, error))
		return NULL;

681
	switch (GDA_SQL_ANY_PART (priv->internal_struct->contents)->type) {
682
	case GDA_SQL_ANY_STMT_UNKNOWN:
683
		return context->render_unknown (GDA_SQL_ANY_PART (priv->internal_struct->contents), context, error);
684 685
	case GDA_SQL_ANY_STMT_BEGIN:
		if (context->render_begin)
686
			return context->render_begin (GDA_SQL_ANY_PART (priv->internal_struct->contents), context, error);
687 688 689
		break;
	case GDA_SQL_ANY_STMT_ROLLBACK:
		if (context->render_rollback)
690
			return context->render_rollback (GDA_SQL_ANY_PART (priv->internal_struct->contents), context, error);
691 692 693
		break;
        case GDA_SQL_ANY_STMT_COMMIT:
		if (context->render_commit)
694
			return context->render_commit (GDA_SQL_ANY_PART (priv->internal_struct->contents), context, error);
695 696 697
		break;
        case GDA_SQL_ANY_STMT_SAVEPOINT:
		if (context->render_savepoint)
698
			return context->render_savepoint (GDA_SQL_ANY_PART (priv->internal_struct->contents), context, error);
699 700 701
		break;
        case GDA_SQL_ANY_STMT_ROLLBACK_SAVEPOINT:
		if (context->render_rollback_savepoint)
702
			return context->render_rollback_savepoint (GDA_SQL_ANY_PART (priv->internal_struct->contents), context, error);
703 704 705
		break;
        case GDA_SQL_ANY_STMT_DELETE_SAVEPOINT:
		if (context->render_delete_savepoint)
706
			return context->render_delete_savepoint (GDA_SQL_ANY_PART (priv->internal_struct->contents), context, error);
707 708
		break;
	case GDA_SQL_ANY_STMT_SELECT:
709
		return context->render_select (GDA_SQL_ANY_PART (priv->internal_struct->contents), context, error);
710
	case GDA_SQL_ANY_STMT_INSERT:
711
		return context->render_insert (GDA_SQL_ANY_PART (priv->internal_struct->contents), context, error);
712
	case GDA_SQL_ANY_STMT_DELETE:
713
		return context->render_delete (GDA_SQL_ANY_PART (priv->internal_struct->contents), context, error);
714
	case GDA_SQL_ANY_STMT_UPDATE:
715
		return context->render_update (GDA_SQL_ANY_PART (priv->internal_struct->contents), context, error);
716
	case GDA_SQL_ANY_STMT_COMPOUND:
717
		return context->render_compound (GDA_SQL_ANY_PART (priv->internal_struct->contents), context, error);
718 719 720 721 722 723
	default:
		TO_IMPLEMENT;
		return NULL;
		break;
	}

724 725 726
	/* default action is to use priv->internal_struct->sql */
	if (priv->internal_struct->sql)
		return g_strdup (priv->internal_struct->sql);
727 728
	else {
		g_set_error (error, GDA_SQL_ERROR, GDA_SQL_STRUCTURE_CONTENTS_ERROR,
729
			     "%s", _("Missing SQL code"));
730 731 732 733 734 735 736
		return NULL;
	}
}

static gchar *
default_render_value (const GValue *value, GdaSqlRenderingContext *context, GError **error)
{
737 738 739
	if (value && !gda_value_is_null (value)) {
		GdaDataHandler *dh;
		if (context->provider)
740
			dh = gda_server_provider_get_data_handler_g_type (context->provider, context->cnc, G_VALUE_TYPE (value));
741
		else  			
742
			dh = gda_data_handler_get_default (G_VALUE_TYPE (value));
743 744

		if (!dh) {
745
			if (g_type_is_a (G_VALUE_TYPE (value), GDA_TYPE_DEFAULT))
746 747 748 749 750 751 752
				return g_strdup ("DEFAULT");
			else {
				g_set_error (error, GDA_SQL_ERROR, GDA_SQL_STRUCTURE_CONTENTS_ERROR,
					     _("No data handler for type '%s'"),
					     g_type_name (G_VALUE_TYPE (value)));
				return NULL;
			}
753
		}
754
		if (context->flags & GDA_STATEMENT_SQL_TIMEZONE_TO_GMT) {
755
			if (g_type_is_a (G_VALUE_TYPE (value), GDA_TYPE_TIME)) {
756 757
				GdaTime *nts;
				nts = (GdaTime*) gda_value_get_time (value);
758
				if (nts && (gda_time_get_timezone (nts) != GDA_TIMEZONE_INVALID)) {
759 760
					nts = gda_time_copy (nts);
					gda_time_change_timezone (nts, 0);
761
					gda_time_set_timezone (nts, GDA_TIMEZONE_INVALID);
762 763 764 765 766 767 768 769 770 771
					GValue v = {0};
					g_value_init (&v, GDA_TYPE_TIME);
					gda_value_set_time (&v, nts);
					gda_time_free (nts);
					gchar *tmp;
					tmp = gda_data_handler_get_sql_from_value (dh, &v);
					g_value_reset (&v);
					return tmp;
				}
			}
772
			else if (g_type_is_a (G_VALUE_TYPE (value), G_TYPE_DATE_TIME)) {
773 774
				GDateTime *nts;
				nts = (GDateTime*) g_value_get_boxed (value);
775
				if (nts != NULL) {
776
					nts = (GDateTime*) g_date_time_to_utc ((GDateTime*) nts);
777 778 779 780 781 782 783 784 785
          if (nts != NULL) {
					  GValue v = {0};
					  g_value_init (&v, G_TYPE_DATE_TIME);
					  g_value_set_boxed (&v, nts);
					  gchar *tmp;
					  tmp = gda_data_handler_get_sql_from_value (dh, &v);
					  g_value_reset (&v);
					  return tmp;
          }
786 787 788 789
				}
			}
		}

790 791 792 793
		return gda_data_handler_get_sql_from_value (dh, value);
	}
	else
		return g_strdup ("NULL");
794 795 796
}

/**
797
 * gda_statement_to_sql_extended:
798
 * @stmt: a #GdaStatement object
799 800
 * @cnc: (nullable): a #GdaConnection object, or %NULL
 * @params: (nullable): parameters contained in a single #GdaSet object, or %NULL
801
 * @flags: a set of flags to control the rendering
802
 * @params_used: (element-type GdaHolder) (out) (transfer container) (nullable):a place to store the list of actual #GdaHolder objects in @params used to do the rendering, or %NULL
803 804 805 806 807
 * @error: a place to store errors, or %NULL
 *
 * Renders @stmt as an SQL statement, with some control on how it is rendered.
 *
 * If @cnc is not %NULL, then the rendered SQL will better be suited to be used by @cnc (in particular
808 809
 * it may include some SQL tweaks and/or proprietary extensions specific to the database engine used by @cnc):
 * in this case the result is similar to calling gda_connection_statement_to_sql().
810
 *
Jonh Wendell's avatar
Jonh Wendell committed
811
 * Returns: (transfer full): a new string if no error occurred
812 813
 */
gchar *
814 815
gda_statement_to_sql_extended (GdaStatement *stmt, GdaConnection *cnc, GdaSet *params,
			       GdaStatementSqlFlag flags, 
816 817 818 819 820 821 822 823 824 825
			       GSList **params_used, GError **error)
{
	gchar *str;
	GdaSqlRenderingContext context;

	g_return_val_if_fail (GDA_IS_STATEMENT (stmt), NULL);

	memset (&context, 0, sizeof (context));
	context.params = params;
	context.flags = flags;
826
	if (cnc) {
827 828 829
		if (gda_connection_is_opened (cnc))
			return _gda_server_provider_statement_to_sql (gda_connection_get_provider (cnc), cnc,
								      stmt, params, flags,
830
								      params_used, error);
831 832
		else
			context.provider = gda_connection_get_provider (cnc);
833
	}
834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 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 879 880 881 882 883

	str = gda_statement_to_sql_real (stmt, &context, error);

	if (str) {
		if (params_used)
			*params_used = context.params_used;
		else
			g_slist_free (context.params_used);
	}
	else {
		if (params_used)
			*params_used = NULL;
		g_slist_free (context.params_used);
	}
	return str;
}

static gchar *
default_render_unknown (GdaSqlStatementUnknown *stmt, GdaSqlRenderingContext *context, GError **error)
{
	GString *string;
	gchar *str;
	GSList *list;

	g_return_val_if_fail (stmt, NULL);
	g_return_val_if_fail (GDA_SQL_ANY_PART (stmt)->type == GDA_SQL_ANY_STMT_UNKNOWN, NULL);

	string = g_string_new ("");
	for (list = stmt->expressions; list; list = list->next) {
		str = context->render_expr ((GdaSqlExpr*) list->data, context, NULL, NULL, error);
		if (!str) goto err;
		g_string_append (string, str);
		g_free (str);
	}

	str = string->str;
	g_string_free (string, FALSE);
	return str;

 err:
	g_string_free (string, TRUE);
	return NULL;
}

static gchar *
default_render_insert (GdaSqlStatementInsert *stmt, GdaSqlRenderingContext *context, GError **error)
{
	GString *string;
	gchar *str;
	GSList *list;
884
	gboolean pretty = context->flags & GDA_STATEMENT_SQL_PRETTY;
885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917

	g_return_val_if_fail (stmt, NULL);
	g_return_val_if_fail (GDA_SQL_ANY_PART (stmt)->type == GDA_SQL_ANY_STMT_INSERT, NULL);

	string = g_string_new ("INSERT ");
	
	/* conflict algo */
	if (stmt->on_conflict)
		g_string_append_printf (string, "OR %s ", stmt->on_conflict);

	/* INTO */
	g_string_append (string, "INTO ");
	str = context->render_table (GDA_SQL_ANY_PART (stmt->table), context, error);
	if (!str) goto err;
	g_string_append (string, str);
	g_free (str);

	/* fields list */
	for (list = stmt->fields_list; list; list = list->next) {
		if (list == stmt->fields_list)
			g_string_append (string, " (");
		else
			g_string_append (string, ", ");
		str = context->render_field (GDA_SQL_ANY_PART (list->data), context, error);
		if (!str) goto err;
		g_string_append (string, str);
		g_free (str);
	}
	if (stmt->fields_list)
		g_string_append_c (string, ')');

	/* values */
	if (stmt->select) {
918 919 920 921
		if (pretty)
			g_string_append_c (string, '\n');
		else
			g_string_append_c (string, ' ');
922 923 924 925 926 927 928 929
		str = context->render_select (GDA_SQL_ANY_PART (stmt->select), context, error);
		if (!str) goto err;
		g_string_append (string, str);
			g_free (str);
	}
	else {
		for (list = stmt->values_list; list; list = list->next) {
			GSList *rlist;
930 931 932 933 934 935
			if (list == stmt->values_list) {
				if (pretty)
					g_string_append (string, "\nVALUES");
				else
					g_string_append (string, " VALUES");
			}
936
			else
937
				g_string_append_c (string, ',');
938 939 940 941 942 943 944
			for (rlist = (GSList*) list->data; rlist; rlist = rlist->next) {
				if (rlist == (GSList*) list->data)
					g_string_append (string, " (");
				else
					g_string_append (string, ", ");
				str = context->render_expr ((GdaSqlExpr*) rlist->data, context, NULL, NULL, error);
				if (!str) goto err;
945 946
				if (pretty && (rlist != (GSList*) list->data))
					g_string_append (string, "\n\t");
947 948 949 950 951
				g_string_append (string, str);
				g_free (str);
			}
			g_string_append_c (string, ')');
		}
952 953 954

		if (!stmt->fields_list && !stmt->values_list)
			g_string_append (string, " DEFAULT VALUES");
955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006
	}

	str = string->str;
	g_string_free (string, FALSE);
	return str;

 err:
	g_string_free (string, TRUE);
	return NULL;	
}

static gchar *
default_render_delete (GdaSqlStatementDelete *stmt, GdaSqlRenderingContext *context, GError **error)
{
	GString *string;
	gchar *str;

	g_return_val_if_fail (stmt, NULL);
	g_return_val_if_fail (GDA_SQL_ANY_PART (stmt)->type == GDA_SQL_ANY_STMT_DELETE, NULL);

	string = g_string_new ("DELETE FROM ");
	
	/* FROM */
	str = context->render_table (GDA_SQL_ANY_PART (stmt->table), context, error);
	if (!str) goto err;
	g_string_append (string, str);
	g_free (str);

	/* cond */
	if (stmt->cond) {
		g_string_append (string, " WHERE ");
		str = context->render_expr (stmt->cond, context, NULL, NULL, error);
		if (!str) goto err;
		g_string_append (string, str);
		g_free (str);
	}	

	str = string->str;
	g_string_free (string, FALSE);
	return str;

 err:
	g_string_free (string, TRUE);
	return NULL;	
}

static gchar *
default_render_update (GdaSqlStatementUpdate *stmt, GdaSqlRenderingContext *context, GError **error)
{
	GString *string;
	gchar *str;
	GSList *flist, *elist;
1007
	gboolean pretty = context->flags & GDA_STATEMENT_SQL_PRETTY;
1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023

	g_return_val_if_fail (stmt, NULL);
	g_return_val_if_fail (GDA_SQL_ANY_PART (stmt)->type == GDA_SQL_ANY_STMT_UPDATE, NULL);

	string = g_string_new ("UPDATE ");
	/* conflict algo */
	if (stmt->on_conflict)
		g_string_append_printf (string, "OR %s ", stmt->on_conflict);

	/* table */
	str = context->render_table (GDA_SQL_ANY_PART (stmt->table), context, error);
	if (!str) goto err;
	g_string_append (string, str);
	g_free (str);

	/* columns set */
1024 1025 1026 1027 1028 1029 1030 1031
	if (pretty)
		g_string_append (string, "\nSET ");
	else
		g_string_append (string, " SET ");
	for (flist = stmt->fields_list, elist = stmt->expr_list;
	     flist && elist;
	     flist = flist->next, elist = elist->next) {
		if (flist != stmt->fields_list) {
1032
			g_string_append (string, ", ");
1033 1034 1035
			if (pretty)
				g_string_append (string, "\n\t");
		}
1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048
		str = context->render_field (GDA_SQL_ANY_PART (flist->data), context, error);
		if (!str) goto err;
		g_string_append (string, str);
		g_free (str);
		g_string_append_c (string, '=');
		str = context->render_expr ((GdaSqlExpr *) elist->data, context, NULL, NULL, error);
		if (!str) goto err;
		g_string_append (string, str);
		g_free (str);
	}

	/* cond */
	if (stmt->cond) {
1049 1050 1051 1052
		if (pretty)
			g_string_append (string, "\nWHERE ");
		else
			g_string_append (string, " WHERE ");
1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109
		str = context->render_expr (stmt->cond, context, NULL, NULL, error);
		if (!str) goto err;
		g_string_append (string, str);
		g_free (str);
	}	

	str = string->str;
	g_string_free (string, FALSE);
	return str;

 err:
	g_string_free (string, TRUE);
	return NULL;
}

static gchar *
default_render_compound (GdaSqlStatementCompound *stmt, GdaSqlRenderingContext *context, GError **error)
{
	GString *string;
	gchar *str;
	GSList *list;

	g_return_val_if_fail (stmt, NULL);
	g_return_val_if_fail (GDA_SQL_ANY_PART (stmt)->type == GDA_SQL_ANY_STMT_COMPOUND, NULL);

	string = g_string_new ("");

	for (list = stmt->stmt_list; list; list = list->next) {
		GdaSqlStatement *sqlstmt = (GdaSqlStatement*) list->data;
		if (list != stmt->stmt_list) {
			switch (stmt->compound_type) {
			case GDA_SQL_STATEMENT_COMPOUND_UNION:
				g_string_append (string, " UNION ");
				break;
			case GDA_SQL_STATEMENT_COMPOUND_UNION_ALL:
				g_string_append (string, " UNION ALL ");
				break;
			case GDA_SQL_STATEMENT_COMPOUND_INTERSECT:
				g_string_append (string, " INTERSECT ");
				break;
			case GDA_SQL_STATEMENT_COMPOUND_INTERSECT_ALL:
				g_string_append (string, " INTERSECT ALL ");
				break;
			case GDA_SQL_STATEMENT_COMPOUND_EXCEPT:
				g_string_append (string, " EXCEPT ");
				break;
			case GDA_SQL_STATEMENT_COMPOUND_EXCEPT_ALL:
				g_string_append (string, " EXCEPT ALL ");
				break;
			default:
				g_assert_not_reached ();
			}
		}
		switch (sqlstmt->stmt_type) {
		case GDA_SQL_ANY_STMT_SELECT:
			str = context->render_select (GDA_SQL_ANY_PART (sqlstmt->contents), context, error);
			if (!str) goto err;
1110
			g_string_append_c (string, '(');
1111
			g_string_append (string, str);
1112
			g_string_append_c (string, ')');
1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137
			g_free (str);
			break;
		case GDA_SQL_ANY_STMT_COMPOUND:
			str = context->render_compound (GDA_SQL_ANY_PART (sqlstmt->contents), context, error);
			if (!str) goto err;
			g_string_append_c (string, '(');
			g_string_append (string, str);
			g_string_append_c (string, ')');
			g_free (str);
			break;
		default:
			g_assert_not_reached ();
		}
	}

	str = string->str;
	g_string_free (string, FALSE);
	return str;

 err:
	g_string_free (string, TRUE);
	return NULL;	
}

static gchar *
1138
default_render_distinct (GdaSqlStatementSelect *stmt, GdaSqlRenderingContext *context, GError **error)
1139
{
1140
	gboolean pretty = context->flags & GDA_STATEMENT_SQL_PRETTY;
1141 1142 1143 1144
	g_return_val_if_fail (stmt, NULL);
	g_return_val_if_fail (GDA_SQL_ANY_PART (stmt)->type == GDA_SQL_ANY_STMT_SELECT, NULL);

	if (stmt->distinct) {
1145 1146
		GString *string;
		string = g_string_new ("DISTINCT");
1147
		if (stmt->distinct_expr) {
1148
			gchar *str;
1149
			str = context->render_expr (stmt->distinct_expr, context, NULL, NULL, error);
1150 1151 1152 1153
			if (!str) {
				g_string_free (string, TRUE);
				return NULL;
			}
1154
			g_string_append (string, " ON (");
1155
			g_string_append (string, str);
1156
			g_string_append (string, ") ");
1157 1158
			g_free (str);
		}
1159 1160
		if (pretty)
			g_string_append_c (string, '\n');
1161 1162 1163 1164 1165 1166 1167 1168 1169 1170 1171 1172 1173 1174 1175 1176 1177 1178 1179 1180 1181 1182 1183 1184 1185
		return g_string_free (string, FALSE);
	}
	else
		return NULL;
}

static gchar *
default_render_select (GdaSqlStatementSelect *stmt, GdaSqlRenderingContext *context, GError **error)
{
	GString *string;
	gchar *str;
	GSList *list;
	gboolean pretty = context->flags & GDA_STATEMENT_SQL_PRETTY;

	g_return_val_if_fail (stmt, NULL);
	g_return_val_if_fail (GDA_SQL_ANY_PART (stmt)->type == GDA_SQL_ANY_STMT_SELECT, NULL);

	string = g_string_new ("SELECT ");
	/* distinct */
	if (stmt->distinct) {
		str = context->render_distinct (GDA_SQL_ANY_PART (stmt), context, error);
		if (!str) goto err;
		g_string_append (string, str);
		g_string_append_c (string, ' ');
		g_free (str);
1186 1187 1188 1189 1190 1191 1192 1193
	}
	
	/* selected expressions */
	for (list = stmt->expr_list; list; list = list->next) {
		str = context->render_select_field (GDA_SQL_ANY_PART (list->data), context, error);
		if (!str) goto err;
		if (list != stmt->expr_list)
			g_string_append (string, ", ");
1194 1195
		if (pretty)
			g_string_append (string, "\n\t");
1196 1197 1198 1199 1200 1201 1202 1203
		g_string_append (string, str);
		g_free (str);
	}

	/* FROM */
	if (stmt->from) {
		str = context->render_select_from (GDA_SQL_ANY_PART (stmt->from), context, error);
		if (!str) goto err;
1204 1205 1206 1207
		if (pretty)
			g_string_append_c (string, '\n');
		else
			g_string_append_c (string, ' ');
1208 1209 1210 1211 1212 1213
		g_string_append (string, str);
		g_free (str);
	}

	/* WHERE */
	if (stmt->where_cond) {
1214 1215 1216 1217
		if (pretty)
			g_string_append (string, "\nWHERE ");
		else
			g_string_append (string, " WHERE ");
1218 1219 1220 1221 1222 1223 1224 1225 1226 1227 1228 1229
		str = context->render_expr (stmt->where_cond, context, NULL, NULL, error);
		if (!str) goto err;
		g_string_append (string, str);
		g_free (str);
	}

	/* GROUP BY */
	for (list = stmt->group_by; list; list = list->next) {
		str = context->render_expr (list->data, context, NULL, NULL, error);
		if (!str) goto err;
		if (list != stmt->group_by)
			g_string_append (string, ", ");
1230 1231 1232 1233 1234 1235
		else {
			if (pretty)
				g_string_append (string, "\nGROUP BY ");
			else
				g_string_append (string, " GROUP BY ");
		}
1236 1237 1238 1239 1240 1241
		g_string_append (string, str);
		g_free (str);
	}

	/* HAVING */
	if (stmt->having_cond) {
1242 1243 1244 1245
		if (pretty)
			g_string_append (string, "\nHAVING ");
		else
			g_string_append (string, " HAVING ");
1246 1247 1248 1249 1250 1251 1252 1253 1254 1255 1256 1257
		str = context->render_expr (stmt->having_cond, context, NULL, NULL, error);
		if (!str) goto err;
		g_string_append (string, str);
		g_free (str);
	}

	/* ORDER BY */
	for (list = stmt->order_by; list; list = list->next) {
		str = context->render_select_order (GDA_SQL_ANY_PART (list->data), context, error);
		if (!str) goto err;
		if (list != stmt->order_by)
			g_string_append (string, ", ");
1258 1259 1260 1261 1262 1263
		else {
			if (pretty)
				g_string_append (string, "\nORDER BY ");
			else
				g_string_append (string, " ORDER BY ");
		}
1264 1265 1266 1267 1268 1269 1270 1271 1272 1273 1274 1275 1276 1277 1278 1279 1280 1281 1282 1283 1284 1285 1286 1287 1288 1289 1290 1291 1292 1293 1294 1295 1296 1297 1298 1299 1300 1301 1302 1303 1304 1305 1306 1307 1308 1309 1310 1311
		g_string_append (string, str);
		g_free (str);
	}

	/* LIMIT */
	if (stmt->limit_count) {
		g_string_append (string, " LIMIT ");
		str = context->render_expr (stmt->limit_count, context, NULL, NULL, error);
		if (!str) goto err;
		g_string_append (string, str);
		g_free (str);
		if (stmt->limit_offset) {
			g_string_append (string, " OFFSET ");
			str = context->render_expr (stmt->limit_offset, context, NULL, NULL, error);
			if (!str) goto err;
			g_string_append (string, str);
			g_free (str);
		}
	}

	str = string->str;
	g_string_free (string, FALSE);
	return str;

 err:
	g_string_free (string, TRUE);
	return NULL;
}

/*
 * Randers @pspec, and the default value stored in @expr->value if it exists
 */
static gchar *
default_render_param_spec (GdaSqlParamSpec *pspec, GdaSqlExpr *expr, GdaSqlRenderingContext *context, 
			   gboolean *is_default, gboolean *is_null, GError **error)
{
	GString *string;
	gchar *str;
	GdaHolder *h = NULL;
	gboolean render_pspec; /* if TRUE, then don't render parameter as its value but as a param specification */

	g_return_val_if_fail (pspec, NULL);

	render_pspec = FALSE;
	if (context->flags & (GDA_STATEMENT_SQL_PARAMS_LONG |
			      GDA_STATEMENT_SQL_PARAMS_SHORT |
			      GDA_STATEMENT_SQL_PARAMS_AS_COLON |
			      GDA_STATEMENT_SQL_PARAMS_AS_DOLLAR |
1312 1313
			      GDA_STATEMENT_SQL_PARAMS_AS_QMARK |
			      GDA_STATEMENT_SQL_PARAMS_AS_UQMARK))
1314 1315 1316 1317 1318 1319 1320 1321 1322 1323 1324 1325 1326 1327 1328 1329 1330 1331 1332 1333 1334
		render_pspec = TRUE;

	if (is_default)
		*is_default = FALSE;
	if (is_null)
		*is_null = FALSE;

	string = g_string_new ("");

	/* try to use a GdaHolder in context->params */
	if (context->params) {
		h = gda_set_get_holder (context->params, pspec->name);
		if (h && (gda_holder_get_g_type (h) != pspec->g_type)) {
			g_set_error (error, GDA_STATEMENT_ERROR, GDA_STATEMENT_PARAM_ERROR,
				     _("Wrong parameter type for '%s': expected type '%s' and got '%s'"), 
				     pspec->name, g_type_name (pspec->g_type), g_type_name (gda_holder_get_g_type (h)));
			goto err;
		}
	}
	if (!h && 
	    (!render_pspec ||
1335 1336 1337
	     (context->flags & (GDA_STATEMENT_SQL_PARAMS_AS_DOLLAR | 
				GDA_STATEMENT_SQL_PARAMS_AS_QMARK |
				GDA_STATEMENT_SQL_PARAMS_AS_UQMARK)))) {
1338 1339 1340 1341 1342 1343 1344 1345 1346 1347 1348 1349 1350 1351 1352 1353 1354 1355 1356 1357 1358 1359 1360 1361 1362 1363 1364 1365 1366 1367 1368 1369 1370 1371 1372 1373 1374 1375 1376 1377 1378 1379 1380 1381
		/* a real value is needed or @context->params_used needs to be correct, and no GdaHolder found */
		g_set_error (error, GDA_STATEMENT_ERROR, GDA_STATEMENT_PARAM_ERROR,
			     _("Missing parameter '%s'"), pspec->name);
		goto err;
	}
	if (h) {
		/* keep track of the params used */
		context->params_used = g_slist_append (context->params_used, h);

		if (! render_pspec) {
			const GValue *cvalue;
			
			if (!gda_holder_is_valid (h)) {
				g_set_error (error, GDA_STATEMENT_ERROR, GDA_STATEMENT_PARAM_ERROR,
					     _("Parameter '%s' is invalid"), pspec->name);
				goto err;
			}
			cvalue = gda_holder_get_value (h);
			if (cvalue) {
				str = context->render_value ((GValue*) cvalue, context, error);
				if (!str) goto err;
				g_string_append (string, str);
				g_free (str);
				if (is_null && gda_value_is_null (cvalue))
					*is_null = TRUE;
			}
			else {
				/* @h is set to a default value */
				g_string_append (string, "DEFAULT");
				if (is_default)
					*is_default = TRUE;
			}
			goto out;
		}
	}

	/* no parameter found in context->params => insert an SQL parameter */
	if (context->flags & GDA_STATEMENT_SQL_PARAMS_AS_COLON) {
		gchar *str;

		str = gda_text_to_alphanum (pspec->name);
		g_string_append_printf (string, ":%s", str);
		g_free (str);
	}
1382 1383 1384
	else if (context->flags & (GDA_STATEMENT_SQL_PARAMS_AS_DOLLAR | 
				   GDA_STATEMENT_SQL_PARAMS_AS_QMARK |
				   GDA_STATEMENT_SQL_PARAMS_AS_UQMARK)) {
1385 1386
		if (context->flags & GDA_STATEMENT_SQL_PARAMS_AS_DOLLAR)
			g_string_append_printf (string, "$%d", g_slist_length (context->params_used));
1387
		else if (context->flags & GDA_STATEMENT_SQL_PARAMS_AS_QMARK)
1388
			g_string_append_printf (string, "?%d", g_slist_length (context->params_used));
1389 1390
		else
			g_string_append_c (string, '?');
1391 1392 1393 1394 1395 1396 1397
	}
	else {
		GdaStatementSqlFlag flag = context->flags;
		gchar *quoted_pname;

		if (! pspec->name) {
			g_set_error (error, GDA_STATEMENT_ERROR, GDA_STATEMENT_PARAM_ERROR,
1398
				     "%s", _("Unnamed parameter"));
1399 1400
			goto err;
		}
1401
		quoted_pname = gda_sql_identifier_force_quotes (pspec->name);
1402 1403 1404 1405 1406 1407 1408 1409 1410 1411

		if (! (flag & (GDA_STATEMENT_SQL_PARAMS_LONG | GDA_STATEMENT_SQL_PARAMS_SHORT))) {
			if (!expr->value || gda_value_is_null (expr->value) || strcmp (quoted_pname, pspec->name))
				flag = GDA_STATEMENT_SQL_PARAMS_LONG;
			else
				flag = GDA_STATEMENT_SQL_PARAMS_SHORT;
		}

		if (flag & GDA_STATEMENT_SQL_PARAMS_LONG) {
			if (expr->value) {
1412 1413 1414 1415
				if (G_VALUE_TYPE (expr->value) == G_TYPE_STRING)
					str = g_value_dup_string (expr->value);
				else
					str = context->render_value (expr->value, context, error);
1416 1417 1418 1419 1420 1421 1422 1423 1424 1425 1426 1427
				if (!str) {
					g_free (quoted_pname);
					goto err;
				}
				g_string_append (string, str);
				g_free (str);
			}
			else
				g_string_append (string, "##");
			
			g_string_append (string, " /* ");
			g_string_append_printf (string, "name:%s", quoted_pname);
1428
			if (pspec->g_type) {
1429
				str = gda_sql_identifier_force_quotes (gda_g_type_to_string (pspec->g_type));
1430 1431 1432 1433
				g_string_append_printf (string, " type:%s", str);
				g_free (str);
			}
			if (pspec->descr) {
1434
				str = gda_sql_identifier_force_quotes (pspec->descr);
1435 1436 1437 1438 1439 1440 1441 1442 1443 1444 1445
				g_string_append_printf (string, " descr:%s", str);
				g_free (str);
			}
			if (pspec->nullok) 
				g_string_append (string, " nullok:true");

			g_string_append (string, " */");
		}
		else {
			g_string_append (string, "##");
			g_string_append (string, pspec->name);
1446
			if (pspec->g_type != GDA_TYPE_NULL) {
1447
				g_string_append (string, "::");
1448
				g_string_append (string, gda_g_type_to_string (pspec->g_type));
1449 1450 1451 1452 1453 1454 1455 1456 1457 1458 1459 1460 1461 1462 1463 1464 1465 1466 1467
				if (pspec->nullok) 
					g_string_append (string, "::NULL");
			}
		}

		g_free (quoted_pname);
	}

 out:
	str = string->str;
	g_string_free (string, FALSE);
	return str;

 err:
	g_string_free (string, TRUE);
	return NULL;
}

static gchar *
1468 1469
default_render_expr (GdaSqlExpr *expr, GdaSqlRenderingContext *context, gboolean *is_default,
		     gboolean *is_null, GError **error)
1470 1471 1472 1473 1474 1475 1476 1477 1478 1479 1480 1481
{
	GString *string;
	gchar *str = NULL;

	g_return_val_if_fail (expr, NULL);
	g_return_val_if_fail (GDA_SQL_ANY_PART (expr)->type == GDA_SQL_ANY_EXPR, NULL);

	if (is_default)
		*is_default = FALSE;
	if (is_null)
		*is_null = FALSE;

1482 1483
	/* can't have:
	 *  - expr->cast_as && expr->param_spec
1484 1485 1486 1487 1488 1489 1490 1491 1492
	 */
	if (!gda_sql_any_part_check_structure (GDA_SQL_ANY_PART (expr), error)) return NULL;

	string = g_string_new ("");
	if (expr->param_spec) {
		str = context->render_param_spec (expr->param_spec, expr, context, is_default, is_null, error);
		if (!str) goto err;
	}
	else if (expr->value) {
1493 1494 1495 1496 1497 1498 1499 1500 1501 1502 1503 1504 1505 1506 1507 1508 1509 1510 1511 1512 1513 1514 1515 1516 1517 1518 1519 1520 1521 1522 1523 1524 1525 1526 1527 1528 1529 1530 1531 1532
		if (G_VALUE_TYPE (expr->value) == G_TYPE_STRING) {
			/* specific treatment for strings, see documentation about GdaSqlExpr's value attribute */
			const gchar *vstr;
			vstr = g_value_get_string (expr->value);
			if (vstr) {
				if (expr->value_is_ident) {
					gchar **ids_array;
					gint i;
					GString *string = NULL;
					GdaConnectionOptions cncoptions = 0;
					if (context->cnc)
						g_object_get (G_OBJECT (context->cnc), "options", &cncoptions, NULL);
					ids_array = gda_sql_identifier_split (vstr);
					if (!ids_array)
						str = g_strdup (vstr);
					else if (!(ids_array[0])) goto err;
					else {
						for (i = 0; ids_array[i]; i++) {
							gchar *tmp;
							if (!string)
								string = g_string_new ("");
							else
								g_string_append_c (string, '.');
							tmp = gda_sql_identifier_quote (ids_array[i], context->cnc,
											context->provider, FALSE,
											cncoptions & GDA_CONNECTION_OPTIONS_SQL_IDENTIFIERS_CASE_SENSITIVE);
							g_string_append (string, tmp);
							g_free (tmp);
						}
						g_strfreev (ids_array);
						str = g_string_free (string, FALSE);
					}
				}
				else {
					/* we don't have an identifier */
					if (!g_ascii_strcasecmp (vstr, "default")) {
						if (is_default)
							*is_default = TRUE;
						str = g_strdup ("DEFAULT");
					}
1533
					else
1534
						str = g_strdup (vstr);
1535
				}
1536 1537 1538 1539 1540
			}
			else {
				str = g_strdup ("NULL");
				if (is_null)
					*is_null = TRUE;
1541 1542
			}
		}
1543 1544
		if (!str) {
			/* use a GdaDataHandler to render the value as valid SQL */
1545 1546 1547 1548 1549 1550 1551 1552 1553 1554 1555 1556 1557 1558 1559 1560
			GdaDataHandler *dh;
			if (context->cnc) {
				GdaServerProvider *prov;
				prov = gda_connection_get_provider (context->cnc);
				dh = gda_server_provider_get_data_handler_g_type (prov, context->cnc,
										  G_VALUE_TYPE (expr->value));
				if (!dh) goto err;
			}
			else
				dh = gda_data_handler_get_default (G_VALUE_TYPE (expr->value));

			if (dh)
				str = gda_data_handler_get_sql_from_value (dh, expr->value);
			else
				str = gda_value_stringify (expr->value);
			if (!str) goto err;
1561
		}
1562 1563 1564 1565 1566 1567
	}
	else if (expr->func) {
		str = context->render_function (GDA_SQL_ANY_PART (expr->func), context, error);
		if (!str) goto err;
	}
	else if (expr->cond) {
1568 1569 1570
		gchar *tmp;
		tmp = context->render_operation (GDA_SQL_ANY_PART (expr->cond), context, error);
		if (!tmp) goto err;
1571 1572 1573 1574 1575 1576 1577 1578 1579 1580 1581 1582 1583 1584 1585 1586 1587 1588 1589 1590 1591 1592 1593 1594 1595 1596 1597
		str = NULL;
		if (GDA_SQL_ANY_PART (expr)->parent) {
			if (GDA_SQL_ANY_PART (expr)->parent->type == GDA_SQL_ANY_STMT_SELECT) {
				GdaSqlStatementSelect *selst;
				selst = (GdaSqlStatementSelect*) (GDA_SQL_ANY_PART (expr)->parent);
				if ((expr == selst->where_cond) ||
				    (expr == selst->having_cond))
					str = tmp;
			}
			else if (GDA_SQL_ANY_PART (expr)->parent->type == GDA_SQL_ANY_STMT_DELETE) {
				GdaSqlStatementDelete *delst;
				delst = (GdaSqlStatementDelete*) (GDA_SQL_ANY_PART (expr)->parent);
				if (expr == delst->cond)
					str = tmp;
			}
			else if (GDA_SQL_ANY_PART (expr)->parent->type == GDA_SQL_ANY_STMT_UPDATE) {
				GdaSqlStatementUpdate *updst;
				updst = (GdaSqlStatementUpdate*) (GDA_SQL_ANY_PART (expr)->parent);
				if (expr == updst->cond)
					str = tmp;
			}
		}

		if (!str) {
			str = g_strconcat ("(", tmp, ")", NULL);
			g_free (tmp);
		}
1598 1599 1600
	}
	else if (expr->select) {
		gchar *str1;
1601 1602 1603 1604 1605 1606
		if (GDA_SQL_ANY_PART (expr->select)->type == GDA_SQL_ANY_STMT_SELECT)
			str1 = context->render_select (GDA_SQL_ANY_PART (expr->select), context, error);
		else if (GDA_SQL_ANY_PART (expr->select)->type == GDA_SQL_ANY_STMT_COMPOUND)
			str1 = context->render_compound (GDA_SQL_ANY_PART (expr->select), context, error);
		else
			g_assert_not_reached ();
1607
		if (!str1) goto err;
1608 1609 1610

		if (! GDA_SQL_ANY_PART (expr)->parent ||
		    (GDA_SQL_ANY_PART (expr)->parent->type != GDA_SQL_ANY_SQL_FUNCTION)) {
1611
			str = g_strconcat ("(", str1, ")", NULL);
1612 1613 1614 1615
			g_free (str1);
		}
		else
			str = str1;
1616 1617 1618 1619 1620 1621 1622 1623 1624 1625 1626
	}
	else if (expr->case_s) {
		str = context->render_case (GDA_SQL_ANY_PART (expr->case_s), context, error);
		if (!str) goto err;
	}
	else {
		if (is_null)
			*is_null = TRUE;
		str = g_strdup ("NULL");
	}

1627
	if (!str) goto err;
1628

1629
	if (expr->cast_as)
1630 1631 1632 1633 1634 1635 1636 1637 1638 1639 1640 1641 1642 1643 1644 1645 1646 1647 1648 1649 1650 1651 1652
		g_string_append_printf (string, "CAST (%s AS %s)", str, expr->cast_as);
	else
		g_string_append (string, str);
	g_free (str);

	str = string->str;
	g_string_free (string, FALSE);
	return str;

 err:
	g_string_free (string, TRUE);
	return NULL;
}

static gchar *
default_render_field (GdaSqlField *field, GdaSqlRenderingContext *context, GError **error)
{
	g_return_val_if_fail (field, NULL);
	g_return_val_if_fail (GDA_SQL_ANY_PART (field)->type == GDA_SQL_ANY_SQL_FIELD, NULL);

	/* can't have: field->field_name not a valid SQL identifier */
	if (!gda_sql_any_part_check_structure (GDA_SQL_ANY_PART (field), error)) return NULL;

1653 1654 1655 1656 1657 1658
	GdaConnectionOptions cncoptions = 0;
	if (context->cnc)
		g_object_get (G_OBJECT (context->cnc), "options", &cncoptions, NULL);
	return gda_sql_identifier_quote (field->field_name, context->cnc, context->provider,
					 FALSE,
					 cncoptions & GDA_CONNECTION_OPTIONS_SQL_IDENTIFIERS_CASE_SENSITIVE);
1659 1660 1661 1662 1663 1664 1665 1666 1667 1668 1669
}

static gchar *
default_render_table (GdaSqlTable *table, GdaSqlRenderingContext *context, GError **error)
{
	g_return_val_if_fail (table, NULL);
	g_return_val_if_fail (GDA_SQL_ANY_PART (table)->type == GDA_SQL_ANY_SQL_TABLE, NULL);

	/* can't have: table->table_name not a valid SQL identifier */
	if (!gda_sql_any_part_check_structure (GDA_SQL_ANY_PART (table), error)) return NULL;

1670 1671 1672 1673 1674 1675 1676 1677 1678 1679
	gchar **ids_array;
	ids_array = gda_sql_identifier_split (table->table_name);
	if (!ids_array) {
		g_set_error (error, GDA_SQL_ERROR, GDA_SQL_STRUCTURE_CONTENTS_ERROR,
			     "%s", _("Malformed table name"));
		return NULL;
	}
	
	gint i;
	GString *string;
1680 1681 1682
	GdaConnectionOptions cncoptions = 0;
	if (context->cnc)
		g_object_get (G_OBJECT (context->cnc), "options", &cncoptions, NULL);
1683 1684 1685 1686
	string = g_string_new ("");
	for (i = 0; ids_array [i]; i++) {
		gchar *tmp;
		tmp = gda_sql_identifier_quote (ids_array [i], context->cnc, context->provider,
1687 1688
						FALSE,
						cncoptions & GDA_CONNECTION_OPTIONS_SQL_IDENTIFIERS_CASE_SENSITIVE);
1689 1690 1691 1692 1693 1694 1695 1696
		g_free (ids_array [i]);
		ids_array [i] = tmp;
		if (i != 0)
			g_string_append_c (string, '.');
		g_string_append (string, ids_array [i]);
	}
	g_strfreev (ids_array);
	return g_string_free (string, FALSE);
1697 1698 1699 1700 1701 1702 1703 1704 1705 1706 1707 1708 1709 1710 1711 1712
}

static gchar *
default_render_function (GdaSqlFunction *func, GdaSqlRenderingContext *context, GError **error)
{
	GString *string;
	gchar *str;
	GSList *list;

	g_return_val_if_fail (func, NULL);
	g_return_val_if_fail (GDA_SQL_ANY_PART (func)->type == GDA_SQL_ANY_SQL_FUNCTION, NULL);

	/* can't have: func->function_name == NULL */
	if (!gda_sql_any_part_check_structure (GDA_SQL_ANY_PART (func), error)) return NULL;

	string = g_string_new (func->function_name);
1713
	g_string_append (string, " (");
1714 1715 1716 1717 1718
	for (list = func->args_list; list; list = list->next) {
		if (list != func->args_list)
			g_string_append (string, ", ");
		str = context->render_expr (list->data, context, NULL, NULL, error);
		if (!str) goto err;
1719 1720
		if (((GdaSqlExpr*) list->data)->select)
			g_string_append_c (string, '(');
1721
		g_string_append (string, str);
1722 1723
		if (((GdaSqlExpr*) list->data)->select)
			g_string_append_c (string, ')');
1724 1725 1726 1727 1728 1729 1730 1731 1732 1733 1734 1735 1736 1737 1738 1739 1740 1741 1742 1743