How do I query multiple similar databases using Peewee?
I'm having a problem querying multiple databases using Peewee:
- I have two existing mysql databases (let's call them A and B) (the structures are similar because they are two Bugzilla databases)
- I am generating models (modelsA.py and modelsB.py) using Pwiz
- I am writing this code:
...
from modelsA import *
from modelsB import *
The problem is this: Since the classes in Model B are (sometimes) the same as Model A, Model B of Class "overwrites" A's classes, making it impossible to query A.
Also, I don't understand how to query one of the specific database. For example, with this code:
c = Customers.get(Customers.customernumber == 12)
How do you know in which database this query will be executed?
I had an idea, but it seems dirty to me: I could manually rename the classes from modelsA.py and modelsB.py to make them different, and then write this code:
ca = CustomersA.get(CustomersA.customernumber == 12)
cb = CustomersB.get(CustomersB.customernumber == 12)
Roughly, is it possible for Peewee to handle such cases? If so what is the way to do it? Fragments would be greatly appreciated ^^ Thanks.
source to share
The following may not be the exact answer to your problem, but what I have tried on my own - successfully - is using a playhouse.Proxy instance for each schema I want to use, and linking to the appropriate proxy in the internal thrower. I think it will work without a proxy too. However, you seem to be looking for cross-sectional queries and have already figured out what I have just come up with.
#!/usr/bin/python
import sqlite3
import peewee
from peewee import *
from playhouse.proxy import *
database_a_proxy = Proxy()
database_b_proxy = Proxy()
class BaseModelA(Model):
class Meta:
database = database_a_proxy
class BaseModelB(Model):
class Meta:
database = database_b_proxy
class RelationInSchemaA(BaseModelA):
textfield = CharField()
class RelationInSchemaB(BaseModelB):
textfield = CharField()
database_a = SqliteDatabase('schemaA', **{})
database_b = SqliteDatabase('schemaB', **{})
database_a_proxy.initialize(database_a)
database_b_proxy.initialize(database_b)
try:
RelationInSchemaA.create_table()
RelationInSchemaB.create_table()
except:
pass
RelationInSchemaA.create(textfield='Hello')
RelationInSchemaB.create(textfield='PeeWee')
Well, this is possible with handcrafting code from pwiz.py. I'm sure there is a more elegant and lazy (i.e. not impatient) way of doing this using some kind of factory, but I haven't spent a lot of time on Python and PeeWee yet. If so, pwiz.py should have an additional flag for this purpose too.
source to share