Advertisement
Guest User

Untitled

a guest
Apr 29th, 2020
128
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 1.87 KB | None | 0 0
  1. import sqlalchemy as sa
  2. from sqlalchemy.ext.declarative import declarative_base
  3. from sqlalchemy.orm import relationship, sessionmaker
  4.  
  5. engine = sa.create_engine(
  6.     r"mssql+pyodbc://@localhost:49242/myDb?driver=ODBC+Driver+17+for+SQL+Server"
  7. )
  8.  
  9. with engine.connect() as conn:
  10.     for tb_name in ["tbl_a", "tbl_c", "tbl_b"]:
  11.         conn.execute(sa.text(f"DROP TABLE IF EXISTS [{tb_name}]"))
  12.  
  13. Base = declarative_base()
  14.  
  15.  
  16. class A(Base):
  17.     __tablename__ = "tbl_a"
  18.     id = sa.Column(sa.Integer(), primary_key=True)
  19.     b_id = sa.Column(sa.Integer(), sa.ForeignKey("tbl_b.id"))
  20.     c_id = sa.Column(sa.Integer(), sa.ForeignKey("tbl_c.id"))
  21.     related_b = relationship("B", back_populates="related_as")
  22.     related_c = relationship("C", back_populates="related_as")
  23.  
  24.  
  25. class B(Base):
  26.     __tablename__ = "tbl_b"
  27.     id = sa.Column(sa.Integer(), primary_key=True)
  28.     related_cs = relationship("C", back_populates="related_b")
  29.     related_as = relationship("A", back_populates="related_b")
  30.  
  31. class C(Base):
  32.     __tablename__ = "tbl_c"
  33.     id = sa.Column(sa.Integer(), primary_key=True)
  34.     b_id = sa.Column(sa.Integer(), sa.ForeignKey("tbl_b.id"))
  35.     related_b = relationship("B", back_populates="related_cs")
  36.     related_as = relationship("A", back_populates="related_c")
  37.  
  38.  
  39. Base.metadata.create_all(engine)
  40.  
  41. Session = sessionmaker(bind=engine)
  42. session = Session()
  43.  
  44. b11 = B(id=11)
  45. c111 = C(id=111)
  46. c111.related_b = b11
  47.  
  48. a1 = A(id=1)
  49. b22 = B(id=22)
  50. a1.related_c = c111
  51. a1.related_b = b22
  52.  
  53. session.add_all([b11, a1])
  54. session.commit()
  55.  
  56. # verify by reading tables
  57. with engine.connect() as conn:
  58.     print(conn.execute(sa.text("SELECT * FROM tbl_b")).fetchall())
  59.     # [(11,), (22,)]
  60.     print(conn.execute(sa.text("SELECT * FROM tbl_c")).fetchall())
  61.     # [(111, 11)]
  62.     print(conn.execute(sa.text("SELECT * FROM tbl_a")).fetchall())
  63.     # [(1, 22, 111)]
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement