Example #1
0
/* insert values into the table (cat, val | dval) */
void insert_value(int cat, int val, double dval)
{
    char buf[1000];

    sprintf(buf, "insert into %s values (%d", Fi->table, cat);
    db_set_string(&sql, buf);

    if (data_type == CELL_TYPE)
	sprintf(buf, ", %d", val);
    else
	sprintf(buf, ", %f", dval);

    db_append_string(&sql, buf);

    if (has_cats) {
	char *lab;

	lab = Rast_get_c_cat(&val, &RastCats);	/*cats are loaded only for CELL type */

	db_set_string(&label, lab);
	db_double_quote_string(&label);
	sprintf(buf, ", '%s'", db_get_string(&label));
	db_append_string(&sql, buf);
    }

    db_append_string(&sql, ")");

    G_debug(3, db_get_string(&sql));

    if (db_execute_immediate(driver, &sql) != DB_OK)
	G_fatal_error(_("Cannot insert new row: %s"), db_get_string(&sql));

}
Example #2
0
int db__driver_describe_table(dbString * table_name, dbTable ** table)
{
    dbString sql;
    PGresult *res;

    db_init_string(&sql);

    db_set_string(&sql, "select * from ");
    db_append_string(&sql, db_get_string(table_name));
    db_append_string(&sql, " where 1 = 0");

    res = PQexec(pg_conn, db_get_string(&sql));

    if (!res || PQresultStatus(res) != PGRES_TUPLES_OK) {
	append_error(db_get_string(&sql));
	append_error("\n");
	append_error(PQerrorMessage(pg_conn));
	report_error();
	PQclear(res);
	return DB_FAILED;
    }

    if (describe_table(res, table, NULL) == DB_FAILED) {
	append_error("Cannot describe table\n");
	report_error();
	PQclear(res);
	return DB_FAILED;
    }

    PQclear(res);

    return DB_OK;
}
Example #3
0
/*!
  \brief Delete table

  \param drvname driver name
  \param dbname database name
  \param tblname table name

  \return DB_OK on success
  \return DB_FAILED on failure
 */
int db_delete_table(const char *drvname, const char *dbname, const char *tblname)
{
    dbDriver *driver;
    dbString sql;

    G_debug(3, "db_delete_table(): driver = %s, db = %s, table = %s\n",
	    drvname, dbname, tblname);

    /* Open driver and database */
    driver = db_start_driver_open_database(drvname, dbname);
    if (driver == NULL) {
	G_warning(_("Unable open database <%s> by driver <%s>"), dbname,
		  drvname);
	return DB_FAILED;
    }

    /* Delete table */
    /* TODO test if the tables exist */
    db_init_string(&sql);
    db_set_string(&sql, "drop table ");
    db_append_string(&sql, tblname);
    G_debug(3, "%s", db_get_string(&sql));

    if (db_execute_immediate(driver, &sql) != DB_OK) {
	G_warning(_("Unable to drop table: '%s'"),
		  db_get_string(&sql));
	db_close_database_shutdown_driver(driver);
	return DB_FAILED;
    }

    db_close_database_shutdown_driver(driver);

    return DB_OK;
}
Example #4
0
int db__driver_open_select_cursor(dbString * sel, dbCursor * dbc, int mode)
{
    cursor *c;
    dbTable *table;
    char *str;

    /* allocate cursor */
    c = alloc_cursor();
    if (c == NULL)
	return DB_FAILED;

    db_set_cursor_mode(dbc, mode);
    db_set_cursor_type_readonly(dbc);

    /* \ must be escaped, see explanation in 
     * db_driver_execute_immediate() */
    str = G_str_replace(db_get_string(sel), "\\", "\\\\");
    G_debug(3, "Escaped SQL: %s", str);

    if (mysql_query(connection, str) != 0) {
	db_d_append_error("%s\n%s\n%s",
			  _("Unable to select data:"),
			  db_get_string(sel),
			  mysql_error(connection));
	if (str)
	    G_free(str);
	db_d_report_error();
	return DB_FAILED;
    }

    if (str)
	G_free(str);
    c->res = mysql_store_result(connection);

    if (c->res == NULL) {
	db_d_append_error("%s\n%s",
			  db_get_string(sel),
			  mysql_error(connection));
	db_d_report_error();
	return DB_FAILED;
    }

    if (describe_table(c->res, &table, c) == DB_FAILED) {
	db_d_append_error(_("Unable to describe table."));
	db_d_report_error();
	mysql_free_result(c->res);
	return DB_FAILED;
    }

    c->nrows = (int)mysql_num_rows(c->res);

    /* record table with dbCursor */
    db_set_cursor_table(dbc, table);

    /* set dbCursor's token for my cursor */
    db_set_cursor_token(dbc, c->token);

    return DB_OK;
}
Example #5
0
int main(int argc, char **argv)
{
    dbString stmt;
    dbDriver *driver;
    dbHandle handle;
    int ret;
    FILE *fd;
    int error;

    error = 0;

    parse_command_line(argc, argv);

    if (strcmp(parms.input, "-")) {
	fd = fopen(parms.input, "r");
	if (fd == NULL) {
	    G_fatal_error(_("Unable to open file <%s> for reading.\n"
			    "Details: %s"), parms.input, strerror(errno));
	}
    }
    else {
	fd = stdin;
    }
    
    driver = db_start_driver(parms.driver);
    if (driver == NULL) {
	G_fatal_error(_("Unable to start driver <%s>"), parms.driver);
    }

    db_init_handle(&handle);
    db_set_handle(&handle, parms.database, parms.schema);
    if (db_open_database(driver, &handle) != DB_OK)
	G_fatal_error(_("Unable to open database <%s>"), parms.database);

    while (get_stmt(fd, &stmt)) {
	if (!stmt_is_empty(&stmt)) {
	    G_debug(3, "sql: %s", db_get_string(&stmt));

	    ret = db_execute_immediate(driver, &stmt);

	    if (ret != DB_OK) {
		if (parms.i) {	/* ignore SQL errors */
		    G_warning(_("Error while executing: '%s'"),
			      db_get_string(&stmt));
		    error++;
		}
		else
		    G_fatal_error(_("Error while executing: '%s'"),
				  db_get_string(&stmt));
	    }
	}
    }

    db_close_database(driver);
    db_shutdown_driver(driver);

    exit(error ? EXIT_FAILURE : EXIT_SUCCESS);
}
Example #6
0
/*
 * db__recv_string (dbString *x)
 *  reads a string from transport
 *
 *  returns DB_OK, DB_MEMORY_ERR, or DB_PROTOCOL_ERR
 *    x.s will be NULL if error
 *
 * NOTE: caller MUST initialize x by calling db_init_string()
 */
int db__recv_string(dbString * x)
{
    int stat = DB_OK;
    int len;
    char *s;

    if (!db__recv(&len, sizeof(len)))
	stat = DB_PROTOCOL_ERR;

    if (len <= 0)		/* len will include the null byte */
	stat = DB_PROTOCOL_ERR;

    if (db_enlarge_string(x, len) != DB_OK)
	stat = DB_PROTOCOL_ERR;

    s = db_get_string(x);

    if (!db__recv(s, len))
	stat = DB_PROTOCOL_ERR;

    if (stat == DB_PROTOCOL_ERR)
	db_protocol_error();

    return stat;
}
bool OGRGRASSLayer::SetAttributes ( OGRFeature *poFeature, dbTable *table )
{
    CPLDebug ( "GRASS", "OGRGRASSLayer::SetAttributes" );

    for ( int i = 0; i < nFields; i++) 
    {
	dbColumn *column = db_get_table_column ( table, i );
	dbValue *value = db_get_column_value ( column );

	int ctype = db_sqltype_to_Ctype ( db_get_column_sqltype(column) );

	if ( !db_test_value_isnull(value) )
	{
	    switch ( ctype ) {
		case DB_C_TYPE_INT:
		    poFeature->SetField( i, db_get_value_int ( value ));
		    break; 
		case DB_C_TYPE_DOUBLE:
		    poFeature->SetField( i, db_get_value_double ( value ));
		    break; 
		case DB_C_TYPE_STRING:
		    poFeature->SetField( i, db_get_value_string ( value ));
		    break; 
		case DB_C_TYPE_DATETIME:
		    db_convert_column_value_to_string ( column, poDbString );
		    poFeature->SetField( i, db_get_string ( poDbString ));
		    break; 
	    }
	}
	
	db_convert_column_value_to_string ( column, poDbString );
	//CPLDebug ( "GRASS", "val = %s", db_get_string ( poDbString ));
    }
    return true;
}
Example #8
0
static void
write_class_info (FILE * fp, DB_OBJECT * classobj)
{
  DB_OBJLIST *objlist, *temp;
  DB_OBJECT *obj;
  DB_VALUE v;

  fprintf (fp, MSGFMT, "open", "class");
  fprintf (fp, MSGFMT, "classname", db_get_class_name (classobj));

  obj = db_get_owner (classobj);
  db_get (obj, "name", &v);
  fprintf (fp, MSGFMT, "owner", db_get_string (&v));

  objlist = db_get_superclasses (classobj);
  for (temp = objlist; temp != NULL; temp = temp->next)
    {
      fprintf (fp, MSGFMT, "superclass", db_get_class_name (temp->op));
    }
  if (objlist != NULL)
    db_objlist_free (objlist);

  if (db_is_vclass (classobj))
    fprintf (fp, MSGFMT, "virtual", "view");
  else
    fprintf (fp, MSGFMT, "virtual", "normal");

  fprintf (fp, MSGFMT, "close", "class");
}
Example #9
0
int db__driver_execute_immediate(dbString * sql)
{
    char *str;

    /* In addition to standard escape character ' (apostrophe) 
     * MySQL supports also \ (backslash). Because this is not SQL
     * standard, GRASS modules cannot escape all \ in the text
     * because other drivers do not support this feature. 
     * For example, if a text contains string \' GRASS modules 
     * escape ' by another ' and the string passed to the driver is \''
     * MySQL converts \' to ' but second ' remains not escaped and 
     * result is error. 
     * Because of this, all occurencies of \ in sql must be 
     * escaped by \ */
    str = G_str_replace(db_get_string(sql), "\\", "\\\\");

    G_debug(3, "Escaped SQL: %s", str);

    if (mysql_query(connection, str) != 0) {
	db_d_append_error("%s\n%s\n%s",
			  _("Unable to execute:"),
			  str,
			  mysql_error(connection));
	db_d_report_error();
	if (str)
	    G_free(str);
	return DB_FAILED;
    }

    if (str)
	G_free(str);

    return DB_OK;
}
Example #10
0
int insert_new_record(dbDriver * driver, struct field_info *Fi,
		      dbString * sql, int cat, int comp)
{
    char buf[2000];

    sprintf(buf, "insert into %s values (%d, %d)", Fi->table, cat, comp);
    db_set_string(sql, buf);
    G_debug(3, "%s", db_get_string(sql));

    if (db_execute_immediate(driver, sql) != DB_OK) {
	db_close_database_shutdown_driver(driver);
	G_fatal_error(_("Cannot insert new record: %s"), db_get_string(sql));
	return 0;
    };
    return 1;
}
Example #11
0
int db__driver_execute_immediate(dbString * sql)
{
    char *s, msg[OD_MSG];
    cursor *c;
    SQLRETURN ret;
    SQLINTEGER err;

    s = db_get_string(sql);

    /* allocate cursor */
    c = alloc_cursor();
    if (c == NULL)
	return DB_FAILED;

    ret = SQLExecDirect(c->stmt, s, SQL_NTS);
    if ((ret != SQL_SUCCESS) && (ret != SQL_SUCCESS_WITH_INFO)) {
	SQLGetDiagRec(SQL_HANDLE_STMT, c->stmt, 1, NULL, &err, msg,
		      sizeof(msg), NULL);
	db_d_append_error("SQLExecDirect():\n%s\n%s (%d)\n", s, msg,
			  (int)err);
	db_d_report_error();

	return DB_FAILED;
    }

    free_cursor(c);

    return DB_OK;
}
Example #12
0
int main(int argc, char **argv)
{
    dbDriver *driver;
    dbHandle handle;
    dbString *names;
    int i, count;
    int system_tables;

    parse_command_line(argc, argv);

    driver = db_start_driver(parms.driver);
    if (driver == NULL)
	G_fatal_error(_("Unable to start driver <%s>"), parms.driver);

    db_init_handle(&handle);
    db_set_handle(&handle, parms.database, NULL);
    if (db_open_database(driver, &handle) != DB_OK)
	G_fatal_error(_("Unable to open database <%s>"), parms.database);

    system_tables = parms.s;
    if (db_list_tables(driver, &names, &count, system_tables) != DB_OK)
	exit(ERROR);
    for (i = 0; i < count; i++)
	fprintf(stdout, "%s\n", db_get_string(&names[i]));

    db_close_database(driver);
    db_shutdown_driver(driver);

    exit(EXIT_SUCCESS);
}
Example #13
0
void write_point(struct Map_info *Out, double x, double y, double z,
		 int line_cat, double along, int table)
{
    char buf[2000];

    G_debug(3, "write_point()");

    Vect_reset_line(PPoints);
    Vect_reset_cats(PCats);

    /* Write point */
    Vect_append_point(PPoints, x, y, z);
    Vect_cat_set(PCats, 1, line_cat);
    Vect_cat_set(PCats, 2, point_cat);
    Vect_write_line(Out, GV_POINT, PPoints, PCats);

    /* Attributes */
    if (!table) {
	db_zero_string(&stmt);
	sprintf(buf, "insert into %s values ( %d, %d, %.15g )", Fi->table,
		point_cat, line_cat, along);
	db_append_string(&stmt, buf);

	if (db_execute_immediate(driver, &stmt) != DB_OK) {
	    G_warning(_("Unable to insert new record: '%s'"),
		      db_get_string(&stmt));
	}
    }
    point_cat++;
}
Example #14
0
/*!
  \brief Get column number

  \param index pointer to dbIndex
  \param column_num column number

  \return string buffer with name
 */
const char *db_get_index_column_name(dbIndex * index, int column_num)
{
    if (column_num < 0 || column_num >= index->numColumns) {
	db_error(_("db_get_index_column_name(): invalid column number"));
	return ((const char *)NULL);
    }
    return db_get_string(&index->columnNames[column_num]);
}
Example #15
0
int db__driver_describe_table(dbString * table_name, dbTable ** table)
{
    dbString sql;
    MYSQL_RES *res;

    db_init_string(&sql);

    db_set_string(&sql, "select * from ");
    db_append_string(&sql, db_get_string(table_name));
    db_append_string(&sql, " where 1 = 0");

    if (mysql_query(connection, db_get_string(&sql)) != 0) {
	append_error(db_get_string(&sql));
	append_error("\n");
	append_error(mysql_error(connection));
	report_error();
	return DB_FAILED;
    }

    res = mysql_store_result(connection);

    if (res == NULL) {
	append_error(db_get_string(&sql));
	append_error("\n");
	append_error(mysql_error(connection));
	report_error();
	return DB_FAILED;
    }

    if (describe_table(res, table, NULL) == DB_FAILED) {
	append_error("Cannot describe table\n");
	report_error();
	mysql_free_result(res);
	return DB_FAILED;
    }

    mysql_free_result(res);

    db_set_table_name(*table, db_get_string(table_name));

    return DB_OK;
}
Example #16
0
/*!
  \brief Open select cursor

  \param sel select statement (given as dbString)
  \param[out] dbc pointer to dbCursor
  \param mode open mode

  \return DB_OK on success
  \return DB_FAILED on failure
*/
int db__driver_open_select_cursor(dbString * sel, dbCursor * dbc, int mode)
{
    cursor *c;
    dbTable *table;

    init_error();

    /* allocate cursor */
    c = alloc_cursor();
    if (c == NULL)
	return DB_FAILED;

    db_set_cursor_mode(dbc, mode);
    db_set_cursor_type_readonly(dbc);

    G_debug(3, "SQL: '%s'", db_get_string(sel));
    c->hLayer = OGR_DS_ExecuteSQL(hDs, db_get_string(sel), NULL, NULL);

    if (c->hLayer == NULL) {
	append_error(_("Unable to select: \n"));
	append_error(db_get_string(sel));
	append_error("\n");
	report_error();
	return DB_FAILED;
    }

    if (describe_table(c->hLayer, &table, c) == DB_FAILED) {
	append_error(_("Unable to describe table\n"));
	report_error();
	OGR_DS_ReleaseResultSet(hDs, c->hLayer);
	return DB_FAILED;
    }

    /* record table with dbCursor */
    db_set_cursor_table(dbc, table);

    /* set dbCursor's token for my cursor */
    db_set_cursor_token(dbc, c->token);

    return DB_OK;
}
Example #17
0
int point_save(double xmm, double ymm, double zmm, double err)




/*
   c  saves point deviations
   c
 */
{
    int cat;

    Vect_reset_line(Pnts);
    Vect_reset_cats(Cats);

    Vect_append_point(Pnts, xmm, ymm, zmm);
    cat = count;
    Vect_cat_set(Cats, 1, cat);
    Vect_write_line(&Map, GV_POINT, Pnts, Cats);

    db_zero_string(&sql);
    sprintf(buf, "insert into %s values ( %d ", f->table, cat);
    db_append_string(&sql, buf);

    sprintf(buf, ", %f", err);
    db_append_string(&sql, buf);
    db_append_string(&sql, ")");
    G_debug(3, "%s", db_get_string(&sql));

    if (db_execute_immediate(driver, &sql) != DB_OK) {
	db_close_database(driver);
	db_shutdown_driver(driver);
	G_fatal_error(_("Cannot insert new row: %s"), db_get_string(&sql));
    }
    count++;

    return 1;
}
Example #18
0
/* extract custom-namespaced attributes if any */
static int mk_attribs(int cat, struct field_info *Fi, dbDriver * Driver,
                      dbTable * Table, int attr_cols[], int attr_size,
                      int do_attr)
{
    int i, more;
    char buf[2000];
    dbString dbstring;
    dbColumn *Column;
    dbCursor cursor;
    dbValue *Value;

    /* include cat in any case */
    fprintf(fpsvg, "gg:cat=\"%d\" ", cat);

    /* skip attribs if none */
    if (do_attr == 0) {
        return 1;
    }

    /* create SQL-string and query attribs */
    db_init_string(&dbstring);

    sprintf(buf, "SELECT * FROM %s WHERE %s = %d", Fi->table, Fi->key, cat);

    db_set_string(&dbstring, buf);

    if (db_open_select_cursor(Driver, &dbstring, &cursor, DB_SEQUENTIAL) !=
            DB_OK) {
        G_fatal_error(_("Cannot select attributes for cat=%d"), cat);
    }
    else {
        if (db_fetch(&cursor, DB_NEXT, &more) != DB_OK) {
            G_fatal_error(_("Unable to fetch data from table"));
        }

        /* extract attribs and data if wanted */
        Table = db_get_cursor_table(&cursor);

        for (i = 0; i < attr_size; i++) {
            Column = db_get_table_column(Table, attr_cols[i]);
            Value = db_get_column_value(Column);
            db_convert_column_value_to_string(Column, &dbstring);
            strcpy(buf, db_get_column_name(Column));
            fprintf(fpsvg, "gg:%s=\"", G_tolcase(buf));
            print_escaped_for_xml(db_get_string(&dbstring));
            fprintf(fpsvg, "\" ");
        }
    }
    return 1;
}
Example #19
0
int db__driver_create_table(dbTable * table)
{
    dbString sql;
    int ret;

    G_debug(3, "db__driver_create_table()");

    db_init_string(&sql);

    db_table_to_sql(table, &sql);

    G_debug(3, " SQL: %s", db_get_string(&sql));

    ret = execute(db_get_string(&sql), NULL);

    if (ret == DB_FAILED) {
	db_d_append_error(_("Unable to create table"));
	db_d_report_error();
	return DB_FAILED;
    }

    return DB_OK;
}
Example #20
0
int db__driver_create_table(dbTable * table)
{
    dbString sql;
    cursor *c;
    char msg[OD_MSG];
    char *emsg = NULL;
    SQLRETURN ret;
    SQLINTEGER err;

    G_debug(3, "db__driver_create_table()");

    db_init_string(&sql);
    db_table_to_sql(table, &sql);

    G_debug(3, " SQL: %s", db_get_string(&sql));

    c = alloc_cursor();
    if (c == NULL)
        return DB_FAILED;

    ret = SQLExecDirect(c->stmt, db_get_string(&sql), SQL_NTS);

    if ((ret != SQL_SUCCESS) && (ret != SQL_SUCCESS_WITH_INFO)) {
        SQLGetDiagRec(SQL_HANDLE_STMT, c->stmt, 1, NULL, &err, msg,
                      sizeof(msg), NULL);
        G_asprintf(&emsg, "SQLExecDirect():\n%s\n%s (%d)\n",
                   db_get_string(&sql), msg, (int)err);
        report_error(emsg);
        G_free(emsg);

        return DB_FAILED;
    }

    free_cursor(c);

    return DB_OK;
}
Example #21
0
int db__driver_describe_table(dbString * table_name, dbTable ** table)
{
    int i, nlayers;
    OGRLayerH hLayer = NULL;
    OGRFeatureDefnH hFeatureDefn;

    /* Find data source */
    nlayers = OGR_DS_GetLayerCount(hDs);

    for (i = 0; i < nlayers; i++) {
	hLayer = OGR_DS_GetLayer(hDs, i);
	hFeatureDefn = OGR_L_GetLayerDefn(hLayer);
	if (G_strcasecmp
	    ((char *)OGR_FD_GetName(hFeatureDefn),
	     db_get_string(table_name)) == 0) {
	    break;
	}
	hLayer = NULL;
    }

    if (hLayer == NULL) {
	append_error("Table '%s' does not exist\n",
		     db_get_string(table_name));
	report_error();
	return DB_FAILED;
    }

    G_debug(3, "->>");
    if (describe_table(hLayer, table, NULL) == DB_FAILED) {
	append_error("Cannot describe table\n");
	report_error();
	return DB_FAILED;
    }

    return DB_OK;
}
Example #22
0
static void create_table(struct Map_info *flowline_vec,
			 struct field_info **f_info, dbDriver ** driver,
			 int write_scalar, int use_sampled_map)
{
    dbString sql;
    char buf[200];
    dbDriver *drvr;
    struct field_info *fi;

    db_init_string(&sql);
    fi = Vect_default_field_info(flowline_vec, 1, NULL, GV_1TABLE);
    *f_info = fi;
    Vect_map_add_dblink(flowline_vec, 1, NULL, fi->table, GV_KEY_COLUMN,
			fi->database, fi->driver);
    drvr = db_start_driver_open_database(fi->driver,
					 Vect_subst_var(fi->database,
							flowline_vec));
    if (drvr == NULL) {
	G_fatal_error(_("Unable to open database <%s> by driver <%s>"),
		      Vect_subst_var(fi->database, flowline_vec), fi->driver);
    }
    db_set_error_handler_driver(drvr);

    *driver = drvr;
    sprintf(buf, "create table %s (cat integer, velocity double precision",
	    fi->table);
    db_set_string(&sql, buf);
    if (write_scalar)
	db_append_string(&sql, ", input double precision");
    if (use_sampled_map)
	db_append_string(&sql, ", sampled double precision");
    db_append_string(&sql, ")");

    db_begin_transaction(drvr);
    /* Create table */
    if (db_execute_immediate(drvr, &sql) != DB_OK) {
	G_fatal_error(_("Unable to create table: %s"), db_get_string(&sql));
    }
    if (db_create_index2(drvr, fi->table, fi->key) != DB_OK)
	G_warning(_("Unable to create index for table <%s>, key <%s>"),
		  fi->table, fi->key);
    /* Grant */
    if (db_grant_on_table
	(drvr, fi->table, DB_PRIV_SELECT, DB_GROUP | DB_PUBLIC) != DB_OK) {
	G_fatal_error(_("Unable to grant privileges on table <%s>"),
		      fi->table);
    }
}
Example #23
0
int get_table_color(int cat, int line,
		    struct Colors *colors, dbCatValArray *cvarr,
		    int *red, int *grn, int *blu)
{
    int custom_rgb;
    char colorstring[12];	/* RRR:GGG:BBB */
    
    dbCatVal *cv;

    custom_rgb = FALSE;
    cv = NULL;

    if (cat < 0)
	return custom_rgb;
    
    if (colors) {
	/* read color table */
	if (Rast_get_c_color(&cat, red, grn, blu, colors) == 1) {
	    custom_rgb = TRUE;
	    G_debug(3, "\tb: %d, g: %d, r: %d", *blu, *grn, *red);
	}
    }

    /* read RGB colors from db for current area # */
    if (cvarr && db_CatValArray_get_value(cvarr, cat, &cv) == DB_OK) {
	sprintf(colorstring, "%s", db_get_string(cv->val.s));
	if (*colorstring != '\0') {
	    G_debug(3, "element %d: colorstring: %s", line,
		    colorstring);
	    
	    if (G_str_to_color(colorstring, red, grn, blu) == 1) {
		custom_rgb = TRUE;
		G_debug(3, "element:%d  cat %d r:%d g:%d b:%d",
			line, cat, *red, *grn, *blu);
	    }
	    else {
                G_debug(3, "Invalid color definition '%s' ignored", colorstring);
                ncolor_rules_skipped++;
		}
	}
	else {
	    G_debug(3, "Invalid color definition '%s' ignored", colorstring);
            ncolor_rules_skipped++;
	}
    }

    return custom_rgb;
}
Example #24
0
int db__driver_execute_immediate(dbString * sql)
{
    char *s;
    int ret;

    s = db_get_string(sql);

    ret = execute(s, NULL);

    if (ret == DB_FAILED) {
	append_error("Error in db_execute_immediate()");
	report_error();
	return DB_FAILED;
    }

    return DB_OK;
}
bool OGRGRASSLayer::OpenSequentialCursor()
{
    CPLDebug ( "GRASS", "OpenSequentialCursor: %s", pszQuery  );

    if ( !poDriver ) 
    {
	CPLError( CE_Failure, CPLE_AppDefined, "Driver not opened.");
	return false;
    }

    if ( bCursorOpened )
    {
	db_close_cursor ( poCursor );
	bCursorOpened = false;
    }

    char buf[2000];
    sprintf ( buf, "SELECT * FROM %s ", poLink->table );
    db_set_string ( poDbString, buf);

    if ( pszQuery ) {
	sprintf ( buf, "WHERE %s ", pszQuery );
	db_append_string ( poDbString, buf);
    }

    sprintf ( buf, "ORDER BY %s", poLink->key);
    db_append_string ( poDbString, buf);

    CPLDebug ( "GRASS", "Query: %s", db_get_string(poDbString) );
    
    if ( db_open_select_cursor ( poDriver, poDbString, 
		poCursor, DB_SCROLL) == DB_OK ) 
    {
	iCurrentCat = -1;
	bCursorOpened = true;
	CPLDebug ( "GRASS", "num rows = %d", db_get_num_rows ( poCursor ) );
    } 
    else 
    {
	CPLError( CE_Failure, CPLE_AppDefined, "Cannot open cursor.");
	return false;
    }
    return true;
}
Example #26
0
int db__send_string(dbString * x)
{
    int stat = DB_OK;
    const char *s = db_get_string(x);
    int len = s ? strlen(s) + 1 : 1;

    if (!s)
	s = "";			/* don't send a NULL string */

    if (!db__send(&len, sizeof(len)))
	stat = DB_PROTOCOL_ERR;

    if (!db__send(s, len))
	stat = DB_PROTOCOL_ERR;

    if (stat == DB_PROTOCOL_ERR)
	db_protocol_error();

    return stat;
}
Example #27
0
void process_node(int node, int cat)
{
    char buf[2000];

    sprintf(buf, "INSERT INTO %s VALUES(%d", Fi->table, cat);
    db_set_string(&sql, buf);
    if (deg_opt->answer)
	append_double(&sql, deg[node]);
    if (close_opt->answer)
	append_double(&sql, closeness[node]);
    if (betw_opt->answer)
	append_double(&sql, betw[node]);
    if (eigen_opt->answer)
	append_double(&sql, eigen[node]);

    db_append_string(&sql, ")");
    if (db_execute_immediate(driver, &sql) != DB_OK) {
	db_close_database_shutdown_driver(driver);
	G_fatal_error(_("Cannot insert new record: %s"), db_get_string(&sql));
    }
}
Example #28
0
/*
    Write a vector geometry to the output GRASS vector map.
    Write attributes to table linked to that map. Link vector object to attribute
    table record.
*/
void write_vect( int cat, int skelID, int boneID, int unitID,
		 double *xpnts, double *ypnts, double *zpnts, 
		 int arr_size, int type )
{
    struct line_cats *Cats;
    struct line_pnts *Points;
    char buf[MAXSTR];
    char rgbbuf[12];
    char rgbbuf2[12];
    

    /* copy xyzpnts to Points */
    Points = Vect_new_line_struct();
    Vect_copy_xyz_to_pnts(Points, xpnts, ypnts, zpnts, arr_size);

    /* write database attributes */
    Cats = Vect_new_cats_struct();
    sprintf ( rgbbuf, "%i:%i:%i", RGB[RGBNUM][0], RGB[RGBNUM][1], RGB[RGBNUM][2] );
    sprintf ( rgbbuf2, "%i:%i:%i", RGB[RGB_MAPPER_COLOUR[boneID-1]][0],RGB[RGB_MAPPER_COLOUR[boneID-1]][1], RGB[RGB_MAPPER_COLOUR[boneID-1]][2] );
    sprintf(buf, "insert into %s (cat, skel_id, bone_id, unit_id, GRASSRGB, BONERGB) values(%i,%i,%i,%i,'%s','%s');",
            Fi->table, cat, skelID, boneID, unitID, rgbbuf, rgbbuf2);

    if ( DEBUG ) {
        fprintf ( stderr, "Writing attribute: %s\n", buf );
    }

    db_set_string(&sql, buf);
    if (db_execute_immediate(driver, &sql) != DB_OK) {
	G_fatal_error(_("Unable to insert new record: %s"), db_get_string(&sql));
    }
    db_free_string(&sql);
 
    Vect_cat_set(Cats, 1, cat);

    /* write */
    Vect_write_line(Map, type, Points, Cats);

    Vect_destroy_cats_struct(Cats);
    Vect_destroy_line_struct(Points);
}
Example #29
0
/*   sets *color and returns 1 on success, -1 if no color found */
int get_ps_color_rgbcol_varea(struct Map_info *map, int vec, int area,
			       dbCatValArray * cvarr_rgb, PSCOLOR *color)
{
    int cat, ret;
    dbCatVal *cv_rgb;
    int red, grn, blu;
    char *rgbstring = NULL;

    cat = Vect_get_area_cat(map, area, vector.layer[vec].field);

    ret = db_CatValArray_get_value(cvarr_rgb, cat, &cv_rgb);

    if (ret != DB_OK) {
	G_warning(_("No record for category [%d]"), cat);
    }
    else {
	rgbstring = db_get_string(cv_rgb->val.s);
	if (rgbstring == NULL ||
	    G_str_to_color(rgbstring, &red, &grn, &blu) != 1) {
	    G_warning(_("Invalid RGB color definition in column <%s> for category [%d]"),
		      vector.layer[vec].rgbcol, cat);
	    rgbstring = NULL;
	}
    }

    if (rgbstring) {
	G_debug(3, "    dynamic varea fill rgb color = %s", rgbstring);
	set_color(color, red, grn, blu);
    }
    else {
	set_color(color, 0, 0, 0);
	return -1;
    }

    return 1;
}
Example #30
0
int line_area(struct Map_info *In, int *field, struct Map_info *Tmp,
	      struct Map_info *Out, struct field_info *Fi,
	      dbDriver * driver, int operator, int *ofield,
	      ATTRIBUTES * attr, struct ilist *BList)
{
    int line, nlines, ncat;
    struct line_pnts *Points;
    struct line_cats *Cats, *ACats, *OCats;

    char buf[1000];
    dbString stmt;

    Points = Vect_new_line_struct();
    Cats = Vect_new_cats_struct();
    ACats = Vect_new_cats_struct();
    OCats = Vect_new_cats_struct();
    db_init_string(&stmt);

    G_message(_("Breaking lines..."));
    Vect_break_lines_list(Tmp, NULL, BList, GV_LINE | GV_BOUNDARY, NULL);

    /*
    G_message(_("Merging lines..."));
    Vect_merge_lines(Tmp, GV_LINE, NULL, NULL);
    */

    nlines = Vect_get_num_lines(Tmp);

    /* Warning!: cleaning process (break) creates new vertices which are usually slightly 
     * moved (RE), to compare such new vertex with original input is a problem?
     * 
     * TODO?: would it be better to copy centroids also and query output map? 
     */

    /* Check if the line is inside or outside binput area */
    G_message(_("Selecting lines..."));
    ncat = 1;
    for (line = 1; line <= nlines; line++) {
	int ltype;

	G_percent(line, nlines, 1);	/* must be before any continue */

	if (!Vect_line_alive(Tmp, line))
	    continue;

	ltype = Vect_get_line_type(Tmp, line);

	if (ltype == GV_BOUNDARY) {	/* No more needed */
	    continue;
	}

	/* Now the type should be only GV_LINE */

	/* Decide if the line is inside or outside the area. In theory:
	 * 1) All vertices outside
	 *      - easy, first vertex must be outside
	 * 2) All vertices inside 
	 * 3) All vertices on the boundary, we take it as inside (attention, 
	 *    result of Vect_point_in_area() for points on segments between vertices may be both
	 *    inside or outside, because of representation of numbers)
	 * 4) One or two end vertices on the boundary, all others outside
	 * 5) One or two end vertices on the boundary, all others inside 
	 *
	 */

	/* Note/TODO: the test done is quite simple, check the point in the middle of segment.
	 * If the line overlaps the boundary, the result may be both outside and inside
	 * this should be solved (check angles?)
	 * This should not happen if Vect_break_lines_list() works correctly
	 */

	/* merge here */
	merge_line(Tmp, line, Points, Cats);

	G_debug(3, "line = %d", line);

	point_area(&(In[1]), field[1], (Points->x[0] + Points->x[1]) / 2,
		   (Points->y[0] + Points->y[1]) / 2, ACats);

	if ((ACats->n_cats > 0 && operator == OP_AND) ||
	    (ACats->n_cats == 0 && operator == OP_NOT)) {
	    int i;

	    /* Point is inside */
	    G_debug(3, "OK, write line, line ncats = %d area ncats = %d",
		    Cats->n_cats, ACats->n_cats);

	    Vect_reset_cats(OCats);

	    if (ofield[0]  > 0) {
		/* rewrite with all combinations of acat - bcat (-1 in cycle for null) */
		for (i = -1; i < Cats->n_cats; i++) {	/* line cats */
		    int j;

		    if (i == -1 && Cats->n_cats > 0)
			continue;	/* no need to make null */

		    for (j = -1; j < ACats->n_cats; j++) {
			if (j == -1 && ACats->n_cats > 0)
			    continue;	/* no need to make null */

			if (ofield[0] > 0)
			    Vect_cat_set(OCats, ofield[0], ncat);

			/* Attributes */
			if (driver) {
			    ATTR *at;

			    sprintf(buf, "insert into %s values ( %d", Fi->table,
				    ncat);
			    db_set_string(&stmt, buf);

			    /* cata */
			    if (i >= 0) {
				if (attr[0].columns) {
				    at = find_attr(&(attr[0]), Cats->cat[i]);
				    if (!at)
					G_fatal_error(_("Attribute not found"));

				    if (at->values)
					db_append_string(&stmt, at->values);
				    else
					db_append_string(&stmt,
							 attr[0].null_values);
				}
				else {
				    sprintf(buf, ", %d", Cats->cat[i]);
				    db_append_string(&stmt, buf);
				}
			    }
			    else {
				if (attr[0].columns) {
				    db_append_string(&stmt, attr[0].null_values);
				}
				else {
				    sprintf(buf, ", null");
				    db_append_string(&stmt, buf);
				}
			    }

			    /* catb */
			    if (j >= 0) {
				if (attr[1].columns) {
				    at = find_attr(&(attr[1]), ACats->cat[j]);
				    if (!at)
					G_fatal_error(_("Attribute not found"));

				    if (at->values)
					db_append_string(&stmt, at->values);
				    else
					db_append_string(&stmt,
							 attr[1].null_values);
				}
				else {
				    sprintf(buf, ", %d", ACats->cat[j]);
				    db_append_string(&stmt, buf);
				}
			    }
			    else {
				if (attr[1].columns) {
				    db_append_string(&stmt, attr[1].null_values);
				}
				else {
				    sprintf(buf, ", null");
				    db_append_string(&stmt, buf);
				}
			    }

			    db_append_string(&stmt, " )");

			    G_debug(3, "%s", db_get_string(&stmt));

			    if (db_execute_immediate(driver, &stmt) != DB_OK)
				G_warning(_("Unable to insert new record: '%s'"),
					  db_get_string(&stmt));
			}

			ncat++;
		    }
		}
	    }

	    /* Add cats from input vectors */
	    if (ofield[1] > 0 && field[0] > 0) {
		for (i = 0; i < Cats->n_cats; i++) {
		    if (Cats->field[i] == field[0])
			Vect_cat_set(OCats, ofield[1], Cats->cat[i]);
		}
	    }

	    if (ofield[2] > 0 && field[1] > 0 && ofield[1] != ofield[2]) {
		for (i = 0; i < ACats->n_cats; i++) {
		    if (ACats->field[i] == field[1])
			Vect_cat_set(OCats, ofield[2], ACats->cat[i]);
		}
	    }

	    Vect_write_line(Out, ltype, Points, OCats);
	}
    }

    return 0;
}