Advertisement
Guest User

Untitled

a guest
Apr 9th, 2022
403
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 1.37 KB | None | 0 0
  1. import sqlalchemy as sa
  2. from sqlalchemy.orm import declarative_base, Session
  3.  
  4. engine = sa.create_engine("mssql+pyodbc://scott:tiger^5HHH@mssql_199")
  5.  
  6. Base = declarative_base()
  7.  
  8.  
  9. class User(Base):
  10.     __tablename__ = "user"
  11.  
  12.     user_id = sa.Column(sa.Integer, primary_key=True)
  13.     full_name = sa.Column(sa.String(255), nullable=False)
  14.     type = sa.Column(sa.String(50))
  15.  
  16.     __mapper_args__ = {
  17.         "polymorphic_identity": "user",
  18.         "polymorphic_on": type,
  19.     }
  20.  
  21.  
  22. class Employee(User):
  23.     __tablename__ = User.__tablename__
  24.     __table_args__ = {"schema": "test_schema"}
  25.  
  26.     id = sa.Column(sa.Integer, sa.ForeignKey("user.user_id"), primary_key=True)
  27.     company_id = sa.Column(sa.Integer)
  28.  
  29.     __mapper_args__ = {
  30.         "polymorphic_identity": "employee",
  31.     }
  32.  
  33.  
  34. Base.metadata.drop_all(engine)
  35. Base.metadata.create_all(engine)
  36.  
  37. with engine.connect() as conn:
  38.     print(
  39.         f'default schema: {conn.exec_driver_sql("SELECT SCHEMA_NAME()").scalar()}'
  40.     )
  41.     # default schema: dbo
  42.  
  43. with Session(engine) as sess:
  44.     sess.add(Employee(full_name="Gord Thompson", company_id=123))
  45.     sess.commit()
  46.  
  47. with engine.connect() as conn:
  48.     print(conn.exec_driver_sql("SELECT * FROM dbo.[user]").all())
  49.     # [(1, 'Gord Thompson', 'employee')]
  50.     print(conn.exec_driver_sql("SELECT * FROM test_schema.[user]").all())
  51.     # [(1, 123)]
  52.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement