CodeSampleX

샘플

sqlalchemy 2.0.51: engine.reflection.Inspector

검증된 샘플 — pypi sqlalchemy 2.0.51: engine.reflection.Inspector. python 3.12 · linux debian/x64 · docker에서 contract를 실행해 통과했습니다…

sha256:2c9ff428e2be0e665102512c9d5568d5437534e4aa51a917ca8e5f12f967c70c

이 네트워크가 제공하는 것은 하나입니다. 빌드되는 샘플. 샌드박스에서 돌리고 서명된 영수증을 보관합니다. 등급을 매기지 않고 무엇도 보증하지 않습니다 — 같은 코드가 당신 환경에서 빌드되는지는 측정한 적이 없습니다. 통과한 계약 영수증을 낸 서로 다른 서명 키의 수입니다. 하나면 작성자 혼자이고, 둘 이상이면 다른 사람도 빌드했다는 뜻입니다. 키는 스스로 만드는 것이고 뒤에 등록된 신원이 없으므로, 세는 것은 사람이 아니라 키입니다. MIT-0

실행 증거

선언된 환경과 서명된 실행을 분리해 두었습니다. 이 샘플이 무엇을 어디서 실행했는지 그대로 볼 수 있습니다.

증거 기준
서명된 컨트랙트 통과
검증 영수증
1
빌드한 서명 키
1
선언된 환경 linux 24 · ubuntu · glibc 2.39 x64 pip

검증 실행 환경

환경 컨트랙트 단계 실행일
python 3.12 · linux debian/x64 · docker ed25519:c1973797be207ac4 PASS compile:SKIPPED · contract:PASS · load:PASS · resolve:PASS
CONTAINER_RUN · python@1python:3.12-slim@sha256:09f7da3bc104…
2026-09-06

케이스

HOW
목표
verify sqlalchemy.engine.reflection.Inspector in pkg:pypi/sqlalchemy@2.0.51
패키지
심벌
  • sqlalchemy.engine.reflection.Inspector
생성일
2026-09-06T02:10:54Z

컨트랙트

  1. sqlalchemy.engine.reflection.Inspector inspects schema tables, returning table names and checking table existence.
  2. sqlalchemy.engine.reflection.Inspector inspects column metadata including name, type, and nullability, as well as primary key constraints.
  3. sqlalchemy.engine.reflection.Inspector inspects foreign keys and table indexes, returning referenced tables and index column definitions.
  4. sqlalchemy.engine.reflection.Inspector reflects database table schema into a Table object via reflect_table.

파일

  • PROMPT.md
  • csx.json
  • requirements.txt
  • sample.py
  • spec.json
  • test/contract.py

소스 아티팩트 내려받기 (tar.gz)

소스

PROMPT.md
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.reflection.Inspector 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.reflection.Inspector
Constraints:
  - executionContext: node
Required runtime conditions:
  - ecosystem: npm
  - language: javascript
  - moduleSystem: cjs
  - packageManager: npm@10.9.8
  - runtime: node@22.23.2

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.
csx.json
{"case":{"caseId":"case:sha256:73ee7f1fe8be2676552f0250285e3db871f32f34d575522816cfc2df14839211","contract":["sqlalchemy.engine.reflection.Inspector inspects schema tables, returning table names and checking table existence.","sqlalchemy.engine.reflection.Inspector inspects column metadata including name, type, and nullability, as well as primary key constraints.","sqlalchemy.engine.reflection.Inspector inspects foreign keys and table indexes, returning referenced tables and index column definitions.","sqlalchemy.engine.reflection.Inspector reflects database table schema into a Table object via reflect_table."],"goal":"verify sqlalchemy.engine.reflection.Inspector in pkg:pypi/sqlalchemy@2.0.51","kind":"HOW","packages":["pkg:pypi/sqlalchemy@2.0.51"],"schemaVersion":1,"symbols":["sqlalchemy.engine.reflection.Inspector"]},"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.reflection.Inspector"],"verifierAdapter":"python@1"}
requirements.txt
sqlalchemy==2.0.51
sample.py
"""Demonstration of database schema reflection using sqlalchemy.engine.reflection.Inspector."""

from typing import Any, Dict, List, Optional, Union
from sqlalchemy import Connection, Engine, Table, inspect
from sqlalchemy.engine.reflection import Inspector


def get_inspector(bind: Union[Engine, Connection]) -> Inspector:
    """Acquire an Inspector instance from an Engine or Connection."""
    insp = inspect(bind)
    if not isinstance(insp, Inspector):
        raise TypeError(f"Expected Inspector instance, got {type(insp)}")
    return insp


def list_table_names(inspector: Inspector, schema: Optional[str] = None) -> List[str]:
    """Retrieve all table names in the specified or default schema."""
    return inspector.get_table_names(schema=schema)


def check_table_exists(inspector: Inspector, table_name: str, schema: Optional[str] = None) -> bool:
    """Check if a table exists in the database schema."""
    return inspector.has_table(table_name, schema=schema)


def get_table_columns(inspector: Inspector, table_name: str, schema: Optional[str] = None) -> List[Dict[str, Any]]:
    """Inspect column definitions for a specific table."""
    return inspector.get_columns(table_name, schema=schema)


def get_table_primary_key(inspector: Inspector, table_name: str, schema: Optional[str] = None) -> Dict[str, Any]:
    """Inspect primary key constraint information for a table."""
    return inspector.get_pk_constraint(table_name, schema=schema)


def get_table_foreign_keys(inspector: Inspector, table_name: str, schema: Optional[str] = None) -> List[Dict[str, Any]]:
    """Inspect foreign key constraints defined on a table."""
    return inspector.get_foreign_keys(table_name, schema=schema)


def get_table_indexes(inspector: Inspector, table_name: str, schema: Optional[str] = None) -> List[Dict[str, Any]]:
    """Inspect index definitions for a table."""
    return inspector.get_indexes(table_name, schema=schema)


def reflect_table_definition(inspector: Inspector, table: Table) -> None:
    """Reflect table schema and columns into an existing Table object."""
    inspector.reflect_table(table, None)
spec.json
{
  "schemaVersion": 1,
  "goal": "verify sqlalchemy.engine.reflection.Inspector in pkg:pypi/sqlalchemy@2.0.51",
  "kind": "HOW",
  "packages": [
    "pkg:pypi/sqlalchemy@2.0.51"
  ],
  "symbols": [
    "sqlalchemy.engine.reflection.Inspector"
  ],
  "constraints": {
    "executionContext": "node"
  },
  "runtimeConditions": {
    "ecosystem": "npm",
    "language": "javascript",
    "moduleSystem": "cjs",
    "packageManager": "npm@10.9.8",
    "runtime": "node@22.23.2"
  }
}
test/contract.py
"""Contract verification test for sqlalchemy.engine.reflection.Inspector."""

import os
import sys

# Ensure sample root directory is in sys.path
sys.path.insert(0, os.path.dirname(os.path.dirname(os.path.abspath(__file__))))

from sqlalchemy import (
    Column,
    ForeignKey,
    Index,
    Integer,
    MetaData,
    String,
    Table,
    UniqueConstraint,
    create_engine,
)
from sqlalchemy.engine.reflection import Inspector
import sample


def create_test_database():
    """Create an in-memory SQLite database populated with test tables and constraints."""
    engine = create_engine("sqlite:///:memory:")
    metadata = MetaData()

    users = Table(
        "users",
        metadata,
        Column("id", Integer, primary_key=True),
        Column("username", String(50), nullable=False, unique=True),
        Column("email", String(100), nullable=False),
        UniqueConstraint("email", name="uq_user_email"),
    )

    posts = Table(
        "posts",
        metadata,
        Column("id", Integer, primary_key=True),
        Column("user_id", Integer, ForeignKey("users.id"), nullable=False),
        Column("title", String(200), nullable=False),
        Index("idx_posts_user_id", "user_id"),
    )

    metadata.create_all(engine)
    return engine


def test_inspector_table_names_and_existence() -> None:
    """Assertion 1: sqlalchemy.engine.reflection.Inspector inspects schema tables, returning table names and checking table existence."""
    engine = create_test_database()
    inspector = sample.get_inspector(engine)

    assert isinstance(inspector, Inspector), f"Expected Inspector instance, got {type(inspector)}"

    tables = sample.list_table_names(inspector)
    assert "users" in tables, f"Expected 'users' in {tables}"
    assert "posts" in tables, f"Expected 'posts' in {tables}"

    assert sample.check_table_exists(inspector, "users") is True
    assert sample.check_table_exists(inspector, "posts") is True
    assert sample.check_table_exists(inspector, "non_existent_table") is False

    with engine.connect() as conn:
        conn_inspector = sample.get_inspector(conn)
        assert isinstance(conn_inspector, Inspector)
        assert conn_inspector.has_table("users") is True


def test_inspector_columns_and_primary_key() -> None:
    """Assertion 2: sqlalchemy.engine.reflection.Inspector inspects column metadata including name, type, and nullability, as well as primary key constraints."""
    engine = create_test_database()
    inspector = sample.get_inspector(engine)

    columns = sample.get_table_columns(inspector, "users")
    col_names = [col["name"] for col in columns]
    assert "id" in col_names
    assert "username" in col_names
    assert "email" in col_names

    col_map = {col["name"]: col for col in columns}
    assert col_map["username"]["nullable"] is False
    assert "VARCHAR" in str(col_map["username"]["type"]).upper()

    pk_info = sample.get_table_primary_key(inspector, "users")
    assert "constrained_columns" in pk_info
    assert pk_info["constrained_columns"] == ["id"]


def test_inspector_foreign_keys_and_indexes() -> None:
    """Assertion 3: sqlalchemy.engine.reflection.Inspector inspects foreign keys and table indexes, returning referenced tables and index column definitions."""
    engine = create_test_database()
    inspector = sample.get_inspector(engine)

    fks = sample.get_table_foreign_keys(inspector, "posts")
    assert len(fks) >= 1
    fk = fks[0]
    assert fk["referred_table"] == "users"
    assert "user_id" in fk["constrained_columns"]
    assert "id" in fk["referred_columns"]

    indexes = sample.get_table_indexes(inspector, "posts")
    idx_names = [idx["name"] for idx in indexes]
    assert "idx_posts_user_id" in idx_names

    post_idx = next(idx for idx in indexes if idx["name"] == "idx_posts_user_id")
    assert "user_id" in post_idx["column_names"]


def test_inspector_reflect_table() -> None:
    """Assertion 4: sqlalchemy.engine.reflection.Inspector reflects database table schema into a Table object via reflect_table."""
    engine = create_test_database()
    inspector = sample.get_inspector(engine)

    target_metadata = MetaData()
    reflected_users = Table("users", target_metadata)
    assert len(reflected_users.columns) == 0

    sample.reflect_table_definition(inspector, reflected_users)

    reflected_col_names = [c.name for c in reflected_users.columns]
    assert "id" in reflected_col_names
    assert "username" in reflected_col_names
    assert "email" in reflected_col_names
    assert len(reflected_users.primary_key.columns) == 1
    assert "id" in [c.name for c in reflected_users.primary_key.columns]


def main() -> None:
    test_inspector_table_names_and_existence()
    test_inspector_columns_and_primary_key()
    test_inspector_foreign_keys_and_indexes()
    test_inspector_reflect_table()
    print("All sqlalchemy.engine.reflection.Inspector contract assertions passed successfully.")


if __name__ == "__main__":
    main()

오리진 시더

익명