hashjoin 源码

时间: 2023-12-03 08:51:22 浏览: 35
hashjoin 是一种常用的关系型数据库的查询算法,用于将两个表中共同的列进行匹配并连接起来。具体实现可以参考 PostgreSQL 数据库中的代码实现。 在 PostgreSQL 中,hashjoin 的实现主要包括三个部分:构建哈希表、扫描哈希表和匹配结果。 构建哈希表: ```c static HashJoinTable ExecHashTableCreate(PlanState *parent, List *hashOperators, /* hash function to use for each join key */ long nbuckets, /* # buckets in hashtable */ Size entrysize, /* size of each entry in hashtable */ bool use_variable_hash_iv) { HashJoinTable hashtable; int nbuckets_est = nbuckets; int log2_nbuckets; /* Limit nbuckets to at most INT_MAX; must do this before sizing to power of 2 */ if ((double) nbuckets_est * (double) entrysize > (double) INT_MAX) nbuckets_est = (int) floor((double) INT_MAX / (double) entrysize); /* Size hash table to a power of 2 */ log2_nbuckets = my_log2(nbuckets_est); hashtable = (HashJoinTable) palloc0(HJTUPLE_OVERHEAD + sizeof(HashJoinTableData) + (entrysize * (1 << log2_nbuckets))); hashtable->nbuckets = nbuckets_est; hashtable->log2_nbuckets = log2_nbuckets; hashtable->buckets = (HashJoinTuple *) (((char *) hashtable) + HJTUPLE_OVERHEAD + sizeof(HashJoinTableData)); hashtable->hash_iv = GetPerTupleExprContext(parent)->ecxt_hashjoin_outer; /* Initialize all hash bucket headers to empty */ MemSet(hashtable->buckets, 0, sizeof(HashJoinTuple) << log2_nbuckets); /* Set up array containing OIDs of hash operators */ ExecChooseHashFuncs(hashOperators, hashtable->hashfunctions, hashtable->nbuckets, use_variable_hash_iv); return hashtable; } ``` 扫描哈希表: ```c static TupleTableSlot * ExecScanHashBucket(HashJoinState *hjstate, ExprContext *econtext) { HashJoinTable hashtable = hjstate->hj_HashTable; AttrNumber *hj_OuterHashKeys = hjstate->hj_OuterHashKeys; TupleTableSlot *innerTupleSlot = hjstate->hj_InnerTupleSlot; TupleTableSlot *outerTupleSlot = hjstate->hj_OuterTupleSlot; HashJoinTuple hashTuple; uint32 hashvalue; int bucketno; /* loop until we find a join tuple */ for (;;) { hashvalue = ExecHashGetBucket(hjstate, hashtable, hj_OuterHashKeys, econtext, false); bucketno = ExecHashGetBucketNumber(hashvalue, hashtable->log2_nbuckets); /* * Scan the bucket for matching tuples. */ for (hashTuple = hashtable->buckets[bucketno]; hashTuple != NULL; hashTuple = hashTuple->next) { if (hashTuple->hashvalue != hashvalue) continue; /* Found a match? Then report and save tuple */ if (ExecQualAndReset(hashTuple->hashressupport, econtext)) { /* save the matching tuple */ ExecStoreMinimalTuple(HJTUPLE_MINTUPLE(hashTuple), innerTupleSlot, false); /* set up for next join tuple, if any */ hjstate->hj_CurHashValue = hashvalue; hjstate->hj_CurBucketNo = bucketno; return outerTupleSlot; } } /* * No match in this bucket; check for additional matches in outer * batches. */ if (!ExecScanHashTableForUnmatched(hjstate, econtext)) return NULL; /* need new outer tuple */ } } ``` 匹配结果: ```c static TupleTableSlot * ExecHashJoin(HashJoinState *node) { PlanState *outerNode = outerPlanState(node); HashJoinTable hashtable = node->hj_HashTable; TupleTableSlot *innerTupleSlot = node->hj_InnerTupleSlot; TupleTableSlot *outerTupleSlot = node->hj_OuterTupleSlot; ExprContext *econtext = node->js.ps.ps_ExprContext; TupleTableSlot *result; MinimalTuple tuple; /* * Reset per-tuple memory context to free any expression evaluation * storage allocated in the previous tuple cycle. */ ResetExprContext(econtext); /* * if first time through, read all inner tuples into hashtable */ if (!node->hj_CurHashValue) { /* Reset hash table to empty */ ExecHashTableReset(hashtable); /* Load hashtable with inner tuples */ ExecHashJoinNewBatch(node); /* If inner relation is completely empty, return no rows */ if (hashtable->totalTuples == 0) return NULL; } /* * We read the outer tuple in the previous iteration, which means that we * have to check for additional join matches for it before continuing. */ if (node->hj_JoinState == HJ_NEED_NEW_OUTER) { if (!ExecScanHashTableForUnmatched(node, econtext)) return NULL; /* need new outer tuple */ } /* * Now check for any matches */ for (;;) { /* * If we've run out of inner tuples, then the current outer tuple * can't have a match, so we're done with it. */ if (node->hj_CurTuple == NULL) { if (!ExecScanHashTableForUnmatched(node, econtext)) break; /* need new outer tuple */ continue; /* search next hash bucket */ } /* * Check for join match. */ if (ExecQual(node->js.ps.qual, econtext)) { /* * qualification was satisfied so we project and return the * slot containing joined tuples, making sure that the slot is * labeled with the join's rowtype. */ ExecProject(node->js.ps.ps_ProjInfo); result = node->js.ps.ps_ProjInfo->pi_slot; /* * We return the first (and only) qualifying join tuple. The * executor doesn't support the idea of generating multiple * join rows from one outer tuple when there are multiple * matching inner tuples (compare the semantics of a nested * loops join). */ if (hashtable->nbatch == 1) { /* In single-batch case, just return the result */ return result; } else { /* * Before returning the first join tuple, force the * other tuples in the same join group to be fetched and * appended to the result list. */ tuple = ExecFetchSlotMinimalTuple(innerTupleSlot); ExecHashTableMarkCurBucket(hjstate); ExecHashTableGetBucketAndBatch(hashtable, node->hj_CurHashValue, &node->hj_CurBucketNo, &node->hj_CurTuple, &node->hj_CurBucketBuf); /* * Set the next tuple to return, if any. Done in this order * so that if there is only one tuple in the group, we don't * advance the pointers at all. */ if (node->hj_CurTuple != NULL) node->hj_NextTuple = node->hj_CurTuple->next; else node->hj_NextTuple = NULL; /* Remember there's a join tuple available */ node->hj_JoinState = HJ_NEED_NEW_OUTER; /* And return the first tuple */ return result; } } /* * Didn't match this time. Try next tuple in inner relation. */ node->hj_CurTuple = node->hj_CurTuple->next; } /* * no more matches */ return NULL; } ``` 以上代码是 PostgreSQL 中 hashjoin 的基本实现,可以作为参考。

相关推荐

最新推荐

recommend-type

linphone源码分析.docx

linphone源码分析,非常详细的源码分析。Linphone 代码的分析主要分为三个部分。在整个分析过程主要是对音频通话相关的内容进行分析,视频的流程类似,但有细节有很大的区别,请自行分析。如果在看代码的过程中碰到...
recommend-type

bitcoin源码分析文档

bitcoin源码分析文档包含bitcoin源码中和各个模块的关联关系图,各个模块类关系图等
recommend-type

snort源码笔记分析

本文是自己在阅读snort时做的笔记,和画的一些数据结构变换图,包括如何解析规则,如何形成otn和rtn等。
recommend-type

开源Ceph10.2.1源码分析.docx

Ceph作为一个开源的分布式存储系统,人人都可以免费获得其源代码,并能够安装部署,但是并不等于人人都能用起来,人人都能用好。用好一个开源分布式存储系统,首先要对其架构、功能原理等方面有比较好的了解,其次要...
recommend-type

详解Docker源码编译安装

本篇文章主要介绍了详解Docker源码编译安装,小编觉得挺不错的,现在分享给大家,也给大家做个参考。一起跟随小编过来看看吧
recommend-type

zigbee-cluster-library-specification

最新的zigbee-cluster-library-specification说明文档。
recommend-type

管理建模和仿真的文件

管理Boualem Benatallah引用此版本:布阿利姆·贝纳塔拉。管理建模和仿真。约瑟夫-傅立叶大学-格勒诺布尔第一大学,1996年。法语。NNT:电话:00345357HAL ID:电话:00345357https://theses.hal.science/tel-003453572008年12月9日提交HAL是一个多学科的开放存取档案馆,用于存放和传播科学研究论文,无论它们是否被公开。论文可以来自法国或国外的教学和研究机构,也可以来自公共或私人研究中心。L’archive ouverte pluridisciplinaire
recommend-type

实现实时数据湖架构:Kafka与Hive集成

![实现实时数据湖架构:Kafka与Hive集成](https://img-blog.csdnimg.cn/img_convert/10eb2e6972b3b6086286fc64c0b3ee41.jpeg) # 1. 实时数据湖架构概述** 实时数据湖是一种现代数据管理架构,它允许企业以低延迟的方式收集、存储和处理大量数据。与传统数据仓库不同,实时数据湖不依赖于预先定义的模式,而是采用灵活的架构,可以处理各种数据类型和格式。这种架构为企业提供了以下优势: - **实时洞察:**实时数据湖允许企业访问最新的数据,从而做出更明智的决策。 - **数据民主化:**实时数据湖使各种利益相关者都可
recommend-type

解释minorization-maximization (MM) algorithm,并给出matlab代码编写的例子

Minorization-maximization (MM) algorithm是一种常用的优化算法,用于求解非凸问题或含有约束的优化问题。该算法的基本思想是通过构造一个凸下界函数来逼近原问题,然后通过求解凸下界函数的最优解来逼近原问题的最优解。具体步骤如下: 1. 初始化参数 $\theta_0$,设 $k=0$; 2. 构造一个凸下界函数 $Q(\theta|\theta_k)$,使其满足 $Q(\theta_k|\theta_k)=f(\theta_k)$; 3. 求解 $Q(\theta|\theta_k)$ 的最优值 $\theta_{k+1}=\arg\min_\theta Q(
recommend-type

JSBSim Reference Manual

JSBSim参考手册,其中包含JSBSim简介,JSBSim配置文件xml的编写语法,编程手册以及一些应用实例等。其中有部分内容还没有写完,估计有生之年很难看到完整版了,但是内容还是很有参考价值的。