how to create table from sqlalchemy mapping - python

I have the following ORM mapping using SqlAlchemy:
class Foo(Base):
__tablename__ = "foo"
id = Column(Integer, primary_key=True)
name = Column(String)
date_imported = Column(DateTime)
However, how can I either get the CREATE TABLE sql syntax or how I can I have it create the table for me?

Use Foo.__table__.create(bind=engine, checkfirst=True) to issue the statement for that table, or metadata.create_all(bind=engine) to issue the statements for all tables registered on that metadata. If you are using Flask-SQLAlchemy, use db.create_all() to honor binds correctly.

Related

Postgresql Sqlalchemy dynamic table partition creation issue

I'm using postgresql and python sqllachmey for creating the partitioned table. Below is the example code.
from sqlalchemy.ext.declarative import declarative_base
from sqlalchemy.types import Text
Base = declarative_base()
class Students(Base):
__tablename__ = "Students"
id = Column(Text, primary_key=True)
name = Column(Text)
type = Column(Text)
desc = Column(Text)
creation_time = Column(DateTime, default=func.now(), nullable=False, primary_key=True)
__table_args__ = {
'postgresql_partition_by': 'RANGE (creation_time)'
}
table_list = [Students.__table__]
Base.metadata.create_all(self.engine, tables=table_list)
The above code creates a paritioned table and i'm creating the partitions using pg_partman extension.
Now, my need is that I want to use the class 'Students' for creating the student table under different databases, and some databases don't need the partitioned table. How can I make the above code dynamic so that I can take out 'postgresql_partition_by' from table_args?
According to the documents, it looks like, I have to use dictionary for table column definition but I'm not quite sure about it.
The keyword arguemnts of Table (or __table_args__) are dialect specific, so your postgresql_partition_by will only be used with postgresql dialects, not sqlite or others.
class sqlalchemy.schema.Table(*args, **kw)
[...]
**kw – Additional keyword arguments not mentioned above are dialect specific, and passed in the form <dialectname>_<argname>. See the documentation regarding an individual dialect at Dialects for detail on documented arguments.

SQLalchemy: Could not determine join condition between parent/child tables on relationship

So I have these two simple classes inside the same python file which I'm trying to map with SQLAlchemy, where User column 'password_id' is a foreign key to the table Password 'password_id' column as well
from sqlalchemy.orm import relationship, declarative_base
from sqlalchemy import Column, Integer, String
from sqlalchemy.sql.schema import ForeignKey
Base = declarative_base()
class User(Base):
__tablename__ = 'users'
user_id = Column(Integer, primary_key=True)
name = Column(String)
email = Column(String)
password_id = Column(Integer, ForeignKey('password.password_id'))
parent = relationship("Password", back_populates="users")
class Password(Base):
__tablename__ = 'passwords'
password_id = Column(Integer, primary_key=True)
password = Column(String)
last_change_date = Column(DateTime)
valid_until = Column(DateTime)
child = relationship("User", back_populates="passwords", uselist=False)
Here's the db schema for context:
I'm following this guide from sql alchemy but for some reason I keep getting the error from the title 'Ensure that referencing columns are associated with a ForeignKey or ForeignKeyConstraint, or specify a 'primaryjoin' expression.', which is strange because accorind to what I see in the guide, my classes have been mapped correctly so I can't understand why this error is happening.
Thank you in advance
I think the issue is in the following line (the table name in ForeignKey)...
password_id = Column(Integer, ForeignKey('password.password_id'))
should be passwords instead of password.

How to ignore some models to migrate? [duplicate]

I am using Flask-SQLAlchemy to define my models, and then using Flask-Migrate to auto-generate migration scripts for deployment onto a PostgreSQL database. I have defined a number of SQL Views on the database that I use in my application like below.
However, Flask-Migrate now generates a migration file for the view as it thinks it's a table. How do I correctly get Flask-Migrate / Alembic to ignore the view during autogenerate?
SQL View name: vw_SampleView with two columns: id and rowcount.
class ViewSampleView(db.Model):
__tablename__ = 'vw_report_high_level_count'
info = dict(is_view=True)
id = db.Column(db.String(), primary_key=True)
rowcount = db.Column(db.Integer(), nullable=False)
Which means I can now do queries like so:
ViewSampleView.query.all()
I tried following instructions on http://alembic.zzzcomputing.com/en/latest/cookbook.html and added the info = dict(is_view=True) portion to my model and the following bits to my env.py file, but don't know where to go from here.
def include_object(object, name, type_, reflected, compare_to):
"""
Exclude views from Alembic's consideration.
"""
return not object.info.get('is_view', False)
...
context.configure(url=url,include_object = include_object)
I think (though haven't tested) that you can mark your Table as a view with the __table_args__ attribute:
class ViewSampleView(db.Model):
__tablename__ = 'vw_report_high_level_count'
__table_args__ = {'info': dict(is_view=True)}
id = db.Column(db.String(), primary_key=True)
rowcount = db.Column(db.Integer(), nullable=False)

Python SqlAlchemy relationships

I'm using Python 2.7.5 and SqlAlchemy 0.9.9 (against an Oracle 11 database) and am trying to figure out how I can create a relationship between two tables where the join value is a string in one table and an integer in another. Here's mockup of my two tables:
class BatchInput(db.Model):
__tablename__ = 'batchinput'
batchinput_id = Column(Integer, primary_key=True)
item_id = Column(Integer)
class SubBatch(db.Model):
__tablename__ = 'subbatch'
subbatch_id = Column(Integer, primary_key=True)
subbatch_no = Column(String)
batch_input = relationship('BatchInput',
primaryjoin='SubBatch.subbatch_no == cast(BatchInput.item_id, VARCHAR)')
When I run a query to get subbatches I get this message:
Internal Server Error, Could not locate any relevant foreign key
columns for primary join condition
'subbatch.subbatchno = CAST(forgebatchinput.item_id AS VARCHAR)'
on relationship SubBatch.forge_batch_input. Ensure that
referencing columns are associated with a ForeignKey or
ForeignKeyConstraint, or are annotated in the join condition
with the foreign() annotation
I've tried a couple variations of this adding foreignkeys and remote, etc., but always get this message. I'm not sure what it's trying to tell me as I do have a primaryjoin specified.

Is there a workaround in sqlalchemy for loading a table from DB without any primary keys?

I have a situation where i load all tables from legacy database. but it gives an error since it does not have any primary keys.
Can anyone give me a solution for this error ?
You can add the primary key information to the autoloaded table.
e.g.
class Subscrib(Base):
__tablename__ = 'mytable'
__table_args__ = {'autoload' : True}
thepk = Column(Integer, primary_key=True)

Categories

Resources