샘플
sqlalchemy 2.0.51: Engine
검증된 샘플 — pypi sqlalchemy 2.0.51: Engine. python 3.12 · linux alpine/x64 · docker에서 contract를 실행해 통과했습니다: sqlalchemy.create_engine creates an Engine instance…
sha256:9dac12e992f9e32ea571369c4c8902591da7930353a829a6dcfb0c0f27801016
이 네트워크가 제공하는 것은 하나입니다. 빌드되는 샘플. 샌드박스에서 돌리고 서명된 영수증을 보관합니다. 등급을 매기지 않고 무엇도 보증하지 않습니다 — 같은 코드가 당신 환경에서 빌드되는지는 측정한 적이 없습니다.
통과한 계약 영수증을 낸 서로 다른 서명 키의 수입니다. 하나면 작성자 혼자이고, 둘 이상이면 다른 사람도 빌드했다는 뜻입니다. 키는 스스로 만드는 것이고 뒤에 등록된 신원이 없으므로, 세는 것은 사람이 아니라 키입니다.
MIT-0
실행 증거
선언된 환경과 서명된 실행을 분리해 두었습니다. 이 샘플이 무엇을 어디서 실행했는지 그대로 볼 수 있습니다.
- 증거 기준
- 서명된 컨트랙트 통과
- 검증 영수증
- 1
- 빌드한 서명 키
- 1
선언된 환경
linux 24 · ubuntu · glibc 2.39 x64 pip
검증 실행 환경
| 환경 | 컨트랙트 | 단계 | 실행일 |
|---|---|---|---|
| python 3.12 · linux alpine/x64 · docker ed25519:c1973797be207ac4 | PASS | compile:SKIPPED · contract:PASS · load:PASS · resolve:PASS CONTAINER_RUN · python@1python:3.12-alpine@sha256:d09d15e60962… |
2026-08-27 |
케이스
HOW- 목표
- verify sqlalchemy.Engine in pkg:pypi/sqlalchemy@2.0.51
- 심벌
-
- sqlalchemy.Engine
- 생성일
- 2026-08-27T19:12:11Z
컨트랙트
- sqlalchemy.create_engine creates an Engine instance configured with connection pool and dialect
- sqlalchemy.Engine.connect acquires connections and executes text() SQL statements with explicit transaction control
- sqlalchemy.Engine.begin manages transactional execution blocks with automatic commit and rollback
- sqlalchemy.Engine in 2.0 does not support connectionless execution (Engine.execute is removed)
- sqlalchemy.Engine.dispose closes and releases pooled database connections
파일
- PROMPT.md
- csx.json
- requirements.txt
- sample.py
- spec.json
- test/contract.py
소스
Clean-room public code sample — generation instructions
Write a brand-new, minimal, self-contained code sample in this clean-room directory.
Do not copy, paraphrase, or reference any existing project source. Work only from this spec.
A csx.json manifest scaffold already exists. Do not recreate it from memory. Preserve its case.goal, packages and symbols; fill its empty case.contract with exact assertions and correct its environment, commands and verifierAdapter for the files you generate.
Goal: verify sqlalchemy.Engine in pkg:pypi/sqlalchemy@2.0.51
Kind: HOW
Use EXACTLY these public packages and versions:
- pkg:pypi/sqlalchemy@2.0.51
Demonstrate these symbols/APIs:
- sqlalchemy.Engine
Rules:
- One focused purpose; the smallest project that proves the goal.
- Include a contract test (test/contract.*) that runs OFFLINE and exits 0 exactly when the goal behavior works.
- Pin every dependency with a lockfile so resolution is reproducible.
- No secrets, credentials, or tokens. No real URLs (only example.com or localhost). No absolute paths.
- No personal names, emails, company names, or project identifiers of any kind.
- No binaries and no generated output (node_modules, dist, target, venv, .git, .env).
- Keep it under 200 files and 256KB packed.
{"case":{"caseId":"case:sha256:b19d590204eb2782baa8d246f2b94a2d7b68d51eccecc55c23f0a4e29f058a9e","contract":["sqlalchemy.create_engine creates an Engine instance configured with connection pool and dialect","sqlalchemy.Engine.connect acquires connections and executes text() SQL statements with explicit transaction control","sqlalchemy.Engine.begin manages transactional execution blocks with automatic commit and rollback","sqlalchemy.Engine in 2.0 does not support connectionless execution (Engine.execute is removed)","sqlalchemy.Engine.dispose closes and releases pooled database connections"],"goal":"verify sqlalchemy.Engine in pkg:pypi/sqlalchemy@2.0.51","kind":"HOW","packages":["pkg:pypi/sqlalchemy@2.0.51"],"schemaVersion":1,"symbols":["sqlalchemy.Engine"]},"contractCommand":["python","test/contract.py"],"environment":{"arch":"x64","distro":"ubuntu","ecosystem":"pypi","libc":"glibc","libcVersion":"2.39","os":"linux","osVersionBucket":"24","packageManager":"pip","schemaVersion":1},"license":"MIT-0","packages":["pkg:pypi/sqlalchemy@2.0.51"],"schemaVersion":1,"subject":"pkg:pypi/sqlalchemy@2.0.51","symbols":["sqlalchemy.Engine"],"verifierAdapter":"python@1"}
greenlet==3.5.5
sqlalchemy==2.0.51
typing-extensions==4.16.0
"""SQLAlchemy 2.0 Engine and connection lifecycle management sample."""
from typing import Any, List, Optional, Sequence, Tuple
from sqlalchemy import Engine, create_engine, text
from sqlalchemy.engine import Connection, CursorResult
from sqlalchemy.pool import Pool
def create_sqlite_engine(db_url: str = "sqlite:///:memory:", echo: bool = False) -> Engine:
"""Create a configured SQLAlchemy Engine instance."""
return create_engine(db_url, echo=echo)
def init_db(engine: Engine) -> None:
"""Initialize table schema using engine.begin context manager."""
with engine.begin() as conn:
conn.execute(
text(
"CREATE TABLE records ("
" id INTEGER PRIMARY KEY AUTOINCREMENT,"
" key TEXT NOT NULL UNIQUE,"
" value INTEGER NOT NULL"
")"
)
)
def insert_record(engine: Engine, key: str, value: int) -> int:
"""Insert a single record within a committed transaction using engine.begin()."""
with engine.begin() as conn:
result: CursorResult[Any] = conn.execute(
text("INSERT INTO records (key, value) VALUES (:key, :value)"),
{"key": key, "value": value},
)
return int(result.rowcount)
def insert_records_batch(engine: Engine, records: Sequence[Tuple[str, int]]) -> int:
"""Insert multiple records in a transaction block."""
with engine.begin() as conn:
result = conn.execute(
text("INSERT INTO records (key, value) VALUES (:key, :value)"),
[{"key": k, "value": v} for k, v in records],
)
return int(result.rowcount)
def fetch_all_records(engine: Engine) -> List[Tuple[int, str, int]]:
"""Fetch all records using engine.connect() context manager."""
with engine.connect() as conn:
result = conn.execute(text("SELECT id, key, value FROM records ORDER BY id"))
return [(int(row[0]), str(row[1]), int(row[2])) for row in result.fetchall()]
def fetch_value_by_key(engine: Engine, key: str) -> Optional[int]:
"""Fetch a scalar value by key using engine.connect()."""
with engine.connect() as conn:
result = conn.execute(
text("SELECT value FROM records WHERE key = :key"),
{"key": key},
)
scalar = result.scalar_one_or_none()
return int(scalar) if scalar is not None else None
def execute_transaction_with_rollback(engine: Engine, key: str, value: int) -> None:
"""Attempt an operation in a transaction that raises and rolls back."""
with engine.begin() as conn:
conn.execute(
text("INSERT INTO records (key, value) VALUES (:key, :value)"),
{"key": key, "value": value},
)
raise RuntimeError("simulated transaction failure")
def dispose_engine(engine: Engine) -> None:
"""Dispose connection pool resources associated with the Engine."""
engine.dispose()
{
"schemaVersion": 1,
"goal": "verify sqlalchemy.Engine in pkg:pypi/sqlalchemy@2.0.51",
"kind": "HOW",
"packages": [
"pkg:pypi/sqlalchemy@2.0.51"
],
"symbols": [
"sqlalchemy.Engine"
]
}
"""Contract verification test for sqlalchemy.Engine in SQLAlchemy 2.0."""
import os
import sys
from pathlib import Path
# Ensure project root is on sys.path for local module imports
sys.path.insert(0, str(Path(__file__).resolve().parents[1]))
import sqlalchemy as sa
from sqlalchemy import Engine, create_engine, text
from sqlalchemy.engine import Connection
from sqlalchemy.exc import ArgumentError, ObjectNotExecutableError
from sqlalchemy.pool import Pool
from sample import (
create_sqlite_engine,
dispose_engine,
execute_transaction_with_rollback,
fetch_all_records,
fetch_value_by_key,
init_db,
insert_record,
insert_records_batch,
)
def test_engine_creation_and_properties() -> None:
"""Assertion: sqlalchemy.create_engine creates an Engine instance configured with connection pool and dialect."""
engine = create_sqlite_engine()
try:
assert isinstance(engine, Engine), "Engine instance must be of type sqlalchemy.Engine"
assert engine.dialect.name == "sqlite", f"Expected sqlite dialect, got {engine.dialect.name}"
assert engine.url.drivername == "sqlite", f"Expected sqlite drivername, got {engine.url.drivername}"
assert isinstance(engine.pool, Pool), "Engine.pool must be an instance of sqlalchemy.pool.Pool"
assert engine.echo is False, "Echo setting should match configuration"
finally:
dispose_engine(engine)
def test_engine_connect_and_execution() -> None:
"""Assertion: sqlalchemy.Engine.connect acquires connections and executes text() SQL statements with explicit transaction control."""
engine = create_sqlite_engine()
try:
init_db(engine)
# Connect and execute valid text() statement
with engine.connect() as conn:
assert isinstance(conn, Connection), "engine.connect() must yield a Connection instance"
scalar_res = conn.execute(text("SELECT 42")).scalar()
assert scalar_res == 42, f"Expected 42, got {scalar_res}"
# Bare strings are not executable in SQLAlchemy 2.0
try:
conn.execute("SELECT 42") # type: ignore[arg-type]
raise AssertionError("Bare string query should raise ObjectNotExecutableError")
except ObjectNotExecutableError:
pass
# Explicit commit-as-you-go within connect()
conn.execute(
text("INSERT INTO records (key, value) VALUES (:key, :value)"),
{"key": "alpha", "value": 100},
)
conn.commit()
# Verify committed record in a new connection
with engine.connect() as conn:
val = conn.execute(
text("SELECT value FROM records WHERE key = :key"),
{"key": "alpha"},
).scalar()
assert val == 100, f"Expected value 100, got {val}"
finally:
dispose_engine(engine)
def test_engine_begin_transaction_lifecycle() -> None:
"""Assertion: sqlalchemy.Engine.begin manages transactional execution blocks with automatic commit and rollback."""
engine = create_sqlite_engine()
try:
init_db(engine)
# Successful transaction block automatically commits
insert_record(engine, "item1", 10)
insert_records_batch(engine, [("item2", 20), ("item3", 30)])
records = fetch_all_records(engine)
assert len(records) == 3, f"Expected 3 records, got {len(records)}"
assert fetch_value_by_key(engine, "item2") == 20
# Transaction block that encounters an exception automatically rolls back
try:
execute_transaction_with_rollback(engine, "rolled_back_item", 999)
raise AssertionError("execute_transaction_with_rollback should have raised RuntimeError")
except RuntimeError as exc:
assert "simulated transaction failure" in str(exc)
# Verify that rolled_back_item was not persisted
records_after = fetch_all_records(engine)
assert len(records_after) == 3, f"Record count should remain 3, got {len(records_after)}"
assert fetch_value_by_key(engine, "rolled_back_item") is None
finally:
dispose_engine(engine)
def test_engine_connectionless_execution_removed() -> None:
"""Assertion: sqlalchemy.Engine in 2.0 does not support connectionless execution (Engine.execute is removed)."""
engine = create_sqlite_engine()
try:
assert not hasattr(engine, "execute"), "Engine.execute must not exist in SQLAlchemy 2.0"
finally:
dispose_engine(engine)
def test_engine_dispose_cleanup() -> None:
"""Assertion: sqlalchemy.Engine.dispose closes and releases pooled database connections."""
engine = create_sqlite_engine()
init_db(engine)
# Establish connection
with engine.connect() as conn:
res = conn.execute(text("SELECT 1")).scalar()
assert res == 1
# Dispose pool
dispose_engine(engine)
# Reconnect transparently works with new pool checkout
with engine.connect() as conn:
res = conn.execute(text("SELECT 2")).scalar()
assert res == 2
dispose_engine(engine)
def main() -> None:
test_engine_creation_and_properties()
test_engine_connect_and_execution()
test_engine_begin_transaction_lifecycle()
test_engine_connectionless_execution_removed()
test_engine_dispose_cleanup()
print(f"Contract verified successfully for sqlalchemy.Engine on {sa.__version__}")
if __name__ == "__main__":
main()
오리진 시더
익명