Mr Dk.'s BlogMr Dk.'s Blog
  • 🦆 About Me
  • ⛏️ Technology Stack
  • 🔗 Links
  • 🗒️ About Blog
  • Algorithm
  • C++
  • Compiler
  • Cryptography
  • DevOps
  • Docker
  • Git
  • Java
  • Linux
  • MS Office
  • MySQL
  • Network
  • Operating System
  • Performance
  • PostgreSQL
  • Productivity
  • Solidity
  • Vue.js
  • Web
  • Wireless
  • 🐧 How Linux Works (notes)
  • 🐧 Linux Kernel Comments (notes)
  • 🐧 Linux Kernel Development (notes)
  • 🐤 μc/OS-II Source Code (notes)
  • ☕ Understanding the JVM (notes)
  • ⛸️ Redis Implementation (notes)
  • 🗜️ Understanding Nginx (notes)
  • ⚙️ Netty in Action (notes)
  • ☁️ Spring Microservices (notes)
  • ⚒️ The Annotated STL Sources (notes)
  • ☕ Java Development Kit 8
GitHub
  • 🦆 About Me
  • ⛏️ Technology Stack
  • 🔗 Links
  • 🗒️ About Blog
  • Algorithm
  • C++
  • Compiler
  • Cryptography
  • DevOps
  • Docker
  • Git
  • Java
  • Linux
  • MS Office
  • MySQL
  • Network
  • Operating System
  • Performance
  • PostgreSQL
  • Productivity
  • Solidity
  • Vue.js
  • Web
  • Wireless
  • 🐧 How Linux Works (notes)
  • 🐧 Linux Kernel Comments (notes)
  • 🐧 Linux Kernel Development (notes)
  • 🐤 μc/OS-II Source Code (notes)
  • ☕ Understanding the JVM (notes)
  • ⛸️ Redis Implementation (notes)
  • 🗜️ Understanding Nginx (notes)
  • ⚙️ Netty in Action (notes)
  • ☁️ Spring Microservices (notes)
  • ⚒️ The Annotated STL Sources (notes)
  • ☕ Java Development Kit 8
GitHub
  • 📝 Notes
    • Algorithm
      • Algorithm - Bloom Filter
      • Algorithm - Disjoint Set
      • Algorithm - Fast Power
      • Algorithm - KMP
      • Algorithm - Monotonic Stack
      • Algorithm - RB-Tree
      • Algorithm - Regular Expression
      • Algorithm - Sliding Window
      • Online Judge - I/O
    • C++
      • C++ - Const
      • C++ File I/O
      • C++ - Object Layout
      • C++ - Operator Overload
      • C++ - Polymorphism
      • C++ STL algorithm
      • C++ STL map
      • C++ STL multimap
      • C++ STL priority_queue
      • C++ STL set
      • C++ STL string
      • C++ STL unordered_map
      • C++ STL vector
      • C++ - Smart Pointer
      • C++ - Template & Genericity
    • Compiler
      • ANTLR - Basic
      • Compiler - LLVM Architecture
      • Compiler - Multi-version GCC
    • Cryptography
      • Cryptography - Certbot
      • Cryptography - Digital Signature & PKCS #7
      • Cryptography - GPG
      • Cryptography - JWT
      • Cryptography - Keystore & Certificates
      • Cryptography - OAuth 2.0
      • Cryptography - Java 实现对称与非对称加密算法
      • Cryptography - TLS
    • DevOps
      • DevOps - Travis CI
    • Docker
      • Docker - Image & Storage Management
      • Docker - Image
      • Docker - Libcontainer
      • Docker - Multi-Arch Image
      • Docker - Multi-Stage Build
      • Docker - Network
      • Docker - Orchestration & Deployment
      • Docker - Overview
      • Docker - Service Building
      • Docker - Volume & Network Usage
      • Docker - Volume
      • Linux - Control Group
      • Linux - Namespace
    • Git
      • Git - Branch & Merge
      • Git - Cached
      • Git - Cherry Pick
      • Git - Commit
      • Git - Patch
      • Git - Proxy
      • Git - Rebase
      • Git - Reset
      • Git - Stash
      • Git - Theme for Git-Bash
    • Java
      • JVM - Synchronized
      • JVM - Volatile
      • Java - Annotation 注解
      • Java - BIO & NIO
      • Java - Class Path
      • Java - Condition and LockSupport
      • Java - Current Timestamp
      • Java - Deep Copy
      • Java - 运行环境配置
      • Java - Equals
      • Java - Exporting JAR
      • Java - Javadoc
      • Java - Lock
      • Java - Maven 项目构建工具
      • Java - References
      • Java - Reflection Mechanism
      • Java - String Split
      • Java - Thread Pool
      • Java - Thread
      • Tomcat - Class Loader
      • Tomcat - Container
    • Linux
      • addr2line
      • cut
      • df
      • du
      • fallocate
      • find
      • fio
      • grep
      • groupadd
      • gzip
      • head / tail
      • hexdump
      • iostat
      • iotop
      • kill
      • ldd
      • lsof
      • ltrace / strace
      • mpstat
      • netstat
      • nm
      • pidstat
      • pmap
      • readlink
      • readlink
      • rpm2cpio / rpm2archive
      • sort
      • tee
      • uniq
      • useradd
      • usermod
      • watch
      • wc
      • which
      • xargs
    • MS Office
      • MS Office - Add-in Dev
      • MS Office - Application
    • MySQL
      • InnoDB - Architecture
      • InnoDB - Backup
      • InnoDB - Checkpoint
      • InnoDB - Critical Features
      • InnoDB - Files
      • InnoDB - Index
      • InnoDB - Insert Buffer
      • InnoDB - Lock
      • InnoDB - Partition Table
      • InnoDB - Table Storage
      • MySQL - Server Configuration
      • MySQL - Storage Engine
    • Network
      • Network - ARP
      • Network - FTP
      • Network - GitHub Accelerating
      • HTTP - Message Format
      • HTTP - POST 提交表单的两种方式
      • Network - Proxy Server
      • Network - SCP
      • Network - SSH
      • Network - TCP Congestion Control
      • Network - TCP Connection Management
      • Network - TCP Flow Control
      • Network - TCP Retransmission
      • Network - Traceroute
      • Network - V2Ray
      • Network - WebSocket
      • Network - Windows 10 Mail APP
      • Network - frp
    • Operating System
      • Linux - Kernel Compilation
      • Linux - Multi-OS
      • Linux - Mutex & Condition
      • Linux - Operations
      • Linux: Package Manager
      • Linux - Process Manipulation
      • Linux - User ID
      • Linux - Execve
      • OS - Compile and Link
      • OS - Dynamic Linking
      • OS - ELF
      • Linux - Image
      • OS - Loading
      • OS - Shared Library Organization
      • OS - Static Linking
      • Syzkaller - Architecture
      • Syzkaller - Description Syntax
      • Syzkaller - Usage
      • Ubuntu - Desktop Recover (Python)
      • WSL: CentOS 8
    • Performance
      • Linux Performance - Perf Event
      • Linux Performance - Perf Record
      • Linux Performance - Perf Report
      • Linux Performance - Flame Graphs
      • Linux Performance - Off CPU Analyze
    • PostgreSQL
      • PostgreSQL - ANALYZE
      • PostgreSQL - Atomics
      • PostgreSQL - CREATE INDEX CONCURRENTLY
      • PostgreSQL - COPY FROM
      • PostgreSQL - COPY TO
      • PostgreSQL - Executor: Append
      • PostgreSQL - Executor: Group
      • PostgreSQL - Executor: Limit
      • PostgreSQL - Executor: Material
      • PostgreSQL - Executor: Nest Loop Join
      • PostgreSQL - Executor: Result
      • PostgreSQL - Executor: Sequential Scan
      • PostgreSQL - Executor: Sort
      • PostgreSQL - Executor: Unique
      • PostgreSQL - FDW Asynchronous Execution
      • PostgreSQL - GUC
      • PostgreSQL - Locking
      • PostgreSQL - LWLock
      • PostgreSQL - Multi Insert
      • PostgreSQL - Plan Hint GUC
      • PostgreSQL - Process Activity
      • PostgreSQL - Query Execution
      • PostgreSQL - Spinlock
      • PostgreSQL - Storage Management
      • PostgreSQL - VFD
      • PostgreSQL - WAL Insert
      • PostgreSQL - WAL Prefetch
    • Productivity
      • LaTeX
      • Venn Diagram
      • VuePress
    • Solidity
      • Solidity - ABI Specification
      • Solidity - Contracts
      • Solidity - Expressions and Control Structures
      • Solidity - Layout and Structure
      • Solidity - Remix IDE
      • Solidity - Slither
      • Solidity - Types
      • Solidity - Units and Globally Available Variables
    • Vue.js
      • Vue.js - Environment Variable
    • Web
      • Web - CORS
      • Web - OpenAPI Specification
    • Wireless
      • Wireless - WEP Cracking by Aircrack-ng
      • Wireless - WPS Cracking by Reaver
      • Wireless - wifiphisher

PostgreSQL - Executor: Unique

Created by : Mr Dk.

2021 / 07 / 11 21:44

Hangzhou, Zhejiang, China


Unique 计划节点用于元组的去重。众所周知,去重操作基于一个很重要的前提:输入数据有序。如果已知输入数据有序,那么去重的实现方式将非常直截了当:缓存前一个元组,如果当前元组与前一个元组相同,就丢弃这个重复元组。可以得知,Unique 节点会被放在一个 Sort 节点的上层。

这也是一个很简单的节点,不对元组做选择和投影操作。

Plan Node

Unique 节点继承自 Plan 结构体,同时扩展了去重相关的信息。由于判断去重实际上是判断是否相等,因此去重信息主要包含用于比较的列信息,以及比较操作的信息:

/* ----------------
 *      unique node
 * ----------------
 */
typedef struct Unique
{
    Plan        plan;
    int         numCols;        /* number of columns to check for uniqueness */
    AttrNumber *uniqColIdx;     /* their indexes in the target list */
    Oid        *uniqOperators;  /* equality operators to compare with */
    Oid        *uniqCollations; /* collations for equality comparisons */
} Unique;

Plan State

UniqueState 继承自 PlanState 结构,同时扩展了用于判断是否相等的 ExprState *:

/* ----------------
 *   UniqueState information
 *
 *      Unique nodes are used "on top of" sort nodes to discard
 *      duplicate tuples returned from the sort phase.  Basically
 *      all it does is compare the current tuple from the subplan
 *      with the previously fetched tuple (stored in its result slot).
 *      If the two are identical in all interesting fields, then
 *      we just fetch another tuple from the sort and try again.
 * ----------------
 */
typedef struct UniqueState
{
    PlanState   ps;             /* its first field is NodeTag */
    ExprState  *eqfunction;     /* tuple equality qual */
} UniqueState;

Initialization

在 ExecInitNode() 生命周期中被调用,主要工作包括分配 UniqueState 节点并初始化,然后递归调用 ExecInitNode()。将 Unique 节点中与比较相关的信息传递给 execTuplesMatchPrepare() 函数,返回 ExprState 结构并将指针设置到 UniqueState 中。

/* ----------------------------------------------------------------
 *      ExecInitUnique
 *
 *      This initializes the unique node state structures and
 *      the node's subplan.
 * ----------------------------------------------------------------
 */
UniqueState *
ExecInitUnique(Unique *node, EState *estate, int eflags)
{
    UniqueState *uniquestate;

    /* check for unsupported flags */
    Assert(!(eflags & (EXEC_FLAG_BACKWARD | EXEC_FLAG_MARK)));

    /*
     * create state structure
     */
    uniquestate = makeNode(UniqueState);
    uniquestate->ps.plan = (Plan *) node;
    uniquestate->ps.state = estate;
    uniquestate->ps.ExecProcNode = ExecUnique;

    /*
     * create expression context
     */
    ExecAssignExprContext(estate, &uniquestate->ps);

    /*
     * then initialize outer plan
     */
    outerPlanState(uniquestate) = ExecInitNode(outerPlan(node), estate, eflags);

    /*
     * Initialize result slot and type. Unique nodes do no projections, so
     * initialize projection info for this node appropriately.
     */
    ExecInitResultTupleSlotTL(&uniquestate->ps, &TTSOpsMinimalTuple);
    uniquestate->ps.ps_ProjInfo = NULL;

    /*
     * Precompute fmgr lookup data for inner loop
     */
    uniquestate->eqfunction =
        execTuplesMatchPrepare(ExecGetResultType(outerPlanState(uniquestate)),
                               node->numCols,
                               node->uniqColIdx,
                               node->uniqOperators,
                               node->uniqCollations,
                               &uniquestate->ps);

    return uniquestate;
}

Execution

在 ExecProcNode() 生命周期中被调用。UniqueState 节点的 ps_ResultTupleSlot 保存了上一个返回给上层节点的元组。在死循环中不断对子节点递归调用 ExecProcNode() 获取一个元组,然后利用之前初始化好的比较函数将当前元组与 ps_ResultTupleSlot 元组进行比较。

  • 如果相同,那么说明元组重复,直接忽略当前元组并扫描下一个
  • 如果不同,那么说明元组从未出现过,那么将当前元组拷贝到 ps_ResultTupleSlot 中 (并返回给上层节点)

直到子节点返回空元组。

/* ----------------------------------------------------------------
 *      ExecUnique
 * ----------------------------------------------------------------
 */
static TupleTableSlot *         /* return: a tuple or NULL */
ExecUnique(PlanState *pstate)
{
    UniqueState *node = castNode(UniqueState, pstate);
    ExprContext *econtext = node->ps.ps_ExprContext;
    TupleTableSlot *resultTupleSlot;
    TupleTableSlot *slot;
    PlanState  *outerPlan;

    CHECK_FOR_INTERRUPTS();

    /*
     * get information from the node
     */
    outerPlan = outerPlanState(node);
    resultTupleSlot = node->ps.ps_ResultTupleSlot;

    /*
     * now loop, returning only non-duplicate tuples. We assume that the
     * tuples arrive in sorted order so we can detect duplicates easily. The
     * first tuple of each group is returned.
     */
    for (;;)
    {
        /*
         * fetch a tuple from the outer subplan
         */
        slot = ExecProcNode(outerPlan);
        if (TupIsNull(slot))
        {
            /* end of subplan, so we're done */
            ExecClearTuple(resultTupleSlot);
            return NULL;
        }

        /*
         * Always return the first tuple from the subplan.
         */
        if (TupIsNull(resultTupleSlot))
            break;

        /*
         * Else test if the new tuple and the previously returned tuple match.
         * If so then we loop back and fetch another new tuple from the
         * subplan.
         */
        econtext->ecxt_innertuple = slot;
        econtext->ecxt_outertuple = resultTupleSlot;
        if (!ExecQualAndReset(node->eqfunction, econtext))
            break;
    }

    /*
     * We have a new tuple different from the previous saved tuple (if any).
     * Save it and return it.  We must copy it because the source subplan
     * won't guarantee that this source tuple is still accessible after
     * fetching the next source tuple.
     */
    return ExecCopySlot(resultTupleSlot, slot);
}

Clean Up

在 ExecEndNode() 生命周期函数中被调用。

/* ----------------------------------------------------------------
 *      ExecEndUnique
 *
 *      This shuts down the subplan and frees resources allocated
 *      to this node.
 * ----------------------------------------------------------------
 */
void
ExecEndUnique(UniqueState *node)
{
    /* clean up tuple table */
    ExecClearTuple(node->ps.ps_ResultTupleSlot);

    ExecFreeExprContext(&node->ps);

    ExecEndNode(outerPlanState(node));
}
Edit this page on GitHub
Prev
PostgreSQL - Executor: Sort
Next
PostgreSQL - FDW Asynchronous Execution