//--------------------------------------------------------------------------- bool TServerModeDemoDataDM::TableExists() { String ASQL; ASQL = "IF DB_ID(N'" + GetDatabaseName() + "') IS NOT NULL AND OBJECT_ID(N'" + GetDatabaseName() + ".dbo." + GetTableName() + "') IS NOT NULL" + sLineBreak + " SELECT 1;" + sLineBreak + "ELSE" + sLineBreak + " SELECT -1;"; ADQuery->Active = False; ADQuery->Open(ASQL); if ((!ADQuery->Eof)&&(ADQuery->Fields->Fields[0]->AsInteger == 1)) return true; else return false; }
// FIXME: Should remove when the simple_optimizer tears down // Initializes the update plan without adding any child nodes and // retrieves column ids for the child scan plan. void UpdatePlan::BuildInitialUpdatePlan( const parser::UpdateStatement *parse_tree, std::vector<oid_t> &column_ids) { LOG_TRACE("Creating an Update Plan"); auto t_ref = parse_tree->table; auto table_name = std::string(t_ref->GetTableName()); auto database_name = t_ref->GetDatabaseName(); LOG_TRACE("Update database %s table %s", database_name, table_name.c_str()); target_table_ = catalog::Catalog::GetInstance()->GetTableWithName( database_name, table_name); PL_ASSERT(target_table_ != nullptr); for (auto update_clause : *parse_tree->updates) { updates_.push_back(update_clause->Copy()); } TargetList tlist; DirectMapList dmlist; oid_t col_id; auto schema = target_table_->GetSchema(); for (auto update : updates_) { // get oid_t of the column and push it to the vector; col_id = schema->GetColumnID(std::string(update->column)); column_ids.push_back(col_id); auto *update_expr = update->value->Copy(); expression::ExpressionUtil::TransformExpression(target_table_->GetSchema(), update_expr); planner::DerivedAttribute attribute{update_expr}; attribute.attribute_info.name = update->column; tlist.emplace_back(col_id, attribute); } auto &schema_columns = schema->GetColumns(); for (uint i = 0; i < schema_columns.size(); i++) { bool is_in_target_list = false; for (auto col_id : column_ids) { if (schema_columns[i].column_name == schema_columns[col_id].column_name) { is_in_target_list = true; break; } } if (is_in_target_list == false) dmlist.emplace_back(i, std::pair<oid_t, oid_t>(0, i)); } std::unique_ptr<const planner::ProjectInfo> project_info( new planner::ProjectInfo(std::move(tlist), std::move(dmlist))); project_info_ = std::move(project_info); if (parse_tree->where != nullptr) where_ = parse_tree->where->Copy(); else where_ = nullptr; expression::ExpressionUtil::TransformExpression(target_table_->GetSchema(), where_); }
void DatabaseWorkerPool<T>::Close() { TC_LOG_INFO("sql.driver", "Closing down DatabasePool '%s'.", GetDatabaseName()); //! Closes the actualy MySQL connection. _connections[IDX_ASYNC].clear(); TC_LOG_INFO("sql.driver", "Asynchronous connections on DatabasePool '%s' terminated. " "Proceeding with synchronous connections.", GetDatabaseName()); //! Shut down the synchronous connections //! There's no need for locking the connection, because DatabaseWorkerPool<>::Close //! should only be called after any other thread tasks in the core have exited, //! meaning there can be no concurrent access at this point. _connections[IDX_SYNCH].clear(); TC_LOG_INFO("sql.driver", "All connections on DatabasePool '%s' closed.", GetDatabaseName()); }
//--------------------------------------------------------------------------- int TServerModeDemoDataDM::GetRecordsCount() { ADQuery->Active = false; String ASQL = "IF DB_ID(N\'%s\') IS NOT NULL AND OBJECT_ID(N\'%0:s.dbo.%1:s\') IS NOT NULL SELECT COUNT(*) FROM %0:s.dbo.%1:s; ELSE SELECT 0;"; TVarRec args[2] = {GetDatabaseName(), GetTableName()}; ADQuery->Open(Format(ASQL, args, 2)); if (!ADQuery->Eof) return ADQuery->Fields->Fields[0]->AsInteger; else return 0; }
uint32 DatabaseWorkerPool<T>::Open() { WPFatal(_connectionInfo.get(), "Connection info was not set!"); TC_LOG_INFO("sql.driver", "Opening DatabasePool '%s'. " "Asynchronous connections: %u, synchronous connections: %u.", GetDatabaseName(), _async_threads, _synch_threads); uint32 error = OpenConnections(IDX_ASYNC, _async_threads); if (error) return error; error = OpenConnections(IDX_SYNCH, _synch_threads); if (!error) { TC_LOG_INFO("sql.driver", "DatabasePool '%s' opened successfully. " SZFMTD " total connections running.", GetDatabaseName(), (_connections[IDX_SYNCH].size() + _connections[IDX_ASYNC].size())); } return error; }
//--------------------------------------------------------------------------- void TServerModeDemoDataDM::CreateTable() { String ASQL; ASQL = "IF OBJECT_ID(N\'" + GetDatabaseName() + ".dbo." + GetTableName() + "\') IS NULL" + sLineBreak + "CREATE TABLE \"dbo\".\"" + GetTableName() + "\"(" + " \"OID\" int IDENTITY(1,1) NOT NULL, \"Subject\" nvarchar(100) NULL," + "\"From\" nvarchar(100) NULL," + " \"Sent\" datetime NULL," + " \"Size\" bigint NULL," + " \"HasAttachment\" bit NULL," + " \"Priority\" int NULL," + " CONSTRAINT \"PK_' + ATableName + '\" PRIMARY KEY CLUSTERED" + "(" + " \"OID\" ASC" + ")WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON \"PRIMARY\"" + ") ON \"PRIMARY\";"; ExecSQL(ASQL); ExecSQL("CREATE NONCLUSTERED INDEX iSubject_ServerModeGridTableDemo ON \"ServerModeGridTableDemo\" (\"Subject\");"); ExecSQL("CREATE NONCLUSTERED INDEX iFrom_ServerModeGridTableDemo ON \"ServerModeGridTableDemo\" (\"From\");"); ExecSQL("CREATE NONCLUSTERED INDEX iSent_ServerModeGridTableDemo ON \"ServerModeGridTableDemo\" (\"Sent\");"); ExecSQL("CREATE NONCLUSTERED INDEX iSize_ServerModeGridTableDemo ON \"ServerModeGridTableDemo\" (\"Size\");"); ExecSQL("CREATE NONCLUSTERED INDEX iHasAttachment_ServerModeGridTableDemo ON \"ServerModeGridTableDemo\" (\"HasAttachment\");"); ExecSQL("CREATE NONCLUSTERED INDEX iPriority_ServerModeGridTableDemo ON \"ServerModeGridTableDemo\" (\"Priority\");"); }
/* -------------------------------- * InitMyDatabaseId() -- Find and record the OID of the database we are * to open. * * The database's oid forms half of the unique key for the system * caches and lock tables. We therefore want it initialized before * we open any relations, since opening relations puts things in the * cache. To get around this problem, this code opens and scans the * pg_database relation by hand. * * This algorithm relies on the fact that first attribute in the * pg_database relation schema is the database name. It also knows * about the internal format of tuples on disk and the length of * the datname attribute. It knows the location of the pg_database * file. * * This code is called from InitDatabase(), after we chdir() to the * database directory but before we open any relations. * -------------------------------- */ void InitMyDatabaseId() { int dbfd; int fileflags; int nbytes; int max, i; HeapTuple tup; Page pg; PageHeader ph; char *dbfname; Form_pg_database tup_db; /* * At bootstrap time, we don't need to check the oid of the database * in use, since we're not using shared memory. This is lucky, since * the database may not be in the tables yet. */ if (IsBootstrapProcessingMode()) { LockDisable(true); return; } dbfname = (char *) palloc(strlen(DataDir) + strlen("pg_database") + 2); sprintf(dbfname, "%s%cpg_database", DataDir, SEP_CHAR); fileflags = O_RDONLY; #ifdef WIN32 fileflags |= _O_BINARY; #endif /* WIN32 */ if ((dbfd = open(dbfname, O_RDONLY, 0666)) < 0) elog(FATAL, "Cannot open %s", dbfname); pfree(dbfname); /* ---------------- * read and examine every page in pg_database * * Raw I/O! Read those tuples the hard way! Yow! * * Why don't we use the access methods or move this code * someplace else? This is really pg_database schema dependent * code. Perhaps it should go in lib/catalog/pg_database? * -cim 10/3/90 * * mao replies 4 apr 91: yeah, maybe this should be moved to * lib/catalog. however, we CANNOT use the access methods since * those use the buffer cache, which uses the relation cache, which * requires that the dbid be set, which is what we're trying to do * here. * ---------------- */ pg = (Page) palloc(BLCKSZ); ph = (PageHeader) pg; while ((nbytes = read(dbfd, pg, BLCKSZ)) == BLCKSZ) { max = PageGetMaxOffsetNumber(pg); /* look at each tuple on the page */ for (i = 0; i <= max; i++) { int offset; /* if it's a freed tuple, ignore it */ if (!(ph->pd_linp[i].lp_flags & LP_USED)) continue; /* get a pointer to the tuple itself */ offset = (int) ph->pd_linp[i].lp_off; tup = (HeapTuple) (((char *) pg) + offset); /* * if the tuple has been deleted (the database was destroyed), * skip this tuple. XXX warning, will robinson: violation of * transaction semantics happens right here. we should check * to be sure that the xact that deleted this tuple actually * committed. only way to do this at init time is to paw over * the log relation by hand, too. let's be optimistic. * * XXX This is an evil type cast. tup->t_xmax is char[5] while * TransactionId is struct * { char data[5] }. It works but * if data is ever moved and no longer the first field this * will be broken!! -mer 11 Nov 1991. */ if (TransactionIdIsValid((TransactionId)tup->t_xmax)) continue; /* * Okay, see if this is the one we want. * XXX 1 july 91: mao and mer discover that tuples now squash * t_bits. Why is this? * * 24 july 92: mer realizes that the t_bits field is only * used in the event of null values. If no * fields are null we reduce the header size * by doing the squash. t_hoff tells you exactly * how big the header actually is. use the PC * means of getting at sys cat attrs. */ tup_db = (Form_pg_database)GETSTRUCT(tup); if (strncmp(GetDatabaseName(), &(tup_db->datname.data[0]), 16) == 0) { MyDatabaseId = tup->t_oid; goto done; } } } done: (void) close(dbfd); pfree(pg); if (!OidIsValid(MyDatabaseId)) elog(FATAL, "Database %s does not exist in %s", GetDatabaseName(), DatabaseRelationName); }
static char * filepath(char *filename) { char *buf; char basename[16]; int len; #ifndef WIN32 if (*filename != Sep_char) { #else if (!(filename[1] == ':' && filename[2] == Sep_char)) { #endif /* WIN32 */ /* Either /base/ or \base\ */ sprintf(basename, "%cbase%c", Sep_char, Sep_char); len = strlen(DataDir) + strlen(basename) + strlen(GetDatabaseName()) + strlen(filename) + 2; buf = (char*) palloc(len); sprintf(buf, "%s%s%s%c%s", DataDir, basename, GetDatabaseName(), Sep_char, filename); } else { buf = (char *) palloc(strlen(filename) + 1); strcpy(buf, filename); } return(buf); } static int FileAccess(File file) { int returnValue; DO_DB(printf("DB: FileAccess %d (%s)\n", file, VfdCache[file].fileName)); /* * Is the file open? If not, close the least recently used, * then open it and stick it at the head of the used ring */ if (FileIsNotOpen(file)) { AssertLruRoom(); returnValue = LruInsert(file); if (returnValue != 0) return returnValue; } else { /* * We now know that the file is open and that it is not the * last one accessed, so we need to more it to the head of * the Lru ring. */ Delete(file); Insert(file); } return (0); }
//--------------------------------------------------------------------------- void TServerModeDemoDataDM::CreateDatabase() { String ASQL = "IF DB_ID(N\'%s\') IS NULL CREATE DATABASE \"%s\";"; TVarRec args[2] = {GetDatabaseName(), GetDatabaseName()}; ExecSQL(Format(ASQL, args, 2)); }