|
| 1 | +# Introduction |
| 2 | + |
| 3 | +[简体中文](https://github.com/amisadmin/sqlalchemy_database/blob/master/README.zh.md) |
| 4 | +| [English](https://github.com/amisadmin/sqlalchemy_database) |
| 5 | + |
| 6 | +<h2 align="center"> |
| 7 | + SQLAlchemy-Database |
| 8 | +</h2> |
| 9 | +<p align="center"> |
| 10 | + <em>SQLAlchemy-Database provides shortcut functions to common database operations for SQLAlchemy ORM.</em><br/> |
| 11 | +</p> |
| 12 | +<p align="center"> |
| 13 | + <a href="https://github.com/amisadmin/sqlalchemy_database/actions/workflows/pytest.yml" target="_blank"> |
| 14 | + <img src="https://github.com/amisadmin/sqlalchemy_database/actions/workflows/pytest.yml/badge.svg" alt="Pytest"> |
| 15 | + </a> |
| 16 | + <a href="https://codecov.io/gh/amisadmin/sqlalchemy_database" > |
| 17 | + <img src="https://codecov.io/gh/amisadmin/sqlalchemy_database/branch/master/graph/badge.svg?token=SKOGAKIX4M" alt="codecov"/> |
| 18 | + </a> |
| 19 | + <a href="https://pypi.org/project/sqlalchemy_database" target="_blank"> |
| 20 | + <img src="https://badgen.net/pypi/v/sqlalchemy_database?color=blue" alt="Package version"> |
| 21 | + </a> |
| 22 | + <a href="https://gitter.im/amisadmin/fastapi-amis-admin"> |
| 23 | + <img src="https://badges.gitter.im/amisadmin/fastapi-amis-admin.svg" alt="Chat on Gitter"/> |
| 24 | + </a> |
| 25 | + <a href="https://jq.qq.com/?_wv=1027&k=U4Dv6x8W" target="_blank"> |
| 26 | + <img src="https://badgen.net/badge/qq%E7%BE%A4/229036692/orange" alt="229036692"> |
| 27 | + </a> |
| 28 | +</p> |
| 29 | + |
| 30 | +## Introduction |
| 31 | + |
| 32 | +- Support `SQLAlchemy` and `SQLModel`,recommend using `SQLModel`. |
| 33 | + |
| 34 | +## Install |
| 35 | + |
| 36 | +```bash |
| 37 | +pip install sqlalchemy-database |
| 38 | +``` |
| 39 | + |
| 40 | +## ORM Model |
| 41 | + |
| 42 | +### SQLAlchemy Model Sample |
| 43 | + |
| 44 | +```python |
| 45 | +import datetime |
| 46 | + |
| 47 | +import sqlalchemy as sa |
| 48 | +from sqlalchemy.orm import declarative_base |
| 49 | + |
| 50 | +Base = declarative_base() |
| 51 | + |
| 52 | + |
| 53 | +class User(Base): |
| 54 | + __tablename__ = "User" |
| 55 | + id = sa.Column(sa.Integer, primary_key=True) |
| 56 | + username = sa.Column(sa.String(30), unique=True, index=True, nullable=False) |
| 57 | + password = sa.Column(sa.String(30), default='') |
| 58 | + create_time = sa.Column(sa.DateTime, default=datetime.datetime.utcnow) |
| 59 | +``` |
| 60 | + |
| 61 | +### SQLModel Model Sample |
| 62 | + |
| 63 | +```python |
| 64 | +import datetime |
| 65 | + |
| 66 | +from sqlmodel import SQLModel, Field |
| 67 | + |
| 68 | + |
| 69 | +class User(SQLModel, table=True): |
| 70 | + id: int = Field(default=None, primary_key=True, nullable=False) |
| 71 | + username: str = Field(title='username', sa_column=Column(String(100), unique=True, index=True, nullable=False)) |
| 72 | + password: str = Field(default='', title='Password') |
| 73 | + create_time: datetime = Field(default_factory=datetime.utcnow, title='Create Time') |
| 74 | +``` |
| 75 | + |
| 76 | +## AsyncDatabase |
| 77 | + |
| 78 | +### Creation Connection |
| 79 | + |
| 80 | +```python |
| 81 | +from sqlalchemy_database import AsyncDatabase |
| 82 | + |
| 83 | +# 1.Create an asynchronous database connection |
| 84 | +db = AsyncDatabase.create('sqlite+aiosqlite:///amisadmin.db?check_same_thread=False') # sqlite |
| 85 | +# db = AsyncDatabase.create('mysql+aiomysql://root:123456@127.0.0.1:3306/amisadmin?charset=utf8mb4')# mysql |
| 86 | +# db = AsyncDatabase.create('postgresql+asyncpg://postgres:root@127.0.0.1:5432/amisadmin')# postgresql |
| 87 | + |
| 88 | +``` |
| 89 | + |
| 90 | +### Shortcut functions |
| 91 | + |
| 92 | +```python |
| 93 | +from sqlalchemy import insert, select, update, delete |
| 94 | + |
| 95 | + |
| 96 | +async def fast_execute(): |
| 97 | + # update |
| 98 | + stmt = update(User).where(User.id == 1).values({'username': 'new_user'}) |
| 99 | + result = await db.execute(stmt) |
| 100 | + |
| 101 | + # select |
| 102 | + stmt = select(User).where(User.id == 1) |
| 103 | + user = await db.execute(stmt, on_close_pre=lambda r: r.scalar()) |
| 104 | + |
| 105 | + # insert |
| 106 | + stmt = insert(User).values({'username': 'User-6', 'password': 'password-6'}) |
| 107 | + result = await db.execute(stmt) |
| 108 | + |
| 109 | + # delete |
| 110 | + stmt = delete(User).where(User.id == 6) |
| 111 | + result = await db.execute(stmt) |
| 112 | + |
| 113 | + # scalar |
| 114 | + user = await db.scalar(select(User).where(User.id == 1)) |
| 115 | + |
| 116 | + # scalars_all |
| 117 | + stmt = select(User) |
| 118 | + result = await db.scalars_all(stmt) |
| 119 | + |
| 120 | + # get |
| 121 | + user = await db.get(User, 1) |
| 122 | + |
| 123 | + # delete |
| 124 | + user = User(id=1, name='test') |
| 125 | + await db.delete(user) |
| 126 | + |
| 127 | + # save(insert or update) |
| 128 | + user = User(name='new_user') |
| 129 | + await db.save(user) |
| 130 | + |
| 131 | + # run_sync |
| 132 | + await db.run_sync(Base.metadata.create_all, is_session=False) |
| 133 | + |
| 134 | + # session_maker |
| 135 | + async with db.session_maker() as session: |
| 136 | + user = await session.get(User, 1) |
| 137 | +``` |
| 138 | + |
| 139 | +## Database |
| 140 | + |
| 141 | +### Creation Connection |
| 142 | + |
| 143 | +```python |
| 144 | +from sqlalchemy_database import Database |
| 145 | + |
| 146 | +# 1.Create a database connection |
| 147 | +db = Database.create('sqlite:///amisadmin.db?check_same_thread=False') # sqlite |
| 148 | +# db = Database.create('mysql+pymysql://root:123456@127.0.0.1:3306/amisadmin?charset=utf8mb4') # mysql |
| 149 | +# db = Database.create('postgresql://postgres:root@127.0.0.1:5432/amisadmin') # postgresql |
| 150 | +# db = Database.create('oracle+cx_oracle://scott:tiger@tnsname') # oracle |
| 151 | +# db = Database.create('mssql+pyodbc://scott:tiger@mydsn') # SQL Server |
| 152 | +``` |
| 153 | + |
| 154 | +### Shortcut functions |
| 155 | + |
| 156 | +```python |
| 157 | +from sqlalchemy import insert, select, update, delete |
| 158 | + |
| 159 | + |
| 160 | +def fast_execute(): |
| 161 | + # update |
| 162 | + stmt = update(User).where(User.id == 1).values({'username': 'new_user'}) |
| 163 | + result = db.execute(stmt) |
| 164 | + |
| 165 | + # select |
| 166 | + stmt = select(User).where(User.id == 1) |
| 167 | + user = db.execute(stmt, on_close_pre=lambda r: r.scalar()) |
| 168 | + |
| 169 | + # insert |
| 170 | + stmt = insert(User).values({'username': 'User-6', 'password': 'password-6'}) |
| 171 | + result = db.execute(stmt) |
| 172 | + |
| 173 | + # delete |
| 174 | + stmt = delete(User).where(User.id == 6) |
| 175 | + result = db.execute(stmt) |
| 176 | + |
| 177 | + # scalar |
| 178 | + user = db.scalar(select(User).where(User.id == 1)) |
| 179 | + |
| 180 | + # scalars_all |
| 181 | + stmt = select(User) |
| 182 | + result = db.scalars_all(stmt) |
| 183 | + |
| 184 | + # get |
| 185 | + user = db.get(User, 1) |
| 186 | + |
| 187 | + # delete |
| 188 | + user = User(id=1, name='test') |
| 189 | + db.delete(user) |
| 190 | + |
| 191 | + # save(insert or update) |
| 192 | + user = User(name='new_user') |
| 193 | + db.save(user) |
| 194 | + |
| 195 | + # run_sync |
| 196 | + db.run_sync(Base.metadata.create_all, is_session=False) |
| 197 | + |
| 198 | + # session_maker |
| 199 | + with db.session_maker() as session: |
| 200 | + user = session.get(User, 1) |
| 201 | +``` |
| 202 | + |
| 203 | +## AbcAsyncDatabase |
| 204 | + |
| 205 | +When you are developing a library of tools, your Python program may require a database connection. |
| 206 | + |
| 207 | +But you can't be sure whether the other person personally prefers synchronous or asynchronous connections. |
| 208 | + |
| 209 | +You can use asynchronous shortcut functions with the `async_` prefix. |
| 210 | + |
| 211 | +`AsyncDatabase` and `Database` both inherit from `AbcAsyncDatabase` and both implement the usual `async_` prefixed asynchronous |
| 212 | +shortcut functions. |
| 213 | + |
| 214 | +For example: `async_execute`,`async_scalar`,`async_scalars_all`,`async_get`,`async_delete`,`async_run_sync`. |
| 215 | + |
| 216 | +Remark: The `async_` prefix in `Database` is implemented by executing the corresponding synchronous shortcut in the thread pool. |
| 217 | + |
| 218 | +### Asynchronous compatible shortcut functions |
| 219 | + |
| 220 | +```python |
| 221 | +from sqlalchemy import insert, select, update, delete |
| 222 | +from sqlalchemy_database import AsyncDatabase, Database |
| 223 | + |
| 224 | + |
| 225 | +async def fast_execute(db: Union[AsyncDatabase, Database]): |
| 226 | + # update |
| 227 | + stmt = update(User).where(User.id == 1).values({'username': 'new_user'}) |
| 228 | + result = await db.async_execute(stmt) |
| 229 | + |
| 230 | + # select |
| 231 | + stmt = select(User).where(User.id == 1) |
| 232 | + user = await db.async_execute(stmt, on_close_pre=lambda r: r.scalar()) |
| 233 | + |
| 234 | + # insert |
| 235 | + stmt = insert(User).values({'username': 'User-6', 'password': 'password-6'}) |
| 236 | + result = await db.async_execute(stmt) |
| 237 | + |
| 238 | + # delete |
| 239 | + stmt = delete(User).where(User.id == 6) |
| 240 | + result = await db.async_execute(stmt) |
| 241 | + |
| 242 | + # scalar |
| 243 | + user = await db.async_scalar(select(User).where(User.id == 1)) |
| 244 | + |
| 245 | + # scalars_all |
| 246 | + stmt = select(User) |
| 247 | + result = await db.async_scalars_all(stmt) |
| 248 | + |
| 249 | + # get |
| 250 | + user = await db.async_get(User, 1) |
| 251 | + |
| 252 | + # delete |
| 253 | + user = User(id=1, name='test') |
| 254 | + await db.async_delete(user) |
| 255 | + |
| 256 | + # save(insert or update) |
| 257 | + user = User(name='new_user') |
| 258 | + await db.async_save(user) |
| 259 | + |
| 260 | + # run_sync |
| 261 | + await db.async_run_sync(Base.metadata.create_all, is_session=False) |
| 262 | + |
| 263 | +``` |
| 264 | + |
| 265 | +## Use dependencies in FastAPI |
| 266 | + |
| 267 | +```python |
| 268 | +app = FastAPI() |
| 269 | + |
| 270 | + |
| 271 | +# AsyncDatabase |
| 272 | +@app.get("/user/{id}") |
| 273 | +async def get_user(id: int, session: AsyncSession = Depends(db.session_generator)): |
| 274 | + return await session.get(User, id) |
| 275 | + |
| 276 | + |
| 277 | +# Database |
| 278 | +@app.get("/user/{id}") |
| 279 | +def get_user(id: int, session: Session = Depends(db.session_generator)): |
| 280 | + return session.get(User, id) |
| 281 | +``` |
| 282 | + |
| 283 | +## More tutorial documentation |
| 284 | + |
| 285 | +### [sqlalchemy](https://github.com/sqlalchemy/sqlalchemy) |
| 286 | + |
| 287 | +`SQLAlchemy-Database` adds extension functionality to `SQLAlchemy`. |
| 288 | + |
| 289 | +More features and complicated to use, please refer to the ` SQLAlchemy ` [documentation](https://www.sqlalchemy.org/). |
| 290 | + |
| 291 | +`SQLAlchemy` is very powerful and can fulfill almost any complex need you have. |
| 292 | + |
| 293 | +### [sqlmodel](https://github.com/tiangolo/sqlmodel) |
| 294 | + |
| 295 | +Recommend you to use ` SQLModel ` definition `ORM` model, please refer to |
| 296 | +the ` SQLModel ` [documentation](https://sqlmodel.tiangolo.com/). |
| 297 | + |
| 298 | +`SQLModel` written by `FastAPI` author, Perfectly combine [SQLAlchemy](https://www.sqlalchemy.org/) |
| 299 | +with [Pydantic](https://pydantic-docs.helpmanual.io/), and have all their features . |
| 300 | + |
| 301 | +## Relevant project |
| 302 | + |
| 303 | +- [FastAPI-Amis-Admin](https://docs.amis.work/) |
| 304 | + |
| 305 | +## License |
| 306 | + |
| 307 | +According to the `Apache2.0` protocol. |
0 commit comments