Skip to content

Commit

Permalink
add old codes for sqlalchemy v1/pydantic v1
Browse files Browse the repository at this point in the history
  • Loading branch information
honglei committed Oct 17, 2023
1 parent 7d99be6 commit 968f495
Show file tree
Hide file tree
Showing 19 changed files with 2,591 additions and 0 deletions.
698 changes: 698 additions & 0 deletions sqlmodel/main.py.bak

Large diffs are not rendered by default.

139 changes: 139 additions & 0 deletions sqlmodel/v1/__init__.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,139 @@
__version__ = "0.0.8"

# Re-export from SQLAlchemy
from sqlalchemy.engine import create_mock_engine as create_mock_engine
from sqlalchemy.engine import engine_from_config as engine_from_config
from sqlalchemy.inspection import inspect as inspect
from sqlalchemy.schema import BLANK_SCHEMA as BLANK_SCHEMA
from sqlalchemy.schema import CheckConstraint as CheckConstraint
from sqlalchemy.schema import Column as Column
from sqlalchemy.schema import ColumnDefault as ColumnDefault
from sqlalchemy.schema import Computed as Computed
from sqlalchemy.schema import Constraint as Constraint
from sqlalchemy.schema import DDL as DDL
from sqlalchemy.schema import DefaultClause as DefaultClause
from sqlalchemy.schema import FetchedValue as FetchedValue
from sqlalchemy.schema import ForeignKey as ForeignKey
from sqlalchemy.schema import ForeignKeyConstraint as ForeignKeyConstraint
from sqlalchemy.schema import Identity as Identity
from sqlalchemy.schema import Index as Index
from sqlalchemy.schema import MetaData as MetaData
from sqlalchemy.schema import PrimaryKeyConstraint as PrimaryKeyConstraint
from sqlalchemy.schema import Sequence as Sequence
from sqlalchemy.schema import Table as Table
from sqlalchemy.schema import ThreadLocalMetaData as ThreadLocalMetaData
from sqlalchemy.schema import UniqueConstraint as UniqueConstraint
from sqlalchemy.sql import alias as alias
from sqlalchemy.sql import all_ as all_
from sqlalchemy.sql import and_ as and_
from sqlalchemy.sql import any_ as any_
from sqlalchemy.sql import asc as asc
from sqlalchemy.sql import between as between
from sqlalchemy.sql import bindparam as bindparam
from sqlalchemy.sql import case as case
from sqlalchemy.sql import cast as cast
from sqlalchemy.sql import collate as collate
from sqlalchemy.sql import column as column
from sqlalchemy.sql import delete as delete
from sqlalchemy.sql import desc as desc
from sqlalchemy.sql import distinct as distinct
from sqlalchemy.sql import except_ as except_
from sqlalchemy.sql import except_all as except_all
from sqlalchemy.sql import exists as exists
from sqlalchemy.sql import extract as extract
from sqlalchemy.sql import false as false
from sqlalchemy.sql import func as func
from sqlalchemy.sql import funcfilter as funcfilter
from sqlalchemy.sql import insert as insert
from sqlalchemy.sql import intersect as intersect
from sqlalchemy.sql import intersect_all as intersect_all
from sqlalchemy.sql import join as join
from sqlalchemy.sql import LABEL_STYLE_DEFAULT as LABEL_STYLE_DEFAULT
from sqlalchemy.sql import (
LABEL_STYLE_DISAMBIGUATE_ONLY as LABEL_STYLE_DISAMBIGUATE_ONLY,
)
from sqlalchemy.sql import LABEL_STYLE_NONE as LABEL_STYLE_NONE
from sqlalchemy.sql import (
LABEL_STYLE_TABLENAME_PLUS_COL as LABEL_STYLE_TABLENAME_PLUS_COL,
)
from sqlalchemy.sql import lambda_stmt as lambda_stmt
from sqlalchemy.sql import lateral as lateral
from sqlalchemy.sql import literal as literal
from sqlalchemy.sql import literal_column as literal_column
from sqlalchemy.sql import modifier as modifier
from sqlalchemy.sql import not_ as not_
from sqlalchemy.sql import null as null
from sqlalchemy.sql import nulls_first as nulls_first
from sqlalchemy.sql import nulls_last as nulls_last
from sqlalchemy.sql import nullsfirst as nullsfirst
from sqlalchemy.sql import nullslast as nullslast
from sqlalchemy.sql import or_ as or_
from sqlalchemy.sql import outerjoin as outerjoin
from sqlalchemy.sql import outparam as outparam
from sqlalchemy.sql import over as over
from sqlalchemy.sql import subquery as subquery
from sqlalchemy.sql import table as table
from sqlalchemy.sql import tablesample as tablesample
from sqlalchemy.sql import text as text
from sqlalchemy.sql import true as true
from sqlalchemy.sql import tuple_ as tuple_
from sqlalchemy.sql import type_coerce as type_coerce
from sqlalchemy.sql import union as union
from sqlalchemy.sql import union_all as union_all
from sqlalchemy.sql import update as update
from sqlalchemy.sql import values as values
from sqlalchemy.sql import within_group as within_group
from sqlalchemy.types import ARRAY as ARRAY
from sqlalchemy.types import BIGINT as BIGINT
from sqlalchemy.types import BigInteger as BigInteger
from sqlalchemy.types import BINARY as BINARY
from sqlalchemy.types import BLOB as BLOB
from sqlalchemy.types import BOOLEAN as BOOLEAN
from sqlalchemy.types import Boolean as Boolean
from sqlalchemy.types import CHAR as CHAR
from sqlalchemy.types import CLOB as CLOB
from sqlalchemy.types import DATE as DATE
from sqlalchemy.types import Date as Date
from sqlalchemy.types import DATETIME as DATETIME
from sqlalchemy.types import DateTime as DateTime
from sqlalchemy.types import DECIMAL as DECIMAL
from sqlalchemy.types import Enum as Enum
from sqlalchemy.types import FLOAT as FLOAT
from sqlalchemy.types import Float as Float
from sqlalchemy.types import INT as INT
from sqlalchemy.types import INTEGER as INTEGER
from sqlalchemy.types import Integer as Integer
from sqlalchemy.types import Interval as Interval
from sqlalchemy.types import JSON as JSON
from sqlalchemy.types import LargeBinary as LargeBinary
from sqlalchemy.types import NCHAR as NCHAR
from sqlalchemy.types import NUMERIC as NUMERIC
from sqlalchemy.types import Numeric as Numeric
from sqlalchemy.types import NVARCHAR as NVARCHAR
from sqlalchemy.types import PickleType as PickleType
from sqlalchemy.types import REAL as REAL
from sqlalchemy.types import SMALLINT as SMALLINT
from sqlalchemy.types import SmallInteger as SmallInteger
from sqlalchemy.types import String as String
from sqlalchemy.types import TEXT as TEXT
from sqlalchemy.types import Text as Text
from sqlalchemy.types import TIME as TIME
from sqlalchemy.types import Time as Time
from sqlalchemy.types import TIMESTAMP as TIMESTAMP
from sqlalchemy.types import TypeDecorator as TypeDecorator
from sqlalchemy.types import Unicode as Unicode
from sqlalchemy.types import UnicodeText as UnicodeText
from sqlalchemy.types import VARBINARY as VARBINARY
from sqlalchemy.types import VARCHAR as VARCHAR

# Extensions and modifications of SQLAlchemy in SQLModel
from .engine.create import create_engine as create_engine
from .orm.session import Session as Session
from .sql.expression import select as select
from .sql.expression import col as col
from .sql.sqltypes import AutoString as AutoString

# Export SQLModel specifics (equivalent to Pydantic)
from .main import SQLModel as SQLModel
from .main import Field as Field
from .main import Relationship as Relationship
32 changes: 32 additions & 0 deletions sqlmodel/v1/default.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,32 @@
from typing import Any, TypeVar


class _DefaultPlaceholder:
"""
You shouldn't use this class directly.
It's used internally to recognize when a default value has been overwritten, even
if the overriden default value was truthy.
"""

def __init__(self, value: Any):
self.value = value

def __bool__(self) -> bool:
return bool(self.value)

def __eq__(self, o: object) -> bool:
return isinstance(o, _DefaultPlaceholder) and o.value == self.value


_TDefaultType = TypeVar("_TDefaultType")


def Default(value: _TDefaultType) -> _TDefaultType:
"""
You shouldn't use this function directly.
It's used internally to recognize when a default value has been overwritten, even
if the overriden default value was truthy.
"""
return _DefaultPlaceholder(value) # type: ignore
Empty file added sqlmodel/v1/engine/__init__.py
Empty file.
139 changes: 139 additions & 0 deletions sqlmodel/v1/engine/create.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,139 @@
import json
import sqlite3
from typing import Any, Callable, Dict, List, Optional, Type, Union

from sqlalchemy import create_engine as _create_engine
from sqlalchemy.engine.url import URL
from sqlalchemy.future import Engine as _FutureEngine
from sqlalchemy.pool import Pool
from typing_extensions import Literal, TypedDict

from ..default import Default, _DefaultPlaceholder

# Types defined in sqlalchemy2-stubs, but can't be imported, so re-define here

_Debug = Literal["debug"]

_IsolationLevel = Literal[
"SERIALIZABLE",
"REPEATABLE READ",
"READ COMMITTED",
"READ UNCOMMITTED",
"AUTOCOMMIT",
]
_ParamStyle = Literal["qmark", "numeric", "named", "format", "pyformat"]
_ResetOnReturn = Literal["rollback", "commit"]


class _SQLiteConnectArgs(TypedDict, total=False):
timeout: float
detect_types: Any
isolation_level: Optional[Literal["DEFERRED", "IMMEDIATE", "EXCLUSIVE"]]
check_same_thread: bool
factory: Type[sqlite3.Connection]
cached_statements: int
uri: bool


_ConnectArgs = Union[_SQLiteConnectArgs, Dict[str, Any]]


# Re-define create_engine to have by default future=True, and assume that's what is used
# Also show the default values used for each parameter, but don't set them unless
# explicitly passed as arguments by the user to prevent errors. E.g. SQLite doesn't
# support pool connection arguments.
def create_engine(
url: Union[str, URL],
*,
connect_args: _ConnectArgs = Default({}), # type: ignore
echo: Union[bool, _Debug] = Default(False),
echo_pool: Union[bool, _Debug] = Default(False),
enable_from_linting: bool = Default(True),
encoding: str = Default("utf-8"),
execution_options: Dict[Any, Any] = Default({}),
future: bool = True,
hide_parameters: bool = Default(False),
implicit_returning: bool = Default(True),
isolation_level: Optional[_IsolationLevel] = Default(None),
json_deserializer: Callable[..., Any] = Default(json.loads),
json_serializer: Callable[..., Any] = Default(json.dumps),
label_length: Optional[int] = Default(None),
logging_name: Optional[str] = Default(None),
max_identifier_length: Optional[int] = Default(None),
max_overflow: int = Default(10),
module: Optional[Any] = Default(None),
paramstyle: Optional[_ParamStyle] = Default(None),
pool: Optional[Pool] = Default(None),
poolclass: Optional[Type[Pool]] = Default(None),
pool_logging_name: Optional[str] = Default(None),
pool_pre_ping: bool = Default(False),
pool_size: int = Default(5),
pool_recycle: int = Default(-1),
pool_reset_on_return: Optional[_ResetOnReturn] = Default("rollback"),
pool_timeout: float = Default(30),
pool_use_lifo: bool = Default(False),
plugins: Optional[List[str]] = Default(None),
query_cache_size: Optional[int] = Default(None),
**kwargs: Any,
) -> _FutureEngine:
current_kwargs: Dict[str, Any] = {
"future": future,
}
if not isinstance(echo, _DefaultPlaceholder):
current_kwargs["echo"] = echo
if not isinstance(echo_pool, _DefaultPlaceholder):
current_kwargs["echo_pool"] = echo_pool
if not isinstance(enable_from_linting, _DefaultPlaceholder):
current_kwargs["enable_from_linting"] = enable_from_linting
if not isinstance(connect_args, _DefaultPlaceholder):
current_kwargs["connect_args"] = connect_args
if not isinstance(encoding, _DefaultPlaceholder):
current_kwargs["encoding"] = encoding
if not isinstance(execution_options, _DefaultPlaceholder):
current_kwargs["execution_options"] = execution_options
if not isinstance(hide_parameters, _DefaultPlaceholder):
current_kwargs["hide_parameters"] = hide_parameters
if not isinstance(implicit_returning, _DefaultPlaceholder):
current_kwargs["implicit_returning"] = implicit_returning
if not isinstance(isolation_level, _DefaultPlaceholder):
current_kwargs["isolation_level"] = isolation_level
if not isinstance(json_deserializer, _DefaultPlaceholder):
current_kwargs["json_deserializer"] = json_deserializer
if not isinstance(json_serializer, _DefaultPlaceholder):
current_kwargs["json_serializer"] = json_serializer
if not isinstance(label_length, _DefaultPlaceholder):
current_kwargs["label_length"] = label_length
if not isinstance(logging_name, _DefaultPlaceholder):
current_kwargs["logging_name"] = logging_name
if not isinstance(max_identifier_length, _DefaultPlaceholder):
current_kwargs["max_identifier_length"] = max_identifier_length
if not isinstance(max_overflow, _DefaultPlaceholder):
current_kwargs["max_overflow"] = max_overflow
if not isinstance(module, _DefaultPlaceholder):
current_kwargs["module"] = module
if not isinstance(paramstyle, _DefaultPlaceholder):
current_kwargs["paramstyle"] = paramstyle
if not isinstance(pool, _DefaultPlaceholder):
current_kwargs["pool"] = pool
if not isinstance(poolclass, _DefaultPlaceholder):
current_kwargs["poolclass"] = poolclass
if not isinstance(pool_logging_name, _DefaultPlaceholder):
current_kwargs["pool_logging_name"] = pool_logging_name
if not isinstance(pool_pre_ping, _DefaultPlaceholder):
current_kwargs["pool_pre_ping"] = pool_pre_ping
if not isinstance(pool_size, _DefaultPlaceholder):
current_kwargs["pool_size"] = pool_size
if not isinstance(pool_recycle, _DefaultPlaceholder):
current_kwargs["pool_recycle"] = pool_recycle
if not isinstance(pool_reset_on_return, _DefaultPlaceholder):
current_kwargs["pool_reset_on_return"] = pool_reset_on_return
if not isinstance(pool_timeout, _DefaultPlaceholder):
current_kwargs["pool_timeout"] = pool_timeout
if not isinstance(pool_use_lifo, _DefaultPlaceholder):
current_kwargs["pool_use_lifo"] = pool_use_lifo
if not isinstance(plugins, _DefaultPlaceholder):
current_kwargs["plugins"] = plugins
if not isinstance(query_cache_size, _DefaultPlaceholder):
current_kwargs["query_cache_size"] = query_cache_size
current_kwargs.update(kwargs)
return _create_engine(url, **current_kwargs) # type: ignore
79 changes: 79 additions & 0 deletions sqlmodel/v1/engine/result.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,79 @@
from typing import Generic, Iterator, List, Optional, TypeVar

from sqlalchemy.engine.result import Result as _Result
from sqlalchemy.engine.result import ScalarResult as _ScalarResult

_T = TypeVar("_T")


class ScalarResult(_ScalarResult, Generic[_T]):
def all(self) -> List[_T]:
return super().all()

def partitions(self, size: Optional[int] = None) -> Iterator[List[_T]]:
return super().partitions(size)

def fetchall(self) -> List[_T]:
return super().fetchall()

def fetchmany(self, size: Optional[int] = None) -> List[_T]:
return super().fetchmany(size)

def __iter__(self) -> Iterator[_T]:
return super().__iter__()

def __next__(self) -> _T:
return super().__next__() # type: ignore

def first(self) -> Optional[_T]:
return super().first()

def one_or_none(self) -> Optional[_T]:
return super().one_or_none()

def one(self) -> _T:
return super().one() # type: ignore


class Result(_Result, Generic[_T]):
def scalars(self, index: int = 0) -> ScalarResult[_T]:
return super().scalars(index) # type: ignore

def __iter__(self) -> Iterator[_T]: # type: ignore
return super().__iter__() # type: ignore

def __next__(self) -> _T: # type: ignore
return super().__next__() # type: ignore

def partitions(self, size: Optional[int] = None) -> Iterator[List[_T]]: # type: ignore
return super().partitions(size) # type: ignore

def fetchall(self) -> List[_T]: # type: ignore
return super().fetchall() # type: ignore

def fetchone(self) -> Optional[_T]: # type: ignore
return super().fetchone() # type: ignore

def fetchmany(self, size: Optional[int] = None) -> List[_T]: # type: ignore
return super().fetchmany() # type: ignore

def all(self) -> List[_T]: # type: ignore
return super().all() # type: ignore

def first(self) -> Optional[_T]: # type: ignore
return super().first() # type: ignore

def one_or_none(self) -> Optional[_T]: # type: ignore
return super().one_or_none() # type: ignore

def scalar_one(self) -> _T:
return super().scalar_one() # type: ignore

def scalar_one_or_none(self) -> Optional[_T]:
return super().scalar_one_or_none()

def one(self) -> _T: # type: ignore
return super().one() # type: ignore

def scalar(self) -> Optional[_T]:
return super().scalar()
Empty file added sqlmodel/v1/ext/__init__.py
Empty file.
Empty file.
Loading

0 comments on commit 968f495

Please sign in to comment.