integer out of range error in BigInteger sqlalchemy column on heroku - python-3.x

I'm trying to understand why I'm getting sql errors for the following objects.
I'm using a PostGresSql database on heroku
class Member(BASE):
__tablename__ = "members"
name = Column(String)
discord_id = Column(BigInteger, primary_key=True,nullable=False)
role = Column(String, ForeignKey('roles.name'))
nick = Column(String)
rs_runs = relationship("RSRun",secondary='member_on_rs_run')
def __init__(self,name,discord_id,nick="" ):
self.name = name
self.discord_id = discord_id
self.nick = nick
class RSRun(BASE):
__tablename__ = "rs_runs"
id = Column(Integer, primary_key=True, nullable=False)
level = Column(String)
dtg = Column(DateTime)
members = relationship("Member",secondary='member_on_rs_run')
class MemberOnRSRun(BASE):
__tablename__ = "member_on_rs_run"
member_id = Column(BigInteger, ForeignKey('members.discord_id'),primary_key = True)
run_id = Column(Integer,ForeignKey('rs_runs.id'),primary_key=True)
The errors I'm getting are here
sqlalchemy.exc.DataError: (psycopg2.errors.NumericValueOutOfRange) integer out of range
[SQL: INSERT INTO members (name, discord_id, role, nick) VALUES (%(name)s, %(discord_id)s, %(role)s, %(nick)s)]
[parameters: {'name': '', 'discord_id': 126793648221192192, 'role': None, 'nick': ''}]
I've checked and the discord_id is within legal range of a PostGres BigInt which is what I'm assuming I'm getting with an sqlalchemy Biginteger Column. But it keeps telling me it's out of range for integer. Obviously I want to use the same ID that Discord is using since that is the identifier for a member on Discord.

Making changes to the python objects that you are using in the sqlalchemy declarative form will not FORCE heroku to update the database. You must manually blow away the database for these changes to take affect.

Related

Error Iterating over Join Query results using Peewe (PostgreSQL)

I am not able to iterate through my query as I would like using Peewee
Those are the related Objects in Models.py
class Conversation(peewee.Model):
id = peewee.AutoField(unique=True, index=True)
creation_date = peewee.DateTimeField(default=datetime.now)
contact_id = ForeignKeyField(Contact, backref='conversation')
launch_id = ForeignKeyField(Launch, backref='conversation')
request_data = peewee.TextField(null=True)
status = peewee.TextField(null=True)
class Contact(peewee.Model):
id = peewee.AutoField(unique=True, index=True)
uuid = peewee.CharField(default=shortuuid.uuid, index=True)
whatsapp_phone = peewee.CharField(index=True, default='')
status = peewee.CharField(default='init')
conversationId = peewee.CharField(null=True)
Here's how I am trying to iterate:
for conversation in Conversation.select().where(Conversation.launch_id == str(launch_id)):
print(conversation.contact.id)
And this is the error that I a getting:
print(conversation.contact.id)
AttributeError: 'Conversation' object has no attribute 'contact'
I've tried to change the way I do my query:
query = Conversation.select(Contact).join(Contact).where(Conversation.launch_id == str(launch_id))
But I get the exact same error if I iterate in the same way.
The issue is you are, for some reason, trying to access .contact when you've named your foreign-key .contact_id. The peewee docs are clear about foreign key naming, but you want this:
class Conversation(peewee.Model):
id = peewee.AutoField(unique=True, index=True)
creation_date = peewee.DateTimeField(default=datetime.now)
# Data will be stored in a column named "contact_id":
contact = ForeignKeyField(Contact, backref='conversations')
# Data will be stored in a column named "launch_id":
launch = ForeignKeyField(Launch, backref='conversations')
request_data = peewee.TextField(null=True)
status = peewee.TextField(null=True)
This allows:
query = (Conversation
.select()
.where(Conversation.launch == str(launch_id)))
for conversation in query:
# Access the underlying foreign-key value.
print(conversation.contact_id)
Or, if you intend to access other fields on the Contact:
query = (Conversation
.select(Conversation, Contact)
.join(Contact)
.where(Conversation.launch == str(launch_id)))
for conversation in query:
# We now have a "full" Contact instance we can access efficiently:
print(conversation.contact.id)
Please read the docs:
http://docs.peewee-orm.com/en/latest/peewee/quickstart.html#lists-of-records
http://docs.peewee-orm.com/en/latest/peewee/relationships.html
http://docs.peewee-orm.com/en/latest/peewee/models.html#foreignkeyfield

How to extract date of birth from the database and match it with the current date

I'm trying to build a flask app and can't figure out a way to extract and match the date of birth of the student with the current date. I'm using sqlalchemy and postgresql.
Below are the models.
class School(db.Model, UserMixin):
__tablename__ = 'school'
id = db.Column(db.Integer, primary_key=True)
email = db.Column(EmailType, nullable = False, unique = True)
username = db.Column(db.String(20), nullable = False, unique = True)
name = db.Column(db.String(100))
class Student(db.Model):
__tablename__ = 'Student'
id = db.Column(db.Integer, primary_key = True)
user_id = db.Column(db.Integer, db.ForeignKey('user.id'), nullable = False)
fname = db.Column(db.String(100))
lname = db.Column(db.String(100))
dob = db.Column(db.Date(), nullable = True)
email = db.Column(EmailType, nullable = False)
user = relationship("School", foreign_keys=[school_id])
verified = db.Column(db.Boolean, default = False, nullable = False)
I want to build a route from where school can send birthday wishes to verified students.
I have tried
#app.route('/dashboard/birthday/',methods=['GET', 'POST'])
#login_required
def birthday():
error = None
user = current_user
id = user.id
total_std = Student.query.filter_by(user_id=id)
verified_std = total_std.filter_by(verified=True).all()
birth = verified_std.dob.strftime('%m/%d/%Y')
ttl = len(birth) #this is to check if things are working or not
return render_template_string('test.html', ttl=ttl)
When I'm running this I'm getting an error
AttributeError: 'list' object has no attribute 'dob'
I want to make a route from where schools can send birthday wishes to verified students only.

I am not able to load Self Reference in SQLAlchemy

I currently having an issue with a self reference relationship.
I have the table Customer which can have a parent (also a Customer) like this:
class CustomerModel(db.Model):
__tablename__ = 'customer'
id = Column(Integer, primary_key=True)
parent_id = Column(Integer, ForeignKey('customer.id'))
parent = relationship("CustomerModel", foreign_keys=[parent_id])
So my problem is that when I'm trying to load the parent, the following query is built by SQLAlchemy:
Lets take this customer for example: Customer(id=1, parent_id=10)
SELECT *
FROM customer
WHERE 1 = customer.parent_id
So the WHERE condition is wrong because it compares the parent_id to the id of the customer I'm trying to load the parent from.
The correct query should be:
SELECT *
FROM customer
WHERE 10 = customer.parent_id
What am I doing wrong?
So i finally found the answer.
I need to add the param remote_side like this:
class CustomerModel(db.Model):
__tablename__ = 'customer'
id = Column(Integer, primary_key=True)
parent_id = Column(Integer, ForeignKey('customer.id'))
parent = relationship("CustomerModel", foreign_keys=[parent_id], remote_side=[id])

SQLAlchemy-Flask Bind not working - NameError: name 'TABLE' is not defined

I'm looking to use Flask-SQLAlchemy Bind to connect to a secondary Oracle database. I'm getting an error that says the table I want to connect to is not defined although it is defined in my model with the appropriate bind configuration added. Here is the specific error: NameError: name 'ACCOUNT' is not defined . This error happens before any attempt to actually query the database.
What am I missing?
I've browsed various examples via Google and StackOverflow and compared them with my code, but I do not see anything out of the ordinary with setup.
Here are the relevant bits of code... mysql queries work, oracle queries do not.
init.py
from flask_sqlalchemy import SQLAlchemy
database_url = "mysql+pymysql://root:xxxx#localhost:3306/db1"
dbbind_url = "oracle://dbuser:xxxx#10.0.0.1:1521/db2"
app.config["SQLALCHEMY_DATABASE_URI"] = database_url
app.config["SQLALCHEMY_BINDS"] = {
'oracle': dbbind_url
}
app.config["SQLALCHEMY_TRACK_MODIFICATIONS"] = False
db = SQLAlchemy(app)
models.py
## Mysql Model (working)
class CUSTOMERS (db.Model):
id = db.Column(db.Integer, primary_key=True)
name = db.Column(db.String(255))
## Oracle Model (not working)
class ACCOUNT(db.Model):
__tablename__ = 'ACCOUNT'
__bind_key__ = 'oracle'
account_id = db.Column(db.Integer, unique=True, nullable=False, primary_key=True)
account = db.Column(db.String(400), nullable=False)
views.py
#app.route('/helper', methods=['GET','POST'])
def helper_search():
form = HelperSearchForm()
if form.validate_on_submit():
accountquery = form.account.data
print (accountquery)
accountInfo = ACCOUNT.query.filter_by(ACCOUNT=accountquery).first()
return redirect(url_for('helper_accountdetail',account=accountInfo))
"CUSTOMERS" Table Structure (MYSQL)
id INT 11
name VARCHAR 255
"ACCOUNT" Table Structure (Oracle)
ACCOUNT_ID NUMBER(11,0)
ACCOUNT VARCHAR2(400 BYTE)
The current result is:
NameError: name 'ACCOUNT' is not defined
The expected result is:
The query is returned with a result.

Trying to join two tables in sqlalchemy orm query, getting an error

Trying to join the tables below using this command:
Subscription.query.filter( return Subscription.query.filter(Subscription.watch_id == id).join(User).filter_by(watch_id=id)
I get this error:
sqlalchemy.exc.InvalidRequestError: Could not find a FROM clause to join from. Tried joining to <class 'app.user.model.User'>, but got: Can't find any foreign key relationships between 'wm_subscription' and 'user'.
Essentially my end goal is to get a query that gets a List of Users that share a watch_id. Not sure if the models or the query is correct. Anybody know what's wrong?
Database = declarative_base(cls=DbBase)
class Subscription(Database):
__tablename__ = 'wm_subscription'
subscription_id = UniqueIdPk()
watch_id = UniqueIdRefNotNull(index=True)
user_id = UniqueIdRefNotNull(ForeignKey('User.user_id'), index=True)
subscription_watch = relationship('Watch',
primaryjoin='Subscription.watch_id == Watch.watch_id',
foreign_keys='Watch.watch_id',
uselist=True)
subscription_user = relationship('User',
primaryjoin='Subscription.watch_id == User.user_id',
foreign_keys='User.user_id',
uselist=True,
backref='user')
class User(Database, UserMixin):
__tablename__ = 'user'
user_id = UniqueIdPk()
# Google sub ID - unique to user https://developers.google.com/identity/protocols/OpenIDConnect
google_id = Column(String(length=50))
# override email mixin for unique index
email = Email(unique=True)
first_name = Name()
last_name = Name()
def get_id(self):
return self.user_id
This is the correct query:
Subscription.query.filter(Subscription.watch_id == id).join(User)

Resources