Example #1
0
/******************************************************************************
 *                                                                            *
 * Function: zbx_db_connect                                                   *
 *                                                                            *
 * Purpose: connect to the database                                           *
 *                                                                            *
 * Return value: ZBX_DB_OK - succefully connected                             *
 *               ZBX_DB_DOWN - database is down                               *
 *               ZBX_DB_FAIL - failed to connect                              *
 *                                                                            *
 ******************************************************************************/
int	zbx_db_connect(char *host, char *user, char *password, char *dbname, char *dbschema, char *dbsocket, int port)
{
	int		ret = ZBX_DB_OK;
#if defined(HAVE_IBM_DB2)
	char		*connect = NULL;
#elif defined(HAVE_ORACLE)
	char		*connect = NULL;
	sword		err = OCI_SUCCESS;
#elif defined(HAVE_POSTGRESQL)
	char		*cport = NULL;
	DB_RESULT	result;
	DB_ROW		row;
#endif

	txn_init = 1;

	assert(NULL != host);

#if defined(HAVE_IBM_DB2)
	connect = zbx_strdup(connect, "PROTOCOL=TCPIP;");
	if ('\0' != *host)
		connect = zbx_strdcatf(connect, "HOSTNAME=%s;", host);
	if (NULL != dbname && '\0' != *dbname)
		connect = zbx_strdcatf(connect, "DATABASE=%s;", dbname);
	if (0 != port)
		connect = zbx_strdcatf(connect, "PORT=%d;", port);
	if (NULL != user && '\0' != *user)
		connect = zbx_strdcatf(connect, "UID=%s;", user);
	if (NULL != password && '\0' != *password)
		connect = zbx_strdcatf(connect, "PWD=%s;", password);

	memset(&ibm_db2, 0, sizeof(ibm_db2));

	/* allocate an environment handle */
	if (SUCCEED != zbx_ibm_db2_success(SQLAllocHandle(SQL_HANDLE_ENV, SQL_NULL_HANDLE, &ibm_db2.henv)))
		ret = ZBX_DB_FAIL;

	/* set attribute to enable application to run as ODBC 3.0 application; */
	/* recommended for pure IBM DB2 CLI, but not required */
	if (ZBX_DB_OK == ret && SUCCEED != zbx_ibm_db2_success(SQLSetEnvAttr(ibm_db2.henv, SQL_ATTR_ODBC_VERSION,
			(void *)SQL_OV_ODBC3, 0)))
		ret = ZBX_DB_FAIL;

	/* allocate a database connection handle */
	if (ZBX_DB_OK == ret && SUCCEED != zbx_ibm_db2_success(SQLAllocHandle(SQL_HANDLE_DBC, ibm_db2.henv,
			&ibm_db2.hdbc)))
		ret = ZBX_DB_FAIL;

	/* connect to the database */
	if (ZBX_DB_OK == ret && SUCCEED != zbx_ibm_db2_success(SQLDriverConnect(ibm_db2.hdbc, NULL, (SQLCHAR *)connect,
			SQL_NTS, NULL, 0, NULL, SQL_DRIVER_NOPROMPT)))
		ret = ZBX_DB_FAIL;

	/* set autocommit on */
  	if (ZBX_DB_OK == ret && SUCCEED != zbx_ibm_db2_success(SQLSetConnectAttr(ibm_db2.hdbc, SQL_ATTR_AUTOCOMMIT,
								(SQLPOINTER)SQL_AUTOCOMMIT_ON, SQL_NTS)))
		ret = ZBX_DB_DOWN;

	/* we do not generate vendor escape clause sequences */
  	if (ZBX_DB_OK == ret && SUCCEED != zbx_ibm_db2_success(SQLSetConnectAttr(ibm_db2.hdbc, SQL_ATTR_NOSCAN,
								(SQLPOINTER)SQL_NOSCAN_ON, SQL_NTS)))
		ret = ZBX_DB_DOWN;

	/* set current schema */
	if (NULL != dbschema && '\0' != *dbschema && ZBX_DB_OK == ret)
	{
		char	*dbschema_esc;

		dbschema_esc = DBdyn_escape_string(dbschema);
		DBexecute("set current schema='%s'", dbschema_esc);
		zbx_free(dbschema_esc);
	}

	/* output error information */
	if (ZBX_DB_OK != ret)
	{
		zbx_ibm_db2_log_errors(SQL_HANDLE_ENV, ibm_db2.henv);
		zbx_ibm_db2_log_errors(SQL_HANDLE_DBC, ibm_db2.hdbc);

		zbx_db_close();
	}

	zbx_free(connect);
#elif defined(HAVE_MYSQL)
	conn = mysql_init(NULL);

	if (!mysql_real_connect(conn, host, user, password, dbname, port, dbsocket, CLIENT_MULTI_STATEMENTS))
	{
		zabbix_errlog(ERR_Z3001, dbname, mysql_errno(conn), mysql_error(conn));
		ret = ZBX_DB_FAIL;
	}

	if (ZBX_DB_OK == ret)
	{
		if (0 != mysql_select_db(conn, dbname))
		{
			zabbix_errlog(ERR_Z3001, dbname, mysql_errno(conn), mysql_error(conn));
			ret = ZBX_DB_FAIL;
		}
	}

	if (ZBX_DB_OK == ret)
	{
		DBexecute("set names utf8");
	}

	if (ZBX_DB_FAIL == ret)
	{
		switch (mysql_errno(conn))
		{
			case CR_CONN_HOST_ERROR:
			case CR_SERVER_GONE_ERROR:
			case CR_CONNECTION_ERROR:
			case CR_SERVER_LOST:
			case ER_SERVER_SHUTDOWN:
			case ER_ACCESS_DENIED_ERROR:		/* wrong user or password */
			case ER_ILLEGAL_GRANT_FOR_TABLE:	/* user without any privileges */
			case ER_TABLEACCESS_DENIED_ERROR:	/* user without some privilege */
			case ER_UNKNOWN_ERROR:
				ret = ZBX_DB_DOWN;
				break;
			default:
				break;
		}
	}
#elif defined(HAVE_ORACLE)
#if defined(HAVE_GETENV) && defined(HAVE_PUTENV)
	if (NULL == getenv("NLS_LANG"))
		putenv("NLS_LANG=.UTF8");
#endif
	memset(&oracle, 0, sizeof(oracle));

	/* connection string format: [//]host[:port][/service name] */

	if ('\0' != *host)
	{
		connect = zbx_strdcatf(connect, "//%s", host);
		if (0 != port)
			connect = zbx_strdcatf(connect, ":%d", port);
		if (NULL != dbname && '\0' != *dbname)
			connect = zbx_strdcatf(connect, "/%s", dbname);
	}
	else
		ret = ZBX_DB_FAIL;

	if (ZBX_DB_OK == ret)
	{
		/* initialize environment */
		err = OCIEnvCreate((OCIEnv **)&oracle.envhp, (ub4)OCI_DEFAULT,
				(dvoid *)0, (dvoid * (*)(dvoid *,size_t))0,
				(dvoid * (*)(dvoid *, dvoid *, size_t))0,
				(void (*)(dvoid *, dvoid *))0, (size_t)0, (dvoid **)0);

		if (OCI_SUCCESS != err)
		{
			zabbix_errlog(ERR_Z3001, connect, err, zbx_oci_error(err));
			ret = ZBX_DB_FAIL;
		}
	}

	if (ZBX_DB_OK == ret)
	{
		/* allocate an error handle */
		(void)OCIHandleAlloc((dvoid *)oracle.envhp, (dvoid **)&oracle.errhp, OCI_HTYPE_ERROR,
				(size_t)0, (dvoid **)0);

		/* get the session */
		err = OCILogon2(oracle.envhp, oracle.errhp, &oracle.svchp,
				(text *)user, (ub4)(NULL != user ? strlen(user) : 0),
				(text *)password, (ub4)(NULL != password ? strlen(password) : 0),
				(text *)connect, (ub4)strlen(connect),
				OCI_DEFAULT);

		if (OCI_SUCCESS != err)
		{
			zabbix_errlog(ERR_Z3001, connect, err, zbx_oci_error(err));
			ret = ZBX_DB_DOWN;
		}
		else
		{
			err = OCIAttrGet((void *)oracle.svchp, OCI_HTYPE_SVCCTX, (void *)&oracle.srvhp, (ub4 *)0,
					OCI_ATTR_SERVER, oracle.errhp);

			if (OCI_SUCCESS != err)
			{
				zabbix_errlog(ERR_Z3001, connect, err, zbx_oci_error(err));
				ret = ZBX_DB_DOWN;
			}
		}
	}

	zbx_free(connect);

	if (ZBX_DB_OK != ret)
		zbx_db_close();
#elif defined(HAVE_POSTGRESQL)
	if (0 != port)
		cport = zbx_dsprintf(cport, "%d", port);

	conn = PQsetdbLogin(host, cport, NULL, NULL, dbname, user, password);

	zbx_free(cport);

	/* check to see that the backend connection was successfully made */
	if (CONNECTION_OK != PQstatus(conn))
	{
		zabbix_errlog(ERR_Z3001, dbname, 0, PQerrorMessage(conn));
		ret = ZBX_DB_DOWN;
	}
	else
	{
		result = DBselect("select oid from pg_type where typname='bytea'");
		if (NULL != (row = DBfetch(result)))
			ZBX_PG_BYTEAOID = atoi(row[0]);
		DBfree_result(result);
	}

#ifdef HAVE_FUNCTION_PQSERVERVERSION
	ZBX_PG_SVERSION = PQserverVersion(conn);
	zabbix_log(LOG_LEVEL_DEBUG, "PostgreSQL Server version: %d", ZBX_PG_SVERSION);
#endif

	if (80100 <= ZBX_PG_SVERSION)
	{
		/* disable "nonstandard use of \' in a string literal" warning */
		DBexecute("set escape_string_warning to off");

		result = DBselect("show standard_conforming_strings");
		if (NULL != (row = DBfetch(result)))
			ZBX_PG_ESCAPE_BACKSLASH = (0 == strcmp(row[0], "off"));
		DBfree_result(result);
	}

	if (90000 <= ZBX_PG_SVERSION)
	{
		/* change the output format for values of type bytea from hex (the default) to escape */
		DBexecute("set bytea_output=escape");
	}
#elif defined(HAVE_SQLITE3)
#ifdef HAVE_FUNCTION_SQLITE3_OPEN_V2
	if (SQLITE_OK != sqlite3_open_v2(dbname, &conn, SQLITE_OPEN_READWRITE, NULL))
#else
	if (SQLITE_OK != sqlite3_open(dbname, &conn))
#endif
	{
		zabbix_errlog(ERR_Z3001, dbname, 0, sqlite3_errmsg(conn));
		sqlite3_close(conn);
		ret = ZBX_DB_DOWN;
	}
	else
	{
		char	*p, *path;

		/* do not return SQLITE_BUSY immediately, wait for N ms */
		sqlite3_busy_timeout(conn, SEC_PER_MIN * 1000);

		path = strdup(dbname);
		if (NULL != (p = strrchr(path, '/')))
			*++p = '\0';
		else
			*path = '\0';

		DBexecute("PRAGMA synchronous = 0");	/* OFF */
		DBexecute("PRAGMA temp_store = 2");	/* MEMORY */
		DBexecute("PRAGMA temp_store_directory = '%s'", path);

		zbx_free(path);
	}
#endif	/* HAVE_SQLITE3 */

	txn_init = 0;

	return ret;
}
Example #2
0
int SQLiteFileSystem::openDatabase(const String& filename, sqlite3** database, bool)
{
    return sqlite3_open_v2(fileSystemRepresentation(filename).data(), database, SQLITE_OPEN_READWRITE | SQLITE_OPEN_CREATE | SQLITE_OPEN_AUTOPROXY, nullptr);
}
Example #3
0
static svn_error_t *
internal_open(svn_sqlite__db_t *db, const char *path, svn_sqlite__mode_t mode,
              apr_int32_t timeout, apr_pool_t *scratch_pool)
{
  {
    int flags;

    if (mode == svn_sqlite__mode_readonly)
      flags = SQLITE_OPEN_READONLY;
    else if (mode == svn_sqlite__mode_readwrite)
      flags = SQLITE_OPEN_READWRITE;
    else if (mode == svn_sqlite__mode_rwcreate)
      flags = SQLITE_OPEN_READWRITE | SQLITE_OPEN_CREATE;
    else
      SVN_ERR_MALFUNCTION();

    /* Turn off SQLite's mutexes. All svn objects are single-threaded,
       so we can already guarantee that our use of the SQLite handle
       will be serialized properly.

       Note: in 3.6.x, we've already config'd SQLite into MULTITHREAD mode,
       so this is probably redundant, but if we are running in a process where
       somebody initialized SQLite before us it is needed anyway.  */
    flags |= SQLITE_OPEN_NOMUTEX;

#if !defined(WIN32) && !defined(SVN_SQLITE_INLINE)
    if (mode == svn_sqlite__mode_rwcreate)
      {
        svn_node_kind_t kind;

        /* Create the file before SQLite to avoid any permissions
           problems with an SQLite build that uses the default
           SQLITE_DEFAULT_FILE_PERMISSIONS of 644 modified by umask.
           We simply want umask permissions. */
        SVN_ERR(svn_io_check_path(path, &kind, scratch_pool));
        if (kind == svn_node_none)
          {
            /* Another thread may have created the file, that's OK. */
            svn_error_t *err = svn_io_file_create_empty(path, scratch_pool);
            if (err && !APR_STATUS_IS_EEXIST(err->apr_err))
              return svn_error_trace(err);
            svn_error_clear(err);
          }
      }
#endif

    /* Open the database. Note that a handle is returned, even when an error
       occurs (except for out-of-memory); thus, we can safely use it to
       extract an error message and construct an svn_error_t.  SQLite always
       requires sqlite3_close() after sqlite3_open_v2() while Subversion
       typically does not require close() after an open() that returns an
       error.  So we must ensure we close the handle if this function, or
       the caller svn_sqlite__open, returns an error to the application. */
    {
      const char *vFs = NULL;

#if defined(WIN32) && SQLITE_VERSION_AT_LEAST(3, 8, 1)
      if (strlen(path) > 248)
        {
          WCHAR *win_path;
          vFs = "win32-longpath"; /* Enable long paths in sqlite */

          /* Long paths must be absolute */
          if (!svn_dirent_is_absolute(path))
            SVN_ERR(svn_dirent_get_absolute(&path, path, scratch_pool));

          /* Convert the path to a properly canonicalized \\?\C:\long\path */
          SVN_ERR(svn_io__utf8_to_unicode_longpath(&win_path, path,
                                                   scratch_pool));

          /* And convert it back to UTF-8 because there is no
              sqlite3_open16_v2() yet */
          SVN_ERR(svn_utf__win32_utf16_to_utf8(&path, win_path, NULL,
                                               scratch_pool));
        }
#endif

      /* ### SQLITE_CANTOPEN */
      SQLITE_ERR_CLOSE(sqlite3_open_v2(path, &db->db3, flags, vFs),
                       db, scratch_pool);
    }
  }

  if (timeout <= 0)
    timeout = BUSY_TIMEOUT;

  /* Retry until timeout when database is busy. */
  SQLITE_ERR_CLOSE(sqlite3_busy_timeout(db->db3, timeout),
                   db, scratch_pool);

  return SVN_NO_ERROR;
}
int
main (int argc, char *argv[])
{
/* the MAIN function simply perform arguments checking */
    sqlite3 *handle;
    int i;
    int next_arg = ARG_NONE;
    const char *gml_path = NULL;
    const char *db_path = NULL;
    const char *table = NULL;
    int in_memory = 0;
    int error = 0;
    char Buff[BUFFSIZE];
    int done = 0;
    int len;
    XML_Parser parser;
    FILE *xml_file;
    struct gml_params params;
    int ret;
    char *err_msg = NULL;
    void *cache;

    params.db_handle = NULL;
    params.stmt = NULL;
    params.geometry_type = GEOM_NONE;
    params.srid = INT_MIN;
    params.is_feature = 0;
    params.is_fid = 0;
    params.is_point = 0;
    params.is_linestring = 0;
    params.is_polygon = 0;
    params.is_multi_point = 0;
    params.is_multi_linestring = 0;
    params.is_multi_polygon = 0;
    params.first = NULL;
    params.last = NULL;
    params.geometry = NULL;
    params.polygon.exterior = NULL;
    params.polygon.first = NULL;
    params.polygon.last = NULL;
    params.CharDataStep = 65536;
    params.CharDataMax = params.CharDataStep;
    params.CharData = malloc (params.CharDataStep);

    for (i = 1; i < argc; i++)
      {
	  /* parsing the invocation arguments */
	  if (next_arg != ARG_NONE)
	    {
		switch (next_arg)
		  {
		  case ARG_GML_PATH:
		      gml_path = argv[i];
		      break;
		  case ARG_DB_PATH:
		      db_path = argv[i];
		      break;
		  case ARG_TABLE:
		      table = argv[i];
		      break;
		  };
		next_arg = ARG_NONE;
		continue;
	    }
	  if (strcasecmp (argv[i], "--help") == 0
	      || strcmp (argv[i], "-h") == 0)
	    {
		do_help ();
		return -1;
	    }
	  if (strcmp (argv[i], "-g") == 0)
	    {
		next_arg = ARG_GML_PATH;
		continue;
	    }
	  if (strcasecmp (argv[i], "--gml-path") == 0)
	    {
		next_arg = ARG_GML_PATH;
		continue;
	    }
	  if (strcmp (argv[i], "-d") == 0)
	    {
		next_arg = ARG_DB_PATH;
		continue;
	    }
	  if (strcasecmp (argv[i], "--db-path") == 0)
	    {
		next_arg = ARG_DB_PATH;
		continue;
	    }
	  if (strcmp (argv[i], "-t") == 0)
	    {
		next_arg = ARG_TABLE;
		continue;
	    }
	  if (strcasecmp (argv[i], "--table-name") == 0)
	    {
		next_arg = ARG_TABLE;
		continue;
	    }
	  if (strcasecmp (argv[i], "-m") == 0)
	    {
		in_memory = 1;
		next_arg = ARG_NONE;
		continue;
	    }
	  if (strcasecmp (argv[i], "-in-memory") == 0)
	    {
		in_memory = 1;
		next_arg = ARG_NONE;
		continue;
	    }
	  if (strcasecmp (argv[i], "-n") == 0)
	    {
		next_arg = ARG_NONE;
		continue;
	    }
	  if (strcasecmp (argv[i], "-no-spatial-index") == 0)
	    {
		next_arg = ARG_NONE;
		continue;
	    }
	  fprintf (stderr, "unknown argument: %s\n", argv[i]);
	  error = 1;
      }
    if (error)
      {
	  do_help ();
	  return -1;
      }

/* checking the arguments */
    if (!gml_path)
      {
	  fprintf (stderr,
		   "did you forget setting the --gml-path argument ?\n");
	  error = 1;
      }
    if (!db_path)
      {
	  fprintf (stderr, "did you forget setting the --db-path argument ?\n");
	  error = 1;
      }
    if (!table)
      {
	  fprintf (stderr,
		   "did you forget setting the --table-name argument ?\n");
	  error = 1;
      }
    if (error)
      {
	  do_help ();
	  return -1;
      }

/* opening the DB */
    cache = spatialite_alloc_connection ();
    open_db (db_path, &handle, cache);
    if (!handle)
	return -1;
    params.db_handle = handle;
    if (in_memory)
      {
	  /* loading the DB in-memory */
	  sqlite3 *mem_db_handle;
	  sqlite3_backup *backup;
	  int ret;
	  ret =
	      sqlite3_open_v2 (":memory:", &mem_db_handle,
			       SQLITE_OPEN_READWRITE | SQLITE_OPEN_CREATE,
			       NULL);
	  if (ret != SQLITE_OK)
	    {
		fprintf (stderr, "cannot open 'MEMORY-DB': %s\n",
			 sqlite3_errmsg (mem_db_handle));
		sqlite3_close (mem_db_handle);
		return -1;
	    }
	  backup = sqlite3_backup_init (mem_db_handle, "main", handle, "main");
	  if (!backup)
	    {
		fprintf (stderr, "cannot load 'MEMORY-DB'\n");
		sqlite3_close (handle);
		sqlite3_close (mem_db_handle);
		return -1;
	    }
	  while (1)
	    {
		ret = sqlite3_backup_step (backup, 1024);
		if (ret == SQLITE_DONE)
		    break;
	    }
	  ret = sqlite3_backup_finish (backup);
	  sqlite3_close (handle);
	  handle = mem_db_handle;
	  printf ("\nusing IN-MEMORY database\n");
	  spatialite_cleanup_ex (cache);
	  cache = spatialite_alloc_connection ();
	  spatialite_init_ex (handle, cache, 0);
      }

/* XML parsing */
    xml_file = fopen (gml_path, "rb");
    if (!xml_file)
      {
	  fprintf (stderr, "cannot open %s\n", gml_path);
	  sqlite3_close (handle);
	  return -1;
      }
    parser = XML_ParserCreate (NULL);
    if (!parser)
      {
	  fprintf (stderr, "Couldn't allocate memory for parser\n");
	  sqlite3_close (handle);
	  return -1;
      }

    XML_SetUserData (parser, &params);
/* XML parsing: pass I */
    XML_SetElementHandler (parser, start1_tag, end1_tag);
    XML_SetCharacterDataHandler (parser, gmlCharData);
    while (!done)
      {
	  len = fread (Buff, 1, BUFFSIZE, xml_file);
	  if (ferror (xml_file))
	    {
		fprintf (stderr, "XML Read error\n");
		sqlite3_close (handle);
		return -1;
	    }
	  done = feof (xml_file);
	  if (!XML_Parse (parser, Buff, len, done))
	    {
		fprintf (stderr, "Parse error at line %d:\n%s\n",
			 (int) XML_GetCurrentLineNumber (parser),
			 XML_ErrorString (XML_GetErrorCode (parser)));
		sqlite3_close (handle);
		return -1;
	    }
      }
    XML_ParserFree (parser);

/* creating the DB table */
    if (!create_table (&params, table))
	goto no_table;

/* XML parsing: pass II */
    parser = XML_ParserCreate (NULL);
    if (!parser)
      {
	  fprintf (stderr, "Couldn't allocate memory for parser\n");
	  sqlite3_close (handle);
	  return -1;
      }
    XML_SetUserData (parser, &params);
    XML_SetElementHandler (parser, start2_tag, end2_tag);
    XML_SetCharacterDataHandler (parser, gmlCharData);
    rewind (xml_file);
    params.is_feature = 0;
    params.is_fid = 0;
    params.is_point = 0;
    params.is_linestring = 0;
    params.is_polygon = 0;
    params.is_multi_point = 0;
    params.is_multi_linestring = 0;
    params.is_multi_polygon = 0;
    done = 0;
    while (!done)
      {
	  len = fread (Buff, 1, BUFFSIZE, xml_file);
	  if (ferror (xml_file))
	    {
		fprintf (stderr, "XML Read error\n");
		sqlite3_close (handle);
		return -1;
	    }
	  done = feof (xml_file);
	  if (!XML_Parse (parser, Buff, len, done))
	    {
		fprintf (stderr, "Parse error at line %d:\n%s\n",
			 (int) XML_GetCurrentLineNumber (parser),
			 XML_ErrorString (XML_GetErrorCode (parser)));
		sqlite3_close (handle);
		return -1;
	    }
      }
    XML_ParserFree (parser);
    if (params.stmt != NULL)
	sqlite3_finalize (params.stmt);
    params.stmt = NULL;

    /* COMMITTing the still pending Transaction */
    ret = sqlite3_exec (handle, "COMMIT", NULL, NULL, &err_msg);
    if (ret != SQLITE_OK)
      {
	  fprintf (stderr, "COMMIT TRANSACTION error: %s\n", err_msg);
	  sqlite3_free (err_msg);
	  return 0;
      }

  no_table:
    free_columns (&params);
    fclose (xml_file);

    if (in_memory)
      {
	  /* exporting the in-memory DB to filesystem */
	  sqlite3 *disk_db_handle;
	  sqlite3_backup *backup;
	  int ret;
	  printf ("\nexporting IN_MEMORY database ... wait please ...\n");
	  ret =
	      sqlite3_open_v2 (db_path, &disk_db_handle,
			       SQLITE_OPEN_READWRITE | SQLITE_OPEN_CREATE,
			       NULL);
	  if (ret != SQLITE_OK)
	    {
		fprintf (stderr, "cannot open '%s': %s\n", db_path,
			 sqlite3_errmsg (disk_db_handle));
		sqlite3_close (disk_db_handle);
		return -1;
	    }
	  backup = sqlite3_backup_init (disk_db_handle, "main", handle, "main");
	  if (!backup)
	    {
		fprintf (stderr, "Backup failure: 'MEMORY-DB' wasn't saved\n");
		sqlite3_close (handle);
		sqlite3_close (disk_db_handle);
		return -1;
	    }
	  while (1)
	    {
		ret = sqlite3_backup_step (backup, 1024);
		if (ret == SQLITE_DONE)
		    break;
	    }
	  ret = sqlite3_backup_finish (backup);
	  sqlite3_close (handle);
	  handle = disk_db_handle;
	  printf ("\tIN_MEMORY database succesfully exported\n");
      }

    sqlite3_close (handle);
    spatialite_cleanup_ex (cache);
    return 0;
}
int
main (int argc, char *argv[])
{
#ifndef OMIT_ICONV		/* only if ICONV is supported */
    int ret;
    sqlite3 *handle;
    char *err_msg = NULL;
    int row_count;
    char **results;
    int rows;
    int columns;
    int pt;
    void *cache = spatialite_alloc_connection ();

    if (argc > 1 || argv[0] == NULL)
	argc = 1;		/* silencing stupid compiler warnings */

    ret =
	sqlite3_open_v2 (":memory:", &handle,
			 SQLITE_OPEN_READWRITE | SQLITE_OPEN_CREATE, NULL);
    if (ret != SQLITE_OK)
      {
	  fprintf (stderr, "cannot open in-memory database: %s\n",
		   sqlite3_errmsg (handle));
	  sqlite3_close (handle);
	  return -1;
      }

    spatialite_init_ex (handle, cache, 0);

    ret =
	sqlite3_exec (handle, "SELECT InitSpatialMetadata(1)", NULL, NULL,
		      &err_msg);
    if (ret != SQLITE_OK)
      {
	  fprintf (stderr, "InitSpatialMetadata() error: %s\n", err_msg);
	  sqlite3_free (err_msg);
	  sqlite3_close (handle);
	  return -2;
      }

    ret = load_shapefile (handle, "shp/foggia/local_councils", "Councils",
			  "CP1252", 23032, "geom", 1, 0, 1, 0, &row_count,
			  err_msg);
    if (!ret)
      {
	  fprintf (stderr, "load_shapefile() error: %s\n", err_msg);
	  sqlite3_close (handle);
	  return -3;
      }
    if (row_count != 61)
      {
	  fprintf (stderr, "unexpected number of rows loaded: %i\n", row_count);
	  sqlite3_close (handle);
	  return -4;
      }

    ret =
	sqlite3_get_table (handle,
			   "SELECT lc_name FROM Councils WHERE MbrWithin(geom, BuildMbr(1040523, 4010000, 1140523, 4850000)) ORDER BY lc_name;",
			   &results, &rows, &columns, &err_msg);
    if (ret != SQLITE_OK)
      {
	  fprintf (stderr, "Error: %s\n", err_msg);
	  sqlite3_free (err_msg);
	  return -5;
      }
    if ((rows != 22) || (columns != 1))
      {
	  fprintf (stderr,
		   "Unexpected error: select lc_name bad result: %i/%i.\n",
		   rows, columns);
	  sqlite3_free_table (results);
	  sqlite3_close (handle);
	  return -6;
      }
    if (strcmp (results[1], "Ascoli Satriano") != 0)
      {
	  fprintf (stderr, "unexpected result at 1: %s\n", results[1]);
	  sqlite3_free_table (results);
	  sqlite3_close (handle);
	  return -7;
      }
    if (strcmp (results[22], "Zapponeta") != 0)
      {
	  fprintf (stderr, "unexpected result at 22: %s\n", results[22]);
	  sqlite3_free_table (results);
	  sqlite3_close (handle);
	  return -8;
      }
    sqlite3_free_table (results);

    ret = sqlite3_exec (handle, "SELECT CreateMbrCache('Councils', 'geom');",
			NULL, NULL, &err_msg);
    if (ret != SQLITE_OK)
      {
	  fprintf (stderr, "CreateMbrCache error: %s\n", err_msg);
	  sqlite3_free (err_msg);
	  return -9;
      }

    rows = 0;
    columns = 0;
    ret =
	sqlite3_get_table (handle,
			   "SELECT lc_name FROM Councils WHERE ROWID IN (SELECT rowid FROM cache_Councils_geom WHERE mbr = FilterMbrWithin(1040523, 4010000, 1140523, 4850000)) ORDER BY lc_name;",
			   &results, &rows, &columns, &err_msg);
    if (ret != SQLITE_OK)
      {
	  fprintf (stderr, "Error in Mbr SELECT: %s\n", err_msg);
	  sqlite3_free (err_msg);
	  return -14;
      }
    if ((rows != 22) || (columns != 1))
      {
	  fprintf (stderr,
		   "Unexpected error: select lc_name bad cache result: %i/%i.\n",
		   rows, columns);
	  sqlite3_free_table (results);
	  sqlite3_close (handle);
	  return -15;
      }
    if (strcmp (results[1], "Ascoli Satriano") != 0)
      {
	  fprintf (stderr, "unexpected mbr result at 1: %s\n", results[1]);
	  sqlite3_free_table (results);
	  sqlite3_close (handle);
	  return -16;
      }
    if (strcmp (results[22], "Zapponeta") != 0)
      {
	  fprintf (stderr, "unexpected mbr result at 22: %s\n", results[22]);
	  sqlite3_free_table (results);
	  sqlite3_close (handle);
	  return -17;
      }
    sqlite3_free_table (results);

    rows = 0;
    columns = 0;
    ret =
	sqlite3_get_table (handle,
			   "SELECT lc_name FROM Councils WHERE ROWID IN (SELECT rowid FROM cache_Councils_geom WHERE mbr = FilterMbrContains(997226.750031, 4627372.000018, 997226.750031, 4627372.000018)) ORDER BY lc_name;",
			   &results, &rows, &columns, &err_msg);
    if (ret != SQLITE_OK)
      {
	  fprintf (stderr, "Error in Mbr SELECT Contains: %s\n", err_msg);
	  sqlite3_free (err_msg);
	  return -18;
      }
    if ((rows != 1) || (columns != 1))
      {
	  fprintf (stderr,
		   "Unexpected error: select lc_name bad cache result: %i/%i.\n",
		   rows, columns);
	  sqlite3_free_table (results);
	  sqlite3_close (handle);
	  return -19;
      }
    if (strcmp (results[1], "Carlantino") != 0)
      {
	  fprintf (stderr, "unexpected mbr result at 1: %s\n", results[1]);
	  sqlite3_free_table (results);
	  sqlite3_close (handle);
	  return -20;
      }
    sqlite3_free_table (results);

    rows = 0;
    columns = 0;
    ret =
	sqlite3_get_table (handle,
			   "SELECT lc_name FROM Councils WHERE ROWID IN (SELECT rowid FROM cache_Councils_geom WHERE mbr = FilterMbrIntersects(1040523, 4010000, 1140523, 4850000)) ORDER BY lc_name;",
			   &results, &rows, &columns, &err_msg);
    if (ret != SQLITE_OK)
      {
	  fprintf (stderr, "Error in Mbr SELECT: %s\n", err_msg);
	  sqlite3_free (err_msg);
	  return -21;
      }
    if ((rows != 35) || (columns != 1))
      {
	  fprintf (stderr,
		   "Unexpected error: select lc_name bad cache result: %i/%i.\n",
		   rows, columns);
	  sqlite3_free_table (results);
	  sqlite3_close (handle);
	  return -22;
      }
    if (strcmp (results[1], "Apricena") != 0)
      {
	  fprintf (stderr, "unexpected mbr result at 1: %s\n", results[1]);
	  sqlite3_free_table (results);
	  sqlite3_close (handle);
	  return -23;
      }
    sqlite3_free_table (results);

    ret =
	sqlite3_exec (handle,
		      "DELETE FROM Councils WHERE lc_name = 'Zapponeta';", NULL,
		      NULL, &err_msg);
    if (ret != SQLITE_OK)
      {
	  fprintf (stderr, "DELETE error: %s\n", err_msg);
	  sqlite3_free (err_msg);
	  return -24;
      }

    rows = 0;
    columns = 0;
    ret =
	sqlite3_get_table (handle,
			   "SELECT lc_name FROM Councils WHERE ROWID IN (SELECT rowid FROM cache_Councils_geom WHERE mbr = FilterMbrWithin(1040523, 4010000, 1140523, 4850000)) ORDER BY lc_name;",
			   &results, &rows, &columns, &err_msg);
    if (ret != SQLITE_OK)
      {
	  fprintf (stderr, "Error in Mbr SELECT: %s\n", err_msg);
	  sqlite3_free (err_msg);
	  return -25;
      }
    if ((rows != 21) || (columns != 1))
      {
	  fprintf (stderr,
		   "Unexpected error: select lc_name bad cache result: %i/%i.\n",
		   rows, columns);
	  sqlite3_free_table (results);
	  sqlite3_close (handle);
	  return -26;
      }
    if (strcmp (results[1], "Ascoli Satriano") != 0)
      {
	  fprintf (stderr, "unexpected mbr result at 1: %s\n", results[1]);
	  sqlite3_free_table (results);
	  sqlite3_close (handle);
	  return -27;
      }
    if (strcmp (results[21], "Vieste") != 0)
      {
	  fprintf (stderr, "unexpected mbr result at 21: %s\n", results[21]);
	  sqlite3_free_table (results);
	  sqlite3_close (handle);
	  return -28;
      }
    sqlite3_free_table (results);

    ret =
	sqlite3_exec (handle,
		      "INSERT INTO Councils (lc_name, geom) VALUES ('Quairading', GeomFromText('MULTIPOLYGON(((997226.750031 4627372.000018, 997301.750031 4627332.000018, 997402.500031 4627344.000018, 997541.500031 4627326.500018,997226.750031 4627372.000018)))', 23032));",
		      NULL, NULL, &err_msg);
    if (ret != SQLITE_OK)
      {
	  fprintf (stderr, "INSERT error: %s\n", err_msg);
	  sqlite3_free (err_msg);
	  return -29;
      }

    rows = 0;
    columns = 0;
    ret =
	sqlite3_get_table (handle,
			   "SELECT lc_name FROM Councils WHERE ROWID IN (SELECT rowid FROM cache_Councils_geom WHERE mbr = FilterMbrWithin(1040523, 4010000, 1140523, 4850000)) ORDER BY lc_name;",
			   &results, &rows, &columns, &err_msg);
    if (ret != SQLITE_OK)
      {
	  fprintf (stderr, "Error in Mbr SELECT2: %s\n", err_msg);
	  sqlite3_free (err_msg);
	  return -30;
      }
    if ((rows != 21) || (columns != 1))
      {
	  fprintf (stderr,
		   "Unexpected error: select lc_name bad cache result: %i/%i.\n",
		   rows, columns);
	  sqlite3_free_table (results);
	  sqlite3_close (handle);
	  return -31;
      }
    if (strcmp (results[1], "Ascoli Satriano") != 0)
      {
	  fprintf (stderr, "unexpected mbr result at 1: %s\n", results[1]);
	  sqlite3_free_table (results);
	  sqlite3_close (handle);
	  return -32;
      }
    if (strcmp (results[21], "Vieste") != 0)
      {
	  fprintf (stderr, "unexpected mbr result at 21: %s\n", results[21]);
	  sqlite3_free_table (results);
	  sqlite3_close (handle);
	  return -33;
      }
    sqlite3_free_table (results);

    ret =
	sqlite3_exec (handle,
		      "UPDATE Councils SET geom = GeomFromText('MULTIPOLYGON(((987226.750031 4627372.000018, 997301.750031 4627331.000018, 997402.500032 4627344.000018, 997541.500031 4627326.500018, 987226.750031 4627372.000018)))', 23032) WHERE lc_name = \"Quairading\";",
		      NULL, NULL, &err_msg);
    if (ret != SQLITE_OK)
      {
	  fprintf (stderr, "UPDATE error: %s\n", err_msg);
	  sqlite3_free (err_msg);
	  return -34;
      }

    rows = 0;
    columns = 0;
    ret =
	sqlite3_get_table (handle,
			   "SELECT lc_name FROM Councils WHERE ROWID IN (SELECT rowid FROM cache_Councils_geom WHERE mbr = FilterMbrWithin(1040523, 4010000, 1140523, 4850000)) ORDER BY lc_name;",
			   &results, &rows, &columns, &err_msg);
    if (ret != SQLITE_OK)
      {
	  fprintf (stderr, "Error in Mbr SELECT3: %s\n", err_msg);
	  sqlite3_free (err_msg);
	  return -35;
      }
    if ((rows != 21) || (columns != 1))
      {
	  fprintf (stderr,
		   "Unexpected error: select lc_name bad cache result: %i/%i.\n",
		   rows, columns);
	  sqlite3_free_table (results);
	  sqlite3_close (handle);
	  return -36;
      }
    if (strcmp (results[1], "Ascoli Satriano") != 0)
      {
	  fprintf (stderr, "unexpected mbr result at 1: %s\n", results[1]);
	  sqlite3_free_table (results);
	  sqlite3_close (handle);
	  return -37;
      }
    if (strcmp (results[21], "Vieste") != 0)
      {
	  fprintf (stderr, "unexpected mbr result at 21: %s\n", results[21]);
	  sqlite3_free_table (results);
	  sqlite3_close (handle);
	  return -38;
      }
    sqlite3_free_table (results);

    rows = 0;
    columns = 0;
    ret =
	sqlite3_get_table (handle,
			   "SELECT rowid, mbr FROM cache_Councils_geom;",
			   &results, &rows, &columns, &err_msg);
    if (ret != SQLITE_OK)
      {
	  fprintf (stderr, "Error in Mbr SELECT: %s\n", err_msg);
	  sqlite3_free (err_msg);
	  return -39;
      }
    if ((rows != 61) || (columns != 2))
      {
	  fprintf (stderr,
		   "Unexpected error: select lc_name bad cache2 result: %i/%i.\n",
		   rows, columns);
	  sqlite3_free_table (results);
	  sqlite3_close (handle);
	  return -40;
      }
    if (strcmp (results[2], "1") != 0)
      {
	  fprintf (stderr, "unexpected mbr result at 1: %s\n", results[2]);
	  sqlite3_free_table (results);
	  sqlite3_close (handle);
	  return -41;
      }
    if (strcmp (results[12], "6") != 0)
      {
	  fprintf (stderr, "unexpected mbr result at 6: %s\n", results[12]);
	  sqlite3_free_table (results);
	  sqlite3_close (handle);
	  return -42;
      }
    sqlite3_free_table (results);

    ret = sqlite3_exec (handle, "DROP TABLE Councils;", NULL, NULL, &err_msg);
    if (ret != SQLITE_OK)
      {
	  fprintf (stderr, "DROP TABLE Councils error: %s\n", err_msg);
	  sqlite3_free (err_msg);
	  return -44;
      }

/* creating and feeding a Point table */
    ret =
	sqlite3_exec (handle, "CREATE TABLE pt (id INTEGER);", NULL, NULL,
		      &err_msg);
    if (ret != SQLITE_OK)
      {
	  fprintf (stderr, "CREATE TABLE pt error: %s\n", err_msg);
	  sqlite3_free (err_msg);
	  return -45;
      }
    ret =
	sqlite3_exec (handle,
		      "SELECT AddGeometryColumn('pt', 'g', 4326, 1, 'XY');",
		      NULL, NULL, &err_msg);
    if (ret != SQLITE_OK)
      {
	  fprintf (stderr, "AddGeometryColumn pt error: %s\n", err_msg);
	  sqlite3_free (err_msg);
	  return -46;
      }
    ret =
	sqlite3_exec (handle,
		      "SELECT AddGeometryColumn('pt', 'g', 4326, 'POINT', 2.5);",
		      NULL, NULL, &err_msg);
    if (ret != SQLITE_OK)
      {
	  fprintf (stderr, "AddGeometryColumn pt error: %s\n", err_msg);
	  sqlite3_free (err_msg);
	  return -47;
      }
    ret =
	sqlite3_exec (handle,
		      "SELECT AddGeometryColumn('pt', 'g', 4326, 'POINT', 'XY', 0.5);",
		      NULL, NULL, &err_msg);
    if (ret != SQLITE_OK)
      {
	  fprintf (stderr, "AddGeometryColumn pt error: %s\n", err_msg);
	  sqlite3_free (err_msg);
	  return -48;
      }
    ret =
	sqlite3_exec (handle,
		      "SELECT AddGeometryColumn('pt', 'g', 4326, 'DUMMY', 'XY');",
		      NULL, NULL, &err_msg);
    if (ret != SQLITE_OK)
      {
	  fprintf (stderr, "AddGeometryColumn pt error: %s\n", err_msg);
	  sqlite3_free (err_msg);
	  return -49;
      }
    ret =
	sqlite3_exec (handle,
		      "SELECT AddGeometryColumn('pt', 'g', 4326, 'POINT', 'DUMMY');",
		      NULL, NULL, &err_msg);
    if (ret != SQLITE_OK)
      {
	  fprintf (stderr, "AddGeometryColumn pt error: %s\n", err_msg);
	  sqlite3_free (err_msg);
	  return -50;
      }
    ret =
	sqlite3_exec (handle,
		      "SELECT AddGeometryColumn('pt', 'g', 4326, 'POINT', 2);",
		      NULL, NULL, &err_msg);
    if (ret != SQLITE_OK)
      {
	  fprintf (stderr, "AddGeometryColumn pt error: %s\n", err_msg);
	  sqlite3_free (err_msg);
	  return -51;
      }
    ret =
	sqlite3_exec (handle, "SELECT CreateMbrCache('pt', 'g');", NULL, NULL,
		      &err_msg);
    if (ret != SQLITE_OK)
      {
	  fprintf (stderr, "CreateMbrCache pt.g error: %s\n", err_msg);
	  sqlite3_free (err_msg);
	  return -52;
      }
    for (pt = 0; pt < 10000; pt++)
      {
	  /* inserting Points */
	  char sql[1024];
	  sprintf (sql,
		   "INSERT INTO pt (id, g) VALUES (%d, GeomFromText('POINT(%1.2f %1.2f)', 4326));",
		   pt, 11.0 + (pt / 10000.0), 43.0 + (pt / 10000.0));
	  ret = sqlite3_exec (handle, sql, NULL, NULL, &err_msg);
	  if (ret != SQLITE_OK)
	    {
		fprintf (stderr, "INSERT INTO pt error: %s\n", err_msg);
		sqlite3_free (err_msg);
		return -53;
	    }
      }
    for (pt = 5000; pt < 6000; pt++)
      {
	  /* updating Points */
	  char sql[1024];
	  sprintf (sql,
		   "UPDATE pt SET g  = GeomFromText('POINT(%1.2f %1.2f)', 4326) WHERE id = %d;",
		   12.0 + (pt / 10000.0), 42.0 + (pt / 10000.0), pt);
	  ret = sqlite3_exec (handle, sql, NULL, NULL, &err_msg);
	  if (ret != SQLITE_OK)
	    {
		fprintf (stderr, "UPDATE pt error: %s\n", err_msg);
		sqlite3_free (err_msg);
		return -54;
	    }
      }
    for (pt = 7000; pt < 8000; pt++)
      {
	  /* deleting Points */
	  char sql[1024];
	  sprintf (sql, "DELETE FROM pt WHERE id = %d;", pt);
	  ret = sqlite3_exec (handle, sql, NULL, NULL, &err_msg);
	  if (ret != SQLITE_OK)
	    {
		fprintf (stderr, "UPDATE pt error: %s\n", err_msg);
		sqlite3_free (err_msg);
		return -55;
	    }
      }

    ret = sqlite3_exec (handle, "SELECT CreateMbrCache(1, 'geom');",
			NULL, NULL, &err_msg);
    if (ret != SQLITE_OK)
      {
	  fprintf (stderr, "invalid CreateMbrCache error: %s\n", err_msg);
	  sqlite3_free (err_msg);
	  return -56;
      }
    ret = sqlite3_exec (handle, "SELECT CreateMbrCache('Councils', 2);",
			NULL, NULL, &err_msg);
    if (ret != SQLITE_OK)
      {
	  fprintf (stderr, "invalid CreateMbrCache error: %s\n", err_msg);
	  sqlite3_free (err_msg);
	  return -57;
      }
    ret = sqlite3_exec (handle, "SELECT FilterMbrWithin('a', 2, 3, 4);",
			NULL, NULL, &err_msg);
    if (ret != SQLITE_OK)
      {
	  fprintf (stderr, "invalid FilterMbrWithin error: %s\n", err_msg);
	  sqlite3_free (err_msg);
	  return -58;
      }
    ret = sqlite3_exec (handle, "SELECT FilterMbrWithin(1, 'a', 3, 4);",
			NULL, NULL, &err_msg);
    if (ret != SQLITE_OK)
      {
	  fprintf (stderr, "invalid FilterMbrWithin error: %s\n", err_msg);
	  sqlite3_free (err_msg);
	  return -59;
      }
    ret = sqlite3_exec (handle, "SELECT FilterMbrWithin(1, 2, 'a', 4);",
			NULL, NULL, &err_msg);
    if (ret != SQLITE_OK)
      {
	  fprintf (stderr, "invalid FilterMbrWithin error: %s\n", err_msg);
	  sqlite3_free (err_msg);
	  return -60;
      }
    ret = sqlite3_exec (handle, "SELECT FilterMbrWithin(1, 2, 3, 'a');",
			NULL, NULL, &err_msg);
    if (ret != SQLITE_OK)
      {
	  fprintf (stderr, "invalid FilterMbrWithin error: %s\n", err_msg);
	  sqlite3_free (err_msg);
	  return -61;
      }

    ret = sqlite3_close (handle);
    if (ret != SQLITE_OK)
      {
	  fprintf (stderr, "sqlite3_close() error: %s\n",
		   sqlite3_errmsg (handle));
	  return -62;
      }

    spatialite_cleanup_ex (cache);
#endif /* end ICONV conditional */

    return 0;
}
/* public native void dbopen(String path, int flags, String locale); */
static void dbopen(JNIEnv* env, jobject object, jstring pathString, jint flags)
{
    int err;
    sqlite3 * handle = NULL;
    sqlite3_stmt * statement = NULL;
    char const * path8 = env->GetStringUTFChars(pathString, NULL);
    int sqliteFlags;

    // register the logging func on sqlite. needs to be done BEFORE any sqlite3 func is called.
    registerLoggingFunc(path8);

    // convert our flags into the sqlite flags
    if (flags & CREATE_IF_NECESSARY) {
        sqliteFlags = SQLITE_OPEN_READWRITE | SQLITE_OPEN_CREATE;
    } else if (flags & OPEN_READONLY) {
        sqliteFlags = SQLITE_OPEN_READONLY;
    } else {
        sqliteFlags = SQLITE_OPEN_READWRITE;
    }

    err = sqlite3_open_v2(path8, &handle, sqliteFlags, NULL);
    if (err != SQLITE_OK) {
        LOGE("sqlite3_open_v2(\"%s\", &handle, %d, NULL) failed\n", path8, sqliteFlags);
        throw_sqlite3_exception(env, handle);
        goto done;
    }

    // The soft heap limit prevents the page cache allocations from growing
    // beyond the given limit, no matter what the max page cache sizes are
    // set to. The limit does not, as of 3.5.0, affect any other allocations.
    sqlite3_soft_heap_limit(SQLITE_SOFT_HEAP_LIMIT);

    // Set the default busy handler to retry for 1000ms and then return SQLITE_BUSY
    err = sqlite3_busy_timeout(handle, 1000 /* ms */);
    if (err != SQLITE_OK) {
        LOGE("sqlite3_busy_timeout(handle, 1000) failed for \"%s\"\n", path8);
        throw_sqlite3_exception(env, handle);
        goto done;
    }

#ifdef DB_INTEGRITY_CHECK
    static const char* integritySql = "pragma integrity_check(1);";
    err = sqlite3_prepare_v2(handle, integritySql, -1, &statement, NULL);
    if (err != SQLITE_OK) {
        LOGE("sqlite_prepare_v2(handle, \"%s\") failed for \"%s\"\n", integritySql, path8);
        throw_sqlite3_exception(env, handle);
        goto done;
    }

    // first is OK or error message
    err = sqlite3_step(statement);
    if (err != SQLITE_ROW) {
        LOGE("integrity check failed for \"%s\"\n", integritySql, path8);
        throw_sqlite3_exception(env, handle);
        goto done;
    } else {
        const char *text = (const char*)sqlite3_column_text(statement, 0);
        if (strcmp(text, "ok") != 0) {
            LOGE("integrity check failed for \"%s\": %s\n", integritySql, path8, text);
            jniThrowException(env, "info/guardianproject/database/sqlcipher/SQLiteDatabaseCorruptException", text);
            goto done;
        }
    }
#endif

    err = register_android_functions(handle, UTF16_STORAGE);
    if (err) {
        throw_sqlite3_exception(env, handle);
        goto done;
    }

    LOGV("Opened '%s' - %p\n", path8, handle);
    env->SetIntField(object, offset_db_handle, (int) handle);
    handle = NULL;  // The caller owns the handle now.

done:
    // Release allocated resources
    if (path8 != NULL) env->ReleaseStringUTFChars(pathString, path8);
    if (statement != NULL) sqlite3_finalize(statement);
    if (handle != NULL) sqlite3_close(handle);
}
Example #7
0
static gboolean
rspamd_sqlite3_wait (rspamd_mempool_t *pool, const gchar *lock)
{
	gint fd;
	struct timespec sleep_ts = {
		.tv_sec = 0,
		.tv_nsec = 1000000
	};

	fd = open (lock, O_RDONLY);

	if (fd == -1) {

		if (errno == ENOENT) {
			/* Lock is already released, so we can continue */
			return TRUE;
		}

		msg_err_pool_check ("cannot open lock file %s: %s", lock, strerror (errno));

		return FALSE;
	}

	while (!rspamd_file_lock (fd, TRUE)) {
		if (nanosleep (&sleep_ts, NULL) == -1 && errno != EINTR) {
			close (fd);
			msg_err_pool_check ("cannot sleep open lock file %s: %s", lock,
					strerror (errno));

			return FALSE;
		}
	}

	rspamd_file_unlock (fd, FALSE);
	unlink (lock);
	close (fd);

	return TRUE;
}

#define RSPAMD_SQLITE_MMAP_LIMIT 268435456
#define RSPAMD_SQLITE_CACHE_SIZE 262144

sqlite3 *
rspamd_sqlite3_open_or_create (rspamd_mempool_t *pool, const gchar *path, const
		gchar *create_sql, GError **err)
{
	sqlite3 *sqlite;
	gint rc, flags, lock_fd;
	gchar lock_path[PATH_MAX], dbdir[PATH_MAX], *pdir;
	static const char sqlite_wal[] =
									"PRAGMA journal_mode=\"wal\";"
									"PRAGMA wal_autocheckpoint = 16;"
									"PRAGMA journal_size_limit = 1536;",
			exclusive_lock_sql[] =	"PRAGMA locking_mode=\"exclusive\";",

			fsync_sql[] = 			"PRAGMA synchronous=\"NORMAL\";",

			foreign_keys[] = 		"PRAGMA foreign_keys=\"ON\";",

			enable_mmap[] = 		"PRAGMA mmap_size="
									G_STRINGIFY(RSPAMD_SQLITE_MMAP_LIMIT) ";",

			other_pragmas[] = 		"PRAGMA read_uncommitted=\"ON\";"
									"PRAGMA cache_size="
									G_STRINGIFY(RSPAMD_SQLITE_CACHE_SIZE) ";";
	gboolean create = FALSE, has_lock = FALSE;

	flags = SQLITE_OPEN_READWRITE;
#ifdef SQLITE_OPEN_SHAREDCACHE
	flags |= SQLITE_OPEN_SHAREDCACHE;
#endif
#ifdef SQLITE_OPEN_WAL
	flags |= SQLITE_OPEN_WAL;
#endif

	rspamd_strlcpy (dbdir, path, sizeof (dbdir));
	pdir = dirname (dbdir);

	if (access (pdir, W_OK) == -1) {
		g_set_error (err, rspamd_sqlite3_quark (),
				errno, "cannot open sqlite directory %s: %s",
				pdir, strerror (errno));

		return NULL;
	}

	rspamd_snprintf (lock_path, sizeof (lock_path), "%s.lock", path);

	if (access (path, R_OK) == -1) {
		flags |= SQLITE_OPEN_CREATE;
		create = TRUE;
	}


	rspamd_snprintf (lock_path, sizeof (lock_path), "%s.lock", path);
	lock_fd = open (lock_path, O_WRONLY|O_CREAT|O_EXCL, 00600);

	if (lock_fd == -1 && (errno == EEXIST || errno == EBUSY)) {
		msg_debug_pool_check ("checking %s to wait for db being initialized", lock_path);

		if (!rspamd_sqlite3_wait (pool, lock_path)) {
			g_set_error (err, rspamd_sqlite3_quark (),
					errno, "cannot create sqlite file %s: %s",
					path, strerror (errno));

			return NULL;
		}

		/* At this point we have database created */
		create = FALSE;
		has_lock = FALSE;
	}
	else {
		msg_debug_pool_check ("locking %s to block other processes", lock_path);

		g_assert (rspamd_file_lock (lock_fd, FALSE));
		has_lock = TRUE;
	}

	sqlite3_enable_shared_cache (1);

	if ((rc = sqlite3_open_v2 (path, &sqlite,
			flags, NULL)) != SQLITE_OK) {
#if SQLITE_VERSION_NUMBER >= 3008000
		g_set_error (err, rspamd_sqlite3_quark (),
				rc, "cannot open sqlite db %s: %s",
				path, sqlite3_errstr (rc));
#else
		g_set_error (err, rspamd_sqlite3_quark (),
				rc, "cannot open sqlite db %s: %d",
				path, rc);
#endif

		return NULL;
	}

	if (create && has_lock) {
		if (sqlite3_exec (sqlite, sqlite_wal, NULL, NULL, NULL) != SQLITE_OK) {
			msg_warn_pool_check ("WAL mode is not supported (%s), locking issues might occur",
					sqlite3_errmsg (sqlite));
		}

		if (sqlite3_exec (sqlite, exclusive_lock_sql, NULL, NULL, NULL) != SQLITE_OK) {
			msg_warn_pool_check ("cannot exclusively lock database to create schema: %s",
					sqlite3_errmsg (sqlite));
		}

		if (create_sql) {
			if (sqlite3_exec (sqlite, create_sql, NULL, NULL, NULL) != SQLITE_OK) {
				g_set_error (err, rspamd_sqlite3_quark (),
						-1, "cannot execute create sql `%s`: %s",
						create_sql, sqlite3_errmsg (sqlite));
				sqlite3_close (sqlite);
				rspamd_file_unlock (lock_fd, FALSE);
				unlink (lock_path);
				close (lock_fd);

				return NULL;
			}
		}

		sqlite3_close (sqlite);

		/* Reopen in normal mode */
		msg_debug_pool_check ("reopening %s in normal mode", path);
		flags &= ~SQLITE_OPEN_CREATE;

		if ((rc = sqlite3_open_v2 (path, &sqlite,
				flags, NULL)) != SQLITE_OK) {
	#if SQLITE_VERSION_NUMBER >= 3008000
			g_set_error (err, rspamd_sqlite3_quark (),
					rc, "cannot open sqlite db after creation %s: %s",
					path, sqlite3_errstr (rc));
	#else
			g_set_error (err, rspamd_sqlite3_quark (),
					rc, "cannot open sqlite db after creation %s: %d",
					path, rc);
	#endif
			rspamd_file_unlock (lock_fd, FALSE);
			unlink (lock_path);
			close (lock_fd);
			return NULL;
		}
	}

	if (sqlite3_exec (sqlite, sqlite_wal, NULL, NULL, NULL) != SQLITE_OK) {
		msg_warn_pool_check ("WAL mode is not supported (%s), locking issues might occur",
				sqlite3_errmsg (sqlite));
	}

	if (sqlite3_exec (sqlite, fsync_sql, NULL, NULL, NULL) != SQLITE_OK) {
		msg_warn_pool_check ("cannot set synchronous: %s",
				sqlite3_errmsg (sqlite));
	}

	if ((rc = sqlite3_exec (sqlite, foreign_keys, NULL, NULL, NULL)) !=
			SQLITE_OK) {
		msg_warn_pool_check ("cannot enable foreign keys: %s",
				sqlite3_errmsg (sqlite));
	}

#if defined(__LP64__) || defined(_LP64)
	if ((rc = sqlite3_exec (sqlite, enable_mmap, NULL, NULL, NULL)) != SQLITE_OK) {
		msg_warn_pool_check ("cannot enable mmap: %s",
				sqlite3_errmsg (sqlite));
	}
#endif

	if ((rc = sqlite3_exec (sqlite, other_pragmas, NULL, NULL, NULL)) !=
			SQLITE_OK) {
		msg_warn_pool_check ("cannot execute tuning pragmas: %s",
				sqlite3_errmsg (sqlite));
	}

	if (has_lock) {
		msg_debug_pool_check ("removing lock from %s", lock_path);
		rspamd_file_unlock (lock_fd, FALSE);
		unlink (lock_path);
		close (lock_fd);
	}

	return sqlite;
}
int main()
{
	int ret;
	sqlite3 *disk_db = NULL;

	fprintf(stderr,
		"Opening disk database and trying to create the in memory database\n");
	ret =
	    sqlite3_open_v2("autocomplete.sqlite", &disk_db, SQLITE_OPEN_READONLY,
			    NULL);
	if (SQLITE_OK != ret) {
		printf("Error opening database: %s\n", sqlite3_errmsg(disk_db));
		goto end;
	}

	ret = sqlite3_open(":memory:", &db);
	if (SQLITE_OK != ret) {
		if (db == NULL)
			fprintf(stderr, "Insufficient Memory\n");
		else
			printf("Error opening database: %s\n",
			       sqlite3_errmsg(db));
		goto close_and_end;
	}

	char *err;
	ret =
	    sqlite3_exec(db,
			 "CREATE TABLE autocomplete (english TEXT COLLATE NOCASE, tamil TEXT COLLATE NOCASE, score int)",
			 NULL, NULL, &err);
	if (SQLITE_OK != ret) {
		printf("Error creating sqlite table: %s\n", sqlite3_errmsg(db));
		goto close_and_end;
	}

	ret =
	    sqlite3_prepare_v2(db, "INSERT INTO autocomplete VALUES (?, ?, ?)",
			       -1, &stmt, NULL);
	if (SQLITE_OK != ret) {
		printf("Error creating prepared statement: %s\n",
		       sqlite3_errmsg(db));
		goto close_and_end;
	}

	ret = sqlite3_exec(db, "BEGIN TRANSACTION", NULL, NULL, &err);
	if (SQLITE_OK != ret) {
		printf("Error beginning a transaction: %s\n",
		       sqlite3_errmsg(db));
		goto close_and_end;
	}

	/* Select each record from the disk db and insert into the in-memory table */
	ret =
	    sqlite3_exec(disk_db,
			 "SELECT english, tamil, score FROM autocomplete",
			 disk_to_mem_cb, NULL, &err);
	if (SQLITE_OK != ret) {
		printf("Error conversion of disk_to_mem: %s\n",
		       sqlite3_errmsg(db));
		goto close_and_end;
	}

	ret = sqlite3_exec(db, "COMMIT", NULL, NULL, &err);
	if (SQLITE_OK != ret) {
		printf("Error committing a transaction: %s\n",
		       sqlite3_errmsg(db));
		goto close_and_end;
	}
	sqlite3_finalize(stmt);
	sqlite3_close(disk_db);

	fprintf(stderr, "In-memory database creation complete. About to create Indexes.\n");

	/* Create Indexes */
	fprintf(stderr, "Data inserted into tables. About to create english index\n");
	ret = sqlite3_exec(db, "CREATE INDEX english_idx ON autocomplete (english)", NULL, NULL, &err);
	if (SQLITE_OK != ret) {
		printf("Error creating an index for the english column: %s\n",
		       sqlite3_errmsg(db));
	}

	fprintf(stderr, "Index created for english. Now creating index for english + tamil\n");
	ret = sqlite3_exec(db, "CREATE INDEX eng_tam_idx ON autocomplete (english, tamil)", NULL, NULL, &err);
	if (SQLITE_OK != ret) {
		printf("Error creating an index for the english+tamil columns: %s\n",
		       sqlite3_errmsg(db));
	}

	fprintf(stderr, "Index created for english + tamil. Now creating index for english + tamil + score\n");
	ret = sqlite3_exec(db, "CREATE INDEX eng_tam_score_idx ON autocomplete (english, tamil, score)", NULL, NULL, &err);
	if (SQLITE_OK != ret) {
		printf("Error creating an index for the english+tamil+score columns: %s\n",
		       sqlite3_errmsg(db));
	}

	fprintf(stderr, "Index created for english + tamil + score. Now creating index for english + score\n");
	ret = sqlite3_exec(db, "CREATE INDEX english_score_idx ON autocomplete (english, score)", NULL, NULL, &err);
	if (SQLITE_OK != ret) {
		printf("Error creating an index for the english+tamil+score columns: %s\n",
		       sqlite3_errmsg(db));
	}

	ret =
	    sqlite3_prepare_v2(db,
			       "SELECT DISTINCT tamil FROM autocomplete WHERE english LIKE ? ORDER BY score DESC LIMIT 5",
			       -1, &stmt, NULL);

	if (SQLITE_OK != ret) {
		printf("Error creating prepared statement: %s\n",
		       sqlite3_errmsg(db));
		goto close_and_end;
	}

	GtkWidget *window;

	gtk_init(NULL, NULL);
	window = gtk_window_new(GTK_WINDOW_TOPLEVEL);
	gtk_window_set_title(GTK_WINDOW(window), "Vaiyakani");

	entry = gtk_entry_new();
	suggestions = gtk_label_new("");

	GtkWidget *box;
	box = gtk_box_new(GTK_ORIENTATION_HORIZONTAL, 10);

	gtk_container_add(GTK_CONTAINER(box), entry);
	gtk_container_add(GTK_CONTAINER(box), suggestions);

	gtk_container_add(GTK_CONTAINER(window), box);
	g_signal_connect(entry, "changed", kb, NULL);

	gtk_widget_show_all(window);
	gtk_main();

	sqlite3_finalize(stmt);

close_and_end:
	if (disk_db)
		sqlite3_close(disk_db);
	if (db)
		sqlite3_close(db);
end:
	return ret;
}
Example #9
0
int main (int argc, char *argv[])
{
#ifndef OMIT_GEOS	/* only if GEOS is supported */
    int ret;
    sqlite3 *handle;
    char *err_msg = NULL;
    const char *sql;
    char **results;
    int rows;
    int columns;
    void *cache = spatialite_alloc_connection();

    if (argc > 1 || argv[0] == NULL)
	argc = 1;		/* silencing stupid compiler warnings */

    ret = system("cp sql_stmt_tests/testFGF.sqlite testFGF.sqlite");
    if (ret != 0)
    {
        fprintf(stderr, "cannot copy testFGF.sqlite database\n");
        return -1001;
    }
    ret = sqlite3_open_v2 ("testFGF.sqlite", &handle, SQLITE_OPEN_READWRITE | SQLITE_OPEN_CREATE, NULL);
    if (ret != SQLITE_OK) {
	fprintf(stderr, "cannot open testFGF.sqlite db: %s\n", sqlite3_errmsg (handle));
	sqlite3_close(handle);
	return -1000;
    }

    spatialite_init_ex (handle, cache, 0);

/* FDO start-up */
    sql = "SELECT AutoFDOStart()";
    ret = sqlite3_exec (handle, sql, NULL, NULL, &err_msg);
    if (ret != SQLITE_OK) {
      fprintf (stderr, "Error: %s\n", err_msg);
      sqlite3_free (err_msg);
      return -1;
    }

/* testing aggregate Union() Point FGF "HouseNumbers" */
    sql = "SELECT AsText(ST_Union(Geometry)) FROM fdo_HouseNumbers WHERE TEXT_LABEL LIKE '11%'";
    ret = sqlite3_get_table (handle, sql, &results, &rows, &columns, &err_msg);
    if (ret != SQLITE_OK) {
      fprintf (stderr, "Error: %s\n", err_msg);
      sqlite3_free (err_msg);
      return -2;
    }
    if ((rows != 1) || (columns != 1)) {
      fprintf (stderr, "Unexpected error: bad result: %i/%i.\n", rows, columns);
      return -3;
    }
    if (results[1] == NULL) {
      fprintf (stderr, "Unexpected error: NULL result\n");
      return -4;
    }
    if (strcmp(results[1], "MULTIPOINT(430417.1 5448290.9, 430666.6 5448125.4)") != 0) {        
      	    fprintf (stderr, "Unexpected error: invalid result |%s|\n", results[1]);
        return -5;
    }
    sqlite3_free_table (results);

/* testing Sum(GLength()) Linestring FGF "Centrerlines" */
    sql = "SELECT Sum(GLength(Geometry)) FROM fdo_Centerlines";
    ret = sqlite3_get_table (handle, sql, &results, &rows, &columns, &err_msg);
    if (ret != SQLITE_OK) {
      fprintf (stderr, "Error: %s\n", err_msg);
      sqlite3_free (err_msg);
      return -6;
    }
    if ((rows != 1) || (columns != 1)) {
      fprintf (stderr, "Unexpected error: bad result: %i/%i.\n", rows, columns);
      return -7;
    }
    if (results[1] == NULL) {
      fprintf (stderr, "Unexpected error: NULL result\n");
      return -8;
    }
    if (strncmp(results[1], "895.3351", 7) != 0) {        
      fprintf (stderr, "Unexpected error: invalid result\n");
      return -9;
    }
    sqlite3_free_table (results);

/* testing Sum(Area()) Polygon FGF "AssessmentParcels" */
    sql = "SELECT Sum(Area(Geometry)) FROM fdo_AssessmentParcels";
    ret = sqlite3_get_table (handle, sql, &results, &rows, &columns, &err_msg);
    if (ret != SQLITE_OK) {
      fprintf (stderr, "Error: %s\n", err_msg);
      sqlite3_free (err_msg);
      return -10;
    }
    if ((rows != 1) || (columns != 1)) {
      fprintf (stderr, "Unexpected error: bad result: %i/%i.\n", rows, columns);
      return -11;
    }
    if (results[1] == NULL) {
      fprintf (stderr, "Unexpected error: NULL result\n");
      return -12;
    }
    if (strncmp(results[1], "9022.1792", 9) != 0) {        
      fprintf (stderr, "Unexpected error: invalid result\n");
      return -13;
    }
    sqlite3_free_table (results);

/* FDO shut-down */
    sql = "SELECT AutoFDOStop()";
    ret = sqlite3_exec (handle, sql, NULL, NULL, &err_msg);
    if (ret != SQLITE_OK) {
      fprintf (stderr, "Error: %s\n", err_msg);
      sqlite3_free (err_msg);
      return -14;
    }

    ret = sqlite3_close (handle);
    if (ret != SQLITE_OK) {
        fprintf (stderr, "sqlite3_close() error: %s\n", sqlite3_errmsg (handle));
	return -15;
    }
    
    spatialite_cleanup_ex (cache);
    ret = unlink("testFGF.sqlite");
    if (ret != 0)
    {
        fprintf(stderr, "cannot remove testFGF database\n");
        return -16;
    }
#endif	/* end GEOS conditional */
    
    return 0;
}
Example #10
0
int
main (int argc, char *argv[])
{
    int result = 0;
    int ret;
    char *err_msg = NULL;
    sqlite3 *db_handle;
    void *cache = spatialite_alloc_connection ();
    void *priv_data = rl2_alloc_private ();
    char *old_SPATIALITE_SECURITY_ENV = NULL;

    if (argc > 1 || argv[0] == NULL)
	argc = 1;		/* silencing stupid compiler warnings */

    old_SPATIALITE_SECURITY_ENV = getenv ("SPATIALITE_SECURITY");
#ifdef _WIN32
    putenv ("SPATIALITE_SECURITY=relaxed");
#else /* not WIN32 */
    setenv ("SPATIALITE_SECURITY", "relaxed", 1);
#endif

/* opening and initializing the "memory" test DB */
    ret = sqlite3_open_v2 (":memory:", &db_handle,
			   SQLITE_OPEN_READWRITE | SQLITE_OPEN_CREATE, NULL);
    if (ret != SQLITE_OK)
      {
	  fprintf (stderr, "sqlite3_open_v2() error: %s\n",
		   sqlite3_errmsg (db_handle));
	  return -1;
      }
    spatialite_init_ex (db_handle, cache, 0);
    rl2_init (db_handle, priv_data, 0);
    ret =
	sqlite3_exec (db_handle, "SELECT InitSpatialMetadata(1)", NULL, NULL,
		      &err_msg);
    if (ret != SQLITE_OK)
      {
	  fprintf (stderr, "InitSpatialMetadata() error: %s\n", err_msg);
	  sqlite3_free (err_msg);
	  return -2;
      }
    ret =
	sqlite3_exec (db_handle, "SELECT CreateRasterCoveragesTable()", NULL,
		      NULL, &err_msg);
    if (ret != SQLITE_OK)
      {
	  fprintf (stderr, "CreateRasterCoveragesTable() error: %s\n", err_msg);
	  sqlite3_free (err_msg);
	  return -3;
      }

/* SRTM NILE-DOUBLE (GRID) tests */
    ret = -100;
    if (!test_coverage (db_handle, RL2_SAMPLE_INT8, TILE_256, &ret))
	return ret;
    ret = -120;
    if (!test_coverage (db_handle, RL2_SAMPLE_INT8, TILE_1024, &ret))
	return ret;
    ret = -140;
    if (!test_coverage (db_handle, RL2_SAMPLE_UINT8, TILE_256, &ret))
	return ret;
    ret = -160;
    if (!test_coverage (db_handle, RL2_SAMPLE_UINT8, TILE_1024, &ret))
	return ret;
    ret = -180;
    if (!test_coverage (db_handle, RL2_SAMPLE_INT16, TILE_256, &ret))
	return ret;
    ret = -200;
    if (!test_coverage (db_handle, RL2_SAMPLE_INT16, TILE_1024, &ret))
	return ret;
    ret = -220;
    if (!test_coverage (db_handle, RL2_SAMPLE_UINT16, TILE_256, &ret))
	return ret;
    ret = -240;
    if (!test_coverage (db_handle, RL2_SAMPLE_UINT16, TILE_1024, &ret))
	return ret;
    ret = -260;
    if (!test_coverage (db_handle, RL2_SAMPLE_INT32, TILE_256, &ret))
	return ret;
    ret = -280;
    if (!test_coverage (db_handle, RL2_SAMPLE_INT32, TILE_1024, &ret))
	return ret;
    ret = -300;
    if (!test_coverage (db_handle, RL2_SAMPLE_UINT32, TILE_256, &ret))
	return ret;
    ret = -320;
    if (!test_coverage (db_handle, RL2_SAMPLE_UINT32, TILE_1024, &ret))
	return ret;
    ret = -340;
    if (!test_coverage (db_handle, RL2_SAMPLE_FLOAT, TILE_256, &ret))
	return ret;
    ret = -360;
    if (!test_coverage (db_handle, RL2_SAMPLE_FLOAT, TILE_1024, &ret))
	return ret;
    ret = -380;
    if (!test_coverage (db_handle, RL2_SAMPLE_DOUBLE, TILE_256, &ret))
	return ret;
    ret = -400;
    if (!test_coverage (db_handle, RL2_SAMPLE_DOUBLE, TILE_1024, &ret))
	return ret;

/* closing the DB */
    sqlite3_close (db_handle);
    spatialite_cleanup_ex (cache);
    rl2_cleanup_private (priv_data);
    spatialite_shutdown ();
    if (old_SPATIALITE_SECURITY_ENV)
      {
#ifdef _WIN32
	  char *env = sqlite3_mprintf ("SPATIALITE_SECURITY=%s",
				       old_SPATIALITE_SECURITY_ENV);
	  putenv (env);
	  sqlite3_free (env);
#else /* not WIN32 */
	  setenv ("SPATIALITE_SECURITY", old_SPATIALITE_SECURITY_ENV, 1);
#endif
      }
    else
      {
#ifdef _WIN32
	  putenv ("SPATIALITE_SECURITY=");
#else /* not WIN32 */
	  unsetenv ("SPATIALITE_SECURITY");
#endif
      }
    return result;
}
Example #11
0
int main(int argc, char *argv[]) {
    sqlite3         *db = NULL;
    sqlite3_stmt    *stmt = NULL;
    int             res = 0;
    int             flags = SQLITE_OPEN_READONLY;
    const char      *colnms[4] = {NULL};     // Nomi delle colonne
    const char      *tail = NULL;
    const char            *sql_str = 
        "SELECT * FROM addressbook ORDER by id;"
        "SELECT * FROM addressbook ORDER by fullname;"
        "SELECT * FROM addressbook ORDER by alias;"
        "SELECT * FROM addressbook ORDER by email;";

    if (argc != 2) {
        fprintf(stderr, "Usage: %s <database name>\n", argv[0]);
        exit(EXIT_FAILURE);
    }

    // Inizializzazione della libreria
    if (sqlite3_initialize() != SQLITE_OK) {
        fprintf(stderr, "Err. Unable to initialize the library.\n");
        exit(EXIT_FAILURE);
    }

    /* Creazione della connessione al database */
    res = sqlite3_open_v2(argv[1], &db, flags, NULL);

    if (res != SQLITE_OK) {
        fprintf(stderr, "Err. can't open database: %s\n", sqlite3_errmsg(db));
        sqlite3_close(db);
        exit(EXIT_FAILURE);
    }

    /* Si utilizza la funzione sqlite3_complete() per la verifica della query,
    si basa essenzialmente sul riconoscimento del punto e virgola - semicolon -
    finale */
    while(sqlite3_complete(sql_str)) {
        if (sqlite3_prepare_v2(db, sql_str,-1, &stmt, &tail) != SQLITE_OK) {
            fprintf(stderr, "Err. Unable to create Prepared Statement.\n");
            exit(EXIT_FAILURE);
        }

        // Stampa il nome di ciascuna colonna.
        for (int i=0; i<sqlite3_column_count(stmt); i++)
            colnms[i] = sqlite3_column_name(stmt, i);
    
            printf("%2s %10s %8s %14s\n", \
                    colnms[0], colnms[1], colnms[2], colnms[3]);

        // Estrazione dei dati riga per riga
        while (sqlite3_step(stmt) == SQLITE_ROW) {
            printf("%2d %10s %5s %20s (byte: %3d)\n",                \
                    sqlite3_column_int(stmt, 0),                    \
                    (const char*)sqlite3_column_text(stmt, 1),      \
                    (const char*)sqlite3_column_text(stmt, 2),      \
                    (const char*)sqlite3_column_text(stmt, 3),      \
                    sqlite3_column_bytes(stmt, 3));
        }
        puts("\n");
        
        // L'istruzione successiva da eseguire e' conservata in 'tail'
        sql_str = tail;
    }


    // Rilascio delle risorse relative alla Prepared Statement
    if (sqlite3_finalize(stmt) != SQLITE_OK) {
        fprintf(stderr, "Err. Unable to finalize.\n");
        exit(EXIT_FAILURE);
    }

    // Close database connection
    if (sqlite3_close_v2(db) != SQLITE_OK) {
        fprintf(stderr, "Err. Unable to close connection.\n");
        exit(EXIT_FAILURE);
    }

    // Rilascio delle risorse di inizializzazione
    sqlite3_shutdown();

    return(EXIT_SUCCESS);
}
Example #12
0
int
main (int argc, char *argv[])
{
    int ret;
    sqlite3 *handle;
    void *cache = spatialite_alloc_connection ();

    if (argc > 1 || argv[0] == NULL)
	argc = 1;		/* silencing stupid compiler warnings */

    ret =
	sqlite3_open_v2 (":memory:", &handle,
			 SQLITE_OPEN_READWRITE | SQLITE_OPEN_CREATE, NULL);
    if (ret != SQLITE_OK)
      {
	  fprintf (stderr, "cannot open in-memory db: %s\n",
		   sqlite3_errmsg (handle));
	  sqlite3_close (handle);
	  return -1;
      }

    spatialite_init_ex (handle, cache, 0);

#ifdef ENABLE_LIBXML2		/* only if LIBXML2 is supported */

    if (!check_parse (cache, "books.xml"))
      {
	  fprintf (stderr, "unable to parse \"books.xml\"\n");
	  return -2;
      }
    if (!check_parse (cache, "opera.xml"))
      {
	  fprintf (stderr, "unable to parse \"opera.xml\"\n");
	  return -3;
      }
    if (!check_parse (cache, "movies.xml"))
      {
	  fprintf (stderr, "unable to parse \"movies.xml\"\n");
	  return -4;
      }

    if (!check_validate (cache, "books.xml"))
      {
	  fprintf (stderr, "unable to validate \"books.xml\"\n");
	  return -5;
      }
    if (!check_validate (cache, "opera.xml"))
      {
	  fprintf (stderr, "unable to validate \"opera.xml\"\n");
	  return -6;
      }
    if (!check_validate (cache, "movies.xml"))
      {
	  fprintf (stderr, "unable to validate \"movies.xml\"\n");
	  return -7;
      }
    if (!check_extended (cache, "inspire-data-example.xml", ISO_METADATA))
      {
	  fprintf (stderr, "unable to parse \"inspire-data-example.xml\"\n");
	  return -8;
      }
    if (!check_extended (cache, "stazioni_se.xml", SLD_SE_STYLE))
      {
	  fprintf (stderr, "unable to parse \"stazioni_se.xml\"\n");
	  return -9;
      }
    if (!check_extended (cache, "thunderstorm_mild.svg", SVG))
      {
	  fprintf (stderr, "unable to parse \"thunderstorm_mild.svg\"\n");
	  return -10;
      }

    if (!check_bad_xml (cache))
      {
	  fprintf (stderr, "unable to test not well-formed XML\n");
	  return -11;
      }
    if (!check_bad_schema (cache))
      {
	  fprintf (stderr, "unable to test invalid Schema\n");
	  return -12;
      }

    if (!check_mline_gpx (handle, cache, "000323485.gpx"))
      {
	  fprintf (stderr, "unable to test \"000323485.gpx\"\n");
	  return -13;
      }
    if (!check_mline_gpx (handle, cache, "Gpx-sample.gpx"))
      {
	  fprintf (stderr, "unable to test \"Gpx-sample.gpx\"\n");
	  return -14;
      }

#endif

    ret = sqlite3_close (handle);
    if (ret != SQLITE_OK)
      {
	  fprintf (stderr, "sqlite3_close() error: %s\n",
		   sqlite3_errmsg (handle));
	  return -10;
      }

    spatialite_cleanup_ex (cache);

    spatialite_shutdown ();

    return 0;
}
int main (int argc, char *argv[])
{
#ifndef OMIT_FREEXL		/* only if FreeXL is supported */
    int ret;
    sqlite3 *handle;
    char *err_msg = NULL;
    unsigned int row_count;
    int rcnt;

    spatialite_init (0);
    ret = sqlite3_open_v2 (":memory:", &handle, SQLITE_OPEN_READWRITE | SQLITE_OPEN_CREATE, NULL);
    if (ret != SQLITE_OK) {
        fprintf(stderr, "cannot open in-memory db: %s\n", sqlite3_errmsg (handle));
        sqlite3_close(handle);
        return -1;
    }

    ret = sqlite3_exec (handle, "SELECT InitSpatialMetadata()", NULL, NULL, &err_msg);
    if (ret != SQLITE_OK) {
        fprintf (stderr, "InitSpatialMetadata() error: %s\n", err_msg);
        sqlite3_free(err_msg);
        sqlite3_close(handle);
        return -2;
    }

    ret = load_XL (handle, "./testcase1.xls", "test1", 0, 0, &row_count, err_msg);
    if (!ret) {
        fprintf (stderr, "load_XL() error: %s\n", err_msg);
        sqlite3_close(handle);
        return -3;
    }
    if (row_count != 17) {
        fprintf (stderr, "load_XL() unexpected row count: %u\n", row_count);
        sqlite3_close(handle);
        return -4;
    }

    ret = load_XL (handle, "./testcase1.xls", "test2", 1, 1, &row_count, err_msg);
    if (!ret) {
        fprintf (stderr, "load_XL() error sheet 2: %s\n", err_msg);
        sqlite3_close(handle);
        return -5;
    }
    if (row_count != 19) {
        fprintf (stderr, "load_XL() unexpected row count sheet 2: %u\n", row_count);
        sqlite3_close(handle);
        return -6;
    }

    check_duplicated_rows (handle, "test1", &rcnt);
    if (rcnt != 0) {
        fprintf (stderr, "check_duplicated_rows() unexpected duplicate count: %d\n", rcnt);
        sqlite3_close(handle);
        return -8;
    }

    check_duplicated_rows (handle, "test2", &rcnt);
    if (rcnt != 2) {
        fprintf (stderr, "check_duplicated_rows() unexpected duplicate count sheet 2: %d\n", rcnt);
        sqlite3_close(handle);
        return -10;
    }

    remove_duplicated_rows (handle, "test1");

    remove_duplicated_rows (handle, "test2");

    ret = sqlite3_close (handle);
    if (ret != SQLITE_OK) {
        fprintf (stderr, "sqlite3_close() error: %s\n", sqlite3_errmsg (handle));
        return -11;
    }

    spatialite_cleanup();
#endif	/* end FreeXL conditional */

    return 0;
}
void QgsNewSpatialiteLayerDialog::on_pbnFindSRID_clicked()
{
  // first get list of supported SRID from the selected Spatialite database
  // to build filter for projection selector
  sqlite3 *db = nullptr;
  bool status = true;
  int rc = sqlite3_open_v2( mDatabaseComboBox->currentText().toUtf8(), &db, SQLITE_OPEN_READONLY, nullptr );
  if ( rc != SQLITE_OK )
  {
    QMessageBox::warning( this, tr( "SpatiaLite Database" ), tr( "Unable to open the database" ) );
    return;
  }

  // load up the srid table
  const char *pzTail;
  sqlite3_stmt *ppStmt;
  QString sql = "select auth_name || ':' || auth_srid from spatial_ref_sys order by srid asc";

  QSet<QString> myCRSs;

  rc = sqlite3_prepare( db, sql.toUtf8(), sql.toUtf8().length(), &ppStmt, &pzTail );
  // XXX Need to free memory from the error msg if one is set
  if ( rc == SQLITE_OK )
  {
    // get the first row of the result set
    while ( sqlite3_step( ppStmt ) == SQLITE_ROW )
    {
      myCRSs.insert( QString::fromUtf8(( const char * )sqlite3_column_text( ppStmt, 0 ) ) );
    }
  }
  else
  {
    // XXX query failed -- warn the user some how
    QMessageBox::warning( nullptr, tr( "Error" ), tr( "Failed to load SRIDS: %1" ).arg( sqlite3_errmsg( db ) ) );
    status = false;
  }
  // close the statement
  sqlite3_finalize( ppStmt );
  sqlite3_close( db );

  if ( !status )
  {
    return;
  }

  // prepare projection selector
  QgsGenericProjectionSelector *mySelector = new QgsGenericProjectionSelector( this );
  mySelector->setMessage();
  mySelector->setOgcWmsCrsFilter( myCRSs );
  mySelector->setSelectedAuthId( mCrsId );

  if ( mySelector->exec() )
  {
    QgsCoordinateReferenceSystem srs;
    srs.createFromOgcWmsCrs( mySelector->selectedAuthId() );
    QString crsId = srs.authid();
    if ( crsId != mCrsId )
    {
      mCrsId = crsId;
      leSRID->setText( srs.authid() + " - " + srs.description() );
    }
  }
  delete mySelector;
}
Example #15
0
DBOP *
dbop3_open(const char *path, int mode, int perm, int flags) {
	int rc, rw = 0;
	char *errmsg = 0;
	DBOP *dbop;
	sqlite3 *db3;
	const char *tblname;
	int cache_size = 0;
	STRBUF *sql = strbuf_open_tempbuf();
	char buf[1024];

	/*
	 * When the path is NULL string and private, temporary file is used.
	 * The database will be removed when the session is closed.
	 */
	if (path == NULL) {
		path = "";
		tblname = "temp";
	} else {
		/*
		 * In case of creation.
		 */
		if (mode == 1)
			(void)truncate(path, 0);
		tblname = "db";
	}
	/*
	 * setup arguments.
	 */
	switch (mode) {
	case 0:
		rw = SQLITE_OPEN_READONLY;
		break;
	case 1:
		rw = SQLITE_OPEN_CREATE|SQLITE_OPEN_READWRITE;
		break;
	case 2:
		rw = SQLITE_OPEN_READWRITE;
		break;
	default:
		assert(0);
	}
	/*
	 * When the forth argument is NULL, sqlite3_vfs is used.
	 */
	rc = sqlite3_open_v2(path, &db3, rw, NULL);
	if (rc != SQLITE_OK)
		die("sqlite3_open_v2 failed. (rc = %d)", rc);
	dbop = (DBOP *)check_calloc(sizeof(DBOP), 1);
	strlimcpy(dbop->dbname, path, sizeof(dbop->dbname));
	dbop->sb        = strbuf_open(0);
	dbop->db3       = db3;
	dbop->openflags	= flags;
	dbop->perm	= (mode == 1) ? perm : 0;
	dbop->mode      = mode;
	dbop->lastdat	= NULL;
	dbop->lastflag	= NULL;
	dbop->lastsize	= 0;
	dbop->sortout	= NULL;
	dbop->sortin	= NULL;
	dbop->stmt      = NULL;
	dbop->tblname   = check_strdup(tblname);
	/*
	 * Maximum file size is DBOP_PAGESIZE * 2147483646.
	 * if DBOP_PAGESIZE == 8192 then maximum file size is 17592186028032 (17T).
	 */
	snprintf(buf, sizeof(buf), "pragma page_size=%d", DBOP_PAGESIZE);
	rc = sqlite3_exec(dbop->db3, buf,  NULL, NULL, &errmsg);
	if (rc != SQLITE_OK)
		die("pragma page_size error: %s", errmsg);
	/*
	 * create table (GTAGS, GRTAGS, GSYMS, GPATH).
	 */
	if (mode == 1) {
		/* drop table */
		strbuf_clear(sql);
		strbuf_puts(sql, "drop table ");
		strbuf_puts(sql, dbop->tblname);
		rc = sqlite3_exec(dbop->db3, strbuf_value(sql), NULL, NULL, &errmsg);
        	if (rc != SQLITE_OK) {
			/* ignore */
		}
		/* create table */
		strbuf_clear(sql);
		strbuf_puts(sql, "create table ");
		strbuf_puts(sql, dbop->tblname);
		strbuf_puts(sql, " (key text, dat text, extra text");
		if (!(flags & DBOP_DUP))
			strbuf_puts(sql, ", primary key(key)");
		strbuf_putc(sql, ')');
		rc = sqlite3_exec(dbop->db3, strbuf_value(sql), NULL, NULL, &errmsg);
        	if (rc != SQLITE_OK)
			die("create table error: %s", errmsg);
	}
	/*
	rc = sqlite3_exec(dbop->db3, "pragma synchronous=off", NULL, NULL, &errmsg);
       	if (rc != SQLITE_OK)
		die("pragma synchronous=off error: %s", errmsg);
	*/
	/*
         * Decide cache size.
         * See libutil/gparam.h for the details.
         */
	cache_size = GTAGSCACHE;
	if (getenv("GTAGSCACHE") != NULL)
		cache_size = atoi(getenv("GTAGSCACHE"));
	if (cache_size < GTAGSMINCACHE)
		cache_size = GTAGSMINCACHE;
	cache_size = (cache_size + DBOP_PAGESIZE - 1) / DBOP_PAGESIZE;
	snprintf(buf, sizeof(buf), "pragma cache_size=%d", cache_size);
	rc = sqlite3_exec(dbop->db3, buf,  NULL, NULL, &errmsg);
       	if (rc != SQLITE_OK)
		die("pragma cache_size error: %s", errmsg);
	sqlite3_exec(dbop->db3, "pragma journal_mode=memory", NULL, NULL, &errmsg);
       	if (rc != SQLITE_OK)
		die("pragma journal_mode=memory error: %s", errmsg);
	sqlite3_exec(dbop->db3, "pragma synchronous=off", NULL, NULL, &errmsg);
       	if (rc != SQLITE_OK)
		die("pragma synchronous=off error: %s", errmsg);
	rc = sqlite3_exec(dbop->db3, "begin transaction", NULL, NULL, &errmsg);
       	if (rc != SQLITE_OK)
		die("begin transaction error: %s", errmsg);
	strbuf_release_tempbuf(sql);
	return dbop;
}
Example #16
0
Status SQLiteDatabasePlugin::setUp() {
  if (!DatabasePlugin::kDBAllowOpen) {
    LOG(WARNING) << RLOG(1629) << "Not allowed to set up database plugin";
  }

  // Consume the current settings.
  // A configuration update may change them, but that does not affect state.
  path_ = FLAGS_database_path;

  if (pathExists(path_).ok() && !isReadable(path_).ok()) {
    return Status(1, "Cannot read database path: " + path_);
  }

  if (!DatabasePlugin::kDBChecking) {
    VLOG(1) << "Opening database handle: " << path_;
  }

  // Tests may trash calls to setUp, make sure subsequent calls do not leak.
  close();

  // Open the SQLite backing storage at path_
  auto result = sqlite3_open_v2(
      path_.c_str(),
      &db_,
      (SQLITE_OPEN_FULLMUTEX | SQLITE_OPEN_READWRITE | SQLITE_OPEN_CREATE),
      nullptr);

  if (result != SQLITE_OK || db_ == nullptr) {
    if (DatabasePlugin::kDBRequireWrite) {
      close();
      // A failed open in R/W mode is a runtime error.
      return Status(1, "Cannot open database: " + std::to_string(result));
    }

    if (!DatabasePlugin::kDBChecking) {
      VLOG(1) << "Opening database failed: Continuing with read-only support";
    }

    read_only_ = true;
  }

  if (!read_only_) {
    for (const auto& domain : kDomains) {
      std::string q = "create table if not exists " + domain +
                      " (key TEXT PRIMARY KEY, value TEXT);";
      result = sqlite3_exec(db_, q.c_str(), nullptr, nullptr, nullptr);
      if (result != SQLITE_OK) {
        close();
        return Status(1, "Cannot create domain: " + domain);
      }
    }

    std::string settings;
    for (const auto& setting : kDBSettings) {
      settings += "PRAGMA " + setting.first + "=" + setting.second + "; ";
    }
    sqlite3_exec(db_, settings.c_str(), nullptr, nullptr, nullptr);
  }

  // RocksDB may not create/append a directory with acceptable permissions.
  if (!read_only_ && platformChmod(path_, S_IRWXU) == false) {
    close();
    return Status(1, "Cannot set permissions on database path: " + path_);
  }
  return Status(0);
}
int main (int argc, char *argv[])
{
    sqlite3 *db_handle = NULL;
    char *sql_statement;
    int ret;
    char *err_msg = NULL;
    int i;
    char **results;
    int rows;
    int columns;

    spatialite_init (0);

    ret = sqlite3_open_v2 (":memory:", &db_handle, SQLITE_OPEN_READWRITE | SQLITE_OPEN_CREATE, NULL);
    if (ret != SQLITE_OK) {
	fprintf (stderr, "cannot open in-memory db: %s\n", sqlite3_errmsg (db_handle));
	sqlite3_close (db_handle);
	db_handle = NULL;
	return -1;
    }
    
    ret = sqlite3_exec (db_handle, "create VIRTUAL TABLE dbftest USING VirtualDBF(\"shp/merano-3d/roads.dbf\", 'CP1252');", NULL, NULL, &err_msg);
    if (ret != SQLITE_OK) {
	fprintf (stderr, "VirtualDBF error: %s\n", err_msg);
	sqlite3_free (err_msg);
	return -2;
    }
    
    ret = sqlite3_exec (db_handle, "DROP TABLE dbftest;", NULL, NULL, &err_msg);
    if (ret != SQLITE_OK) {
	fprintf (stderr, "DROP TABLE error: %s\n", err_msg);
	sqlite3_free (err_msg);
	return -3;
    }

    ret = sqlite3_exec (db_handle, "create VIRTUAL TABLE dbftest USING VirtualDBF('shp/merano-3d/roads.dbf', \"CP1252\");", NULL, NULL, &err_msg);
    if (ret != SQLITE_OK) {
	fprintf (stderr, "VirtualDBF error: %s\n", err_msg);
	sqlite3_free (err_msg);
	return -4;
    }
    
    ret = sqlite3_exec (db_handle, "DROP TABLE dbftest;", NULL, NULL, &err_msg);
    if (ret != SQLITE_OK) {
	fprintf (stderr, "DROP TABLE error: %s\n", err_msg);
	sqlite3_free (err_msg);
	return -5;
    }

    ret = sqlite3_exec (db_handle, "create VIRTUAL TABLE dbftest USING VirtualDBF('shp/merano-3d/roads.dbf', CP1252);", NULL, NULL, &err_msg);
    if (ret != SQLITE_OK) {
	fprintf (stderr, "VirtualDBF error: %s\n", err_msg);
	sqlite3_free (err_msg);
	return -6;
    }
    
    for (i = 0; steps[i].sql; ++i) {
	ret = sqlite3_get_table (db_handle, steps[i].sql, &results, &rows, &columns, &err_msg);
	if (ret != SQLITE_OK) {
	    fprintf (stderr, "Error: %s\n", err_msg);
	    sqlite3_free (err_msg);
	    return -7;
	}
	if (rows != steps[i].num_rows) {
	    fprintf (stderr, "Unexpected num of rows for test %i: %i.\n", i, rows);
	    return  -8;
	}
	sqlite3_free_table (results);
    }

    ret = sqlite3_exec (db_handle, "DROP TABLE dbftest;", NULL, NULL, &err_msg);
    if (ret != SQLITE_OK) {
	fprintf (stderr, "DROP TABLE error: %s\n", err_msg);
	sqlite3_free (err_msg);
	return -9;
    }

    sqlite3_close (db_handle);
    spatialite_cleanup();
    sqlite3_reset_auto_extension();
    
    return 0;
}
Example #18
0
    char*   filename;
    int     rc;
    am_sqlite3* am_db;

    /* at least a filename argument is required */
    rb_scan_args( argc, argv, "11", &rFilename, &rFlags );

    /* convert flags to the sqlite version */
    flags  = ( Qnil == rFlags ) ? flags : FIX2INT(rFlags);
    filename = StringValuePtr(rFilename);

    /* extract the sqlite3 wrapper struct */
    Data_Get_Struct(self, am_sqlite3, am_db);

    /* open the sqlite3 database */
    rc = sqlite3_open_v2( filename, &(am_db->db), flags, 0);
    if ( SQLITE_OK != rc ) {
        rb_raise(eAS_Error, "Failure to open database %s : [SQLITE_ERROR %d] : %s\n",
                filename, rc, sqlite3_errmsg(am_db->db));
    }

    /* by default turn on the extended result codes */
    rc = sqlite3_extended_result_codes( am_db->db, 1);
    if ( SQLITE_OK != rc ) {
        rb_raise(eAS_Error, "Failure to set extended result codes %s : [SQLITE_ERROR %d] : %s\n",
                filename, rc, sqlite3_errmsg(am_db->db));
    }

    return self;
}
Example #19
0
int sql_init(struct rekey_session *sess) 
{
  sqlite3 *dbh;
  int dblock, rc, i;
  char *sql, *errmsg;

  if (sess->dbh)
    return 0;
  
  dblock = open(REKEY_DATABASE_LOCK, O_WRONLY | O_CREAT, 0644);
  if (dblock < 0) {
    prtmsg("Cannot create/open database lock: %s", strerror(errno));
    return 1;
  }

  if (flock(dblock, LOCK_EX)) {
    prtmsg("Cannot obtain database lock: %s", strerror(errno));
    close(dblock);
    return 1;
  }

#if SQLITE_VERSION_NUMBER >= 3005000
  rc = sqlite3_open_v2(REKEY_LOCAL_DATABASE, &dbh, SQLITE_OPEN_READWRITE, NULL);
  if (rc == SQLITE_OK) {
    sess->db_lock = dblock;
    sess->dbh = dbh;
    return 0;
  }
  
  if (rc != SQLITE_ERROR && rc != SQLITE_CANTOPEN) {
    prtmsg("Cannot open database: %d", rc);
    close(dblock);
    return 1;
  }

  rc = sqlite3_open_v2(REKEY_LOCAL_DATABASE, &dbh, SQLITE_OPEN_READWRITE | 
                       SQLITE_OPEN_CREATE, NULL);
  if (rc != SQLITE_OK) { 
    prtmsg("Cannot create/open database: %d", rc);
    close(dblock);
    return 1;
  }
#else
  rc = sqlite3_open(REKEY_LOCAL_DATABASE, &dbh);
  if (rc != SQLITE_OK) { 
    prtmsg("Cannot create/open database: %d", rc);
    close(dblock);
    return 1;
  }
#endif

  rc = sqlite3_busy_timeout(dbh, 30000);
  if (rc != SQLITE_OK) {
    prtmsg("Failed setting database busy handler: %d", rc);
    sqlite3_close(dbh);
    close(dblock);
    return 1;
  }
    
#if SQLITE_VERSION_NUMBER >= 3003007 /* need support for CREATE TRIGGER IF NOT EXIST */
  for (sql=sql_embeded_init[i=0]; sql;sql=sql_embeded_init[++i]) {
    rc = sqlite3_exec(dbh, sql, NULL, NULL, &errmsg);
    if (rc != SQLITE_OK) {
      if (errmsg) {
        prtmsg("SQL Initialization action %d failed: %s", i, errmsg);
        sqlite3_free(errmsg);
      } else {
        prtmsg("SQL Initialization action %d failed: %d", i, rc);
      }
      sqlite3_close(dbh);
      close(dblock);
      return 1;
    }
  }
#else
#warning Automatic database initialization not available
#endif
  sess->db_lock = dblock;
  sess->dbh = dbh;
  return 0;
}
int pysqlite_connection_init(pysqlite_Connection* self, PyObject* args, PyObject* kwargs)
{
    static char *kwlist[] = {
        "database", "timeout", "detect_types", "isolation_level",
        "check_same_thread", "factory", "cached_statements", "uri",
        NULL
    };

    char* database;
    int detect_types = 0;
    PyObject* isolation_level = NULL;
    PyObject* factory = NULL;
    int check_same_thread = 1;
    int cached_statements = 100;
    int uri = 0;
    double timeout = 5.0;
    int rc;

    if (!PyArg_ParseTupleAndKeywords(args, kwargs, "s|diOiOip", kwlist,
                                     &database, &timeout, &detect_types,
                                     &isolation_level, &check_same_thread,
                                     &factory, &cached_statements, &uri))
    {
        return -1;
    }

    self->initialized = 1;

    self->begin_statement = NULL;

    self->statement_cache = NULL;
    self->statements = NULL;
    self->cursors = NULL;

    Py_INCREF(Py_None);
    self->row_factory = Py_None;

    Py_INCREF(&PyUnicode_Type);
    self->text_factory = (PyObject*)&PyUnicode_Type;

#ifdef SQLITE_OPEN_URI
    Py_BEGIN_ALLOW_THREADS
    rc = sqlite3_open_v2(database, &self->db,
                         SQLITE_OPEN_READWRITE | SQLITE_OPEN_CREATE |
                         (uri ? SQLITE_OPEN_URI : 0), NULL);
#else
    if (uri) {
        PyErr_SetString(pysqlite_NotSupportedError, "URIs not supported");
        return -1;
    }
    Py_BEGIN_ALLOW_THREADS
    rc = sqlite3_open(database, &self->db);
#endif
    Py_END_ALLOW_THREADS

    if (rc != SQLITE_OK) {
        _pysqlite_seterror(self->db, NULL);
        return -1;
    }

    if (!isolation_level) {
        isolation_level = PyUnicode_FromString("");
        if (!isolation_level) {
            return -1;
        }
    } else {
        Py_INCREF(isolation_level);
    }
    self->isolation_level = NULL;
    if (pysqlite_connection_set_isolation_level(self, isolation_level) < 0) {
        Py_DECREF(isolation_level);
        return -1;
    }
    Py_DECREF(isolation_level);

    self->statement_cache = (pysqlite_Cache*)PyObject_CallFunction((PyObject*)&pysqlite_CacheType, "Oi", self, cached_statements);
    if (PyErr_Occurred()) {
        return -1;
    }

    self->created_statements = 0;
    self->created_cursors = 0;

    /* Create lists of weak references to statements/cursors */
    self->statements = PyList_New(0);
    self->cursors = PyList_New(0);
    if (!self->statements || !self->cursors) {
        return -1;
    }

    /* By default, the Cache class INCREFs the factory in its initializer, and
     * decrefs it in its deallocator method. Since this would create a circular
     * reference here, we're breaking it by decrementing self, and telling the
     * cache class to not decref the factory (self) in its deallocator.
     */
    self->statement_cache->decref_factory = 0;
    Py_DECREF(self);

    self->detect_types = detect_types;
    self->timeout = timeout;
    (void)sqlite3_busy_timeout(self->db, (int)(timeout*1000));
#ifdef WITH_THREAD
    self->thread_ident = PyThread_get_thread_ident();
#endif
    if (!check_same_thread && sqlite3_libversion_number() < 3003001) {
        PyErr_SetString(pysqlite_NotSupportedError, "shared connections not available");
        return -1;
    }
    self->check_same_thread = check_same_thread;

    self->function_pinboard = PyDict_New();
    if (!self->function_pinboard) {
        return -1;
    }

    self->collations = PyDict_New();
    if (!self->collations) {
        return -1;
    }

    self->Warning               = pysqlite_Warning;
    self->Error                 = pysqlite_Error;
    self->InterfaceError        = pysqlite_InterfaceError;
    self->DatabaseError         = pysqlite_DatabaseError;
    self->DataError             = pysqlite_DataError;
    self->OperationalError      = pysqlite_OperationalError;
    self->IntegrityError        = pysqlite_IntegrityError;
    self->InternalError         = pysqlite_InternalError;
    self->ProgrammingError      = pysqlite_ProgrammingError;
    self->NotSupportedError     = pysqlite_NotSupportedError;

    return 0;
}
static void
open_db (const char *path, sqlite3 ** handle, void *cache)
{
/* opening the DB */
    sqlite3 *db_handle;
    int ret;
    char sql[1024];
    int spatialite_rs = 0;
    int spatialite_gc = 0;
    int rs_srid = 0;
    int auth_name = 0;
    int auth_srid = 0;
    int ref_sys_name = 0;
    int proj4text = 0;
    int f_table_name = 0;
    int f_geometry_column = 0;
    int coord_dimension = 0;
    int gc_srid = 0;
    int type = 0;
    int geometry_type = 0;
    int spatial_index_enabled = 0;
    const char *name;
    int i;
    char **results;
    int rows;
    int columns;

    *handle = NULL;
    printf ("SQLite version: %s\n", sqlite3_libversion ());
    printf ("SpatiaLite version: %s\n\n", spatialite_version ());

    ret =
	sqlite3_open_v2 (path, &db_handle,
			 SQLITE_OPEN_READWRITE | SQLITE_OPEN_CREATE, NULL);
    if (ret != SQLITE_OK)
      {
	  fprintf (stderr, "cannot open '%s': %s\n", path,
		   sqlite3_errmsg (db_handle));
	  sqlite3_close (db_handle);
	  db_handle = NULL;
	  return;
      }
    spatialite_init_ex (db_handle, cache, 0);
    spatialite_autocreate (db_handle);

/* checking the GEOMETRY_COLUMNS table */
    strcpy (sql, "PRAGMA table_info(geometry_columns)");
    ret = sqlite3_get_table (db_handle, sql, &results, &rows, &columns, NULL);
    if (ret != SQLITE_OK)
	goto unknown;
    if (rows < 1)
	;
    else
      {
	  for (i = 1; i <= rows; i++)
	    {
		name = results[(i * columns) + 1];
		if (strcasecmp (name, "f_table_name") == 0)
		    f_table_name = 1;
		if (strcasecmp (name, "f_geometry_column") == 0)
		    f_geometry_column = 1;
		if (strcasecmp (name, "coord_dimension") == 0)
		    coord_dimension = 1;
		if (strcasecmp (name, "srid") == 0)
		    gc_srid = 1;
		if (strcasecmp (name, "type") == 0)
		    type = 1;
		if (strcasecmp (name, "geometry_type") == 0)
		    geometry_type = 1;
		if (strcasecmp (name, "spatial_index_enabled") == 0)
		    spatial_index_enabled = 1;
	    }
      }
    sqlite3_free_table (results);
    if (f_table_name && f_geometry_column && type && coord_dimension
	&& gc_srid && spatial_index_enabled)
	spatialite_gc = 1;
    if (f_table_name && f_geometry_column && geometry_type && coord_dimension
	&& gc_srid && spatial_index_enabled)
	spatialite_gc = 3;

/* checking the SPATIAL_REF_SYS table */
    strcpy (sql, "PRAGMA table_info(spatial_ref_sys)");
    ret = sqlite3_get_table (db_handle, sql, &results, &rows, &columns, NULL);
    if (ret != SQLITE_OK)
	goto unknown;
    if (rows < 1)
	;
    else
      {
	  for (i = 1; i <= rows; i++)
	    {
		name = results[(i * columns) + 1];
		if (strcasecmp (name, "srid") == 0)
		    rs_srid = 1;
		if (strcasecmp (name, "auth_name") == 0)
		    auth_name = 1;
		if (strcasecmp (name, "auth_srid") == 0)
		    auth_srid = 1;
		if (strcasecmp (name, "ref_sys_name") == 0)
		    ref_sys_name = 1;
		if (strcasecmp (name, "proj4text") == 0)
		    proj4text = 1;
	    }
      }
    sqlite3_free_table (results);
    if (rs_srid && auth_name && auth_srid && ref_sys_name && proj4text)
	spatialite_rs = 1;
/* verifying the MetaData format */
    if (spatialite_gc && spatialite_rs)
	;
    else
	goto unknown;

    *handle = db_handle;
    return;

  unknown:
    if (db_handle)
	sqlite3_close (db_handle);
    fprintf (stderr, "DB '%s'\n", path);
    fprintf (stderr, "doesn't seems to contain valid Spatial Metadata ...\n\n");
    fprintf (stderr, "Please, initialize Spatial Metadata\n\n");
    return;
}
Example #22
0
int main(int argc, char *argv[]) {
    sqlite3 *db = NULL;
    sqlite3_stmt *stmt = NULL;
    FILE *fblob = NULL;
    int res = 0;
    int blob_size = 0;
    int flags = SQLITE_OPEN_READWRITE;
    const char *blob_data = NULL;
    char *sql_data = "SELECT data FROM blobs WHERE id = 1";

    if (argc < 3) {
        fprintf(stderr, "Usage: %s <database> <filename>\n", argv[0]);
        exit(EXIT_FAILURE);
    }

    // Nome della tabella e del dato binario di prelevare
    const char *const db_name = (argc && argv[1]) ? argv[1] : "";
    const char *const data_name = (argc && argv[2]) ? argv[2] : "";

    // Inizializzazione della libreria
    if (sqlite3_initialize() != SQLITE_OK) {
        fprintf(stderr, "Err. Unable to initialize the library.\n");
        exit(EXIT_FAILURE);
    }

    /* Creazione della connessione al database */
    res = sqlite3_open_v2(db_name, &db, flags, NULL);

    if (res != SQLITE_OK) {
        fprintf(stderr, "Err. Can't create database: %s\n", sqlite3_errmsg(db));
        sqlite3_close(db);
        exit(EXIT_FAILURE);
    }

    // Creazione della "Prepared Statement".
    if (sqlite3_prepare_v2(db, sql_data,-1, &stmt, NULL) != SQLITE_OK) {
        fprintf(stderr, "Err. Unable to create Prepared Statement.\n");
        exit(EXIT_FAILURE);
    }

    /* Per acquisire il dato binario si deve prima di tutto calcolare il peso
    del dato stesso, dopodiche' prelevare il puntatore al dato. */
    if (sqlite3_step(stmt) == SQLITE_ROW) {
        // Primo modo per prelevare il dato, blob_data
        blob_size = sqlite3_column_bytes(stmt, 0);
        blob_data = sqlite3_column_blob(stmt, 0);

        /* Secondo modo per prelevare il dato, si alloca la memoria e si copia
        il dato mediante la funzione memcpy().
        char *blob_data;
        blob_size = sqlite3_column_bytes(stmt, 0);
        blob_data = malloc(blob_size);
        memcpy(blob_data, sqlite3_column_blob(stmt, 0), blob_size); */
    }

    fblob = fopen(data_name, "w");

    if (fblob == NULL) {
        fprintf(stderr, "Err. Open file failed: %s\n", strerror(errno));
        return 1;
    }

    if (fwrite(blob_data, blob_size, 1, fblob) != 1) {
        fprintf(stderr, "Err. Write file failed: %s\n", strerror(errno));
        return 1;
    } else
        printf("Written BLOB data into \'%s\'\n", data_name);

    fclose(fblob);

    // Rilascio della prepared statement
    if (sqlite3_finalize(stmt) == SQLITE_OK)
        puts("... Prepared Statemend destroyed.");

    // Close database connection
    if (sqlite3_close_v2(db) == SQLITE_OK)
        puts("... Closed database connection. ");

    sqlite3_shutdown();

    return(EXIT_SUCCESS);
}
Example #23
0
	inline int connectImpl()
	{
		return sqlite3_open_v2(_connectString.c_str(), _ppDB, SQLITE_OPEN_READWRITE | SQLITE_OPEN_CREATE | SQLITE_OPEN_URI, NULL);
	}
Example #24
0
static int
do_test (int legacy_mode)
{
#ifndef OMIT_GEOS		/* only if GEOS is supported */
    int ret;
    sqlite3 *handle;
    char *err_msg = NULL;
    const char *sql;
    int i;
    char **results;
    int rows;
    int columns;
    void *cache = NULL;
    if (!legacy_mode)
	cache = spatialite_alloc_connection ();
    else
	spatialite_init (0);

    ret = system ("cp sql_stmt_tests/testFDO.sqlite testFDO.sqlite");
    if (ret != 0)
      {
	  fprintf (stderr, "cannot copy testFDO.sqlite database\n");
	  return -1001;
      }

    ret =
	sqlite3_open_v2 ("testFDO.sqlite", &handle,
			 SQLITE_OPEN_READWRITE | SQLITE_OPEN_CREATE, NULL);
    if (ret != SQLITE_OK)
      {
	  fprintf (stderr, "cannot open testFDO.sqlite db: %s\n",
		   sqlite3_errmsg (handle));
	  sqlite3_close (handle);
	  return -1000;
      }

    if (!legacy_mode)
	spatialite_init_ex (handle, cache, 0);

/* FDO start-up */
    sql = "SELECT AutoFDOStart()";
    ret = sqlite3_exec (handle, sql, NULL, NULL, &err_msg);
    if (ret != SQLITE_OK)
      {
	  fprintf (stderr, "Error: %s\n", err_msg);
	  sqlite3_free (err_msg);
	  return -1;
      }

/* testing aggregate Union() PointZ WKT "p02" */
    sql = "SELECT AsText(ST_Union(WKT_GEOMETRY)) FROM fdo_p02";
    ret = sqlite3_get_table (handle, sql, &results, &rows, &columns, &err_msg);
    if (ret != SQLITE_OK)
      {
	  fprintf (stderr, "Error: %s\n", err_msg);
	  sqlite3_free (err_msg);
	  return -2;
      }
    if ((rows != 1) || (columns != 1))
      {
	  fprintf (stderr, "Unexpected error: bad result: %i/%i.\n", rows,
		   columns);
	  return -3;
      }
    if (results[1] == NULL)
      {
	  fprintf (stderr, "Unexpected error: NULL result\n");
	  return -4;
      }
    if (strcmp
	(results[1],
	 "MULTIPOINT Z(664350.17954 5171957.915655 314.52, 664642.363686 5169415.339218 294.37, 664964.447225 5170571.245732 318.25)")
	!= 0)
      {
	  fprintf (stderr, "Unexpected error: invalid result %s\n", results[1]);
	  return -5;
      }
    sqlite3_free_table (results);

/* testing aggregate Union() PointZ WKB "p03" */
    sql =
	"SELECT AsText(ST_Union(GEOMETRY)) FROM fdo_p03 WHERE text_dil IS NULL AND OGC_FID < 3";
    ret = sqlite3_get_table (handle, sql, &results, &rows, &columns, &err_msg);
    if (ret != SQLITE_OK)
      {
	  fprintf (stderr, "Error: %s\n", err_msg);
	  sqlite3_free (err_msg);
	  return -6;
      }
    if ((rows != 1) || (columns != 1))
      {
	  fprintf (stderr, "Unexpected error: bad result: %i/%i.\n", rows,
		   columns);
	  return -7;
      }
    if (results[1] == NULL)
      {
	  fprintf (stderr, "Unexpected error: NULL result\n");
	  return -8;
      }
    if (strcmp
	(results[1],
	 "MULTIPOINT Z(665216.306643 5169825.707161 296.06, 665224.506512 5169827.907054 296.16)")
	!= 0)
      {
	  fprintf (stderr, "Unexpected error: invalid result |%s|\n",
		   results[1]);
	  return -9;
      }
    sqlite3_free_table (results);

/* testing aggregate Union() PointZ SpatiaLite "p05" */
    sql =
	"SELECT AsText(ST_Union(GEOMETRY)) FROM fdo_p05 WHERE text_dil IS NULL AND OGC_FID < 3";
    ret = sqlite3_get_table (handle, sql, &results, &rows, &columns, &err_msg);
    if (ret != SQLITE_OK)
      {
	  fprintf (stderr, "Error: %s\n", err_msg);
	  sqlite3_free (err_msg);
	  return -10;
      }
    if ((rows != 1) || (columns != 1))
      {
	  fprintf (stderr, "Unexpected error: bad result: %i/%i.\n", rows,
		   columns);
	  return -11;
      }
    if (results[1] == NULL)
      {
	  fprintf (stderr, "Unexpected error: NULL result %s\n", results[1]);
	  return -12;
      }
    if (strcmp
	(results[1],
	 "MULTIPOINT Z(667687.978175 5169352.045712 583.140015, 667710.008189 5169402.894615 589.849976)")
	!= 0)
      {
	  fprintf (stderr, "Unexpected error: invalid result b|%s|\n",
		   results[1]);
	  return -13;
      }
    sqlite3_free_table (results);

/* testing Sum(GLength()) LinestringZ WKT "l05" */
    sql = "SELECT Sum(GLength(WKT_GEOMETRY)) FROM fdo_l05";
    ret = sqlite3_get_table (handle, sql, &results, &rows, &columns, &err_msg);
    if (ret != SQLITE_OK)
      {
	  fprintf (stderr, "Error: %s\n", err_msg);
	  sqlite3_free (err_msg);
	  return -14;
      }
    if ((rows != 1) || (columns != 1))
      {
	  fprintf (stderr, "Unexpected error: bad result: %i/%i.\n", rows,
		   columns);
	  return -15;
      }
    if (results[1] == NULL)
      {
	  fprintf (stderr, "Unexpected error: NULL result\n");
	  return -16;
      }
    if (strncmp (results[1], "59.417763", 9) != 0)
      {
	  fprintf (stderr, "Unexpected error: invalid result\n");
	  return -17;
      }
    sqlite3_free_table (results);

/* testing Sum(GLength()) LinestringZ WKB "l06" */
    sql = "SELECT Sum(GLength(GEOMETRY)) FROM fdo_l06";
    ret = sqlite3_get_table (handle, sql, &results, &rows, &columns, &err_msg);
    if (ret != SQLITE_OK)
      {
	  fprintf (stderr, "Error: %s\n", err_msg);
	  sqlite3_free (err_msg);
	  return -18;
      }
    if ((rows != 1) || (columns != 1))
      {
	  fprintf (stderr, "Unexpected error: bad result: %i/%i.\n", rows,
		   columns);
	  return -19;
      }
    if (results[1] == NULL)
      {
	  fprintf (stderr, "Unexpected error: NULL result\n");
	  return -20;
      }
    if (strncmp (results[1], "273.076064", 10) != 0)
      {
	  fprintf (stderr, "Unexpected error: invalid result\n");
	  return -21;
      }
    sqlite3_free_table (results);

/* testing Sum(GLength()) LinestringZ SpatiaLite "l07" */
    sql = "SELECT Sum(GLength(GEOMETRY)) FROM fdo_l07";
    ret = sqlite3_get_table (handle, sql, &results, &rows, &columns, &err_msg);
    if (ret != SQLITE_OK)
      {
	  fprintf (stderr, "Error: %s\n", err_msg);
	  sqlite3_free (err_msg);
	  return -22;
      }
    if ((rows != 1) || (columns != 1))
      {
	  fprintf (stderr, "Unexpected error: bad result: %i/%i.\n", rows,
		   columns);
	  return -23;
      }
    if (results[1] == NULL)
      {
	  fprintf (stderr, "Unexpected error: NULL result\n");
	  return -24;
      }
    if (strncmp (results[1], "219.459808", 10) != 0)
      {
	  fprintf (stderr, "Unexpected error: invalid result\n");
	  return -25;
      }
    sqlite3_free_table (results);

/* testing Sum(Area()) PolygonZ WKT "f04" */
    sql = "SELECT Sum(Area(WKT_GEOMETRY)) FROM fdo_f04";
    ret = sqlite3_get_table (handle, sql, &results, &rows, &columns, &err_msg);
    if (ret != SQLITE_OK)
      {
	  fprintf (stderr, "Error: %s\n", err_msg);
	  sqlite3_free (err_msg);
	  return -26;
      }
    if ((rows != 1) || (columns != 1))
      {
	  fprintf (stderr, "Unexpected error: bad result: %i/%i.\n", rows,
		   columns);
	  return -27;
      }
    if (results[1] == NULL)
      {
	  fprintf (stderr, "Unexpected error: NULL result\n");
	  return -28;
      }
    if (strncmp (results[1], "9960.931239", 11) != 0)
      {
	  fprintf (stderr, "Unexpected error: invalid result\n");
	  return -29;
      }
    sqlite3_free_table (results);

/* testing Sum(Area()) PolygonZ WKB "f05" */
    sql = "SELECT Sum(Area(GEOMETRY)) FROM fdo_f05";
    ret = sqlite3_get_table (handle, sql, &results, &rows, &columns, &err_msg);
    if (ret != SQLITE_OK)
      {
	  fprintf (stderr, "Error: %s\n", err_msg);
	  sqlite3_free (err_msg);
	  return -30;
      }
    if ((rows != 1) || (columns != 1))
      {
	  fprintf (stderr, "Unexpected error: bad result: %i/%i.\n", rows,
		   columns);
	  return -31;
      }
    if (results[1] == NULL)
      {
	  fprintf (stderr, "Unexpected error: NULL result\n");
	  return -32;
      }
    if (strncmp (results[1], "69972.113393", 12) != 0)
      {
	  fprintf (stderr, "Unexpected error: invalid result\n");
	  return -33;
      }
    sqlite3_free_table (results);

/* testing Sum(Area()) PolygonZ SpatiaLite "f06" */
    sql = "SELECT Sum(Area(GEOMETRY)) FROM fdo_f06";
    ret = sqlite3_get_table (handle, sql, &results, &rows, &columns, &err_msg);
    if (ret != SQLITE_OK)
      {
	  fprintf (stderr, "Error: %s\n", err_msg);
	  sqlite3_free (err_msg);
	  return -34;
      }
    if ((rows != 1) || (columns != 1))
      {
	  fprintf (stderr, "Unexpected error: bad result: %i/%i.\n", rows,
		   columns);
	  return -35;
      }
    if (results[1] == NULL)
      {
	  fprintf (stderr, "Unexpected error: NULL result\n");
	  return -36;
      }
    if (strncmp (results[1], "1125.064396", 11) != 0)
      {
	  fprintf (stderr, "Unexpected error: invalid result\n");
	  return -37;
      }
    sqlite3_free_table (results);

/* testing IsValid() LinestringZ WKB "l06" */
    sql = "SELECT IsValid(GEOMETRY) FROM fdo_l06";
    ret = sqlite3_get_table (handle, sql, &results, &rows, &columns, &err_msg);
    if (ret != SQLITE_OK)
      {
	  fprintf (stderr, "Error: %s\n", err_msg);
	  sqlite3_free (err_msg);
	  return -38;
      }
    if ((rows != 12) || (columns != 1))
      {
	  fprintf (stderr, "Unexpected error: bad result: %i/%i.\n", rows,
		   columns);
	  return -39;
      }
    for (i = 1; i <= rows; i++)
      {
	  if (results[i] == NULL)
	    {
		fprintf (stderr, "Unexpected error: NULL result\n");
		return -40;
	    }
	  if (strcmp (results[i], "0") == 0)
	    {
		const char *geos_msg;
		if (legacy_mode)
		    geos_msg = gaiaGetGeosErrorMsg ();
		else
		    geos_msg = gaiaGetGeosErrorMsg_r (cache);
		if (geos_msg == NULL)
		  {
		      if (legacy_mode)
			  geos_msg = gaiaGetGeosWarningMsg ();
		      else
			  geos_msg = gaiaGetGeosWarningMsg_r (cache);
		  }
		if (geos_msg == NULL)
		  {
		      fprintf (stderr, "Unexpected error: invalid result\n");
		      return -41;
		  }
	    }
      }
    sqlite3_free_table (results);

/* testing IsValid() PolygonZ WKT "f04" */
    sql = "SELECT IsValid(WKT_GEOMETRY) FROM fdo_f04";
    ret = sqlite3_get_table (handle, sql, &results, &rows, &columns, &err_msg);
    if (ret != SQLITE_OK)
      {
	  fprintf (stderr, "Error: %s\n", err_msg);
	  sqlite3_free (err_msg);
	  return -42;
      }
    if ((rows != 16) || (columns != 1))
      {
	  fprintf (stderr, "Unexpected error: bad result: %i/%i.\n", rows,
		   columns);
	  return -43;
      }
    for (i = 1; i <= rows; i++)
      {
	  if (results[i] == NULL)
	    {
		fprintf (stderr, "Unexpected error: NULL result\n");
		return -44;
	    }
	  if (strcmp (results[i], "0") == 0)
	    {
		const char *geos_msg;
		if (legacy_mode)
		    geos_msg = gaiaGetGeosErrorMsg ();
		else
		    geos_msg = gaiaGetGeosErrorMsg_r (cache);
		if (geos_msg == NULL)
		  {
		      if (legacy_mode)
			  geos_msg = gaiaGetGeosWarningMsg ();
		      else
			  geos_msg = gaiaGetGeosWarningMsg_r (cache);
		  }
		if (geos_msg == NULL)
		  {
		      fprintf (stderr, "Unexpected error: invalid result\n");
		      return -45;
		  }
	    }
      }
    sqlite3_free_table (results);

/* testing IsValid() PolygonZ WKB "f05" */
    sql = "SELECT IsValid(GEOMETRY) FROM fdo_f05";
    ret = sqlite3_get_table (handle, sql, &results, &rows, &columns, &err_msg);
    if (ret != SQLITE_OK)
      {
	  fprintf (stderr, "Error: %s\n", err_msg);
	  sqlite3_free (err_msg);
	  return -46;
      }
    if ((rows != 13) || (columns != 1))
      {
	  fprintf (stderr, "Unexpected error: bad result: %i/%i.\n", rows,
		   columns);
	  return -47;
      }
    for (i = 1; i <= rows; i++)
      {
	  if (results[i] == NULL)
	    {
		fprintf (stderr, "Unexpected error: NULL result\n");
		return -48;
	    }
	  if (strcmp (results[i], "0") == 0)
	    {
		const char *geos_msg;
		if (legacy_mode)
		    geos_msg = gaiaGetGeosErrorMsg ();
		else
		    geos_msg = gaiaGetGeosErrorMsg_r (cache);
		if (geos_msg == NULL)
		  {
		      if (legacy_mode)
			  geos_msg = gaiaGetGeosWarningMsg ();
		      else
			  geos_msg = gaiaGetGeosWarningMsg_r (cache);
		  }
		if (geos_msg == NULL)
		  {
		      fprintf (stderr, "Unexpected error: invalid result\n");
		      return -49;
		  }
	    }
      }
    sqlite3_free_table (results);

/* testing DOUBLE and TEXT columns */
    sql = "SELECT datum, hoehe FROM fdo_p05 WHERE OGC_FID = 5";
    ret = sqlite3_get_table (handle, sql, &results, &rows, &columns, &err_msg);
    if (ret != SQLITE_OK)
      {
	  fprintf (stderr, "Error: %s\n", err_msg);
	  sqlite3_free (err_msg);
	  return -50;
      }
    if ((rows != 1) || (columns != 2))
      {
	  fprintf (stderr, "Unexpected error: bad result: %i/%i.\n", rows,
		   columns);
	  return -51;
      }
    if (results[2] == NULL)
      {
	  fprintf (stderr, "Unexpected error: NULL result\n");
	  return -52;
      }
    if (strcmp (results[2], "1997/03/07") != 0)
      {
	  fprintf (stderr, "Unexpected error: invalid result\n");
	  return -53;
      }
    if (results[3] == NULL)
      {
	  fprintf (stderr, "Unexpected error: NULL result\n");
	  return -54;
      }
    if (strcmp (results[3], "277.55") != 0)
      {
	  fprintf (stderr, "Unexpected error: invalid result\n");
	  return -54;
      }
    sqlite3_free_table (results);

/* FDO shut-down */
    sql = "SELECT AutoFDOStop()";
    ret = sqlite3_exec (handle, sql, NULL, NULL, &err_msg);
    if (ret != SQLITE_OK)
      {
	  fprintf (stderr, "Error: %s\n", err_msg);
	  sqlite3_free (err_msg);
	  return -55;
      }

    ret = sqlite3_close (handle);
    if (ret != SQLITE_OK)
      {
	  fprintf (stderr, "sqlite3_close() error: %s\n",
		   sqlite3_errmsg (handle));
	  return -56;
      }

    spatialite_cleanup_ex (cache);
    ret = unlink ("testFDO.sqlite");
    if (ret != 0)
      {
	  fprintf (stderr, "cannot remove testFDO database\n");
	  return -57;
      }
#endif /* end GEOS conditional */

    return 0;
}
Example #25
0
bool QgsDistanceArea::setEllipsoid( const QString& ellipsoid )
{
  QString radius, parameter2;
  //
  // SQLITE3 stuff - get parameters for selected ellipsoid
  //
  sqlite3      *myDatabase;
  const char   *myTail;
  sqlite3_stmt *myPreparedStatement;
  int           myResult;

  // Shortcut if ellipsoid is none.
  if ( ellipsoid == GEO_NONE )
  {
    mEllipsoid = GEO_NONE;
    return true;
  }

  // Check if we have a custom projection, and set from text string.
  // Format is "PARAMETER:<semi-major axis>:<semi minor axis>
  // Numbers must be with (optional) decimal point and no other separators (C locale)
  // Distances in meters.  Flattening is calculated.
  if ( ellipsoid.startsWith( QLatin1String( "PARAMETER" ) ) )
  {
    QStringList paramList = ellipsoid.split( ':' );
    bool semiMajorOk, semiMinorOk;
    double semiMajor = paramList[1].toDouble( & semiMajorOk );
    double semiMinor = paramList[2].toDouble( & semiMinorOk );
    if ( semiMajorOk && semiMinorOk )
    {
      return setEllipsoid( semiMajor, semiMinor );
    }
    else
    {
      return false;
    }
  }

  // Continue with PROJ.4 list of ellipsoids.

  //check the db is available
  myResult = sqlite3_open_v2( QgsApplication::srsDatabaseFilePath().toUtf8().data(), &myDatabase, SQLITE_OPEN_READONLY, nullptr );
  if ( myResult )
  {
    QgsMessageLog::logMessage( QObject::tr( "Can't open database: %1" ).arg( sqlite3_errmsg( myDatabase ) ) );
    // XXX This will likely never happen since on open, sqlite creates the
    //     database if it does not exist.
    return false;
  }
  // Set up the query to retrieve the projection information needed to populate the ELLIPSOID list
  QString mySql = "select radius, parameter2 from tbl_ellipsoid where acronym='" + ellipsoid + '\'';
  myResult = sqlite3_prepare( myDatabase, mySql.toUtf8(), mySql.toUtf8().length(), &myPreparedStatement, &myTail );
  // XXX Need to free memory from the error msg if one is set
  if ( myResult == SQLITE_OK )
  {
    if ( sqlite3_step( myPreparedStatement ) == SQLITE_ROW )
    {
      radius = QString( reinterpret_cast< const char * >( sqlite3_column_text( myPreparedStatement, 0 ) ) );
      parameter2 = QString( reinterpret_cast< const char * >( sqlite3_column_text( myPreparedStatement, 1 ) ) );
    }
  }
  // close the sqlite3 statement
  sqlite3_finalize( myPreparedStatement );
  sqlite3_close( myDatabase );

  // row for this ellipsoid wasn't found?
  if ( radius.isEmpty() || parameter2.isEmpty() )
  {
    QgsDebugMsg( QString( "setEllipsoid: no row in tbl_ellipsoid for acronym '%1'" ).arg( ellipsoid ) );
    return false;
  }

  // get major semiaxis
  if ( radius.left( 2 ) == QLatin1String( "a=" ) )
    mSemiMajor = radius.midRef( 2 ).toDouble();
  else
  {
    QgsDebugMsg( QString( "setEllipsoid: wrong format of radius field: '%1'" ).arg( radius ) );
    return false;
  }

  // get second parameter
  // one of values 'b' or 'f' is in field parameter2
  // second one must be computed using formula: invf = a/(a-b)
  if ( parameter2.left( 2 ) == QLatin1String( "b=" ) )
  {
    mSemiMinor = parameter2.midRef( 2 ).toDouble();
    mInvFlattening = mSemiMajor / ( mSemiMajor - mSemiMinor );
  }
  else if ( parameter2.left( 3 ) == QLatin1String( "rf=" ) )
  {
    mInvFlattening = parameter2.midRef( 3 ).toDouble();
    mSemiMinor = mSemiMajor - ( mSemiMajor / mInvFlattening );
  }
  else
  {
    QgsDebugMsg( QString( "setEllipsoid: wrong format of parameter2 field: '%1'" ).arg( parameter2 ) );
    return false;
  }

  QgsDebugMsg( QString( "setEllipsoid: a=%1, b=%2, 1/f=%3" ).arg( mSemiMajor ).arg( mSemiMinor ).arg( mInvFlattening ) );


  // get spatial ref system for ellipsoid
  QString proj4 = "+proj=longlat +ellps=" + ellipsoid + " +no_defs";
  QgsCoordinateReferenceSystem destCRS = QgsCoordinateReferenceSystem::fromProj4( proj4 );
  //TODO: createFromProj4 used to save to the user database any new CRS
  // this behavior was changed in order to separate creation and saving.
  // Not sure if it necessary to save it here, should be checked by someone
  // familiar with the code (should also give a more descriptive name to the generated CRS)
  if ( destCRS.srsid() == 0 )
  {
    QString myName = QStringLiteral( " * %1 (%2)" )
                     .arg( QObject::tr( "Generated CRS", "A CRS automatically generated from layer info get this prefix for description" ),
                           destCRS.toProj4() );
    destCRS.saveAsUserCrs( myName );
  }
  //

  // set transformation from project CRS to ellipsoid coordinates
  mCoordTransform.setDestinationCrs( destCRS );

  mEllipsoid = ellipsoid;

  // precalculate some values for area calculations
  computeAreaInit();

  return true;
}
bool QgsDistanceArea::setEllipsoid( const QString& ellipsoid )
{
  QString radius, parameter2;
  //
  // SQLITE3 stuff - get parameters for selected ellipsoid
  //
  sqlite3      *myDatabase;
  const char   *myTail;
  sqlite3_stmt *myPreparedStatement;
  int           myResult;

  // Shortcut if ellipsoid is none.
  if ( ellipsoid == "NONE" )
  {
    mEllipsoid = "NONE";
    return true;
  }

  //check the db is available
  myResult = sqlite3_open_v2( QgsApplication::srsDbFilePath().toUtf8().data(), &myDatabase, SQLITE_OPEN_READONLY, NULL );
  if ( myResult )
  {
    QgsMessageLog::logMessage( QObject::tr( "Can't open database: %1" ).arg( sqlite3_errmsg( myDatabase ) ) );
    // XXX This will likely never happen since on open, sqlite creates the
    //     database if it does not exist.
    return false;
  }
  // Set up the query to retrieve the projection information needed to populate the ELLIPSOID list
  QString mySql = "select radius, parameter2 from tbl_ellipsoid where acronym='" + ellipsoid + "'";
  myResult = sqlite3_prepare( myDatabase, mySql.toUtf8(), mySql.toUtf8().length(), &myPreparedStatement, &myTail );
  // XXX Need to free memory from the error msg if one is set
  if ( myResult == SQLITE_OK )
  {
    if ( sqlite3_step( myPreparedStatement ) == SQLITE_ROW )
    {
      radius = QString(( char * )sqlite3_column_text( myPreparedStatement, 0 ) );
      parameter2 = QString(( char * )sqlite3_column_text( myPreparedStatement, 1 ) );
    }
  }
  // close the sqlite3 statement
  sqlite3_finalize( myPreparedStatement );
  sqlite3_close( myDatabase );

  // row for this ellipsoid wasn't found?
  if ( radius.isEmpty() || parameter2.isEmpty() )
  {
    QgsDebugMsg( QString( "setEllipsoid: no row in tbl_ellipsoid for acronym '%1'" ).arg( ellipsoid ) );
    return false;
  }

  // get major semiaxis
  if ( radius.left( 2 ) == "a=" )
    mSemiMajor = radius.mid( 2 ).toDouble();
  else
  {
    QgsDebugMsg( QString( "setEllipsoid: wrong format of radius field: '%1'" ).arg( radius ) );
    return false;
  }

  // get second parameter
  // one of values 'b' or 'f' is in field parameter2
  // second one must be computed using formula: invf = a/(a-b)
  if ( parameter2.left( 2 ) == "b=" )
  {
    mSemiMinor = parameter2.mid( 2 ).toDouble();
    mInvFlattening = mSemiMajor / ( mSemiMajor - mSemiMinor );
  }
  else if ( parameter2.left( 3 ) == "rf=" )
  {
    mInvFlattening = parameter2.mid( 3 ).toDouble();
    mSemiMinor = mSemiMajor - ( mSemiMajor / mInvFlattening );
  }
  else
  {
    QgsDebugMsg( QString( "setEllipsoid: wrong format of parameter2 field: '%1'" ).arg( parameter2 ) );
    return false;
  }

  QgsDebugMsg( QString( "setEllipsoid: a=%1, b=%2, 1/f=%3" ).arg( mSemiMajor ).arg( mSemiMinor ).arg( mInvFlattening ) );


  // get spatial ref system for ellipsoid
  QString proj4 = "+proj=longlat +ellps=" + ellipsoid + " +no_defs";
  QgsCoordinateReferenceSystem destCRS;
  destCRS.createFromProj4( proj4 );

  // set transformation from project CRS to ellipsoid coordinates
  mCoordTransform->setDestCRS( destCRS );

  // precalculate some values for area calculations
  computeAreaInit();

  mEllipsoid = ellipsoid;
  return true;
}
Example #27
0
static void
backup_job (GTask        *task,
            gpointer      source_object,
            gpointer      task_data,
            GCancellable *cancellable)
{
	BackupInfo *info = task_data;

	const gchar *src_path;
	GFile *parent_file, *temp_file;
	gchar *temp_path;

	sqlite3 *src_db = NULL;
	sqlite3 *temp_db = NULL;
	sqlite3_backup *backup = NULL;

	src_path = tracker_db_manager_get_file (TRACKER_DB_METADATA);
	parent_file = g_file_get_parent (info->destination);
	temp_file = g_file_get_child (parent_file, TRACKER_DB_BACKUP_META_FILENAME_T);
	g_file_delete (temp_file, NULL, NULL);
	temp_path = g_file_get_path (temp_file);

	if (sqlite3_open_v2 (src_path, &src_db, SQLITE_OPEN_READONLY, NULL) != SQLITE_OK) {
		g_set_error (&info->error, TRACKER_DB_BACKUP_ERROR, TRACKER_DB_BACKUP_ERROR_UNKNOWN,
		             "Could not open sqlite3 database:'%s'", src_path);
	}

	if (!info->error && sqlite3_open (temp_path, &temp_db) != SQLITE_OK) {
		g_set_error (&info->error, TRACKER_DB_BACKUP_ERROR, TRACKER_DB_BACKUP_ERROR_UNKNOWN,
		             "Could not open sqlite3 database:'%s'", temp_path);
	}

	if (!info->error) {
		backup = sqlite3_backup_init (temp_db, "main", src_db, "main");

		if (!backup) {
			g_set_error (&info->error, TRACKER_DB_BACKUP_ERROR, TRACKER_DB_BACKUP_ERROR_UNKNOWN,
				     "Unable to initialize sqlite3 backup from '%s' to '%s'", src_path, temp_path);
		}
	}

	if (!info->error && sqlite3_backup_step (backup, -1) != SQLITE_DONE) {
		g_set_error (&info->error, TRACKER_DB_BACKUP_ERROR, TRACKER_DB_BACKUP_ERROR_UNKNOWN,
		             "Unable to complete sqlite3 backup");
	}

	if (backup) {
		if (sqlite3_backup_finish (backup) != SQLITE_OK) {
			if (info->error) {
				/* sqlite3_backup_finish can provide more detailed error message */
				g_clear_error (&info->error);
			}
			g_set_error (&info->error,
			             TRACKER_DB_BACKUP_ERROR,
			             TRACKER_DB_BACKUP_ERROR_UNKNOWN,
				     "Unable to finish sqlite3 backup: %s",
				     sqlite3_errmsg (temp_db));
		}
		backup = NULL;
	}

	if (temp_db) {
		sqlite3_close (temp_db);
		temp_db = NULL;
	}

	if (src_db) {
		sqlite3_close (src_db);
		src_db = NULL;
	}

	if (!info->error) {
		g_file_move (temp_file, info->destination,
		             G_FILE_COPY_OVERWRITE,
		             NULL, NULL, NULL,
		             &info->error);
	}

	g_free (temp_path);
	g_object_unref (temp_file);
	g_object_unref (parent_file);

	g_idle_add_full (G_PRIORITY_DEFAULT, perform_callback, info,
	                 backup_info_free);
}
    const uint8_t *blob0;
    const uint8_t *blob1;
    void *cache = spatialite_alloc_connection();
    char *old_SPATIALITE_SECURITY_ENV = NULL;
#ifdef _WIN32
	char *env;
#endif /* not WIN32 */

    old_SPATIALITE_SECURITY_ENV = getenv("SPATIALITE_SECURITY");
#ifdef _WIN32
	putenv("SPATIALITE_SECURITY=relaxed");
#else /* not WIN32 */
    setenv("SPATIALITE_SECURITY", "relaxed", 1);
#endif
    
    ret = sqlite3_open_v2 (":memory:", &db_handle, SQLITE_OPEN_READWRITE | SQLITE_OPEN_CREATE, NULL);
    // For debugging / testing if required
    // ret = sqlite3_open_v2 ("check_point_to_tile.sqlite", &db_handle, SQLITE_OPEN_READWRITE | SQLITE_OPEN_CREATE, NULL);
    spatialite_init_ex(db_handle, cache, 0);
    if (old_SPATIALITE_SECURITY_ENV)
    {
#ifdef _WIN32 
	  env = sqlite3_mprintf("SPATIALITE_SECURITY=%s", old_SPATIALITE_SECURITY_ENV);
	  putenv(env);
	  sqlite3_free(env);
#else /* not WIN32 */
      setenv("SPATIALITE_SECURITY", old_SPATIALITE_SECURITY_ENV, 1);
#endif
    }
    else
    {
Example #29
0
int main(int argc, char **argv){
  sqlite3_int64 iBegin;        /* Start time of this program */
  int quietFlag = 0;           /* True if --quiet or -q */
  int verboseFlag = 0;         /* True if --verbose or -v */
  char *zInsSql = 0;           /* SQL statement for --load-db or --load-sql */
  int iFirstInsArg = 0;        /* First argv[] to use for --load-db or --load-sql */
  sqlite3 *db = 0;             /* The open database connection */
  sqlite3_stmt *pStmt;         /* A prepared statement */
  int rc;                      /* Result code from SQLite interface calls */
  Blob *pSql;                  /* For looping over SQL scripts */
  Blob *pDb;                   /* For looping over template databases */
  int i;                       /* Loop index for the argv[] loop */
  int onlySqlid = -1;          /* --sqlid */
  int onlyDbid = -1;           /* --dbid */
  int nativeFlag = 0;          /* --native-vfs */
  int rebuildFlag = 0;         /* --rebuild */
  int vdbeLimitFlag = 0;       /* --limit-vdbe */
  int timeoutTest = 0;         /* undocumented --timeout-test flag */
  int runFlags = 0;            /* Flags sent to runSql() */
  char *zMsg = 0;              /* Add this message */
  int nSrcDb = 0;              /* Number of source databases */
  char **azSrcDb = 0;          /* Array of source database names */
  int iSrcDb;                  /* Loop over all source databases */
  int nTest = 0;               /* Total number of tests performed */
  char *zDbName = "";          /* Appreviated name of a source database */
  const char *zFailCode = 0;   /* Value of the TEST_FAILURE environment variable */
  int cellSzCkFlag = 0;        /* --cell-size-check */
  int sqlFuzz = 0;             /* True for SQL fuzz testing. False for DB fuzz */
  int iTimeout = 120;          /* Default 120-second timeout */
  int nMem = 0;                /* Memory limit */
  char *zExpDb = 0;            /* Write Databases to files in this directory */
  char *zExpSql = 0;           /* Write SQL to files in this directory */
  void *pHeap = 0;             /* Heap for use by SQLite */

  iBegin = timeOfDay();
#ifdef __unix__
  signal(SIGALRM, timeoutHandler);
#endif
  g.zArgv0 = argv[0];
  zFailCode = getenv("TEST_FAILURE");
  for(i=1; i<argc; i++){
    const char *z = argv[i];
    if( z[0]=='-' ){
      z++;
      if( z[0]=='-' ) z++;
      if( strcmp(z,"cell-size-check")==0 ){
        cellSzCkFlag = 1;
      }else
      if( strcmp(z,"dbid")==0 ){
        if( i>=argc-1 ) fatalError("missing arguments on %s", argv[i]);
        onlyDbid = integerValue(argv[++i]);
      }else
      if( strcmp(z,"export-db")==0 ){
        if( i>=argc-1 ) fatalError("missing arguments on %s", argv[i]);
        zExpDb = argv[++i];
      }else
      if( strcmp(z,"export-sql")==0 ){
        if( i>=argc-1 ) fatalError("missing arguments on %s", argv[i]);
        zExpSql = argv[++i];
      }else
      if( strcmp(z,"help")==0 ){
        showHelp();
        return 0;
      }else
      if( strcmp(z,"limit-mem")==0 ){
#if !defined(SQLITE_ENABLE_MEMSYS3) && !defined(SQLITE_ENABLE_MEMSYS5)
        fatalError("the %s option requires -DSQLITE_ENABLE_MEMSYS5 or _MEMSYS3",
                   argv[i]);
#else
        if( i>=argc-1 ) fatalError("missing arguments on %s", argv[i]);
        nMem = integerValue(argv[++i]);
#endif
      }else
      if( strcmp(z,"limit-vdbe")==0 ){
        vdbeLimitFlag = 1;
      }else
      if( strcmp(z,"load-sql")==0 ){
        zInsSql = "INSERT INTO xsql(sqltext) VALUES(CAST(readfile(?1) AS text))";
        iFirstInsArg = i+1;
        break;
      }else
      if( strcmp(z,"load-db")==0 ){
        zInsSql = "INSERT INTO db(dbcontent) VALUES(readfile(?1))";
        iFirstInsArg = i+1;
        break;
      }else
      if( strcmp(z,"m")==0 ){
        if( i>=argc-1 ) fatalError("missing arguments on %s", argv[i]);
        zMsg = argv[++i];
      }else
      if( strcmp(z,"native-vfs")==0 ){
        nativeFlag = 1;
      }else
      if( strcmp(z,"quiet")==0 || strcmp(z,"q")==0 ){
        quietFlag = 1;
        verboseFlag = 0;
      }else
      if( strcmp(z,"rebuild")==0 ){
        rebuildFlag = 1;
      }else
      if( strcmp(z,"result-trace")==0 ){
        runFlags |= SQL_OUTPUT;
      }else
      if( strcmp(z,"sqlid")==0 ){
        if( i>=argc-1 ) fatalError("missing arguments on %s", argv[i]);
        onlySqlid = integerValue(argv[++i]);
      }else
      if( strcmp(z,"timeout")==0 ){
        if( i>=argc-1 ) fatalError("missing arguments on %s", argv[i]);
        iTimeout = integerValue(argv[++i]);
      }else
      if( strcmp(z,"timeout-test")==0 ){
        timeoutTest = 1;
#ifndef __unix__
        fatalError("timeout is not available on non-unix systems");
#endif
      }else
      if( strcmp(z,"verbose")==0 || strcmp(z,"v")==0 ){
        quietFlag = 0;
        verboseFlag = 1;
        runFlags |= SQL_TRACE;
      }else
      {
        fatalError("unknown option: %s", argv[i]);
      }
    }else{
      nSrcDb++;
      azSrcDb = safe_realloc(azSrcDb, nSrcDb*sizeof(azSrcDb[0]));
      azSrcDb[nSrcDb-1] = argv[i];
    }
  }
  if( nSrcDb==0 ) fatalError("no source database specified");
  if( nSrcDb>1 ){
    if( zMsg ){
      fatalError("cannot change the description of more than one database");
    }
    if( zInsSql ){
      fatalError("cannot import into more than one database");
    }
  }

  /* Process each source database separately */
  for(iSrcDb=0; iSrcDb<nSrcDb; iSrcDb++){
    rc = sqlite3_open(azSrcDb[iSrcDb], &db);
    if( rc ){
      fatalError("cannot open source database %s - %s",
      azSrcDb[iSrcDb], sqlite3_errmsg(db));
    }
    rc = sqlite3_exec(db,
       "CREATE TABLE IF NOT EXISTS db(\n"
       "  dbid INTEGER PRIMARY KEY, -- database id\n"
       "  dbcontent BLOB            -- database disk file image\n"
       ");\n"
       "CREATE TABLE IF NOT EXISTS xsql(\n"
       "  sqlid INTEGER PRIMARY KEY,   -- SQL script id\n"
       "  sqltext TEXT                 -- Text of SQL statements to run\n"
       ");"
       "CREATE TABLE IF NOT EXISTS readme(\n"
       "  msg TEXT -- Human-readable description of this file\n"
       ");", 0, 0, 0);
    if( rc ) fatalError("cannot create schema: %s", sqlite3_errmsg(db));
    if( zMsg ){
      char *zSql;
      zSql = sqlite3_mprintf(
               "DELETE FROM readme; INSERT INTO readme(msg) VALUES(%Q)", zMsg);
      rc = sqlite3_exec(db, zSql, 0, 0, 0);
      sqlite3_free(zSql);
      if( rc ) fatalError("cannot change description: %s", sqlite3_errmsg(db));
    }
    if( zInsSql ){
      sqlite3_create_function(db, "readfile", 1, SQLITE_UTF8, 0,
                              readfileFunc, 0, 0);
      rc = sqlite3_prepare_v2(db, zInsSql, -1, &pStmt, 0);
      if( rc ) fatalError("cannot prepare statement [%s]: %s",
                          zInsSql, sqlite3_errmsg(db));
      rc = sqlite3_exec(db, "BEGIN", 0, 0, 0);
      if( rc ) fatalError("cannot start a transaction");
      for(i=iFirstInsArg; i<argc; i++){
        sqlite3_bind_text(pStmt, 1, argv[i], -1, SQLITE_STATIC);
        sqlite3_step(pStmt);
        rc = sqlite3_reset(pStmt);
        if( rc ) fatalError("insert failed for %s", argv[i]);
      }
      sqlite3_finalize(pStmt);
      rc = sqlite3_exec(db, "COMMIT", 0, 0, 0);
      if( rc ) fatalError("cannot commit the transaction: %s", sqlite3_errmsg(db));
      rebuild_database(db);
      sqlite3_close(db);
      return 0;
    }
    if( zExpDb!=0 || zExpSql!=0 ){
      sqlite3_create_function(db, "writefile", 2, SQLITE_UTF8, 0,
                              writefileFunc, 0, 0);
      if( zExpDb!=0 ){
        const char *zExDb = 
          "SELECT writefile(printf('%s/db%06d.db',?1,dbid),dbcontent),"
          "       dbid, printf('%s/db%06d.db',?1,dbid), length(dbcontent)"
          "  FROM db WHERE ?2<0 OR dbid=?2;";
        rc = sqlite3_prepare_v2(db, zExDb, -1, &pStmt, 0);
        if( rc ) fatalError("cannot prepare statement [%s]: %s",
                            zExDb, sqlite3_errmsg(db));
        sqlite3_bind_text64(pStmt, 1, zExpDb, strlen(zExpDb),
                            SQLITE_STATIC, SQLITE_UTF8);
        sqlite3_bind_int(pStmt, 2, onlyDbid);
        while( sqlite3_step(pStmt)==SQLITE_ROW ){
          printf("write db-%d (%d bytes) into %s\n",
             sqlite3_column_int(pStmt,1),
             sqlite3_column_int(pStmt,3),
             sqlite3_column_text(pStmt,2));
        }
        sqlite3_finalize(pStmt);
      }
      if( zExpSql!=0 ){
        const char *zExSql = 
          "SELECT writefile(printf('%s/sql%06d.txt',?1,sqlid),sqltext),"
          "       sqlid, printf('%s/sql%06d.txt',?1,sqlid), length(sqltext)"
          "  FROM xsql WHERE ?2<0 OR sqlid=?2;";
        rc = sqlite3_prepare_v2(db, zExSql, -1, &pStmt, 0);
        if( rc ) fatalError("cannot prepare statement [%s]: %s",
                            zExSql, sqlite3_errmsg(db));
        sqlite3_bind_text64(pStmt, 1, zExpSql, strlen(zExpSql),
                            SQLITE_STATIC, SQLITE_UTF8);
        sqlite3_bind_int(pStmt, 2, onlySqlid);
        while( sqlite3_step(pStmt)==SQLITE_ROW ){
          printf("write sql-%d (%d bytes) into %s\n",
             sqlite3_column_int(pStmt,1),
             sqlite3_column_int(pStmt,3),
             sqlite3_column_text(pStmt,2));
        }
        sqlite3_finalize(pStmt);
      }
      sqlite3_close(db);
      return 0;
    }
  
    /* Load all SQL script content and all initial database images from the
    ** source db
    */
    blobListLoadFromDb(db, "SELECT sqlid, sqltext FROM xsql", onlySqlid,
                           &g.nSql, &g.pFirstSql);
    if( g.nSql==0 ) fatalError("need at least one SQL script");
    blobListLoadFromDb(db, "SELECT dbid, dbcontent FROM db", onlyDbid,
                       &g.nDb, &g.pFirstDb);
    if( g.nDb==0 ){
      g.pFirstDb = safe_realloc(0, sizeof(Blob));
      memset(g.pFirstDb, 0, sizeof(Blob));
      g.pFirstDb->id = 1;
      g.pFirstDb->seq = 0;
      g.nDb = 1;
      sqlFuzz = 1;
    }
  
    /* Print the description, if there is one */
    if( !quietFlag ){
      zDbName = azSrcDb[iSrcDb];
      i = strlen(zDbName) - 1;
      while( i>0 && zDbName[i-1]!='/' && zDbName[i-1]!='\\' ){ i--; }
      zDbName += i;
      sqlite3_prepare_v2(db, "SELECT msg FROM readme", -1, &pStmt, 0);
      if( pStmt && sqlite3_step(pStmt)==SQLITE_ROW ){
        printf("%s: %s\n", zDbName, sqlite3_column_text(pStmt,0));
      }
      sqlite3_finalize(pStmt);
    }

    /* Rebuild the database, if requested */
    if( rebuildFlag ){
      if( !quietFlag ){
        printf("%s: rebuilding... ", zDbName);
        fflush(stdout);
      }
      rebuild_database(db);
      if( !quietFlag ) printf("done\n");
    }
  
    /* Close the source database.  Verify that no SQLite memory allocations are
    ** outstanding.
    */
    sqlite3_close(db);
    if( sqlite3_memory_used()>0 ){
      fatalError("SQLite has memory in use before the start of testing");
    }

    /* Limit available memory, if requested */
    if( nMem>0 ){
      sqlite3_shutdown();
      pHeap = malloc(nMem);
      if( pHeap==0 ){
        fatalError("failed to allocate %d bytes of heap memory", nMem);
      }
      sqlite3_config(SQLITE_CONFIG_HEAP, pHeap, nMem, 128);
    }
  
    /* Register the in-memory virtual filesystem
    */
    formatVfs();
    inmemVfsRegister();
    
    /* Run a test using each SQL script against each database.
    */
    if( !verboseFlag && !quietFlag ) printf("%s:", zDbName);
    for(pSql=g.pFirstSql; pSql; pSql=pSql->pNext){
      for(pDb=g.pFirstDb; pDb; pDb=pDb->pNext){
        int openFlags;
        const char *zVfs = "inmem";
        sqlite3_snprintf(sizeof(g.zTestName), g.zTestName, "sqlid=%d,dbid=%d",
                         pSql->id, pDb->id);
        if( verboseFlag ){
          printf("%s\n", g.zTestName);
          fflush(stdout);
        }else if( !quietFlag ){
          static int prevAmt = -1;
          int idx = pSql->seq*g.nDb + pDb->id - 1;
          int amt = idx*10/(g.nDb*g.nSql);
          if( amt!=prevAmt ){
            printf(" %d%%", amt*10);
            fflush(stdout);
            prevAmt = amt;
          }
        }
        createVFile("main.db", pDb->sz, pDb->a);
        openFlags = SQLITE_OPEN_CREATE | SQLITE_OPEN_READWRITE;
        if( nativeFlag && pDb->sz==0 ){
          openFlags |= SQLITE_OPEN_MEMORY;
          zVfs = 0;
        }
        rc = sqlite3_open_v2("main.db", &db, openFlags, zVfs);
        if( rc ) fatalError("cannot open inmem database");
        if( cellSzCkFlag ) runSql(db, "PRAGMA cell_size_check=ON", runFlags);
        setAlarm(iTimeout);
#ifndef SQLITE_OMIT_PROGRESS_CALLBACK
        if( sqlFuzz || vdbeLimitFlag ){
          sqlite3_progress_handler(db, 100000, progressHandler, &vdbeLimitFlag);
        }
#endif
        do{
          runSql(db, (char*)pSql->a, runFlags);
        }while( timeoutTest );
        setAlarm(0);
        sqlite3_close(db);
        if( sqlite3_memory_used()>0 ) fatalError("memory leak");
        reformatVfs();
        nTest++;
        g.zTestName[0] = 0;

        /* Simulate an error if the TEST_FAILURE environment variable is "5".
        ** This is used to verify that automated test script really do spot
        ** errors that occur in this test program.
        */
        if( zFailCode ){
          if( zFailCode[0]=='5' && zFailCode[1]==0 ){
            fatalError("simulated failure");
          }else if( zFailCode[0]!=0 ){
            /* If TEST_FAILURE is something other than 5, just exit the test
            ** early */
            printf("\nExit early due to TEST_FAILURE being set\n");
            iSrcDb = nSrcDb-1;
            goto sourcedb_cleanup;
          }
        }
      }
    }
    if( !quietFlag && !verboseFlag ){
      printf(" 100%% - %d tests\n", g.nDb*g.nSql);
    }
  
    /* Clean up at the end of processing a single source database
    */
  sourcedb_cleanup:
    blobListFree(g.pFirstSql);
    blobListFree(g.pFirstDb);
    reformatVfs();
 
  } /* End loop over all source databases */

  if( !quietFlag ){
    sqlite3_int64 iElapse = timeOfDay() - iBegin;
    printf("fuzzcheck: 0 errors out of %d tests in %d.%03d seconds\n"
           "SQLite %s %s\n",
           nTest, (int)(iElapse/1000), (int)(iElapse%1000),
           sqlite3_libversion(), sqlite3_sourceid());
  }
  free(azSrcDb);
  free(pHeap);
  return 0;
}
int
main (int argc, char *argv[])
{
    int ret;
    sqlite3 *handle;
    char *err_msg = NULL;
    const char *sql;
    char **results;
    int rows;
    int columns;
    void *cache = spatialite_alloc_connection ();

    if (argc > 1 || argv[0] == NULL)
	argc = 1;		/* silencing stupid compiler warnings */

    ret =
	sqlite3_open_v2 (":memory:", &handle,
			 SQLITE_OPEN_READWRITE | SQLITE_OPEN_CREATE, NULL);
    if (ret != SQLITE_OK)
      {
	  fprintf (stderr, "cannot open in-memory database: %s\n",
		   sqlite3_errmsg (handle));
	  sqlite3_close (handle);
	  return -1;
      }

    spatialite_init_ex (handle, cache, 0);

    ret =
	sqlite3_exec (handle, "SELECT InitSpatialMetadata(1)", NULL, NULL,
		      &err_msg);
    if (ret != SQLITE_OK)
      {
	  fprintf (stderr, "InitSpatialMetadata() error: %s\n", err_msg);
	  sqlite3_free (err_msg);
	  sqlite3_close (handle);
	  return -2;
      }
/* creating a Point XY table */
    sql = "CREATE TABLE pt_xy (id INTEGER, g BLOB)";
    ret = sqlite3_exec (handle, sql, NULL, NULL, &err_msg);
    if (ret != SQLITE_OK)
      {
	  fprintf (stderr, "Error: %s\n", err_msg);
	  sqlite3_free (err_msg);
	  return -3;
      }

/* creating a Point XYZ table */
    sql = "CREATE TABLE pt_xyz (id INTEGER, g BLOB)";
    ret = sqlite3_exec (handle, sql, NULL, NULL, &err_msg);
    if (ret != SQLITE_OK)
      {
	  fprintf (stderr, "Error: %s\n", err_msg);
	  sqlite3_free (err_msg);
	  return -4;
      }

/* creating a Point XYM table */
    sql = "CREATE TABLE pt_xym (id INTEGER, g BLOB)";
    ret = sqlite3_exec (handle, sql, NULL, NULL, &err_msg);
    if (ret != SQLITE_OK)
      {
	  fprintf (stderr, "Error: %s\n", err_msg);
	  sqlite3_free (err_msg);
	  return -5;
      }

/* creating a Point XYZM table */
    sql = "CREATE TABLE pt_xyzm (id INTEGER, g BLOB)";
    ret = sqlite3_exec (handle, sql, NULL, NULL, &err_msg);
    if (ret != SQLITE_OK)
      {
	  fprintf (stderr, "Error: %s\n", err_msg);
	  sqlite3_free (err_msg);
	  return -6;
      }

/* creating a Linestring XY table */
    sql = "CREATE TABLE ln_xy (id INTEGER, g BLOB)";
    ret = sqlite3_exec (handle, sql, NULL, NULL, &err_msg);
    if (ret != SQLITE_OK)
      {
	  fprintf (stderr, "Error: %s\n", err_msg);
	  sqlite3_free (err_msg);
	  return -7;
      }

/* creating a Linestring XYZ table */
    sql = "CREATE TABLE ln_xyz (id INTEGER, g BLOB)";
    ret = sqlite3_exec (handle, sql, NULL, NULL, &err_msg);
    if (ret != SQLITE_OK)
      {
	  fprintf (stderr, "Error: %s\n", err_msg);
	  sqlite3_free (err_msg);
	  return -8;
      }

/* creating a Linestring XYM table */
    sql = "CREATE TABLE ln_xym (id INTEGER, g BLOB)";
    ret = sqlite3_exec (handle, sql, NULL, NULL, &err_msg);
    if (ret != SQLITE_OK)
      {
	  fprintf (stderr, "Error: %s\n", err_msg);
	  sqlite3_free (err_msg);
	  return -9;
      }

/* creating a Linestring XYZM table */
    sql = "CREATE TABLE ln_xyzm (id INTEGER, g BLOB)";
    ret = sqlite3_exec (handle, sql, NULL, NULL, &err_msg);
    if (ret != SQLITE_OK)
      {
	  fprintf (stderr, "Error: %s\n", err_msg);
	  sqlite3_free (err_msg);
	  return -10;
      }

/* creating a Polygon XY table */
    sql = "CREATE TABLE pg_xy (id INTEGER, g BLOB)";
    ret = sqlite3_exec (handle, sql, NULL, NULL, &err_msg);
    if (ret != SQLITE_OK)
      {
	  fprintf (stderr, "Error: %s\n", err_msg);
	  sqlite3_free (err_msg);
	  return -11;
      }

/* creating a Polygon XYZ table */
    sql = "CREATE TABLE pg_xyz (id INTEGER, g BLOB)";
    ret = sqlite3_exec (handle, sql, NULL, NULL, &err_msg);
    if (ret != SQLITE_OK)
      {
	  fprintf (stderr, "Error: %s\n", err_msg);
	  sqlite3_free (err_msg);
	  return -12;
      }

/* creating a Polygon XYM table */
    sql = "CREATE TABLE pg_xym (id INTEGER, g BLOB)";
    ret = sqlite3_exec (handle, sql, NULL, NULL, &err_msg);
    if (ret != SQLITE_OK)
      {
	  fprintf (stderr, "Error: %s\n", err_msg);
	  sqlite3_free (err_msg);
	  return -13;
      }

/* creating a Polygon XYZM table */
    sql = "CREATE TABLE pg_xyzm (id INTEGER, g BLOB)";
    ret = sqlite3_exec (handle, sql, NULL, NULL, &err_msg);
    if (ret != SQLITE_OK)
      {
	  fprintf (stderr, "Error: %s\n", err_msg);
	  sqlite3_free (err_msg);
	  return -14;
      }

/* creating a MultiPoint XY table */
    sql = "CREATE TABLE mpt_xy (id INTEGER, g BLOB)";
    ret = sqlite3_exec (handle, sql, NULL, NULL, &err_msg);
    if (ret != SQLITE_OK)
      {
	  fprintf (stderr, "Error: %s\n", err_msg);
	  sqlite3_free (err_msg);
	  return -15;
      }

/* creating a MultiPoint XYZ table */
    sql = "CREATE TABLE mpt_XYZ (id INTEGER, g BLOB)";
    ret = sqlite3_exec (handle, sql, NULL, NULL, &err_msg);
    if (ret != SQLITE_OK)
      {
	  fprintf (stderr, "Error: %s\n", err_msg);
	  sqlite3_free (err_msg);
	  return -16;
      }

/* creating a MultiPoint XYM table */
    sql = "CREATE TABLE mpt_xym (id INTEGER, g BLOB)";
    ret = sqlite3_exec (handle, sql, NULL, NULL, &err_msg);
    if (ret != SQLITE_OK)
      {
	  fprintf (stderr, "Error: %s\n", err_msg);
	  sqlite3_free (err_msg);
	  return -17;
      }

/* creating a MultiPoint XYZM table */
    sql = "CREATE TABLE mpt_xyzm (id INTEGER, g BLOB)";
    ret = sqlite3_exec (handle, sql, NULL, NULL, &err_msg);
    if (ret != SQLITE_OK)
      {
	  fprintf (stderr, "Error: %s\n", err_msg);
	  sqlite3_free (err_msg);
	  return -18;
      }

/* creating a MultiLinestring XY table */
    sql = "CREATE TABLE mln_xy (id INTEGER, g BLOB)";
    ret = sqlite3_exec (handle, sql, NULL, NULL, &err_msg);
    if (ret != SQLITE_OK)
      {
	  fprintf (stderr, "Error: %s\n", err_msg);
	  sqlite3_free (err_msg);
	  return -19;
      }

/* creating a MultiLinestring XYZ table */
    sql = "CREATE TABLE mln_xyz (id INTEGER, g BLOB)";
    ret = sqlite3_exec (handle, sql, NULL, NULL, &err_msg);
    if (ret != SQLITE_OK)
      {
	  fprintf (stderr, "Error: %s\n", err_msg);
	  sqlite3_free (err_msg);
	  return -20;
      }

/* creating a MultiLinestring XYM table */
    sql = "CREATE TABLE mln_xym (id INTEGER, g BLOB)";
    ret = sqlite3_exec (handle, sql, NULL, NULL, &err_msg);
    if (ret != SQLITE_OK)
      {
	  fprintf (stderr, "Error: %s\n", err_msg);
	  sqlite3_free (err_msg);
	  return -21;
      }

/* creating a MultiLinestring XYZM table */
    sql = "CREATE TABLE mln_xyzm (id INTEGER, g BLOB)";
    ret = sqlite3_exec (handle, sql, NULL, NULL, &err_msg);
    if (ret != SQLITE_OK)
      {
	  fprintf (stderr, "Error: %s\n", err_msg);
	  sqlite3_free (err_msg);
	  return -22;
      }

/* creating a MultiPolygon XY table */
    sql = "CREATE TABLE mpg_xy (id INTEGER, g BLOB)";
    ret = sqlite3_exec (handle, sql, NULL, NULL, &err_msg);
    if (ret != SQLITE_OK)
      {
	  fprintf (stderr, "Error: %s\n", err_msg);
	  sqlite3_free (err_msg);
	  return -23;
      }

/* creating a MultiPolygon XYZ table */
    sql = "CREATE TABLE mpg_xyz (id INTEGER, g BLOB)";
    ret = sqlite3_exec (handle, sql, NULL, NULL, &err_msg);
    if (ret != SQLITE_OK)
      {
	  fprintf (stderr, "Error: %s\n", err_msg);
	  sqlite3_free (err_msg);
	  return -24;
      }

/* creating a MultiPolygon XYM table */
    sql = "CREATE TABLE mpg_xym (id INTEGER, g BLOB)";
    ret = sqlite3_exec (handle, sql, NULL, NULL, &err_msg);
    if (ret != SQLITE_OK)
      {
	  fprintf (stderr, "Error: %s\n", err_msg);
	  sqlite3_free (err_msg);
	  return -25;
      }

/* creating a MultiPolygon XYZM table */
    sql = "CREATE TABLE mpg_xyzm (id INTEGER, g BLOB)";
    ret = sqlite3_exec (handle, sql, NULL, NULL, &err_msg);
    if (ret != SQLITE_OK)
      {
	  fprintf (stderr, "Error: %s\n", err_msg);
	  sqlite3_free (err_msg);
	  return -26;
      }

/* creating a GeometryCollection XY table */
    sql = "CREATE TABLE gcoll_xy (id INTEGER, g BLOB)";
    ret = sqlite3_exec (handle, sql, NULL, NULL, &err_msg);
    if (ret != SQLITE_OK)
      {
	  fprintf (stderr, "Error: %s\n", err_msg);
	  sqlite3_free (err_msg);
	  return -27;
      }

/* creating a GeometryCollection XYZ table */
    sql = "CREATE TABLE gcoll_xyz (id INTEGER, g BLOB)";
    ret = sqlite3_exec (handle, sql, NULL, NULL, &err_msg);
    if (ret != SQLITE_OK)
      {
	  fprintf (stderr, "Error: %s\n", err_msg);
	  sqlite3_free (err_msg);
	  return -28;
      }

/* creating a GeometryCollection XYM table */
    sql = "CREATE TABLE gcoll_xym (id INTEGER, g BLOB)";
    ret = sqlite3_exec (handle, sql, NULL, NULL, &err_msg);
    if (ret != SQLITE_OK)
      {
	  fprintf (stderr, "Error: %s\n", err_msg);
	  sqlite3_free (err_msg);
	  return -29;
      }

/* creating a GeometryCollection XYZM table */
    sql = "CREATE TABLE gcoll_xyzm (id INTEGER, g BLOB)";
    ret = sqlite3_exec (handle, sql, NULL, NULL, &err_msg);
    if (ret != SQLITE_OK)
      {
	  fprintf (stderr, "Error: %s\n", err_msg);
	  sqlite3_free (err_msg);
	  return -30;
      }


/* creating a Geometry XY table */
    sql = "CREATE TABLE geom_xy (id INTEGER, g BLOB)";
    ret = sqlite3_exec (handle, sql, NULL, NULL, &err_msg);
    if (ret != SQLITE_OK)
      {
	  fprintf (stderr, "Error: %s\n", err_msg);
	  sqlite3_free (err_msg);
	  return -31;
      }

/* creating a Geometry XYZ table */
    sql = "CREATE TABLE geom_xyz (id INTEGER, g BLOB)";
    ret = sqlite3_exec (handle, sql, NULL, NULL, &err_msg);
    if (ret != SQLITE_OK)
      {
	  fprintf (stderr, "Error: %s\n", err_msg);
	  sqlite3_free (err_msg);
	  return -32;
      }

/* creating a Geometry XYM table */
    sql = "CREATE TABLE geom_xym (id INTEGER, g BLOB)";
    ret = sqlite3_exec (handle, sql, NULL, NULL, &err_msg);
    if (ret != SQLITE_OK)
      {
	  fprintf (stderr, "Error: %s\n", err_msg);
	  sqlite3_free (err_msg);
	  return -33;
      }

/* creating a Geometry XYZM table */
    sql = "CREATE TABLE geom_xyzm (id INTEGER, g BLOB)";
    ret = sqlite3_exec (handle, sql, NULL, NULL, &err_msg);
    if (ret != SQLITE_OK)
      {
	  fprintf (stderr, "Error: %s\n", err_msg);
	  sqlite3_free (err_msg);
	  return -34;
      }

/* Inserting into pt_xy */
    sql =
	"INSERT INTO pt_xy (id, g) VALUES (1, GeomFromText('POINT(1 2)', 4326))";
    ret = sqlite3_exec (handle, sql, NULL, NULL, &err_msg);
    if (ret != SQLITE_OK)
      {
	  fprintf (stderr, "Error: %s\n", err_msg);
	  sqlite3_free (err_msg);
	  return -35;
      }

/* Inserting into pt_xyz */
    sql =
	"INSERT INTO pt_xyz (id, g) VALUES (1, GeomFromText('POINTZ(1 2 3)', 4326))";
    ret = sqlite3_exec (handle, sql, NULL, NULL, &err_msg);
    if (ret != SQLITE_OK)
      {
	  fprintf (stderr, "Error: %s\n", err_msg);
	  sqlite3_free (err_msg);
	  return -36;
      }

/* Inserting into pt_xym */
    sql =
	"INSERT INTO pt_xym (id, g) VALUES (1, GeomFromText('POINTM(1 2 10)', 4326))";
    ret = sqlite3_exec (handle, sql, NULL, NULL, &err_msg);
    if (ret != SQLITE_OK)
      {
	  fprintf (stderr, "Error: %s\n", err_msg);
	  sqlite3_free (err_msg);
	  return -37;
      }

/* Inserting into pt_xyzm */
    sql =
	"INSERT INTO pt_xyzm (id, g) VALUES (1, GeomFromText('POINTZM(1 2 3 10)', 4326))";
    ret = sqlite3_exec (handle, sql, NULL, NULL, &err_msg);
    if (ret != SQLITE_OK)
      {
	  fprintf (stderr, "Error: %s\n", err_msg);
	  sqlite3_free (err_msg);
	  return -38;
      }

/* Inserting into ln_xy */
    sql =
	"INSERT INTO ln_xy (id, g) VALUES (1, GeomFromText('LINESTRING(1 2, 4 5)', 4326))";
    ret = sqlite3_exec (handle, sql, NULL, NULL, &err_msg);
    if (ret != SQLITE_OK)
      {
	  fprintf (stderr, "Error: %s\n", err_msg);
	  sqlite3_free (err_msg);
	  return -39;
      }

/* Inserting into ln_xyz */
    sql =
	"INSERT INTO ln_xyz (id, g) VALUES (1, GeomFromText('LINESTRINGZ(1 2 3, 4 5 6)', 4326))";
    ret = sqlite3_exec (handle, sql, NULL, NULL, &err_msg);
    if (ret != SQLITE_OK)
      {
	  fprintf (stderr, "Error: %s\n", err_msg);
	  sqlite3_free (err_msg);
	  return -40;
      }

/* Inserting into ln_xym */
    sql =
	"INSERT INTO ln_xym (id, g) VALUES (1, GeomFromText('LINESTRINGM(1 2 10, 4 5 11)', 4326))";
    ret = sqlite3_exec (handle, sql, NULL, NULL, &err_msg);
    if (ret != SQLITE_OK)
      {
	  fprintf (stderr, "Error: %s\n", err_msg);
	  sqlite3_free (err_msg);
	  return -41;
      }

/* Inserting into ln_xyzm */
    sql =
	"INSERT INTO ln_xyzm (id, g) VALUES (2, GeomFromText('LINESTRINGZM(1 2 3 10, 4 5 6 11)', 4326))";
    ret = sqlite3_exec (handle, sql, NULL, NULL, &err_msg);
    if (ret != SQLITE_OK)
      {
	  fprintf (stderr, "Error: %s\n", err_msg);
	  sqlite3_free (err_msg);
	  return -42;
      }

/* Inserting into pg_xy */
    sql =
	"INSERT INTO pg_xy (id, g) VALUES (1, GeomFromText('POLYGON((10 10, 15 10, 15 15, 10 15, 10 10), (11 11, 12 11, 1 12, 11 12, 11 11))', 4326))";
    ret = sqlite3_exec (handle, sql, NULL, NULL, &err_msg);
    if (ret != SQLITE_OK)
      {
	  fprintf (stderr, "Error: %s\n", err_msg);
	  sqlite3_free (err_msg);
	  return -43;
      }

/* Inserting into pg_xyz */
    sql =
	"INSERT INTO pg_xyz (id, g) VALUES (1, GeomFromText('POLYGONZ((10 10 100, 15 10 101, 15 15 102, 10 15 103, 10 10 100), (11 11 100, 12 11 101, 1 12 102, 11 12 103, 11 11 100))', 4326))";
    ret = sqlite3_exec (handle, sql, NULL, NULL, &err_msg);
    if (ret != SQLITE_OK)
      {
	  fprintf (stderr, "Error: %s\n", err_msg);
	  sqlite3_free (err_msg);
	  return -44;
      }

/* Inserting into pg_xym */
    sql =
	"INSERT INTO pg_xym (id, g) VALUES (1, GeomFromText('POLYGONM((10 10 10, 15 10 11, 15 15 12, 10 15 13, 10 10 10), (11 11 10, 12 11 11, 1 12 12, 11 12 13, 11 11 10))', 4326))";
    ret = sqlite3_exec (handle, sql, NULL, NULL, &err_msg);
    if (ret != SQLITE_OK)
      {
	  fprintf (stderr, "Error: %s\n", err_msg);
	  sqlite3_free (err_msg);
	  return -45;
      }

/* Inserting into pg_xyzm */
    sql =
	"INSERT INTO pg_xyzm (id, g) VALUES (1, GeomFromText('POLYGONZM((10 10 100 10, 15 10 101 11, 15 15 102 12, 10 15 103 13, 10 10 100 10), (11 11 100 10, 12 11 101 11, 1 12 102 12, 11 12 103 13, 11 11 100 10))', 4326))";
    ret = sqlite3_exec (handle, sql, NULL, NULL, &err_msg);
    if (ret != SQLITE_OK)
      {
	  fprintf (stderr, "Error: %s\n", err_msg);
	  sqlite3_free (err_msg);
	  return -46;
      }

/* Inserting into mpt_xy */
    sql =
	"INSERT INTO mpt_xy (id, g) VALUES (1, GeomFromText('MULTIPOINT(1 2, 4 5)', 4326))";
    ret = sqlite3_exec (handle, sql, NULL, NULL, &err_msg);
    if (ret != SQLITE_OK)
      {
	  fprintf (stderr, "Error: %s\n", err_msg);
	  sqlite3_free (err_msg);
	  return -47;
      }

/* Inserting into mpt_xyz */
    sql =
	"INSERT INTO mpt_xyz (id, g) VALUES (1, GeomFromText('MULTIPOINTZ(1 2 3, 4 5 6)', 4326))";
    ret = sqlite3_exec (handle, sql, NULL, NULL, &err_msg);
    if (ret != SQLITE_OK)
      {
	  fprintf (stderr, "Error: %s\n", err_msg);
	  sqlite3_free (err_msg);
	  return -48;
      }

/* Inserting into mpt_xym */
    sql =
	"INSERT INTO mpt_xym (id, g) VALUES (1, GeomFromText('MULTIPOINTM(1 2 10, 4 5 11)', 4326))";
    ret = sqlite3_exec (handle, sql, NULL, NULL, &err_msg);
    if (ret != SQLITE_OK)
      {
	  fprintf (stderr, "Error: %s\n", err_msg);
	  sqlite3_free (err_msg);
	  return -49;
      }

/* Inserting into mpt_xyzm */
    sql =
	"INSERT INTO mpt_xyzm (id, g) VALUES (1, GeomFromText('MULTIPOINTZM(1 2 3 10, 4 5 6 10)', 4326))";
    ret = sqlite3_exec (handle, sql, NULL, NULL, &err_msg);
    if (ret != SQLITE_OK)
      {
	  fprintf (stderr, "Error: %s\n", err_msg);
	  sqlite3_free (err_msg);
	  return -50;
      }

/* Inserting into mln_xy */
    sql =
	"INSERT INTO mln_xy (id, g) VALUES (1, GeomFromText('MULTILINESTRING((1 2, 4 5), (7 8, 10 11))', 4326))";
    ret = sqlite3_exec (handle, sql, NULL, NULL, &err_msg);
    if (ret != SQLITE_OK)
      {
	  fprintf (stderr, "Error: %s\n", err_msg);
	  sqlite3_free (err_msg);
	  return -51;
      }

/* Inserting into mln_xyz */
    sql =
	"INSERT INTO mln_xyz (id, g) VALUES (1, GeomFromText('MULTILINESTRINGZ((1 2 3, 4 5 6), (7 8 9, 10 11 12))', 4326))";
    ret = sqlite3_exec (handle, sql, NULL, NULL, &err_msg);
    if (ret != SQLITE_OK)
      {
	  fprintf (stderr, "Error: %s\n", err_msg);
	  sqlite3_free (err_msg);
	  return -52;
      }

/* Inserting into mln_xym */
    sql =
	"INSERT INTO mln_xym (id, g) VALUES (1, GeomFromText('MULTILINESTRINGM((1 2 10, 4 5 11), (7 8 12, 10 11 13))', 4326))";
    ret = sqlite3_exec (handle, sql, NULL, NULL, &err_msg);
    if (ret != SQLITE_OK)
      {
	  fprintf (stderr, "Error: %s\n", err_msg);
	  sqlite3_free (err_msg);
	  return -53;
      }

/* Inserting into mln_xyzm */
    sql =
	"INSERT INTO mln_xyzm (id, g) VALUES (1, GeomFromText('MULTILINESTRINGZM((1 2 3 10, 4 5 6 11), (7 8 9 12, 10 11 12 13))', 4326))";
    ret = sqlite3_exec (handle, sql, NULL, NULL, &err_msg);
    if (ret != SQLITE_OK)
      {
	  fprintf (stderr, "Error: %s\n", err_msg);
	  sqlite3_free (err_msg);
	  return -54;
      }

/* Inserting into mpg_xy */
    sql =
	"INSERT INTO mpg_xy (id, g) VALUES (1, GeomFromText('MULTIPOLYGON(((10 10, 15 10, 15 15, 10 15, 10 10), (11 11, 12 11, 1 12, 11 12, 11 11)), ((0 0, 1 0, 1 1, 0 1, 0 0)))', 4326))";
    ret = sqlite3_exec (handle, sql, NULL, NULL, &err_msg);
    if (ret != SQLITE_OK)
      {
	  fprintf (stderr, "Error: %s\n", err_msg);
	  sqlite3_free (err_msg);
	  return -55;
      }

/* Inserting into mpg_xyz */
    sql =
	"INSERT INTO mpg_xyz (id, g) VALUES (1, GeomFromText('MULTIPOLYGONZ(((10 10 100, 15 10 101, 15 15 102, 10 15 103, 10 10 100), (11 11 100, 12 11 101, 1 12 102, 11 12 103, 11 11 100)), ((0 0 1, 1 0 2, 1 1 3, 0 1 4, 0 0 1)))', 4326))";
    ret = sqlite3_exec (handle, sql, NULL, NULL, &err_msg);
    if (ret != SQLITE_OK)
      {
	  fprintf (stderr, "Error: %s\n", err_msg);
	  sqlite3_free (err_msg);
	  return -56;
      }

/* Inserting into mpg_xym */
    sql =
	"INSERT INTO mpg_xym (id, g) VALUES (1, GeomFromText('MULTIPOLYGONM(((10 10 11, 15 10 12, 15 15 13, 10 15 14, 10 10 11), (11 11 5, 12 11 6, 12 12 7, 11 12 8, 11 11 5)), ((0 0 11, 1 0 12, 1 1 13, 0 1 14, 0 0 11)))', 4326))";
    ret = sqlite3_exec (handle, sql, NULL, NULL, &err_msg);
    if (ret != SQLITE_OK)
      {
	  fprintf (stderr, "Error: %s\n", err_msg);
	  sqlite3_free (err_msg);
	  return -57;
      }

/* Inserting into mpg_xyzm */
    sql =
	"INSERT INTO mpg_xyzm (id, g) VALUES (1, GeomFromText('MULTIPOLYGONZM(((10 10 100 11, 15 10 101 12, 15 15 102 13, 10 15 103 14, 10 10 100 11), (11 11 100 5, 12 11 101 6, 1 12 102 7, 11 12 103 8, 11 11 100 5)), ((0 0 1 11, 1 0 2 12, 1 1 3 13, 0 1 4 14, 0 0 1 11)))', 4326))";
    ret = sqlite3_exec (handle, sql, NULL, NULL, &err_msg);
    if (ret != SQLITE_OK)
      {
	  fprintf (stderr, "Error: %s\n", err_msg);
	  sqlite3_free (err_msg);
	  return -58;
      }

/* Inserting into gcoll_xy */
    sql =
	"INSERT INTO gcoll_xy (id, g) VALUES (1, GeomFromText('GEOMETRYCOLLECTION(POINT(10 10), LINESTRING(5 5, 6 6), POLYGON((0 0, 1 0, 1 1, 0 1, 0 0)))', 4326))";
    ret = sqlite3_exec (handle, sql, NULL, NULL, &err_msg);
    if (ret != SQLITE_OK)
      {
	  fprintf (stderr, "Error: %s\n", err_msg);
	  sqlite3_free (err_msg);
	  return -59;
      }

/* Inserting into gcoll_xyz */
    sql =
	"INSERT INTO gcoll_xyz (id, g) VALUES (1, GeomFromText('GEOMETRYCOLLECTIONZ(POINTZ(10 10 100), LINESTRINGZ(5 5 10, 6 6 11), POLYGONZ((0 0 1, 1 0 2, 1 1 3, 0 1 4, 0 0 1)))', 4326))";
    ret = sqlite3_exec (handle, sql, NULL, NULL, &err_msg);
    if (ret != SQLITE_OK)
      {
	  fprintf (stderr, "Error: %s\n", err_msg);
	  sqlite3_free (err_msg);
	  return -60;
      }

/* Inserting into gcoll_xym */
    sql =
	"INSERT INTO gcoll_xym (id, g) VALUES (1, GeomFromText('GEOMETRYCOLLECTIONM(POINTM(10 10 100), LINESTRINGM(5 5 10, 6 6 11), POLYGONM((0 0 1, 1 0 2, 1 1 3, 0 1 4, 0 0 1)))', 4326))";
    ret = sqlite3_exec (handle, sql, NULL, NULL, &err_msg);
    if (ret != SQLITE_OK)
      {
	  fprintf (stderr, "Error: %s\n", err_msg);
	  sqlite3_free (err_msg);
	  return -61;
      }

/* Inserting into gcoll_xyzm */
    sql =
	"INSERT INTO gcoll_xyzm (id, g) VALUES (1, GeomFromText('GEOMETRYCOLLECTIONZM(POINTZM(10 10 100 11), LINESTRINGZM(5 5 10 11, 6 6 11 12), POLYGONZM((0 0 1 10, 1 0 2 11, 1 1 3 12, 0 1 4 13, 0 0 1 10)))', 4326))";
    ret = sqlite3_exec (handle, sql, NULL, NULL, &err_msg);
    if (ret != SQLITE_OK)
      {
	  fprintf (stderr, "Error: %s\n", err_msg);
	  sqlite3_free (err_msg);
	  return -62;
      }

/* Inserting into geom_xy */
    sql =
	"INSERT INTO geom_xy (id, g) VALUES (1, GeomFromText('GEOMETRYCOLLECTION(POINT(10 10), LINESTRING(5 5, 6 6), POLYGON((0 0, 1 0, 1 1, 0 1, 0 0)))', 4326))";
    ret = sqlite3_exec (handle, sql, NULL, NULL, &err_msg);
    if (ret != SQLITE_OK)
      {
	  fprintf (stderr, "Error: %s\n", err_msg);
	  sqlite3_free (err_msg);
	  return -63;
      }
    sql =
	"INSERT INTO geom_xy (id, g) VALUES (2, GeomFromText('POINT(10 10)', 4326))";
    ret = sqlite3_exec (handle, sql, NULL, NULL, &err_msg);
    if (ret != SQLITE_OK)
      {
	  fprintf (stderr, "Error: %s\n", err_msg);
	  sqlite3_free (err_msg);
	  return -64;
      }

/* Inserting into geom_xyz */
    sql =
	"INSERT INTO geom_xyz (id, g) VALUES (1, GeomFromText('GEOMETRYCOLLECTIONZ(POINTZ(10 10 100), LINESTRINGZ(5 5 10, 6 6 11), POLYGONZ((0 0 1, 1 0 2, 1 1 3, 0 1 4, 0 0 1)))', 4326))";
    ret = sqlite3_exec (handle, sql, NULL, NULL, &err_msg);
    if (ret != SQLITE_OK)
      {
	  fprintf (stderr, "Error: %s\n", err_msg);
	  sqlite3_free (err_msg);
	  return -65;
      }
    sql =
	"INSERT INTO geom_xyz (id, g) VALUES (2, GeomFromText('POINTZ(10 10 100)', 4326))";
    ret = sqlite3_exec (handle, sql, NULL, NULL, &err_msg);
    if (ret != SQLITE_OK)
      {
	  fprintf (stderr, "Error: %s\n", err_msg);
	  sqlite3_free (err_msg);
	  return -66;
      }

/* Inserting into geom_xym */
    sql =
	"INSERT INTO geom_xym (id, g) VALUES (1, GeomFromText('GEOMETRYCOLLECTIONM(POINTM(10 10 100), LINESTRINGM(5 5 10, 6 6 11), POLYGONM((0 0 1, 1 0 2, 1 1 3, 0 1 4, 0 0 1)))', 4326))";
    ret = sqlite3_exec (handle, sql, NULL, NULL, &err_msg);
    if (ret != SQLITE_OK)
      {
	  fprintf (stderr, "Error: %s\n", err_msg);
	  sqlite3_free (err_msg);
	  return -67;
      }
    sql =
	"INSERT INTO geom_xym (id, g) VALUES (2, GeomFromText('POINTM(10 10 100)', 4326))";
    ret = sqlite3_exec (handle, sql, NULL, NULL, &err_msg);
    if (ret != SQLITE_OK)
      {
	  fprintf (stderr, "Error: %s\n", err_msg);
	  sqlite3_free (err_msg);
	  return -68;
      }

/* Inserting into geom_xyzm */
    sql =
	"INSERT INTO geom_xyzm (id, g) VALUES (1, GeomFromText('GEOMETRYCOLLECTIONZM(POINTZM(10 10 100 11), LINESTRINGZM(5 5 10 11, 6 6 11 12), POLYGONZM((0 0 1 10, 1 0 2 11, 1 1 3 12, 0 1 4 13, 0 0 1 10)))', 4326))";
    ret = sqlite3_exec (handle, sql, NULL, NULL, &err_msg);
    if (ret != SQLITE_OK)
      {
	  fprintf (stderr, "Error: %s\n", err_msg);
	  sqlite3_free (err_msg);
	  return -69;
      }
    sql =
	"INSERT INTO geom_xyzm (id, g) VALUES (2, GeomFromText('POINTZM(10 10 100 11)', 4326))";
    ret = sqlite3_exec (handle, sql, NULL, NULL, &err_msg);
    if (ret != SQLITE_OK)
      {
	  fprintf (stderr, "Error: %s\n", err_msg);
	  sqlite3_free (err_msg);
	  return -70;
      }

/* recovering pt_xy */
    sql = "SELECT RecoverGeometryColumn('pt_xy', 'g', 4326, 'POINT', 2);";
    ret = sqlite3_get_table (handle, sql, &results, &rows, &columns, &err_msg);
    if (ret != SQLITE_OK)
      {
	  fprintf (stderr, "Error: %s\n", err_msg);
	  sqlite3_free (err_msg);
	  return -71;
      }
    if ((rows != 1) || (columns != 1))
      {
	  fprintf (stderr, "Unexpected error: bad result: %i/%i.\n", rows,
		   columns);
	  return -72;
      }
    if (results[1] == NULL)
      {
	  fprintf (stderr, "Unexpected error: NULL result\n");
	  return -73;
      }
    if (strcmp (results[1], "1") != 0)
      {
	  fprintf (stderr, "Unexpected error: invalid result\n");
	  return -74;
      }
    sqlite3_free_table (results);

/* recovering pt_xyz */
    sql = "SELECT RecoverGeometryColumn('pt_xyz', 'g', 4326, 'POINT', 3);";
    ret = sqlite3_get_table (handle, sql, &results, &rows, &columns, &err_msg);
    if (ret != SQLITE_OK)
      {
	  fprintf (stderr, "Error: %s\n", err_msg);
	  sqlite3_free (err_msg);
	  return -75;
      }
    if ((rows != 1) || (columns != 1))
      {
	  fprintf (stderr, "Unexpected error: bad result: %i/%i.\n", rows,
		   columns);
	  return -76;
      }
    if (results[1] == NULL)
      {
	  fprintf (stderr, "Unexpected error: NULL result\n");
	  return -77;
      }
    if (strcmp (results[1], "1") != 0)
      {
	  fprintf (stderr, "Unexpected error: invalid result\n");
	  return -78;
      }
    sqlite3_free_table (results);

/* recovering pt_xym */
    sql = "SELECT RecoverGeometryColumn('pt_xym', 'g', 4326, 'POINT', 'XYM');";
    ret = sqlite3_get_table (handle, sql, &results, &rows, &columns, &err_msg);
    if (ret != SQLITE_OK)
      {
	  fprintf (stderr, "Error: %s\n", err_msg);
	  sqlite3_free (err_msg);
	  return -79;
      }
    if ((rows != 1) || (columns != 1))
      {
	  fprintf (stderr, "Unexpected error: bad result: %i/%i.\n", rows,
		   columns);
	  return -80;
      }
    if (results[1] == NULL)
      {
	  fprintf (stderr, "Unexpected error: NULL result\n");
	  return -81;
      }
    if (strcmp (results[1], "1") != 0)
      {
	  fprintf (stderr, "Unexpected error: invalid result\n");
	  return -82;
      }
    sqlite3_free_table (results);

/* recovering pt_xyzm */
    sql =
	"SELECT RecoverGeometryColumn('pt_xyzm', 'g', 4326, 'POINT', 'XYZM');";
    ret = sqlite3_get_table (handle, sql, &results, &rows, &columns, &err_msg);
    if (ret != SQLITE_OK)
      {
	  fprintf (stderr, "Error: %s\n", err_msg);
	  sqlite3_free (err_msg);
	  return -83;
      }
    if ((rows != 1) || (columns != 1))
      {
	  fprintf (stderr, "Unexpected error: bad result: %i/%i.\n", rows,
		   columns);
	  return -84;
      }
    if (results[1] == NULL)
      {
	  fprintf (stderr, "Unexpected error: NULL result\n");
	  return -85;
      }
    if (strcmp (results[1], "1") != 0)
      {
	  fprintf (stderr, "Unexpected error: invalid result\n");
	  return -86;
      }
    sqlite3_free_table (results);

/* recovering ln_xy */
    sql =
	"SELECT RecoverGeometryColumn('ln_xy', 'g', 4326, 'LINESTRING', 'XY');";
    ret = sqlite3_get_table (handle, sql, &results, &rows, &columns, &err_msg);
    if (ret != SQLITE_OK)
      {
	  fprintf (stderr, "Error: %s\n", err_msg);
	  sqlite3_free (err_msg);
	  return -87;
      }
    if ((rows != 1) || (columns != 1))
      {
	  fprintf (stderr, "Unexpected error: bad result: %i/%i.\n", rows,
		   columns);
	  return -88;
      }
    if (results[1] == NULL)
      {
	  fprintf (stderr, "Unexpected error: NULL result\n");
	  return -89;
      }
    if (strcmp (results[1], "1") != 0)
      {
	  fprintf (stderr, "Unexpected error: invalid result\n");
	  return -90;
      }
    sqlite3_free_table (results);

/* recovering ln_xyz */
    sql =
	"SELECT RecoverGeometryColumn('ln_xyz', 'g', 4326, 'LINESTRING', 'XYZ');";
    ret = sqlite3_get_table (handle, sql, &results, &rows, &columns, &err_msg);
    if (ret != SQLITE_OK)
      {
	  fprintf (stderr, "Error: %s\n", err_msg);
	  sqlite3_free (err_msg);
	  return -91;
      }
    if ((rows != 1) || (columns != 1))
      {
	  fprintf (stderr, "Unexpected error: bad result: %i/%i.\n", rows,
		   columns);
	  return -92;
      }
    if (results[1] == NULL)
      {
	  fprintf (stderr, "Unexpected error: NULL result\n");
	  return -93;
      }
    if (strcmp (results[1], "1") != 0)
      {
	  fprintf (stderr, "Unexpected error: invalid result\n");
	  return -94;
      }
    sqlite3_free_table (results);

/* recovering ln_xym */
    sql =
	"SELECT RecoverGeometryColumn('ln_xym', 'g', 4326, 'LINESTRING', 'XYM');";
    ret = sqlite3_get_table (handle, sql, &results, &rows, &columns, &err_msg);
    if (ret != SQLITE_OK)
      {
	  fprintf (stderr, "Error: %s\n", err_msg);
	  sqlite3_free (err_msg);
	  return -95;
      }
    if ((rows != 1) || (columns != 1))
      {
	  fprintf (stderr, "Unexpected error: bad result: %i/%i.\n", rows,
		   columns);
	  return -96;
      }
    if (results[1] == NULL)
      {
	  fprintf (stderr, "Unexpected error: NULL result\n");
	  return -97;
      }
    if (strcmp (results[1], "1") != 0)
      {
	  fprintf (stderr, "Unexpected error: invalid result\n");
	  return -98;
      }
    sqlite3_free_table (results);

/* recovering ln_xyzm */
    sql =
	"SELECT RecoverGeometryColumn('ln_xyzm', 'g', 4326, 'LINESTRING', 'XYZM');";
    ret = sqlite3_get_table (handle, sql, &results, &rows, &columns, &err_msg);
    if (ret != SQLITE_OK)
      {
	  fprintf (stderr, "Error: %s\n", err_msg);
	  sqlite3_free (err_msg);
	  return -99;
      }
    if ((rows != 1) || (columns != 1))
      {
	  fprintf (stderr, "Unexpected error: bad result: %i/%i.\n", rows,
		   columns);
	  return -100;
      }
    if (results[1] == NULL)
      {
	  fprintf (stderr, "Unexpected error: NULL result\n");
	  return -101;
      }
    if (strcmp (results[1], "1") != 0)
      {
	  fprintf (stderr, "Unexpected error: invalid result\n");
	  return -102;
      }
    sqlite3_free_table (results);

/* recovering pg_xy */
    sql = "SELECT RecoverGeometryColumn('pg_xy', 'g', 4326, 'POLYGON', 'XY');";
    ret = sqlite3_get_table (handle, sql, &results, &rows, &columns, &err_msg);
    if (ret != SQLITE_OK)
      {
	  fprintf (stderr, "Error: %s\n", err_msg);
	  sqlite3_free (err_msg);
	  return -103;
      }
    if ((rows != 1) || (columns != 1))
      {
	  fprintf (stderr, "Unexpected error: bad result: %i/%i.\n", rows,
		   columns);
	  return -104;
      }
    if (results[1] == NULL)
      {
	  fprintf (stderr, "Unexpected error: NULL result\n");
	  return -105;
      }
    if (strcmp (results[1], "1") != 0)
      {
	  fprintf (stderr, "Unexpected error: invalid result\n");
	  return -106;
      }
    sqlite3_free_table (results);

/* recovering pg_xyz */
    sql =
	"SELECT RecoverGeometryColumn('pg_xyz', 'g', 4326, 'POLYGON', 'XYZ');";
    ret = sqlite3_get_table (handle, sql, &results, &rows, &columns, &err_msg);
    if (ret != SQLITE_OK)
      {
	  fprintf (stderr, "Error: %s\n", err_msg);
	  sqlite3_free (err_msg);
	  return -107;
      }
    if ((rows != 1) || (columns != 1))
      {
	  fprintf (stderr, "Unexpected error: bad result: %i/%i.\n", rows,
		   columns);
	  return -108;
      }
    if (results[1] == NULL)
      {
	  fprintf (stderr, "Unexpected error: NULL result\n");
	  return -109;
      }
    if (strcmp (results[1], "1") != 0)
      {
	  fprintf (stderr, "Unexpected error: invalid result\n");
	  return -110;
      }
    sqlite3_free_table (results);

/* recovering pg_xym */
    sql =
	"SELECT RecoverGeometryColumn('pg_xym', 'g', 4326, 'POLYGON', 'XYM');";
    ret = sqlite3_get_table (handle, sql, &results, &rows, &columns, &err_msg);
    if (ret != SQLITE_OK)
      {
	  fprintf (stderr, "Error: %s\n", err_msg);
	  sqlite3_free (err_msg);
	  return -111;
      }
    if ((rows != 1) || (columns != 1))
      {
	  fprintf (stderr, "Unexpected error: bad result: %i/%i.\n", rows,
		   columns);
	  return -112;
      }
    if (results[1] == NULL)
      {
	  fprintf (stderr, "Unexpected error: NULL result\n");
	  return -113;
      }
    if (strcmp (results[1], "1") != 0)
      {
	  fprintf (stderr, "Unexpected error: invalid result\n");
	  return -114;
      }
    sqlite3_free_table (results);

/* recovering pg_xyzm */
    sql =
	"SELECT RecoverGeometryColumn('pg_xyzm', 'g', 4326, 'POLYGON', 'XYZM');";
    ret = sqlite3_get_table (handle, sql, &results, &rows, &columns, &err_msg);
    if (ret != SQLITE_OK)
      {
	  fprintf (stderr, "Error: %s\n", err_msg);
	  sqlite3_free (err_msg);
	  return -115;
      }
    if ((rows != 1) || (columns != 1))
      {
	  fprintf (stderr, "Unexpected error: bad result: %i/%i.\n", rows,
		   columns);
	  return -116;
      }
    if (results[1] == NULL)
      {
	  fprintf (stderr, "Unexpected error: NULL result\n");
	  return -117;
      }
    if (strcmp (results[1], "1") != 0)
      {
	  fprintf (stderr, "Unexpected error: invalid result\n");
	  return -118;
      }
    sqlite3_free_table (results);

/* recovering mpt_xy */
    sql =
	"SELECT RecoverGeometryColumn('mpt_xy', 'g', 4326, 'MULTIPOINT', 'XY');";
    ret = sqlite3_get_table (handle, sql, &results, &rows, &columns, &err_msg);
    if (ret != SQLITE_OK)
      {
	  fprintf (stderr, "Error: %s\n", err_msg);
	  sqlite3_free (err_msg);
	  return -119;
      }
    if ((rows != 1) || (columns != 1))
      {
	  fprintf (stderr, "Unexpected error: bad result: %i/%i.\n", rows,
		   columns);
	  return -120;
      }
    if (results[1] == NULL)
      {
	  fprintf (stderr, "Unexpected error: NULL result\n");
	  return -121;
      }
    if (strcmp (results[1], "1") != 0)
      {
	  fprintf (stderr, "Unexpected error: invalid result\n");
	  return -122;
      }
    sqlite3_free_table (results);

/* recovering mpt_xyz */
    sql =
	"SELECT RecoverGeometryColumn('mpt_xyz', 'g', 4326, 'MULTIPOINT', 'XYZ');";
    ret = sqlite3_get_table (handle, sql, &results, &rows, &columns, &err_msg);
    if (ret != SQLITE_OK)
      {
	  fprintf (stderr, "Error: %s\n", err_msg);
	  sqlite3_free (err_msg);
	  return -123;
      }
    if ((rows != 1) || (columns != 1))
      {
	  fprintf (stderr, "Unexpected error: bad result: %i/%i.\n", rows,
		   columns);
	  return -124;
      }
    if (results[1] == NULL)
      {
	  fprintf (stderr, "Unexpected error: NULL result\n");
	  return -125;
      }
    if (strcmp (results[1], "1") != 0)
      {
	  fprintf (stderr, "Unexpected error: invalid result\n");
	  return -126;
      }
    sqlite3_free_table (results);

/* recovering mpt_xym */
    sql =
	"SELECT RecoverGeometryColumn('mpt_xym', 'g', 4326, 'MULTIPOINT', 'XYM');";
    ret = sqlite3_get_table (handle, sql, &results, &rows, &columns, &err_msg);
    if (ret != SQLITE_OK)
      {
	  fprintf (stderr, "Error: %s\n", err_msg);
	  sqlite3_free (err_msg);
	  return -127;
      }
    if ((rows != 1) || (columns != 1))
      {
	  fprintf (stderr, "Unexpected error: bad result: %i/%i.\n", rows,
		   columns);
	  return -128;
      }
    if (results[1] == NULL)
      {
	  fprintf (stderr, "Unexpected error: NULL result\n");
	  return -129;
      }
    if (strcmp (results[1], "1") != 0)
      {
	  fprintf (stderr, "Unexpected error: invalid result\n");
	  return -130;
      }
    sqlite3_free_table (results);

/* recovering mpt_xyzm */
    sql =
	"SELECT RecoverGeometryColumn('mpt_xyzm', 'g', 4326, 'MULTIPOINT', 'XYZM');";
    ret = sqlite3_get_table (handle, sql, &results, &rows, &columns, &err_msg);
    if (ret != SQLITE_OK)
      {
	  fprintf (stderr, "Error: %s\n", err_msg);
	  sqlite3_free (err_msg);
	  return -131;
      }
    if ((rows != 1) || (columns != 1))
      {
	  fprintf (stderr, "Unexpected error: bad result: %i/%i.\n", rows,
		   columns);
	  return -132;
      }
    if (results[1] == NULL)
      {
	  fprintf (stderr, "Unexpected error: NULL result\n");
	  return -133;
      }
    if (strcmp (results[1], "1") != 0)
      {
	  fprintf (stderr, "Unexpected error: invalid result\n");
	  return -134;
      }
    sqlite3_free_table (results);

/* recovering mln_xy */
    sql =
	"SELECT RecoverGeometryColumn('mln_xy', 'g', 4326, 'MULTILINESTRING', 'XY');";
    ret = sqlite3_get_table (handle, sql, &results, &rows, &columns, &err_msg);
    if (ret != SQLITE_OK)
      {
	  fprintf (stderr, "Error: %s\n", err_msg);
	  sqlite3_free (err_msg);
	  return -135;
      }
    if ((rows != 1) || (columns != 1))
      {
	  fprintf (stderr, "Unexpected error: bad result: %i/%i.\n", rows,
		   columns);
	  return -136;
      }
    if (results[1] == NULL)
      {
	  fprintf (stderr, "Unexpected error: NULL result\n");
	  return -137;
      }
    if (strcmp (results[1], "1") != 0)
      {
	  fprintf (stderr, "Unexpected error: invalid result\n");
	  return -138;
      }
    sqlite3_free_table (results);

/* recovering mln_xyz */
    sql =
	"SELECT RecoverGeometryColumn('mln_xyz', 'g', 4326, 'MULTILINESTRING', 'XYZ');";
    ret = sqlite3_get_table (handle, sql, &results, &rows, &columns, &err_msg);
    if (ret != SQLITE_OK)
      {
	  fprintf (stderr, "Error: %s\n", err_msg);
	  sqlite3_free (err_msg);
	  return -139;
      }
    if ((rows != 1) || (columns != 1))
      {
	  fprintf (stderr, "Unexpected error: bad result: %i/%i.\n", rows,
		   columns);
	  return -140;
      }
    if (results[1] == NULL)
      {
	  fprintf (stderr, "Unexpected error: NULL result\n");
	  return -141;
      }
    if (strcmp (results[1], "1") != 0)
      {
	  fprintf (stderr, "Unexpected error: invalid result\n");
	  return -142;
      }
    sqlite3_free_table (results);

/* recovering mln_xym */
    sql =
	"SELECT RecoverGeometryColumn('mln_xym', 'g', 4326, 'MULTILINESTRING', 'XYM');";
    ret = sqlite3_get_table (handle, sql, &results, &rows, &columns, &err_msg);
    if (ret != SQLITE_OK)
      {
	  fprintf (stderr, "Error: %s\n", err_msg);
	  sqlite3_free (err_msg);
	  return -143;
      }
    if ((rows != 1) || (columns != 1))
      {
	  fprintf (stderr, "Unexpected error: bad result: %i/%i.\n", rows,
		   columns);
	  return -144;
      }
    if (results[1] == NULL)
      {
	  fprintf (stderr, "Unexpected error: NULL result\n");
	  return -145;
      }
    if (strcmp (results[1], "1") != 0)
      {
	  fprintf (stderr, "Unexpected error: invalid result\n");
	  return -146;
      }
    sqlite3_free_table (results);

/* recovering mln_xyzm */
    sql =
	"SELECT RecoverGeometryColumn('mln_xyzm', 'g', 4326, 'MULTILINESTRING', 'XYZM');";
    ret = sqlite3_get_table (handle, sql, &results, &rows, &columns, &err_msg);
    if (ret != SQLITE_OK)
      {
	  fprintf (stderr, "Error: %s\n", err_msg);
	  sqlite3_free (err_msg);
	  return -147;
      }
    if ((rows != 1) || (columns != 1))
      {
	  fprintf (stderr, "Unexpected error: bad result: %i/%i.\n", rows,
		   columns);
	  return -148;
      }
    if (results[1] == NULL)
      {
	  fprintf (stderr, "Unexpected error: NULL result\n");
	  return -149;
      }
    if (strcmp (results[1], "1") != 0)
      {
	  fprintf (stderr, "Unexpected error: invalid result\n");
	  return -150;
      }
    sqlite3_free_table (results);

/* recovering mpg_xy */
    sql =
	"SELECT RecoverGeometryColumn('mpg_xy', 'g', 4326, 'MULTIPOLYGON', 'XY');";
    ret = sqlite3_get_table (handle, sql, &results, &rows, &columns, &err_msg);
    if (ret != SQLITE_OK)
      {
	  fprintf (stderr, "Error: %s\n", err_msg);
	  sqlite3_free (err_msg);
	  return -151;
      }
    if ((rows != 1) || (columns != 1))
      {
	  fprintf (stderr, "Unexpected error: bad result: %i/%i.\n", rows,
		   columns);
	  return -152;
      }
    if (results[1] == NULL)
      {
	  fprintf (stderr, "Unexpected error: NULL result\n");
	  return -153;
      }
    if (strcmp (results[1], "1") != 0)
      {
	  fprintf (stderr, "Unexpected error: invalid result\n");
	  return -154;
      }
    sqlite3_free_table (results);

/* recovering mpg_xyz */
    sql =
	"SELECT RecoverGeometryColumn('mpg_xyz', 'g', 4326, 'MULTIPOLYGON', 'XYZ');";
    ret = sqlite3_get_table (handle, sql, &results, &rows, &columns, &err_msg);
    if (ret != SQLITE_OK)
      {
	  fprintf (stderr, "Error: %s\n", err_msg);
	  sqlite3_free (err_msg);
	  return -155;
      }
    if ((rows != 1) || (columns != 1))
      {
	  fprintf (stderr, "Unexpected error: bad result: %i/%i.\n", rows,
		   columns);
	  return -156;
      }
    if (results[1] == NULL)
      {
	  fprintf (stderr, "Unexpected error: NULL result\n");
	  return -157;
      }
    if (strcmp (results[1], "1") != 0)
      {
	  fprintf (stderr, "Unexpected error: invalid result\n");
	  return -158;
      }
    sqlite3_free_table (results);

/* recovering mpg_xym */
    sql =
	"SELECT RecoverGeometryColumn('mpg_xym', 'g', 4326, 'MULTIPOLYGON', 'XYM');";
    ret = sqlite3_get_table (handle, sql, &results, &rows, &columns, &err_msg);
    if (ret != SQLITE_OK)
      {
	  fprintf (stderr, "Error: %s\n", err_msg);
	  sqlite3_free (err_msg);
	  return -159;
      }
    if ((rows != 1) || (columns != 1))
      {
	  fprintf (stderr, "Unexpected error: bad result: %i/%i.\n", rows,
		   columns);
	  return -160;
      }
    if (results[1] == NULL)
      {
	  fprintf (stderr, "Unexpected error: NULL result\n");
	  return -161;
      }
    if (strcmp (results[1], "1") != 0)
      {
	  fprintf (stderr, "Unexpected error: invalid result\n");
	  return -162;
      }
    sqlite3_free_table (results);

/* recovering mpg_xyzm */
    sql =
	"SELECT RecoverGeometryColumn('mpg_xyzm', 'g', 4326, 'MULTIPOLYGON', 'XYZM');";
    ret = sqlite3_get_table (handle, sql, &results, &rows, &columns, &err_msg);
    if (ret != SQLITE_OK)
      {
	  fprintf (stderr, "Error: %s\n", err_msg);
	  sqlite3_free (err_msg);
	  return -163;
      }
    if ((rows != 1) || (columns != 1))
      {
	  fprintf (stderr, "Unexpected error: bad result: %i/%i.\n", rows,
		   columns);
	  return -164;
      }
    if (results[1] == NULL)
      {
	  fprintf (stderr, "Unexpected error: NULL result\n");
	  return -165;
      }
    if (strcmp (results[1], "1") != 0)
      {
	  fprintf (stderr, "Unexpected error: invalid result\n");
	  return -166;
      }
    sqlite3_free_table (results);

/* recovering gcoll_xy */
    sql =
	"SELECT RecoverGeometryColumn('gcoll_xy', 'g', 4326, 'GEOMETRYCOLLECTION', 'XY');";
    ret = sqlite3_get_table (handle, sql, &results, &rows, &columns, &err_msg);
    if (ret != SQLITE_OK)
      {
	  fprintf (stderr, "Error: %s\n", err_msg);
	  sqlite3_free (err_msg);
	  return -167;
      }
    if ((rows != 1) || (columns != 1))
      {
	  fprintf (stderr, "Unexpected error: bad result: %i/%i.\n", rows,
		   columns);
	  return -168;
      }
    if (results[1] == NULL)
      {
	  fprintf (stderr, "Unexpected error: NULL result\n");
	  return -169;
      }
    if (strcmp (results[1], "1") != 0)
      {
	  fprintf (stderr, "Unexpected error: invalid result\n");
	  return -170;
      }
    sqlite3_free_table (results);

/* recovering gcoll_xyz */
    sql =
	"SELECT RecoverGeometryColumn('gcoll_xyz', 'g', 4326, 'GEOMETRYCOLLECTION', 'XYZ');";
    ret = sqlite3_get_table (handle, sql, &results, &rows, &columns, &err_msg);
    if (ret != SQLITE_OK)
      {
	  fprintf (stderr, "Error: %s\n", err_msg);
	  sqlite3_free (err_msg);
	  return -171;
      }
    if ((rows != 1) || (columns != 1))
      {
	  fprintf (stderr, "Unexpected error: bad result: %i/%i.\n", rows,
		   columns);
	  return -172;
      }
    if (results[1] == NULL)
      {
	  fprintf (stderr, "Unexpected error: NULL result\n");
	  return -173;
      }
    if (strcmp (results[1], "1") != 0)
      {
	  fprintf (stderr, "Unexpected error: invalid result\n");
	  return -174;
      }
    sqlite3_free_table (results);

/* recovering gcoll_xym */
    sql =
	"SELECT RecoverGeometryColumn('gcoll_xym', 'g', 4326, 'GEOMETRYCOLLECTION', 'XYM');";
    ret = sqlite3_get_table (handle, sql, &results, &rows, &columns, &err_msg);
    if (ret != SQLITE_OK)
      {
	  fprintf (stderr, "Error: %s\n", err_msg);
	  sqlite3_free (err_msg);
	  return -175;
      }
    if ((rows != 1) || (columns != 1))
      {
	  fprintf (stderr, "Unexpected error: bad result: %i/%i.\n", rows,
		   columns);
	  return -176;
      }
    if (results[1] == NULL)
      {
	  fprintf (stderr, "Unexpected error: NULL result\n");
	  return -177;
      }
    if (strcmp (results[1], "1") != 0)
      {
	  fprintf (stderr, "Unexpected error: invalid result\n");
	  return -178;
      }
    sqlite3_free_table (results);

/* recovering gcoll_xyzm */
    sql =
	"SELECT RecoverGeometryColumn('gcoll_xyzm', 'g', 4326, 'GEOMETRYCOLLECTION', 'XYZM');";
    ret = sqlite3_get_table (handle, sql, &results, &rows, &columns, &err_msg);
    if (ret != SQLITE_OK)
      {
	  fprintf (stderr, "Error: %s\n", err_msg);
	  sqlite3_free (err_msg);
	  return -179;
      }
    if ((rows != 1) || (columns != 1))
      {
	  fprintf (stderr, "Unexpected error: bad result: %i/%i.\n", rows,
		   columns);
	  return -180;
      }
    if (results[1] == NULL)
      {
	  fprintf (stderr, "Unexpected error: NULL result\n");
	  return -181;
      }
    if (strcmp (results[1], "1") != 0)
      {
	  fprintf (stderr, "Unexpected error: invalid result\n");
	  return -182;
      }
    sqlite3_free_table (results);

/* recovering geom_xy */
    sql =
	"SELECT RecoverGeometryColumn('geom_xy', 'g', 4326, 'GEOMETRY', 'XY');";
    ret = sqlite3_get_table (handle, sql, &results, &rows, &columns, &err_msg);
    if (ret != SQLITE_OK)
      {
	  fprintf (stderr, "Error: %s\n", err_msg);
	  sqlite3_free (err_msg);
	  return -183;
      }
    if ((rows != 1) || (columns != 1))
      {
	  fprintf (stderr, "Unexpected error: bad result: %i/%i.\n", rows,
		   columns);
	  return -184;
      }
    if (results[1] == NULL)
      {
	  fprintf (stderr, "Unexpected error: NULL result\n");
	  return -185;
      }
    if (strcmp (results[1], "1") != 0)
      {
	  fprintf (stderr, "Unexpected error: invalid result\n");
	  return -186;
      }
    sqlite3_free_table (results);

/* recovering geom_xyz */
    sql =
	"SELECT RecoverGeometryColumn('geom_xyz', 'g', 4326, 'GEOMETRY', 'XYZ');";
    ret = sqlite3_get_table (handle, sql, &results, &rows, &columns, &err_msg);
    if (ret != SQLITE_OK)
      {
	  fprintf (stderr, "Error: %s\n", err_msg);
	  sqlite3_free (err_msg);
	  return -187;
      }
    if ((rows != 1) || (columns != 1))
      {
	  fprintf (stderr, "Unexpected error: bad result: %i/%i.\n", rows,
		   columns);
	  return -188;
      }
    if (results[1] == NULL)
      {
	  fprintf (stderr, "Unexpected error: NULL result\n");
	  return -189;
      }
    if (strcmp (results[1], "1") != 0)
      {
	  fprintf (stderr, "Unexpected error: invalid result\n");
	  return -190;
      }
    sqlite3_free_table (results);

/* recovering geom_xym */
    sql =
	"SELECT RecoverGeometryColumn('geom_xym', 'g', 4326, 'GEOMETRY', 'XYM');";
    ret = sqlite3_get_table (handle, sql, &results, &rows, &columns, &err_msg);
    if (ret != SQLITE_OK)
      {
	  fprintf (stderr, "Error: %s\n", err_msg);
	  sqlite3_free (err_msg);
	  return -191;
      }
    if ((rows != 1) || (columns != 1))
      {
	  fprintf (stderr, "Unexpected error: bad result: %i/%i.\n", rows,
		   columns);
	  return -192;
      }
    if (results[1] == NULL)
      {
	  fprintf (stderr, "Unexpected error: NULL result\n");
	  return -193;
      }
    if (strcmp (results[1], "1") != 0)
      {
	  fprintf (stderr, "Unexpected error: invalid result\n");
	  return -194;
      }
    sqlite3_free_table (results);

/* recovering geom_xyzm */
    sql =
	"SELECT RecoverGeometryColumn('geom_xyzm', 'g', 4326, 'GEOMETRY', 'XYZM');";
    ret = sqlite3_get_table (handle, sql, &results, &rows, &columns, &err_msg);
    if (ret != SQLITE_OK)
      {
	  fprintf (stderr, "Error: %s\n", err_msg);
	  sqlite3_free (err_msg);
	  return -195;
      }
    if ((rows != 1) || (columns != 1))
      {
	  fprintf (stderr, "Unexpected error: bad result: %i/%i.\n", rows,
		   columns);
	  return -196;
      }
    if (results[1] == NULL)
      {
	  fprintf (stderr, "Unexpected error: NULL result\n");
	  return -197;
      }
    if (strcmp (results[1], "1") != 0)
      {
	  fprintf (stderr, "Unexpected error: invalid result\n");
	  return -198;
      }
    sqlite3_free_table (results);

    ret = sqlite3_close (handle);
    if (ret != SQLITE_OK)
      {
	  fprintf (stderr, "sqlite3_close() error: %s\n",
		   sqlite3_errmsg (handle));
	  return -199;
      }

    spatialite_cleanup_ex (cache);

    return 0;
}