TeDatabase.cpp

Go to the documentation of this file.
00001 /************************************************************************************
00002 TerraLib - a library for developing GIS applications.
00003 Copyright � 2001-2007 INPE and Tecgraf/PUC-Rio.
00004 
00005 This code is part of the TerraLib library.
00006 This library is free software; you can redistribute it and/or
00007 modify it under the terms of the GNU Lesser General Public
00008 License as published by the Free Software Foundation; either
00009 version 2.1 of the License, or (at your option) any later version.
00010 
00011 You should have received a copy of the GNU Lesser General Public
00012 License along with this library.
00013 
00014 The authors reassure the license terms regarding the warranties.
00015 They specifically disclaim any warranties, including, but not limited to,
00016 the implied warranties of merchantability and fitness for a particular purpose.
00017 The library provided hereunder is on an "as is" basis, and the authors have no
00018 obligation to provide maintenance, support, updates, enhancements, or modifications.
00019 In no event shall INPE and Tecgraf / PUC-Rio be held liable to any party for direct,
00020 indirect, special, incidental, or consequential damages arising out of the use
00021 of this library and its documentation.
00022 *************************************************************************************/
00023 
00024 #include "TeDatabase.h"
00025 #include "TeDecoderDatabase.h"
00026 #include "TeGeometryAlgorithms.h"
00027 #include "TeSpatialOperations.h"
00028 #include "TeImportRaster.h"
00029 #include "TeLayer.h"
00030 #include "TeAbstractTheme.h"
00031 #include "TeExternalTheme.h"
00032 #include "TeDatabaseFactoryParams.h"
00033 #include "TeRasterTransform.h"
00034 #include "TeTimeInterval.h"
00035 #include "TeDBConnectionsPool.h"
00036 
00037 #include <sys/stat.h>
00038 #include <stdio.h>
00039 #include <sstream>
00040 
00041 #include <string.h>
00042 
00043 typedef map<int,TeNode> TeNodeMap;
00044 
00045 static const int scales [] =
00046 {       150000,
00047         80000,
00048         40000,
00049         20000,
00050         10000,
00051         3000,
00052         1500,
00053         800,
00054         400,
00055         200,
00056         100,
00057         30,
00058         15,
00059         8,
00060         4,
00061         2,
00062         1
00063 };
00064 
00065 //-*********************
00066 
00067 TeDatabase::TeDatabase() :
00068         isConnected_ (false),
00069         host_(""),
00070         user_(""),
00071         password_(""),
00072         database_(""),
00073         portNumber_(-1),
00074         errorNumber_(0),
00075         errorMessage_(""),
00076         transactionCounter_(0)
00077 {
00078         metaModel_.reset(new TeMetaModelCache);
00079 }
00080 
00081 TeDatabase& TeDatabase::operator=(const TeDatabase& other)
00082 {
00083         if(this != &other)
00084                 metaModel_ = other.metaModel_;  
00085 
00086         return *this;
00087 }
00088 
00089 TeDatabase::~TeDatabase()
00090 {
00091 }
00092 
00093 void TeDatabase::setConnection(TeConnection* c)
00094 {
00095         user_ = "";
00096     host_ = "";
00097     database_ = "";
00098     dbmsName_ = "";
00099     password_ = "";
00100     portNumber_ = -1;
00101 
00102         if(c != 0)
00103         {
00104                 user_ = c->getUser();
00105                 host_ = c->getHost();
00106                 database_ = c->getDatabaseName();
00107                 dbmsName_ = c->getDBMS();
00108                 password_ = c->getPassword();
00109                 portNumber_ = c->getPortNumber();
00110         }
00111 }
00112 
00113 TeConnection* TeDatabase::getConnection()
00114 {
00115     return 0;
00116 }
00117 
00118 string
00119 TeDatabase::getDatabaseDescription()
00120 {
00121     std::stringstream desc;
00122     const char sep = ';';
00123 
00124     desc << dbmsName_;
00125     desc << sep << host_;
00126     desc << sep << portNumber_;
00127     desc << sep << database_;
00128     desc << sep << user_;
00129     desc << sep << password_;
00130 
00131     return desc.str();
00132 } 
00133 
00134 void TeDatabase::alterTableInfoInMemory(const string& updatedTableName, string oldTableName)
00135 {
00136         //update table in memory
00137         TeTable updatedTable(updatedTableName);
00138         loadTableInfo(updatedTable);
00139         if(oldTableName.empty())
00140                 oldTableName = updatedTableName;
00141 
00142         TeLayerMap::iterator itLayer = metaModel_->layerMap().begin();
00143         while(itLayer!=metaModel_->layerMap().end())
00144         {
00145                 TeAttrTableVector::iterator itAttr = itLayer->second->attrTables().begin();
00146                 while(itAttr!=itLayer->second->attrTables().end())
00147                 {
00148                         if(TeConvertToUpperCase(itAttr->name())==TeConvertToUpperCase(oldTableName))
00149                         {
00150                                 (*itAttr)=updatedTable;
00151                                 break;
00152                         }
00153                         ++itAttr;
00154                 }
00155                 ++itLayer;
00156         }
00157         TeThemeMap::iterator itTheme = metaModel_->themeMap().begin();
00158         while(itTheme!=metaModel_->themeMap().end())
00159         {
00160                 if(itTheme->second->getProductId() != TeTHEME)
00161                 {
00162                         ++itTheme; 
00163                         continue;
00164                 }
00165 
00166                 TeTheme* theme = static_cast<TeTheme*>(itTheme->second);
00167                                 
00168                 TeAttrTableVector::iterator itAttr = theme->attrTables().begin();
00169                 while(itAttr!=theme->attrTables().end())
00170                 {
00171                         if(TeConvertToUpperCase(itAttr->name())==TeConvertToUpperCase(oldTableName))
00172                         {
00173                                 (*itAttr)=updatedTable;
00174                                 theme->loadAliasVector();
00175                                 theme->loadAttrLists();
00176                                 theme->loadTablesJoin(); 
00177                                 break;
00178                         }
00179                         ++itAttr;
00180                 }
00181                 ++itTheme;
00182         }
00183         return;
00184 }
00185 
00186 bool TeDatabase::validTable (TeTable& table)
00187 {
00188         int cont=0;
00189         bool change = false;
00190         bool changeTable = false;
00191         bool uniqueName, linkName; 
00192         
00193         TeAttributeList::iterator it = table.attributeList().begin();
00194         TeAttributeList::iterator it2;  
00195         while(it != table.attributeList().end())
00196         {
00197                 uniqueName = false;
00198                 linkName = false;
00199 
00200                 if((*it).rep_.name_==table.uniqueName())
00201                         uniqueName=true;
00202                 
00203                 if((*it).rep_.name_==table.linkName())
00204                         linkName=true;
00205 
00206                 string errorMess;
00207                 string temp = TeCheckName((*it).rep_.name_, change, errorMess);
00208                 
00209                 if(change)
00210                 {
00211                         it2 = table.attributeList().begin();
00212                         while(it2!=table.attributeList().end())
00213                         {
00214                                 if(temp==(*it2).rep_.name_)
00215                                 {
00216                                         temp += Te2String(cont);
00217                                         it2 = table.attributeList().begin();
00218                                         ++cont;
00219                                 }
00220                                 else
00221                                         ++it2;
00222                         }
00223 
00224                         changeTable = true;
00225                 }
00226 
00227                 if(change && uniqueName)
00228                         table.setUniqueName(temp);
00229                 if(change && linkName)
00230                         table.setLinkName (temp);
00231 
00232                 (*it).rep_.name_ = temp;
00233                 ++it;
00234                 ++cont;
00235         }
00236         
00237         return changeTable;
00238 }
00239 
00240 string TeDatabase::getTableName(int tableId)
00241 {
00242         string tableName;
00243 
00244         TeDatabasePortal* pt = getPortal();
00245         string q = "SELECT attr_table FROM te_layer_table";
00246         q += " WHERE table_id = " + Te2String(tableId);
00247         if (pt->query(q) == true && pt->fetchRow())
00248                 tableName = pt->getData("attr_table");
00249         delete pt;
00250         return tableName;
00251 }
00252 
00253 bool
00254 TeDatabase::deleteTable (const string& table)
00255 {
00256 //      int f = table.find ("te_collection", std::string::npos);
00257         int f = table.find ("te_collection");
00258 
00259         if( table=="te_theme" ||
00260                 table=="te_layer" ||
00261                 table=="te_representation" ||
00262                 table=="te_tables_relation" ||
00263                 table=="te_layer_table" ||
00264                 table=="te_raster_metadata" ||
00265                 table=="te_datum" ||
00266                 table=="te_projection" ||
00267                 table=="te_view" ||
00268                 table=="te_legend" ||
00269                 table=="te_visual" ||
00270                 table=="te_database" ||
00271                 f == 0)
00272         {
00273                 errorMessage_ = "Não é possível deletar tabelas do modelo!";
00274                 return false;
00275         }
00276 
00277         string del = "DROP TABLE " + table;
00278         if(tableExist(table))
00279         {
00280                 if(!execute(del))
00281                         return false;
00282         }
00283 
00284         return true;
00285 }
00286 
00287 
00288 bool 
00289 TeDatabase::deleteColumn (const string& table, const string& colName)
00290 {
00291         if(!tableExist(table))
00292                 return false;
00293         TeAttribute attr;
00294         if (!columnExist(table,colName,attr))
00295                 return true;
00296         string drop = "ALTER  TABLE "+ table +" DROP COLUMN "+ colName;
00297         if(execute(drop) == false)
00298                 return false;
00299 
00300         string tableId;
00301         TeDatabasePortal* portal = getPortal();
00302         string sql = "SELECT table_id FROM te_layer_table WHERE attr_table = '" + table + "'";
00303         if(portal->query(sql) && portal->fetchRow())
00304                 tableId = portal->getData(0);
00305 
00306         delete portal;
00307         if(tableId.empty() == false)
00308         {
00309                 // delete relation
00310                 sql = "DELETE FROM te_tables_relation WHERE (related_table_id = " + tableId;
00311                 sql += " AND related_attr = '" + colName + "')";
00312                 sql += " OR (external_table_name = '" + table + "'";
00313                 sql += " AND external_attr = '" + colName + "')";
00314                 if(execute(sql) == false)
00315                         return false;
00316 
00317                 // delete grouping
00318                 TeDatabasePortal* portal = getPortal();
00319                 sql = "SELECT theme_id FROM te_grouping WHERE grouping_attr = '" + table + "." + colName + "'";
00320                 if(portal->query(sql) && portal->fetchRow())
00321                 {
00322                         string themeId = portal->getData(0);
00323 
00324                         sql = "DELETE FROM te_legend WHERE theme_id = " + themeId + " AND group_id >= 0";
00325                         if(execute(sql) == false)
00326                         {
00327                                 delete portal;
00328                                 return false;
00329                         }
00330                 }
00331                 delete portal;
00332 
00333                 sql = "DELETE FROM te_grouping";
00334                 sql += " WHERE grouping_attr = '" + table + "." + colName + "'";
00335                 if(execute(sql) == false)
00336                         return false;
00337         }
00338         alterTableInfoInMemory(table);
00339         return true;
00340 }
00341 
00342 bool 
00343 TeDatabase::defineIntegrity(void)
00344 {
00345         if (existRelation("te_layer","fk_layer_proj_id") == TeNoRelation )
00346                 if (!createRelation("fk_layer_proj_id", "te_layer", "projection_id", "te_projection", "projection_id", false))
00347                         return false;
00348         
00349         if (existRelation("te_representation","fk_rep_layer_id") == TeNoRelation )
00350                 if (!createRelation("fk_rep_layer_id", "te_representation", "layer_id", "te_layer", "layer_id", true))
00351                         return false;
00352 
00353         if (existRelation("te_view","fk_view_proj_id") == TeNoRelation )
00354                 if (!createRelation("fk_view_proj_id", "te_view", "projection_id", "te_projection", "projection_id", false))
00355                         return false;
00356 
00357         if (existRelation("te_view", "fk_view_current_theme") == TeNoRelation )
00358                 if (!createRelation("fk_view_current_theme", "te_view", "current_theme", "te_theme", "theme_id", false))
00359                         return false;
00360         
00361         if (existRelation("te_theme","fk_theme_layer_id") == TeNoRelation )
00362                 if (!createRelation("fk_theme_layer_id", "te_theme", "layer_id", "te_layer", "layer_id", true))
00363                         return false;
00364 
00365         if (existRelation("te_theme","fk_theme_view_id") == TeNoRelation )
00366                 if (!createRelation("fk_theme_view_id", "te_theme", "view_id", "te_view", "view_id", true))
00367                         return false;
00368 
00369         if (existRelation("te_theme_table","fk_thmtable_theme_id") == TeNoRelation )
00370                 if (!createRelation("fk_thmtable_theme_id", "te_theme_table", "theme_id", "te_theme", "theme_id", true))
00371                         return false;
00372 
00373         if (existRelation("te_theme_table","fk_thmtable_lytable_id") == TeNoRelation )
00374                 if (!createRelation("fk_thmtable_lytable_id", "te_theme_table", "table_id", "te_layer_table", "table_id", false))
00375                         return false;
00376 
00377         if (existRelation("te_theme_table","fk_thmtable_relation_id") == TeNoRelation )
00378                 if (!createRelation("fk_thmtable_relation_id", "te_theme_table", "relation_id", "te_tables_relation", "relation_id", false))
00379                         return false;
00380 
00381         if (existRelation("te_grouping","fk_group_theme_id") == TeNoRelation )
00382                 if (!createRelation("fk_group_theme_id", "te_grouping", "theme_id", "te_theme", "theme_id", true))
00383                         return false;
00384 
00385         if (existRelation("te_legend","fk_legend_theme_id") == TeNoRelation )
00386                 if (!createRelation("fk_legend_theme_id", "te_legend", "theme_id", "te_theme", "theme_id", true))
00387                         return false;
00388 
00389         if (existRelation("te_visual","fk_visual_legend_id") == TeNoRelation )
00390                 if (!createRelation("fk_visual_legend_id", "te_visual", "legend_id", "te_legend", "legend_id", true))
00391                         return false;
00392         
00393         if (existRelation("te_layer_table","fk_laytable_layer_id") == TeNoRelation )
00394                 if (!createRelation ("fk_laytable_layer_id", "te_layer_table", "layer_id", "te_layer", "layer_id", true))
00395                         return false;
00396         
00397         if (existRelation("te_tables_relation","fk_tabrelation_laytable_id") == TeNoRelation )
00398                 if (!createRelation("fk_tabrelation_laytable_id", "te_tables_relation", "related_table_id", "te_layer_table", "table_id", true))
00399                         return false;
00400 
00401         if (existRelation("te_visual_raster","fk_visrast_theme_id") == TeNoRelation )
00402                 if (!createRelation("fk_visrast_theme_id", "te_visual_raster", "theme_id", "te_theme", "theme_id", true))
00403                         return false;
00404 
00405         if (existRelation("te_project_view","fk_projectview_project_id") == TeNoRelation )
00406                 if (!createRelation("fk_projectview_project_id", "te_project_view", "project_id", "te_project", "project_id", true))
00407                         return false;
00408 
00409         if (existRelation("te_project_view","fk_projectview_view_id") == TeNoRelation )
00410                 if (!createRelation("fk_projectview_view_id", "te_project_view", "view_id", "te_view", "view_id", true))
00411                         return false;
00412 
00413         if (existRelation("te_projection","fk_proj_datum_name") == TeNoRelation )
00414                 if (!createRelation("fk_proj_datum_name", "te_projection", "datum", "te_datum", "name", false))
00415                         return false;
00416 
00417         if (existRelation("te_srs","fk_srs_proj_id") == TeNoRelation )
00418                 if (!createRelation("fk_srs_proj_id", "te_srs", "projection_id", "te_projection", "projection_id", true))
00419                         return false;
00420 
00421         return true;
00422 }
00423 
00424 bool 
00425 TeDatabase::createConceptualModel(bool withIntegrity, bool newDatabase, bool /* createIndex */)
00426 {
00427         bool status = true;
00428         bool createMainTables = false;
00429         
00430         if (!this->tableExist("te_datum"))
00431         {
00432                 status = this->createDatumTable();
00433                 if (!status)
00434                         return false;   
00435                 createMainTables = true;
00436                 populateDatumTable();
00437         }
00438 
00439         if (!this->tableExist("te_projection"))
00440         {
00441                 status = this->createProjectionTable();
00442                 if (!status)
00443                         return false;   
00444                 createMainTables = true;
00445         }
00446 
00447         if (!this->tableExist("te_srs"))
00448         {
00449                 status = this->createSRSTable();
00450                 if (!status)
00451                         return false;   
00452                 createMainTables = true;
00453         }
00454 
00455         if (!this->tableExist("te_layer"))
00456         {
00457                 status = this->createLayerTable();
00458                 if (!status)
00459                         return false;
00460                 createMainTables = true;
00461         }
00462 
00463         if (!this->tableExist("te_layer_table"))
00464         {
00465                 status = this->createLayerTableTable();
00466                 if (!status)
00467                         return false;
00468                 createMainTables = true;
00469         }
00470 
00471         if (!this->tableExist("te_tables_relation"))
00472         {
00473                 status = this->createTablesRelationTable();
00474                 if (!status)
00475                         return false;
00476                 createMainTables = true;
00477         }
00478         
00479         if (!this->tableExist("te_representation"))
00480         {
00481                 status = this->createRepresentationTable();
00482                 if (!status)
00483                         return false;
00484                 createMainTables = true;
00485         }
00486 
00487         if (!this->tableExist("te_theme"))
00488         {
00489                 status = this->createThemeTable();
00490                 if (!status)
00491                         return false;
00492                 createMainTables = true;
00493         }
00494 
00495         if (!this->tableExist("te_view"))
00496         {
00497                 status = this->createViewTable();
00498                 if (!status)
00499                         return false;
00500                 createMainTables = true;
00501         }
00502 
00503         if (!this->tableExist("te_grouping"))
00504         {
00505                 status = this->createGroupingTable();
00506                 if (!status)
00507                         return false;
00508         }
00509 
00510         if (!this->tableExist("te_theme_table"))
00511         {
00512                 status = this->createThemeTablesTable();
00513                 if (!status)
00514                         return false;
00515         }
00516 
00517         if (!this->tableExist("te_legend"))
00518         {
00519                 status = this->createLegendTable();
00520                 if (!status)
00521                         return false;   
00522         }
00523 
00524         if (!this->tableExist("te_visual"))
00525         {
00526                 status = this->createVisualTable();
00527                 if (!status)
00528                         return false;   
00529         }
00530 
00531         if (!this->tableExist("te_visual_raster"))
00532         {
00533                 status = this->createVisualRasterTable();
00534                 if (!status)
00535                         return false;   
00536         }
00537 
00538         if (!this->tableExist("te_database"))
00539         {
00540                 status = this->createDatabaseTable();
00541                 if (!status)
00542                         return false;
00543         }
00544 
00545         if (!this->tableExist("te_project"))
00546         {
00547                 status = this->createProjectTable();
00548                 if (!status)
00549                         return false;
00550         }
00551 
00552         if (!this->tableExist("te_project_view"))
00553         {
00554                 status = this->createProjectViewTable();
00555                 if (!status)
00556                         return false;
00557         }
00558         if (newDatabase || createMainTables)
00559         {
00560                 string ins = "INSERT INTO te_database (db_version) VALUES ('" + TeDBVERSION + "')";
00561                 if (!execute(ins))
00562                         return false;
00563         }
00564 
00565         if (withIntegrity)
00566                 status = defineIntegrity();
00567 
00568         return status;
00569 }
00570 
00571 bool
00572 TeDatabase::createIndex(const string& tableName, const string& indexName, const string& columnsName)
00573 {
00574         string sql = "CREATE INDEX " + indexName + " ON " + tableName + "(" + columnsName + ")";        
00575         return execute (sql);
00576 }
00577 
00578 bool
00579 TeDatabase::deleteIndex(const string& , const string& indexName)
00580 {
00581         string sql = "DROP INDEX " + indexName; 
00582         return execute(sql);
00583 }
00584 
00585 bool
00586 TeDatabase::getIndexesFromTable(const string& , std::vector<TeDatabaseIndex>& )
00587 {
00588         return true;
00589 }
00590 
00591 bool 
00592 TeDatabase::createDatabaseTable()
00593 {
00594         TeAttributeList attList;
00595 
00596         {TeAttribute attDBVersion;
00597         attDBVersion.rep_.name_ = "db_version";
00598         attDBVersion.rep_.type_ = TeSTRING;
00599         attDBVersion.rep_.numChar_ = 50;
00600         attDBVersion.rep_.isPrimaryKey_ = true;
00601         attDBVersion.rep_.null_ = false;
00602         attList.push_back(attDBVersion);}
00603 
00604         {TeAttribute attDBCreation;
00605         attDBCreation.rep_.name_ = "db_creation";
00606         attDBCreation.rep_.type_ = TeDATETIME;
00607         attList.push_back(attDBCreation);}
00608 
00609         return createTable("te_database", attList);
00610 }
00611 
00612 bool 
00613 TeDatabase::createProjectTable()
00614 {
00615         TeAttributeList attList;
00616 
00617         {TeAttribute attProjectId;
00618         attProjectId.rep_.name_ = "project_id";
00619         attProjectId.rep_.type_ = TeUNSIGNEDINT;
00620         attProjectId.rep_.isAutoNumber_ = true;
00621         attProjectId.rep_.isPrimaryKey_ = true;
00622         attProjectId.rep_.null_ = false;
00623         attList.push_back(attProjectId);}
00624 
00625         {TeAttribute attName;
00626         attName.rep_.name_ = "name";
00627         attName.rep_.type_ = TeSTRING;
00628         attName.rep_.numChar_ = 50;
00629         attName.rep_.null_ = false;
00630         attList.push_back(attName);}
00631 
00632         {TeAttribute attDescription;
00633         attDescription.rep_.name_ = "description";
00634         attDescription.rep_.type_ = TeSTRING;
00635         attDescription.rep_.numChar_ = 255;
00636         attDescription.rep_.null_ = true;
00637         attList.push_back(attDescription);}
00638 
00639         {TeAttribute attCurrentView;
00640         attCurrentView.rep_.name_ = "current_view";
00641         attCurrentView.rep_.type_ = TeINT;
00642         attList.push_back(attCurrentView);}
00643 
00644         return createTable("te_project", attList);
00645 }
00646 
00647 bool 
00648 TeDatabase::createProjectViewTable()
00649 {
00650         TeAttributeList attList;
00651 
00652         {TeAttribute attProjectId;
00653         attProjectId.rep_.name_ = "project_id";
00654         attProjectId.rep_.type_ = TeUNSIGNEDINT;
00655         attProjectId.rep_.isPrimaryKey_ = true;
00656         attProjectId.rep_.null_ = false;
00657         attList.push_back(attProjectId);}
00658 
00659         {TeAttribute attViewId;
00660         attViewId.rep_.name_ = "view_id";
00661         attViewId.rep_.type_ = TeUNSIGNEDINT;
00662         attViewId.rep_.isPrimaryKey_ = true;
00663         attViewId.rep_.null_ = false;
00664         attList.push_back(attViewId);}
00665 
00666         return createTable("te_project_view", attList);
00667 }
00668 
00669 bool TeDatabase::createDatumTable()
00670 {
00671         if(tableExist("te_datum"))
00672         {
00673                 return true;
00674         }
00675 
00676         TeAttributeList attList;
00677 
00678         {TeAttribute attDatumName;
00679         attDatumName.rep_.name_ = "name";
00680         attDatumName.rep_.type_ = TeSTRING;
00681         attDatumName.rep_.numChar_ = 50;
00682         attDatumName.rep_.isPrimaryKey_ = true;
00683         attDatumName.rep_.isAutoNumber_ = false;
00684         attDatumName.rep_.null_ = false;
00685         attList.push_back(attDatumName);}
00686 
00687         {TeAttribute attRadius;
00688         attRadius.rep_.name_ = "radius";
00689         attRadius.rep_.type_ = TeREAL;
00690         attRadius.rep_.decimals_ = 15;
00691         attRadius.rep_.defaultValue_ = "0.0";
00692         attList.push_back(attRadius);}
00693 
00694         {TeAttribute attFlattening;
00695         attFlattening.rep_.name_ = "flattening";
00696         attFlattening.rep_.type_ = TeREAL;
00697         attFlattening.rep_.decimals_ = 15;
00698         attFlattening.rep_.defaultValue_ = "0.0";
00699         attList.push_back(attFlattening);}
00700 
00701         {TeAttribute attDX;
00702         attDX.rep_.name_ = "dx";
00703         attDX.rep_.type_ = TeREAL;
00704         attDX.rep_.decimals_ = 15;
00705         attDX.rep_.defaultValue_ = "0.0";
00706         attList.push_back(attDX);}
00707 
00708         {TeAttribute attDY;
00709         attDY.rep_.name_ = "dy";
00710         attDY.rep_.type_ = TeREAL;
00711         attDY.rep_.decimals_ = 15;
00712         attDY.rep_.defaultValue_ = "0.0";
00713         attList.push_back(attDY);}
00714 
00715         {TeAttribute attDZ;
00716         attDZ.rep_.name_ = "dz";
00717         attDZ.rep_.type_ = TeREAL;
00718         attDZ.rep_.decimals_ = 15;
00719         attDZ.rep_.defaultValue_ = "0.0";
00720         attList.push_back(attDZ);}
00721 
00722         return createTable("te_datum", attList);
00723 }
00724 
00725 bool 
00726 TeDatabase::createProjectionTable ()
00727 {
00728         TeAttributeList attList;
00729 
00730         {TeAttribute attProjectId;
00731         attProjectId.rep_.name_ = "projection_id";
00732         attProjectId.rep_.type_ = TeUNSIGNEDINT;
00733         attProjectId.rep_.isPrimaryKey_ = true;
00734         attProjectId.rep_.isAutoNumber_ = true;
00735         attProjectId.rep_.null_ = false;
00736         attList.push_back(attProjectId);}
00737 
00738         {TeAttribute attName;
00739         attName.rep_.name_ = "name";
00740         attName.rep_.type_ = TeSTRING;
00741         attName.rep_.numChar_ = 50;
00742         attName.rep_.null_ = false;
00743         attList.push_back(attName);}
00744 
00745         {TeAttribute attLong0;
00746         attLong0.rep_.name_ = "long0";
00747         attLong0.rep_.type_ = TeREAL;
00748         attLong0.rep_.decimals_ = 15;
00749         attLong0.rep_.defaultValue_ = "0.0";
00750         attList.push_back(attLong0);}
00751 
00752         {TeAttribute attLat0;
00753         attLat0.rep_.name_ = "lat0";
00754         attLat0.rep_.type_ = TeREAL;
00755         attLat0.rep_.decimals_ = 15;
00756         attLat0.rep_.defaultValue_ = "0.0";
00757         attList.push_back(attLat0);}
00758 
00759         {TeAttribute attOffX;
00760         attOffX.rep_.name_ = "offx";
00761         attOffX.rep_.type_ = TeREAL;
00762         attOffX.rep_.decimals_ = 15;
00763         attOffX.rep_.defaultValue_ = "0.0";
00764         attList.push_back(attOffX);}
00765 
00766         {TeAttribute attOffY;
00767         attOffY.rep_.name_ = "offy";
00768         attOffY.rep_.type_ = TeREAL;
00769         attOffY.rep_.decimals_ = 15;
00770         attOffY.rep_.defaultValue_ = "0.0";
00771         attList.push_back(attOffY);}
00772 
00773         {TeAttribute attSlat1;
00774         attSlat1.rep_.name_ = "stlat1";
00775         attSlat1.rep_.type_ = TeREAL;
00776         attSlat1.rep_.decimals_ = 15;
00777         attSlat1.rep_.defaultValue_ = "0.0";
00778         attList.push_back(attSlat1);}
00779 
00780         {TeAttribute attSlat2;
00781         attSlat2.rep_.name_ = "stlat2";
00782         attSlat2.rep_.type_ = TeREAL;
00783         attSlat2.rep_.decimals_ = 15;
00784         attSlat2.rep_.defaultValue_ = "0.0";
00785         attList.push_back(attSlat2);}
00786 
00787         {TeAttribute attUnit;
00788         attUnit.rep_.name_ = "unit";
00789         attUnit.rep_.type_ = TeSTRING;
00790         attUnit.rep_.numChar_ = 50;
00791         attUnit.rep_.null_ = false;
00792         attList.push_back(attUnit);}
00793 
00794         {TeAttribute attScale;
00795         attScale.rep_.name_ = "scale";
00796         attScale.rep_.type_ = TeREAL;
00797         attScale.rep_.decimals_ = 15;
00798         attScale.rep_.defaultValue_ = "0.0";
00799         attList.push_back(attScale);}
00800 
00801         {TeAttribute attHemis;
00802         attHemis.rep_.name_ = "hemis";
00803         attHemis.rep_.type_ = TeINT;
00804         attHemis.rep_.null_ = false;
00805         attList.push_back(attHemis);}
00806 
00807         {TeAttribute attDatum;
00808         attDatum.rep_.name_ = "datum";
00809         attDatum.rep_.type_ = TeSTRING;
00810         attDatum.rep_.numChar_ = 50;
00811         attDatum.rep_.null_ = false;
00812         attList.push_back(attDatum);}
00813 
00814         return createTable("te_projection", attList);
00815 }
00816 
00817 bool TeDatabase::createSRSTable()
00818 {
00819         if(tableExist("te_srs"))
00820         {
00821                 return true;
00822         }
00823 
00824         TeAttributeList attList;
00825 
00826         {TeAttribute attProjectId;
00827         attProjectId.rep_.name_ = "projection_id";
00828         attProjectId.rep_.type_ = TeUNSIGNEDINT;
00829         attProjectId.rep_.isPrimaryKey_ = true;
00830         attProjectId.rep_.isAutoNumber_ = false;
00831         attProjectId.rep_.null_ = false;
00832         attList.push_back(attProjectId);}
00833 
00834         {TeAttribute attSRSId;
00835         attSRSId.rep_.name_ = "srs_id";
00836         attSRSId.rep_.type_ = TeINT;
00837         attSRSId.rep_.null_ = false;
00838         attList.push_back(attSRSId);}
00839 
00840         return createTable("te_srs", attList);
00841 }
00842 
00843 bool TeDatabase::createLayerTable ()
00844 {
00845         TeAttributeList attList;
00846 
00847         {TeAttribute attLayerId;
00848         attLayerId.rep_.name_ = "layer_id";
00849         attLayerId.rep_.type_ = TeUNSIGNEDINT;
00850         attLayerId.rep_.isPrimaryKey_ = true;
00851         attLayerId.rep_.isAutoNumber_ = true;
00852         attLayerId.rep_.null_ = false;
00853         attList.push_back(attLayerId);}
00854 
00855         {TeAttribute attProjectionId;
00856         attProjectionId.rep_.name_ = "projection_id";
00857         attProjectionId.rep_.type_ = TeUNSIGNEDINT;
00858         attProjectionId.rep_.null_ = false;
00859         attList.push_back(attProjectionId);}
00860 
00861         {TeAttribute attName;
00862         attName.rep_.name_ = "name";
00863         attName.rep_.type_ = TeSTRING;
00864         attName.rep_.numChar_ = 255;
00865         attName.rep_.null_ = false;
00866         attList.push_back(attName);}
00867 
00868         {TeAttribute attLowerX;
00869         attLowerX.rep_.name_ = "lower_x";
00870         attLowerX.rep_.type_ = TeREAL;
00871         attLowerX.rep_.decimals_ = 15;
00872         attLowerX.rep_.defaultValue_ = "0.0";
00873         attList.push_back(attLowerX);}
00874 
00875         {TeAttribute attLowerY;
00876         attLowerY.rep_.name_ = "lower_y";
00877         attLowerY.rep_.type_ = TeREAL;
00878         attLowerY.rep_.decimals_ = 15;
00879         attLowerY.rep_.defaultValue_ = "0.0";
00880         attList.push_back(attLowerY);}
00881 
00882         {TeAttribute attUpperX;
00883         attUpperX.rep_.name_ = "upper_x";
00884         attUpperX.rep_.type_ = TeREAL;
00885         attUpperX.rep_.decimals_ = 15;
00886         attUpperX.rep_.defaultValue_ = "0.0";
00887         attList.push_back(attUpperX);}
00888 
00889         {TeAttribute attUpperY;
00890         attUpperY.rep_.name_ = "upper_y";
00891         attUpperY.rep_.type_ = TeREAL;
00892         attUpperY.rep_.decimals_ = 15;
00893         attUpperY.rep_.defaultValue_ = "0.0";
00894         attList.push_back(attUpperY);}
00895 
00896         {TeAttribute attInitialTime;
00897         attInitialTime.rep_.name_ = "initial_time";
00898         attInitialTime.rep_.type_ = TeDATETIME;
00899         attList.push_back(attInitialTime);}
00900 
00901         {TeAttribute attFinalTime;
00902         attFinalTime.rep_.name_ = "final_time";
00903         attFinalTime.rep_.type_ = TeDATETIME;
00904         attList.push_back(attFinalTime);}
00905 
00906         {TeAttribute attEditionTime;
00907         attEditionTime.rep_.name_ = "edition_time";
00908         attEditionTime.rep_.type_ = TeDATETIME;
00909         attList.push_back(attEditionTime);}
00910 
00911         if(!createTable("te_layer", attList))
00912                 return false;
00913 
00914         string idxName = "te_idx_layer_proj";
00915 
00916         if(!createIndex("te_layer", idxName, "projection_id"))
00917                 return false;
00918 
00919         idxName = "te_idx_layer_name";
00920 
00921         return createIndex("te_layer", idxName, "name");
00922 }
00923 
00924 bool TeDatabase::createLayerTableTable()
00925 {
00926         TeAttributeList attList;
00927 
00928         {TeAttribute attTableId;
00929         attTableId.rep_.name_ = "table_id";
00930         attTableId.rep_.type_ = TeUNSIGNEDINT;
00931         attTableId.rep_.isPrimaryKey_ = true;
00932         attTableId.rep_.isAutoNumber_ = true;
00933         attTableId.rep_.null_ = false;
00934         attList.push_back(attTableId);}
00935 
00936         {TeAttribute attLayerId;
00937         attLayerId.rep_.name_ = "layer_id";
00938         attLayerId.rep_.type_ = TeUNSIGNEDINT;
00939         attList.push_back(attLayerId);}
00940 
00941         {TeAttribute attTable;
00942         attTable.rep_.name_ = "attr_table";
00943         attTable.rep_.type_ = TeSTRING;
00944         attTable.rep_.numChar_ = 255;
00945         attTable.rep_.null_ = false;
00946         attList.push_back(attTable);}
00947 
00948         {TeAttribute attUniqueID;
00949         attUniqueID.rep_.name_ = "unique_id";
00950         attUniqueID.rep_.type_ = TeSTRING;
00951         attUniqueID.rep_.numChar_ = 255;
00952         attList.push_back(attUniqueID);}
00953 
00954         {TeAttribute attLink;
00955         attLink.rep_.name_ = "attr_link";
00956         attLink.rep_.type_ = TeSTRING;
00957         attLink.rep_.numChar_ = 255;
00958         attList.push_back(attLink);}
00959 
00960         {TeAttribute attAttrInitialTime;
00961         attAttrInitialTime.rep_.name_ = "attr_initial_time";
00962         attAttrInitialTime.rep_.type_ = TeSTRING;
00963         attAttrInitialTime.rep_.numChar_ = 255;
00964         attList.push_back(attAttrInitialTime);}
00965 
00966         {TeAttribute attAttrFinalTime;
00967         attAttrFinalTime.rep_.name_ = "attr_final_time";
00968         attAttrFinalTime.rep_.type_ = TeSTRING;
00969         attAttrFinalTime.rep_.numChar_ = 255;
00970         attList.push_back(attAttrFinalTime);}
00971 
00972         {TeAttribute attTimeUnit;
00973         attTimeUnit.rep_.name_ = "attr_time_unit";
00974         attTimeUnit.rep_.type_ = TeUNSIGNEDINT;
00975         attList.push_back(attTimeUnit);}
00976 
00977         {TeAttribute attTableType;
00978         attTableType.rep_.name_ = "attr_table_type";
00979         attTableType.rep_.type_ = TeUNSIGNEDINT;
00980         attList.push_back(attTableType);}
00981 
00982         {TeAttribute attUserName;
00983         attUserName.rep_.name_ = "user_name";
00984         attUserName.rep_.type_ = TeSTRING;
00985         attUserName.rep_.numChar_ = 255;
00986         attList.push_back(attUserName);}
00987 
00988         {TeAttribute attInitialTime;
00989         attInitialTime.rep_.name_ = "initial_time";
00990         attInitialTime.rep_.type_ = TeDATETIME;
00991         attList.push_back(attInitialTime);}
00992 
00993         {TeAttribute attFinalTime;
00994         attFinalTime.rep_.name_ = "final_time";
00995         attFinalTime.rep_.type_ = TeDATETIME;
00996         attList.push_back(attFinalTime);}
00997 
00998         if(!createTable("te_layer_table", attList))
00999                 return false;
01000 
01001         string idxName = "te_idx_layertable_layer";
01002 
01003         if(!createIndex("te_layer_table", idxName, "layer_id"))
01004                 return false;
01005 
01006         idxName = "te_idx_layertable_att";
01007 
01008         return createIndex("te_layer_table", idxName, "attr_table");
01009 }
01010 
01011 bool 
01012 TeDatabase::updateTableInfo(int layerId, TeTable &table, const string user)
01013 {
01014         if (table.id() <= 0 )  // table information doesn�t exist in database yet
01015                 return this->insertTableInfo(layerId,table,user);
01016         string sql;
01017         sql = "UPDATE te_layer_table SET ";
01018         sql += "unique_id='" + table.uniqueName() + "', ";
01019         sql += "attr_link='" + table.linkName() + "', ";
01020         sql += "attr_initial_time='" + table.attInitialTime() + "', ";
01021         sql += "attr_final_time='" + table.attFinalTime() + "', ";
01022         sql += "attr_time_unit=" + Te2String(table.attTimeUnit()) + ", ";
01023         sql += "attr_table_type="+ Te2String(table.tableType()) + ", ";
01024         sql += "user_name='" + user + "' WHERE ";
01025         sql += "layer_id=" + Te2String(layerId) + " AND ";
01026         sql += "attr_table_name='" + table.name() + "'";
01027         return execute (sql);
01028 }
01029 
01030 bool 
01031 TeDatabase::loadTableInfo(TeTable& table)
01032 {
01033         if (table.name().empty())
01034                 return false;
01035 
01036         TeDatabasePortal* portal = this->getPortal();
01037         if(!portal)
01038         {
01039                 this->errorMessage_ = "N�o foi poss�vel abrir portal para o banco";
01040                 return false;
01041         }
01042         
01043         //theme tables
01044         string sel = " SELECT table_id, layer_id, attr_table, unique_id, ";
01045         sel += " attr_link, attr_initial_time, attr_final_time, attr_time_unit, ";
01046         sel += " attr_table_type, user_name, initial_time, final_time ";
01047         sel += " FROM te_layer_table ";
01048         sel += " WHERE  attr_table = '" + table.name() + "'";
01049                 
01050         if ((!portal->query(sel)) || (!portal->fetchRow()))
01051         {       
01052                 delete portal;
01053                 return false;
01054         }
01055         
01056         if(!portal->getAttrTable(table))
01057         {
01058                 delete portal;
01059                 return false;
01060         }
01061 
01062         TeAttributeList attrList;
01063         getAttributeList(table.name(), attrList);
01064         table.setAttributeList(attrList);
01065         
01066         if (table.tableType() == TeAttrExternal) //information about external table 
01067         {
01068                 portal->freeResult();
01069 
01070                 sel = " SELECT te_layer_table.attr_table, te_tables_relation.related_table_id, ";
01071                 sel += " te_tables_relation.related_attr, te_tables_relation.external_attr  ";
01072                 sel += " FROM te_layer_table INNER JOIN te_tables_relation";
01073                 sel += " ON te_layer_table.table_id = te_tables_relation.related_table_id ";
01074                 sel += " WHERE  te_tables_relation.external_table_name = '" + table.name() + "'";
01075 
01076                 if (!portal->query(sel))
01077                 {       
01078                         delete portal;
01079                         return false;
01080                 }
01081 
01082                 if (!portal->fetchRow())
01083                 {
01084                         delete portal;
01085                         return true;
01086                 }
01087                 
01088                 int relatedTableId = portal->getInt(1); //related_table_id
01089                 string relatedTable = portal->getData(0); //static table name 
01090                 string relatedAttr = portal->getData(2); // static column name - related_attr
01091                         
01092                 table.setTableType(TeAttrExternal, relatedTableId, relatedAttr);
01093                 table.relatedTableName(relatedTable);
01094                 table.setLinkName(portal->getData(3));  //external column name - external_attr
01095         }
01096         
01097         delete portal;
01098         return true;
01099 }
01100 
01101 
01102 bool TeDatabase::createLUTTable(const string& name)
01103 {
01104         if(name.empty())
01105                 return false;
01106 
01107         TeAttributeList attList;
01108 
01109         {TeAttribute attIndexId;
01110         attIndexId.rep_.name_ = "index_id";
01111         attIndexId.rep_.type_ = TeUNSIGNEDINT;
01112         attIndexId.rep_.isPrimaryKey_ = true;
01113         attIndexId.rep_.null_ = false;
01114         attList.push_back(attIndexId);}
01115 
01116         {TeAttribute attRVal;
01117         attRVal.rep_.name_ = "r_val";
01118         attRVal.rep_.type_ = TeUNSIGNEDINT;
01119         attRVal.rep_.null_ = false;
01120         attList.push_back(attRVal);}
01121 
01122         {TeAttribute attGVal;
01123         attGVal.rep_.name_ = "g_val";
01124         attGVal.rep_.type_ = TeUNSIGNEDINT;
01125         attGVal.rep_.null_ = false;
01126         attList.push_back(attGVal);}
01127 
01128         {TeAttribute attBVal;
01129         attBVal.rep_.name_ = "b_val";
01130         attBVal.rep_.type_ = TeUNSIGNEDINT;
01131         attBVal.rep_.null_ = false;
01132         attList.push_back(attBVal);}
01133 
01134         {TeAttribute attName;
01135         attName.rep_.name_ = "class_name";
01136         attName.rep_.type_ = TeSTRING;
01137         attName.rep_.numChar_ = 255;
01138         attList.push_back(attName);}
01139 
01140         return createTable(name, attList);
01141 }
01142 
01143 bool TeDatabase::createTablesRelationTable()
01144 {
01145         TeAttributeList attList;
01146         
01147         {TeAttribute attRelationId;
01148         attRelationId.rep_.name_ = "relation_id";
01149         attRelationId.rep_.type_ = TeUNSIGNEDINT;
01150         attRelationId.rep_.isAutoNumber_ = true;
01151         attRelationId.rep_.isPrimaryKey_ = true;
01152         attRelationId.rep_.null_ = false;
01153         attList.push_back(attRelationId);}
01154 
01155         {TeAttribute attRelatedTableId;
01156         attRelatedTableId.rep_.name_ = "related_table_id";
01157         attRelatedTableId.rep_.type_ = TeINT;
01158         attRelatedTableId.rep_.null_ = false;
01159         attList.push_back(attRelatedTableId);}
01160 
01161         {TeAttribute attRelatedAttr;
01162         attRelatedAttr.rep_.name_ = "related_attr";
01163         attRelatedAttr.rep_.type_ = TeSTRING;
01164         attRelatedAttr.rep_.numChar_ = 255;
01165         attRelatedAttr.rep_.null_ = false;
01166         attList.push_back(attRelatedAttr);}
01167 
01168         {TeAttribute attExternalTableName;
01169         attExternalTableName.rep_.name_ = "external_table_name";
01170         attExternalTableName.rep_.type_ = TeSTRING;
01171         attExternalTableName.rep_.numChar_ = 255;
01172         attExternalTableName.rep_.null_ = false;
01173         attList.push_back(attExternalTableName);}
01174 
01175         {TeAttribute attExternalAttr;
01176         attExternalAttr.rep_.name_ = "external_attr";
01177         attExternalAttr.rep_.type_ = TeSTRING;
01178         attExternalAttr.rep_.numChar_ = 255;
01179         attExternalAttr.rep_.null_ = false;
01180         attList.push_back(attExternalAttr);}
01181 
01182         return createTable("te_tables_relation", attList);
01183 }
01184 
01185 bool TeDatabase::createRepresentationTable ()
01186 {
01187         TeAttributeList attList;
01188         
01189         {TeAttribute attRepresId;
01190         attRepresId.rep_.name_ = "repres_id";
01191         attRepresId.rep_.type_ = TeUNSIGNEDINT;
01192         attRepresId.rep_.isAutoNumber_ = true;
01193         attRepresId.rep_.isPrimaryKey_ = true;
01194         attRepresId.rep_.null_ = false;
01195         attList.push_back(attRepresId);}
01196 
01197         {TeAttribute attLayerId;
01198         attLayerId.rep_.name_ = "layer_id";
01199         attLayerId.rep_.type_ = TeUNSIGNEDINT;
01200         attLayerId.rep_.null_ = false;
01201         attList.push_back(attLayerId);}
01202 
01203         {TeAttribute attGeomType;
01204         attGeomType.rep_.name_ = "geom_type";
01205         attGeomType.rep_.type_ = TeINT;
01206         attGeomType.rep_.null_ = false;
01207         attList.push_back(attGeomType);}
01208 
01209         {TeAttribute attGeomTable;
01210         attGeomTable.rep_.name_ = "geom_table";
01211         attGeomTable.rep_.type_ = TeSTRING;
01212         attGeomTable.rep_.numChar_ = 255;
01213         attGeomTable.rep_.null_ = false;
01214         attList.push_back(attGeomTable);}
01215 
01216         {TeAttribute attDescription;
01217         attDescription.rep_.name_ = "description";
01218         attDescription.rep_.type_ = TeSTRING;
01219         attDescription.rep_.numChar_ = 255;
01220         attList.push_back(attDescription);}
01221 
01222         {TeAttribute attLowerX;
01223         attLowerX.rep_.name_ = "lower_x";
01224         attLowerX.rep_.type_ = TeREAL;
01225         attLowerX.rep_.decimals_ = 15;
01226         attLowerX.rep_.defaultValue_ = "0.0";
01227         attList.push_back(attLowerX);}
01228 
01229         {TeAttribute attLowerY;
01230         attLowerY.rep_.name_ = "lower_y";
01231         attLowerY.rep_.type_ = TeREAL;
01232         attLowerY.rep_.decimals_ = 15;
01233         attLowerY.rep_.defaultValue_ = "0.0";
01234         attList.push_back(attLowerY);}
01235 
01236         {TeAttribute attUpperX;
01237         attUpperX.rep_.name_ = "upper_x";
01238         attUpperX.rep_.type_ = TeREAL;
01239         attUpperX.rep_.decimals_ = 15;
01240         attUpperX.rep_.defaultValue_ = "0.0";
01241         attList.push_back(attUpperX);}
01242 
01243         {TeAttribute attUpperY;
01244         attUpperY.rep_.name_ = "upper_y";
01245         attUpperY.rep_.type_ = TeREAL;
01246         attUpperY.rep_.decimals_ = 15;
01247         attUpperY.rep_.defaultValue_ = "0.0";
01248         attList.push_back(attUpperY);}
01249 
01250         {TeAttribute attResX;
01251         attResX.rep_.name_ = "res_x";
01252         attResX.rep_.type_ = TeREAL;
01253         attResX.rep_.decimals_ = 15;
01254         attResX.rep_.defaultValue_ = "0.0";
01255         attList.push_back(attResX);}
01256 
01257         {TeAttribute attResY;
01258         attResY.rep_.name_ = "res_y";
01259         attResY.rep_.type_ = TeREAL;
01260         attResY.rep_.decimals_ = 15;
01261         attResY.rep_.defaultValue_ = "0.0";
01262         attList.push_back(attResY);}
01263 
01264         {TeAttribute attNumCols;
01265         attNumCols.rep_.name_ = "num_cols";
01266         attNumCols.rep_.type_ = TeINT;
01267         attList.push_back(attNumCols);}
01268 
01269         {TeAttribute attNumRows;
01270         attNumRows.rep_.name_ = "num_rows";
01271         attNumRows.rep_.type_ = TeINT;
01272         attList.push_back(attNumRows);}
01273 
01274         {TeAttribute attInitialTime;
01275         attInitialTime.rep_.name_ = "initial_time";
01276         attInitialTime.rep_.type_ = TeDATETIME;
01277         attList.push_back(attInitialTime);}
01278 
01279         {TeAttribute attFinalTime;
01280         attFinalTime.rep_.name_ = "final_time";
01281         attFinalTime.rep_.type_ = TeDATETIME;
01282         attList.push_back(attFinalTime);}
01283 
01284         if(!createTable("te_representation", attList))
01285                 return false;
01286 
01287         string idxName = "te_idx_representation";
01288 
01289         return createIndex("te_representation", idxName, "layer_id");
01290 }
01291 
01292 bool TeDatabase::createRasterMetadataTable(const string& tableName)
01293 {
01294         if(tableName.empty())
01295                 return false;
01296 
01297         TeAttributeList attList;
01298         
01299         {TeAttribute attGeomId;
01300         attGeomId.rep_.name_ = "geom_id";
01301         attGeomId.rep_.type_ = TeUNSIGNEDINT;
01302         attGeomId.rep_.isPrimaryKey_ = true;
01303         attGeomId.rep_.null_ = false;
01304         attList.push_back(attGeomId);}
01305 
01306         {TeAttribute attBandId;
01307         attBandId.rep_.name_ = "band_id";
01308         attBandId.rep_.type_ = TeUNSIGNEDINT;
01309         attBandId.rep_.isPrimaryKey_ = true;
01310         attBandId.rep_.null_ = false;
01311         attList.push_back(attBandId);}
01312 
01313         {TeAttribute attMinValue;
01314         attMinValue.rep_.name_ = "min_value";
01315         attMinValue.rep_.type_ = TeREAL;
01316         attMinValue.rep_.decimals_ = 15;
01317         attMinValue.rep_.defaultValue_ = "0.0";
01318         attList.push_back(attMinValue);}
01319 
01320         {TeAttribute attMaxValue;
01321         attMaxValue.rep_.name_ = "max_value";
01322         attMaxValue.rep_.type_ = TeREAL;
01323         attMaxValue.rep_.decimals_ = 15;
01324         attMaxValue.rep_.defaultValue_ = "0.0";
01325         attList.push_back(attMaxValue);}
01326 
01327         {TeAttribute attNumBits;
01328         attNumBits.rep_.name_ = "num_bits";
01329         attNumBits.rep_.type_ = TeINT;
01330         attList.push_back(attNumBits);}
01331 
01332         {TeAttribute attDatatype;
01333         attDatatype.rep_.name_ = "data_type";
01334         attDatatype.rep_.type_ = TeINT;
01335         attList.push_back(attDatatype);}
01336 
01337         {TeAttribute attPhotoType;
01338         attPhotoType.rep_.name_ = "photometric_type";
01339         attPhotoType.rep_.type_ = TeINT;
01340         attList.push_back(attPhotoType);}
01341 
01342         {TeAttribute attCompressType;
01343         attCompressType.rep_.name_ = "compression_type";
01344         attCompressType.rep_.type_ = TeINT;
01345         attList.push_back(attCompressType);}
01346 
01347         {TeAttribute attDummy;
01348         attDummy.rep_.name_ = "dummy";
01349         attDummy.rep_.type_ = TeREAL;
01350         attDummy.rep_.decimals_ = 15;
01351         attList.push_back(attDummy);}
01352 
01353         {TeAttribute attName;
01354         attName.rep_.name_ = "band_name";
01355         attName.rep_.type_ = TeSTRING;
01356         attName.rep_.numChar_ = 255;
01357         attList.push_back(attName);}
01358 
01359         return createTable(tableName, attList);
01360 }
01361 
01362 bool TeDatabase::createRasterTable(const string& tableName)
01363 {
01364         if(tableName.empty())
01365                 return false;
01366 
01367         TeAttributeList attList;
01368         
01369         {TeAttribute attGeomId;
01370         attGeomId.rep_.name_ = "block_id";
01371         attGeomId.rep_.type_ = TeSTRING;
01372         attGeomId.rep_.numChar_ = 50;
01373         attGeomId.rep_.isPrimaryKey_ = true;
01374         attGeomId.rep_.null_ = false;
01375         attList.push_back(attGeomId);}
01376 
01377         {TeAttribute attSpatialData;
01378         attSpatialData.rep_.name_ = "spatial_data";
01379         attSpatialData.rep_.type_ = TeRASTERTYPE;
01380         attList.push_back(attSpatialData);}
01381 
01382         if(!createTable(tableName, attList))
01383                 return false;
01384 
01385         string idxName = "te_idx_" + tableName + "_b";
01386 
01387         return createIndex(tableName, idxName, "band_id");
01388 }
01389 
01390 bool TeDatabase::createRasterGeometry(const string& tableName)
01391 {
01392         if(tableName.empty())
01393                 return false;
01394 
01395         TeAttributeList attList;
01396 
01397         {TeAttribute attGeomId;
01398         attGeomId.rep_.name_ = "geom_id";
01399         attGeomId.rep_.type_ = TeUNSIGNEDINT;
01400         attGeomId.rep_.isAutoNumber_ = true;
01401         attGeomId.rep_.isPrimaryKey_ = true;
01402         attGeomId.rep_.null_ = false;
01403         attList.push_back(attGeomId);}
01404 
01405         {TeAttribute attObjId;
01406         attObjId.rep_.name_ = "object_id";
01407         attObjId.rep_.type_ = TeSTRING;
01408         attObjId.rep_.numChar_ = 255;
01409         attObjId.rep_.null_ = false;
01410         attList.push_back(attObjId);}
01411 
01412         {TeAttribute attRasterTable;
01413         attRasterTable.rep_.name_ = "raster_table";
01414         attRasterTable.rep_.type_ = TeSTRING;
01415         attRasterTable.rep_.numChar_ = 255;
01416         attRasterTable.rep_.null_ = false;
01417         attList.push_back(attRasterTable);}
01418 
01419         {TeAttribute attLutTable;
01420         attLutTable.rep_.name_ = "lut_table";
01421         attLutTable.rep_.type_ = TeSTRING;
01422         attLutTable.rep_.numChar_ = 255;
01423         attList.push_back(attLutTable);}
01424 
01425         {TeAttribute attResX;
01426         attResX.rep_.name_ = "res_x";
01427         attResX.rep_.type_ = TeREAL;
01428         attResX.rep_.decimals_ = 15;
01429         attResX.rep_.defaultValue_ = "0.0";
01430         attList.push_back(attResX);}
01431 
01432         {TeAttribute attResY;
01433         attResY.rep_.name_ = "res_y";
01434         attResY.rep_.type_ = TeREAL;
01435         attResY.rep_.decimals_ = 15;
01436         attResY.rep_.defaultValue_ = "0.0";
01437         attList.push_back(attResY);}
01438 
01439         {TeAttribute attNumBands;
01440         attNumBands.rep_.name_ = "num_bands";
01441         attNumBands.rep_.type_ = TeINT;
01442         attList.push_back(attNumBands);}
01443 
01444         {TeAttribute attNumCols;
01445         attNumCols.rep_.name_ = "num_cols";
01446         attNumCols.rep_.type_ = TeINT;
01447         attList.push_back(attNumCols);}
01448 
01449         {TeAttribute attNumRows;
01450         attNumRows.rep_.name_ = "num_rows";
01451         attNumRows.rep_.type_ = TeINT;
01452         attList.push_back(attNumRows);}
01453 
01454         {TeAttribute attBlockHeight;
01455         attBlockHeight.rep_.name_ = "block_height";
01456         attBlockHeight.rep_.type_ = TeINT;
01457         attList.push_back(attBlockHeight);}
01458 
01459         {TeAttribute attBlockWidth;
01460         attBlockWidth.rep_.name_ = "block_width";
01461         attBlockWidth.rep_.type_ = TeINT;
01462         attList.push_back(attBlockWidth);}
01463 
01464         {TeAttribute attLowerX;
01465         attLowerX.rep_.name_ = "lower_x";
01466         attLowerX.rep_.type_ = TeREAL;
01467         attLowerX.rep_.decimals_ = 15;
01468         attLowerX.rep_.defaultValue_ = "0.0";
01469         attList.push_back(attLowerX);}
01470 
01471         {TeAttribute attLowerY;
01472         attLowerY.rep_.name_ = "lower_y";
01473         attLowerY.rep_.type_ = TeREAL;
01474         attLowerY.rep_.decimals_ = 15;
01475         attLowerY.rep_.defaultValue_ = "0.0";
01476         attList.push_back(attLowerY);}
01477 
01478         {TeAttribute attUpperX;
01479         attUpperX.rep_.name_ = "upper_x";
01480         attUpperX.rep_.type_ = TeREAL;
01481         attUpperX.rep_.decimals_ = 15;
01482         attUpperX.rep_.defaultValue_ = "0.0";
01483         attList.push_back(attUpperX);}
01484 
01485         {TeAttribute attUpperY;
01486         attUpperY.rep_.name_ = "upper_y";
01487         attUpperY.rep_.type_ = TeREAL;
01488         attUpperY.rep_.decimals_ = 15;
01489         attUpperY.rep_.defaultValue_ = "0.0";
01490         attList.push_back(attUpperY);}
01491 
01492         {TeAttribute attTilingType;
01493         attTilingType.rep_.name_ = "tiling_type";
01494         attTilingType.rep_.type_ = TeINT;
01495         attList.push_back(attTilingType);}
01496 
01497         if(!createTable(tableName, attList))
01498                 return  false;
01499 
01500         string idxName = "te_idx_" + tableName;
01501 
01502         return createIndex(tableName,  idxName, "object_id");
01503 }
01504 
01505 bool TeDatabase::createViewTable ()
01506 {
01507         TeAttributeList attList;
01508 
01509         {TeAttribute attViewId;
01510         attViewId.rep_.name_ = "view_id";
01511         attViewId.rep_.type_ = TeUNSIGNEDINT;
01512         attViewId.rep_.isPrimaryKey_ = true;
01513         attViewId.rep_.isAutoNumber_ = true;
01514         attViewId.rep_.null_ = false;
01515         attList.push_back(attViewId);}
01516 
01517         {TeAttribute attProjectionId;
01518         attProjectionId.rep_.name_ = "projection_id";
01519         attProjectionId.rep_.type_ = TeUNSIGNEDINT;
01520         attProjectionId.rep_.null_ = false;
01521         attList.push_back(attProjectionId);}
01522 
01523         {TeAttribute attName;
01524         attName.rep_.name_ = "name";
01525         attName.rep_.type_ = TeSTRING;
01526         attName.rep_.numChar_ = 255;
01527         attName.rep_.null_ = false;
01528         attList.push_back(attName);}
01529 
01530         {TeAttribute attUserName;
01531         attUserName.rep_.name_ = "user_name";
01532         attUserName.rep_.type_ = TeSTRING;
01533         attUserName.rep_.numChar_ = 255;
01534         attList.push_back(attUserName);}
01535 
01536         {TeAttribute attVisibility;
01537         attVisibility.rep_.name_ = "visibility";
01538         attVisibility.rep_.type_ = TeINT;
01539         attList.push_back(attVisibility);}
01540 
01541         {TeAttribute attLowerX;
01542         attLowerX.rep_.name_ = "lower_x";
01543         attLowerX.rep_.type_ = TeREAL;
01544         attLowerX.rep_.decimals_ = 15;
01545         attList.push_back(attLowerX);}
01546 
01547         {TeAttribute attLowerY;
01548         attLowerY.rep_.name_ = "lower_y";
01549         attLowerY.rep_.type_ = TeREAL;
01550         attLowerY.rep_.decimals_ = 15;
01551         attList.push_back(attLowerY);}
01552 
01553         {TeAttribute attUpperX;
01554         attUpperX.rep_.name_ = "upper_x";
01555         attUpperX.rep_.type_ = TeREAL;
01556         attUpperX.rep_.decimals_ = 15;
01557         attList.push_back(attUpperX);}
01558 
01559         {TeAttribute attUpperY;
01560         attUpperY.rep_.name_ = "upper_y";
01561         attUpperY.rep_.type_ = TeREAL;
01562         attUpperY.rep_.decimals_ = 15;
01563         attList.push_back(attUpperY);}
01564 
01565         {TeAttribute attCurrentTheme;
01566         attCurrentTheme.rep_.name_ = "current_theme";
01567         attCurrentTheme.rep_.type_ = TeINT;
01568         attList.push_back(attCurrentTheme);}
01569 
01570         if(!createTable("te_view", attList))
01571                 return false;
01572 
01573         string idxName = "te_idx_view_projid";
01574 
01575         if(!createIndex("te_view", idxName, "projection_id"))
01576                 return false;
01577 
01578         idxName = "te_idx_view_name";
01579 
01580         if(!createIndex("te_view", idxName, "name"))
01581                 return false;
01582 
01583         idxName = "te_idx_view_user_name";
01584 
01585         return createIndex("te_view", idxName, "user_name");
01586 }
01587 
01588 bool TeDatabase::createThemeTable ()
01589 {
01590         TeAttributeList attList;
01591 
01592         {TeAttribute attThemeId;
01593         attThemeId.rep_.name_ = "theme_id";
01594         attThemeId.rep_.type_ = TeUNSIGNEDINT;
01595         attThemeId.rep_.isPrimaryKey_ = true;
01596         attThemeId.rep_.isAutoNumber_ = true;
01597         attThemeId.rep_.null_ = false;
01598         attList.push_back(attThemeId);}
01599 
01600         {TeAttribute attLayerId;
01601         attLayerId.rep_.name_ = "layer_id";
01602         attLayerId.rep_.type_ = TeUNSIGNEDINT;
01603         attList.push_back(attLayerId);}
01604 
01605         {TeAttribute attViewId;
01606         attViewId.rep_.name_ = "view_id";
01607         attViewId.rep_.type_ = TeUNSIGNEDINT;
01608         attViewId.rep_.null_ = false;
01609         attList.push_back(attViewId);}
01610 
01611         {TeAttribute attName;
01612         attName.rep_.name_ = "name";
01613         attName.rep_.type_ = TeSTRING;
01614         attName.rep_.numChar_ = 255;
01615         attName.rep_.null_ = false;
01616         attList.push_back(attName);}
01617 
01618         {TeAttribute attParentId;
01619         attParentId.rep_.name_ = "parent_id";
01620         attParentId.rep_.type_ = TeUNSIGNEDINT;
01621         attParentId.rep_.null_ = false;
01622         attList.push_back(attParentId);}
01623 
01624         {TeAttribute attPriority;
01625         attPriority.rep_.name_ = "priority";
01626         attPriority.rep_.type_ = TeUNSIGNEDINT;
01627         attPriority.rep_.null_ = false;
01628         attList.push_back(attPriority);}
01629 
01630         {TeAttribute attNodeType;
01631         attNodeType.rep_.name_ = "node_type";
01632         attNodeType.rep_.type_ = TeUNSIGNEDINT;
01633         attNodeType.rep_.null_ = false;
01634         attList.push_back(attNodeType);}
01635 
01636         {TeAttribute attMinScale;
01637         attMinScale.rep_.name_ = "min_scale";
01638         attMinScale.rep_.type_ = TeREAL;
01639         attMinScale.rep_.decimals_ = 15;
01640         attList.push_back(attMinScale);}
01641 
01642         {TeAttribute attMaxScale;
01643         attMaxScale.rep_.name_ = "max_scale";
01644         attMaxScale.rep_.type_ = TeREAL;
01645         attMaxScale.rep_.decimals_ = 15;
01646         attList.push_back(attMaxScale);}
01647 
01648         {TeAttribute attGenAttWhere;
01649         attGenAttWhere.rep_.name_ = "generate_attribute_where";
01650         attGenAttWhere.rep_.type_ = TeSTRING;
01651         attGenAttWhere.rep_.numChar_ = 0;
01652         attList.push_back(attGenAttWhere);}
01653 
01654         {TeAttribute attGenSpatWhere;
01655         attGenSpatWhere.rep_.name_ = "generate_spatial_where";
01656         attGenSpatWhere.rep_.type_ = TeSTRING;
01657         attGenSpatWhere.rep_.numChar_ = 0;
01658         attList.push_back(attGenSpatWhere);}
01659 
01660         {TeAttribute attGenTempWhere;
01661         attGenTempWhere.rep_.name_ = "generate_temporal_where";
01662         attGenTempWhere.rep_.type_ = TeSTRING;
01663         attGenTempWhere.rep_.numChar_ = 0;
01664         attList.push_back(attGenTempWhere);}
01665 
01666         {TeAttribute attCollectionT;
01667         attCollectionT.rep_.name_ = "collection_table";
01668         attCollectionT.rep_.type_ = TeSTRING;
01669         attCollectionT.rep_.numChar_ = 255;
01670         attList.push_back(attCollectionT);}
01671 
01672         {TeAttribute attVisiRep;
01673         attVisiRep.rep_.name_ = "visible_rep";
01674         attVisiRep.rep_.type_ = TeINT;
01675         attList.push_back(attVisiRep);}
01676 
01677         {TeAttribute attEnableVis;
01678         attEnableVis.rep_.name_ = "enable_visibility";
01679         attEnableVis.rep_.type_ = TeINT;
01680         attList.push_back(attEnableVis);}
01681 
01682         {TeAttribute attLowerX;
01683         attLowerX.rep_.name_ = "lower_x";
01684         attLowerX.rep_.type_ = TeREAL;
01685         attLowerX.rep_.decimals_ = 15;
01686         attLowerX.rep_.defaultValue_ = "0.0";
01687         attList.push_back(attLowerX);}
01688 
01689         {TeAttribute attLowerY;
01690         attLowerY.rep_.name_ = "lower_y";
01691         attLowerY.rep_.type_ = TeREAL;
01692         attLowerY.rep_.decimals_ = 15;
01693         attLowerY.rep_.defaultValue_ = "0.0";
01694         attList.push_back(attLowerY);}
01695 
01696         {TeAttribute attUpperX;
01697         attUpperX.rep_.name_ = "upper_x";
01698         attUpperX.rep_.type_ = TeREAL;
01699         attUpperX.rep_.decimals_ = 15;
01700         attUpperX.rep_.defaultValue_ = "0.0";
01701         attList.push_back(attUpperX);}
01702 
01703         {TeAttribute attUpperY;
01704         attUpperY.rep_.name_ = "upper_y";
01705         attUpperY.rep_.type_ = TeREAL;
01706         attUpperY.rep_.decimals_ = 15;
01707         attUpperY.rep_.defaultValue_ = "0.0";
01708         attList.push_back(attUpperY);}
01709 
01710         {TeAttribute attCreationTime;
01711         attCreationTime.rep_.name_ = "creation_time";
01712         attCreationTime.rep_.type_ = TeDATETIME;
01713         attList.push_back(attCreationTime);}
01714 
01715         if(!createTable("te_theme", attList))
01716                 return false;   
01717 
01718         string idxName = "te_idx_theme_view_id";
01719 
01720         if(!createIndex("te_theme", idxName, "view_id"))
01721                 return false;
01722 
01723         idxName = "te_idx_theme_name";
01724 
01725         if(!createIndex("te_theme", idxName, "name"))
01726                 return false;
01727 
01728         idxName = "te_idx_theme_layer_id";
01729 
01730         return createIndex("te_theme", idxName, "layer_id");
01731 }
01732 
01733 bool TeDatabase::createGroupingTable()
01734 {
01735         TeAttributeList attList;
01736 
01737         {TeAttribute attThemeId;
01738         attThemeId.rep_.name_ = "theme_id";
01739         attThemeId.rep_.type_ = TeUNSIGNEDINT;
01740         attThemeId.rep_.isPrimaryKey_ = true;
01741         attThemeId.rep_.null_ = false;
01742         attList.push_back(attThemeId);}
01743 
01744         {TeAttribute attGNumber;
01745         attGNumber.rep_.name_ = "grouping_number";
01746         attGNumber.rep_.type_ = TeUNSIGNEDINT;
01747         attList.push_back(attGNumber);}
01748 
01749         {TeAttribute attGAttr;
01750         attGAttr.rep_.name_ = "grouping_attr";
01751         attGAttr.rep_.type_ = TeSTRING;
01752         attGAttr.rep_.numChar_ = 255;
01753         attList.push_back(attGAttr);}
01754 
01755         {TeAttribute attGAttrType;
01756         attGAttrType.rep_.name_ = "grouping_attr_type";
01757         attGAttrType.rep_.type_ = TeUNSIGNEDINT;
01758         attList.push_back(attGAttrType);}
01759 
01760         {TeAttribute attGMode;
01761         attGMode.rep_.name_ = "grouping_mode";
01762         attGMode.rep_.type_ = TeUNSIGNEDINT;
01763         attList.push_back(attGMode);}
01764 
01765         {TeAttribute attGNormAttr;
01766         attGNormAttr.rep_.name_ = "grouping_norm_attr";
01767         attGNormAttr.rep_.type_ = TeSTRING;
01768         attGNormAttr.rep_.numChar_ = 255;
01769         attList.push_back(attGNormAttr);}
01770 
01771         {TeAttribute attGStdDev;
01772         attGStdDev.rep_.name_ = "grouping_std_dev";
01773         attGStdDev.rep_.type_ = TeREAL;
01774         attGStdDev.rep_.decimals_ = 15;
01775         attGStdDev.rep_.defaultValue_ = "0.0";
01776         attList.push_back(attGStdDev);}
01777 
01778         {TeAttribute attGPrec;
01779         attGPrec.rep_.name_ = "grouping_precision";
01780         attGPrec.rep_.type_ = TeUNSIGNEDINT;
01781         attList.push_back(attGPrec);}
01782 
01783         {TeAttribute attGFunc;
01784         attGFunc.rep_.name_ = "grouping_function";
01785         attGFunc.rep_.type_ = TeSTRING;
01786         attGFunc.rep_.numChar_ = 20;
01787         attList.push_back(attGFunc);}
01788 
01789         {TeAttribute attGChronon;
01790         attGChronon.rep_.name_ = "grouping_chronon";
01791         attGChronon.rep_.type_ = TeUNSIGNEDINT;
01792         attList.push_back(attGChronon);}
01793 
01794         return createTable("te_grouping", attList);
01795 }
01796 
01797 bool TeDatabase::createThemeTablesTable()
01798 {
01799         TeAttributeList attList;
01800 
01801         {TeAttribute attThemeTableId;
01802         attThemeTableId.rep_.name_ = "theme_table_id";
01803         attThemeTableId.rep_.type_ = TeUNSIGNEDINT;
01804         attThemeTableId.rep_.isPrimaryKey_ = true;
01805         attThemeTableId.rep_.isAutoNumber_ = true;
01806         attThemeTableId.rep_.null_ = false;
01807         attList.push_back(attThemeTableId);}
01808 
01809         {TeAttribute attThemeId;
01810         attThemeId.rep_.name_ = "theme_id";
01811         attThemeId.rep_.type_ = TeUNSIGNEDINT;
01812         attThemeId.rep_.null_ = false;
01813         attList.push_back(attThemeId);}
01814 
01815         {TeAttribute attTableId;
01816         attTableId.rep_.name_ = "table_id";
01817         attTableId.rep_.type_ = TeUNSIGNEDINT;
01818         attTableId.rep_.null_ = false;
01819         attList.push_back(attTableId);}
01820 
01821         {TeAttribute attRelationId;
01822         attRelationId.rep_.name_ = "relation_id";
01823         attRelationId.rep_.type_ = TeUNSIGNEDINT;
01824         attList.push_back(attRelationId);}
01825 
01826         {TeAttribute attTableOrderId;
01827         attTableOrderId.rep_.name_ = "table_order";
01828         attTableOrderId.rep_.type_ = TeUNSIGNEDINT;
01829         attList.push_back(attTableOrderId);}
01830 
01831         if(!createTable("te_theme_table", attList))
01832                 return false;
01833 
01834         string idxName = "te_idx_theme_table_id";
01835 
01836         if(!createIndex("te_theme_table", idxName, "table_id"))
01837                 return false;
01838 
01839         idxName = "te_idx_theme_relat_id";
01840 
01841         if(!createIndex("te_theme_table", idxName, "relation_id"))
01842                 return false;
01843 
01844         idxName = "te_idx_themetable_theme";
01845 
01846         return createIndex("te_theme_table", idxName, "theme_id");
01847 }
01848 
01849 bool TeDatabase::createLegendTable ()
01850 {
01851         TeAttributeList attList;
01852 
01853         {TeAttribute attLegendId;
01854         attLegendId.rep_.name_ = "legend_id";
01855         attLegendId.rep_.type_ = TeUNSIGNEDINT;
01856         attLegendId.rep_.isPrimaryKey_ = true;
01857         attLegendId.rep_.isAutoNumber_ = true;
01858         attLegendId.rep_.null_ = false;
01859         attList.push_back(attLegendId); }
01860 
01861         {TeAttribute attThemeId;
01862         attThemeId.rep_.name_ = "theme_id";
01863         attThemeId.rep_.type_ = TeUNSIGNEDINT;
01864         attThemeId.rep_.null_ = false;
01865         attList.push_back(attThemeId);}
01866 
01867         {TeAttribute attGId;
01868         attGId.rep_.name_ = "group_id";
01869         attGId.rep_.type_ = TeINT;
01870         attList.push_back(attGId);}
01871 
01872         {TeAttribute attNObjs;
01873         attNObjs.rep_.name_ = "num_objs";
01874         attNObjs.rep_.type_ = TeUNSIGNEDINT;
01875         attList.push_back(attNObjs);}
01876 
01877         {TeAttribute attLValue;
01878         attLValue.rep_.name_ = "lower_value";
01879         attLValue.rep_.type_ = TeSTRING;
01880         attLValue.rep_.numChar_ = 255;
01881         attList.push_back(attLValue);}
01882 
01883         {TeAttribute attUValue;
01884         attUValue.rep_.name_ = "upper_value";
01885         attUValue.rep_.type_ = TeSTRING;
01886         attUValue.rep_.numChar_ = 255;
01887         attList.push_back(attUValue);}
01888 
01889         {TeAttribute attLabel;
01890         attLabel.rep_.name_ = "label";
01891         attLabel.rep_.type_ = TeSTRING;
01892         attLabel.rep_.numChar_ = 255;
01893         attList.push_back(attLabel);}
01894         
01895         if(!createTable("te_legend", attList))
01896                 return false;
01897 
01898         string idxName = "te_idx_legend_theme";
01899 
01900         return createIndex("te_legend", idxName, "theme_id");
01901 }
01902 
01903 bool TeDatabase::createVisualTable()
01904 {
01905         TeAttributeList attList;
01906 
01907         {TeAttribute attLegendId;
01908         attLegendId.rep_.name_ = "legend_id";
01909         attLegendId.rep_.type_ = TeUNSIGNEDINT;
01910         attLegendId.rep_.isPrimaryKey_ = true;
01911         attLegendId.rep_.null_ = false;
01912         attList.push_back(attLegendId);}
01913 
01914         {TeAttribute attGeomType;
01915         attGeomType.rep_.name_ = "geom_type";
01916         attGeomType.rep_.type_ = TeUNSIGNEDINT;
01917         attGeomType.rep_.isPrimaryKey_ = true;
01918         attGeomType.rep_.null_ = false;
01919         attList.push_back(attGeomType);}
01920 
01921         {TeAttribute attSymbId;
01922         attSymbId.rep_.name_ = "symb_id";
01923         attSymbId.rep_.type_ = TeINT;
01924         attList.push_back(attSymbId);}
01925 
01926         {TeAttribute attRed;
01927         attRed.rep_.name_ = "red";
01928         attRed.rep_.type_ = TeUNSIGNEDINT;
01929         attList.push_back(attRed);}
01930 
01931         {TeAttribute attGreen;
01932         attGreen.rep_.name_ = "green";
01933         attGreen.rep_.type_ = TeUNSIGNEDINT;
01934         attList.push_back(attGreen);}
01935 
01936         {TeAttribute attBlue;
01937         attBlue.rep_.name_ = "blue";
01938         attBlue.rep_.type_ = TeUNSIGNEDINT;
01939         attList.push_back(attBlue);}
01940 
01941         {TeAttribute attTransp;
01942         attTransp.rep_.name_ = "transparency";
01943         attTransp.rep_.type_ = TeUNSIGNEDINT;
01944         attList.push_back(attTransp);}
01945 
01946         {TeAttribute attWidth;
01947         attWidth.rep_.name_ = "width";
01948         attWidth.rep_.type_ = TeUNSIGNEDINT;
01949         attList.push_back(attWidth);}
01950 
01951         {TeAttribute attContourSymbId;
01952         attContourSymbId.rep_.name_ = "contour_symb_id";
01953         attContourSymbId.rep_.type_ = TeINT;
01954         attList.push_back(attContourSymbId);}
01955 
01956         {TeAttribute attContourRed;
01957         attContourRed.rep_.name_ = "contour_red";
01958         attContourRed.rep_.type_ = TeUNSIGNEDINT;
01959         attList.push_back(attContourRed);}
01960 
01961         {TeAttribute attContourGreen;
01962         attContourGreen.rep_.name_ = "contour_green";
01963         attContourGreen.rep_.type_ = TeUNSIGNEDINT;
01964         attList.push_back(attContourGreen);}
01965 
01966         {TeAttribute attContourBlue;
01967         attContourBlue.rep_.name_ = "contour_blue";
01968         attContourBlue.rep_.type_ = TeUNSIGNEDINT;
01969         attList.push_back(attContourBlue);}
01970 
01971         {TeAttribute attContourTransp;
01972         attContourTransp.rep_.name_ = "contour_transp";
01973         attContourTransp.rep_.type_ = TeUNSIGNEDINT;
01974         attList.push_back(attContourTransp);}
01975 
01976         {TeAttribute attContourWidth;
01977         attContourWidth.rep_.name_ = "contour_width";
01978         attContourWidth.rep_.type_ = TeUNSIGNEDINT;
01979         attList.push_back(attContourWidth);}
01980 
01981         {TeAttribute attSizeValue;
01982         attSizeValue.rep_.name_ = "size_value";
01983         attSizeValue.rep_.type_ = TeUNSIGNEDINT;
01984         attList.push_back(attSizeValue);}
01985 
01986         {TeAttribute attPtAngle;
01987         attPtAngle.rep_.name_ = "pt_angle";
01988         attPtAngle.rep_.type_ = TeUNSIGNEDINT;
01989         attList.push_back(attPtAngle);}
01990 
01991         {TeAttribute attFamily;
01992         attFamily.rep_.name_ = "family";
01993         attFamily.rep_.type_ = TeSTRING;
01994         attFamily.rep_.numChar_ = 255;
01995         attList.push_back(attFamily);}
01996 
01997         {TeAttribute attBold;
01998         attBold.rep_.name_ = "bold";
01999         attBold.rep_.type_ = TeUNSIGNEDINT;
02000         attList.push_back(attBold);}
02001 
02002         {TeAttribute attItalic;
02003         attItalic.rep_.name_ = "italic";
02004         attItalic.rep_.type_ = TeUNSIGNEDINT;
02005         attList.push_back(attItalic);}
02006 
02007         {TeAttribute attAlignVert;
02008         attAlignVert.rep_.name_ = "alignment_vert";
02009         attAlignVert.rep_.type_ = TeREAL;
02010         attAlignVert.rep_.decimals_ = 15;
02011         attList.push_back(attAlignVert);}
02012 
02013         {TeAttribute attAlignHoriz;
02014         attAlignHoriz.rep_.name_ = "alignment_horiz";
02015         attAlignHoriz.rep_.type_ = TeREAL;
02016         attAlignHoriz.rep_.decimals_ = 15;
02017         attList.push_back(attAlignHoriz);}
02018 
02019         {TeAttribute attTabSize;
02020         attTabSize.rep_.name_ = "tab_size";
02021         attTabSize.rep_.type_ = TeUNSIGNEDINT;
02022         attList.push_back(attTabSize);}
02023 
02024         {TeAttribute attLineSpace;
02025         attLineSpace.rep_.name_ = "line_space";
02026         attLineSpace.rep_.type_ = TeUNSIGNEDINT;
02027         attList.push_back(attLineSpace);}
02028 
02029         {TeAttribute attFixedSize;
02030         attFixedSize.rep_.name_ = "fixed_size";
02031         attFixedSize.rep_.type_ = TeUNSIGNEDINT;
02032         attList.push_back(attFixedSize);}
02033 
02034         return createTable("te_visual", attList);
02035 }
02036 
02037 
02038 bool TeDatabase::createVisualRasterTable()
02039 {       
02040         TeAttributeList attList;
02041 
02042         {TeAttribute attThemeId;
02043         attThemeId.rep_.name_ = "theme_id";
02044         attThemeId.rep_.type_ = TeUNSIGNEDINT;
02045         attThemeId.rep_.isPrimaryKey_ = true;
02046         attThemeId.rep_.null_ = false;
02047         attList.push_back(attThemeId);}
02048 
02049         {TeAttribute attBandIn;
02050         attBandIn.rep_.name_ = "band_in";
02051         attBandIn.rep_.type_ = TeUNSIGNEDINT;
02052         attBandIn.rep_.isPrimaryKey_ = true;
02053         attBandIn.rep_.null_ = false;
02054         attList.push_back(attBandIn);}
02055 
02056         {TeAttribute attBandOut;
02057         attBandOut.rep_.name_ = "band_out";
02058         attBandOut.rep_.type_ = TeUNSIGNEDINT;
02059         attList.push_back(attBandOut);}
02060 
02061         {TeAttribute attTransfType;
02062         attTransfType.rep_.name_ = "transf_type";
02063         attTransfType.rep_.type_ = TeINT;
02064         attList.push_back(attTransfType);}
02065 
02066         {TeAttribute attParam1;
02067         attParam1.rep_.name_ = "param1";
02068         attParam1.rep_.type_ = TeREAL;
02069         attParam1.rep_.decimals_ = 15;
02070         attList.push_back(attParam1);}
02071 
02072         {TeAttribute attParam2;
02073         attParam2.rep_.name_ = "param2";
02074         attParam2.rep_.type_ = TeREAL;
02075         attParam2.rep_.decimals_ = 15;
02076         attList.push_back(attParam2);}
02077 
02078         {TeAttribute attLutTable;
02079         attLutTable.rep_.name_ = "lut_table";
02080         attLutTable.rep_.type_ = TeSTRING;
02081         attLutTable.rep_.numChar_ = 255;
02082         attList.push_back(attLutTable);}
02083 
02084         return createTable("te_visual_raster", attList);
02085 }
02086 
02087 bool TeDatabase::insertVisual (TeLegendEntry *legend)
02088 {
02089         TeGeomRepVisualMap::iterator it;
02090 
02091         for ( it = legend->getVisualMap().begin(); it != legend->getVisualMap().end(); ++it)
02092         { 
02093                 string style("0"), contourStyle("0"), sizeValue("0"), width("0");
02094 
02095                 if(it->first == TePOLYGONS || it->first == TeCELLS)
02096                 {
02097                         contourStyle = Te2String(it->second->contourStyle());
02098                         style = Te2String(it->second->style());
02099                 }
02100                 else if(it->first == TeLINES)
02101                 {
02102                         width = Te2String(it->second->width());
02103                         style = Te2String(it->second->style());
02104                 }
02105                 else if(it->first == TePOINTS)
02106                 {
02107                         sizeValue = Te2String(it->second->size());
02108                         style = Te2String(it->second->style());
02109                 }
02110                 else if(it->first == TeTEXT)
02111                 {
02112                         sizeValue = Te2String(it->second->size());
02113                 }
02114                 
02115                 string insert = "INSERT INTO te_visual(legend_id, geom_type, ";
02116                 insert += " symb_id, "; 
02117                 insert += "red, green, blue, transparency, width, ";
02118                 insert += " contour_symb_id, "; 
02119                 insert += "contour_red, contour_green,";
02120                 insert += "contour_blue, contour_transp, contour_width, size_value,";
02121                 insert += "pt_angle, family, bold, italic, ";
02122                 insert += "alignment_vert, alignment_horiz, tab_size, line_space, fixed_size) ";
02123                 insert += " VALUES (";  
02124                 insert += Te2String(legend->id()) + ", ";
02125                 insert += Te2String(it->first)+ ", ";
02126                 insert += style + ", ";
02127                 insert += Te2String(it->second->color().red_) + ", ";
02128                 insert += Te2String(it->second->color().green_) + ", ";
02129                 insert += Te2String(it->second->color().blue_) + ", ";
02130                 insert += Te2String(it->second->transparency()) + ", ";
02131                 insert += width +",";
02132                 insert += contourStyle + ", ";
02133                 insert += Te2String(it->second->contourColor().red_) + ", ";
02134                 insert += Te2String(it->second->contourColor().green_) + ", ";
02135                 insert += Te2String(it->second->contourColor().blue_) + ", ";
02136                 insert += Te2String(it->second->contourTransparency()) + ", ";  
02137                 insert += Te2String(it->second->contourWidth()) + ", ";
02138 
02139                 insert += sizeValue +",";
02140                 insert += Te2String(it->second->ptAngle()) +", ";
02141 
02142                 insert += "'" + it->second->family() + "', ";
02143                 if (it->second->bold())
02144                         insert += "1, ";
02145                 else
02146                         insert += "0, ";
02147                 if (it->second->italic())
02148                         insert += "1, ";
02149                 else
02150                         insert += "0, ";
02151                 insert += Te2String(it->second->alignmentVert()) + ",";
02152                 insert += Te2String(it->second->alignmentHoriz()) + ",";
02153                 insert += Te2String(it->second->tabSize()) + ",";
02154                 insert += Te2String(it->second->lineSpace()) +",";
02155                 if (it->second->fixedSize())
02156                         insert += "1 ";
02157                 else
02158                         insert += "0";                  
02159                 insert += ")";  
02160 
02161                 if (!execute(insert))
02162                         return false;
02163         }
02164         return true;
02165 }
02166 
02167 bool TeDatabase::createCollectionTable(const string& tableName)
02168 {
02169         if(tableName.empty())
02170                 return false;
02171 
02172         TeAttributeList attList;
02173 
02174         {TeAttribute attCObjId;
02175         attCObjId.rep_.name_ = "c_object_id";
02176         attCObjId.rep_.type_ = TeSTRING;
02177         attCObjId.rep_.numChar_ = 255;
02178         attCObjId.rep_.isPrimaryKey_ = true;
02179         attCObjId.rep_.null_ = false;
02180         attList.push_back(attCObjId);}
02181 
02182         {TeAttribute attCLegendId;
02183         attCLegendId.rep_.name_ = "c_legend_id";
02184         attCLegendId.rep_.type_ = TeINT;
02185         attList.push_back(attCLegendId);}
02186 
02187         {TeAttribute attLabelX;
02188         attLabelX.rep_.name_ = "label_x";
02189         attLabelX.rep_.type_ = TeREAL;
02190         attLabelX.rep_.decimals_ = 15;
02191         attList.push_back(attLabelX);}
02192 
02193         {TeAttribute attLabelY;
02194         attLabelY.rep_.name_ = "label_y";
02195         attLabelY.rep_.type_ = TeREAL;
02196         attLabelY.rep_.decimals_ = 15;
02197         attList.push_back(attLabelY);}
02198 
02199         {TeAttribute attCLegendOwn;
02200         attCLegendOwn.rep_.name_ = "c_legend_own";
02201         attCLegendOwn.rep_.type_ = TeINT;
02202         attList.push_back(attCLegendOwn);}
02203 
02204         {TeAttribute attCObjStatus;
02205         attCObjStatus.rep_.name_ = "c_object_status";
02206         attCObjStatus.rep_.type_ = TeINT;
02207         attList.push_back(attCObjStatus);}
02208 
02209         if(!createTable(tableName, attList))
02210                 return false;
02211 
02212         string collectionId;
02213         unsigned int pos = tableName.rfind("_");
02214         if ( (pos != std::string::npos ) && (pos+1<tableName.size()) )
02215        collectionId = tableName.substr(pos+1); 
02216 
02217         string idxName = "te_idx_c" + collectionId  + "_clegid";
02218 
02219         if(!createIndex(tableName, idxName, "c_legend_id"))
02220                 return false;
02221 
02222         idxName = "te_idx_c" + collectionId + "_clegown";
02223 
02224         return createIndex(tableName, idxName, "c_legend_own");
02225 }
02226 
02227 
02228 
02229 
02230 
02231 
02232 
02233 bool
02234 TeDatabase::insertTable (TeTable &table)
02235 {
02236         string tableName = table.name();
02237         int size = table.size();
02238         TeAttributeList att = table.attributeList();
02239         TeAttributeList::iterator it = att.begin();
02240         TeAttributeList::iterator itEnd = att.end();
02241         TeTableRow row;
02242         
02243         int blobIndex=-1;
02244         if (!beginTransaction())
02245                 return false;
02246 
02247         int i;
02248         unsigned int j;
02249         for ( i = 0; i < size; i++ )    
02250         {
02251                 row = table[i];
02252                 it = att.begin();
02253                 string attrs;
02254                 string values;
02255                 j = 1;
02256                 int jj = 0;
02257                 while ( it != itEnd )
02258                 {
02259                         if (row[jj].empty() || (*it).rep_.isAutoNumber_)
02260                         {
02261                                 ++it;
02262                                 j++;
02263                                 jj++;
02264                                 continue;
02265                         }
02266                         
02267                         if (!values.empty())
02268                         {
02269                                 attrs += ", ";
02270                                 values += ", ";
02271                         }                       
02272                         attrs += (*it).rep_.name_;                      
02273                         switch ((*it).rep_.type_)
02274                         {
02275                         case TeSTRING:
02276                                 values += "'"+ escapeSequence( row[jj] ) +"'";
02277                                 break;
02278                         case TeREAL:
02279                                 {
02280                                 std::string strValue = row[jj];
02281                                 replace(strValue.begin(), strValue.end(), ',', '.');
02282                                 values += strValue;
02283                                 }
02284                                 break;
02285                         case TeINT:
02286                                 values += row[jj];
02287                                 break;
02288                         case TeDATETIME:
02289                                 {
02290                                         const string temp_dt = string(row[jj].c_str());
02291                                         TeTime t(temp_dt, (*it).dateChronon_, (*it).dateTimeFormat_, (*it).dateSeparator_, (*it).timeSeparator_, (*it).indicatorPM_);
02292                                         values += this->getSQLTime(t);
02293                                 }
02294                                 break;
02295                         case TeCHARACTER:
02296                                 values += "'" + escapeSequence(row[jj]) + "'";
02297                                 break;
02298                         case TeBLOB:
02299                                 blobIndex = jj;
02300                         default:
02301                                 values += "'"+ escapeSequence(row[jj]) +"'";
02302                                 break;
02303                         }
02304                         ++it;
02305                         j++;
02306                         jj++;
02307                 }
02308 
02309                 if (values.empty()) 
02310                         continue;
02311 
02312                 string q = "INSERT INTO "+tableName + " ("+ attrs+") " + " VALUES ("+values+") ";
02313                 if (!execute(q)) 
02314                         continue;
02315 
02316                 //If there were blob type 
02317                 if(blobIndex>=0)
02318                 {
02319                         TeAttribute uniqueAttr;
02320                         table.attrUnique(uniqueAttr);
02321                         string uniqueValue;
02322                         int indexUniquePos = table.attrUniquePosition();
02323                         if(uniqueAttr.rep_.isAutoNumber_)
02324                         {
02325                                 //we have to get the last autonumber inserted
02326                                 string sql = " SELECT MAX("+ uniqueAttr.rep_.name_ +") FROM ";
02327                                 sql += tableName;
02328                                 TeDatabasePortal* portal = getPortal();
02329                                 if(!portal)
02330                                 {
02331                                         rollbackTransaction();
02332                                         return false;
02333                                 }
02334                                 if(!portal->query(sql) || !portal->fetchRow())
02335                                 {
02336                                         delete portal;
02337                                         rollbackTransaction();
02338                                         return false;
02339                                 }
02340                                 uniqueValue = portal->getData(0);
02341                                 delete portal;
02342                         }
02343                         else
02344                                 //we can use the unique value
02345                                 uniqueValue = row[indexUniquePos];
02346                         
02347                         if(!insertBlob(tableName, att[blobIndex].rep_.name_, uniqueAttr.rep_, uniqueValue, 
02348                                 (unsigned char*) row[blobIndex].c_str(), row[blobIndex].size()))
02349                         {
02350                                 rollbackTransaction();
02351                                 return false;
02352                         } 
02353                 }
02354         }
02355         if (!commitTransaction())
02356         {
02357                 rollbackTransaction();
02358                 return false;
02359         }
02360         return true;
02361 }
02362 
02363 bool 
02364 TeDatabase::alterTable(const string& tableName, TeAttributeRep& rep, const string& oldColName)
02365 {
02366         if(!tableExist(tableName))
02367                 return false;
02368 
02369         string tab;
02370 
02371         if(oldColName.empty())
02372         {
02373                 tab = " ALTER TABLE " + tableName + " MODIFY ";
02374                 tab += rep.name_ +"  ";
02375         }
02376         else
02377         {
02378                 tab = " ALTER TABLE " + tableName + " CHANGE ";
02379                 tab += oldColName +" "+ rep.name_ +"  ";
02380         }
02381 
02382         switch (rep.type_)
02383         {
02384                 case TeSTRING:
02385                         tab += "VARCHAR(" + Te2String(rep.numChar_) + ") ";
02386                         break;
02387                         
02388                 case TeREAL:
02389                         tab += "DOUBLE(24, 15)";        
02390                         break;
02391                         
02392                 case TeINT:
02393                         tab += "INT";
02394                         break;
02395 
02396                 case TeDATETIME:
02397                         tab += "DATETIME";
02398                         break;
02399 
02400                 case TeCHARACTER:
02401                         tab += "CHAR";
02402                         break;
02403 
02404                 case TeBLOB:
02405                         tab += "LONGBLOB";
02406                         break; 
02407                 
02408                 default:
02409                         tab += "VARCHAR(" + Te2String(rep.numChar_) + ") ";
02410                         break;
02411         }
02412 
02413         tab += " NULL ";
02414 
02415         if(!execute(tab))
02416         {
02417                 if(errorMessage_.empty())
02418                         errorMessage_ = "Error alter table " + tableName + " !";
02419                 return false;
02420         }
02421 
02422         string tableId;
02423         TeDatabasePortal* portal = getPortal();
02424         string sql = "SELECT table_id FROM te_layer_table WHERE attr_table = '" + tableName + "'";
02425         if(portal->query(sql) && portal->fetchRow())
02426                 tableId = portal->getData(0);
02427 
02428         delete portal;
02429 
02430         if(tableId.empty() == false)
02431         {
02432                 if(oldColName.empty() == false) // column name changed
02433                 {
02434                          // update relation
02435                         sql = "UPDATE te_tables_relation SET related_attr = '" + rep.name_ + "'";
02436                         sql += " WHERE related_table_id = " + tableId;
02437                         sql += " AND related_attr = '" + oldColName + "'";
02438                         if(execute(sql) == false)
02439                                 return false;
02440 
02441                         sql = "UPDATE te_tables_relation SET external_attr = '" + rep.name_ + "'";
02442                         sql += " WHERE external_table_name = '" + tableName + "'";
02443                         sql += " AND external_attr = '" + oldColName + "'";
02444                         if(execute(sql) == false)
02445                                 return false;
02446 
02447                          // update grouping
02448                         sql = "UPDATE te_grouping SET grouping_attr = '" + tableName + "." + rep.name_ + "'";
02449                         sql += " WHERE grouping_attr = '" + tableName + "." + oldColName + "'";
02450                         if(execute(sql) == false)
02451                                 return false;
02452                 }
02453                 else // column type changed
02454                 {
02455                         // delete relation
02456                         sql = "DELETE FROM te_tables_relation WHERE (related_table_id = " + tableId;
02457                         sql += " AND related_attr = '" + rep.name_ + "')";
02458                         sql += " OR (external_table_name = '" + tableName + "'";
02459                         sql += " AND external_attr = '" + rep.name_ + "')";
02460                         if(execute(sql) == false)
02461                                 return false;
02462 
02463                         // delete grouping
02464                         TeDatabasePortal* portal = getPortal();
02465                         sql = "SELECT theme_id FROM te_grouping WHERE grouping_attr = '" + tableName + "." + oldColName + "'";
02466                         if(portal->query(sql) && portal->fetchRow())
02467                         {
02468                                 string themeId = portal->getData(0);
02469 
02470                                 sql = "DELETE FROM te_legend WHERE theme_id = " + themeId + " AND group_id >= 0";
02471                                 if(execute(sql) == false)
02472                                 {
02473                                         delete portal;
02474                                         return false;
02475                                 }
02476                         }
02477                         delete portal;
02478 
02479                         sql = "DELETE FROM te_grouping";
02480                         sql += " WHERE grouping_attr = '" + tableName + "." + oldColName + "'";
02481                         if(execute(sql) == false)
02482                                 return false;
02483                 }
02484         }
02485 
02486         alterTableInfoInMemory(tableName);
02487         return true;
02488 }
02489 
02490 bool 
02491 TeDatabase::alterTable(const string& oldTableName, const string& newTablename)
02492 {
02493         string sql = " ALTER TABLE "+ oldTableName +" RENAME "+ newTablename;
02494         if(!execute(sql))
02495                 return false;
02496 
02497         //update te_layer_table
02498         sql = " UPDATE te_layer_table ";
02499         sql += " SET attr_table = '"+ newTablename +"'";
02500         sql += " WHERE attr_table = '"+ oldTableName +"'";
02501         execute(sql);
02502 
02503         //update te_tables_relation
02504         sql = " UPDATE te_tables_relation ";
02505         sql += " SET external_table_name = '"+ newTablename +"'";
02506         sql += " WHERE external_table_name = '"+ oldTableName +"'";
02507         execute(sql);
02508         
02509         alterTableInfoInMemory(newTablename, oldTableName);
02510         return true;
02511 }
02512 
02513 bool 
02514 TeDatabase::insertBlob (const string& tableName, const string& columnBlob, TeAttributeRep& columnId, const string& valueId, unsigned char* data, int size)
02515 {
02516         string whereClause = columnId.name_ +" = ";
02517         switch (columnId.type_ )
02518         {
02519                 case TeSTRING:
02520                         whereClause += "'"+ valueId + "'";
02521                         break;
02522                 default:
02523                         whereClause += valueId;
02524                         break;
02525         }
02526         return (insertBlob (tableName, columnBlob, whereClause, data, size));
02527 }
02528 
02529 bool 
02530 TeDatabase::insertBlob (const string& tableName, const string& columnBlob, TeAttributeRep& columnId, const string& valueId, const string& fileName)
02531 {
02532         string whereClause = columnId.name_ +" = ";
02533         switch (columnId.type_ )
02534         {
02535                 case TeSTRING:
02536                         whereClause += "'"+ valueId + "'";
02537                         break;
02538                 default:
02539                         whereClause += valueId;
02540                         break;
02541         }
02542         return (insertBlob(tableName, columnBlob, whereClause, fileName));
02543 }
02544 
02545 bool 
02546 TeDatabase::insertBlob (const string& tableName, const string& columnBlob, const string& whereClause, const string& fileName)
02547 {
02548         unsigned char   *cdata = 0;
02549         int             size;
02550         FILE    *fp = 0;
02551         
02552         struct  stat buf;
02553         int             result;
02554         
02555         result = stat(fileName.c_str(), &buf);
02556         
02557         if( result != 0 )
02558                 return false;
02559         
02560         size = buf.st_size;
02561 
02562         cdata = new unsigned char[size];
02563         fp = fopen(fileName.c_str(), "rb");
02564         fread(cdata, sizeof(unsigned char), size, fp); 
02565 
02566         bool status = insertBlob (tableName, columnBlob, whereClause, cdata, size);
02567 
02568         if(fp)
02569                 fclose(fp);
02570 
02571         if (cdata)
02572                 delete []cdata;
02573 
02574         return status;
02575 }
02576 
02577 bool 
02578 TeDatabase::getAttrTables(TeAttrTableVector& atts, TeAttrTableType attType)
02579 {
02580         TeDatabasePortal* portal = this->getPortal();
02581         if(!portal)
02582         {
02583                 this->errorMessage_ = "N�o foi poss�vel abrir portal para o banco";
02584                 return false;
02585         }
02586         
02587         // Get layer tables     
02588         string get =  " SELECT * FROM te_layer_table"; 
02589         if (attType != TeAllAttrTypes)
02590                 get += " WHERE attr_table_type = " + Te2String(attType);
02591         if (!portal->query(get))
02592         {       
02593                 delete portal;
02594                 return false;
02595         }
02596 
02597         while (portal->fetchRow())
02598         {
02599                 TeTable attTable;
02600                 if(!portal->getAttrTable(attTable))
02601                 {
02602                         delete portal;
02603                         return false;
02604                 }
02605                 
02606                 TeAttributeList attrList;
02607                 getAttributeList(attTable.name(), attrList);
02608 
02609                 attTable.setAttributeList(attrList);
02610 
02611                 atts.push_back(attTable);
02612         }
02613         delete portal;
02614         return (atts.size() > 0);
02615 }
02616 
02617 bool
02618 TeDatabase::updateTable (TeTable &table)
02619 {
02620         TeAttributeList& att = table.attributeList();
02621         unsigned int i;
02622         string uniqueVal;
02623         bool isUniqueValString = false;
02624         
02625         if (!beginTransaction())
02626                 return false;
02627 
02628         string uniqueName = table.uniqueName(); // primary key explicitly defined or 
02629         if (table.uniqueName().empty())                 // check in the attribute list
02630         {                                                               
02631                 for (i=0; i<att.size(); ++i)
02632                         if (att[i].rep_.isPrimaryKey_)
02633                         {
02634                                 uniqueName = att[i].rep_.name_;
02635                                 table.setUniqueName(uniqueName);
02636                                 break;
02637                         }
02638         }
02639 
02640         int blobIndex = -1;
02641         TeAttributeList::iterator it;
02642         TeTableRow row;
02643         unsigned int j;
02644         bool useComma = false;
02645         for (i = 0; i < table.size(); i++  )
02646         {
02647                 row = table[i];
02648                 it = att.begin();
02649                 string q;
02650                 j = 1;
02651                 int jj = 0;
02652     useComma = false;  
02653                 while ( it != att.end() )
02654                 {
02655                         if (uniqueName != (*it).rep_.name_)
02656                         {
02657                                 if ((*it).rep_.isAutoNumber_)
02658                                 {
02659                                         ++it;
02660                                         j++;
02661                                         jj++;
02662                                         continue;
02663                                 }                       
02664 
02665                                 if ((*it).rep_.type_ != TeBLOB)
02666                                 {
02667                                         if(useComma == true)
02668                                         {
02669                                                 q += ", ";
02670                                         }
02671                                         else
02672                                         {
02673                                                 useComma = true;
02674                                         }
02675                                         
02676                                         q += (*it).rep_.name_ + " = ";
02677                                         
02678                                         if(row[jj].empty())
02679                                         {
02680                                                 q += " null";
02681 
02682                                                 ++it;
02683                                                 j++;
02684                                                 jj++;
02685                                                 continue;
02686                                         }
02687                                 }
02688                                 
02689                                 switch ((*it).rep_.type_)
02690                                 {
02691                                         case TeSTRING:                                          
02692                                                 q += "'"+escapeSequence(row[jj])+"'";
02693                                         break;
02694                                         case TeREAL:
02695                                         {
02696                                                 std::string value = row[jj];
02697                                                 replace(value.begin(), value.end(), ',', '.');
02698                                                 q += value;
02699                                         }
02700                                         break;
02701                                         case TeINT:
02702                                                 q += row[jj];
02703                                         break;
02704                                         case TeDATETIME:
02705                                         {
02706                                                 const string temp_dt = string(row[jj].c_str());
02707                                                 TeTime t(temp_dt, (*it).dateChronon_, (*it).dateTimeFormat_, (*it).dateSeparator_, (*it).timeSeparator_, (*it).indicatorPM_);
02708                                                 q += this->getSQLTime(t);
02709                                         }
02710                                         break;
02711                                         case TeCHARACTER:
02712                                                 q += "'" + escapeSequence(row[jj]) + "'";
02713                                         break;
02714                                         case TeBLOB:
02715                                                 blobIndex = jj;
02716                                         break;
02717                                         default:
02718                                                 q += "'"+escapeSequence(row[jj])+"'";
02719                                         break;
02720                                 }
02721                                 
02722                         }
02723                         else
02724                         {
02725                                 uniqueVal = row[jj];
02726                                 isUniqueValString = ((*it).rep_.type_ == TeSTRING);
02727                         }
02728                         ++it;
02729                         j++;
02730                         jj++;
02731                 }
02732                 if (q.empty())
02733                         continue;
02734                 
02735                 if (!uniqueName.empty() && !uniqueVal.empty())  
02736                 {
02737                         if(isUniqueValString)
02738                                 q += " WHERE " + uniqueName + " = '" + uniqueVal +"'";
02739                         else
02740                                 q += " WHERE " + uniqueName + " = " + uniqueVal;
02741                 }
02742                 string sql = "UPDATE "+ table.name() + " SET " + q;
02743                 if (!execute(sql))
02744                 {
02745                         rollbackTransaction();
02746                         return false;
02747                 }
02748 
02749                 //verify if there was blob type
02750                 if(blobIndex>=0)
02751                 {
02752                         TeAttribute uniqueAttr;
02753                         table.attrUnique(uniqueAttr);
02754                         if(!insertBlob (table.name(), att[blobIndex].rep_.name_, uniqueAttr.rep_, uniqueVal, 
02755                                 (unsigned char*)row[blobIndex].c_str(), row[blobIndex].size()))
02756                         {
02757                                 rollbackTransaction();
02758                                 return false;
02759                         }
02760                 }
02761         }
02762         if (!commitTransaction())
02763         {
02764                 rollbackTransaction();
02765                 return false;
02766         }
02767         return true;
02768 }
02769 
02770 
02771 bool 
02772 TeDatabase::loadTable(const string& tableName, TeTable &table)
02773 {
02774         bool isreg = false;
02775         table.name(tableName);
02776         if (loadTableInfo(table)) // this is not a registered table...
02777                 isreg = true;
02778 
02779         TeDatabasePortal* portal = this->getPortal();
02780         if (!portal)
02781                 return false;
02782 
02783         string q ="SELECT * FROM " + tableName;
02784         if (!portal->query(q))
02785         {       
02786                 delete portal;
02787                 return false;
02788         }
02789         if (!isreg)
02790                 table.setAttributeList(portal->getAttributeList());
02791         while (portal->fetchRow())
02792         {
02793                 TeTableRow row;
02794                 for (int j = 0; j < portal->numFields(); j++)
02795                 {
02796            TeAttribute& attr = table.attributeList()[j];
02797            if (attr.rep_.type_ == TeBLOB)
02798            {
02799                unsigned char* data = NULL;
02800                long size = 0;
02801                portal->getBlob (attr.rep_.name_, data, size);
02802                string blobValue;
02803                if (data != NULL)
02804                {                                      
02805                                    blobValue.assign((char*)data, size);
02806                                    delete [] data;
02807                    data = NULL;
02808                }
02809                row.push_back(blobValue);
02810            }
02811            else
02812                row.push_back (portal->getData (j)); 
02813                 }
02814                 table.add(row);
02815         }
02816         delete portal;
02817         return true;
02818 }
02819 
02820 bool 
02821 TeDatabase::selectTable (const string& tableName, const string& criteria, TeTable &table)
02822 {
02823         bool isreg = false;
02824         table.name(tableName);
02825         if (loadTableInfo(table)) // this is not a registered table...
02826                 isreg = true;
02827 
02828         TeDatabasePortal* portal = this->getPortal();
02829         if (!portal)
02830                 return false;
02831 
02832         string q ="SELECT * FROM " + tableName;
02833         if (!criteria.empty())
02834                 q += " WHERE " + criteria;
02835 
02836         if (!portal->query(q))
02837         {       
02838                 delete portal;
02839                 return false;
02840         }
02841         if (!isreg)
02842                 table.setAttributeList(portal->getAttributeList());
02843         while (portal->fetchRow())
02844         {
02845                 TeTableRow row;
02846                 for(int i = 0; i < portal->numFields(); i++)
02847                         row.push_back(portal->getData(i));
02848                 table.add(row);
02849         }
02850         delete portal;
02851         return true;
02852 }
02853 
02854 bool 
02855 TeDatabase::updateView (TeView *view)
02856 {
02857         TeProjection* proj = view->projection();
02858         if (proj)
02859         {
02860                 if (proj->id() <= 0)
02861                         this->insertProjection(view->projection());
02862                 else
02863                         this->updateProjection(view->projection());
02864         }
02865         else
02866         {
02867                 errorMessage_ = "N�o � poss�vel atualizar vista sem proje��o!";
02868                 return false;
02869         }
02870 
02871         string sql = "UPDATE te_view SET projection_id=" + Te2String(proj->id());
02872         sql+= ", name='" + view->name() + "'";
02873         sql+= ", user_name='" + view->user() + "'";
02874         sql+= ", visibility= " + Te2String((int)view->isVisible());
02875         sql+= ", lower_x = " + Te2String(view->getCurrentBox().lowerLeft().x());
02876         sql+= ", lower_y = " + Te2String(view->getCurrentBox().lowerLeft().y());
02877         sql+= ", upper_x = " + Te2String(view->getCurrentBox().upperRight().x());
02878         sql+= ", upper_y = " + Te2String(view->getCurrentBox().upperRight().y());
02879         if(view->getCurrentTheme() > 0)
02880                 sql+= ", current_theme = " + Te2String(view->getCurrentTheme());
02881         else
02882                 sql+= ", current_theme = null";
02883         sql +=" WHERE view_id = " + Te2String(view->id());
02884 
02885         if (!this->execute (sql))
02886                 return false;
02887 
02888         TeViewTree* tree = view->root();
02889         if (tree) 
02890                 return  updateViewTree(tree);
02891         return true;
02892 
02893 }
02894 
02895 
02896 bool 
02897 TeDatabase::loadViewSet (const string& user, const bool& loadAttrList, const string& visualType)
02898 {
02899         std::vector<TeAbstractTheme*> vecExternalThemes;
02900 
02901         //clear view map
02902         TeViewMap::iterator it = metaModel_->viewMap().begin();
02903         while (it != metaModel_->viewMap().end())
02904         {
02905                 if(it->second)
02906                         delete it->second;
02907                 ++it;
02908         }
02909         metaModel_->viewMap().clear();
02910 
02911         //clear theme map
02912         TeThemeMap::iterator itTheme = metaModel_->themeMap().begin();
02913         while (itTheme != metaModel_->themeMap().end())
02914         {
02915                 if(itTheme->second)
02916                         delete itTheme->second;
02917                 ++itTheme;
02918         }
02919 
02920         //clear invalid theme map
02921         itTheme = metaModel_->invalidThemeMap().begin();
02922         while (itTheme != metaModel_->invalidThemeMap().end())
02923         {
02924                 if(itTheme->second)
02925                         delete itTheme->second;
02926                 ++itTheme;
02927         }
02928         metaModel_->invalidThemeMap().clear();
02929         metaModel_->themeMap().clear();
02930         metaModel_->legendMap().clear();
02931         
02932         //load view, projection, themes and grouping
02933         string sql = " SELECT ";
02934         sql += " te_view.*, "; //0-9  (10 columns)
02935         sql += " te_projection.*, "; //10 - 21 (12 columns)
02936         sql += " te_datum.radius, te_datum.flattening, te_datum.dx, te_datum.dy, te_datum.dz, "; //22 - 26 (5 columns)
02937         sql += " te_theme.*, "; // 27 - 46 (20 columns)
02938         sql += " te_grouping.*, "; //47 - 56 (10 columns)
02939         sql += " te_legend.*,  "; // 57 - 63    (7 columns)
02940         sql += " te_visual.*, "; //  64 - 87 (24 columns)
02941         sql += " te_visual_raster.* "; //  88 (7 columns)
02942 
02943         sql += " FROM (((((((te_view INNER JOIN te_projection ";
02944         sql += " ON te_view.projection_id = te_projection.projection_id) ";
02945         sql += " LEFT JOIN te_theme ON te_view.view_id = te_theme.view_id ) ";
02946         sql += " LEFT JOIN te_grouping ON te_theme.theme_id = te_grouping.theme_id) ";
02947         sql += " LEFT JOIN te_legend ON te_theme.theme_id = te_legend.theme_id) ";
02948         sql += " LEFT JOIN te_visual ON te_visual.legend_id = te_legend.legend_id) ";
02949         sql += " LEFT JOIN te_visual_raster ON te_theme.theme_id = te_visual_raster.theme_id) ";
02950         sql += " LEFT JOIN te_datum ON te_projection.datum = te_datum.name) ";
02951                         
02952         sql += " WHERE ";
02953         if (!user.empty())
02954                 sql += " te_view.user_name = '" + user + "'";
02955         else
02956                 sql += " te_view.user_name = '" + this->user() + "'";
02957         sql += " ORDER BY te_view.view_id, te_theme.priority, te_theme.theme_id, te_legend.legend_id, ";
02958         sql += " te_legend.group_id, te_visual.geom_type, te_visual_raster.band_in  "; 
02959 
02960         TeDatabasePortal* portal = this->getPortal();
02961         if (!portal)
02962                 return false;
02963         
02964         if (!portal->query(sql))
02965         {       
02966                 delete portal;
02967                 return false;
02968         }
02969         
02970         int lastViewId = -1;
02971         TeView *view = 0;
02972         bool hasNewRow = portal->fetchRow(); //idicates that this portal was fetched 
02973         while(hasNewRow)
02974         {
02975                 //load view and its projection 
02976                 if(lastViewId!=atoi(portal->getData(0)))
02977                 {
02978                         //store the last view
02979                         if(view)
02980                         {
02981                                 metaModel_->viewMap()[view->id()] = view;
02982                                 view = 0;
02983                         }
02984                         TeProjection* proj = 0;
02985                         if(!portal->getProjection(&proj, 10)) //load projection
02986                         {
02987                                 delete portal;
02988                                 return false;
02989                         }
02990                         view = new TeView();
02991                         if(!portal->getView(*view, 0)) //load view
02992                         {
02993                                 delete portal;
02994                                 delete view;
02995                                 return false;
02996                         }
02997                         if (proj != 0)
02998                                 view->projection(proj);
02999                         lastViewId = view->id();
03000                 }  
03001                 
03002                 //make the rigth object
03003                 string aux = portal->getData(27);
03004                 if (aux.empty())
03005                 {
03006                         hasNewRow = portal->fetchRow();
03007                         continue;
03008                 }
03009                 TeViewNodeType viewNodeType = (TeViewNodeType)portal->getInt(33);
03010                 TeViewNode* viewNode = TeViewNodeFactory::make(viewNodeType);
03011 
03012                 if(!viewNode)
03013                 {
03014                         int currentThemeId = portal->getInt(27);
03015 
03016                         while((hasNewRow = portal->fetchRow()) && (portal->getInt(27) == currentThemeId))
03017                                 ;
03018 
03019                         continue;
03020                 }
03021 
03022                 if(viewNodeType == TeTREE)
03023                 {
03024                         viewNode = loadViewTree(view, portal->getInt(27), loadAttrList, visualType); 
03025                         view->add(viewNode);
03026 
03027                         hasNewRow = portal->fetchRow();
03028                         continue;
03029                 }
03030                 else 
03031                 {
03032                         if(!portal->getTheme(static_cast<TeAbstractTheme&>(*viewNode), 27))
03033                         {
03034                                 delete viewNode;
03035                                 delete portal;
03036                                 return false;
03037                         }
03038 
03039                         if(viewNodeType == TeTHEME)
03040                         {
03041                                 //load layer
03042                                 int id = static_cast<TeTheme*>(viewNode)->layerId();
03043                                 TeLayerMap::iterator it = metaModel_->layerMap().find(id);
03044                                 if (it == metaModel_->layerMap().end())
03045                                         loadLayerSet(loadAttrList);
03046                                 
03047                                 static_cast<TeTheme*>(viewNode)->layer(metaModel_->layerMap()[id]);
03048                         }
03049                 }
03050                 
03051                 TeAbstractTheme* theme = static_cast<TeAbstractTheme*>(viewNode);
03052 
03053                 //load grouping 
03054                 TeGrouping group;
03055                 if(portal->getGrouping(group, 47))
03056                         theme->grouping(group);
03057 
03058                 //load all legends of this theme
03059                 //and its visual
03060                 bool hasLegsToThisTheme = true;
03061                 while(hasLegsToThisTheme)
03062                 {
03063                         //legend
03064                         TeLegendEntry legend;
03065                         if(!portal->getLegend(legend, 57))
03066                         {
03067                                 delete theme;
03068                                 delete view;
03069                                 delete portal;
03070                                 return false;
03071                         }
03072 
03073                         //visual
03074                         TeRasterVisual* rasterVisual = theme->rasterVisual();
03075                         if(rasterVisual == NULL)
03076                         {
03077                                 rasterVisual = new TeRasterVisual();
03078                         }
03079                         bool hasVisualToThisLeg = true;
03080                         bool hasRasterVisual = false;
03081                         while(hasVisualToThisLeg)
03082                         {
03083                                 TeVisual* visual = TeVisualFactory::make(visualType);
03084                                 TeGeomRep geomRep;
03085                                 if(portal->getVisual(visual, geomRep, 64))
03086                                         legend.setVisual(visual, geomRep);
03087                                                                         
03088                                 if(rasterVisual != NULL && portal->getRasterVisual(*rasterVisual, 88))
03089                                         hasRasterVisual=true;
03090                                 
03091                                 hasNewRow = portal->fetchRow();
03092                                 if(!hasNewRow || portal->getInt(59)!= legend.group() || portal->getInt(57)!= legend.id())
03093                                         hasVisualToThisLeg = false;
03094                         }
03095 
03096                         //Set raster visual to this theme
03097                         if(hasRasterVisual)
03098                                 theme->rasterVisual(rasterVisual);
03099                         else
03100                                 delete rasterVisual;
03101 
03102                         //Set legend to this theme
03103                         theme->legend(legend); 
03104                                                                                                                         
03105                         //fill legend buffer
03106                         if(legend.group() == -6)        
03107                                 metaModel_->legendMap()[legend.id()] = &theme->queryAndPointingLegend();
03108                         else if(legend.group() == -5)   
03109                                 metaModel_->legendMap()[legend.id()] = &theme->queryLegend(); 
03110                         else if (legend.group() == -4)
03111                                 metaModel_->legendMap()[legend.id()] = &theme->pointingLegend(); 
03112                         else if (legend.group() == -3)
03113                                 metaModel_->legendMap()[legend.id()] = &theme->defaultLegend(); 
03114                         else if (legend.group() == -2)
03115                                 metaModel_->legendMap()[legend.id()] = &theme->withoutDataConnectionLegend(); 
03116                         else if (legend.group() == -1)
03117                                 metaModel_->legendMap()[legend.id()] = &theme->outOfCollectionLegend(); 
03118                         else if (legend.group() == -10) //own legend
03119                         {
03120                                 TeLegendEntry* legendTemp = new TeLegendEntry(legend);
03121                                 metaModel_->legendMap()[legend.id()] = legendTemp;
03122                         }                               
03123                         
03124                         if(!hasNewRow || portal->getInt(27)!= theme->id())
03125                                 hasLegsToThisTheme = false;
03126                 }
03127                         
03128                 for (unsigned int i = 0; i < theme->legend().size(); ++i)
03129                         metaModel_->legendMap()[theme->legend()[i].id()] = &theme->legend()[i];
03130 
03131                 if(viewNode->type()==(int)TeTHEME)
03132                 {
03133                         //load theme table
03134                         if(!loadThemeTable(static_cast<TeTheme*>(theme), loadAttrList))
03135                         {
03136                                 delete portal;
03137                                 return false;
03138                         }
03139                 }
03140                 
03141                 if(viewNode->type() != (int)TeEXTERNALTHEME)
03142                 {
03143                         //load specific theme parameters
03144                         if(!theme->loadMetadata(this))
03145                         {
03146                                 metaModel_->invalidThemeMap()[viewNode->id()] = theme;
03147                                 continue;
03148                         }
03149                         metaModel_->themeMap()[viewNode->id()] = theme;
03150                 }
03151                 else
03152                 {
03153                         vecExternalThemes.push_back(theme);
03154                 }
03155                 
03156                 view->add(viewNode);
03157         }
03158 
03159         //store the last view
03160         if(view)
03161         {
03162                 metaModel_->viewMap()[view->id()] = view;
03163                 view = 0;
03164         }
03165 
03166         if(!vecExternalThemes.empty())
03167         {
03168                 if(!loadExternalThemes(vecExternalThemes))
03169                 {
03170                         //todos se tornam invalidos
03171                         for(unsigned int i = 0; i < vecExternalThemes.size(); ++i)
03172                         {
03173                                 TeView* view = metaModel_->viewMap()[vecExternalThemes[i]->view()];
03174 
03175                                 invalidThemeMap()[vecExternalThemes[i]->id()] = vecExternalThemes[i];
03176                                 view->remove(vecExternalThemes[i]->id());
03177                         }
03178                         return true;
03179                 }
03180 
03181                 TeViewMap::iterator itView = metaModel_->viewMap().begin();
03182                 while(itView != metaModel_->viewMap().end())
03183                 {
03184                         unsigned int i = 0;
03185                         while(i < itView->second->themes().size())
03186                         {
03187                                 unsigned int id = itView->second->themes()[i]->id();
03188                                 if(invalidThemeMap().find(id) != invalidThemeMap().end())
03189                                 {
03190                                         itView->second->remove(id);
03191                                 }
03192                                 else
03193                                 {
03194                                         ++i;
03195                                 }
03196                         }
03197                         ++itView;
03198                 }
03199         }
03200 
03201         delete portal;
03202         return true;
03203         
03204 }
03205 
03206 TeViewTree* 
03207 TeDatabase::loadViewTree(TeView* view, int id, const bool& loadAttrList, const string& visualType)
03208 {
03209         if( view == 0) 
03210                 return 0;
03211         
03212         TeDatabasePortal* portal = this->getPortal();
03213         if (!portal)
03214                 return 0;
03215 
03216         string q;
03217         TeViewTree *node = 0;
03218 
03219         if (id != 0)
03220         {
03221                 q = "SELECT * FROM te_theme";
03222                 q += " WHERE view_id = " + Te2String (view->id());
03223                 q += " AND theme_id = " + Te2String(id);
03224 
03225                 if (!portal->query(q) || !portal->fetchRow())
03226                 {
03227                         delete portal;
03228                         return 0;
03229                 }
03230                 TeViewNodeType type = (TeViewNodeType)portal->getInt("node_type");
03231                 if(type != TeTREE)
03232                 {
03233                         portal->freeResult();
03234                         delete portal;
03235                         return NULL;
03236                 }
03237                 node = portal->getViewTree();
03238                 portal->freeResult();
03239         }
03240 
03241         q ="SELECT * FROM te_theme";
03242         q += " WHERE view_id = " + Te2String (view->id());
03243         q += " AND parent_id = " + Te2String(id);
03244         q += " ORDER BY priority ASC";
03245 
03246         if (!portal->query(q))
03247         {
03248                 delete portal;
03249                 return node;
03250         }
03251 
03252         while (portal->fetchRow())
03253         {
03254                 TeViewNodeType childType = (TeViewNodeType)portal->getInt("node_type");
03255                 TeViewNode *childNode;
03256                 if (childType == TeTHEME)
03257                 {
03258                         childNode = new TeTheme();
03259                         childNode->id(portal->getInt(0));
03260                         this->loadTheme((TeTheme*)childNode, loadAttrList, visualType);
03261                 } 
03262                 else
03263                 {
03264                         childNode = loadViewTree(view, portal->getInt("theme_id"), loadAttrList, visualType);
03265                 }
03266 
03267                 if(id == 0)
03268                 {
03269                         view->add(childNode);
03270                 } 
03271                 else
03272                 {
03273 //                      view->addTheme(childNode);
03274                         node->add(childNode);
03275                 }
03276         }
03277         delete portal;
03278         return node;
03279 }
03280 
03281 bool 
03282 TeDatabase::loadView (TeView* view, const bool& loadAttrList, const string& visualType)
03283 {
03284     std::vector<TeAbstractTheme*> vecExternalThemes;
03285 
03286     string rest;
03287     if (view->id() > 0)
03288         rest = " te_view.view_id=" + Te2String(view->id());
03289     else if (!view->name().empty())
03290     {
03291         rest = " te_view.name='" + view->name() + "'";
03292 
03293         if(!view->user().empty())
03294             rest += " AND te_view.user_name='" + view->user() + "'";
03295     }
03296     else
03297         return false;
03298 
03299     //load view, projection, themes and grouping
03300     string sql = " SELECT ";
03301     sql += " te_view.*, "; //0-9  (10 columns)
03302     sql += " te_projection.*, "; //10 - 21 (12 columns)
03303         sql += " te_datum.radius, te_datum.flattening, te_datum.dx, te_datum.dy, te_datum.dz, "; //22 - 26 (5 columns)
03304     sql += " te_theme.*, "; // 27 - 46 (20 columns)
03305     sql += " te_grouping.*, "; //47 - 56 (10 columns)
03306     sql += " te_legend.*,  "; // 57 - 63    (7 columns)
03307     sql += " te_visual.*, "; //  64 - 87 (24 columns)
03308     sql += " te_visual_raster.* "; //  88 (7 columns)
03309 
03310     sql += " FROM (((((((te_view INNER JOIN te_projection ";
03311     sql += " ON te_view.projection_id = te_projection.projection_id) ";
03312     sql += " LEFT JOIN te_theme ON te_view.view_id = te_theme.view_id ) ";
03313     sql += " LEFT JOIN te_grouping ON te_theme.theme_id = te_grouping.theme_id) ";
03314     sql += " LEFT JOIN te_legend ON te_theme.theme_id = te_legend.theme_id) ";
03315     sql += " LEFT JOIN te_visual ON te_visual.legend_id = te_legend.legend_id) ";
03316     sql += " LEFT JOIN te_visual_raster ON te_theme.theme_id = te_visual_raster.theme_id) ";
03317         sql += " LEFT JOIN te_datum ON te_projection.datum = te_datum.name) ";
03318 
03319     sql += " WHERE "+ rest;
03320     sql += " ORDER BY te_view.view_id, te_theme.priority, te_theme.theme_id, te_legend.legend_id, ";
03321     sql += " te_legend.group_id, te_visual.geom_type, te_visual_raster.band_in  ";
03322 
03323     TeDatabasePortal* portal = this->getPortal();
03324     if (!portal)
03325         return false;
03326 
03327     if (!portal->query(sql) || !portal->fetchRow())
03328     {
03329         delete portal;
03330         return false;
03331     }
03332     //load projection
03333     TeProjection* proj = 0;
03334     if(!portal->getProjection(&proj, 10))
03335     {
03336         delete portal;
03337         return false;
03338     }
03339     //load view
03340     if(!portal->getView(*view, 0))
03341     {
03342         delete portal;
03343         return false;
03344     }
03345     if (proj != 0)
03346         view->projection(proj);
03347 
03348     bool hasNewRow = true;
03349 
03350     while(hasNewRow)
03351     {
03352         string aux = portal->getData(27);
03353         if (aux.empty())
03354         {
03355             hasNewRow = portal->fetchRow();
03356             continue;
03357         }
03358         TeViewNodeType viewNodeType = (TeViewNodeType)portal->getInt(33);
03359         //make the rigth object
03360         TeViewNode* viewNode = TeViewNodeFactory::make(viewNodeType);
03361 
03362         if(!viewNode)
03363         {
03364             int currentThemeId = portal->getInt(27);
03365 
03366             while((hasNewRow = portal->fetchRow()) && (portal->getInt(27) == currentThemeId))
03367                     ;
03368 
03369             continue;
03370         }
03371 
03372         if(viewNodeType == TeTREE)
03373         {
03374             viewNode = loadViewTree(view, portal->getInt(27), loadAttrList, visualType);
03375             view->add(viewNode);
03376             hasNewRow = portal->fetchRow();
03377             continue;
03378         }
03379         else
03380         {
03381             if(!portal->getTheme(static_cast<TeAbstractTheme&>(*viewNode), 27))
03382             {
03383                 delete viewNode;
03384                 delete portal;
03385                 return false;
03386             }
03387 
03388             if(viewNodeType == TeTHEME)
03389             {
03390                 //load layer
03391                 int id = static_cast<TeTheme*>(viewNode)->layerId();
03392                 TeLayerMap::iterator it = metaModel_->layerMap().find(id);
03393                 if (it == metaModel_->layerMap().end())
03394                         loadLayerSet(loadAttrList);
03395 
03396                 static_cast<TeTheme*>(viewNode)->layer(metaModel_->layerMap()[id]);
03397             }
03398         }
03399 
03400         TeAbstractTheme* abstractTheme = static_cast<TeAbstractTheme*>(viewNode);
03401 
03402         //load grouping
03403         TeGrouping group;
03404         if(portal->getGrouping(group, 47))
03405             abstractTheme->grouping(group);
03406 
03407         //load all legends of this theme
03408         //and its visual
03409         bool hasLegsToThisTheme = true;
03410         while(hasLegsToThisTheme)
03411         {
03412             //legend
03413             TeLegendEntry legend;
03414             if(!portal->getLegend(legend, 57))
03415             {
03416                 delete viewNode;
03417                 delete portal;
03418                 return false;
03419             }
03420 
03421             //visual
03422             TeRasterVisual* rasterVisual = abstractTheme->rasterVisual();
03423             if(rasterVisual == NULL)
03424                 rasterVisual = new TeRasterVisual();
03425 
03426             bool hasVisualToThisLeg = true;
03427             bool hasRasterVisual = false;
03428             while(hasVisualToThisLeg)
03429             {
03430                 TeVisual* visual = TeVisualFactory::make(visualType);
03431                 TeGeomRep geomRep;
03432                 if(portal->getVisual(visual, geomRep, 64))
03433                     legend.setVisual(visual, geomRep);
03434 
03435                 if(rasterVisual != NULL && portal->getRasterVisual(*rasterVisual, 88))
03436                     hasRasterVisual=true;
03437 
03438                 hasNewRow = portal->fetchRow();
03439                 if(!hasNewRow || portal->getInt(59)!= legend.group() || portal->getInt(57)!= legend.id())
03440                     hasVisualToThisLeg = false;
03441             }
03442 
03443             //Set raster visual to this theme
03444             if(hasRasterVisual)
03445                 abstractTheme->rasterVisual(rasterVisual);
03446             else
03447                 delete rasterVisual;
03448 
03449             //Set legend to this theme
03450             abstractTheme->legend(legend);
03451 
03452             //fill legend buffer
03453             if(legend.group() == -6)
03454                 metaModel_->legendMap()[legend.id()] = & abstractTheme->queryAndPointingLegend();
03455             else if(legend.group() == -5)
03456                 metaModel_->legendMap()[legend.id()] = & abstractTheme->queryLegend();
03457             else if (legend.group() == -4)
03458                 metaModel_->legendMap()[legend.id()] = & abstractTheme->pointingLegend();
03459             else if (legend.group() == -3)
03460                 metaModel_->legendMap()[legend.id()] = & abstractTheme->defaultLegend();
03461             else if (legend.group() == -2)
03462                 metaModel_->legendMap()[legend.id()] = & abstractTheme->withoutDataConnectionLegend();
03463             else if (legend.group() == -1)
03464                 metaModel_->legendMap()[legend.id()] = & abstractTheme->outOfCollectionLegend();
03465             else if (legend.group() == -10) //own legend
03466             {
03467                 TeLegendEntry* legendTemp = new TeLegendEntry(legend);
03468                 metaModel_->legendMap()[legend.id()] = legendTemp;
03469             }
03470 
03471             if(!hasNewRow || portal->getInt(27)!= abstractTheme->id())
03472                 hasLegsToThisTheme = false;
03473         }
03474 
03475         for (unsigned int i = 0; i < abstractTheme->legend().size(); ++i)
03476             metaModel_->legendMap()[abstractTheme->legend()[i].id()] = & abstractTheme->legend()[i];
03477 
03478         if(viewNode->type()==(int)TeTHEME)
03479         {
03480             //load theme table
03481             if(!loadThemeTable(static_cast<TeTheme*>(abstractTheme), loadAttrList))
03482             {
03483                 delete portal;
03484                 return false;
03485             }
03486         }
03487 
03488         if(viewNode->type() != (int)TeEXTERNALTHEME)
03489         {
03490             //load specific theme parameters
03491             if(!abstractTheme->loadMetadata(this))
03492             {
03493                 metaModel_->invalidThemeMap()[viewNode->id()] = abstractTheme;
03494                 continue;
03495             }
03496             metaModel_->themeMap()[viewNode->id()] = abstractTheme;
03497         }
03498         else
03499         {
03500             vecExternalThemes.push_back(abstractTheme);
03501         }
03502 
03503         view->add(viewNode);
03504     }
03505 
03506     delete portal;
03507     portal = NULL;
03508         
03509          if(metaModel_->viewMap().find(view->id()) != metaModel_->viewMap().end())
03510          {
03511                 delete metaModel_->viewMap()[view->id()];
03512          }
03513 
03514         metaModel_->viewMap()[view->id()] = view;
03515 
03516     if(!vecExternalThemes.empty())
03517     {
03518         if(!loadExternalThemes(vecExternalThemes))
03519         {
03520             //todos se tornam invalidos
03521             for(unsigned int i = 0; i < vecExternalThemes.size(); ++i)
03522             {
03523                 invalidThemeMap()[vecExternalThemes[i]->id()] = vecExternalThemes[i];
03524                 view->remove(vecExternalThemes[i]->id());
03525             }
03526         }
03527         else
03528         {
03529             unsigned int i = 0;
03530             while(i < view->themes().size())
03531             {
03532                 unsigned int id = view->themes()[i]->id();
03533                 
03534                 if(invalidThemeMap().find(id) != invalidThemeMap().end())
03535                     view->remove(id);
03536                 else
03537                     ++i;
03538             }
03539         }
03540     }
03541 
03542     delete portal;
03543     return true;
03544 }
03545 
03546 
03547 void
03548 TeDatabase::clear()
03549 {
03550         metaModel_->clear();
03551 }
03552 
03553 bool 
03554 TeDatabase::deleteView (int viewId)
03555 {
03556         TeDatabasePortal* portal = this->getPortal();
03557 
03558         // view projection should be deleted manually
03559         string sql =  "SELECT projection_id FROM te_view WHERE view_id=" + Te2String(viewId);
03560         portal->freeResult();
03561         if (!portal->query(sql))
03562         {
03563                 delete portal;
03564                 return false;
03565         }
03566         if (!portal->fetchRow())
03567         {
03568                 delete portal;
03569                 return false;
03570         }
03571         int projId = portal->getInt("projection_id");
03572         portal->freeResult();
03573         
03574         // delete themes belonging to this view 
03575         sql = "SELECT theme_id FROM te_theme WHERE view_id=" + Te2String(viewId);
03576         if (!portal->query(sql))
03577         {
03578                 delete portal;
03579                 return false;
03580         }
03581         while (portal->fetchRow())
03582         {
03583                 int id = atoi(portal->getData(0));
03584                 if(deleteTheme(id) == false)
03585                 {       
03586                         delete portal;
03587                         return false;
03588                 }
03589         }
03590 
03591         //delete the entries in the project relation
03592         if (existRelation("te_project_view","fk_projectview_view_id") != TeRICascadeDeletion)
03593         {
03594                 sql = "DELETE FROM te_project_view WHERE view_id =" + Te2String(viewId);
03595                 if (!this->execute (sql))
03596                         return false;
03597         }
03598 
03599         // delete view
03600         sql = "DELETE FROM te_view WHERE view_id = " + Te2String(viewId);
03601         if (!this->execute (sql))
03602         {
03603                 delete portal;
03604                 return false;
03605         }
03606 
03607         if(!deleteProjection(projId))
03608         {
03609                 delete portal;
03610                 return false;
03611         }
03612 
03613         // Delete the view and its themes
03614         TeView* view = metaModel_->viewMap()[viewId];
03615         metaModel_->viewMap().erase(viewId);
03616         delete view;
03617         delete portal;
03618         return true;
03619 }
03620 
03621 bool
03622 TeDatabase::updateViewTree (TeViewTree *tree)
03623 {
03624         if(tree ->type() == 1) //tree->id() > 0) //only for TeTREE
03625         {
03626                 string sql;
03627                 sql = "UPDATE te_theme SET ";
03628                 sql += "name='" + tree->name()+"'";
03629                 sql += ", parent_id=" + Te2String (tree->parentId());
03630                 sql += ", node_type=" + Te2String (tree->type());
03631                 sql += " ,priority=" + Te2String (tree->priority());
03632                 sql += " WHERE theme_id = " + Te2String(tree->id());
03633 
03634                 if(!this->execute (sql)) return false;
03635         }
03636 
03637         for (unsigned int th=0; th<tree->size(); th++)
03638         {
03639                 TeViewNode* node = tree->retrieve(th);
03640                 if (node->type() == TeTREE)
03641                 {
03642                         TeViewTree* tree = (TeViewTree*)node;
03643                         if(!updateViewTree(tree)) return false;
03644                 }
03645                 else
03646                 {
03647                         TeTheme *theme = (TeTheme*)node;
03648                         if(!updateTheme(theme)) return false;
03649                 }
03650         }
03651         return true;
03652 }
03653 
03654 bool 
03655 TeDatabase::viewExist(string viewName)
03656 {
03657         TeDatabasePortal* portal = this->getPortal();
03658         if (!portal)
03659                 return false;
03660 
03661         viewName = TeConvertToUpperCase(viewName);
03662 
03663         string sql = "SELECT name FROM te_view";
03664         if (!portal->query(sql))
03665         {       
03666                 delete portal;
03667                 return false;
03668         }
03669         while (portal->fetchRow())
03670         {
03671                 string name = portal->getData(0);
03672                 name = TeConvertToUpperCase(name);
03673                 if (viewName == name)
03674                 {
03675                         delete portal;
03676                         return true;
03677                 }
03678         }
03679         delete portal;
03680         return false;
03681 }
03682 
03683 
03684 bool
03685 TeDatabase::updateTheme (TeAbstractTheme *theme)
03686 {
03687         string sql;
03688 
03689         if (theme->id() <= 0 )  // theme doesn�t exist in the database yet
03690         {
03691                 return this->insertTheme(theme);
03692         }
03693         
03694         // update theme metadata
03695         sql = "UPDATE te_theme SET ";
03696         
03697         if(theme->type()==TeTHEME)
03698         {
03699                 sql += " layer_id=" + Te2String (static_cast<TeTheme*>(theme)->layerId());
03700                 sql += ", ";
03701         }
03702         
03703         sql += "  view_id=" + Te2String (theme->view());
03704         sql += ", name='" + escapeSequence(theme->name())+"'";
03705         sql += ", parent_id=" + Te2String (theme->parentId());
03706         sql += ", priority=" + Te2String (theme->priority());
03707         sql += ", node_type=" + Te2String (theme->type());
03708         sql += ", min_scale=" + Te2String (theme->minScale(),15);
03709         sql += ", max_scale=" + Te2String (theme->maxScale(),15);
03710         sql += ", generate_attribute_where='" + escapeSequence(theme->attributeRest())+"'";
03711         sql += ", generate_spatial_where='" + escapeSequence(theme->spatialRest())+"'";
03712         sql += ", generate_temporal_where='" + escapeSequence(theme->temporalRest())+"'";
03713 
03714         if(theme->type()==TeTHEME || theme->type()==TeEXTERNALTHEME )
03715                 sql += ", collection_table='" + static_cast<TeTheme*>(theme)->collectionTable() + "'";
03716 
03717         sql += ", visible_rep= " + Te2String(theme->visibleRep ());
03718         sql += ", enable_visibility= " + Te2String(theme->visibility()); 
03719         sql += ", lower_x = " + Te2String(theme->box().x1(), 15); 
03720         sql += ", lower_y = " + Te2String(theme->box().y1(), 15); 
03721         sql += ", upper_x = " + Te2String(theme->box().x2(), 15); 
03722         sql += ", upper_y = " + Te2String(theme->box().y2(), 15);
03723         if(theme->getCreationTime().isValid())
03724         {
03725                 TeTime creationTime = theme->getCreationTime();
03726                 sql += ", creation_time = " + this->getSQLTime(creationTime);
03727         }
03728 
03729         sql += " WHERE theme_id=" + Te2String (theme->id(), 15);
03730 
03731         if (!this->execute (sql))
03732                 return false;
03733          
03734         //delete grouping 
03735         sql = "DELETE FROM te_grouping WHERE theme_id= "+ Te2String(theme->id());
03736         this->execute (sql);
03737                 
03738         if(theme->grouping().groupMode_ != TeNoGrouping)
03739         {
03740                 if(!insertGrouping(theme->id(), theme->grouping()))
03741                         return false;
03742         }
03743         
03744         // update each of its legends
03745         bool status = true;
03746         
03747         if(theme->legend().size() == 0)
03748         {
03749                 if(!deleteLegend(theme->id()))
03750                         return false;
03751         }
03752         else
03753         {
03754                 status = updateLegend(theme->legend());
03755                 if (!status)
03756                         return status;
03757         }
03758 
03759         status = updateLegend(&(theme->withoutDataConnectionLegend()));
03760         if (!status)
03761                 return status;
03762 
03763         status = updateLegend(&(theme->outOfCollectionLegend()));
03764         if (!status)
03765                 return status;
03766 
03767         status = updateLegend(&(theme->defaultLegend()));
03768         if (!status)
03769                 return status;
03770 
03771         status = updateLegend(&(theme->pointingLegend()));
03772         if (!status)
03773                 return status;
03774 
03775         status = updateLegend(&(theme->queryLegend()));
03776         if (!status)
03777                 return status;
03778 
03779         status = updateLegend(&(theme->queryAndPointingLegend()));
03780         if (!status)
03781                 return status;
03782         
03783         //insert metadata theme
03784         if(!theme->saveMetadata(this))
03785                 return false;
03786 
03787         // theme tables
03788         if(theme->type()==TeTHEME && !updateThemeTable(static_cast<TeTheme*>(theme)))
03789                 return false;
03790 
03791         return true;
03792 }
03793 
03794 bool
03795 TeDatabase::loadTheme (TeAbstractTheme* theme, const bool& loadAttrList, const string& visualType)
03796 {
03797         if (theme == 0)
03798                 return false;
03799 
03800         string rest;
03801         if (theme->id() > 0)
03802                 rest = " te_theme.theme_id = "+  Te2String(theme->id());
03803         else if (!theme->name().empty())
03804                 rest = " te_theme.name = '"+  theme->name() + "'";
03805         else
03806         {
03807                 this->errorMessage_ = "Theme procurado n�o possui nem id nem nome";
03808                 return false;
03809         }
03810         rest += " AND te_view.user_name = \'" + this->user() +"\'";
03811         
03812         //load view, projection, themes and grouping
03813         string sql = " SELECT ";
03814         sql += " te_theme.*, "; // 0 - 19 (20 columns)   
03815         sql += " te_grouping.*, "; //20 - 29 (10 columns)
03816         sql += " te_legend.*,  "; // 30 - 36    (7 columns)
03817         sql += " te_visual.*, "; //  37 - 60 (24 columns)
03818         sql += " te_visual_raster.* "; //  61 (7 columns)
03819         sql += " FROM (((((te_view INNER JOIN te_theme ON te_view.view_id = te_theme.view_id) ";
03820         sql += " LEFT JOIN te_grouping ON te_theme.theme_id = te_grouping.theme_id ) ";
03821         sql += " LEFT JOIN te_legend ON te_theme.theme_id = te_legend.theme_id ) ";
03822         sql += " LEFT JOIN te_visual ON te_legend.legend_id = te_visual.legend_id ) ";
03823         sql += " LEFT JOIN te_visual_raster ON te_theme.theme_id = te_visual_raster.theme_id) ";
03824         sql += " WHERE "+ rest;
03825         sql += " ORDER BY te_theme.theme_id, te_legend.legend_id, te_legend.group_id, te_visual.geom_type, te_visual_raster.band_in  "; 
03826 
03827         TeDatabasePortal* portal = this->getPortal();
03828         if(!portal)
03829                 return false;
03830         
03831         if(!portal->query(sql) || !portal->fetchRow())
03832         {       
03833                 delete portal;
03834                 return false;
03835         }
03836         
03837         TeViewNodeType viewNodeType = (TeViewNodeType)portal->getInt(6);
03838         if(viewNodeType == TeTREE)
03839         {               
03840                 TeViewNodeParams params;
03841                 portal->getViewNodeParams(params, 0);
03842                 theme->viewNodeParams(params);
03843                 delete portal;
03844                 return true;
03845         }
03846                         
03847         if(!portal->getTheme(*theme, 0))
03848         {
03849                 delete portal;
03850                 return false;
03851         }
03852         
03853         if(viewNodeType==(int)TeTHEME)
03854         {
03855                 //load layer
03856                 int id = static_cast<TeTheme*>(theme)->layerId();
03857                 TeLayerMap::iterator it = metaModel_->layerMap().find(id);
03858                 if (it == metaModel_->layerMap().end())
03859                         loadLayerSet(loadAttrList);
03860                 
03861                 static_cast<TeTheme*>(theme)->layer(metaModel_->layerMap()[id]);
03862         }
03863                 
03864         //load grouping 
03865         TeGrouping group;
03866         if(portal->getGrouping(group, 20))
03867                 theme->grouping(group);
03868 
03869         //load all legends of this theme
03870         //and its visual
03871         bool hasLegsToThisTheme = true;
03872         bool hasNewRow = true;
03873         while(hasLegsToThisTheme)
03874         {
03875                 //legend
03876                 TeLegendEntry legend;
03877                 if(!portal->getLegend(legend, 30))
03878                 {
03879                         delete portal;
03880                         return false;
03881                 }
03882 
03883                 //visual
03884                 //TeRasterVisual* rasterVisual = new TeRasterVisual();
03885                 TeRasterVisual* rasterVisual = theme->rasterVisual();
03886                 if(rasterVisual == NULL)
03887                 {
03888                         rasterVisual = new TeRasterVisual();
03889                 }
03890                 
03891                 bool hasVisualToThisLeg = true;
03892                 bool hasRasterVisual = false;
03893                 while(hasVisualToThisLeg)
03894                 {
03895                         TeVisual* visual = TeVisualFactory::make(visualType);
03896                         TeGeomRep geomRep;
03897                         if(portal->getVisual(visual, geomRep, 37))
03898                                 legend.setVisual(visual, geomRep);
03899                                                                 
03900                         if(rasterVisual != NULL && portal->getRasterVisual(*rasterVisual, 61))
03901                                 hasRasterVisual=true;
03902                         
03903                         hasNewRow = portal->fetchRow();
03904                         if(!hasNewRow || portal->getInt(32)!= legend.group() || portal->getInt(30)!= legend.id() )  //if legend_id and group_id
03905                                 hasVisualToThisLeg = false;
03906                 }
03907 
03908                 //Set raster visual to this theme
03909                 if(hasRasterVisual)
03910                         theme->rasterVisual(rasterVisual);
03911                 else
03912                         delete rasterVisual;
03913 
03914                 //Set legend to this theme
03915                 theme->legend(legend); 
03916                                                                                                                 
03917                 //fill legend buffer
03918                 if(legend.group() == -6)        
03919                         metaModel_->legendMap()[legend.id()] = &theme->queryAndPointingLegend();
03920                 else if(legend.group() == -5)   
03921                         metaModel_->legendMap()[legend.id()] = &theme->queryLegend(); 
03922                 else if (legend.group() == -4)
03923                         metaModel_->legendMap()[legend.id()] = &theme->pointingLegend(); 
03924                 else if (legend.group() == -3)
03925                         metaModel_->legendMap()[legend.id()] = &theme->defaultLegend(); 
03926                 else if (legend.group() == -2)
03927                         metaModel_->legendMap()[legend.id()] = &theme->withoutDataConnectionLegend(); 
03928                 else if (legend.group() == -1)
03929                         metaModel_->legendMap()[legend.id()] = &theme->outOfCollectionLegend(); 
03930                 else if (legend.group() == -10) //own legend
03931                 {
03932                         TeLegendEntry* legendTemp = new TeLegendEntry(legend);
03933                         metaModel_->legendMap()[legend.id()] = legendTemp;
03934                 }       
03935                 
03936                 if(!hasNewRow || portal->getInt(0)!= theme->id())
03937                         hasLegsToThisTheme = false;
03938         }
03939 
03940         delete portal;
03941                         
03942         for (unsigned int i = 0; i < theme->legend().size(); ++i)
03943                 metaModel_->legendMap()[theme->legend()[i].id()] = &theme->legend()[i];
03944 
03945         //load theme table
03946         if(theme->type()==(int)TeTHEME)
03947         {
03948                 if(!loadThemeTable(static_cast<TeTheme*>(theme), loadAttrList))
03949                         return false;
03950         }
03951 
03952         //load specific theme parameters
03953         if(!theme->loadMetadata(this))
03954         {
03955                 metaModel_->invalidThemeMap()[theme->id()] = theme;
03956                 delete portal;
03957                 return false;
03958         }
03959                         
03960         metaModel_->themeMap()[theme->id()] = theme;
03961         return true;
03962 }
03963 
03964 bool
03965 TeDatabase::loadThemes(std::vector<TeAbstractTheme*>& vecThemes, const bool& loadAttrList, const std::string& userName, const bool& loadMetadata, const string& visualType)
03966 {
03967         if (vecThemes.empty())
03968                 return false;   
03969 
03970         std::set<int> setThemes;
03971 
03972         std::string rest = "";
03973         std::string idClause = "";
03974         std::string nameClause = "";
03975         for(unsigned int i = 0; i < vecThemes.size(); ++i)
03976         {
03977                 TeAbstractTheme* theme = vecThemes[i];
03978                 if(theme == NULL)
03979                 {
03980                         return false;
03981                 }
03982 
03983                 if (theme->id() > 0)
03984                 {
03985                         //rest = " te_theme.theme_id = "+  Te2String(theme->id());
03986                         if(!idClause.empty())
03987                         {
03988                                 idClause += ",";
03989                         }
03990                         idClause += Te2String(theme->id());
03991                 }
03992                 else if (!theme->name().empty())
03993                 {
03994                         //rest = " te_theme.name = '"+  theme->name() + "'";
03995                         if(!nameClause.empty())
03996                         {
03997                                 nameClause += ",";
03998                         }
03999                         nameClause += "'" + theme->name() + "'";
04000                 }
04001                 else
04002                 {
04003                         this->errorMessage_ = "Theme procurado n�o possui nem id nem nome";
04004                         return false;
04005                 }
04006         }
04007         if(!idClause.empty())
04008         {
04009                 rest += "te_theme.theme_id in (" + idClause + ")";
04010         }
04011         if(!nameClause.empty())
04012         {
04013                 if(!rest.empty())
04014                 {
04015                         rest += " AND ";
04016                 }
04017                 rest += "te_theme.name in (" + nameClause + ")";
04018         }
04019 
04020         rest += " AND te_view.user_name = \'" + userName +"\'";
04021         //rest += " AND te_view.user_name = \'postgres\'";
04022         
04023         //load view, projection, themes and grouping
04024         string sql = " SELECT ";
04025         sql += " te_theme.*, "; // 0 - 19 (20 columns)   
04026         sql += " te_grouping.*, "; //20 - 29 (10 columns)
04027         sql += " te_legend.*,  "; // 30 - 36    (7 columns)
04028         sql += " te_visual.*, "; //  37 - 60 (24 columns)
04029         sql += " te_visual_raster.* "; //  61 (7 columns)
04030         sql += " FROM (((((te_view INNER JOIN te_theme ON te_view.view_id = te_theme.view_id) ";
04031         sql += " LEFT JOIN te_grouping ON te_theme.theme_id = te_grouping.theme_id ) ";
04032         sql += " LEFT JOIN te_legend ON te_theme.theme_id = te_legend.theme_id ) ";
04033         sql += " LEFT JOIN te_visual ON te_legend.legend_id = te_visual.legend_id ) ";
04034         sql += " LEFT JOIN te_visual_raster ON te_theme.theme_id = te_visual_raster.theme_id) ";
04035         sql += " WHERE "+ rest;
04036         sql += " ORDER BY te_theme.theme_id, te_legend.legend_id, te_legend.group_id, te_visual.geom_type, te_visual_raster.band_in  "; 
04037 
04038         TeDatabasePortal* portal = this->getPortal();
04039         if(!portal)
04040                 return false;
04041         
04042         if(!portal->query(sql))
04043         {       
04044                 delete portal;
04045                 return false;
04046         }
04047 
04048         bool hasNewRow = portal->fetchRow();
04049 
04050         while(hasNewRow)
04051         {
04052                 TeAbstractTheme* theme = NULL;;
04053                 int id = portal->getInt(0);
04054                 for(unsigned int i = 0; i < vecThemes.size(); ++i)
04055                 {
04056                         if(id == vecThemes[i]->id())
04057                         {
04058                                 theme = vecThemes[i];
04059                                 setThemes.insert(id);
04060                                 break;
04061                         }
04062                 }               
04063 
04064                 TeViewNodeType viewNodeType = (TeViewNodeType)portal->getInt(6);
04065                 if(viewNodeType == TeTREE)
04066                 {               
04067                         TeViewNodeParams params;
04068                         portal->getViewNodeParams(params, 0);
04069                         theme->viewNodeParams(params);
04070                         delete portal;
04071                         return true;
04072                 }
04073                                 
04074                 if(!portal->getTheme(*theme, 0))
04075                 {
04076                         delete portal;
04077                         return false;
04078                 }               
04079                 
04080                 if(viewNodeType==(int)TeTHEME)
04081                 {
04082                         //load layer
04083                         int id = static_cast<TeTheme*>(theme)->layerId();
04084                         TeLayerMap::iterator it = metaModel_->layerMap().find(id);
04085                         if (it == metaModel_->layerMap().end())
04086                                 loadLayerSet(loadAttrList);
04087                         
04088                         static_cast<TeTheme*>(theme)->layer(metaModel_->layerMap()[id]);
04089                 }
04090                         
04091                 //load grouping 
04092                 TeGrouping group;
04093                 if(portal->getGrouping(group, 20))
04094                         theme->grouping(group);
04095 
04096                 //load all legends of this theme
04097                 //and its visual
04098                 bool hasLegsToThisTheme = true; 
04099                 while(hasLegsToThisTheme)
04100                 {
04101                         //legend
04102                         TeLegendEntry legend;
04103                         if(!portal->getLegend(legend, 30))
04104                         {
04105                                 delete portal;
04106                                 return false;
04107                         }
04108 
04109                         //visual
04110                         //TeRasterVisual* rasterVisual = new TeRasterVisual();
04111                         TeRasterVisual* rasterVisual = theme->rasterVisual();
04112                         if(rasterVisual == NULL)
04113                         {
04114                                 rasterVisual = new TeRasterVisual();
04115                         }
04116                         bool hasVisualToThisLeg = true;
04117                         bool hasRasterVisual = false;
04118                         while(hasVisualToThisLeg)
04119                         {
04120                                 TeVisual* visual = TeVisualFactory::make(visualType);
04121                                 TeGeomRep geomRep;
04122                                 if(portal->getVisual(visual, geomRep, 37))
04123                                         legend.setVisual(visual, geomRep);
04124                                                                         
04125                                 if(rasterVisual != NULL && portal->getRasterVisual(*rasterVisual, 61))
04126                                         hasRasterVisual=true;
04127                                 
04128                                 hasNewRow = portal->fetchRow();
04129                                 if(!hasNewRow || portal->getInt(32)!= legend.group() || portal->getInt(30)!= legend.id() )  //if legend_id and group_id
04130                                         hasVisualToThisLeg = false;
04131                         }
04132 
04133                         //Set raster visual to this theme
04134                         if(hasRasterVisual)
04135                                 theme->rasterVisual(rasterVisual);
04136                         else
04137                                 delete rasterVisual;
04138 
04139                         //Set legend to this theme
04140                         theme->legend(legend); 
04141                                                                                                                         
04142                         //fill legend buffer
04143                         if(legend.group() == -6)        
04144                                 metaModel_->legendMap()[legend.id()] = &theme->queryAndPointingLegend();
04145                         else if(legend.group() == -5)   
04146                                 metaModel_->legendMap()[legend.id()] = &theme->queryLegend(); 
04147                         else if (legend.group() == -4)
04148                                 metaModel_->legendMap()[legend.id()] = &theme->pointingLegend(); 
04149                         else if (legend.group() == -3)
04150                                 metaModel_->legendMap()[legend.id()] = &theme->defaultLegend(); 
04151                         else if (legend.group() == -2)
04152                                 metaModel_->legendMap()[legend.id()] = &theme->withoutDataConnectionLegend(); 
04153                         else if (legend.group() == -1)
04154                                 metaModel_->legendMap()[legend.id()] = &theme->outOfCollectionLegend(); 
04155                         else if (legend.group() == -10) //own legend
04156                         {
04157                                 TeLegendEntry* legendTemp = new TeLegendEntry(legend);
04158                                 metaModel_->legendMap()[legend.id()] = legendTemp;
04159                         }       
04160                         
04161                         if(!hasNewRow || portal->getInt(0)!= theme->id())
04162                                 hasLegsToThisTheme = false;
04163                 }               
04164                                 
04165                 for (unsigned int i = 0; i < theme->legend().size(); ++i)
04166                         metaModel_->legendMap()[theme->legend()[i].id()] = &theme->legend()[i];
04167 
04168                 //load theme table
04169                 if(theme->type()==(int)TeTHEME)
04170                 {
04171                         if(!loadThemeTable(static_cast<TeTheme*>(theme), loadAttrList))
04172                                 return false;
04173                 }
04174 
04175                 if(loadMetadata == true)
04176                 {
04177                         //load specific theme parameters
04178                         if(!theme->loadMetadata(this))
04179                         {
04180                                 metaModel_->invalidThemeMap()[theme->id()] = theme;
04181                                 delete portal;
04182                                 return false;
04183                         }
04184                 }
04185                                 
04186                 //metaModel_->themeMap()[theme->id()] = theme;
04187         }
04188 
04189         delete portal;
04190 
04191         for(unsigned int i = 0; i < vecThemes.size(); ++i)
04192         {
04193                 if(setThemes.find(vecThemes[i]->id()) != setThemes.end())
04194                 {
04195                         metaModel_->themeMap()[vecThemes[i]->id()] = vecThemes[i];
04196                 }
04197                 else
04198                 {
04199                         metaModel_->invalidThemeMap()[vecThemes[i]->id()] = vecThemes[i];
04200                 }
04201         }
04202 
04203         return true;
04204 }
04205 
04206 bool TeDatabase::loadExternalThemes(std::vector<TeAbstractTheme*>& vecExternalThemes)
04207 {
04208         if(vecExternalThemes.empty())
04209         {
04210                 return true;
04211         }
04212 
04213         std::map<int, std::vector< std::pair<int, TeAbstractTheme*> > > mapExternalThemes;
04214 
04215         for(unsigned int i = 0; i < vecExternalThemes.size(); ++i)
04216         {
04217                 TeAbstractTheme* abstractTheme = vecExternalThemes[i];
04218 
04219                 TeExternalTheme* extTheme = dynamic_cast<TeExternalTheme*>(abstractTheme);
04220                 if(extTheme != NULL)
04221                 {
04222                         extTheme->setSourceDatabase(this);
04223                         int remoteThemeId = -1;
04224                         int remoteDBId = -1;
04225 
04226                         if(!extTheme->getRemoteThemeInfo(remoteThemeId, remoteDBId))
04227                                 return false;                           
04228 
04229                         mapExternalThemes[remoteDBId].push_back(std::pair<int,TeAbstractTheme*>/*::pair*/(remoteThemeId, extTheme));
04230                 }
04231         }
04232 
04233         std::map<int, std::vector< std::pair<int, TeAbstractTheme*> > >::iterator itExtThemes = mapExternalThemes.begin();
04234         while(itExtThemes != mapExternalThemes.end())
04235         {
04236                 TeDatabase* remotedb = TeDBConnectionsPool::instance().getDatabase(itExtThemes->first);
04237                 if(remotedb == NULL)
04238                 {       
04239                         std::string hostName, dbmsName, dbName, userName, password;
04240                         int port = 0;
04241                         if(!TeDBConnectionsPool::instance().getConnectionInfo(this, itExtThemes->first, hostName, dbmsName, dbName, userName, password, port))
04242                         {
04243                                 return false;
04244                         }
04245 
04246                         remotedb = TeDBConnectionsPool::instance().getDatabase(dbmsName, dbName, hostName, userName, password, port);
04247 
04248                         if(remotedb != NULL)
04249                         {
04250                                 TeDBConnectionsPool::instance().saveExternalDBConnection(this, remotedb);
04251                         }
04252                 }
04253                 
04254                 if(remotedb == NULL || remotedb->isConnected() == false)
04255                 {
04256                         for(unsigned int i = 0; i < itExtThemes->second.size(); ++i)
04257                         {
04258                                 metaModel_->invalidThemeMap()[itExtThemes->second[i].second->id()] = itExtThemes->second[i].second;
04259                         }
04260                         ++itExtThemes;
04261                         continue;
04262                 }
04263                 
04264                 std::vector<TeAbstractTheme*> vecThemesToLoad;
04265                 for(unsigned int i = 0; i < itExtThemes->second.size(); ++i)
04266                 {
04267                         bool add = true;
04268                         for(unsigned int j = 0; j < vecThemesToLoad.size(); ++j)
04269                         {
04270                                 if(itExtThemes->second[i].first == vecThemesToLoad[j]->id())
04271                                 {
04272                                         add = false;
04273                                         break;
04274                                 }
04275                         }
04276                         if(add == false)
04277                         {
04278                                 continue;
04279                         }
04280 
04281                         TeTheme* remoteTheme = new TeTheme();
04282                         remoteTheme->id(itExtThemes->second[i].first);
04283                         vecThemesToLoad.push_back(remoteTheme);
04284                 }
04285 
04286                 if(!remotedb->loadThemes(vecThemesToLoad, true, remotedb->user(), false))
04287                 {
04288                         return false;
04289                 }
04290 
04291                 for(unsigned int i = 0; i < itExtThemes->second.size(); ++i)
04292                 {
04293                         TeExternalTheme* extTheme = dynamic_cast<TeExternalTheme*>(itExtThemes->second[i].second);                      
04294                         if(extTheme != NULL)
04295                         {
04296                                 //verifica se o tema eh invalido
04297                                 TeThemeMap::iterator itTheme = remotedb->metaModel_->invalidThemeMap().find(itExtThemes->second[i].first);
04298                                 if(itTheme != remotedb->metaModel_->invalidThemeMap().end())
04299                                 {
04300                                         metaModel_->invalidThemeMap()[extTheme->id()] = extTheme;
04301                                 }
04302                                 else
04303                                 {
04304                                         metaModel_->themeMap()[extTheme->id()] = extTheme;
04305 
04306                                         TeThemeMap::iterator itTheme = remotedb->metaModel_->themeMap().find(itExtThemes->second[i].first);
04307 
04308                                         if(itTheme == remotedb->metaModel_->themeMap().end())
04309                                         {
04310                                                 return false;
04311                                         }
04312 
04313                                         extTheme->setRemoteTheme((TeTheme*)itTheme->second);
04314                                         extTheme->loadObjectLegendMap();
04315                                 }
04316                         }
04317                 }
04318 
04319                 remotedb->clear();
04320 
04321                 ++itExtThemes;
04322         }
04323 
04324         return true;
04325 }
04326 
04327 bool
04328 TeDatabase::loadThemeTable (TeTheme* theme, const bool& loadAttrList)
04329 {
04330         TeDatabasePortal* portal = this->getPortal();
04331         if(!portal)
04332         {
04333                 this->errorMessage_ = "N�o foi poss�vel abrir portal para o banco";
04334                 return false;
04335         }
04336         
04337         //theme tables
04338         string sel = "SELECT te_theme_table.*, ";  //0 - 4 (5 columnns)
04339         sel += " te_tables_relation.*, ";          //5 - 9  (5 columns)
04340         sel += " te_layer_table.* ";                       //10 
04341         sel += " FROM (te_theme_table LEFT JOIN te_tables_relation";
04342         sel += " ON te_theme_table.relation_id = te_tables_relation.relation_id)";
04343         sel += " LEFT JOIN te_layer_table ON te_theme_table.table_id = te_layer_table.table_id";
04344         sel += " WHERE  te_theme_table.theme_id = " + Te2String(theme->id());
04345         sel += " ORDER BY table_order";
04346         
04347         if (!portal->query (sel))
04348         {       
04349                 delete portal;
04350                 return false;
04351         }
04352 
04353         while(portal->fetchRow ())
04354         {
04355                 string tableName = portal->getData(12);
04356                 if(tableName.empty())
04357                         continue;
04358 
04359                 TeTable table(tableName);
04360 
04361                 TeLayerMap::iterator itLayer = metaModel_->layerMap().find(theme->layerId());
04362                 if(itLayer->second == 0) return false;
04363                 if(itLayer!=metaModel_->layerMap().end() && (!itLayer->second->getAttrTablesByName(tableName, table)))
04364                 {
04365                         TeAttributeList attrList;
04366                         if(loadAttrList)
04367                                 getAttributeList(tableName, attrList);
04368                         table.setAttributeList(attrList);
04369                         if(!portal->getAttrTable(table, 10))
04370                         {
04371                                 delete portal;
04372                                 return false;
04373                         }
04374                 }
04375 
04376                 table.setId(portal->getInt(2)); //"te_theme_table.table_id"
04377                 table.setOrder(portal->getInt(4)); //"table_order"
04378                 TeAttrTableType tableType = table.tableType(); //portal->getInt("attr_table_type");
04379                 if (tableType == TeAttrExternal)
04380                 {
04381                         int relatedTableId = portal->getInt(6); //"related_table_id"
04382                         table.relatedTableName(getTableName(relatedTableId));
04383                         int relationId = portal->getInt(3); //"te_theme_table.relation_id"
04384                         metaModel_->relationMSet().insert(relationId);
04385 
04386                         string relatedAttr = portal->getData(7); //"related_attr"
04387                         table.setTableType(TeAttrExternal, relatedTableId, relatedAttr);
04388 
04389                         table.setLinkName(portal->getData(9)); //"external_attr"
04390                 }
04391                 else
04392                         table.setTableType((TeAttrTableType)tableType);
04393 
04394                 theme->addThemeTable(table);
04395         }
04396 
04397         delete portal;
04398         return true;
04399 }
04400 
04401 
04402 bool
04403 TeDatabase::insertThemeTable(TeTheme *theme, TeTable& inputTable)
04404 {
04405         int themeId = theme->id();
04406         int     tableOrder = 0;
04407         int     relationId;
04408         bool status;
04409         string qString;
04410 
04411         // Get the order of the last theme table
04412         qString = "SELECT MAX(table_order) FROM te_theme_table";
04413         qString += " WHERE theme_id = " + Te2String(themeId);
04414 
04415         TeDatabasePortal* portal = getPortal();
04416         if (portal->query(qString) == false || portal->fetchRow() == false)
04417                 return false;
04418 
04419         string data = portal->getData(0);
04420         if (data.empty())
04421                 tableOrder = 0;
04422         else
04423         {
04424                 tableOrder = atoi(portal->getData(0));
04425                 ++tableOrder;
04426         }
04427         inputTable.setOrder(tableOrder);
04428         delete portal;
04429 
04430         if (inputTable.tableType() == TeAttrExternal)
04431         {
04432                 status = insertRelationInfo(inputTable.relatedTableId(),inputTable.relatedAttribute(),
04433                                                                         inputTable.name(),inputTable.linkName(),relationId);
04434                 if (status == false)
04435                         return false;
04436                 metaModel_->relationMSet().insert(relationId);
04437 
04438                 status = insertThemeTable(themeId, inputTable.id(), relationId, tableOrder);
04439         }
04440         else
04441         {
04442                 // Insert the table in the te_theme_table
04443                 status = insertThemeTable(themeId, inputTable.id(), 0, tableOrder);
04444         }
04445         return status;
04446 }
04447 
04448 bool
04449 TeDatabase::removeThemeTable(TeTheme *theme, int tableOrder)
04450 {
04451         if (tableOrder < 0)
04452                 return false;
04453 
04454         int relationId = -1;
04455         string qString;
04456 
04457         TeAttrTableVector attrTableVector; 
04458         theme->getAttTables(attrTableVector);
04459 
04460         // If the table is external, find the relation id
04461         qString = "SELECT relation_id FROM te_theme_table";
04462         qString += " WHERE theme_id = " + Te2String(theme->id());
04463         qString += " AND relation_id IS NOT NULL";
04464         qString += " AND table_order = " + Te2String(tableOrder);
04465 
04466         TeDatabasePortal* portal = getPortal();
04467         if (portal->query(qString) && portal->fetchRow())
04468                 relationId = portal->getInt("relation_id");
04469         else
04470         {
04471                 delete portal;
04472                 return false;
04473         }
04474         delete portal;
04475 
04476         // Remove the table from the te_theme_table
04477         qString = "DELETE FROM te_theme_table WHERE theme_id = " + Te2String(theme->id());
04478         qString += " AND table_order = " + Te2String(tableOrder);
04479         if (execute(qString) == false)
04480                 return false;
04481 
04482         // Remove the relation from the te_tables_relation
04483         // table if only this theme is using it
04484         if (relationId > 0)
04485         {
04486                 if (metaModel_->relationMSet().count(relationId) == 1)
04487                 {
04488                         qString = "DELETE FROM te_tables_relation WHERE relation_id = " + Te2String(relationId);
04489                         if (execute(qString) == false)
04490                                 return false;
04491                         metaModel_->relationMSet().erase(relationId);
04492                 }
04493                 else
04494                         metaModel_->relationMSet().erase(metaModel_->relationMSet().find(relationId));
04495         }
04496         return true;
04497 }
04498 
04499 
04500 bool 
04501 TeDatabase::updateThemeTable(TeTheme *theme)
04502 {
04503         //Initially remove from te_theme_table all the records of this theme
04504         string q = "SELECT * FROM te_theme_table WHERE theme_id = " + Te2String(theme->id());
04505         TeDatabasePortal *portal = getPortal();
04506 
04507         if (portal->query(q) == false)
04508         {
04509                 delete portal;
04510                 return false;
04511         }
04512 
04513         while (portal->fetchRow())
04514         {
04515                 int relationId;
04516                 int themeTableId = portal->getInt("theme_table_id");
04517 
04518                 string data = portal->getData("relation_id");
04519                 if (data.empty())
04520                         relationId = -1;
04521                 else
04522                         relationId = atoi(data.c_str());
04523 
04524                 // Remove the relation from the te_tables_relation
04525                 // table if only this theme is using it
04526                 bool b = false;
04527                 if (relationId > 0)
04528                 {
04529                         if (metaModel_->relationMSet().count(relationId) == 1)
04530                                 b = true;
04531                         else
04532                                 metaModel_->relationMSet().erase(metaModel_->relationMSet().find(relationId));
04533                 }
04534 
04535                 // Remove the table from the te_theme_table
04536                 q = "DELETE FROM te_theme_table WHERE theme_id = " + Te2String(theme->id());
04537                 q += " AND theme_table_id = " + Te2String(themeTableId);
04538                 if (execute(q) == false)
04539                 {
04540                         delete portal;
04541                         return false;
04542                 }
04543                 if(b)
04544                 {
04545                         q = "DELETE FROM te_tables_relation WHERE relation_id = " + Te2String(relationId);
04546                         if (execute(q) == false)
04547                         {
04548                                 delete portal;
04549                                 return false;
04550                         }
04551                         metaModel_->relationMSet().erase(relationId);
04552                 }
04553         }
04554         delete portal;
04555 
04556         // Update te_theme_table and te_tables_relation(if there are any external tables)
04557         // with the information provided from the new vector of theme tables
04558         TeAttrTableVector tablesVector; 
04559         theme->getAttTables(tablesVector);
04560         for (unsigned i = 0; i < tablesVector.size(); ++i)
04561                 insertThemeTable(theme, tablesVector[i]);
04562 
04563         return true;
04564 }
04565 
04566 
04567 bool 
04568 TeDatabase::insertGrouping (int themeId, const TeGrouping& grouping)
04569 {
04570         if((themeId < 1) || (grouping.groupMode_ == TeNoGrouping) )
04571                 return false;
04572 
04573         string ins = " INSERT INTO te_grouping (theme_id, grouping_number, ";
04574         ins += " grouping_attr, grouping_attr_type, grouping_mode, "; 
04575         ins += " grouping_norm_attr, grouping_std_dev, grouping_precision, "; 
04576         ins += " grouping_function, grouping_chronon)"; 
04577         ins += " VALUES ( ";
04578         ins += Te2String(themeId);
04579         ins += ", "+ Te2String(grouping.groupNumSlices_);
04580 
04581         string attname = grouping.groupAttribute_.name_;
04582         if(attname.empty() || (attname=="NONE") )
04583                 attname = "";
04584         
04585         string norname = grouping.groupNormAttribute_;
04586         if(norname.empty() || (norname=="NONE"))
04587                 norname = "";
04588 
04589         map<int, map<string, string> >::iterator it = metaModel_->mapThemeAlias().find(themeId);
04590         if(it != metaModel_->mapThemeAlias().end())
04591         {
04592                 map<string, string>::iterator tit = it->second.find(attname);
04593                 if(tit != it->second.end())
04594                 {
04595                         string alias = tit->second;
04596                         attname += "(" + alias + ")";
04597                 }
04598                 if(norname.empty() == false)
04599                 {
04600                         map<string, string>::iterator tit = it->second.find(norname);
04601                         if(tit != it->second.end())
04602                         {
04603                                 string nalias = tit->second;
04604                                 norname += "(" + nalias + ")";
04605                         }
04606                 }
04607         }
04608 
04609         ins += ", '"+ attname +"'";
04610         ins += ", "+ Te2String(grouping.groupAttribute_.type_);
04611         ins += ", "+ Te2String(grouping.groupMode_);
04612         ins += ", '"+ norname +"'";
04613         ins += ", "+ Te2String(grouping.groupStdDev_); 
04614         ins += ", "+ Te2String(grouping.groupPrecision_);
04615         ins += ", '"+ grouping.groupFunction_ +"'";
04616         ins += ", "+ Te2String(grouping.groupChronon_);
04617         ins += ")";
04618 
04619         return (execute(ins));
04620 }
04621 
04622 bool 
04623 TeDatabase::updateGrouping (int themeId, const TeGrouping& grouping)
04624 {
04625         if((themeId < 1) || (grouping.groupMode_ == TeNoGrouping))
04626                 return false;
04627 
04628         string up = " UPDATE te_grouping SET ";
04629         up += "  grouping_number = "+ Te2String(grouping.groupNumSlices_);
04630 
04631         string attname = grouping.groupAttribute_.name_;
04632         if(attname.empty() || (attname=="NONE"))
04633                 attname = "";
04634 
04635         string norname = grouping.groupNormAttribute_;
04636         if(norname.empty()|| (norname=="NONE"))
04637                 norname = "";
04638 
04639         map<int, map<string, string> >::iterator it = metaModel_->mapThemeAlias().find(themeId);
04640         if(it != metaModel_->mapThemeAlias().end())
04641         {
04642                 map<string, string>::iterator tit = it->second.find(attname);
04643                 if(tit != it->second.end())
04644                 {
04645                         string alias = tit->second;
04646                         attname += "(" + alias + ")";
04647                 }
04648                 if(norname.empty() == false)
04649                 {
04650                         map<string, string>::iterator tit = it->second.find(norname);
04651                         if(tit != it->second.end())
04652                         {
04653                                 string nalias = tit->second;
04654                                 norname += "(" + nalias + ")";
04655                         }
04656                 }
04657         }
04658 
04659         up += ", grouping_attr = '"+ attname +"'";
04660         up += ", grouping_attr_type = "+ Te2String(grouping.groupAttribute_.type_);
04661         up += ", grouping_mode = "+ Te2String(grouping.groupMode_);
04662         up += ", grouping_norm_attr = '"+ norname +"'";
04663         up += ", grouping_std_dev = "+ Te2String(grouping.groupStdDev_); 
04664         up += ", grouping_precision = "+ Te2String(grouping.groupPrecision_);
04665         up += ", grouping_function = '"+ grouping.groupFunction_ +"'";
04666         up += ", grouping_chronon = "+ Te2String(grouping.groupChronon_);
04667         up += " WHERE theme_id = "+ Te2String(themeId);
04668 
04669         return (execute(up));
04670 }
04671 
04672 bool 
04673 TeDatabase::generateLabelPositions(TeTheme *theme, const std::string& objectId)
04674 {
04675         string  piebar, geomTable, upd;
04676         string  collTable = theme->collectionTable();
04677         
04678         if((collTable.empty()) || (!tableExist(collTable)))
04679                 return false;
04680 
04681         if (theme->layer()->hasGeometry(TeCELLS) )
04682         {
04683                 geomTable = theme->layer()->tableName(TeCELLS);
04684 
04685                 piebar = "SELECT label_x, label_y, lower_x, lower_y, upper_x, upper_y";
04686                 piebar += " FROM " + collTable + " LEFT JOIN " + geomTable;
04687                 piebar += " ON " + collTable + ".c_object_id = " + geomTable + ".object_id";
04688                 if (!objectId.empty())
04689                         upd += " WHERE " +  collTable + ".c_object_id = '" + objectId + "'";
04690 
04691                 upd = " UPDATE (" + piebar + ") SET";
04692                 upd += " label_x = lower_x + (upper_x-lower_x)/2,";
04693                 upd += " label_y = lower_y + (upper_y-lower_y)/2";
04694                 
04695 
04696                 if(!execute(upd))
04697                         return false;
04698         }
04699 
04700         if( theme->layer()->hasGeometry(TePOLYGONS))
04701         {
04702                 geomTable = theme->layer()->tableName(TePOLYGONS);
04703 
04704                 piebar = "SELECT label_x, label_y, lower_x, lower_y, upper_x, upper_y";
04705                 piebar += " FROM " + collTable + " LEFT JOIN " + geomTable;
04706                 piebar += " ON " + collTable + ".c_object_id = " + geomTable + ".object_id";
04707                 piebar += " WHERE label_x is null OR label_y is null";
04708                 if (!objectId.empty())
04709                         upd += " AND " +  collTable + ".c_object_id = '" + objectId + "'";
04710                 piebar += " ORDER BY c_object_id ASC, ext_max ASC";
04711                 
04712                 upd = " UPDATE (" + piebar + ") SET";
04713                 upd += " label_x = lower_x + (upper_x-lower_x)/2,";
04714                 upd += " label_y = lower_y + (upper_y-lower_y)/2";
04715 
04716                 if(!execute(upd))
04717                         return false;
04718         }
04719         
04720         if (theme->layer()->hasGeometry(TePOINTS))
04721         {
04722                 geomTable = theme->layer()->tableName(TePOINTS);
04723 
04724                 piebar = "SELECT label_x, label_y, x, y";
04725                 piebar += " FROM " + collTable + " LEFT JOIN " + geomTable;
04726                 piebar += " ON " + collTable + ".c_object_id = " + geomTable + ".object_id";
04727                 piebar += " WHERE label_x is null OR label_y is null";
04728                 if (!objectId.empty())
04729                         upd += " AND " +  collTable + ".c_object_id = '" + objectId + "'";
04730 
04731                 upd = " UPDATE (" + piebar + ") SET";
04732                 upd += " label_x = x,";
04733                 upd += " label_y = y";
04734 
04735                 if(!execute(upd))
04736                         return false;
04737         }
04738         
04739         if(theme->layer()->hasGeometry(TeLINES))
04740         {
04741                 geomTable = theme->layer()->tableName(TeLINES);
04742 
04743                 piebar = "SELECT label_x, label_y, lower_x, lower_y, upper_x, upper_y";
04744                 piebar += " FROM " + collTable + " LEFT JOIN " + geomTable;
04745                 piebar += " ON " + collTable + ".c_object_id = " + geomTable + ".object_id";
04746                 piebar += " WHERE label_x is null OR label_y is null";
04747                 if (!objectId.empty())
04748                         upd += " AND " +  collTable + ".c_object_id = '" + objectId + "'";
04749                 piebar += " ORDER BY c_object_id ASC, ext_max ASC";
04750                 
04751                 upd = " UPDATE (" + piebar + ") SET";
04752                 upd += " label_x = lower_x + (upper_x-lower_x)/2,";
04753                 upd += " label_y = lower_y + (upper_y-lower_y)/2";
04754 
04755                 if(!execute(upd))
04756                         return false;
04757         }
04758         return true;
04759 }
04760 
04761 bool
04762 TeDatabase::themeExist(const std::string &viewName, const std::string &userName, const std::string &themeName)
04763 {
04764         bool status=false;
04765         TeDatabasePortal* portal = this->getPortal();
04766         if (!portal)
04767                 return status;
04768 
04769         string sql = "SELECT name FROM te_theme ";
04770         sql+= " where view_id=( select view_id from te_view where name='";
04771         sql+=viewName;
04772         sql+="' and user_name='";
04773         sql+=userName;
04774         sql+="')and name='";
04775         sql+=themeName +  "'";
04776 
04777         if (portal->query(sql) && portal->fetchRow()) status=true;
04778         delete portal;
04779         return status;
04780 }
04781 
04782 bool 
04783 TeDatabase::themeExist(string themeName)
04784 {
04785         TeDatabasePortal* portal = this->getPortal();
04786         if (!portal)
04787                 return false;
04788 
04789         themeName = TeConvertToUpperCase(themeName);
04790 
04791         string sql = "SELECT name FROM te_theme";
04792         if (!portal->query(sql))
04793         {       
04794                 delete portal;
04795                 return false;
04796         }
04797         while (portal->fetchRow())
04798         {
04799                 string name = portal->getData(0);
04800                 name = TeConvertToUpperCase(name);
04801                 if (themeName == name)
04802                 {
04803                         delete portal;
04804                         return true;
04805                 }
04806         }
04807         delete portal;
04808         return false;
04809 }
04810 
04811 string TeDatabase::getNewThemeName(const string& n)
04812 {
04813         bool changed;
04814         string invalidChar;
04815         string name = TeCheckName(n, changed, invalidChar);
04816         string newName = name;
04817 
04818         string q = "SELECT name FROM te_theme WHERE name = '" + newName + "'";
04819 
04820         TeDatabasePortal* portal = this->getPortal();
04821         if(portal && portal->query(q) && portal->fetchRow())
04822         {
04823                 // there is already a theme with this theme 
04824                 q = "SELECT name FROM te_theme WHERE name LIKE '" + name + "_%' ORDER BY name DESC";
04825                 portal->freeResult();
04826                 if(portal && portal->query(q))
04827                 {
04828                         newName.clear();
04829                         while(portal->fetchRow())
04830                         {
04831                                 string s = portal->getData(0);
04832                                 size_t i, f = s.rfind("_");
04833                                 f++;
04834                                 newName = s.substr(0, f);
04835                                 string ss = s.substr(f);
04836                                 for(i=0; i < ss.size(); ++i)
04837                                 {
04838                                         if(ss[i] < 0x30 || ss[i] > 0x39)
04839                                                 break;
04840                                 }
04841                                 if(i < ss.size())
04842                                         continue;
04843 
04844                                 int n = atoi(ss.c_str()) + 1;
04845                                 s = Te2String(n);
04846                                 newName += s;
04847                                 break;
04848                         }
04849                         if(newName.empty())
04850                                 newName = name + "_1";
04851                 }
04852         }
04853         delete portal;
04854         return newName;
04855 }
04856 
04857 string TeDatabase::getNewTableName(const string& n)
04858 {
04859         bool changed;
04860         string invalidChar;
04861         string name = TeCheckName(n, changed, invalidChar);
04862         string newName = name;
04863         int     i=1;
04864         while (this->tableExist(newName))
04865         {
04866                 newName = name + Te2String(i);
04867                 ++i;
04868         }
04869         return newName;
04870 }
04871 
04872 string TeDatabase::getConcatFieldsExpression(const vector<string>& fNamesVec)
04873 {
04874         string concatExp;
04875         for (unsigned int i = 0; i < fNamesVec.size(); ++i)
04876         {
04877                 if (i != 0)
04878                         concatExp += " & ";
04879                 concatExp += fNamesVec[i];
04880         }
04881         return concatExp;
04882 }
04883 
04884 
04885 bool
04886 TeDatabase::deleteTheme(int themeId)
04887 {
04888         TeAbstractTheme* tema;
04889         bool themeWasFound = false;
04890         TeThemeMap::iterator it;
04891 
04892         it = invalidThemeMap().find(themeId);
04893         if (it != invalidThemeMap().end())
04894         {
04895                 themeWasFound = true;
04896                 tema = it->second;
04897                 invalidThemeMap().erase(themeId);
04898         }
04899 
04900         if (themeWasFound == false)
04901         {
04902                 it = themeMap().find(themeId);
04903                 if(it != themeMap().end())
04904                 {
04905                         themeWasFound = true;
04906                         tema = it->second;
04907                         themeMap().erase(themeId);
04908                 }
04909         }
04910 
04911         if (themeWasFound == false)
04912                 return false;
04913         
04914         if(!tema->eraseMetadata(this))
04915                 return false;
04916         
04917         string sql;
04918         // delete the collection table associated to this theme
04919         TeDatabasePortal* portal = this->getPortal();
04920         if(!portal)
04921                 return false;
04922 
04923         sql = "SELECT collection_table FROM te_theme WHERE theme_id = " + Te2String(themeId);
04924         if (!portal->query(sql) ||!portal->fetchRow())
04925         {       
04926                 delete portal;
04927                 return false;
04928         }
04929         string colTab = portal->getData("collection_table");
04930         //delete collection table
04931         if (this->tableExist(colTab))   
04932         {
04933                 sql = "DROP TABLE " + colTab;
04934                 if (!this->execute(sql) )
04935                 {       
04936                         delete portal;
04937                         return false;
04938                 }
04939         }
04940         //delete auxiliar collection table
04941         if (this->tableExist(colTab +"_aux"))   
04942         {
04943                 sql = "DROP TABLE " +colTab +"_aux";
04944                 if (!this->execute(sql) )
04945                 {       
04946                         delete portal;
04947                         return false;
04948                 }
04949         }
04950         portal->freeResult();
04951 
04952         //delete the visual associated to this theme
04953         if (existRelation("te_visual","fk_visual_legend_id") != TeRICascadeDeletion)
04954         {
04955                 sql = "SELECT legend_id FROM te_legend WHERE theme_id = " + Te2String(themeId);
04956                 if (!portal->query(sql))
04957                 {       
04958                         delete portal;
04959                         return false;
04960                 }
04961                 string wherec;
04962                 int c = 0;
04963                 while (portal->fetchRow())
04964                 {
04965                         if (c)
04966                                 wherec += ",";
04967                         c++;
04968                         wherec += portal->getData(0);
04969                 }
04970                 portal->freeResult();
04971         if (!wherec.empty()) 
04972         {
04973                         sql = "DELETE FROM te_visual WHERE legend_id IN (" + wherec + ")";
04974                         if (!this->execute(sql))
04975                         {       
04976                                 delete portal;
04977                                 return false;
04978                         }
04979            }
04980         }
04981 
04982         //delete lut table from current raster visual, if it exist
04983         if(tema->rasterVisual())
04984         {
04985                 if(!tema->rasterVisual()->getLutTableName().empty())
04986                 {
04987                         std::string lutTableName = tema->rasterVisual()->getLutTableName();
04988 
04989                         if (this->tableExist(lutTableName))
04990                         {
04991                                 if(!this->deleteTable(lutTableName))
04992                                         return false;
04993                         }
04994                 }
04995         }
04996 
04997         //delete all visuals of raster associated to this theme
04998         if (existRelation("te_visual_raster","fk_visrast_theme_id") != TeRICascadeDeletion)
04999         {
05000                 sql = "DELETE FROM te_visual_raster WHERE theme_id =" + Te2String(themeId);
05001                 if (!this->execute (sql))
05002                 {       
05003                         delete portal;
05004                         return false;
05005                 }
05006         }
05007         
05008         //delete all legends associated to this theme
05009         if (existRelation("te_legend","fk_legend_theme_id") != TeRICascadeDeletion)
05010         {
05011                 sql = "DELETE FROM te_legend WHERE theme_id =" + Te2String(themeId);
05012                 if (!this->execute (sql))
05013                 {       
05014                         delete portal;
05015                         return false;
05016                 }
05017         }
05018         
05019         //select the view of this theme
05020         sql = "SELECT view_id FROM te_theme WHERE theme_id = " + Te2String(themeId);
05021         portal->freeResult();
05022         if(!portal->query(sql) || !portal->fetchRow())
05023         {       
05024                 delete portal;
05025                 return false;
05026         }
05027 
05028         //delete theme of the view tree
05029         int viewId = portal->getInt("view_id");
05030         delete portal;
05031 
05032         //delete the tables associated to this theme
05033         if (existRelation("te_theme_table","fk_thmtable_theme_id") != TeRICascadeDeletion)
05034         {
05035                 sql = "DELETE FROM te_theme_table WHERE theme_id =" + Te2String(themeId);
05036                 if (!this->execute (sql))
05037                         return false;
05038         }
05039                 
05040         //delete the grouping
05041         if (existRelation("te_grouping","fk_group_theme_id")  != TeRICascadeDeletion)
05042         {
05043                 sql = "DELETE FROM te_grouping WHERE theme_id =" + Te2String(themeId);
05044                 if (!this->execute (sql))
05045                         return false;
05046         }
05047 
05048         // delete raster visual
05049         if (existRelation("te_visual_raster","fk_visrast_theme_id") == TeNoRelation )
05050         {
05051                 sql = "DELETE FROM te_visual_raster WHERE theme_id =" + Te2String(themeId);
05052                 if (!this->execute (sql))
05053                         return false;
05054         }
05055 
05056         sql = " UPDATE te_view SET current_theme = NULL WHERE current_theme = "+ Te2String(themeId);
05057         this->execute(sql);
05058         
05059         // delete the theme
05060         sql = " DELETE FROM te_theme WHERE theme_id = " + Te2String(themeId);
05061         if (!this->execute (sql))
05062                 return false;
05063 
05064         //delete in the maps
05065         TeView* view = viewMap()[viewId];
05066         if (view) //this view exists
05067                 view->remove(themeId); 
05068 
05069     unsigned int i;
05070         TeLegendEntryVector& legendVector = tema->legend();
05071         for (i = 0; i < legendVector.size(); ++i)
05072                 legendMap().erase(legendVector[i].id());
05073         
05074         delete tema;
05075         return true;
05076 }
05077 
05078 bool
05079 TeDatabase::deleteThemeGroup(int themeId)
05080 {
05081         string sql;
05082         // delete the theme
05083         sql = "DELETE FROM te_grouping WHERE theme_id = " + Te2String(themeId);
05084         if (!this->execute (sql))
05085                 return false;
05086         return true;
05087 }
05088 
05089 bool
05090 TeDatabase::deleteLegend(int themeId)
05091 {
05092         // If there is a collection table update legend of the objects in it
05093         TeDatabasePortal* portal = this->getPortal();
05094         if(!portal)
05095                 return false;
05096         string sel = "SELECT collection_table FROM te_theme WHERE theme_id = " + Te2String(themeId);
05097         string TC;
05098         if (portal->query(sel) && portal->fetchRow())
05099                 TC = portal->getData(0);
05100         delete portal;
05101 
05102         if (!TC.empty() && this->tableExist(TC))
05103         {
05104                 string up = "UPDATE " + TC + " SET c_legend_id = 0";
05105                 if (!execute(up))
05106                         return false;
05107         }
05108 
05109         // Delete visual of the legends
05110         string del = "DELETE FROM te_visual WHERE legend_id IN ";
05111         del += "(SELECT legend_id FROM te_legend WHERE theme_id = " + Te2String(themeId);
05112         del += " AND group_id > -1)";
05113         if (!execute(del))
05114                 return false;
05115 
05116         del = "DELETE FROM te_legend WHERE theme_id = " + Te2String(themeId);
05117         del += " AND group_id > -1";
05118         if (!execute(del))
05119                 return false;
05120 
05121         // Delete from memory the legends of the theme
05122         unsigned int i;
05123         TeAbstractTheme *theme = metaModel_->themeMap()[themeId];
05124         if(theme == NULL)
05125         {
05126                 theme = metaModel_->invalidThemeMap()[themeId];
05127                 if(theme == NULL)
05128                 {
05129                         return false;
05130                 }
05131         }
05132         TeLegendEntryVector& legendVector = theme->legend();
05133         for (i = 0; i < legendVector.size(); ++i)
05134                 metaModel_->legendMap().erase(legendVector[i].id());
05135         legendVector.clear();
05136 
05137         //delete grouping
05138         del = "DELETE FROM te_grouping WHERE theme_id =" + Te2String(themeId);
05139         if (!execute (del))
05140                 return false;
05141                 
05142         return true;
05143 }
05144 
05145 bool
05146 TeDatabase::updateLayer(TeLayer *layer)
05147 {
05148         if (!layer)
05149                 return false;
05150 
05151         if (layer->projection())
05152                 updateProjection(layer->projection());
05153 
05154         string sql;
05155         sql = "UPDATE te_layer SET ";
05156         sql += "name = '" + layer->name() + "' ";
05157         if (layer->box().isValid())
05158         {
05159                 sql += ", lower_x = " + Te2String(layer->box().x1(),15) + " ";
05160                 sql += ", lower_y = " + Te2String(layer->box().y1(),15) + " ";
05161                 sql += ", upper_x = " + Te2String(layer->box().x2(),15) + " ";
05162                 sql += ", upper_y = " + Te2String(layer->box().y2(),15) + " ";
05163         }else
05164         {
05165                 sql += ", lower_x = " + Te2String(layer->box().x1()) + " ";
05166                 sql += ", lower_y = " + Te2String(layer->box().y1()) + " ";
05167                 sql += ", upper_x = " + Te2String(layer->box().x2()) + " ";
05168                 sql += ", upper_y = " + Te2String(layer->box().y2()) + " ";
05169         }
05170         if(layer->getEditionTime().isValid())
05171         {
05172                 TeTime editionTime = layer->getEditionTime();
05173                 sql += ", edition_time = " + this->getSQLTime(editionTime);
05174         }
05175         sql +=  " WHERE layer_id = " + Te2String(layer->id());
05176 
05177         return (this->execute (sql));
05178 }
05179 
05180 bool
05181 TeDatabase::loadLayerSet(const bool& loadAttrList)
05182 {
05183         //clear layer map
05184         TeLayerMap::iterator it = metaModel_->layerMap().begin();
05185         while (it != metaModel_->layerMap().end())
05186         {
05187                 if(it->second)
05188                         delete it->second;
05189                 ++it;
05190         }
05191         metaModel_->layerMap().clear();
05192         
05193         string sql = " SELECT te_layer.*, "; // 0 - 9 (10 columns)
05194         sql += " te_projection.*, "; //10 - 21 (12 columns)
05195         sql += " te_datum.radius, te_datum.flattening, te_datum.dx, te_datum.dy, te_datum.dz, "; //22 - 26 (5 columns)
05196         sql += " te_representation.*, "; // 27 - 41 (15 columns)
05197         sql += " te_layer_table.* "; // 42 - 53 (12 columns)
05198         
05199         sql += " FROM ((((te_layer INNER JOIN te_projection ";
05200         sql += " ON te_layer.projection_id = te_projection.projection_id) ";
05201         sql += " LEFT JOIN te_representation ON ";
05202         sql += " te_layer.layer_id = te_representation.layer_id) ";
05203         sql += " LEFT JOIN te_layer_table ON ";
05204         sql += " te_layer.layer_id = te_layer_table.layer_id) ";
05205         sql += " LEFT JOIN te_datum ON te_projection.datum = te_datum.name) ";
05206 
05207         sql += " ORDER BY te_layer.layer_id, te_representation.geom_type, te_layer_table.table_id ";
05208 
05209         TeDatabasePortal* portal = this->getPortal();
05210         if(!portal)
05211                 return false;
05212 
05213         if (!portal->query(sql))
05214         {       
05215                 delete portal;
05216                 return false;
05217         }
05218         
05219         int lastLayerId = -1;
05220         TeLayer *layer = 0;
05221         bool hasNewRow = portal->fetchRow(); //idicates that this portal was fetched 
05222         while(hasNewRow)
05223         {
05224                 //load view and its projection 
05225                 if(lastLayerId!=atoi(portal->getData(0)))
05226                 {
05227                         TeProjection* proj = 0;
05228                         if(!portal->getProjection(&proj, 10)) //load projection
05229                         {
05230                                 delete portal;
05231                                 return false;
05232                         }
05233                         layer = new TeLayer();
05234                         if(!portal->getLayer(*layer, 0)) //load layer
05235                         {
05236                                 delete portal;
05237                                 delete layer;
05238                                 return false;
05239                         }
05240                         if (proj != 0)
05241                                 layer->setProjection(proj);
05242                         lastLayerId = layer->id();
05243                 }
05244 
05245                 //load its representation and its tables
05246                 bool hasRepsTablesToThisLayer = true;
05247                 vector<int> loadedTableId;
05248                 while(hasRepsTablesToThisLayer)
05249                 {
05250                         //load representation
05251                         string repId = portal->getData(27);
05252 
05253                         TeRepresPointerVector::iterator it;
05254 
05255                         //bool textLoaded = false;
05256 
05257                         //for(it = layer->vectRepres().begin(); it != layer->vectRepres().end(); ++it)
05258                         //{
05259                         //      if((*it)->id_ == atoi(repId.c_str()))
05260                         //      {
05261                         //              textLoaded = true;
05262                         //              break;
05263                         //      }
05264                         //}
05265 
05266                         if(!repId.empty() && 
05267                                 (!layer->hasGeometry(TeGeomRep(portal->getInt(29))) || 
05268                                 (TeGeomRep(portal->getInt(29)) == TeTEXT))/* && (!textLoaded)*/)
05269                         {
05270                                 TeRepresentation* rep = new TeRepresentation();
05271                                 if(!portal->getRepresentation(*rep, 27))
05272                                 {
05273                                         delete rep;
05274                                         delete layer;
05275                                         delete portal;
05276                                 }
05277                                 layer->addVectRepres(rep);
05278                         }
05279                         
05280                         //load tables
05281                         if( find(loadedTableId.begin(), loadedTableId.end(), portal->getInt(42)) == loadedTableId.end())
05282                         {
05283                                 TeTable attrTable;
05284                                 if(portal->getAttrTable(attrTable, 42))
05285                                 {
05286                                         TeAttributeList attrList;
05287                                         if(loadAttrList)
05288                                                 getAttributeList(attrTable.name(), attrList);
05289                                         attrTable.setAttributeList(attrList);
05290                                         layer->addAttributeTable(attrTable);
05291                                         loadedTableId.push_back(attrTable.id());
05292                                 }
05293                         }
05294                         hasNewRow = portal->fetchRow();
05295                         if(!hasNewRow || portal->getInt(0)!= layer->id())
05296                                 hasRepsTablesToThisLayer = false;
05297                 }
05298 
05299                 layer->setDatabase(this);
05300                 metaModel_->layerMap()[layer->id()] = layer;
05301         }
05302 
05303         delete portal;
05304         return true;
05305 
05306 }
05307 
05308 string
05309 TeDatabase::getRasterTable(int layerId, const string& objectId)
05310 {
05311         if (layerId <=0 )
05312                 return "";
05313 
05314         TeDatabasePortal* portal = this->getPortal();
05315         if(!portal)
05316                 return "";
05317 
05318         string get;
05319         // get the raster representation
05320         get = "SELECT geom_table FROM te_representation WHERE layer_id = "+Te2String(layerId);
05321         get += " AND (geom_type= " + Te2String((int)TeRASTER) + " OR geom_type= " + Te2String((int)TeRASTERFILE) + ")";
05322         
05323         // error executing query or no there is no raster representation 
05324         if (!portal->query(get) || !portal->fetchRow())
05325         {
05326                 delete portal;
05327                 return "";
05328         }
05329 
05330         string tableName = portal->getData(0);
05331         portal->freeResult();
05332         if (tableName.empty())
05333         {
05334                 delete portal;
05335                 return "";
05336         }
05337 
05338         // check if a specific object is being looked for
05339         get = "SELECT raster_table FROM " + tableName + " WHERE object_id='" + objectId + "'";
05340         if (!portal->query(get) || !portal->fetchRow())
05341         {
05342                 delete portal;
05343                 return "";
05344         }
05345         tableName = portal->getData(0);
05346         delete portal;
05347         return tableName;
05348 }
05349 
05350 
05351 TeRaster*
05352 TeDatabase::loadLayerRaster(int layerId, const string& objectId, const char& mode)
05353 {
05354         if (layerId <=0 )
05355                 return 0;
05356 
05357         TeDatabasePortal* portal = this->getPortal();
05358         if(!portal)
05359                 return 0;
05360 
05361         TeRaster* raster = 0;
05362         string get;
05363 
05364         // get the raster representation
05365         get = "SELECT geom_table, geom_type, initial_time FROM te_representation WHERE layer_id = "+Te2String(layerId);
05366         get += " AND (geom_type= " + Te2String((int)TeRASTER) + " OR geom_type= " + Te2String((int)TeRASTERFILE) + ")";
05367         
05368         // error executing query or no there is no raster representation 
05369         if (!portal->query(get) || !portal->fetchRow())
05370         {
05371                 delete portal;
05372                 return 0;
05373         }
05374         string tableName = portal->getData(0);
05375         TeGeomRep rep = static_cast<TeGeomRep>(portal->getInt(1));
05376         TeTime date = portal->getDate(2);
05377         portal->freeResult();
05378         if (tableName.empty())
05379         {
05380                 delete portal;
05381                 return 0;
05382         }
05383 
05384         //--- this check is made for compatibility reasons with older terralib databases
05385         TeAttributeRep  attrRep;
05386         attrRep.name_ = "tiling_type";
05387         attrRep.type_ = TeINT;
05388                 
05389         TeAttribute att;
05390         if(!columnExist(tableName, attrRep.name_,att))
05391         {
05392                 addColumn (tableName, attrRep);
05393                 string sql = "UPDATE " + tableName + " SET tiling_type = " + Te2String(static_cast<int>(TeRasterParams::TeExpansible));
05394                 this->execute(sql);
05395         }
05396 
05397         // ---
05398 
05399         // check if a specific object is being looked for
05400         get = "SELECT * FROM " + tableName;
05401         if (!objectId.empty())
05402                 get += " WHERE object_id='" + objectId + "'"; 
05403         if (!portal->query(get, TeSERVERSIDE, TeUNIDIRECTIONAL, TeREADONLY, TeBINARYCURSOR) || !portal->fetchRow())
05404         {
05405                 delete portal;
05406                 return 0;
05407         }
05408 
05409         string oid = portal->getData("object_id");
05410         int geomId = portal->getInt("geom_id"); // get raster representation id
05411 
05412         // get raster parameters from te_raster_table table
05413         TeRasterParams params;
05414         params.fileName_ = portal->getData("raster_table");
05415         params.lutName_ = portal->getData("lut_table");
05416         params.nBands(portal->getInt("num_bands"));
05417         params.boundingBoxResolution(portal->getDouble("lower_x"),portal->getDouble("lower_y"),
05418                                                                  portal->getDouble("upper_x"),portal->getDouble("upper_y"),
05419                                                              portal->getDouble("res_x"),portal->getDouble("res_y"));
05420         params.blockHeight_ = portal->getInt("block_height");
05421         params.blockWidth_ = portal->getInt("block_width");
05422         params.tiling_type_ = static_cast<TeRasterParams::TeRasterTilingType>(portal->getInt("tiling_type"));
05423 
05424         if(date.isValid())
05425         {
05426                 params.date_ = date;
05427         }
05428 
05429         portal->freeResult();
05430 
05431         // get extra information from te_raster_metadata table
05432         string metadatatable = tableName + "_metadata"; 
05433         unsigned int nb = params.nBands();
05434         unsigned int i;
05435         for (i=0; i<nb; i++)
05436         {
05437                 get = "SELECT * FROM " + metadatatable + " WHERE geom_id=" + Te2String(geomId);
05438                 get += " AND band_id=" + Te2String(i);
05439                 if (portal->query(get) && portal->fetchRow()) 
05440                 {
05441                         params.vmax_[i] = portal->getDouble("max_value");
05442                         params.vmin_[i] = portal->getDouble("min_value");
05443                         params.nbitsperPixel_[i] = portal->getInt("num_bits");
05444                         params.dataType_[i] =  static_cast<TeDataType>(portal->getInt("data_type"));
05445                         params.compression_[i] = static_cast<TeRasterParams::TeRasterCompressionMode>(portal->getInt("compression_type"));
05446                         params.photometric_[i] = static_cast<TeRasterParams::TeRasterPhotometricInterpretation>(portal->getInt("photometric_type"));
05447                         params.bandName_[i] = portal->getData("band_name");
05448                 }
05449                 portal->freeResult();
05450         }
05451 
05452         // if raster is pallete get the associated LUT
05453         if (params.photometric_[0] == TeRasterParams::TePallete &&      rep != TeRASTERFILE)
05454                 this->loadRasterLUT(&params);
05455 
05456         // raster has the same projection as its layer
05457         get = "SELECT te_projection.*, te_datum.radius, te_datum.flattening, te_datum.dx, te_datum.dy, te_datum.dz";
05458         get += " FROM ((te_projection LEFT JOIN te_datum ON te_projection.datum = te_datum.name)";
05459         get += " INNER JOIN te_layer ON te_projection.projection_id = te_layer.projection_id)";
05460         get += " WHERE layer_id = " + Te2String(layerId);
05461         
05462         TeProjection* proj=0;
05463         if (portal->query(get) && portal->fetchRow())
05464                 portal->getProjection(&proj);
05465 
05466         portal->freeResult();
05467         params.projection(proj);
05468         if (proj)
05469                 delete proj;
05470 
05471         bool hasDummy = false;
05472         get = "SELECT band_id, dummy FROM " + metadatatable + " WHERE geom_id=" + Te2String(geomId);
05473         get += " AND NOT (dummy IS NULL)";
05474         if (portal->query(get))
05475         {
05476                 while (portal->fetchRow())
05477                 {
05478                         int b = portal->getInt(0);
05479                         double d = portal->getDouble("dummy");
05480                         params.setDummy(d,b);
05481                         hasDummy = true;
05482                 }
05483         }
05484         params.useDummy_ = hasDummy;
05485         params.mode_ = mode;
05486         params.objectId_ = oid;
05487         params.layerId_ = layerId;
05488         delete portal;
05489 
05490         if ( rep == TeRASTER)
05491         {
05492                 params.nTilesInMemory_ = 0;
05493                 params.database_ = this;
05494                 TeDecoderDatabase* dec = new TeDecoderDatabase(params);
05495                 dec->init();
05496                 raster = new TeRaster();
05497                 raster->setDecoder(dec);
05498                 raster->objectId(oid);
05499                 return raster;
05500         }
05501         try
05502         {
05503                 raster = new TeRaster(params);
05504         }
05505         catch(...)
05506         {
05507                 if (params.fileName_.empty() == false)
05508                 {
05509                         errorMessage_ = "File doesn't exist: ";
05510                         errorMessage_ += params.fileName_;
05511                 }
05512                 else
05513                 {
05514                         errorMessage_ = "Raster file is not accessible.";
05515                 }
05516                 return 0;
05517         } 
05518         raster->init();
05519         return raster;
05520 }
05521 
05522 bool 
05523 TeDatabase::loadRasterLUT(TeRasterParams* par)
05524 {
05525         if (par->lutName_.empty())              
05526                 return false;
05527         
05528         TeDatabasePortal* portal = this->getPortal();
05529         if (!portal)
05530                 return false;
05531 
05532         string get = "SELECT COUNT(index_id) FROM " + par->lutName_;
05533         if (!portal->query(get) || !portal->fetchRow())  // if there is no table, or table is empty
05534         {
05535                 delete portal;
05536                 return false;
05537         }
05538         int nentries = atoi(portal->getData(0));
05539         if (nentries <= 0)
05540         {
05541                 delete portal;
05542                 return false;
05543         }
05544         portal->freeResult();
05545 
05546         par->lutr_.clear();
05547         par->lutg_.clear();
05548         par->lutb_.clear();
05549         par->lutClassName_.clear();
05550 
05551         par->lutr_.resize(nentries);
05552         par->lutg_.resize(nentries);
05553         par->lutb_.resize(nentries);
05554         par->lutClassName_.resize(nentries);
05555 
05556         par->lutr_.assign(nentries,0);
05557         par->lutg_.assign(nentries,0);
05558         par->lutb_.assign(nentries,0);
05559         par->lutClassName_.assign(nentries,"");
05560 
05561         get = "SELECT * FROM " + par->lutName_ + " ORDER BY index_id ASC ";
05562         if (!portal->query(get) || !portal->fetchRow())  // if there is no table, or table is empty
05563         {
05564                 delete portal;
05565                 return false;
05566         }
05567 
05568         do
05569         {
05570                 int index = atoi(portal->getData(0));
05571                 par->lutr_[index] = atoi(portal->getData(1));
05572                 par->lutg_[index] = atoi(portal->getData(2));
05573                 par->lutb_[index] = atoi(portal->getData(3));
05574                 par->lutClassName_[index] = portal->getData(4);
05575         }while (portal->fetchRow());
05576 
05577         delete portal;
05578         return true;
05579 }
05580 
05581 bool
05582 TeDatabase::createSpatialIndex(const string& table, const string& columns, TeSpatialIndexType /*type*/, short /*level*/, short /*tile*/)
05583 {
05584         string idxName = "sp_idx_" + table;
05585         return createIndex(table, idxName, columns);
05586 }
05587 
05588 string TeDatabase::getSpatialIdxColumn(TeGeomRep rep)
05589 {
05590         string columns = "";
05591         switch(rep)
05592         {
05593                 case TePOINTS:
05594                 case TeNODES:   columns = "x, y";
05595                                                 break;
05596                 case TeLINES:
05597                 case TePOLYGONS:
05598                 case TeCELLS:
05599                                                 columns = "lower_x, lower_y, upper_x, upper_y";
05600                                                 break;
05601                 case TeRASTER:
05602                                                 columns = " lower_x, lower_y, upper_x, upper_y, resolution_factor, subband ";
05603                                                 break;
05604                 default:                columns = "";
05605         }
05606         
05607     return columns;
05608 }
05609 
05610 bool
05611 TeDatabase::loadLayer(TeLayer* layer, const bool& loadAttrList)
05612 {
05613         if (layer == 0)
05614                 return false;
05615 
05616         string rest;
05617         if (layer->id() > 0)
05618                 rest = " te_layer.layer_id = "+  Te2String(layer->id());
05619         else if (!layer->name().empty())
05620                 rest = " te_layer.name = '"+  layer->name() + "'";
05621         else
05622         {
05623                 this->errorMessage_ = "Layer procurado n�o possui nem id nem nome";
05624                 return false;
05625         }
05626         
05627         string sql = " SELECT te_layer.*, "; // 0 - 9 (10 columns)
05628         sql += " te_projection.*, "; //10 - 21 (12 columns)
05629         sql += " te_datum.radius, te_datum.flattening, te_datum.dx, te_datum.dy, te_datum.dz, "; //22 - 26 (5 columns)
05630         sql += " te_representation.*, "; // 27 - 41 (15 columns)
05631         sql += " te_layer_table.* "; // 42 - 53 (12 columns)
05632         
05633         sql += " FROM ((((te_layer INNER JOIN te_projection ";
05634         sql += " ON te_layer.projection_id = te_projection.projection_id) ";
05635         sql += " LEFT JOIN te_representation ON ";
05636         sql += " te_layer.layer_id = te_representation.layer_id) ";
05637         sql += " LEFT JOIN te_layer_table ON ";
05638         sql += " te_layer.layer_id = te_layer_table.layer_id) ";
05639         sql += " LEFT JOIN te_datum ON te_projection.datum = te_datum.name) ";
05640 
05641         sql += " WHERE "+ rest;
05642 
05643         sql += " ORDER BY te_representation.geom_type, te_layer_table.table_id ";
05644 
05645         TeDatabasePortal* portal = this->getPortal();
05646         if(!portal)
05647                 return false;
05648 
05649         if(!portal->query(sql) || !portal->fetchRow())
05650         {       
05651                 delete portal;
05652                 return false;
05653         }
05654 
05655         bool hasNewRow = true;
05656         TeProjection* proj = 0;
05657         if(!portal->getProjection(&proj, 10)) //load projection
05658         {
05659                 delete portal;
05660                 return false;
05661         }
05662         
05663         if(!portal->getLayer(*layer, 0)) //load layer
05664         {
05665                 delete portal;
05666                 delete layer;
05667                 return false;
05668         }
05669         if (proj != 0)
05670                 layer->setProjection(proj);
05671                 
05672         //load its representation and its tables
05673         bool hasRepsTablesToThisLayer = true;
05674         vector<int> loadedTableId;
05675         while(hasRepsTablesToThisLayer)
05676         {
05677                 string repId = portal->getData(27);
05678                 if(!repId.empty() && !layer->hasGeometry(TeGeomRep(portal->getInt(29))))
05679                 {
05680                         //load the geometry representation
05681                         TeRepresentation* rep = new TeRepresentation();
05682                         if(!portal->getRepresentation(*rep, 27))
05683                         {
05684                                 delete rep;
05685                                 delete layer;
05686                                 delete portal;
05687                         }
05688                         layer->addVectRepres(rep);
05689                 }
05690                 
05691                 //load tables
05692                 if(find(loadedTableId.begin(), loadedTableId.end(), portal->getInt(42)) == loadedTableId.end())
05693                 {
05694                         TeTable attrTable;
05695                         if(portal->getAttrTable(attrTable, 42))
05696                         {
05697                                 TeAttributeList attrList;
05698                                 if(loadAttrList)
05699                                         getAttributeList(attrTable.name(), attrList);
05700                                 attrTable.setAttributeList(attrList);
05701                                 layer->addAttributeTable(attrTable);
05702                                 loadedTableId.push_back(attrTable.id());
05703                         }
05704                 }
05705                 
05706                 hasNewRow = portal->fetchRow();
05707                 if(!hasNewRow || portal->getInt(0)!= layer->id())
05708                         hasRepsTablesToThisLayer = false;
05709         }
05710         layer->setDatabase(this);
05711         metaModel_->layerMap()[layer->id()] = layer;
05712         
05713         delete portal;
05714         return true;
05715 }
05716 
05717 bool
05718 TeDatabase::loadLayerTable(TeLayer* layer, const bool& loadAttrList)
05719 {
05720         TeDatabasePortal* portal = this->getPortal();
05721         if(!portal)
05722         {
05723                 this->errorMessage_ = "N�o foi poss�vel abrir portal para o banco";
05724                 return false;
05725         }
05726         
05727         // Get layer tables     
05728         string get =  " SELECT * FROM te_layer_table"; 
05729         get += " WHERE layer_id = " + Te2String(layer->id());
05730         get += " ORDER BY attr_table_type, table_id";
05731 
05732         if (!portal->query (get))
05733         {       
05734                 delete portal;
05735                 return false;
05736         }
05737 
05738         while (portal->fetchRow())
05739         {
05740                 TeTable attTable;
05741                 if(!portal->getAttrTable (attTable))
05742                 {
05743                         delete portal;
05744                         return false;
05745                 }
05746                 TeAttributeList attrList;
05747                 if(loadAttrList)
05748                         getAttributeList(attTable.name(), attrList);
05749                 attTable.setAttributeList(attrList);
05750                 layer->addAttributeTable(attTable);
05751         }
05752 
05753         delete portal;
05754         return true;
05755 }
05756 
05757 bool 
05758 TeDatabase::layerExist(int layerId)
05759 {
05760         TeDatabasePortal* portal = this->getPortal();
05761         if (!portal)
05762                 return false;
05763 
05764         string sql = "SELECT layer_id FROM te_layer WHERE layer_id = " + Te2String(layerId);
05765         if (!portal->query(sql))
05766         {       
05767                 delete portal;
05768                 return false;
05769         }
05770         if (!portal->fetchRow())
05771         {
05772                 delete portal;
05773                 return false;
05774         }
05775         delete portal;
05776         return true;
05777 }
05778 
05779 bool 
05780 TeDatabase::layerExist(string layerName)
05781 {
05782         TeDatabasePortal* portal = this->getPortal();
05783         if (!portal)
05784                 return false;
05785 
05786         string sql = "SELECT name FROM te_layer WHERE " + this->toUpper("name") + " = " + this->toUpper("'" + layerName + "'");
05787         if (!portal->query(sql))
05788         {       
05789                 delete portal;
05790                 return false;
05791         }
05792         if (!portal->fetchRow())
05793         {
05794                 delete portal;
05795                 return false;
05796         }
05797         delete portal;
05798         return true;
05799 }
05800 
05801 string TeDatabase::getNewLayerName(const string& n)
05802 {
05803         bool changed;
05804         string invalidChar;
05805         string name = TeCheckName(n, changed, invalidChar);
05806         string newName = name;
05807         
05808         TeDatabasePortal* portal = this->getPortal();
05809         if(!portal)
05810                 return "";
05811         
05812         bool flag = true;
05813         int count = 0;
05814         while(flag)
05815         {
05816                 portal->freeResult();
05817                 string q = "SELECT name FROM te_layer WHERE " + this->toUpper("name") + " = '" + TeConvertToUpperCase(newName) + "'";
05818                 if(portal->query(q) && portal->fetchRow())
05819                 {
05820                         // there is already this theme name 
05821                         newName = newName+"_"+Te2String(count);
05822                         ++count;
05823                         flag = true;
05824          }
05825                 else
05826                         flag = false; //found the new name
05827         }
05828         delete portal;
05829         return newName;
05830 }
05831 
05832 bool
05833 TeDatabase::deleteLayer(int layerId)
05834 {
05835         TeDatabasePortal* portal = this->getPortal();
05836         if (!portal)
05837                 return false;
05838         
05839         string sql = "SELECT projection_id FROM te_layer WHERE layer_id = ";
05840         sql += Te2String(layerId);
05841 
05842         if (!portal->query(sql))
05843         {       
05844                 delete portal;
05845                 return false;
05846         }
05847 
05848         if (!portal->fetchRow())
05849         {
05850                 delete portal;
05851                 return false;
05852         }
05853 
05854         int projId = portal->getInt("projection_id");
05855         portal->freeResult();
05856 
05857         // Get all representations that are associated to this layer
05858         sql = "SELECT * FROM te_representation WHERE layer_id = "+ Te2String(layerId);
05859         if (!portal->query (sql))
05860         {
05861                 delete portal;
05862                 return false;
05863         }
05864 
05865         while (portal->fetchRow())
05866         {       
05867                 // Save the name of the geometry table
05868                 string geomTable = portal->getData("geom_table");
05869 
05870                 // Delete lut table
05871                 TeGeomRep rep = TeGeomRep(portal->getInt("geom_type"));
05872                 if (rep == TeRASTER || rep == TeRASTERFILE)
05873                 {
05874                         if(!this->tableExist(geomTable))
05875                         {
05876                                 continue;
05877                         }
05878 
05879                         TeDatabasePortal* portal2 = this->getPortal();
05880                         sql = "SELECT lut_table, raster_table FROM " + geomTable;
05881                         string tabName;
05882                         if (!portal2->query (sql))
05883                         {
05884                                 delete portal2;
05885                                 continue;
05886                         }
05887 
05888                         while (portal2->fetchRow())
05889                         {
05890                                 // remove lut table
05891                                 tabName = portal2->getData(0);
05892                                 if (!tabName.empty() && this->tableExist(tabName))
05893                                 {
05894                                         sql = "DROP TABLE " + tabName;
05895                                         this->execute(sql);
05896                                 }
05897                                 // remove raster table
05898                                 tabName = portal2->getData(1);
05899                                 if (!tabName.empty() && this->tableExist(tabName))
05900                                 {
05901                                         //sql = "DROP TABLE " + tabName;
05902                                         //this->execute(sql);
05903                                         deleteTable(tabName);
05904                                 }
05905                         }
05906                         delete portal2;
05907                         // remove raster metadata table
05908                         tabName = geomTable + "_metadata";
05909                         if (!tabName.empty() && this->tableExist(tabName))
05910                         {
05911                                 //sql = "DROP TABLE " + tabName;
05912                                 //this->execute(sql);
05913                                 deleteTable(tabName);
05914                         }
05915                 }
05916                 if (this->tableExist(geomTable))
05917                 {
05918                         //sql = "DROP TABLE " + geomTable;
05919                         //if (!this->execute(sql) )
05920                         if(!deleteTable(geomTable))
05921                         {
05922                                 delete portal;
05923                                 return false;
05924                         }
05925                 }
05926         }
05927         portal->freeResult();
05928 
05929         if (existRelation("te_representation","fk_rep_layer_id") != TeRICascadeDeletion)
05930         {
05931                 // Delete entries into representations table
05932                 sql = "DELETE FROM te_representation WHERE layer_id = " +Te2String(layerId);
05933                 if (!this->execute(sql) )
05934                 {
05935                         delete portal;
05936                         return false;
05937                 }
05938         }
05939 
05940         // delete layer themes
05941         sql = "SELECT theme_id FROM te_theme WHERE layer_id=" + Te2String(layerId);
05942         if (!portal->query (sql))
05943         {
05944                 delete portal;
05945                 return false;
05946         }
05947         
05948         int themeId;
05949         while (portal->fetchRow())
05950         {       
05951                 themeId = portal->getInt("theme_id");
05952                 this->deleteTheme(themeId);
05953         }
05954 
05955         //Delete attributes tables
05956         if(!deleteLayerTable(layerId))
05957                 return false;
05958         
05959         sql = "DELETE FROM te_layer WHERE layer_id=" + Te2String(layerId);
05960         if (!this->execute(sql))
05961         {
05962                 delete portal;
05963                 return false;
05964         }
05965 
05966         if(!deleteProjection(projId))
05967         {
05968                 delete portal;
05969                 return false;
05970         }
05971 
05972         // remove all the items� themes associated to the layer to be removed
05973         TeThemeMap::iterator it;
05974         for (it = metaModel_->themeMap().begin(); it != metaModel_->themeMap().end();)
05975         {
05976                 if(it->second->getProductId() != TeTHEME)
05977                 {
05978                         ++it;
05979                         continue;
05980                 }
05981                 TeTheme *theme = static_cast<TeTheme*> (it->second);
05982                 ++it;
05983                 if (theme && theme->layer() && (theme->layer()->id() == layerId))
05984                 {
05985                         metaModel_->themeMap().erase(theme->id());
05986                         delete theme;
05987                 }
05988         }
05989         // delete layer and its entry in the layer map
05990         TeLayer* layer = metaModel_->layerMap()[layerId];
05991         metaModel_->layerMap().erase(layerId);
05992         delete layer;
05993 
05994         delete portal;
05995         return true;
05996 }
05997 
05998 
05999 bool
06000 TeDatabase::deleteLayerTable (int layerId, TeAttrTableType ttype)
06001 {
06002         TeDatabasePortal* portal = this->getPortal();
06003         if(!portal)
06004                 return false;
06005 
06006         //tables of the type 1 can be relationed with other layer ??? Conferir
06007         string query = "SELECT attr_table, table_id FROM te_layer_table WHERE layer_id = " + Te2String(layerId);
06008         query += " AND attr_table_type = " + Te2String(static_cast<int>(ttype));
06009         if(!portal->query(query))
06010         {
06011                 delete portal;
06012                 return false;
06013         }
06014                 
06015         vector<int> tableIds;
06016         string attrTable;
06017         string tableId;
06018         string drop;
06019         while (portal->fetchRow())
06020         {
06021                 attrTable = portal->getData(0);
06022                 tableId = portal->getData(1);
06023                 if(tableExist(attrTable))
06024                 {
06025                         if(!deleteTable(attrTable))
06026                         {
06027                                 delete portal;
06028                                 return false;
06029                         }
06030                 }
06031                 tableIds.push_back(atoi(tableId.c_str()));
06032 
06033                 if(tableExist("te_address_locator"))
06034                 {
06035                         string del  = "DELETE FROM te_address_locator WHERE table_id = "+ tableId;
06036                         execute(del);
06037                 }
06038         }
06039 
06040         delete portal;
06041         string del;
06042         if (existRelation("te_tables_relation","fk_tabrelation_laytable_id") != TeRICascadeDeletion)
06043         {
06044                 for (unsigned int i=0; i<tableIds.size();i++)
06045                 {
06046                         del = "DELETE FROM te_tables_relation WHERE relation_id = " + Te2String(tableIds[i]);
06047                         if (!execute (del))
06048                                 return false;
06049                 }
06050         }
06051         del = "DELETE FROM te_layer_table WHERE layer_id = " + Te2String(layerId);
06052         if (!execute (del))
06053                 return false;
06054         return true;
06055 }
06056 
06057 bool 
06058 TeDatabase::updateRepresentation (int layerId, TeRepresentation& rep)
06059 {
06060         if (layerId <= 0)
06061                 return false;
06062 
06063         string sql;
06064         sql  = "UPDATE te_representation SET ";
06065         sql += " lower_x= " + Te2String(rep.box_.x1(),15);
06066         sql += ", lower_y= " + Te2String(rep.box_.y1(),15);
06067         sql += ", upper_x= " + Te2String(rep.box_.x2(),15);
06068         sql += ", upper_y= " + Te2String(rep.box_.y2(),15);
06069         sql += ", description= '" + rep.description_ + "'";
06070         sql += ", res_x= " + Te2String(rep.resX_,15);
06071         sql += ", res_y= " + Te2String(rep.resY_,15);
06072         sql += ", num_cols=" + Te2String(rep.nCols_);
06073         sql += ", num_rows=" + Te2String(rep.nLins_);
06074 
06075         if (rep.geomRep_ != TeTEXT)
06076                 sql += ", geom_table='" + rep.tableName_ + "'";
06077 
06078         sql += " WHERE layer_id=" + Te2String(layerId);
06079         sql += " AND geom_type= " + Te2String(rep.geomRep_);
06080 
06081         if (rep.geomRep_ == TeTEXT)
06082                 sql += " AND geom_table='" + rep.tableName_ + "'";
06083 
06084         return this->execute(sql);
06085 }
06086 
06087 bool 
06088 TeDatabase::insertRasterGeometry(const string& tableName, TeRasterParams& par, const string& objectId)
06089 {
06090         if (tableName.empty())
06091                 return false;
06092         
06093         string objId; 
06094         if (objectId.empty())
06095                 objId = "O1";
06096         else
06097                 objId = objectId;
06098 
06099         //------ this check is made for compatibility reasons with old versions of TerraLib databases
06100         TeAttributeRep  attrRep;
06101         attrRep.name_ = "tiling_type";
06102         attrRep.type_ = TeINT;
06103                 
06104         TeAttribute att;
06105         if(!columnExist(tableName, attrRep.name_,att))
06106         {
06107                 addColumn (tableName, attrRep);
06108                 string sql = "UPDATE " + tableName + " SET tiling_type = " + Te2String(static_cast<int>(TeRasterParams::TeExpansible));
06109                 this->execute(sql);
06110         }
06111 
06112         //------
06113 
06114         // finds the name of the raster geometry table
06115         TeDatabasePortal* portal = this->getPortal();
06116         if(!portal)
06117                 return false;
06118 
06119         TeBox box = par.boundingBox();
06120 
06121         string ins = "INSERT INTO " + tableName + " (object_id, raster_table, lut_table, ";
06122         ins += "res_x, res_y, num_bands, num_cols, num_rows, block_height, block_width, ";
06123         ins += "lower_x, lower_y, upper_x, upper_y, tiling_type) ";
06124         ins += " VALUES ('" + objId + "', '" + par.fileName_+ "', '" +  par.lutName_ + "', ";
06125         ins += Te2String(par.resx_) + ", " + Te2String(par.resy_) + ", ";
06126         ins += Te2String(par.nBands()) + ", " + Te2String(par.ncols_) + ", " + Te2String(par.nlines_) + ", ";
06127         ins += Te2String(par.blockHeight_) + ", " + Te2String(par.blockWidth_) + ", ";
06128         ins += Te2String(box.x1_,15) +", " + Te2String(box.y1_,15) + ", ";
06129         ins += Te2String(box.x2_,15) +", " + Te2String(box.y2_,15) + ", ";
06130         ins     += Te2String(par.tiling_type_) + ")";
06131         if (!this->execute(ins))
06132         {
06133                 delete portal;
06134                 return false;
06135         }
06136 
06137         // save the pallete associated to the raster
06138         // if it doesn�t exist yet
06139         if (par.photometric_[0] == TeRasterParams::TePallete && !par.lutName_.empty()) 
06140         {
06141                  if (!this->tableExist(par.lutName_))
06142                  {
06143                          if (this->createLUTTable(par.lutName_))
06144                         {
06145                                 for (unsigned int i=0; i<par.lutb_.size(); i++)
06146                                 {
06147                                         string sql = "INSERT INTO " + par.lutName_ + " VALUES(";
06148                                         sql += Te2String(i) + ", ";
06149                                         sql += Te2String(par.lutr_[i]) + ", ";
06150                                         sql += Te2String(par.lutg_[i]) + ", ";
06151                                         sql += Te2String(par.lutb_[i]) + ", '";
06152                                         sql += par.lutClassName_[i] + "')";
06153                                         this->execute(sql);
06154                                 }
06155                          }
06156                  }
06157         }
06158         
06159         ins = "SELECT geom_id FROM " + tableName + " WHERE object_id='" + objId + "'";
06160         ins += " AND raster_table='" + par.fileName_+ "'";
06161         if(!portal->query(ins) || !portal->fetchRow())
06162         {
06163                 delete portal;
06164                 return false;
06165         }
06166         int geomId = atoi(portal->getData(0));
06167         delete portal;
06168         string  metadataTableName = tableName+"_metadata";
06169         insertRasterMetadata(metadataTableName, geomId,par);
06170          return true;
06171 }
06172 
06173 bool 
06174 TeDatabase::updateRasterRepresentation(int layerId, TeRasterParams& par, const string& objectId)
06175 {
06176         TeDatabasePortal* portal = this->getPortal();
06177         if(!portal)
06178                 return false;
06179 
06180         string sql = "SELECT repres_id, lower_x, lower_y, upper_x, upper_y, geom_table ";
06181         sql += " FROM te_representation WHERE layer_id= " + Te2String(layerId);
06182         sql += " AND geom_type= " + Te2String(TeRASTER);
06183 
06184         if(!portal->query(sql) || !portal->fetchRow())
06185         {
06186                 delete portal;
06187                 return false;
06188         }
06189         TeBox box (portal->getDouble(1),portal->getDouble(2),
06190                        portal->getDouble(3),portal->getDouble(4));
06191         int represId = atoi(portal->getData(0));
06192         string rasterrep = portal->getData(5);
06193         portal->freeResult();
06194 
06195         updateBox(box,par.boundingBox());
06196         sql = "UPDATE te_representation SET lower_x = " + Te2String(box.x1_,15);
06197         sql += ", lower_y = " + Te2String(box.y1_,15) + ", upper_x = " + Te2String(box.x2_,15);
06198         sql += ", upper_y = " + Te2String(box.y2_,15);
06199 
06200         if(par.date_.isValid())
06201         {       
06202                 std::string sqlTime = getSQLTime(par.date_);
06203                 if(!sqlTime.empty())
06204                 {
06205                         sql += ", initial_time = " + sqlTime;
06206                         sql += ", final_time = " + sqlTime;
06207                 }
06208         }
06209         sql += " WHERE repres_id=" + Te2String(represId);
06210         if(!execute(sql))
06211         {
06212                 delete portal;
06213                 return false;
06214         }        
06215 
06216         string objId; 
06217         if (objectId.empty())
06218                 objId = "O1";
06219         else
06220                 objId = objectId;
06221 
06222         box = par.boundingBox();
06223 
06224         sql = "UPDATE " + rasterrep + " SET lut_table ='" + par.lutName_ + "'";
06225         sql += ", res_x= " + Te2String(par.resx_,15) + ", res_y=" + Te2String(par.resy_,15);
06226         sql += ", num_bands=" + Te2String(par.nBands()) + ", num_cols=" + Te2String(par.ncols_);
06227         sql += ", num_rows=" + Te2String(par.nlines_) + ", block_height=" +  Te2String(par.blockHeight_);
06228         sql += ", block_width= " + Te2String(par.blockWidth_) + ", lower_x = " + Te2String(box.x1_,15);
06229         sql += ", lower_y = " + Te2String(box.y1_,15) +  ", upper_x = " + Te2String(box.x2_,15);
06230         sql += ", upper_y = " + Te2String(box.y2_,15);
06231         sql += "  WHERE object_id='" + objId + "' AND raster_table='" + par.fileName_ + "'";
06232         if (!this->execute(sql))
06233         {
06234                 delete portal;
06235                 return false;
06236         }
06237         
06238         sql = "SELECT geom_id FROM " + rasterrep + " WHERE object_id='" + objId + "'";
06239         sql+= " AND raster_table='" + par.fileName_+ "'";
06240         if(!portal->query(sql) || !portal->fetchRow())
06241         {
06242                 delete portal;
06243                 return false;
06244         }
06245 
06246         // save the pallete associated to the raster
06247         // if it doesn�t exist yet
06248         if (par.photometric_[0] == TeRasterParams::TePallete && !par.lutName_.empty()) 
06249         {
06250 
06251                  if (!this->tableExist(par.lutName_))
06252                  {
06253                          if (this->createLUTTable(par.lutName_))
06254                         {
06255                                 for (unsigned int i=0; i<par.lutb_.size(); i++)
06256                                 {
06257                                         string sql = "INSERT INTO " + par.lutName_ + " VALUES(";
06258                                         sql += Te2String(i) + ", ";
06259                                         sql += Te2String(par.lutr_[i]) + ", ";
06260                                         sql += Te2String(par.lutg_[i]) + ", ";
06261                                         sql += Te2String(par.lutb_[i]) + ", '";
06262                                         sql += par.lutClassName_[i] + "')";
06263                                         if (!this->execute(sql) )       
06264                                         {
06265                                                 delete portal;
06266                                                 return false;                                           
06267                                         }
06268                                 }
06269                          }
06270                  }
06271         }
06272 
06273         int geomId = atoi(portal->getData(0));
06274         delete portal;
06275         string metadatatabel = rasterrep + "_metadata";
06276         return updateRasterMetadata(metadatatabel,geomId,par);
06277 }
06278 
06279 bool 
06280 TeDatabase::insertRasterMetadata (const string& tableName, int geomId, TeRasterParams& par)
06281 {
06282         if (geomId <= 0)
06283                 return false;
06284         
06285         string ins;
06286         unsigned int i;
06287 
06288         unsigned int nb = par.nBands();
06289         ins = "INSERT INTO " + tableName + " (geom_id, band_id, min_value, max_value, ";
06290         ins += " num_bits, data_type, photometric_type, compression_type, band_name ) VALUES (";
06291         string vals;
06292         for (i=0; i<nb; i++)
06293         {
06294                 vals = Te2String(geomId) + ", " + Te2String(i) + ", ";
06295                 vals += Te2String(par.vmin_[i]) + ", " +  Te2String(par.vmax_[i]) + ", ";
06296                 vals += Te2String(par.nbitsperPixel_[i]) + ", " +  Te2String(par.dataType_[i]) + ", " ;
06297                 vals += Te2String(par.photometric_[i]) + ", " +  Te2String(par.compression_[i]) + ", '" + par.bandName_[i] + "' )" ;
06298                 string sql = ins + vals;
06299                 if (!this->execute(sql))
06300                         return false;
06301         }
06302 
06303         // update dummy value
06304         if (par.useDummy_)
06305         {
06306                 ins = "UPDATE " + tableName + " SET dummy = ";
06307                 for (i=0; i<nb; i++)
06308                 {
06309                         vals = Te2String(par.dummy_[i]) + " WHERE geom_id = " +  Te2String(geomId);
06310                         vals += " AND band_id=" + Te2String(i);
06311                         string sql = ins + vals;
06312                         if (!this->execute(sql))
06313                                 return false;
06314                 }
06315         }
06316         return true;
06317 }
06318 
06319 bool 
06320 TeDatabase::updateRasterMetadata (const string& tableName, int geomId, TeRasterParams& par)
06321 {
06322         if (geomId <= 0)
06323                 return false;
06324 
06325         string sql = "DELETE FROM " + tableName + " WHERE geom_id = " + Te2String(geomId);
06326         if (!this->execute (sql))
06327                 return false;
06328         return insertRasterMetadata(tableName,geomId,par);
06329 }
06330 
06331 bool 
06332 TeDatabase::updateLegend (TeLegendEntry *legend)
06333 {
06334         if (!legend)
06335                 return false;
06336 
06337         string sql;
06338         if (legend->id() > 0 )
06339         {
06340                 sql = "UPDATE te_legend SET ";
06341                 sql += " theme_id=" + Te2String (legend->theme());
06342                 sql += ",group_id=" + Te2String (legend->group());
06343                 sql += ",num_objs=" + Te2String (legend->count());
06344                 sql += ",lower_value='" + escapeSequence(legend->from())+"'";
06345                 sql += ",upper_value='" + escapeSequence(legend->to())+"'";
06346                 sql += ",label='" + escapeSequence(legend->label())+"'";
06347                 sql += " WHERE legend_id=" + Te2String (legend->id());
06348 
06349                 if (execute(sql) == false)
06350                         return false;
06351         }
06352         else
06353         {
06354                 if (!insertLegend(legend))
06355                         return false;
06356         }
06357         metaModel_->legendMap()[legend->id()] = legend;
06358 
06359         return updateVisual(legend);
06360 }
06361 
06362 bool 
06363 TeDatabase::updateLegend (vector<TeLegendEntry>& legVec)
06364 {
06365         unsigned int i;
06366         for (i = 0; i < legVec.size(); ++i)
06367         {
06368                 if(!updateLegend(&legVec[i]))
06369                         return false;
06370         }
06371         return true;
06372 }
06373 
06374 bool
06375 TeDatabase::updateVisual(TeLegendEntry *legend)
06376 {
06377         if (!legend)
06378                 return false;
06379 
06380         TeGeomRepVisualMap& mapVis = legend->getVisualMap();
06381         TeGeomRepVisualMap::iterator it =  mapVis.begin();
06382         while ( it != mapVis.end())
06383         { 
06384                         
06385                 TeGeomRep rep = it->first;
06386                 TeVisual* vis = it->second;
06387 
06388                 TeColor cor = vis->color();                             // filling color
06389                 TeColor contourCor = vis->contourColor();// contour color
06390 
06391                 string update = "UPDATE te_visual SET ";
06392                 update += "red = "+ Te2String(cor.red_) + ", ";
06393                 update += "green =" + Te2String(cor.green_) + ", ";
06394                 update += "blue =" + Te2String(cor.blue_) + ", ";
06395                 update += "transparency =" + Te2String(vis->transparency()) + ", ";
06396                 update += "contour_red=" + Te2String(contourCor.red_) + ", ";
06397                 update += "contour_green=" + Te2String(contourCor.green_) + ", ";
06398                 update += "contour_blue=" + Te2String(contourCor.blue_) + ", "; 
06399                 update += "contour_transp=" + Te2String(vis->contourTransparency()) + ", ";
06400                 update += "contour_width=" + Te2String(vis->contourWidth()) + ", ";
06401 
06402                 if(rep == TePOLYGONS)
06403                 {
06404                         update += "width=" + Te2String(vis->contourWidth()) + ", ";
06405                         update += "contour_symb_id=" + Te2String(vis->contourStyle()) + ", ";
06406                         update += "symb_id=" + Te2String(vis->style()) + ", ";
06407                 }
06408                 else if(rep == TeLINES)
06409                 {
06410                         update += "width=" + Te2String(vis->width()) + ", ";
06411                         update += "symb_id=" + Te2String(vis->style()) + ", ";
06412                 }
06413                 else if(rep == TePOINTS)
06414                 {
06415                         update += "size_value=" + Te2String(vis->size()) + ", ";
06416                         update += "symb_id=" + Te2String(vis->style ()) + ", ";
06417                 }
06418                 else if(rep == TeTEXT)
06419                 {
06420                         update += "size_value=" + Te2String(vis->size()) + ", ";
06421                         update += "pt_angle=" + Te2String(vis->ptAngle()) + ", ";
06422                 }
06423 
06424                 update += "family='" + vis->family() + "', ";
06425