使用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>)
  • 各种空格格式(包括换行和多余空格)
相关推荐
微学AI2 小时前
一根针指向所有方向:挂谷猜想对 LLM Agent 技能-记忆架构的启示
开发语言·人工智能·架构·挂谷猜想
豆瓣鸡3 小时前
算法日记 - Day3
java·开发语言·算法
凯丨3 小时前
AI 蠕虫来了:恶意文档如何通过 Copilot for Word 自我传播?
人工智能·c#·copilot
韭菜炒鸡肝天3 小时前
VTK开发笔记(一):VTK介绍,Qt..+VSx+VTK.编译
开发语言·笔记·qt
Aaron - Wistron4 小时前
Web API C# (Furion版)带 单元测试
开发语言·后端·c#
Dxy12393102165 小时前
Python项目打包成EXE完整教程(PyInstaller实战避坑)
开发语言·python
0566466 小时前
Python康复训练——常用标准库
开发语言·python·学习
骊城英雄6 小时前
基于C#+avalonia ui实现的跨平台点胶机灌胶监控控制上位机软件
开发语言·ui·c#
吾儿良辰6 小时前
一个被BCL遗忘的高性能集合:C# CircularBuffer<T>深度解析
开发语言·windows·c#
哎呦喂我去去去6 小时前
C#实现屏幕墙:同时监控多个电脑桌面(支持Windows、信创Linux、银河麒麟、统信UOS)
linux·windows·c#