How to fetch rows from postgresql database by specifying schema? - python

I am new to Postgresql & Sqlalchemy. I have below file layout.py. In this, I have created two table name "layout" & "layout default" under "col" schemas.
import json, decimal
from sqlalchemy.dialects.postgresql import UUID
from sqlalchemy import create_engine
from sqlalchemy import Column, String, Integer, TIMESTAMP, Sequence, text, types
from sqlalchemy.ext.declarative import declarative_base
from sqlalchemy.orm import sessionmaker
import datetime, uuid
db_string = "postgres://postgres:PWDd#10.**.**.***:1111/d_demo"
Base = declarative_base()
db = create_engine(db_string)
class Layout(Base):
__tablename__ = "col.layout"
layout_id = Column(UUID(as_uuid=True), nullable=False, primary_key=True)
name = Column(String(1000), nullable=False)
layout = Column(String(10000), nullable=False)
grid_id = Column(Integer, nullable=False)
user_id = Column(Integer, nullable=False)
issystemlayout = Column(Integer, default=0, nullable=False)
ispublic = Column(Integer, default=0, nullable=False)
isactive = Column(Integer, default=0, nullable=False)
createdby = Column(Integer, default=1, nullable=False)
createdat = Column(TIMESTAMP, default=(datetime.datetime.now()), nullable=False)
modifiedat = Column(TIMESTAMP, default=(datetime.datetime.now()), nullable=False)
modifiedby = Column(Integer, default=1, nullable=False)
Insert datas :
INSERT INTO col.layout(layout_id,name,layout,grid_id,user_id,ispublic,issystemlayout,isactive,createdby,createdat, modifiedat,modifiedby) VALUES('ba0233d7-d917-4303-b4bf-c2544a617d33','Layout1','{"Name":"Manish","Place":"Pune"}',1,12345,'1','0','1','201819','2015/05/20','2015/05/16',123);
Fetching data :
Session = sessionmaker(bind=db)
session = Session()
Base.metadata.create_all(db)
session.query("SET search_path TO col;")
result = []
selected_columns = Layout.__table__.columns
print("Selected columns {}".format(selected_columns))
record = session.query(Layout).with_entities(*selected_columns).all()
for row in record:
print(row)
result.append(row)
print(json.dumps(result))
session.close()
But it is not showing data under "col" schemas. Please suggest, how should I do?

https://docs.sqlalchemy.org/en/13/orm/extensions/declarative/table_config.html#table-configuration
Schema for postgres database can be passed through table_args attribute either as a tuple or a dict.
So for your problem your class definition should have this extra attribute:
class Layout(Base):
__tablename__ = "layout"
__table_args__ = {"schema": "col"}
layout_id = Column(UUID(as_uuid=True), nullable=False, primary_key=True)
name = Column(String(1000), nullable=False)
layout = Column(String(10000), nullable=False)
grid_id = Column(Integer, nullable=False)
user_id = Column(Integer, nullable=False)
issystemlayout = Column(Integer, default=0, nullable=False)
ispublic = Column(Integer, default=0, nullable=False)
isactive = Column(Integer, default=0, nullable=False)
createdby = Column(Integer, default=1, nullable=False)
createdat = Column(TIMESTAMP, default=(datetime.datetime.now()), nullable=False)
modifiedat = Column(TIMESTAMP, default=(datetime.datetime.now()), nullable=False)
modifiedby = Column(Integer, default=1, nullable=False)

Related

sqlalchemy throws an error when using foreign_key

Hi can someone help with this sqlalchemy code. When i invoke this code, it throws this error
~/.local/lib/python3.8/site-packages/sqlalchemy/sql/base.py:425: SAWarning: Can't validate argument 'foreign_key'; can't locate any SQLAlchemy dialect named 'foreign'
util.warn(
Code follows:
from sqlalchemy.ext.declarative import declarative_base
from sqlalchemy import Column, Integer, String
Base = declarative_base()
class Users(Base):
__tablename__ = 'users'
email = Column(String, primary_key=True, nullable=False)
firstname = Column(String)
lastname = Column(String)
userid = Column(String, unique=True, nullable=False)
class Account(Base):
__tablename__ = 'account'
userid = Column(Integer, foreign_key='Users.userid', nullable=False)
internal_account_id = Column(Integer, primary_key=True, nullable=False)
account_id = Column(String, nullable=False)

How to set relationship between two tables in SQLAlchemy?

I have got two tables:
Announcements
AnnouncementsSchedule
Relationship is one(Announcements) to many(AnnouncementsSchedule) by keys:
Announcements.id = AnnouncementsSchedule.announcements_id
I tried to describe models in SQLAlchemy:
The first table is described as model:
class Announcements(db.Model):
__tablename__ = 'announcements'
id = db.Column(db.Integer, primary_key=True)
name = db.Column(db.String(150), nullable=False)
text = db.Column(db.Text(), nullable=False)
category = db.Column(db.Integer(), nullable=False)
subcategory = db.Column(db.Integer(), nullable=False)
offer_type = db.Column(db.Integer(), nullable=False)
url = db.Column(db.String(150), nullable=True)
status = db.Column(db.Integer(), nullable=False)
#children = relationship("AnnouncementsSchedule", back_populates="announcements")
Second is:
class AnnouncementsSchedule(db.Model):
__tablename__ = 'announcements_schedule'
id = Column(Integer, primary_key=True)
week_day = db.Column(db.Integer(), nullable=True)
week_all = db.Column(db.Integer(), nullable=False)
time = db.Column(db.Time(), nullable=False)
announcement_id = Column(Integer, ForeignKey('announcements.announcements_id'))
What I do wrong?
You have a mistake in the column name (announcements doesn't have announcement_id ):
# announcement_id = Column(Integer, ForeignKey('announcements.announcements_id'))
# change to ->
announcement_id = Column(Integer, ForeignKey('announcements.id'))

Database tables generation using sqlalchemy

I'm currently trying to generate SQL tables using the sqlalchemy library.
I have two tables : t_volume and t_volume_snapshot
class Volume(...):
""" Represent a volume element"""
__tablename__ = "t_volume"
created_at = Column(DateTime, nullable=False)
deleted_at = Column(DateTime, nullable=False)
volume_id = Column(String(length=255), nullable=False, primary_key=True)
volume_name = Column(String(length=255), nullable=False)
volume_type = Column(String(length=255), nullable=False)
volume_disk_space = Column(Integer, nullable=False)
class VolumeSnapshot(...):
""" Represent a volume snapshot element"""
__tablename__ = "t_volume_snapshot"
created_at = Column(DateTime, nullable=False)
deleted_at = Column(DateTime, nullable=False)
volume_snapshot_id = Column(String(length=255), nullable=False, primary_key=True)
volume_snapshot_name = Column(String(length=255), nullable=False)
volume_id = Column(String(length=255), ForeignKey("t_volume.volume_id"))
I would like that a volume snapshot refers to a volume using the value volume_id. I tried to define the t_volume_snapshot.volume_id column as a ForeignKey pointing to t_volume.volume_id but all I get is
OperationalError: (OperationalError) (1005, "Can't create table 'db.t_volume_snapshot' (errno: 150)")
I'm not used to sqlalchemy and SQL in general so I'm probably missing something...
You should be able to do something like below
class Volume(...):
""" Represent a volume element"""
__tablename__ = "t_volume"
created_at = Column(DateTime, nullable=False)
deleted_at = Column(DateTime, nullable=False)
volume_id = Column(String(length=255), nullable=False, primary_key=True)
volume_name = Column(String(length=255), nullable=False)
volume_type = Column(String(length=255), nullable=False)
volume_disk_space = Column(Integer, nullable=False)
snapshots = relationship("VolumeSnapshot", back_populates="t_volume")
class VolumeSnapshot(...):
""" Represent a volume snapshot element"""
__tablename__ = "t_volume_snapshot"
created_at = Column(DateTime, nullable=False)
deleted_at = Column(DateTime, nullable=False)
volume_snapshot_id = Column(String(length=255), nullable=False, primary_key=True)
volume_snapshot_name = Column(String(length=255), nullable=False)
snapshot_volume_id = Column(String(length=255), ForeignKey("volume_id"))
This should establish a bidirectional connection.

how to insert symbol(,) to result in SQLAlchemy level?

#mapping class
class Billing(Base):
__tablename__ = 'billing'
id = Column(Integer, primary_key=True)
billingdate= Column(DateTime, nullable=False)
amt = Column(Integer, nullable=False)
rate = Column(Integer, nullable=False)
fk_cpid = Column(Integer, ForeignKey('company.cpid'))
#run
query = self.mssql_session.query(Billing.billingdate).all()
result
$83749283 => $83,749,283
how to insert symbol(,) at Billing.billingdate in ONLY SQLAlchemy level?
Replace, SubString?
from sqlalchemy.ext.hybrid import hybrid_property
class Billing(Base):
__tablename__ = 'billing'
id = Column(Integer, primary_key=True)
billingdate= Column(DateTime, nullable=False)
_amt = Column(Integer, nullable=False)
rate = Column(Integer, nullable=False)
fk_cpid = Column(Integer, ForeignKey('company.cpid'))
#hybrid_property
def amt(self):
return '${:,}'.format(self._amt)
Hopes, this code can help you.

How to fetch pairs from join where second value can be none, left join

I have two models in database like
class Base(object):
def __tablename__(self):
return self.__name__.lower()
id = Column(Integer, primary_key=True, nullable=False)
utc_time = Column(BigInteger, default=utc_time, onupdate=utc_time)
class EntityModel(Base):
__tablename__ = 'entities'
town_id = Column(Integer, ForeignKey('towns.id', ondelete='CASCADE'), nullable=False)
type = Column(Integer, nullable=False)
level = Column(Integer, nullable=False, default=Level.LEVEL_ONE)
energy = Column(Float, nullable=False, default=0)
x = Column(Integer, nullable=False)
y = Column(Integer, nullable=False)
class CommandModel(Base):
__tablename__ = 'commands'
entity_id = Column(Integer, ForeignKey('entities.id', ondelete='CASCADE'), nullable=False)
command = Column(Integer, nullable=False)
started_at = Column(BigInteger, nullable=False)
ends_at = Column(BigInteger, nullable=False)
type = Column(Integer, default=None)
Entity can have one or none command. How to fetch pairs entity, command (entity can exists without command)
I tried like but it doesn't work
for e, c in session.query(EntityModel, CommandModel).join(CommandModel).filter(EntityModel.town_id == 100).all():
You can use outerjoin for a left outer join, which seems to be what you want.
http://docs.sqlalchemy.org/en/rel_0_7/orm/query.html#sqlalchemy.orm.query.Query.outerjoin

Categories