Odoo-Creation sequence based on PostgreSQL sequence - postgresql

I am working with odoo 14 and I want to customize sale.order number generation. So, I want to create new sequence (ir.sequence) based on PostgreSQL database sequence object.
Do you have any idea?
Thank you for your help.
SAAD

from odoo import api, fields, models
import psycopg2
class ventes(models.Model):
_inherit = ['sale.order']
company = fields.Char()
name = fields.Char(string='Order Reference')
#Connection a la base de donnees
def open_conn(self):
try:
connection = psycopg2.connect(user="user",
password="xxxxxxxxxxxxxx",
host="192.168.1.1",
port="5432",
database="ventes")
print("Using Python variable in PostgreSQL select Query")
cursor = connection.cursor()
postgreSQL_select_Query = "select nextval('myOdoo')"
cursor.execute(postgreSQL_select_Query)
row = cursor.fetchone()
return row[0]
except (Exception, psycopg2.Error) as error:
print("Error fetching data from PostgreSQL table", error)
finally:
# closing database connection
if connection:
cursor.close()
connection.close()
print("PostgreSQL connection is closed \n")
#api.model
def create(self, vals):
num = self.open_conn()
vals['name'] = num
result = super(ventes, self).create(vals)
return result

Related

Insert to postgres DB: invalid String format (parsing exception error)

I am creating a log db where I track execution steps and catch where it might or might not fail.
I am having issues inserting the Exceptions thrown to a DB.
I am calling an endpoint first in order then query a django database.
In this case I wanted to catch a mistake in the selection_query and thus being unable to fetch the data from the DB.
I want to log this message.
Example:
Exception catch
try:
select_query = "SELECT columnn from row"
cur.execute(select_query)
selected_vals = cur.fetchall()
except Exception as e:
response = insert_into_logging(message = f"{e}", logging_id = 3)
Error
File "/usr/lib/python3.6/json/decoder.py", line 357, in raw_decode
raise JSONDecodeError("Expecting value", s, err.value) from None
This is because of the value passed in the message argument.
(message = f"{e}")
It is not insertable in the DB
The value of "e" is:
auto_close_alarm relation "row" does not exist
LINE 1: SELECT columnn from row
^
I tried to pass
str(e)
Value passed: identical output as above
repr(e.args[0])
Output: 'relation "row" does not exist\nLINE 1: SELECT columnn from row\n ^\n'
repr(e)
Value passed: UndefinedTable('relation "row" does not exist\nLINE 1: SELECT columnn from row\n ^\n',)
And multiple other ways but to no avail.
They all result in the same JSONDecodeError.
Basically the key problem is that this is not a valid String format for it to be able to be parsed in the DB.
All I need is a representation of this Exception error for it to be insertable
Flow of data:
insert function
def insert_into_logging(message, logging_id, date_time):
url = f"""url/insert-into-logging/"""
data = {
"message": message,
"logging_id": logging_id,
}
response = r.post(url, data=json.dumps(data, indent=4, sort_keys=True, default=str))
print(response)
return response.json()
Querying DB
def insert_to_logging(request):
from datetime import datetime, timedelta
if request.method != 'POST':
print(request.method)
return JsonResponse({'status':'error', 'message':'Client insertion only accepts post requests.' + str(request.method)})
today = datetime.today()
body = json.loads(request.body)
message = body.get('message')
logging_id = body.get('logging_id')
Logging.objects.create(message = message, logging_id = logging_id, time_stamp = today)
return JsonResponse({'status':'OK', 'message':'Logging successful'})
Django Model
class Logging(models.Model):
objects = GetOrNoneManager()
message = models.CharField(max_length=64, blank=True, null=True)
logging_id = models.IntegerField(blank=True, null=True)
time_stamp = models.DateTimeField(blank=True, null=True)
class Meta:
db_table = 'logging'

I am trying to delete the data from postgres using spark but unable to delete same code is working for select statements

Class.forName("org.postgresql.Driver")
val conn = Url
val del = s"(delete from db.table where timestamp = '1950-09-08 00:00:00.000')"
val db = DriverManager.getConnection(conn)
println("delete query :" + del)
val pstdel = db.prepareStatement(del)
try {
pstdel.execute()
}
I am getting the below error:
org.postgresql.util.PSQLException: ERROR: syntax error at or near "delete"
The same code is working for select statements. I do have delete permissions.
Try this
val del = s"delete from db.table where timestamp = '1950-09-08 00:00:00.000'"

Calling a custom function in Rasa Actions

I am facing a problem in developing a chatbot using rasa .
I am trying to call a custom function in rasa action file. But i am getting an error saying "name 'areThereAnyErrors' is not defined"
here is my action class. I want to call areThereAnyErrors function from run method. Could someone please help how to resolve this?
class ActionDayStatus(Action):
def areThereAnyErrors(procid):
errormessagecursor = connection.cursor()
errormessagecursor.execute(u"select count(*) from MT_PROSS_MEAGE where pro_id = :procid and msg_T = :messageT",{"procid": procid, "messageT": 'E'})
counts = errormessagecursor.fetchone()
errorCount = counts[0]
print("error count is {}".format(errorCount))
if errorCount == 0:
return False
else:
return True
def name(self):
return 'action_day_status'
def run(self, dispatcher, tracker, domain):
import cx_Oracle
import datetime
# Connect as user "hr" with password "welcome" to the "oraclepdb" service running on this computer.
conn_str = dbconnection
connection = cx_Oracle.connect(conn_str)
cursor = connection.cursor()
dateIndicator = tracker.get_slot('requiredDate')
delta = datetime.timedelta(days = 1)
now = datetime.datetime.now()
currentDate = (now - delta).strftime('%Y-%m-%d')
print(currentDate)
cursor = connection.cursor()
cursor.execute(u"select * from M_POCESS_FILE where CREATE_DATE >= TO_DATE(:createDate,'YYYY/MM/DD') fetch first 50 rows only",{"createDate":currentDate})
all_files = cursor.fetchall()
total_number_of_files = len(all_files)
print("total_number_of_files are {}".format(total_number_of_files))
Answer given by one of the intellectuals :
https://realpython.com/instance-class-and-static-methods-demystified/ Decide whether you want a static method or class method or instance method and call it appropriately . Also when you are using connection within the function it should be a member variable or passed to the method You dont have self as a parameter so you may be intending it as a static method - but you dont have it created as such

loading data in bulk into a postgreSQL table that has a ForeignKey using SQLAlchemy

I have the following code in PostgreSQL/SQLAlchemy.
def load_books():
with open('C:\\Users\\books_raw.csv', 'r') as file:
for line in file.readlines():
record = line.split('$') # split at delimiter
book_isbn = record[0].strip('"')
book_title = record[1]
book_authors = record[2]
book_avg_rating = record[2]
book_format = record[4]
book_img_url = record[5]
book_num_pages = record[6]
book_pub_date = record[7]
book_publisher = record[8].strip() # ESTABLISH RELATIONSHIP
book = Books(title=book_title, isbn=book_isbn, authors=book_authors, avg_rating=book_avg_rating, format=book_format,
img_url=book_img_url, num_pages=book_num_pages, pub_date=book_pub_date, publisher=Publication(name=book_publisher))
session.add(book)
session.commit()
count = session.query(Books).count()
print(count, ' books added to the database')
My problem was with the relationship. If you see this part of the code:
publisher=Publication(name=book_publisher))
here i don't want the record to be inserted into the table, but just establish a relation with an existing record in the main table. Any ideas how i can achieve this ?
In for loop check if publisher in db or not if not in db then can create new one and save book with this publisher:
for line in file.readlines():
...
publisher=Publication.query.filter(name=book_publisher).first()
if not publisher:
publisher=Publication(name=book_publisher)
book = Books(..., publisher=publisher)
r = session.query(Publication).filter(Publication.name == book_publisher).first()
book = Books(title=book_title, isbn=book_isbn, authors=book_authors, avg_rating=book_avg_rating, format=book_format,
img_url=book_img_url, num_pages=book_num_pages, pub_date=book_pub_date, pub_id=r.id)
session.add(book)

How to use Multiple resultsets with POSTGRES JDBC?

I am using JDBC on a PostgreSQL database.
When I query for an entity in a resultset, it returns 5 rows.
Related to that entity is another entity, for which I query while i am using a row in the above resultset.
When I execute this query, the above resultset is closed.
This means that it is allowing only 1 resultset to be active on 1 connection at a time.
Previously the same code was working perfect for Oracle DB server.
Is it that I need to ask the DB admin to configure the server to allow multiple resultsets?
Or to do some change in the code?
Or is it impossible to do it in postgre?
Here is the code for more details:
Connection conn = PTSConnection.getConnection();
Statement stmt = conn.createStatement();
ResultSet lines = stmt.executeQuery("SELECT LINEID,STARTSTOPID,ENDSTOPID FROM LINES"); **//first resultset is active**
while (lines.next()){
int lineId= lines.getInt(1);
Stop ss = StopStorage.getByID(lines.getInt(2));
Stop es = StopStorage.getByID(lines.getInt(3));
ResultSet stops = stmt.executeQuery("SELECT STOPID FROM STOPSINLINES WHERE LINEID=" + lineId); **//first resultset dies**
List<Stop> lineStops = new ArrayList<Stop>();
while(stops.next()){
Stop stop = StopStorage.getByID(stops.getInt(1));
lineStops.add(stop);
}
stops.close();
Line aLine = null;
ResultSet emergencyLine = stmt.executeQuery("SELECT CAUSE, STARTTIME, ENDTIME FROM EMERGENCYLINES WHERE LINEID =" + lineId);
if(emergencyLine.next()){
String cause = emergencyLine.getString(1);
Time startTime = emergencyLine.getTime(2);
Time endTime = emergencyLine.getTime(3);
aLine = new EmergencyLine(ss, es, cause, startTime, endTime, (Stop[]) lineStops.toArray(new Stop[lineStops.size()]));
} else {
aLine = new Line(ss, es, (Stop[]) lineStops.toArray(new Stop[lineStops.size()]));
}
emergencyLine.close();
LineRepository.getInstance().addLine(aLine);
}
lines.close();
The reason is not that you are using two resultsets on the same connection, but you are re-using the same Statement object for a new query. When you run executeQuery() on a Statement instance, any previous result will be closed (I'm surprised that your code did work with Oracle...)
Simply create a new Statement object before executing the second query:
Statement stmt = conn.createStatement();
Statement nestedStmt = conn.createStatement();
ResultSet lines = stmt.executeQuery("SELECT LINEID,STARTSTOPID,ENDSTOPID FROM LINES"); **//first resultset is active**
while (lines.next()){
...
ResultSet stops = nestedStmt.executeQuery("SELECT STOPID FROM STOPSINLINES WHERE LINEID=" + lineId); **//first resultset dies**
List lineStops = new ArrayList();
while(stops.next()){
Stop stop = StopStorage.getByID(stops.getInt(1));
lineStops.add(stop);
}
stops.close();
...
ResultSet emergencyLine = nestedStmt.executeQuery("SELECT CAUSE, STARTTIME, ENDTIME FROM EMERGENCYLINES WHERE LINEID =" + lineId);
if(emergencyLine.next()){
String cause = emergencyLine.getString(1);
....
}
emergencyLine.close();
And don't for get to properly close all Statements and ResultSets !