PostgreSQL+Alembic环境下persons表已存在却报不存在错误
PostgreSQL + Alembic 迁移后查询报错:表存在但提示"relation does not exist"
执行数据库迁移后,已确认persons表实际存在,但调用validateExistPerson函数进行查询时触发如下错误:
sqlalchemy.exc.ProgrammingError: (psycopg2.errors.UndefinedTable) relation "persons" does not exist test_srit | LINE 2: FROM persons test_srit | ^ test_srit | test_srit | [SQL: SELECT persons.id AS persons_id, persons.name AS persons_name, persons.email AS persons_email test_srit | FROM persons test_srit | WHERE persons.name = %(name_1)s test_srit | LIMIT %(param_1)s] test_srit | [parameters: {'name_1': 'maria gomez', 'param_1': 1}] test_srit | (Background on this error at: https://sqlalche.me/e/20/f405)
相关代码
数据库连接代码
from sqlalchemy import create_engine from sqlalchemy.orm import sessionmaker ,declarative_base from database.base import SQLALCHEMY_DATABASE_URL DATABASE_URL = SQLALCHEMY_DATABASE_URL engine = create_engine(DATABASE_URL,pool_pre_ping=True, pool_size=20, max_overflow=30) SessionLocal = sessionmaker(autocommit=False, autoflush=False, bind=engine) Base = declarative_base() def get_db(): db = SessionLocal() try: yield db finally: db.close()
Person模型代码
class Person(Base): __tablename__ = "persons" id = Column("id",Integer, primary_key=True, index=True,autoincrement=True) name = Column("name",String(50)) email = Column("email",String(50))
已执行的迁移命令
alembic revision --autogenerate -m "create table" alembic upgrade head
验证函数代码
def validateExistPerson(db: Session, name: str) -> bool: existPerson = getPersonByName(db, name) if not existPerson: return False return True
接口路由代码
@person_router.post( '/add', tags=["Person"], response_model=Person, status_code=status.HTTP_201_CREATED, ) async def addPerson(person: Person, db: Session = Depends(get_db)): existPerson = validateExistPerson(db, person.name) if existPerson: raise HTTPException(status_code=status.HTTP_400_BAD_REQUEST, detail="Name person already exist") result = createPerson(person, db) if result: return result raise HTTPException(status_code=status.HTTP_400_BAD_REQUEST, detail="Error to create person")
可能的原因及排查方案
- 数据库Schema不匹配:PostgreSQL默认使用
publicschema,若迁移脚本将表创建到其他schema,或连接字符串未指定schema,SQLAlchemy会默认查找public下的表。检查SQLALCHEMY_DATABASE_URL是否指定了正确的schema,比如添加?options=-csearch_path%3Dyour_schema参数。 - 迁移脚本未正确生成或执行:查看
alembic/versions目录下对应的迁移文件,确认是否包含创建persons表的DDL语句;执行alembic current命令,检查当前迁移版本是否与head一致。 - Base类不统一:数据库连接代码中重新定义了
Base = declarative_base(),但Person模型可能继承自其他文件中的Base类(比如database.base里的),导致Alembic未识别到该模型,迁移时未创建表。确保模型的Base类与Alembic配置中使用的Base是同一个。 - 表名大小写问题:PostgreSQL对表名大小写敏感,若迁移时创建的是带双引号的
"Persons",而模型中__tablename__设为小写persons,查询时会找不到表。直接查询数据库确认表名的实际大小写,保持与模型配置一致。 - 连接池缓存旧连接:迁移后连接池中的旧连接可能未感知到表的变化,重启应用程序让连接池重新建立连接即可。
内容的提问来源于stack exchange,提问作者Lana YC.
相关产品推荐
相关产品推荐

