我的 SQLAlchemy 2.0 与 SQLite 数据库的映射列正在创建一个主键列,因此我无法插入。
模式类别:
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
我认为在 SQLite 中需要像这样创建主键:
id integer primary key autoincrement
。如何映射列来创建这样的主键?
您还需要创建一个负责自动递增的序列:
class UserClass(Base):
__tablename__ = "user"
id_seq = sa.Sequence("seq_user_id", metadata= Base.metadata)
id: Mapped[Integer] = mapped_column(Integer, primary_key=True, server_default=id_seq.next_value())
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())