Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Flask-sqalchemy and oracle database id not autoincrement

I want to make a new table in my database (Oracle 11g but the Express Edition for Ubuntu 16.04) using Python and Flask framework with the SQLAlchemy module. The first field of the table it's and ID, is an Integer field and I want it to autoincrement, but Oracle database don't support the autoincrement. I have a form to add a new comment, but when I try to add a new record it reports a error:

sqlalchemy.exc.IntegrityError: (cx_Oracle.IntegrityError) ORA-01400: cannot insert NULL into ("WIKTOR"."TBL_COMENTARIOS"."ID") [SQL: 'INSERT INTO tbl_comentarios (usuario, comentario, fecha) VALUES (:usuario, :comentario, :fecha) RETURNING tbl_comentarios.id INTO :ret_0'] [parameters: {'usuario': 'wiktor', 'comentario': 'hola', 'fecha': datetime.datetime(2017, 5, 24, 11, 23, 45, 39450), 'ret_0': }]

Basically it says that the ID cannot be null, that happens because there's no field in the form to add it so it sends the id empty and then the autoincrement of the database model don't work. Here's the code:

db = SQLAlchemy()

class Comentarios(db.Model):
    __tablename__ = 'tbl_comentarios'
    id = db.Column(db.Integer, primary_key=True, autoincrement=True)
    usuario = db.Column(db.String(50))
    comentario = db.Column(db.Text())
    fecha = db.Column(db.DateTime, default = datetime.datetime.now)

def __init__(self, usuario, comentario):
    self.usuario = usuario
    self.comentario = comentario

I also tried:

id = db.Column(db.Integer, primary_key=True)

That code did work in SQL Database but neither works in Oracle Database.

Sorry for my english, I hope someone can help me... Thanks!

like image 483
Wiktor Avatar asked Oct 21 '25 10:10

Wiktor


1 Answers

You can find here the SQLAlchemy documentation that discusses this. Oracle has no auto increment feature and relies on sequence to mimic the behavior.

So, your id column should look like this:

id_seq = Sequence('id_seq')
id = db.Column(db.Integer, id_seq,
        server_default=id_seq.next_value(), primary_key=True)
like image 87
Dana Avatar answered Oct 23 '25 07:10

Dana



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!