简体   繁体   中英

Oracle database schema using SQLAlchemy

I have a problem with SqlAlchemy. When I define the schema in my Oracle database, foreign keys are not recognized in other tables. Tested without using layout and it worked. But I need to define the schema of this application because the user is not the owner of the tables. I would like your help to solve this problem. code:

Base = declarative_base()
SCHEMA = {'schema' : 'SIATDESV'}

class Pgdasd(Base):
    __tablename__ = 'PGDASD'
    __table_args__ = SCHEMA

    PGDASD_00000_ID_DECLARACAO    = Column(String(17), primary_key = True)

class Pgdasd_01000(Base):
    __tablename__ = 'pgdasd_01000'
    __table_args__ = SCHEMA

    PGDASD_00000_ID_DECLARACAO  = Column(String, ForeignKey('PGDASD.PGDASD_00000_ID_DECLARACAO'))   
    PGDASD_01000_NRPAGTO        = Column(String, primary_key = True)

error: *Foreign key associated with column 'pgdasd_01000.PGDASD_00000_ID_DECLARACAO' could not find table 'PGDASD' with which to generate a foreign key to target column 'PGDASD_00000_ID_DECLARACAO'*

thanks!

Step 1: check that table(s) are created in db. BTW How did you create these tables? Have you run metadata.create_all() method ?

Step 2: Try to add the name of the schema to the ForeignKey defintion:

Base = declarative_base()
SCHEMA = {'schema' : 'SIATDESV'}

class Pgdasd(Base):
    __tablename__ = 'PGDASD'
    __table_args__ = SCHEMA

    PGDASD_00000_ID_DECLARACAO    = Column(String(17), primary_key = True)

class Pgdasd_01000(Base):
    __tablename__ = 'pgdasd_01000'
    __table_args__ = SCHEMA

    PGDASD_00000_ID_DECLARACAO  = Column(String, ForeignKey('SIATDESV.PGDASD.PGDASD_00000_ID_DECLARACAO'))   
    PGDASD_01000_NRPAGTO        = Column(String, primary_key = True)

If this will help you may also make code to use schema value to avoid hardcoding the schema.

    PGDASD_00000_ID_DECLARACAO  = Column(String, ForeignKey(SCHEMA['schema']+'.PGDASD.PGDASD_00000_ID_DECLARACAO'))   

PS: Anyway it is always useful to check SQLAlchemy log what SQL queries it generates.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM