使用C#实现从Hive的CREATE TABLE语句中提取分区字段名和数据类型

csharp 复制代码
using System;
using System.Collections.Generic;
using System.Text.RegularExpressions;

namespace HivePartitionParser
{
    public class Program
    {
        private static readonly Regex PartitionedByRegex = new Regex(
            @"PARTITIONED\s+BY\s*\(([^)]*)\)",
            RegexOptions.IgnoreCase | RegexOptions.Compiled
        );

        private static readonly Regex FieldRegex = new Regex(
            @"^(?:`(?<name>[^`]+)`|(?<name>\w+))\s+(?<type>\w+(?:\([^)]*\)|<[^>]*>)?)",
            RegexOptions.ExplicitCapture | RegexOptions.Compiled
        );

        public static void Main(string[] args)
        {
            const string createTableSql = @"
                CREATE TABLE employees (
                    id INT,
                    name STRING
                )
                PARTITIONED BY (year INT, month STRING, salary DECIMAL(10,2))
                STORED AS ORC;";

            foreach (var (name, type) in ParsePartitionColumns(createTableSql))
            {
                Console.WriteLine($"Partition Column: {name.PadRight(15)} Type: {type}");
            }
        }

        public static IEnumerable<(string Name, string Type)> ParsePartitionColumns(string sql)
        {
            var partitionedByMatch = PartitionedByRegex.Match(sql);
            if (!partitionedByMatch.Success) yield break;

            var columnsText = partitionedByMatch.Groups[1].Value.Trim();
            foreach (var columnDef in SplitColumnDefinitions(columnsText))
            {
                var match = FieldRegex.Match(columnDef);
                if (match.Success)
                {
                    yield return (
                        match.Groups["name"].Value,
                        match.Groups["type"].Value
                    );
                }
            }
        }

        private static IEnumerable<string> SplitColumnDefinitions(string input)
        {
            int depth = 0, start = 0;
            for (int i = 0; i < input.Length; i++)
            {
                switch (input[i])
                {
                    case '(': depth++; break;
                    case ')': depth--; break;
                    case ',' when depth == 0:
                        yield return input.Substring(start, i - start).Trim();
                        start = i + 1;
                        break;
                }
            }
            if (start < input.Length)
                yield return input.Substring(start).Trim();
        }
    }
}

代码说明:

  1. 正则表达式优化

    • 使用预编译正则表达式(RegexOptions.Compiled)提升匹配性能
    • PartitionedByRegex 用于定位分区定义部分
    • FieldRegex 用于解析字段名称和类型
  2. 核心解析逻辑

    • 使用括号深度感知的分割算法处理嵌套结构
    • 支持处理带括号的复杂类型(如DECIMAL(10,2))
    • 支持反引号包裹的字段名
  3. 性能优化

    • 避免不必要的字符串分配
    • 使用迭代器实现延迟处理
    • 减少中间集合的创建
  4. 关键方法

    • ParsePartitionColumns:主解析方法
    • SplitColumnDefinitions:智能分割字段定义

示例输出:

复制代码
Partition Column: year            Type: INT
Partition Column: month           Type: STRING
Partition Column: salary          Type: DECIMAL(10,2)

该实现能够正确处理以下复杂场景:

  • 带括号的类型定义
  • 反引号包裹的字段名
  • 嵌套的复杂类型(如MAP<STRING,ARRAY>)
  • 各种空格格式(包括换行和多余空格)
相关推荐
Chester_19996 小时前
CSP202203C.计算资源调度器
开发语言·数据结构·c++·蓝桥杯
EXI-小洲7 小时前
Java 操作 Word:字符串替换、图片插入、动态生成表格与API接口下载
java·开发语言·spring boot·word
会周易的程序员8 小时前
给 PLC 写一个字节码虚拟机:STVM 虚拟机架构设计
开发语言·c++·虚拟机·软plc·iec61131·stvm
机器视觉知识推荐、就业指导8 小时前
为什么老说“纯 Qt 没啥就业市场”?
开发语言·qt
telepan8 小时前
Qt 开发避坑与性能指南:如何优雅、安全地定义全局常量字符串?
开发语言·qt
m0_695251498 小时前
Qt MaintenanceTool 使用国内镜像加速下载(超详细教程)
开发语言·qt
大衛說9 小时前
《Python 从入门到精通》系列总览与学习路线
开发语言·python·学习
可乐鸡翅yeah_10 小时前
hls.js 内存泄漏实战排查,直播 M3U8 长时间播放异常定位方案
开发语言·javascript·python·django·ecmascript·m3u8·m3u8在线
2601_9622035110 小时前
Java进阶07集合(续)
java·开发语言
郑州光合科技余经理11 小时前
本地生活服务系统:模块边界与结算字段怎么拆
java·开发语言·前端·后端·系统架构·uni-app·php