OmniSciDB  a5dc49c757
 All Classes Namespaces Files Functions Variables Typedefs Enumerations Enumerator Friends Macros Groups Pages
Catalog_Namespace::Catalog Class Referencefinal

class for a per-database catalog. also includes metadata for the current database and the current user. More...

#include <Catalog.h>

+ Collaboration diagram for Catalog_Namespace::Catalog:

Classes

struct  NoTableFoundException
 

Public Member Functions

 Catalog (const std::string &basePath, const DBMetadata &curDB, std::shared_ptr< Data_Namespace::DataMgr > dataMgr, const std::vector< LeafHostInfo > &string_dict_hosts, std::shared_ptr< Calcite > calcite, bool is_new_db)
 Constructor - takes basePath to already extant data directory for writing. More...
 
 Catalog ()
 Constructor builds a hollow catalog used during constructor of other catalogs. More...
 
 ~Catalog ()
 Destructor - deletes all ColumnDescriptor and TableDescriptor structures which were allocated on the heap and writes Catalog to Sqlite. More...
 
void createTable (TableDescriptor &td, const std::list< ColumnDescriptor > &columns, const std::vector< Parser::SharedDictionaryDef > &shared_dict_defs, bool isLogicalTable)
 
void createShardedTable (TableDescriptor &td, const std::list< ColumnDescriptor > &columns, const std::vector< Parser::SharedDictionaryDef > &shared_dict_defs)
 
int32_t createDashboard (DashboardDescriptor &vd)
 
void replaceDashboard (DashboardDescriptor &vd)
 
std::string createLink (LinkDescriptor &ld, size_t min_length)
 
void dropTable (const TableDescriptor *td)
 
void truncateTable (const TableDescriptor *td)
 
void renameTable (const TableDescriptor *td, const std::string &newTableName)
 
void renameTables (const std::vector< std::pair< std::string, std::string >> &names)
 
void renameColumn (const TableDescriptor *td, const ColumnDescriptor *cd, const std::string &newColumnName)
 
int getNextAddedColumnId (const TableDescriptor &td)
 
void addColumn (const TableDescriptor &td, ColumnDescriptor &cd)
 
void addColumnTransactional (const TableDescriptor &td, ColumnDescriptor &cd)
 
void alterColumnTypeTransactional (const ColumnDescriptor &cd)
 
void dropColumnTransactional (const TableDescriptor &td, const ColumnDescriptor &cd)
 
void dropColumnNontransactional (const TableDescriptor &td, const ColumnDescriptor &cd)
 
void dropColumn (const TableDescriptor &td, const ColumnDescriptor &cd)
 
void dropColumnPolicies (const TableDescriptor &td, const ColumnDescriptor &cd)
 
void invalidateCachesForTable (const int table_id)
 
void removeFragmenterForTable (const int table_id) const
 
const std::map< int, const
ColumnDescriptor * > 
getDictionaryToColumnMapping ()
 
const TableDescriptorgetMetadataForTable (const std::string &tableName, const bool populateFragmenter=true) const
 Returns a pointer to a const TableDescriptor struct matching the provided tableName. More...
 
const TableDescriptorgetMetadataForTable (int tableId, bool populateFragmenter=true) const
 
std::optional< std::string > getTableName (int32_t table_id) const
 
std::optional< int32_t > getTableId (const std::string &table_name) const
 
const ColumnDescriptorgetMetadataForColumn (int tableId, const std::string &colName) const
 
const ColumnDescriptorgetMetadataForColumn (int tableId, int columnId) const
 
const std::optional< std::string > getColumnName (int table_id, int column_id) const
 
const int getColumnIdBySpi (const int tableId, const size_t spi) const
 
const ColumnDescriptorgetMetadataForColumnBySpi (const int tableId, const size_t spi) const
 
const DashboardDescriptorgetMetadataForDashboard (const std::string &userId, const std::string &dashName) const
 
const DashboardDescriptorgetMetadataForDashboard (const int32_t dashboard_id) const
 
void deleteMetadataForDashboards (const std::vector< int32_t > ids, const UserMetadata &user)
 
const LinkDescriptorgetMetadataForLink (const std::string &link) const
 
const LinkDescriptorgetMetadataForLink (int linkId) const
 
const
foreign_storage::ForeignTable
getForeignTable (const std::string &tableName) const
 
const
foreign_storage::ForeignTable
getForeignTable (int table_id) const
 
std::list< const
ColumnDescriptor * > 
getAllColumnMetadataForTable (const int tableId, const bool fetchSystemColumns, const bool fetchVirtualColumns, const bool fetchPhysicalColumns) const
 Returns a list of pointers to constant ColumnDescriptor structs for all the columns from a particular table specified by table id. More...
 
std::list< const
TableDescriptor * > 
getAllTableMetadata () const
 
std::vector< TableDescriptorgetAllTableMetadataCopy () const
 
std::list< const
DashboardDescriptor * > 
getAllDashboardsMetadata () const
 
std::vector< DashboardDescriptorgetAllDashboardsMetadataForSysTable () const
 
const DBMetadatagetCurrentDB () const
 
Data_Namespace::DataMgrgetDataMgr () const
 
std::shared_ptr< CalcitegetCalciteMgr () const
 
void setCalciteMgr (const std::shared_ptr< Calcite > &new_calcite_mgr)
 
const std::string & getCatalogBasePath () const
 
const DictDescriptorgetMetadataForDict (int dict_ref, bool loadDict=true) const
 
const std::vector< LeafHostInfo > & getStringDictionaryHosts () const
 
const ColumnDescriptorgetShardColumnMetadataForTable (const TableDescriptor *td) const
 
std::vector< const
TableDescriptor * > 
getPhysicalTablesDescriptors (const TableDescriptor *logical_table_desc, bool populate_fragmenter=true) const
 
std::vector< std::pair
< int32_t, int32_t > > 
getAllPersistedTableAndShardIds () const
 
std::vector< std::string > getTableNamesForUser (const UserMetadata &user, const GetTablesType get_tables_type) const
 
std::vector< TableMetadatagetTablesMetadataForUser (const UserMetadata &user_metadata, const GetTablesType get_tables_type, const std::string &filter_table_name) const
 
int32_t getTableEpoch (const int32_t db_id, const int32_t table_id) const
 
void setTableEpoch (const int db_id, const int table_id, const int new_epoch)
 
void setMaxRollbackEpochs (const int32_t table_id, const int32_t max_rollback_epochs)
 
void setMaxRows (const int32_t table_id, const int64_t max_rows)
 
std::vector< TableEpochInfogetTableEpochs (const int32_t db_id, const int32_t table_id) const
 
void setTableEpochs (const int32_t db_id, const std::vector< TableEpochInfo > &table_epochs) const
 
void setTableEpochsLogExceptions (const int32_t db_id, const std::vector< TableEpochInfo > &table_epochs) const
 
int getDatabaseId () const
 
SqliteConnectorgetSqliteConnector ()
 
void rollLegacy (const bool forward)
 
void getDictionary (const ColumnDescriptor &cd, std::map< int, StringDictionary * > &stringDicts)
 
size_t getTotalMemorySizeForDictionariesForDatabase () const
 
DictRef addDictionaryTransactional (ColumnDescriptor &cd)
 
void delDictionaryTransactional (const ColumnDescriptor &cd)
 
std::list< const DictDescriptor * > getAllDictionariesWithColumnInName (const ColumnDescriptor *cd)
 
const bool checkMetadataForDeletedRecs (const TableDescriptor *td, int column_id) const
 
const ColumnDescriptorgetDeletedColumn (const TableDescriptor *td) const
 
const ColumnDescriptorgetDeletedColumnIfRowsDeleted (const TableDescriptor *td) const
 
void setDeletedColumn (const TableDescriptor *td, const ColumnDescriptor *cd)
 
int getLogicalTableId (const int physicalTableId) const
 
void checkpoint (const int logicalTableId) const
 
void checkpointWithAutoRollback (const int logical_table_id) const
 
void resetTableEpochFloor (const int logicalTableId) const
 
std::string name () const
 
void eraseDbMetadata ()
 
void eraseDbPhysicalData ()
 
void eraseTablePhysicalData (const TableDescriptor *td)
 
void setForReload (const int32_t tableId)
 
std::vector< std::string > getTableDataDirectories (const TableDescriptor *td) const
 
std::vector< std::string > getTableDictDirectories (const TableDescriptor *td) const
 
std::set< std::string > getTableDictDirectoryPaths (int32_t table_id) const
 
std::string getColumnDictDirectory (const ColumnDescriptor *cd, bool file_name_only=true) const
 
std::string dumpSchema (const TableDescriptor *td) const
 
std::string dumpCreateTable (const TableDescriptor *td, bool multiline_formatting=true, bool dump_defaults=false) const
 
std::optional< std::string > dumpCreateTable (int32_t table_id, bool multiline_formatting=true, bool dump_defaults=false) const
 
std::string dumpCreateServer (const std::string &name, bool multiline_formatting=true) const
 
void createForeignServer (std::unique_ptr< foreign_storage::ForeignServer > foreign_server, bool if_not_exists)
 
const
foreign_storage::ForeignServer
getForeignServer (const std::string &server_name) const
 
const std::unique_ptr< const
foreign_storage::ForeignServer
getForeignServerFromStorage (const std::string &server_name)
 
const std::unique_ptr< const
foreign_storage::ForeignTable
getForeignTableFromStorage (int table_id)
 
void changeForeignServerOwner (const std::string &server_name, const int new_owner_id)
 
void setForeignServerDataWrapper (const std::string &server_name, const std::string &data_wrapper)
 
void setForeignServerOptions (const std::string &server_name, const std::string &options)
 
void renameForeignServer (const std::string &server_name, const std::string &name)
 
void dropForeignServer (const std::string &server_name)
 
std::vector< const
foreign_storage::ForeignTable * > 
getAllForeignTablesForForeignServer (const int32_t foreign_server_id)
 Get all of the foreign tables for associated with a foreign server id. More...
 
void getForeignServersForUser (const rapidjson::Value *filters, const UserMetadata &user, std::vector< const foreign_storage::ForeignServer * > &results)
 
void createDefaultServersIfNotExists ()
 
bool validateNonExistentTableOrView (const std::string &name, const bool if_not_exists)
 
std::vector< const
TableDescriptor * > 
getAllForeignTablesForRefresh () const
 
void updateForeignTableRefreshTimes (const int32_t table_id)
 
void setForeignTableOptions (const std::string &table_name, foreign_storage::OptionsMap &options_map, bool clear_existing_options=true)
 
void updateLeaf (const LeafHostInfo &string_dict_host)
 
void setUncappedTableEpoch (const std::string &table_name)
 
int32_t createCustomExpression (std::unique_ptr< CustomExpression > custom_expression)
 
const CustomExpressiongetCustomExpression (int32_t custom_expression_id) const
 
const std::unique_ptr< const
CustomExpression
getCustomExpressionFromStorage (int32_t custom_expression_id)
 
std::vector< const
CustomExpression * > 
getCustomExpressionsForUser (const UserMetadata &user) const
 
void updateCustomExpression (int32_t custom_expression_id, const std::string &expression_json)
 
void deleteCustomExpressions (const std::vector< int32_t > &custom_expression_ids, bool do_soft_delete)
 
void reassignOwners (const std::set< std::string > &old_owners, const std::string &new_owner)
 
bool isInfoSchemaDb () const
 
bool checkDropRenderGroupColumnsMigration ()
 

Static Public Member Functions

static void expandGeoColumn (const ColumnDescriptor &cd, std::list< ColumnDescriptor > &columns)
 
static const std::string getForeignTableSchema (bool if_not_exists=false)
 
static const std::string getForeignServerSchema (bool if_not_exists=false)
 
static const std::string getCustomExpressionsSchema (bool if_not_exists=false)
 

Public Attributes

std::unique_ptr
< heavyai::DistributedSharedMutex
dcatalogMutex_
 
std::unique_ptr
< heavyai::DistributedSharedMutex
dsqliteMutex_
 
std::mutex sqliteMutex_
 
heavyai::shared_mutex sharedMutex_
 
std::atomic< std::thread::id > thread_holding_sqlite_lock
 
std::atomic< std::thread::id > thread_holding_write_lock
 
bool initialized_ = false
 

Static Public Attributes

static thread_local bool thread_holds_read_lock = false
 

Protected Types

using ColumnDescriptorsForRoll = std::vector< std::pair< ColumnDescriptor *, ColumnDescriptor * >>
 

Protected Member Functions

void CheckAndExecuteMigrations ()
 
void CheckAndExecuteMigrationsPostBuildMaps ()
 
void updateDictionaryNames ()
 
void updateTableDescriptorSchema ()
 
void updateFixlenArrayColumns ()
 
void updateGeoColumns ()
 
void updateFrontendViewSchema ()
 
void updateLinkSchema ()
 
void updateFrontendViewAndLinkUsers ()
 
void updateLogicalToPhysicalTableLinkSchema ()
 
void updateLogicalToPhysicalTableMap (const int32_t logical_tb_id)
 
void updateDictionarySchema ()
 
void updatePageSize ()
 
void updateDeletedColumnIndicator ()
 
void updateDefaultColumnValues ()
 
void updateFrontendViewsToDashboards ()
 
void updateCustomExpressionsSchema ()
 
void updateFsiSchemas ()
 
void renameLegacyDataWrappers ()
 
void recordOwnershipOfObjectsInObjectPermissions ()
 
void checkDateInDaysColumnMigration ()
 
void createDashboardSystemRoles ()
 
void buildMaps ()
 
void addTableToMap (const TableDescriptor *td, const std::list< ColumnDescriptor > &columns, const std::list< DictDescriptor > &dicts)
 
void addReferenceToForeignDict (ColumnDescriptor &referencing_column, Parser::SharedDictionaryDef shared_dict_def, const bool persist_reference)
 
bool setColumnSharedDictionary (ColumnDescriptor &cd, std::list< ColumnDescriptor > &cdd, std::list< DictDescriptor > &dds, const TableDescriptor td, const std::vector< Parser::SharedDictionaryDef > &shared_dict_defs)
 
void setColumnDictionary (ColumnDescriptor &cd, std::list< DictDescriptor > &dds, const TableDescriptor &td, bool is_logical_table, bool use_temp_dictionary=false)
 
void addFrontendViewToMap (DashboardDescriptor &vd)
 
void addFrontendViewToMapNoLock (DashboardDescriptor &vd)
 
void addLinkToMap (LinkDescriptor &ld)
 
void removeTableFromMap (const std::string &tableName, const int tableId, const bool is_on_error=false)
 
void eraseTableMetadata (const TableDescriptor *td)
 
void executeDropTableSqliteQueries (const TableDescriptor *td)
 
void doTruncateTable (const TableDescriptor *td)
 
void renamePhysicalTable (const TableDescriptor *td, const std::string &newTableName)
 
void renamePhysicalTables (std::vector< std::pair< std::string, std::string >> &names, std::vector< int > &tableIds)
 
void instantiateFragmenter (TableDescriptor *td) const
 
void getAllColumnMetadataForTableImpl (const TableDescriptor *td, std::list< const ColumnDescriptor * > &colDescs, const bool fetchSystemColumns, const bool fetchVirtualColumns, const bool fetchPhysicalColumns) const
 
std::string calculateSHA1 (const std::string &data)
 
std::string generatePhysicalTableName (const std::string &logicalTableName, const size_t shardNumber)
 
std::vector< DBObjectparseDashboardObjects (const std::string &view_meta, const int &user_id)
 
void createOrUpdateDashboardSystemRole (const std::string &view_meta, const int32_t &user_id, const std::string &dash_role_name)
 
const int getColumnIdBySpiUnlocked (const int table_id, const size_t spi) const
 
void serializeTableJsonUnlocked (const TableDescriptor *td, const std::list< ColumnDescriptor > &cds) const
 
void dropTableFromJsonUnlocked (const std::string &table_name) const
 

Protected Attributes

std::string basePath_
 
TableDescriptorMap tableDescriptorMap_
 
TableDescriptorMapById tableDescriptorMapById_
 
ColumnDescriptorMap columnDescriptorMap_
 
ColumnDescriptorMapById columnDescriptorMapById_
 
DictDescriptorMapById dictDescriptorMapByRef_
 
DashboardDescriptorMap dashboardDescriptorMap_
 
LinkDescriptorMap linkDescriptorMap_
 
LinkDescriptorMapById linkDescriptorMapById_
 
ForeignServerMap foreignServerMap_
 
ForeignServerMapById foreignServerMapById_
 
CustomExpressionMapById custom_expr_map_by_id_
 
TableDictColumnsMap dict_columns_by_table_id_
 
SqliteConnector sqliteConnector_
 
const DBMetadata currentDB_
 
std::shared_ptr
< Data_Namespace::DataMgr
dataMgr_
 
const std::vector< LeafHostInfostring_dict_hosts_
 
std::shared_ptr< CalcitecalciteMgr_
 
LogicalToPhysicalTableMapById logicalToPhysicalTableMapById_
 
int nextTempTableId_
 
int nextTempDictId_
 
ColumnDescriptorsForRoll columnDescriptorsForRoll
 

Static Protected Attributes

static const std::string physicalTableNameTag_
 

Private Member Functions

void addColumnDescriptor (const ColumnDescriptor *cd)
 
void removeColumnDescriptor (const ColumnDescriptor *cd)
 
void delDictionaryNontransactional (const ColumnDescriptor &cd)
 
void addColumnNontransactional (const TableDescriptor &td, ColumnDescriptor &cd)
 
DictRef addDictionaryNontransactional (ColumnDescriptor &cd)
 
void buildDictionaryMapUnlocked ()
 
void reloadTableMetadata (int table_id)
 
void reloadTableMetadataUnlocked (int table_id)
 
TableDescriptorcreateTableFromDiskUnlocked (int32_t table_id)
 
void reloadDictionariesFromDiskUnlocked ()
 
std::list< ColumnDescriptor * > sqliteGetColumnsForTableUnlocked (int32_t table_id)
 
void reloadForeignTableUnlocked (foreign_storage::ForeignTable &foreign_table)
 
void reloadCatalogMetadata (const std::map< int32_t, std::string > &user_name_by_user_id)
 
void reloadCatalogMetadataUnlocked (const std::map< int32_t, std::string > &user_name_by_user_id)
 
void refreshDictionaryCachesForTableUnlocked (const TableDescriptor &td)
 
void buildTablesMapUnlocked ()
 
void buildColumnsMapUnlocked ()
 
void updateViewsInMapUnlocked ()
 
void updateViewUnlocked (TableDescriptor &)
 
void buildDashboardsMapUnlocked (const std::map< int32_t, std::string > &user_name_by_user_id)
 
void buildLinksMapUnlocked ()
 
void buildLogicalToPhysicalMapUnlocked ()
 
void updateForeignTablesInMapUnlocked ()
 
void gatherAdditionalInfo (std::vector< std::string > &additional_info, std::set< std::string > &shared_dict_column_names, const TableDescriptor *td) const
 
std::string quoteIfRequired (const std::string &column_name) const
 
void adjustAlteredTableFiles (const std::string &temp_data_dir, const std::unordered_map< int, int > &all_column_ids_map) const
 
void renameTableDirectories (const std::string &temp_data_dir, const std::vector< std::string > &target_paths, const std::string &name_prefix) const
 
void buildForeignServerMapUnlocked ()
 
void setForeignServerProperty (const std::string &server_name, const std::string &property, const std::string &value)
 
void setForeignTableProperty (const foreign_storage::ForeignTable *table, const std::string &property, const std::string &value)
 
void alterPhysicalTableMetadata (const TableDescriptor *td, const TableDescriptorUpdateParams &table_update_params)
 
void alterTableMetadata (const TableDescriptor *td, const TableDescriptorUpdateParams &table_update_params)
 
void setTableFileMgrParams (const int table_id, const File_Namespace::FileMgrParams &file_mgr_params)
 
bool filterTableByTypeAndUser (const TableDescriptor *td, const UserMetadata &user_metadata, const GetTablesType get_tables_type) const
 
TableDescriptorgetMutableMetadataForTableUnlocked (int table_id) const
 
TableDescriptorgetMutableMetadataForTableUnlocked (const std::string &table_name) const
 
void createForeignServerNoLocks (std::unique_ptr< foreign_storage::ForeignServer > foreign_server, bool if_not_exists)
 
foreign_storage::ForeignTablegetForeignTableUnlocked (const std::string &tableName) const
 
const CataloggetObjForLock ()
 
void removeChunks (const int table_id) const
 
void buildCustomExpressionsMapUnlocked ()
 
std::unique_ptr< CustomExpressiongetCustomExpressionFromConnector (size_t row)
 
void restoreOldOwners (const std::map< int32_t, std::string > &old_owners_user_name_by_id, const std::map< int32_t, std::vector< DBObject >> &old_owner_db_objects, int32_t new_owner_id)
 
void restoreOldOwnersInMemory (const std::map< int32_t, std::string > &old_owners_user_name_by_id, const std::map< int32_t, std::vector< DBObject >> &old_owner_db_objects, int32_t new_owner_id)
 
void conditionallyInitializeSystemObjects ()
 
void initializeSystemServers ()
 
void initializeSystemTables ()
 
void initializeUsersSystemTable ()
 
void initializeDatabasesSystemTable ()
 
void initializePermissionsSystemTable ()
 
void initializeRolesSystemTable ()
 
void initializeTablesSystemTable ()
 
void initializeDashboardsSystemTable ()
 
void initializeRoleAssignmentsSystemTable ()
 
void initializeMemorySummarySystemTable ()
 
void initializeMemoryDetailsSystemTable ()
 
void initializeStorageDetailsSystemTable ()
 
void initializeExecutorResourcePoolSummarySystemTable ()
 
void initializeMLModelMetadataSystemTable ()
 
void initializeServerLogsSystemTables ()
 
void initializeRequestLogsSystemTables ()
 
void initializeWebServerLogsSystemTables ()
 
void initializeWebServerAccessLogsSystemTables ()
 
void createSystemTableServer (const std::string &server_name, const std::string &data_wrapper_type, const foreign_storage::OptionsMap &options={})
 
std::pair
< foreign_storage::ForeignTable,
std::list< ColumnDescriptor > > 
getSystemTableSchema (const std::string &table_name, const std::string &server_name, const std::vector< std::pair< std::string, SQLTypeInfo >> &column_type_by_name, bool is_in_memory_system_table)
 
bool recreateSystemTableIfUpdated (foreign_storage::ForeignTable &foreign_table, const std::list< ColumnDescriptor > &columns)
 
void setDeletedColumnUnlocked (const TableDescriptor *td, const ColumnDescriptor *cd)
 
void updateInColumnMap (ColumnDescriptor *cd, ColumnDescriptor *old_cd)
 
void addToColumnMap (ColumnDescriptor *cd)
 
void removeFromColumnMap (ColumnDescriptor *cd)
 
void deleteTableCatalogMetadata (const TableDescriptor *logical_table, const std::vector< const TableDescriptor * > &physical_tables)
 
std::string dumpCreateTableUnlocked (const TableDescriptor *td, bool multiline_formatting, bool dump_defaults) const
 
void removeDiskCachedDataForMutableTable (int32_t table_id) const
 
template<typename F , typename... Args>
void execInTransaction (F &&f, Args &&...args)
 
const TableDescriptorgetCachedTableDescriptor (const std::map< std::string, int > &cached_table_map, const std::string &cur_table_name)
 

Private Attributes

DeletedColumnPerTableMap deletedColumnPerTable_
 

Static Private Attributes

static constexpr const char * CATALOG_SERVER_NAME {"system_catalog_server"}
 
static constexpr const char * MEMORY_STATS_SERVER_NAME {"system_memory_stats_server"}
 
static constexpr const char * STORAGE_STATS_SERVER_NAME {"system_storage_stats_server"}
 
static constexpr const char * EXECUTOR_STATS_SERVER_NAME {"system_executor_stats_server"}
 
static constexpr const char * ML_METADATA_SERVER_NAME {"ml_metadata_server"}
 
static constexpr const char * LOGS_SERVER_NAME {"system_logs_server"}
 
static constexpr std::array
< const char *, 6 > 
INTERNAL_SERVERS
 

Friends

template<class T >
class lockmgr::TableLockMgrImpl
 

Detailed Description

class for a per-database catalog. also includes metadata for the current database and the current user.

Catalog

Definition at line 143 of file Catalog.h.

Member Typedef Documentation

Definition at line 738 of file Catalog.h.

Constructor & Destructor Documentation

Catalog_Namespace::Catalog::Catalog ( const std::string &  basePath,
const DBMetadata curDB,
std::shared_ptr< Data_Namespace::DataMgr dataMgr,
const std::vector< LeafHostInfo > &  string_dict_hosts,
std::shared_ptr< Calcite calcite,
bool  is_new_db 
)

Constructor - takes basePath to already extant data directory for writing.

Parameters
basePathdirectory path for writing catalog
dbNamename of the database
fragmenterFragmenter object metadata - expects for this directory to already exist
Catalog_Namespace::Catalog::Catalog ( )

Constructor builds a hollow catalog used during constructor of other catalogs.

Definition at line 174 of file Catalog.cpp.

174 {}
Catalog_Namespace::Catalog::~Catalog ( )

Destructor - deletes all ColumnDescriptor and TableDescriptor structures which were allocated on the heap and writes Catalog to Sqlite.

Definition at line 234 of file Catalog.cpp.

References basePath_, columnDescriptorMap_, currentDB_, Catalog_Namespace::DBMetadata::dbName, g_serialize_temp_tables, Catalog_Namespace::anonymous_namespace{Catalog.cpp}::table_json_filepath(), and tableDescriptorMap_.

234  {
235  // cat_write_lock write_lock(this);
236 
237  // must clean up heap-allocated TableDescriptor and ColumnDescriptor structs
238  for (TableDescriptorMap::iterator tableDescIt = tableDescriptorMap_.begin();
239  tableDescIt != tableDescriptorMap_.end();
240  ++tableDescIt) {
241  tableDescIt->second->fragmenter = nullptr;
242  delete tableDescIt->second;
243  }
244 
245  // TableDescriptorMapById points to the same descriptors. No need to delete
246 
247  for (ColumnDescriptorMap::iterator columnDescIt = columnDescriptorMap_.begin();
248  columnDescIt != columnDescriptorMap_.end();
249  ++columnDescIt) {
250  delete columnDescIt->second;
251  }
252 
253  // ColumnDescriptorMapById points to the same descriptors. No need to delete
254 
256  boost::filesystem::remove(table_json_filepath(basePath_, currentDB_.dbName));
257  }
258 }
ColumnDescriptorMap columnDescriptorMap_
Definition: Catalog.h:709
const DBMetadata currentDB_
Definition: Catalog.h:721
auto table_json_filepath(const std::string &base_path, const std::string &db_name)
Definition: Catalog.cpp:165
bool g_serialize_temp_tables
Definition: Catalog.cpp:109
TableDescriptorMap tableDescriptorMap_
Definition: Catalog.h:707

+ Here is the call graph for this function:

Member Function Documentation

void Catalog_Namespace::Catalog::addColumn ( const TableDescriptor td,
ColumnDescriptor cd 
)

Definition at line 2538 of file Catalog.cpp.

References ColumnDescriptor::columnId, ColumnDescriptor::columnName, ColumnDescriptor::columnType, ColumnDescriptor::db_id, ColumnDescriptor::default_value, SQLTypeInfo::get_comp_param(), SQLTypeInfo::get_compression(), SQLTypeInfo::get_dimension(), SQLTypeInfo::get_notnull(), SQLTypeInfo::get_scale(), SQLTypeInfo::get_size(), SQLTypeInfo::get_subtype(), SQLTypeInfo::get_type(), ColumnDescriptor::isDeletedCol, ColumnDescriptor::isSystemCol, ColumnDescriptor::isVirtualCol, kENCODING_DICT, TableDescriptor::nShards, TableDescriptor::shard, ColumnDescriptor::tableId, TableDescriptor::tableId, to_string(), and ColumnDescriptor::virtualExpr.

2538  {
2539  // caller must handle sqlite/chunk transaction TOGETHER
2540  cd.tableId = td.tableId;
2541  cd.db_id = getDatabaseId();
2542  if (td.nShards > 0 && td.shard < 0) {
2543  for (const auto shard : getPhysicalTablesDescriptors(&td)) {
2544  auto shard_cd = cd;
2545  addColumn(*shard, shard_cd);
2546  }
2547  }
2550  }
2551 
2552  using BindType = SqliteConnector::BindType;
2553  std::vector<BindType> types(17, BindType::TEXT);
2554  if (!cd.default_value.has_value()) {
2555  types[16] = BindType::NULL_TYPE;
2556  }
2558  "INSERT INTO mapd_columns (tableid, columnid, name, coltype, colsubtype, coldim, "
2559  "colscale, is_notnull, "
2560  "compression, comp_param, size, chunks, is_systemcol, is_virtualcol, virtual_expr, "
2561  "is_deletedcol, default_value) "
2562  "VALUES (?, "
2563  "(SELECT max(columnid) + 1 FROM mapd_columns WHERE tableid = ?), "
2564  "?, ?, ?, "
2565  "?, "
2566  "?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)",
2567  std::vector<std::string>{std::to_string(td.tableId),
2568  std::to_string(td.tableId),
2569  cd.columnName,
2578  "",
2581  cd.virtualExpr,
2583  cd.default_value.value_or("NULL")},
2584  types);
2585 
2587  "UPDATE mapd_tables SET ncolumns = ncolumns + 1 WHERE tableid = ?",
2588  std::vector<std::string>{std::to_string(td.tableId)});
2589 
2591  "SELECT columnid FROM mapd_columns WHERE tableid = ? AND name = ?",
2592  std::vector<std::string>{std::to_string(td.tableId), cd.columnName});
2593  cd.columnId = sqliteConnector_.getData<int>(0, 0);
2594 
2595  ++tableDescriptorMapById_[td.tableId]->nColumns;
2596  auto ncd = new ColumnDescriptor(cd);
2597  addToColumnMap(ncd);
2598  columnDescriptorsForRoll.emplace_back(nullptr, ncd);
2599 }
std::string virtualExpr
HOST DEVICE SQLTypes get_subtype() const
Definition: sqltypes.h:392
DictRef addDictionaryNontransactional(ColumnDescriptor &cd)
Definition: Catalog.cpp:2252
HOST DEVICE int get_size() const
Definition: sqltypes.h:403
T getData(const int row, const int col)
virtual void query_with_text_params(std::string const &query_only)
void addColumn(const TableDescriptor &td, ColumnDescriptor &cd)
Definition: Catalog.cpp:2538
SqliteConnector sqliteConnector_
Definition: Catalog.h:720
HOST DEVICE int get_scale() const
Definition: sqltypes.h:396
HOST DEVICE SQLTypes get_type() const
Definition: sqltypes.h:391
std::string to_string(char const *&&v)
int getDatabaseId() const
Definition: Catalog.h:326
TableDescriptorMapById tableDescriptorMapById_
Definition: Catalog.h:708
specifies the content in-memory of a row in the column metadata table
std::vector< const TableDescriptor * > getPhysicalTablesDescriptors(const TableDescriptor *logical_table_desc, bool populate_fragmenter=true) const
Definition: Catalog.cpp:4879
std::optional< std::string > default_value
HOST DEVICE EncodingType get_compression() const
Definition: sqltypes.h:399
HOST DEVICE int get_dimension() const
Definition: sqltypes.h:393
HOST DEVICE int get_comp_param() const
Definition: sqltypes.h:402
SQLTypeInfo columnType
HOST DEVICE bool get_notnull() const
Definition: sqltypes.h:398
ColumnDescriptorsForRoll columnDescriptorsForRoll
Definition: Catalog.h:739
std::string columnName
void addToColumnMap(ColumnDescriptor *cd)
Definition: Catalog.cpp:7007

+ Here is the call graph for this function:

void Catalog_Namespace::Catalog::addColumnDescriptor ( const ColumnDescriptor cd)
private

Definition at line 2711 of file Catalog.cpp.

References CHECK, ColumnDescriptor::columnId, ColumnDescriptor::isGeoPhyCol, gpu_enabled::sort(), and ColumnDescriptor::tableId.

2711  {
2712  if (!cd || cd->isGeoPhyCol) {
2713  return;
2714  }
2715 
2716  auto tabDescIt = tableDescriptorMapById_.find(cd->tableId);
2717  CHECK(tableDescriptorMapById_.end() != tabDescIt);
2718  auto td = tabDescIt->second;
2719  auto& cd_by_spi = td->columnIdBySpi_;
2720 
2721  if (cd_by_spi.end() == std::find(cd_by_spi.begin(), cd_by_spi.end(), cd->columnId)) {
2722  cd_by_spi.push_back(cd->columnId);
2723  }
2724  std::sort(cd_by_spi.begin(), cd_by_spi.end());
2725 }
DEVICE void sort(ARGS &&...args)
Definition: gpu_enabled.h:105
TableDescriptorMapById tableDescriptorMapById_
Definition: Catalog.h:708
#define CHECK(condition)
Definition: Logger.h:291

+ Here is the call graph for this function:

void Catalog_Namespace::Catalog::addColumnNontransactional ( const TableDescriptor td,
ColumnDescriptor cd 
)
private

Definition at line 2472 of file Catalog.cpp.

References ColumnDescriptor::columnId, ColumnDescriptor::columnName, ColumnDescriptor::columnType, ColumnDescriptor::db_id, ColumnDescriptor::default_value, SQLTypeInfo::get_comp_param(), SQLTypeInfo::get_compression(), SQLTypeInfo::get_dimension(), SQLTypeInfo::get_notnull(), SQLTypeInfo::get_scale(), SQLTypeInfo::get_size(), SQLTypeInfo::get_subtype(), SQLTypeInfo::get_type(), ColumnDescriptor::isDeletedCol, ColumnDescriptor::isSystemCol, ColumnDescriptor::isVirtualCol, kENCODING_DICT, TableDescriptor::nShards, TableDescriptor::shard, ColumnDescriptor::tableId, TableDescriptor::tableId, TableDescriptor::tableName, to_string(), and ColumnDescriptor::virtualExpr.

2472  {
2473  cat_write_lock write_lock(this);
2474  cat_sqlite_lock sqlite_lock(this);
2475  cd.tableId = td.tableId;
2476  cd.db_id = getDatabaseId();
2477  if (td.nShards > 0 && td.shard < 0) {
2478  for (const auto shard : getPhysicalTablesDescriptors(&td)) {
2479  auto shard_cd = cd;
2480  addColumnNontransactional(*shard, shard_cd);
2481  }
2482  }
2485  }
2486 
2487  using BindType = SqliteConnector::BindType;
2488  std::vector<BindType> types(17, BindType::TEXT);
2489  if (!cd.default_value.has_value()) {
2490  types[16] = BindType::NULL_TYPE;
2491  }
2493  "INSERT INTO mapd_columns (tableid, columnid, name, coltype, colsubtype, coldim, "
2494  "colscale, is_notnull, "
2495  "compression, comp_param, size, chunks, is_systemcol, is_virtualcol, virtual_expr, "
2496  "is_deletedcol, default_value) "
2497  "VALUES (?, "
2498  "(SELECT max(columnid) + 1 FROM mapd_columns WHERE tableid = ?), "
2499  "?, ?, ?, "
2500  "?, "
2501  "?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)",
2502  std::vector<std::string>{std::to_string(td.tableId),
2503  std::to_string(td.tableId),
2504  cd.columnName,
2513  "",
2516  cd.virtualExpr,
2518  cd.default_value.value_or("NULL")},
2519  types);
2520 
2522  "UPDATE mapd_tables SET ncolumns = ncolumns + 1 WHERE tableid = ?",
2523  std::vector<std::string>{std::to_string(td.tableId)});
2524 
2526  "SELECT columnid FROM mapd_columns WHERE tableid = ? AND name = ?",
2527  std::vector<std::string>{std::to_string(td.tableId), cd.columnName});
2528  cd.columnId = sqliteConnector_.getData<int>(0, 0);
2529 
2530  ++tableDescriptorMapById_[td.tableId]->nColumns;
2531  auto ncd = new ColumnDescriptor(cd);
2532  addToColumnMap(ncd);
2533  addColumnDescriptor(ncd);
2534  calciteMgr_->updateMetadata(currentDB_.dbName, td.tableName);
2535 }
std::string virtualExpr
HOST DEVICE SQLTypes get_subtype() const
Definition: sqltypes.h:392
DictRef addDictionaryNontransactional(ColumnDescriptor &cd)
Definition: Catalog.cpp:2252
HOST DEVICE int get_size() const
Definition: sqltypes.h:403
T getData(const int row, const int col)
std::string tableName
virtual void query_with_text_params(std::string const &query_only)
void addColumnNontransactional(const TableDescriptor &td, ColumnDescriptor &cd)
Definition: Catalog.cpp:2472
SqliteConnector sqliteConnector_
Definition: Catalog.h:720
const DBMetadata currentDB_
Definition: Catalog.h:721
HOST DEVICE int get_scale() const
Definition: sqltypes.h:396
HOST DEVICE SQLTypes get_type() const
Definition: sqltypes.h:391
std::string to_string(char const *&&v)
int getDatabaseId() const
Definition: Catalog.h:326
TableDescriptorMapById tableDescriptorMapById_
Definition: Catalog.h:708
specifies the content in-memory of a row in the column metadata table
std::vector< const TableDescriptor * > getPhysicalTablesDescriptors(const TableDescriptor *logical_table_desc, bool populate_fragmenter=true) const
Definition: Catalog.cpp:4879
std::optional< std::string > default_value
std::shared_ptr< Calcite > calciteMgr_
Definition: Catalog.h:725
HOST DEVICE EncodingType get_compression() const
Definition: sqltypes.h:399
HOST DEVICE int get_dimension() const
Definition: sqltypes.h:393
write_lock< Catalog > cat_write_lock
Definition: Catalog.cpp:125
HOST DEVICE int get_comp_param() const
Definition: sqltypes.h:402
void addColumnDescriptor(const ColumnDescriptor *cd)
Definition: Catalog.cpp:2711
SQLTypeInfo columnType
HOST DEVICE bool get_notnull() const
Definition: sqltypes.h:398
sqlite_lock< Catalog > cat_sqlite_lock
Definition: Catalog.cpp:126
std::string columnName
void addToColumnMap(ColumnDescriptor *cd)
Definition: Catalog.cpp:7007

+ Here is the call graph for this function:

void Catalog_Namespace::Catalog::addColumnTransactional ( const TableDescriptor td,
ColumnDescriptor cd 
)

Definition at line 2459 of file Catalog.cpp.

2459  {
2460  cat_write_lock write_lock(this);
2461  cat_sqlite_lock sqlite_lock(this);
2462  sqliteConnector_.query("BEGIN TRANSACTION");
2463  try {
2464  addColumnNontransactional(td, cd);
2465  } catch (std::exception& e) {
2466  sqliteConnector_.query("ROLLBACK TRANSACTION");
2467  throw;
2468  }
2469  sqliteConnector_.query("END TRANSACTION");
2470 }
void addColumnNontransactional(const TableDescriptor &td, ColumnDescriptor &cd)
Definition: Catalog.cpp:2472
SqliteConnector sqliteConnector_
Definition: Catalog.h:720
virtual void query(const std::string &queryString)
write_lock< Catalog > cat_write_lock
Definition: Catalog.cpp:125
sqlite_lock< Catalog > cat_sqlite_lock
Definition: Catalog.cpp:126
DictRef Catalog_Namespace::Catalog::addDictionaryNontransactional ( ColumnDescriptor cd)
private

Definition at line 2252 of file Catalog.cpp.

References CHECK, DictDescriptor::dictFolderPath, and ColumnDescriptor::tableId.

2252  {
2253  cat_write_lock write_lock(this);
2254  const auto& td = *tableDescriptorMapById_[cd.tableId];
2255  list<DictDescriptor> dds;
2256  setColumnDictionary(cd, dds, td, true);
2257  auto& dd = dds.back();
2258  CHECK(dd.dictRef.dictId);
2259 
2260  std::unique_ptr<StringDictionaryClient> client;
2261  if (!string_dict_hosts_.empty()) {
2262  client.reset(new StringDictionaryClient(
2263  string_dict_hosts_.front(), DictRef(currentDB_.dbId, -1), true));
2264  }
2265  if (client) {
2266  client->create(dd.dictRef, dd.dictIsTemp);
2267  }
2268 
2269  DictDescriptor* new_dd = new DictDescriptor(dd);
2270  dictDescriptorMapByRef_[dd.dictRef].reset(new_dd);
2271  if (!dd.dictIsTemp) {
2272  boost::filesystem::create_directory(new_dd->dictFolderPath);
2273  }
2274  return dd.dictRef;
2275 }
std::string dictFolderPath
const std::vector< LeafHostInfo > string_dict_hosts_
Definition: Catalog.h:724
const DBMetadata currentDB_
Definition: Catalog.h:721
DictDescriptorMapById dictDescriptorMapByRef_
Definition: Catalog.h:711
void setColumnDictionary(ColumnDescriptor &cd, std::list< DictDescriptor > &dds, const TableDescriptor &td, bool is_logical_table, bool use_temp_dictionary=false)
Definition: Catalog.cpp:4066
TableDescriptorMapById tableDescriptorMapById_
Definition: Catalog.h:708
struct dict_ref_t DictRef
Definition: DictRef.h:54
write_lock< Catalog > cat_write_lock
Definition: Catalog.cpp:125
#define CHECK(condition)
Definition: Logger.h:291
Descriptor for a dictionary for a string columne.
DictRef Catalog_Namespace::Catalog::addDictionaryTransactional ( ColumnDescriptor cd)

Definition at line 2237 of file Catalog.cpp.

2237  {
2238  cat_write_lock write_lock(this);
2239  cat_sqlite_lock sqlite_lock(this);
2240  DictRef ref{};
2241  sqliteConnector_.query("BEGIN TRANSACTION");
2242  try {
2244  } catch (std::exception& e) {
2245  sqliteConnector_.query("ROLLBACK TRANSACTION");
2246  throw;
2247  }
2248  sqliteConnector_.query("END TRANSACTION");
2249  return ref;
2250 }
DictRef addDictionaryNontransactional(ColumnDescriptor &cd)
Definition: Catalog.cpp:2252
SqliteConnector sqliteConnector_
Definition: Catalog.h:720
virtual void query(const std::string &queryString)
write_lock< Catalog > cat_write_lock
Definition: Catalog.cpp:125
sqlite_lock< Catalog > cat_sqlite_lock
Definition: Catalog.cpp:126
void Catalog_Namespace::Catalog::addFrontendViewToMap ( DashboardDescriptor vd)
protected

Definition at line 1686 of file Catalog.cpp.

1686  {
1687  cat_write_lock write_lock(this);
1689 }
void addFrontendViewToMapNoLock(DashboardDescriptor &vd)
Definition: Catalog.cpp:1691
write_lock< Catalog > cat_write_lock
Definition: Catalog.cpp:125
void Catalog_Namespace::Catalog::addFrontendViewToMapNoLock ( DashboardDescriptor vd)
protected

Definition at line 1691 of file Catalog.cpp.

References DashboardDescriptor::dashboardName, to_string(), and DashboardDescriptor::userId.

1691  {
1692  cat_write_lock write_lock(this);
1694  std::make_shared<DashboardDescriptor>(vd);
1695 }
DashboardDescriptorMap dashboardDescriptorMap_
Definition: Catalog.h:712
std::string to_string(char const *&&v)
write_lock< Catalog > cat_write_lock
Definition: Catalog.cpp:125

+ Here is the call graph for this function:

void Catalog_Namespace::Catalog::addLinkToMap ( LinkDescriptor ld)
protected

Definition at line 1773 of file Catalog.cpp.

References LinkDescriptor::link, LinkDescriptor::linkId, and to_string().

1773  {
1774  cat_write_lock write_lock(this);
1775  LinkDescriptor* new_ld = new LinkDescriptor();
1776  *new_ld = ld;
1778  linkDescriptorMapById_[ld.linkId] = new_ld;
1779 }
const DBMetadata currentDB_
Definition: Catalog.h:721
std::string to_string(char const *&&v)
write_lock< Catalog > cat_write_lock
Definition: Catalog.cpp:125
LinkDescriptorMapById linkDescriptorMapById_
Definition: Catalog.h:714
LinkDescriptorMap linkDescriptorMap_
Definition: Catalog.h:713

+ Here is the call graph for this function:

void Catalog_Namespace::Catalog::addReferenceToForeignDict ( ColumnDescriptor referencing_column,
Parser::SharedDictionaryDef  shared_dict_def,
const bool  persist_reference 
)
protected

Definition at line 3975 of file Catalog.cpp.

References CHECK, CHECK_GE, ColumnDescriptor::columnType, SQLTypeInfo::get_comp_param(), Catalog_Namespace::anonymous_namespace{Catalog.cpp}::get_foreign_col(), and to_string().

3977  {
3978  cat_write_lock write_lock(this);
3979  const auto foreign_ref_col = get_foreign_col(*this, shared_dict_def);
3980  CHECK(foreign_ref_col);
3981  referencing_column.columnType = foreign_ref_col->columnType;
3982  const int dict_id = referencing_column.columnType.get_comp_param();
3983  const DictRef dict_ref(currentDB_.dbId, dict_id);
3984  const auto dictIt = dictDescriptorMapByRef_.find(dict_ref);
3985  CHECK(dictIt != dictDescriptorMapByRef_.end());
3986  const auto& dd = dictIt->second;
3987  CHECK_GE(dd->refcount, 1);
3988  ++dd->refcount;
3989  if (persist_reference) {
3990  cat_sqlite_lock sqlite_lock(getObjForLock());
3992  "UPDATE mapd_dictionaries SET refcount = refcount + 1 WHERE dictid = ?",
3993  {std::to_string(dict_id)});
3994  }
3995 }
virtual void query_with_text_params(std::string const &query_only)
SqliteConnector sqliteConnector_
Definition: Catalog.h:720
const DBMetadata currentDB_
Definition: Catalog.h:721
DictDescriptorMapById dictDescriptorMapByRef_
Definition: Catalog.h:711
#define CHECK_GE(x, y)
Definition: Logger.h:306
const ColumnDescriptor * get_foreign_col(const Catalog &cat, const Parser::SharedDictionaryDef &shared_dict_def)
Definition: Catalog.cpp:3963
std::string to_string(char const *&&v)
const Catalog * getObjForLock()
Definition: Catalog.cpp:260
write_lock< Catalog > cat_write_lock
Definition: Catalog.cpp:125
HOST DEVICE int get_comp_param() const
Definition: sqltypes.h:402
#define CHECK(condition)
Definition: Logger.h:291
SQLTypeInfo columnType
sqlite_lock< Catalog > cat_sqlite_lock
Definition: Catalog.cpp:126

+ Here is the call graph for this function:

void Catalog_Namespace::Catalog::addTableToMap ( const TableDescriptor td,
const std::list< ColumnDescriptor > &  columns,
const std::list< DictDescriptor > &  dicts 
)
protected

Definition at line 1545 of file Catalog.cpp.

References anonymous_namespace{Utm.h}::a, CHECK, TableDescriptor::columnIdBySpi_, DictDescriptor::dictFolderPath, dict_ref_t::dictId, TableDescriptor::hasDeletedCol, TableDescriptor::mutex_, gpu_enabled::sort(), TableDescriptor::tableId, TableDescriptor::tableName, and to_upper().

1547  {
1548  cat_write_lock write_lock(this);
1549  TableDescriptor* new_td;
1550 
1551  auto foreign_table = dynamic_cast<const foreign_storage::ForeignTable*>(td);
1552  if (foreign_table) {
1553  auto new_foreign_table = new foreign_storage::ForeignTable();
1554  *new_foreign_table = *foreign_table;
1555  new_td = new_foreign_table;
1556  } else {
1557  new_td = new TableDescriptor();
1558  *new_td = *td;
1559  }
1560 
1561  new_td->mutex_ = std::make_shared<std::mutex>();
1562  tableDescriptorMap_[to_upper(td->tableName)] = new_td;
1563  tableDescriptorMapById_[td->tableId] = new_td;
1564  for (auto cd : columns) {
1565  ColumnDescriptor* new_cd = new ColumnDescriptor();
1566  *new_cd = cd;
1567  addToColumnMap(new_cd);
1568 
1569  // Add deleted column to the map
1570  if (cd.isDeletedCol) {
1571  CHECK(new_td->hasDeletedCol);
1572  setDeletedColumnUnlocked(new_td, new_cd);
1573  }
1574  }
1575 
1576  std::sort(new_td->columnIdBySpi_.begin(),
1577  new_td->columnIdBySpi_.end(),
1578  [](const size_t a, const size_t b) -> bool { return a < b; });
1579  // TODO(sy): Why does addTableToMap() sort columnIdBySpi_ but not insert into it while
1580  // buildColumnsMapUnlocked() does both?
1581 
1582  std::unique_ptr<StringDictionaryClient> client;
1583  DictRef dict_ref(currentDB_.dbId, -1);
1584  if (!string_dict_hosts_.empty()) {
1585  client.reset(new StringDictionaryClient(string_dict_hosts_.front(), dict_ref, true));
1586  }
1587  for (auto dd : dicts) {
1588  if (!dd.dictRef.dictId) {
1589  // Dummy entry created for a shard of a logical table, nothing to do.
1590  continue;
1591  }
1592  dict_ref.dictId = dd.dictRef.dictId;
1593  if (client) {
1594  client->create(dict_ref, dd.dictIsTemp);
1595  }
1596  DictDescriptor* new_dd = new DictDescriptor(dd);
1597  dictDescriptorMapByRef_[dict_ref].reset(new_dd);
1598  if (!dd.dictIsTemp) {
1599  boost::filesystem::create_directory(new_dd->dictFolderPath);
1600  }
1601  }
1602 }
std::string dictFolderPath
std::string tableName
const std::vector< LeafHostInfo > string_dict_hosts_
Definition: Catalog.h:724
const DBMetadata currentDB_
Definition: Catalog.h:721
DictDescriptorMapById dictDescriptorMapByRef_
Definition: Catalog.h:711
DEVICE void sort(ARGS &&...args)
Definition: gpu_enabled.h:105
std::vector< int > columnIdBySpi_
std::shared_ptr< std::mutex > mutex_
constexpr double a
Definition: Utm.h:32
void setDeletedColumnUnlocked(const TableDescriptor *td, const ColumnDescriptor *cd)
Definition: Catalog.cpp:3955
TableDescriptorMapById tableDescriptorMapById_
Definition: Catalog.h:708
specifies the content in-memory of a row in the column metadata table
std::string to_upper(const std::string &str)
write_lock< Catalog > cat_write_lock
Definition: Catalog.cpp:125
#define CHECK(condition)
Definition: Logger.h:291
Descriptor for a dictionary for a string columne.
void addToColumnMap(ColumnDescriptor *cd)
Definition: Catalog.cpp:7007
TableDescriptorMap tableDescriptorMap_
Definition: Catalog.h:707

+ Here is the call graph for this function:

void Catalog_Namespace::Catalog::addToColumnMap ( ColumnDescriptor cd)
private

Definition at line 7007 of file Catalog.cpp.

References ColumnDescriptor::columnId, ColumnDescriptor::columnName, ColumnDescriptor::columnType, SQLTypeInfo::is_dict_encoded_type(), ColumnDescriptor::tableId, and to_upper().

7007  {
7010  if (cd->columnType.is_dict_encoded_type()) {
7011  dict_columns_by_table_id_[cd->tableId].emplace(cd);
7012  }
7013 }
TableDictColumnsMap dict_columns_by_table_id_
Definition: Catalog.h:718
std::tuple< int, std::string > ColumnKey
Definition: Types.h:37
ColumnDescriptorMap columnDescriptorMap_
Definition: Catalog.h:709
ColumnDescriptorMapById columnDescriptorMapById_
Definition: Catalog.h:710
bool is_dict_encoded_type() const
Definition: sqltypes.h:655
std::string to_upper(const std::string &str)
SQLTypeInfo columnType
std::string columnName
std::tuple< int, int > ColumnIdKey
Definition: Types.h:39

+ Here is the call graph for this function:

void Catalog_Namespace::Catalog::adjustAlteredTableFiles ( const std::string &  temp_data_dir,
const std::unordered_map< int, int > &  all_column_ids_map 
) const
private
void Catalog_Namespace::Catalog::alterColumnTypeTransactional ( const ColumnDescriptor cd)

Definition at line 2393 of file Catalog.cpp.

References CHECK, ColumnDescriptor::columnId, ColumnDescriptor::columnName, ColumnDescriptor::columnType, ColumnDescriptor::default_value, SQLTypeInfo::get_comp_param(), SQLTypeInfo::get_compression(), SQLTypeInfo::get_dimension(), SQLTypeInfo::get_notnull(), SQLTypeInfo::get_scale(), SQLTypeInfo::get_size(), SQLTypeInfo::get_subtype(), SQLTypeInfo::get_type(), ColumnDescriptor::tableId, to_string(), and to_upper().

Referenced by AlterTableAlterColumnCommandRecoveryMgr::rollback().

2393  {
2394  cat_write_lock write_lock(this);
2395  cat_sqlite_lock sqlite_lock(this);
2396 
2397  sqliteConnector_.query("BEGIN TRANSACTION");
2398  try {
2399  const auto table_id = cd.tableId;
2400 
2401  auto catalog_cd = getMetadataForColumn(table_id, cd.columnId);
2402 
2403  CHECK(catalog_cd) << " can not alter non existing column";
2404 
2405  using BindType = SqliteConnector::BindType;
2406  std::vector<BindType> types(11, BindType::TEXT);
2407  if (!cd.default_value.has_value()) {
2408  types[8] = BindType::NULL_TYPE;
2409  }
2411  "UPDATE mapd_columns SET "
2412  "coltype = ?,"
2413  "colsubtype = ?,"
2414  "coldim = ?,"
2415  "colscale = ?,"
2416  "is_notnull = ?,"
2417  "compression = ?,"
2418  "comp_param = ?,"
2419  "size = ?,"
2420  "default_value = ? "
2421  "WHERE tableid = ? and columnid = ?",
2422  std::vector<std::string>{std::to_string(cd.columnType.get_type()),
2430  cd.default_value.value_or("NULL"),
2431  std::to_string(table_id),
2432  std::to_string(cd.columnId)},
2433 
2434  types);
2435 
2436  auto ncd = new ColumnDescriptor(cd);
2437 
2438  ColumnDescriptorMap::iterator columnDescIt =
2440  CHECK(columnDescIt != columnDescriptorMap_.end());
2441  auto ocd = columnDescIt->second;
2442 
2443  updateInColumnMap(ncd, ocd);
2444  } catch (std::exception& e) {
2445  sqliteConnector_.query("ROLLBACK TRANSACTION");
2446  throw;
2447  }
2448  sqliteConnector_.query("END TRANSACTION");
2449 }
HOST DEVICE SQLTypes get_subtype() const
Definition: sqltypes.h:392
std::tuple< int, std::string > ColumnKey
Definition: Types.h:37
HOST DEVICE int get_size() const
Definition: sqltypes.h:403
ColumnDescriptorMap columnDescriptorMap_
Definition: Catalog.h:709
virtual void query_with_text_params(std::string const &query_only)
SqliteConnector sqliteConnector_
Definition: Catalog.h:720
HOST DEVICE int get_scale() const
Definition: sqltypes.h:396
virtual void query(const std::string &queryString)
HOST DEVICE SQLTypes get_type() const
Definition: sqltypes.h:391
std::string to_string(char const *&&v)
const ColumnDescriptor * getMetadataForColumn(int tableId, const std::string &colName) const
specifies the content in-memory of a row in the column metadata table
void updateInColumnMap(ColumnDescriptor *cd, ColumnDescriptor *old_cd)
Definition: Catalog.cpp:6983
std::string to_upper(const std::string &str)
std::optional< std::string > default_value
HOST DEVICE EncodingType get_compression() const
Definition: sqltypes.h:399
HOST DEVICE int get_dimension() const
Definition: sqltypes.h:393
write_lock< Catalog > cat_write_lock
Definition: Catalog.cpp:125
HOST DEVICE int get_comp_param() const
Definition: sqltypes.h:402
#define CHECK(condition)
Definition: Logger.h:291
SQLTypeInfo columnType
HOST DEVICE bool get_notnull() const
Definition: sqltypes.h:398
sqlite_lock< Catalog > cat_sqlite_lock
Definition: Catalog.cpp:126
std::string columnName

+ Here is the call graph for this function:

+ Here is the caller graph for this function:

void Catalog_Namespace::Catalog::alterPhysicalTableMetadata ( const TableDescriptor td,
const TableDescriptorUpdateParams table_update_params 
)
private

Definition at line 3690 of file Catalog.cpp.

References CHECK, TableDescriptorUpdateParams::max_rollback_epochs, TableDescriptorUpdateParams::max_rows, TableDescriptor::maxRollbackEpochs, TableDescriptor::maxRows, TableDescriptor::tableId, and to_string().

3692  {
3693  // Only called from parent alterTableParamMetadata, expect already to have catalog and
3694  // sqlite write locks
3695 
3696  // Sqlite transaction should have already been begun in parent alterTableCatalogMetadata
3697 
3699  CHECK(mutable_td);
3700  if (td->maxRollbackEpochs != table_update_params.max_rollback_epochs) {
3702  "UPDATE mapd_tables SET max_rollback_epochs = ? WHERE tableid = ?",
3703  std::vector<std::string>{std::to_string(table_update_params.max_rollback_epochs),
3704  std::to_string(td->tableId)});
3705  mutable_td->maxRollbackEpochs = table_update_params.max_rollback_epochs;
3706  }
3707 
3708  if (td->maxRows != table_update_params.max_rows) {
3710  "UPDATE mapd_tables SET max_rows = ? WHERE tableid = ?",
3711  std::vector<std::string>{std::to_string(table_update_params.max_rows),
3712  std::to_string(td->tableId)});
3713  mutable_td->maxRows = table_update_params.max_rows;
3714  }
3715 }
int32_t maxRollbackEpochs
virtual void query_with_text_params(std::string const &query_only)
SqliteConnector sqliteConnector_
Definition: Catalog.h:720
TableDescriptor * getMutableMetadataForTableUnlocked(int table_id) const
Definition: Catalog.cpp:1899
std::string to_string(char const *&&v)
#define CHECK(condition)
Definition: Logger.h:291

+ Here is the call graph for this function:

void Catalog_Namespace::Catalog::alterTableMetadata ( const TableDescriptor td,
const TableDescriptorUpdateParams table_update_params 
)
private

Definition at line 3717 of file Catalog.cpp.

References CHECK, logger::FATAL, LOG, TableDescriptor::tableId, and TableDescriptor::tableName.

3718  {
3719  cat_write_lock write_lock(this);
3720  cat_sqlite_lock sqlite_lock(getObjForLock());
3721  sqliteConnector_.query("BEGIN TRANSACTION");
3722  try {
3723  const auto physical_table_it = logicalToPhysicalTableMapById_.find(td->tableId);
3724  if (physical_table_it != logicalToPhysicalTableMapById_.end()) {
3725  const auto physical_tables = physical_table_it->second;
3726  CHECK(!physical_tables.empty());
3727  for (size_t i = 0; i < physical_tables.size(); i++) {
3728  int32_t physical_tb_id = physical_tables[i];
3729  const TableDescriptor* phys_td = getMetadataForTable(physical_tb_id, false);
3730  CHECK(phys_td);
3731  alterPhysicalTableMetadata(phys_td, table_update_params);
3732  }
3733  }
3734  alterPhysicalTableMetadata(td, table_update_params);
3735  } catch (std::exception& e) {
3736  sqliteConnector_.query("ROLLBACK TRANSACTION");
3737  LOG(FATAL) << "Table '" << td->tableName << "' catalog update failed";
3738  }
3739  sqliteConnector_.query("END TRANSACTION");
3740 }
std::string tableName
#define LOG(tag)
Definition: Logger.h:285
SqliteConnector sqliteConnector_
Definition: Catalog.h:720
virtual void query(const std::string &queryString)
void alterPhysicalTableMetadata(const TableDescriptor *td, const TableDescriptorUpdateParams &table_update_params)
Definition: Catalog.cpp:3690
const Catalog * getObjForLock()
Definition: Catalog.cpp:260
write_lock< Catalog > cat_write_lock
Definition: Catalog.cpp:125
#define CHECK(condition)
Definition: Logger.h:291
const TableDescriptor * getMetadataForTable(const std::string &tableName, const bool populateFragmenter=true) const
Returns a pointer to a const TableDescriptor struct matching the provided tableName.
sqlite_lock< Catalog > cat_sqlite_lock
Definition: Catalog.cpp:126
LogicalToPhysicalTableMapById logicalToPhysicalTableMapById_
Definition: Catalog.h:727
void Catalog_Namespace::Catalog::buildColumnsMapUnlocked ( )
private

Definition at line 1336 of file Catalog.cpp.

References anonymous_namespace{Utm.h}::a, CHECK, ColumnDescriptor::chunks, ColumnDescriptor::columnId, ColumnDescriptor::columnName, ColumnDescriptor::columnType, ColumnDescriptor::db_id, ColumnDescriptor::default_value, SQLTypeInfo::get_physical_cols(), SQLTypeInfo::is_geometry(), ColumnDescriptor::isDeletedCol, ColumnDescriptor::isGeoPhyCol, ColumnDescriptor::isSystemCol, ColumnDescriptor::isVirtualCol, SQLTypeInfo::set_comp_param(), SQLTypeInfo::set_compression(), Catalog_Namespace::anonymous_namespace{Catalog.cpp}::set_dict_key(), SQLTypeInfo::set_dimension(), SQLTypeInfo::set_notnull(), SQLTypeInfo::set_scale(), SQLTypeInfo::set_size(), SQLTypeInfo::set_subtype(), SQLTypeInfo::set_type(), gpu_enabled::sort(), ColumnDescriptor::tableId, and ColumnDescriptor::virtualExpr.

1336  {
1337  std::string columnQuery(
1338  "SELECT tableid, columnid, name, coltype, colsubtype, coldim, colscale, "
1339  "is_notnull, compression, comp_param, "
1340  "size, chunks, is_systemcol, is_virtualcol, virtual_expr, is_deletedcol, "
1341  "default_value from "
1342  "mapd_columns ORDER BY tableid, "
1343  "columnid");
1344  sqliteConnector_.query(columnQuery);
1345  auto numRows = sqliteConnector_.getNumRows();
1346  int32_t skip_physical_cols = 0;
1347  for (size_t r = 0; r < numRows; ++r) {
1348  ColumnDescriptor* cd = new ColumnDescriptor();
1349  cd->tableId = sqliteConnector_.getData<int>(r, 0);
1350  cd->columnId = sqliteConnector_.getData<int>(r, 1);
1351  cd->columnName = sqliteConnector_.getData<string>(r, 2);
1355  cd->columnType.set_scale(sqliteConnector_.getData<int>(r, 6));
1359  cd->columnType.set_size(sqliteConnector_.getData<int>(r, 10));
1360  cd->chunks = sqliteConnector_.getData<string>(r, 11);
1361  cd->isSystemCol = sqliteConnector_.getData<bool>(r, 12);
1362  cd->isVirtualCol = sqliteConnector_.getData<bool>(r, 13);
1363  cd->virtualExpr = sqliteConnector_.getData<string>(r, 14);
1364  cd->isDeletedCol = sqliteConnector_.getData<bool>(r, 15);
1365  if (sqliteConnector_.isNull(r, 16)) {
1366  cd->default_value = std::nullopt;
1367  } else {
1368  cd->default_value = std::make_optional(sqliteConnector_.getData<string>(r, 16));
1369  }
1370  cd->isGeoPhyCol = skip_physical_cols > 0;
1371  cd->db_id = getDatabaseId();
1372  set_dict_key(*cd);
1373  addToColumnMap(cd);
1374 
1375  if (skip_physical_cols <= 0) {
1376  skip_physical_cols = cd->columnType.get_physical_cols();
1377  }
1378 
1379  auto td_itr = tableDescriptorMapById_.find(cd->tableId);
1380  CHECK(td_itr != tableDescriptorMapById_.end());
1381 
1382  if (cd->isDeletedCol) {
1383  td_itr->second->hasDeletedCol = true;
1384  setDeletedColumnUnlocked(td_itr->second, cd);
1385  } else if (cd->columnType.is_geometry() || skip_physical_cols-- <= 0) {
1386  tableDescriptorMapById_[cd->tableId]->columnIdBySpi_.push_back(cd->columnId);
1387  }
1388  }
1389 
1390  // sort columnIdBySpi_ based on columnId
1391  for (auto& tit : tableDescriptorMapById_) {
1392  std::sort(tit.second->columnIdBySpi_.begin(),
1393  tit.second->columnIdBySpi_.end(),
1394  [](const size_t a, const size_t b) -> bool { return a < b; });
1395  }
1396 }
std::string virtualExpr
void set_compression(EncodingType c)
Definition: sqltypes.h:481
void set_size(int s)
Definition: sqltypes.h:478
T getData(const int row, const int col)
SQLTypes
Definition: sqltypes.h:65
SqliteConnector sqliteConnector_
Definition: Catalog.h:720
HOST DEVICE void set_subtype(SQLTypes st)
Definition: sqltypes.h:471
DEVICE void sort(ARGS &&...args)
Definition: gpu_enabled.h:105
virtual void query(const std::string &queryString)
std::string chunks
constexpr double a
Definition: Utm.h:32
EncodingType
Definition: sqltypes.h:240
int get_physical_cols() const
Definition: sqltypes.h:432
void set_scale(int s)
Definition: sqltypes.h:475
void setDeletedColumnUnlocked(const TableDescriptor *td, const ColumnDescriptor *cd)
Definition: Catalog.cpp:3955
int getDatabaseId() const
Definition: Catalog.h:326
TableDescriptorMapById tableDescriptorMapById_
Definition: Catalog.h:708
specifies the content in-memory of a row in the column metadata table
void set_comp_param(int p)
Definition: sqltypes.h:482
std::optional< std::string > default_value
bool isNull(const int row, const int col) const
void set_dimension(int d)
Definition: sqltypes.h:472
void set_notnull(bool n)
Definition: sqltypes.h:477
#define CHECK(condition)
Definition: Logger.h:291
bool is_geometry() const
Definition: sqltypes.h:597
SQLTypeInfo columnType
std::string columnName
void addToColumnMap(ColumnDescriptor *cd)
Definition: Catalog.cpp:7007
virtual size_t getNumRows() const
HOST DEVICE void set_type(SQLTypes t)
Definition: sqltypes.h:470

+ Here is the call graph for this function:

void Catalog_Namespace::Catalog::buildCustomExpressionsMapUnlocked ( )
private

Definition at line 1517 of file Catalog.cpp.

1517  {
1519  "SELECT id, name, expression_json, data_source_type, data_source_id, "
1520  "is_deleted "
1521  "FROM omnisci_custom_expressions");
1522  auto num_rows = sqliteConnector_.getNumRows();
1523  for (size_t row = 0; row < num_rows; row++) {
1524  auto custom_expr = getCustomExpressionFromConnector(row);
1525  custom_expr_map_by_id_[custom_expr->id] = std::move(custom_expr);
1526  }
1527 }
SqliteConnector sqliteConnector_
Definition: Catalog.h:720
virtual void query(const std::string &queryString)
std::unique_ptr< CustomExpression > getCustomExpressionFromConnector(size_t row)
Definition: Catalog.cpp:1529
CustomExpressionMapById custom_expr_map_by_id_
Definition: Catalog.h:717
virtual size_t getNumRows() const
void Catalog_Namespace::Catalog::buildDashboardsMapUnlocked ( const std::map< int32_t, std::string > &  user_name_by_user_id)
private

Definition at line 1420 of file Catalog.cpp.

References generate_dashboard_system_rolename(), Catalog_Namespace::anonymous_namespace{Catalog.cpp}::get_user_name_from_id(), and to_string().

1421  {
1422  std::string frontendViewQuery(
1423  "SELECT id, state, name, image_hash, strftime('%Y-%m-%dT%H:%M:%SZ', update_time), "
1424  "userid, "
1425  "metadata "
1426  "FROM mapd_dashboards");
1427  sqliteConnector_.query(frontendViewQuery);
1428  auto numRows = sqliteConnector_.getNumRows();
1429  for (size_t r = 0; r < numRows; ++r) {
1430  auto vd = std::make_shared<DashboardDescriptor>();
1431  vd->dashboardId = sqliteConnector_.getData<int>(r, 0);
1432  vd->dashboardState = sqliteConnector_.getData<string>(r, 1);
1433  vd->dashboardName = sqliteConnector_.getData<string>(r, 2);
1434  vd->imageHash = sqliteConnector_.getData<string>(r, 3);
1435  vd->updateTime = sqliteConnector_.getData<string>(r, 4);
1436  vd->userId = sqliteConnector_.getData<int>(r, 5);
1437  vd->dashboardMetadata = sqliteConnector_.getData<string>(r, 6);
1438  vd->user = get_user_name_from_id(vd->userId, user_name_by_user_id);
1439  vd->dashboardSystemRoleName = generate_dashboard_system_rolename(
1441  dashboardDescriptorMap_[std::to_string(vd->userId) + ":" + vd->dashboardName] = vd;
1442  }
1443 }
T getData(const int row, const int col)
SqliteConnector sqliteConnector_
Definition: Catalog.h:720
const DBMetadata currentDB_
Definition: Catalog.h:721
virtual void query(const std::string &queryString)
DashboardDescriptorMap dashboardDescriptorMap_
Definition: Catalog.h:712
std::string to_string(char const *&&v)
std::string get_user_name_from_id(int32_t id, const std::map< int32_t, std::string > &user_name_by_user_id)
Definition: Catalog.cpp:1054
virtual size_t getNumRows() const
std::string generate_dashboard_system_rolename(const std::string &db_id, const std::string &dash_id)

+ Here is the call graph for this function:

void Catalog_Namespace::Catalog::buildDictionaryMapUnlocked ( )
private

Definition at line 1075 of file Catalog.cpp.

References currentDB_, Catalog_Namespace::DBMetadata::dbId, dictDescriptorMapByRef_, g_base_path, SqliteConnector::getData(), SqliteConnector::getNumRows(), shared::kDataDirectoryName, SqliteConnector::query(), sqliteConnector_, and to_string().

1075  {
1076  std::string dictQuery(
1077  "SELECT dictid, name, nbits, is_shared, refcount from mapd_dictionaries");
1078  sqliteConnector_.query(dictQuery);
1079  auto numRows = sqliteConnector_.getNumRows();
1080  for (size_t r = 0; r < numRows; ++r) {
1081  auto dictId = sqliteConnector_.getData<int>(r, 0);
1082  auto dictName = sqliteConnector_.getData<string>(r, 1);
1083  auto dictNBits = sqliteConnector_.getData<int>(r, 2);
1084  auto is_shared = sqliteConnector_.getData<bool>(r, 3);
1085  auto refcount = sqliteConnector_.getData<int>(r, 4);
1086  auto fname = g_base_path + "/" + shared::kDataDirectoryName + "/DB_" +
1087  std::to_string(currentDB_.dbId) + "_DICT_" + std::to_string(dictId);
1088  DictRef dict_ref(currentDB_.dbId, dictId);
1089  auto dd = new DictDescriptor(
1090  dict_ref, dictName, dictNBits, is_shared, refcount, fname, false);
1091  dictDescriptorMapByRef_[dict_ref].reset(dd);
1092  }
1093 }
const std::string kDataDirectoryName
T getData(const int row, const int col)
SqliteConnector sqliteConnector_
Definition: Catalog.h:720
const DBMetadata currentDB_
Definition: Catalog.h:721
DictDescriptorMapById dictDescriptorMapByRef_
Definition: Catalog.h:711
virtual void query(const std::string &queryString)
std::string to_string(char const *&&v)
std::string g_base_path
Definition: SysCatalog.cpp:62
Descriptor for a dictionary for a string columne.
virtual size_t getNumRows() const

+ Here is the call graph for this function:

void Catalog_Namespace::Catalog::buildForeignServerMapUnlocked ( )
private

Definition at line 5102 of file Catalog.cpp.

References CHECK, and g_enable_fsi.

5102  {
5105  "SELECT id, name, data_wrapper_type, options, owner_user_id, creation_time FROM "
5106  "omnisci_foreign_servers");
5107  auto num_rows = sqliteConnector_.getNumRows();
5108 
5109  for (size_t row = 0; row < num_rows; row++) {
5110  auto foreign_server = std::make_shared<foreign_storage::ForeignServer>(
5111  sqliteConnector_.getData<int>(row, 0),
5112  sqliteConnector_.getData<std::string>(row, 1),
5113  sqliteConnector_.getData<std::string>(row, 2),
5114  sqliteConnector_.getData<std::string>(row, 3),
5115  sqliteConnector_.getData<std::int32_t>(row, 4),
5116  sqliteConnector_.getData<std::int32_t>(row, 5));
5117  foreignServerMap_[foreign_server->name] = foreign_server;
5118  foreignServerMapById_[foreign_server->id] = foreign_server;
5119  }
5120 }
T getData(const int row, const int col)
SqliteConnector sqliteConnector_
Definition: Catalog.h:720
virtual void query(const std::string &queryString)
ForeignServerMapById foreignServerMapById_
Definition: Catalog.h:716
ForeignServerMap foreignServerMap_
Definition: Catalog.h:715
#define CHECK(condition)
Definition: Logger.h:291
bool g_enable_fsi
Definition: Catalog.cpp:96
virtual size_t getNumRows() const
void Catalog_Namespace::Catalog::buildLinksMapUnlocked ( )
private

Definition at line 1445 of file Catalog.cpp.

References to_string().

1445  {
1446  std::string linkQuery(
1447  "SELECT linkid, userid, link, view_state, strftime('%Y-%m-%dT%H:%M:%SZ', "
1448  "update_time), view_metadata "
1449  "FROM mapd_links");
1450  sqliteConnector_.query(linkQuery);
1451  auto numRows = sqliteConnector_.getNumRows();
1452  for (size_t r = 0; r < numRows; ++r) {
1453  auto ld = new LinkDescriptor();
1454  ld->linkId = sqliteConnector_.getData<int>(r, 0);
1455  ld->userId = sqliteConnector_.getData<int>(r, 1);
1456  ld->link = sqliteConnector_.getData<string>(r, 2);
1457  ld->viewState = sqliteConnector_.getData<string>(r, 3);
1458  ld->updateTime = sqliteConnector_.getData<string>(r, 4);
1459  ld->viewMetadata = sqliteConnector_.getData<string>(r, 5);
1461  linkDescriptorMapById_[ld->linkId] = ld;
1462  }
1463 }
T getData(const int row, const int col)
SqliteConnector sqliteConnector_
Definition: Catalog.h:720
const DBMetadata currentDB_
Definition: Catalog.h:721
virtual void query(const std::string &queryString)
std::string to_string(char const *&&v)
LinkDescriptorMapById linkDescriptorMapById_
Definition: Catalog.h:714
virtual size_t getNumRows() const
LinkDescriptorMap linkDescriptorMap_
Definition: Catalog.h:713

+ Here is the call graph for this function:

void Catalog_Namespace::Catalog::buildLogicalToPhysicalMapUnlocked ( )
private

Definition at line 1465 of file Catalog.cpp.

References CHECK.

1465  {
1466  /* rebuild map linking logical tables to corresponding physical ones */
1467  std::string logicalToPhysicalTableMapQuery(
1468  "SELECT logical_table_id, physical_table_id "
1469  "FROM mapd_logical_to_physical");
1470  sqliteConnector_.query(logicalToPhysicalTableMapQuery);
1471  auto numRows = sqliteConnector_.getNumRows();
1472  for (size_t r = 0; r < numRows; ++r) {
1473  auto logical_tb_id = sqliteConnector_.getData<int>(r, 0);
1474  auto physical_tb_id = sqliteConnector_.getData<int>(r, 1);
1475  const auto physicalTableIt = logicalToPhysicalTableMapById_.find(logical_tb_id);
1476  if (physicalTableIt == logicalToPhysicalTableMapById_.end()) {
1477  /* add new entity to the map logicalToPhysicalTableMapById_ */
1478  std::vector<int32_t> physicalTables{physical_tb_id};
1479  const auto it_ok =
1480  logicalToPhysicalTableMapById_.emplace(logical_tb_id, physicalTables);
1481  CHECK(it_ok.second);
1482  } else {
1483  /* update map logicalToPhysicalTableMapById_ */
1484  physicalTableIt->second.push_back(physical_tb_id);
1485  }
1486  }
1487 }
T getData(const int row, const int col)
SqliteConnector sqliteConnector_
Definition: Catalog.h:720
virtual void query(const std::string &queryString)
#define CHECK(condition)
Definition: Logger.h:291
virtual size_t getNumRows() const
LogicalToPhysicalTableMapById logicalToPhysicalTableMapById_
Definition: Catalog.h:727
void Catalog_Namespace::Catalog::buildMaps ( )
protected

Definition at line 1492 of file Catalog.cpp.

References g_enable_fsi, and Catalog_Namespace::anonymous_namespace{Catalog.cpp}::get_user_id_to_user_name_map().

1492  {
1493  // Get all user id to username mapping here in order to avoid making a call to
1494  // SysCatalog (and attempting to acquire SysCatalog locks) while holding locks for this
1495  // catalog.
1496  const auto user_name_by_user_id = get_user_id_to_user_name_map();
1497 
1498  cat_write_lock write_lock(this);
1499  cat_sqlite_lock sqlite_lock(getObjForLock());
1500 
1503 
1504  if (g_enable_fsi) {
1507  }
1508 
1511  buildDashboardsMapUnlocked(user_name_by_user_id);
1515 }
void buildLogicalToPhysicalMapUnlocked()
Definition: Catalog.cpp:1465
void buildDashboardsMapUnlocked(const std::map< int32_t, std::string > &user_name_by_user_id)
Definition: Catalog.cpp:1420
void buildCustomExpressionsMapUnlocked()
Definition: Catalog.cpp:1517
const Catalog * getObjForLock()
Definition: Catalog.cpp:260
write_lock< Catalog > cat_write_lock
Definition: Catalog.cpp:125
void updateForeignTablesInMapUnlocked()
Definition: Catalog.cpp:5122
sqlite_lock< Catalog > cat_sqlite_lock
Definition: Catalog.cpp:126
bool g_enable_fsi
Definition: Catalog.cpp:96
std::map< int32_t, std::string > get_user_id_to_user_name_map()
Definition: Catalog.cpp:1045

+ Here is the call graph for this function:

void Catalog_Namespace::Catalog::buildTablesMapUnlocked ( )
private

Definition at line 1277 of file Catalog.cpp.

References logger::FATAL, StorageType::FOREIGN_TABLE, TableDescriptor::fragmenter, TableDescriptor::fragments, TableDescriptor::fragPageSize, TableDescriptor::fragType, TableDescriptor::hasDeletedCol, TableDescriptor::is_system_table, TableDescriptor::isView, TableDescriptor::keyMetainfo, LOG, TableDescriptor::maxChunkSize, TableDescriptor::maxFragRows, TableDescriptor::maxRollbackEpochs, TableDescriptor::maxRows, TableDescriptor::nColumns, TableDescriptor::nShards, TableDescriptor::partitions, TableDescriptor::shard, TableDescriptor::shardedColumnId, TableDescriptor::sortedColumnId, TableDescriptor::storageType, TableDescriptor::tableId, TableDescriptor::tableName, to_upper(), and TableDescriptor::userId.

1277  {
1278  std::string tableQuery(
1279  "SELECT tableid, name, ncolumns, isview, fragments, frag_type, max_frag_rows, "
1280  "max_chunk_size, frag_page_size, "
1281  "max_rows, partitions, shard_column_id, shard, num_shards, key_metainfo, userid, "
1282  "sort_column_id, storage_type, max_rollback_epochs, is_system_table "
1283  "from mapd_tables");
1284  sqliteConnector_.query(tableQuery);
1285  auto numRows = sqliteConnector_.getNumRows();
1286  for (size_t r = 0; r < numRows; ++r) {
1287  TableDescriptor* td;
1288  const auto& storage_type = sqliteConnector_.getData<string>(r, 17);
1289  if (!storage_type.empty() && storage_type != StorageType::FOREIGN_TABLE) {
1290  const auto table_id = sqliteConnector_.getData<int>(r, 0);
1291  const auto& table_name = sqliteConnector_.getData<string>(r, 1);
1292  LOG(FATAL) << "Unable to read Catalog metadata: storage type is currently not a "
1293  "supported table option (table "
1294  << table_name << " [" << table_id << "] in database "
1295  << currentDB_.dbName << ").";
1296  }
1297 
1298  if (storage_type == StorageType::FOREIGN_TABLE) {
1299  td = new foreign_storage::ForeignTable();
1300  } else {
1301  td = new TableDescriptor();
1302  }
1303 
1304  td->storageType = storage_type;
1305  td->tableId = sqliteConnector_.getData<int>(r, 0);
1306  td->tableName = sqliteConnector_.getData<string>(r, 1);
1307  td->nColumns = sqliteConnector_.getData<int>(r, 2);
1308  td->isView = sqliteConnector_.getData<bool>(r, 3);
1309  td->fragments = sqliteConnector_.getData<string>(r, 4);
1310  td->fragType =
1312  td->maxFragRows = sqliteConnector_.getData<int>(r, 6);
1313  td->maxChunkSize = sqliteConnector_.getData<int64_t>(r, 7);
1314  td->fragPageSize = sqliteConnector_.getData<int>(r, 8);
1315  td->maxRows = sqliteConnector_.getData<int64_t>(r, 9);
1316  td->partitions = sqliteConnector_.getData<string>(r, 10);
1317  td->shardedColumnId = sqliteConnector_.getData<int>(r, 11);
1318  td->shard = sqliteConnector_.getData<int>(r, 12);
1319  td->nShards = sqliteConnector_.getData<int>(r, 13);
1320  td->keyMetainfo = sqliteConnector_.getData<string>(r, 14);
1321  td->userId = sqliteConnector_.getData<int>(r, 15);
1322  td->sortedColumnId =
1323  sqliteConnector_.isNull(r, 16) ? 0 : sqliteConnector_.getData<int>(r, 16);
1324  if (!td->isView) {
1325  td->fragmenter = nullptr;
1326  }
1327  td->maxRollbackEpochs = sqliteConnector_.getData<int>(r, 18);
1328  td->is_system_table = sqliteConnector_.getData<bool>(r, 19);
1329  td->hasDeletedCol = false;
1330 
1332  tableDescriptorMapById_[td->tableId] = td;
1333  }
1334 }
int32_t maxRollbackEpochs
std::string partitions
T getData(const int row, const int col)
std::string tableName
#define LOG(tag)
Definition: Logger.h:285
SqliteConnector sqliteConnector_
Definition: Catalog.h:720
const DBMetadata currentDB_
Definition: Catalog.h:721
std::string storageType
virtual void query(const std::string &queryString)
std::string fragments
TableDescriptorMapById tableDescriptorMapById_
Definition: Catalog.h:708
std::string keyMetainfo
std::shared_ptr< Fragmenter_Namespace::AbstractFragmenter > fragmenter
std::string to_upper(const std::string &str)
bool isNull(const int row, const int col) const
Fragmenter_Namespace::FragmenterType fragType
static constexpr char const * FOREIGN_TABLE
virtual size_t getNumRows() const
TableDescriptorMap tableDescriptorMap_
Definition: Catalog.h:707

+ Here is the call graph for this function:

std::string Catalog_Namespace::Catalog::calculateSHA1 ( const std::string &  data)
protected

Definition at line 4811 of file Catalog.cpp.

4811  {
4812  boost::uuids::detail::sha1 sha1;
4813  unsigned int digest[5];
4814  sha1.process_bytes(data.c_str(), data.length());
4815  sha1.get_digest(digest);
4816  std::stringstream ss;
4817  for (size_t i = 0; i < 5; i++) {
4818  ss << std::hex << digest[i];
4819  }
4820  return ss.str();
4821 }
void Catalog_Namespace::Catalog::changeForeignServerOwner ( const std::string &  server_name,
const int  new_owner_id 
)

Change the owner of a Foreign Server to a new owner.

Parameters
server_name- Name of the foreign server whose owner to change
new_owner_id- New owner's user id

Definition at line 3396 of file Catalog.cpp.

References CHECK, to_string(), and foreign_storage::ForeignServer::user_id.

3397  {
3398  cat_write_lock write_lock(this);
3399  foreign_storage::ForeignServer* foreign_server =
3400  foreignServerMap_.find(server_name)->second.get();
3401  CHECK(foreign_server);
3402  setForeignServerProperty(server_name, "owner_user_id", std::to_string(new_owner_id));
3403  // update in-memory server
3404  foreign_server->user_id = new_owner_id;
3405 }
std::string to_string(char const *&&v)
ForeignServerMap foreignServerMap_
Definition: Catalog.h:715
write_lock< Catalog > cat_write_lock
Definition: Catalog.cpp:125
#define CHECK(condition)
Definition: Logger.h:291
void setForeignServerProperty(const std::string &server_name, const std::string &property, const std::string &value)
Definition: Catalog.cpp:5320

+ Here is the call graph for this function:

void Catalog_Namespace::Catalog::CheckAndExecuteMigrations ( )
protected

Definition at line 1015 of file Catalog.cpp.

References g_enable_fsi, getObjForLock(), recordOwnershipOfObjectsInObjectPermissions(), renameLegacyDataWrappers(), updateCustomExpressionsSchema(), updateDefaultColumnValues(), updateDeletedColumnIndicator(), updateDictionaryNames(), updateDictionarySchema(), updateFixlenArrayColumns(), updateFrontendViewAndLinkUsers(), updateFrontendViewSchema(), updateFrontendViewsToDashboards(), updateFsiSchemas(), updateGeoColumns(), updateLinkSchema(), updateLogicalToPhysicalTableLinkSchema(), updatePageSize(), and updateTableDescriptorSchema().

1015  {
1016  cat_write_lock write_lock(this);
1017  cat_sqlite_lock sqlite_lock(getObjForLock());
1020  updateGeoColumns();
1023  updateLinkSchema();
1027  updatePageSize();
1031  if (g_enable_fsi) {
1032  updateFsiSchemas();
1034  }
1037 }
void updateFrontendViewAndLinkUsers()
Definition: Catalog.cpp:473
void recordOwnershipOfObjectsInObjectPermissions()
Definition: Catalog.cpp:800
void updateFrontendViewsToDashboards()
Definition: Catalog.cpp:132
const Catalog * getObjForLock()
Definition: Catalog.cpp:260
write_lock< Catalog > cat_write_lock
Definition: Catalog.cpp:125
void updateCustomExpressionsSchema()
Definition: Catalog.cpp:766
void updateLogicalToPhysicalTableLinkSchema()
Definition: Catalog.cpp:634
sqlite_lock< Catalog > cat_sqlite_lock
Definition: Catalog.cpp:126
bool g_enable_fsi
Definition: Catalog.cpp:96

+ Here is the call graph for this function:

void Catalog_Namespace::Catalog::CheckAndExecuteMigrationsPostBuildMaps ( )
protected

Definition at line 1039 of file Catalog.cpp.

References checkDateInDaysColumnMigration(), and createDashboardSystemRoles().

1039  {
1042 }
void checkDateInDaysColumnMigration()
Definition: Catalog.cpp:928

+ Here is the call graph for this function:

void Catalog_Namespace::Catalog::checkDateInDaysColumnMigration ( )
protected

Definition at line 928 of file Catalog.cpp.

References getCurrentDB(), getObjForLock(), migrations::MigrationMgr::migrateDateInDaysMetadata(), sqliteConnector_, and tableDescriptorMapById_.

Referenced by CheckAndExecuteMigrationsPostBuildMaps().

928  {
929  cat_sqlite_lock sqlite_lock(getObjForLock());
932 }
SqliteConnector sqliteConnector_
Definition: Catalog.h:720
const DBMetadata & getCurrentDB() const
Definition: Catalog.h:265
TableDescriptorMapById tableDescriptorMapById_
Definition: Catalog.h:708
const Catalog * getObjForLock()
Definition: Catalog.cpp:260
static void migrateDateInDaysMetadata(const Catalog_Namespace::TableDescriptorMapById &table_descriptors_by_id, const int database_id, Catalog_Namespace::Catalog *cat, SqliteConnector &sqlite)
sqlite_lock< Catalog > cat_sqlite_lock
Definition: Catalog.cpp:126

+ Here is the call graph for this function:

+ Here is the caller graph for this function:

bool Catalog_Namespace::Catalog::checkDropRenderGroupColumnsMigration ( )

Definition at line 934 of file Catalog.cpp.

References migrations::MigrationMgr::dropRenderGroupColumns(), and tableDescriptorMapById_.

Referenced by Catalog_Namespace::SysCatalog::checkDropRenderGroupColumnsMigration().

934  {
935  // do not take cat_sqlite_lock here as Catalog functions do that themselves
937 }
static bool dropRenderGroupColumns(const Catalog_Namespace::TableDescriptorMapById &table_descriptors_by_id, Catalog_Namespace::Catalog *cat)
TableDescriptorMapById tableDescriptorMapById_
Definition: Catalog.h:708

+ Here is the call graph for this function:

+ Here is the caller graph for this function:

const bool Catalog_Namespace::Catalog::checkMetadataForDeletedRecs ( const TableDescriptor td,
int  column_id 
) const

Definition at line 3913 of file Catalog.cpp.

References CHECK, and TableDescriptor::fragmenter.

3914  {
3915  // check if there are rows deleted by examining the deletedColumn metadata
3916  CHECK(td);
3917  auto fragmenter = td->fragmenter;
3918  if (fragmenter) {
3919  return fragmenter->hasDeletedRows(delete_column_id);
3920  } else {
3921  return false;
3922  }
3923 }
std::shared_ptr< Fragmenter_Namespace::AbstractFragmenter > fragmenter
#define CHECK(condition)
Definition: Logger.h:291
void Catalog_Namespace::Catalog::checkpoint ( const int  logicalTableId) const

Definition at line 5032 of file Catalog.cpp.

Referenced by UpdelRoll::commitUpdate(), TableOptimizer::vacuumDeletedRows(), and TableOptimizer::vacuumFragmentsAboveMinSelectivity().

5032  {
5033  const auto td = getMetadataForTable(logicalTableId);
5034  const auto shards = getPhysicalTablesDescriptors(td);
5035  for (const auto shard : shards) {
5036  getDataMgr().checkpoint(getCurrentDB().dbId, shard->tableId);
5037  }
5038 }
Data_Namespace::DataMgr & getDataMgr() const
Definition: Catalog.h:266
void checkpoint(const int db_id, const int tb_id)
Definition: DataMgr.cpp:634
const DBMetadata & getCurrentDB() const
Definition: Catalog.h:265
std::vector< const TableDescriptor * > getPhysicalTablesDescriptors(const TableDescriptor *logical_table_desc, bool populate_fragmenter=true) const
Definition: Catalog.cpp:4879
const TableDescriptor * getMetadataForTable(const std::string &tableName, const bool populateFragmenter=true) const
Returns a pointer to a const TableDescriptor struct matching the provided tableName.

+ Here is the caller graph for this function:

void Catalog_Namespace::Catalog::checkpointWithAutoRollback ( const int  logical_table_id) const

Definition at line 5040 of file Catalog.cpp.

Referenced by AlterTableAlterColumnCommandRecoveryMgr::checkpoint(), Fragmenter_Namespace::LocalInsertConnector::checkpoint(), import_export::Loader::checkpoint(), StorageIOFacility::TransactionParameters::finalizeTransaction(), and TableOptimizer::vacuumFragmentsAboveMinSelectivity().

5040  {
5041  auto table_epochs = getTableEpochs(getDatabaseId(), logical_table_id);
5042  try {
5043  checkpoint(logical_table_id);
5044  } catch (...) {
5045  setTableEpochsLogExceptions(getDatabaseId(), table_epochs);
5046  throw;
5047  }
5048 }
int getDatabaseId() const
Definition: Catalog.h:326
void checkpoint(const int logicalTableId) const
Definition: Catalog.cpp:5032
void setTableEpochsLogExceptions(const int32_t db_id, const std::vector< TableEpochInfo > &table_epochs) const
Definition: Catalog.cpp:3895
std::vector< TableEpochInfo > getTableEpochs(const int32_t db_id, const int32_t table_id) const
Definition: Catalog.cpp:3831

+ Here is the caller graph for this function:

void Catalog_Namespace::Catalog::conditionallyInitializeSystemObjects ( )
private

Definition at line 6392 of file Catalog.cpp.

References g_enable_system_tables.

6392  {
6396  }
6397 }
bool g_enable_system_tables
Definition: SysCatalog.cpp:64
bool isInfoSchemaDb() const
Definition: Catalog.cpp:6399
int32_t Catalog_Namespace::Catalog::createCustomExpression ( std::unique_ptr< CustomExpression custom_expression)

Creates a new custom expression.

Parameters
custom_expression- unique pointer to struct containing custom expression details.
Returns
id of created custom expression

Definition at line 5954 of file Catalog.cpp.

References CHECK, CHECK_EQ, CHECK_GT, and to_string().

5955  {
5956  cat_write_lock write_lock(this);
5957  cat_sqlite_lock sqlite_lock(getObjForLock());
5958  sqliteConnector_.query("BEGIN TRANSACTION");
5959  int32_t custom_expression_id{-1};
5960  try {
5961  auto data_source_type_str =
5962  CustomExpression::dataSourceTypeToString(custom_expression->data_source_type);
5963  auto data_source_id_str = std::to_string(custom_expression->data_source_id);
5964  std::string custom_expr_select_query{
5965  "SELECT id FROM omnisci_custom_expressions WHERE name = ? and data_source_type = "
5966  "? and data_source_id = ? and is_deleted = ?"};
5967  std::vector<std::string> custom_expr_select_params{custom_expression->name,
5968  data_source_type_str,
5969  data_source_id_str,
5970  std::to_string(false)};
5971  sqliteConnector_.query_with_text_params(custom_expr_select_query,
5972  custom_expr_select_params);
5973  if (sqliteConnector_.getNumRows() > 0) {
5974  throw std::runtime_error{
5975  "A custom expression with the given "
5976  "name and data source already exists."};
5977  }
5979  "INSERT INTO omnisci_custom_expressions(name, expression_json, "
5980  "data_source_type, data_source_id, is_deleted) VALUES (?,?,?,?,?)",
5981  std::vector<std::string>{custom_expression->name,
5982  custom_expression->expression_json,
5983  data_source_type_str,
5984  data_source_id_str,
5985  std::to_string(false)});
5986  sqliteConnector_.query_with_text_params(custom_expr_select_query,
5987  custom_expr_select_params);
5988  CHECK_EQ(sqliteConnector_.getNumRows(), static_cast<size_t>(1));
5989  custom_expression->id = sqliteConnector_.getData<int32_t>(0, 0);
5990  custom_expression_id = custom_expression->id;
5991  CHECK(custom_expr_map_by_id_.find(custom_expression->id) ==
5992  custom_expr_map_by_id_.end());
5993  custom_expr_map_by_id_[custom_expression->id] = std::move(custom_expression);
5994  } catch (std::exception& e) {
5995  sqliteConnector_.query("ROLLBACK TRANSACTION");
5996  throw;
5997  }
5998  sqliteConnector_.query("END TRANSACTION");
5999  CHECK_GT(custom_expression_id, 0);
6000  return custom_expression_id;
6001 }
#define CHECK_EQ(x, y)
Definition: Logger.h:301
T getData(const int row, const int col)
virtual void query_with_text_params(std::string const &query_only)
SqliteConnector sqliteConnector_
Definition: Catalog.h:720
virtual void query(const std::string &queryString)
#define CHECK_GT(x, y)
Definition: Logger.h:305
std::string to_string(char const *&&v)
static std::string dataSourceTypeToString(DataSourceType type_enum)
const Catalog * getObjForLock()
Definition: Catalog.cpp:260
write_lock< Catalog > cat_write_lock
Definition: Catalog.cpp:125
#define CHECK(condition)
Definition: Logger.h:291
CustomExpressionMapById custom_expr_map_by_id_
Definition: Catalog.h:717
sqlite_lock< Catalog > cat_sqlite_lock
Definition: Catalog.cpp:126
virtual size_t getNumRows() const

+ Here is the call graph for this function:

int32_t Catalog_Namespace::Catalog::createDashboard ( DashboardDescriptor vd)

Definition at line 4670 of file Catalog.cpp.

References DashboardDescriptor::dashboardId, DashboardDescriptor::dashboardMetadata, DashboardDescriptor::dashboardName, DashboardDescriptor::dashboardState, DashboardDescriptor::dashboardSystemRoleName, generate_dashboard_system_rolename(), DashboardDescriptor::imageHash, to_string(), Catalog_Namespace::sqlite_lock< T >::unlock(), Catalog_Namespace::write_lock< T >::unlock(), DashboardDescriptor::updateTime, and DashboardDescriptor::userId.

4670  {
4671  cat_write_lock write_lock(this);
4672  cat_sqlite_lock sqlite_lock(getObjForLock());
4673  sqliteConnector_.query("BEGIN TRANSACTION");
4674  try {
4675  // TODO(andrew): this should be an upsert
4677  "SELECT id FROM mapd_dashboards WHERE name = ? and userid = ?",
4678  std::vector<std::string>{vd.dashboardName, std::to_string(vd.userId)});
4679  if (sqliteConnector_.getNumRows() > 0) {
4681  "UPDATE mapd_dashboards SET state = ?, image_hash = ?, metadata = ?, "
4682  "update_time = "
4683  "datetime('now') where name = ? "
4684  "and userid = ?",
4685  std::vector<std::string>{vd.dashboardState,
4686  vd.imageHash,
4687  vd.dashboardMetadata,
4688  vd.dashboardName,
4689  std::to_string(vd.userId)});
4690  } else {
4692  "INSERT INTO mapd_dashboards (name, state, image_hash, metadata, "
4693  "update_time, "
4694  "userid) "
4695  "VALUES "
4696  "(?,?,?,?, "
4697  "datetime('now'), ?)",
4698  std::vector<std::string>{vd.dashboardName,
4699  vd.dashboardState,
4700  vd.imageHash,
4701  vd.dashboardMetadata,
4702  std::to_string(vd.userId)});
4703  }
4704  } catch (std::exception& e) {
4705  sqliteConnector_.query("ROLLBACK TRANSACTION");
4706  throw;
4707  }
4708  sqliteConnector_.query("END TRANSACTION");
4709 
4710  // now get the auto generated dashboardId
4711  try {
4713  "SELECT id, strftime('%Y-%m-%dT%H:%M:%SZ', update_time) FROM mapd_dashboards "
4714  "WHERE name = ? and userid = ?",
4715  std::vector<std::string>{vd.dashboardName, std::to_string(vd.userId)});
4716  vd.dashboardId = sqliteConnector_.getData<int>(0, 0);
4717  vd.updateTime = sqliteConnector_.getData<std::string>(0, 1);
4718  } catch (std::exception& e) {
4719  throw;
4720  }
4724  sqlite_lock.unlock();
4725  write_lock.unlock();
4726  if (!isInfoSchemaDb()) {
4727  // NOTE(wamsi): Transactionally unsafe
4730  }
4731  return vd.dashboardId;
4732 }
T getData(const int row, const int col)
virtual void query_with_text_params(std::string const &query_only)
SqliteConnector sqliteConnector_
Definition: Catalog.h:720
const DBMetadata currentDB_
Definition: Catalog.h:721
virtual void query(const std::string &queryString)
void addFrontendViewToMap(DashboardDescriptor &vd)
Definition: Catalog.cpp:1686
std::string to_string(char const *&&v)
std::string dashboardSystemRoleName
void createOrUpdateDashboardSystemRole(const std::string &view_meta, const int32_t &user_id, const std::string &dash_role_name)
Definition: Catalog.cpp:1727
const Catalog * getObjForLock()
Definition: Catalog.cpp:260
write_lock< Catalog > cat_write_lock
Definition: Catalog.cpp:125
bool isInfoSchemaDb() const
Definition: Catalog.cpp:6399
sqlite_lock< Catalog > cat_sqlite_lock
Definition: Catalog.cpp:126
virtual size_t getNumRows() const
std::string generate_dashboard_system_rolename(const std::string &db_id, const std::string &dash_id)

+ Here is the call graph for this function:

void Catalog_Namespace::Catalog::createDashboardSystemRoles ( )
protected

Definition at line 939 of file Catalog.cpp.

References createOrUpdateDashboardSystemRole(), currentDB_, Catalog_Namespace::DBMetadata::dbId, logger::ERROR, generate_dashboard_system_rolename(), SqliteConnector::getData(), Catalog_Namespace::SysCatalog::getGranteesOfSharedDashboards(), SqliteConnector::getNumRows(), getObjForLock(), Catalog_Namespace::SysCatalog::getRoleGrantee(), Catalog_Namespace::SysCatalog::grantRoleBatch(), logger::INFO, Catalog_Namespace::SysCatalog::instance(), LOG, MAPD_VERSION, SqliteConnector::query(), SqliteConnector::query_with_text_params(), run_benchmark_import::result, sqliteConnector_, and to_string().

Referenced by CheckAndExecuteMigrationsPostBuildMaps().

939  {
940  std::unordered_map<std::string, std::pair<int, std::string>> dashboards;
941  std::vector<std::string> dashboard_ids;
942  static const std::string migration_name{"dashboard_roles_migration"};
943  {
944  cat_sqlite_lock sqlite_lock(getObjForLock());
945  sqliteConnector_.query("BEGIN TRANSACTION");
946  try {
947  // migration_history should be present in all catalogs by now
948  // if not then would be created before this migration
950  "select * from mapd_version_history where migration_history = '" +
951  migration_name + "'");
952  if (sqliteConnector_.getNumRows() != 0) {
953  // no need for further execution
954  sqliteConnector_.query("END TRANSACTION");
955  return;
956  }
957  LOG(INFO) << "Performing dashboard internal roles Migration.";
958  sqliteConnector_.query("select id, userid, metadata from mapd_dashboards");
959  for (size_t i = 0; i < sqliteConnector_.getNumRows(); ++i) {
962  sqliteConnector_.getData<string>(i, 0)))) {
963  // Successfully created roles during previous migration/crash
964  // No need to include them
965  continue;
966  }
967  dashboards[sqliteConnector_.getData<string>(i, 0)] = std::make_pair(
968  sqliteConnector_.getData<int>(i, 1), sqliteConnector_.getData<string>(i, 2));
969  dashboard_ids.push_back(sqliteConnector_.getData<string>(i, 0));
970  }
971  } catch (const std::exception& e) {
972  sqliteConnector_.query("ROLLBACK TRANSACTION");
973  throw;
974  }
975  sqliteConnector_.query("END TRANSACTION");
976  }
977  // All current grantees with shared dashboards.
978  const auto active_grantees =
980 
981  try {
982  // NOTE(wamsi): Transactionally unsafe
983  for (auto dash : dashboards) {
984  createOrUpdateDashboardSystemRole(dash.second.second,
985  dash.second.first,
987  std::to_string(currentDB_.dbId), dash.first));
988  auto result = active_grantees.find(dash.first);
989  if (result != active_grantees.end()) {
992  dash.first)},
993  result->second);
994  }
995  }
996  cat_sqlite_lock sqlite_lock(getObjForLock());
997  // check if this has already been completed
999  "select * from mapd_version_history where migration_history = '" +
1000  migration_name + "'");
1001  if (sqliteConnector_.getNumRows() != 0) {
1002  return;
1003  }
1005  "INSERT INTO mapd_version_history(version, migration_history) values(?,?)",
1006  std::vector<std::string>{std::to_string(MAPD_VERSION), migration_name});
1007  } catch (const std::exception& e) {
1008  LOG(ERROR) << "Failed to create dashboard system roles during migration: "
1009  << e.what();
1010  throw;
1011  }
1012  LOG(INFO) << "Successfully created dashboard system roles during migration.";
1013 }
T getData(const int row, const int col)
virtual void query_with_text_params(std::string const &query_only)
#define LOG(tag)
Definition: Logger.h:285
SqliteConnector sqliteConnector_
Definition: Catalog.h:720
const DBMetadata currentDB_
Definition: Catalog.h:721
virtual void query(const std::string &queryString)
std::string to_string(char const *&&v)
void grantRoleBatch(const std::vector< std::string > &roles, const std::vector< std::string > &grantees)
static SysCatalog & instance()
Definition: SysCatalog.h:343
static const int32_t MAPD_VERSION
Definition: release.h:32
Role * getRoleGrantee(const std::string &name) const
void createOrUpdateDashboardSystemRole(const std::string &view_meta, const int32_t &user_id, const std::string &dash_role_name)
Definition: Catalog.cpp:1727
const Catalog * getObjForLock()
Definition: Catalog.cpp:260
std::unordered_map< std::string, std::vector< std::string > > getGranteesOfSharedDashboards(const std::vector< std::string > &dashboard_ids)
sqlite_lock< Catalog > cat_sqlite_lock
Definition: Catalog.cpp:126
virtual size_t getNumRows() const
std::string generate_dashboard_system_rolename(const std::string &db_id, const std::string &dash_id)

+ Here is the call graph for this function:

+ Here is the caller graph for this function:

void Catalog_Namespace::Catalog::createDefaultServersIfNotExists ( )

Creates default local file servers (if they don't already exist).

Definition at line 5341 of file Catalog.cpp.

References CHECK, foreign_storage::DataWrapperType::CSV, g_enable_fsi, shared::kRootUserId, foreign_storage::AbstractFileStorageDataWrapper::LOCAL_FILE_STORAGE_TYPE, foreign_storage::DataWrapperType::PARQUET, foreign_storage::DataWrapperType::REGEX_PARSER, and foreign_storage::AbstractFileStorageDataWrapper::STORAGE_TYPE_KEY.

5341  {
5346 
5347  auto local_csv_server = std::make_unique<foreign_storage::ForeignServer>(
5348  "default_local_delimited",
5350  options,
5352  local_csv_server->validate();
5353  createForeignServerNoLocks(std::move(local_csv_server), true);
5354 
5355 #ifdef ENABLE_IMPORT_PARQUET
5356  auto local_parquet_server = std::make_unique<foreign_storage::ForeignServer>(
5357  "default_local_parquet",
5359  options,
5361  local_parquet_server->validate();
5362  createForeignServerNoLocks(std::move(local_parquet_server), true);
5363 #endif
5364 
5365  auto local_regex_parser_server = std::make_unique<foreign_storage::ForeignServer>(
5366  "default_local_regex_parsed",
5368  options,
5370  local_regex_parser_server->validate();
5371  createForeignServerNoLocks(std::move(local_regex_parser_server), true);
5372 }
const int kRootUserId
static constexpr char const * REGEX_PARSER
void createForeignServerNoLocks(std::unique_ptr< foreign_storage::ForeignServer > foreign_server, bool if_not_exists)
Definition: Catalog.cpp:3301
#define CHECK(condition)
Definition: Logger.h:291
static constexpr char const * CSV
std::map< std::string, std::string, std::less<>> OptionsMap
bool g_enable_fsi
Definition: Catalog.cpp:96
static constexpr char const * PARQUET
void Catalog_Namespace::Catalog::createForeignServer ( std::unique_ptr< foreign_storage::ForeignServer foreign_server,
bool  if_not_exists 
)

Creates a new foreign server DB object.

Parameters
foreign_server- unique pointer to struct containing foreign server details
if_not_exists- flag indicating whether or not an attempt to create a new foreign server should occur if a server with the same name already exists. An exception is thrown if this flag is set to "false" and an attempt is made to create a pre-existing foreign server

Definition at line 3293 of file Catalog.cpp.

3295  {
3296  cat_write_lock write_lock(this);
3297  cat_sqlite_lock sqlite_lock(getObjForLock());
3298  createForeignServerNoLocks(std::move(foreign_server), if_not_exists);
3299 }
void createForeignServerNoLocks(std::unique_ptr< foreign_storage::ForeignServer > foreign_server, bool if_not_exists)
Definition: Catalog.cpp:3301
const Catalog * getObjForLock()
Definition: Catalog.cpp:260
write_lock< Catalog > cat_write_lock
Definition: Catalog.cpp:125
sqlite_lock< Catalog > cat_sqlite_lock
Definition: Catalog.cpp:126
void Catalog_Namespace::Catalog::createForeignServerNoLocks ( std::unique_ptr< foreign_storage::ForeignServer foreign_server,
bool  if_not_exists 
)
private

Same as createForeignServer() but without acquiring locks. This should only be called from within a function/code block that already acquires appropriate locks.

Definition at line 3301 of file Catalog.cpp.

References CHECK, CHECK_EQ, setup::name, and to_string().

3303  {
3304  const auto& name = foreign_server->name;
3305 
3307  "SELECT name from omnisci_foreign_servers where name = ?",
3308  std::vector<std::string>{name});
3309 
3310  if (sqliteConnector_.getNumRows() == 0) {
3311  foreign_server->creation_time = std::time(nullptr);
3313  "INSERT INTO omnisci_foreign_servers (name, data_wrapper_type, owner_user_id, "
3314  "creation_time, "
3315  "options) "
3316  "VALUES (?, ?, ?, ?, ?)",
3317  std::vector<std::string>{name,
3318  foreign_server->data_wrapper_type,
3319  std::to_string(foreign_server->user_id),
3320  std::to_string(foreign_server->creation_time),
3321  foreign_server->getOptionsAsJsonString()});
3323  "SELECT id from omnisci_foreign_servers where name = ?",
3324  std::vector<std::string>{name});
3325  CHECK_EQ(sqliteConnector_.getNumRows(), size_t(1));
3326  foreign_server->id = sqliteConnector_.getData<int32_t>(0, 0);
3327  std::shared_ptr<foreign_storage::ForeignServer> foreign_server_shared =
3328  std::move(foreign_server);
3330  << "Attempting to insert a foreign server into foreign server map that already "
3331  "exists.";
3332  foreignServerMap_[name] = foreign_server_shared;
3333  foreignServerMapById_[foreign_server_shared->id] = foreign_server_shared;
3334  } else if (!if_not_exists) {
3335  throw std::runtime_error{"A foreign server with name \"" + foreign_server->name +
3336  "\" already exists."};
3337  }
3338 
3339  const auto& server_it = foreignServerMap_.find(name);
3340  CHECK(server_it != foreignServerMap_.end());
3341  CHECK(foreignServerMapById_.find(server_it->second->id) != foreignServerMapById_.end());
3342 }
#define CHECK_EQ(x, y)
Definition: Logger.h:301
T getData(const int row, const int col)
virtual void query_with_text_params(std::string const &query_only)
SqliteConnector sqliteConnector_
Definition: Catalog.h:720
std::string to_string(char const *&&v)
std::string name() const
Definition: Catalog.h:348
ForeignServerMapById foreignServerMapById_
Definition: Catalog.h:716
ForeignServerMap foreignServerMap_
Definition: Catalog.h:715
#define CHECK(condition)
Definition: Logger.h:291
virtual size_t getNumRows() const

+ Here is the call graph for this function:

std::string Catalog_Namespace::Catalog::createLink ( LinkDescriptor ld,
size_t  min_length 
)

Definition at line 4823 of file Catalog.cpp.

References LinkDescriptor::link, LinkDescriptor::linkId, to_string(), LinkDescriptor::updateTime, LinkDescriptor::userId, LinkDescriptor::viewMetadata, and LinkDescriptor::viewState.

4823  {
4824  cat_write_lock write_lock(this);
4825  cat_sqlite_lock sqlite_lock(getObjForLock());
4826  sqliteConnector_.query("BEGIN TRANSACTION");
4827  try {
4829  .substr(0, 8);
4831  "SELECT linkid FROM mapd_links WHERE link = ? and userid = ?",
4832  std::vector<std::string>{ld.link, std::to_string(ld.userId)});
4833  if (sqliteConnector_.getNumRows() > 0) {
4835  "UPDATE mapd_links SET update_time = datetime('now') WHERE userid = ? AND "
4836  "link = ?",
4837  std::vector<std::string>{std::to_string(ld.userId), ld.link});
4838  } else {
4840  "INSERT INTO mapd_links (userid, link, view_state, view_metadata, "
4841  "update_time) VALUES (?,?,?,?, datetime('now'))",
4842  std::vector<std::string>{
4843  std::to_string(ld.userId), ld.link, ld.viewState, ld.viewMetadata});
4844  }
4845  // now get the auto generated dashid
4847  "SELECT linkid, strftime('%Y-%m-%dT%H:%M:%SZ', update_time) FROM mapd_links "
4848  "WHERE link = ?",
4849  ld.link);
4850  ld.linkId = sqliteConnector_.getData<int>(0, 0);
4851  ld.updateTime = sqliteConnector_.getData<std::string>(0, 1);
4852  } catch (std::exception& e) {
4853  sqliteConnector_.query("ROLLBACK TRANSACTION");
4854  throw;
4855  }
4856  sqliteConnector_.query("END TRANSACTION");
4857  addLinkToMap(ld);
4858  return ld.link;
4859 }
T getData(const int row, const int col)
virtual void query_with_text_params(std::string const &query_only)
SqliteConnector sqliteConnector_
Definition: Catalog.h:720
virtual void query(const std::string &queryString)
std::string to_string(char const *&&v)
std::string calculateSHA1(const std::string &data)
Definition: Catalog.cpp:4811
void addLinkToMap(LinkDescriptor &ld)
Definition: Catalog.cpp:1773
const Catalog * getObjForLock()
Definition: Catalog.cpp:260
write_lock< Catalog > cat_write_lock
Definition: Catalog.cpp:125
sqlite_lock< Catalog > cat_sqlite_lock
Definition: Catalog.cpp:126
virtual void query_with_text_param(const std::string &queryString, const std::string &text_param)
virtual size_t getNumRows() const

+ Here is the call graph for this function:

void Catalog_Namespace::Catalog::createOrUpdateDashboardSystemRole ( const std::string &  view_meta,
const int32_t &  user_id,
const std::string &  dash_role_name 
)
protected

Definition at line 1727 of file Catalog.cpp.

References Grantee::findDbObject(), Grantee::getDbObjects(), lockmgr::instance(), TableDBObjectType, and ViewDBObjectType.

Referenced by createDashboardSystemRoles().

1729  {
1730  auto objects = parseDashboardObjects(view_meta, user_id);
1731  Role* rl = SysCatalog::instance().getRoleGrantee(dash_role_name);
1732  if (!rl) {
1733  // Dashboard role does not exist
1734  // create role and grant privileges
1735  // NOTE(wamsi): Transactionally unsafe
1737  dash_role_name, /*user_private_role=*/false, /*is_temporary=*/false);
1738  SysCatalog::instance().grantDBObjectPrivilegesBatch({dash_role_name}, objects, *this);
1739  } else {
1740  // Dashboard system role already exists
1741  // Add/remove privileges on objects
1742  std::set<DBObjectKey> revoke_keys;
1743  auto ex_objects = rl->getDbObjects(true);
1744  for (auto key : *ex_objects | boost::adaptors::map_keys) {
1745  if (key.permissionType != TableDBObjectType &&
1746  key.permissionType != ViewDBObjectType) {
1747  continue;
1748  }
1749  bool found = false;
1750  for (auto obj : objects) {
1751  found = key == obj.getObjectKey() ? true : false;
1752  if (found) {
1753  break;
1754  }
1755  }
1756  if (!found) {
1757  revoke_keys.insert(key);
1758  }
1759  }
1760  for (auto& key : revoke_keys) {
1761  // revoke privs on object since the object is no
1762  // longer used by the dashboard as source
1763  // NOTE(wamsi): Transactionally unsafe
1765  dash_role_name, *rl->findDbObject(key, true), *this);
1766  }
1767  // Update privileges on remaining objects
1768  // NOTE(wamsi): Transactionally unsafe
1769  SysCatalog::instance().grantDBObjectPrivilegesBatch({dash_role_name}, objects, *this);
1770  }
1771 }
void revokeDBObjectPrivileges(const std::string &grantee, const DBObject &object, const Catalog_Namespace::Catalog &catalog)
void createRole(const std::string &roleName, const bool user_private_role, const bool is_temporary=false)
Definition: Grantee.h:81
DBObject * findDbObject(const DBObjectKey &objectKey, bool only_direct) const
Definition: Grantee.cpp:85
static SysCatalog & instance()
Definition: SysCatalog.h:343
Role * getRoleGrantee(const std::string &name) const
void grantDBObjectPrivilegesBatch(const std::vector< std::string > &grantees, const std::vector< DBObject > &objects, const Catalog_Namespace::Catalog &catalog)
const DBObjectMap * getDbObjects(bool only_direct) const
Definition: Grantee.h:56
std::vector< DBObject > parseDashboardObjects(const std::string &view_meta, const int &user_id)
Definition: Catalog.cpp:1697

+ Here is the call graph for this function:

+ Here is the caller graph for this function:

void Catalog_Namespace::Catalog::createShardedTable ( TableDescriptor td,
const std::list< ColumnDescriptor > &  columns,
const std::vector< Parser::SharedDictionaryDef > &  shared_dict_defs 
)

Definition at line 4109 of file Catalog.cpp.

References CHECK, TableDescriptor::nShards, TableDescriptor::shard, table_is_temporary(), TableDescriptor::tableId, and TableDescriptor::tableName.

4112  {
4113  /* create logical table */
4114  TableDescriptor* tdl = &td;
4115  createTable(*tdl, cols, shared_dict_defs, true); // create logical table
4116  int32_t logical_tb_id = tdl->tableId;
4117  std::string logical_table_name = tdl->tableName;
4118 
4119  /* create physical tables and link them to the logical table */
4120  std::vector<int32_t> physicalTables;
4121  for (int32_t i = 1; i <= td.nShards; i++) {
4122  TableDescriptor* tdp = &td;
4123  tdp->tableName = generatePhysicalTableName(logical_table_name, i);
4124  tdp->shard = i - 1;
4125  createTable(*tdp, cols, shared_dict_defs, false); // create physical table
4126  int32_t physical_tb_id = tdp->tableId;
4127 
4128  /* add physical table to the vector of physical tables */
4129  physicalTables.push_back(physical_tb_id);
4130  }
4131 
4132  if (!physicalTables.empty()) {
4133  cat_write_lock write_lock(this);
4134  /* add logical to physical tables correspondence to the map */
4135  const auto it_ok =
4136  logicalToPhysicalTableMapById_.emplace(logical_tb_id, physicalTables);
4137  CHECK(it_ok.second);
4138  /* update sqlite mapd_logical_to_physical in sqlite database */
4139  if (!table_is_temporary(&td)) {
4140  updateLogicalToPhysicalTableMap(logical_tb_id);
4141  }
4142  }
4143 }
std::string tableName
void createTable(TableDescriptor &td, const std::list< ColumnDescriptor > &columns, const std::vector< Parser::SharedDictionaryDef > &shared_dict_defs, bool isLogicalTable)
Definition: Catalog.cpp:2945
bool table_is_temporary(const TableDescriptor *const td)
write_lock< Catalog > cat_write_lock
Definition: Catalog.cpp:125
#define CHECK(condition)
Definition: Logger.h:291
std::string generatePhysicalTableName(const std::string &logicalTableName, const size_t shardNumber)
Definition: Catalog.cpp:5095
LogicalToPhysicalTableMapById logicalToPhysicalTableMapById_
Definition: Catalog.h:727
void updateLogicalToPhysicalTableMap(const int32_t logical_tb_id)
Definition: Catalog.cpp:648

+ Here is the call graph for this function:

void Catalog_Namespace::Catalog::createSystemTableServer ( const std::string &  server_name,
const std::string &  data_wrapper_type,
const foreign_storage::OptionsMap options = {} 
)
private

Definition at line 6856 of file Catalog.cpp.

References logger::INFO, shared::kRootUserId, LOG, and run_benchmark_import::tables.

6858  {
6859  auto server = std::make_unique<foreign_storage::ForeignServer>(
6860  server_name, data_wrapper_type, options, shared::kRootUserId);
6861  server->validate();
6862  auto stored_server = getForeignServer(server_name);
6863  if (stored_server && stored_server->options != server->options) {
6864  // Drop all tables for server before dropping server.
6865  auto tables = getAllForeignTablesForForeignServer(stored_server->id);
6866  for (const auto table : tables) {
6867  LOG(INFO) << "Dropping existing \"" << table->tableName << "\" system table for \""
6868  << server_name << "\" foreign server.";
6869  dropTable(table);
6870  }
6871  LOG(INFO) << "Dropping existing \"" << server_name
6872  << "\" system table foreign server.";
6873  dropForeignServer(server_name);
6874  stored_server = nullptr;
6875  }
6876  if (!stored_server) {
6877  LOG(INFO) << "Creating a new \"" << server_name << "\" system table foreign server.";
6878  createForeignServer(std::move(server), true);
6879  }
6880 }
const int kRootUserId
void createForeignServer(std::unique_ptr< foreign_storage::ForeignServer > foreign_server, bool if_not_exists)
Definition: Catalog.cpp:3293
const foreign_storage::ForeignServer * getForeignServer(const std::string &server_name) const
Definition: Catalog.cpp:3344
#define LOG(tag)
Definition: Logger.h:285
std::vector< const foreign_storage::ForeignTable * > getAllForeignTablesForForeignServer(const int32_t foreign_server_id)
Get all of the foreign tables for associated with a foreign server id.
Definition: Catalog.cpp:3641
void dropForeignServer(const std::string &server_name)
Definition: Catalog.cpp:3460
void dropTable(const TableDescriptor *td)
Definition: Catalog.cpp:4292
void Catalog_Namespace::Catalog::createTable ( TableDescriptor td,
const std::list< ColumnDescriptor > &  columns,
const std::vector< Parser::SharedDictionaryDef > &  shared_dict_defs,
bool  isLogicalTable 
)

Definition at line 2945 of file Catalog.cpp.

References CHECK, ColumnDescriptor::columnId, TableDescriptor::columnIdBySpi_, ColumnDescriptor::columnName, ColumnDescriptor::columnType, ColumnDescriptor::default_value, dict_ref_t::dictId, Data_Namespace::DISK_LEVEL, StorageType::FOREIGN_TABLE, TableDescriptor::fragPageSize, TableDescriptor::fragType, g_enable_fsi, g_serialize_temp_tables, SQLTypeInfo::get_comp_param(), SQLTypeInfo::get_compression(), SQLTypeInfo::get_dimension(), Catalog_Namespace::anonymous_namespace{Catalog.cpp}::get_next_refresh_time(), SQLTypeInfo::get_notnull(), SQLTypeInfo::get_scale(), SQLTypeInfo::get_size(), SQLTypeInfo::get_subtype(), SQLTypeInfo::get_type(), TableDescriptor::hasDeletedCol, SQLTypeInfo::is_array(), TableDescriptor::is_system_table, ColumnDescriptor::isDeletedCol, ColumnDescriptor::isGeoPhyCol, ColumnDescriptor::isSystemCol, TableDescriptor::isView, ColumnDescriptor::isVirtualCol, kBIGINT, kBOOLEAN, kENCODING_DICT, TableDescriptor::keyMetainfo, TableDescriptor::maxChunkSize, TableDescriptor::maxFragRows, TableDescriptor::maxRollbackEpochs, TableDescriptor::maxRows, TableDescriptor::nColumns, foreign_storage::ForeignTable::next_refresh_time, TableDescriptor::nShards, TableDescriptor::partitions, TableDescriptor::persistenceLevel, SQLTypeInfo::set_comp_param(), Catalog_Namespace::anonymous_namespace{Catalog.cpp}::set_dict_key(), SQLTypeInfo::set_size(), TableDescriptor::shard, TableDescriptor::shardedColumnId, TableDescriptor::sortedColumnId, TableDescriptor::storageType, ColumnDescriptor::tableId, TableDescriptor::tableId, TableDescriptor::tableName, to_string(), TableDescriptor::userId, TableDescriptor::viewSQL, and ColumnDescriptor::virtualExpr.

2949  {
2950  cat_write_lock write_lock(this);
2951  list<ColumnDescriptor> cds = cols;
2952  list<DictDescriptor> dds;
2953  std::set<std::string> toplevel_column_names;
2954  list<ColumnDescriptor> columns;
2955 
2956  if (!td.storageType.empty() &&
2959  throw std::runtime_error("Only temporary tables can be backed by foreign storage.");
2960  }
2961  dataMgr_->getForeignStorageInterface()->prepareTable(getCurrentDB().dbId, td, cds);
2962  }
2963 
2964  for (auto cd : cds) {
2965  if (cd.columnName == "rowid") {
2966  throw std::runtime_error(
2967  "Cannot create column with name rowid. rowid is a system defined column.");
2968  }
2969  columns.push_back(cd);
2970  toplevel_column_names.insert(cd.columnName);
2971  if (cd.columnType.is_geometry()) {
2972  expandGeoColumn(cd, columns);
2973  }
2974  }
2975  cds.clear();
2976 
2977  ColumnDescriptor cd;
2978  // add row_id column -- Must be last column in the table
2979  cd.columnName = "rowid";
2980  cd.isSystemCol = true;
2981  cd.columnType = SQLTypeInfo(kBIGINT, true);
2982 #ifdef MATERIALIZED_ROWID
2983  cd.isVirtualCol = false;
2984 #else
2985  cd.isVirtualCol = true;
2986  cd.virtualExpr = "MAPD_FRAG_ID * MAPD_ROWS_PER_FRAG + MAPD_FRAG_ROW_ID";
2987 #endif
2988  columns.push_back(cd);
2989  toplevel_column_names.insert(cd.columnName);
2990 
2991  if (td.hasDeletedCol) {
2992  ColumnDescriptor cd_del;
2993  cd_del.columnName = "$deleted$";
2994  cd_del.isSystemCol = true;
2995  cd_del.isVirtualCol = false;
2996  cd_del.columnType = SQLTypeInfo(kBOOLEAN, true);
2997  cd_del.isDeletedCol = true;
2998 
2999  columns.push_back(cd_del);
3000  }
3001 
3002  for (auto& column : columns) {
3003  column.db_id = getDatabaseId();
3004  }
3005 
3006  td.nColumns = columns.size();
3007  // TODO(sy): don't take disk locks or touch sqlite connector for temporary tables
3008  cat_sqlite_lock sqlite_lock(getObjForLock());
3009  sqliteConnector_.query("BEGIN TRANSACTION");
3011  try {
3013  R"(INSERT INTO mapd_tables (name, userid, ncolumns, isview, fragments, frag_type, max_frag_rows, max_chunk_size, frag_page_size, max_rows, partitions, shard_column_id, shard, num_shards, sort_column_id, storage_type, max_rollback_epochs, is_system_table, key_metainfo) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?))",
3014  std::vector<std::string>{td.tableName,
3015  std::to_string(td.userId),
3017  std::to_string(td.isView),
3018  "",
3023  std::to_string(td.maxRows),
3024  td.partitions,
3026  std::to_string(td.shard),
3027  std::to_string(td.nShards),
3029  td.storageType,
3032  td.keyMetainfo});
3033 
3034  // now get the auto generated tableid
3036  "SELECT tableid FROM mapd_tables WHERE name = ?", td.tableName);
3037  td.tableId = sqliteConnector_.getData<int>(0, 0);
3038  int colId = 1;
3039  for (auto cd : columns) {
3041  const bool is_foreign_col =
3042  setColumnSharedDictionary(cd, cds, dds, td, shared_dict_defs);
3043  if (!is_foreign_col) {
3044  // Ideally we would like to not persist string dictionaries for system tables,
3045  // since system table content can be highly dynamic and string dictionaries
3046  // are not currently vacuumed. However, in distributed this causes issues
3047  // when the cluster is out of sync (when the agg resets but leaves persist) so
3048  // for the sake of testing we need to leave this as normal dictionaries until
3049  // we solve the distributed issue.
3050  auto use_temp_dictionary = false; // td.is_system_table;
3051  setColumnDictionary(cd, dds, td, isLogicalTable, use_temp_dictionary);
3052  }
3053  }
3054 
3055  if (toplevel_column_names.count(cd.columnName)) {
3056  if (!cd.isGeoPhyCol) {
3057  td.columnIdBySpi_.push_back(colId);
3058  }
3059  }
3060 
3061  using BindType = SqliteConnector::BindType;
3062  std::vector<BindType> types(17, BindType::TEXT);
3063  if (!cd.default_value.has_value()) {
3064  types[16] = BindType::NULL_TYPE;
3065  }
3067  "INSERT INTO mapd_columns (tableid, columnid, name, coltype, colsubtype, "
3068  "coldim, colscale, is_notnull, "
3069  "compression, comp_param, size, chunks, is_systemcol, is_virtualcol, "
3070  "virtual_expr, is_deletedcol, default_value) "
3071  "VALUES (?, ?, ?, ?, ?, "
3072  "?, "
3073  "?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)",
3074  std::vector<std::string>{std::to_string(td.tableId),
3075  std::to_string(colId),
3076  cd.columnName,
3085  "",
3088  cd.virtualExpr,
3090  cd.default_value.value_or("NULL")},
3091  types);
3092  cd.tableId = td.tableId;
3093  cd.columnId = colId++;
3094  cds.push_back(cd);
3095  }
3096  if (td.isView) {
3098  "INSERT INTO mapd_views (tableid, sql) VALUES (?,?)",
3099  std::vector<std::string>{std::to_string(td.tableId), td.viewSQL});
3100  }
3102  auto& foreign_table = dynamic_cast<foreign_storage::ForeignTable&>(td);
3103  foreign_table.next_refresh_time = get_next_refresh_time(foreign_table);
3105  "INSERT INTO omnisci_foreign_tables (table_id, server_id, options, "
3106  "last_refresh_time, next_refresh_time) VALUES (?, ?, ?, ?, ?)",
3107  std::vector<std::string>{std::to_string(foreign_table.tableId),
3108  std::to_string(foreign_table.foreign_server->id),
3109  foreign_table.getOptionsAsJsonString(),
3110  std::to_string(foreign_table.last_refresh_time),
3111  std::to_string(foreign_table.next_refresh_time)});
3112  }
3113  } catch (std::exception& e) {
3114  sqliteConnector_.query("ROLLBACK TRANSACTION");
3115  throw;
3116  }
3117  } else { // Temporary table
3118  td.tableId = nextTempTableId_++;
3119  int colId = 1;
3120  for (auto cd : columns) {
3122  const bool is_foreign_col =
3123  setColumnSharedDictionary(cd, cds, dds, td, shared_dict_defs);
3124 
3125  if (!is_foreign_col) {
3126  // Create a new temporary dictionary
3127  std::string fileName("");
3128  std::string folderPath("");
3130  nextTempDictId_++;
3131  DictDescriptor dd(dict_ref,
3132  fileName,
3134  false,
3135  1,
3136  folderPath,
3137  true); // Is dictName (2nd argument) used?
3138  dds.push_back(dd);
3139  if (!cd.columnType.is_array()) {
3141  }
3142  cd.columnType.set_comp_param(dict_ref.dictId);
3143  set_dict_key(cd);
3144  }
3145  }
3146  if (toplevel_column_names.count(cd.columnName)) {
3147  if (!cd.isGeoPhyCol) {
3148  td.columnIdBySpi_.push_back(colId);
3149  }
3150  }
3151  cd.tableId = td.tableId;
3152  cd.columnId = colId++;
3153  cds.push_back(cd);
3154  }
3155 
3157  serializeTableJsonUnlocked(&td, cds);
3158  }
3159  }
3160 
3161  try {
3162  auto cache = dataMgr_->getPersistentStorageMgr()->getDiskCache();
3163  if (cache) {
3164  CHECK(!cache->hasCachedMetadataForKeyPrefix({getCurrentDB().dbId, td.tableId}))
3165  << "Disk cache at " + cache->getCacheDirectory()
3166  << " contains preexisting data for new table. Please "
3167  "delete or clear cache before continuing";
3168  }
3169 
3170  addTableToMap(&td, cds, dds);
3171  calciteMgr_->updateMetadata(currentDB_.dbName, td.tableName);
3172  if (!td.storageType.empty() && td.storageType != StorageType::FOREIGN_TABLE) {
3173  dataMgr_->getForeignStorageInterface()->registerTable(this, td, cds);
3174  }
3175  } catch (std::exception& e) {
3176  sqliteConnector_.query("ROLLBACK TRANSACTION");
3177  removeTableFromMap(td.tableName, td.tableId, true);
3178  throw;
3179  }
3180  sqliteConnector_.query("END TRANSACTION");
3181 
3183  write_lock.unlock();
3184  sqlite_lock.unlock();
3186  true); // cause instantiateFragmenter() to be called
3187  }
3188 }
int32_t maxRollbackEpochs
void serializeTableJsonUnlocked(const TableDescriptor *td, const std::list< ColumnDescriptor > &cds) const
Definition: Catalog.cpp:3190
int64_t get_next_refresh_time(const foreign_storage::ForeignTable &foreign_table)
Definition: Catalog.cpp:2932
std::string virtualExpr
HOST DEVICE SQLTypes get_subtype() const
Definition: sqltypes.h:392
void set_size(int s)
Definition: sqltypes.h:478
std::string partitions
HOST DEVICE int get_size() const
Definition: sqltypes.h:403
T getData(const int row, const int col)
std::string tableName
virtual void query_with_text_params(std::string const &query_only)
SqliteConnector sqliteConnector_
Definition: Catalog.h:720
const DBMetadata currentDB_
Definition: Catalog.h:721
HOST DEVICE int get_scale() const
Definition: sqltypes.h:396
std::string storageType
void setColumnDictionary(ColumnDescriptor &cd, std::list< DictDescriptor > &dds, const TableDescriptor &td, bool is_logical_table, bool use_temp_dictionary=false)
Definition: Catalog.cpp:4066
std::shared_ptr< Data_Namespace::DataMgr > dataMgr_
Definition: Catalog.h:722
virtual void query(const std::string &queryString)
HOST DEVICE SQLTypes get_type() const
Definition: sqltypes.h:391
std::vector< int > columnIdBySpi_
std::string to_string(char const *&&v)
void addTableToMap(const TableDescriptor *td, const std::list< ColumnDescriptor > &columns, const std::list< DictDescriptor > &dicts)
Definition: Catalog.cpp:1545
const DBMetadata & getCurrentDB() const
Definition: Catalog.h:265
int getDatabaseId() const
Definition: Catalog.h:326
specifies the content in-memory of a row in the column metadata table
static void expandGeoColumn(const ColumnDescriptor &cd, std::list< ColumnDescriptor > &columns)
Definition: Catalog.cpp:2784
std::string keyMetainfo
bool g_serialize_temp_tables
Definition: Catalog.cpp:109
void set_comp_param(int p)
Definition: sqltypes.h:482
std::optional< std::string > default_value
std::shared_ptr< Calcite > calciteMgr_
Definition: Catalog.h:725
HOST DEVICE EncodingType get_compression() const
Definition: sqltypes.h:399
Fragmenter_Namespace::FragmenterType fragType
Data_Namespace::MemoryLevel persistenceLevel
const Catalog * getObjForLock()
Definition: Catalog.cpp:260
HOST DEVICE int get_dimension() const
Definition: sqltypes.h:393
void removeTableFromMap(const std::string &tableName, const int tableId, const bool is_on_error=false)
Definition: Catalog.cpp:1604
write_lock< Catalog > cat_write_lock
Definition: Catalog.cpp:125
HOST DEVICE int get_comp_param() const
Definition: sqltypes.h:402
bool setColumnSharedDictionary(ColumnDescriptor &cd, std::list< ColumnDescriptor > &cdd, std::list< DictDescriptor > &dds, const TableDescriptor td, const std::vector< Parser::SharedDictionaryDef > &shared_dict_defs)
Definition: Catalog.cpp:3997
#define CHECK(condition)
Definition: Logger.h:291
Descriptor for a dictionary for a string columne.
std::string viewSQL
SQLTypeInfo columnType
const TableDescriptor * getMetadataForTable(const std::string &tableName, const bool populateFragmenter=true) const
Returns a pointer to a const TableDescriptor struct matching the provided tableName.
HOST DEVICE bool get_notnull() const
Definition: sqltypes.h:398
sqlite_lock< Catalog > cat_sqlite_lock
Definition: Catalog.cpp:126
static constexpr char const * FOREIGN_TABLE
bool g_enable_fsi
Definition: Catalog.cpp:96
std::string columnName
virtual void query_with_text_param(const std::string &queryString, const std::string &text_param)
bool is_array() const
Definition: sqltypes.h:585

+ Here is the call graph for this function:

TableDescriptor * Catalog_Namespace::Catalog::createTableFromDiskUnlocked ( int32_t  table_id)
private

Definition at line 5253 of file Catalog.cpp.

References logger::FATAL, StorageType::FOREIGN_TABLE, LOG, and to_string().

5253  {
5254  std::string query(
5255  "SELECT tableid, name, ncolumns, isview, fragments, frag_type, max_frag_rows, "
5256  "max_chunk_size, frag_page_size, max_rows, partitions, shard_column_id, shard, "
5257  "num_shards, key_metainfo, userid, sort_column_id, storage_type, "
5258  "max_rollback_epochs, is_system_table from mapd_tables WHERE tableid = " +
5259  std::to_string(table_id));
5260  sqliteConnector_.query(query);
5261  auto numRows = sqliteConnector_.getNumRows();
5262  if (!numRows) {
5263  throw NoTableFoundException(table_id);
5264  }
5265 
5266  const auto& storage_type = sqliteConnector_.getData<string>(0, 17);
5267  if (!storage_type.empty() && storage_type != StorageType::FOREIGN_TABLE) {
5268  const auto& table_name = sqliteConnector_.getData<string>(0, 1);
5269  LOG(FATAL) << "Unable to read Catalog metadata: storage type is currently not a "
5270  "supported table option (table "
5271  << table_name << " [" << table_id << "] in database " << currentDB_.dbName
5272  << ").";
5273  }
5274 
5275  // TODO(Misiu): Get rid of manual memory allocation and use smart pointers for
5276  // TableDecriptorMap_. Currently we use a smartpointer to cleanup if we catch
5277  // exceptions during initialization and then release ownership into the existing system.
5278  std::unique_ptr<TableDescriptor> td;
5279  td = (storage_type == StorageType::FOREIGN_TABLE)
5280  ? std::make_unique<foreign_storage::ForeignTable>()
5281  : std::make_unique<TableDescriptor>();
5282 
5283  td->tableId = sqliteConnector_.getData<int>(0, 0);
5284  td->tableName = sqliteConnector_.getData<string>(0, 1);
5285  td->nColumns = sqliteConnector_.getData<int>(0, 2);
5286  td->isView = sqliteConnector_.getData<bool>(0, 3);
5287  td->fragments = sqliteConnector_.getData<string>(0, 4);
5288  td->fragType = static_cast<Fragmenter_Namespace::FragmenterType>(
5289  sqliteConnector_.getData<int>(0, 5));
5290  td->maxFragRows = sqliteConnector_.getData<int>(0, 6);
5291  td->maxChunkSize = sqliteConnector_.getData<int64_t>(0, 7);
5292  td->fragPageSize = sqliteConnector_.getData<int>(0, 8);
5293  td->maxRows = sqliteConnector_.getData<int64_t>(0, 9);
5294  td->partitions = sqliteConnector_.getData<string>(0, 10);
5295  td->shardedColumnId = sqliteConnector_.getData<int>(0, 11);
5296  td->shard = sqliteConnector_.getData<int>(0, 12);
5297  td->nShards = sqliteConnector_.getData<int>(0, 13);
5298  td->keyMetainfo = sqliteConnector_.getData<string>(0, 14);
5299  td->userId = sqliteConnector_.getData<int>(0, 15);
5300  td->sortedColumnId =
5301  sqliteConnector_.isNull(0, 16) ? 0 : sqliteConnector_.getData<int>(0, 16);
5302  td->storageType = storage_type;
5303  td->maxRollbackEpochs = sqliteConnector_.getData<int>(0, 18);
5304  td->is_system_table = sqliteConnector_.getData<bool>(0, 19);
5305  td->hasDeletedCol = false;
5306 
5307  if (td->isView) {
5308  updateViewUnlocked(*td);
5309  } else {
5310  td->fragmenter = nullptr;
5311  }
5312 
5313  if (auto ftd = dynamic_cast<foreign_storage::ForeignTable*>(td.get())) {
5315  }
5316 
5317  return td.release();
5318 }
void updateViewUnlocked(TableDescriptor &)
Definition: Catalog.cpp:1398
T getData(const int row, const int col)
#define LOG(tag)
Definition: Logger.h:285
SqliteConnector sqliteConnector_
Definition: Catalog.h:720
const DBMetadata currentDB_
Definition: Catalog.h:721
virtual void query(const std::string &queryString)
std::string to_string(char const *&&v)
void reloadForeignTableUnlocked(foreign_storage::ForeignTable &foreign_table)
Definition: Catalog.cpp:5152
bool isNull(const int row, const int col) const
static constexpr char const * FOREIGN_TABLE
virtual size_t getNumRows() const

+ Here is the call graph for this function:

void Catalog_Namespace::Catalog::delDictionaryNontransactional ( const ColumnDescriptor cd)
private

Definition at line 2290 of file Catalog.cpp.

References CHECK, CHECK_GT, ColumnDescriptor::columnType, g_base_path, SQLTypeInfo::get_comp_param(), SQLTypeInfo::get_compression(), SQLTypeInfo::is_string(), SQLTypeInfo::is_string_array(), shared::kDataDirectoryName, kENCODING_DICT, File_Namespace::renameForDelete(), ColumnDescriptor::tableId, to_string(), and VLOG.

2290  {
2291  cat_write_lock write_lock(this);
2292  cat_sqlite_lock sqlite_lock(getObjForLock());
2293  if (!(cd.columnType.is_string() || cd.columnType.is_string_array())) {
2294  return;
2295  }
2296  if (!(cd.columnType.get_compression() == kENCODING_DICT)) {
2297  return;
2298  }
2299  const auto dictId = cd.columnType.get_comp_param();
2300  CHECK_GT(dictId, 0);
2301  // decrement and zero check dict ref count
2302  const auto td = getMetadataForTable(cd.tableId, false);
2303  CHECK(td);
2305  "UPDATE mapd_dictionaries SET refcount = refcount - 1 WHERE dictid = ?",
2306  std::to_string(dictId));
2308  "SELECT refcount FROM mapd_dictionaries WHERE dictid = ?", std::to_string(dictId));
2309  const auto refcount = sqliteConnector_.getData<int>(0, 0);
2310  VLOG(3) << "Dictionary " << dictId << "from dropped table has reference count "
2311  << refcount;
2312  if (refcount > 0) {
2313  return;
2314  }
2315  const DictRef dictRef(currentDB_.dbId, dictId);
2316  sqliteConnector_.query_with_text_param("DELETE FROM mapd_dictionaries WHERE dictid = ?",
2317  std::to_string(dictId));
2319  "/DB_" + std::to_string(currentDB_.dbId) + "_DICT_" +
2320  std::to_string(dictId));
2321 
2322  std::unique_ptr<StringDictionaryClient> client;
2323  if (!string_dict_hosts_.empty()) {
2324  client.reset(new StringDictionaryClient(string_dict_hosts_.front(), dictRef, true));
2325  }
2326  if (client) {
2327  client->drop(dictRef);
2328  }
2329 
2330  dictDescriptorMapByRef_.erase(dictRef);
2331 }
const std::string kDataDirectoryName
T getData(const int row, const int col)
SqliteConnector sqliteConnector_
Definition: Catalog.h:720
const std::vector< LeafHostInfo > string_dict_hosts_
Definition: Catalog.h:724
const DBMetadata currentDB_
Definition: Catalog.h:721
DictDescriptorMapById dictDescriptorMapByRef_
Definition: Catalog.h:711
#define CHECK_GT(x, y)
Definition: Logger.h:305
std::string to_string(char const *&&v)
std::string g_base_path
Definition: SysCatalog.cpp:62
HOST DEVICE EncodingType get_compression() const
Definition: sqltypes.h:399
const Catalog * getObjForLock()
Definition: Catalog.cpp:260
write_lock< Catalog > cat_write_lock
Definition: Catalog.cpp:125
HOST DEVICE int get_comp_param() const
Definition: sqltypes.h:402
#define CHECK(condition)
Definition: Logger.h:291
SQLTypeInfo columnType
const TableDescriptor * getMetadataForTable(const std::string &tableName, const bool populateFragmenter=true) const
Returns a pointer to a const TableDescriptor struct matching the provided tableName.
bool is_string() const
Definition: sqltypes.h:561
void renameForDelete(const std::string directoryName)
Renames a directory to DELETE_ME_&lt;EPOCH&gt;_&lt;oldname&gt;.
Definition: File.cpp:210
sqlite_lock< Catalog > cat_sqlite_lock
Definition: Catalog.cpp:126
bool is_string_array() const
Definition: sqltypes.h:564
virtual void query_with_text_param(const std::string &queryString, const std::string &text_param)
#define VLOG(n)
Definition: Logger.h:388

+ Here is the call graph for this function:

void Catalog_Namespace::Catalog::delDictionaryTransactional ( const ColumnDescriptor cd)

Definition at line 2277 of file Catalog.cpp.

Referenced by AlterTableAlterColumnCommandRecoveryMgr::cleanupDeleteDictionaries(), and AlterTableAlterColumnCommandRecoveryMgr::rollback().

2277  {
2278  cat_write_lock write_lock(this);
2279  cat_sqlite_lock sqlite_lock(this);
2280  sqliteConnector_.query("BEGIN TRANSACTION");
2281  try {
2283  } catch (std::exception& e) {
2284  sqliteConnector_.query("ROLLBACK TRANSACTION");
2285  throw;
2286  }
2287  sqliteConnector_.query("END TRANSACTION");
2288 }
SqliteConnector sqliteConnector_
Definition: Catalog.h:720
virtual void query(const std::string &queryString)
write_lock< Catalog > cat_write_lock
Definition: Catalog.cpp:125
void delDictionaryNontransactional(const ColumnDescriptor &cd)
Definition: Catalog.cpp:2290
sqlite_lock< Catalog > cat_sqlite_lock
Definition: Catalog.cpp:126

+ Here is the caller graph for this function:

void Catalog_Namespace::Catalog::deleteCustomExpressions ( const std::vector< int32_t > &  custom_expression_ids,
bool  do_soft_delete 
)

Deletes custom expressions with the given ids.

Parameters
custom_expression_ids- ids of custom expressions to delete
do_soft_delete- flag indicating whether or not to do a soft delete

Definition at line 6079 of file Catalog.cpp.

References CHECK, CHECK_EQ, join(), and to_string().

6080  {
6081  cat_write_lock write_lock(this);
6082  cat_sqlite_lock sqlite_lock(getObjForLock());
6083 
6084  std::vector<int32_t> invalid_ids;
6085  for (const auto id : custom_expression_ids) {
6086  if (custom_expr_map_by_id_.find(id) == custom_expr_map_by_id_.end()) {
6087  invalid_ids.emplace_back(id);
6088  }
6089  }
6090  if (!invalid_ids.empty()) {
6091  throw std::runtime_error{"Custom expressions with ids: " + join(invalid_ids, ",") +
6092  " do not exist."};
6093  }
6094  sqliteConnector_.query("BEGIN TRANSACTION");
6095  try {
6096  for (const auto id : custom_expression_ids) {
6098  "SELECT id FROM omnisci_custom_expressions WHERE id = ?",
6099  std::vector<std::string>{std::to_string(id)});
6100  CHECK_EQ(sqliteConnector_.getNumRows(), static_cast<size_t>(1));
6101  if (do_soft_delete) {
6103  "UPDATE omnisci_custom_expressions SET is_deleted = ? WHERE id = ?",
6104  std::vector<std::string>{std::to_string(true), std::to_string(id)});
6105  } else {
6107  "DELETE FROM omnisci_custom_expressions WHERE id = ?",
6108  std::vector<std::string>{std::to_string(id)});
6109  }
6110  }
6111 
6112  for (const auto id : custom_expression_ids) {
6113  if (do_soft_delete) {
6114  auto it = custom_expr_map_by_id_.find(id);
6115  CHECK(it != custom_expr_map_by_id_.end());
6116  it->second->is_deleted = true;
6117  } else {
6118  custom_expr_map_by_id_.erase(id);
6119  }
6120  }
6121  } catch (std::exception& e) {
6122  sqliteConnector_.query("ROLLBACK TRANSACTION");
6123  throw;
6124  }
6125  sqliteConnector_.query("END TRANSACTION");
6126 }
#define CHECK_EQ(x, y)
Definition: Logger.h:301
virtual void query_with_text_params(std::string const &query_only)
SqliteConnector sqliteConnector_
Definition: Catalog.h:720
std::string join(T const &container, std::string const &delim)
virtual void query(const std::string &queryString)
std::string to_string(char const *&&v)
const Catalog * getObjForLock()
Definition: Catalog.cpp:260
write_lock< Catalog > cat_write_lock
Definition: Catalog.cpp:125
#define CHECK(condition)
Definition: Logger.h:291
CustomExpressionMapById custom_expr_map_by_id_
Definition: Catalog.h:717
sqlite_lock< Catalog > cat_sqlite_lock
Definition: Catalog.cpp:126
virtual size_t getNumRows() const

+ Here is the call graph for this function:

void Catalog_Namespace::Catalog::deleteMetadataForDashboards ( const std::vector< int32_t >  ids,
const UserMetadata user 
)

Definition at line 2014 of file Catalog.cpp.

References DashboardDBObjectType, AccessPrivileges::DELETE_DASHBOARD, lockmgr::instance(), and to_string().

2015  {
2016  std::stringstream invalid_ids, restricted_ids;
2017 
2018  for (int32_t dashboard_id : dashboard_ids) {
2019  if (!getMetadataForDashboard(dashboard_id)) {
2020  invalid_ids << (!invalid_ids.str().empty() ? ", " : "") << dashboard_id;
2021  continue;
2022  }
2023  DBObject object(dashboard_id, DashboardDBObjectType);
2024  object.loadKey(*this);
2025  object.setPrivileges(AccessPrivileges::DELETE_DASHBOARD);
2026  std::vector<DBObject> privs = {object};
2027  if (!SysCatalog::instance().checkPrivileges(user, privs)) {
2028  restricted_ids << (!restricted_ids.str().empty() ? ", " : "") << dashboard_id;
2029  }
2030  }
2031 
2032  if (invalid_ids.str().size() > 0 || restricted_ids.str().size() > 0) {
2033  std::stringstream error_message;
2034  error_message << "Delete dashboard(s) failed with error(s):";
2035  if (invalid_ids.str().size() > 0) {
2036  error_message << "\nDashboard id: " << invalid_ids.str()
2037  << " - Dashboard id does not exist";
2038  }
2039  if (restricted_ids.str().size() > 0) {
2040  error_message
2041  << "\nDashboard id: " << restricted_ids.str()
2042  << " - User should be either owner of dashboard or super user to delete it";
2043  }
2044  throw std::runtime_error(error_message.str());
2045  }
2046  std::vector<DBObject> dash_objs;
2047 
2048  for (int32_t dashboard_id : dashboard_ids) {
2049  dash_objs.emplace_back(dashboard_id, DashboardDBObjectType);
2050  }
2051  // BE-5245: Transactionally unsafe (like other combined Catalog/Syscatalog operations)
2053  {
2054  cat_write_lock write_lock(this);
2055  cat_sqlite_lock sqlite_lock(getObjForLock());
2056 
2057  sqliteConnector_.query("BEGIN TRANSACTION");
2058  try {
2059  for (int32_t dashboard_id : dashboard_ids) {
2060  auto dash = getMetadataForDashboard(dashboard_id);
2061  // Dash should still exist if revokeDBObjectPrivileges passed but throw and
2062  // rollback if already deleted
2063  if (!dash) {
2064  throw std::runtime_error(
2065  std::string("Delete dashboard(s) failed with error(s):\nDashboard id: ") +
2066  std::to_string(dashboard_id) + " - Dashboard id does not exist ");
2067  }
2068  std::string user_id = std::to_string(dash->userId);
2069  std::string dash_name = dash->dashboardName;
2070  auto viewDescIt = dashboardDescriptorMap_.find(user_id + ":" + dash_name);
2071  dashboardDescriptorMap_.erase(viewDescIt);
2073  "DELETE FROM mapd_dashboards WHERE name = ? and userid = ?",
2074  std::vector<std::string>{dash_name, user_id});
2075  }
2076  } catch (std::exception& e) {
2077  sqliteConnector_.query("ROLLBACK TRANSACTION");
2078  throw;
2079  }
2080  sqliteConnector_.query("END TRANSACTION");
2081  }
2082 }
virtual void query_with_text_params(std::string const &query_only)
SqliteConnector sqliteConnector_
Definition: Catalog.h:720
virtual void query(const std::string &queryString)
DashboardDescriptorMap dashboardDescriptorMap_
Definition: Catalog.h:712
std::string to_string(char const *&&v)
static SysCatalog & instance()
Definition: SysCatalog.h:343
const DashboardDescriptor * getMetadataForDashboard(const std::string &userId, const std::string &dashName) const
const Catalog * getObjForLock()
Definition: Catalog.cpp:260
write_lock< Catalog > cat_write_lock
Definition: Catalog.cpp:125
static const AccessPrivileges DELETE_DASHBOARD
Definition: DBObject.h:173
sqlite_lock< Catalog > cat_sqlite_lock
Definition: Catalog.cpp:126
void revokeDBObjectPrivilegesFromAllBatch(std::vector< DBObject > &objects, Catalog *catalog)

+ Here is the call graph for this function:

void Catalog_Namespace::Catalog::deleteTableCatalogMetadata ( const TableDescriptor logical_table,
const std::vector< const TableDescriptor * > &  physical_tables 
)
private

Definition at line 4320 of file Catalog.cpp.

References TableDescriptor::tableId, and to_string().

4322  {
4323  cat_write_lock write_lock(this);
4324  cat_sqlite_lock sqlite_lock(getObjForLock());
4325  sqliteConnector_.query("BEGIN TRANSACTION");
4326  try {
4327  // remove corresponding record from the logicalToPhysicalTableMap in sqlite database
4329  "DELETE FROM mapd_logical_to_physical WHERE logical_table_id = ?",
4330  std::to_string(logical_table->tableId));
4331  logicalToPhysicalTableMapById_.erase(logical_table->tableId);
4332  for (auto table : physical_tables) {
4333  eraseTableMetadata(table);
4334  }
4335  } catch (std::exception& e) {
4336  sqliteConnector_.query("ROLLBACK TRANSACTION");
4337  throw;
4338  }
4339  sqliteConnector_.query("END TRANSACTION");
4340 }
SqliteConnector sqliteConnector_
Definition: Catalog.h:720
virtual void query(const std::string &queryString)
std::string to_string(char const *&&v)
const Catalog * getObjForLock()
Definition: Catalog.cpp:260
write_lock< Catalog > cat_write_lock
Definition: Catalog.cpp:125
void eraseTableMetadata(const TableDescriptor *td)
Definition: Catalog.cpp:4342
sqlite_lock< Catalog > cat_sqlite_lock
Definition: Catalog.cpp:126
virtual void query_with_text_param(const std::string &queryString, const std::string &text_param)
LogicalToPhysicalTableMapById logicalToPhysicalTableMapById_
Definition: Catalog.h:727

+ Here is the call graph for this function:

void Catalog_Namespace::Catalog::doTruncateTable ( const TableDescriptor td)
protected

Definition at line 4153 of file Catalog.cpp.

References CHECK, CHECK_GE, ColumnDescriptor::columnType, Data_Namespace::CPU_LEVEL, dict_ref_t::dictId, DictDescriptor::dictIsTemp, DictDescriptor::dictRef, SQLTypeInfo::get_comp_param(), SQLTypeInfo::get_compression(), Data_Namespace::GPU_LEVEL, lockmgr::instance(), kENCODING_DICT, File_Namespace::renameForDelete(), ColumnDescriptor::tableId, and TableDescriptor::tableId.

4153  {
4154  // must destroy fragmenter before deleteChunks is called.
4156 
4157  const int tableId = td->tableId;
4158  ChunkKey chunkKeyPrefix = {currentDB_.dbId, tableId};
4159  // assuming deleteChunksWithPrefix is atomic
4160  dataMgr_->deleteChunksWithPrefix(chunkKeyPrefix, MemoryLevel::CPU_LEVEL);
4161  dataMgr_->deleteChunksWithPrefix(chunkKeyPrefix, MemoryLevel::GPU_LEVEL);
4162 
4163  dataMgr_->removeTableRelatedDS(currentDB_.dbId, tableId);
4164 
4165  cat_write_lock write_lock(this);
4166  std::unique_ptr<StringDictionaryClient> client;
4167  if (SysCatalog::instance().isAggregator()) {
4168  CHECK(!string_dict_hosts_.empty());
4169  DictRef dict_ref(currentDB_.dbId, -1);
4170  client.reset(new StringDictionaryClient(string_dict_hosts_.front(), dict_ref, true));
4171  }
4172  // clean up any dictionaries
4173  // delete all column descriptors for the table
4174  for (const auto& columnDescriptor : columnDescriptorMapById_) {
4175  auto cd = columnDescriptor.second;
4176  if (cd->tableId != td->tableId) {
4177  continue;
4178  }
4179  const int dict_id = cd->columnType.get_comp_param();
4180  // Dummy dictionaries created for a shard of a logical table have the id set to zero.
4181  if (cd->columnType.get_compression() == kENCODING_DICT && dict_id) {
4182  const DictRef dict_ref(currentDB_.dbId, dict_id);
4183  const auto dictIt = dictDescriptorMapByRef_.find(dict_ref);
4184  CHECK(dictIt != dictDescriptorMapByRef_.end());
4185  const auto& dd = dictIt->second;
4186  CHECK_GE(dd->refcount, 1);
4187  // if this is the only table using this dict reset the dict
4188  if (dd->refcount == 1) {
4189  // close the dictionary
4190  dd->stringDict.reset();
4191  File_Namespace::renameForDelete(dd->dictFolderPath);
4192  if (client) {
4193  client->drop(dd->dictRef);
4194  }
4195  if (!dd->dictIsTemp) {
4196  boost::filesystem::create_directory(dd->dictFolderPath);
4197  }
4198  }
4199 
4200  DictDescriptor* new_dd = new DictDescriptor(dd->dictRef,
4201  dd->dictName,
4202  dd->dictNBits,
4203  dd->dictIsShared,
4204  dd->refcount,
4205  dd->dictFolderPath,
4206  dd->dictIsTemp);
4207  dictDescriptorMapByRef_.erase(dictIt);
4208  // now create new Dict -- need to figure out what to do here for temp tables
4209  if (client) {
4210  client->create(new_dd->dictRef, new_dd->dictIsTemp);
4211  }
4212  dictDescriptorMapByRef_[new_dd->dictRef].reset(new_dd);
4214  }
4215  }
4216 }
std::vector< int > ChunkKey
Definition: types.h:36
const std::vector< LeafHostInfo > string_dict_hosts_
Definition: Catalog.h:724
const DBMetadata currentDB_
Definition: Catalog.h:721
DictDescriptorMapById dictDescriptorMapByRef_
Definition: Catalog.h:711
std::shared_ptr< Data_Namespace::DataMgr > dataMgr_
Definition: Catalog.h:722
#define CHECK_GE(x, y)
Definition: Logger.h:306
ColumnDescriptorMapById columnDescriptorMapById_
Definition: Catalog.h:710
static SysCatalog & instance()
Definition: SysCatalog.h:343
const DictDescriptor * getMetadataForDict(int dict_ref, bool loadDict=true) const
Definition: Catalog.cpp:1907
int32_t dictId
Definition: DictRef.h:14
write_lock< Catalog > cat_write_lock
Definition: Catalog.cpp:125
void removeFragmenterForTable(const int table_id) const
Definition: Catalog.cpp:4270
#define CHECK(condition)
Definition: Logger.h:291
Descriptor for a dictionary for a string columne.
void renameForDelete(const std::string directoryName)
Renames a directory to DELETE_ME_&lt;EPOCH&gt;_&lt;oldname&gt;.
Definition: File.cpp:210

+ Here is the call graph for this function:

void Catalog_Namespace::Catalog::dropColumn ( const TableDescriptor td,
const ColumnDescriptor cd 
)

Definition at line 2663 of file Catalog.cpp.

References CHECK, ColumnDescriptor::columnId, ColumnDescriptor::columnName, TableDescriptor::nShards, TableDescriptor::shard, ColumnDescriptor::tableId, TableDescriptor::tableId, to_string(), and to_upper().

2663  {
2664  {
2665  cat_write_lock write_lock(this);
2666  cat_sqlite_lock sqlite_lock(getObjForLock());
2667  // caller must handle sqlite/chunk transaction TOGETHER
2669  "DELETE FROM mapd_columns where tableid = ? and columnid = ?",
2670  std::vector<std::string>{std::to_string(td.tableId),
2671  std::to_string(cd.columnId)});
2672 
2674  "UPDATE mapd_tables SET ncolumns = ncolumns - 1 WHERE tableid = ?",
2675  std::vector<std::string>{std::to_string(td.tableId)});
2676 
2677  ColumnDescriptorMap::iterator columnDescIt =
2679  CHECK(columnDescIt != columnDescriptorMap_.end());
2680 
2681  columnDescriptorsForRoll.emplace_back(columnDescIt->second, nullptr);
2682  removeFromColumnMap(columnDescIt->second);
2683  --tableDescriptorMapById_[td.tableId]->nColumns;
2684  }
2685 
2686  // for each shard
2687  if (td.nShards > 0 && td.shard < 0) {
2688  for (const auto shard : getPhysicalTablesDescriptors(&td)) {
2689  const auto shard_cd = getMetadataForColumn(shard->tableId, cd.columnId);
2690  CHECK(shard_cd);
2691  dropColumn(*shard, *shard_cd);
2692  }
2693  }
2694 }
void removeFromColumnMap(ColumnDescriptor *cd)
Definition: Catalog.cpp:7015
std::tuple< int, std::string > ColumnKey
Definition: Types.h:37
ColumnDescriptorMap columnDescriptorMap_
Definition: Catalog.h:709
virtual void query_with_text_params(std::string const &query_only)
SqliteConnector sqliteConnector_
Definition: Catalog.h:720
void dropColumn(const TableDescriptor &td, const ColumnDescriptor &cd)
Definition: Catalog.cpp:2663
std::string to_string(char const *&&v)
const ColumnDescriptor * getMetadataForColumn(int tableId, const std::string &colName) const
TableDescriptorMapById tableDescriptorMapById_
Definition: Catalog.h:708
std::vector< const TableDescriptor * > getPhysicalTablesDescriptors(const TableDescriptor *logical_table_desc, bool populate_fragmenter=true) const
Definition: Catalog.cpp:4879
std::string to_upper(const std::string &str)
const Catalog * getObjForLock()
Definition: Catalog.cpp:260
write_lock< Catalog > cat_write_lock
Definition: Catalog.cpp:125
#define CHECK(condition)
Definition: Logger.h:291
sqlite_lock< Catalog > cat_sqlite_lock
Definition: Catalog.cpp:126
ColumnDescriptorsForRoll columnDescriptorsForRoll
Definition: Catalog.h:739
std::string columnName

+ Here is the call graph for this function:

void Catalog_Namespace::Catalog::dropColumnNontransactional ( const TableDescriptor td,
const ColumnDescriptor cd 
)

Definition at line 2617 of file Catalog.cpp.

References CHECK, ColumnDescriptor::columnId, ColumnDescriptor::columnName, TableDescriptor::nShards, TableDescriptor::shard, ColumnDescriptor::tableId, TableDescriptor::tableId, TableDescriptor::tableName, to_string(), and to_upper().

2618  {
2619  cat_write_lock write_lock(this);
2620  cat_sqlite_lock sqlite_lock(this);
2621 
2623  "DELETE FROM mapd_columns where tableid = ? and columnid = ?",
2624  std::vector<std::string>{std::to_string(td.tableId), std::to_string(cd.columnId)});
2625 
2627  "UPDATE mapd_tables SET ncolumns = ncolumns - 1 WHERE tableid = ?",
2628  std::vector<std::string>{std::to_string(td.tableId)});
2629 
2630  ColumnDescriptorMap::iterator columnDescIt =
2632  CHECK(columnDescIt != columnDescriptorMap_.end());
2633 
2634  auto ocd = columnDescIt->second;
2635  removeFromColumnMap(ocd);
2636  --tableDescriptorMapById_[td.tableId]->nColumns;
2638  calciteMgr_->updateMetadata(currentDB_.dbName, td.tableName);
2639 
2640  // for each shard
2641  if (td.nShards > 0 && td.shard < 0) {
2642  for (const auto shard : getPhysicalTablesDescriptors(&td)) {
2643  const auto shard_cd = getMetadataForColumn(shard->tableId, cd.columnId);
2644  CHECK(shard_cd);
2645  dropColumnNontransactional(*shard, *shard_cd);
2646  }
2647  }
2648 }
void removeFromColumnMap(ColumnDescriptor *cd)
Definition: Catalog.cpp:7015
std::tuple< int, std::string > ColumnKey
Definition: Types.h:37
std::string tableName
ColumnDescriptorMap columnDescriptorMap_
Definition: Catalog.h:709
virtual void query_with_text_params(std::string const &query_only)
SqliteConnector sqliteConnector_
Definition: Catalog.h:720
const DBMetadata currentDB_
Definition: Catalog.h:721
std::string to_string(char const *&&v)
void removeColumnDescriptor(const ColumnDescriptor *cd)
Definition: Catalog.cpp:2696
const ColumnDescriptor * getMetadataForColumn(int tableId, const std::string &colName) const
TableDescriptorMapById tableDescriptorMapById_
Definition: Catalog.h:708
std::vector< const TableDescriptor * > getPhysicalTablesDescriptors(const TableDescriptor *logical_table_desc, bool populate_fragmenter=true) const
Definition: Catalog.cpp:4879
std::string to_upper(const std::string &str)
std::shared_ptr< Calcite > calciteMgr_
Definition: Catalog.h:725
write_lock< Catalog > cat_write_lock
Definition: Catalog.cpp:125
#define CHECK(condition)
Definition: Logger.h:291
sqlite_lock< Catalog > cat_sqlite_lock
Definition: Catalog.cpp:126
std::string columnName
void dropColumnNontransactional(const TableDescriptor &td, const ColumnDescriptor &cd)
Definition: Catalog.cpp:2617

+ Here is the call graph for this function:

void Catalog_Namespace::Catalog::dropColumnPolicies ( const TableDescriptor td,
const ColumnDescriptor cd 
)

Definition at line 2650 of file Catalog.cpp.

References CHECK, ColumnDescriptor::columnId, TableDescriptor::nShards, and TableDescriptor::shard.

2650  {
2651 
2652  // for each shard
2653  if (td.nShards > 0 && td.shard < 0) {
2654  for (const auto shard : getPhysicalTablesDescriptors(&td)) {
2655  const auto shard_cd = getMetadataForColumn(shard->tableId, cd.columnId);
2656  CHECK(shard_cd);
2657  dropColumnPolicies(*shard, *shard_cd);
2658  }
2659  }
2660 }
const ColumnDescriptor * getMetadataForColumn(int tableId, const std::string &colName) const
std::vector< const TableDescriptor * > getPhysicalTablesDescriptors(const TableDescriptor *logical_table_desc, bool populate_fragmenter=true) const
Definition: Catalog.cpp:4879
void dropColumnPolicies(const TableDescriptor &td, const ColumnDescriptor &cd)
Definition: Catalog.cpp:2650
#define CHECK(condition)
Definition: Logger.h:291
void Catalog_Namespace::Catalog::dropColumnTransactional ( const TableDescriptor td,
const ColumnDescriptor cd 
)

Definition at line 2601 of file Catalog.cpp.

Referenced by AlterTableAlterColumnCommandRecoveryMgr::cleanupDropSourceGeoColumns(), and AlterTableAlterColumnCommandRecoveryMgr::rollback().

2602  {
2603  dropColumnPolicies(td, cd);
2604 
2605  cat_write_lock write_lock(this);
2606  cat_sqlite_lock sqlite_lock(this);
2607  sqliteConnector_.query("BEGIN TRANSACTION");
2608  try {
2610  } catch (std::exception& e) {
2611  sqliteConnector_.query("ROLLBACK TRANSACTION");
2612  throw;
2613  }
2614  sqliteConnector_.query("END TRANSACTION");
2615 }
SqliteConnector sqliteConnector_
Definition: Catalog.h:720
virtual void query(const std::string &queryString)
void dropColumnPolicies(const TableDescriptor &td, const ColumnDescriptor &cd)
Definition: Catalog.cpp:2650
write_lock< Catalog > cat_write_lock
Definition: Catalog.cpp:125
sqlite_lock< Catalog > cat_sqlite_lock
Definition: Catalog.cpp:126
void dropColumnNontransactional(const TableDescriptor &td, const ColumnDescriptor &cd)
Definition: Catalog.cpp:2617

+ Here is the caller graph for this function:

void Catalog_Namespace::Catalog::dropForeignServer ( const std::string &  server_name)

Drops/deletes a foreign server DB object.

Parameters
server_name- Name of foreign server that will be deleted

Definition at line 3460 of file Catalog.cpp.

References CHECK_EQ, and to_string().

3460  {
3461  cat_write_lock write_lock(this);
3462  cat_sqlite_lock sqlite_lock(getObjForLock());
3463 
3465  "SELECT id from omnisci_foreign_servers where name = ?",
3466  std::vector<std::string>{server_name});
3467  auto num_rows = sqliteConnector_.getNumRows();
3468  if (num_rows > 0) {
3469  CHECK_EQ(size_t(1), num_rows);
3470  auto server_id = sqliteConnector_.getData<int32_t>(0, 0);
3472  "SELECT table_id from omnisci_foreign_tables where server_id = ?",
3473  std::to_string(server_id));
3474  if (sqliteConnector_.getNumRows() > 0) {
3475  throw std::runtime_error{"Foreign server \"" + server_name +
3476  "\" is referenced "
3477  "by existing foreign tables and cannot be dropped."};
3478  }
3479  sqliteConnector_.query("BEGIN TRANSACTION");
3480  try {
3482  "DELETE FROM omnisci_foreign_servers WHERE name = ?",
3483  std::vector<std::string>{server_name});
3484  } catch (const std::exception& e) {
3485  sqliteConnector_.query("ROLLBACK TRANSACTION");
3486  throw;
3487  }
3488  sqliteConnector_.query("END TRANSACTION");
3489  foreignServerMap_.erase(server_name);
3490  foreignServerMapById_.erase(server_id);
3491  }
3492 }
#define CHECK_EQ(x, y)
Definition: Logger.h:301
T getData(const int row, const int col)
virtual void query_with_text_params(std::string const &query_only)
SqliteConnector sqliteConnector_
Definition: Catalog.h:720
virtual void query(const std::string &queryString)
std::string to_string(char const *&&v)
ForeignServerMapById foreignServerMapById_
Definition: Catalog.h:716
ForeignServerMap foreignServerMap_
Definition: Catalog.h:715
const Catalog * getObjForLock()
Definition: Catalog.cpp:260
write_lock< Catalog > cat_write_lock
Definition: Catalog.cpp:125
sqlite_lock< Catalog > cat_sqlite_lock
Definition: Catalog.cpp:126
virtual void query_with_text_param(const std::string &queryString, const std::string &text_param)
virtual size_t getNumRows() const

+ Here is the call graph for this function:

void Catalog_Namespace::Catalog::dropTable ( const TableDescriptor td)

Definition at line 4292 of file Catalog.cpp.

References CHECK, lockmgr::instance(), TableDescriptor::isView, TableDBObjectType, TableDescriptor::tableId, TableDescriptor::tableName, and ViewDBObjectType.

Referenced by Catalog_Namespace::anonymous_namespace{Catalog.cpp}::drop_tables().

4292  {
4295  std::vector<const TableDescriptor*> tables_to_drop;
4296  {
4297  cat_read_lock read_lock(this);
4298  const auto physicalTableIt = logicalToPhysicalTableMapById_.find(td->tableId);
4299  if (physicalTableIt != logicalToPhysicalTableMapById_.end()) {
4300  // remove all corresponding physical tables if this is a logical table
4301  const auto physicalTables = physicalTableIt->second;
4302  CHECK(!physicalTables.empty());
4303  for (size_t i = 0; i < physicalTables.size(); i++) {
4304  int32_t physical_tb_id = physicalTables[i];
4305  const TableDescriptor* phys_td =
4306  getMutableMetadataForTableUnlocked(physical_tb_id);
4307  CHECK(phys_td);
4308  tables_to_drop.emplace_back(phys_td);
4309  }
4310  }
4311  tables_to_drop.emplace_back(td);
4312  }
4313 
4314  for (auto table : tables_to_drop) {
4315  eraseTablePhysicalData(table);
4316  }
4317  deleteTableCatalogMetadata(td, tables_to_drop);
4318 }
void eraseTablePhysicalData(const TableDescriptor *td)
Definition: Catalog.cpp:5077
std::string tableName
void revokeDBObjectPrivilegesFromAll(DBObject object, Catalog *catalog)
read_lock< Catalog > cat_read_lock
Definition: Catalog.cpp:124
void deleteTableCatalogMetadata(const TableDescriptor *logical_table, const std::vector< const TableDescriptor * > &physical_tables)
Definition: Catalog.cpp:4320
TableDescriptor * getMutableMetadataForTableUnlocked(int table_id) const
Definition: Catalog.cpp:1899
static SysCatalog & instance()
Definition: SysCatalog.h:343
#define CHECK(condition)
Definition: Logger.h:291
LogicalToPhysicalTableMapById logicalToPhysicalTableMapById_
Definition: Catalog.h:727

+ Here is the call graph for this function:

+ Here is the caller graph for this function:

void Catalog_Namespace::Catalog::dropTableFromJsonUnlocked ( const std::string &  table_name) const
protected

Definition at line 3261 of file Catalog.cpp.

References CHECK, Catalog_Namespace::anonymous_namespace{Catalog.cpp}::table_json_filepath(), and VLOG.

3261  {
3262  // relies on the catalog write lock
3263  using namespace rapidjson;
3264 
3265  VLOG(1) << "Dropping temporary table " << table_name << " to JSON for Calcite.";
3266 
3267  const auto db_name = currentDB_.dbName;
3268  const auto file_path = table_json_filepath(basePath_, db_name);
3269 
3270  CHECK(boost::filesystem::exists(file_path));
3271  Document d;
3272 
3273  std::ifstream reader(file_path.string());
3274  CHECK(reader.is_open());
3275  IStreamWrapper json_read_wrapper(reader);
3276  d.ParseStream(json_read_wrapper);
3277 
3278  CHECK(d.IsObject());
3279  auto table_name_ref = StringRef(table_name.c_str());
3280  CHECK(d.HasMember(table_name_ref));
3281  CHECK(d.RemoveMember(table_name_ref));
3282 
3283  // Overwrite the existing file
3284  std::ofstream writer(file_path.string(), std::ios::trunc | std::ios::out);
3285  CHECK(writer.is_open());
3286  OStreamWrapper json_wrapper(writer);
3287 
3288  Writer<OStreamWrapper> json_writer(json_wrapper);
3289  d.Accept(json_writer);
3290  writer.close();
3291 }
const DBMetadata currentDB_
Definition: Catalog.h:721
auto table_json_filepath(const std::string &base_path, const std::string &db_name)
Definition: Catalog.cpp:165
#define CHECK(condition)
Definition: Logger.h:291
#define VLOG(n)
Definition: Logger.h:388

+ Here is the call graph for this function:

std::string Catalog_Namespace::Catalog::dumpCreateServer ( const std::string &  name,
bool  multiline_formatting = true 
) const

Definition at line 5756 of file Catalog.cpp.

References join().

5757  {
5758  cat_read_lock read_lock(this);
5759  auto server_it = foreignServerMap_.find(name);
5760  if (server_it == foreignServerMap_.end()) {
5761  throw std::runtime_error("Foreign server " + name + " does not exist.");
5762  }
5763  auto server = server_it->second.get();
5764  std::ostringstream os;
5765  os << "CREATE SERVER " << name << " FOREIGN DATA WRAPPER " << server->data_wrapper_type;
5766  std::vector<std::string> with_options;
5767  for (const auto& [option, value] : server->options) {
5768  with_options.emplace_back(option + "='" + value + "'");
5769  }
5770  if (!with_options.empty()) {
5771  if (!multiline_formatting) {
5772  os << " ";
5773  } else {
5774  os << "\n";
5775  }
5776  os << "WITH (" + boost::algorithm::join(with_options, ", ") + ")";
5777  }
5778  os << ";";
5779  return os.str();
5780 }
std::string join(T const &container, std::string const &delim)
read_lock< Catalog > cat_read_lock
Definition: Catalog.cpp:124
std::string name() const
Definition: Catalog.h:348
ForeignServerMap foreignServerMap_
Definition: Catalog.h:715

+ Here is the call graph for this function:

std::string Catalog_Namespace::Catalog::dumpCreateTable ( const TableDescriptor td,
bool  multiline_formatting = true,
bool  dump_defaults = false 
) const

Definition at line 5577 of file Catalog.cpp.

5579  {
5580  cat_read_lock read_lock(this);
5581  return dumpCreateTableUnlocked(td, multiline_formatting, dump_defaults);
5582 }
read_lock< Catalog > cat_read_lock
Definition: Catalog.cpp:124
std::string dumpCreateTableUnlocked(const TableDescriptor *td, bool multiline_formatting, bool dump_defaults) const
Definition: Catalog.cpp:5595
std::optional< std::string > Catalog_Namespace::Catalog::dumpCreateTable ( int32_t  table_id,
bool  multiline_formatting = true,
bool  dump_defaults = false 
) const

Definition at line 5584 of file Catalog.cpp.

5586  {
5587  cat_read_lock read_lock(this);
5588  const auto td = getMutableMetadataForTableUnlocked(table_id);
5589  if (!td) {
5590  return {};
5591  }
5592  return dumpCreateTableUnlocked(td, multiline_formatting, dump_defaults);
5593 }
read_lock< Catalog > cat_read_lock
Definition: Catalog.cpp:124
std::string dumpCreateTableUnlocked(const TableDescriptor *td, bool multiline_formatting, bool dump_defaults) const
Definition: Catalog.cpp:5595
TableDescriptor * getMutableMetadataForTableUnlocked(int table_id) const
Definition: Catalog.cpp:1899
std::string Catalog_Namespace::Catalog::dumpCreateTableUnlocked ( const TableDescriptor td,
bool  multiline_formatting,
bool  dump_defaults 
) const
private

Definition at line 5595 of file Catalog.cpp.

References CHECK, Data_Namespace::CPU_LEVEL, DEFAULT_FRAGMENT_ROWS, DEFAULT_MAX_CHUNK_SIZE, DEFAULT_MAX_ROLLBACK_EPOCHS, DEFAULT_MAX_ROWS, DEFAULT_PAGE_SIZE, TableDescriptor::fragPageSize, g_leaf_count, TableDescriptor::hasDeletedCol, TableDescriptor::is_system_table, TableDescriptor::isView, join(), kCHAR, kENCODING_DICT, kENCODING_GEOINT, kTEXT, TableDescriptor::maxChunkSize, TableDescriptor::maxFragRows, TableDescriptor::maxRollbackEpochs, TableDescriptor::maxRows, TableDescriptor::nShards, TableDescriptor::partitions, TableDescriptor::persistenceLevel, TableDescriptor::shardedColumnId, TableDescriptor::sortedColumnId, TableDescriptor::tableId, TableDescriptor::tableName, to_string(), and TableDescriptor::viewSQL.

5597  {
5598  auto foreign_table = dynamic_cast<const foreign_storage::ForeignTable*>(td);
5599  std::ostringstream os;
5600 
5601  if (foreign_table && !td->is_system_table) {
5602  os << "CREATE FOREIGN TABLE " << td->tableName << " (";
5603  } else if (!td->isView) {
5604  os << "CREATE ";
5606  os << "TEMPORARY ";
5607  }
5608  os << "TABLE " + td->tableName + " (";
5609  } else {
5610  os << "CREATE VIEW " + td->tableName + " AS " << td->viewSQL;
5611  return os.str();
5612  }
5613  // scan column defines
5614  std::vector<std::string> additional_info;
5615  std::set<std::string> shared_dict_column_names;
5616 
5617  gatherAdditionalInfo(additional_info, shared_dict_column_names, td);
5618 
5619  // gather column defines
5620  const auto cds = getAllColumnMetadataForTable(td->tableId, false, false, false);
5621  std::map<const std::string, const ColumnDescriptor*> dict_root_cds;
5622  bool first = true;
5623  for (const auto cd : cds) {
5624  if (!(cd->isSystemCol || cd->isVirtualCol)) {
5625  const auto& ti = cd->columnType;
5626  if (!first) {
5627  os << ",";
5628  if (!multiline_formatting) {
5629  os << " ";
5630  }
5631  } else {
5632  first = false;
5633  }
5634  if (multiline_formatting) {
5635  os << "\n ";
5636  }
5637  // column name
5638  os << quoteIfRequired(cd->columnName);
5639  // CHAR is perculiar... better dump it as TEXT(32) like \d does
5640  if (ti.get_type() == SQLTypes::kCHAR) {
5641  os << " "
5642  << "TEXT";
5643  } else if (ti.get_subtype() == SQLTypes::kCHAR) {
5644  os << " "
5645  << "TEXT[]";
5646  } else {
5647  os << " " << ti.get_type_name();
5648  }
5649  os << (ti.get_notnull() ? " NOT NULL" : "");
5650  if (cd->default_value.has_value()) {
5651  os << " DEFAULT " << cd->getDefaultValueLiteral();
5652  }
5653  if (shared_dict_column_names.find(cd->columnName) ==
5654  shared_dict_column_names.end()) {
5655  // avoids "Column ... shouldn't specify an encoding, it borrows it
5656  // from the referenced column"
5657  if (ti.is_string() || (ti.is_array() && ti.get_subtype() == kTEXT)) {
5658  auto size = ti.is_array() ? ti.get_logical_size() : ti.get_size();
5659  if (ti.get_compression() == kENCODING_DICT) {
5660  os << " ENCODING " << ti.get_compression_name() << "(" << (size * 8) << ")";
5661  } else {
5662  os << " ENCODING NONE";
5663  }
5664  } else if (ti.is_date_in_days() ||
5665  (ti.get_size() > 0 && ti.get_size() != ti.get_logical_size())) {
5666  const auto comp_param = ti.get_comp_param() ? ti.get_comp_param() : 32;
5667  os << " ENCODING " << ti.get_compression_name() << "(" << comp_param << ")";
5668  } else if (ti.is_geometry()) {
5669  if (ti.get_compression() == kENCODING_GEOINT) {
5670  os << " ENCODING " << ti.get_compression_name() << "(" << ti.get_comp_param()
5671  << ")";
5672  } else {
5673  os << " ENCODING NONE";
5674  }
5675  }
5676  }
5677  }
5678  }
5679  // gather SHARED DICTIONARYs
5680  if (additional_info.size()) {
5681  std::string comma;
5682  if (!multiline_formatting) {
5683  comma = ", ";
5684  } else {
5685  comma = ",\n ";
5686  }
5687  os << comma;
5688  os << boost::algorithm::join(additional_info, comma);
5689  }
5690  os << ")";
5691 
5692  std::vector<std::string> with_options;
5693  if (foreign_table && !td->is_system_table) {
5694  if (multiline_formatting) {
5695  os << "\n";
5696  } else {
5697  os << " ";
5698  }
5699  os << "SERVER " << foreign_table->foreign_server->name;
5700 
5701  // gather WITH options ...
5702  for (const auto& [option, value] : foreign_table->options) {
5703  with_options.emplace_back(option + "='" + value + "'");
5704  }
5705  }
5706 
5707  if (dump_defaults || td->maxFragRows != DEFAULT_FRAGMENT_ROWS) {
5708  with_options.push_back("FRAGMENT_SIZE=" + std::to_string(td->maxFragRows));
5709  }
5710  if (dump_defaults || td->maxChunkSize != DEFAULT_MAX_CHUNK_SIZE) {
5711  with_options.push_back("MAX_CHUNK_SIZE=" + std::to_string(td->maxChunkSize));
5712  }
5713  if (!foreign_table && (dump_defaults || td->fragPageSize != DEFAULT_PAGE_SIZE)) {
5714  with_options.push_back("PAGE_SIZE=" + std::to_string(td->fragPageSize));
5715  }
5716  if (!foreign_table && (dump_defaults || td->maxRows != DEFAULT_MAX_ROWS)) {
5717  with_options.push_back("MAX_ROWS=" + std::to_string(td->maxRows));
5718  }
5719  if ((dump_defaults || td->maxRollbackEpochs != DEFAULT_MAX_ROLLBACK_EPOCHS) &&
5720  td->maxRollbackEpochs != -1) {
5721  with_options.push_back("MAX_ROLLBACK_EPOCHS=" +
5723  }
5724  if (!foreign_table && (dump_defaults || !td->hasDeletedCol)) {
5725  with_options.emplace_back(td->hasDeletedCol ? "VACUUM='DELAYED'"
5726  : "VACUUM='IMMEDIATE'");
5727  }
5728  if (!foreign_table && !td->partitions.empty()) {
5729  with_options.push_back("PARTITIONS='" + td->partitions + "'");
5730  }
5731  if (!foreign_table && td->nShards > 0) {
5732  const auto shard_cd = getMetadataForColumn(td->tableId, td->shardedColumnId);
5733  CHECK(shard_cd);
5734  with_options.push_back(
5735  "SHARD_COUNT=" +
5736  std::to_string(td->nShards * std::max(g_leaf_count, static_cast<size_t>(1))));
5737  }
5738  if (!foreign_table && td->sortedColumnId > 0) {
5739  const auto sort_cd = getMetadataForColumn(td->tableId, td->sortedColumnId);
5740  CHECK(sort_cd);
5741  with_options.push_back("SORT_COLUMN='" + sort_cd->columnName + "'");
5742  }
5743 
5744  if (!with_options.empty()) {
5745  if (!multiline_formatting) {
5746  os << " ";
5747  } else {
5748  os << "\n";
5749  }
5750  os << "WITH (" + boost::algorithm::join(with_options, ", ") + ")";
5751  }
5752  os << ";";
5753  return os.str();
5754 }
int32_t maxRollbackEpochs
std::string partitions
std::string tableName
std::string join(T const &container, std::string const &delim)
#define DEFAULT_MAX_CHUNK_SIZE
std::string to_string(char const *&&v)
std::string quoteIfRequired(const std::string &column_name) const
Definition: Catalog.cpp:5877
#define DEFAULT_MAX_ROWS
void gatherAdditionalInfo(std::vector< std::string > &additional_info, std::set< std::string > &shared_dict_column_names, const TableDescriptor *td) const
Definition: Catalog.cpp:5888
const ColumnDescriptor * getMetadataForColumn(int tableId, const std::string &colName) const
#define DEFAULT_MAX_ROLLBACK_EPOCHS
specifies the content in-memory of a row in the table metadata table
#define DEFAULT_PAGE_SIZE
Definition: sqltypes.h:79
#define DEFAULT_FRAGMENT_ROWS
std::list< const ColumnDescriptor * > getAllColumnMetadataForTable(const int tableId, const bool fetchSystemColumns, const bool fetchVirtualColumns, const bool fetchPhysicalColumns) const
Returns a list of pointers to constant ColumnDescriptor structs for all the columns from a particular...
Definition: Catalog.cpp:2175
Data_Namespace::MemoryLevel persistenceLevel
Definition: sqltypes.h:68
#define CHECK(condition)
Definition: Logger.h:291
std::string viewSQL
size_t g_leaf_count
Definition: ParserNode.cpp:79

+ Here is the call graph for this function:

std::string Catalog_Namespace::Catalog::dumpSchema ( const TableDescriptor td) const

Definition at line 5450 of file Catalog.cpp.

References CHECK, DEFAULT_MAX_ROLLBACK_EPOCHS, TableDescriptor::fragPageSize, g_leaf_count, TableDescriptor::hasDeletedCol, TableDescriptor::is_system_table, join(), kCHAR, kENCODING_DICT, kENCODING_GEOINT, kTEXT, TableDescriptor::maxChunkSize, TableDescriptor::maxFragRows, TableDescriptor::maxRollbackEpochs, TableDescriptor::maxRows, TableDescriptor::nShards, TableDescriptor::partitions, TableDescriptor::shardedColumnId, TableDescriptor::sortedColumnId, TableDescriptor::tableId, and to_string().

Referenced by TableArchiver::dumpTable().

5450  {
5451  CHECK(!td->is_system_table);
5452  cat_read_lock read_lock(this);
5453 
5454  std::ostringstream os;
5455  os << "CREATE TABLE @T (";
5456  // gather column defines
5457  const auto cds = getAllColumnMetadataForTable(td->tableId, false, false, false);
5458  std::string comma;
5459  std::vector<std::string> shared_dicts;
5460  std::map<const std::string, const ColumnDescriptor*> dict_root_cds;
5461  for (const auto cd : cds) {
5462  if (!(cd->isSystemCol || cd->isVirtualCol)) {
5463  const auto& ti = cd->columnType;
5464  os << comma << quoteIfRequired(cd->columnName);
5465  // CHAR is perculiar... better dump it as TEXT(32) like \d does
5466  if (ti.get_type() == SQLTypes::kCHAR) {
5467  os << " "
5468  << "TEXT";
5469  } else if (ti.get_subtype() == SQLTypes::kCHAR) {
5470  os << " "
5471  << "TEXT[]";
5472  } else {
5473  os << " " << ti.get_type_name();
5474  }
5475  os << (ti.get_notnull() ? " NOT NULL" : "");
5476  if (cd->default_value.has_value()) {
5477  os << " DEFAULT " << cd->getDefaultValueLiteral();
5478  }
5479  if (ti.is_string() || (ti.is_array() && ti.get_subtype() == kTEXT)) {
5480  auto size = ti.is_array() ? ti.get_logical_size() : ti.get_size();
5481  if (ti.get_compression() == kENCODING_DICT) {
5482  // if foreign reference, get referenced tab.col
5483  const auto dict_id = ti.get_comp_param();
5484  const DictRef dict_ref(currentDB_.dbId, dict_id);
5485  const auto dict_it = dictDescriptorMapByRef_.find(dict_ref);
5486  CHECK(dict_it != dictDescriptorMapByRef_.end());
5487  const auto dict_name = dict_it->second->dictName;
5488  // when migrating a table, any foreign dict ref will be dropped
5489  // and the first cd of a dict will become root of the dict
5490  if (dict_root_cds.end() == dict_root_cds.find(dict_name)) {
5491  dict_root_cds[dict_name] = cd;
5492  os << " ENCODING " << ti.get_compression_name() << "(" << (size * 8) << ")";
5493  } else {
5494  const auto dict_root_cd = dict_root_cds[dict_name];
5495  shared_dicts.push_back("SHARED DICTIONARY (" + cd->columnName +
5496  ") REFERENCES @T(" + dict_root_cd->columnName + ")");
5497  // "... shouldn't specify an encoding, it borrows from the referenced
5498  // column"
5499  }
5500  } else {
5501  os << " ENCODING NONE";
5502  }
5503  } else if (ti.is_date_in_days() ||
5504  (ti.get_size() > 0 && ti.get_size() != ti.get_logical_size())) {
5505  const auto comp_param = ti.get_comp_param() ? ti.get_comp_param() : 32;
5506  os << " ENCODING " << ti.get_compression_name() << "(" << comp_param << ")";
5507  } else if (ti.is_geometry()) {
5508  if (ti.get_compression() == kENCODING_GEOINT) {
5509  os << " ENCODING " << ti.get_compression_name() << "(" << ti.get_comp_param()
5510  << ")";
5511  } else {
5512  os << " ENCODING NONE";
5513  }
5514  }
5515  comma = ", ";
5516  }
5517  }
5518  // gather SHARED DICTIONARYs
5519  if (shared_dicts.size()) {
5520  os << ", " << boost::algorithm::join(shared_dicts, ", ");
5521  }
5522  // gather WITH options ...
5523  std::vector<std::string> with_options;
5524  with_options.push_back("FRAGMENT_SIZE=" + std::to_string(td->maxFragRows));
5525  with_options.push_back("MAX_CHUNK_SIZE=" + std::to_string(td->maxChunkSize));
5526  with_options.push_back("PAGE_SIZE=" + std::to_string(td->fragPageSize));
5527  with_options.push_back("MAX_ROWS=" + std::to_string(td->maxRows));
5528  with_options.emplace_back(td->hasDeletedCol ? "VACUUM='DELAYED'"
5529  : "VACUUM='IMMEDIATE'");
5530  if (!td->partitions.empty()) {
5531  with_options.push_back("PARTITIONS='" + td->partitions + "'");
5532  }
5533  if (td->nShards > 0) {
5534  const auto shard_cd = getMetadataForColumn(td->tableId, td->shardedColumnId);
5535  CHECK(shard_cd);
5536  os << ", SHARD KEY(" << shard_cd->columnName << ")";
5537  with_options.push_back(
5538  "SHARD_COUNT=" +
5539  std::to_string(td->nShards * std::max(g_leaf_count, static_cast<size_t>(1))));
5540  }
5541  if (td->sortedColumnId > 0) {
5542  const auto sort_cd = getMetadataForColumn(td->tableId, td->sortedColumnId);
5543  CHECK(sort_cd);
5544  with_options.push_back("SORT_COLUMN='" + sort_cd->columnName + "'");
5545  }
5547  td->maxRollbackEpochs != -1) {
5548  with_options.push_back("MAX_ROLLBACK_EPOCHS=" +
5550  }
5551  os << ") WITH (" + boost::algorithm::join(with_options, ", ") + ");";
5552  return os.str();
5553 }
int32_t maxRollbackEpochs
std::string partitions
const DBMetadata currentDB_
Definition: Catalog.h:721
DictDescriptorMapById dictDescriptorMapByRef_
Definition: Catalog.h:711
std::string join(T const &container, std::string const &delim)
read_lock< Catalog > cat_read_lock
Definition: Catalog.cpp:124
std::string to_string(char const *&&v)
std::string quoteIfRequired(const std::string &column_name) const
Definition: Catalog.cpp:5877
const ColumnDescriptor * getMetadataForColumn(int tableId, const std::string &colName) const
#define DEFAULT_MAX_ROLLBACK_EPOCHS
specifies the content in-memory of a row in the table metadata table
Definition: sqltypes.h:79
std::list< const ColumnDescriptor * > getAllColumnMetadataForTable(const int tableId, const bool fetchSystemColumns, const bool fetchVirtualColumns, const bool fetchPhysicalColumns) const
Returns a list of pointers to constant ColumnDescriptor structs for all the columns from a particular...
Definition: Catalog.cpp:2175
Definition: sqltypes.h:68
#define CHECK(condition)
Definition: Logger.h:291
size_t g_leaf_count
Definition: ParserNode.cpp:79

+ Here is the call graph for this function:

+ Here is the caller graph for this function:

void Catalog_Namespace::Catalog::eraseDbMetadata ( )

Definition at line 5059 of file Catalog.cpp.

References shared::kCatalogDirectoryName, and run_benchmark_import::tables.

5059  {
5060  const auto tables = getAllTableMetadata();
5061  for (const auto table : tables) {
5062  eraseTableMetadata(table);
5063  }
5064  // Physically erase database metadata
5065  boost::filesystem::remove(basePath_ + "/" + shared::kCatalogDirectoryName + "/" +
5066  currentDB_.dbName);
5067  calciteMgr_->updateMetadata(currentDB_.dbName, "");
5068 }
std::list< const TableDescriptor * > getAllTableMetadata() const
Definition: Catalog.cpp:2191
const DBMetadata currentDB_
Definition: Catalog.h:721
std::shared_ptr< Calcite > calciteMgr_
Definition: Catalog.h:725
const std::string kCatalogDirectoryName
void eraseTableMetadata(const TableDescriptor *td)
Definition: Catalog.cpp:4342
void Catalog_Namespace::Catalog::eraseDbPhysicalData ( )

Definition at line 5070 of file Catalog.cpp.

References run_benchmark_import::tables.

5070  {
5071  const auto tables = getAllTableMetadata();
5072  for (const auto table : tables) {
5073  eraseTablePhysicalData(table);
5074  }
5075 }
void eraseTablePhysicalData(const TableDescriptor *td)
Definition: Catalog.cpp:5077
std::list< const TableDescriptor * > getAllTableMetadata() const
Definition: Catalog.cpp:2191
void Catalog_Namespace::Catalog::eraseTableMetadata ( const TableDescriptor td)
protected

Definition at line 4342 of file Catalog.cpp.

References g_serialize_temp_tables, INJECT_TIMER, table_is_temporary(), TableDescriptor::tableId, and TableDescriptor::tableName.

4342  {
4346  }
4347  calciteMgr_->updateMetadata(currentDB_.dbName, td->tableName);
4348  {
4349  INJECT_TIMER(removeTableFromMap_);
4351  }
4352 }
void executeDropTableSqliteQueries(const TableDescriptor *td)
Definition: Catalog.cpp:4354
std::string tableName
const DBMetadata currentDB_
Definition: Catalog.h:721
void dropTableFromJsonUnlocked(const std::string &table_name) const
Definition: Catalog.cpp:3261
#define INJECT_TIMER(DESC)
Definition: measure.h:122
bool g_serialize_temp_tables
Definition: Catalog.cpp:109
std::shared_ptr< Calcite > calciteMgr_
Definition: Catalog.h:725
bool table_is_temporary(const TableDescriptor *const td)
void removeTableFromMap(const std::string &tableName, const int tableId, const bool is_on_error=false)
Definition: Catalog.cpp:1604

+ Here is the call graph for this function:

void Catalog_Namespace::Catalog::eraseTablePhysicalData ( const TableDescriptor td)

Definition at line 5077 of file Catalog.cpp.

References Data_Namespace::CPU_LEVEL, Data_Namespace::GPU_LEVEL, INJECT_TIMER, TableDescriptor::isView, and TableDescriptor::tableId.

5077  {
5078  const int tableId = td->tableId;
5079  // must destroy fragmenter before deleteChunks is called.
5080  removeFragmenterForTable(tableId);
5081 
5082  ChunkKey chunkKeyPrefix = {currentDB_.dbId, tableId};
5083  {
5084  INJECT_TIMER(deleteChunksWithPrefix);
5085  // assuming deleteChunksWithPrefix is atomic
5086  dataMgr_->deleteChunksWithPrefix(chunkKeyPrefix, MemoryLevel::CPU_LEVEL);
5087  dataMgr_->deleteChunksWithPrefix(chunkKeyPrefix, MemoryLevel::GPU_LEVEL);
5088  }
5089  if (!td->isView) {
5090  INJECT_TIMER(Remove_Table);
5091  dataMgr_->removeTableRelatedDS(currentDB_.dbId, tableId);
5092  }
5093 }
std::vector< int > ChunkKey
Definition: types.h:36
const DBMetadata currentDB_
Definition: Catalog.h:721
std::shared_ptr< Data_Namespace::DataMgr > dataMgr_
Definition: Catalog.h:722
#define INJECT_TIMER(DESC)
Definition: measure.h:122
void removeFragmenterForTable(const int table_id) const
Definition: Catalog.cpp:4270
template<typename F , typename... Args>
void Catalog_Namespace::Catalog::execInTransaction ( F &&  f,
Args &&...  args 
)
private

Definition at line 7025 of file Catalog.cpp.

References run_benchmark_import::args, and f().

7025  {
7026  cat_write_lock write_lock(this);
7027  cat_sqlite_lock sqlite_lock(this);
7028  sqliteConnector_.query("BEGIN TRANSACTION");
7029  try {
7030  (this->*f)(std::forward<Args>(args)...);
7031  } catch (std::exception&) {
7032  sqliteConnector_.query("ROLLBACK TRANSACTION");
7033  throw;
7034  }
7035  sqliteConnector_.query("END TRANSACTION");
7036 }
SqliteConnector sqliteConnector_
Definition: Catalog.h:720
virtual void query(const std::string &queryString)
write_lock< Catalog > cat_write_lock
Definition: Catalog.cpp:125
torch::Tensor f(torch::Tensor x, torch::Tensor W_target, torch::Tensor b_target)
sqlite_lock< Catalog > cat_sqlite_lock
Definition: Catalog.cpp:126

+ Here is the call graph for this function:

void Catalog_Namespace::Catalog::executeDropTableSqliteQueries ( const TableDescriptor td)
protected

Definition at line 4354 of file Catalog.cpp.

References StorageType::FOREIGN_TABLE, TableDescriptor::isView, kENCODING_DICT, TableDescriptor::storageType, TableDescriptor::tableId, and to_string().

4354  {
4355  const int tableId = td->tableId;
4356  sqliteConnector_.query_with_text_param("DELETE FROM mapd_tables WHERE tableid = ?",
4357  std::to_string(tableId));
4359  "select comp_param from mapd_columns where compression = ? and tableid = ?",
4360  std::vector<std::string>{std::to_string(kENCODING_DICT), std::to_string(tableId)});
4361  int numRows = sqliteConnector_.getNumRows();
4362  std::vector<int> dict_id_list;
4363  for (int r = 0; r < numRows; ++r) {
4364  dict_id_list.push_back(sqliteConnector_.getData<int>(r, 0));
4365  }
4366  for (auto dict_id : dict_id_list) {
4368  "UPDATE mapd_dictionaries SET refcount = refcount - 1 WHERE dictid = ?",
4369  std::vector<std::string>{std::to_string(dict_id)});
4370  }
4372  "DELETE FROM mapd_dictionaries WHERE dictid in (select comp_param from "
4373  "mapd_columns where compression = ? "
4374  "and tableid = ?) and refcount = 0",
4375  std::vector<std::string>{std::to_string(kENCODING_DICT), std::to_string(tableId)});
4376  sqliteConnector_.query_with_text_param("DELETE FROM mapd_columns WHERE tableid = ?",
4377  std::to_string(tableId));
4378  if (td->isView) {
4379  sqliteConnector_.query_with_text_param("DELETE FROM mapd_views WHERE tableid = ?",
4380  std::to_string(tableId));
4381  }
4384  "DELETE FROM omnisci_foreign_tables WHERE table_id = ?", std::to_string(tableId));
4385  }
4386 }
T getData(const int row, const int col)
virtual void query_with_text_params(std::string const &query_only)
SqliteConnector sqliteConnector_
Definition: Catalog.h:720
std::string storageType
std::string to_string(char const *&&v)
static constexpr char const * FOREIGN_TABLE
virtual void query_with_text_param(const std::string &queryString, const std::string &text_param)
virtual size_t getNumRows() const

+ Here is the call graph for this function:

void Catalog_Namespace::Catalog::expandGeoColumn ( const ColumnDescriptor cd,
std::list< ColumnDescriptor > &  columns 
)
static

Definition at line 2784 of file Catalog.cpp.

References CHECK, ColumnDescriptor::columnName, ColumnDescriptor::columnType, IS_GEO, kARRAY, kDOUBLE, kENCODING_GEOINT, kENCODING_NONE, kINT, kLINESTRING, kMULTILINESTRING, kMULTIPOINT, kMULTIPOLYGON, kPOINT, kPOLYGON, kTINYINT, SQLTypeInfo::set_size(), and SQLTypeInfo::set_subtype().

2785  {
2786  const auto& col_ti = cd.columnType;
2787  if (IS_GEO(col_ti.get_type())) {
2788  switch (col_ti.get_type()) {
2789  case kPOINT: {
2790  ColumnDescriptor physical_cd_coords(true);
2791  physical_cd_coords.columnName = cd.columnName + "_coords";
2792  SQLTypeInfo coords_ti = SQLTypeInfo(kARRAY, col_ti.get_notnull());
2793  // Raw data: compressed/uncompressed coords
2794  coords_ti.set_subtype(kTINYINT);
2795  size_t unit_size;
2796  if (col_ti.get_compression() == kENCODING_GEOINT &&
2797  col_ti.get_comp_param() == 32) {
2798  unit_size = 4 * sizeof(int8_t);
2799  } else {
2800  CHECK(col_ti.get_compression() == kENCODING_NONE);
2801  unit_size = 8 * sizeof(int8_t);
2802  }
2803  coords_ti.set_size(2 * unit_size);
2804  physical_cd_coords.columnType = coords_ti;
2805  columns.push_back(physical_cd_coords);
2806 
2807  // If adding more physical columns - update SQLTypeInfo::get_physical_cols()
2808 
2809  break;
2810  }
2811  case kMULTIPOINT:
2812  case kLINESTRING: {
2813  ColumnDescriptor physical_cd_coords(true);
2814  physical_cd_coords.columnName = cd.columnName + "_coords";
2815  SQLTypeInfo coords_ti = SQLTypeInfo(kARRAY, col_ti.get_notnull());
2816  // Raw data: compressed/uncompressed coords
2817  coords_ti.set_subtype(kTINYINT);
2818  physical_cd_coords.columnType = coords_ti;
2819  columns.push_back(physical_cd_coords);
2820 
2821  ColumnDescriptor physical_cd_bounds(true);
2822  physical_cd_bounds.columnName = cd.columnName + "_bounds";
2823  SQLTypeInfo bounds_ti = SQLTypeInfo(kARRAY, col_ti.get_notnull());
2824  bounds_ti.set_subtype(kDOUBLE);
2825  bounds_ti.set_size(4 * sizeof(double));
2826  physical_cd_bounds.columnType = bounds_ti;
2827  columns.push_back(physical_cd_bounds);
2828 
2829  // If adding more physical columns - update SQLTypeInfo::get_physical_cols()
2830 
2831  break;
2832  }
2833  case kMULTILINESTRING: {
2834  ColumnDescriptor physical_cd_coords(true);
2835  physical_cd_coords.columnName = cd.columnName + "_coords";
2836  SQLTypeInfo coords_ti = SQLTypeInfo(kARRAY, col_ti.get_notnull());
2837  // Raw data: compressed/uncompressed coords
2838  coords_ti.set_subtype(kTINYINT);
2839  physical_cd_coords.columnType = coords_ti;
2840  columns.push_back(physical_cd_coords);
2841 
2842  ColumnDescriptor physical_cd_linestring_sizes(true);
2843  physical_cd_linestring_sizes.columnName = cd.columnName + "_linestring_sizes";
2844  SQLTypeInfo linestring_sizes_ti = SQLTypeInfo(kARRAY, col_ti.get_notnull());
2845  linestring_sizes_ti.set_subtype(kINT);
2846  physical_cd_linestring_sizes.columnType = linestring_sizes_ti;
2847  columns.push_back(physical_cd_linestring_sizes);
2848 
2849  ColumnDescriptor physical_cd_bounds(true);
2850  physical_cd_bounds.columnName = cd.columnName + "_bounds";
2851  SQLTypeInfo bounds_ti = SQLTypeInfo(kARRAY, col_ti.get_notnull());
2852  bounds_ti.set_subtype(kDOUBLE);
2853  bounds_ti.set_size(4 * sizeof(double));
2854  physical_cd_bounds.columnType = bounds_ti;
2855  columns.push_back(physical_cd_bounds);
2856 
2857  // If adding more physical columns - update SQLTypeInfo::get_physical_cols()
2858 
2859  break;
2860  }
2861  case kPOLYGON: {
2862  ColumnDescriptor physical_cd_coords(true);
2863  physical_cd_coords.columnName = cd.columnName + "_coords";
2864  SQLTypeInfo coords_ti = SQLTypeInfo(kARRAY, col_ti.get_notnull());
2865  // Raw data: compressed/uncompressed coords
2866  coords_ti.set_subtype(kTINYINT);
2867  physical_cd_coords.columnType = coords_ti;
2868  columns.push_back(physical_cd_coords);
2869 
2870  ColumnDescriptor physical_cd_ring_sizes(true);
2871  physical_cd_ring_sizes.columnName = cd.columnName + "_ring_sizes";
2872  SQLTypeInfo ring_sizes_ti = SQLTypeInfo(kARRAY, col_ti.get_notnull());
2873  ring_sizes_ti.set_subtype(kINT);
2874  physical_cd_ring_sizes.columnType = ring_sizes_ti;
2875  columns.push_back(physical_cd_ring_sizes);
2876 
2877  ColumnDescriptor physical_cd_bounds(true);
2878  physical_cd_bounds.columnName = cd.columnName + "_bounds";
2879  SQLTypeInfo bounds_ti = SQLTypeInfo(kARRAY, col_ti.get_notnull());
2880  bounds_ti.set_subtype(kDOUBLE);
2881  bounds_ti.set_size(4 * sizeof(double));
2882  physical_cd_bounds.columnType = bounds_ti;
2883  columns.push_back(physical_cd_bounds);
2884 
2885  // If adding more physical columns - update SQLTypeInfo::get_physical_cols()
2886 
2887  break;
2888  }
2889  case kMULTIPOLYGON: {
2890  ColumnDescriptor physical_cd_coords(true);
2891  physical_cd_coords.columnName = cd.columnName + "_coords";
2892  SQLTypeInfo coords_ti = SQLTypeInfo(kARRAY, col_ti.get_notnull());
2893  // Raw data: compressed/uncompressed coords
2894  coords_ti.set_subtype(kTINYINT);
2895  physical_cd_coords.columnType = coords_ti;
2896  columns.push_back(physical_cd_coords);
2897 
2898  ColumnDescriptor physical_cd_ring_sizes(true);
2899  physical_cd_ring_sizes.columnName = cd.columnName + "_ring_sizes";
2900  SQLTypeInfo ring_sizes_ti = SQLTypeInfo(kARRAY, col_ti.get_notnull());
2901  ring_sizes_ti.set_subtype(kINT);
2902  physical_cd_ring_sizes.columnType = ring_sizes_ti;
2903  columns.push_back(physical_cd_ring_sizes);
2904 
2905  ColumnDescriptor physical_cd_poly_rings(true);
2906  physical_cd_poly_rings.columnName = cd.columnName + "_poly_rings";
2907  SQLTypeInfo poly_rings_ti = SQLTypeInfo(kARRAY, col_ti.get_notnull());
2908  poly_rings_ti.set_subtype(kINT);
2909  physical_cd_poly_rings.columnType = poly_rings_ti;
2910  columns.push_back(physical_cd_poly_rings);
2911 
2912  ColumnDescriptor physical_cd_bounds(true);
2913  physical_cd_bounds.columnName = cd.columnName + "_bounds";
2914  SQLTypeInfo bounds_ti = SQLTypeInfo(kARRAY, col_ti.get_notnull());
2915  bounds_ti.set_subtype(kDOUBLE);
2916  bounds_ti.set_size(4 * sizeof(double));
2917  physical_cd_bounds.columnType = bounds_ti;
2918  columns.push_back(physical_cd_bounds);
2919 
2920  // If adding more physical columns - update SQLTypeInfo::get_physical_cols()
2921 
2922  break;
2923  }
2924  default:
2925  throw runtime_error("Unrecognized geometry type.");
2926  break;
2927  }
2928  }
2929 }
void set_size(int s)
Definition: sqltypes.h:478
HOST DEVICE void set_subtype(SQLTypes st)
Definition: sqltypes.h:471
specifies the content in-memory of a row in the column metadata table
#define CHECK(condition)
Definition: Logger.h:291
Definition: sqltypes.h:72
SQLTypeInfo columnType
std::string columnName
#define IS_GEO(T)
Definition: sqltypes.h:310

+ Here is the call graph for this function:

bool Catalog_Namespace::Catalog::filterTableByTypeAndUser ( const TableDescriptor td,
const UserMetadata user_metadata,
const GetTablesType  get_tables_type 
) const
private

Definition at line 4946 of file Catalog.cpp.

References GET_PHYSICAL_TABLES, GET_VIEWS, lockmgr::instance(), TableDescriptor::isView, DBObject::loadKey(), TableDescriptor::shard, TableDBObjectType, TableDescriptor::tableName, and ViewDBObjectType.

4948  {
4949  if (td->shard >= 0) {
4950  // skip shards, they're not standalone tables
4951  return false;
4952  }
4953  switch (get_tables_type) {
4954  case GET_PHYSICAL_TABLES: {
4955  if (td->isView) {
4956  return false;
4957  }
4958  break;
4959  }
4960  case GET_VIEWS: {
4961  if (!td->isView) {
4962  return false;
4963  }
4964  break;
4965  }
4966  default:
4967  break;
4968  }
4970  dbObject.loadKey(*this);
4971  std::vector<DBObject> privObjects = {dbObject};
4972  if (!SysCatalog::instance().hasAnyPrivileges(user_metadata, privObjects)) {
4973  // skip table, as there are no privileges to access it
4974  return false;
4975  }
4976  return true;
4977 }
std::string tableName
static SysCatalog & instance()
Definition: SysCatalog.h:343

+ Here is the call graph for this function:

void Catalog_Namespace::Catalog::gatherAdditionalInfo ( std::vector< std::string > &  additional_info,
std::set< std::string > &  shared_dict_column_names,
const TableDescriptor td 
) const
private

Definition at line 5888 of file Catalog.cpp.

References CHECK, logger::ERROR, SQLTypeInfo::get_comp_param(), SQLTypeInfo::get_compression(), kENCODING_DICT, LOG, TableDescriptor::nShards, TableDescriptor::shardedColumnId, TableDescriptor::tableId, and TableDescriptor::tableName.

5890  {
5891  if (td->nShards > 0) {
5892  ColumnIdKey columnIdKey(td->tableId, td->shardedColumnId);
5893  auto scd = columnDescriptorMapById_.find(columnIdKey)->second;
5894  CHECK(scd);
5895  std::string txt = "SHARD KEY (" + quoteIfRequired(scd->columnName) + ")";
5896  additional_info.emplace_back(txt);
5897  }
5898  const auto cds = getAllColumnMetadataForTable(td->tableId, false, false, false);
5899  for (const auto cd : cds) {
5900  if (!(cd->isSystemCol || cd->isVirtualCol)) {
5901  const SQLTypeInfo& ti = cd->columnType;
5902  if (ti.get_compression() != kENCODING_DICT) {
5903  continue;
5904  }
5905  auto dictId = ti.get_comp_param();
5906 
5907  // now we need to check how many other users have this dictionary
5908 
5909  DictRef dict_ref(currentDB_.dbId, dictId);
5910  const auto dictIt = dictDescriptorMapByRef_.find(dict_ref);
5911  if (dictIt == dictDescriptorMapByRef_.end()) {
5912  LOG(ERROR) << "missing dictionary " << dictId << " for table " << td->tableName;
5913  continue;
5914  }
5915 
5916  const auto& dd = dictIt->second;
5917  if (dd->refcount > 1) {
5918  auto lowest_table = td->tableId;
5919  auto lowest_column = cd->columnId;
5920  std::string lowest_column_name;
5921  // we have multiple tables using this dictionary
5922  // find the other occurances and keep the "lowest"
5923  for (auto const& [key, val] : columnDescriptorMap_) {
5924  if (val->columnType.get_compression() == kENCODING_DICT &&
5925  val->columnType.get_comp_param() == dictId &&
5926  !(val->tableId == td->tableId && val->columnId == cd->columnId)) {
5927  if (val->tableId < lowest_table) {
5928  lowest_table = val->tableId;
5929  lowest_column = val->columnId;
5930  lowest_column_name = val->columnName;
5931  }
5932  if (val->columnId < lowest_column) {
5933  lowest_column = val->columnId;
5934  lowest_column_name = val->columnName;
5935  }
5936  }
5937  }
5938  if (lowest_table != td->tableId || lowest_column != cd->columnId) {
5939  // we are referencing a different tables dictionary
5940  auto lowest_td = tableDescriptorMapById_.find(lowest_table)->second;
5941  CHECK(lowest_td);
5942  std::string txt = "SHARED DICTIONARY (" + quoteIfRequired(cd->columnName) +
5943  ") REFERENCES " + lowest_td->tableName + "(" +
5944  quoteIfRequired(lowest_column_name) + ")";
5945 
5946  additional_info.emplace_back(txt);
5947  shared_dict_column_names.insert(cd->columnName);
5948  }
5949  }
5950  }
5951  }
5952 }
std::string tableName
ColumnDescriptorMap columnDescriptorMap_
Definition: Catalog.h:709
#define LOG(tag)
Definition: Logger.h:285
const DBMetadata currentDB_
Definition: Catalog.h:721
DictDescriptorMapById dictDescriptorMapByRef_
Definition: Catalog.h:711
ColumnDescriptorMapById columnDescriptorMapById_
Definition: Catalog.h:710
std::string quoteIfRequired(const std::string &column_name) const
Definition: Catalog.cpp:5877
TableDescriptorMapById tableDescriptorMapById_
Definition: Catalog.h:708
HOST DEVICE EncodingType get_compression() const
Definition: sqltypes.h:399
std::list< const ColumnDescriptor * > getAllColumnMetadataForTable(const int tableId, const bool fetchSystemColumns, const bool fetchVirtualColumns, const bool fetchPhysicalColumns) const
Returns a list of pointers to constant ColumnDescriptor structs for all the columns from a particular...
Definition: Catalog.cpp:2175
HOST DEVICE int get_comp_param() const
Definition: sqltypes.h:402
#define CHECK(condition)
Definition: Logger.h:291
std::tuple< int, int > ColumnIdKey
Definition: Types.h:39

+ Here is the call graph for this function:

std::string Catalog_Namespace::Catalog::generatePhysicalTableName ( const std::string &  logicalTableName,
const size_t  shardNumber 
)
protected

Definition at line 5095 of file Catalog.cpp.

References to_string().

5096  {
5097  std::string physicalTableName =
5098  logicalTableName + physicalTableNameTag_ + std::to_string(shardNumber);
5099  return (physicalTableName);
5100 }
std::string to_string(char const *&&v)
static const std::string physicalTableNameTag_
Definition: Catalog.h:729

+ Here is the call graph for this function:

std::list< const ColumnDescriptor * > Catalog_Namespace::Catalog::getAllColumnMetadataForTable ( const int  tableId,
const bool  fetchSystemColumns,
const bool  fetchVirtualColumns,
const bool  fetchPhysicalColumns 
) const

Returns a list of pointers to constant ColumnDescriptor structs for all the columns from a particular table specified by table id.

Parameters
tableIdtable id we want the column metadata for
Returns
list of pointers to const ColumnDescriptor structs - one for each and every column in the table

Definition at line 2175 of file Catalog.cpp.

Referenced by Analyzer::RangeTableEntry::add_all_column_descs(), Parser::InsertStmt::analyze(), Parser::InsertValuesStmt::analyze(), Fragmenter_Namespace::copyDataOfShard(), anonymous_namespace{ForeignDataImporter.cpp}::create_fragment_buffers(), TableArchiver::dumpTable(), Analyzer::RangeTableEntry::expand_star_in_targetlist(), import_export::fill_missing_columns(), import_export::ForeignDataImporter::finalize(), import_export::anonymous_namespace{ForeignDataImporter.cpp}::get_proxy_foreign_table_fragment_size(), anonymous_namespace{TableOptimizer.cpp}::get_uncached_cpu_chunk_keys(), Parser::InsertValuesStmt::InsertValuesStmt(), TableOptimizer::recomputeMetadata(), TableArchiver::restoreTable(), AlterTableAlterColumnCommandRecoveryMgr::rollback(), and validate_shared_dictionary().

2179  {
2180  cat_read_lock read_lock(this);
2181  std::list<const ColumnDescriptor*> columnDescriptors;
2184  columnDescriptors,
2185  fetchSystemColumns,
2186  fetchVirtualColumns,
2187  fetchPhysicalColumns);
2188  return columnDescriptors;
2189 }
read_lock< Catalog > cat_read_lock
Definition: Catalog.cpp:124
TableDescriptor * getMutableMetadataForTableUnlocked(int table_id) const
Definition: Catalog.cpp:1899
void getAllColumnMetadataForTableImpl(const TableDescriptor *td, std::list< const ColumnDescriptor * > &colDescs, const bool fetchSystemColumns, const bool fetchVirtualColumns, const bool fetchPhysicalColumns) const
Definition: Catalog.cpp:2145

+ Here is the caller graph for this function:

void Catalog_Namespace::Catalog::getAllColumnMetadataForTableImpl ( const TableDescriptor td,
std::list< const ColumnDescriptor * > &  colDescs,
const bool  fetchSystemColumns,
const bool  fetchVirtualColumns,
const bool  fetchPhysicalColumns 
) const
protected

Definition at line 2145 of file Catalog.cpp.

References TableDescriptor::tableId.

2150  {
2151  int32_t skip_physical_cols = 0;
2152  for (const auto& columnDescriptor : columnDescriptorMapById_) {
2153  if (!fetchPhysicalColumns && skip_physical_cols > 0) {
2154  --skip_physical_cols;
2155  continue;
2156  }
2157  auto cd = columnDescriptor.second;
2158  if (cd->tableId != td->tableId) {
2159  continue;
2160  }
2161  if (!fetchSystemColumns && cd->isSystemCol) {
2162  continue;
2163  }
2164  if (!fetchVirtualColumns && cd->isVirtualCol) {
2165  continue;
2166  }
2167  if (!fetchPhysicalColumns) {
2168  const auto& col_ti = cd->columnType;
2169  skip_physical_cols = col_ti.get_physical_cols();
2170  }
2171  columnDescriptors.push_back(cd);
2172  }
2173 }
ColumnDescriptorMapById columnDescriptorMapById_
Definition: Catalog.h:710
list< const DashboardDescriptor * > Catalog_Namespace::Catalog::getAllDashboardsMetadata ( ) const

Definition at line 2211 of file Catalog.cpp.

2211  {
2212  cat_read_lock read_lock(this);
2213  list<const DashboardDescriptor*> dashboards;
2214  for (auto dashboard_entry : dashboardDescriptorMap_) {
2215  dashboards.push_back(dashboard_entry.second.get());
2216  }
2217  return dashboards;
2218 }
read_lock< Catalog > cat_read_lock
Definition: Catalog.cpp:124
DashboardDescriptorMap dashboardDescriptorMap_
Definition: Catalog.h:712
std::vector< DashboardDescriptor > Catalog_Namespace::Catalog::getAllDashboardsMetadataForSysTable ( ) const

Definition at line 2220 of file Catalog.cpp.

2220  {
2221  cat_read_lock read_lock(this);
2222  std::vector<DashboardDescriptor> dashboards;
2223  dashboards.reserve(dashboardDescriptorMap_.size());
2224  for (auto dashboard_entry : dashboardDescriptorMap_) {
2225  const auto& cat_dashboard = dashboard_entry.second;
2226  dashboards.emplace_back();
2227  auto& dashboard = dashboards.back();
2228  dashboard.dashboardId = cat_dashboard->dashboardId;
2229  dashboard.dashboardName = cat_dashboard->dashboardName;
2230  dashboard.userId = cat_dashboard->userId;
2231  dashboard.updateTime = cat_dashboard->updateTime;
2232  dashboard.dashboardMetadata = cat_dashboard->dashboardMetadata;
2233  }
2234  return dashboards;
2235 }
read_lock< Catalog > cat_read_lock
Definition: Catalog.cpp:124
DashboardDescriptorMap dashboardDescriptorMap_
Definition: Catalog.h:712
std::list< const DictDescriptor * > Catalog_Namespace::Catalog::getAllDictionariesWithColumnInName ( const ColumnDescriptor cd)

Definition at line 2333 of file Catalog.cpp.

References CHECK, ColumnDescriptor::columnName, and ColumnDescriptor::tableId.

Referenced by AlterTableAlterColumnCommandRecoveryMgr::rollback().

2334  {
2335  cat_read_lock read_lock(this);
2336  std::list<const DictDescriptor*> dds;
2337 
2338  auto table_name_opt = getTableName(cd->tableId);
2339  CHECK(table_name_opt.has_value());
2340  auto table_name = table_name_opt.value();
2341 
2342  for (const auto& [dkey, dd] : dictDescriptorMapByRef_) {
2343  if (dd->dictName.find(table_name + "_" + cd->columnName + "_dict") !=
2344  std::string::npos) {
2345  dds.push_back(dd.get());
2346  }
2347  }
2348 
2349  return dds;
2350 }
DictDescriptorMapById dictDescriptorMapByRef_
Definition: Catalog.h:711
read_lock< Catalog > cat_read_lock
Definition: Catalog.cpp:124
#define CHECK(condition)
Definition: Logger.h:291
std::optional< std::string > getTableName(int32_t table_id) const
Definition: Catalog.cpp:1872
std::string columnName

+ Here is the caller graph for this function:

std::vector< const foreign_storage::ForeignTable * > Catalog_Namespace::Catalog::getAllForeignTablesForForeignServer ( const int32_t  foreign_server_id)

Get all of the foreign tables for associated with a foreign server id.

Parameters
foreign_server_id- id of foreign server
Returns
std::vector<const ForeignTable*> a vector containing foreign tables which use the foreign server

Definition at line 3641 of file Catalog.cpp.

References CHECK, and StorageType::FOREIGN_TABLE.

3641  {
3642  cat_read_lock read_lock(this);
3643  std::vector<const foreign_storage::ForeignTable*> foreign_tables;
3644  for (auto entry : tableDescriptorMapById_) {
3645  auto table_descriptor = entry.second;
3646  if (table_descriptor->storageType == StorageType::FOREIGN_TABLE) {
3647  auto foreign_table = dynamic_cast<foreign_storage::ForeignTable*>(table_descriptor);
3648  CHECK(foreign_table);
3649  if (foreign_table->foreign_server->id == foreign_server_id) {
3650  foreign_tables.emplace_back(foreign_table);
3651  }
3652  }
3653  }
3654  return foreign_tables;
3655 }
read_lock< Catalog > cat_read_lock
Definition: Catalog.cpp:124
TableDescriptorMapById tableDescriptorMapById_
Definition: Catalog.h:708
#define CHECK(condition)
Definition: Logger.h:291
static constexpr char const * FOREIGN_TABLE
std::vector< const TableDescriptor * > Catalog_Namespace::Catalog::getAllForeignTablesForRefresh ( ) const

Gets all the foreign tables that are pending refreshes. The list of tables includes tables that are configured for scheduled refreshes with next refresh timestamps that are in the past.

Returns
foreign tables pending refreshes

Definition at line 5793 of file Catalog.cpp.

References CHECK, StorageType::FOREIGN_TABLE, foreign_storage::RefreshTimeCalculator::getCurrentTime(), foreign_storage::ForeignTable::REFRESH_TIMING_TYPE_KEY, foreign_storage::ForeignTable::SCHEDULE_REFRESH_TIMING_TYPE, and run_benchmark_import::tables.

5793  {
5794  cat_read_lock read_lock(this);
5795  std::vector<const TableDescriptor*> tables;
5796  for (auto entry : tableDescriptorMapById_) {
5797  auto table_descriptor = entry.second;
5798  if (table_descriptor->storageType == StorageType::FOREIGN_TABLE) {
5799  auto foreign_table = dynamic_cast<foreign_storage::ForeignTable*>(table_descriptor);
5800  CHECK(foreign_table);
5801  auto timing_type_entry = foreign_table->options.find(
5803  CHECK(timing_type_entry != foreign_table->options.end());
5805  if (timing_type_entry->second ==
5807  foreign_table->next_refresh_time <= current_time) {
5808  tables.emplace_back(foreign_table);
5809  }
5810  }
5811  }
5812  return tables;
5813 }
read_lock< Catalog > cat_read_lock
Definition: Catalog.cpp:124
TableDescriptorMapById tableDescriptorMapById_
Definition: Catalog.h:708
static constexpr const char * REFRESH_TIMING_TYPE_KEY
Definition: ForeignTable.h:43
#define CHECK(condition)
Definition: Logger.h:291
static constexpr char const * FOREIGN_TABLE
static constexpr const char * SCHEDULE_REFRESH_TIMING_TYPE
Definition: ForeignTable.h:53

+ Here is the call graph for this function:

std::vector< std::pair< int32_t, int32_t > > Catalog_Namespace::Catalog::getAllPersistedTableAndShardIds ( ) const

Definition at line 4899 of file Catalog.cpp.

4900  {
4901  cat_read_lock read_lock(this);
4902  std::vector<std::pair<int32_t, int32_t>> table_and_shard_ids;
4903  table_and_shard_ids.reserve(tableDescriptorMapById_.size());
4904  for (const auto [table_id, td] : tableDescriptorMapById_) {
4905  // Only include ids for physical persisted tables
4906  if (!td->isView && !td->isTemporaryTable() && !td->isForeignTable() &&
4907  logicalToPhysicalTableMapById_.find(table_id) ==
4909  table_and_shard_ids.emplace_back(table_id, td->shard);
4910  }
4911  }
4912  return table_and_shard_ids;
4913 }
read_lock< Catalog > cat_read_lock
Definition: Catalog.cpp:124
TableDescriptorMapById tableDescriptorMapById_
Definition: Catalog.h:708
LogicalToPhysicalTableMapById logicalToPhysicalTableMapById_
Definition: Catalog.h:727
list< const TableDescriptor * > Catalog_Namespace::Catalog::getAllTableMetadata ( ) const

Definition at line 2191 of file Catalog.cpp.

Referenced by system_validator::SingleNodeValidator::validate().

2191  {
2192  cat_read_lock read_lock(this);
2193  list<const TableDescriptor*> table_list;
2194  for (auto p : tableDescriptorMapById_) {
2195  table_list.push_back(p.second);
2196  }
2197  return table_list;
2198 }
read_lock< Catalog > cat_read_lock
Definition: Catalog.cpp:124
TableDescriptorMapById tableDescriptorMapById_
Definition: Catalog.h:708

+ Here is the caller graph for this function:

std::vector< TableDescriptor > Catalog_Namespace::Catalog::getAllTableMetadataCopy ( ) const

Definition at line 2200 of file Catalog.cpp.

References run_benchmark_import::tables.

2200  {
2201  cat_read_lock read_lock(this);
2202  std::vector<TableDescriptor> tables;
2203  tables.reserve(tableDescriptorMapById_.size());
2204  for (auto table_entry : tableDescriptorMapById_) {
2205  tables.emplace_back(*table_entry.second);
2206  tables.back().fragmenter = nullptr;
2207  }
2208  return tables;
2209 }
read_lock< Catalog > cat_read_lock
Definition: Catalog.cpp:124
TableDescriptorMapById tableDescriptorMapById_
Definition: Catalog.h:708
const TableDescriptor * Catalog_Namespace::Catalog::getCachedTableDescriptor ( const std::map< std::string, int > &  cached_table_map,
const std::string &  cur_table_name 
)
private

Definition at line 4490 of file Catalog.cpp.

4492  {
4493  if (auto it = cached_table_map.find(cur_table_name); it != cached_table_map.end()) {
4494  auto table_id = it->second;
4495  return (table_id == -1) ? NULL : getMetadataForTable(table_id);
4496  }
4497  return getMetadataForTable(cur_table_name);
4498 }
const TableDescriptor * getMetadataForTable(const std::string &tableName, const bool populateFragmenter=true) const
Returns a pointer to a const TableDescriptor struct matching the provided tableName.
std::shared_ptr<Calcite> Catalog_Namespace::Catalog::getCalciteMgr ( ) const
inline

Definition at line 267 of file Catalog.h.

References calciteMgr_.

267 { return calciteMgr_; }
std::shared_ptr< Calcite > calciteMgr_
Definition: Catalog.h:725
const std::string& Catalog_Namespace::Catalog::getCatalogBasePath ( ) const
inline

Definition at line 273 of file Catalog.h.

References basePath_.

Referenced by AlterTableAlterColumnCommandRecoveryMgr::getRecoveryFilepathInfo().

273 { return basePath_; }

+ Here is the caller graph for this function:

std::string Catalog_Namespace::Catalog::getColumnDictDirectory ( const ColumnDescriptor cd,
bool  file_name_only = true 
) const

Definition at line 5398 of file Catalog.cpp.

References CHECK, ColumnDescriptor::columnType, SQLTypeInfo::get_comp_param(), SQLTypeInfo::get_compression(), SQLTypeInfo::is_string(), SQLTypeInfo::is_string_array(), and kENCODING_DICT.

Referenced by TableArchiver::dumpTable(), and TableArchiver::restoreTable().

5399  {
5400  if ((cd->columnType.is_string() || cd->columnType.is_string_array()) &&
5402  cd->columnType.get_comp_param() > 0) {
5403  const auto dictId = cd->columnType.get_comp_param();
5404  const DictRef dictRef(currentDB_.dbId, dictId);
5405  const auto dit = dictDescriptorMapByRef_.find(dictRef);
5406  CHECK(dit != dictDescriptorMapByRef_.end());
5407  CHECK(dit->second);
5408  if (file_name_only) {
5409  boost::filesystem::path file_path(dit->second->dictFolderPath);
5410  return file_path.filename().string();
5411  } else {
5412  return dit->second->dictFolderPath;
5413  }
5414  }
5415  return std::string();
5416 }
const DBMetadata currentDB_
Definition: Catalog.h:721
DictDescriptorMapById dictDescriptorMapByRef_
Definition: Catalog.h:711
HOST DEVICE EncodingType get_compression() const
Definition: sqltypes.h:399
HOST DEVICE int get_comp_param() const
Definition: sqltypes.h:402
#define CHECK(condition)
Definition: Logger.h:291
SQLTypeInfo columnType
bool is_string() const
Definition: sqltypes.h:561
bool is_string_array() const
Definition: sqltypes.h:564

+ Here is the call graph for this function:

+ Here is the caller graph for this function:

const int Catalog_Namespace::Catalog::getColumnIdBySpi ( const int  tableId,
const size_t  spi 
) const

Definition at line 1999 of file Catalog.cpp.

1999  {
2000  cat_read_lock read_lock(this);
2001  return getColumnIdBySpiUnlocked(table_id, spi);
2002 }
read_lock< Catalog > cat_read_lock
Definition: Catalog.cpp:124
const int getColumnIdBySpiUnlocked(const int table_id, const size_t spi) const
Definition: Catalog.cpp:1981
const int Catalog_Namespace::Catalog::getColumnIdBySpiUnlocked ( const int  table_id,
const size_t  spi 
) const
protected

Definition at line 1981 of file Catalog.cpp.

References CHECK, SPIMAP_MAGIC1, and SPIMAP_MAGIC2.

1981  {
1982  const auto tabDescIt = tableDescriptorMapById_.find(table_id);
1983  CHECK(tableDescriptorMapById_.end() != tabDescIt);
1984  const auto& columnIdBySpi = tabDescIt->second->columnIdBySpi_;
1985 
1986  auto spx = spi;
1987  int phi = 0;
1988  if (spx >= SPIMAP_MAGIC1) // see Catalog.h
1989  {
1990  phi = (spx - SPIMAP_MAGIC1) % SPIMAP_MAGIC2;
1991  spx = (spx - SPIMAP_MAGIC1) / SPIMAP_MAGIC2;
1992  }
1993 
1994  CHECK(0 < spx && spx <= columnIdBySpi.size())
1995  << "spx = " << spx << ", size = " << columnIdBySpi.size();
1996  return columnIdBySpi[spx - 1] + phi;
1997 }
#define SPIMAP_MAGIC1
Definition: Catalog.h:82
#define SPIMAP_MAGIC2
Definition: Catalog.h:83
TableDescriptorMapById tableDescriptorMapById_
Definition: Catalog.h:708
#define CHECK(condition)
Definition: Logger.h:291
const std::optional< std::string > Catalog_Namespace::Catalog::getColumnName ( int  table_id,
int  column_id 
) const

Definition at line 1971 of file Catalog.cpp.

1972  {
1973  cat_read_lock read_lock(this);
1974  auto it = columnDescriptorMapById_.find(ColumnIdKey{table_id, column_id});
1975  if (it == columnDescriptorMapById_.end()) {
1976  return {};
1977  }
1978  return it->second->columnName;
1979 }
read_lock< Catalog > cat_read_lock
Definition: Catalog.cpp:124
ColumnDescriptorMapById columnDescriptorMapById_
Definition: Catalog.h:710
std::tuple< int, int > ColumnIdKey
Definition: Types.h:39
const DBMetadata& Catalog_Namespace::Catalog::getCurrentDB ( ) const
inline

Definition at line 265 of file Catalog.h.

References currentDB_.

Referenced by lockmgr::TableSchemaLockContainer< ReadLock >::acquireTableDescriptor(), lockmgr::TableSchemaLockContainer< WriteLock >::acquireTableDescriptor(), checkDateInDaysColumnMigration(), lockmgr::helpers::chunk_key_for_table(), AlterTableAlterColumnCommandRecoveryMgr::cleanupDropSourceGeoColumns(), Catalog_Namespace::SysCatalog::deleteObjectDescriptorMap(), TableArchiver::dumpTable(), Fragmenter_Namespace::get_chunks(), getChunkAccessorTable(), Fragmenter_Namespace::InsertOrderFragmenter::getChunksForAllColumns(), AlterTableAlterColumnCommandRecoveryMgr::getRecoveryFilepathInfo(), Parser::getTableChunkKey(), import_export::Loader::init(), DBHandler::interruptQuery(), DBObject::loadKey(), name(), query_state::operator<<(), TableOptimizer::recomputeMetadata(), AlterTableAlterColumnCommandRecoveryMgr::recoverAlterTableAlterColumnFromFile(), foreign_storage::refresh_foreign_table_unlocked(), ForeignStorageInterface::registerTable(), Catalog_Namespace::SysCatalog::renameDBObject(), Catalog_Namespace::SysCatalog::renameObjectsInDescriptorMap(), TableArchiver::restoreTable(), AlterTableAlterColumnCommandRecoveryMgr::rollback(), Fragmenter_Namespace::InsertOrderFragmenter::updateColumn(), Fragmenter_Namespace::InsertOrderFragmenter::updateColumns(), Catalog_Namespace::SysCatalog::updateObjectDescriptorMap(), lockmgr::validate_table_descriptor_after_lock(), and StorageIOFacility::yieldUpdateCallback().

265 { return currentDB_; }
const DBMetadata currentDB_
Definition: Catalog.h:721

+ Here is the caller graph for this function:

const CustomExpression * Catalog_Namespace::Catalog::getCustomExpression ( int32_t  custom_expression_id) const

Gets a pointer to the custom expression object with the given id.

Parameters
custom_expression_id- id of custom expression to get
Returns
pointer to custom expression object. nullptr is returned if no custom expression is found for the given id.

Definition at line 6003 of file Catalog.cpp.

6003  {
6004  cat_read_lock read_lock(this);
6005  auto it = custom_expr_map_by_id_.find(custom_expression_id);
6006  if (it != custom_expr_map_by_id_.end()) {
6007  return it->second.get();
6008  }
6009  return nullptr;
6010 }
read_lock< Catalog > cat_read_lock
Definition: Catalog.cpp:124
CustomExpressionMapById custom_expr_map_by_id_
Definition: Catalog.h:717
std::unique_ptr< CustomExpression > Catalog_Namespace::Catalog::getCustomExpressionFromConnector ( size_t  row)
private

Definition at line 1529 of file Catalog.cpp.

References setup::name.

1529  {
1530  auto id = sqliteConnector_.getData<int>(row, 0);
1531  auto name = sqliteConnector_.getData<string>(row, 1);
1532  auto expression_json = sqliteConnector_.getData<string>(row, 2);
1533  auto data_source_type_str = sqliteConnector_.getData<string>(row, 3);
1534  auto data_source_id = sqliteConnector_.getData<int>(row, 4);
1535  auto is_deleted = sqliteConnector_.getData<bool>(row, 5);
1536  return std::make_unique<CustomExpression>(
1537  id,
1538  name,
1539  expression_json,
1540  CustomExpression::dataSourceTypeFromString(data_source_type_str),
1541  data_source_id,
1542  is_deleted);
1543 }
T getData(const int row, const int col)
SqliteConnector sqliteConnector_
Definition: Catalog.h:720
static DataSourceType dataSourceTypeFromString(const std::string &type_str)
std::string name() const
Definition: Catalog.h:348
const std::unique_ptr< const CustomExpression > Catalog_Namespace::Catalog::getCustomExpressionFromStorage ( int32_t  custom_expression_id)

Gets a pointer to a struct containing custom expression details fetched from storage. This is intended for use in tests, when asserting that expected custom expression data is persisted.

Parameters
custom_expression_id- id of custom expression to get
Returns
pointer to custom expression object. nullptr is returned if no custom expression is found for the given id.

Definition at line 6012 of file Catalog.cpp.

References CHECK_EQ, and to_string().

6013  {
6014  cat_sqlite_lock sqlite_lock(getObjForLock());
6016  "SELECT id, name, expression_json, data_source_type, data_source_id, "
6017  "is_deleted FROM omnisci_custom_expressions WHERE id = ?",
6018  std::vector<std::string>{to_string(custom_expression_id)});
6019  if (sqliteConnector_.getNumRows() > 0) {
6020  CHECK_EQ(sqliteConnector_.getNumRows(), static_cast<size_t>(1));
6022  }
6023  return nullptr;
6024 }
#define CHECK_EQ(x, y)
Definition: Logger.h:301
virtual void query_with_text_params(std::string const &query_only)
SqliteConnector sqliteConnector_
Definition: Catalog.h:720
std::unique_ptr< CustomExpression > getCustomExpressionFromConnector(size_t row)
Definition: Catalog.cpp:1529
std::string to_string(char const *&&v)
const Catalog * getObjForLock()
Definition: Catalog.cpp:260
sqlite_lock< Catalog > cat_sqlite_lock
Definition: Catalog.cpp:126
virtual size_t getNumRows() const

+ Here is the call graph for this function:

std::vector< const CustomExpression * > Catalog_Namespace::Catalog::getCustomExpressionsForUser ( const UserMetadata user) const

Gets pointers to all the custom expression objects that the given user has access to. For custom expressions that are associated with a table data source, custom expressions for tables that the given user has SELECT access to are returned.

Parameters
user- user for which to get accessible custom expressions
Returns
pointer to custom expression objects that the given user has access to

Definition at line 6026 of file Catalog.cpp.

References CHECK, lockmgr::instance(), AccessPrivileges::SELECT_FROM_TABLE, and TableDBObjectType.

6027  {
6028  std::vector<const CustomExpression*> all_custom_expressions;
6029  {
6030  // Get custom expression pointers separately in order to avoid holding the catalog
6031  // read lock while checking privileges (which may cause a deadlock).
6032  cat_read_lock read_lock(this);
6033  for (const auto& [id, custom_expression] : custom_expr_map_by_id_) {
6034  all_custom_expressions.emplace_back(custom_expression.get());
6035  }
6036  }
6037 
6038  std::vector<const CustomExpression*> filtered_custom_expressions;
6039  for (const auto custom_expression : all_custom_expressions) {
6040  CHECK(custom_expression->data_source_type == DataSourceType::TABLE);
6041  DBObject db_object{custom_expression->data_source_id, TableDBObjectType};
6042  db_object.loadKey(*this);
6043  db_object.setPrivileges(AccessPrivileges::SELECT_FROM_TABLE);
6044  if (SysCatalog::instance().checkPrivileges(user, {db_object})) {
6045  filtered_custom_expressions.emplace_back(custom_expression);
6046  }
6047  }
6048  return filtered_custom_expressions;
6049 }
read_lock< Catalog > cat_read_lock
Definition: Catalog.cpp:124
static const AccessPrivileges SELECT_FROM_TABLE
Definition: DBObject.h:160
static SysCatalog & instance()
Definition: SysCatalog.h:343
#define CHECK(condition)
Definition: Logger.h:291
CustomExpressionMapById custom_expr_map_by_id_
Definition: Catalog.h:717

+ Here is the call graph for this function:

const std::string Catalog_Namespace::Catalog::getCustomExpressionsSchema ( bool  if_not_exists = false)
static

Gets the DDL statement used to create the custom expressions table.

Parameters
if_not_exists- flag the indicates whether or not to include the "IF NOT EXISTS" phrase in the DDL statement.
Returns
string containing DDL statement

Definition at line 793 of file Catalog.cpp.

Referenced by Catalog_Namespace::SysCatalog::createDatabase(), and updateCustomExpressionsSchema().

793  {
794  return "CREATE TABLE " + (if_not_exists ? std::string{"IF NOT EXISTS "} : "") +
795  "omnisci_custom_expressions(id integer primary key, name text, " +
796  "expression_json text, data_source_type text, " +
797  "data_source_id integer, is_deleted boolean)";
798 }

+ Here is the caller graph for this function:

int Catalog_Namespace::Catalog::getDatabaseId ( ) const
inline

Definition at line 326 of file Catalog.h.

References currentDB_, and Catalog_Namespace::DBMetadata::dbId.

Referenced by UpdelRoll::addDirtyChunk(), Parser::ColumnRef::analyze(), UpdelRoll::cancelUpdate(), AlterTableAlterColumnCommandRecoveryMgr::cleanupClearRemainingChunks(), UpdelRoll::commitUpdate(), anonymous_namespace{ForeignDataImporter.cpp}::create_fragment_buffers(), DictionaryValueConverter< TARGET_TYPE >::DictionaryValueConverter(), Catalog_Namespace::anonymous_namespace{Catalog.cpp}::drop_tables(), Analyzer::RangeTableEntry::expand_star_in_targetlist(), anonymous_namespace{DdlCommandExecutor.cpp}::get_agg_storage_stats(), anonymous_namespace{TableOptimizer.cpp}::get_uncached_cpu_chunk_keys(), TableOptimizer::getDeletedColumnStats(), lockmgr::TableLockMgrImpl< T >::getMutexTracker(), getSyntheticColumnVar(), anonymous_namespace{ForeignDataImporter.cpp}::load_foreign_data_buffers(), Catalog_Namespace::SysCatalog::reassignObjectOwners(), TableOptimizer::recomputeColumnMetadata(), AlterTableAlterColumnCommandRecoveryMgr::recoverAlterTableAlterColumnFromFile(), foreign_storage::refresh_foreign_table_unlocked(), AlterTableAlterColumnCommandRecoveryMgr::rollback(), Fragmenter_Namespace::LocalInsertConnector::rollback(), UpdelRoll::stageUpdate(), TableOptimizer::vacuumDeletedRows(), TableOptimizer::vacuumFragments(), TableOptimizer::vacuumFragmentsAboveMinSelectivity(), system_validator::SingleNodeValidator::validate(), anonymous_namespace{DdlCommandExecutor.cpp}::validate_alter_type_metadata(), and anonymous_namespace{QueryPhysicalInputsCollector.cpp}::RelAlgPhysicalTableInputsVisitor::visit().

326 { return currentDB_.dbId; }
const DBMetadata currentDB_
Definition: Catalog.h:721

+ Here is the caller graph for this function:

Data_Namespace::DataMgr& Catalog_Namespace::Catalog::getDataMgr ( ) const
inline

Definition at line 266 of file Catalog.h.

References dataMgr_.

Referenced by UpdelRoll::cancelUpdate(), AlterTableAlterColumnCommandRecoveryMgr::cleanupClearChunk(), AlterTableAlterColumnCommandRecoveryMgr::cleanupClearRemainingChunks(), AlterTableAlterColumnCommandRecoveryMgr::cleanupDropSourceGeoColumns(), anonymous_namespace{TableOptimizer.cpp}::delete_cpu_chunks(), Catalog_Namespace::anonymous_namespace{Catalog.cpp}::drop_tables(), TableArchiver::dumpTable(), anonymous_namespace{DdlCommandExecutor.cpp}::get_agg_storage_stats(), Fragmenter_Namespace::get_chunks(), anonymous_namespace{TableOptimizer.cpp}::get_uncached_cpu_chunk_keys(), getChunkAccessorTable(), Fragmenter_Namespace::InsertOrderFragmenter::getChunksForAllColumns(), anonymous_namespace{DBHandler.cpp}::log_system_cpu_memory_status(), TableOptimizer::recomputeMetadata(), AlterTableAlterColumnCommandRecoveryMgr::recoverAlterTableAlterColumnFromFile(), foreign_storage::refresh_foreign_table_unlocked(), TableArchiver::restoreTable(), AlterTableAlterColumnCommandRecoveryMgr::rollback(), UpdelRoll::stageUpdate(), Fragmenter_Namespace::InsertOrderFragmenter::updateColumn(), UpdelRoll::updateFragmenterAndCleanupChunks(), TableOptimizer::vacuumDeletedRows(), TableOptimizer::vacuumFragments(), and anonymous_namespace{DdlCommandExecutor.cpp}::validate_alter_type_metadata().

266 { return *dataMgr_; }
std::shared_ptr< Data_Namespace::DataMgr > dataMgr_
Definition: Catalog.h:722

+ Here is the caller graph for this function:

const ColumnDescriptor * Catalog_Namespace::Catalog::getDeletedColumn ( const TableDescriptor td) const

Definition at line 3907 of file Catalog.cpp.

Referenced by TableOptimizer::getDeletedColumnStats(), TableOptimizer::recomputeDeletedColumnMetadata(), and TableOptimizer::vacuumFragments().

3907  {
3908  cat_read_lock read_lock(this);
3909  const auto it = deletedColumnPerTable_.find(td);
3910  return it != deletedColumnPerTable_.end() ? it->second : nullptr;
3911 }
read_lock< Catalog > cat_read_lock
Definition: Catalog.cpp:124
DeletedColumnPerTableMap deletedColumnPerTable_
Definition: Catalog.h:774

+ Here is the caller graph for this function:

const ColumnDescriptor * Catalog_Namespace::Catalog::getDeletedColumnIfRowsDeleted ( const TableDescriptor td) const

Definition at line 3925 of file Catalog.cpp.

References ColumnDescriptor::columnId.

3926  {
3927  std::vector<const TableDescriptor*> tds;
3928  const ColumnDescriptor* cd;
3929  {
3930  cat_read_lock read_lock(this);
3931 
3932  const auto it = deletedColumnPerTable_.find(td);
3933  // if not a table that supports delete return nullptr, nothing more to do
3934  if (it == deletedColumnPerTable_.end()) {
3935  return nullptr;
3936  }
3937  cd = it->second;
3938  tds = getPhysicalTablesDescriptors(td, false);
3939  }
3940  // individual tables are still protected by higher level locks
3941  for (auto tdd : tds) {
3942  if (checkMetadataForDeletedRecs(tdd, cd->columnId)) {
3943  return cd;
3944  }
3945  }
3946  // no deletes so far recorded in metadata
3947  return nullptr;
3948 }
read_lock< Catalog > cat_read_lock
Definition: Catalog.cpp:124
DeletedColumnPerTableMap deletedColumnPerTable_
Definition: Catalog.h:774
const bool checkMetadataForDeletedRecs(const TableDescriptor *td, int column_id) const
Definition: Catalog.cpp:3913
specifies the content in-memory of a row in the column metadata table
std::vector< const TableDescriptor * > getPhysicalTablesDescriptors(const TableDescriptor *logical_table_desc, bool populate_fragmenter=true) const
Definition: Catalog.cpp:4879
void Catalog_Namespace::Catalog::getDictionary ( const ColumnDescriptor cd,
std::map< int, StringDictionary * > &  stringDicts 
)

Definition at line 2352 of file Catalog.cpp.

References CHECK, ColumnDescriptor::columnName, kENCODING_DICT, ColumnDescriptor::tableId, and to_upper().

2353  {
2354  // learn 'committed' ColumnDescriptor of this column
2355  auto cit = columnDescriptorMap_.find(ColumnKey(cd.tableId, to_upper(cd.columnName)));
2356  CHECK(cit != columnDescriptorMap_.end());
2357  auto& ccd = *cit->second;
2358 
2359  if (!(ccd.columnType.is_string() || ccd.columnType.is_string_array())) {
2360  return;
2361  }
2362  if (!(ccd.columnType.get_compression() == kENCODING_DICT)) {
2363  return;
2364  }
2365  if (!(ccd.columnType.get_comp_param() > 0)) {
2366  return;
2367  }
2368 
2369  auto dictId = ccd.columnType.get_comp_param();
2370  getMetadataForDict(dictId);
2371 
2372  const DictRef dictRef(currentDB_.dbId, dictId);
2373  auto dit = dictDescriptorMapByRef_.find(dictRef);
2374  CHECK(dit != dictDescriptorMapByRef_.end());
2375  CHECK(dit->second);
2376  CHECK(dit->second.get()->stringDict);
2377  stringDicts[ccd.columnId] = dit->second.get()->stringDict.get();
2378 }
std::tuple< int, std::string > ColumnKey
Definition: Types.h:37
ColumnDescriptorMap columnDescriptorMap_
Definition: Catalog.h:709
const DBMetadata currentDB_
Definition: Catalog.h:721
DictDescriptorMapById dictDescriptorMapByRef_
Definition: Catalog.h:711
const DictDescriptor * getMetadataForDict(int dict_ref, bool loadDict=true) const
Definition: Catalog.cpp:1907
std::string to_upper(const std::string &str)
#define CHECK(condition)
Definition: Logger.h:291
std::string columnName

+ Here is the call graph for this function:

const std::map< int, const ColumnDescriptor * > Catalog_Namespace::Catalog::getDictionaryToColumnMapping ( )

Definition at line 4915 of file Catalog.cpp.

References kENCODING_DICT, and run_benchmark_import::tables.

4915  {
4916  cat_read_lock read_lock(this);
4917 
4918  std::map<int, const ColumnDescriptor*> mapping;
4919 
4920  const auto tables = getAllTableMetadata();
4921  for (const auto td : tables) {
4922  if (td->shard >= 0) {
4923  // skip shards, they're not standalone tables
4924  continue;
4925  }
4926 
4927  for (auto& cd : getAllColumnMetadataForTable(td->tableId, false, false, true)) {
4928  const auto& ti = cd->columnType;
4929  if (ti.is_string()) {
4930  if (ti.get_compression() == kENCODING_DICT) {
4931  // if foreign reference, get referenced tab.col
4932  const auto dict_id = ti.get_comp_param();
4933 
4934  // ignore temp (negative) dictionaries
4935  if (dict_id > 0 && mapping.end() == mapping.find(dict_id)) {
4936  mapping[dict_id] = cd;
4937  }
4938  }
4939  }
4940  }
4941  }
4942 
4943  return mapping;
4944 }
std::list< const TableDescriptor * > getAllTableMetadata() const
Definition: Catalog.cpp:2191
read_lock< Catalog > cat_read_lock
Definition: Catalog.cpp:124
std::list< const ColumnDescriptor * > getAllColumnMetadataForTable(const int tableId, const bool fetchSystemColumns, const bool fetchVirtualColumns, const bool fetchPhysicalColumns) const
Returns a list of pointers to constant ColumnDescriptor structs for all the columns from a particular...
Definition: Catalog.cpp:2175
const foreign_storage::ForeignServer * Catalog_Namespace::Catalog::getForeignServer ( const std::string &  server_name) const

Gets a pointer to a struct containing foreign server details.

Parameters
server_name- Name of foreign server whose details will be fetched
Returns
pointer to a struct containing foreign server details. nullptr is returned if no foreign server exists with the given name

Definition at line 3344 of file Catalog.cpp.

Referenced by DBObject::loadKey().

3345  {
3346  foreign_storage::ForeignServer* foreign_server = nullptr;
3347  cat_read_lock read_lock(this);
3348 
3349  if (foreignServerMap_.find(server_name) != foreignServerMap_.end()) {
3350  foreign_server = foreignServerMap_.find(server_name)->second.get();
3351  }
3352  return foreign_server;
3353 }
read_lock< Catalog > cat_read_lock
Definition: Catalog.cpp:124
ForeignServerMap foreignServerMap_
Definition: Catalog.h:715

+ Here is the caller graph for this function:

const std::unique_ptr< const foreign_storage::ForeignServer > Catalog_Namespace::Catalog::getForeignServerFromStorage ( const std::string &  server_name)

Gets a pointer to a struct containing foreign server details fetched from storage. This is mainly used for testing when asserting that expected catalog data is persisted.

Parameters
server_name- Name of foreign server whose details will be fetched
Returns
pointer to a struct containing foreign server details. nullptr is returned if no foreign server exists with the given name

Definition at line 3356 of file Catalog.cpp.

3356  {
3357  std::unique_ptr<foreign_storage::ForeignServer> foreign_server = nullptr;
3358  cat_sqlite_lock sqlite_lock(getObjForLock());
3360  "SELECT id, name, data_wrapper_type, options, owner_user_id, creation_time "
3361  "FROM omnisci_foreign_servers WHERE name = ?",
3362  std::vector<std::string>{server_name});
3363  if (sqliteConnector_.getNumRows() > 0) {
3364  foreign_server = std::make_unique<foreign_storage::ForeignServer>(
3365  sqliteConnector_.getData<int>(0, 0),
3366  sqliteConnector_.getData<std::string>(0, 1),
3367  sqliteConnector_.getData<std::string>(0, 2),
3368  sqliteConnector_.getData<std::string>(0, 3),
3369  sqliteConnector_.getData<std::int32_t>(0, 4),
3370  sqliteConnector_.getData<std::int32_t>(0, 5));
3371  }
3372  return foreign_server;
3373 }
T getData(const int row, const int col)
virtual void query_with_text_params(std::string const &query_only)
SqliteConnector sqliteConnector_
Definition: Catalog.h:720
const Catalog * getObjForLock()
Definition: Catalog.cpp:260
sqlite_lock< Catalog > cat_sqlite_lock
Definition: Catalog.cpp:126
virtual size_t getNumRows() const
const std::string Catalog_Namespace::Catalog::getForeignServerSchema ( bool  if_not_exists = false)
static

Gets the DDL statement used to create a foreign server schema.

Parameters
if_not_exists- flag that indicates whether or not to include the "IF NOT EXISTS" phrase in the DDL statement
Returns
string containing DDL statement

Definition at line 778 of file Catalog.cpp.

Referenced by Catalog_Namespace::SysCatalog::createDatabase(), and updateFsiSchemas().

778  {
779  return "CREATE TABLE " + (if_not_exists ? std::string{"IF NOT EXISTS "} : "") +
780  "omnisci_foreign_servers(id integer primary key, name text unique, " +
781  "data_wrapper_type text, owner_user_id integer, creation_time integer, " +
782  "options text)";
783 }

+ Here is the caller graph for this function:

void Catalog_Namespace::Catalog::getForeignServersForUser ( const rapidjson::Value *  filters,
const UserMetadata user,
std::vector< const foreign_storage::ForeignServer * > &  results 
)

Performs a query on all foreign servers accessible to user with optional filter, and returns pointers toresulting server objects

Parameters
filters- Json Value representing SQL WHERE clause to filter results, eg.: "WHERE attribute1 = value1 AND attribute2 LIKE value2", or Null Value Array of Values with attribute, value, operator, and chain specifier after first entry
user- user to retrieve server names
results- results returned as a vector of pointers to const foreign_storage::ForeignServer

Definition at line 3494 of file Catalog.cpp.

References CHECK, shared::contains(), lockmgr::instance(), DBObject::loadKey(), foreign_storage::ForeignServer::name, ServerDBObjectType, and to_string().

3497  {
3498  sys_read_lock syscat_read_lock(&SysCatalog::instance());
3499  cat_read_lock read_lock(this);
3500  cat_sqlite_lock sqlite_lock(getObjForLock());
3501  // Customer facing and internal SQlite names
3502  std::map<std::string, std::string> col_names{{"server_name", "name"},
3503  {"data_wrapper", "data_wrapper_type"},
3504  {"created_at", "creation_time"},
3505  {"options", "options"}};
3506 
3507  // TODO add "owner" when FSI privilege is implemented
3508  std::stringstream filter_string;
3509  std::vector<std::string> arguments;
3510 
3511  if (filters != nullptr) {
3512  // Create SQL WHERE clause for SQLite query
3513  int num_filters = 0;
3514  filter_string << " WHERE";
3515  for (auto& filter_def : filters->GetArray()) {
3516  if (num_filters > 0) {
3517  filter_string << " " << std::string(filter_def["chain"].GetString());
3518  ;
3519  }
3520 
3521  if (col_names.find(std::string(filter_def["attribute"].GetString())) ==
3522  col_names.end()) {
3523  throw std::runtime_error{"Attribute with name \"" +
3524  std::string(filter_def["attribute"].GetString()) +
3525  "\" does not exist."};
3526  }
3527 
3528  filter_string << " " << col_names[std::string(filter_def["attribute"].GetString())];
3529 
3530  bool equals_operator = false;
3531  if (std::strcmp(filter_def["operation"].GetString(), "EQUALS") == 0) {
3532  filter_string << " = ? ";
3533  equals_operator = true;
3534  } else {
3535  filter_string << " LIKE ? ";
3536  }
3537 
3538  bool timestamp_column =
3539  (std::strcmp(filter_def["attribute"].GetString(), "created_at") == 0);
3540 
3541  if (timestamp_column && !equals_operator) {
3542  throw std::runtime_error{"LIKE operator is incompatible with TIMESTAMP data"};
3543  }
3544 
3545  if (timestamp_column && equals_operator) {
3546  arguments.push_back(std::to_string(
3547  dateTimeParse<kTIMESTAMP>(filter_def["value"].GetString(), 0)));
3548  } else {
3549  arguments.emplace_back(filter_def["value"].GetString());
3550  }
3551 
3552  num_filters++;
3553  }
3554  }
3555  // Create select query for the omnisci_foreign_servers table
3556  std::string query = std::string("SELECT name from omnisci_foreign_servers ");
3557  query += filter_string.str();
3558 
3559  sqliteConnector_.query_with_text_params(query, arguments);
3560  auto num_rows = sqliteConnector_.getNumRows();
3561 
3562  if (sqliteConnector_.getNumRows() == 0) {
3563  return;
3564  }
3565 
3567  // Return pointers to objects
3568  results.reserve(num_rows);
3569  for (size_t row = 0; row < num_rows; ++row) {
3570  const auto& server_name = sqliteConnector_.getData<std::string>(row, 0);
3571  if (shared::contains(INTERNAL_SERVERS, server_name)) {
3572  continue;
3573  }
3574  const foreign_storage::ForeignServer* foreign_server = getForeignServer(server_name);
3575  CHECK(foreign_server != nullptr);
3576 
3577  DBObject dbObject(foreign_server->name, ServerDBObjectType);
3578  dbObject.loadKey(*this);
3579  std::vector<DBObject> privObjects = {dbObject};
3580  if (!SysCatalog::instance().hasAnyPrivileges(user, privObjects)) {
3581  // skip server, as there are no privileges to access it
3582  continue;
3583  }
3584  results.push_back(foreign_server);
3585  }
3586 }
bool contains(const T &container, const U &element)
Definition: misc.h:204
T getData(const int row, const int col)
virtual void query_with_text_params(std::string const &query_only)
const foreign_storage::ForeignServer * getForeignServer(const std::string &server_name) const
Definition: Catalog.cpp:3344
SqliteConnector sqliteConnector_
Definition: Catalog.h:720
read_lock< Catalog > cat_read_lock
Definition: Catalog.cpp:124
static constexpr std::array< const char *, 6 > INTERNAL_SERVERS
Definition: Catalog.h:898
std::string to_string(char const *&&v)
static SysCatalog & instance()
Definition: SysCatalog.h:343
const Catalog * getObjForLock()
Definition: Catalog.cpp:260
virtual size_t getNumCols() const
#define CHECK(condition)
Definition: Logger.h:291
read_lock< SysCatalog > sys_read_lock
Definition: Catalog.cpp:123
sqlite_lock< Catalog > cat_sqlite_lock
Definition: Catalog.cpp:126
virtual size_t getNumRows() const

+ Here is the call graph for this function:

const foreign_storage::ForeignTable * Catalog_Namespace::Catalog::getForeignTable ( const std::string &  tableName) const

Definition at line 1830 of file Catalog.cpp.

1831  {
1832  cat_read_lock read_lock(this);
1833  return getForeignTableUnlocked(tableName);
1834 }
read_lock< Catalog > cat_read_lock
Definition: Catalog.cpp:124
foreign_storage::ForeignTable * getForeignTableUnlocked(const std::string &tableName) const
Definition: Catalog.cpp:1821
const foreign_storage::ForeignTable * Catalog_Namespace::Catalog::getForeignTable ( int  table_id) const

Definition at line 2136 of file Catalog.cpp.

References CHECK.

2136  {
2137  cat_read_lock read_lock(this);
2138  const auto table = getMutableMetadataForTableUnlocked(table_id);
2139  CHECK(table);
2140  auto foreign_table = dynamic_cast<const foreign_storage::ForeignTable*>(table);
2141  CHECK(foreign_table);
2142  return foreign_table;
2143 }
read_lock< Catalog > cat_read_lock
Definition: Catalog.cpp:124
TableDescriptor * getMutableMetadataForTableUnlocked(int table_id) const
Definition: Catalog.cpp:1899
#define CHECK(condition)
Definition: Logger.h:291
const std::unique_ptr< const foreign_storage::ForeignTable > Catalog_Namespace::Catalog::getForeignTableFromStorage ( int  table_id)

Gets a pointer to a struct containing foreign table details fetched from storage. This is mainly used for testing when asserting that expected catalog data is persisted.

Parameters
table_name- Name of foreign table whose details will be fetched
Returns
pointer to a struct containing foreign table details. nullptr is returned if no foreign table exists with the given name

Definition at line 3376 of file Catalog.cpp.

References CHECK_EQ, and to_string().

3376  {
3377  std::unique_ptr<foreign_storage::ForeignTable> foreign_table = nullptr;
3378  cat_sqlite_lock sqlite_lock(getObjForLock());
3380  "SELECT table_id, server_id, options, last_refresh_time, next_refresh_time from "
3381  "omnisci_foreign_tables WHERE table_id = ?",
3382  std::vector<std::string>{to_string(table_id)});
3383  auto num_rows = sqliteConnector_.getNumRows();
3384  if (num_rows > 0) {
3385  CHECK_EQ(size_t(1), num_rows);
3386  foreign_table = std::make_unique<foreign_storage::ForeignTable>(
3387  sqliteConnector_.getData<int>(0, 0),
3388  foreignServerMapById_[sqliteConnector_.getData<int32_t>(0, 1)].get(),
3389  sqliteConnector_.getData<std::string>(0, 2),
3390  sqliteConnector_.getData<int64_t>(0, 3),
3391  sqliteConnector_.getData<int64_t>(0, 4));
3392  }
3393  return foreign_table;
3394 }
#define CHECK_EQ(x, y)
Definition: Logger.h:301
T getData(const int row, const int col)
virtual void query_with_text_params(std::string const &query_only)
SqliteConnector sqliteConnector_
Definition: Catalog.h:720
std::string to_string(char const *&&v)
ForeignServerMapById foreignServerMapById_
Definition: Catalog.h:716
const Catalog * getObjForLock()
Definition: Catalog.cpp:260
sqlite_lock< Catalog > cat_sqlite_lock
Definition: Catalog.cpp:126
virtual size_t getNumRows() const

+ Here is the call graph for this function:

const std::string Catalog_Namespace::Catalog::getForeignTableSchema ( bool  if_not_exists = false)
static

Gets the DDL statement used to create a foreign table schema.

Parameters
if_not_exists- flag that indicates whether or not to include the "IF NOT EXISTS" phrase in the DDL statement
Returns
string containing DDL statement

Definition at line 785 of file Catalog.cpp.

Referenced by Catalog_Namespace::SysCatalog::createDatabase(), and updateFsiSchemas().

785  {
786  return "CREATE TABLE " + (if_not_exists ? std::string{"IF NOT EXISTS "} : "") +
787  "omnisci_foreign_tables(table_id integer unique, server_id integer, " +
788  "options text, last_refresh_time integer, next_refresh_time integer, " +
789  "FOREIGN KEY(table_id) REFERENCES mapd_tables(tableid), " +
790  "FOREIGN KEY(server_id) REFERENCES omnisci_foreign_servers(id))";
791 }

+ Here is the caller graph for this function:

foreign_storage::ForeignTable * Catalog_Namespace::Catalog::getForeignTableUnlocked ( const std::string &  tableName) const
private

Definition at line 1821 of file Catalog.cpp.

References to_upper().

1822  {
1823  auto tableDescIt = tableDescriptorMap_.find(to_upper(tableName));
1824  if (tableDescIt == tableDescriptorMap_.end()) { // check to make sure table exists
1825  return nullptr;
1826  }
1827  return dynamic_cast<foreign_storage::ForeignTable*>(tableDescIt->second);
1828 }
std::string to_upper(const std::string &str)
TableDescriptorMap tableDescriptorMap_
Definition: Catalog.h:707

+ Here is the call graph for this function:

int Catalog_Namespace::Catalog::getLogicalTableId ( const int  physicalTableId) const

Definition at line 5018 of file Catalog.cpp.

Referenced by Fragmenter_Namespace::InsertOrderFragmenter::updateColumn(), Fragmenter_Namespace::InsertOrderFragmenter::updateColumns(), and TableOptimizer::vacuumFragments().

5018  {
5019  cat_read_lock read_lock(this);
5020  for (const auto& l : logicalToPhysicalTableMapById_) {
5021  if (l.second.end() != std::find_if(l.second.begin(),
5022  l.second.end(),
5023  [&](decltype(*l.second.begin()) tid) -> bool {
5024  return physicalTableId == tid;
5025  })) {
5026  return l.first;
5027  }
5028  }
5029  return physicalTableId;
5030 }
read_lock< Catalog > cat_read_lock
Definition: Catalog.cpp:124
LogicalToPhysicalTableMapById logicalToPhysicalTableMapById_
Definition: Catalog.h:727

+ Here is the caller graph for this function:

const ColumnDescriptor* Catalog_Namespace::Catalog::getMetadataForColumn ( int  tableId,
const std::string &  colName 
) const

Referenced by Parser::InsertStmt::analyze(), Parser::InsertValuesStmt::analyze(), Parser::QuerySpec::analyze_select_clause(), RelModify::applyUpdateModificationsToInputNode(), AlterTableAlterColumnCommandRecoveryMgr::cleanupDropSourceGeoColumns(), GeoLinestringValueConverter::GeoLinestringValueConverter(), GeoMultiLinestringValueConverter::GeoMultiLinestringValueConverter(), GeoMultiPointValueConverter::GeoMultiPointValueConverter(), GeoMultiPolygonValueConverter::GeoMultiPolygonValueConverter(), GeoPointValueConverter::GeoPointValueConverter(), GeoPolygonValueConverter::GeoPolygonValueConverter(), anonymous_namespace{DdlCommandExecutor.cpp}::get_alter_column_src_dst_cds(), Fragmenter_Namespace::get_chunks(), Analyzer::RangeTableEntry::get_column_desc(), foreign_storage::anonymous_namespace{AbstractTextFileDataWrapper.cpp}::get_columns(), Catalog_Namespace::anonymous_namespace{Catalog.cpp}::get_foreign_col(), getChunkAccessorTable(), Fragmenter_Namespace::InsertOrderFragmenter::getChunksForAllColumns(), AlterTableAlterColumnCommandRecoveryMgr::getSrcDstCds(), getSyntheticColumnVar(), foreign_storage::anonymous_namespace{InternalSystemDataWrapper.cpp}::initialize_chunks(), anonymous_namespace{ForeignDataImporter.cpp}::load_foreign_data_buffers(), serialize_column_ref(), import_export::Importer::set_geo_physical_import_buffer(), import_export::Importer::set_geo_physical_import_buffer_columnar(), Fragmenter_Namespace::SortedOrderFragmenter::sortData(), and Fragmenter_Namespace::InsertOrderFragmenter::updateColumn().

+ Here is the caller graph for this function:

const ColumnDescriptor * Catalog_Namespace::Catalog::getMetadataForColumn ( int  tableId,
int  columnId 
) const

Definition at line 1960 of file Catalog.cpp.

1960  {
1961  cat_read_lock read_lock(this);
1962  ColumnIdKey columnIdKey(table_id, column_id);
1963  auto colDescIt = columnDescriptorMapById_.find(columnIdKey);
1964  if (colDescIt == columnDescriptorMapById_
1965  .end()) { // need to check to make sure column exists for table
1966  return nullptr;
1967  }
1968  return colDescIt->second;
1969 }
read_lock< Catalog > cat_read_lock
Definition: Catalog.cpp:124
ColumnDescriptorMapById columnDescriptorMapById_
Definition: Catalog.h:710
std::tuple< int, int > ColumnIdKey
Definition: Types.h:39
const ColumnDescriptor * Catalog_Namespace::Catalog::getMetadataForColumnBySpi ( const int  tableId,
const size_t  spi 
) const

Definition at line 2004 of file Catalog.cpp.

2005  {
2006  cat_read_lock read_lock(this);
2007 
2008  const auto columnId = getColumnIdBySpiUnlocked(tableId, spi);
2009  ColumnIdKey columnIdKey(tableId, columnId);
2010  const auto colDescIt = columnDescriptorMapById_.find(columnIdKey);
2011  return columnDescriptorMapById_.end() == colDescIt ? nullptr : colDescIt->second;
2012 }
read_lock< Catalog > cat_read_lock
Definition: Catalog.cpp:124
ColumnDescriptorMapById columnDescriptorMapById_
Definition: Catalog.h:710
const int getColumnIdBySpiUnlocked(const int table_id, const size_t spi) const
Definition: Catalog.cpp:1981
std::tuple< int, int > ColumnIdKey
Definition: Types.h:39
const DashboardDescriptor* Catalog_Namespace::Catalog::getMetadataForDashboard ( const std::string &  userId,
const std::string &  dashName 
) const

Referenced by anonymous_namespace{DBHandler.cpp}::dashboard_exists(), and DBObject::loadKey().

+ Here is the caller graph for this function:

const DashboardDescriptor * Catalog_Namespace::Catalog::getMetadataForDashboard ( const int32_t  dashboard_id) const

Definition at line 2096 of file Catalog.cpp.

References setup::name, and to_string().

2096  {
2097  cat_read_lock read_lock(this);
2098  std::string userId;
2099  std::string name;
2100  bool found{false};
2101  {
2102  for (auto descp : dashboardDescriptorMap_) {
2103  auto dash = descp.second.get();
2104  if (dash->dashboardId == id) {
2105  userId = std::to_string(dash->userId);
2106  name = dash->dashboardName;
2107  found = true;
2108  break;
2109  }
2110  }
2111  }
2112  if (found) {
2113  return getMetadataForDashboard(userId, name);
2114  }
2115  return nullptr;
2116 }
read_lock< Catalog > cat_read_lock
Definition: Catalog.cpp:124
DashboardDescriptorMap dashboardDescriptorMap_
Definition: Catalog.h:712
std::string to_string(char const *&&v)
std::string name() const
Definition: Catalog.h:348
const DashboardDescriptor * getMetadataForDashboard(const std::string &userId, const std::string &dashName) const

+ Here is the call graph for this function:

const DictDescriptor * Catalog_Namespace::Catalog::getMetadataForDict ( int  dict_ref,
bool  loadDict = true 
) const

Definition at line 1907 of file Catalog.cpp.

References measure< TimeT >::execution(), g_cache_string_hash, logger::INFO, and LOG.

Referenced by AlterTableAlterColumnCommandRecoveryMgr::checkpoint(), DictionaryValueConverter< TARGET_TYPE >::DictionaryValueConverter(), import_export::fill_missing_columns(), import_export::Loader::init(), foreign_storage::anonymous_namespace{InternalSystemDataWrapper.cpp}::initialize_import_buffers(), anonymous_namespace{RelAlgExecutor.cpp}::insert_one_dict_str(), ArrowForeignStorageBase::parseArrowTable(), DBHandler::populateThriftColumnType(), and Fragmenter_Namespace::InsertOrderFragmenter::updateColumn().

1908  {
1909  cat_read_lock read_lock(this);
1910  const DictRef dictRef(currentDB_.dbId, dict_id);
1911  auto dictDescIt = dictDescriptorMapByRef_.find(dictRef);
1912  if (dictDescIt ==
1913  dictDescriptorMapByRef_.end()) { // check to make sure dictionary exists
1914  return nullptr;
1915  }
1916  auto& dd = dictDescIt->second;
1917 
1918  if (load_dict) {
1919  std::lock_guard string_dict_lock(*dd->string_dict_mutex);
1920  if (!dd->stringDict) {
1921  auto time_ms = measure<>::execution([&]() {
1922  if (string_dict_hosts_.empty()) {
1923  if (dd->dictIsTemp) {
1924  dd->stringDict = std::make_shared<StringDictionary>(
1925  dd->dictRef, dd->dictFolderPath, true, true, g_cache_string_hash);
1926  } else {
1927  dd->stringDict = std::make_shared<StringDictionary>(
1928  dd->dictRef, dd->dictFolderPath, false, true, g_cache_string_hash);
1929  }
1930  } else {
1931  dd->stringDict =
1932  std::make_shared<StringDictionary>(string_dict_hosts_.front(), dd->dictRef);
1933  }
1934  });
1935  LOG(INFO) << "Time to load Dictionary " << dd->dictRef.dbId << "_"
1936  << dd->dictRef.dictId << " was " << time_ms << "ms";
1937  }
1938  }
1939 
1940  return dd.get();
1941 }
std::lock_guard< T > lock_guard
static TimeT::rep execution(F func, Args &&...args)
Definition: sample.cpp:29
#define LOG(tag)
Definition: Logger.h:285
const std::vector< LeafHostInfo > string_dict_hosts_
Definition: Catalog.h:724
const DBMetadata currentDB_
Definition: Catalog.h:721
DictDescriptorMapById dictDescriptorMapByRef_
Definition: Catalog.h:711
read_lock< Catalog > cat_read_lock
Definition: Catalog.cpp:124
bool g_cache_string_hash

+ Here is the call graph for this function:

+ Here is the caller graph for this function:

const LinkDescriptor* Catalog_Namespace::Catalog::getMetadataForLink ( const std::string &  link) const
const LinkDescriptor * Catalog_Namespace::Catalog::getMetadataForLink ( int  linkId) const

Definition at line 2127 of file Catalog.cpp.

2127  {
2128  cat_read_lock read_lock(this);
2129  auto linkDescIt = linkDescriptorMapById_.find(linkId);
2130  if (linkDescIt == linkDescriptorMapById_.end()) { // check to make sure view exists
2131  return nullptr;
2132  }
2133  return linkDescIt->second;
2134 }
read_lock< Catalog > cat_read_lock
Definition: Catalog.cpp:124
LinkDescriptorMapById linkDescriptorMapById_
Definition: Catalog.h:714
const TableDescriptor* Catalog_Namespace::Catalog::getMetadataForTable ( const std::string &  tableName,
const bool  populateFragmenter = true 
) const

Returns a pointer to a const TableDescriptor struct matching the provided tableName.

Parameters
tableNametable specified column belongs to
Returns
pointer to const TableDescriptor object queried for or nullptr if it does not exist.

Referenced by lockmgr::TableSchemaLockContainer< ReadLock >::acquireTableDescriptor(), lockmgr::TableSchemaLockContainer< WriteLock >::acquireTableDescriptor(), Parser::InsertStmt::analyze(), Parser::QuerySpec::analyze_from_clause(), UpdelRoll::cancelUpdate(), anonymous_namespace{DBHandler.cpp}::check_and_reset_in_memory_system_table(), UpdelRoll::commitUpdate(), Fragmenter_Namespace::compute_row_indices_of_shards(), Fragmenter_Namespace::computeRowIndicesOfShards(), Fragmenter_Namespace::copy_data_of_shard(), Fragmenter_Namespace::copyDataOfShard(), anonymous_namespace{DBHandler.cpp}::create_custom_expr_from_thrift_obj(), anonymous_namespace{DBHandler.cpp}::create_thrift_obj_from_custom_expr(), Catalog_Namespace::anonymous_namespace{Catalog.cpp}::drop_tables(), RelAlgExecutor::executeSimpleInsert(), Executor::executeUpdate(), Catalog_Namespace::anonymous_namespace{Catalog.cpp}::get_foreign_col(), getSyntheticColumnVar(), Fragmenter_Namespace::LocalInsertConnector::insertChunksToLeaf(), Fragmenter_Namespace::LocalInsertConnector::insertDataToLeaf(), Parser::InsertValuesStmt::InsertValuesStmt(), DBObject::loadKey(), Parser::anonymous_namespace{ParserNode.cpp}::loadTable(), TableOptimizer::recomputeMetadataUnlocked(), TableArchiver::restoreTable(), serialize_table_ref(), Fragmenter_Namespace::set_chunk_metadata(), Fragmenter_Namespace::SortedOrderFragmenter::sortData(), Fragmenter_Namespace::InsertOrderFragmenter::updateColumnMetadata(), anonymous_namespace{DdlCommandExecutor.cpp}::vacuum_table_if_required(), TableOptimizer::vacuumFragmentsAboveMinSelectivity(), validate_shared_dictionary(), lockmgr::validate_table_descriptor_after_lock(), Parser::verifyObject(), StorageIOFacility::yieldDeleteCallback(), and StorageIOFacility::yieldUpdateCallback().

+ Here is the caller graph for this function:

const TableDescriptor * Catalog_Namespace::Catalog::getMetadataForTable ( int  tableId,
bool  populateFragmenter = true 
) const

Definition at line 1855 of file Catalog.cpp.

References Catalog_Namespace::read_lock< T >::unlock().

1856  {
1857  cat_read_lock read_lock(this);
1858  auto td = getMutableMetadataForTableUnlocked(table_id);
1859  if (!td) {
1860  return nullptr;
1861  }
1862  read_lock.unlock();
1863  if (populateFragmenter) {
1864  std::unique_lock<std::mutex> td_lock(*td->mutex_.get());
1865  if (td->fragmenter == nullptr && !td->isView) {
1867  }
1868  }
1869  return td;
1870 }
void instantiateFragmenter(TableDescriptor *td) const
Definition: Catalog.cpp:1781
read_lock< Catalog > cat_read_lock
Definition: Catalog.cpp:124
TableDescriptor * getMutableMetadataForTableUnlocked(int table_id) const
Definition: Catalog.cpp:1899

+ Here is the call graph for this function:

TableDescriptor * Catalog_Namespace::Catalog::getMutableMetadataForTableUnlocked ( int  table_id) const
private

Definition at line 1899 of file Catalog.cpp.

1899  {
1900  auto tableDescIt = tableDescriptorMapById_.find(table_id);
1901  if (tableDescIt == tableDescriptorMapById_.end()) { // check to make sure table exists
1902  return nullptr;
1903  }
1904  return tableDescIt->second;
1905 }
TableDescriptorMapById tableDescriptorMapById_
Definition: Catalog.h:708
TableDescriptor * Catalog_Namespace::Catalog::getMutableMetadataForTableUnlocked ( const std::string &  table_name) const
private

Definition at line 1890 of file Catalog.cpp.

References to_upper().

1891  {
1892  auto it = tableDescriptorMap_.find(to_upper(table_name));
1893  if (it == tableDescriptorMap_.end()) {
1894  return nullptr;
1895  }
1896  return it->second;
1897 }
std::string to_upper(const std::string &str)
TableDescriptorMap tableDescriptorMap_
Definition: Catalog.h:707

+ Here is the call graph for this function:

int Catalog_Namespace::Catalog::getNextAddedColumnId ( const TableDescriptor td)

Definition at line 2451 of file Catalog.cpp.

References TableDescriptor::tableId, and to_string().

2451  {
2452  cat_read_lock read_lock(this);
2454  "SELECT max(columnid) + 1 FROM mapd_columns WHERE tableid = ?",
2455  std::vector<std::string>{std::to_string(td.tableId)});
2456  return sqliteConnector_.getData<int>(0, 0);
2457 }
T getData(const int row, const int col)
virtual void query_with_text_params(std::string const &query_only)
SqliteConnector sqliteConnector_
Definition: Catalog.h:720
read_lock< Catalog > cat_read_lock
Definition: Catalog.cpp:124
std::string to_string(char const *&&v)

+ Here is the call graph for this function:

const Catalog * Catalog_Namespace::Catalog::getObjForLock ( )
private

Definition at line 260 of file Catalog.cpp.

References Catalog_Namespace::SysCatalog::getDummyCatalog(), initialized_, and Catalog_Namespace::SysCatalog::instance().

Referenced by CheckAndExecuteMigrations(), checkDateInDaysColumnMigration(), createDashboardSystemRoles(), recordOwnershipOfObjectsInObjectPermissions(), reloadTableMetadata(), renameLegacyDataWrappers(), updateCustomExpressionsSchema(), updateDefaultColumnValues(), updateDeletedColumnIndicator(), updateDictionaryNames(), updateDictionarySchema(), updateFixlenArrayColumns(), updateFrontendViewAndLinkUsers(), updateFrontendViewSchema(), updateFrontendViewsToDashboards(), updateFsiSchemas(), updateGeoColumns(), updateLinkSchema(), updateLogicalToPhysicalTableLinkSchema(), updateLogicalToPhysicalTableMap(), updatePageSize(), and updateTableDescriptorSchema().

260  {
261  if (initialized_) {
262  return this;
263  } else {
264  return SysCatalog::instance().getDummyCatalog().get();
265  }
266 }
std::shared_ptr< Catalog > getDummyCatalog()
Definition: SysCatalog.h:369
static SysCatalog & instance()
Definition: SysCatalog.h:343

+ Here is the call graph for this function:

+ Here is the caller graph for this function:

std::vector< const TableDescriptor * > Catalog_Namespace::Catalog::getPhysicalTablesDescriptors ( const TableDescriptor logical_table_desc,
bool  populate_fragmenter = true 
) const

Definition at line 4879 of file Catalog.cpp.

References CHECK, TableDescriptor::tableId, and Catalog_Namespace::read_lock< T >::unlock().

Referenced by Fragmenter_Namespace::copy_data_of_shard(), Fragmenter_Namespace::copyDataOfShard(), import_export::Loader::distributeToShardsNewColumns(), import_export::Loader::dropColumns(), anonymous_namespace{DdlCommandExecutor.cpp}::get_agg_storage_stats(), import_export::Loader::loadImpl(), TableOptimizer::recomputeMetadata(), and TableOptimizer::vacuumDeletedRows().

4881  {
4882  cat_read_lock read_lock(this);
4883  const auto physicalTableIt =
4884  logicalToPhysicalTableMapById_.find(logical_table_desc->tableId);
4885  if (physicalTableIt == logicalToPhysicalTableMapById_.end()) {
4886  return {logical_table_desc};
4887  }
4888  const auto physicalTablesIds = physicalTableIt->second;
4889  CHECK(!physicalTablesIds.empty());
4890  read_lock.unlock();
4891  std::vector<const TableDescriptor*> physicalTables;
4892  for (size_t i = 0; i < physicalTablesIds.size(); i++) {
4893  physicalTables.push_back(
4894  getMetadataForTable(physicalTablesIds[i], populate_fragmenter));
4895  }
4896  return physicalTables;
4897 }
read_lock< Catalog > cat_read_lock
Definition: Catalog.cpp:124
#define CHECK(condition)
Definition: Logger.h:291
const TableDescriptor * getMetadataForTable(const std::string &tableName, const bool populateFragmenter=true) const
Returns a pointer to a const TableDescriptor struct matching the provided tableName.
LogicalToPhysicalTableMapById logicalToPhysicalTableMapById_
Definition: Catalog.h:727

+ Here is the call graph for this function:

+ Here is the caller graph for this function:

const ColumnDescriptor * Catalog_Namespace::Catalog::getShardColumnMetadataForTable ( const TableDescriptor td) const

Definition at line 4861 of file Catalog.cpp.

References TableDescriptor::shardedColumnId, and TableDescriptor::tableId.

Referenced by RelModify::applyUpdateModificationsToInputNode(), Fragmenter_Namespace::compute_row_indices_of_shards(), and Fragmenter_Namespace::computeRowIndicesOfShards().

4862  {
4863  cat_read_lock read_lock(this);
4864 
4865  const auto column_descriptors =
4866  getAllColumnMetadataForTable(td->tableId, false, true, true);
4867 
4868  const ColumnDescriptor* shard_cd{nullptr};
4869  int i = 1;
4870  for (auto cd_itr = column_descriptors.begin(); cd_itr != column_descriptors.end();
4871  ++cd_itr, ++i) {
4872  if (i == td->shardedColumnId) {
4873  shard_cd = *cd_itr;
4874  }
4875  }
4876  return shard_cd;
4877 }
read_lock< Catalog > cat_read_lock
Definition: Catalog.cpp:124
specifies the content in-memory of a row in the column metadata table
std::list< const ColumnDescriptor * > getAllColumnMetadataForTable(const int tableId, const bool fetchSystemColumns, const bool fetchVirtualColumns, const bool fetchPhysicalColumns) const
Returns a list of pointers to constant ColumnDescriptor structs for all the columns from a particular...
Definition: Catalog.cpp:2175

+ Here is the caller graph for this function:

SqliteConnector& Catalog_Namespace::Catalog::getSqliteConnector ( )
inline

Definition at line 327 of file Catalog.h.

References sqliteConnector_.

327 { return sqliteConnector_; }
SqliteConnector sqliteConnector_
Definition: Catalog.h:720
const std::vector< LeafHostInfo > & Catalog_Namespace::Catalog::getStringDictionaryHosts ( ) const

Definition at line 1943 of file Catalog.cpp.

1943  {
1944  return string_dict_hosts_;
1945 }
const std::vector< LeafHostInfo > string_dict_hosts_
Definition: Catalog.h:724
std::pair< foreign_storage::ForeignTable, std::list< ColumnDescriptor > > Catalog_Namespace::Catalog::getSystemTableSchema ( const std::string &  table_name,
const std::string &  server_name,
const std::vector< std::pair< std::string, SQLTypeInfo >> &  column_type_by_name,
bool  is_in_memory_system_table 
)
private

Definition at line 6883 of file Catalog.cpp.

References CHECK, DEFAULT_FRAGMENT_ROWS, DEFAULT_MAX_CHUNK_SIZE, DEFAULT_MAX_ROWS, DEFAULT_PAGE_SIZE, foreign_storage::ForeignTable::foreign_server, StorageType::FOREIGN_TABLE, TableDescriptor::fragmenter, TableDescriptor::fragments, TableDescriptor::fragPageSize, TableDescriptor::fragType, TableDescriptor::hasDeletedCol, Fragmenter_Namespace::INSERT_ORDER, TableDescriptor::is_in_memory_system_table, TableDescriptor::is_system_table, TableDescriptor::isView, TableDescriptor::keyMetainfo, shared::kRootUserId, TableDescriptor::maxChunkSize, TableDescriptor::maxFragRows, TableDescriptor::maxRows, TableDescriptor::nColumns, TableDescriptor::partitions, TableDescriptor::storageType, TableDescriptor::tableName, and TableDescriptor::userId.

6887  {
6888  foreign_storage::ForeignTable foreign_table;
6889  foreign_table.tableName = table_name;
6890  foreign_table.nColumns = column_type_by_name.size();
6891  foreign_table.isView = false;
6892  foreign_table.is_system_table = true;
6893  foreign_table.is_in_memory_system_table = is_in_memory_system_table;
6894  foreign_table.fragmenter = nullptr;
6896  foreign_table.maxFragRows = DEFAULT_FRAGMENT_ROWS;
6897  foreign_table.maxChunkSize = DEFAULT_MAX_CHUNK_SIZE;
6898  foreign_table.fragPageSize = DEFAULT_PAGE_SIZE;
6899  foreign_table.maxRows = DEFAULT_MAX_ROWS;
6900  foreign_table.userId = shared::kRootUserId;
6901  foreign_table.storageType = StorageType::FOREIGN_TABLE;
6902  foreign_table.hasDeletedCol = false;
6903  foreign_table.keyMetainfo = "[]";
6904  foreign_table.fragments = "";
6905  foreign_table.partitions = "";
6906  foreign_table.foreign_server = getForeignServer(server_name);
6907  CHECK(foreign_table.foreign_server);
6908 
6909  list<ColumnDescriptor> columns;
6910  for (const auto& [column_name, column_type] : column_type_by_name) {
6911  columns.emplace_back();
6912  auto& cd = columns.back();
6913  cd.columnName = column_name;
6914  cd.columnType = column_type;
6915  cd.isSystemCol = false;
6916  cd.isVirtualCol = false;
6917  }
6918  return {foreign_table, columns};
6919 }
std::string partitions
const int kRootUserId
std::string tableName
const foreign_storage::ForeignServer * getForeignServer(const std::string &server_name) const
Definition: Catalog.cpp:3344
std::string storageType
#define DEFAULT_MAX_CHUNK_SIZE
std::string fragments
bool is_in_memory_system_table
#define DEFAULT_MAX_ROWS
std::string keyMetainfo
std::shared_ptr< Fragmenter_Namespace::AbstractFragmenter > fragmenter
#define DEFAULT_PAGE_SIZE
#define DEFAULT_FRAGMENT_ROWS
Fragmenter_Namespace::FragmenterType fragType
const ForeignServer * foreign_server
Definition: ForeignTable.h:57
#define CHECK(condition)
Definition: Logger.h:291
static constexpr char const * FOREIGN_TABLE
std::vector< std::string > Catalog_Namespace::Catalog::getTableDataDirectories ( const TableDescriptor td) const

Definition at line 5384 of file Catalog.cpp.

Referenced by TableArchiver::dumpTable(), and TableArchiver::restoreTable().

5385  {
5386  const auto global_file_mgr = getDataMgr().getGlobalFileMgr();
5387  std::vector<std::string> file_paths;
5388  for (auto shard : getPhysicalTablesDescriptors(td)) {
5389  const auto file_mgr = dynamic_cast<File_Namespace::FileMgr*>(
5390  global_file_mgr->getFileMgr(currentDB_.dbId, shard->tableId));
5391  boost::filesystem::path file_path(file_mgr->getFileMgrBasePath());
5392  file_paths.push_back(file_path.filename().string());
5393  }
5394  return file_paths;
5395 }
Data_Namespace::DataMgr & getDataMgr() const
Definition: Catalog.h:266
const DBMetadata currentDB_
Definition: Catalog.h:721
std::vector< const TableDescriptor * > getPhysicalTablesDescriptors(const TableDescriptor *logical_table_desc, bool populate_fragmenter=true) const
Definition: Catalog.cpp:4879
File_Namespace::GlobalFileMgr * getGlobalFileMgr() const
Definition: DataMgr.cpp:699

+ Here is the caller graph for this function:

std::vector< std::string > Catalog_Namespace::Catalog::getTableDictDirectories ( const TableDescriptor td) const

Definition at line 5419 of file Catalog.cpp.

References TableDescriptor::tableId.

Referenced by TableArchiver::dumpTable(), and TableArchiver::restoreTable().

5420  {
5421  std::vector<std::string> file_paths;
5422  for (auto cd : getAllColumnMetadataForTable(td->tableId, false, false, true)) {
5423  auto file_base = getColumnDictDirectory(cd);
5424  if (!file_base.empty() &&
5425  file_paths.end() == std::find(file_paths.begin(), file_paths.end(), file_base)) {
5426  file_paths.push_back(file_base);
5427  }
5428  }
5429  return file_paths;
5430 }
std::string getColumnDictDirectory(const ColumnDescriptor *cd, bool file_name_only=true) const
Definition: Catalog.cpp:5398
std::list< const ColumnDescriptor * > getAllColumnMetadataForTable(const int tableId, const bool fetchSystemColumns, const bool fetchVirtualColumns, const bool fetchPhysicalColumns) const
Returns a list of pointers to constant ColumnDescriptor structs for all the columns from a particular...
Definition: Catalog.cpp:2175

+ Here is the caller graph for this function:

std::set< std::string > Catalog_Namespace::Catalog::getTableDictDirectoryPaths ( int32_t  table_id) const

Definition at line 5432 of file Catalog.cpp.

5432  {
5433  cat_read_lock read_lock(this);
5434  std::set<std::string> directory_paths;
5435  auto it = dict_columns_by_table_id_.find(table_id);
5436  if (it != dict_columns_by_table_id_.end()) {
5437  for (auto cd : it->second) {
5438  auto directory_path = getColumnDictDirectory(cd, false);
5439  if (!directory_path.empty()) {
5440  directory_paths.emplace(directory_path);
5441  }
5442  }
5443  }
5444  return directory_paths;
5445 }
TableDictColumnsMap dict_columns_by_table_id_
Definition: Catalog.h:718
std::string getColumnDictDirectory(const ColumnDescriptor *cd, bool file_name_only=true) const
Definition: Catalog.cpp:5398
read_lock< Catalog > cat_read_lock
Definition: Catalog.cpp:124
int32_t Catalog_Namespace::Catalog::getTableEpoch ( const int32_t  db_id,
const int32_t  table_id 
) const

Definition at line 3589 of file Catalog.cpp.

References CHECK, logger::ERROR, logger::INFO, and LOG.

Referenced by TableArchiver::dumpTable().

3589  {
3590  cat_read_lock read_lock(this);
3591  const auto td = getMetadataForTable(table_id, false);
3592  if (!td) {
3593  std::stringstream table_not_found_error_message;
3594  table_not_found_error_message << "Table (" << db_id << "," << table_id
3595  << ") not found";
3596  throw std::runtime_error(table_not_found_error_message.str());
3597  }
3598  const auto physicalTableIt = logicalToPhysicalTableMapById_.find(table_id);
3599  if (physicalTableIt != logicalToPhysicalTableMapById_.end()) {
3600  // check all shards have same checkpoint
3601  const auto physicalTables = physicalTableIt->second;
3602  CHECK(!physicalTables.empty());
3603  size_t curr_epoch{0}, first_epoch{0};
3604  int32_t first_table_id{0};
3605  bool are_epochs_inconsistent{false};
3606  for (size_t i = 0; i < physicalTables.size(); i++) {
3607  int32_t physical_tb_id = physicalTables[i];
3608  const TableDescriptor* phys_td = getMetadataForTable(physical_tb_id, false);
3609  CHECK(phys_td);
3610 
3611  curr_epoch = dataMgr_->getTableEpoch(db_id, physical_tb_id);
3612  LOG(INFO) << "Got sharded table epoch for db id: " << db_id
3613  << ", table id: " << physical_tb_id << ", epoch: " << curr_epoch;
3614  if (i == 0) {
3615  first_epoch = curr_epoch;
3616  first_table_id = physical_tb_id;
3617  } else if (first_epoch != curr_epoch) {
3618  are_epochs_inconsistent = true;
3619  LOG(ERROR) << "Epochs on shards do not all agree on table id: " << table_id
3620  << ", db id: " << db_id
3621  << ". First table (table id: " << first_table_id
3622  << ") has epoch: " << first_epoch << ". Table id: " << physical_tb_id
3623  << ", has inconsistent epoch: " << curr_epoch
3624  << ". See previous INFO logs for all epochs and their table ids.";
3625  }
3626  }
3627  if (are_epochs_inconsistent) {
3628  // oh dear the shards do not agree on the epoch for this table
3629  return -1;
3630  }
3631  return curr_epoch;
3632  } else {
3633  auto epoch = dataMgr_->getTableEpoch(db_id, table_id);
3634  LOG(INFO) << "Got table epoch for db id: " << db_id << ", table id: " << table_id
3635  << ", epoch: " << epoch;
3636  return epoch;
3637  }
3638 }
#define LOG(tag)
Definition: Logger.h:285
std::shared_ptr< Data_Namespace::DataMgr > dataMgr_
Definition: Catalog.h:722
read_lock< Catalog > cat_read_lock
Definition: Catalog.cpp:124
#define CHECK(condition)
Definition: Logger.h:291
const TableDescriptor * getMetadataForTable(const std::string &tableName, const bool populateFragmenter=true) const
Returns a pointer to a const TableDescriptor struct matching the provided tableName.
LogicalToPhysicalTableMapById logicalToPhysicalTableMapById_
Definition: Catalog.h:727

+ Here is the caller graph for this function:

std::vector< TableEpochInfo > Catalog_Namespace::Catalog::getTableEpochs ( const int32_t  db_id,
const int32_t  table_id 
) const

Definition at line 3831 of file Catalog.cpp.

References CHECK, logger::INFO, and LOG.

Referenced by UpdelRoll::cancelUpdate(), UpdelRoll::commitUpdate(), import_export::Loader::getTableEpochs(), AlterTableAlterColumnCommandRecoveryMgr::recoverAlterTableAlterColumnFromFile(), TableOptimizer::vacuumDeletedRows(), TableOptimizer::vacuumFragmentsAboveMinSelectivity(), and system_validator::SingleNodeValidator::validate().

3832  {
3833  cat_read_lock read_lock(this);
3834  std::vector<TableEpochInfo> table_epochs;
3835  const auto physical_table_it = logicalToPhysicalTableMapById_.find(table_id);
3836  if (physical_table_it != logicalToPhysicalTableMapById_.end()) {
3837  const auto physical_tables = physical_table_it->second;
3838  CHECK(!physical_tables.empty());
3839 
3840  for (const auto physical_tb_id : physical_tables) {
3841  const auto phys_td = getMutableMetadataForTableUnlocked(physical_tb_id);
3842  CHECK(phys_td);
3843 
3844  auto table_id = phys_td->tableId;
3845  auto epoch = dataMgr_->getTableEpoch(db_id, phys_td->tableId);
3846  table_epochs.emplace_back(table_id, epoch);
3847  LOG(INFO) << "Got sharded table epoch for db id: " << db_id
3848  << ", table id: " << table_id << ", epoch: " << epoch;
3849  }
3850  } else {
3851  auto epoch = dataMgr_->getTableEpoch(db_id, table_id);
3852  LOG(INFO) << "Got table epoch for db id: " << db_id << ", table id: " << table_id
3853  << ", epoch: " << epoch;
3854  table_epochs.emplace_back(table_id, epoch);
3855  }
3856  return table_epochs;
3857 }
#define LOG(tag)
Definition: Logger.h:285
std::shared_ptr< Data_Namespace::DataMgr > dataMgr_
Definition: Catalog.h:722
read_lock< Catalog > cat_read_lock
Definition: Catalog.cpp:124
TableDescriptor * getMutableMetadataForTableUnlocked(int table_id) const
Definition: Catalog.cpp:1899
#define CHECK(condition)
Definition: Logger.h:291
LogicalToPhysicalTableMapById logicalToPhysicalTableMapById_
Definition: Catalog.h:727

+ Here is the caller graph for this function:

std::optional< int32_t > Catalog_Namespace::Catalog::getTableId ( const std::string &  table_name) const

Definition at line 1881 of file Catalog.cpp.

Referenced by lockmgr::helpers::chunk_key_for_table(), and lockmgr::TableLockMgrImpl< T >::validateAndGetExistingTableId().

1881  {
1882  cat_read_lock read_lock(this);
1883  auto td = getMutableMetadataForTableUnlocked(table_name);
1884  if (!td) {
1885  return {};
1886  }
1887  return td->tableId;
1888 }
read_lock< Catalog > cat_read_lock
Definition: Catalog.cpp:124
TableDescriptor * getMutableMetadataForTableUnlocked(int table_id) const
Definition: Catalog.cpp:1899

+ Here is the caller graph for this function:

std::optional< std::string > Catalog_Namespace::Catalog::getTableName ( int32_t  table_id) const

Definition at line 1872 of file Catalog.cpp.

Referenced by lockmgr::TableSchemaLockContainer< ReadLock >::acquireTableDescriptor(), lockmgr::TableSchemaLockContainer< WriteLock >::acquireTableDescriptor(), Catalog_Namespace::anonymous_namespace{Catalog.cpp}::get_checked_table_name(), AlterTableAlterColumnCommandRecoveryMgr::getRecoveryFilepathInfo(), and AlterTableAlterColumnCommandRecoveryMgr::recoverAlterTableAlterColumnFromFile().

1872  {
1873  cat_read_lock read_lock(this);
1874  auto td = getMutableMetadataForTableUnlocked(table_id);
1875  if (!td) {
1876  return {};
1877  }
1878  return td->tableName;
1879 }
read_lock< Catalog > cat_read_lock
Definition: Catalog.cpp:124
TableDescriptor * getMutableMetadataForTableUnlocked(int table_id) const
Definition: Catalog.cpp:1899

+ Here is the caller graph for this function:

std::vector< std::string > Catalog_Namespace::Catalog::getTableNamesForUser ( const UserMetadata user,
const GetTablesType  get_tables_type 
) const

Get names of all tables accessible to user.

Parameters
user- user to retrieve table names for
get_tables_type- enum indicating if tables, views or tables & views should be returned
Returns
table_names - vector of table names accessible by user

Definition at line 4979 of file Catalog.cpp.

References lockmgr::instance(), and run_benchmark_import::tables.

Referenced by DBHandler::get_tables_impl().

4981  {
4982  sys_read_lock syscat_read_lock(&SysCatalog::instance());
4983  cat_read_lock read_lock(this);
4984  std::vector<std::string> table_names;
4985  const auto tables = getAllTableMetadata();
4986  for (const auto td : tables) {
4987  if (filterTableByTypeAndUser(td, user_metadata, get_tables_type)) {
4988  table_names.push_back(td->tableName);
4989  }
4990  }
4991  return table_names;
4992 }
std::list< const TableDescriptor * > getAllTableMetadata() const
Definition: Catalog.cpp:2191
read_lock< Catalog > cat_read_lock
Definition: Catalog.cpp:124
bool filterTableByTypeAndUser(const TableDescriptor *td, const UserMetadata &user_metadata, const GetTablesType get_tables_type) const
Definition: Catalog.cpp:4946
static SysCatalog & instance()
Definition: SysCatalog.h:343
read_lock< SysCatalog > sys_read_lock
Definition: Catalog.cpp:123

+ Here is the call graph for this function:

+ Here is the caller graph for this function:

std::vector< TableMetadata > Catalog_Namespace::Catalog::getTablesMetadataForUser ( const UserMetadata user_metadata,
const GetTablesType  get_tables_type,
const std::string &  filter_table_name 
) const

Get table descriptors of all tables accessible to user.

Parameters
user- user to retrieve table descriptors for
get_tables_type- enum indicating if tables, views or tables & views should be returned
Returns
table_descriptors - vector of table descriptors accessible by user

Definition at line 4994 of file Catalog.cpp.

References lockmgr::instance(), and run_benchmark_import::tables.

4997  {
4998  sys_read_lock syscat_read_lock(&SysCatalog::instance());
4999  cat_read_lock read_lock(this);
5000 
5001  std::vector<TableMetadata> tables_metadata;
5002  const auto tables = getAllTableMetadata();
5003  for (const auto td : tables) {
5004  if (filterTableByTypeAndUser(td, user_metadata, get_tables_type)) {
5005  if (!filter_table_name.empty()) {
5006  if (td->tableName != filter_table_name) {
5007  continue;
5008  }
5009  }
5010  TableMetadata table_metadata(td); // Makes a copy, not safe to access raw table
5011  // descriptor outside catalog lock
5012  tables_metadata.emplace_back(table_metadata);
5013  }
5014  }
5015  return tables_metadata;
5016 }
std::list< const TableDescriptor * > getAllTableMetadata() const
Definition: Catalog.cpp:2191
read_lock< Catalog > cat_read_lock
Definition: Catalog.cpp:124
bool filterTableByTypeAndUser(const TableDescriptor *td, const UserMetadata &user_metadata, const GetTablesType get_tables_type) const
Definition: Catalog.cpp:4946
static SysCatalog & instance()
Definition: SysCatalog.h:343
read_lock< SysCatalog > sys_read_lock
Definition: Catalog.cpp:123

+ Here is the call graph for this function:

size_t Catalog_Namespace::Catalog::getTotalMemorySizeForDictionariesForDatabase ( ) const

Definition at line 2380 of file Catalog.cpp.

Referenced by anonymous_namespace{DBHandler.cpp}::log_cache_size().

2380  {
2381  size_t ret{0};
2382  for (auto const& kv : dictDescriptorMapByRef_) {
2383  if (kv.first.dbId == currentDB_.dbId) {
2384  auto dictionary = kv.second.get()->stringDict.get();
2385  if (dictionary) {
2386  ret += dictionary->computeCacheSize();
2387  }
2388  }
2389  }
2390  return ret;
2391 }
const DBMetadata currentDB_
Definition: Catalog.h:721
DictDescriptorMapById dictDescriptorMapByRef_
Definition: Catalog.h:711

+ Here is the caller graph for this function:

void Catalog_Namespace::Catalog::initializeDashboardsSystemTable ( )
private

Definition at line 6605 of file Catalog.cpp.

References Catalog_Namespace::DASHBOARDS_SYS_TABLE_NAME, Catalog_Namespace::anonymous_namespace{Catalog.cpp}::get_encoded_text_type(), Catalog_Namespace::anonymous_namespace{Catalog.cpp}::get_var_encoded_text_array_type(), kINT, and kTIMESTAMP.

6605  {
6606  auto [foreign_table, columns] =
6609  {{"database_id", {kINT}},
6610  {"database_name", get_encoded_text_type()},
6611  {"dashboard_id", {kINT}},
6612  {"dashboard_name", get_encoded_text_type()},
6613  {"owner_id", {kINT}},
6614  {"owner_user_name", get_encoded_text_type()},
6615  {"last_updated_at", {kTIMESTAMP}},
6616  {"data_sources", get_var_encoded_text_array_type()}},
6617  true);
6618  recreateSystemTableIfUpdated(foreign_table, columns);
6619 }
std::pair< foreign_storage::ForeignTable, std::list< ColumnDescriptor > > getSystemTableSchema(const std::string &table_name, const std::string &server_name, const std::vector< std::pair< std::string, SQLTypeInfo >> &column_type_by_name, bool is_in_memory_system_table)
Definition: Catalog.cpp:6883
static constexpr const char * DASHBOARDS_SYS_TABLE_NAME
Definition: Catalog.h:114
static constexpr const char * CATALOG_SERVER_NAME
Definition: Catalog.h:892
Definition: sqltypes.h:72
bool recreateSystemTableIfUpdated(foreign_storage::ForeignTable &foreign_table, const std::list< ColumnDescriptor > &columns)
Definition: Catalog.cpp:6921

+ Here is the call graph for this function:

void Catalog_Namespace::Catalog::initializeDatabasesSystemTable ( )
private

Definition at line 6542 of file Catalog.cpp.

References Catalog_Namespace::DATABASES_SYS_TABLE_NAME, Catalog_Namespace::anonymous_namespace{Catalog.cpp}::get_encoded_text_type(), and kINT.

6542  {
6543  auto [foreign_table, columns] =
6546  {{"database_id", {kINT}},
6547  {"database_name", get_encoded_text_type()},
6548  {"owner_id", {kINT}},
6549  {"owner_user_name", get_encoded_text_type()}},
6550  true);
6551  recreateSystemTableIfUpdated(foreign_table, columns);
6552 }
std::pair< foreign_storage::ForeignTable, std::list< ColumnDescriptor > > getSystemTableSchema(const std::string &table_name, const std::string &server_name, const std::vector< std::pair< std::string, SQLTypeInfo >> &column_type_by_name, bool is_in_memory_system_table)
Definition: Catalog.cpp:6883
static constexpr const char * DATABASES_SYS_TABLE_NAME
Definition: Catalog.h:115
static constexpr const char * CATALOG_SERVER_NAME
Definition: Catalog.h:892
Definition: sqltypes.h:72
bool recreateSystemTableIfUpdated(foreign_storage::ForeignTable &foreign_table, const std::list< ColumnDescriptor > &columns)
Definition: Catalog.cpp:6921

+ Here is the call graph for this function:

void Catalog_Namespace::Catalog::initializeExecutorResourcePoolSummarySystemTable ( )
private

Definition at line 6696 of file Catalog.cpp.

References Catalog_Namespace::EXECUTOR_RESOURCE_POOL_SUMMARY_SYS_TABLE_NAME, kBIGINT, and kINT.

6696  {
6697  auto [foreign_table, columns] =
6700  {{"total_cpu_slots", {kINT}},
6701  {"total_gpu_slots", {kINT}},
6702  {"total_cpu_result_mem", {kBIGINT}},
6703  {"total_cpu_buffer_pool_mem", {kBIGINT}},
6704  {"total_gpu_buffer_pool_mem", {kBIGINT}},
6705  {"allocated_cpu_slots", {kINT}},
6706  {"allocated_gpu_slots", {kINT}},
6707  {"allocated_cpu_result_mem", {kBIGINT}},
6708  {"allocated_cpu_buffer_pool_mem", {kBIGINT}},
6709  {"allocated_gpu_buffer_pool_mem", {kBIGINT}},
6710  {"allocated_cpu_buffers", {kINT}},
6711  {"allocated_gpu_buffers", {kINT}},
6712  {"allocated_temp_cpu_buffer_pool_mem", {kBIGINT}},
6713  {"allocated_temp_gpu_buffer_pool_mem", {kBIGINT}},
6714  {"total_requests", {kBIGINT}},
6715  {"outstanding_requests", {kINT}},
6716  {"outstanding_cpu_slots_requests", {kINT}},
6717  {"outstanding_gpu_slots_requests", {kINT}},
6718  {"outstanding_cpu_result_mem_requests", {kINT}},
6719  {"outstanding_cpu_buffer_pool_mem_requests", {kINT}},
6720  {"outstanding_gpu_buffer_pool_mem_requests", {kINT}}},
6721  true);
6722  recreateSystemTableIfUpdated(foreign_table, columns);
6723 }
std::pair< foreign_storage::ForeignTable, std::list< ColumnDescriptor > > getSystemTableSchema(const std::string &table_name, const std::string &server_name, const std::vector< std::pair< std::string, SQLTypeInfo >> &column_type_by_name, bool is_in_memory_system_table)
Definition: Catalog.cpp:6883
static constexpr const char * EXECUTOR_RESOURCE_POOL_SUMMARY_SYS_TABLE_NAME
Definition: Catalog.h:122
static constexpr const char * EXECUTOR_STATS_SERVER_NAME
Definition: Catalog.h:895
Definition: sqltypes.h:72
bool recreateSystemTableIfUpdated(foreign_storage::ForeignTable &foreign_table, const std::list< ColumnDescriptor > &columns)
Definition: Catalog.cpp:6921
void Catalog_Namespace::Catalog::initializeMemoryDetailsSystemTable ( )
private

Definition at line 6646 of file Catalog.cpp.

References Catalog_Namespace::anonymous_namespace{Catalog.cpp}::get_encoded_text_type(), Catalog_Namespace::anonymous_namespace{Catalog.cpp}::get_var_array_type(), kBIGINT, kINT, and Catalog_Namespace::MEMORY_DETAILS_SYS_TABLE_NAME.

6646  {
6647  auto [foreign_table, columns] =
6650  {{"node", get_encoded_text_type()},
6651  {"database_id", {kINT}},
6652  {"database_name", get_encoded_text_type()},
6653  {"table_id", {kINT}},
6654  {"table_name", get_encoded_text_type()},
6655  {"column_id", {kINT}},
6656  {"column_name", get_encoded_text_type()},
6657  {"chunk_key", get_var_array_type(kINT)},
6658  {"device_id", {kINT}},
6659  {"device_type", get_encoded_text_type()},
6660  {"memory_status", get_encoded_text_type()},
6661  {"page_count", {kBIGINT}},
6662  {"page_size", {kBIGINT}},
6663  {"slab_id", {kINT}},
6664  {"start_page", {kBIGINT}},
6665  {"last_touch_epoch", {kBIGINT}}},
6666  true);
6667  recreateSystemTableIfUpdated(foreign_table, columns);
6668 }
static constexpr const char * MEMORY_DETAILS_SYS_TABLE_NAME
Definition: Catalog.h:120
std::pair< foreign_storage::ForeignTable, std::list< ColumnDescriptor > > getSystemTableSchema(const std::string &table_name, const std::string &server_name, const std::vector< std::pair< std::string, SQLTypeInfo >> &column_type_by_name, bool is_in_memory_system_table)
Definition: Catalog.cpp:6883
Definition: sqltypes.h:72
static constexpr const char * MEMORY_STATS_SERVER_NAME
Definition: Catalog.h:893
bool recreateSystemTableIfUpdated(foreign_storage::ForeignTable &foreign_table, const std::list< ColumnDescriptor > &columns)
Definition: Catalog.cpp:6921

+ Here is the call graph for this function:

void Catalog_Namespace::Catalog::initializeMemorySummarySystemTable ( )
private

Definition at line 6630 of file Catalog.cpp.

References Catalog_Namespace::anonymous_namespace{Catalog.cpp}::get_encoded_text_type(), kBIGINT, kINT, and Catalog_Namespace::MEMORY_SUMMARY_SYS_TABLE_NAME.

6630  {
6631  auto [foreign_table, columns] =
6634  {{"node", get_encoded_text_type()},
6635  {"device_id", {kINT}},
6636  {"device_type", get_encoded_text_type()},
6637  {"max_page_count", {kBIGINT}},
6638  {"page_size", {kBIGINT}},
6639  {"allocated_page_count", {kBIGINT}},
6640  {"used_page_count", {kBIGINT}},
6641  {"free_page_count", {kBIGINT}}},
6642  true);
6643  recreateSystemTableIfUpdated(foreign_table, columns);
6644 }
std::pair< foreign_storage::ForeignTable, std::list< ColumnDescriptor > > getSystemTableSchema(const std::string &table_name, const std::string &server_name, const std::vector< std::pair< std::string, SQLTypeInfo >> &column_type_by_name, bool is_in_memory_system_table)
Definition: Catalog.cpp:6883
static constexpr const char * MEMORY_SUMMARY_SYS_TABLE_NAME
Definition: Catalog.h:119
Definition: sqltypes.h:72
static constexpr const char * MEMORY_STATS_SERVER_NAME
Definition: Catalog.h:893
bool recreateSystemTableIfUpdated(foreign_storage::ForeignTable &foreign_table, const std::list< ColumnDescriptor > &columns)
Definition: Catalog.cpp:6921

+ Here is the call graph for this function:

void Catalog_Namespace::Catalog::initializeMLModelMetadataSystemTable ( )
private

Definition at line 6725 of file Catalog.cpp.

References Catalog_Namespace::anonymous_namespace{Catalog.cpp}::get_encoded_text_type(), Catalog_Namespace::anonymous_namespace{Catalog.cpp}::get_var_encoded_text_array_type(), kBIGINT, kDOUBLE, and Catalog_Namespace::ML_MODEL_METADATA_SYS_TABLE_NAME.

6725  {
6726  auto [foreign_table, columns] =
6729  {{"model_name", get_encoded_text_type()},
6730  {"model_type", get_encoded_text_type()},
6731  {"predicted", get_encoded_text_type()},
6732  {"features", get_var_encoded_text_array_type()},
6733  {"training_query", get_encoded_text_type()},
6734  {"num_logical_features", {kBIGINT}},
6735  {"num_physical_features", {kBIGINT}},
6736  {"num_categorical_features", {kBIGINT}},
6737  {"num_numeric_features", {kBIGINT}},
6738  {"train_fraction", {kDOUBLE}},
6739  {"eval_fraction", {kDOUBLE}}},
6740  true);
6741  recreateSystemTableIfUpdated(foreign_table, columns);
6742 }
std::pair< foreign_storage::ForeignTable, std::list< ColumnDescriptor > > getSystemTableSchema(const std::string &table_name, const std::string &server_name, const std::vector< std::pair< std::string, SQLTypeInfo >> &column_type_by_name, bool is_in_memory_system_table)
Definition: Catalog.cpp:6883
static constexpr const char * ML_METADATA_SERVER_NAME
Definition: Catalog.h:896
static constexpr const char * ML_MODEL_METADATA_SYS_TABLE_NAME
Definition: Catalog.h:124
bool recreateSystemTableIfUpdated(foreign_storage::ForeignTable &foreign_table, const std::list< ColumnDescriptor > &columns)
Definition: Catalog.cpp:6921

+ Here is the call graph for this function:

void Catalog_Namespace::Catalog::initializePermissionsSystemTable ( )
private

Definition at line 6554 of file Catalog.cpp.

References Catalog_Namespace::anonymous_namespace{Catalog.cpp}::get_encoded_text_type(), Catalog_Namespace::anonymous_namespace{Catalog.cpp}::get_var_encoded_text_array_type(), kBOOLEAN, kINT, and Catalog_Namespace::PERMISSIONS_SYS_TABLE_NAME.

6554  {
6555  auto [foreign_table, columns] =
6558  {{"role_name", get_encoded_text_type()},
6559  {"is_user_role", {kBOOLEAN}},
6560  {"database_id", {kINT}},
6561  {"database_name", get_encoded_text_type()},
6562  {"object_name", get_encoded_text_type()},
6563  {"object_id", {kINT}},
6564  {"object_owner_id", {kINT}},
6565  {"object_owner_user_name", get_encoded_text_type()},
6566  {"object_permission_type", get_encoded_text_type()},
6567  {"object_permissions", get_var_encoded_text_array_type()}},
6568  true);
6569  recreateSystemTableIfUpdated(foreign_table, columns);
6570 }
std::pair< foreign_storage::ForeignTable, std::list< ColumnDescriptor > > getSystemTableSchema(const std::string &table_name, const std::string &server_name, const std::vector< std::pair< std::string, SQLTypeInfo >> &column_type_by_name, bool is_in_memory_system_table)
Definition: Catalog.cpp:6883
static constexpr const char * PERMISSIONS_SYS_TABLE_NAME
Definition: Catalog.h:116
static constexpr const char * CATALOG_SERVER_NAME
Definition: Catalog.h:892
Definition: sqltypes.h:72
bool recreateSystemTableIfUpdated(foreign_storage::ForeignTable &foreign_table, const std::list< ColumnDescriptor > &columns)
Definition: Catalog.cpp:6921

+ Here is the call graph for this function:

void Catalog_Namespace::Catalog::initializeRequestLogsSystemTables ( )
private

Definition at line 6769 of file Catalog.cpp.

References Catalog_Namespace::anonymous_namespace{Catalog.cpp}::clear_cached_table_data(), Catalog_Namespace::anonymous_namespace{Catalog.cpp}::get_encoded_text_type(), kBIGINT, kINT, kTIMESTAMP, Catalog_Namespace::REQUEST_LOGS_SYS_TABLE_NAME, and Catalog_Namespace::anonymous_namespace{Catalog.cpp}::set_common_db_log_system_table_options().

6769  {
6770  auto [foreign_table, columns] =
6773  {{"log_timestamp", {kTIMESTAMP}},
6774  {"severity", get_encoded_text_type()},
6775  {"process_id", {kINT}},
6776  {"query_id", {kINT}},
6777  {"thread_id", {kINT}},
6778  {"file_location", get_encoded_text_type()},
6779  {"api_name", get_encoded_text_type()},
6780  {"request_duration_ms", {kBIGINT}},
6781  {"database_name", get_encoded_text_type()},
6782  {"user_name", get_encoded_text_type()},
6783  {"public_session_id", get_encoded_text_type()},
6784  {"query_string", get_encoded_text_type()},
6785  {"client", get_encoded_text_type()},
6786  {"dashboard_id", {kINT}},
6787  {"dashboard_name", get_encoded_text_type()},
6788  {"chart_id", {kINT}},
6789  {"execution_time_ms", {kBIGINT}},
6790  {"total_time_ms", {kBIGINT}}},
6791  false);
6794  // Matches request logs like those seen in the "heavydb.INFO.20220518-210103.log" test
6795  // file (specifically, lines containing " stdlog ").
6796  foreign_table.options[RegexFileBufferParser::LINE_REGEX_KEY] =
6797  "^([^\\s]+)\\s(\\w)\\s(\\d+)\\s(\\d+)\\s(\\d+)\\s([^\\s]+)\\s(?:stdlog)\\s(\\w+)"
6798  "\\s(?:\\d+)\\s(\\d+)\\s(\\w+)\\s([^\\s]+)\\s([^\\s]+)\\s(\\{[^\\}]+\\})\\s(\\{[^"
6799  "\\}]+\\})$";
6800  if (recreateSystemTableIfUpdated(foreign_table, columns)) {
6801  // Clear table cache if the table schema is updated
6802  clear_cached_table_data(dataMgr_.get(), currentDB_.dbId, foreign_table.tableId);
6803  }
6804 }
std::pair< foreign_storage::ForeignTable, std::list< ColumnDescriptor > > getSystemTableSchema(const std::string &table_name, const std::string &server_name, const std::vector< std::pair< std::string, SQLTypeInfo >> &column_type_by_name, bool is_in_memory_system_table)
Definition: Catalog.cpp:6883
const DBMetadata currentDB_
Definition: Catalog.h:721
std::shared_ptr< Data_Namespace::DataMgr > dataMgr_
Definition: Catalog.h:722
void clear_cached_table_data(const Data_Namespace::DataMgr *data_mgr, int32_t db_id, int32_t table_id)
Definition: Catalog.cpp:6479
static constexpr const char * LOGS_SERVER_NAME
Definition: Catalog.h:897
static constexpr const char * REQUEST_LOGS_SYS_TABLE_NAME
Definition: Catalog.h:126
void set_common_db_log_system_table_options(foreign_storage::ForeignTable &foreign_table)
Definition: Catalog.cpp:6467
Definition: sqltypes.h:72
bool recreateSystemTableIfUpdated(foreign_storage::ForeignTable &foreign_table, const std::list< ColumnDescriptor > &columns)
Definition: Catalog.cpp:6921

+ Here is the call graph for this function:

void Catalog_Namespace::Catalog::initializeRoleAssignmentsSystemTable ( )
private

Definition at line 6621 of file Catalog.cpp.

References Catalog_Namespace::anonymous_namespace{Catalog.cpp}::get_encoded_text_type(), and Catalog_Namespace::ROLE_ASSIGNMENTS_SYS_TABLE_NAME.

6621  {
6622  auto [foreign_table, columns] = getSystemTableSchema(
6625  {{"role_name", get_encoded_text_type()}, {"user_name", get_encoded_text_type()}},
6626  true);
6627  recreateSystemTableIfUpdated(foreign_table, columns);
6628 }
std::pair< foreign_storage::ForeignTable, std::list< ColumnDescriptor > > getSystemTableSchema(const std::string &table_name, const std::string &server_name, const std::vector< std::pair< std::string, SQLTypeInfo >> &column_type_by_name, bool is_in_memory_system_table)
Definition: Catalog.cpp:6883
static constexpr const char * ROLE_ASSIGNMENTS_SYS_TABLE_NAME
Definition: Catalog.h:118
static constexpr const char * CATALOG_SERVER_NAME
Definition: Catalog.h:892
bool recreateSystemTableIfUpdated(foreign_storage::ForeignTable &foreign_table, const std::list< ColumnDescriptor > &columns)
Definition: Catalog.cpp:6921

+ Here is the call graph for this function:

void Catalog_Namespace::Catalog::initializeRolesSystemTable ( )
private

Definition at line 6572 of file Catalog.cpp.

References Catalog_Namespace::anonymous_namespace{Catalog.cpp}::get_encoded_text_type(), and Catalog_Namespace::ROLES_SYS_TABLE_NAME.

6572  {
6573  auto [foreign_table, columns] =
6576  {{"role_name", get_encoded_text_type()}},
6577  true);
6578  recreateSystemTableIfUpdated(foreign_table, columns);
6579 }
std::pair< foreign_storage::ForeignTable, std::list< ColumnDescriptor > > getSystemTableSchema(const std::string &table_name, const std::string &server_name, const std::vector< std::pair< std::string, SQLTypeInfo >> &column_type_by_name, bool is_in_memory_system_table)
Definition: Catalog.cpp:6883
static constexpr const char * ROLES_SYS_TABLE_NAME
Definition: Catalog.h:117
static constexpr const char * CATALOG_SERVER_NAME
Definition: Catalog.h:892
bool recreateSystemTableIfUpdated(foreign_storage::ForeignTable &foreign_table, const std::list< ColumnDescriptor > &columns)
Definition: Catalog.cpp:6921

+ Here is the call graph for this function:

void Catalog_Namespace::Catalog::initializeServerLogsSystemTables ( )
private

Definition at line 6744 of file Catalog.cpp.

References Catalog_Namespace::anonymous_namespace{Catalog.cpp}::clear_cached_table_data(), Catalog_Namespace::anonymous_namespace{Catalog.cpp}::get_encoded_text_type(), kINT, kTIMESTAMP, Catalog_Namespace::SERVER_LOGS_SYS_TABLE_NAME, and Catalog_Namespace::anonymous_namespace{Catalog.cpp}::set_common_db_log_system_table_options().

6744  {
6745  auto [foreign_table, columns] =
6748  {{"node", get_encoded_text_type()},
6749  {"log_timestamp", {kTIMESTAMP}},
6750  {"severity", get_encoded_text_type()},
6751  {"process_id", {kINT}},
6752  {"query_id", {kINT}},
6753  {"thread_id", {kINT}},
6754  {"file_location", get_encoded_text_type()},
6755  {"message", get_encoded_text_type()}},
6756  false);
6759  // Matches server logs like those seen in the "heavydb.INFO.20220518-210103.log" test
6760  // file.
6761  foreign_table.options[RegexFileBufferParser::LINE_REGEX_KEY] =
6762  "^([^\\s]+)\\s(\\w)\\s(\\d+)\\s(\\d+)\\s(\\d+)\\s([^\\s]+)\\s(.+)$";
6763  if (recreateSystemTableIfUpdated(foreign_table, columns)) {
6764  // Clear table cache if the table schema is updated
6765  clear_cached_table_data(dataMgr_.get(), currentDB_.dbId, foreign_table.tableId);
6766  }
6767 }
std::pair< foreign_storage::ForeignTable, std::list< ColumnDescriptor > > getSystemTableSchema(const std::string &table_name, const std::string &server_name, const std::vector< std::pair< std::string, SQLTypeInfo >> &column_type_by_name, bool is_in_memory_system_table)
Definition: Catalog.cpp:6883
static constexpr const char * SERVER_LOGS_SYS_TABLE_NAME
Definition: Catalog.h:125
const DBMetadata currentDB_
Definition: Catalog.h:721
std::shared_ptr< Data_Namespace::DataMgr > dataMgr_
Definition: Catalog.h:722
void clear_cached_table_data(const Data_Namespace::DataMgr *data_mgr, int32_t db_id, int32_t table_id)
Definition: Catalog.cpp:6479
static constexpr const char * LOGS_SERVER_NAME
Definition: Catalog.h:897
void set_common_db_log_system_table_options(foreign_storage::ForeignTable &foreign_table)
Definition: Catalog.cpp:6467
Definition: sqltypes.h:72
bool recreateSystemTableIfUpdated(foreign_storage::ForeignTable &foreign_table, const std::list< ColumnDescriptor > &columns)
Definition: Catalog.cpp:6921

+ Here is the call graph for this function:

void Catalog_Namespace::Catalog::initializeStorageDetailsSystemTable ( )
private

Definition at line 6670 of file Catalog.cpp.

References Catalog_Namespace::anonymous_namespace{Catalog.cpp}::get_encoded_text_type(), kBIGINT, kINT, and Catalog_Namespace::STORAGE_DETAILS_SYS_TABLE_NAME.

6670  {
6671  auto [foreign_table, columns] =
6674  {{"node", get_encoded_text_type()},
6675  {"database_id", {kINT}},
6676  {"database_name", get_encoded_text_type()},
6677  {"table_id", {kINT}},
6678  {"table_name", get_encoded_text_type()},
6679  {"epoch", {kINT}},
6680  {"epoch_floor", {kINT}},
6681  {"fragment_count", {kINT}},
6682  {"shard_id", {kINT}},
6683  {"data_file_count", {kINT}},
6684  {"metadata_file_count", {kINT}},
6685  {"total_data_file_size", {kBIGINT}},
6686  {"total_data_page_count", {kBIGINT}},
6687  {"total_free_data_page_count", {kBIGINT}},
6688  {"total_metadata_file_size", {kBIGINT}},
6689  {"total_metadata_page_count", {kBIGINT}},
6690  {"total_free_metadata_page_count", {kBIGINT}},
6691  {"total_dictionary_data_file_size", {kBIGINT}}},
6692  true);
6693  recreateSystemTableIfUpdated(foreign_table, columns);
6694 }
std::pair< foreign_storage::ForeignTable, std::list< ColumnDescriptor > > getSystemTableSchema(const std::string &table_name, const std::string &server_name, const std::vector< std::pair< std::string, SQLTypeInfo >> &column_type_by_name, bool is_in_memory_system_table)
Definition: Catalog.cpp:6883
static constexpr const char * STORAGE_DETAILS_SYS_TABLE_NAME
Definition: Catalog.h:121
Definition: sqltypes.h:72
bool recreateSystemTableIfUpdated(foreign_storage::ForeignTable &foreign_table, const std::list< ColumnDescriptor > &columns)
Definition: Catalog.cpp:6921
static constexpr const char * STORAGE_STATS_SERVER_NAME
Definition: Catalog.h:894

+ Here is the call graph for this function:

void Catalog_Namespace::Catalog::initializeSystemServers ( )
private

Definition at line 6403 of file Catalog.cpp.

References foreign_storage::AbstractFileStorageDataWrapper::BASE_PATH_KEY, g_enable_logs_system_tables, logger::get_log_dir_path(), foreign_storage::DataWrapperType::INTERNAL_CATALOG, foreign_storage::DataWrapperType::INTERNAL_EXECUTOR_STATS, foreign_storage::DataWrapperType::INTERNAL_LOGS, foreign_storage::DataWrapperType::INTERNAL_MEMORY_STATS, foreign_storage::DataWrapperType::INTERNAL_ML_MODEL_METADATA, foreign_storage::DataWrapperType::INTERNAL_STORAGE_STATS, foreign_storage::AbstractFileStorageDataWrapper::LOCAL_FILE_STORAGE_TYPE, and foreign_storage::AbstractFileStorageDataWrapper::STORAGE_TYPE_KEY.

6403  {
6414 
6416  foreign_storage::OptionsMap log_server_options;
6417  log_server_options
6421  logger::get_log_dir_path().string();
6424  log_server_options);
6425  }
6426 }
bool g_enable_logs_system_tables
Definition: Catalog.cpp:100
static constexpr char const * INTERNAL_STORAGE_STATS
static constexpr const char * ML_METADATA_SERVER_NAME
Definition: Catalog.h:896
fs::path get_log_dir_path()
Definition: Logger.cpp:906
static constexpr const char * LOGS_SERVER_NAME
Definition: Catalog.h:897
static constexpr char const * INTERNAL_CATALOG
static constexpr char const * INTERNAL_ML_MODEL_METADATA
static constexpr const char * EXECUTOR_STATS_SERVER_NAME
Definition: Catalog.h:895
static constexpr char const * INTERNAL_EXECUTOR_STATS
static constexpr char const * INTERNAL_MEMORY_STATS
static constexpr const char * CATALOG_SERVER_NAME
Definition: Catalog.h:892
std::map< std::string, std::string, std::less<>> OptionsMap
static constexpr const char * MEMORY_STATS_SERVER_NAME
Definition: Catalog.h:893
void createSystemTableServer(const std::string &server_name, const std::string &data_wrapper_type, const foreign_storage::OptionsMap &options={})
Definition: Catalog.cpp:6856
static constexpr char const * INTERNAL_LOGS
static constexpr const char * STORAGE_STATS_SERVER_NAME
Definition: Catalog.h:894

+ Here is the call graph for this function:

void Catalog_Namespace::Catalog::initializeSystemTables ( )
private

Definition at line 6499 of file Catalog.cpp.

References Catalog_Namespace::anonymous_namespace{Catalog.cpp}::drop_tables(), g_enable_logs_system_tables, Catalog_Namespace::REQUEST_LOGS_SYS_TABLE_NAME, Catalog_Namespace::SERVER_LOGS_SYS_TABLE_NAME, Catalog_Namespace::WS_SERVER_ACCESS_LOGS_SYS_TABLE_NAME, and Catalog_Namespace::WS_SERVER_LOGS_SYS_TABLE_NAME.

6499  {
6512 
6516  } else {
6517  drop_tables(*this,
6524  }
6525  }
6526 }
static constexpr const char * WS_SERVER_ACCESS_LOGS_SYS_TABLE_NAME
Definition: Catalog.h:128
void initializePermissionsSystemTable()
Definition: Catalog.cpp:6554
static constexpr const char * SERVER_LOGS_SYS_TABLE_NAME
Definition: Catalog.h:125
bool g_enable_logs_system_tables
Definition: Catalog.cpp:100
const foreign_storage::ForeignServer * getForeignServer(const std::string &server_name) const
Definition: Catalog.cpp:3344
void initializeServerLogsSystemTables()
Definition: Catalog.cpp:6744
static constexpr const char * LOGS_SERVER_NAME
Definition: Catalog.h:897
void initializeMLModelMetadataSystemTable()
Definition: Catalog.cpp:6725
static constexpr const char * REQUEST_LOGS_SYS_TABLE_NAME
Definition: Catalog.h:126
void initializeMemorySummarySystemTable()
Definition: Catalog.cpp:6630
void initializeStorageDetailsSystemTable()
Definition: Catalog.cpp:6670
void dropForeignServer(const std::string &server_name)
Definition: Catalog.cpp:3460
void initializeRoleAssignmentsSystemTable()
Definition: Catalog.cpp:6621
void initializeMemoryDetailsSystemTable()
Definition: Catalog.cpp:6646
void initializeRequestLogsSystemTables()
Definition: Catalog.cpp:6769
void initializeExecutorResourcePoolSummarySystemTable()
Definition: Catalog.cpp:6696
void drop_tables(Catalog &catalog, const std::vector< std::string > &table_names)
Definition: Catalog.cpp:6488
static constexpr const char * WS_SERVER_LOGS_SYS_TABLE_NAME
Definition: Catalog.h:127
void initializeDashboardsSystemTable()
Definition: Catalog.cpp:6605

+ Here is the call graph for this function:

void Catalog_Namespace::Catalog::initializeTablesSystemTable ( )
private

Definition at line 6581 of file Catalog.cpp.

References Catalog_Namespace::anonymous_namespace{Catalog.cpp}::get_encoded_text_type(), kBIGINT, kINT, and Catalog_Namespace::TABLES_SYS_TABLE_NAME.

6581  {
6582  auto [foreign_table, columns] =
6585  {{"database_id", {kINT}},
6586  {"database_name", get_encoded_text_type()},
6587  {"table_id", {kINT}},
6588  {"table_name", get_encoded_text_type()},
6589  {"owner_id", {kINT}},
6590  {"owner_user_name", get_encoded_text_type()},
6591  {"column_count", {kINT}},
6592  {"table_type", get_encoded_text_type()},
6593  {"view_sql", get_encoded_text_type()},
6594  {"max_fragment_size", {kINT}},
6595  {"max_chunk_size", {kBIGINT}},
6596  {"fragment_page_size", {kINT}},
6597  {"max_rows", {kBIGINT}},
6598  {"max_rollback_epochs", {kINT}},
6599  {"shard_count", {kINT}},
6600  {"ddl_statement", get_encoded_text_type()}},
6601  true);
6602  recreateSystemTableIfUpdated(foreign_table, columns);
6603 }
std::pair< foreign_storage::ForeignTable, std::list< ColumnDescriptor > > getSystemTableSchema(const std::string &table_name, const std::string &server_name, const std::vector< std::pair< std::string, SQLTypeInfo >> &column_type_by_name, bool is_in_memory_system_table)
Definition: Catalog.cpp:6883
static constexpr const char * TABLES_SYS_TABLE_NAME
Definition: Catalog.h:113
static constexpr const char * CATALOG_SERVER_NAME
Definition: Catalog.h:892
Definition: sqltypes.h:72
bool recreateSystemTableIfUpdated(foreign_storage::ForeignTable &foreign_table, const std::list< ColumnDescriptor > &columns)
Definition: Catalog.cpp:6921

+ Here is the call graph for this function:

void Catalog_Namespace::Catalog::initializeUsersSystemTable ( )
private

Definition at line 6528 of file Catalog.cpp.

References Catalog_Namespace::anonymous_namespace{Catalog.cpp}::get_encoded_text_type(), kBOOLEAN, kINT, and Catalog_Namespace::USERS_SYS_TABLE_NAME.

6528  {
6529  auto [foreign_table, columns] =
6532  {{"user_id", {kINT}},
6533  {"user_name", get_encoded_text_type()},
6534  {"is_super_user", {kBOOLEAN}},
6535  {"default_db_id", {kINT}},
6536  {"default_db_name", get_encoded_text_type()},
6537  {"can_login", {kBOOLEAN}}},
6538  true);
6539  recreateSystemTableIfUpdated(foreign_table, columns);
6540 }
std::pair< foreign_storage::ForeignTable, std::list< ColumnDescriptor > > getSystemTableSchema(const std::string &table_name, const std::string &server_name, const std::vector< std::pair< std::string, SQLTypeInfo >> &column_type_by_name, bool is_in_memory_system_table)
Definition: Catalog.cpp:6883
static constexpr const char * USERS_SYS_TABLE_NAME
Definition: Catalog.h:112
static constexpr const char * CATALOG_SERVER_NAME
Definition: Catalog.h:892
Definition: sqltypes.h:72
bool recreateSystemTableIfUpdated(foreign_storage::ForeignTable &foreign_table, const std::list< ColumnDescriptor > &columns)
Definition: Catalog.cpp:6921

+ Here is the call graph for this function:

void Catalog_Namespace::Catalog::initializeWebServerAccessLogsSystemTables ( )
private

Definition at line 6829 of file Catalog.cpp.

References Catalog_Namespace::anonymous_namespace{Catalog.cpp}::clear_cached_table_data(), Catalog_Namespace::anonymous_namespace{Catalog.cpp}::get_encoded_text_type(), kBIGINT, kSMALLINT, kTIMESTAMP, Catalog_Namespace::anonymous_namespace{Catalog.cpp}::set_common_log_system_table_options(), and Catalog_Namespace::WS_SERVER_ACCESS_LOGS_SYS_TABLE_NAME.

6829  {
6830  auto [foreign_table, columns] =
6833  {{"ip_address", get_encoded_text_type()},
6834  {"log_timestamp", {kTIMESTAMP}},
6835  {"http_method", get_encoded_text_type()},
6836  {"endpoint", get_encoded_text_type()},
6837  {"http_status", {kSMALLINT}},
6838  {"response_size", {kBIGINT}}},
6839  false);
6840  set_common_log_system_table_options(foreign_table);
6842  foreign_table.options[AbstractFileStorageDataWrapper::REGEX_PATH_FILTER_KEY] =
6843  ".*heavy_web_server.*ACCESS\\..*";
6845  // Matches web server access logs like those seen in the
6846  // "heavy_web_server.test.log.ACCESS.20220518-210103.307016" test file.
6847  foreign_table.options[RegexFileBufferParser::LINE_REGEX_KEY] =
6848  "^(\\d+\\.\\d+\\.\\d+\\.\\d+)\\s+\\-\\s+\\-\\s+\\[([^\\]]+)\\]\\s+\"(\\w+)\\s+([^"
6849  "\\s]+)\\s+HTTP\\/1\\.1\"\\s+(\\d+)\\s+(\\d+)$";
6850  if (recreateSystemTableIfUpdated(foreign_table, columns)) {
6851  // Clear table cache if the table schema is updated
6852  clear_cached_table_data(dataMgr_.get(), currentDB_.dbId, foreign_table.tableId);
6853  }
6854 }
static constexpr const char * WS_SERVER_ACCESS_LOGS_SYS_TABLE_NAME
Definition: Catalog.h:128
std::pair< foreign_storage::ForeignTable, std::list< ColumnDescriptor > > getSystemTableSchema(const std::string &table_name, const std::string &server_name, const std::vector< std::pair< std::string, SQLTypeInfo >> &column_type_by_name, bool is_in_memory_system_table)
Definition: Catalog.cpp:6883
void set_common_log_system_table_options(foreign_storage::ForeignTable &foreign_table)
Definition: Catalog.cpp:6446
const DBMetadata currentDB_
Definition: Catalog.h:721
std::shared_ptr< Data_Namespace::DataMgr > dataMgr_
Definition: Catalog.h:722
void clear_cached_table_data(const Data_Namespace::DataMgr *data_mgr, int32_t db_id, int32_t table_id)
Definition: Catalog.cpp:6479
static constexpr const char * LOGS_SERVER_NAME
Definition: Catalog.h:897
bool recreateSystemTableIfUpdated(foreign_storage::ForeignTable &foreign_table, const std::list< ColumnDescriptor > &columns)
Definition: Catalog.cpp:6921

+ Here is the call graph for this function:

void Catalog_Namespace::Catalog::initializeWebServerLogsSystemTables ( )
private

Definition at line 6806 of file Catalog.cpp.

References Catalog_Namespace::anonymous_namespace{Catalog.cpp}::clear_cached_table_data(), Catalog_Namespace::anonymous_namespace{Catalog.cpp}::get_encoded_text_type(), kTIMESTAMP, Catalog_Namespace::anonymous_namespace{Catalog.cpp}::set_common_log_system_table_options(), and Catalog_Namespace::WS_SERVER_LOGS_SYS_TABLE_NAME.

6806  {
6807  auto [foreign_table, columns] =
6810  {{"log_timestamp", {kTIMESTAMP}},
6811  {"severity", get_encoded_text_type()},
6812  {"message", get_encoded_text_type()}},
6813  false);
6814  set_common_log_system_table_options(foreign_table);
6816  foreign_table.options[AbstractFileStorageDataWrapper::REGEX_PATH_FILTER_KEY] =
6817  ".*heavy_web_server.*ALL\\..*";
6819  // Matches web server logs like those seen in the
6820  // "heavy_web_server.test.log.ALL.20220518-210103.307016" test file.
6821  foreign_table.options[RegexFileBufferParser::LINE_REGEX_KEY] =
6822  "^time=\"([^\"]+)\"\\slevel=([^\\s]+)\\smsg=\"([^\"]+)\"$";
6823  if (recreateSystemTableIfUpdated(foreign_table, columns)) {
6824  // Clear table cache if the table schema is updated
6825  clear_cached_table_data(dataMgr_.get(), currentDB_.dbId, foreign_table.tableId);
6826  }
6827 }
std::pair< foreign_storage::ForeignTable, std::list< ColumnDescriptor > > getSystemTableSchema(const std::string &table_name, const std::string &server_name, const std::vector< std::pair< std::string, SQLTypeInfo >> &column_type_by_name, bool is_in_memory_system_table)
Definition: Catalog.cpp:6883
void set_common_log_system_table_options(foreign_storage::ForeignTable &foreign_table)
Definition: Catalog.cpp:6446
const DBMetadata currentDB_
Definition: Catalog.h:721
std::shared_ptr< Data_Namespace::DataMgr > dataMgr_
Definition: Catalog.h:722
void clear_cached_table_data(const Data_Namespace::DataMgr *data_mgr, int32_t db_id, int32_t table_id)
Definition: Catalog.cpp:6479
static constexpr const char * LOGS_SERVER_NAME
Definition: Catalog.h:897
bool recreateSystemTableIfUpdated(foreign_storage::ForeignTable &foreign_table, const std::list< ColumnDescriptor > &columns)
Definition: Catalog.cpp:6921
static constexpr const char * WS_SERVER_LOGS_SYS_TABLE_NAME
Definition: Catalog.h:127

+ Here is the call graph for this function:

void Catalog_Namespace::Catalog::instantiateFragmenter ( TableDescriptor td) const
protected

Definition at line 1781 of file Catalog.cpp.

References CHECK_EQ, measure< TimeT >::execution(), TableDescriptor::fragmenter, TableDescriptor::fragPageSize, TableDescriptor::fragType, logger::INFO, Fragmenter_Namespace::INSERT_ORDER, LOG, TableDescriptor::maxChunkSize, TableDescriptor::maxFragRows, TableDescriptor::maxRows, TableDescriptor::persistenceLevel, TableDescriptor::shard, TableDescriptor::sortedColumnId, TableDescriptor::storageType, TableDescriptor::tableId, and TableDescriptor::tableName.

1781  {
1782  auto time_ms = measure<>::execution([&]() {
1783  // instanciate table fragmenter upon first use
1784  // assume only insert order fragmenter is supported
1786  vector<Chunk> chunkVec;
1787  auto columnDescs = getAllColumnMetadataForTable(td->tableId, true, false, true);
1788  Chunk::translateColumnDescriptorsToChunkVec(columnDescs, chunkVec);
1789  ChunkKey chunkKeyPrefix = {currentDB_.dbId, td->tableId};
1790  if (td->sortedColumnId > 0) {
1791  td->fragmenter = std::make_shared<SortedOrderFragmenter>(chunkKeyPrefix,
1792  chunkVec,
1793  dataMgr_.get(),
1794  const_cast<Catalog*>(this),
1795  td->tableId,
1796  td->shard,
1797  td->maxFragRows,
1798  td->maxChunkSize,
1799  td->fragPageSize,
1800  td->maxRows,
1801  td->persistenceLevel);
1802  } else {
1803  td->fragmenter = std::make_shared<InsertOrderFragmenter>(chunkKeyPrefix,
1804  chunkVec,
1805  dataMgr_.get(),
1806  const_cast<Catalog*>(this),
1807  td->tableId,
1808  td->shard,
1809  td->maxFragRows,
1810  td->maxChunkSize,
1811  td->fragPageSize,
1812  td->maxRows,
1813  td->persistenceLevel,
1814  !td->storageType.empty());
1815  }
1816  });
1817  LOG(INFO) << "Instantiating Fragmenter for table " << td->tableName << " took "
1818  << time_ms << "ms";
1819 }
#define CHECK_EQ(x, y)
Definition: Logger.h:301
std::vector< int > ChunkKey
Definition: types.h:36
std::string tableName
static TimeT::rep execution(F func, Args &&...args)
Definition: sample.cpp:29
#define LOG(tag)
Definition: Logger.h:285
const DBMetadata currentDB_
Definition: Catalog.h:721
std::string storageType
std::shared_ptr< Data_Namespace::DataMgr > dataMgr_
Definition: Catalog.h:722
std::shared_ptr< Fragmenter_Namespace::AbstractFragmenter > fragmenter
Fragmenter_Namespace::FragmenterType fragType
std::list< const ColumnDescriptor * > getAllColumnMetadataForTable(const int tableId, const bool fetchSystemColumns, const bool fetchVirtualColumns, const bool fetchPhysicalColumns) const
Returns a list of pointers to constant ColumnDescriptor structs for all the columns from a particular...
Definition: Catalog.cpp:2175
Data_Namespace::MemoryLevel persistenceLevel
Catalog()
Constructor builds a hollow catalog used during constructor of other catalogs.
Definition: Catalog.cpp:174

+ Here is the call graph for this function:

void Catalog_Namespace::Catalog::invalidateCachesForTable ( const int  table_id)

Definition at line 4239 of file Catalog.cpp.

References CHECK, CHUNK_KEY_DB_IDX, CHUNK_KEY_TABLE_IDX, Executor::clearExternalCaches(), Data_Namespace::CPU_LEVEL, and Data_Namespace::GPU_LEVEL.

4239  {
4240  // When called, exactly one thread has a LockMgr data or insert lock for the table.
4241  cat_read_lock read_lock(this);
4242  ChunkKey const table_key{getDatabaseId(), table_id};
4243  auto td = getMutableMetadataForTableUnlocked(table_id);
4244  CHECK(td);
4248 
4250 
4251  // TODO(sy): doTruncateTable() says "destroy fragmenter before deleteChunks is called"
4252  // removeFragmenterForTable(table_key[CHUNK_KEY_TABLE_IDX]);
4253  if (td->fragmenter != nullptr) {
4254  auto tableDescIt = tableDescriptorMapById_.find(table_id);
4255  CHECK(tableDescIt != tableDescriptorMapById_.end());
4256  tableDescIt->second->fragmenter = nullptr;
4257  CHECK(td->fragmenter == nullptr);
4258  }
4260  table_key[CHUNK_KEY_TABLE_IDX]);
4261  if (dynamic_cast<foreign_storage::ForeignTable*>(td)) {
4262  dataMgr_->getPersistentStorageMgr()->getForeignStorageMgr()->refreshTable(table_key,
4263  true);
4264  } else {
4265  dataMgr_->removeMutableTableDiskCacheData(currentDB_.dbId, table_id);
4266  }
4268 }
void instantiateFragmenter(TableDescriptor *td) const
Definition: Catalog.cpp:1781
std::vector< int > ChunkKey
Definition: types.h:36
Data_Namespace::DataMgr & getDataMgr() const
Definition: Catalog.h:266
const DBMetadata currentDB_
Definition: Catalog.h:721
#define CHUNK_KEY_DB_IDX
Definition: types.h:38
std::shared_ptr< Data_Namespace::DataMgr > dataMgr_
Definition: Catalog.h:722
read_lock< Catalog > cat_read_lock
Definition: Catalog.cpp:124
TableDescriptor * getMutableMetadataForTableUnlocked(int table_id) const
Definition: Catalog.cpp:1899
#define CHUNK_KEY_TABLE_IDX
Definition: types.h:39
int getDatabaseId() const
Definition: Catalog.h:326
TableDescriptorMapById tableDescriptorMapById_
Definition: Catalog.h:708
File_Namespace::GlobalFileMgr * getGlobalFileMgr() const
Definition: DataMgr.cpp:699
void deleteChunksWithPrefix(const ChunkKey &keyPrefix)
Definition: DataMgr.cpp:572
void closeFileMgr(const int32_t db_id, const int32_t tb_id)
#define CHECK(condition)
Definition: Logger.h:291
static void clearExternalCaches(bool for_update, const TableDescriptor *td, const int current_db_id)
Definition: Execute.h:438
void refreshDictionaryCachesForTableUnlocked(const TableDescriptor &td)
Definition: Catalog.cpp:4219

+ Here is the call graph for this function:

bool Catalog_Namespace::Catalog::isInfoSchemaDb ( ) const

Definition at line 6399 of file Catalog.cpp.

References shared::kInfoSchemaDbName, and setup::name.

6399  {
6400  return name() == shared::kInfoSchemaDbName;
6401 }
const std::string kInfoSchemaDbName
std::string name() const
Definition: Catalog.h:348
std::string Catalog_Namespace::Catalog::name ( ) const
inline

Definition at line 348 of file Catalog.h.

References Catalog_Namespace::DBMetadata::dbName, and getCurrentDB().

Referenced by anonymous_namespace{Calcite.cpp}::check_db_access(), AlterTableAlterColumnCommandRecoveryMgr::getRecoveryFiles(), recordOwnershipOfObjectsInObjectPermissions(), AlterTableAlterColumnCommandRecoveryMgr::resolveIncompleteAlterColumnCommands(), boost::serialization::save_construct_data(), and lockmgr::TableLockMgrImpl< T >::validateAndGetExistingTableId().

348 { return getCurrentDB().dbName; }
const DBMetadata & getCurrentDB() const
Definition: Catalog.h:265

+ Here is the call graph for this function:

+ Here is the caller graph for this function:

std::vector< DBObject > Catalog_Namespace::Catalog::parseDashboardObjects ( const std::string &  view_meta,
const int &  user_id 
)
protected

Definition at line 1697 of file Catalog.cpp.

References DBObjectKey::dbId, logger::INFO, LOG, DBObjectKey::objectId, parse_underlying_dashboard_objects(), DBObjectKey::permissionType, AccessPrivileges::SELECT_FROM_TABLE, AccessPrivileges::SELECT_FROM_VIEW, TableDBObjectType, run_benchmark_import::type, and ViewDBObjectType.

1698  {
1699  std::vector<DBObject> objects;
1700  DBObjectKey key;
1701  key.dbId = currentDB_.dbId;
1702  auto _key_place = [&key](auto type, auto id) {
1703  key.permissionType = type;
1704  key.objectId = id;
1705  return key;
1706  };
1707  for (auto object_name : parse_underlying_dashboard_objects(view_meta)) {
1708  auto td = getMetadataForTable(object_name, false);
1709  if (!td) {
1710  // Parsed object source is not present in current database
1711  // LOG the info and ignore
1712  LOG(INFO) << "Ignoring dashboard source Table/View: " << object_name
1713  << " no longer exists in current DB.";
1714  continue;
1715  }
1716  // Dashboard source can be Table or View
1717  const auto object_type = td->isView ? ViewDBObjectType : TableDBObjectType;
1718  const auto priv = td->isView ? AccessPrivileges::SELECT_FROM_VIEW
1720  objects.emplace_back(_key_place(object_type, td->tableId), priv, user_id);
1721  objects.back().setObjectType(td->isView ? ViewDBObjectType : TableDBObjectType);
1722  objects.back().setName(td->tableName);
1723  }
1724  return objects;
1725 }
#define LOG(tag)
Definition: Logger.h:285
const DBMetadata currentDB_
Definition: Catalog.h:721
int32_t objectId
Definition: DBObject.h:55
static const AccessPrivileges SELECT_FROM_TABLE
Definition: DBObject.h:160
std::vector< std::string > parse_underlying_dashboard_objects(const std::string &meta)
static const AccessPrivileges SELECT_FROM_VIEW
Definition: DBObject.h:180
int32_t dbId
Definition: DBObject.h:54
int32_t permissionType
Definition: DBObject.h:53
const TableDescriptor * getMetadataForTable(const std::string &tableName, const bool populateFragmenter=true) const
Returns a pointer to a const TableDescriptor struct matching the provided tableName.

+ Here is the call graph for this function:

std::string Catalog_Namespace::Catalog::quoteIfRequired ( const std::string &  column_name) const
private

Definition at line 5877 of file Catalog.cpp.

References Catalog_Namespace::contains_spaces(), Catalog_Namespace::contains_sql_reserved_chars(), get_quoted_string(), and Catalog_Namespace::is_reserved_sql_keyword().

5877  {
5878  if (is_reserved_sql_keyword(column_name) || contains_spaces(column_name) ||
5879  contains_sql_reserved_chars(column_name)) {
5880  return get_quoted_string(column_name, '"', '"');
5881  } else {
5882  return column_name;
5883  }
5884 }
bool contains_spaces(std::string_view str)
returns true if the string contains one or more spaces
Definition: Catalog.cpp:5558
bool contains_sql_reserved_chars(std::string_view str, std::string_view chars="`~!@#$%^&*()-=+[{]}\\|;:'\",<.>/?")
returns true if the string contains one or more OmniSci SQL reserved characters
Definition: Catalog.cpp:5565
std::string get_quoted_string(const std::string &filename, char quote, char escape)
Quote a string while escaping any existing quotes in the string.
bool is_reserved_sql_keyword(std::string_view str)
returns true if the string equals an OmniSci SQL reserved keyword
Definition: Catalog.cpp:5572

+ Here is the call graph for this function:

void Catalog_Namespace::Catalog::reassignOwners ( const std::set< std::string > &  old_owners,
const std::string &  new_owner 
)

Reassigns database object ownership from a set of users (old owners) to another user (new owner).

Parameters
old_owners- users whose database object ownership will be reassigned to a new user
new_owner- user who will own reassigned database objects

Definition at line 6171 of file Catalog.cpp.

References Catalog_Namespace::anonymous_namespace{Catalog.cpp}::add_db_object(), AccessPrivileges::ALL_DASHBOARD, AccessPrivileges::ALL_SERVER, AccessPrivileges::ALL_TABLE, AccessPrivileges::ALL_VIEW, CHECK, CHECK_EQ, CHECK_NE, shared::contains(), DashboardDBObjectType, g_enable_fsi, lockmgr::instance(), ServerDBObjectType, TableDBObjectType, to_string(), Catalog_Namespace::anonymous_namespace{Catalog.cpp}::validate_and_get_user_id(), and ViewDBObjectType.

6172  {
6173  CHECK(!old_owners.empty());
6174  int32_t new_owner_id = validate_and_get_user_id(new_owner);
6175  std::map<int32_t, std::string> old_owners_user_name_by_id;
6176  std::set<int32_t> old_owner_ids;
6177  for (const auto& old_owner : old_owners) {
6178  auto old_owner_id = validate_and_get_user_id(old_owner);
6179  if (old_owner_id != new_owner_id) {
6180  old_owner_ids.emplace(old_owner_id);
6181  old_owners_user_name_by_id[old_owner_id] = old_owner;
6182  }
6183  }
6184 
6185  // An empty set after the above loop implies reassignment to the same user (i.e. all
6186  // users in the old_owners set is the same as new_owner). Do nothing in this case.
6187  if (old_owner_ids.empty()) {
6188  return;
6189  }
6190 
6191  std::map<int32_t, std::vector<DBObject>> old_owner_db_objects;
6192  {
6193  cat_write_lock write_lock(this);
6194  cat_sqlite_lock sqlite_lock(getObjForLock());
6195  sqliteConnector_.query("BEGIN TRANSACTION");
6196  try {
6197  for (const auto old_user_id : old_owner_ids) {
6199  "UPDATE mapd_tables SET userid = ? WHERE userid = ?",
6200  std::vector<std::string>{std::to_string(new_owner_id),
6201  std::to_string(old_user_id)});
6202 
6204  "UPDATE mapd_dashboards SET userid = ? WHERE userid = ?",
6205  std::vector<std::string>{std::to_string(new_owner_id),
6206  std::to_string(old_user_id)});
6207 
6208  if (g_enable_fsi) {
6210  "UPDATE omnisci_foreign_servers SET owner_user_id = ? "
6211  "WHERE owner_user_id = ?",
6212  std::vector<std::string>{std::to_string(new_owner_id),
6213  std::to_string(old_user_id)});
6214  }
6215  }
6216 
6217  for (const auto& [table_name, td] : tableDescriptorMap_) {
6218  if (shared::contains(old_owner_ids, td->userId)) {
6219  if (td->isView) {
6220  add_db_object(td->tableName,
6222  td->userId,
6224  old_owner_db_objects);
6225  } else {
6226  add_db_object(td->tableName,
6228  td->userId,
6230  old_owner_db_objects);
6231  }
6232  td->userId = new_owner_id;
6233  }
6234  }
6235 
6236  DashboardDescriptorMap new_owner_dashboard_map;
6237  for (auto it = dashboardDescriptorMap_.begin();
6238  it != dashboardDescriptorMap_.end();) {
6239  if (auto dashboard = it->second;
6240  shared::contains(old_owner_ids, dashboard->userId)) {
6241  DBObject db_object{dashboard->dashboardId, DBObjectType::DashboardDBObjectType};
6242  db_object.setPrivileges(AccessPrivileges::ALL_DASHBOARD);
6243  old_owner_db_objects[dashboard->userId].emplace_back(db_object);
6244 
6245  // Dashboards in the dashboardDescriptorMap_ use keys with the format
6246  // "{user id}:{dashboard name}". Ensure that map entries are replaced
6247  // with the new owner's user id.
6248  std::string old_key{std::to_string(dashboard->userId) + ":" +
6249  dashboard->dashboardName};
6250  CHECK_EQ(it->first, old_key);
6251  std::string new_key{std::to_string(new_owner_id) + ":" +
6252  dashboard->dashboardName};
6253  CHECK(dashboardDescriptorMap_.find(new_key) == dashboardDescriptorMap_.end());
6254  new_owner_dashboard_map[new_key] = dashboard;
6255  dashboard->userId = new_owner_id;
6256  dashboard->user = new_owner;
6257  it = dashboardDescriptorMap_.erase(it);
6258  } else {
6259  it++;
6260  }
6261  }
6262  dashboardDescriptorMap_.merge(new_owner_dashboard_map);
6263 
6264  if (g_enable_fsi) {
6265  for (const auto& [server_name, server] : foreignServerMap_) {
6266  if (shared::contains(old_owner_ids, server->user_id)) {
6267  add_db_object(server->name,
6269  server->user_id,
6271  old_owner_db_objects);
6272  server->user_id = new_owner_id;
6273  }
6274  }
6275  }
6276 
6277  // Ensure new owner is set in the DB objects.
6278  for (auto& [old_owner_id, db_objects] : old_owner_db_objects) {
6279  for (auto& db_object : db_objects) {
6280  db_object.loadKey(*this);
6281  CHECK_EQ(db_object.getOwner(), new_owner_id);
6282  const auto& object_key = db_object.getObjectKey();
6283  CHECK_EQ(object_key.dbId, getDatabaseId());
6284  CHECK_NE(object_key.objectId, -1);
6285  }
6286  }
6287  } catch (std::exception& e) {
6288  sqliteConnector_.query("ROLLBACK TRANSACTION");
6290  old_owners_user_name_by_id, old_owner_db_objects, new_owner_id);
6291  throw;
6292  }
6293  sqliteConnector_.query("END TRANSACTION");
6294  }
6295 
6296  try {
6298  old_owner_db_objects, new_owner_id, *this);
6299  } catch (std::exception& e) {
6300  restoreOldOwners(old_owners_user_name_by_id, old_owner_db_objects, new_owner_id);
6301  throw;
6302  }
6303 }
bool contains(const T &container, const U &element)
Definition: misc.h:204
#define CHECK_EQ(x, y)
Definition: Logger.h:301
void add_db_object(const std::string &object_name, DBObjectType object_type, int32_t user_id, const AccessPrivileges &privileges, std::map< int32_t, std::vector< DBObject >> &db_objects)
Definition: Catalog.cpp:6160
virtual void query_with_text_params(std::string const &query_only)
SqliteConnector sqliteConnector_
Definition: Catalog.h:720
virtual void query(const std::string &queryString)
void reassignObjectOwners(const std::map< int32_t, std::vector< DBObject >> &old_owner_db_objects, int32_t new_owner_id, const Catalog_Namespace::Catalog &catalog)
DashboardDescriptorMap dashboardDescriptorMap_
Definition: Catalog.h:712
std::string to_string(char const *&&v)
static const AccessPrivileges ALL_VIEW
Definition: DBObject.h:177
void restoreOldOwnersInMemory(const std::map< int32_t, std::string > &old_owners_user_name_by_id, const std::map< int32_t, std::vector< DBObject >> &old_owner_db_objects, int32_t new_owner_id)
Definition: Catalog.cpp:6354
static SysCatalog & instance()
Definition: SysCatalog.h:343
#define CHECK_NE(x, y)
Definition: Logger.h:302
void restoreOldOwners(const std::map< int32_t, std::string > &old_owners_user_name_by_id, const std::map< int32_t, std::vector< DBObject >> &old_owner_db_objects, int32_t new_owner_id)
Definition: Catalog.cpp:6305
int getDatabaseId() const
Definition: Catalog.h:326
static const AccessPrivileges ALL_SERVER
Definition: DBObject.h:187
ForeignServerMap foreignServerMap_
Definition: Catalog.h:715
std::map< std::string, std::shared_ptr< DashboardDescriptor >> DashboardDescriptorMap
Definition: Types.h:44
const Catalog * getObjForLock()
Definition: Catalog.cpp:260
write_lock< Catalog > cat_write_lock
Definition: Catalog.cpp:125
static const AccessPrivileges ALL_DASHBOARD
Definition: DBObject.h:169
static const AccessPrivileges ALL_TABLE
Definition: DBObject.h:157
#define CHECK(condition)
Definition: Logger.h:291
int32_t validate_and_get_user_id(const std::string &user_name)
Definition: Catalog.cpp:6129
sqlite_lock< Catalog > cat_sqlite_lock
Definition: Catalog.cpp:126
bool g_enable_fsi
Definition: Catalog.cpp:96
TableDescriptorMap tableDescriptorMap_
Definition: Catalog.h:707

+ Here is the call graph for this function:

void Catalog_Namespace::Catalog::recordOwnershipOfObjectsInObjectPermissions ( )
protected

Definition at line 800 of file Catalog.cpp.

References AccessPrivileges::ALL_DASHBOARD, AccessPrivileges::ALL_DATABASE, AccessPrivileges::ALL_SERVER, AccessPrivileges::ALL_TABLE, AccessPrivileges::ALL_VIEW, CHECK, currentDB_, DashboardDBObjectType, DatabaseDBObjectType, DBObjectKey::dbId, Catalog_Namespace::DBMetadata::dbId, Catalog_Namespace::DBMetadata::dbName, Catalog_Namespace::DBMetadata::dbOwner, logger::ERROR, SqliteConnector::getData(), SqliteConnector::getNumRows(), getObjForLock(), Catalog_Namespace::SysCatalog::instance(), LOG, name(), DBObjectKey::objectId, DBObjectKey::permissionType, Catalog_Namespace::SysCatalog::populateRoleDbObjects(), SqliteConnector::query(), SqliteConnector::query_with_text_params(), ServerDBObjectType, DBObject::setObjectKey(), DBObject::setOwner(), DBObject::setPrivileges(), sqliteConnector_, TableDBObjectType, to_string(), run_benchmark_import::type, and ViewDBObjectType.

Referenced by CheckAndExecuteMigrations().

800  {
801  cat_sqlite_lock sqlite_lock(getObjForLock());
802  sqliteConnector_.query("BEGIN TRANSACTION");
803  std::vector<DBObject> objects;
804  try {
806  "SELECT name FROM sqlite_master WHERE type='table' AND "
807  "name='mapd_record_ownership_marker'");
808  // check if mapd catalog - marker exists
809  if (sqliteConnector_.getNumRows() != 0 && currentDB_.dbId == 1) {
810  // already done
811  sqliteConnector_.query("END TRANSACTION");
812  return;
813  }
814  // check if different catalog - marker exists
815  else if (sqliteConnector_.getNumRows() != 0 && currentDB_.dbId != 1) {
816  sqliteConnector_.query("SELECT dummy FROM mapd_record_ownership_marker");
817  // Check if migration is being performed on existing non mapd catalogs
818  // Older non mapd dbs will have table but no record in them
819  if (sqliteConnector_.getNumRows() != 0) {
820  // already done
821  sqliteConnector_.query("END TRANSACTION");
822  return;
823  }
824  }
825  // marker not exists - create one
826  else {
827  sqliteConnector_.query("CREATE TABLE mapd_record_ownership_marker (dummy integer)");
828  }
829 
830  DBMetadata db;
831  CHECK(SysCatalog::instance().getMetadataForDB(currentDB_.dbName, db));
832  // place dbId as a refernce for migration being performed
834  "INSERT INTO mapd_record_ownership_marker (dummy) VALUES (?1)",
835  std::vector<std::string>{std::to_string(db.dbOwner)});
836 
837  static const std::map<const DBObjectType, const AccessPrivileges>
838  object_level_all_privs_lookup{
844 
845  // grant owner all permissions on DB
846  DBObjectKey key;
847  key.dbId = currentDB_.dbId;
848  auto _key_place = [&key](auto type) {
849  key.permissionType = type;
850  return key;
851  };
852  for (auto& it : object_level_all_privs_lookup) {
853  objects.emplace_back(_key_place(it.first), it.second, db.dbOwner);
854  objects.back().setName(currentDB_.dbName);
855  }
856 
857  {
858  // other users tables and views
859  string tableQuery(
860  "SELECT tableid, name, userid, isview FROM mapd_tables WHERE userid > 0");
861  sqliteConnector_.query(tableQuery);
862  size_t numRows = sqliteConnector_.getNumRows();
863  for (size_t r = 0; r < numRows; ++r) {
864  int32_t tableid = sqliteConnector_.getData<int>(r, 0);
865  std::string tableName = sqliteConnector_.getData<string>(r, 1);
866  int32_t ownerid = sqliteConnector_.getData<int>(r, 2);
867  bool isview = sqliteConnector_.getData<bool>(r, 3);
868 
871  DBObjectKey key;
872  key.dbId = currentDB_.dbId;
873  key.objectId = tableid;
874  key.permissionType = type;
875 
876  DBObject obj(tableName, type);
877  obj.setObjectKey(key);
878  obj.setOwner(ownerid);
879  obj.setPrivileges(isview ? AccessPrivileges::ALL_VIEW
881 
882  objects.push_back(obj);
883  }
884  }
885 
886  {
887  // other users dashboards
888  string tableQuery("SELECT id, name, userid FROM mapd_dashboards WHERE userid > 0");
889  sqliteConnector_.query(tableQuery);
890  size_t numRows = sqliteConnector_.getNumRows();
891  for (size_t r = 0; r < numRows; ++r) {
892  int32_t dashId = sqliteConnector_.getData<int>(r, 0);
893  std::string dashName = sqliteConnector_.getData<string>(r, 1);
894  int32_t ownerid = sqliteConnector_.getData<int>(r, 2);
895 
897  DBObjectKey key;
898  key.dbId = currentDB_.dbId;
899  key.objectId = dashId;
900  key.permissionType = type;
901 
902  DBObject obj(dashName, type);
903  obj.setObjectKey(key);
904  obj.setOwner(ownerid);
905  obj.setPrivileges(AccessPrivileges::ALL_DASHBOARD);
906 
907  objects.push_back(obj);
908  }
909  }
910  } catch (const std::exception& e) {
911  sqliteConnector_.query("ROLLBACK TRANSACTION");
912  throw;
913  }
914  sqliteConnector_.query("END TRANSACTION");
915 
916  // now apply the objects to the syscat to track the permisisons
917  // moved outside transaction to avoid lock in sqlite
918  try {
920  } catch (const std::exception& e) {
921  LOG(ERROR) << " Issue during migration of DB " << name() << " issue was " << e.what();
922  throw std::runtime_error(" Issue during migration of DB " + name() + " issue was " +
923  e.what());
924  // will need to remove the mapd_record_ownership_marker table and retry
925  }
926 }
T getData(const int row, const int col)
static const AccessPrivileges ALL_DATABASE
Definition: DBObject.h:151
virtual void query_with_text_params(std::string const &query_only)
DBObjectType
Definition: DBObject.h:40
#define LOG(tag)
Definition: Logger.h:285
SqliteConnector sqliteConnector_
Definition: Catalog.h:720
const DBMetadata currentDB_
Definition: Catalog.h:721
virtual void query(const std::string &queryString)
int32_t objectId
Definition: DBObject.h:55
std::string to_string(char const *&&v)
static const AccessPrivileges ALL_VIEW
Definition: DBObject.h:177
std::string name() const
Definition: Catalog.h:348
static SysCatalog & instance()
Definition: SysCatalog.h:343
static const AccessPrivileges ALL_SERVER
Definition: DBObject.h:187
int32_t dbId
Definition: DBObject.h:54
const Catalog * getObjForLock()
Definition: Catalog.cpp:260
static const AccessPrivileges ALL_DASHBOARD
Definition: DBObject.h:169
static const AccessPrivileges ALL_TABLE
Definition: DBObject.h:157
#define CHECK(condition)
Definition: Logger.h:291
int32_t permissionType
Definition: DBObject.h:53
void populateRoleDbObjects(const std::vector< DBObject > &objects)
sqlite_lock< Catalog > cat_sqlite_lock
Definition: Catalog.cpp:126
virtual size_t getNumRows() const

+ Here is the call graph for this function:

+ Here is the caller graph for this function:

bool Catalog_Namespace::Catalog::recreateSystemTableIfUpdated ( foreign_storage::ForeignTable foreign_table,
const std::list< ColumnDescriptor > &  columns 
)
private

Definition at line 6921 of file Catalog.cpp.

References CHECK, foreign_storage::ForeignTable::foreign_server, logger::INFO, LOG, foreign_storage::ForeignServer::name, foreign_storage::OptionsContainer::options, and TableDescriptor::tableName.

6922  {
6923  auto stored_td = getMetadataForTable(foreign_table.tableName, false);
6924  bool should_recreate{false};
6925  if (stored_td) {
6926  auto stored_foreign_table =
6927  dynamic_cast<const foreign_storage::ForeignTable*>(stored_td);
6928  CHECK(stored_foreign_table);
6929  if (stored_foreign_table->foreign_server->name !=
6930  foreign_table.foreign_server->name ||
6931  stored_foreign_table->options != foreign_table.options) {
6932  should_recreate = true;
6933  } else {
6934  auto stored_columns =
6935  getAllColumnMetadataForTable(stored_td->tableId, false, false, false);
6936  if (stored_columns.size() != columns.size()) {
6937  should_recreate = true;
6938  } else {
6939  auto it_1 = stored_columns.begin();
6940  auto it_2 = columns.begin();
6941  for (; it_1 != stored_columns.end() && it_2 != columns.end(); it_1++, it_2++) {
6942  // Need a custom comparison here since we don't care if the dictionary comp
6943  // param has changed (comp can change because the column was assigned a
6944  // dictionary, whereas before it was just a compression number).
6945  if ((*it_1)->columnName != it_2->columnName ||
6946  (*it_1)->columnType.get_type() != it_2->columnType.get_type() ||
6947  (*it_1)->columnType.get_subtype() != it_2->columnType.get_subtype() ||
6948  (*it_1)->columnType.get_dimension() != it_2->columnType.get_dimension() ||
6949  (*it_1)->columnType.get_scale() != it_2->columnType.get_scale() ||
6950  (*it_1)->columnType.get_notnull() != it_2->columnType.get_notnull() ||
6951  (*it_1)->columnType.get_compression() !=
6952  it_2->columnType.get_compression() ||
6953  (*it_1)->columnType.get_size() != it_2->columnType.get_size()) {
6954  should_recreate = true;
6955  break;
6956  }
6957  }
6958  }
6959  }
6960  } else {
6961  should_recreate = true;
6962  }
6963  if (should_recreate) {
6964  if (stored_td) {
6965  LOG(INFO) << "Dropping existing \"" << foreign_table.tableName
6966  << "\" system table.";
6967  deleteTableCatalogMetadata(stored_td, {stored_td});
6968  }
6969  LOG(INFO) << "Creating a new \"" << foreign_table.tableName << "\" system table.";
6970  createTable(foreign_table, columns, {}, true);
6971  }
6972  return should_recreate;
6973 }
std::string tableName
void createTable(TableDescriptor &td, const std::list< ColumnDescriptor > &columns, const std::vector< Parser::SharedDictionaryDef > &shared_dict_defs, bool isLogicalTable)
Definition: Catalog.cpp:2945
#define LOG(tag)
Definition: Logger.h:285
void deleteTableCatalogMetadata(const TableDescriptor *logical_table, const std::vector< const TableDescriptor * > &physical_tables)
Definition: Catalog.cpp:4320
std::list< const ColumnDescriptor * > getAllColumnMetadataForTable(const int tableId, const bool fetchSystemColumns, const bool fetchVirtualColumns, const bool fetchPhysicalColumns) const
Returns a list of pointers to constant ColumnDescriptor structs for all the columns from a particular...
Definition: Catalog.cpp:2175
const ForeignServer * foreign_server
Definition: ForeignTable.h:57
#define CHECK(condition)
Definition: Logger.h:291
const TableDescriptor * getMetadataForTable(const std::string &tableName, const bool populateFragmenter=true) const
Returns a pointer to a const TableDescriptor struct matching the provided tableName.
void Catalog_Namespace::Catalog::refreshDictionaryCachesForTableUnlocked ( const TableDescriptor td)
private

Definition at line 4219 of file Catalog.cpp.

References ColumnDescriptor::columnType, SQLTypeInfo::get_comp_param(), SQLTypeInfo::get_compression(), kENCODING_DICT, TableDescriptor::nColumns, and TableDescriptor::tableId.

4219  {
4220  for (auto col_id = 0; col_id < td.nColumns; ++col_id) {
4221  if (auto it = columnDescriptorMapById_.find({td.tableId, col_id});
4222  it != columnDescriptorMapById_.end()) {
4223  auto cd = it->second;
4224  auto dict_id = cd->columnType.get_comp_param();
4225  if (cd->columnType.get_compression() == kENCODING_DICT && dict_id) {
4226  DictRef dict_ref(currentDB_.dbId, dict_id);
4227  if (auto dict_it = dictDescriptorMapByRef_.find(dict_ref);
4228  dict_it != dictDescriptorMapByRef_.end()) {
4229  // getMetadataForDict() will only reload if the stringDict is null.
4230  dict_it->second->stringDict = nullptr;
4231  }
4232  getMetadataForDict(dict_id, true);
4233  }
4234  }
4235  }
4236 }
const DBMetadata currentDB_
Definition: Catalog.h:721
DictDescriptorMapById dictDescriptorMapByRef_
Definition: Catalog.h:711
ColumnDescriptorMapById columnDescriptorMapById_
Definition: Catalog.h:710
const DictDescriptor * getMetadataForDict(int dict_ref, bool loadDict=true) const
Definition: Catalog.cpp:1907

+ Here is the call graph for this function:

void Catalog_Namespace::Catalog::reloadCatalogMetadata ( const std::map< int32_t, std::string > &  user_name_by_user_id)
private

Definition at line 1193 of file Catalog.cpp.

References Catalog_Namespace::anonymous_namespace{Catalog.cpp}::get_user_id_to_user_name_map().

1194  {
1195  cat_write_lock write_lock(this);
1196  cat_sqlite_lock sqlite_lock(getObjForLock());
1198 }
void reloadCatalogMetadataUnlocked(const std::map< int32_t, std::string > &user_name_by_user_id)
Definition: Catalog.cpp:1201
const Catalog * getObjForLock()
Definition: Catalog.cpp:260
write_lock< Catalog > cat_write_lock
Definition: Catalog.cpp:125
sqlite_lock< Catalog > cat_sqlite_lock
Definition: Catalog.cpp:126
std::map< int32_t, std::string > get_user_id_to_user_name_map()
Definition: Catalog.cpp:1045

+ Here is the call graph for this function:

void Catalog_Namespace::Catalog::reloadCatalogMetadataUnlocked ( const std::map< int32_t, std::string > &  user_name_by_user_id)
private

Definition at line 1201 of file Catalog.cpp.

References CHECK_EQ, CHUNK_KEY_DB_IDX, CHUNK_KEY_TABLE_IDX, g_enable_fsi, lockmgr::TableSchemaLockMgr::instance(), and shared::kCatalogDirectoryName.

1202  {
1204 
1206  currentDB_.dbName);
1207 
1208  // Notice when tables or columns have been created, dropped, or changed by other nodes.
1209  // Needed so that users will see reasonably-correct lists of what objects exist.
1210 
1211  // Load the list of table ID's that exist on disk storage.
1212  std::set<int> cluster_table_ids;
1213  std::string tableQuery("SELECT tableid from mapd_tables");
1214  sqliteConnector_.query(tableQuery);
1215  auto numRows = sqliteConnector_.getNumRows();
1216  for (size_t r = 0; r < numRows; ++r) {
1217  const auto table_id = sqliteConnector_.getData<int>(r, 0);
1218  cluster_table_ids.insert(table_id);
1219  }
1220 
1221  // Ignore any table ID's locked by other threads on this node.
1222  // Those other threads are already handling any necessary reloading for those tables.
1223  std::set<int> ignored_table_ids;
1224  for (ChunkKey const& k : lockmgr::TableSchemaLockMgr::instance().getLockedTables()) {
1225  CHECK_EQ(k.size(), 2U);
1226  if (k[CHUNK_KEY_DB_IDX] != currentDB_.dbId) {
1227  continue;
1228  }
1229  ignored_table_ids.insert(k[CHUNK_KEY_TABLE_IDX]);
1230  }
1231 
1232  // For this node's Catalog cache:
1233  // Newly created table schemas created by other nodes need to be loaded.
1234  // Unlocked table schemas might have been renamed by other nodes; just reload them all.
1235  // Deleted table schemas still in this node's cache need to be flushed.
1236  std::set<int> reload_table_ids;
1237  for (auto const& cluster_table_id : cluster_table_ids) {
1238  if (ignored_table_ids.find(cluster_table_id) == ignored_table_ids.end()) {
1239  reload_table_ids.insert(cluster_table_id);
1240  }
1241  }
1242  for (auto const& [cached_table_id, td] : tableDescriptorMapById_) {
1243  if (cluster_table_ids.find(cached_table_id) == cluster_table_ids.end()) {
1244  reload_table_ids.insert(cached_table_id);
1245  }
1246  }
1247 
1248  // Reload tables.
1249  for (auto const& reload_table_id : reload_table_ids) {
1250  reloadTableMetadataUnlocked(reload_table_id);
1251  }
1252 
1254 
1255  dashboardDescriptorMap_.clear();
1256  linkDescriptorMap_.clear();
1257  linkDescriptorMapById_.clear();
1258  foreignServerMap_.clear();
1259  foreignServerMapById_.clear();
1260  custom_expr_map_by_id_.clear();
1261 
1262  if (g_enable_fsi) {
1264  }
1265 
1267  buildDashboardsMapUnlocked(user_name_by_user_id);
1270 
1271  // Notify Calcite about the reloaded database.
1272  if (calciteMgr_) {
1273  calciteMgr_->updateMetadata(currentDB_.dbName, {});
1274  }
1275 }
#define CHECK_EQ(x, y)
Definition: Logger.h:301
std::vector< int > ChunkKey
Definition: types.h:36
static TableSchemaLockMgr & instance()
Definition: LockMgr.h:40
T getData(const int row, const int col)
SqliteConnector sqliteConnector_
Definition: Catalog.h:720
const DBMetadata currentDB_
Definition: Catalog.h:721
#define CHUNK_KEY_DB_IDX
Definition: types.h:38
virtual void query(const std::string &queryString)
DashboardDescriptorMap dashboardDescriptorMap_
Definition: Catalog.h:712
void reset(const std::string &path)
void buildDashboardsMapUnlocked(const std::map< int32_t, std::string > &user_name_by_user_id)
Definition: Catalog.cpp:1420
#define CHUNK_KEY_TABLE_IDX
Definition: types.h:39
TableDescriptorMapById tableDescriptorMapById_
Definition: Catalog.h:708
void buildCustomExpressionsMapUnlocked()
Definition: Catalog.cpp:1517
ForeignServerMapById foreignServerMapById_
Definition: Catalog.h:716
ForeignServerMap foreignServerMap_
Definition: Catalog.h:715
std::shared_ptr< Calcite > calciteMgr_
Definition: Catalog.h:725
const std::string kCatalogDirectoryName
void reloadTableMetadataUnlocked(int table_id)
Definition: Catalog.cpp:1103
CustomExpressionMapById custom_expr_map_by_id_
Definition: Catalog.h:717
LinkDescriptorMapById linkDescriptorMapById_
Definition: Catalog.h:714
bool g_enable_fsi
Definition: Catalog.cpp:96
virtual size_t getNumRows() const
LinkDescriptorMap linkDescriptorMap_
Definition: Catalog.h:713

+ Here is the call graph for this function:

void Catalog_Namespace::Catalog::reloadDictionariesFromDiskUnlocked ( )
private

Definition at line 5180 of file Catalog.cpp.

References g_base_path, shared::kDataDirectoryName, and to_string().

Referenced by reloadTableMetadataUnlocked().

5180  {
5181  std::string dictQuery(
5182  "SELECT dictid, name, nbits, is_shared, refcount from mapd_dictionaries");
5183  sqliteConnector_.query(dictQuery);
5184  auto numRows = sqliteConnector_.getNumRows();
5185  for (size_t r = 0; r < numRows; ++r) {
5186  auto dictId = sqliteConnector_.getData<int>(r, 0);
5187  auto dictName = sqliteConnector_.getData<string>(r, 1);
5188  auto dictNBits = sqliteConnector_.getData<int>(r, 2);
5189  auto is_shared = sqliteConnector_.getData<bool>(r, 3);
5190  auto refcount = sqliteConnector_.getData<int>(r, 4);
5191  auto fname = g_base_path + "/" + shared::kDataDirectoryName + "/DB_" +
5192  std::to_string(currentDB_.dbId) + "_DICT_" + std::to_string(dictId);
5193  DictRef dict_ref(currentDB_.dbId, dictId);
5194  DictDescriptor dd(dict_ref, dictName, dictNBits, is_shared, refcount, fname, false);
5195  if (auto it = dictDescriptorMapByRef_.find(dict_ref);
5196  it == dictDescriptorMapByRef_.end()) {
5197  dictDescriptorMapByRef_[dict_ref] = std::make_unique<DictDescriptor>(dd);
5198  } else {
5199  *it->second = dd;
5200  }
5201  }
5202 }
const std::string kDataDirectoryName
T getData(const int row, const int col)
SqliteConnector sqliteConnector_
Definition: Catalog.h:720
const DBMetadata currentDB_
Definition: Catalog.h:721
DictDescriptorMapById dictDescriptorMapByRef_
Definition: Catalog.h:711
virtual void query(const std::string &queryString)
std::string to_string(char const *&&v)
std::string g_base_path
Definition: SysCatalog.cpp:62
Descriptor for a dictionary for a string columne.
virtual size_t getNumRows() const

+ Here is the call graph for this function:

+ Here is the caller graph for this function:

void Catalog_Namespace::Catalog::reloadForeignTableUnlocked ( foreign_storage::ForeignTable foreign_table)
private

Definition at line 5152 of file Catalog.cpp.

References CHECK, CHECK_EQ, CHECK_NE, shared::contains(), foreign_storage::ForeignServer::data_wrapper_type, foreign_storage::ForeignTable::foreign_server, g_enable_fsi, foreign_storage::DataWrapperType::IN_MEMORY_DATA_WRAPPERS, TableDescriptor::is_in_memory_system_table, TableDescriptor::is_system_table, foreign_storage::ForeignTable::last_refresh_time, foreign_storage::ForeignTable::next_refresh_time, foreign_storage::OptionsContainer::populateOptionsMap(), TableDescriptor::tableId, TableDescriptor::tableName, and to_string().

5152  {
5154  CHECK_NE(foreign_table.tableId, 0)
5155  << "reloadForeignTable expects a table with valid id";
5157  "SELECT server_id, options, last_refresh_time, next_refresh_time from "
5158  "omnisci_foreign_tables WHERE table_id == " +
5159  std::to_string(foreign_table.tableId));
5160  auto num_rows = sqliteConnector_.getNumRows();
5161  CHECK_EQ(num_rows, 1U) << "Expected single entry in omnisci_foreign_tables for table'"
5162  << foreign_table.tableName << "', instead got " << num_rows;
5163  const auto server_id = sqliteConnector_.getData<int32_t>(0, 0);
5164  const auto& options = sqliteConnector_.getData<std::string>(0, 1);
5165  const auto last_refresh_time = sqliteConnector_.getData<int64_t>(0, 2);
5166  const auto next_refresh_time = sqliteConnector_.getData<int64_t>(0, 3);
5167 
5168  foreign_table.foreign_server = foreignServerMapById_[server_id].get();
5169  CHECK(foreign_table.foreign_server);
5170  foreign_table.populateOptionsMap(options);
5171  foreign_table.last_refresh_time = last_refresh_time;
5172  foreign_table.next_refresh_time = next_refresh_time;
5173  if (foreign_table.is_system_table) {
5174  foreign_table.is_in_memory_system_table =
5176  foreign_table.foreign_server->data_wrapper_type);
5177  }
5178 }
bool contains(const T &container, const U &element)
Definition: misc.h:204
#define CHECK_EQ(x, y)
Definition: Logger.h:301
T getData(const int row, const int col)
std::string tableName
SqliteConnector sqliteConnector_
Definition: Catalog.h:720
virtual void query(const std::string &queryString)
std::string to_string(char const *&&v)
static constexpr std::array< char const *, 5 > IN_MEMORY_DATA_WRAPPERS
bool is_in_memory_system_table
#define CHECK_NE(x, y)
Definition: Logger.h:302
void populateOptionsMap(OptionsMap &&options_map, bool clear=false)
ForeignServerMapById foreignServerMapById_
Definition: Catalog.h:716
const ForeignServer * foreign_server
Definition: ForeignTable.h:57
#define CHECK(condition)
Definition: Logger.h:291
bool g_enable_fsi
Definition: Catalog.cpp:96
virtual size_t getNumRows() const

+ Here is the call graph for this function:

void Catalog_Namespace::Catalog::reloadTableMetadata ( int  table_id)
private

Definition at line 1096 of file Catalog.cpp.

References getObjForLock(), and reloadTableMetadataUnlocked().

1096  {
1097  cat_write_lock write_lock(this);
1098  cat_sqlite_lock sqlite_lock(getObjForLock());
1099  reloadTableMetadataUnlocked(table_id);
1100 }
const Catalog * getObjForLock()
Definition: Catalog.cpp:260
write_lock< Catalog > cat_write_lock
Definition: Catalog.cpp:125
void reloadTableMetadataUnlocked(int table_id)
Definition: Catalog.cpp:1103
sqlite_lock< Catalog > cat_sqlite_lock
Definition: Catalog.cpp:126

+ Here is the call graph for this function:

void Catalog_Namespace::Catalog::reloadTableMetadataUnlocked ( int  table_id)
private

Definition at line 1103 of file Catalog.cpp.

References CHECK_EQ, columnDescriptorMapById_, currentDB_, dataMgr_, Catalog_Namespace::DBMetadata::dbId, deletedColumnPerTable_, TableDescriptor::hasDeletedCol, TableDescriptor::nColumns, reloadDictionariesFromDiskUnlocked(), removeFromColumnMap(), tableDescriptorMap_, tableDescriptorMapById_, TableDescriptor::tableName, and to_upper().

Referenced by reloadTableMetadata().

1103  {
1104  // Reload dictionaries first.
1105  // TODO(sy): Does dictionary reloading really belong here?
1106  // We don't have dictionary locks in the system but maybe we need them.
1108 
1109  // Delete this table's metadata from the in-memory cache before reloading.
1110  TableDescriptor* original_td = nullptr;
1111  std::list<ColumnDescriptor*> original_cds;
1112  if (auto it1 = tableDescriptorMapById_.find(table_id);
1113  it1 != tableDescriptorMapById_.end()) {
1114  original_td = it1->second;
1115  if (dynamic_cast<foreign_storage::ForeignTable*>(original_td)) {
1116  // If have a foreign table then we need to destroy the local data wrapper or it will
1117  // contain (potentially invalid) cached data. This needs to be done before we
1118  // remove the table descriptors.
1119  dataMgr_->removeTableRelatedDS(currentDB_.dbId, table_id);
1120  } else {
1121  dataMgr_->removeMutableTableDiskCacheData(currentDB_.dbId, table_id);
1122  }
1123  tableDescriptorMapById_.erase(it1);
1124  if (auto it2 = tableDescriptorMap_.find(to_upper(original_td->tableName));
1125  it2 != tableDescriptorMap_.end()) {
1126  CHECK_EQ(original_td, it2->second);
1127  tableDescriptorMap_.erase(it2);
1128  }
1129  if (original_td->hasDeletedCol) {
1130  const auto ret = deletedColumnPerTable_.erase(original_td);
1131  CHECK_EQ(ret, size_t(1));
1132  }
1133  for (int column_id = 0; column_id < original_td->nColumns; ++column_id) {
1134  if (auto it3 = columnDescriptorMapById_.find({table_id, column_id});
1135  it3 != columnDescriptorMapById_.end()) {
1136  ColumnDescriptor* original_cd = it3->second;
1137  original_cds.push_back(original_cd);
1138  removeFromColumnMap(original_cd);
1139  }
1140  }
1141  }
1142 
1143  TableDescriptor* td;
1144  try {
1145  td = createTableFromDiskUnlocked(table_id);
1146  } catch (const NoTableFoundException& e) {
1147  // No entry found for table on disk. Another node may have deleted it.
1148  return;
1149  }
1150 
1151  if (auto tableDescIt = tableDescriptorMapById_.find(table_id);
1152  tableDescIt != tableDescriptorMapById_.end()) {
1153  tableDescIt->second->fragmenter = nullptr;
1154  delete tableDescIt->second;
1155  }
1156 
1157  // Reload the column descriptors.
1158  auto cds = sqliteGetColumnsForTableUnlocked(table_id);
1159 
1160  // Store the descriptors into the cache.
1161  if (original_td) {
1162  td->mutex_ = original_td->mutex_; // TODO(sy): Unnecessary?
1163  delete original_td;
1164  original_td = nullptr;
1165  }
1166  for (ColumnDescriptor* original_cd : original_cds) {
1167  delete original_cd;
1168  }
1169  original_cds.clear();
1171  tableDescriptorMapById_[td->tableId] = td;
1172  int32_t skip_physical_cols = 0;
1173  for (ColumnDescriptor* cd : cds) {
1174  addToColumnMap(cd);
1175 
1176  if (skip_physical_cols <= 0) {
1177  skip_physical_cols = cd->columnType.get_physical_cols();
1178  }
1179 
1180  if (cd->isDeletedCol) {
1181  td->hasDeletedCol = true;
1182  setDeletedColumnUnlocked(td, cd);
1183  } else if (cd->columnType.is_geometry() || skip_physical_cols-- <= 0) {
1184  td->columnIdBySpi_.push_back(cd->columnId);
1185  }
1186  }
1187 
1188  // Notify Calcite about the reloaded table.
1189  calciteMgr_->updateMetadata(currentDB_.dbName, td->tableName);
1190 }
void removeFromColumnMap(ColumnDescriptor *cd)
Definition: Catalog.cpp:7015
#define CHECK_EQ(x, y)
Definition: Logger.h:301
std::string tableName
const DBMetadata currentDB_
Definition: Catalog.h:721
std::shared_ptr< Data_Namespace::DataMgr > dataMgr_
Definition: Catalog.h:722
TableDescriptor * createTableFromDiskUnlocked(int32_t table_id)
Definition: Catalog.cpp:5253
std::vector< int > columnIdBySpi_
DeletedColumnPerTableMap deletedColumnPerTable_
Definition: Catalog.h:774
ColumnDescriptorMapById columnDescriptorMapById_
Definition: Catalog.h:710
std::shared_ptr< std::mutex > mutex_
void setDeletedColumnUnlocked(const TableDescriptor *td, const ColumnDescriptor *cd)
Definition: Catalog.cpp:3955
TableDescriptorMapById tableDescriptorMapById_
Definition: Catalog.h:708
specifies the content in-memory of a row in the column metadata table
std::string to_upper(const std::string &str)
std::shared_ptr< Calcite > calciteMgr_
Definition: Catalog.h:725
std::list< ColumnDescriptor * > sqliteGetColumnsForTableUnlocked(int32_t table_id)
Definition: Catalog.cpp:5204
void reloadDictionariesFromDiskUnlocked()
Definition: Catalog.cpp:5180
void addToColumnMap(ColumnDescriptor *cd)
Definition: Catalog.cpp:7007
TableDescriptorMap tableDescriptorMap_
Definition: Catalog.h:707

+ Here is the call graph for this function:

+ Here is the caller graph for this function:

void Catalog_Namespace::Catalog::removeChunks ( const int  table_id) const
private

Definition at line 4282 of file Catalog.cpp.

References Data_Namespace::CPU_LEVEL, and Data_Namespace::GPU_LEVEL.

4282  {
4283  removeFragmenterForTable(table_id);
4284 
4285  // remove the chunks from in memory structures
4286  ChunkKey chunkKey = {currentDB_.dbId, table_id};
4287 
4288  dataMgr_->deleteChunksWithPrefix(chunkKey, MemoryLevel::CPU_LEVEL);
4289  dataMgr_->deleteChunksWithPrefix(chunkKey, MemoryLevel::GPU_LEVEL);
4290 }
std::vector< int > ChunkKey
Definition: types.h:36
const DBMetadata currentDB_
Definition: Catalog.h:721
std::shared_ptr< Data_Namespace::DataMgr > dataMgr_
Definition: Catalog.h:722
void removeFragmenterForTable(const int table_id) const
Definition: Catalog.cpp:4270
void Catalog_Namespace::Catalog::removeColumnDescriptor ( const ColumnDescriptor cd)
private

Definition at line 2696 of file Catalog.cpp.

References CHECK, ColumnDescriptor::columnId, gpu_enabled::sort(), and ColumnDescriptor::tableId.

2696  {
2697  if (!cd) {
2698  return;
2699  }
2700 
2701  auto tabDescIt = tableDescriptorMapById_.find(cd->tableId);
2702  CHECK(tableDescriptorMapById_.end() != tabDescIt);
2703  auto td = tabDescIt->second;
2704  auto& cd_by_spi = td->columnIdBySpi_;
2705  cd_by_spi.erase(std::remove(cd_by_spi.begin(), cd_by_spi.end(), cd->columnId),
2706  cd_by_spi.end());
2707  delete cd;
2708  std::sort(cd_by_spi.begin(), cd_by_spi.end());
2709 }
DEVICE void sort(ARGS &&...args)
Definition: gpu_enabled.h:105
TableDescriptorMapById tableDescriptorMapById_
Definition: Catalog.h:708
#define CHECK(condition)
Definition: Logger.h:291

+ Here is the call graph for this function:

void Catalog_Namespace::Catalog::removeDiskCachedDataForMutableTable ( int32_t  table_id) const
private
void Catalog_Namespace::Catalog::removeFragmenterForTable ( const int  table_id) const

Definition at line 4270 of file Catalog.cpp.

References CHECK.

Referenced by anonymous_namespace{DBHandler.cpp}::check_and_reset_in_memory_system_table(), foreign_storage::refresh_foreign_table_unlocked(), and TableOptimizer::vacuumDeletedRows().

4270  {
4271  cat_write_lock write_lock(this);
4272  auto td = getMetadataForTable(table_id, false);
4273  if (td->fragmenter != nullptr) {
4274  auto tableDescIt = tableDescriptorMapById_.find(table_id);
4275  CHECK(tableDescIt != tableDescriptorMapById_.end());
4276  tableDescIt->second->fragmenter = nullptr;
4277  CHECK(td->fragmenter == nullptr);
4278  }
4279 }
TableDescriptorMapById tableDescriptorMapById_
Definition: Catalog.h:708
write_lock< Catalog > cat_write_lock
Definition: Catalog.cpp:125
#define CHECK(condition)
Definition: Logger.h:291
const TableDescriptor * getMetadataForTable(const std::string &tableName, const bool populateFragmenter=true) const
Returns a pointer to a const TableDescriptor struct matching the provided tableName.

+ Here is the caller graph for this function:

void Catalog_Namespace::Catalog::removeFromColumnMap ( ColumnDescriptor cd)
private

Definition at line 7015 of file Catalog.cpp.

References ColumnDescriptor::columnId, ColumnDescriptor::columnName, ColumnDescriptor::columnType, SQLTypeInfo::is_dict_encoded_type(), ColumnDescriptor::tableId, and to_upper().

Referenced by reloadTableMetadataUnlocked().

7015  {
7016  if (cd->columnType.is_dict_encoded_type()) {
7017  dict_columns_by_table_id_[cd->tableId].erase(cd);
7018  }
7021 }
TableDictColumnsMap dict_columns_by_table_id_
Definition: Catalog.h:718
std::tuple< int, std::string > ColumnKey
Definition: Types.h:37
ColumnDescriptorMap columnDescriptorMap_
Definition: Catalog.h:709
ColumnDescriptorMapById columnDescriptorMapById_
Definition: Catalog.h:710
bool is_dict_encoded_type() const
Definition: sqltypes.h:655
std::string to_upper(const std::string &str)
SQLTypeInfo columnType
std::string columnName
std::tuple< int, int > ColumnIdKey
Definition: Types.h:39

+ Here is the call graph for this function:

+ Here is the caller graph for this function:

void Catalog_Namespace::Catalog::removeTableFromMap ( const std::string &  tableName,
const int  tableId,
const bool  is_on_error = false 
)
protected

Definition at line 1604 of file Catalog.cpp.

References CHECK, CHECK_EQ, CHECK_GE, ColumnDescriptor::columnName, ColumnDescriptor::columnType, Data_Namespace::CPU_LEVEL, TableDescriptor::fragmenter, SQLTypeInfo::get_comp_param(), SQLTypeInfo::get_compression(), TableDescriptor::hasDeletedCol, INJECT_TIMER, lockmgr::instance(), kENCODING_DICT, TableDescriptor::persistenceLevel, File_Namespace::renameForDelete(), and to_upper().

1606  {
1607  cat_write_lock write_lock(this);
1608  TableDescriptorMapById::iterator tableDescIt = tableDescriptorMapById_.find(tableId);
1609  if (tableDescIt == tableDescriptorMapById_.end()) {
1610  throw TableNotFoundException(tableName, currentDB_.dbName, " Cannot remove.");
1611  }
1612 
1613  TableDescriptor* td = tableDescIt->second;
1614 
1615  if (td->hasDeletedCol) {
1616  const auto ret = deletedColumnPerTable_.erase(td);
1617  CHECK_EQ(ret, size_t(1));
1618  }
1619 
1620  tableDescriptorMapById_.erase(tableDescIt);
1621  tableDescriptorMap_.erase(to_upper(tableName));
1622  td->fragmenter = nullptr;
1623  dict_columns_by_table_id_.erase(tableId);
1624 
1626  delete td;
1627 
1628  std::unique_ptr<StringDictionaryClient> client;
1629  if (SysCatalog::instance().isAggregator()) {
1630  CHECK(!string_dict_hosts_.empty());
1631  DictRef dict_ref(currentDB_.dbId, -1);
1632  client.reset(new StringDictionaryClient(string_dict_hosts_.front(), dict_ref, true));
1633  }
1634 
1635  // delete all column descriptors for the table
1636  // no more link columnIds to sequential indexes!
1637  for (auto cit = columnDescriptorMapById_.begin();
1638  cit != columnDescriptorMapById_.end();) {
1639  if (tableId != std::get<0>(cit->first)) {
1640  ++cit;
1641  } else {
1642  int i = std::get<1>(cit++->first);
1643  ColumnIdKey cidKey(tableId, i);
1644  ColumnDescriptorMapById::iterator colDescIt = columnDescriptorMapById_.find(cidKey);
1645  ColumnDescriptor* cd = colDescIt->second;
1646  columnDescriptorMapById_.erase(colDescIt);
1647  ColumnKey cnameKey(tableId, to_upper(cd->columnName));
1648  columnDescriptorMap_.erase(cnameKey);
1649  const int dictId = cd->columnType.get_comp_param();
1650  // Dummy dictionaries created for a shard of a logical table have the id set to
1651  // zero.
1652  if (cd->columnType.get_compression() == kENCODING_DICT && dictId) {
1653  INJECT_TIMER(removingDicts);
1654  DictRef dict_ref(currentDB_.dbId, dictId);
1655  const auto dictIt = dictDescriptorMapByRef_.find(dict_ref);
1656  // If we're removing this table due to an error, it is possible that the string
1657  // dictionary reference was never populated. Don't crash, just continue cleaning
1658  // up the TableDescriptor and ColumnDescriptors
1659  if (!is_on_error) {
1660  CHECK(dictIt != dictDescriptorMapByRef_.end());
1661  } else {
1662  if (dictIt == dictDescriptorMapByRef_.end()) {
1663  continue;
1664  }
1665  }
1666  const auto& dd = dictIt->second;
1667  CHECK_GE(dd->refcount, 1);
1668  --dd->refcount;
1669  if (!dd->refcount) {
1670  dd->stringDict.reset();
1671  if (!isTemp) {
1672  File_Namespace::renameForDelete(dd->dictFolderPath);
1673  }
1674  if (client) {
1675  client->drop(dict_ref);
1676  }
1677  dictDescriptorMapByRef_.erase(dictIt);
1678  }
1679  }
1680 
1681  delete cd;
1682  }
1683  }
1684 }
#define CHECK_EQ(x, y)
Definition: Logger.h:301
TableDictColumnsMap dict_columns_by_table_id_
Definition: Catalog.h:718
std::tuple< int, std::string > ColumnKey
Definition: Types.h:37
ColumnDescriptorMap columnDescriptorMap_
Definition: Catalog.h:709
const std::vector< LeafHostInfo > string_dict_hosts_
Definition: Catalog.h:724
const DBMetadata currentDB_
Definition: Catalog.h:721
DictDescriptorMapById dictDescriptorMapByRef_
Definition: Catalog.h:711
#define CHECK_GE(x, y)
Definition: Logger.h:306
DeletedColumnPerTableMap deletedColumnPerTable_
Definition: Catalog.h:774
ColumnDescriptorMapById columnDescriptorMapById_
Definition: Catalog.h:710
static SysCatalog & instance()
Definition: SysCatalog.h:343
#define INJECT_TIMER(DESC)
Definition: measure.h:122
TableDescriptorMapById tableDescriptorMapById_
Definition: Catalog.h:708
specifies the content in-memory of a row in the column metadata table
std::shared_ptr< Fragmenter_Namespace::AbstractFragmenter > fragmenter
std::string to_upper(const std::string &str)
HOST DEVICE EncodingType get_compression() const
Definition: sqltypes.h:399
Data_Namespace::MemoryLevel persistenceLevel
write_lock< Catalog > cat_write_lock
Definition: Catalog.cpp:125
HOST DEVICE int get_comp_param() const
Definition: sqltypes.h:402
#define CHECK(condition)
Definition: Logger.h:291
SQLTypeInfo columnType
void renameForDelete(const std::string directoryName)
Renames a directory to DELETE_ME_&lt;EPOCH&gt;_&lt;oldname&gt;.
Definition: File.cpp:210
std::string columnName
TableDescriptorMap tableDescriptorMap_
Definition: Catalog.h:707
std::tuple< int, int > ColumnIdKey
Definition: Types.h:39

+ Here is the call graph for this function:

void Catalog_Namespace::Catalog::renameColumn ( const TableDescriptor td,
const ColumnDescriptor cd,
const std::string &  newColumnName 
)

Definition at line 4631 of file Catalog.cpp.

References CHECK, ColumnDescriptor::columnId, ColumnDescriptor::columnName, ColumnDescriptor::columnType, SQLTypeInfo::get_physical_cols(), TableDescriptor::tableId, TableDescriptor::tableName, to_string(), and to_upper().

Referenced by AlterTableAlterColumnCommandRecoveryMgr::rollback().

4633  {
4634  cat_write_lock write_lock(this);
4635  cat_sqlite_lock sqlite_lock(getObjForLock());
4636  sqliteConnector_.query("BEGIN TRANSACTION");
4637  try {
4638  for (int i = 0; i <= cd->columnType.get_physical_cols(); ++i) {
4639  auto cdx = getMetadataForColumn(td->tableId, cd->columnId + i);
4640  CHECK(cdx);
4641  std::string new_column_name = cdx->columnName;
4642  new_column_name.replace(0, cd->columnName.size(), newColumnName);
4644  "UPDATE mapd_columns SET name = ? WHERE tableid = ? AND columnid = ?",
4645  std::vector<std::string>{new_column_name,
4646  std::to_string(td->tableId),
4647  std::to_string(cdx->columnId)});
4648  }
4649  } catch (std::exception& e) {
4650  sqliteConnector_.query("ROLLBACK TRANSACTION");
4651  throw;
4652  }
4653  sqliteConnector_.query("END TRANSACTION");
4654  calciteMgr_->updateMetadata(currentDB_.dbName, td->tableName);
4655  for (int i = 0; i <= cd->columnType.get_physical_cols(); ++i) {
4656  auto cdx = getMetadataForColumn(td->tableId, cd->columnId + i);
4657  CHECK(cdx);
4658  ColumnDescriptorMap::iterator columnDescIt = columnDescriptorMap_.find(
4659  std::make_tuple(td->tableId, to_upper(cdx->columnName)));
4660  CHECK(columnDescIt != columnDescriptorMap_.end());
4661  ColumnDescriptor* changeCd = columnDescIt->second;
4662  changeCd->columnName.replace(0, cd->columnName.size(), newColumnName);
4663  columnDescriptorMap_.erase(columnDescIt); // erase entry under old name
4664  columnDescriptorMap_[std::make_tuple(td->tableId, to_upper(changeCd->columnName))] =
4665  changeCd;
4666  }
4667  calciteMgr_->updateMetadata(currentDB_.dbName, td->tableName);
4668 }
std::string tableName
ColumnDescriptorMap columnDescriptorMap_
Definition: Catalog.h:709
virtual void query_with_text_params(std::string const &query_only)
SqliteConnector sqliteConnector_
Definition: Catalog.h:720
const DBMetadata currentDB_
Definition: Catalog.h:721
virtual void query(const std::string &queryString)
std::string to_string(char const *&&v)
int get_physical_cols() const
Definition: sqltypes.h:432
const ColumnDescriptor * getMetadataForColumn(int tableId, const std::string &colName) const
specifies the content in-memory of a row in the column metadata table
std::string to_upper(const std::string &str)
std::shared_ptr< Calcite > calciteMgr_
Definition: Catalog.h:725
const Catalog * getObjForLock()
Definition: Catalog.cpp:260
write_lock< Catalog > cat_write_lock
Definition: Catalog.cpp:125
#define CHECK(condition)
Definition: Logger.h:291
SQLTypeInfo columnType
sqlite_lock< Catalog > cat_sqlite_lock
Definition: Catalog.cpp:126
std::string columnName

+ Here is the call graph for this function:

+ Here is the caller graph for this function:

void Catalog_Namespace::Catalog::renameForeignServer ( const std::string &  server_name,
const std::string &  name 
)

Rename a Foreign Server.

Parameters
server_name- Name of the foreign server whose name will be changed
name- New name of server

Definition at line 3448 of file Catalog.cpp.

References CHECK, and setup::name.

3449  {
3450  cat_write_lock write_lock(this);
3451  auto foreign_server_it = foreignServerMap_.find(server_name);
3452  CHECK(foreign_server_it != foreignServerMap_.end());
3453  setForeignServerProperty(server_name, "name", name);
3454  auto foreign_server_shared = foreign_server_it->second;
3455  foreign_server_shared->name = name;
3456  foreignServerMap_[name] = foreign_server_shared;
3457  foreignServerMap_.erase(foreign_server_it);
3458 }
std::string name() const
Definition: Catalog.h:348
ForeignServerMap foreignServerMap_
Definition: Catalog.h:715
write_lock< Catalog > cat_write_lock
Definition: Catalog.cpp:125
#define CHECK(condition)
Definition: Logger.h:291
void setForeignServerProperty(const std::string &server_name, const std::string &property, const std::string &value)
Definition: Catalog.cpp:5320
void Catalog_Namespace::Catalog::renameLegacyDataWrappers ( )
protected

Definition at line 708 of file Catalog.cpp.

References SqliteConnector::getNumRows(), getObjForLock(), logger::INFO, LOG, MAPD_VERSION, SqliteConnector::query(), SqliteConnector::query_with_text_params(), sqliteConnector_, and to_string().

Referenced by CheckAndExecuteMigrations().

708  {
709  // TODO: Move common migration logic to a shared function.
710  cat_sqlite_lock sqlite_lock(getObjForLock());
711  sqliteConnector_.query("BEGIN TRANSACTION");
712  try {
714  "select name from sqlite_master WHERE type='table' AND "
715  "name='mapd_version_history'");
716  static const std::string migration_name{"rename_legacy_data_wrappers"};
717  if (sqliteConnector_.getNumRows() == 0) {
719  "CREATE TABLE mapd_version_history(version integer, migration_history text "
720  "unique)");
721  } else {
723  "select * from mapd_version_history where migration_history = "
724  "'" +
725  migration_name + "'");
726  if (sqliteConnector_.getNumRows() != 0) {
727  // Migration already done.
728  sqliteConnector_.query("END TRANSACTION");
729  return;
730  }
731  }
732  LOG(INFO) << "Executing " << migration_name << " migration.";
733 
734  // Update legacy data wrapper names
736  // clang-format off
737  std::map<std::string, std::string> old_to_new_wrapper_names{
738  {"OMNISCI_CSV", DataWrapperType::CSV},
739  {"OMNISCI_PARQUET", DataWrapperType::PARQUET},
740  {"OMNISCI_REGEX_PARSER", DataWrapperType::REGEX_PARSER},
741  {"OMNISCI_INTERNAL_CATALOG", DataWrapperType::INTERNAL_CATALOG},
742  {"INTERNAL_OMNISCI_MEMORY_STATS", DataWrapperType::INTERNAL_MEMORY_STATS},
743  {"INTERNAL_OMNISCI_STORAGE_STATS", DataWrapperType::INTERNAL_STORAGE_STATS}
744  };
745  // clang-format on
746 
747  for (const auto& [old_wrapper_name, new_wrapper_name] : old_to_new_wrapper_names) {
749  "UPDATE omnisci_foreign_servers SET data_wrapper_type = ? WHERE "
750  "data_wrapper_type = ?",
751  std::vector<std::string>{new_wrapper_name, old_wrapper_name});
752  }
753 
754  // Record migration.
756  "INSERT INTO mapd_version_history(version, migration_history) values(?,?)",
757  std::vector<std::string>{std::to_string(MAPD_VERSION), migration_name});
758  LOG(INFO) << migration_name << " migration completed.";
759  } catch (std::exception& e) {
760  sqliteConnector_.query("ROLLBACK TRANSACTION");
761  throw;
762  }
763  sqliteConnector_.query("END TRANSACTION");
764 }
virtual void query_with_text_params(std::string const &query_only)
#define LOG(tag)
Definition: Logger.h:285
SqliteConnector sqliteConnector_
Definition: Catalog.h:720
virtual void query(const std::string &queryString)
std::string to_string(char const *&&v)
Encapsulates an enumeration of foreign data wrapper type strings.
static const int32_t MAPD_VERSION
Definition: release.h:32
const Catalog * getObjForLock()
Definition: Catalog.cpp:260
sqlite_lock< Catalog > cat_sqlite_lock
Definition: Catalog.cpp:126
virtual size_t getNumRows() const

+ Here is the call graph for this function:

+ Here is the caller graph for this function:

void Catalog_Namespace::Catalog::renamePhysicalTable ( const TableDescriptor td,
const std::string &  newTableName 
)
protected

Definition at line 4388 of file Catalog.cpp.

References CHECK, TableDescriptor::tableId, TableDescriptor::tableName, to_string(), and to_upper().

4388  {
4389  cat_write_lock write_lock(this);
4390  cat_sqlite_lock sqlite_lock(getObjForLock());
4391 
4392  sqliteConnector_.query("BEGIN TRANSACTION");
4393  try {
4395  "UPDATE mapd_tables SET name = ? WHERE tableid = ?",
4396  std::vector<std::string>{newTableName, std::to_string(td->tableId)});
4397  } catch (std::exception& e) {
4398  sqliteConnector_.query("ROLLBACK TRANSACTION");
4399  throw;
4400  }
4401  sqliteConnector_.query("END TRANSACTION");
4402  TableDescriptorMap::iterator tableDescIt =
4404  CHECK(tableDescIt != tableDescriptorMap_.end());
4405  calciteMgr_->updateMetadata(currentDB_.dbName, td->tableName);
4406  // Get table descriptor to change it
4407  TableDescriptor* changeTd = tableDescIt->second;
4408  changeTd->tableName = newTableName;
4409  tableDescriptorMap_.erase(tableDescIt); // erase entry under old name
4410  tableDescriptorMap_[to_upper(newTableName)] = changeTd;
4411  calciteMgr_->updateMetadata(currentDB_.dbName, td->tableName);
4412 }
std::string tableName
virtual void query_with_text_params(std::string const &query_only)
SqliteConnector sqliteConnector_
Definition: Catalog.h:720
const DBMetadata currentDB_
Definition: Catalog.h:721
virtual void query(const std::string &queryString)
std::string to_string(char const *&&v)
std::string to_upper(const std::string &str)
std::shared_ptr< Calcite > calciteMgr_
Definition: Catalog.h:725
const Catalog * getObjForLock()
Definition: Catalog.cpp:260
write_lock< Catalog > cat_write_lock
Definition: Catalog.cpp:125
#define CHECK(condition)
Definition: Logger.h:291
sqlite_lock< Catalog > cat_sqlite_lock
Definition: Catalog.cpp:126
TableDescriptorMap tableDescriptorMap_
Definition: Catalog.h:707

+ Here is the call graph for this function:

void Catalog_Namespace::Catalog::renamePhysicalTables ( std::vector< std::pair< std::string, std::string >> &  names,
std::vector< int > &  tableIds 
)
protected

Definition at line 4454 of file Catalog.cpp.

References CHECK, TableDescriptor::tableName, to_string(), and to_upper().

4456  {
4457  cat_write_lock write_lock(this);
4458  cat_sqlite_lock sqlite_lock(getObjForLock());
4459 
4460  // execute the SQL query
4461  for (size_t i = 0; i < names.size(); i++) {
4462  int tableId = tableIds[i];
4463  const std::string& newTableName = names[i].second;
4465  "UPDATE mapd_tables SET name = ? WHERE tableid = ?",
4466  std::vector<std::string>{newTableName, std::to_string(tableId)});
4467  }
4468 
4469  // reset the table descriptors, give Calcite a kick
4470  for (size_t i = 0; i < names.size(); i++) {
4471  const auto& [curTableName, newTableName] = names[i];
4472 
4473  TableDescriptorMap::iterator tableDescIt =
4474  tableDescriptorMap_.find(to_upper(curTableName));
4475  CHECK(tableDescIt != tableDescriptorMap_.end());
4476  calciteMgr_->updateMetadata(currentDB_.dbName, curTableName);
4477 
4478  // Get table descriptor to change it
4479  TableDescriptor* changeTd = tableDescIt->second;
4480  changeTd->tableName = newTableName;
4481  tableDescriptorMap_.erase(tableDescIt); // erase entry under old name
4482  tableDescriptorMap_[to_upper(newTableName)] = changeTd;
4483  calciteMgr_->updateMetadata(currentDB_.dbName, curTableName);
4484  }
4485 }
std::string tableName
virtual void query_with_text_params(std::string const &query_only)
SqliteConnector sqliteConnector_
Definition: Catalog.h:720
const DBMetadata currentDB_
Definition: Catalog.h:721
std::string to_string(char const *&&v)
std::string to_upper(const std::string &str)
std::shared_ptr< Calcite > calciteMgr_
Definition: Catalog.h:725
const Catalog * getObjForLock()
Definition: Catalog.cpp:260
write_lock< Catalog > cat_write_lock
Definition: Catalog.cpp:125
#define CHECK(condition)
Definition: Logger.h:291
sqlite_lock< Catalog > cat_sqlite_lock
Definition: Catalog.cpp:126
TableDescriptorMap tableDescriptorMap_
Definition: Catalog.h:707

+ Here is the call graph for this function:

void Catalog_Namespace::Catalog::renameTable ( const TableDescriptor td,
const std::string &  newTableName 
)

Definition at line 4414 of file Catalog.cpp.

References CHECK, DBObjectKey::dbId, lockmgr::instance(), DBObjectKey::objectId, DBObjectKey::permissionType, Grantee::renameDbObject(), TableDBObjectType, and TableDescriptor::tableId.

4414  {
4415  {
4416  cat_write_lock write_lock(this);
4417  cat_sqlite_lock sqlite_lock(getObjForLock());
4418  // rename all corresponding physical tables if this is a logical table
4419  const auto physicalTableIt = logicalToPhysicalTableMapById_.find(td->tableId);
4420  if (physicalTableIt != logicalToPhysicalTableMapById_.end()) {
4421  const auto physicalTables = physicalTableIt->second;
4422  CHECK(!physicalTables.empty());
4423  for (size_t i = 0; i < physicalTables.size(); i++) {
4424  int32_t physical_tb_id = physicalTables[i];
4425  const TableDescriptor* phys_td = getMetadataForTable(physical_tb_id);
4426  CHECK(phys_td);
4427  std::string newPhysTableName =
4428  generatePhysicalTableName(newTableName, static_cast<int32_t>(i + 1));
4429  renamePhysicalTable(phys_td, newPhysTableName);
4430  }
4431  }
4432  renamePhysicalTable(td, newTableName);
4433  }
4434  {
4435  DBObject object(newTableName, TableDBObjectType);
4436  // update table name in direct and effective priv map
4437  DBObjectKey key;
4438  key.dbId = currentDB_.dbId;
4439  key.objectId = td->tableId;
4440  key.permissionType = static_cast<int>(DBObjectType::TableDBObjectType);
4441  object.setObjectKey(key);
4442  auto objdescs = SysCatalog::instance().getMetadataForObject(
4443  currentDB_.dbId, static_cast<int>(DBObjectType::TableDBObjectType), td->tableId);
4444  for (auto obj : objdescs) {
4445  Grantee* grnt = SysCatalog::instance().getGrantee(obj->roleName);
4446  if (grnt) {
4447  grnt->renameDbObject(object);
4448  }
4449  }
4451  }
4452 }
const DBMetadata currentDB_
Definition: Catalog.h:721
Grantee * getGrantee(const std::string &name) const
int32_t objectId
Definition: DBObject.h:55
static SysCatalog & instance()
Definition: SysCatalog.h:343
void renameObjectsInDescriptorMap(DBObject &object, const Catalog_Namespace::Catalog &cat)
int32_t dbId
Definition: DBObject.h:54
const Catalog * getObjForLock()
Definition: Catalog.cpp:260
write_lock< Catalog > cat_write_lock
Definition: Catalog.cpp:125
#define CHECK(condition)
Definition: Logger.h:291
std::string generatePhysicalTableName(const std::string &logicalTableName, const size_t shardNumber)
Definition: Catalog.cpp:5095
int32_t permissionType
Definition: DBObject.h:53
const TableDescriptor * getMetadataForTable(const std::string &tableName, const bool populateFragmenter=true) const
Returns a pointer to a const TableDescriptor struct matching the provided tableName.
sqlite_lock< Catalog > cat_sqlite_lock
Definition: Catalog.cpp:126
void renamePhysicalTable(const TableDescriptor *td, const std::string &newTableName)
Definition: Catalog.cpp:4388
std::vector< ObjectRoleDescriptor * > getMetadataForObject(int32_t dbId, int32_t dbType, int32_t objectId) const
virtual void renameDbObject(const DBObject &object)
Definition: Grantee.cpp:121
LogicalToPhysicalTableMapById logicalToPhysicalTableMapById_
Definition: Catalog.h:727

+ Here is the call graph for this function:

void Catalog_Namespace::Catalog::renameTableDirectories ( const std::string &  temp_data_dir,
const std::vector< std::string > &  target_paths,
const std::string &  name_prefix 
) const
private
void Catalog_Namespace::Catalog::renameTables ( const std::vector< std::pair< std::string, std::string >> &  names)

Definition at line 4513 of file Catalog.cpp.

References CHECK, CHECK_EQ, DBObjectKey::dbId, lockmgr::instance(), DBObjectKey::objectId, DBObjectKey::permissionType, Grantee::renameDbObject(), Catalog_Namespace::anonymous_namespace{Catalog.cpp}::replace_cached_table_name(), TableDBObjectType, TableDescriptor::tableId, and TableDescriptor::tableName.

4514  {
4515  // tableId of all tables being renamed
4516  // ... in matching order to 'names'
4517  std::vector<int> tableIds;
4518 
4519  // (sorted & unique) list of tables ids for locking
4520  // (with names index of src in case of error)
4521  // <tableId, strIndex>
4522  // std::map is by definition/implementation sorted
4523  // std::map current usage below tests to avoid over-write
4524  std::map<int, size_t> uniqueOrderedTableIds;
4525 
4526  // mapping of modified tables names -> tableId
4527  std::map<std::string, int> cachedTableMap;
4528 
4529  // -------- Setup --------
4530 
4531  // gather tableIds pre-execute; build maps
4532  for (size_t i = 0; i < names.size(); i++) {
4533  const auto& [curTableName, newTableName] = names[i];
4534 
4535  // make sure the table being renamed exists,
4536  // or will exist when executed in 'name' order
4537  auto td = getCachedTableDescriptor(cachedTableMap, curTableName);
4538  CHECK(td);
4539 
4540  tableIds.push_back(td->tableId);
4541  if (uniqueOrderedTableIds.find(td->tableId) == uniqueOrderedTableIds.end()) {
4542  // don't overwrite as it should map to the first names index 'i'
4543  uniqueOrderedTableIds[td->tableId] = i;
4544  }
4545  replace_cached_table_name(cachedTableMap, curTableName, newTableName, td->tableId);
4546  }
4547 
4548  CHECK_EQ(tableIds.size(), names.size());
4549 
4550  // The outer Stmt created a write lock before calling the catalog rename table
4551  // -> TODO: might want to sort out which really should set the lock :
4552  // the comment in the outer scope indicates it should be in here
4553  // but it's not clear if the access done there *requires* it out there
4554  //
4555  // Lock tables pre-execute (may/will be in different order than rename occurs)
4556  // const auto execute_write_lock = heavyai::unique_lock<heavyai::shared_mutex>(
4557  // *legacylockmgr::LockMgr<heavyai::shared_mutex, bool>::getMutex(
4558  // legacylockmgr::ExecutorOuterLock, true));
4559 
4560  // acquire the locks for all tables being renamed
4562  for (auto& idPair : uniqueOrderedTableIds) {
4563  const std::string& tableName = names[idPair.second].first;
4564  tableLocks.emplace_back(
4567  *this, tableName, false)));
4568  }
4569 
4570  // -------- Rename --------
4571 
4572  {
4573  cat_write_lock write_lock(this);
4574  // collect all (tables + physical tables) into a single list
4575  std::vector<std::pair<std::string, std::string>> allNames;
4576  std::vector<int> allTableIds;
4577 
4578  for (size_t i = 0; i < names.size(); i++) {
4579  int tableId = tableIds[i];
4580  const auto& [curTableName, newTableName] = names[i];
4581 
4582  // rename all corresponding physical tables if this is a logical table
4583  const auto physicalTableIt = logicalToPhysicalTableMapById_.find(tableId);
4584  if (physicalTableIt != logicalToPhysicalTableMapById_.end()) {
4585  const auto physicalTables = physicalTableIt->second;
4586  CHECK(!physicalTables.empty());
4587  for (size_t k = 0; k < physicalTables.size(); k++) {
4588  int32_t physical_tb_id = physicalTables[k];
4589  const TableDescriptor* phys_td = getMetadataForTable(physical_tb_id);
4590  CHECK(phys_td);
4591  std::string newPhysTableName = generatePhysicalTableName(newTableName, (k + 1));
4592  allNames.emplace_back(phys_td->tableName, newPhysTableName);
4593  allTableIds.push_back(phys_td->tableId);
4594  }
4595  }
4596  allNames.emplace_back(curTableName, newTableName);
4597  allTableIds.push_back(tableId);
4598  }
4599 
4600  // rename all tables in one transaction
4601  execInTransaction(&Catalog::renamePhysicalTables, allNames, allTableIds);
4602  }
4603 
4604  // now update the SysCatalog
4605  for (size_t i = 0; i < names.size(); i++) {
4606  int tableId = tableIds[i];
4607  const std::string& newTableName = names[i].second;
4608  {
4609  // update table name in direct and effective priv map
4610  DBObjectKey key;
4611  key.dbId = currentDB_.dbId;
4612  key.objectId = tableId;
4613  key.permissionType = static_cast<int>(DBObjectType::TableDBObjectType);
4614 
4615  DBObject object(newTableName, TableDBObjectType);
4616  object.setObjectKey(key);
4617 
4618  auto objdescs = SysCatalog::instance().getMetadataForObject(
4619  currentDB_.dbId, static_cast<int>(DBObjectType::TableDBObjectType), tableId);
4620  for (auto obj : objdescs) {
4621  Grantee* grnt = SysCatalog::instance().getGrantee(obj->roleName);
4622  if (grnt) {
4623  grnt->renameDbObject(object);
4624  }
4625  }
4627  }
4628  }
4629 }
#define CHECK_EQ(x, y)
Definition: Logger.h:301
std::vector< std::unique_ptr< lockmgr::AbstractLockContainer< const TableDescriptor * >>> LockedTableDescriptors
Definition: LockMgr.h:272
std::string tableName
const DBMetadata currentDB_
Definition: Catalog.h:721
const TableDescriptor * getCachedTableDescriptor(const std::map< std::string, int > &cached_table_map, const std::string &cur_table_name)
Definition: Catalog.cpp:4490
Grantee * getGrantee(const std::string &name) const
int32_t objectId
Definition: DBObject.h:55
static SysCatalog & instance()
Definition: SysCatalog.h:343
void renameObjectsInDescriptorMap(DBObject &object, const Catalog_Namespace::Catalog &cat)
void execInTransaction(F &&f, Args &&...args)
Definition: Catalog.cpp:7025
void replace_cached_table_name(std::map< std::string, int > &cachedTableMap, const std::string &curTableName, const std::string &newTableName, int tableId)
Definition: Catalog.cpp:4501
int32_t dbId
Definition: DBObject.h:54
write_lock< Catalog > cat_write_lock
Definition: Catalog.cpp:125
void renamePhysicalTables(std::vector< std::pair< std::string, std::string >> &names, std::vector< int > &tableIds)
Definition: Catalog.cpp:4454
#define CHECK(condition)
Definition: Logger.h:291
std::string generatePhysicalTableName(const std::string &logicalTableName, const size_t shardNumber)
Definition: Catalog.cpp:5095
int32_t permissionType
Definition: DBObject.h:53
const TableDescriptor * getMetadataForTable(const std::string &tableName, const bool populateFragmenter=true) const
Returns a pointer to a const TableDescriptor struct matching the provided tableName.
std::vector< ObjectRoleDescriptor * > getMetadataForObject(int32_t dbId, int32_t dbType, int32_t objectId) const
virtual void renameDbObject(const DBObject &object)
Definition: Grantee.cpp:121
LogicalToPhysicalTableMapById logicalToPhysicalTableMapById_
Definition: Catalog.h:727

+ Here is the call graph for this function:

void Catalog_Namespace::Catalog::replaceDashboard ( DashboardDescriptor vd)

Definition at line 4734 of file Catalog.cpp.

References CHECK, DashboardDescriptor::dashboardId, DashboardDescriptor::dashboardMetadata, DashboardDescriptor::dashboardName, DashboardDescriptor::dashboardState, DashboardDescriptor::dashboardSystemRoleName, logger::ERROR, generate_dashboard_system_rolename(), DashboardDescriptor::imageHash, LOG, to_string(), Catalog_Namespace::sqlite_lock< T >::unlock(), Catalog_Namespace::write_lock< T >::unlock(), DashboardDescriptor::updateTime, and DashboardDescriptor::userId.

4734  {
4735  cat_write_lock write_lock(this);
4736  cat_sqlite_lock sqlite_lock(getObjForLock());
4737 
4739  sqliteConnector_.query("BEGIN TRANSACTION");
4740  try {
4742  "SELECT id FROM mapd_dashboards WHERE id = ?",
4743  std::vector<std::string>{std::to_string(vd.dashboardId)});
4744  if (sqliteConnector_.getNumRows() > 0) {
4746  "UPDATE mapd_dashboards SET name = ?, state = ?, image_hash = ?, metadata = "
4747  "?, userid = ?, update_time = datetime('now') where id = ? ",
4748  std::vector<std::string>{vd.dashboardName,
4749  vd.dashboardState,
4750  vd.imageHash,
4751  vd.dashboardMetadata,
4752  std::to_string(vd.userId),
4754  } else {
4755  LOG(ERROR) << "Error replacing dashboard id " << vd.dashboardId
4756  << " does not exist in db";
4757  throw runtime_error("Error replacing dashboard id " +
4758  std::to_string(vd.dashboardId) + " does not exist in db");
4759  }
4760  } catch (std::exception& e) {
4761  sqliteConnector_.query("ROLLBACK TRANSACTION");
4762  throw;
4763  }
4764  sqliteConnector_.query("END TRANSACTION");
4765 
4766  bool found{false};
4767  for (auto descp : dashboardDescriptorMap_) {
4768  auto dash = descp.second.get();
4769  if (dash->dashboardId == vd.dashboardId) {
4770  found = true;
4771  auto viewDescIt = dashboardDescriptorMap_.find(std::to_string(dash->userId) + ":" +
4772  dash->dashboardName);
4773  if (viewDescIt ==
4774  dashboardDescriptorMap_.end()) { // check to make sure view exists
4775  LOG(ERROR) << "No metadata for dashboard for user " << dash->userId
4776  << " dashboard " << dash->dashboardName << " does not exist in map";
4777  throw runtime_error("No metadata for dashboard for user " +
4778  std::to_string(dash->userId) + " dashboard " +
4779  dash->dashboardName + " does not exist in map");
4780  }
4781  dashboardDescriptorMap_.erase(viewDescIt);
4782  break;
4783  }
4784  }
4785  if (!found) {
4786  LOG(ERROR) << "Error replacing dashboard id " << vd.dashboardId
4787  << " does not exist in map";
4788  throw runtime_error("Error replacing dashboard id " + std::to_string(vd.dashboardId) +
4789  " does not exist in map");
4790  }
4791 
4792  // now reload the object
4794  "SELECT id, strftime('%Y-%m-%dT%H:%M:%SZ', update_time) FROM "
4795  "mapd_dashboards "
4796  "WHERE id = ?",
4797  std::vector<std::string>{std::to_string(vd.dashboardId)});
4798  vd.updateTime = sqliteConnector_.getData<string>(0, 1);
4802  sqlite_lock.unlock();
4803  write_lock.unlock();
4804  if (!isInfoSchemaDb()) {
4805  // NOTE(wamsi): Transactionally unsafe
4808  }
4809 }
T getData(const int row, const int col)
virtual void query_with_text_params(std::string const &query_only)
#define LOG(tag)
Definition: Logger.h:285
SqliteConnector sqliteConnector_
Definition: Catalog.h:720
const DBMetadata currentDB_
Definition: Catalog.h:721
virtual void query(const std::string &queryString)
DashboardDescriptorMap dashboardDescriptorMap_
Definition: Catalog.h:712
std::string to_string(char const *&&v)
std::string dashboardSystemRoleName
void createOrUpdateDashboardSystemRole(const std::string &view_meta, const int32_t &user_id, const std::string &dash_role_name)
Definition: Catalog.cpp:1727
void addFrontendViewToMapNoLock(DashboardDescriptor &vd)
Definition: Catalog.cpp:1691
const Catalog * getObjForLock()
Definition: Catalog.cpp:260
write_lock< Catalog > cat_write_lock
Definition: Catalog.cpp:125
bool isInfoSchemaDb() const
Definition: Catalog.cpp:6399
#define CHECK(condition)
Definition: Logger.h:291
sqlite_lock< Catalog > cat_sqlite_lock
Definition: Catalog.cpp:126
auto getSqlitePtr() const
virtual size_t getNumRows() const
std::string generate_dashboard_system_rolename(const std::string &db_id, const std::string &dash_id)

+ Here is the call graph for this function:

void Catalog_Namespace::Catalog::resetTableEpochFloor ( const int  logicalTableId) const

Definition at line 5050 of file Catalog.cpp.

Referenced by AlterTableAlterColumnCommandRecoveryMgr::cleanup().

5050  {
5051  cat_read_lock read_lock(this);
5052  const auto td = getMetadataForTable(logicalTableId, false);
5053  const auto shards = getPhysicalTablesDescriptors(td, false);
5054  for (const auto shard : shards) {
5055  getDataMgr().resetTableEpochFloor(getCurrentDB().dbId, shard->tableId);
5056  }
5057 }
Data_Namespace::DataMgr & getDataMgr() const
Definition: Catalog.h:266
read_lock< Catalog > cat_read_lock
Definition: Catalog.cpp:124
void resetTableEpochFloor(const int32_t db_id, const int32_t tb_id)
Definition: DataMgr.cpp:692
const DBMetadata & getCurrentDB() const
Definition: Catalog.h:265
std::vector< const TableDescriptor * > getPhysicalTablesDescriptors(const TableDescriptor *logical_table_desc, bool populate_fragmenter=true) const
Definition: Catalog.cpp:4879
const TableDescriptor * getMetadataForTable(const std::string &tableName, const bool populateFragmenter=true) const
Returns a pointer to a const TableDescriptor struct matching the provided tableName.

+ Here is the caller graph for this function:

void Catalog_Namespace::Catalog::restoreOldOwners ( const std::map< int32_t, std::string > &  old_owners_user_name_by_id,
const std::map< int32_t, std::vector< DBObject >> &  old_owner_db_objects,
int32_t  new_owner_id 
)
private

Definition at line 6305 of file Catalog.cpp.

References CHECK, CHECK_GT, Catalog_Namespace::anonymous_namespace{Catalog.cpp}::convert_object_owners_map_to_string(), DashboardDBObjectType, logger::FATAL, g_enable_fsi, LOG, ServerDBObjectType, TableDBObjectType, to_string(), UNREACHABLE, and ViewDBObjectType.

6308  {
6309  cat_write_lock write_lock(this);
6310  cat_sqlite_lock sqlite_lock(getObjForLock());
6311  sqliteConnector_.query("BEGIN TRANSACTION");
6312  try {
6313  for (const auto& [old_owner_id, db_objects] : old_owner_db_objects) {
6314  for (const auto& db_object : db_objects) {
6315  auto object_id = db_object.getObjectKey().objectId;
6316  CHECK_GT(object_id, 0);
6317  std::vector<std::string> query_params{std::to_string(old_owner_id),
6318  std::to_string(new_owner_id),
6319  std::to_string(object_id)};
6320  auto object_type = db_object.getType();
6321  if (object_type == DBObjectType::TableDBObjectType ||
6322  object_type == DBObjectType::ViewDBObjectType) {
6324  "UPDATE mapd_tables SET userid = ? WHERE userid = ? AND tableid = ?",
6325  query_params);
6326  } else if (object_type == DBObjectType::DashboardDBObjectType) {
6328  "UPDATE mapd_dashboards SET userid = ? WHERE userid = ? AND id = ?",
6329  query_params);
6330  } else if (object_type == DBObjectType::ServerDBObjectType) {
6333  "UPDATE omnisci_foreign_servers SET owner_user_id = ? "
6334  "WHERE owner_user_id = ? AND id = ?",
6335  query_params);
6336  } else {
6337  UNREACHABLE() << "Unexpected DB object type: " << static_cast<int>(object_type);
6338  }
6339  }
6340  }
6342  old_owners_user_name_by_id, old_owner_db_objects, new_owner_id);
6343  } catch (std::exception& e) {
6344  sqliteConnector_.query("ROLLBACK TRANSACTION");
6345  LOG(FATAL)
6346  << "Unable to restore database objects ownership after an error occurred. "
6347  "Database object ownership information may be in an inconsistent state. " +
6349  getDatabaseId(), new_owner_id, old_owner_db_objects);
6350  }
6351  sqliteConnector_.query("END TRANSACTION");
6352 }
virtual void query_with_text_params(std::string const &query_only)
#define LOG(tag)
Definition: Logger.h:285
SqliteConnector sqliteConnector_
Definition: Catalog.h:720
#define UNREACHABLE()
Definition: Logger.h:338
virtual void query(const std::string &queryString)
#define CHECK_GT(x, y)
Definition: Logger.h:305
std::string to_string(char const *&&v)
void restoreOldOwnersInMemory(const std::map< int32_t, std::string > &old_owners_user_name_by_id, const std::map< int32_t, std::vector< DBObject >> &old_owner_db_objects, int32_t new_owner_id)
Definition: Catalog.cpp:6354
int getDatabaseId() const
Definition: Catalog.h:326
const Catalog * getObjForLock()
Definition: Catalog.cpp:260
std::string convert_object_owners_map_to_string(int32_t db_id, int32_t new_owner_id, const std::map< int32_t, std::vector< DBObject >> &old_owner_db_objects)
Definition: Catalog.cpp:6137
write_lock< Catalog > cat_write_lock
Definition: Catalog.cpp:125
#define CHECK(condition)
Definition: Logger.h:291
sqlite_lock< Catalog > cat_sqlite_lock
Definition: Catalog.cpp:126
bool g_enable_fsi
Definition: Catalog.cpp:96

+ Here is the call graph for this function:

void Catalog_Namespace::Catalog::restoreOldOwnersInMemory ( const std::map< int32_t, std::string > &  old_owners_user_name_by_id,
const std::map< int32_t, std::vector< DBObject >> &  old_owner_db_objects,
int32_t  new_owner_id 
)
private

Definition at line 6354 of file Catalog.cpp.

References CHECK, DashboardDBObjectType, ServerDBObjectType, TableDBObjectType, to_string(), UNREACHABLE, and ViewDBObjectType.

6357  {
6358  for (const auto& [old_owner_id, db_objects] : old_owner_db_objects) {
6359  for (const auto& db_object : db_objects) {
6360  auto object_id = db_object.getObjectKey().objectId;
6361  auto object_type = db_object.getType();
6362  if (object_type == DBObjectType::TableDBObjectType ||
6363  object_type == DBObjectType::ViewDBObjectType) {
6364  auto it = tableDescriptorMapById_.find(object_id);
6365  CHECK(it != tableDescriptorMapById_.end());
6366  CHECK(it->second);
6367  it->second->userId = old_owner_id;
6368  } else if (object_type == DBObjectType::DashboardDBObjectType) {
6369  auto it = dashboardDescriptorMap_.find(std::to_string(new_owner_id) + ":" +
6370  db_object.getName());
6371  CHECK(it != dashboardDescriptorMap_.end());
6372  CHECK(it->second);
6373  it->second->userId = old_owner_id;
6374  auto user_name_it = old_owners_user_name_by_id.find(old_owner_id);
6375  CHECK(user_name_it != old_owners_user_name_by_id.end());
6376  it->second->user = user_name_it->second;
6377  dashboardDescriptorMap_[std::to_string(old_owner_id) + ":" +
6378  db_object.getName()] = it->second;
6379  dashboardDescriptorMap_.erase(it);
6380  } else if (object_type == DBObjectType::ServerDBObjectType) {
6381  auto it = foreignServerMapById_.find(object_id);
6382  CHECK(it != foreignServerMapById_.end());
6383  CHECK(it->second);
6384  it->second->user_id = old_owner_id;
6385  } else {
6386  UNREACHABLE() << "Unexpected DB object type: " << static_cast<int>(object_type);
6387  }
6388  }
6389  }
6390 }
#define UNREACHABLE()
Definition: Logger.h:338
DashboardDescriptorMap dashboardDescriptorMap_
Definition: Catalog.h:712
std::string to_string(char const *&&v)
TableDescriptorMapById tableDescriptorMapById_
Definition: Catalog.h:708
ForeignServerMapById foreignServerMapById_
Definition: Catalog.h:716
#define CHECK(condition)
Definition: Logger.h:291

+ Here is the call graph for this function:

void Catalog_Namespace::Catalog::rollLegacy ( const bool  forward)

Definition at line 2728 of file Catalog.cpp.

References CHECK.

2728  {
2729  cat_write_lock write_lock(this);
2730  std::set<const TableDescriptor*> tds;
2731 
2732  for (const auto& cdr : columnDescriptorsForRoll) {
2733  auto ocd = cdr.first;
2734  auto ncd = cdr.second;
2735  CHECK(ocd || ncd);
2736  auto tabDescIt = tableDescriptorMapById_.find((ncd ? ncd : ocd)->tableId);
2737  CHECK(tableDescriptorMapById_.end() != tabDescIt);
2738  auto td = tabDescIt->second;
2739  auto& vc = td->columnIdBySpi_;
2740  if (forward) {
2741  if (ocd) {
2742  if (nullptr == ncd ||
2743  ncd->columnType.get_comp_param() != ocd->columnType.get_comp_param()) {
2745  }
2746 
2747  vc.erase(std::remove(vc.begin(), vc.end(), ocd->columnId), vc.end());
2748 
2749  delete ocd;
2750  }
2751  if (ncd) {
2752  // append columnId if its new and not phy geo
2753  if (vc.end() == std::find(vc.begin(), vc.end(), ncd->columnId)) {
2754  if (!ncd->isGeoPhyCol) {
2755  vc.push_back(ncd->columnId);
2756  }
2757  }
2758  }
2759  tds.insert(td);
2760  } else {
2761  if (ocd) {
2762  addToColumnMap(ocd);
2763  }
2764  // roll back the dict of new column
2765  if (ncd) {
2766  removeFromColumnMap(ncd);
2767  if (nullptr == ocd ||
2768  ocd->columnType.get_comp_param() != ncd->columnType.get_comp_param()) {
2770  }
2771  delete ncd;
2772  }
2773  }
2774  }
2775  columnDescriptorsForRoll.clear();
2776 
2777  if (forward) {
2778  for (const auto td : tds) {
2779  calciteMgr_->updateMetadata(currentDB_.dbName, td->tableName);
2780  }
2781  }
2782 }
void removeFromColumnMap(ColumnDescriptor *cd)
Definition: Catalog.cpp:7015
const DBMetadata currentDB_
Definition: Catalog.h:721
TableDescriptorMapById tableDescriptorMapById_
Definition: Catalog.h:708
std::shared_ptr< Calcite > calciteMgr_
Definition: Catalog.h:725
write_lock< Catalog > cat_write_lock
Definition: Catalog.cpp:125
void delDictionaryNontransactional(const ColumnDescriptor &cd)
Definition: Catalog.cpp:2290
#define CHECK(condition)
Definition: Logger.h:291
ColumnDescriptorsForRoll columnDescriptorsForRoll
Definition: Catalog.h:739
void addToColumnMap(ColumnDescriptor *cd)
Definition: Catalog.cpp:7007
void Catalog_Namespace::Catalog::serializeTableJsonUnlocked ( const TableDescriptor td,
const std::list< ColumnDescriptor > &  cds 
) const
protected

Definition at line 3190 of file Catalog.cpp.

References CHECK, Catalog_Namespace::anonymous_namespace{Catalog.cpp}::table_json_filepath(), TableDescriptor::tableId, TableDescriptor::tableName, and VLOG.

3191  {
3192  // relies on the catalog write lock
3193  using namespace rapidjson;
3194 
3195  VLOG(1) << "Serializing temporary table " << td->tableName << " to JSON for Calcite.";
3196 
3197  const auto db_name = currentDB_.dbName;
3198  const auto file_path = table_json_filepath(basePath_, db_name);
3199 
3200  Document d;
3201  if (boost::filesystem::exists(file_path)) {
3202  // look for an existing file for this database
3203  std::ifstream reader(file_path.string());
3204  CHECK(reader.is_open());
3205  IStreamWrapper json_read_wrapper(reader);
3206  d.ParseStream(json_read_wrapper);
3207  } else {
3208  d.SetObject();
3209  }
3210  CHECK(d.IsObject());
3211  CHECK(!d.HasMember(StringRef(td->tableName.c_str())));
3212 
3213  Value table(kObjectType);
3214  table.AddMember(
3215  "name", Value().SetString(StringRef(td->tableName.c_str())), d.GetAllocator());
3216  table.AddMember("id", Value().SetInt(td->tableId), d.GetAllocator());
3217  table.AddMember("columns", Value(kArrayType), d.GetAllocator());
3218 
3219  for (const auto& cd : cds) {
3220  Value column(kObjectType);
3221  column.AddMember(
3222  "name", Value().SetString(StringRef(cd.columnName)), d.GetAllocator());
3223  column.AddMember("coltype",
3224  Value().SetInt(static_cast<int>(cd.columnType.get_type())),
3225  d.GetAllocator());
3226  column.AddMember("colsubtype",
3227  Value().SetInt(static_cast<int>(cd.columnType.get_subtype())),
3228  d.GetAllocator());
3229  column.AddMember("compression",
3230  Value().SetInt(static_cast<int>(cd.columnType.get_compression())),
3231  d.GetAllocator());
3232  column.AddMember("comp_param",
3233  Value().SetInt(static_cast<int>(cd.columnType.get_comp_param())),
3234  d.GetAllocator());
3235  column.AddMember("size",
3236  Value().SetInt(static_cast<int>(cd.columnType.get_size())),
3237  d.GetAllocator());
3238  column.AddMember(
3239  "coldim", Value().SetInt(cd.columnType.get_dimension()), d.GetAllocator());
3240  column.AddMember(
3241  "colscale", Value().SetInt(cd.columnType.get_scale()), d.GetAllocator());
3242  column.AddMember(
3243  "is_notnull", Value().SetBool(cd.columnType.get_notnull()), d.GetAllocator());
3244  column.AddMember("is_systemcol", Value().SetBool(cd.isSystemCol), d.GetAllocator());
3245  column.AddMember("is_virtualcol", Value().SetBool(cd.isVirtualCol), d.GetAllocator());
3246  column.AddMember("is_deletedcol", Value().SetBool(cd.isDeletedCol), d.GetAllocator());
3247  table["columns"].PushBack(column, d.GetAllocator());
3248  }
3249  d.AddMember(StringRef(td->tableName.c_str()), table, d.GetAllocator());
3250 
3251  // Overwrite the existing file
3252  std::ofstream writer(file_path.string(), std::ios::trunc | std::ios::out);
3253  CHECK(writer.is_open());
3254  OStreamWrapper json_wrapper(writer);
3255 
3256  Writer<OStreamWrapper> json_writer(json_wrapper);
3257  d.Accept(json_writer);
3258  writer.close();
3259 }
std::string tableName
const DBMetadata currentDB_
Definition: Catalog.h:721
auto table_json_filepath(const std::string &base_path, const std::string &db_name)
Definition: Catalog.cpp:165
#define CHECK(condition)
Definition: Logger.h:291
#define VLOG(n)
Definition: Logger.h:388

+ Here is the call graph for this function:

void Catalog_Namespace::Catalog::setCalciteMgr ( const std::shared_ptr< Calcite > &  new_calcite_mgr)
inline

Definition at line 268 of file Catalog.h.

References calciteMgr_.

268  {
269  // Used for testing.
270  calciteMgr_ = new_calcite_mgr;
271  }
std::shared_ptr< Calcite > calciteMgr_
Definition: Catalog.h:725
void Catalog_Namespace::Catalog::setColumnDictionary ( ColumnDescriptor cd,
std::list< DictDescriptor > &  dds,
const TableDescriptor td,
bool  is_logical_table,
bool  use_temp_dictionary = false 
)
protected

Definition at line 4066 of file Catalog.cpp.

References ColumnDescriptor::columnName, ColumnDescriptor::columnType, g_base_path, SQLTypeInfo::get_comp_param(), SQLTypeInfo::is_array(), shared::kDataDirectoryName, SQLTypeInfo::set_comp_param(), Catalog_Namespace::anonymous_namespace{Catalog.cpp}::set_dict_key(), SQLTypeInfo::set_size(), TableDescriptor::tableName, and to_string().

4070  {
4071  cat_write_lock write_lock(this);
4072 
4073  std::string dictName{"Initial_key"};
4074  int dictId{0};
4075  std::string folderPath;
4076  if (is_logical_table) {
4077  cat_sqlite_lock sqlite_lock(getObjForLock());
4078 
4080  "INSERT INTO mapd_dictionaries (name, nbits, is_shared, refcount) VALUES (?, ?, "
4081  "?, 1)",
4082  std::vector<std::string>{
4083  dictName, std::to_string(cd.columnType.get_comp_param()), "0"});
4085  "SELECT dictid FROM mapd_dictionaries WHERE name = ?", dictName);
4086  dictId = sqliteConnector_.getData<int>(0, 0);
4087  dictName = td.tableName + "_" + cd.columnName + "_dict" + std::to_string(dictId);
4089  "UPDATE mapd_dictionaries SET name = ? WHERE name = 'Initial_key'", dictName);
4090  folderPath = g_base_path + "/" + shared::kDataDirectoryName + "/DB_" +
4091  std::to_string(currentDB_.dbId) + "_DICT_" + std::to_string(dictId);
4092  }
4094  dictId,
4095  dictName,
4097  false,
4098  1,
4099  folderPath,
4100  use_temp_dictionary);
4101  dds.push_back(dd);
4102  if (!cd.columnType.is_array()) {
4104  }
4105  cd.columnType.set_comp_param(dictId);
4106  set_dict_key(cd);
4107 }
void set_size(int s)
Definition: sqltypes.h:478
const std::string kDataDirectoryName
T getData(const int row, const int col)
std::string tableName
virtual void query_with_text_params(std::string const &query_only)
SqliteConnector sqliteConnector_
Definition: Catalog.h:720
const DBMetadata currentDB_
Definition: Catalog.h:721
std::string to_string(char const *&&v)
std::string g_base_path
Definition: SysCatalog.cpp:62
void set_comp_param(int p)
Definition: sqltypes.h:482
const Catalog * getObjForLock()
Definition: Catalog.cpp:260
write_lock< Catalog > cat_write_lock
Definition: Catalog.cpp:125
HOST DEVICE int get_comp_param() const
Definition: sqltypes.h:402
Descriptor for a dictionary for a string columne.
SQLTypeInfo columnType
sqlite_lock< Catalog > cat_sqlite_lock
Definition: Catalog.cpp:126
std::string columnName
virtual void query_with_text_param(const std::string &queryString, const std::string &text_param)
bool is_array() const
Definition: sqltypes.h:585

+ Here is the call graph for this function:

bool Catalog_Namespace::Catalog::setColumnSharedDictionary ( ColumnDescriptor cd,
std::list< ColumnDescriptor > &  cdd,
std::list< DictDescriptor > &  dds,
const TableDescriptor  td,
const std::vector< Parser::SharedDictionaryDef > &  shared_dict_defs 
)
protected

Definition at line 3997 of file Catalog.cpp.

References CHECK, CHECK_GE, ColumnDescriptor::columnName, ColumnDescriptor::columnType, compress_reference_path(), SQLTypeInfo::get_comp_param(), table_is_temporary(), TableDescriptor::tableName, and to_string().

4002  {
4003  cat_write_lock write_lock(this);
4004  cat_sqlite_lock sqlite_lock(getObjForLock());
4005 
4006  if (shared_dict_defs.empty()) {
4007  return false;
4008  }
4009  for (const auto& shared_dict_def : shared_dict_defs) {
4010  // check if the current column is a referencing column
4011  const auto& column = shared_dict_def.get_column();
4012  if (cd.columnName == column) {
4013  if (!shared_dict_def.get_foreign_table().compare(td.tableName)) {
4014  // Dictionaries are being shared in table to be created
4015  const auto& ref_column = shared_dict_def.get_foreign_column();
4016  auto colIt =
4017  std::find_if(cdd.begin(), cdd.end(), [ref_column](const ColumnDescriptor it) {
4018  return !ref_column.compare(it.columnName);
4019  });
4020  CHECK(colIt != cdd.end());
4021  cd.columnType = colIt->columnType;
4022 
4023  const int dict_id = colIt->columnType.get_comp_param();
4024  CHECK_GE(dict_id, 1);
4025  auto dictIt = std::find_if(
4026  dds.begin(), dds.end(), [this, dict_id](const DictDescriptor it) {
4027  return it.dictRef.dbId == this->currentDB_.dbId &&
4028  it.dictRef.dictId == dict_id;
4029  });
4030  if (dictIt != dds.end()) {
4031  // There exists dictionary definition of a dictionary column
4032  CHECK_GE(dictIt->refcount, 1);
4033  ++dictIt->refcount;
4034  if (!table_is_temporary(&td)) {
4035  // Persist reference count
4037  "UPDATE mapd_dictionaries SET refcount = refcount + 1 WHERE dictid = ?",
4038  {std::to_string(dict_id)});
4039  }
4040  } else {
4041  // The dictionary is referencing a column which is referencing a column in
4042  // diffrent table
4043  auto root_dict_def = compress_reference_path(shared_dict_def, shared_dict_defs);
4044  addReferenceToForeignDict(cd, root_dict_def, !table_is_temporary(&td));
4045  }
4046  } else {
4047  const auto& foreign_table_name = shared_dict_def.get_foreign_table();
4048  const auto foreign_td = getMetadataForTable(foreign_table_name, false);
4049  if (table_is_temporary(foreign_td)) {
4050  if (!table_is_temporary(&td)) {
4051  throw std::runtime_error(
4052  "Only temporary tables can share dictionaries with other temporary "
4053  "tables.");
4054  }
4055  addReferenceToForeignDict(cd, shared_dict_def, false);
4056  } else {
4057  addReferenceToForeignDict(cd, shared_dict_def, !table_is_temporary(&td));
4058  }
4059  }
4060  return true;
4061  }
4062  }
4063  return false;
4064 }
const Parser::SharedDictionaryDef compress_reference_path(Parser::SharedDictionaryDef cur_node, const std::vector< Parser::SharedDictionaryDef > &shared_dict_defs)
std::string tableName
void addReferenceToForeignDict(ColumnDescriptor &referencing_column, Parser::SharedDictionaryDef shared_dict_def, const bool persist_reference)
Definition: Catalog.cpp:3975
virtual void query_with_text_params(std::string const &query_only)
SqliteConnector sqliteConnector_
Definition: Catalog.h:720
const DBMetadata currentDB_
Definition: Catalog.h:721
#define CHECK_GE(x, y)
Definition: Logger.h:306
std::string to_string(char const *&&v)
specifies the content in-memory of a row in the column metadata table
bool table_is_temporary(const TableDescriptor *const td)
const Catalog * getObjForLock()
Definition: Catalog.cpp:260
write_lock< Catalog > cat_write_lock
Definition: Catalog.cpp:125
HOST DEVICE int get_comp_param() const
Definition: sqltypes.h:402
#define CHECK(condition)
Definition: Logger.h:291
Descriptor for a dictionary for a string columne.
SQLTypeInfo columnType
const TableDescriptor * getMetadataForTable(const std::string &tableName, const bool populateFragmenter=true) const
Returns a pointer to a const TableDescriptor struct matching the provided tableName.
sqlite_lock< Catalog > cat_sqlite_lock
Definition: Catalog.cpp:126
std::string columnName

+ Here is the call graph for this function:

void Catalog_Namespace::Catalog::setDeletedColumn ( const TableDescriptor td,
const ColumnDescriptor cd 
)

Definition at line 3950 of file Catalog.cpp.

3950  {
3951  cat_write_lock write_lock(this);
3952  setDeletedColumnUnlocked(td, cd);
3953 }
void setDeletedColumnUnlocked(const TableDescriptor *td, const ColumnDescriptor *cd)
Definition: Catalog.cpp:3955
write_lock< Catalog > cat_write_lock
Definition: Catalog.cpp:125
void Catalog_Namespace::Catalog::setDeletedColumnUnlocked ( const TableDescriptor td,
const ColumnDescriptor cd 
)
private

Definition at line 3955 of file Catalog.cpp.

References CHECK.

3956  {
3957  const auto it_ok = deletedColumnPerTable_.emplace(td, cd);
3958  CHECK(it_ok.second);
3959 }
DeletedColumnPerTableMap deletedColumnPerTable_
Definition: Catalog.h:774
#define CHECK(condition)
Definition: Logger.h:291
void Catalog_Namespace::Catalog::setForeignServerDataWrapper ( const std::string &  server_name,
const std::string &  data_wrapper 
)

Set the data wrapper of a Foreign Server.

Parameters
server_name- Name of the foreign server whose data wrapper will be set
data_wrapper- Data wrapper to use

Definition at line 3407 of file Catalog.cpp.

References CHECK, foreign_storage::ForeignServer::data_wrapper_type, to_upper(), and foreign_storage::ForeignServer::validate().

3408  {
3409  cat_write_lock write_lock(this);
3410  auto data_wrapper_type = to_upper(data_wrapper);
3411  // update in-memory server
3412  foreign_storage::ForeignServer* foreign_server =
3413  foreignServerMap_.find(server_name)->second.get();
3414  CHECK(foreign_server);
3415  std::string saved_data_wrapper_type = foreign_server->data_wrapper_type;
3416  foreign_server->data_wrapper_type = data_wrapper_type;
3417  try {
3418  foreign_server->validate();
3419  } catch (const std::exception& e) {
3420  // validation did not succeed:
3421  // revert to saved data_wrapper_type & throw exception
3422  foreign_server->data_wrapper_type = saved_data_wrapper_type;
3423  throw;
3424  }
3425  setForeignServerProperty(server_name, "data_wrapper_type", data_wrapper_type);
3426 }
ForeignServerMap foreignServerMap_
Definition: Catalog.h:715
std::string to_upper(const std::string &str)
write_lock< Catalog > cat_write_lock
Definition: Catalog.cpp:125
#define CHECK(condition)
Definition: Logger.h:291
void setForeignServerProperty(const std::string &server_name, const std::string &property, const std::string &value)
Definition: Catalog.cpp:5320

+ Here is the call graph for this function:

void Catalog_Namespace::Catalog::setForeignServerOptions ( const std::string &  server_name,
const std::string &  options 
)

Set the options of a Foreign Server.

Parameters
server_name- Name of the foreign server whose options will be set
options- Options to set

Definition at line 3428 of file Catalog.cpp.

References CHECK, foreign_storage::OptionsContainer::options, foreign_storage::OptionsContainer::populateOptionsMap(), and foreign_storage::ForeignServer::validate().

3429  {
3430  cat_write_lock write_lock(this);
3431  // update in-memory server
3432  foreign_storage::ForeignServer* foreign_server =
3433  foreignServerMap_.find(server_name)->second.get();
3434  CHECK(foreign_server);
3435  auto saved_options = foreign_server->options;
3436  foreign_server->populateOptionsMap(options, true);
3437  try {
3438  foreign_server->validate();
3439  } catch (const std::exception& e) {
3440  // validation did not succeed:
3441  // revert to saved options & throw exception
3442  foreign_server->options = saved_options;
3443  throw;
3444  }
3445  setForeignServerProperty(server_name, "options", options);
3446 }
void populateOptionsMap(OptionsMap &&options_map, bool clear=false)
ForeignServerMap foreignServerMap_
Definition: Catalog.h:715
write_lock< Catalog > cat_write_lock
Definition: Catalog.cpp:125
#define CHECK(condition)
Definition: Logger.h:291
void setForeignServerProperty(const std::string &server_name, const std::string &property, const std::string &value)
Definition: Catalog.cpp:5320

+ Here is the call graph for this function:

void Catalog_Namespace::Catalog::setForeignServerProperty ( const std::string &  server_name,
const std::string &  property,
const std::string &  value 
)
private

Definition at line 5320 of file Catalog.cpp.

References CHECK_EQ, and to_string().

5322  {
5323  cat_sqlite_lock sqlite_lock(getObjForLock());
5325  "SELECT id from omnisci_foreign_servers where name = ?",
5326  std::vector<std::string>{server_name});
5327  auto num_rows = sqliteConnector_.getNumRows();
5328  if (num_rows > 0) {
5329  CHECK_EQ(size_t(1), num_rows);
5330  auto server_id = sqliteConnector_.getData<int32_t>(0, 0);
5332  "UPDATE omnisci_foreign_servers SET " + property + " = ? WHERE id = ?",
5333  std::vector<std::string>{value, std::to_string(server_id)});
5334  } else {
5335  throw std::runtime_error{"Can not change property \"" + property +
5336  "\" for foreign server." + " Foreign server \"" +
5337  server_name + "\" is not found."};
5338  }
5339 }
#define CHECK_EQ(x, y)
Definition: Logger.h:301
T getData(const int row, const int col)
virtual void query_with_text_params(std::string const &query_only)
SqliteConnector sqliteConnector_
Definition: Catalog.h:720
std::string to_string(char const *&&v)
const Catalog * getObjForLock()
Definition: Catalog.cpp:260
sqlite_lock< Catalog > cat_sqlite_lock
Definition: Catalog.cpp:126
virtual size_t getNumRows() const

+ Here is the call graph for this function:

void Catalog_Namespace::Catalog::setForeignTableOptions ( const std::string &  table_name,
foreign_storage::OptionsMap options_map,
bool  clear_existing_options = true 
)

Set the options of a Foreign Table.

Parameters
table_name- Name of the foreign table whose options will be set
options- Options to set

Definition at line 5837 of file Catalog.cpp.

5839  {
5840  cat_write_lock write_lock(this);
5841  // update in-memory table
5842  auto foreign_table = getForeignTableUnlocked(table_name);
5843  auto saved_options = foreign_table->options;
5844  foreign_table->populateOptionsMap(std::move(options_map), clear_existing_options);
5845  try {
5846  foreign_table->validateOptionValues();
5847  } catch (const std::exception& e) {
5848  // validation did not succeed:
5849  // revert to saved options & throw exception
5850  foreign_table->options = saved_options;
5851  throw;
5852  }
5854  foreign_table, "options", foreign_table->getOptionsAsJsonString());
5855 }
void setForeignTableProperty(const foreign_storage::ForeignTable *table, const std::string &property, const std::string &value)
Definition: Catalog.cpp:5857
write_lock< Catalog > cat_write_lock
Definition: Catalog.cpp:125
foreign_storage::ForeignTable * getForeignTableUnlocked(const std::string &tableName) const
Definition: Catalog.cpp:1821
void Catalog_Namespace::Catalog::setForeignTableProperty ( const foreign_storage::ForeignTable table,
const std::string &  property,
const std::string &  value 
)
private

Definition at line 5857 of file Catalog.cpp.

References CHECK_EQ, TableDescriptor::tableId, TableDescriptor::tableName, and to_string().

5859  {
5860  cat_sqlite_lock sqlite_lock(getObjForLock());
5862  "SELECT table_id from omnisci_foreign_tables where table_id = ?",
5863  std::vector<std::string>{std::to_string(table->tableId)});
5864  auto num_rows = sqliteConnector_.getNumRows();
5865  if (num_rows > 0) {
5866  CHECK_EQ(size_t(1), num_rows);
5868  "UPDATE omnisci_foreign_tables SET " + property + " = ? WHERE table_id = ?",
5869  std::vector<std::string>{value, std::to_string(table->tableId)});
5870  } else {
5871  throw std::runtime_error{"Can not change property \"" + property +
5872  "\" for foreign table." + " Foreign table \"" +
5873  table->tableName + "\" is not found."};
5874  }
5875 }
#define CHECK_EQ(x, y)
Definition: Logger.h:301
std::string tableName
virtual void query_with_text_params(std::string const &query_only)
SqliteConnector sqliteConnector_
Definition: Catalog.h:720
std::string to_string(char const *&&v)
const Catalog * getObjForLock()
Definition: Catalog.cpp:260
sqlite_lock< Catalog > cat_sqlite_lock
Definition: Catalog.cpp:126
virtual size_t getNumRows() const

+ Here is the call graph for this function:

void Catalog_Namespace::Catalog::setForReload ( const int32_t  tableId)

Definition at line 5375 of file Catalog.cpp.

5375  {
5376  const auto td = getMetadataForTable(tableId);
5377  for (const auto shard : getPhysicalTablesDescriptors(td)) {
5378  const auto tableEpoch = getTableEpoch(currentDB_.dbId, shard->tableId);
5379  setTableEpoch(currentDB_.dbId, shard->tableId, tableEpoch);
5380  }
5381 }
const DBMetadata currentDB_
Definition: Catalog.h:721
int32_t getTableEpoch(const int32_t db_id, const int32_t table_id) const
Definition: Catalog.cpp:3589
std::vector< const TableDescriptor * > getPhysicalTablesDescriptors(const TableDescriptor *logical_table_desc, bool populate_fragmenter=true) const
Definition: Catalog.cpp:4879
void setTableEpoch(const int db_id, const int table_id, const int new_epoch)
Definition: Catalog.cpp:3657
const TableDescriptor * getMetadataForTable(const std::string &tableName, const bool populateFragmenter=true) const
Returns a pointer to a const TableDescriptor struct matching the provided tableName.
void Catalog_Namespace::Catalog::setMaxRollbackEpochs ( const int32_t  table_id,
const int32_t  max_rollback_epochs 
)

Definition at line 3742 of file Catalog.cpp.

References CHECK, File_Namespace::FileMgrParams::epoch, logger::INFO, LOG, File_Namespace::FileMgrParams::max_rollback_epochs, and TableDescriptorUpdateParams::max_rollback_epochs.

3743  {
3744  // Must be called from AlterTableParamStmt or other method that takes executor and
3745  // TableSchema locks
3746  if (max_rollback_epochs <= -1) {
3747  throw std::runtime_error("Cannot set max_rollback_epochs < 0.");
3748  }
3749  const auto td = getMetadataForTable(
3750  table_id, false); // Deep copy as there will be gap between read and write locks
3751  CHECK(td); // Existence should have already been checked in
3752  // ParserNode::AlterTableParmStmt
3753  TableDescriptorUpdateParams table_update_params(td);
3754  table_update_params.max_rollback_epochs = max_rollback_epochs;
3755  if (table_update_params == td) { // Operator is overloaded to test for equality
3756  LOG(INFO) << "Setting max_rollback_epochs for table " << table_id
3757  << " to existing value, skipping operation";
3758  return;
3759  }
3760  File_Namespace::FileMgrParams file_mgr_params;
3761  file_mgr_params.epoch = -1; // Use existing epoch
3762  file_mgr_params.max_rollback_epochs = max_rollback_epochs;
3763  setTableFileMgrParams(table_id, file_mgr_params);
3764  alterTableMetadata(td, table_update_params);
3765 }
void setTableFileMgrParams(const int table_id, const File_Namespace::FileMgrParams &file_mgr_params)
Definition: Catalog.cpp:3804
#define LOG(tag)
Definition: Logger.h:285
void alterTableMetadata(const TableDescriptor *td, const TableDescriptorUpdateParams &table_update_params)
Definition: Catalog.cpp:3717
#define CHECK(condition)
Definition: Logger.h:291
const TableDescriptor * getMetadataForTable(const std::string &tableName, const bool populateFragmenter=true) const
Returns a pointer to a const TableDescriptor struct matching the provided tableName.
void Catalog_Namespace::Catalog::setMaxRows ( const int32_t  table_id,
const int64_t  max_rows 
)

Definition at line 3767 of file Catalog.cpp.

References CHECK, logger::INFO, LOG, and TableDescriptorUpdateParams::max_rows.

3767  {
3768  if (max_rows < 0) {
3769  throw std::runtime_error("Max rows cannot be a negative number.");
3770  }
3771  const auto td = getMetadataForTable(table_id);
3772  CHECK(td);
3773  TableDescriptorUpdateParams table_update_params(td);
3774  table_update_params.max_rows = max_rows;
3775  if (table_update_params == td) {
3776  LOG(INFO) << "Max rows value of " << max_rows
3777  << " is the same as the existing value. Skipping update.";
3778  return;
3779  }
3780  alterTableMetadata(td, table_update_params);
3781  CHECK(td->fragmenter);
3782  td->fragmenter->dropFragmentsToSize(max_rows);
3783 }
#define LOG(tag)
Definition: Logger.h:285
void alterTableMetadata(const TableDescriptor *td, const TableDescriptorUpdateParams &table_update_params)
Definition: Catalog.cpp:3717
#define CHECK(condition)
Definition: Logger.h:291
const TableDescriptor * getMetadataForTable(const std::string &tableName, const bool populateFragmenter=true) const
Returns a pointer to a const TableDescriptor struct matching the provided tableName.
void Catalog_Namespace::Catalog::setTableEpoch ( const int  db_id,
const int  table_id,
const int  new_epoch 
)

Definition at line 3657 of file Catalog.cpp.

References CHECK, Data_Namespace::DISK_LEVEL, File_Namespace::FileMgrParams::epoch, logger::INFO, LOG, and File_Namespace::FileMgrParams::max_rollback_epochs.

Referenced by AlterTableAlterColumnCommandRecoveryMgr::recoverAlterTableAlterColumnFromFile(), and TableArchiver::restoreTable().

3657  {
3658  LOG(INFO) << "Set table epoch db:" << db_id << " Table ID " << table_id
3659  << " back to new epoch " << new_epoch;
3660  const auto td = getMetadataForTable(table_id, false);
3661  if (!td) {
3662  std::stringstream table_not_found_error_message;
3663  table_not_found_error_message << "Table (" << db_id << "," << table_id
3664  << ") not found";
3665  throw std::runtime_error(table_not_found_error_message.str());
3666  }
3667  if (td->persistenceLevel != Data_Namespace::MemoryLevel::DISK_LEVEL) {
3668  std::stringstream is_temp_table_error_message;
3669  is_temp_table_error_message << "Cannot set epoch on temporary table";
3670  throw std::runtime_error(is_temp_table_error_message.str());
3671  }
3672 
3673  File_Namespace::FileMgrParams file_mgr_params;
3674  file_mgr_params.epoch = new_epoch;
3675  file_mgr_params.max_rollback_epochs = td->maxRollbackEpochs;
3676 
3677  const auto physical_tables = getPhysicalTablesDescriptors(td, false);
3678  CHECK(!physical_tables.empty());
3679  for (const auto table : physical_tables) {
3680  auto table_id = table->tableId;
3681  LOG(INFO) << "Set sharded table epoch db:" << db_id << " Table ID " << table_id
3682  << " back to new epoch " << new_epoch;
3683  // Should have table lock from caller so safe to do this after, avoids
3684  // having to repopulate data on error
3685  removeChunks(table_id);
3686  dataMgr_->getGlobalFileMgr()->setFileMgrParams(db_id, table_id, file_mgr_params);
3687  }
3688 }
#define LOG(tag)
Definition: Logger.h:285
std::shared_ptr< Data_Namespace::DataMgr > dataMgr_
Definition: Catalog.h:722
void removeChunks(const int table_id) const
Definition: Catalog.cpp:4282
std::vector< const TableDescriptor * > getPhysicalTablesDescriptors(const TableDescriptor *logical_table_desc, bool populate_fragmenter=true) const
Definition: Catalog.cpp:4879
#define CHECK(condition)
Definition: Logger.h:291
const TableDescriptor * getMetadataForTable(const std::string &tableName, const bool populateFragmenter=true) const
Returns a pointer to a const TableDescriptor struct matching the provided tableName.

+ Here is the caller graph for this function:

void Catalog_Namespace::Catalog::setTableEpochs ( const int32_t  db_id,
const std::vector< TableEpochInfo > &  table_epochs 
) const

Definition at line 3859 of file Catalog.cpp.

References CHECK, File_Namespace::FileMgrParams::epoch, logger::INFO, LOG, and File_Namespace::FileMgrParams::max_rollback_epochs.

Referenced by UpdelRoll::cancelUpdate(), and import_export::Loader::setTableEpochs().

3860  {
3861  const auto td = getMetadataForTable(table_epochs[0].table_id, false);
3862  CHECK(td);
3863  File_Namespace::FileMgrParams file_mgr_params;
3864  file_mgr_params.max_rollback_epochs = td->maxRollbackEpochs;
3865 
3866  for (const auto& table_epoch_info : table_epochs) {
3867  removeChunks(table_epoch_info.table_id);
3868  file_mgr_params.epoch = table_epoch_info.table_epoch;
3869  dataMgr_->getGlobalFileMgr()->setFileMgrParams(
3870  db_id, table_epoch_info.table_id, file_mgr_params);
3871  LOG(INFO) << "Set table epoch for db id: " << db_id
3872  << ", table id: " << table_epoch_info.table_id
3873  << ", back to epoch: " << table_epoch_info.table_epoch;
3874  }
3875 }
#define LOG(tag)
Definition: Logger.h:285
std::shared_ptr< Data_Namespace::DataMgr > dataMgr_
Definition: Catalog.h:722
void removeChunks(const int table_id) const
Definition: Catalog.cpp:4282
#define CHECK(condition)
Definition: Logger.h:291
const TableDescriptor * getMetadataForTable(const std::string &tableName, const bool populateFragmenter=true) const
Returns a pointer to a const TableDescriptor struct matching the provided tableName.

+ Here is the caller graph for this function:

void Catalog_Namespace::Catalog::setTableEpochsLogExceptions ( const int32_t  db_id,
const std::vector< TableEpochInfo > &  table_epochs 
) const

Definition at line 3895 of file Catalog.cpp.

References logger::ERROR, LOG, and Catalog_Namespace::anonymous_namespace{Catalog.cpp}::table_epochs_to_string().

Referenced by UpdelRoll::commitUpdate(), TableOptimizer::vacuumDeletedRows(), and TableOptimizer::vacuumFragmentsAboveMinSelectivity().

3897  {
3898  try {
3899  setTableEpochs(db_id, table_epochs);
3900  } catch (std::exception& e) {
3901  LOG(ERROR) << "An error occurred when attempting to set table epochs. DB id: "
3902  << db_id << ", Table epochs: " << table_epochs_to_string(table_epochs)
3903  << ", Error: " << e.what();
3904  }
3905 }
#define LOG(tag)
Definition: Logger.h:285
std::string table_epochs_to_string(const std::vector< TableEpochInfo > &table_epochs)
Definition: Catalog.cpp:3878
void setTableEpochs(const int32_t db_id, const std::vector< TableEpochInfo > &table_epochs) const
Definition: Catalog.cpp:3859

+ Here is the call graph for this function:

+ Here is the caller graph for this function:

void Catalog_Namespace::Catalog::setTableFileMgrParams ( const int  table_id,
const File_Namespace::FileMgrParams file_mgr_params 
)
private

Definition at line 3804 of file Catalog.cpp.

References CHECK, and Data_Namespace::DISK_LEVEL.

3806  {
3807  // Expects parent to have write lock
3808  const auto td = getMetadataForTable(table_id, false);
3809  const auto db_id = this->getDatabaseId();
3810  if (!td) {
3811  std::stringstream table_not_found_error_message;
3812  table_not_found_error_message << "Table (" << db_id << "," << table_id
3813  << ") not found";
3814  throw std::runtime_error(table_not_found_error_message.str());
3815  }
3816  if (td->persistenceLevel != Data_Namespace::MemoryLevel::DISK_LEVEL) {
3817  std::stringstream is_temp_table_error_message;
3818  is_temp_table_error_message << "Cannot set storage params on temporary table";
3819  throw std::runtime_error(is_temp_table_error_message.str());
3820  }
3821 
3822  const auto physical_tables = getPhysicalTablesDescriptors(td, false);
3823  CHECK(!physical_tables.empty());
3824  for (const auto table : physical_tables) {
3825  auto table_id = table->tableId;
3826  removeChunks(table_id);
3827  dataMgr_->getGlobalFileMgr()->setFileMgrParams(db_id, table_id, file_mgr_params);
3828  }
3829 }
std::shared_ptr< Data_Namespace::DataMgr > dataMgr_
Definition: Catalog.h:722
void removeChunks(const int table_id) const
Definition: Catalog.cpp:4282
int getDatabaseId() const
Definition: Catalog.h:326
std::vector< const TableDescriptor * > getPhysicalTablesDescriptors(const TableDescriptor *logical_table_desc, bool populate_fragmenter=true) const
Definition: Catalog.cpp:4879
#define CHECK(condition)
Definition: Logger.h:291
const TableDescriptor * getMetadataForTable(const std::string &tableName, const bool populateFragmenter=true) const
Returns a pointer to a const TableDescriptor struct matching the provided tableName.
void Catalog_Namespace::Catalog::setUncappedTableEpoch ( const std::string &  table_name)

Definition at line 3786 of file Catalog.cpp.

References CHECK, Executor::clearExternalCaches(), File_Namespace::FileMgrParams::max_rollback_epochs, TableDescriptorUpdateParams::max_rollback_epochs, to_upper(), and Catalog_Namespace::write_lock< T >::unlock().

3786  {
3787  cat_write_lock write_lock(this);
3788  auto td_entry = tableDescriptorMap_.find(to_upper(table_name));
3789  CHECK(td_entry != tableDescriptorMap_.end());
3790  auto td = td_entry->second;
3791 
3793 
3794  TableDescriptorUpdateParams table_update_params(td);
3795  table_update_params.max_rollback_epochs = -1;
3796  write_lock.unlock();
3797 
3798  alterTableMetadata(td, table_update_params);
3799  File_Namespace::FileMgrParams file_mgr_params;
3800  file_mgr_params.max_rollback_epochs = -1;
3801  setTableFileMgrParams(td->tableId, file_mgr_params);
3802 }
void setTableFileMgrParams(const int table_id, const File_Namespace::FileMgrParams &file_mgr_params)
Definition: Catalog.cpp:3804
int getDatabaseId() const
Definition: Catalog.h:326
std::string to_upper(const std::string &str)
void alterTableMetadata(const TableDescriptor *td, const TableDescriptorUpdateParams &table_update_params)
Definition: Catalog.cpp:3717
write_lock< Catalog > cat_write_lock
Definition: Catalog.cpp:125
#define CHECK(condition)
Definition: Logger.h:291
static void clearExternalCaches(bool for_update, const TableDescriptor *td, const int current_db_id)
Definition: Execute.h:438
TableDescriptorMap tableDescriptorMap_
Definition: Catalog.h:707

+ Here is the call graph for this function:

std::list< ColumnDescriptor * > Catalog_Namespace::Catalog::sqliteGetColumnsForTableUnlocked ( int32_t  table_id)
private

Definition at line 5204 of file Catalog.cpp.

References Catalog_Namespace::anonymous_namespace{Catalog.cpp}::set_dict_key(), and to_string().

5204  {
5205  std::list<ColumnDescriptor*> cds;
5206  // TODO(Misiu): Change ColumnDescriptorMap_ to use smartpointers. Right now we use
5207  // temporary smartpointers that release their memory once initialized.
5208  std::list<std::unique_ptr<ColumnDescriptor>> smart_cds;
5209  std::string columnQuery(
5210  "SELECT tableid, columnid, name, coltype, colsubtype, coldim, colscale, "
5211  "is_notnull, compression, comp_param, size, chunks, is_systemcol, is_virtualcol, "
5212  "virtual_expr, is_deletedcol, default_value from mapd_columns WHERE tableid = " +
5213  std::to_string(table_id) + " ORDER BY tableid, columnid");
5214  sqliteConnector_.query(columnQuery);
5215  auto numRows = sqliteConnector_.getNumRows();
5216  int32_t skip_physical_cols = 0;
5217  for (size_t r = 0; r < numRows; ++r) {
5218  std::unique_ptr<ColumnDescriptor> cd = std::make_unique<ColumnDescriptor>();
5219  cd->tableId = sqliteConnector_.getData<int>(r, 0);
5220  cd->columnId = sqliteConnector_.getData<int>(r, 1);
5221  cd->columnName = sqliteConnector_.getData<string>(r, 2);
5222  cd->columnType.set_type((SQLTypes)sqliteConnector_.getData<int>(r, 3));
5223  cd->columnType.set_subtype((SQLTypes)sqliteConnector_.getData<int>(r, 4));
5224  cd->columnType.set_dimension(sqliteConnector_.getData<int>(r, 5));
5225  cd->columnType.set_scale(sqliteConnector_.getData<int>(r, 6));
5226  cd->columnType.set_notnull(sqliteConnector_.getData<bool>(r, 7));
5227  cd->columnType.set_compression((EncodingType)sqliteConnector_.getData<int>(r, 8));
5228  cd->columnType.set_comp_param(sqliteConnector_.getData<int>(r, 9));
5229  cd->columnType.set_size(sqliteConnector_.getData<int>(r, 10));
5230  cd->chunks = sqliteConnector_.getData<string>(r, 11);
5231  cd->isSystemCol = sqliteConnector_.getData<bool>(r, 12);
5232  cd->isVirtualCol = sqliteConnector_.getData<bool>(r, 13);
5233  cd->virtualExpr = sqliteConnector_.getData<string>(r, 14);
5234  cd->isDeletedCol = sqliteConnector_.getData<bool>(r, 15);
5235  if (sqliteConnector_.isNull(r, 16)) {
5236  cd->default_value = std::nullopt;
5237  } else {
5238  cd->default_value = std::make_optional(sqliteConnector_.getData<string>(r, 16));
5239  }
5240  cd->isGeoPhyCol = skip_physical_cols-- > 0;
5241  cd->db_id = getDatabaseId();
5242  set_dict_key(*cd);
5243  smart_cds.emplace_back(std::move(cd));
5244  }
5245  // Once we have correctly initialized all columns, release their ownership as we
5246  // currently handle them as free pointers.
5247  for (auto& cd : smart_cds) {
5248  cds.emplace_back(cd.release());
5249  }
5250  return cds;
5251 }
T getData(const int row, const int col)
SQLTypes
Definition: sqltypes.h:65
SqliteConnector sqliteConnector_
Definition: Catalog.h:720
virtual void query(const std::string &queryString)
std::string to_string(char const *&&v)
EncodingType
Definition: sqltypes.h:240
int getDatabaseId() const
Definition: Catalog.h:326
bool isNull(const int row, const int col) const
virtual size_t getNumRows() const

+ Here is the call graph for this function:

void Catalog_Namespace::Catalog::truncateTable ( const TableDescriptor td)

Definition at line 4145 of file Catalog.cpp.

4145  {
4146  // truncate all corresponding physical tables
4147  const auto physical_tables = getPhysicalTablesDescriptors(td);
4148  for (const auto table : physical_tables) {
4149  doTruncateTable(table);
4150  }
4151 }
std::vector< const TableDescriptor * > getPhysicalTablesDescriptors(const TableDescriptor *logical_table_desc, bool populate_fragmenter=true) const
Definition: Catalog.cpp:4879
void doTruncateTable(const TableDescriptor *td)
Definition: Catalog.cpp:4153
void Catalog_Namespace::Catalog::updateCustomExpression ( int32_t  custom_expression_id,
const std::string &  expression_json 
)

Updates the custom expression for the given id with the given expression json string.

Parameters
custom_expression_id- id of custom expression to update
expression_json- expression json string to be set

Definition at line 6051 of file Catalog.cpp.

References CHECK_EQ, and to_string().

6052  {
6053  cat_write_lock write_lock(this);
6054  cat_sqlite_lock sqlite_lock(getObjForLock());
6055  auto it = custom_expr_map_by_id_.find(custom_expression_id);
6056  if (it == custom_expr_map_by_id_.end() || it->second->is_deleted) {
6057  throw std::runtime_error{"Custom expression with id \"" +
6058  std::to_string(custom_expression_id) + "\" does not exist."};
6059  }
6060  auto old_expression_json = it->second->expression_json;
6061  sqliteConnector_.query("BEGIN TRANSACTION");
6062  try {
6064  "SELECT id FROM omnisci_custom_expressions WHERE id = ?",
6065  std::vector<std::string>{std::to_string(custom_expression_id)});
6066  CHECK_EQ(sqliteConnector_.getNumRows(), static_cast<size_t>(1));
6068  "UPDATE omnisci_custom_expressions SET expression_json = ? WHERE id = ?",
6069  std::vector<std::string>{expression_json, std::to_string(custom_expression_id)});
6070  it->second->expression_json = expression_json;
6071  } catch (std::exception& e) {
6072  sqliteConnector_.query("ROLLBACK TRANSACTION");
6073  it->second->expression_json = old_expression_json;
6074  throw;
6075  }
6076  sqliteConnector_.query("END TRANSACTION");
6077 }
#define CHECK_EQ(x, y)
Definition: Logger.h:301
virtual void query_with_text_params(std::string const &query_only)
SqliteConnector sqliteConnector_
Definition: Catalog.h:720
virtual void query(const std::string &queryString)
std::string to_string(char const *&&v)
const Catalog * getObjForLock()
Definition: Catalog.cpp:260
write_lock< Catalog > cat_write_lock
Definition: Catalog.cpp:125
CustomExpressionMapById custom_expr_map_by_id_
Definition: Catalog.h:717
sqlite_lock< Catalog > cat_sqlite_lock
Definition: Catalog.cpp:126
virtual size_t getNumRows() const

+ Here is the call graph for this function:

void Catalog_Namespace::Catalog::updateCustomExpressionsSchema ( )
protected

Definition at line 766 of file Catalog.cpp.

References getCustomExpressionsSchema(), getObjForLock(), SqliteConnector::query(), and sqliteConnector_.

Referenced by CheckAndExecuteMigrations().

766  {
767  cat_sqlite_lock sqlite_lock(getObjForLock());
768  sqliteConnector_.query("BEGIN TRANSACTION");
769  try {
771  } catch (const std::exception& e) {
772  sqliteConnector_.query("ROLLBACK TRANSACTION");
773  throw;
774  }
775  sqliteConnector_.query("END TRANSACTION");
776 }
SqliteConnector sqliteConnector_
Definition: Catalog.h:720
virtual void query(const std::string &queryString)
static const std::string getCustomExpressionsSchema(bool if_not_exists=false)
Definition: Catalog.cpp:793
const Catalog * getObjForLock()
Definition: Catalog.cpp:260
sqlite_lock< Catalog > cat_sqlite_lock
Definition: Catalog.cpp:126

+ Here is the call graph for this function:

+ Here is the caller graph for this function:

void Catalog_Namespace::Catalog::updateDefaultColumnValues ( )
protected

Definition at line 558 of file Catalog.cpp.

References logger::ERROR, SqliteConnector::getData(), SqliteConnector::getNumRows(), getObjForLock(), logger::INFO, LOG, SqliteConnector::query(), and sqliteConnector_.

Referenced by CheckAndExecuteMigrations().

558  {
559  cat_sqlite_lock sqlite_lock(getObjForLock());
560  sqliteConnector_.query("BEGIN TRANSACTION");
561  try {
562  sqliteConnector_.query("PRAGMA TABLE_INFO(mapd_columns)");
563  std::vector<std::string> cols;
564  for (size_t i = 0; i < sqliteConnector_.getNumRows(); i++) {
565  cols.push_back(sqliteConnector_.getData<std::string>(i, 1));
566  }
567  if (std::find(cols.begin(), cols.end(), std::string("default_value")) == cols.end()) {
568  LOG(INFO) << "Adding support for default values to mapd_columns";
569  sqliteConnector_.query("ALTER TABLE mapd_columns ADD default_value TEXT");
570  }
571  } catch (std::exception& e) {
572  sqliteConnector_.query("ROLLBACK TRANSACTION");
573  LOG(ERROR) << "Failed to make metadata update for default values` support";
574  throw;
575  }
576  sqliteConnector_.query("END TRANSACTION");
577 }
T getData(const int row, const int col)
#define LOG(tag)
Definition: Logger.h:285
SqliteConnector sqliteConnector_
Definition: Catalog.h:720
virtual void query(const std::string &queryString)
const Catalog * getObjForLock()
Definition: Catalog.cpp:260
sqlite_lock< Catalog > cat_sqlite_lock
Definition: Catalog.cpp:126
virtual size_t getNumRows() const

+ Here is the call graph for this function:

+ Here is the caller graph for this function:

void Catalog_Namespace::Catalog::updateDeletedColumnIndicator ( )
protected

Definition at line 531 of file Catalog.cpp.

References Catalog_Namespace::DEFAULT_INITIAL_VERSION, SqliteConnector::getData(), SqliteConnector::getNumRows(), getObjForLock(), logger::INFO, LOG, SqliteConnector::query(), sqliteConnector_, and to_string().

Referenced by CheckAndExecuteMigrations().

531  {
532  cat_sqlite_lock sqlite_lock(getObjForLock());
533  sqliteConnector_.query("BEGIN TRANSACTION");
534  try {
535  sqliteConnector_.query("PRAGMA TABLE_INFO(mapd_columns)");
536  std::vector<std::string> cols;
537  for (size_t i = 0; i < sqliteConnector_.getNumRows(); i++) {
538  cols.push_back(sqliteConnector_.getData<std::string>(i, 1));
539  }
540  if (std::find(cols.begin(), cols.end(), std::string("version_num")) == cols.end()) {
541  LOG(INFO) << "Updating mapd_columns updateDeletedColumnIndicator";
542  // need to add new version info
543  string queryString("ALTER TABLE mapd_columns ADD version_num BIGINT DEFAULT " +
545  sqliteConnector_.query(queryString);
546  // need to add new column to table defintion to indicate deleted column, column used
547  // as bitmap for deleted rows.
549  "ALTER TABLE mapd_columns ADD is_deletedcol boolean default 0 ");
550  }
551  } catch (std::exception& e) {
552  sqliteConnector_.query("ROLLBACK TRANSACTION");
553  throw;
554  }
555  sqliteConnector_.query("END TRANSACTION");
556 }
T getData(const int row, const int col)
#define LOG(tag)
Definition: Logger.h:285
SqliteConnector sqliteConnector_
Definition: Catalog.h:720
virtual void query(const std::string &queryString)
std::string to_string(char const *&&v)
const int DEFAULT_INITIAL_VERSION
Definition: Catalog.cpp:113
const Catalog * getObjForLock()
Definition: Catalog.cpp:260
sqlite_lock< Catalog > cat_sqlite_lock
Definition: Catalog.cpp:126
virtual size_t getNumRows() const

+ Here is the call graph for this function:

+ Here is the caller graph for this function:

void Catalog_Namespace::Catalog::updateDictionaryNames ( )
protected

Definition at line 582 of file Catalog.cpp.

References currentDB_, Catalog_Namespace::DBMetadata::dbId, Catalog_Namespace::DBMetadata::dbName, Catalog_Namespace::DEFAULT_INITIAL_VERSION, logger::ERROR, g_base_path, SqliteConnector::getData(), SqliteConnector::getNumRows(), getObjForLock(), logger::INFO, shared::kDataDirectoryName, LOG, SqliteConnector::query(), run_benchmark_import::result, sqliteConnector_, and to_string().

Referenced by CheckAndExecuteMigrations().

582  {
583  cat_sqlite_lock sqlite_lock(getObjForLock());
584  if (currentDB_.dbName.length() == 0) {
585  // updateDictionaryNames dbName length is zero nothing to do here
586  return;
587  }
588  sqliteConnector_.query("BEGIN TRANSACTION");
589  try {
590  sqliteConnector_.query("PRAGMA TABLE_INFO(mapd_dictionaries)");
591  std::vector<std::string> cols;
592  for (size_t i = 0; i < sqliteConnector_.getNumRows(); i++) {
593  cols.push_back(sqliteConnector_.getData<std::string>(i, 1));
594  }
595  if (std::find(cols.begin(), cols.end(), std::string("version_num")) == cols.end()) {
596  // No version number
597  // need to rename dictionaries
598  string dictQuery("SELECT dictid, name from mapd_dictionaries");
599  sqliteConnector_.query(dictQuery);
600  size_t numRows = sqliteConnector_.getNumRows();
601  for (size_t r = 0; r < numRows; ++r) {
602  int dictId = sqliteConnector_.getData<int>(r, 0);
603  std::string dictName = sqliteConnector_.getData<string>(r, 1);
604 
605  std::string oldName = g_base_path + "/" + shared::kDataDirectoryName + "/" +
606  currentDB_.dbName + "_" + dictName;
607  std::string newName = g_base_path + "/" + shared::kDataDirectoryName + "/DB_" +
608  std::to_string(currentDB_.dbId) + "_DICT_" +
609  std::to_string(dictId);
610 
611  int result = rename(oldName.c_str(), newName.c_str());
612 
613  if (result == 0) {
614  LOG(INFO) << "Dictionary upgrade: successfully renamed " << oldName << " to "
615  << newName;
616  } else {
617  LOG(ERROR) << "Failed to rename old dictionary directory " << oldName << " to "
618  << newName + " dbname '" << currentDB_.dbName << "' error code "
619  << std::to_string(result);
620  }
621  }
622  // need to add new version info
623  string queryString("ALTER TABLE mapd_dictionaries ADD version_num BIGINT DEFAULT " +
625  sqliteConnector_.query(queryString);
626  }
627  } catch (std::exception& e) {
628  sqliteConnector_.query("ROLLBACK TRANSACTION");
629  throw;
630  }
631  sqliteConnector_.query("END TRANSACTION");
632 }
const std::string kDataDirectoryName
T getData(const int row, const int col)
#define LOG(tag)
Definition: Logger.h:285
SqliteConnector sqliteConnector_
Definition: Catalog.h:720
const DBMetadata currentDB_
Definition: Catalog.h:721
virtual void query(const std::string &queryString)
std::string to_string(char const *&&v)
std::string g_base_path
Definition: SysCatalog.cpp:62
const int DEFAULT_INITIAL_VERSION
Definition: Catalog.cpp:113
const Catalog * getObjForLock()
Definition: Catalog.cpp:260
sqlite_lock< Catalog > cat_sqlite_lock
Definition: Catalog.cpp:126
virtual size_t getNumRows() const

+ Here is the call graph for this function:

+ Here is the caller graph for this function:

void Catalog_Namespace::Catalog::updateDictionarySchema ( )
protected

Definition at line 676 of file Catalog.cpp.

References SqliteConnector::getData(), SqliteConnector::getNumRows(), getObjForLock(), SqliteConnector::query(), and sqliteConnector_.

Referenced by CheckAndExecuteMigrations().

676  {
677  cat_sqlite_lock sqlite_lock(getObjForLock());
678  sqliteConnector_.query("BEGIN TRANSACTION");
679  try {
680  sqliteConnector_.query("PRAGMA TABLE_INFO(mapd_dictionaries)");
681  std::vector<std::string> cols;
682  for (size_t i = 0; i < sqliteConnector_.getNumRows(); i++) {
683  cols.push_back(sqliteConnector_.getData<std::string>(i, 1));
684  }
685  if (std::find(cols.begin(), cols.end(), std::string("refcount")) == cols.end()) {
686  sqliteConnector_.query("ALTER TABLE mapd_dictionaries ADD refcount DEFAULT 1");
687  }
688  } catch (std::exception& e) {
689  sqliteConnector_.query("ROLLBACK TRANSACTION");
690  throw;
691  }
692  sqliteConnector_.query("END TRANSACTION");
693 }
T getData(const int row, const int col)
SqliteConnector sqliteConnector_
Definition: Catalog.h:720
virtual void query(const std::string &queryString)
const Catalog * getObjForLock()
Definition: Catalog.cpp:260
sqlite_lock< Catalog > cat_sqlite_lock
Definition: Catalog.cpp:126
virtual size_t getNumRows() const

+ Here is the call graph for this function:

+ Here is the caller graph for this function:

void Catalog_Namespace::Catalog::updateFixlenArrayColumns ( )
protected

Definition at line 335 of file Catalog.cpp.

References SqliteConnector::getNumRows(), getObjForLock(), logger::INFO, kARRAY, LOG, MAPD_VERSION, SqliteConnector::query(), SqliteConnector::query_with_text_params(), sqliteConnector_, and to_string().

Referenced by CheckAndExecuteMigrations().

335  {
336  cat_sqlite_lock sqlite_lock(getObjForLock());
337  sqliteConnector_.query("BEGIN TRANSACTION");
338  try {
340  "select name from sqlite_master WHERE type='table' AND "
341  "name='mapd_version_history'");
342  if (sqliteConnector_.getNumRows() == 0) {
344  "CREATE TABLE mapd_version_history(version integer, migration_history text "
345  "unique)");
346  } else {
348  "select * from mapd_version_history where migration_history = "
349  "'notnull_fixlen_arrays'");
350  if (sqliteConnector_.getNumRows() != 0) {
351  // legacy fixlen arrays had migrated
352  // no need for further execution
353  sqliteConnector_.query("END TRANSACTION");
354  return;
355  }
356  }
357  // Insert check for migration
359  "INSERT INTO mapd_version_history(version, migration_history) values(?,?)",
360  std::vector<std::string>{std::to_string(MAPD_VERSION), "notnull_fixlen_arrays"});
361  LOG(INFO) << "Updating mapd_columns, legacy fixlen arrays";
362  // Upating all fixlen array columns
363  string queryString("UPDATE mapd_columns SET is_notnull=1 WHERE coltype=" +
364  std::to_string(kARRAY) + " AND size>0;");
365  sqliteConnector_.query(queryString);
366  } catch (std::exception& e) {
367  sqliteConnector_.query("ROLLBACK TRANSACTION");
368  throw;
369  }
370  sqliteConnector_.query("END TRANSACTION");
371 }
virtual void query_with_text_params(std::string const &query_only)
#define LOG(tag)
Definition: Logger.h:285
SqliteConnector sqliteConnector_
Definition: Catalog.h:720
virtual void query(const std::string &queryString)
std::string to_string(char const *&&v)
static const int32_t MAPD_VERSION
Definition: release.h:32
const Catalog * getObjForLock()
Definition: Catalog.cpp:260
sqlite_lock< Catalog > cat_sqlite_lock
Definition: Catalog.cpp:126
virtual size_t getNumRows() const

+ Here is the call graph for this function:

+ Here is the caller graph for this function:

void Catalog_Namespace::Catalog::updateForeignTableRefreshTimes ( const int32_t  table_id)

Updates the last and next (if applicable) refresh times of the foreign table with the given table id.

Parameters
table_id- id of table to apply updates to

Definition at line 5815 of file Catalog.cpp.

References CHECK, Catalog_Namespace::anonymous_namespace{Catalog.cpp}::get_next_refresh_time(), foreign_storage::RefreshTimeCalculator::getCurrentTime(), and to_string().

Referenced by foreign_storage::refresh_foreign_table_unlocked().

5815  {
5816  cat_write_lock write_lock(this);
5817  cat_sqlite_lock sqlite_lock(getObjForLock());
5818  CHECK(tableDescriptorMapById_.find(table_id) != tableDescriptorMapById_.end());
5819  auto table_descriptor = tableDescriptorMapById_.find(table_id)->second;
5820  CHECK(table_descriptor);
5821  auto foreign_table = dynamic_cast<foreign_storage::ForeignTable*>(table_descriptor);
5822  CHECK(foreign_table);
5823  auto last_refresh_time = foreign_storage::RefreshTimeCalculator::getCurrentTime();
5824  auto next_refresh_time = get_next_refresh_time(*foreign_table);
5826  "UPDATE omnisci_foreign_tables SET last_refresh_time = ?, next_refresh_time = ? "
5827  "WHERE table_id = ?",
5828  std::vector<std::string>{std::to_string(last_refresh_time),
5829  std::to_string(next_refresh_time),
5830  std::to_string(foreign_table->tableId)});
5831  foreign_table->last_refresh_time = last_refresh_time;
5832  foreign_table->next_refresh_time = next_refresh_time;
5833 }
int64_t get_next_refresh_time(const foreign_storage::ForeignTable &foreign_table)
Definition: Catalog.cpp:2932
virtual void query_with_text_params(std::string const &query_only)
SqliteConnector sqliteConnector_
Definition: Catalog.h:720
std::string to_string(char const *&&v)
TableDescriptorMapById tableDescriptorMapById_
Definition: Catalog.h:708
const Catalog * getObjForLock()
Definition: Catalog.cpp:260
write_lock< Catalog > cat_write_lock
Definition: Catalog.cpp:125
#define CHECK(condition)
Definition: Logger.h:291
sqlite_lock< Catalog > cat_sqlite_lock
Definition: Catalog.cpp:126

+ Here is the call graph for this function:

+ Here is the caller graph for this function:

void Catalog_Namespace::Catalog::updateForeignTablesInMapUnlocked ( )
private

Definition at line 5122 of file Catalog.cpp.

References CHECK, shared::contains(), g_enable_fsi, and foreign_storage::DataWrapperType::IN_MEMORY_DATA_WRAPPERS.

5122  {
5125  "SELECT table_id, server_id, options, last_refresh_time, next_refresh_time from "
5126  "omnisci_foreign_tables");
5127  auto num_rows = sqliteConnector_.getNumRows();
5128  for (size_t r = 0; r < num_rows; r++) {
5129  const auto table_id = sqliteConnector_.getData<int32_t>(r, 0);
5130  const auto server_id = sqliteConnector_.getData<int32_t>(r, 1);
5131  const auto& options = sqliteConnector_.getData<std::string>(r, 2);
5132  const auto last_refresh_time = sqliteConnector_.getData<int64_t>(r, 3);
5133  const auto next_refresh_time = sqliteConnector_.getData<int64_t>(r, 4);
5134 
5135  CHECK(tableDescriptorMapById_.find(table_id) != tableDescriptorMapById_.end());
5136  auto foreign_table =
5137  dynamic_cast<foreign_storage::ForeignTable*>(tableDescriptorMapById_[table_id]);
5138  CHECK(foreign_table);
5139  foreign_table->foreign_server = foreignServerMapById_[server_id].get();
5140  CHECK(foreign_table->foreign_server);
5141  foreign_table->populateOptionsMap(options);
5142  foreign_table->last_refresh_time = last_refresh_time;
5143  foreign_table->next_refresh_time = next_refresh_time;
5144  if (foreign_table->is_system_table) {
5145  foreign_table->is_in_memory_system_table =
5147  foreign_table->foreign_server->data_wrapper_type);
5148  }
5149  }
5150 }
bool contains(const T &container, const U &element)
Definition: misc.h:204
T getData(const int row, const int col)
SqliteConnector sqliteConnector_
Definition: Catalog.h:720
virtual void query(const std::string &queryString)
static constexpr std::array< char const *, 5 > IN_MEMORY_DATA_WRAPPERS
TableDescriptorMapById tableDescriptorMapById_
Definition: Catalog.h:708
ForeignServerMapById foreignServerMapById_
Definition: Catalog.h:716
#define CHECK(condition)
Definition: Logger.h:291
bool g_enable_fsi
Definition: Catalog.cpp:96
virtual size_t getNumRows() const

+ Here is the call graph for this function:

void Catalog_Namespace::Catalog::updateFrontendViewAndLinkUsers ( )
protected

Definition at line 473 of file Catalog.cpp.

References SqliteConnector::getNumRows(), getObjForLock(), SqliteConnector::query(), and sqliteConnector_.

Referenced by CheckAndExecuteMigrations().

473  {
474  cat_sqlite_lock sqlite_lock(getObjForLock());
475  sqliteConnector_.query("BEGIN TRANSACTION");
476  try {
477  sqliteConnector_.query("UPDATE mapd_links SET userid = 0 WHERE userid IS NULL");
478  // check table still exists
480  "SELECT name FROM sqlite_master WHERE type='table' AND "
481  "name='mapd_frontend_views'");
482  if (sqliteConnector_.getNumRows() == 0) {
483  // table does not exists
484  // no need to migrate
485  sqliteConnector_.query("END TRANSACTION");
486  return;
487  }
489  "UPDATE mapd_frontend_views SET userid = 0 WHERE userid IS NULL");
490  } catch (const std::exception& e) {
491  sqliteConnector_.query("ROLLBACK TRANSACTION");
492  throw;
493  }
494  sqliteConnector_.query("END TRANSACTION");
495 }
SqliteConnector sqliteConnector_
Definition: Catalog.h:720
virtual void query(const std::string &queryString)
const Catalog * getObjForLock()
Definition: Catalog.cpp:260
sqlite_lock< Catalog > cat_sqlite_lock
Definition: Catalog.cpp:126
virtual size_t getNumRows() const

+ Here is the call graph for this function:

+ Here is the caller graph for this function:

void Catalog_Namespace::Catalog::updateFrontendViewSchema ( )
protected

Definition at line 415 of file Catalog.cpp.

References SqliteConnector::getData(), SqliteConnector::getNumRows(), getObjForLock(), SqliteConnector::query(), and sqliteConnector_.

Referenced by CheckAndExecuteMigrations().

415  {
416  cat_sqlite_lock sqlite_lock(getObjForLock());
417  sqliteConnector_.query("BEGIN TRANSACTION");
418  try {
419  // check table still exists
421  "SELECT name FROM sqlite_master WHERE type='table' AND "
422  "name='mapd_frontend_views'");
423  if (sqliteConnector_.getNumRows() == 0) {
424  // table does not exists
425  // no need to migrate
426  sqliteConnector_.query("END TRANSACTION");
427  return;
428  }
429  sqliteConnector_.query("PRAGMA TABLE_INFO(mapd_frontend_views)");
430  std::vector<std::string> cols;
431  for (size_t i = 0; i < sqliteConnector_.getNumRows(); i++) {
432  cols.push_back(sqliteConnector_.getData<std::string>(i, 1));
433  }
434  if (std::find(cols.begin(), cols.end(), std::string("image_hash")) == cols.end()) {
435  sqliteConnector_.query("ALTER TABLE mapd_frontend_views ADD image_hash text");
436  }
437  if (std::find(cols.begin(), cols.end(), std::string("update_time")) == cols.end()) {
438  sqliteConnector_.query("ALTER TABLE mapd_frontend_views ADD update_time timestamp");
439  }
440  if (std::find(cols.begin(), cols.end(), std::string("view_metadata")) == cols.end()) {
441  sqliteConnector_.query("ALTER TABLE mapd_frontend_views ADD view_metadata text");
442  }
443  } catch (std::exception& e) {
444  sqliteConnector_.query("ROLLBACK TRANSACTION");
445  throw;
446  }
447  sqliteConnector_.query("END TRANSACTION");
448 }
T getData(const int row, const int col)
SqliteConnector sqliteConnector_
Definition: Catalog.h:720
virtual void query(const std::string &queryString)
const Catalog * getObjForLock()
Definition: Catalog.cpp:260
sqlite_lock< Catalog > cat_sqlite_lock
Definition: Catalog.cpp:126
virtual size_t getNumRows() const

+ Here is the call graph for this function:

+ Here is the caller graph for this function:

void Catalog_Namespace::Catalog::updateFrontendViewsToDashboards ( )
protected

Definition at line 132 of file Catalog.cpp.

References SqliteConnector::getNumRows(), getObjForLock(), SqliteConnector::query(), and sqliteConnector_.

Referenced by CheckAndExecuteMigrations().

132  {
133  cat_sqlite_lock sqlite_lock(getObjForLock());
134  sqliteConnector_.query("BEGIN TRANSACTION");
135  try {
137  "SELECT name FROM sqlite_master WHERE type='table' AND name='mapd_dashboards'");
138  if (sqliteConnector_.getNumRows() != 0) {
139  // already done
140  sqliteConnector_.query("END TRANSACTION");
141  return;
142  }
144  "CREATE TABLE mapd_dashboards (id integer primary key autoincrement, name text , "
145  "userid integer references mapd_users, state text, image_hash text, update_time "
146  "timestamp, "
147  "metadata text, UNIQUE(userid, name) )");
148  // now copy content from old table to new table
150  "insert into mapd_dashboards (id, name , "
151  "userid, state, image_hash, update_time , "
152  "metadata) "
153  "SELECT viewid , name , userid, view_state, image_hash, update_time, "
154  "view_metadata "
155  "from mapd_frontend_views");
156  } catch (const std::exception& e) {
157  sqliteConnector_.query("ROLLBACK TRANSACTION");
158  throw;
159  }
160  sqliteConnector_.query("END TRANSACTION");
161 }
SqliteConnector sqliteConnector_
Definition: Catalog.h:720
virtual void query(const std::string &queryString)
const Catalog * getObjForLock()
Definition: Catalog.cpp:260
sqlite_lock< Catalog > cat_sqlite_lock
Definition: Catalog.cpp:126
virtual size_t getNumRows() const

+ Here is the call graph for this function:

+ Here is the caller graph for this function:

void Catalog_Namespace::Catalog::updateFsiSchemas ( )
protected

Definition at line 695 of file Catalog.cpp.

References getForeignServerSchema(), getForeignTableSchema(), getObjForLock(), SqliteConnector::query(), and sqliteConnector_.

Referenced by CheckAndExecuteMigrations().

695  {
696  cat_sqlite_lock sqlite_lock(getObjForLock());
697  sqliteConnector_.query("BEGIN TRANSACTION");
698  try {
701  } catch (std::exception& e) {
702  sqliteConnector_.query("ROLLBACK TRANSACTION");
703  throw;
704  }
705  sqliteConnector_.query("END TRANSACTION");
706 }
SqliteConnector sqliteConnector_
Definition: Catalog.h:720
virtual void query(const std::string &queryString)
static const std::string getForeignTableSchema(bool if_not_exists=false)
Definition: Catalog.cpp:785
static const std::string getForeignServerSchema(bool if_not_exists=false)
Definition: Catalog.cpp:778
const Catalog * getObjForLock()
Definition: Catalog.cpp:260
sqlite_lock< Catalog > cat_sqlite_lock
Definition: Catalog.cpp:126

+ Here is the call graph for this function:

+ Here is the caller graph for this function:

void Catalog_Namespace::Catalog::updateGeoColumns ( )
protected

Definition at line 373 of file Catalog.cpp.

References SqliteConnector::getNumRows(), getObjForLock(), logger::INFO, kLINESTRING, kMULTILINESTRING, kMULTIPOINT, kMULTIPOLYGON, kPOINT, kPOLYGON, LOG, MAPD_VERSION, SqliteConnector::query(), SqliteConnector::query_with_text_params(), sqliteConnector_, and to_string().

Referenced by CheckAndExecuteMigrations().

373  {
374  cat_sqlite_lock sqlite_lock(getObjForLock());
375  sqliteConnector_.query("BEGIN TRANSACTION");
376  try {
378  "select name from sqlite_master WHERE type='table' AND "
379  "name='mapd_version_history'");
380  if (sqliteConnector_.getNumRows() == 0) {
382  "CREATE TABLE mapd_version_history(version integer, migration_history text "
383  "unique)");
384  } else {
386  "select * from mapd_version_history where migration_history = "
387  "'notnull_geo_columns'");
388  if (sqliteConnector_.getNumRows() != 0) {
389  // legacy geo columns had migrated
390  // no need for further execution
391  sqliteConnector_.query("END TRANSACTION");
392  return;
393  }
394  }
395  // Insert check for migration
397  "INSERT INTO mapd_version_history(version, migration_history) values(?,?)",
398  std::vector<std::string>{std::to_string(MAPD_VERSION), "notnull_geo_columns"});
399  LOG(INFO) << "Updating mapd_columns, legacy geo columns";
400  // Upating all geo columns
401  string queryString(
402  "UPDATE mapd_columns SET is_notnull=1 WHERE coltype=" + std::to_string(kPOINT) +
403  " OR coltype=" + std::to_string(kMULTIPOINT) + " OR coltype=" +
405  " OR coltype=" + std::to_string(kPOLYGON) +
406  " OR coltype=" + std::to_string(kMULTIPOLYGON) + ";");
407  sqliteConnector_.query(queryString);
408  } catch (std::exception& e) {
409  sqliteConnector_.query("ROLLBACK TRANSACTION");
410  throw;
411  }
412  sqliteConnector_.query("END TRANSACTION");
413 }
virtual void query_with_text_params(std::string const &query_only)
#define LOG(tag)
Definition: Logger.h:285
SqliteConnector sqliteConnector_
Definition: Catalog.h:720
virtual void query(const std::string &queryString)
std::string to_string(char const *&&v)
static const int32_t MAPD_VERSION
Definition: release.h:32
const Catalog * getObjForLock()
Definition: Catalog.cpp:260
sqlite_lock< Catalog > cat_sqlite_lock
Definition: Catalog.cpp:126
virtual size_t getNumRows() const

+ Here is the call graph for this function:

+ Here is the caller graph for this function:

void Catalog_Namespace::Catalog::updateInColumnMap ( ColumnDescriptor cd,
ColumnDescriptor old_cd 
)
private

Definition at line 6983 of file Catalog.cpp.

References ColumnDescriptor::columnId, ColumnDescriptor::columnName, ColumnDescriptor::columnType, Catalog_Namespace::anonymous_namespace{Catalog.cpp}::get_checked_table_name(), shared::get_from_map(), SQLTypeInfo::is_dict_encoded_type(), ColumnDescriptor::tableId, and to_upper().

6983  {
6985  ColumnKey{cd->tableId, to_upper(cd->columnName)}) = cd;
6987  cd;
6988  auto dict_it = dict_columns_by_table_id_.find(cd->tableId);
6989  if (dict_it != dict_columns_by_table_id_.end()) {
6990  auto& set = dict_it->second;
6991  for (auto it = set.begin(); it != set.end(); ++it) {
6992  if ((*it)->columnId == cd->columnId) {
6993  set.erase(it);
6994  break;
6995  }
6996  }
6997  }
6998  if (cd->columnType.is_dict_encoded_type()) {
6999  dict_columns_by_table_id_[cd->tableId].emplace(cd);
7000  }
7001 
7002  removeColumnDescriptor(old_cd);
7003  addColumnDescriptor(cd);
7004  calciteMgr_->updateMetadata(currentDB_.dbName, get_checked_table_name(this, cd));
7005 }
TableDictColumnsMap dict_columns_by_table_id_
Definition: Catalog.h:718
std::tuple< int, std::string > ColumnKey
Definition: Types.h:37
ColumnDescriptorMap columnDescriptorMap_
Definition: Catalog.h:709
const DBMetadata currentDB_
Definition: Catalog.h:721
ColumnDescriptorMapById columnDescriptorMapById_
Definition: Catalog.h:710
void removeColumnDescriptor(const ColumnDescriptor *cd)
Definition: Catalog.cpp:2696
bool is_dict_encoded_type() const
Definition: sqltypes.h:655
std::string get_checked_table_name(const Catalog *catalog, const ColumnDescriptor *cd)
Definition: Catalog.cpp:6976
std::string to_upper(const std::string &str)
std::shared_ptr< Calcite > calciteMgr_
Definition: Catalog.h:725
V & get_from_map(std::map< K, V, comp > &map, const K &key)
Definition: misc.h:62
void addColumnDescriptor(const ColumnDescriptor *cd)
Definition: Catalog.cpp:2711
SQLTypeInfo columnType
std::string columnName
std::tuple< int, int > ColumnIdKey
Definition: Types.h:39

+ Here is the call graph for this function:

void Catalog_Namespace::Catalog::updateLeaf ( const LeafHostInfo string_dict_host)
void Catalog_Namespace::Catalog::updateLinkSchema ( )
protected

Definition at line 450 of file Catalog.cpp.

References SqliteConnector::getData(), SqliteConnector::getNumRows(), getObjForLock(), SqliteConnector::query(), and sqliteConnector_.

Referenced by CheckAndExecuteMigrations().

450  {
451  cat_sqlite_lock sqlite_lock(getObjForLock());
452  sqliteConnector_.query("BEGIN TRANSACTION");
453  try {
455  "CREATE TABLE IF NOT EXISTS mapd_links (linkid integer primary key, userid "
456  "integer references mapd_users, "
457  "link text unique, view_state text, update_time timestamp, view_metadata text)");
458  sqliteConnector_.query("PRAGMA TABLE_INFO(mapd_links)");
459  std::vector<std::string> cols;
460  for (size_t i = 0; i < sqliteConnector_.getNumRows(); i++) {
461  cols.push_back(sqliteConnector_.getData<std::string>(i, 1));
462  }
463  if (std::find(cols.begin(), cols.end(), std::string("view_metadata")) == cols.end()) {
464  sqliteConnector_.query("ALTER TABLE mapd_links ADD view_metadata text");
465  }
466  } catch (const std::exception& e) {
467  sqliteConnector_.query("ROLLBACK TRANSACTION");
468  throw;
469  }
470  sqliteConnector_.query("END TRANSACTION");
471 }
T getData(const int row, const int col)
SqliteConnector sqliteConnector_
Definition: Catalog.h:720
virtual void query(const std::string &queryString)
const Catalog * getObjForLock()
Definition: Catalog.cpp:260
sqlite_lock< Catalog > cat_sqlite_lock
Definition: Catalog.cpp:126
virtual size_t getNumRows() const

+ Here is the call graph for this function:

+ Here is the caller graph for this function:

void Catalog_Namespace::Catalog::updateLogicalToPhysicalTableLinkSchema ( )
protected

Definition at line 634 of file Catalog.cpp.

References getObjForLock(), SqliteConnector::query(), and sqliteConnector_.

Referenced by CheckAndExecuteMigrations().

634  {
635  cat_sqlite_lock sqlite_lock(getObjForLock());
636  sqliteConnector_.query("BEGIN TRANSACTION");
637  try {
639  "CREATE TABLE IF NOT EXISTS mapd_logical_to_physical("
640  "logical_table_id integer, physical_table_id integer)");
641  } catch (const std::exception& e) {
642  sqliteConnector_.query("ROLLBACK TRANSACTION");
643  throw;
644  }
645  sqliteConnector_.query("END TRANSACTION");
646 }
SqliteConnector sqliteConnector_
Definition: Catalog.h:720
virtual void query(const std::string &queryString)
const Catalog * getObjForLock()
Definition: Catalog.cpp:260
sqlite_lock< Catalog > cat_sqlite_lock
Definition: Catalog.cpp:126

+ Here is the call graph for this function:

+ Here is the caller graph for this function:

void Catalog_Namespace::Catalog::updateLogicalToPhysicalTableMap ( const int32_t  logical_tb_id)
protected

Definition at line 648 of file Catalog.cpp.

References CHECK, getObjForLock(), logicalToPhysicalTableMapById_, SqliteConnector::query(), SqliteConnector::query_with_text_params(), sqliteConnector_, and to_string().

648  {
649  /* this proc inserts/updates all pairs of (logical_tb_id, physical_tb_id) in
650  * sqlite mapd_logical_to_physical table for given logical_tb_id as needed
651  */
652 
653  cat_sqlite_lock sqlite_lock(getObjForLock());
654  sqliteConnector_.query("BEGIN TRANSACTION");
655  try {
656  const auto physicalTableIt = logicalToPhysicalTableMapById_.find(logical_tb_id);
657  if (physicalTableIt != logicalToPhysicalTableMapById_.end()) {
658  const auto physicalTables = physicalTableIt->second;
659  CHECK(!physicalTables.empty());
660  for (size_t i = 0; i < physicalTables.size(); i++) {
661  int32_t physical_tb_id = physicalTables[i];
663  "INSERT OR REPLACE INTO mapd_logical_to_physical (logical_table_id, "
664  "physical_table_id) VALUES (?1, ?2)",
665  std::vector<std::string>{std::to_string(logical_tb_id),
666  std::to_string(physical_tb_id)});
667  }
668  }
669  } catch (std::exception& e) {
670  sqliteConnector_.query("ROLLBACK TRANSACTION");
671  throw;
672  }
673  sqliteConnector_.query("END TRANSACTION");
674 }
virtual void query_with_text_params(std::string const &query_only)
SqliteConnector sqliteConnector_
Definition: Catalog.h:720
virtual void query(const std::string &queryString)
std::string to_string(char const *&&v)
const Catalog * getObjForLock()
Definition: Catalog.cpp:260
#define CHECK(condition)
Definition: Logger.h:291
sqlite_lock< Catalog > cat_sqlite_lock
Definition: Catalog.cpp:126
LogicalToPhysicalTableMapById logicalToPhysicalTableMapById_
Definition: Catalog.h:727

+ Here is the call graph for this function:

void Catalog_Namespace::Catalog::updatePageSize ( )
protected

Definition at line 501 of file Catalog.cpp.

References currentDB_, Catalog_Namespace::DBMetadata::dbName, Catalog_Namespace::DEFAULT_INITIAL_VERSION, SqliteConnector::getData(), SqliteConnector::getNumRows(), getObjForLock(), logger::INFO, LOG, SqliteConnector::query(), sqliteConnector_, and to_string().

Referenced by CheckAndExecuteMigrations().

501  {
502  cat_sqlite_lock sqlite_lock(getObjForLock());
503  if (currentDB_.dbName.length() == 0) {
504  // updateDictionaryNames dbName length is zero nothing to do here
505  return;
506  }
507  sqliteConnector_.query("BEGIN TRANSACTION");
508  try {
509  sqliteConnector_.query("PRAGMA TABLE_INFO(mapd_tables)");
510  std::vector<std::string> cols;
511  for (size_t i = 0; i < sqliteConnector_.getNumRows(); i++) {
512  cols.push_back(sqliteConnector_.getData<std::string>(i, 1));
513  }
514  if (std::find(cols.begin(), cols.end(), std::string("version_num")) == cols.end()) {
515  LOG(INFO) << "Updating mapd_tables updatePageSize";
516  // No version number
517  // need to update the defaul tpagesize to old correct value
518  sqliteConnector_.query("UPDATE mapd_tables SET frag_page_size = 2097152 ");
519  // need to add new version info
520  string queryString("ALTER TABLE mapd_tables ADD version_num BIGINT DEFAULT " +
522  sqliteConnector_.query(queryString);
523  }
524  } catch (std::exception& e) {
525  sqliteConnector_.query("ROLLBACK TRANSACTION");
526  throw;
527  }
528  sqliteConnector_.query("END TRANSACTION");
529 }
T getData(const int row, const int col)
#define LOG(tag)
Definition: Logger.h:285
SqliteConnector sqliteConnector_
Definition: Catalog.h:720
const DBMetadata currentDB_
Definition: Catalog.h:721
virtual void query(const std::string &queryString)
std::string to_string(char const *&&v)
const int DEFAULT_INITIAL_VERSION
Definition: Catalog.cpp:113
const Catalog * getObjForLock()
Definition: Catalog.cpp:260
sqlite_lock< Catalog > cat_sqlite_lock
Definition: Catalog.cpp:126
virtual size_t getNumRows() const

+ Here is the call graph for this function:

+ Here is the caller graph for this function:

void Catalog_Namespace::Catalog::updateTableDescriptorSchema ( )
protected

Definition at line 268 of file Catalog.cpp.

References DEFAULT_MAX_CHUNK_SIZE, SqliteConnector::getData(), SqliteConnector::getNumRows(), getObjForLock(), shared::kRootUserId, SqliteConnector::query(), sqliteConnector_, and to_string().

Referenced by CheckAndExecuteMigrations().

268  {
269  cat_sqlite_lock sqlite_lock(getObjForLock());
270  sqliteConnector_.query("BEGIN TRANSACTION");
271  try {
272  sqliteConnector_.query("PRAGMA TABLE_INFO(mapd_tables)");
273  std::vector<std::string> cols;
274  for (size_t i = 0; i < sqliteConnector_.getNumRows(); i++) {
275  cols.push_back(sqliteConnector_.getData<std::string>(i, 1));
276  }
277  if (std::find(cols.begin(), cols.end(), std::string("max_chunk_size")) ==
278  cols.end()) {
279  string queryString("ALTER TABLE mapd_tables ADD max_chunk_size BIGINT DEFAULT " +
281  sqliteConnector_.query(queryString);
282  }
283  if (std::find(cols.begin(), cols.end(), std::string("shard_column_id")) ==
284  cols.end()) {
285  string queryString("ALTER TABLE mapd_tables ADD shard_column_id BIGINT DEFAULT " +
286  std::to_string(0));
287  sqliteConnector_.query(queryString);
288  }
289  if (std::find(cols.begin(), cols.end(), std::string("shard")) == cols.end()) {
290  string queryString("ALTER TABLE mapd_tables ADD shard BIGINT DEFAULT " +
291  std::to_string(-1));
292  sqliteConnector_.query(queryString);
293  }
294  if (std::find(cols.begin(), cols.end(), std::string("num_shards")) == cols.end()) {
295  string queryString("ALTER TABLE mapd_tables ADD num_shards BIGINT DEFAULT " +
296  std::to_string(0));
297  sqliteConnector_.query(queryString);
298  }
299  if (std::find(cols.begin(), cols.end(), std::string("key_metainfo")) == cols.end()) {
300  string queryString("ALTER TABLE mapd_tables ADD key_metainfo TEXT DEFAULT '[]'");
301  sqliteConnector_.query(queryString);
302  }
303  if (std::find(cols.begin(), cols.end(), std::string("userid")) == cols.end()) {
304  string queryString("ALTER TABLE mapd_tables ADD userid integer DEFAULT " +
306  sqliteConnector_.query(queryString);
307  }
308  if (std::find(cols.begin(), cols.end(), std::string("sort_column_id")) ==
309  cols.end()) {
311  "ALTER TABLE mapd_tables ADD sort_column_id INTEGER DEFAULT 0");
312  }
313  if (std::find(cols.begin(), cols.end(), std::string("storage_type")) == cols.end()) {
314  string queryString("ALTER TABLE mapd_tables ADD storage_type TEXT DEFAULT ''");
315  sqliteConnector_.query(queryString);
316  }
317  if (std::find(cols.begin(), cols.end(), std::string("max_rollback_epochs")) ==
318  cols.end()) {
319  string queryString("ALTER TABLE mapd_tables ADD max_rollback_epochs INT DEFAULT " +
320  std::to_string(-1));
321  sqliteConnector_.query(queryString);
322  }
323  if (std::find(cols.begin(), cols.end(), std::string("is_system_table")) ==
324  cols.end()) {
325  string queryString("ALTER TABLE mapd_tables ADD is_system_table BOOLEAN DEFAULT 0");
326  sqliteConnector_.query(queryString);
327  }
328  } catch (std::exception& e) {
329  sqliteConnector_.query("ROLLBACK TRANSACTION");
330  throw;
331  }
332  sqliteConnector_.query("END TRANSACTION");
333 }
const int kRootUserId
T getData(const int row, const int col)
SqliteConnector sqliteConnector_
Definition: Catalog.h:720
#define DEFAULT_MAX_CHUNK_SIZE
virtual void query(const std::string &queryString)
std::string to_string(char const *&&v)
const Catalog * getObjForLock()
Definition: Catalog.cpp:260
sqlite_lock< Catalog > cat_sqlite_lock
Definition: Catalog.cpp:126
virtual size_t getNumRows() const

+ Here is the call graph for this function:

+ Here is the caller graph for this function:

void Catalog_Namespace::Catalog::updateViewsInMapUnlocked ( )
private

Definition at line 1408 of file Catalog.cpp.

1408  {
1409  std::string viewQuery("SELECT tableid, sql FROM mapd_views");
1410  sqliteConnector_.query(viewQuery);
1411  auto numRows = sqliteConnector_.getNumRows();
1412  for (size_t r = 0; r < numRows; ++r) {
1413  auto tableId = sqliteConnector_.getData<int>(r, 0);
1414  auto td = tableDescriptorMapById_[tableId];
1415  td->viewSQL = sqliteConnector_.getData<string>(r, 1);
1416  td->fragmenter = nullptr;
1417  }
1418 }
T getData(const int row, const int col)
SqliteConnector sqliteConnector_
Definition: Catalog.h:720
virtual void query(const std::string &queryString)
TableDescriptorMapById tableDescriptorMapById_
Definition: Catalog.h:708
virtual size_t getNumRows() const
void Catalog_Namespace::Catalog::updateViewUnlocked ( TableDescriptor td)
private

Definition at line 1398 of file Catalog.cpp.

References CHECK_EQ, TableDescriptor::tableId, TableDescriptor::tableName, to_string(), and TableDescriptor::viewSQL.

1398  {
1399  std::string viewQuery("SELECT sql FROM mapd_views where tableid = " +
1400  std::to_string(td.tableId));
1401  sqliteConnector_.query(viewQuery);
1402  auto num_rows = sqliteConnector_.getNumRows();
1403  CHECK_EQ(num_rows, 1U) << "Expected single entry in mapd_views for view '"
1404  << td.tableName << "', instead got " << num_rows;
1405  td.viewSQL = sqliteConnector_.getData<string>(0, 0);
1406 }
#define CHECK_EQ(x, y)
Definition: Logger.h:301
T getData(const int row, const int col)
std::string tableName
SqliteConnector sqliteConnector_
Definition: Catalog.h:720
virtual void query(const std::string &queryString)
std::string to_string(char const *&&v)
std::string viewSQL
virtual size_t getNumRows() const

+ Here is the call graph for this function:

bool Catalog_Namespace::Catalog::validateNonExistentTableOrView ( const std::string &  name,
const bool  if_not_exists 
)

Validates that a table or view with given name does not already exist. An exception is thrown if a table or view with given name already exists and "if_not_exists" is false.

Parameters
name- Name of table or view whose existence is checked
if_not_exists- flag indicating whether or not existence of a table or view with given name is an exception
Returns
true if table or view with name does not exist. Otherwise, return false

Definition at line 5782 of file Catalog.cpp.

5783  {
5784  if (getMetadataForTable(name, false)) {
5785  if (if_not_exists) {
5786  return false;
5787  }
5788  throw std::runtime_error("Table or View with name \"" + name + "\" already exists.");
5789  }
5790  return true;
5791 }
std::string name() const
Definition: Catalog.h:348
const TableDescriptor * getMetadataForTable(const std::string &tableName, const bool populateFragmenter=true) const
Returns a pointer to a const TableDescriptor struct matching the provided tableName.

Friends And Related Function Documentation

template<class T >
friend class lockmgr::TableLockMgrImpl
friend

Definition at line 750 of file Catalog.h.

Member Data Documentation

std::string Catalog_Namespace::Catalog::basePath_
protected

Definition at line 706 of file Catalog.h.

Referenced by getCatalogBasePath(), and ~Catalog().

std::shared_ptr<Calcite> Catalog_Namespace::Catalog::calciteMgr_
protected

Definition at line 725 of file Catalog.h.

Referenced by getCalciteMgr(), and setCalciteMgr().

constexpr const char* Catalog_Namespace::Catalog::CATALOG_SERVER_NAME {"system_catalog_server"}
staticprivate

Definition at line 892 of file Catalog.h.

ColumnDescriptorMap Catalog_Namespace::Catalog::columnDescriptorMap_
protected

Definition at line 709 of file Catalog.h.

Referenced by ~Catalog().

ColumnDescriptorMapById Catalog_Namespace::Catalog::columnDescriptorMapById_
protected

Definition at line 710 of file Catalog.h.

Referenced by reloadTableMetadataUnlocked().

ColumnDescriptorsForRoll Catalog_Namespace::Catalog::columnDescriptorsForRoll
protected

Definition at line 739 of file Catalog.h.

CustomExpressionMapById Catalog_Namespace::Catalog::custom_expr_map_by_id_
protected

Definition at line 717 of file Catalog.h.

DashboardDescriptorMap Catalog_Namespace::Catalog::dashboardDescriptorMap_
protected

Definition at line 712 of file Catalog.h.

std::shared_ptr<Data_Namespace::DataMgr> Catalog_Namespace::Catalog::dataMgr_
protected

Definition at line 722 of file Catalog.h.

Referenced by getDataMgr(), and reloadTableMetadataUnlocked().

std::unique_ptr<heavyai::DistributedSharedMutex> Catalog_Namespace::Catalog::dcatalogMutex_
mutable

Definition at line 906 of file Catalog.h.

DeletedColumnPerTableMap Catalog_Namespace::Catalog::deletedColumnPerTable_
private

Definition at line 774 of file Catalog.h.

Referenced by reloadTableMetadataUnlocked().

TableDictColumnsMap Catalog_Namespace::Catalog::dict_columns_by_table_id_
protected

Definition at line 718 of file Catalog.h.

DictDescriptorMapById Catalog_Namespace::Catalog::dictDescriptorMapByRef_
protected

Definition at line 711 of file Catalog.h.

Referenced by buildDictionaryMapUnlocked().

std::unique_ptr<heavyai::DistributedSharedMutex> Catalog_Namespace::Catalog::dsqliteMutex_
mutable

Definition at line 907 of file Catalog.h.

constexpr const char* Catalog_Namespace::Catalog::EXECUTOR_STATS_SERVER_NAME {"system_executor_stats_server"}
staticprivate

Definition at line 895 of file Catalog.h.

ForeignServerMap Catalog_Namespace::Catalog::foreignServerMap_
protected

Definition at line 715 of file Catalog.h.

ForeignServerMapById Catalog_Namespace::Catalog::foreignServerMapById_
protected

Definition at line 716 of file Catalog.h.

bool Catalog_Namespace::Catalog::initialized_ = false

Definition at line 914 of file Catalog.h.

Referenced by getObjForLock().

constexpr std::array<const char*, 6> Catalog_Namespace::Catalog::INTERNAL_SERVERS
staticprivate
LinkDescriptorMap Catalog_Namespace::Catalog::linkDescriptorMap_
protected

Definition at line 713 of file Catalog.h.

LinkDescriptorMapById Catalog_Namespace::Catalog::linkDescriptorMapById_
protected

Definition at line 714 of file Catalog.h.

LogicalToPhysicalTableMapById Catalog_Namespace::Catalog::logicalToPhysicalTableMapById_
protected

Definition at line 727 of file Catalog.h.

Referenced by updateLogicalToPhysicalTableMap().

constexpr const char* Catalog_Namespace::Catalog::LOGS_SERVER_NAME {"system_logs_server"}
staticprivate

Definition at line 897 of file Catalog.h.

constexpr const char* Catalog_Namespace::Catalog::MEMORY_STATS_SERVER_NAME {"system_memory_stats_server"}
staticprivate

Definition at line 893 of file Catalog.h.

constexpr const char* Catalog_Namespace::Catalog::ML_METADATA_SERVER_NAME {"ml_metadata_server"}
staticprivate

Definition at line 896 of file Catalog.h.

int Catalog_Namespace::Catalog::nextTempDictId_
protected

Definition at line 731 of file Catalog.h.

int Catalog_Namespace::Catalog::nextTempTableId_
protected

Definition at line 730 of file Catalog.h.

const std::string Catalog_Namespace::Catalog::physicalTableNameTag_
staticprotected

Definition at line 729 of file Catalog.h.

heavyai::shared_mutex Catalog_Namespace::Catalog::sharedMutex_
mutable

Definition at line 909 of file Catalog.h.

std::mutex Catalog_Namespace::Catalog::sqliteMutex_
mutable

Definition at line 908 of file Catalog.h.

constexpr const char* Catalog_Namespace::Catalog::STORAGE_STATS_SERVER_NAME {"system_storage_stats_server"}
staticprivate

Definition at line 894 of file Catalog.h.

const std::vector<LeafHostInfo> Catalog_Namespace::Catalog::string_dict_hosts_
protected

Definition at line 724 of file Catalog.h.

TableDescriptorMap Catalog_Namespace::Catalog::tableDescriptorMap_
protected

Definition at line 707 of file Catalog.h.

Referenced by reloadTableMetadataUnlocked(), and ~Catalog().

TableDescriptorMapById Catalog_Namespace::Catalog::tableDescriptorMapById_
protected
std::atomic<std::thread::id> Catalog_Namespace::Catalog::thread_holding_sqlite_lock
mutable

Definition at line 910 of file Catalog.h.

std::atomic<std::thread::id> Catalog_Namespace::Catalog::thread_holding_write_lock
mutable

Definition at line 911 of file Catalog.h.

thread_local bool Catalog_Namespace::Catalog::thread_holds_read_lock = false
static

Definition at line 913 of file Catalog.h.


The documentation for this class was generated from the following files: