Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
48 commits
Select commit Hold shift + click to select a range
1b671e2
refactor, fix scoped session
Apr 9, 2021
d23ed8a
remove unused import
Apr 9, 2021
b5f0300
fix logger
Apr 9, 2021
022a3da
remove test_database, rename param
Apr 10, 2021
a3b32c4
fix exception formatting
Apr 10, 2021
663e6bd
simplify _session, execute
Apr 10, 2021
f8afbcc
fix is_postgres
Apr 10, 2021
62b9982
abstract away engine creation
Apr 10, 2021
da613be
fix pylint errors
Apr 10, 2021
4a593dd
rename _parse_command
Apr 12, 2021
6fcf7ed
rename _bind_params
Apr 12, 2021
a4989eb
wrap flask wrapper
Apr 12, 2021
e8827bf
factor out sanitizer
Apr 13, 2021
bd330a7
promote paramstyle and placeholders to instance variables
Apr 13, 2021
db4cce1
pass token type/value around
Apr 13, 2021
88adfb9
rename methods
Apr 13, 2021
a4a8810
move escape_verbatim_colons to constructor
Apr 13, 2021
f618840
reorder methods
Apr 13, 2021
9a153fe
use else
Apr 13, 2021
456cea5
escape args and kwargs in constructor
Apr 13, 2021
713368f
reorder methods
Apr 13, 2021
2187d95
refactor logger
Apr 13, 2021
758910e
fix style
Apr 13, 2021
32db777
factor out utility functions
Apr 13, 2021
1f62283
factor out session utility functions
Apr 13, 2021
c0534e2
factor out sql utility functions
Apr 13, 2021
37fba4f
remove underscore from util functions
Apr 13, 2021
e06131c
fix style
Apr 13, 2021
86f981f
reorder imports
Apr 13, 2021
67a7f0c
remove manual tests
Apr 13, 2021
839b1f1
add statement tests, rollback on error in autocommit
Apr 13, 2021
9302a1e
move operation check to Statement
Apr 14, 2021
f6912d2
use statement factory
Apr 14, 2021
08a6636
use remove instead of rollback
Apr 14, 2021
7f9b77c
rename _sanitized_statement
Apr 14, 2021
944934f
abstract away catch_warnings
Apr 14, 2021
006657e
remove BEGIN and COMMIT
Apr 14, 2021
36fb280
Revert "remove BEGIN and COMMIT"
Apr 14, 2021
a6668c0
rename methods
Apr 14, 2021
1440ae5
add docstrings
Apr 14, 2021
9e9cb0b
update cs50 docstrings
Apr 15, 2021
789bb40
use assertAlmostEqual
Apr 16, 2021
05a4d9d
enable autocommit by default
Apr 16, 2021
7bf7e16
avoid using sessions
Apr 16, 2021
0674b7c
delete transaction connection on failure
Apr 16, 2021
ff9e69f
Deploy with GitHub Actions
Jul 26, 2021
6aabf0c
Update sql.py
Jul 26, 2021
d0b3f99
Merge branch 'main' into refactor/scoped-session-fix
Jul 26, 2021
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 2 additions & 2 deletions setup.py
Original file line number Diff line number Diff line change
Expand Up @@ -10,11 +10,11 @@
"Topic :: Software Development :: Libraries :: Python Modules"
],
description="CS50 library for Python",
install_requires=["Flask>=1.0", "SQLAlchemy", "sqlparse", "termcolor"],
install_requires=["Flask>=1.0", "SQLAlchemy<2", "sqlparse", "termcolor"],
keywords="cs50",
name="cs50",
package_dir={"": "src"},
packages=["cs50"],
url="https://github.com/cs50/python-cs50",
version="6.0.5"
version="7.0.0"
)
23 changes: 4 additions & 19 deletions src/cs50/__init__.py
Original file line number Diff line number Diff line change
@@ -1,20 +1,5 @@
import logging
import os
import sys


# Disable cs50 logger by default
logging.getLogger("cs50").disabled = True

# Import cs50_*
from .cs50 import get_char, get_float, get_int, get_string
try:
from .cs50 import get_long
except ImportError:
pass

# Hook into flask importing
from . import flask

# Wrap SQLAlchemy
from .cs50 import get_float, get_int, get_string
from .sql import SQL
from ._logger import _setup_logger

_setup_logger()
66 changes: 66 additions & 0 deletions src/cs50/_engine.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,66 @@
import threading

from ._engine_util import create_engine


thread_local_data = threading.local()


class Engine:
"""Wraps a SQLAlchemy engine.
"""

def __init__(self, url):
self._engine = create_engine(url)

def get_transaction_connection(self):
"""
:returns: A new connection with autocommit disabled (to be used for transactions).
"""

_thread_local_connections()[self] = self._engine.connect().execution_options(
autocommit=False)
return self.get_existing_transaction_connection()

def get_connection(self):
"""
:returns: A new connection with autocommit enabled
"""

return self._engine.connect().execution_options(autocommit=True)

def get_existing_transaction_connection(self):
"""
:returns: The transaction connection bound to this Engine instance, if one exists, or None.
"""

return _thread_local_connections().get(self)

def close_transaction_connection(self):
"""Closes the transaction connection bound to this Engine instance, if one exists and
removes it.
"""

connection = self.get_existing_transaction_connection()
if connection:
connection.close()
del _thread_local_connections()[self]

def is_postgres(self):
return self._engine.dialect.name in {"postgres", "postgresql"}

def __getattr__(self, attr):
return getattr(self._engine, attr)

def _thread_local_connections():
"""
:returns: A thread local dict to keep track of transaction connection. If one does not exist,
creates one.
"""

try:
connections = thread_local_data.connections
except AttributeError:
connections = thread_local_data.connections = {}

return connections
43 changes: 43 additions & 0 deletions src/cs50/_engine_util.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,43 @@
"""Utility functions used by _session.py.
"""

import os
import sqlite3

import sqlalchemy

sqlite_url_prefix = "sqlite:///"


def create_engine(url, **kwargs):
"""Creates a new SQLAlchemy engine. If ``url`` is a URL for a SQLite database, makes sure that
the SQLite file exits and enables foreign key constraints.
"""

try:
engine = sqlalchemy.create_engine(url, **kwargs)
except sqlalchemy.exc.ArgumentError:
raise RuntimeError(f"invalid URL: {url}") from None

if _is_sqlite_url(url):
_assert_sqlite_file_exists(url)
sqlalchemy.event.listen(engine, "connect", _enable_sqlite_foreign_key_constraints)

return engine

def _is_sqlite_url(url):
return url.startswith(sqlite_url_prefix)


def _assert_sqlite_file_exists(url):
path = url[len(sqlite_url_prefix):]
if not os.path.exists(path):
raise RuntimeError(f"does not exist: {path}")
if not os.path.isfile(path):
raise RuntimeError(f"not a file: {path}")


def _enable_sqlite_foreign_key_constraints(dbapi_connection, _):
cursor = dbapi_connection.cursor()
cursor.execute("PRAGMA foreign_keys=ON")
cursor.close()
98 changes: 98 additions & 0 deletions src/cs50/_logger.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,98 @@
"""Sets up logging for the library.
"""

import logging
import os.path
import re
import sys
import traceback

import termcolor


def green(msg):
return _colored(msg, "green")


def red(msg):
return _colored(msg, "red")


def yellow(msg):
return _colored(msg, "yellow")


def _colored(msg, color):
return termcolor.colored(str(msg), color)


def _setup_logger():
_configure_default_logger()
_patch_root_handler_format_exception()
_configure_cs50_logger()
_patch_excepthook()


def _configure_default_logger():
"""Configures a default handler and formatter to prevent flask and werkzeug from adding theirs.
"""

logging.basicConfig(format="%(levelname)s: %(message)s", level=logging.DEBUG)


def _patch_root_handler_format_exception():
"""Patches formatException for the root handler to use ``_format_exception``.
"""

try:
formatter = logging.root.handlers[0].formatter
formatter.formatException = lambda exc_info: _format_exception(*exc_info)
except IndexError:
pass


def _configure_cs50_logger():
"""Disables the cs50 logger by default. Disables logging propagation to prevent messages from
being logged more than once. Sets the logging handler and formatter.
"""

_logger = logging.getLogger("cs50")
_logger.disabled = True
_logger.setLevel(logging.DEBUG)

# Log messages once
_logger.propagate = False

handler = logging.StreamHandler()
handler.setLevel(logging.DEBUG)

formatter = logging.Formatter("%(levelname)s: %(message)s")
formatter.formatException = lambda exc_info: _format_exception(*exc_info)
handler.setFormatter(formatter)
_logger.addHandler(handler)


def _patch_excepthook():
sys.excepthook = lambda type_, value, exc_tb: print(
_format_exception(type_, value, exc_tb), file=sys.stderr)


def _format_exception(type_, value, exc_tb):
"""Formats traceback, darkening entries from global site-packages directories and user-specific
site-packages directory.
https://stackoverflow.com/a/46071447/5156190
"""

# Absolute paths to site-packages
packages = tuple(os.path.join(os.path.abspath(p), "") for p in sys.path[1:])

# Highlight lines not referring to files in site-packages
lines = []
for line in traceback.format_exception(type_, value, exc_tb):
matches = re.search(r"^ File \"([^\"]+)\", line \d+, in .+", line)
if matches and matches.group(1).startswith(packages):
lines += line
else:
matches = re.search(r"^(\s*)(.*?)(\s*)$", line, re.DOTALL)
lines.append(matches.group(1) + yellow(matches.group(2)) + matches.group(3))
return "".join(lines).rstrip()
95 changes: 95 additions & 0 deletions src/cs50/_sql_sanitizer.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,95 @@
import datetime
import re

import sqlalchemy
import sqlparse


class SQLSanitizer:
"""Sanitizes SQL values.
"""

def __init__(self, dialect):
self._dialect = dialect

def escape(self, value):
"""Escapes value using engine's conversion function.
https://docs.sqlalchemy.org/en/latest/core/type_api.html#sqlalchemy.types.TypeEngine.literal_processor

:param value: The value to be sanitized

:returns: The sanitized value
"""
# pylint: disable=too-many-return-statements
if isinstance(value, (list, tuple)):
return self.escape_iterable(value)

if isinstance(value, bool):
return sqlparse.sql.Token(
sqlparse.tokens.Number,
sqlalchemy.types.Boolean().literal_processor(self._dialect)(value))

if isinstance(value, bytes):
if self._dialect.name in {"mysql", "sqlite"}:
# https://dev.mysql.com/doc/refman/8.0/en/hexadecimal-literals.html
return sqlparse.sql.Token(sqlparse.tokens.Other, f"x'{value.hex()}'")
if self._dialect.name in {"postgres", "postgresql"}:
# https://dba.stackexchange.com/a/203359
return sqlparse.sql.Token(sqlparse.tokens.Other, f"'\\x{value.hex()}'")

raise RuntimeError(f"unsupported value: {value}")

string_processor = sqlalchemy.types.String().literal_processor(self._dialect)
if isinstance(value, datetime.date):
return sqlparse.sql.Token(
sqlparse.tokens.String, string_processor(value.strftime("%Y-%m-%d")))

if isinstance(value, datetime.datetime):
return sqlparse.sql.Token(
sqlparse.tokens.String, string_processor(value.strftime("%Y-%m-%d %H:%M:%S")))

if isinstance(value, datetime.time):
return sqlparse.sql.Token(
sqlparse.tokens.String, string_processor(value.strftime("%H:%M:%S")))

if isinstance(value, float):
return sqlparse.sql.Token(
sqlparse.tokens.Number,
sqlalchemy.types.Float().literal_processor(self._dialect)(value))

if isinstance(value, int):
return sqlparse.sql.Token(
sqlparse.tokens.Number,
sqlalchemy.types.Integer().literal_processor(self._dialect)(value))

if isinstance(value, str):
return sqlparse.sql.Token(sqlparse.tokens.String, string_processor(value))

if value is None:
return sqlparse.sql.Token(
sqlparse.tokens.Keyword,
sqlalchemy.types.NullType().literal_processor(self._dialect)(value))

raise RuntimeError(f"unsupported value: {value}")

def escape_iterable(self, iterable):
"""Escapes each value in iterable and joins all the escaped values with ", ", formatted for
SQL's ``IN`` operator.

:param: An iterable of values to be escaped

:returns: A comma-separated list of escaped values from ``iterable``
:rtype: :class:`sqlparse.sql.TokenList`
"""

return sqlparse.sql.TokenList(
sqlparse.parse(", ".join([str(self.escape(v)) for v in iterable])))


def escape_verbatim_colon(value):
"""Escapes verbatim colon from a value so as it is not confused with a parameter marker.
"""

# E.g., ':foo, ":foo, :foo will be replaced with
# '\:foo, "\:foo, \:foo respectively
return re.sub(r"(^(?:'|\")|\s+):", r"\1\:", value)
51 changes: 51 additions & 0 deletions src/cs50/_sql_util.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,51 @@
"""Utility functions used by sql.py.
"""

import contextlib
import decimal
import warnings

import sqlalchemy


def process_select_result(result):
"""Converts a SQLAlchemy result to a ``list`` of ``dict`` objects, each of which represents a
row in the result set.

:param result: A SQLAlchemy result
:type result: :class:`sqlalchemy.engine.Result`
"""
rows = [dict(row) for row in result.fetchall()]
for row in rows:
for column in row:
# Coerce decimal.Decimal objects to float objects
# https://groups.google.com/d/msg/sqlalchemy/0qXMYJvq8SA/oqtvMD9Uw-kJ
if isinstance(row[column], decimal.Decimal):
row[column] = float(row[column])

# Coerce memoryview objects (as from PostgreSQL's bytea columns) to bytes
elif isinstance(row[column], memoryview):
row[column] = bytes(row[column])

return rows


@contextlib.contextmanager
def raise_errors_for_warnings():
"""Catches warnings and raises errors instead.
"""

with warnings.catch_warnings():
warnings.simplefilter("error")
yield


def postgres_lastval(connection):
"""
:returns: The ID of the last inserted row, if defined in this session, or None
"""

try:
return connection.execute("SELECT LASTVAL()").first()[0]
except sqlalchemy.exc.OperationalError:
return None
Loading