How to create a postgresql function in SQLAchemy DDL - python-3.x

everyone!
I wondered how I could create a function in PostgreSQL every time I create or replace a table on my database. I can't find an example that works for my case. So I tried to pass a string with the create command like this:
from sqlalchemy import create_engine
engine = create_engine('/path/to/db...')
conn = engine.connect()
func = 'CREATE OR REPLACE FUNCTION my_func() RETURN SETOF....'
conn.execute(func)
I got a Syntax error running the above code just before the "RETURN SETOF...". So, I try to do something like this:
from sqlalchemy import create_engine
engine = create_engine('/path/to/db...')
conn = engine.connect()
func = DDL('CREATE OR REPLACE FUNCTION my_func()'
'RETURN SETOF....')
func.execute_if(dialect='postgresql')
I know I'm missing something here, but I could not find out what's missing.

The syntax error was RETURN rather than RETURNS.

Related

How to import psycopg2 into a new module im writing

So to simplify, I'm trying to write my own module (test.py) that looks as follows:
import psycopg2
get_data(xyz):
connection = psycopg2.connect(user="",
password="",
host="",
port="",
database="")
last_qry = """select * from xyz.abc"""
cursor = connection.cursor()
cursor.execute(last_qry)
last_data = cursor.fetchone()
cursor.close()
connection.close()
return last_data
in a different file I am running:
import test
get_data(xyz)
and I get the following error:
name 'psycopg2' is not defined
What am I doing wrong?
There are many bugs in these code snippets that you put here:
Your import should be like this:
from test import get_data
or in this way:
import test
test.get_data()
What is the use of xyz ? the second code snippet must return
NameError because xyz is not define;if you want to use it in last_qry you must have .format() for it.
What is the structure of directory that included the second file ?
and where is the first file?

Use a function from one script in another

I have a function that connects to a database thats predefined. The code looks like:
file1.py
def conn_db():
try:
cursor = pymysql.cursors.DictCursor
conn = pymysql.connect(host=settings.host,
user=settings.user,
password=settings.password,
db=settings.database,
port=settings.port,
cursorclass=cursor)
dbcursor = conn.cursor()
except pymysql.err.OperationalError as e:
print("Unable to make a connection to the mysql database. \n Error was:{}".format(e))
return conn, dbcursor
How can I use this function conn_db from file1.py in file2.py. And then call file2.py from executing python's intrepreter via python ?
Having a hard time even identifying something so basic, after several attempts.
Thank you.
You can use import file1 and then use file1.conn_db() to use the function.

SQLAlchemy scoped_session is not getting latest data from DB

I'm rather new to the whole ORM topic, and I've already searched forums and docs.
The question is about a flask application with SQLAlchemy as ORM for the PostgreSQL.
The __init__.py contains the following line:
db = SQLAlchemy()
the created object is referenced in the other files to access the DB.
There is a save function for the model:
def save(self):
db.session.add(self)
db.session.commit()
and also an update function:
def update(self):
for var_name in self.__dict__.keys():
if var_name is not ('_sa_instance_state' or 'id' or 'foreign_id'):
# Workaround for JSON update problem
flag_modified(self, var_name)
db.session.merge(self)
db.session.commit()
The problem occurs when I'm trying to save a new object. The save function writes it to DB, it's visible when querying the DB directly (psql, etc.), but a following ORM query like:
model_list = db.session.query(MyModel).filter(MyModel.foreign_id == this_id).all()
gives an empty response.
A call of the update function does work as expected, new data is visible when requesting with the ORM.
I'm always using the same session object for example this:
<sqlalchemy.orm.scoping.scoped_session object at 0x7f0cff68fda0>
If the application is restarted everything works fine until a new object was created and tried to get with the ORM.
An unhandsome workaround is using raw SQL like:
model_list = db.session.execute('SELECT * FROM models_table WHERE
foreign_id = ' + str(this_id))
which gives a ResultProxy with latest data like this:
<sqlalchemy.engine.result.ResultProxy object at 0x7f0cf74d0390>
I think my problem is a misunderstanding of the session. Can anyone help me?
It figured out that the problem has nothing to do with the session, but the filter() method:
# Neccessary import for string input into filter() function
from sqlalchemy import text
# Solution or workaround
model_list = db.session.query(MyModel).filter(text('foreign_key = ' + str(this_id))).all()
I could not figure out the problem with:
filter(MyModel.foreign_id == this_id) but that's another problem.
I think this way is better than executing raw SQL.

Substituting Variables Value in Mongodb statement

My main intention is to dynamically change the Employees collection while using pymongo, and i was able to do it for insert commands, I am facing problems with the find command, no matter what i do exec() always returns None. but if i copy the string and run it value gets assigned to the variable.
can someone throw some light on why the exec is unable to return a resultset or assign a the resultset to a variable?
db.Employees.update_one(
{"id": criteria},
{
"$set": {
"name":name,
"age":age,
"country":country
}
}
)
from pymongo import MongoClient
import ast
client = MongoClient('localhost:27017')
db = client.TextClassifier
insert works
def mongo_insert_one(COLLECTION_NAME, JSON):
QUERY = """db.%(COLLECTION_NAME)s.insert_one( %(JSON)s )""" % locals();
exec(QUERY)
def mongo_retrive(COLLECTION_NAME, JSON):
resultset = None
query = """resultset = db.%(COLLECTION_NAME)s.find( %(JSON)s )""" % locals();
return resultset
print(mongo_retrive('hungry_intent', "{'Intent':'Hungry'}"))
neither this would work
resultset = exec(""" db.%(COLLECTION_NAME)s.find( %(JSON)s )""" % locals();)
this would not work for an entirely different reason,it says If you meant to call the 'locals' method on a 'Database' object it is failing because no such method exists.
resultset = db.locals()[COLLECTION_NAME].find()
PyMongo Database objects support bracket notation to access a named collection, and PyMongo's included bson module provides a much better JSON decoder than "eval":
from bson import json_util
COLLECTION_NAME = 'hungry_intent'
JSON = "{'Intent':'Hungry'}"
print(list(db[COLLECTION_NAME].find(json_util.loads(JSON))))
This will be faster and more reliable than your "eval" code, and also prevents the injection attack that your "eval" code is vulnerable to.
If you can avoid using JSON at all it could be preferable:
COLLECTION_NAME = 'hungry_intent'
QUERY = {'Intent':'Hungry'}
print(list(db[COLLECTION_NAME].find(QUERY)))

Python Coding in Blender

can someone help me solve this problem?
I'm using Blender 2.74 and Python 3.4 with the correct connector for MySQL. (By the way, I'm just a beginner in using Blender and Python.)
What I want is to make a login UI and save the inputted name into the database, but my code seems a bit off or wrong. When I try to run the code, it didn't save the value in the variable, but when i try to run it in python IDE (PyCharm) it worked.
Here's the code:
import sys
sys.path.append('C:\Python34\Lib\site-packages')
sys.path.append('C:\Python34\DLLs')
import mysql.connector
import bge
bge.render.showMouse(1)
cont = bge.logic.getCurrentController()
own = cont.owner
sensor = cont.sensors ["enter"]
pname = own.get("prpText")
enter = cont.sensors ["enter"]
numpadenter = cont.sensors ["numpadenter"]
if enter.positive or numpadenter.positive:
db = mysql.connector.connect(user='root', password='', host='localhost', database='dbname')
cursor = db.cursor()
cursor.execute("INSERT INTO tblname VALUE(%s", (pname))
#this are the other codes that i have tried so far:
#add_player = ("INSERT INTO storymode " "(PlayerName) " "VALUES (%s)")
#data_player = (pname)
#cursor.execute(add_player, data_player)
#cursor.execute("INSERT INTO storymode" "(PlayerName)" "VALUES (%(pname)s)")
db.commit()
db.close()
The Error is:
mysql.connector.errors.ProgrammingError: 1064 (42000): You have an error in your SQL syntax; check the manual that corresponds to your mysql server version for the right syntax to use near '%s' at line 1.
Can someone tell what i need to do here? Do I need some add-ons for it to work?
Thank you very much for reading my post and for the people who will give their opinions.
Looks like you're missing a closing parenthesis and an 'S' in you're sql INSERT statement?
INSERT INTO tblname VALUE (%s
needs to be
INSERT INTO tblname VALUES (%s)

Resources