- 
                Notifications
    You must be signed in to change notification settings 
- Fork 524
NO-SNOW: Cherry-picks to aio branch #2611
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
          
     Open
      
      
            sfc-gh-turbaszek
  wants to merge
  2
  commits into
  dev/aio-connector
  
    
      
        
          
  
    
      Choose a base branch
      
     
    
      
        
      
      
        
          
          
        
        
          
            
              
              
              
  
           
        
        
          
            
              
              
           
        
       
     
  
        
          
            
          
            
          
        
       
    
      
from
turbaszek-aio-cp-5
  
      
      
   
  
    
  
  
  
 
  
      
    base: dev/aio-connector
Could not load branches
            
              
  
    Branch not found: {{ refName }}
  
            
                
      Loading
              
            Could not load tags
            
            
              Nothing to show
            
              
  
            
                
      Loading
              
            Are you sure you want to change the base?
            Some commits from the old base branch may be removed from the timeline,
            and old review comments may become outdated.
          
          
      
        
          +492
        
        
          −18
        
        
          
        
      
    
  
  
     Open
                    Changes from all commits
      Commits
    
    
  File filter
Filter by extension
Conversations
          Failed to load comments.   
        
        
          
      Loading
        
  Jump to
        
          Jump to file
        
      
      
          Failed to load files.   
        
        
          
      Loading
        
  Diff view
Diff view
There are no files selected for viewing
  
    
      This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
      Learn more about bidirectional Unicode characters
    
  
  
    
              | Original file line number | Diff line number | Diff line change | 
|---|---|---|
| @@ -0,0 +1,56 @@ | ||
| name: Test Installation | ||
|  | ||
| on: | ||
| push: | ||
| branches: | ||
| - master | ||
| - main | ||
| pull_request: | ||
| branches: | ||
| - '**' | ||
| workflow_dispatch: | ||
|  | ||
| concurrency: | ||
| # older builds for the same pull request number or branch should be cancelled | ||
| cancel-in-progress: true | ||
| group: ${{ github.workflow }}-${{ github.event.pull_request.number || github.ref }} | ||
|  | ||
| jobs: | ||
| test-installation: | ||
| name: Test Boto Dependency | ||
| runs-on: ubuntu-latest | ||
| steps: | ||
| - uses: actions/checkout@v4 | ||
|  | ||
| - name: Set up Python | ||
| uses: actions/setup-python@v4 | ||
| with: | ||
| python-version: 3.12 | ||
|  | ||
| - name: Test default installation (should include boto) | ||
| shell: bash | ||
| run: | | ||
| python -m venv test_default_env | ||
| source test_default_env/bin/activate | ||
|  | ||
| python -m pip install . | ||
| pip freeze | grep boto || exit 1 # boto3/botocore should be installed by default | ||
|  | ||
| # Deactivate and clean up | ||
| deactivate | ||
| rm -rf test_default_env | ||
|  | ||
| - name: Test installation with SNOWFLAKE_NO_BOTO=1 (should exclude boto) | ||
| shell: bash | ||
| run: | | ||
| python -m venv test_no_boto_env | ||
| source test_no_boto_env/bin/activate | ||
|  | ||
| SNOWFLAKE_NO_BOTO=1 python -m pip install . | ||
|  | ||
| # Check that boto3 and botocore are NOT installed | ||
| pip freeze | grep boto && exit 1 # boto3 and botocore should be not installed | ||
|  | ||
| # Deactivate and clean up | ||
| deactivate | ||
| rm -rf test_no_boto_env | 
  
    
      This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
      Learn more about bidirectional Unicode characters
    
  
  
    
              
  
    
      This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
      Learn more about bidirectional Unicode characters
    
  
  
    
              
  
    
      This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
      Learn more about bidirectional Unicode characters
    
  
  
    
              | Original file line number | Diff line number | Diff line change | 
|---|---|---|
| @@ -0,0 +1,149 @@ | ||
| #!/usr/bin/env python3 | ||
| """ | ||
| Pre-commit hook to ensure optional dependencies are always imported from .options module. | ||
| This ensures that the connector can operate in environments where these optional libraries are not available. | ||
| """ | ||
| import argparse | ||
| import ast | ||
| import sys | ||
| from dataclasses import dataclass | ||
| from pathlib import Path | ||
| from typing import List | ||
|  | ||
| CHECKED_MODULES = ["boto3", "botocore", "pandas", "pyarrow", "keyring"] | ||
|  | ||
|  | ||
| @dataclass(frozen=True) | ||
| class ImportViolation: | ||
| """Pretty prints a violation import restrictions.""" | ||
|  | ||
| filename: str | ||
| line: int | ||
| col: int | ||
| message: str | ||
|  | ||
| def __str__(self): | ||
| return f"{self.filename}:{self.line}:{self.col}: {self.message}" | ||
|  | ||
|  | ||
| class ImportChecker(ast.NodeVisitor): | ||
| """Checks that optional imports are only imported from .options module.""" | ||
|  | ||
| def __init__(self, filename: str): | ||
| self.filename = filename | ||
| self.violations: List[ImportViolation] = [] | ||
|  | ||
| def visit_If(self, node: ast.If): | ||
| # Always visit the condition, but ignore imports inside "if TYPE_CHECKING:" blocks | ||
| if getattr(node.test, "id", None) == "TYPE_CHECKING": | ||
| # Skip the body and orelse for TYPE_CHECKING blocks | ||
| pass | ||
| else: | ||
| self.generic_visit(node) | ||
|  | ||
| def visit_Import(self, node: ast.Import): | ||
| """Check import statements.""" | ||
| for alias in node.names: | ||
| self._check_import(alias.name, node.lineno, node.col_offset) | ||
| self.generic_visit(node) | ||
|  | ||
| def visit_ImportFrom(self, node: ast.ImportFrom): | ||
| """Check from...import statements.""" | ||
| if node.module: | ||
| # Check if importing from a checked module directly | ||
| for module in CHECKED_MODULES: | ||
| if node.module.startswith(module): | ||
| self.violations.append( | ||
| ImportViolation( | ||
| self.filename, | ||
| node.lineno, | ||
| node.col_offset, | ||
| f"Import from '{node.module}' is not allowed. Use 'from .options import {module}' instead", | ||
| ) | ||
| ) | ||
|  | ||
| # Check if importing checked modules from .options (this is allowed) | ||
| if node.module == ".options": | ||
| # This is the correct way to import these modules | ||
| pass | ||
| self.generic_visit(node) | ||
|  | ||
| def _check_import(self, module_name: str, line: int, col: int): | ||
| """Check if a module import is for checked modules and not from .options.""" | ||
| for module in CHECKED_MODULES: | ||
| if module_name.startswith(module): | ||
| self.violations.append( | ||
| ImportViolation( | ||
| self.filename, | ||
| line, | ||
| col, | ||
| f"Direct import of '{module_name}' is not allowed. Use 'from .options import {module}' instead", | ||
| ) | ||
| ) | ||
| break | ||
|  | ||
|  | ||
| def check_file(filename: str) -> List[ImportViolation]: | ||
| """Check a file for optional import violations.""" | ||
| try: | ||
| tree = ast.parse(Path(filename).read_text()) | ||
| except SyntaxError: | ||
| # gracefully handle syntax errors | ||
| return [] | ||
| checker = ImportChecker(filename) | ||
| checker.visit(tree) | ||
| return checker.violations | ||
|  | ||
|  | ||
| def main(): | ||
| """Main function for pre-commit hook.""" | ||
| parser = argparse.ArgumentParser( | ||
| description="Check that optional imports are only imported from .options module" | ||
| ) | ||
| parser.add_argument("filenames", nargs="*", help="Filenames to check") | ||
| parser.add_argument( | ||
| "--show-fixes", action="store_true", help="Show suggested fixes" | ||
| ) | ||
| args = parser.parse_args() | ||
|  | ||
| all_violations = [] | ||
| for filename in args.filenames: | ||
| if not filename.endswith(".py"): | ||
| continue | ||
| all_violations.extend(check_file(filename)) | ||
|  | ||
| # Show violations | ||
| if all_violations: | ||
| print("Optional import violations found:") | ||
| print() | ||
|  | ||
| for violation in all_violations: | ||
| print(f" {violation}") | ||
|  | ||
| if args.show_fixes: | ||
| print() | ||
| print("How to fix:") | ||
| print(" - Import optional modules only from .options module") | ||
| print(" - Example:") | ||
| print(" # CORRECT:") | ||
| print(" from .options import boto3, botocore, installed_boto") | ||
| print(" if installed_boto:") | ||
| print(" SigV4Auth = botocore.auth.SigV4Auth") | ||
| print() | ||
| print(" # INCORRECT:") | ||
| print(" import boto3") | ||
| print(" from botocore.auth import SigV4Auth") | ||
| print() | ||
| print( | ||
| " - This ensures the connector works in environments where optional libraries are not installed" | ||
| ) | ||
|  | ||
| print() | ||
| print(f"Found {len(all_violations)} violation(s)") | ||
| return 1 | ||
|  | ||
| return 0 | ||
|  | ||
|  | ||
| if __name__ == "__main__": | ||
| sys.exit(main()) | 
  
    
      This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
      Learn more about bidirectional Unicode characters
    
  
  
    
              
  
    
      This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
      Learn more about bidirectional Unicode characters
    
  
  
    
              
  
    
      This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
      Learn more about bidirectional Unicode characters
    
  
  
    
              
      
      Oops, something went wrong.
        
    
  
      
      Oops, something went wrong.
        
    
  
  Add this suggestion to a batch that can be applied as a single commit.
  This suggestion is invalid because no changes were made to the code.
  Suggestions cannot be applied while the pull request is closed.
  Suggestions cannot be applied while viewing a subset of changes.
  Only one suggestion per line can be applied in a batch.
  Add this suggestion to a batch that can be applied as a single commit.
  Applying suggestions on deleted lines is not supported.
  You must change the existing code in this line in order to create a valid suggestion.
  Outdated suggestions cannot be applied.
  This suggestion has been applied or marked resolved.
  Suggestions cannot be applied from pending reviews.
  Suggestions cannot be applied on multi-line comments.
  Suggestions cannot be applied while the pull request is queued to merge.
  Suggestion cannot be applied right now. Please check back later.
  
    
  
    
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
I think we should add separate logic for aioboto here, but use the same flag
SNOWFLAKE_NO_BOTO=1 pip install snowflake-connector-python[aio]