#pragma once #include #include #include "catalog/catalog_entry/rel_group_catalog_entry.h" #include "common/api.h" #include "storage/table/rel_table_data.h" #include "storage/table/table.h" namespace lbug { namespace evaluator { class ExpressionEvaluator; } // namespace evaluator namespace transaction { class Transaction; } namespace storage { class MemoryManager; struct LocalRelTableScanState; // Exported for extensions providing columnar table storage (e.g. the lance extension). struct LBUG_API RelTableScanState : TableScanState { common::RelDataDirection direction; common::sel_t currBoundNodeIdx; Column* csrOffsetColumn; Column* csrLengthColumn; bool randomLookup; // Copy of the input boundNodeIDVector's selection. Native tables sort it by node offset and, // while a multi-group batch is scanned, keep only the current node group's positions in it. common::SelectionVector cachedBoundNodeSelVector; // Per-node-group scan plan for the current batch of bound nodes. When the input is a // node table scan, the bound node IDs form a contiguous sequence within a single node // group. However, when this scan extends from the output of a previous extend (e.g. // planning (a)->(b)->(c) as scan(a) -> extend(a->b) -> extend(b->c)), the bound nodes // are the children of a single parent and can have arbitrary offsets, spanning // multiple node groups. Such batches are scanned one node group at a time: each plan // entry holds a node group, null past the rel table's last one, and the positions (into // nodeIDVector) of the bound nodes that belong to it. Empty when the batch is covered by // a single node group (the common case). std::vector>> boundNodeGroupPlan; // All bound node positions of the current batch. Only populated for multi-group // batches, so cachedBoundNodeSelVector can be restored to the full batch once all node // groups have been scanned (the local/uncommitted scan and downstream resume paths // iterate over the full batch). std::vector allBoundNodePositions; // Reusable workspace for RelTable::initScanState: the batch's bound-node positions // (copied from the input selection vector, then sorted by node offset). Kept on the // scan state so repeated per-morsel inits reuse the buffer instead of allocating. std::vector positionsBuffer; // Multi-parent packed scan support (see docs/multi_parent_lifetime.md). When // packedMultiParentScan is true, the CSR scan may serve children of MULTIPLE bound parents // in a single output batch: the bound node vector's chunk state is set to unflat with its // selection vector holding the served parents, and packedChildOffsets holds the prefix-sum // offsets over those parents (offsets.size() == numServedParents + 1; zero-length ranges // are skipped by consumers). Only the persistent with-cache CSR scan path packs multiple // parents; all other paths keep the one-parent-per-batch contract (bound vector flat with // selSize 1, packedChildOffsets left empty). bool packedMultiParentScan = false; std::vector packedChildOffsets; std::unique_ptr localTableScanState; // Drops what the scan pinned in its current node group (see CSRNodeGroupScanPin), so a // checkpoint that ran meanwhile can free the pages it replaced. Call when the scan is // exhausted. The state can be scanned again: the next initScanState pins afresh. void releaseScanPin(); RelTableScanState(MemoryManager& mm, common::ValueVector* nodeIDVector, std::vector outputVectors, std::shared_ptr outChunkState, bool randomLookup = false); RelTableScanState(common::ValueVector* nodeIDVector, std::vector outputVectors, std::shared_ptr outChunkState); virtual void setToTable(const transaction::Transaction* transaction, Table* table_, std::vector columnIDs_, std::vector columnPredicateSets_, common::RelDataDirection direction_) override; void initState(transaction::Transaction* transaction, NodeGroup* nodeGroup, bool resetCachedBoundNodeIDs = true) override; bool scanNext(transaction::Transaction* transaction) override; // Advance to the next node group of a multi-group bound node batch (see // boundNodeGroupPlan). Returns false if the batch is exhausted. bool startNextBoundNodeGroup(transaction::Transaction* transaction); void setCachedBoundNodeSelVectorToPositions(const std::vector& positions); void setNodeIDVectorToFlat(common::sel_t selPos) const; // The scan leaves the bound chunk flat on the last node it served, and pulling the next tuple // refills that chunk only if the pull reaches its producer. Call this after the batch is // exhausted and before pulling. Each batch is restored at most once. void restoreBoundNodeBatch(); private: bool hasUnCommittedData() const; void initCachedBoundNodeIDSelVector(); void initStateForCommitted(const transaction::Transaction* transaction); void initStateForUncommitted(); }; class LocalRelTable; struct LocalRelTableScanState final : RelTableScanState { LocalRelTable* localRelTable; // TODO(Guodong): Copy of rowIndices here is only to simplify the implementation. We can always // go to the fwdIndex/bwdIndex inside LocalRelTable to find the row indices. We can revisit this // if the copy of rowIndices from fwdIndex/bwdIndex becomes a problem. row_idx_vec_t rowIndices; common::row_idx_t nextRowToScan = 0; LocalRelTableScanState(const RelTableScanState& baseScanState, LocalRelTable* localRelTable, std::vector columnIDs) : RelTableScanState{baseScanState.nodeIDVector, baseScanState.outputVectors, baseScanState.outState}, localRelTable{localRelTable} { this->columnIDs = std::move(columnIDs); this->direction = baseScanState.direction; // Setting source to UNCOMMITTED is not necessary but just to keep it semantically // consistent. this->source = TableScanSource::UNCOMMITTED; this->nodeGroupScanState->chunkStates.resize(this->columnIDs.size()); } }; struct LBUG_API RelTableInsertState : TableInsertState { common::ValueVector& srcNodeIDVector; common::ValueVector& dstNodeIDVector; common::ValueVector& getBoundNodeIDVector(common::RelDataDirection direction) const { return direction == common::RelDataDirection::FWD ? srcNodeIDVector : dstNodeIDVector; } RelTableInsertState(common::ValueVector& srcNodeIDVector, common::ValueVector& dstNodeIDVector, std::vector propertyVectors) : TableInsertState{std::move(propertyVectors)}, srcNodeIDVector{srcNodeIDVector}, dstNodeIDVector{dstNodeIDVector} {} }; struct RelTableUpdateState final : TableUpdateState { common::ValueVector& srcNodeIDVector; common::ValueVector& dstNodeIDVector; common::ValueVector& relIDVector; common::ValueVector& getBoundNodeIDVector(common::RelDataDirection direction) const { return direction == common::RelDataDirection::FWD ? srcNodeIDVector : dstNodeIDVector; } RelTableUpdateState(common::column_id_t columnID, common::ValueVector& srcNodeIDVector, common::ValueVector& dstNodeIDVector, common::ValueVector& relIDVector, common::ValueVector& propertyVector) : TableUpdateState{columnID, propertyVector}, srcNodeIDVector{srcNodeIDVector}, dstNodeIDVector{dstNodeIDVector}, relIDVector{relIDVector} {} }; struct LBUG_API RelTableDeleteState final : TableDeleteState { common::ValueVector& srcNodeIDVector; common::ValueVector& dstNodeIDVector; common::ValueVector& relIDVector; common::RelDataDirection detachDeleteDirection; common::ValueVector& getBoundNodeIDVector(common::RelDataDirection direction) const { return direction == common::RelDataDirection::FWD ? srcNodeIDVector : dstNodeIDVector; } RelTableDeleteState(common::ValueVector& srcNodeIDVector, common::ValueVector& dstNodeIDVector, common::ValueVector& relIDVector, common::RelDataDirection detachDeleteDirection = common::RelDataDirection::FWD) : srcNodeIDVector{srcNodeIDVector}, dstNodeIDVector{dstNodeIDVector}, relIDVector{relIDVector}, detachDeleteDirection{detachDeleteDirection} {} }; struct RelDegreeSummary { common::row_idx_t numActiveBoundNodes = 0; common::row_idx_t totalDegree = 0; common::row_idx_t maxDegree = 0; }; class LBUG_API RelTable : public Table { public: using rel_multiplicity_constraint_throw_func_t = std::function; RelTable(catalog::RelGroupCatalogEntry* relGroupEntry, common::table_id_t fromTableID, common::table_id_t toTableID, const StorageManager* storageManager, MemoryManager* memoryManager); common::table_id_t getFromNodeTableID() const { return fromNodeTableID; } common::table_id_t getToNodeTableID() const { return toNodeTableID; } void initScanState(transaction::Transaction* transaction, TableScanState& scanState, bool resetCachedBoundNodeSelVec = true) const override; bool scanInternal(transaction::Transaction* transaction, TableScanState& scanState) override; void initInsertState(main::ClientContext*, TableInsertState&) override { // DO NOTHING. } void insert(transaction::Transaction* transaction, TableInsertState& insertState) override; void update(transaction::Transaction* transaction, TableUpdateState& updateState) override; bool delete_(transaction::Transaction* transaction, TableDeleteState& deleteState) override; // Deletes all edges attached to the node(s) specified in the deleteState // Currently only supports deleting from a single src node // Note that since the rel table doesn't store nodes this doesn't delete the node itself void detachDelete(transaction::Transaction* transaction, RelTableDeleteState* deleteState); void detachDeleteBatch(transaction::Transaction* transaction, common::ValueVector& srcNodeIDVector, common::ValueVector& dstNodeIDVector, common::ValueVector& relIDVector, common::RelDataDirection direction); bool checkIfNodeHasRels(transaction::Transaction* transaction, common::RelDataDirection direction, common::ValueVector* srcNodeIDVector) const; void throwIfNodeHasRels(transaction::Transaction* transaction, common::RelDataDirection direction, common::ValueVector* srcNodeIDVector, const rel_multiplicity_constraint_throw_func_t& throwFunc) const; void addColumn(transaction::Transaction* transaction, TableAddColumnState& addColumnState, PageAllocator& pageAllocator) override; Column* getCSROffsetColumn(common::RelDataDirection direction) const { return getDirectedTableData(direction)->getCSROffsetColumn(); } Column* getCSRLengthColumn(common::RelDataDirection direction) const { return getDirectedTableData(direction)->getCSRLengthColumn(); } common::column_id_t getNumColumns() const { DASSERT(directedRelData.size() >= 1); RUNTIME_CHECK(for (const auto& relData : directedRelData) { DASSERT(relData->getNumColumns() == directedRelData[0]->getNumColumns()); }); return directedRelData[0]->getNumColumns(); } Column* getColumn(common::column_id_t columnID, common::RelDataDirection direction) const { return getDirectedTableData(direction)->getColumn(columnID); } NodeGroup* getOrCreateNodeGroup(const transaction::Transaction* transaction, common::node_group_idx_t nodeGroupIdx, common::RelDataDirection direction) const; void commit(main::ClientContext* context, catalog::TableCatalogEntry* tableEntry, LocalTable* localTable) override; bool checkpoint(main::ClientContext*, catalog::TableCatalogEntry* tableEntry, PageAllocator& pageAllocator, const transaction::Transaction* snapshotTxn = nullptr, uint64_t epochWatermark = 0, common::transaction_t retentionHorizon = common::INVALID_TRANSACTION, const std::vector& openStartTSs = {}) override; void rollbackCheckpoint() override {}; void reclaimStorage(PageAllocator& pageAllocator) const override; bool vacuumInMemoryUpdates(common::transaction_t horizon) override; common::row_idx_t getNumTotalRows(const transaction::Transaction* transaction) override; // Rels of a native rel table that the transaction can see, as count(*) counts them. common::row_idx_t getNumVisibleRels(const transaction::Transaction* transaction, common::RelDataDirection direction); virtual common::row_idx_t getNumActiveBoundNodes(const transaction::Transaction* transaction, common::RelDataDirection direction); virtual std::vector> getDegreeEntries( const transaction::Transaction* transaction, common::RelDataDirection direction); virtual common::row_idx_t getDegreeForOffset(const transaction::Transaction* transaction, common::RelDataDirection direction, common::offset_t nodeOffset); virtual std::vector> getTopKDegrees( const transaction::Transaction* transaction, common::RelDataDirection direction, common::idx_t k); virtual RelDegreeSummary getDegreeSummary(const transaction::Transaction* transaction, common::RelDataDirection direction); RelTableData* getDirectedTableData(common::RelDataDirection direction) const; common::offset_t reserveRelOffsets(common::offset_t numRels) { std::unique_lock xLck{relOffsetMtx}; const auto currentRelOffset = nextRelOffset; nextRelOffset += numRels; return currentRelOffset; } void pushInsertInfo(const transaction::Transaction* transaction, common::RelDataDirection direction, const CSRNodeGroup& nodeGroup, common::row_idx_t numRows_, CSRNodeGroupScanSource source) const; std::vector getStorageDirections() const; common::table_id_t getRelGroupID() const { return relGroupID; } void serialize(common::Serializer& ser) const override; void deserialize(main::ClientContext* context, StorageManager* storageManager, common::Deserializer& deSer) override; private: static void prepareCommitForNodeGroup(const transaction::Transaction* transaction, const std::vector& columnIDs, const NodeGroup& localNodeGroup, CSRNodeGroup& csrNodeGroup, common::offset_t boundOffsetInGroup, const row_idx_vec_t& rowIndices, common::column_id_t skippedColumn); void updateRelOffsets(const LocalRelTable& localRelTable); static common::offset_t getCommittedOffset(common::offset_t uncommittedOffset, common::offset_t maxCommittedOffset); void detachDeleteForCSRRels(transaction::Transaction* transaction, RelTableData* tableData, RelTableData* reverseTableData, RelTableScanState* relDataReadState, RelTableDeleteState* deleteState); void checkRelMultiplicityConstraint(transaction::Transaction* transaction, const TableInsertState& state) const; template void forEachDegree(const transaction::Transaction* transaction, common::RelDataDirection direction, FUNC&& func); private: common::table_id_t relGroupID; common::table_id_t fromNodeTableID; common::table_id_t toNodeTableID; std::mutex relOffsetMtx; common::offset_t nextRelOffset; std::vector> directedRelData; }; } // namespace storage } // namespace lbug