mirror of
				https://github.com/fastapi/sqlmodel.git
				synced 2025-11-04 06:37:29 +08:00 
			
		
		
		
	Co-authored-by: pre-commit-ci[bot] <66853113+pre-commit-ci[bot]@users.noreply.github.com> Co-authored-by: Sebastián Ramírez <tiangolo@gmail.com>
		
			
				
	
	
		
			38 lines
		
	
	
		
			1.3 KiB
		
	
	
	
		
			Python
		
	
	
	
	
	
			
		
		
	
	
			38 lines
		
	
	
		
			1.3 KiB
		
	
	
	
		
			Python
		
	
	
	
	
	
from typing import Any, List, Union
 | 
						|
 | 
						|
import pytest
 | 
						|
from sqlmodel import Field, Relationship, SQLModel
 | 
						|
 | 
						|
 | 
						|
def test_ondelete_requires_nullable(clear_sqlmodel: Any) -> None:
 | 
						|
    with pytest.raises(RuntimeError) as exc:
 | 
						|
 | 
						|
        class Team(SQLModel, table=True):
 | 
						|
            id: Union[int, None] = Field(default=None, primary_key=True)
 | 
						|
 | 
						|
            heroes: List["Hero"] = Relationship(
 | 
						|
                back_populates="team", passive_deletes="all"
 | 
						|
            )
 | 
						|
 | 
						|
        class Hero(SQLModel, table=True):
 | 
						|
            id: Union[int, None] = Field(default=None, primary_key=True)
 | 
						|
            name: str = Field(index=True)
 | 
						|
            secret_name: str
 | 
						|
            age: Union[int, None] = Field(default=None, index=True)
 | 
						|
 | 
						|
            team_id: int = Field(foreign_key="team.id", ondelete="SET NULL")
 | 
						|
            team: Team = Relationship(back_populates="heroes")
 | 
						|
 | 
						|
    assert 'ondelete="SET NULL" requires nullable=True' in str(exc.value)
 | 
						|
 | 
						|
 | 
						|
def test_ondelete_requires_foreign_key(clear_sqlmodel: Any) -> None:
 | 
						|
    with pytest.raises(RuntimeError) as exc:
 | 
						|
 | 
						|
        class Team(SQLModel, table=True):
 | 
						|
            id: Union[int, None] = Field(default=None, primary_key=True)
 | 
						|
 | 
						|
            age: int = Field(ondelete="CASCADE")
 | 
						|
 | 
						|
    assert "ondelete can only be used with foreign_key" in str(exc.value)
 |