Skip to content

Commit

Permalink
Initial commit
Browse files Browse the repository at this point in the history
Signed-off-by: Mike Fiedler <[email protected]>
  • Loading branch information
miketheman committed Apr 15, 2023
0 parents commit b3fdcff
Show file tree
Hide file tree
Showing 19 changed files with 626 additions and 0 deletions.
16 changes: 16 additions & 0 deletions .editorconfig
Original file line number Diff line number Diff line change
@@ -0,0 +1,16 @@
# http://editorconfig.org

root = true

[*]
indent_style = space
insert_final_newline = true
trim_trailing_whitespace = true
end_of_line = lf
charset = utf-8

[*.py]
indent_size = 4

[*.{md,toml,yml,yaml}]
indent_size = 2
3 changes: 3 additions & 0 deletions .flake8
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
[flake8]
max-line-length = 88
extend-ignore = E203
160 changes: 160 additions & 0 deletions .gitignore
Original file line number Diff line number Diff line change
@@ -0,0 +1,160 @@
# Byte-compiled / optimized / DLL files
__pycache__/
*.py[cod]
*$py.class

# C extensions
*.so

# Distribution / packaging
.Python
build/
develop-eggs/
dist/
downloads/
eggs/
.eggs/
lib/
lib64/
parts/
sdist/
var/
wheels/
share/python-wheels/
*.egg-info/
.installed.cfg
*.egg
MANIFEST

# PyInstaller
# Usually these files are written by a python script from a template
# before PyInstaller builds the exe, so as to inject date/other infos into it.
*.manifest
*.spec

# Installer logs
pip-log.txt
pip-delete-this-directory.txt

# Unit test / coverage reports
htmlcov/
.tox/
.nox/
.coverage
.coverage.*
.cache
nosetests.xml
coverage.xml
*.cover
*.py,cover
.hypothesis/
.pytest_cache/
cover/

# Translations
*.mo
*.pot

# Django stuff:
*.log
local_settings.py
db.sqlite3
db.sqlite3-journal

# Flask stuff:
instance/
.webassets-cache

# Scrapy stuff:
.scrapy

# Sphinx documentation
docs/_build/

# PyBuilder
.pybuilder/
target/

# Jupyter Notebook
.ipynb_checkpoints

# IPython
profile_default/
ipython_config.py

# pyenv
# For a library or package, you might want to ignore these files since the code is
# intended to run in multiple environments; otherwise, check them in:
.python-version

# pipenv
# According to pypa/pipenv#598, it is recommended to include Pipfile.lock in version control.
# However, in case of collaboration, if having platform-specific dependencies or dependencies
# having no cross-platform support, pipenv may install dependencies that don't work, or not
# install all needed dependencies.
#Pipfile.lock

# poetry
# Similar to Pipfile.lock, it is generally recommended to include poetry.lock in version control.
# This is especially recommended for binary packages to ensure reproducibility, and is more
# commonly ignored for libraries.
# https://python-poetry.org/docs/basic-usage/#commit-your-poetrylock-file-to-version-control
poetry.lock

# pdm
# Similar to Pipfile.lock, it is generally recommended to include pdm.lock in version control.
#pdm.lock
# pdm stores project-wide configurations in .pdm.toml, but it is recommended to not include it
# in version control.
# https://pdm.fming.dev/#use-with-ide
.pdm.toml

# PEP 582; used by e.g. github.com/David-OConnor/pyflow and github.com/pdm-project/pdm
__pypackages__/

# Celery stuff
celerybeat-schedule
celerybeat.pid

# SageMath parsed files
*.sage.py

# Environments
.env
.venv
env/
venv/
ENV/
env.bak/
venv.bak/

# Spyder project settings
.spyderproject
.spyproject

# Rope project settings
.ropeproject

# mkdocs documentation
/site

# mypy
.mypy_cache/
.dmypy.json
dmypy.json

# Pyre type checker
.pyre/

# pytype static type analyzer
.pytype/

# Cython debug symbols
cython_debug/

# PyCharm
# JetBrains specific template is maintained in a separate JetBrains.gitignore that can
# be found at https://github.com/github/gitignore/blob/main/Global/JetBrains.gitignore
# and can be added to the global gitignore or merged into this file. For a more nuclear
# option (not recommended) you can uncomment the following to ignore the entire idea folder.
#.idea/
35 changes: 35 additions & 0 deletions .pre-commit-config.yaml
Original file line number Diff line number Diff line change
@@ -0,0 +1,35 @@
# See https://pre-commit.com for more information
# See https://pre-commit.com/hooks.html for more hooks
repos:
- repo: https://github.com/pre-commit/pre-commit-hooks
rev: v4.4.0
hooks:
- id: check-yaml
- id: check-added-large-files
- repo: https://github.com/editorconfig-checker/editorconfig-checker.python
rev: '2.7.1'
hooks:
- id: editorconfig-checker
alias: ec
- repo: https://github.com/pycqa/flake8
rev: '6.0.0'
hooks:
- id: flake8
- repo: https://github.com/pycqa/isort
rev: 5.12.0
hooks:
- id: isort
name: isort (python)
- repo: https://github.com/psf/black
rev: 23.3.0
hooks:
- id: black
- repo: https://github.com/asottile/pyupgrade
rev: v3.3.1
hooks:
- id: pyupgrade
args: [--py38-plus]
- repo: https://github.com/jendrikseipp/vulture
rev: 'v2.7'
hooks:
- id: vulture
21 changes: 21 additions & 0 deletions LICENSE.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
# MIT License

Copyright (c) 2023 Mike Fiedler

Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
85 changes: 85 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,85 @@
# flake8-SQAlchemy

[![PyPI current version](https://img.shields.io/pypi/v/flake8-sqlalchemy.svg)](https://pypi.python.org/pypi/flake8-sqlalchemy)
[![Python Support](https://img.shields.io/pypi/pyversions/flake8-sqlalchemy.svg)](https://pypi.python.org/pypi/flake8-sqlalchemy)
[![pre-commit.ci status](https://results.pre-commit.ci/badge/github/miketheman/flake8-sqlalchemy/main.svg)](https://results.pre-commit.ci/latest/github/miketheman/flake8-sqlalchemy/main)
[![Code style: black](https://img.shields.io/badge/code%20style-black-000000.svg)](https://github.com/psf/black)

A flake8 plugin for SQLAlchemy code.

## Installation

```bash
pip install flake8-sqlalchemy
```

## Configuration

By default, all checks are enabled.
You can disable **all** checks by adding the following to your `setup.cfg`:

```ini
[flake8]
ignore = SQA
```

or ignore specific checks:

```ini
[flake8]
ignore = SQA100
```

### `SQA100` - `sqlalchemy` import alias

Checks that when `sqlalchemy` is imported with an alias,
the alias is either `sa` or `db`.

#### Bad

```python
import sqlalchemy as foo
```

#### Good

```python
import sqlalchemy as sa
# or
import sqlalchemy as db
```

### `SQA200` - `Column` keyword argument `comment` required

When writing a `Column` definition the `comment` keyword argument is required.
This provides inline documentation for the column,
as well as generating the SQL to add the comment to the database.

#### Bad

```python
class Users(Base):
__tablename__ = "users"

id = Column(Integer, primary_key=True)
name = Column(String)
```

#### Good

```python
class Users(Base):
__tablename__ = "users"

id = Column(Integer, primary_key=True, comment="User ID from Auth Service")
name = Column(String, comment="User name: first, middle, last")
```

## License

This project is licensed under the terms of the MIT license.
See the [LICENSE](LICENSE.md) file for the full license text.

## Author

- [Mike Fiedler](https://github.com/miketheman)
4 changes: 4 additions & 0 deletions flake8_sqlalchemy/__init__.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,4 @@
from .plugin import Plugin

__version__ = "0.3.0"
__all__ = ("Plugin",)
7 changes: 7 additions & 0 deletions flake8_sqlalchemy/checkers/__init__.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
from .column_comment import ColumnCommentChecker
from .import_alias import ImportAliasChecker

__all__ = (
"ColumnCommentChecker",
"ImportAliasChecker",
)
18 changes: 18 additions & 0 deletions flake8_sqlalchemy/checkers/_base.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,18 @@
import ast
from typing import Any, List

from ..issue import Issue


class Checker:
@staticmethod
def get_call_name(node: ast.Call) -> str:
if isinstance(node.func, ast.Attribute):
return node.func.attr
if isinstance(node.func, ast.Name):
return node.func.id
# Fallthrough for any unknown conditions. Eventually remove this.
raise Exception(f"Unknown node.func type for {node.func}") # pragma: no cover

def run(self, node: Any) -> List[Issue]: # TODO correct type hint
raise NotImplementedError
40 changes: 40 additions & 0 deletions flake8_sqlalchemy/checkers/column_comment.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,40 @@
"""Checks that Columns have comments."""

import ast
from typing import List

from ..issue import Issue
from ._base import Checker


class SQA200(Issue):
code = "SQA200"
message = f"{code} Column missing comment keyword argument"


class ColumnCommentChecker(Checker):
def run(self, node: ast.Call) -> List[Issue]:
"""
Checks if a `sqlalchemy.Column` is missing a `comment` keyword argument.
"""
issues: List[Issue] = []

if self.is_column(node) and not self.has_comment(node):
issues.append(SQA200(node.lineno, node.col_offset))

return issues

def is_column(self, node: ast.Call) -> bool:
call_name = self.get_call_name(node)
if call_name == "Column":
return True
return False

def has_comment(self, node: ast.Call) -> bool:
return self.has_keyword(node, "comment")

def has_keyword(self, node: ast.Call, keyword: str) -> bool:
for keyword_node in node.keywords:
if keyword_node.arg == keyword:
return True
return False
Loading

0 comments on commit b3fdcff

Please sign in to comment.