sqlalchemy: create two databases in the same file












1














I'm trying to create two separate databases in a single file using SQLAlchemy. Here's the code I have so far:



from sqlalchemy import create_engine, Column, String, Integer, inspect
from sqlalchemy.ext.declarative import declarative_base

Base = declarative_base()

class Table1(Base):
__tablename__ = 'table_1'
id = Column(Integer, primary_key=True)
name = Column(String)

class Table2(Base):
__tablename__ = 'table_2'
id = Column(Integer, primary_key=True)
name = Column(String)


engine1 = create_engine('sqlite:///db1.db')
engine2 = create_engine('sqlite:///db2.db')
Base.metadata.drop_all(bind=engine1)
Base.metadata.drop_all(bind=engine2)
Base.metadata.create_all(bind=engine1)
Base.metadata.create_all(bind=engine2)

print(inspect(engine1).get_table_names())
# ['table_1', 'table_2']
print(inspect(engine2).get_table_names())
# ['table_1', 'table_2']


I want to create only Table1 in db1 and only Table2 in db2; however, I'm getting both tables in both databases.



Is there anyway to resolve this or do I need to create the databases in two separate files.










share|improve this question





























    1














    I'm trying to create two separate databases in a single file using SQLAlchemy. Here's the code I have so far:



    from sqlalchemy import create_engine, Column, String, Integer, inspect
    from sqlalchemy.ext.declarative import declarative_base

    Base = declarative_base()

    class Table1(Base):
    __tablename__ = 'table_1'
    id = Column(Integer, primary_key=True)
    name = Column(String)

    class Table2(Base):
    __tablename__ = 'table_2'
    id = Column(Integer, primary_key=True)
    name = Column(String)


    engine1 = create_engine('sqlite:///db1.db')
    engine2 = create_engine('sqlite:///db2.db')
    Base.metadata.drop_all(bind=engine1)
    Base.metadata.drop_all(bind=engine2)
    Base.metadata.create_all(bind=engine1)
    Base.metadata.create_all(bind=engine2)

    print(inspect(engine1).get_table_names())
    # ['table_1', 'table_2']
    print(inspect(engine2).get_table_names())
    # ['table_1', 'table_2']


    I want to create only Table1 in db1 and only Table2 in db2; however, I'm getting both tables in both databases.



    Is there anyway to resolve this or do I need to create the databases in two separate files.










    share|improve this question



























      1












      1








      1







      I'm trying to create two separate databases in a single file using SQLAlchemy. Here's the code I have so far:



      from sqlalchemy import create_engine, Column, String, Integer, inspect
      from sqlalchemy.ext.declarative import declarative_base

      Base = declarative_base()

      class Table1(Base):
      __tablename__ = 'table_1'
      id = Column(Integer, primary_key=True)
      name = Column(String)

      class Table2(Base):
      __tablename__ = 'table_2'
      id = Column(Integer, primary_key=True)
      name = Column(String)


      engine1 = create_engine('sqlite:///db1.db')
      engine2 = create_engine('sqlite:///db2.db')
      Base.metadata.drop_all(bind=engine1)
      Base.metadata.drop_all(bind=engine2)
      Base.metadata.create_all(bind=engine1)
      Base.metadata.create_all(bind=engine2)

      print(inspect(engine1).get_table_names())
      # ['table_1', 'table_2']
      print(inspect(engine2).get_table_names())
      # ['table_1', 'table_2']


      I want to create only Table1 in db1 and only Table2 in db2; however, I'm getting both tables in both databases.



      Is there anyway to resolve this or do I need to create the databases in two separate files.










      share|improve this question















      I'm trying to create two separate databases in a single file using SQLAlchemy. Here's the code I have so far:



      from sqlalchemy import create_engine, Column, String, Integer, inspect
      from sqlalchemy.ext.declarative import declarative_base

      Base = declarative_base()

      class Table1(Base):
      __tablename__ = 'table_1'
      id = Column(Integer, primary_key=True)
      name = Column(String)

      class Table2(Base):
      __tablename__ = 'table_2'
      id = Column(Integer, primary_key=True)
      name = Column(String)


      engine1 = create_engine('sqlite:///db1.db')
      engine2 = create_engine('sqlite:///db2.db')
      Base.metadata.drop_all(bind=engine1)
      Base.metadata.drop_all(bind=engine2)
      Base.metadata.create_all(bind=engine1)
      Base.metadata.create_all(bind=engine2)

      print(inspect(engine1).get_table_names())
      # ['table_1', 'table_2']
      print(inspect(engine2).get_table_names())
      # ['table_1', 'table_2']


      I want to create only Table1 in db1 and only Table2 in db2; however, I'm getting both tables in both databases.



      Is there anyway to resolve this or do I need to create the databases in two separate files.







      python sqlalchemy






      share|improve this question















      share|improve this question













      share|improve this question




      share|improve this question








      edited Nov 21 '18 at 19:45







      Johnny Metz

















      asked Nov 21 '18 at 19:25









      Johnny MetzJohnny Metz

      1,06911029




      1,06911029
























          1 Answer
          1






          active

          oldest

          votes


















          2














          Your problem isn't caused by trying to create the two databases in the same module. Rather, you are calling create_all() on the same metadata object that has mapped both of the tables. E.g.



          print(Base.metadata.tables)


          result:



          dict_keys(['table_1', 'table_2'])


          From the docs about MetaData.create_all():




          This method will issue queries that first check for the existence of
          each individual table, and if not found will issue the CREATE
          statements...




          Key point is it checks for the existence of each table. So here:



          Base.metadata.create_all(bind=engine1)
          Base.metadata.create_all(bind=engine2)


          ... it first checks for both tables in the db referenced by engine1, doesn't find them and creates them. Then, it checks for both tables in the db referenced by engine2, doesn't find them, and creates them.



          There's a couple of options.



          Have different Base objects (i.e. a distinct MetaData instance) for each database:



          Base1 = declarative_base()
          Base2 = declarative_base()


          class Table1(Base1):
          __tablename__ = 'table_1'
          id = Column(Integer, primary_key=True)
          name = Column(String)

          class Table2(Base2):
          __tablename__ = 'table_2'
          id = Column(Integer, primary_key=True)
          name = Column(String)

          engine1 = create_engine('sqlite:///db1.db')
          engine2 = create_engine('sqlite:///db2.db')
          Base1.metadata.drop_all(bind=engine1)
          Base2.metadata.drop_all(bind=engine2)
          Base1.metadata.create_all(bind=engine1)
          Base2.metadata.create_all(bind=engine2)

          print(inspect(engine1).get_table_names())
          # ['table_1']
          print(inspect(engine2).get_table_names())
          # ['table_2']


          Or, selectively create the tables while binding to the desired engine:



          Base = declarative_base()

          class Table1(Base):
          __tablename__ = 'table_1'
          id = Column(Integer, primary_key=True)
          name = Column(String)

          class Table2(Base):
          __tablename__ = 'table_2'
          id = Column(Integer, primary_key=True)
          name = Column(String)


          engine1 = create_engine('sqlite:///db1.db')
          engine2 = create_engine('sqlite:///db2.db')
          Base.metadata.drop_all(bind=engine1)
          Base.metadata.drop_all(bind=engine2)
          Base.metadata.tables['table_1'].create(bind=engine1)
          Base.metadata.tables['table_2'].create(bind=engine2)

          print(inspect(engine1).get_table_names())
          # ['table_1']
          print(inspect(engine2).get_table_names())
          # ['table_2']





          share|improve this answer





















          • Awesome! Are there pros and cons for either approach?
            – Johnny Metz
            Nov 21 '18 at 22:44










          • TBH not really. Either way you need to make sure that you are querying through a session that is bound to the right engine for the model. I'd be interested to hear if you come across any limitations in either case.
            – SuperShoot
            Nov 22 '18 at 0:58











          Your Answer






          StackExchange.ifUsing("editor", function () {
          StackExchange.using("externalEditor", function () {
          StackExchange.using("snippets", function () {
          StackExchange.snippets.init();
          });
          });
          }, "code-snippets");

          StackExchange.ready(function() {
          var channelOptions = {
          tags: "".split(" "),
          id: "1"
          };
          initTagRenderer("".split(" "), "".split(" "), channelOptions);

          StackExchange.using("externalEditor", function() {
          // Have to fire editor after snippets, if snippets enabled
          if (StackExchange.settings.snippets.snippetsEnabled) {
          StackExchange.using("snippets", function() {
          createEditor();
          });
          }
          else {
          createEditor();
          }
          });

          function createEditor() {
          StackExchange.prepareEditor({
          heartbeatType: 'answer',
          autoActivateHeartbeat: false,
          convertImagesToLinks: true,
          noModals: true,
          showLowRepImageUploadWarning: true,
          reputationToPostImages: 10,
          bindNavPrevention: true,
          postfix: "",
          imageUploader: {
          brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
          contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
          allowUrls: true
          },
          onDemand: true,
          discardSelector: ".discard-answer"
          ,immediatelyShowMarkdownHelp:true
          });


          }
          });














          draft saved

          draft discarded


















          StackExchange.ready(
          function () {
          StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f53419236%2fsqlalchemy-create-two-databases-in-the-same-file%23new-answer', 'question_page');
          }
          );

          Post as a guest















          Required, but never shown

























          1 Answer
          1






          active

          oldest

          votes








          1 Answer
          1






          active

          oldest

          votes









          active

          oldest

          votes






          active

          oldest

          votes









          2














          Your problem isn't caused by trying to create the two databases in the same module. Rather, you are calling create_all() on the same metadata object that has mapped both of the tables. E.g.



          print(Base.metadata.tables)


          result:



          dict_keys(['table_1', 'table_2'])


          From the docs about MetaData.create_all():




          This method will issue queries that first check for the existence of
          each individual table, and if not found will issue the CREATE
          statements...




          Key point is it checks for the existence of each table. So here:



          Base.metadata.create_all(bind=engine1)
          Base.metadata.create_all(bind=engine2)


          ... it first checks for both tables in the db referenced by engine1, doesn't find them and creates them. Then, it checks for both tables in the db referenced by engine2, doesn't find them, and creates them.



          There's a couple of options.



          Have different Base objects (i.e. a distinct MetaData instance) for each database:



          Base1 = declarative_base()
          Base2 = declarative_base()


          class Table1(Base1):
          __tablename__ = 'table_1'
          id = Column(Integer, primary_key=True)
          name = Column(String)

          class Table2(Base2):
          __tablename__ = 'table_2'
          id = Column(Integer, primary_key=True)
          name = Column(String)

          engine1 = create_engine('sqlite:///db1.db')
          engine2 = create_engine('sqlite:///db2.db')
          Base1.metadata.drop_all(bind=engine1)
          Base2.metadata.drop_all(bind=engine2)
          Base1.metadata.create_all(bind=engine1)
          Base2.metadata.create_all(bind=engine2)

          print(inspect(engine1).get_table_names())
          # ['table_1']
          print(inspect(engine2).get_table_names())
          # ['table_2']


          Or, selectively create the tables while binding to the desired engine:



          Base = declarative_base()

          class Table1(Base):
          __tablename__ = 'table_1'
          id = Column(Integer, primary_key=True)
          name = Column(String)

          class Table2(Base):
          __tablename__ = 'table_2'
          id = Column(Integer, primary_key=True)
          name = Column(String)


          engine1 = create_engine('sqlite:///db1.db')
          engine2 = create_engine('sqlite:///db2.db')
          Base.metadata.drop_all(bind=engine1)
          Base.metadata.drop_all(bind=engine2)
          Base.metadata.tables['table_1'].create(bind=engine1)
          Base.metadata.tables['table_2'].create(bind=engine2)

          print(inspect(engine1).get_table_names())
          # ['table_1']
          print(inspect(engine2).get_table_names())
          # ['table_2']





          share|improve this answer





















          • Awesome! Are there pros and cons for either approach?
            – Johnny Metz
            Nov 21 '18 at 22:44










          • TBH not really. Either way you need to make sure that you are querying through a session that is bound to the right engine for the model. I'd be interested to hear if you come across any limitations in either case.
            – SuperShoot
            Nov 22 '18 at 0:58
















          2














          Your problem isn't caused by trying to create the two databases in the same module. Rather, you are calling create_all() on the same metadata object that has mapped both of the tables. E.g.



          print(Base.metadata.tables)


          result:



          dict_keys(['table_1', 'table_2'])


          From the docs about MetaData.create_all():




          This method will issue queries that first check for the existence of
          each individual table, and if not found will issue the CREATE
          statements...




          Key point is it checks for the existence of each table. So here:



          Base.metadata.create_all(bind=engine1)
          Base.metadata.create_all(bind=engine2)


          ... it first checks for both tables in the db referenced by engine1, doesn't find them and creates them. Then, it checks for both tables in the db referenced by engine2, doesn't find them, and creates them.



          There's a couple of options.



          Have different Base objects (i.e. a distinct MetaData instance) for each database:



          Base1 = declarative_base()
          Base2 = declarative_base()


          class Table1(Base1):
          __tablename__ = 'table_1'
          id = Column(Integer, primary_key=True)
          name = Column(String)

          class Table2(Base2):
          __tablename__ = 'table_2'
          id = Column(Integer, primary_key=True)
          name = Column(String)

          engine1 = create_engine('sqlite:///db1.db')
          engine2 = create_engine('sqlite:///db2.db')
          Base1.metadata.drop_all(bind=engine1)
          Base2.metadata.drop_all(bind=engine2)
          Base1.metadata.create_all(bind=engine1)
          Base2.metadata.create_all(bind=engine2)

          print(inspect(engine1).get_table_names())
          # ['table_1']
          print(inspect(engine2).get_table_names())
          # ['table_2']


          Or, selectively create the tables while binding to the desired engine:



          Base = declarative_base()

          class Table1(Base):
          __tablename__ = 'table_1'
          id = Column(Integer, primary_key=True)
          name = Column(String)

          class Table2(Base):
          __tablename__ = 'table_2'
          id = Column(Integer, primary_key=True)
          name = Column(String)


          engine1 = create_engine('sqlite:///db1.db')
          engine2 = create_engine('sqlite:///db2.db')
          Base.metadata.drop_all(bind=engine1)
          Base.metadata.drop_all(bind=engine2)
          Base.metadata.tables['table_1'].create(bind=engine1)
          Base.metadata.tables['table_2'].create(bind=engine2)

          print(inspect(engine1).get_table_names())
          # ['table_1']
          print(inspect(engine2).get_table_names())
          # ['table_2']





          share|improve this answer





















          • Awesome! Are there pros and cons for either approach?
            – Johnny Metz
            Nov 21 '18 at 22:44










          • TBH not really. Either way you need to make sure that you are querying through a session that is bound to the right engine for the model. I'd be interested to hear if you come across any limitations in either case.
            – SuperShoot
            Nov 22 '18 at 0:58














          2












          2








          2






          Your problem isn't caused by trying to create the two databases in the same module. Rather, you are calling create_all() on the same metadata object that has mapped both of the tables. E.g.



          print(Base.metadata.tables)


          result:



          dict_keys(['table_1', 'table_2'])


          From the docs about MetaData.create_all():




          This method will issue queries that first check for the existence of
          each individual table, and if not found will issue the CREATE
          statements...




          Key point is it checks for the existence of each table. So here:



          Base.metadata.create_all(bind=engine1)
          Base.metadata.create_all(bind=engine2)


          ... it first checks for both tables in the db referenced by engine1, doesn't find them and creates them. Then, it checks for both tables in the db referenced by engine2, doesn't find them, and creates them.



          There's a couple of options.



          Have different Base objects (i.e. a distinct MetaData instance) for each database:



          Base1 = declarative_base()
          Base2 = declarative_base()


          class Table1(Base1):
          __tablename__ = 'table_1'
          id = Column(Integer, primary_key=True)
          name = Column(String)

          class Table2(Base2):
          __tablename__ = 'table_2'
          id = Column(Integer, primary_key=True)
          name = Column(String)

          engine1 = create_engine('sqlite:///db1.db')
          engine2 = create_engine('sqlite:///db2.db')
          Base1.metadata.drop_all(bind=engine1)
          Base2.metadata.drop_all(bind=engine2)
          Base1.metadata.create_all(bind=engine1)
          Base2.metadata.create_all(bind=engine2)

          print(inspect(engine1).get_table_names())
          # ['table_1']
          print(inspect(engine2).get_table_names())
          # ['table_2']


          Or, selectively create the tables while binding to the desired engine:



          Base = declarative_base()

          class Table1(Base):
          __tablename__ = 'table_1'
          id = Column(Integer, primary_key=True)
          name = Column(String)

          class Table2(Base):
          __tablename__ = 'table_2'
          id = Column(Integer, primary_key=True)
          name = Column(String)


          engine1 = create_engine('sqlite:///db1.db')
          engine2 = create_engine('sqlite:///db2.db')
          Base.metadata.drop_all(bind=engine1)
          Base.metadata.drop_all(bind=engine2)
          Base.metadata.tables['table_1'].create(bind=engine1)
          Base.metadata.tables['table_2'].create(bind=engine2)

          print(inspect(engine1).get_table_names())
          # ['table_1']
          print(inspect(engine2).get_table_names())
          # ['table_2']





          share|improve this answer












          Your problem isn't caused by trying to create the two databases in the same module. Rather, you are calling create_all() on the same metadata object that has mapped both of the tables. E.g.



          print(Base.metadata.tables)


          result:



          dict_keys(['table_1', 'table_2'])


          From the docs about MetaData.create_all():




          This method will issue queries that first check for the existence of
          each individual table, and if not found will issue the CREATE
          statements...




          Key point is it checks for the existence of each table. So here:



          Base.metadata.create_all(bind=engine1)
          Base.metadata.create_all(bind=engine2)


          ... it first checks for both tables in the db referenced by engine1, doesn't find them and creates them. Then, it checks for both tables in the db referenced by engine2, doesn't find them, and creates them.



          There's a couple of options.



          Have different Base objects (i.e. a distinct MetaData instance) for each database:



          Base1 = declarative_base()
          Base2 = declarative_base()


          class Table1(Base1):
          __tablename__ = 'table_1'
          id = Column(Integer, primary_key=True)
          name = Column(String)

          class Table2(Base2):
          __tablename__ = 'table_2'
          id = Column(Integer, primary_key=True)
          name = Column(String)

          engine1 = create_engine('sqlite:///db1.db')
          engine2 = create_engine('sqlite:///db2.db')
          Base1.metadata.drop_all(bind=engine1)
          Base2.metadata.drop_all(bind=engine2)
          Base1.metadata.create_all(bind=engine1)
          Base2.metadata.create_all(bind=engine2)

          print(inspect(engine1).get_table_names())
          # ['table_1']
          print(inspect(engine2).get_table_names())
          # ['table_2']


          Or, selectively create the tables while binding to the desired engine:



          Base = declarative_base()

          class Table1(Base):
          __tablename__ = 'table_1'
          id = Column(Integer, primary_key=True)
          name = Column(String)

          class Table2(Base):
          __tablename__ = 'table_2'
          id = Column(Integer, primary_key=True)
          name = Column(String)


          engine1 = create_engine('sqlite:///db1.db')
          engine2 = create_engine('sqlite:///db2.db')
          Base.metadata.drop_all(bind=engine1)
          Base.metadata.drop_all(bind=engine2)
          Base.metadata.tables['table_1'].create(bind=engine1)
          Base.metadata.tables['table_2'].create(bind=engine2)

          print(inspect(engine1).get_table_names())
          # ['table_1']
          print(inspect(engine2).get_table_names())
          # ['table_2']






          share|improve this answer












          share|improve this answer



          share|improve this answer










          answered Nov 21 '18 at 22:39









          SuperShootSuperShoot

          1,624619




          1,624619












          • Awesome! Are there pros and cons for either approach?
            – Johnny Metz
            Nov 21 '18 at 22:44










          • TBH not really. Either way you need to make sure that you are querying through a session that is bound to the right engine for the model. I'd be interested to hear if you come across any limitations in either case.
            – SuperShoot
            Nov 22 '18 at 0:58


















          • Awesome! Are there pros and cons for either approach?
            – Johnny Metz
            Nov 21 '18 at 22:44










          • TBH not really. Either way you need to make sure that you are querying through a session that is bound to the right engine for the model. I'd be interested to hear if you come across any limitations in either case.
            – SuperShoot
            Nov 22 '18 at 0:58
















          Awesome! Are there pros and cons for either approach?
          – Johnny Metz
          Nov 21 '18 at 22:44




          Awesome! Are there pros and cons for either approach?
          – Johnny Metz
          Nov 21 '18 at 22:44












          TBH not really. Either way you need to make sure that you are querying through a session that is bound to the right engine for the model. I'd be interested to hear if you come across any limitations in either case.
          – SuperShoot
          Nov 22 '18 at 0:58




          TBH not really. Either way you need to make sure that you are querying through a session that is bound to the right engine for the model. I'd be interested to hear if you come across any limitations in either case.
          – SuperShoot
          Nov 22 '18 at 0:58


















          draft saved

          draft discarded




















































          Thanks for contributing an answer to Stack Overflow!


          • Please be sure to answer the question. Provide details and share your research!

          But avoid



          • Asking for help, clarification, or responding to other answers.

          • Making statements based on opinion; back them up with references or personal experience.


          To learn more, see our tips on writing great answers.





          Some of your past answers have not been well-received, and you're in danger of being blocked from answering.


          Please pay close attention to the following guidance:


          • Please be sure to answer the question. Provide details and share your research!

          But avoid



          • Asking for help, clarification, or responding to other answers.

          • Making statements based on opinion; back them up with references or personal experience.


          To learn more, see our tips on writing great answers.




          draft saved


          draft discarded














          StackExchange.ready(
          function () {
          StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f53419236%2fsqlalchemy-create-two-databases-in-the-same-file%23new-answer', 'question_page');
          }
          );

          Post as a guest















          Required, but never shown





















































          Required, but never shown














          Required, but never shown












          Required, but never shown







          Required, but never shown

































          Required, but never shown














          Required, but never shown












          Required, but never shown







          Required, but never shown







          Popular posts from this blog

          Feedback on college project

          Futebolista

          Albești (Vaslui)