Created
July 24, 2021 22:03
-
-
Save etienne-napoleone/57cd22b1ec69fd84072ab2e58335e998 to your computer and use it in GitHub Desktop.
terra ltv bot db migration
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| import asyncio | |
| import motor | |
| from beanie import Document, Indexed, init_beanie | |
| from pydantic import validator | |
| from terra_ltv_bot import models as new_models | |
| from terra_ltv_bot.terra import is_account_address | |
| OLD_DB = "ltv" | |
| NEW_DB = "terra_ltv_bot" | |
| class Address(Document): | |
| account_address: Indexed(str, unique=True) # type: ignore | |
| subscribers: list[int] = [] # telegram ids | |
| is_staker: bool = False | |
| @validator("account_address", always=True) | |
| def account_address_should_be_a_terra_address(cls, v: str): | |
| if not is_account_address(v): | |
| raise ValueError("invalid account address") | |
| return v | |
| @staticmethod | |
| async def get_or_create(account_address: str) -> "Address": | |
| address = await Address.find_one(Address.account_address == account_address) | |
| if not address: | |
| new_address = Address(account_address=account_address) | |
| await new_address.insert() | |
| return new_address | |
| else: | |
| return address | |
| async def main(): | |
| old_db = motor.motor_asyncio.AsyncIOMotorClient()[OLD_DB] | |
| await init_beanie( | |
| database=old_db, | |
| document_models=[Address], | |
| ) | |
| old_addresses = await Address.find_all().to_list() | |
| new_db = motor.motor_asyncio.AsyncIOMotorClient()[NEW_DB] | |
| await init_beanie( | |
| database=new_db, | |
| document_models=new_models.all_models, | |
| ) | |
| for old_address in old_addresses: | |
| new_address = new_models.Address(account_address=old_address.account_address) | |
| await new_address.insert() | |
| for old_subscriber in old_address.subscribers: | |
| new_subscription = new_models.Subscription( | |
| address_id=new_address.id, | |
| protocol="anchor", | |
| alert_threshold=45, | |
| telegram_id=old_subscriber, | |
| ) | |
| await new_subscription.insert() | |
| if __name__ == "__main__": | |
| asyncio.run(main()) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment