CodeSampleX

示例

sqlalchemy 2.0.51: inspect

已验证示例 — pypi sqlalchemy 2.0.51: inspect. contract 在 python 3.12 · linux debian/x64 · docker 上运行并通过: sqlalchemy.inspect reflects database schema from an…

sha256:f27766cd633b759a3fa13a6e456ed13126c6bef794bbe7ffb7a05b286dbda537

本网络只提供一件事:能构建的样本。它在沙箱中运行并保留签名回执。它不评级、不担保——同样的代码能否在你的环境构建,它没有测量过。 提交了通过的契约回执的不同签名密钥数量。为 1 表示只有作者;大于 1 表示还有其他人构建过。密钥是自行生成的,背后没有注册身份,因此计的是密钥而非人。 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.inspect in pkg:pypi/sqlalchemy@2.0.51
包
符号
  • sqlalchemy.inspect
创建时间
2026-09-06T01:18:06Z

契约

  1. sqlalchemy.inspect reflects database schema from an Engine or Connection, returning an Inspector capable of querying table names and column metadata.
  2. sqlalchemy.inspect inspects mapped ORM classes, returning a Mapper providing access to underlying local_table, primary_key columns, and relationships.
  3. sqlalchemy.inspect inspects ORM model instances, returning an InstanceState tracking object lifecycle states (transient, persistent) and attribute values.
  4. sqlalchemy.inspect raises NoInspectionAvailable when inspecting unsupported types if raiseerr=True, and returns None if raiseerr=False.

文件

  • 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.inspect 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.inspect

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:f53984917619d461b441e45e5659963ce7df2fa9faaace7d3d5b4fb8982bf7e1","contract":["sqlalchemy.inspect reflects database schema from an Engine or Connection, returning an Inspector capable of querying table names and column metadata.","sqlalchemy.inspect inspects mapped ORM classes, returning a Mapper providing access to underlying local_table, primary_key columns, and relationships.","sqlalchemy.inspect inspects ORM model instances, returning an InstanceState tracking object lifecycle states (transient, persistent) and attribute values.","sqlalchemy.inspect raises NoInspectionAvailable when inspecting unsupported types if raiseerr=True, and returns None if raiseerr=False."],"goal":"verify sqlalchemy.inspect in pkg:pypi/sqlalchemy@2.0.51","kind":"HOW","packages":["pkg:pypi/sqlalchemy@2.0.51"],"schemaVersion":1,"symbols":["sqlalchemy.inspect"]},"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.inspect"],"verifierAdapter":"python@1"}
requirements.txt
sqlalchemy==2.0.51
sample.py
"""Clean demonstration of schema and ORM inspection using sqlalchemy.inspect."""

from typing import Any, List
from sqlalchemy import (
    Column,
    ForeignKey,
    Integer,
    String,
    create_engine,
    inspect,
)
from sqlalchemy.engine import Engine
from sqlalchemy.engine.reflection import Inspector
from sqlalchemy.orm import DeclarativeBase, InstanceState, Mapper, relationship


class Base(DeclarativeBase):
    """Base declarative class for ORM models."""


class Department(Base):
    __tablename__ = "departments"

    id = Column(Integer, primary_key=True)
    name = Column(String(50), nullable=False)

    employees = relationship("Employee", back_populates="department")


class Employee(Base):
    __tablename__ = "employees"

    id = Column(Integer, primary_key=True)
    name = Column(String(100), nullable=False)
    department_id = Column(Integer, ForeignKey("departments.id"))

    department = relationship("Department", back_populates="employees")


def init_database() -> Engine:
    """Initialize an in-memory SQLite database with sample schema."""
    engine = create_engine("sqlite:///:memory:")
    Base.metadata.create_all(engine)
    return engine


def get_inspector(target: Any) -> Inspector:
    """Obtain an Inspector instance for an Engine or Connection using inspect."""
    return inspect(target)


def get_table_names(engine: Engine) -> List[str]:
    """Retrieve all table names via the reflected Inspector."""
    inspector = inspect(engine)
    return inspector.get_table_names()


def get_table_column_names(engine: Engine, table_name: str) -> List[str]:
    """Retrieve column names for a specific table via the reflected Inspector."""
    inspector = inspect(engine)
    return [col["name"] for col in inspector.get_columns(table_name)]


def get_model_mapper(model_cls: type) -> Mapper:
    """Obtain the Mapper instance for a declarative class using inspect."""
    return inspect(model_cls)


def get_model_primary_keys(model_cls: type) -> List[str]:
    """Retrieve primary key column names from a mapped class using inspect."""
    mapper = inspect(model_cls)
    return [col.name for col in mapper.primary_key]


def get_instance_state(instance: Any) -> InstanceState:
    """Obtain the InstanceState tracking object for an ORM instance using inspect."""
    return inspect(instance)


def inspect_safely(target: Any, raise_error: bool = True) -> Any:
    """Inspect target with optional exception suppression."""
    return inspect(target, raiseerr=raise_error)
spec.json
{
  "schemaVersion": 1,
  "goal": "verify sqlalchemy.inspect in pkg:pypi/sqlalchemy@2.0.51",
  "kind": "HOW",
  "packages": [
    "pkg:pypi/sqlalchemy@2.0.51"
  ],
  "symbols": [
    "sqlalchemy.inspect"
  ]
}
test/contract.py
"""Contract verification tests for sqlalchemy.inspect."""

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.engine.reflection import Inspector
from sqlalchemy.exc import NoInspectionAvailable
from sqlalchemy.orm import InstanceState, Mapper
import sample


def test_inspect_engine_schema() -> None:
    """Assertion 1: sqlalchemy.inspect reflects database schema from an Engine or Connection, returning an Inspector capable of querying table names and column metadata."""
    engine = sample.init_database()
    inspector = sample.get_inspector(engine)

    assert isinstance(inspector, Inspector)
    tables = sample.get_table_names(engine)
    assert "departments" in tables
    assert "employees" in tables

    emp_columns = sample.get_table_column_names(engine, "employees")
    assert "id" in emp_columns
    assert "name" in emp_columns
    assert "department_id" in emp_columns

    assert inspector.has_table("employees") is True
    assert inspector.has_table("non_existent_table") is False


def test_inspect_mapped_class() -> None:
    """Assertion 2: sqlalchemy.inspect inspects mapped ORM classes, returning a Mapper providing access to underlying local_table, primary_key columns, and relationships."""
    mapper = sample.get_model_mapper(sample.Employee)

    assert isinstance(mapper, Mapper)
    assert mapper.local_table.name == "employees"

    pk_names = sample.get_model_primary_keys(sample.Employee)
    assert pk_names == ["id"]

    assert "department" in mapper.relationships.keys()


def test_inspect_mapped_instance() -> None:
    """Assertion 3: sqlalchemy.inspect inspects ORM model instances, returning an InstanceState tracking object lifecycle states (transient, persistent) and attribute values."""
    emp = sample.Employee(id=1, name="Alice")
    state = sample.get_instance_state(emp)

    assert isinstance(state, InstanceState)
    assert state.transient is True
    assert state.persistent is False
    assert state.attrs.name.loaded_value == "Alice"


def test_inspect_unsupported_targets() -> None:
    """Assertion 4: sqlalchemy.inspect raises NoInspectionAvailable when inspecting unsupported types if raiseerr=True, and returns None if raiseerr=False."""
    try:
        sample.inspect_safely(42, raise_error=True)
        assert False, "Expected NoInspectionAvailable exception"
    except NoInspectionAvailable:
        pass

    result = sample.inspect_safely(42, raise_error=False)
    assert result is None


def main() -> None:
    test_inspect_engine_schema()
    test_inspect_mapped_class()
    test_inspect_mapped_instance()
    test_inspect_unsupported_targets()
    print("All sqlalchemy.inspect contract assertions passed successfully.")


if __name__ == "__main__":
    main()

原始种子者

匿名