SQLAlchemy 2.0 映射列主键在 SQLLite 中不起作用

问题描述 投票:0回答:1

在使用 SQLLite 数据库测试

SQLAlchemy 2.0
映射列时,它正在创建具有主键值的表。但表现在显示其使用主键创建的。因此无法将值插入到该表中。

模式类

import datetime
from typing import Optional

from sqlalchemy import String, TIMESTAMP, Integer
from sqlalchemy import func
from sqlalchemy.dialects import postgresql, sqlite
from sqlalchemy.orm import DeclarativeBase
from sqlalchemy.orm import Mapped, mapped_column
from sqlalchemy.schema import CreateTable
from typing_extensions import Annotated

timestamp = Annotated[datetime.datetime, mapped_column(nullable=False, server_default=func.CURRENT_TIMESTAMP()),]


class Base(DeclarativeBase):
    type_annotation_map = {datetime.datetime: TIMESTAMP(timezone=True), }


class UserClass(Base):
    __tablename__ = "user"

    id: Mapped[Integer] = mapped_column(Integer, primary_key=True, autoincrement=True)
    name: Mapped[str] = mapped_column(String(50))
    fullname: Mapped[Optional[str]] = mapped_column(String(50), nullable=False)
    nickname: Mapped[Optional[str]] = mapped_column(String(30))
    date: Mapped[datetime.datetime]
    status: Mapped[str]
    created_at: Mapped[timestamp] = mapped_column(server_default=func.UTC_TIMESTAMP())
    updated_at: Mapped[timestamp] = mapped_column(server_default=func.UTC_TIMESTAMP())

桌子

它的创建表是这样的:

CREATE TABLE user (
    id BIGINT NOT NULL, 
    name VARCHAR(50) NOT NULL, 
    fullname VARCHAR(50) NOT NULL, 
    nickname VARCHAR(30), 
    date TIMESTAMP NOT NULL, 
    status VARCHAR NOT NULL, 
    created_at TIMESTAMP DEFAULT (UTC_TIMESTAMP()) NOT NULL, 
    updated_at TIMESTAMP DEFAULT (UTC_TIMESTAMP()) NOT NULL, 
    PRIMARY KEY (id)
);

但是当我插入值时,给出以下错误消息:

插入命令:

INSERT INTO user (name, fullname, nickname, date, status, created_at, updated_at) VALUES ('John', 'John Doe', 'Johnny', '2024-09-21 19:09:51.484769', 'active', '2024-09-21 19:09:51.490379', '2024-09-21 19:09:51.490400')

sqlite3.IntegrityError)NOT NULL 约束失败:user.id

我认为主键需要在sqllite中像这样创建

id integer primary key autoincrement
。如何映射列来创建这样的主键?

谢谢

python sqlite sqlalchemy flask-sqlalchemy alembic
1个回答
0
投票

在 SQLite 中

声明为 INTEGER PRIMARY KEY 的列将自动增量。

https://www.sqlite.org/faq.html#q1

插入时,您必须在该列上传递

NULL

创建表如下:

CREATE TABLE user (
    id INTEGER PRIMARY KEY, 
    name VARCHAR(50) NOT NULL, 
    fullname VARCHAR(50) NOT NULL, 
    nickname VARCHAR(30), 
    date TIMESTAMP NOT NULL, 
    status VARCHAR NOT NULL, 
    created_at TIMESTAMP DEFAULT (UTC_TIMESTAMP()) NOT NULL, 
    updated_at TIMESTAMP DEFAULT (UTC_TIMESTAMP()) NOT NULL, 
);

通过在主键中传递 NULL 来插入:

INSERT INTO user (id, name, fullname, nickname, date, status, created_at, updated_at) VALUES (NULL, 'John', 'John Doe', 'Johnny', '2024-09-21 19:09:51.484769', 'active', '2024-09-21 19:09:51.490379', '2024-09-21 19:09:51.490400')
© www.soinside.com 2019 - 2024. All rights reserved.