Skip to content
TheChatArchiveThe Chat Archive
Claudeclaude-3-5-haiku-20241022· AnthropicHugging Face LMArena Human Preference 140K

我想要請你完成一個python程式任務 輸入一個GEN SQL 一個 Golden SQL 然後比對兩者的 Component Match 指標…

From a Chatbot Arena battleThe same person sent this prompt to two anonymous models at once. Compare it with Claudeclaude-3-5-sonnet-20241022’s answer.
  1. User

    我想要請你完成一個python程式任務 輸入一個GEN SQL 一個 Golden SQL 然後比對兩者的 Component Match 指標 需要支援多嵌套,然後用AST的方式寫,盡量不要用regex的方式寫

  2. Claude Assistant

    我可以幫您設計一個使用 AST (Abstract Syntax Tree) 方法來比對 SQL 查詢的 Python 程式。以下是一個實現方案:

    import sqlparse
    from sqlparse.sql import IdentifierList, Identifier, Function
    from sqlparse.tokens import Keyword, DML, Comparison
    import ast
    
    class SQLComponentMatcher:
        def __init__(self, gen_sql, golden_sql):
            self.gen_sql = sqlparse.parse(gen_sql)[0]
            self.golden_sql = sqlparse.parse(golden_sql)[0]
    
        def _extract_components(self, sql):
            """
            遞歸提取 SQL 的抽象語法樹組件
            """
            def _parse_node(node):
                if isinstance(node, IdentifierList):
                    return [_parse_node(token) for token in node.tokens if not token.is_whitespace]
                
                if isinstance(node, Identifier):
                    return node.value
                
                if isinstance(node, Function):
                    return {
                        'type': 'function',
                        'name': node.tokens[0].value,
                        'args': [_parse_node(token) for token in node.tokens[1:-1] if not token.is_whitespace]
                    }
                
                if node.ttype in (Keyword, DML, Comparison):
                    return node.value
                
                return None
    
            return [comp for comp in _parse_node(sql) if comp is not None]
    
        def calculate_component_match(self):
            """
            計算組件匹配指標
            """
            gen_components = self._extract_components(self.gen_sql)
            golden_components = self._extract_components(self.golden_sql)
    
            total_components = len(golden_components)
            matched_components = sum(
                1 for gc in gen_components 
                if any(self._deep_compare(gc, goc) for goc in golden_components)
            )
    
            match_ratio = matched_components / total_components if total_components > 0 else 0
            return {
                'total_components': total_components,
                'matched_components': matched_components,
                'match_ratio': match_ratio
            }
    
        def _deep_compare(self, comp1, comp2):
            """
            深度比較兩個組件
            支持巢狀結構和不同類型的比較
            """
            if isinstance(comp1, dict) and isinstance(comp2, dict):
                # 函數比較
                if comp1.get('type') == 'function' and comp2.get('type') == 'function':
                    if comp1['name'].lower() != comp2['name'].lower():
                        return False
                    
                    # 遞歸比較函數參數
                    if len(comp1['args']) != len(comp2['args']):
                        return False
                    
                    return all(
                        self._deep_compare(arg1, arg2) 
                        for arg1, arg2 in zip(comp1['args'], comp2['args'])
                    )
            
            # 基本值比較(不區分大小寫)
            return str(comp1).lower() == str(comp2).lower()
    
    # 使用範例
    def main():
        gen_sql = "SELECT name, age FROM users WHERE age > 18"
        golden_sql = "SELECT name, age FROM users WHERE age > 21"
    
        matcher = SQLComponentMatcher(gen_sql, golden_sql)
        result = matcher.calculate_component_match()
    
        print("Component Match Result:")
        print(f"Total Components: {result['total_components']}")
        print(f"Matched Components: {result['matched_components']}")
        print(f"Match Ratio: {result['match_ratio']:.2%}")
    
    if __name__ == "__main__":
        main()
    

    這個實現有以下特點:

    1. 使用 sqlparse 庫解析 SQL,避免使用正則表達式
    2. 支持多層巢狀結構的比較
    3. 不區分大小寫的比較
    4. 提供組件匹配指標:
      • 總組件數
      • 匹配組件數
      • 匹配比率

    主要方法說明:

    • _extract_components(): 遞歸提取 SQL 的組件
    • _deep_compare(): 深度比較組件,支持函數、標識符等
    • calculate_component_match(): 計算匹配指標

    您可以根據實際需求調整和擴展這個實現。如果有特定的 SQL 結構或比較邏輯,我們可以進一步客製化這個方法。

Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.