void aRTstatictable::Create(SEXP options)
{
	string id   = GET_STRING_ELEMENT  (options, aRTstrId);
	int length  = GET_INTEGER_ELEMENT (options, "length");
	bool genids = GET_BOOL_ELEMENT    (options, "generateids");

	TeAttributeList attList;
	TeAttribute at;
			
    at.rep_.type_         = TeSTRING;
    at.rep_.numChar_      = length;
    at.rep_.name_         = id;
    at.rep_.isPrimaryKey_ = true;

    attList.push_back(at);

	TeTable attTable(TableName, attList, id, id, TeAttrStatic);

	PrintSilent("Creating static table \'%s\' on layer \'%s\' ... ", TableName.c_str(), LayerName.c_str());
	if( !Layer()->createAttributeTable(attTable) )
	{
		stringstream err;
		err << "Could not create the table:"
			<< Database->errorMessage() << endl;
		error( StreamToChar(err) );
	}
	PrintSilentYes;

	if(genids) CreateLinkIds(id);
}
void 
TeSPRFile::writeAttributeInfo( TeAttributeList& attList, const string& objCategory,
							   const string& indexName ) 
{
	fprintf (file_, "%s %s \n", "CATEGORY_OBJ", objCategory.c_str() ); 	
	fprintf (file_, "%s%c%s%c%s%c%s \n", "T_KEY", separator_, "TEXT", separator_, "32", separator_, "0"); 	

	TeAttributeList::iterator it = attList.begin();
	for ( ;it != attList.end();++it )
	{
		string name = (*it).rep_.name_;
		if ( TeConvertToUpperCase(name) == TeConvertToUpperCase(indexName) ) continue; // skip the index name
		switch ((*it).rep_.type_)
		{
			case TeSTRING:
				this->writeTextParameterInfo(name, (*it).rep_.numChar_);
				break;
			case TeREAL:
				this->writeRealParameterInfo(name);
				break;
			case TeINT:
				this->writeIntParameterInfo(name);
				break;
			case TeCHARACTER:
				this->writeTextParameterInfo(name,1);
				break;
			case TeDATETIME:
				this->writeTextParameterInfo(name,25);
            default:
                break;
		}
	}  
} 
void attributeListToCoverageDimensions(const TeAttributeList& attributes, std::vector<TeCoverageDimension>& dimensions)
{
    dimensions.clear();

    unsigned int count = 0;
    for (TeAttributeList::const_iterator it = attributes.begin(); it != attributes.end(); it++)
    {
        TeDataType dimensionType = (it->rep_.type_ == TeINT) ? TeINTEGER : TeDOUBLE;
        dimensions.push_back(TeCoverageDimension(count, it->rep_.name_, dimensionType));
        count++;
    }
}
DBFHandle TeCreateDBFFile (const string& dbfFilename, TeAttributeList& attList)
{
	DBFHandle hDBF = DBFCreate( dbfFilename.c_str() );
	if( hDBF == 0 )
		return 0;
	
	int i =0;
	TeAttributeList::iterator it=attList.begin();

	while ( it != attList.end() )
	{
		TeAttribute at = (*it);
		string atName = at.rep_.name_;

		if (atName.size() > 10)
		{
			int extra = (int)(atName.size() - 10)/2;
			int middle = (int)(atName.size()/2);
			string str = atName.substr(0,middle-extra-1);
			str += atName.substr(middle+extra);
			atName = str;
		}
		if (at.rep_.type_ == TeSTRING )
		{
			if (DBFAddField( hDBF, atName.c_str(), FTString, at.rep_.numChar_, 0 ) == -1 )
				return 0;
		}
		else if (at.rep_.type_ == TeINT)
		{
			if (DBFAddField( hDBF, atName.c_str(), FTInteger, 32, 0 ) == -1 )
				return 0;
		}
		else if (at.rep_.type_ == TeREAL)
		{
			if (DBFAddField( hDBF, atName.c_str(), FTDouble, 40, 15 ) == -1 )
				return 0;
		}
		// OBS: shapelib doesn´t deal with xBase field type for Date 
		// we are transforming it to string
		else if (at.rep_.type_ == TeDATETIME)
		{
			if (DBFAddField( hDBF, atName.c_str(), FTDate, 8, 0 ) == -1 )
				return 0;
		}
		++i;
		++it;
	}
	return hDBF;
}
void aRTexternaltable::Create(SEXP options)
{
	string id  = GET_STRING_ELEMENT  (options, aRTstrId);
	int length = GET_INTEGER_ELEMENT (options, "length");

	TeAttributeList attList;
	TeAttribute at;
			
    at.rep_.type_         = TeSTRING;
    at.rep_.numChar_      = length;
    at.rep_.name_         = id;
    at.rep_.isPrimaryKey_ = true;

    attList.push_back(at);
	//TeAttrTableType atttype; // apaguei aqui 2011/04/22
	string link = "";
	//atttype = TeAttrExternal;

	if( !Database->createTable(TableName, attList))
		{
			stringstream err;
			err << "Could not create the table:"
				<< Database->errorMessage() << endl;
			delete this;
			error( StreamToChar(err) );
		}
		
	TeTable attTable(TableName, attList, id, "", TeAttrExternal);

	if( !Database->insertTableInfo(-1, attTable))
	{
		stringstream err;
		err << "Could not make the table external:"
			<< Database->errorMessage() << endl;
		delete this;
		error( StreamToChar(err) );
	}
/*
	TeTable attTable(TableName, attList, id, link, atttype);

	if( !Layer()->createAttributeTable(attTable) )
	{
		stringstream err;
		err << "Could not create the table:"
			<< Database->errorMessage() << endl;
		error( StreamToChar(err) );
	}*/
}
bool TeOGRDriver::createAttributeTable(TeTable &table)
{
	if(ogrLayer_ == 0)
		return false;

	TeAttributeList::iterator it;
	TeAttributeList list = table.attributeList();
	for(it = list.begin(); it != list.end(); ++it)
	{
		OGRFieldDefn oField = Convert2OGR(*it);
		
		if((*it).rep_.type_ == TeSTRING)
			oField.SetWidth((*it).rep_.numChar_);
		
		if(ogrLayer_->CreateField(&oField) != OGRERR_NONE)
			return false;
	}
	return true;
}
bool TeSQLite::getAttributeList(const string& tableName,TeAttributeList& attList)
{
	if(!tableExist(tableName))
	{
		return false;
	}

	TeDatabasePortal* portal = this->getPortal();
	if (!portal)
		return false;

	string sql = "PRAGMA table_info(" + tableName + ")";
	if (!portal->query(sql))
	{
		delete portal;
		return false;
	}

	while(portal->fetchRow())
	{
		TeAttribute attr;
		attr.rep_.name_ = portal->getData("name");
		attr.rep_.isPrimaryKey_ = portal->getBool("pk");
		attr.rep_.null_ = !portal->getBool("notnull");
		attr.rep_.defaultValue_ = portal->getData("dflt_value");

		std::string type = portal->getData("type");
		if(type == "TEXT")
		{
			attr.rep_.type_ = TeSTRING;
		}
		else if(type == "INTEGER")
		{
			attr.rep_.type_ = TeINT;
		}
		else if(type == "REAL")
		{
			attr.rep_.type_ = TeREAL;
		}
		else if(type == "BLOB")
		{
			attr.rep_.type_ = TeBLOB;
		}
		else
		{
			attr.rep_.type_ = TeSTRING;
		}

		attList.push_back(attr);
	}

	delete portal;

	return true;
}
void
createCoverageLayerTable(TeLayer* layer, std::string& tableName)
{
    TeAttributeList attList;
    
    TeAttribute geomIdAtt;
    geomIdAtt.rep_.type_ = TeINT;
    geomIdAtt.rep_.name_ = "geom_id";
    geomIdAtt.rep_.isPrimaryKey_ = true;
    geomIdAtt.rep_.isAutoNumber_ = true;
    attList.push_back(geomIdAtt);

    TeAttribute coverageIdAtt;
    coverageIdAtt.rep_.type_ = TeSTRING;
    coverageIdAtt.rep_.numChar_ = 25;
    coverageIdAtt.rep_.name_ = "coverage_id";
    coverageIdAtt.rep_.isPrimaryKey_ = false;
	attList.push_back(coverageIdAtt);

    TeAttribute coverageTableAtt;
    coverageTableAtt.rep_.type_ = TeSTRING;
    coverageTableAtt.rep_.numChar_ = 255;
    coverageTableAtt.rep_.name_ = "coverage_table";
    coverageTableAtt.rep_.isPrimaryKey_ = false;
	attList.push_back(coverageTableAtt);

    TeAttribute lowerXAtt;
    lowerXAtt.rep_.type_ = TeREAL;
    lowerXAtt.rep_.name_ = "lower_x";
    attList.push_back(lowerXAtt);

    TeAttribute lowerYAtt;
    lowerYAtt.rep_.type_ = TeREAL;
    lowerYAtt.rep_.name_ = "lower_y";
    attList.push_back(lowerYAtt);

    TeAttribute upperXAtt;
    upperXAtt.rep_.type_ = TeREAL;
    upperXAtt.rep_.name_ = "upper_x";
    attList.push_back(upperXAtt);

    TeAttribute upperYAtt;
    upperYAtt.rep_.type_ = TeREAL;
    upperYAtt.rep_.name_ = "upper_y";
    attList.push_back(upperYAtt);

    if (!layer->database()->createTable(tableName, attList))
    {
        std::string errorMsg = "Couldn't create table '" + tableName + "'.";
        throw TeException(UNKNOWN_ERROR_TYPE, errorMsg, false);
    }
}
void
createCoverageTable(TeLayer* layer, std::string& tableName)
{
    TeAttributeList attList;
    
    TeAttribute blockIdAtt;

    blockIdAtt.rep_.type_ = TeINT;
    blockIdAtt.rep_.name_ = "block_id";
    blockIdAtt.rep_.isPrimaryKey_ = true;
    attList.push_back(blockIdAtt);

    TeAttribute lowerXAtt;
    lowerXAtt.rep_.type_ = TeREAL;
    lowerXAtt.rep_.name_ = "lower_x";
    attList.push_back(lowerXAtt);

    TeAttribute lowerYAtt;
    lowerYAtt.rep_.type_ = TeREAL;
    lowerYAtt.rep_.name_ = "lower_y";
    attList.push_back(lowerYAtt);

    TeAttribute upperXAtt;
    upperXAtt.rep_.type_ = TeREAL;
    upperXAtt.rep_.name_ = "upper_x";
    attList.push_back(upperXAtt);

    TeAttribute upperYAtt;
    upperYAtt.rep_.type_ = TeREAL;
    upperYAtt.rep_.name_ = "upper_y";
    attList.push_back(upperYAtt);

    TeAttribute numElementsAtt;
    numElementsAtt.rep_.type_ = TeINT;
    numElementsAtt.rep_.name_ = "num_elements";
    attList.push_back(numElementsAtt);

    TeAttribute spatialDataAtt;
    spatialDataAtt.rep_.type_ = TeBLOB;
    spatialDataAtt.rep_.name_ = "spatial_data";
    attList.push_back(spatialDataAtt);

    if (!layer->database()->createTable(tableName, attList))
    {
        std::string errorMsg = "Couldn't create table '" + tableName + "'.";
        throw TeException(UNKNOWN_ERROR_TYPE, errorMsg, false);
    }

}
void
createCoverageMetadataTable(TeLayer* layer, std::string& metadataTableName)
{
    TeAttributeList attList;

    TeAttribute coverageIdAtt;
    coverageIdAtt.rep_.type_ = TeSTRING;
    coverageIdAtt.rep_.numChar_ = 25;
    coverageIdAtt.rep_.name_ = "coverage_id";
    coverageIdAtt.rep_.isPrimaryKey_ = true;
	attList.push_back(coverageIdAtt);

    TeAttribute dimensionIdAtt;
    dimensionIdAtt.rep_.type_ = TeINT;
    dimensionIdAtt.rep_.name_ = "dimension_id";
    dimensionIdAtt.rep_.isPrimaryKey_ = true;
    attList.push_back(dimensionIdAtt);

    TeAttribute dataTypeAtt;
    dataTypeAtt.rep_.type_ = TeINT;
    dataTypeAtt.rep_.name_ = "data_type";
    dataTypeAtt.rep_.isPrimaryKey_ = false;
    attList.push_back(dataTypeAtt);

    TeAttribute nameAtt;
    nameAtt.rep_.type_ = TeSTRING;
    nameAtt.rep_.numChar_ = 25;
    nameAtt.rep_.name_ = "name";
    nameAtt.rep_.isPrimaryKey_ = false;
	attList.push_back(nameAtt);

    if (!layer->database()->createTable(metadataTableName, attList))
    {
        std::string errorMsg = "Couldn't create table '" + metadataTableName + "'.";
        throw TeException(UNKNOWN_ERROR_TYPE, errorMsg, false);
    }
}
bool updateDB301To302(TeDatabase* db, string& errorMessage)
{
		
	TeDatabasePortal* portal = db->getPortal();
	if(!portal)
		return false;

	// ----- valid attribute table 
	
	TeAttrTableVector attrTableVec;
	if(db->getAttrTables(attrTableVec))
	{
		for(unsigned int i=0; i<attrTableVec.size(); ++i)
		{
			TeTable fromTable = attrTableVec[i];
			bool	flag = false;
			
			if(fromTable.tableType()==TeAttrMedia)
				continue;

			//verify if there is another table with the same name
			for(unsigned int j=0; j<i; ++j)
			{
				if(TeConvertToUpperCase(attrTableVec[j].name())==TeConvertToUpperCase(fromTable.name())) 
				{
					flag = true;
					break;
				}
			}

			if(flag)
				continue;
			
			if(db->validTable(fromTable)) //fromTable was modified
			{
				TeAttributeList newAttrList = fromTable.attributeList();
				TeAttributeList oldAttrList = attrTableVec[i].attributeList();
				TeAttributeList::iterator newAttIt = newAttrList.begin();
				TeAttributeList::iterator oldAttIt = oldAttrList.begin();

				bool change = false;
				while(newAttIt!=newAttrList.end())
				{
					if(((*oldAttIt).rep_.name_) != ((*newAttIt).rep_.name_))
					{
						TeAttributeRep rep = (*newAttIt).rep_;
						if(db->alterTable(fromTable.name(), rep, (*oldAttIt).rep_.name_))
							change = true;
					}

					++newAttIt;
					++oldAttIt;
				}

				if(change)
				{
					// update te_layer_table
					string upd = " UPDATE te_layer_table ";
					upd +=	" SET unique_id = '"+ fromTable.uniqueName() +"'";
					upd +=  ", attr_link = '"+ fromTable.linkName() +"'";
					upd +=	" WHERE attr_table = '"+ fromTable.name() +"'";

					if(!db->execute (upd))
					{
						delete portal;
						errorMessage = "Error updating te_layer_table!\n";
						errorMessage += db->errorMessage();
						return false;
					}
				}
			}//if
		}//for
		portal->freeResult();
	}

	// ----- te_grouping table

	string sel = " SELECT theme_id, grouping_attr, grouping_attr_type FROM te_grouping ";
	if(!portal->query(sel))
	{
		delete portal;
		return false;
	}

	while(portal->fetchRow())
	{
		string themeId, gAttr;
		themeId = portal->getData(0);
		gAttr = portal->getData(1);
		int gTypr = portal->getInt(2);
		
		if(((gAttr.empty()) || (gAttr=="NONE")) && (gTypr==0))
		{
			string del = " DELETE FROM te_grouping WHERE theme_id = "+ themeId; 
			db->execute(del);
		}
	}

	// ----- te_grouping table

	delete portal;
	return true; 
}
bool updateDB20To30(TeDatabase* db, string& errorMessage)
{
	TeAttribute fattr;

	// ----- te_grouping 

	if(db->columnExist("te_grouping", "grouping_function", fattr) == false)
	{
		TeAttributeRep atRep;
		atRep.type_ = TeSTRING;
		atRep.name_ = "grouping_function";
		atRep.numChar_ = 10;
		if(db->addColumn("te_grouping", atRep) == false)
		{
			errorMessage = "The column grouping_function could not be appended!\n";
			errorMessage += db->errorMessage();
			return false;
		}

		string upd;
		if(db->columnExist("te_theme_application", "group_function", fattr))
		{
			upd =	" UPDATE te_grouping g, te_theme_application ta ";
			upd +=	" SET g.grouping_function = ta.group_function ";
			upd +=	" WHERE ta.theme_id = g.theme_id ";

			if(!db->execute (upd))
			{
				errorMessage = db->errorMessage();
				return false;
			}

			db->deleteColumn("te_theme_application", "group_function");
		}
		else
		{
			upd =	" UPDATE te_grouping g ";
			upd +=	" SET g.grouping_function = 'AVG' ";
			
			if(!db->execute (upd))
			{
				errorMessage = db->errorMessage();
				return false;
			}
		}
	}

	// ----- te_theme_application

	if(db->columnExist("te_theme_application", "chart_function", fattr) == false)
	{
		TeAttributeRep atRep;
		atRep.type_ = TeSTRING;
		atRep.name_ = "chart_function";
		atRep.numChar_ = 10;
		if(db->addColumn("te_theme_application", atRep) == false)
		{
			errorMessage = "The column chart_function could not be appended!\n";
			errorMessage += db->errorMessage();
			return false;
		}
		db->execute("UPDATE te_theme_application SET chart_function = 'AVG'");
	}

	// ----- te_theme 
	if(db->columnExist("te_theme", "visible_rep", fattr) == false)
	{
		TeAttributeRep atRep;
		atRep.type_ = TeINT;
		atRep.name_ = "visible_rep";
		if(db->addColumn("te_theme", atRep) == false)
		{
			errorMessage = "The column visible_rep could not be appended!\n";
			errorMessage += db->errorMessage();
			return false;
		}

		atRep.name_ = "enable_visibility";
		if(db->addColumn("te_theme", atRep) == false)
		{
			errorMessage = "The column enable_visibility could not be appended!\n";
			errorMessage += db->errorMessage();
			return false;
		}

		string upd = " UPDATE te_theme t, te_theme_application ta ";
		upd +=       " SET t.visible_rep = ta.visible_rep ";
		upd +=       " WHERE ta.theme_id = t.theme_id ";
		if(!db->execute (upd))
		{
			errorMessage = db->errorMessage();
			return false;
		}

		upd =		 " UPDATE te_theme t, te_theme_application ta ";
		upd +=       " SET t.enable_visibility = ta.enable_visibility ";
		upd +=       " WHERE ta.theme_id = t.theme_id ";
		if(!db->execute (upd))
		{
			errorMessage = db->errorMessage();
			return false;
		}
			
		db->deleteColumn("te_theme_application", "visible_rep");
		db->deleteColumn("te_theme_application", "enable_visibility");
	}

	//if for ADO passar todas as tabelas para aceitar comprimento iguel a zero!!!
	if(db->dbmsName() == "Ado")
	{
		//te_layer 
		//te_layer_table
		db->allowEmptyString ("te_layer_table", "attr_initial_time");
		db->allowEmptyString ("te_layer_table", "attr_final_time");
		db->allowEmptyString ("te_layer_table", "user_name");

		//te_representation
		db->allowEmptyString ("te_representation", "description");
		
		//te_view
		db->allowEmptyString ("te_view", "user_name");

		//te_visual
		db->allowEmptyString ("te_visual", "lib_name");
		db->allowEmptyString ("te_visual", "contour_lib_name");
		db->allowEmptyString ("te_visual", "family");

		//te_legend
		db->allowEmptyString ("te_legend", "lower_value");
		db->allowEmptyString ("te_legend", "upper_value");
		db->allowEmptyString ("te_legend", "label");
		
		//te_theme
		db->allowEmptyString ("te_theme", "generate_attribute_where");
		db->allowEmptyString ("te_theme", "generate_spatial_where");
		db->allowEmptyString ("te_theme", "generate_temporal_where");
		db->allowEmptyString ("te_theme", "collection_table");

		//te_grouping
		db->allowEmptyString ("te_grouping", "grouping_attr");
		db->allowEmptyString ("te_grouping", "grouping_norm_attr");
		db->allowEmptyString ("te_grouping", "grouping_function");

		//te_theme_application
		db->allowEmptyString ("te_theme_application", "refine_attribute_where");
		db->allowEmptyString ("te_theme_application", "refine_spatial_where");
		db->allowEmptyString ("te_theme_application", "refine_temporal_where");
		db->allowEmptyString ("te_theme_application", "grouping_color");
		db->allowEmptyString ("te_theme_application", "pie_dimension_attr");
		db->allowEmptyString ("te_theme_application", "text_table");
		db->allowEmptyString ("te_theme_application", "chart_function");
	}

	//------------ auxiliary collection  
	TeDatabasePortal* portal = db->getPortal();
	if(!portal)
		return false;

	string sql = " SELECT theme_id, visible_rep FROM te_theme ";
	if(!portal->query(sql))
	{
		delete portal;
		return true;
	}

	while(portal->fetchRow ())
	{
		string	themeId = portal->getData(0);
		int		visRep  = atoi(portal->getData(1));

		string collExtTable = "te_collection_"+ themeId +"_aux";
		
		if	((db->tableExist("te_collection_"+ themeId)) && 
			((visRep & TeRASTER) != TeRASTER)			 && 
			(!db->tableExist(collExtTable)))
		{
			TeTheme* theme = new TeTheme();
			theme->id(atoi(themeId.c_str()));
			if(!db->loadTheme (theme))
			{
				delete portal;
				return false;
			}

			string up = "UPDATE " + theme->collectionTable() + " SET c_object_status = 0";
			up += " WHERE c_object_status <> " + Te2String(theme->pointingLegend().id());
			up += " AND c_object_status <> " + Te2String(theme->queryLegend().id());
			up += " AND c_object_status <> " + Te2String(theme->queryAndPointingLegend().id());
			db->execute(up);

			up = "UPDATE " + theme->collectionTable() + " SET c_object_status = 1";
			up += " WHERE c_object_status = " + Te2String(theme->pointingLegend().id());
			db->execute(up);

			up = "UPDATE " + theme->collectionTable() + " SET c_object_status = 2";
			up += " WHERE c_object_status = " + Te2String(theme->queryLegend().id());
			db->execute(up);

			up = "UPDATE " + theme->collectionTable() + " SET c_object_status = 3";
			up += " WHERE c_object_status = " + Te2String(theme->queryAndPointingLegend().id());
			db->execute(up);

			if ((!theme->createCollectionAuxTable()) || (!theme->populateCollectionAux())) 
			{
				errorMessage = "Fail to mount the auxiliary table of the collection!\n";
				errorMessage += db->errorMessage();
				delete portal;
				return false;
			}

			theme->collectionAuxTable(collExtTable);
			theme->addThemeTable(collExtTable);
					
			string oldTCE = theme->collectionTable() + "_ext";
			if (db->tableExist(oldTCE))
			{
				string delTable = "DROP TABLE " + oldTCE;
				db->execute(delTable);
			}
		}
		
	}
	//------------ end auxiliary collection  

	portal->freeResult();

	//------------ text table  
	// if text table have not text visual table associated, create it
	string sel = "SELECT geom_table FROM te_representation WHERE";
	sel += " geom_type = " + Te2String(TeTEXT);
	if(portal->query(sel))
	{
		while(portal->fetchRow())
		{
			string table = portal->getData(0);
			string tvis = table + "_txvisual";
			if(!db->tableExist(tvis))
			{
				TeAttributeList atl;
				TeAttribute		at;

				at.rep_.name_ = "geom_id";
				at.rep_.type_ = TeINT;
				at.rep_.numChar_ = 0;
				at.rep_.isPrimaryKey_ = true;
				atl.push_back(at);

				at.rep_.isPrimaryKey_ = false;
				at.rep_.name_ = "dot_height";
				at.rep_.type_ = TeINT;
				atl.push_back(at);

				at.rep_.name_ = "fix_size";
				at.rep_.type_ = TeINT;
				atl.push_back(at);

				at.rep_.name_ = "color";
				at.rep_.type_ = TeINT;
				atl.push_back(at);

				at.rep_.name_ = "family";
				at.rep_.type_ = TeSTRING;
				at.rep_.numChar_ = 128;
				atl.push_back(at);

				at.rep_.name_ = "bold";
				at.rep_.type_ = TeINT;
				at.rep_.numChar_ = 0;
				atl.push_back(at);

				at.rep_.name_ = "italic";
				at.rep_.type_ = TeINT;
				atl.push_back(at);

				db->createTable(tvis, atl);
				string fk = "fk_" + tvis;
				db->createRelation(fk, tvis, "geom_id", table, "geom_id", true);
				string ins = "INSERT INTO " + tvis + " (geom_id) SELECT geom_id FROM " + table;
				db->execute(ins);

				string popule = "UPDATE " + tvis;
				popule += " SET dot_height = 12";
				popule += ", fix_size = 0";
				popule += ", color = 16711680";
				popule += ", family = 'verdana'";
				popule += ", bold = 1";
				popule += ", italic = 0";
				if(!db->execute(popule))
				{
					errorMessage = "Fail to generate the text visual table!\n";
					errorMessage += db->errorMessage();
					delete portal;
					return false;;
				}
			}
		}
	}
	//------------ end text table  
	delete portal;
	return true;
}
bool TeExportPolygonSet2SHP( const TePolygonSet& ps,const std::string& base_file_name  )
{
    // creating files names
    std::string dbfFilename = base_file_name + ".dbf";
    std::string shpFilename = base_file_name + ".shp";

    // creating polygons attribute list ( max attribute size == 25 )
    TeAttributeList attList;
    TeAttribute at;
    at.rep_.type_ = TeSTRING;               //the id of the cell
    at.rep_.numChar_ = 25;
    at.rep_.name_ = "object_id_";
    at.rep_.isPrimaryKey_ = true;
	attList.push_back(at);
    
    /* DBF output file handle creation */
	DBFHandle hDBF = TeCreateDBFFile (dbfFilename, attList);
	if ( hDBF == 0 )
		return false;
    
    /* SHP output file handle creation */
    SHPHandle hSHP = SHPCreate( shpFilename.c_str(), SHPT_POLYGON );
    if( hSHP == 0 ) 
	{
      DBFClose( hDBF );
      return false;
    }
    
    /* Writing polygons */
    int iRecord = 0;
    int totpoints = 0;
    double  *padfX, *padfY;
    SHPObject       *psObject;
    int posXY, npoints, nelem;
    int nVertices;
    int* panParts;

    TePolygonSet::iterator itps;
    TePolygon poly;

    for (itps = ps.begin() ; itps != ps.end() ; itps++ ) {
      poly=(*itps);
      totpoints = 0;
      nVertices = poly.size();
      for (unsigned int n=0; n<poly.size();n++) {
        totpoints += poly[n].size();
      }

      panParts = (int *) malloc(sizeof(int) * nVertices);
      padfX = (double *) malloc(sizeof(double) * totpoints);
      padfY = (double *) malloc(sizeof(double) * totpoints);
      posXY = 0;
      nelem = 0;
      
      for (unsigned int l=0; l<poly.size(); ++l) {
        if (l==0) {
          if (TeOrientation(poly[l]) == TeCOUNTERCLOCKWISE) {
            TeReverseLine(poly[l]);
          }
        } else {
          if (TeOrientation(poly[l]) == TeCLOCKWISE) {
            TeReverseLine(poly[l]);
          }
        }
        
        npoints = poly[l].size();
        panParts[nelem]=posXY;
        
        for (int m=0; m<npoints; m++ ) {
          padfX[posXY] = poly[l][m].x_;
          padfY[posXY] = poly[l][m].y_;
          posXY++;
        }
        nelem++;
      }
                
      psObject = SHPCreateObject( SHPT_POLYGON, -1, nelem, panParts, NULL,
        posXY, padfX, padfY, NULL, NULL );
        
      int shpRes = SHPWriteObject( hSHP, -1, psObject );
      if (shpRes == -1 )
	  {
	      DBFClose( hDBF );
		  SHPClose( hSHP );
		  return false;
	  }
        
      SHPDestroyObject( psObject );
      free( panParts );
      free( padfX );
      free( padfY );

      // writing attributes - same creation order
      DBFWriteStringAttribute(hDBF, iRecord, 0, poly.objectId().c_str() );
            
      iRecord++;
    }
    
    DBFClose( hDBF );
    SHPClose( hSHP );
    return true;  
}
bool
TeExportQuerierToShapefile(TeQuerier* querier, const std::string& base)
{
	// check initial conditions
	if (!querier)
		return false;

	if (!querier->loadInstances())
		return false;

	// Get the list of attributes defined by the input querier
	bool onlyObjId = false;
	TeAttributeList qAttList = querier->getAttrList();
	if (qAttList.empty())
	{
		TeAttributeList qAttList;
		TeAttribute at;
		at.rep_.type_ = TeSTRING;               
		at.rep_.numChar_ = 100;
		at.rep_.name_ = "ID";
		at.rep_.isPrimaryKey_ = true;
		qAttList.push_back(at);
		onlyObjId = true;
	}

	// Handles to each type of geometries that will be created if necessary
	DBFHandle hDBFPol = 0;
	SHPHandle hSHPPol = 0;
	DBFHandle hDBFLin = 0;
	SHPHandle hSHPLin = 0;
	DBFHandle hDBFPt = 0;
	SHPHandle hSHPPt = 0;

	// Some auxiliary variables
    int totpoints;
    double*	padfX;
	double*	padfY;
    unsigned int nVertices;
    int* panPart;
    SHPObject *psObject;
    unsigned int posXY, npoints, nelem;
	int shpRes;

	// progress information
	if (TeProgress::instance())
		TeProgress::instance()->setTotalSteps(querier->numElemInstances());
	clock_t	t0, t1, t2;
	t2 = clock();
	t0 = t1 = t2;
	int dt = CLOCKS_PER_SEC/2;
	int dt2 = CLOCKS_PER_SEC; //* .000001;

	// Loop through the instances writting their geometries and attributes
	unsigned int iRecPol=0, iRecLin=0, iRecPt=0;
	unsigned int n, l, m;
	unsigned int nIProcessed = 0;
	TeSTInstance st;
	while(querier->fetchInstance(st))
	{
		totpoints = 0;
		nVertices = 0;
		if (st.hasPolygons())
		{
			TePolygonSet& polSet = st.getPolygons();
			TePolygonSet::iterator itps;
			int nVerticesCount = 0;
			for (itps = polSet.begin(); itps != polSet.end(); ++itps) 
			{
				nVertices = (*itps).size();
				nVerticesCount += nVertices;
				for (n=0; n<nVertices;++n) 
					totpoints += (*itps)[n].size();
			}

			panPart = (int *) malloc(sizeof(int) * nVerticesCount);
			padfX = (double *) malloc(sizeof(double) * totpoints);
			padfY = (double *) malloc(sizeof(double) * totpoints);

			posXY = 0;
			nelem = 0;
			for (itps = polSet.begin(); itps != polSet.end(); ++itps) 
			{
				TePolygon poly = *itps;
				for (l=0; l<poly.size(); ++l) 
				{
					if (l==0) 
					{
						if (TeOrientation(poly[l]) == TeCOUNTERCLOCKWISE) 
							TeReverseLine(poly[l]);
					}
					else 
					{
						if (TeOrientation(poly[l]) == TeCLOCKWISE)
							TeReverseLine(poly[l]);
					}
					npoints = poly[l].size();
					panPart[nelem]=posXY;
        
					for (m=0; m<npoints; ++m) 
					{
						padfX[posXY] = poly[l][m].x_;
						padfY[posXY] = poly[l][m].y_;
						posXY++;
					}
					nelem++;
				}
			}
			psObject = SHPCreateObject(SHPT_POLYGON, -1, nelem, panPart, NULL, posXY, padfX, padfY, NULL, NULL);
			if (hSHPPol == 0)
			{
				string fname = base + "_pol.shp";
				hSHPPol = SHPCreate(fname.c_str(), SHPT_POLYGON);
   				assert (hSHPPol != 0);
			}	
			shpRes = SHPWriteObject(hSHPPol, -1, psObject);
			SHPDestroyObject(psObject);
			free(panPart);
			free(padfX);
			free(padfY);
			assert(shpRes != -1);   
			if (hDBFPol == 0)
			{
				hDBFPol = TeCreateDBFFile(base + "_pol.dbf", qAttList);
				assert (hDBFPol != 0);
			}
			if (onlyObjId)
			{
				DBFWriteStringAttribute(hDBFPol, iRecPol, 0, st.objectId().c_str());
			}
			else
			{
				string val;
				for (n=0; n<qAttList.size();++n) 
				{
					st.getPropertyValue(val,n);
					if (qAttList[n].rep_.type_ == TeSTRING || qAttList[n].rep_.type_ == TeDATETIME)
					{
						DBFWriteStringAttribute(hDBFPol, iRecPol, n, val.c_str());
					}
					else if (qAttList[n].rep_.type_ == TeINT)
					{
						DBFWriteIntegerAttribute(hDBFPol, iRecPol, n, atoi(val.c_str()));
					}
					else if (qAttList[n].rep_.type_ == TeREAL)
					{
						DBFWriteDoubleAttribute(hDBFPol, iRecPol, n, atof(val.c_str()));
					}
				}
			}
			++iRecPol;
		}
		if (st.hasCells())
		{
			TeCellSet& cellSet = st.getCells();
			nVertices = cellSet.size();
			totpoints = nVertices*5;
			panPart = (int *) malloc(sizeof(int) * nVertices);
			padfX = (double *) malloc(sizeof(double) * totpoints);
			padfY = (double *) malloc(sizeof(double) * totpoints);
			posXY = 0;
			nelem = 0;
			TeCellSet::iterator itcs;
			for (itcs=cellSet.begin(); itcs!=cellSet.end(); ++itcs)
			{
				panPart[nelem]=posXY;
				padfX[posXY] = (*itcs).box().lowerLeft().x();
				padfY[posXY] = (*itcs).box().lowerLeft().y();
				posXY++;		
				padfX[posXY] = (*itcs).box().upperRight().x();
				padfY[posXY] = (*itcs).box().lowerLeft().y();
				posXY++;		
				padfX[posXY] = (*itcs).box().upperRight().x();
				padfY[posXY] = (*itcs).box().upperRight().y();
				posXY++;		
				padfX[posXY] = (*itcs).box().lowerLeft().x();
				padfY[posXY] = (*itcs).box().upperRight().y();
				posXY++;		
				padfX[posXY] = (*itcs).box().lowerLeft().x();
				padfY[posXY] = (*itcs).box().lowerLeft().y();
				++posXY;	
				++nelem;
			} 
			psObject = SHPCreateObject(SHPT_POLYGON, -1, nelem, panPart, NULL,posXY, padfX, padfY, NULL, NULL);
			if (hSHPPol == 0)
			{
				string fname = base + "_pol.shp";
				hSHPPol = SHPCreate(fname.c_str(), SHPT_POLYGON);
   				assert (hSHPPol != 0);
			}	
			shpRes = SHPWriteObject(hSHPPol, -1, psObject);
			SHPDestroyObject(psObject);
			free(panPart);
			free(padfX);
			free(padfY);
			assert(shpRes != -1);
			if (hDBFPol == 0)
			{
				hDBFPol = TeCreateDBFFile(base + "_pol.dbf", qAttList);
				assert (hDBFPol != 0);
			}

			if (onlyObjId)
			{
				DBFWriteStringAttribute(hDBFPol, iRecPol, 0, st.objectId().c_str());
			}
			else
			{
				string val;
				for (n=0; n<qAttList.size();++n) 
				{
					st.getPropertyValue(val,n);
					if (qAttList[n].rep_.type_ == TeSTRING || qAttList[n].rep_.type_ == TeDATETIME)
					{
						DBFWriteStringAttribute(hDBFPol, iRecPol, n, val.c_str());
					}
					else if (qAttList[n].rep_.type_ == TeINT)
					{
						DBFWriteIntegerAttribute(hDBFPol, iRecPol, n, atoi(val.c_str()));
					}
					else if (qAttList[n].rep_.type_ == TeREAL)
					{
						DBFWriteDoubleAttribute(hDBFPol, iRecPol, n, atof(val.c_str()));
					}
				}
			}
			++iRecPol;
		}
		if (st.hasLines())
		{
			TeLineSet& lineSet = st.getLines();
			nVertices = lineSet.size();
			TeLineSet::iterator itls;
			for (itls=lineSet.begin(); itls!=lineSet.end(); ++itls)
				totpoints += (*itls).size();
			panPart = (int *) malloc(sizeof(int) * nVertices);
			padfX = (double *) malloc(sizeof(double) * totpoints);
			padfY = (double *) malloc(sizeof(double) * totpoints);
			posXY = 0;
			nelem = 0;
			for (itls=lineSet.begin(); itls!=lineSet.end(); ++itls)
			{
				panPart[nelem]=posXY;
				for (l=0; l<(*itls).size(); ++l)
				{
					padfX[posXY] = (*itls)[l].x();
					padfY[posXY] = (*itls)[l].y();
					++posXY;
				}
				++nelem;
			}
			psObject = SHPCreateObject(SHPT_ARC, -1, nVertices, panPart, NULL,	posXY, padfX, padfY, NULL, NULL);
			if (hSHPLin == 0)
			{
				string fname = base + "_lin.shp"; 
				hSHPLin = SHPCreate(fname.c_str(), SHPT_ARC);
   				assert (hSHPLin != 0);
			}		
			shpRes = SHPWriteObject(hSHPLin, -1, psObject);
			SHPDestroyObject(psObject);
			free(panPart);
			free(padfX);
			free(padfY);
			assert(shpRes != -1);
			if (hDBFLin == 0)
			{
				hDBFLin = TeCreateDBFFile(base + "_lin.dbf", qAttList);
				assert (hDBFLin != 0);
			}
			if (onlyObjId)
			{
				DBFWriteStringAttribute(hDBFLin, iRecLin, 0, st.objectId().c_str());
			}
			else
			{
				string val;
				for (n=0; n<qAttList.size();++n) 
				{
					st.getPropertyValue(val,n);
					if (qAttList[n].rep_.type_ == TeSTRING || qAttList[n].rep_.type_ == TeDATETIME)
					{
						DBFWriteStringAttribute(hDBFLin, iRecLin, n, val.c_str());
					}
					else if (qAttList[n].rep_.type_ == TeINT)
					{
						DBFWriteIntegerAttribute(hDBFLin, iRecLin, n, atoi(val.c_str()));
					}
					else if (qAttList[n].rep_.type_ == TeREAL)
					{
						DBFWriteDoubleAttribute(hDBFLin, iRecLin, n, atof(val.c_str()));
					}
				}
			}
			++iRecLin;
		}
		if (st.hasPoints())
		{
			TePointSet& pointSet = st.getPoints();
			nVertices = pointSet.size();
			panPart = (int *) malloc(sizeof(int) * nVertices);
			padfX = (double *) malloc(sizeof(double) * nVertices);
			padfY = (double *) malloc(sizeof(double) * nVertices);
			nelem = 0;
			TePointSet::iterator itpts;
			for (itpts=pointSet.begin(); itpts!=pointSet.end(); ++itpts)
			{
				panPart[nelem] = nelem;
				padfX[nelem] = (*itpts).location().x();
				padfY[nelem] = (*itpts).location().y();
				++nelem;
			}
			psObject = SHPCreateObject(SHPT_POINT, -1, nVertices, panPart, NULL, nVertices, padfX, padfY, NULL, NULL );
			if (hSHPPt == 0)
			{
				string fname = base + "_pt.shp";
				hSHPPt = SHPCreate(fname.c_str(), SHPT_POINT);
   				assert (hSHPPt != 0);
			}		
			shpRes = SHPWriteObject(hSHPPt, -1, psObject);
			SHPDestroyObject(psObject);
			free(panPart);
			free(padfX);
			free(padfY);
			assert(shpRes != -1);
			if (hDBFPt == 0)
			{
				hDBFPt = TeCreateDBFFile(base + "_pt.dbf", qAttList);
				assert (hDBFPt != 0);
			}
			if (onlyObjId)
			{
				DBFWriteStringAttribute(hDBFPt, iRecPt, 0, st.objectId().c_str());
			}
			else
			{
				string val;
				for (n=0; n<qAttList.size();++n) 
				{
					st.getPropertyValue(val,n);
						if (qAttList[n].rep_.type_ == TeSTRING || qAttList[n].rep_.type_ == TeDATETIME)
					{
						DBFWriteStringAttribute(hDBFPt, iRecPt, n, val.c_str());
					}
					else if (qAttList[n].rep_.type_ == TeINT)
					{
						DBFWriteIntegerAttribute(hDBFPt, iRecPt, n, atoi(val.c_str()));
					}
					else if (qAttList[n].rep_.type_ == TeREAL)
					{
						DBFWriteDoubleAttribute(hDBFPt, iRecPt, n, atof(val.c_str()));
					}
				}
			}
			++iRecPt;
		}
		++nIProcessed;
		if (TeProgress::instance() && int(t2-t1) > dt)
		{
			t1 = t2;
			if(((int)(t2-t0) > dt2))
			{
				if (TeProgress::instance()->wasCancelled())
					break;
				else
					TeProgress::instance()->setProgress(nIProcessed);
			}
		}

	}
	if (hDBFPol != 0)
		DBFClose(hDBFPol);
	if (hSHPPol != 0)
        SHPClose(hSHPPol);
	if (hDBFLin != 0)
		DBFClose(hDBFLin);
	if (hSHPLin != 0)
        SHPClose(hSHPLin);
	if (hDBFPt != 0)
		DBFClose(hDBFPt);
	if (hSHPPt != 0)
        SHPClose(hSHPPt);

	if (TeProgress::instance())
		TeProgress::instance()->reset();
	return true;
}
void VoronoiWindow::okPushButton_clicked()
{
    std::string layerName = layerNameLineEdit->text().utf8();	
	if(layerName.empty())
	{
		QMessageBox::information(this, tr("Information"), tr("Please, define a name to result Layer."));
        voronoiTabWidget->setCurrentPage(0);
        layerNameLineEdit->setFocus();
		return;
	}

    std::string layerLinesName;
    if(generateLinesCheckBox->isChecked())
    {
        layerLinesName = layerLinesLineEdit->text().ascii();
        if(layerLinesName.empty())
	    {
		    QMessageBox::information(this, tr("Information"), tr("Please, define a name to Layer of Lines."));
            voronoiTabWidget->setCurrentPage(1);
            layerLinesLineEdit->setFocus();
		    return;
	    }
    }

    if(!isLayerNameValid(layerName))
    {
        voronoiTabWidget->setCurrentPage(0);
        layerNameLineEdit->setFocus();
        return;
    }

    if(!isLayerNameValid(layerLinesName))
    {
        voronoiTabWidget->setCurrentPage(1);
        layerLinesLineEdit->setFocus();
        return;
    }

    if(layerName == layerLinesName)
    {
        QMessageBox::information(this, tr("Information"), tr("Please, define names differents to Layer result and Layer of Lines."));
	    return;
    }

	TeDatabase* db = plugin_params_->getCurrentDatabasePtr();
    TeTheme* theme = getTheme(themeComboBox->currentText().latin1());
	if(theme == 0)
	{
		QMessageBox::critical(this, tr("Error"), tr("Error getting the input Theme."));
		return;
	}
    
    TePrecision::instance().setPrecision(TeGetPrecision(theme->layer()->projection()));
    
    TeTheme *themeDelimiter = getTheme(boxComboBox->currentText().latin1());
    if(themeDelimiter == 0)
    {
        QMessageBox::critical(this, tr("Error"), tr("Error getting the delimiter Layer."));
		return;
    }

    // Verifies is the box chosen is valid
    TeBox b = themeDelimiter->layer()->box();
    TeProjection* projFrom = themeDelimiter->layer()->projection();
    TeProjection* projTo = theme->layer()->projection();
    if(!((*projFrom) == (*projTo))) // need remap?
        b = TeRemapBox(b, projFrom, projTo);

    TeBox& inputBox = theme->layer()->box();
    if(!TeIntersects(b, inputBox))
    {
        QMessageBox::information(this, tr("Information"), tr("The box chosen do not intercepts the input Theme. Please, try another."));
        voronoiTabWidget->setCurrentPage(1);
        boxComboBox->setFocus();
        return;
    }
    
    //preparing to read the layer
    bool loadAllAttributes=false;
    if (diagramType==MWVoronoi) loadAllAttributes = true;
    bool loadGeometries = true;
    TeQuerierParams querierParams(loadGeometries, loadAllAttributes);
    querierParams.setParams(theme->layer());
    TeQuerier  querier(querierParams);
    querier.loadInstances();
    //finding weight's attribute
    TeAttributeList attrList = querier.getAttrList();
    int weightAttrN=0;
    if (diagramType==MWVoronoi) {
        for (std::vector<TeAttribute>::iterator i=attrList.begin(); i!=attrList.end();++i) {
            if (weightComboBox->currentText()==i->rep_.name_) {
                break;
            }
            weightAttrN++;
        }    
    }
    int n=querier.numElemInstances();

    if(n==0)
    {
        QMessageBox::critical(this, tr("Error"), tr("Error getting the points of input Theme."));
        return;
    }

    TeWaitCursor wait;

    // Converts x,y to a float array in order to pass to VoronoiDiagramGenerator class
    float* x = new float[n];
	float* y = new float[n];
    //pointers for weighted voronoi
    float* w;
    int numPoints;
    w= new float[n];
    numPoints = 0;
    TeSTInstance sti;
    string peso;
    //TePoint pointBefore(0,0);
    while(querier.fetchInstance(sti)) { // for each point
        // Stores on float array
        if(sti.hasPoints())
            {
                TePointSet pointSet;
                //reading geometry
                sti.getGeometry(pointSet);
                x[numPoints] = pointSet[0].location().x();
                y[numPoints] = pointSet[0].location().y();
    
                //reading weight
                if (diagramType==MWVoronoi) {
                    stringstream ss;
                    sti.getPropertyValue(peso,weightAttrN);
                    ss<<peso;
                    ss>>w[numPoints];
                }                    
                numPoints++;
            }
bool updateDB310To311(TeDatabase* db, string& errorMessage)
{
	string sql = " SELECT collection_table FROM te_theme ";
	TeDatabasePortal* portal = db->getPortal();
	if(!portal)
		return false;

	if(!portal->query(sql))
	{
		delete portal;
		return false;
	}

	while(portal->fetchRow())
	{
		string tableName = portal->getData(0);
		if(!db->tableExist(tableName+"_aux"))
			continue;

		TeDatabasePortal* portal2 = db->getPortal();
		if(!portal2)
		{
			delete portal;
			return false;
		}

		sql = " SELECT * FROM "+ tableName+"_aux WHERE 1=2";
		if(!portal2->query(sql))
		{
			delete portal;
			delete portal2;
			return false;
		}

		TeAttributeList attrList;
		for(int i=0; i<portal2->numFields(); ++i)
		{
      TeAttribute attr = portal2->getAttribute(i);
      attr.rep_.isPrimaryKey_= false;
			if(TeConvertToUpperCase(portal2->getAttribute(i).rep_.name_) != "UNIQUE_ID" )
				attrList.push_back(attr);
		}

        delete portal2;

		//add new autonumber column
		TeAttribute attr;
		attr.rep_.name_= "unique_id" ;
		attr.rep_.type_= TeINT;
		attr.rep_.isAutoNumber_ = true;
		attr.rep_.isPrimaryKey_ = true;
		attrList.push_back(attr);
		
		//create new table 
		if(!db->createTable(tableName+"_aux2", attrList))
		{
			errorMessage = "Error creating table "+ tableName+"_aux2 !\n";
			errorMessage += db->errorMessage();
			delete portal;
			return false;
		}

		//insert records
		string ins = " INSERT INTO "+ tableName +"_aux2 ( ";
		string ins2 ="";
		for(unsigned int j=0; j<(attrList.size()-1); ++j)
		{
			if(j>0)
				ins2 += ",";
			ins2 += attrList[j].rep_.name_;
		}
		ins += ins2 +" ) SELECT "+ ins2;
		ins += " FROM "+ tableName+"_aux";
		if(!db->execute(ins))
		{
			errorMessage = "Error inserting table "+ tableName+"_aux2 !\n";
			errorMessage += db->errorMessage();
			delete portal;
			return false;
		}

		sql = " DROP TABLE "+ tableName+"_aux";
		if(db->tableExist(tableName+"_aux"))
		{
			if(!db->execute(sql))
			{
				errorMessage = "Error dropping table "+ tableName+"_aux2 !\n";
				errorMessage += db->errorMessage();
				delete portal;
				return false;
			}
		}
		
		if(!db->alterTable(tableName+"_aux2", tableName+"_aux"))
		{
			errorMessage = "Error renaming table "+ tableName+"_aux2 !\n";
			errorMessage += db->errorMessage();
			delete portal;
			return false;
		}
	}

	delete portal;
	return true;
}
bool TeSQLite::createTable(const string& table, TeAttributeList &attr)
{
	errorMessage_ = "";

	bool first = true;

	TeAttributeList::iterator it = attr.begin();
	
	string createTable ="CREATE TABLE " + table +" (";
	
	string type;

	string pkeys;

	while(it != attr.end())
	{
		switch ((*it).rep_.type_)
		{
			case TeSTRING:		type = "TEXT";
								break;

			case TeREAL:		type = "REAL";
								break;

			case TeINT:
			case TeUNSIGNEDINT:
								type = "INTEGER";
								break;

			case TeBLOB:		//type = "OID";
				                type = "BLOB";
								break;

			case TeDATETIME:	type = "NUMERIC";
								break;

			case TeCHARACTER:	type = "TEXT";
								break;

			case TeBOOLEAN:		type = "NUMERIC";
								break;

			case TePOINTTYPE:
			case TePOINTSETTYPE:
								if(!first)
									createTable += ", ";
								else
									first = false;

								createTable += " x		      REAL        DEFAULT 0.0,";
								createTable += " y            REAL        DEFAULT 0.0 ";
								++it;
								continue;

			case TeLINE2DTYPE:
			case TeLINESETTYPE:
							if(!first)
								createTable += ", ";
							else
								first = false;

							createTable += "lower_x REAL not null ,";
							createTable += "lower_y REAL not null ,";
							createTable += "upper_x REAL not null ,";
							createTable += "upper_y REAL not null ,";
							createTable += "spatial_data BLOB not null ";
							++it;
							continue;

			case TePOLYGONTYPE:
			case TePOLYGONSETTYPE:
							if(!first)
								createTable += ", ";
							else
								first = false;							

							createTable += "lower_x REAL not null ,";
							createTable += "lower_y REAL not null ,";
							createTable += "upper_x REAL not null ,";
							createTable += "upper_y REAL not null ,";
							createTable += "spatial_data BLOB not null ";

							++it;
							continue;

			case TeCELLTYPE:
			case TeCELLSETTYPE:
							if(!first)
								createTable += ", ";
							else
								first = false;

							createTable += "lower_x REAL not null ,";
							createTable += "lower_y REAL not null ,";
							createTable += "upper_x REAL not null ,";
							createTable += "upper_y REAL not null ,";
							createTable += " col_number   INTEGER      NOT NULL,";
							createTable += " row_number	  INTEGER      NOT NULL ";
							++it;
							continue;					

			case TeRASTERTYPE:
							if(!first)
								createTable += ", ";
							else
								first = false;

							createTable += "lower_x REAL not null ,";
							createTable += "lower_y REAL not null ,";
							createTable += "upper_x REAL not null ,";
							createTable += "upper_y REAL not null ,";
							createTable += "band_id integer unsigned not null, ";
							createTable += "resolution_factor integer unsigned , ";
							createTable += "subband integer unsigned,";
							createTable += "spatial_data BLOB NOT NULL, ";
							createTable += "block_size integer unsigned not null ";
		   					++it;
							continue;

			case TeNODETYPE:
			case TeNODESETTYPE:
							if(!first)
								createTable += ", ";
							else
								first = false;

							createTable += " x		    REAL        DEFAULT 0.0,";
							createTable += " y          REAL        DEFAULT 0.0 ";
							++it;
							continue;

			case TeTEXTTYPE:
			case TeTEXTSETTYPE:

			default:			type += "TEXT";
								break;
		}

		if(!((*it).rep_.defaultValue_.empty()))
			type += " DEFAULT '" + (*it).rep_.defaultValue_ + "' ";

		if(!((*it).rep_.null_))
			type += " NOT NULL ";
		
		if(!first)
			createTable += ",  ";
		else
			first = false;

		createTable += (*it).rep_.name_ + " ";
		createTable += type;

		// check if column is part of primary key
		if((*it).rep_.isPrimaryKey_ && (*it).rep_.type_ != TeBLOB )
		{
			if(!pkeys.empty())
				pkeys += ", ";
			
			pkeys += (*it).rep_.name_;
		}

		++it;
	}

	if(!pkeys.empty())
	{	string pk = ", PRIMARY KEY(";
	           pk += pkeys;
			   pk += ")";

		createTable += pk;
	}

	createTable += ");";

	return execute(createTable);
}