From ce56855cfe2b9b90dc7802e909dd93578aa47751 Mon Sep 17 00:00:00 2001 From: Adek Maulana Date: Fri, 19 May 2023 19:31:20 +0700 Subject: [PATCH] Initial import from https://github.com/userbotindo/Anjani/tree/staging/anjani/util/db Co-authored-by: mrmissx Co-authored-by: wulan17 Signed-off-by: wulan17 --- .gitignore | 17 + LICENSE | 674 ++++++++++++++++++++++++++++++++ README.md | 1 + async_pymongo/__init__.py | 23 ++ async_pymongo/async_helper.py | 29 ++ async_pymongo/base.py | 103 +++++ async_pymongo/change_stream.py | 133 +++++++ async_pymongo/client.py | 260 ++++++++++++ async_pymongo/client_session.py | 201 ++++++++++ async_pymongo/collection.py | 543 +++++++++++++++++++++++++ async_pymongo/command_cursor.py | 236 +++++++++++ async_pymongo/cursor.py | 212 ++++++++++ async_pymongo/cursor_base.py | 217 ++++++++++ async_pymongo/db.py | 286 ++++++++++++++ async_pymongo/errors.py | 22 ++ async_pymongo/typings.py | 38 ++ poetry.lock | 122 ++++++ pyproject.toml | 38 ++ tests/__init__.py | 0 19 files changed, 3155 insertions(+) create mode 100644 .gitignore create mode 100644 LICENSE create mode 100644 README.md create mode 100644 async_pymongo/__init__.py create mode 100644 async_pymongo/async_helper.py create mode 100644 async_pymongo/base.py create mode 100644 async_pymongo/change_stream.py create mode 100644 async_pymongo/client.py create mode 100644 async_pymongo/client_session.py create mode 100644 async_pymongo/collection.py create mode 100644 async_pymongo/command_cursor.py create mode 100644 async_pymongo/cursor.py create mode 100644 async_pymongo/cursor_base.py create mode 100644 async_pymongo/db.py create mode 100644 async_pymongo/errors.py create mode 100644 async_pymongo/typings.py create mode 100644 poetry.lock create mode 100644 pyproject.toml create mode 100644 tests/__init__.py diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000..5977d6a --- /dev/null +++ b/.gitignore @@ -0,0 +1,17 @@ +__pycache__/ + +# Build folder +dist/ + +# file +.DS_Store +*.pyc +*.log +*.session +*.session-journal +downloads/ + +# IDE specific files +.idea/ +.vscode/ +*.sw* diff --git a/LICENSE b/LICENSE new file mode 100644 index 0000000..f288702 --- /dev/null +++ b/LICENSE @@ -0,0 +1,674 @@ + GNU GENERAL PUBLIC LICENSE + Version 3, 29 June 2007 + + Copyright (C) 2007 Free Software Foundation, Inc. + Everyone is permitted to copy and distribute verbatim copies + of this license document, but changing it is not allowed. + + Preamble + + The GNU General Public License is a free, copyleft license for +software and other kinds of works. + + The licenses for most software and other practical works are designed +to take away your freedom to share and change the works. By contrast, +the GNU General Public License is intended to guarantee your freedom to +share and change all versions of a program--to make sure it remains free +software for all its users. We, the Free Software Foundation, use the +GNU General Public License for most of our software; it applies also to +any other work released this way by its authors. You can apply it to +your programs, too. + + When we speak of free software, we are referring to freedom, not +price. Our General Public Licenses are designed to make sure that you +have the freedom to distribute copies of free software (and charge for +them if you wish), that you receive source code or can get it if you +want it, that you can change the software or use pieces of it in new +free programs, and that you know you can do these things. + + To protect your rights, we need to prevent others from denying you +these rights or asking you to surrender the rights. Therefore, you have +certain responsibilities if you distribute copies of the software, or if +you modify it: responsibilities to respect the freedom of others. + + For example, if you distribute copies of such a program, whether +gratis or for a fee, you must pass on to the recipients the same +freedoms that you received. You must make sure that they, too, receive +or can get the source code. And you must show them these terms so they +know their rights. + + Developers that use the GNU GPL protect your rights with two steps: +(1) assert copyright on the software, and (2) offer you this License +giving you legal permission to copy, distribute and/or modify it. + + For the developers' and authors' protection, the GPL clearly explains +that there is no warranty for this free software. For both users' and +authors' sake, the GPL requires that modified versions be marked as +changed, so that their problems will not be attributed erroneously to +authors of previous versions. + + Some devices are designed to deny users access to install or run +modified versions of the software inside them, although the manufacturer +can do so. This is fundamentally incompatible with the aim of +protecting users' freedom to change the software. The systematic +pattern of such abuse occurs in the area of products for individuals to +use, which is precisely where it is most unacceptable. Therefore, we +have designed this version of the GPL to prohibit the practice for those +products. If such problems arise substantially in other domains, we +stand ready to extend this provision to those domains in future versions +of the GPL, as needed to protect the freedom of users. + + Finally, every program is threatened constantly by software patents. +States should not allow patents to restrict development and use of +software on general-purpose computers, but in those that do, we wish to +avoid the special danger that patents applied to a free program could +make it effectively proprietary. To prevent this, the GPL assures that +patents cannot be used to render the program non-free. + + The precise terms and conditions for copying, distribution and +modification follow. + + TERMS AND CONDITIONS + + 0. Definitions. + + "This License" refers to version 3 of the GNU General Public License. + + "Copyright" also means copyright-like laws that apply to other kinds of +works, such as semiconductor masks. + + "The Program" refers to any copyrightable work licensed under this +License. Each licensee is addressed as "you". "Licensees" and +"recipients" may be individuals or organizations. + + To "modify" a work means to copy from or adapt all or part of the work +in a fashion requiring copyright permission, other than the making of an +exact copy. The resulting work is called a "modified version" of the +earlier work or a work "based on" the earlier work. + + A "covered work" means either the unmodified Program or a work based +on the Program. + + To "propagate" a work means to do anything with it that, without +permission, would make you directly or secondarily liable for +infringement under applicable copyright law, except executing it on a +computer or modifying a private copy. Propagation includes copying, +distribution (with or without modification), making available to the +public, and in some countries other activities as well. + + To "convey" a work means any kind of propagation that enables other +parties to make or receive copies. Mere interaction with a user through +a computer network, with no transfer of a copy, is not conveying. + + An interactive user interface displays "Appropriate Legal Notices" +to the extent that it includes a convenient and prominently visible +feature that (1) displays an appropriate copyright notice, and (2) +tells the user that there is no warranty for the work (except to the +extent that warranties are provided), that licensees may convey the +work under this License, and how to view a copy of this License. If +the interface presents a list of user commands or options, such as a +menu, a prominent item in the list meets this criterion. + + 1. Source Code. + + The "source code" for a work means the preferred form of the work +for making modifications to it. "Object code" means any non-source +form of a work. + + A "Standard Interface" means an interface that either is an official +standard defined by a recognized standards body, or, in the case of +interfaces specified for a particular programming language, one that +is widely used among developers working in that language. + + The "System Libraries" of an executable work include anything, other +than the work as a whole, that (a) is included in the normal form of +packaging a Major Component, but which is not part of that Major +Component, and (b) serves only to enable use of the work with that +Major Component, or to implement a Standard Interface for which an +implementation is available to the public in source code form. A +"Major Component", in this context, means a major essential component +(kernel, window system, and so on) of the specific operating system +(if any) on which the executable work runs, or a compiler used to +produce the work, or an object code interpreter used to run it. + + The "Corresponding Source" for a work in object code form means all +the source code needed to generate, install, and (for an executable +work) run the object code and to modify the work, including scripts to +control those activities. However, it does not include the work's +System Libraries, or general-purpose tools or generally available free +programs which are used unmodified in performing those activities but +which are not part of the work. For example, Corresponding Source +includes interface definition files associated with source files for +the work, and the source code for shared libraries and dynamically +linked subprograms that the work is specifically designed to require, +such as by intimate data communication or control flow between those +subprograms and other parts of the work. + + The Corresponding Source need not include anything that users +can regenerate automatically from other parts of the Corresponding +Source. + + The Corresponding Source for a work in source code form is that +same work. + + 2. Basic Permissions. + + All rights granted under this License are granted for the term of +copyright on the Program, and are irrevocable provided the stated +conditions are met. This License explicitly affirms your unlimited +permission to run the unmodified Program. The output from running a +covered work is covered by this License only if the output, given its +content, constitutes a covered work. This License acknowledges your +rights of fair use or other equivalent, as provided by copyright law. + + You may make, run and propagate covered works that you do not +convey, without conditions so long as your license otherwise remains +in force. You may convey covered works to others for the sole purpose +of having them make modifications exclusively for you, or provide you +with facilities for running those works, provided that you comply with +the terms of this License in conveying all material for which you do +not control copyright. Those thus making or running the covered works +for you must do so exclusively on your behalf, under your direction +and control, on terms that prohibit them from making any copies of +your copyrighted material outside their relationship with you. + + Conveying under any other circumstances is permitted solely under +the conditions stated below. Sublicensing is not allowed; section 10 +makes it unnecessary. + + 3. Protecting Users' Legal Rights From Anti-Circumvention Law. + + No covered work shall be deemed part of an effective technological +measure under any applicable law fulfilling obligations under article +11 of the WIPO copyright treaty adopted on 20 December 1996, or +similar laws prohibiting or restricting circumvention of such +measures. + + When you convey a covered work, you waive any legal power to forbid +circumvention of technological measures to the extent such circumvention +is effected by exercising rights under this License with respect to +the covered work, and you disclaim any intention to limit operation or +modification of the work as a means of enforcing, against the work's +users, your or third parties' legal rights to forbid circumvention of +technological measures. + + 4. Conveying Verbatim Copies. + + You may convey verbatim copies of the Program's source code as you +receive it, in any medium, provided that you conspicuously and +appropriately publish on each copy an appropriate copyright notice; +keep intact all notices stating that this License and any +non-permissive terms added in accord with section 7 apply to the code; +keep intact all notices of the absence of any warranty; and give all +recipients a copy of this License along with the Program. + + You may charge any price or no price for each copy that you convey, +and you may offer support or warranty protection for a fee. + + 5. Conveying Modified Source Versions. + + You may convey a work based on the Program, or the modifications to +produce it from the Program, in the form of source code under the +terms of section 4, provided that you also meet all of these conditions: + + a) The work must carry prominent notices stating that you modified + it, and giving a relevant date. + + b) The work must carry prominent notices stating that it is + released under this License and any conditions added under section + 7. This requirement modifies the requirement in section 4 to + "keep intact all notices". + + c) You must license the entire work, as a whole, under this + License to anyone who comes into possession of a copy. This + License will therefore apply, along with any applicable section 7 + additional terms, to the whole of the work, and all its parts, + regardless of how they are packaged. This License gives no + permission to license the work in any other way, but it does not + invalidate such permission if you have separately received it. + + d) If the work has interactive user interfaces, each must display + Appropriate Legal Notices; however, if the Program has interactive + interfaces that do not display Appropriate Legal Notices, your + work need not make them do so. + + A compilation of a covered work with other separate and independent +works, which are not by their nature extensions of the covered work, +and which are not combined with it such as to form a larger program, +in or on a volume of a storage or distribution medium, is called an +"aggregate" if the compilation and its resulting copyright are not +used to limit the access or legal rights of the compilation's users +beyond what the individual works permit. Inclusion of a covered work +in an aggregate does not cause this License to apply to the other +parts of the aggregate. + + 6. Conveying Non-Source Forms. + + You may convey a covered work in object code form under the terms +of sections 4 and 5, provided that you also convey the +machine-readable Corresponding Source under the terms of this License, +in one of these ways: + + a) Convey the object code in, or embodied in, a physical product + (including a physical distribution medium), accompanied by the + Corresponding Source fixed on a durable physical medium + customarily used for software interchange. + + b) Convey the object code in, or embodied in, a physical product + (including a physical distribution medium), accompanied by a + written offer, valid for at least three years and valid for as + long as you offer spare parts or customer support for that product + model, to give anyone who possesses the object code either (1) a + copy of the Corresponding Source for all the software in the + product that is covered by this License, on a durable physical + medium customarily used for software interchange, for a price no + more than your reasonable cost of physically performing this + conveying of source, or (2) access to copy the + Corresponding Source from a network server at no charge. + + c) Convey individual copies of the object code with a copy of the + written offer to provide the Corresponding Source. This + alternative is allowed only occasionally and noncommercially, and + only if you received the object code with such an offer, in accord + with subsection 6b. + + d) Convey the object code by offering access from a designated + place (gratis or for a charge), and offer equivalent access to the + Corresponding Source in the same way through the same place at no + further charge. You need not require recipients to copy the + Corresponding Source along with the object code. If the place to + copy the object code is a network server, the Corresponding Source + may be on a different server (operated by you or a third party) + that supports equivalent copying facilities, provided you maintain + clear directions next to the object code saying where to find the + Corresponding Source. Regardless of what server hosts the + Corresponding Source, you remain obligated to ensure that it is + available for as long as needed to satisfy these requirements. + + e) Convey the object code using peer-to-peer transmission, provided + you inform other peers where the object code and Corresponding + Source of the work are being offered to the general public at no + charge under subsection 6d. + + A separable portion of the object code, whose source code is excluded +from the Corresponding Source as a System Library, need not be +included in conveying the object code work. + + A "User Product" is either (1) a "consumer product", which means any +tangible personal property which is normally used for personal, family, +or household purposes, or (2) anything designed or sold for incorporation +into a dwelling. In determining whether a product is a consumer product, +doubtful cases shall be resolved in favor of coverage. For a particular +product received by a particular user, "normally used" refers to a +typical or common use of that class of product, regardless of the status +of the particular user or of the way in which the particular user +actually uses, or expects or is expected to use, the product. A product +is a consumer product regardless of whether the product has substantial +commercial, industrial or non-consumer uses, unless such uses represent +the only significant mode of use of the product. + + "Installation Information" for a User Product means any methods, +procedures, authorization keys, or other information required to install +and execute modified versions of a covered work in that User Product from +a modified version of its Corresponding Source. The information must +suffice to ensure that the continued functioning of the modified object +code is in no case prevented or interfered with solely because +modification has been made. + + If you convey an object code work under this section in, or with, or +specifically for use in, a User Product, and the conveying occurs as +part of a transaction in which the right of possession and use of the +User Product is transferred to the recipient in perpetuity or for a +fixed term (regardless of how the transaction is characterized), the +Corresponding Source conveyed under this section must be accompanied +by the Installation Information. But this requirement does not apply +if neither you nor any third party retains the ability to install +modified object code on the User Product (for example, the work has +been installed in ROM). + + The requirement to provide Installation Information does not include a +requirement to continue to provide support service, warranty, or updates +for a work that has been modified or installed by the recipient, or for +the User Product in which it has been modified or installed. Access to a +network may be denied when the modification itself materially and +adversely affects the operation of the network or violates the rules and +protocols for communication across the network. + + Corresponding Source conveyed, and Installation Information provided, +in accord with this section must be in a format that is publicly +documented (and with an implementation available to the public in +source code form), and must require no special password or key for +unpacking, reading or copying. + + 7. Additional Terms. + + "Additional permissions" are terms that supplement the terms of this +License by making exceptions from one or more of its conditions. +Additional permissions that are applicable to the entire Program shall +be treated as though they were included in this License, to the extent +that they are valid under applicable law. If additional permissions +apply only to part of the Program, that part may be used separately +under those permissions, but the entire Program remains governed by +this License without regard to the additional permissions. + + When you convey a copy of a covered work, you may at your option +remove any additional permissions from that copy, or from any part of +it. (Additional permissions may be written to require their own +removal in certain cases when you modify the work.) You may place +additional permissions on material, added by you to a covered work, +for which you have or can give appropriate copyright permission. + + Notwithstanding any other provision of this License, for material you +add to a covered work, you may (if authorized by the copyright holders of +that material) supplement the terms of this License with terms: + + a) Disclaiming warranty or limiting liability differently from the + terms of sections 15 and 16 of this License; or + + b) Requiring preservation of specified reasonable legal notices or + author attributions in that material or in the Appropriate Legal + Notices displayed by works containing it; or + + c) Prohibiting misrepresentation of the origin of that material, or + requiring that modified versions of such material be marked in + reasonable ways as different from the original version; or + + d) Limiting the use for publicity purposes of names of licensors or + authors of the material; or + + e) Declining to grant rights under trademark law for use of some + trade names, trademarks, or service marks; or + + f) Requiring indemnification of licensors and authors of that + material by anyone who conveys the material (or modified versions of + it) with contractual assumptions of liability to the recipient, for + any liability that these contractual assumptions directly impose on + those licensors and authors. + + All other non-permissive additional terms are considered "further +restrictions" within the meaning of section 10. If the Program as you +received it, or any part of it, contains a notice stating that it is +governed by this License along with a term that is a further +restriction, you may remove that term. If a license document contains +a further restriction but permits relicensing or conveying under this +License, you may add to a covered work material governed by the terms +of that license document, provided that the further restriction does +not survive such relicensing or conveying. + + If you add terms to a covered work in accord with this section, you +must place, in the relevant source files, a statement of the +additional terms that apply to those files, or a notice indicating +where to find the applicable terms. + + Additional terms, permissive or non-permissive, may be stated in the +form of a separately written license, or stated as exceptions; +the above requirements apply either way. + + 8. Termination. + + You may not propagate or modify a covered work except as expressly +provided under this License. Any attempt otherwise to propagate or +modify it is void, and will automatically terminate your rights under +this License (including any patent licenses granted under the third +paragraph of section 11). + + However, if you cease all violation of this License, then your +license from a particular copyright holder is reinstated (a) +provisionally, unless and until the copyright holder explicitly and +finally terminates your license, and (b) permanently, if the copyright +holder fails to notify you of the violation by some reasonable means +prior to 60 days after the cessation. + + Moreover, your license from a particular copyright holder is +reinstated permanently if the copyright holder notifies you of the +violation by some reasonable means, this is the first time you have +received notice of violation of this License (for any work) from that +copyright holder, and you cure the violation prior to 30 days after +your receipt of the notice. + + Termination of your rights under this section does not terminate the +licenses of parties who have received copies or rights from you under +this License. If your rights have been terminated and not permanently +reinstated, you do not qualify to receive new licenses for the same +material under section 10. + + 9. Acceptance Not Required for Having Copies. + + You are not required to accept this License in order to receive or +run a copy of the Program. Ancillary propagation of a covered work +occurring solely as a consequence of using peer-to-peer transmission +to receive a copy likewise does not require acceptance. However, +nothing other than this License grants you permission to propagate or +modify any covered work. These actions infringe copyright if you do +not accept this License. Therefore, by modifying or propagating a +covered work, you indicate your acceptance of this License to do so. + + 10. Automatic Licensing of Downstream Recipients. + + Each time you convey a covered work, the recipient automatically +receives a license from the original licensors, to run, modify and +propagate that work, subject to this License. You are not responsible +for enforcing compliance by third parties with this License. + + An "entity transaction" is a transaction transferring control of an +organization, or substantially all assets of one, or subdividing an +organization, or merging organizations. If propagation of a covered +work results from an entity transaction, each party to that +transaction who receives a copy of the work also receives whatever +licenses to the work the party's predecessor in interest had or could +give under the previous paragraph, plus a right to possession of the +Corresponding Source of the work from the predecessor in interest, if +the predecessor has it or can get it with reasonable efforts. + + You may not impose any further restrictions on the exercise of the +rights granted or affirmed under this License. For example, you may +not impose a license fee, royalty, or other charge for exercise of +rights granted under this License, and you may not initiate litigation +(including a cross-claim or counterclaim in a lawsuit) alleging that +any patent claim is infringed by making, using, selling, offering for +sale, or importing the Program or any portion of it. + + 11. Patents. + + A "contributor" is a copyright holder who authorizes use under this +License of the Program or a work on which the Program is based. The +work thus licensed is called the contributor's "contributor version". + + A contributor's "essential patent claims" are all patent claims +owned or controlled by the contributor, whether already acquired or +hereafter acquired, that would be infringed by some manner, permitted +by this License, of making, using, or selling its contributor version, +but do not include claims that would be infringed only as a +consequence of further modification of the contributor version. For +purposes of this definition, "control" includes the right to grant +patent sublicenses in a manner consistent with the requirements of +this License. + + Each contributor grants you a non-exclusive, worldwide, royalty-free +patent license under the contributor's essential patent claims, to +make, use, sell, offer for sale, import and otherwise run, modify and +propagate the contents of its contributor version. + + In the following three paragraphs, a "patent license" is any express +agreement or commitment, however denominated, not to enforce a patent +(such as an express permission to practice a patent or covenant not to +sue for patent infringement). To "grant" such a patent license to a +party means to make such an agreement or commitment not to enforce a +patent against the party. + + If you convey a covered work, knowingly relying on a patent license, +and the Corresponding Source of the work is not available for anyone +to copy, free of charge and under the terms of this License, through a +publicly available network server or other readily accessible means, +then you must either (1) cause the Corresponding Source to be so +available, or (2) arrange to deprive yourself of the benefit of the +patent license for this particular work, or (3) arrange, in a manner +consistent with the requirements of this License, to extend the patent +license to downstream recipients. "Knowingly relying" means you have +actual knowledge that, but for the patent license, your conveying the +covered work in a country, or your recipient's use of the covered work +in a country, would infringe one or more identifiable patents in that +country that you have reason to believe are valid. + + If, pursuant to or in connection with a single transaction or +arrangement, you convey, or propagate by procuring conveyance of, a +covered work, and grant a patent license to some of the parties +receiving the covered work authorizing them to use, propagate, modify +or convey a specific copy of the covered work, then the patent license +you grant is automatically extended to all recipients of the covered +work and works based on it. + + A patent license is "discriminatory" if it does not include within +the scope of its coverage, prohibits the exercise of, or is +conditioned on the non-exercise of one or more of the rights that are +specifically granted under this License. You may not convey a covered +work if you are a party to an arrangement with a third party that is +in the business of distributing software, under which you make payment +to the third party based on the extent of your activity of conveying +the work, and under which the third party grants, to any of the +parties who would receive the covered work from you, a discriminatory +patent license (a) in connection with copies of the covered work +conveyed by you (or copies made from those copies), or (b) primarily +for and in connection with specific products or compilations that +contain the covered work, unless you entered into that arrangement, +or that patent license was granted, prior to 28 March 2007. + + Nothing in this License shall be construed as excluding or limiting +any implied license or other defenses to infringement that may +otherwise be available to you under applicable patent law. + + 12. No Surrender of Others' Freedom. + + If conditions are imposed on you (whether by court order, agreement or +otherwise) that contradict the conditions of this License, they do not +excuse you from the conditions of this License. If you cannot convey a +covered work so as to satisfy simultaneously your obligations under this +License and any other pertinent obligations, then as a consequence you may +not convey it at all. For example, if you agree to terms that obligate you +to collect a royalty for further conveying from those to whom you convey +the Program, the only way you could satisfy both those terms and this +License would be to refrain entirely from conveying the Program. + + 13. Use with the GNU Affero General Public License. + + Notwithstanding any other provision of this License, you have +permission to link or combine any covered work with a work licensed +under version 3 of the GNU Affero General Public License into a single +combined work, and to convey the resulting work. The terms of this +License will continue to apply to the part which is the covered work, +but the special requirements of the GNU Affero General Public License, +section 13, concerning interaction through a network will apply to the +combination as such. + + 14. Revised Versions of this License. + + The Free Software Foundation may publish revised and/or new versions of +the GNU General Public License from time to time. Such new versions will +be similar in spirit to the present version, but may differ in detail to +address new problems or concerns. + + Each version is given a distinguishing version number. If the +Program specifies that a certain numbered version of the GNU General +Public License "or any later version" applies to it, you have the +option of following the terms and conditions either of that numbered +version or of any later version published by the Free Software +Foundation. If the Program does not specify a version number of the +GNU General Public License, you may choose any version ever published +by the Free Software Foundation. + + If the Program specifies that a proxy can decide which future +versions of the GNU General Public License can be used, that proxy's +public statement of acceptance of a version permanently authorizes you +to choose that version for the Program. + + Later license versions may give you additional or different +permissions. However, no additional obligations are imposed on any +author or copyright holder as a result of your choosing to follow a +later version. + + 15. Disclaimer of Warranty. + + THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY +APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT +HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY +OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, +THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR +PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM +IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF +ALL NECESSARY SERVICING, REPAIR OR CORRECTION. + + 16. Limitation of Liability. + + IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING +WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS +THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY +GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE +USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF +DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD +PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS), +EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF +SUCH DAMAGES. + + 17. Interpretation of Sections 15 and 16. + + If the disclaimer of warranty and limitation of liability provided +above cannot be given local legal effect according to their terms, +reviewing courts shall apply local law that most closely approximates +an absolute waiver of all civil liability in connection with the +Program, unless a warranty or assumption of liability accompanies a +copy of the Program in return for a fee. + + END OF TERMS AND CONDITIONS + + How to Apply These Terms to Your New Programs + + If you develop a new program, and you want it to be of the greatest +possible use to the public, the best way to achieve this is to make it +free software which everyone can redistribute and change under these terms. + + To do so, attach the following notices to the program. It is safest +to attach them to the start of each source file to most effectively +state the exclusion of warranty; and each file should have at least +the "copyright" line and a pointer to where the full notice is found. + + + Copyright (C) + + This program is free software: you can redistribute it and/or modify + it under the terms of the GNU General Public License as published by + the Free Software Foundation, either version 3 of the License, or + (at your option) any later version. + + This program is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU General Public License for more details. + + You should have received a copy of the GNU General Public License + along with this program. If not, see . + +Also add information on how to contact you by electronic and paper mail. + + If the program does terminal interaction, make it output a short +notice like this when it starts in an interactive mode: + + Copyright (C) + This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'. + This is free software, and you are welcome to redistribute it + under certain conditions; type `show c' for details. + +The hypothetical commands `show w' and `show c' should show the appropriate +parts of the General Public License. Of course, your program's commands +might be different; for a GUI interface, you would use an "about box". + + You should also get your employer (if you work as a programmer) or school, +if any, to sign a "copyright disclaimer" for the program, if necessary. +For more information on this, and how to apply and follow the GNU GPL, see +. + + The GNU General Public License does not permit incorporating your program +into proprietary programs. If your program is a subroutine library, you +may consider it more useful to permit linking proprietary applications with +the library. If this is what you want to do, use the GNU Lesser General +Public License instead of this License. But first, please read +. diff --git a/README.md b/README.md new file mode 100644 index 0000000..5483f55 --- /dev/null +++ b/README.md @@ -0,0 +1 @@ +Asynchronous wrapper for pymongo diff --git a/async_pymongo/__init__.py b/async_pymongo/__init__.py new file mode 100644 index 0000000..e43df46 --- /dev/null +++ b/async_pymongo/__init__.py @@ -0,0 +1,23 @@ +"""async_pymongo init""" +# Copyright (C) 2020 - 2023 UserbotIndo Team, +# Copyright (C) 2023 Mayuri-Chan, +# +# This program is free software: you can redistribute it and/or modify +# it under the terms of the GNU General Public License as published by +# the Free Software Foundation, either version 3 of the License, or +# (at your option) any later version. +# +# This program is distributed in the hope that it will be useful, +# but WITHOUT ANY WARRANTY; without even the implied warranty of +# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +# GNU General Public License for more details. +# +# You should have received a copy of the GNU General Public License +# along with this program. If not, see . + +from .client import AsyncClient # skipcq: PY-W2000 +from .collection import AsyncCollection # skipcq: PY-W2000 +from .cursor import AsyncCursor # skipcq: PY-W2000 +from .db import AsyncDatabase # skipcq: PY-W2000 + +__all__ = ["AsyncClient", "AsyncCollection", "AsyncCursor", "AsyncDatabase"] diff --git a/async_pymongo/async_helper.py b/async_pymongo/async_helper.py new file mode 100644 index 0000000..4db1476 --- /dev/null +++ b/async_pymongo/async_helper.py @@ -0,0 +1,29 @@ +"""async_pymongo async utils""" +# Copyright (C) 2020 - 2023 UserbotIndo Team, +# Copyright (C) 2023 Mayuri-Chan, +# +# This program is free software: you can redistribute it and/or modify +# it under the terms of the GNU General Public License as published by +# the Free Software Foundation, either version 3 of the License, or +# (at your option) any later version. +# +# This program is distributed in the hope that it will be useful, +# but WITHOUT ANY WARRANTY; without even the implied warranty of +# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +# GNU General Public License for more details. +# +# You should have received a copy of the GNU General Public License +# along with this program. If not, see . + +import asyncio +import functools +from typing import Any, Callable, TypeVar + +Result = TypeVar("Result") + + +async def run_sync(func: Callable[..., Result], *args: Any, **kwargs: Any) -> Result: + """Runs the given sync function (optionally with arguments) on a separate thread.""" + + loop = asyncio.get_event_loop() + return await loop.run_in_executor(None, functools.partial(func, *args, **kwargs)) diff --git a/async_pymongo/base.py b/async_pymongo/base.py new file mode 100644 index 0000000..3034dd7 --- /dev/null +++ b/async_pymongo/base.py @@ -0,0 +1,103 @@ +"""async_pymongo database core""" +# Copyright (C) 2020 - 2023 UserbotIndo Team, +# Copyright (C) 2023 Mayuri-Chan, +# +# This program is free software: you can redistribute it and/or modify +# it under the terms of the GNU General Public License as published by +# the Free Software Foundation, either version 3 of the License, or +# (at your option) any later version. +# +# This program is distributed in the hope that it will be useful, +# but WITHOUT ANY WARRANTY; without even the implied warranty of +# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +# GNU General Public License for more details. +# +# You should have received a copy of the GNU General Public License +# along with this program. If not, see . + +from typing import TYPE_CHECKING, Any, Generic, Union + +from bson.codec_options import CodecOptions +from pymongo.client_session import ClientSession +from pymongo.collection import Collection +from pymongo.command_cursor import CommandCursor, RawBatchCommandCursor +from pymongo.cursor import Cursor, RawBatchCursor +from pymongo.database import Database +from pymongo.mongo_client import MongoClient +from pymongo.read_concern import ReadConcern +from pymongo.read_preferences import _ServerMode +from pymongo.typings import _DocumentType +from pymongo.write_concern import WriteConcern + +if TYPE_CHECKING: + from .command_cursor import _LatentCursor + + +class AsyncBase(Generic[_DocumentType]): + """Base Class for AsyncIOMongoDB Instances""" + + dispatch: Union[ + "_LatentCursor[_DocumentType]", + ClientSession, + Collection[_DocumentType], + CommandCursor[_DocumentType], + Cursor[_DocumentType], + Database[_DocumentType], + MongoClient[_DocumentType], + RawBatchCursor[_DocumentType], + RawBatchCommandCursor[_DocumentType], + ] + + def __init__( + self, + dispatch: Union[ + "_LatentCursor[_DocumentType]", + ClientSession, + Collection[_DocumentType], + CommandCursor[_DocumentType], + Cursor[_DocumentType], + Database[_DocumentType], + MongoClient[_DocumentType], + RawBatchCursor[_DocumentType], + RawBatchCommandCursor[_DocumentType], + ], + ) -> None: + self.dispatch = dispatch + + def __eq__(self, other: Any) -> bool: + if ( + isinstance(other, self.__class__) + and hasattr(self, "dispatch") + and hasattr(other, "dispatch") + ): + return self.dispatch == other.dispatch + + return NotImplemented + + def __hash__(self): + return hash(self.dispatch) + + def __repr__(self) -> str: + return type(self).__name__ + f"({self.dispatch!r})" + + +class AsyncBaseProperty(AsyncBase): + """Base class property for AsyncIOMongoDB instances""" + + dispatch: Union[Collection, Database, MongoClient] + + @property + def codec_options(self) -> CodecOptions: + return self.dispatch.codec_options + + @property + def read_preference(self) -> _ServerMode: + return self.dispatch.read_preference + + @property + def read_concern(self) -> ReadConcern: + return self.dispatch.read_concern + + @property + def write_concern(self) -> WriteConcern: + return self.dispatch.write_concern diff --git a/async_pymongo/change_stream.py b/async_pymongo/change_stream.py new file mode 100644 index 0000000..cc3fcd4 --- /dev/null +++ b/async_pymongo/change_stream.py @@ -0,0 +1,133 @@ +"""async_pymongo database stream""" +# Copyright (C) 2020 - 2023 UserbotIndo Team, +# Copyright (C) 2023 Mayuri-Chan, +# +# This program is free software: you can redistribute it and/or modify +# it under the terms of the GNU General Public License as published by +# the Free Software Foundation, either version 3 of the License, or +# (at your option) any later version. +# +# This program is distributed in the hope that it will be useful, +# but WITHOUT ANY WARRANTY; without even the implied warranty of +# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +# GNU General Public License for more details. +# +# You should have received a copy of the GNU General Public License +# along with this program. If not, see . + +from typing import TYPE_CHECKING, Any, List, Literal, Mapping, Optional, Union + +from bson.timestamp import Timestamp +from pymongo.change_stream import ChangeStream +from pymongo.collation import Collation + +from async_pymongo.async_helper import run_sync + +from .base import AsyncBase +from .client_session import AsyncClientSession + +if TYPE_CHECKING: + from .client import AsyncClient + from .collection import AsyncCollection + from .db import AsyncDatabase + + +class AsyncChangeStream(AsyncBase): + """AsyncIO :obj:`~ChangeStream` + + *DEPRECATED* methods are removed in this class. + """ + + _target: Union["AsyncClient", "AsyncDatabase", "AsyncCollection"] + + dispatch: ChangeStream + + def __init__( + self, + target: Union["AsyncClient", "AsyncDatabase", "AsyncCollection"], + pipeline: Optional[List[Mapping[str, Any]]], + full_document: Optional[Literal["updateLookup"]], + resume_after: Optional[Mapping[str, str]], + max_await_time_ms: Optional[int], + batch_size: Optional[int], + collation: Optional[Collation], + start_at_operation_time: Optional[Timestamp], + session: Optional[AsyncClientSession], + start_after: Optional[Mapping[str, str]], + comment: Optional[str], + full_document_before_change: Optional[Literal["required", "whenAvailable"]] = None, + ) -> None: + self._target = target + self._options: Mapping[str, Any] = { + "pipeline": pipeline, + "full_document": full_document, + "resume_after": resume_after, + "max_await_time_ms": max_await_time_ms, + "batch_size": batch_size, + "collation": collation, + "start_at_operation_time": start_at_operation_time, + "session": session.dispatch if session else session, + "start_after": start_after, + "comment": comment, + "full_document_before_change": full_document_before_change, + } + + super().__init__(None) # type: ignore + + def __aiter__(self) -> "AsyncChangeStream": + return self + + def __iter__(self) -> None: + raise RuntimeError("Use 'async for' instead of 'for'") + + async def __anext__(self) -> Mapping[str, Any]: + return await self.next() + + async def __aenter__(self) -> "AsyncChangeStream": + if not self.dispatch: + await self._init() + + return self + + async def __aexit__(self, exc_type: Any, exc_val: Any, exc_tb: Any) -> None: + if self.dispatch: + await self.close() + + def __enter__(self) -> None: + raise RuntimeError("Use 'async with' not just 'with'") + + async def _init(self) -> ChangeStream: + if not self.dispatch: + self.dispatch = await run_sync(self._target.dispatch.watch, **self._options) + + return self.dispatch + + async def close(self): + if self.dispatch: + await run_sync(self.dispatch.close) + + async def next(self) -> Mapping[str, Any]: + while self.alive: + document = await self.try_next() + if document: + return document + + raise StopAsyncIteration + + async def try_next(self) -> Optional[Mapping[str, Any]]: + self.dispatch = await self._init() + return await run_sync(self.dispatch.try_next) + + @property + def alive(self) -> bool: + if not self.dispatch: + return True + + return self.dispatch.alive + + @property + def resume_token(self) -> Any: + if self.dispatch: + return self.dispatch.resume_token + + return None diff --git a/async_pymongo/client.py b/async_pymongo/client.py new file mode 100644 index 0000000..4626eed --- /dev/null +++ b/async_pymongo/client.py @@ -0,0 +1,260 @@ +"""async_pymongo database client""" +# Copyright (C) 2020 - 2023 UserbotIndo Team, +# Copyright (C) 2023 Mayuri-Chan, +# +# This program is free software: you can redistribute it and/or modify +# it under the terms of the GNU General Public License as published by +# the Free Software Foundation, either version 3 of the License, or +# (at your option) any later version. +# +# This program is distributed in the hope that it will be useful, +# but WITHOUT ANY WARRANTY; without even the implied warranty of +# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +# GNU General Public License for more details. +# +# You should have received a copy of the GNU General Public License +# along with this program. If not, see . + +from contextlib import asynccontextmanager +from typing import ( + Any, + AsyncGenerator, + FrozenSet, + List, + Literal, + Mapping, + Optional, + Set, + Tuple, + Union, +) + +from bson.codec_options import DEFAULT_CODEC_OPTIONS, CodecOptions +from bson.son import SON +from bson.timestamp import Timestamp +from pymongo.client_session import TransactionOptions +from pymongo.collation import Collation +from pymongo.driver_info import DriverInfo +from pymongo.mongo_client import MongoClient +from pymongo.read_concern import ReadConcern +from pymongo.read_preferences import ReadPreference +from pymongo.topology_description import TopologyDescription +from pymongo.typings import _Address +from pymongo.write_concern import DEFAULT_WRITE_CONCERN, WriteConcern + +from async_pymongo.async_helper import run_sync + +from .base import AsyncBaseProperty +from .change_stream import AsyncChangeStream +from .client_session import AsyncClientSession +from .command_cursor import AsyncCommandCursor, CommandCursor +from .db import AsyncDatabase +from .typings import ReadPreferences + + +class AsyncClient(AsyncBaseProperty): + """AsyncIO :obj:`~MongoClient` + + *DEPRECATED* methods are removed in this class. + """ + + dispatch: MongoClient + + def __init__(self, *args: Any, **kwargs: Any) -> None: + kwargs.update( + {"driver": DriverInfo("AsyncIOMongoDB", version="staging", platform="AsyncIO")} + ) + dispatch = MongoClient(*args, **kwargs) + + # Propagate initialization to base + super().__init__(dispatch) + + def __getitem__(self, name: str) -> AsyncDatabase: + return AsyncDatabase(self, self.dispatch[name]) + + def __hash__(self) -> int: + return hash(self.address) + + async def close(self) -> None: + await run_sync(self.dispatch.close) + + async def drop_database( + self, + name_or_database: Union[str, AsyncDatabase], + session: Optional[AsyncClientSession] = None, + ) -> None: + if isinstance(name_or_database, AsyncDatabase): + name_or_database = name_or_database.name + + return await run_sync( + self.dispatch.drop_database, + name_or_database, + session=session.dispatch if session else session, + ) + + def get_database( + self, + name: Optional[str] = None, + *, + codec_options: Optional[CodecOptions] = None, + read_preference: Optional[ReadPreferences] = None, + write_concern: Optional[WriteConcern] = None, + read_concern: Optional[ReadConcern] = None, + ) -> AsyncDatabase: + return AsyncDatabase( + self, + self.dispatch.get_database( + name, + codec_options=codec_options, + read_preference=read_preference, + write_concern=write_concern, + read_concern=read_concern, + ), + ) + + def get_default_database( + self, + default: Optional[str] = None, + *, + codec_options: Optional[CodecOptions] = None, + read_preference: Optional[ReadPreferences] = None, + write_concern: Optional[WriteConcern] = None, + read_concern: Optional[ReadConcern] = None, + ) -> AsyncDatabase: + return AsyncDatabase( + self, + self.dispatch.get_default_database( + default, + codec_options=codec_options, + read_preference=read_preference, + write_concern=write_concern, + read_concern=read_concern, + ), + ) + + async def list_database_names(self, session: Optional[AsyncClientSession] = None) -> List[str]: + return await run_sync( + self.dispatch.list_database_names, session=session.dispatch if session else session + ) + + async def list_databases( + self, session: Optional[AsyncClientSession] = None, **kwargs: Any + ) -> AsyncCommandCursor: + cmd = SON([("listDatabases", 1)]) + cmd.update(kwargs) + database = self.get_database( + "admin", + codec_options=DEFAULT_CODEC_OPTIONS, + read_preference=ReadPreference.PRIMARY, + write_concern=DEFAULT_WRITE_CONCERN, + ) + res: Mapping[str, Any] = await run_sync( + database.dispatch._retryable_read_command, # skipcq: PYL-W0212 + cmd, + session=session.dispatch if session else session, + ) + cursor: Mapping[str, Any] = { + "id": 0, + "firstBatch": res["databases"], + "ns": "admin.$cmd", + } + return AsyncCommandCursor(CommandCursor(database["$cmd"], cursor, None)) + + async def server_info(self, session: Optional[AsyncClientSession] = None) -> Mapping[str, Any]: + return await run_sync( + self.dispatch.server_info, session=session.dispatch if session else session + ) + + # Don't need await when entering the context manager, + # because it's slightly different than motor libs. + @asynccontextmanager + async def start_session( + self, + *, + causal_consistency: Optional[bool] = None, + default_transaction_options: Optional[TransactionOptions] = None, + snapshot: bool = False, + ) -> AsyncGenerator[AsyncClientSession, None]: + session = await run_sync( + self.dispatch.start_session, + causal_consistency=causal_consistency, + default_transaction_options=default_transaction_options, + snapshot=snapshot, + ) + + async with AsyncClientSession(self, session) as session: + yield session + + def watch( + self, + pipeline: Optional[List[Mapping[str, Any]]] = None, + *, + full_document: Optional[Literal["updateLookup"]] = None, + resume_after: Optional[Mapping[str, str]] = None, + max_await_time_ms: Optional[int] = None, + batch_size: Optional[int] = None, + collation: Optional[Collation] = None, + start_at_operation_time: Optional[Timestamp] = None, + session: Optional[AsyncClientSession] = None, + start_after: Optional[Mapping[str, str]] = None, + comment: Optional[str] = None, + full_document_before_change: Optional[Literal["required", "whenAvailable"]] = None, + ) -> AsyncChangeStream: + return AsyncChangeStream( + self, + pipeline, + full_document, + resume_after, + max_await_time_ms, + batch_size, + collation, + start_at_operation_time, + session, + start_after, + comment, + full_document_before_change, + ) + + @property + def HOST(self) -> str: + return self.dispatch.HOST + + @property + def PORT(self) -> int: + return self.dispatch.PORT + + @property + def address(self) -> Optional[Tuple[str, int]]: + return self.dispatch.address + + @property + def arbiters(self) -> Set[Tuple[str, int]]: + return self.dispatch.arbiters + + @property + def event_listeners(self) -> Any: + return self.dispatch.event_listeners + + @property + def is_mongos(self) -> bool: + return self.dispatch.is_mongos + + @property + def is_primary(self) -> bool: + return self.dispatch.is_primary + + @property + def nodes(self) -> FrozenSet[_Address]: + return self.dispatch.nodes + + @property + def primary(self) -> Optional[Tuple[str, int]]: + return self.dispatch.primary + + @property + def secondaries(self) -> Set[Tuple[str, int]]: + return self.dispatch.secondaries + + @property + def topology_description(self) -> TopologyDescription: + return self.dispatch.topology_description diff --git a/async_pymongo/client_session.py b/async_pymongo/client_session.py new file mode 100644 index 0000000..2923602 --- /dev/null +++ b/async_pymongo/client_session.py @@ -0,0 +1,201 @@ +"""async_pymongo database session""" +# Copyright (C) 2020 - 2023 UserbotIndo Team, +# Copyright (C) 2023 Mayuri-Chan, +# +# This program is free software: you can redistribute it and/or modify +# it under the terms of the GNU General Public License as published by +# the Free Software Foundation, either version 3 of the License, or +# (at your option) any later version. +# +# This program is distributed in the hope that it will be useful, +# but WITHOUT ANY WARRANTY; without even the implied warranty of +# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +# GNU General Public License for more details. +# +# You should have received a copy of the GNU General Public License +# along with this program. If not, see . + +from contextlib import asynccontextmanager +from time import monotonic as monotonic_time +from typing import ( + TYPE_CHECKING, + Any, + AsyncGenerator, + Callable, + Coroutine, + Mapping, + Optional, +) + +from bson.timestamp import Timestamp +from pymongo.client_session import ClientSession, SessionOptions +from pymongo.read_concern import ReadConcern +from pymongo.write_concern import WriteConcern + +from async_pymongo.async_helper import run_sync + +from .base import AsyncBase +from .errors import OperationFailure, PyMongoError +from .typings import ReadPreferences, Results + +if TYPE_CHECKING: + from .client import AsyncClient + + +class AsyncClientSession(AsyncBase): + """AsyncIO :obj:`~ClientSession` + + *DEPRECATED* methods are removed in this class. + """ + + _client: "AsyncClient" + + dispatch: ClientSession + + def __init__(self, client: "AsyncClient", dispatch: ClientSession) -> None: + self._client = client + + # Propagate initialization to base + super().__init__(dispatch) + + async def __aenter__(self) -> "AsyncClientSession": + return self + + async def __aexit__(self, exc_type: Any, exc_val: Any, exc_tb: Any) -> None: + await run_sync(self.dispatch.__exit__, exc_type, exc_val, exc_tb) + + def __enter__(self) -> None: + raise RuntimeError("Use 'async with' not just 'with'") + + async def abort_transaction(self) -> None: + return await run_sync(self.dispatch.abort_transaction) + + async def commit_transaction(self) -> None: + return await run_sync(self.dispatch.commit_transaction) + + async def end_session(self) -> None: + return await run_sync(self.dispatch.end_session) + + @asynccontextmanager + async def start_transaction( + self, + *, + read_concern: Optional[ReadConcern] = None, + write_concern: Optional[WriteConcern] = None, + read_preference: Optional[ReadPreferences] = None, + max_commit_time_ms: Optional[int] = None, + ) -> AsyncGenerator["AsyncClientSession", None]: + await run_sync( + self.dispatch.start_transaction, + read_concern=read_concern, + write_concern=write_concern, + read_preference=read_preference, + max_commit_time_ms=max_commit_time_ms, + ) + try: + yield self + except Exception: # skipcq: PYL-W0703 + if self.in_transaction: + await self.abort_transaction() + else: + if self.in_transaction: + await self.commit_transaction() + + async def with_transaction( + self, + callback: Callable[["AsyncClientSession"], Coroutine[Any, Any, Results]], + *, + read_concern: Optional[ReadConcern] = None, + write_concern: Optional[WriteConcern] = None, + read_preference: Optional[ReadPreferences] = None, + max_commit_time_ms: Optional[int] = None, + ) -> Results: + # 99% Of this code from motor's lib + + def _within_time_limit(s: float) -> bool: + return monotonic_time() - s < 120 + + def _max_time_expired_error(exc: PyMongoError) -> bool: + return isinstance(exc, OperationFailure) and exc.code == 50 + + start_time = monotonic_time() + while True: + async with self.start_transaction( + read_concern=read_concern, + write_concern=write_concern, + read_preference=read_preference, + max_commit_time_ms=max_commit_time_ms, + ): + try: + ret = await callback(self) + except Exception as exc: + if self.in_transaction: + await self.abort_transaction() + if ( + isinstance(exc, PyMongoError) + and exc.has_error_label("TransientTransactionError") + and _within_time_limit(start_time) + ): + # Retry the entire transaction. + continue + raise + + if not self.in_transaction: + # Assume callback intentionally ended the transaction. + return ret + + while True: + try: + await self.commit_transaction() + except PyMongoError as exc: + if ( + exc.has_error_label("UnknownTransactionCommitResult") + and _within_time_limit(start_time) + and not _max_time_expired_error(exc) + ): + # Retry the commit. + continue + + if exc.has_error_label("TransientTransactionError") and _within_time_limit( + start_time + ): + # Retry the entire transaction. + break + raise + + # Commit succeeded. + return ret + + def advance_cluster_time(self, cluster_time: Mapping[str, Any]) -> None: + self.dispatch.advance_cluster_time(cluster_time=cluster_time) + + def advance_operation_time(self, operation_time: Timestamp) -> None: + self.dispatch.advance_operation_time(operation_time=operation_time) + + @property + def client(self) -> "AsyncClient": + return self._client + + @property + def cluster_time(self) -> Optional[Mapping[str, Any]]: + return self.dispatch.cluster_time + + @property + def has_ended(self) -> bool: + return self.dispatch.has_ended + + @property + def in_transaction(self) -> bool: + return self.dispatch.in_transaction + + @property + def operation_time(self) -> Optional[Timestamp]: + return self.dispatch.operation_time + + @property + def options(self) -> SessionOptions: + return self.dispatch.options + + @property + def session_id(self) -> Mapping[str, Any]: + return self.dispatch.session_id diff --git a/async_pymongo/collection.py b/async_pymongo/collection.py new file mode 100644 index 0000000..e79eaf6 --- /dev/null +++ b/async_pymongo/collection.py @@ -0,0 +1,543 @@ +"""async_pymongo database collection""" +# Copyright (C) 2020 - 2023 UserbotIndo Team, +# Copyright (C) 2023 Mayuri-Chan, +# +# This program is free software: you can redistribute it and/or modify +# it under the terms of the GNU General Public License as published by +# the Free Software Foundation, either version 3 of the License, or +# (at your option) any later version. +# +# This program is distributed in the hope that it will be useful, +# but WITHOUT ANY WARRANTY; without even the implied warranty of +# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +# GNU General Public License for more details. +# +# You should have received a copy of the GNU General Public License +# along with this program. If not, see . + +from typing import ( + TYPE_CHECKING, + Any, + Generic, + List, + Literal, + Mapping, + Optional, + Tuple, + Union, +) + +from bson.codec_options import CodecOptions +from bson.timestamp import Timestamp +from pymongo.collation import Collation +from pymongo.collection import Collection +from pymongo.operations import IndexModel +from pymongo.read_concern import ReadConcern +from pymongo.read_preferences import _ServerMode +from pymongo.results import ( + BulkWriteResult, + DeleteResult, + InsertManyResult, + InsertOneResult, + UpdateResult, +) +from pymongo.typings import _DocumentType +from pymongo.write_concern import WriteConcern + +from async_pymongo.async_helper import run_sync + +from .base import AsyncBaseProperty +from .change_stream import AsyncChangeStream +from .client_session import AsyncClientSession +from .command_cursor import AsyncLatentCommandCursor +from .cursor import AsyncCursor, AsyncRawBatchCursor, Cursor +from .typings import ReadPreferences, Request + +if TYPE_CHECKING: + from .db import AsyncDatabase + + +class AsyncCollection(AsyncBaseProperty, Generic[_DocumentType]): + """AsyncIO :obj:`~Collection` + + *DEPRECATED* methods are removed in this class. + """ + + database: "AsyncDatabase" + dispatch: Collection + + def __init__( + self, + database: "AsyncDatabase", + name: str, + *, + create: bool = False, + codec_options: Optional[CodecOptions] = None, + read_preference: Optional[_ServerMode] = None, + write_concern: Optional[WriteConcern] = None, + read_concern: Optional[ReadConcern] = None, + collection: Optional[Collection] = None, + session: Optional[AsyncClientSession] = None, + **kwargs: Any, + ) -> None: + dispatch = ( + collection + if collection is not None + else Collection( + database.dispatch, + name, + create=create, + codec_options=codec_options, + read_preference=read_preference, + write_concern=write_concern, + read_concern=read_concern, + session=session.dispatch if session else session, + **kwargs, + ) + ) + # Propagate initialization to base + super().__init__(dispatch) + self.database = database + + def __bool__(self) -> bool: + return self.dispatch is not None + + def __getitem__(self, name: str) -> "AsyncCollection": + return AsyncCollection( + self.database, + f"{self.name}.{name}", + collection=self.dispatch[name], + ) + + def __hash__(self) -> int: + return hash((self.database, self.name)) + + def aggregate( + self, + pipeline: List[Mapping[str, Any]], + *args: Any, + session: Optional[AsyncClientSession] = None, + **kwargs: Any, + ) -> AsyncLatentCommandCursor: + return AsyncLatentCommandCursor( + self, + self.dispatch.aggregate, + pipeline, + session=session.dispatch if session else session, + *args, + **kwargs, + ) + + def aggregate_raw_batches( + self, + pipeline: List[Mapping[str, Any]], + *, + session: Optional[AsyncClientSession] = None, + **kwargs: Any, + ) -> AsyncLatentCommandCursor: + return AsyncLatentCommandCursor( + self, + self.dispatch.aggregate_raw_batches, + pipeline, + session=session.dispatch if session else session, + **kwargs, + ) + + async def bulk_write( + self, + request: List[Request], + *, + ordered: bool = True, + bypass_document_validation: bool = False, + session: Optional[AsyncClientSession] = None, + ) -> BulkWriteResult: + return await run_sync( + self.dispatch.bulk_write, + request, + ordered=ordered, + bypass_document_validation=bypass_document_validation, + session=session.dispatch if session else session, + ) + + async def count_documents( + self, + query: Mapping[str, Any], + *, + session: Optional[AsyncClientSession] = None, + **kwargs: Any, + ) -> int: + return await run_sync( + self.dispatch.count_documents, + query, + session=session.dispatch if session else session, + **kwargs, + ) + + async def create_index(self, keys: Union[str, List[Tuple[str, Any]]], **kwargs: Any) -> str: + return await run_sync(self.dispatch.create_index, keys, **kwargs) + + async def create_indexes( + self, + indexes: List[IndexModel], + *, + session: Optional[AsyncClientSession] = None, + **kwargs: Any, + ) -> List[str]: + return await run_sync( + self.dispatch.create_indexes, + indexes, + session=session.dispatch if session else session, + **kwargs, + ) + + async def delete_many( + self, + query: Mapping[str, Any], + *, + collation: Optional[Collation] = None, + hint: Optional[Union[IndexModel, List[Tuple[str, Any]]]] = None, + session: Optional[AsyncClientSession] = None, + ) -> DeleteResult: + return await run_sync( + self.dispatch.delete_many, + query, + collation=collation, + hint=hint, + session=session.dispatch if session else session, + ) + + async def delete_one( + self, + query: Mapping[str, Any], + *, + collation: Optional[Collation] = None, + hint: Optional[Union[IndexModel, List[Tuple[str, Any]]]] = None, + session: Optional[AsyncClientSession] = None, + ) -> DeleteResult: + return await run_sync( + self.dispatch.delete_one, + query, + collation=collation, + hint=hint, + session=session.dispatch if session else session, + ) + + async def distinct( + self, + key: str, + query: Optional[Mapping[str, Any]] = None, + *, + session: Optional[AsyncClientSession] = None, + **kwargs: Any, + ) -> List[str]: + return await run_sync( + self.dispatch.distinct, + key, + filter=query, + session=session.dispatch if session else session, + **kwargs, + ) + + async def drop(self, session: Optional[AsyncClientSession] = None) -> None: + await run_sync(self.dispatch.drop, session=session.dispatch if session else session) + + async def drop_index( + self, + index_or_name: Union[str, IndexModel], + *, + session: Optional[AsyncClientSession] = None, + **kwargs: Any, + ) -> None: + await run_sync( + self.dispatch.drop_index, + index_or_name, + session=session.dispatch if session else session, + **kwargs, + ) + + async def drop_indexes(self, session: Optional[AsyncClientSession] = None, **kwargs) -> None: + await run_sync( + self.dispatch.drop_indexes, session=session.dispatch if session else session, **kwargs + ) + + async def estimated_document_count(self, **kwargs: Any) -> int: + return await run_sync(self.dispatch.estimated_document_count, **kwargs) + + def find(self, *args: Any, **kwargs: Any) -> AsyncCursor: + return AsyncCursor(Cursor(self, *args, **kwargs), self) + + async def find_one( + self, query: Optional[Mapping[str, Any]], *args: Any, **kwargs: Any + ) -> Optional[Mapping[str, Any]]: + return await run_sync(self.dispatch.find_one, query, *args, **kwargs) + + async def find_one_and_delete( + self, + query: Mapping[str, Any], + *, + projection: Optional[Union[List[Any], Mapping[str, Any]]] = None, + sort: Optional[List[Tuple[str, Any]]] = None, + hint: Optional[Union[IndexModel, List[Tuple[str, Any]]]] = None, + session: Optional[AsyncClientSession] = None, + **kwargs: Any, + ) -> Mapping[str, Any]: + return await run_sync( + self.dispatch.find_one_and_delete, + query, + projection=projection, + sort=sort, + hint=hint, + session=session.dispatch if session else session, + **kwargs, + ) + + async def find_one_and_replace( + self, + query: Mapping[str, Any], + replacement: Mapping[str, Any], + *, + projection: Optional[Union[List[Any], Mapping[str, Any]]] = None, + sort: Optional[List[Tuple[str, Any]]] = None, + upsert: bool = False, + return_document: bool = False, + hint: Optional[Union[IndexModel, List[Tuple[str, Any]]]] = None, + session: Optional[AsyncClientSession] = None, + **kwargs: Any, + ) -> Mapping[str, Any]: + return await run_sync( + self.dispatch.find_one_and_replace, + query, + replacement, + projection=projection, + sort=sort, + upsert=upsert, + return_document=return_document, + hint=hint, + session=session.dispatch if session else session, + **kwargs, + ) + + async def find_one_and_update( + self, + query: Mapping[str, Any], + update: Mapping[str, Any], + *, + projection: Optional[Union[List[Any], Mapping[str, Any]]] = None, + sort: Optional[List[Tuple[str, Any]]] = None, + upsert: bool = False, + return_document: bool = False, + array_filters: Optional[List[Mapping[str, Any]]] = None, + hint: Optional[Union[IndexModel, List[Tuple[str, Any]]]] = None, + session: Optional[AsyncClientSession] = None, + **kwargs: Any, + ) -> Mapping[str, Any]: + return await run_sync( + self.dispatch.find_one_and_update, + query, + update, + projection=projection, + sort=sort, + upsert=upsert, + return_document=return_document, + array_filters=array_filters, + hint=hint, + session=session.dispatch if session else session, + **kwargs, + ) + + def find_raw_batches(self, *args: Any, **kwargs: Any) -> AsyncRawBatchCursor: + if "session" in kwargs: + session = kwargs["session"] + kwargs["session"] = session.dispatch if session else session + + cursor = self.dispatch.find_raw_batches(*args, **kwargs) + + return AsyncRawBatchCursor(cursor, self) + + async def index_information( + self, session: Optional[AsyncClientSession] = None + ) -> Mapping[str, Any]: + return await run_sync( + self.dispatch.index_information, session=session.dispatch if session else session + ) + + async def insert_many( + self, + documents: List[Mapping[str, Any]], + *, + ordered: bool = True, + bypass_document_validation: bool = False, + session: Optional[AsyncClientSession] = None, + ) -> InsertManyResult: + return await run_sync( + self.dispatch.insert_many, + documents, + ordered=ordered, + bypass_document_validation=bypass_document_validation, + session=session.dispatch if session else session, + ) + + async def insert_one( + self, + document: Mapping[str, Any], + *, + bypass_document_validation: bool = False, + session: Optional[AsyncClientSession] = None, + ) -> InsertOneResult: + return await run_sync( + self.dispatch.insert_one, + document, + bypass_document_validation=bypass_document_validation, + session=session.dispatch if session else session, + ) + + def list_indexes( + self, *args: Any, session: Optional[AsyncClientSession] = None, **kwargs: Any + ) -> AsyncLatentCommandCursor: + return AsyncLatentCommandCursor( + self, + self.dispatch.list_indexes, + session=session.dispatch if session else session, + *args, + **kwargs, + ) + + async def options(self, session: Optional[AsyncClientSession] = None) -> Mapping[str, Any]: + return await run_sync( + self.dispatch.options, session=session.dispatch if session else session + ) + + async def rename( + self, new_name: str, *, session: Optional[AsyncClientSession] = None, **kwargs: Any + ) -> Mapping[str, Any]: + return await run_sync( + self.dispatch.rename, + new_name, + session=session.dispatch if session else session, + **kwargs, + ) + + async def replace_one( + self, + query: Mapping[str, Any], + replacement: Mapping[str, Any], + *, + upsert: bool = False, + bypass_document_validation: bool = False, + collation: Optional[Collation] = None, + hint: Optional[Union[IndexModel, List[Tuple[str, Any]]]] = None, + session: Optional[AsyncClientSession] = None, + ) -> UpdateResult: + return await run_sync( + self.dispatch.replace_one, + query, + replacement, + upsert=upsert, + bypass_document_validation=bypass_document_validation, + collation=collation, + hint=hint, + session=session.dispatch if session else session, + ) + + async def update_many( + self, + query: Mapping[str, Any], + update: Mapping[str, Any], + *, + upsert: bool = False, + array_filters: Optional[List[Mapping[str, Any]]] = None, + bypass_document_validation: bool = False, + collation: Optional[Collation] = None, + hint: Optional[Union[IndexModel, List[Tuple[str, Any]]]] = None, + session: Optional[AsyncClientSession] = None, + ) -> UpdateResult: + return await run_sync( + self.dispatch.update_many, + query, + update, + upsert=upsert, + array_filters=array_filters, + bypass_document_validation=bypass_document_validation, + collation=collation, + hint=hint, + session=session.dispatch if session else session, + ) + + async def update_one( + self, + query: Mapping[str, Any], + update: Mapping[str, Any], + *, + upsert: bool = False, + array_filters: Optional[List[Mapping[str, Any]]] = None, + bypass_document_validation: bool = False, + collation: Optional[Collation] = None, + hint: Optional[Union[IndexModel, List[Tuple[str, Any]]]] = None, + session: Optional[AsyncClientSession] = None, + ) -> UpdateResult: + return await run_sync( + self.dispatch.update_one, + query, + update, + upsert=upsert, + array_filters=array_filters, + bypass_document_validation=bypass_document_validation, + collation=collation, + hint=hint, + session=session.dispatch if session else session, + ) + + def watch( + self, + pipeline: Optional[List[Mapping[str, Any]]] = None, + *, + full_document: Optional[Literal["updateLookup"]] = None, + resume_after: Optional[Mapping[str, str]] = None, + max_await_time_ms: Optional[int] = None, + batch_size: Optional[int] = None, + collation: Optional[Collation] = None, + start_at_operation_time: Optional[Timestamp] = None, + session: Optional[AsyncClientSession] = None, + start_after: Optional[Mapping[str, str]] = None, + comment: Optional[str] = None, + full_document_before_change: Optional[Literal["required", "whenAvailable"]] = None, + ) -> AsyncChangeStream: + return AsyncChangeStream( + self, + pipeline, + full_document, + resume_after, + max_await_time_ms, + batch_size, + collation, + start_at_operation_time, + session, + start_after, + comment, + full_document_before_change, + ) + + def with_options( + self, + *, + codec_options: Optional[CodecOptions] = None, + read_preference: Optional[ReadPreferences] = None, + write_concern: Optional[WriteConcern] = None, + read_concern: Optional[ReadConcern] = None, + ) -> "AsyncCollection": + self.dispatch = self.dispatch.with_options( + codec_options=codec_options, + read_preference=read_preference, + write_concern=write_concern, + read_concern=read_concern, + ) + + return self + + @property + def full_name(self) -> str: + return self.dispatch.full_name + + @property + def name(self) -> str: + return self.dispatch.name diff --git a/async_pymongo/command_cursor.py b/async_pymongo/command_cursor.py new file mode 100644 index 0000000..3c8a811 --- /dev/null +++ b/async_pymongo/command_cursor.py @@ -0,0 +1,236 @@ +"""async_pymongo database commmand cursor""" +# Copyright (C) 2020 - 2023 UserbotIndo Team, +# Copyright (C) 2023 Mayuri-Chan, +# +# This program is free software: you can redistribute it and/or modify +# it under the terms of the GNU General Public License as published by +# the Free Software Foundation, either version 3 of the License, or +# (at your option) any later version. +# +# This program is distributed in the hope that it will be useful, +# but WITHOUT ANY WARRANTY; without even the implied warranty of +# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +# GNU General Public License for more details. +# +# You should have received a copy of the GNU General Public License +# along with this program. If not, see . + +import asyncio +from collections import deque +from functools import partial +from typing import ( + TYPE_CHECKING, + Any, + Callable, + ClassVar, + Coroutine, + Deque, + Generic, + Mapping, + Optional, + Tuple, + Union, +) + +from pymongo.client_session import ClientSession +from pymongo.command_cursor import CommandCursor as _CommandCursor +from pymongo.typings import _Address, _DocumentType + +from async_pymongo.async_helper import run_sync + +from .client_session import AsyncClientSession +from .cursor_base import AsyncCursorBase + +if TYPE_CHECKING: + from .collection import AsyncCollection + + +class CommandCursor(_CommandCursor, Generic[_DocumentType]): + + _CommandCursor__data: Deque[Any] + _CommandCursor__killed: bool + + delegate: "AsyncCollection" + + def __init__( + self, + collection: "AsyncCollection", + cursor_info: Mapping[str, Any], + address: Optional[Union[Tuple[str, int], _Address]] = None, + *, + batch_size: int = 0, + max_await_time_ms: Optional[int] = None, + session: Optional[AsyncClientSession] = None, + explicit_session: bool = False, + ) -> None: + self.delegate = collection + + super().__init__( + collection.dispatch, + cursor_info, + address, + batch_size=batch_size, + max_await_time_ms=max_await_time_ms, + session=session.dispatch if session else session, + explicit_session=explicit_session, + ) + + async def _AsyncCommandCursor__die(self, synchronous: bool = False) -> None: + await run_sync(self.__die, synchronous=synchronous) + + @property + def _AsyncCommandCursor__data(self) -> Deque[Any]: + return self.__data + + @property + def _AsyncCommandCursor__killed(self) -> bool: + return self.__killed + + @property + def collection(self) -> "AsyncCollection[_DocumentType]": + return self.delegate + + +class RawBatchCommandCursor(CommandCursor, Generic[_DocumentType]): + pass + + +class AsyncCommandCursor(AsyncCursorBase): + """AsyncIO :obj:`~CommandCursor` + + *DEPRECATED* methods are removed in this class. + """ + + dispatch: CommandCursor + + def _query_flags(self) -> int: + return 0 + + def _data(self) -> Deque[Any]: + return self.dispatch._CommandCursor__data # skipcq: PYL-W0212 + + def _killed(self) -> bool: + return self.dispatch._CommandCursor__killed # skipcq: PYL-W0212 + + +class _LatentCursor(Generic[_DocumentType]): + """Base class for LatentCursor AsyncIOMongoDB instance""" + + # ClassVar + alive: ClassVar[bool] = True + _CommandCursor__data: ClassVar[Deque[Any]] = deque() + _CommandCursor__id: ClassVar[Optional[Any]] = None + _CommandCursor__killed: ClassVar[bool] = False + _CommandCursor__sock_mgr: ClassVar[Optional[Any]] = None + _CommandCursor__session: ClassVar[Optional[AsyncClientSession]] = None + _CommandCursor__explicit_session: ClassVar[Optional[bool]] = None + address: ClassVar[Optional[Union[Tuple[str, int], _Address]]] = None + cursor_id: ClassVar[Optional[Any]] = None + session: Optional[ClientSession] = None + + _CommandCursor__collection: "AsyncCollection" + + def __init__(self, collection: "AsyncCollection") -> None: + self._CommandCursor__collection = collection + + def _CommandCursor__end_session(self, *args: Any, **kwargs: Any) -> None: + pass # Only for initialization + + def _CommandCursor__die(self, *args: Any, **kwargs: Any) -> None: + pass # Only for initialization + + def _refresh(self) -> int: # skipcq: PYL-R0201 + """Only for initialization""" + return 0 + + def batch_size(self, batch_size: int) -> None: + pass # Only for initialization + + def close(self) -> None: + pass # Only for initialization + + def clone(self) -> "_LatentCursor": + return _LatentCursor(self._CommandCursor__collection) + + def rewind(self): + pass # Only for initialization + + @property + def collection(self): + return self._CommandCursor__collection + + +class AsyncLatentCommandCursor(AsyncCommandCursor): + """Temporary Cursor for initializing in aggregate, + and will be overwrite by :obj:`~asyncio.Future`""" + + dispatch: Union[CommandCursor, RawBatchCommandCursor] + + def __init__( + self, + collection: "AsyncCollection", + start: Callable[..., Any], + *args: Any, + **kwargs: Any, + ) -> None: + self.start = start + self.args = args + self.kwargs = kwargs + + super().__init__(_LatentCursor(collection), collection) + + def batch_size(self, batch_size: int) -> "AsyncLatentCommandCursor": + self.kwargs["batchSize"] = batch_size + + return self + + def _get_more(self) -> Union[asyncio.Future[int], Coroutine[Any, Any, int]]: + if not self.started: + self.started = True + original_future = self.loop.create_future() + future = self.loop.create_task(run_sync(self.start, *self.args, **self.kwargs)) + future.add_done_callback( + partial(self.loop.call_soon_threadsafe, self._on_started, original_future) + ) + + self.start, self.args, self.kwargs = lambda _: None, (), {} + + return original_future + + return super()._get_more() + + def _on_started( + self, + original_future: asyncio.Future[int], + future: asyncio.Future[Union[CommandCursor, RawBatchCommandCursor]], + ) -> None: + try: + self.dispatch = future.result() + except Exception as exc: # skipcq: PYL-W0703 + if not original_future.done(): + original_future.set_exception(exc) + else: + # Return early if the task was cancelled. + if original_future.done(): + return + + if self.dispatch._CommandCursor__data or not self.dispatch.alive: # skipcq: PYL-W0212 + # _get_more is complete. + original_future.set_result( + len(self.dispatch._CommandCursor__data) # skipcq: PYL-W0212 + ) + else: + # Send a getMore. + fut = self.loop.create_task(super()._get_more()) + + def copy(f: asyncio.Future[int]) -> None: + if original_future.done(): + return + + exc = f.exception() + if exc is not None: + original_future.set_exception(exc) + else: + original_future.set_result(f.result()) + + fut.add_done_callback(copy) diff --git a/async_pymongo/cursor.py b/async_pymongo/cursor.py new file mode 100644 index 0000000..56f82d3 --- /dev/null +++ b/async_pymongo/cursor.py @@ -0,0 +1,212 @@ +"""async_pymongo database cursor""" +# Copyright (C) 2020 - 2023 UserbotIndo Team, +# Copyright (C) 2023 Mayuri-Chan, +# +# This program is free software: you can redistribute it and/or modify +# it under the terms of the GNU General Public License as published by +# the Free Software Foundation, either version 3 of the License, or +# (at your option) any later version. +# +# This program is distributed in the hope that it will be useful, +# but WITHOUT ANY WARRANTY; without even the implied warranty of +# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +# GNU General Public License for more details. +# +# You should have received a copy of the GNU General Public License +# along with this program. If not, see . + +from abc import abstractmethod +from typing import ( + TYPE_CHECKING, + Any, + Deque, + Generic, + List, + Mapping, + Optional, + Tuple, + Union, +) + +from bson.code import Code +from pymongo.cursor import Cursor as _Cursor +from pymongo.typings import _CollationIn, _DocumentType + +from async_pymongo.async_helper import run_sync + +from .cursor_base import AsyncCursorBase + +if TYPE_CHECKING: + from .collection import AsyncCollection + + +class Cursor(_Cursor, Generic[_DocumentType]): + + _Cursor__data: Deque[Any] + _Cursor__killed: bool + _Cursor__query_flags: int + + delegate: "AsyncCollection[_DocumentType]" + + def __init__( + self, collection: "AsyncCollection[_DocumentType]", *args: Any, **kwargs: Any + ) -> None: + self.delegate = collection + + super().__init__(collection.dispatch, *args, **kwargs) + + @abstractmethod + def add_option(self, mask: int) -> "Cursor[_DocumentType]": + raise NotImplementedError + + @abstractmethod + def allow_disk_use(self, allow_disk_use: bool) -> "Cursor[_DocumentType]": + raise NotImplementedError + + @abstractmethod + def collation(self, collation: Optional[_CollationIn]) -> "Cursor[_DocumentType]": + raise NotImplementedError + + @abstractmethod + def comment(self, comment: str) -> "Cursor[_DocumentType]": + raise NotImplementedError + + @property + def _AsyncCursor__data(self) -> Deque[Any]: + return self.__data + + async def _AsyncCursor__die(self, synchronous: bool = False) -> None: + await run_sync(self.__die, synchronous=synchronous) + + @property + def _AsyncCursor__exhaust(self) -> bool: + return self.__exhaust + + @property + def _AsyncCursor__killed(self) -> bool: + return self.__killed + + @property + def _AsyncCursor__max_await_time_ms(self) -> Optional[int]: + return self.__max_await_time_ms + + @property + def _AsyncCursor__max_time_ms(self) -> Optional[int]: + return self.__max_time_ms + + @property + def _AsyncCursor__query_flags(self) -> int: + return self.__query_flags + + @property + def _AsyncCursor__query_spec(self) -> Optional[Any]: + return self.__query_spec + + @property + def _AsyncCursor__retrieved(self) -> int: + return self.__retrieved + + @property + def _AsyncCursor__spec(self) -> Mapping[str, Any]: + return self.__spec + + @property + def collection(self) -> "AsyncCollection[_DocumentType]": + return self.delegate + + +class RawBatchCursor(Cursor): # skipcq: PYL-W0223 + pass + + +class AsyncCursor(AsyncCursorBase, Generic[_DocumentType]): + """AsyncIO :obj:`~Cursor` + + *DEPRECATED* methods are removed in this class. + """ + + dispatch: _Cursor + + def add_option(self, mask: int) -> "AsyncCursor[_DocumentType]": + self.dispatch = self.dispatch.add_option(mask) + return self + + def allow_disk_use(self, allow_disk_use: bool) -> "AsyncCursor[_DocumentType]": + self.dispatch = self.dispatch.allow_disk_use(allow_disk_use) + return self + + def collation(self, collation: _CollationIn) -> "AsyncCursor[_DocumentType]": + self.dispatch = self.dispatch.collation(collation) + return self + + def comment(self, comment: str) -> "AsyncCursor[_DocumentType]": + self.dispatch = self.dispatch.comment(comment) + return self + + async def distinct(self, key: str) -> List[Any]: + return await run_sync(self.dispatch.distinct, key) + + async def explain(self) -> _DocumentType: + return await run_sync(self.dispatch.explain) + + def hint(self, index: Union[str, List[Tuple[str, Any]]]) -> "AsyncCursor[_DocumentType]": + self.dispatch = self.dispatch.hint(index) + return self + + def limit(self, limit: int) -> "AsyncCursor[_DocumentType]": + self.dispatch = self.dispatch.limit(limit) + return self + + def max(self, spec: List[Any]) -> "AsyncCursor[_DocumentType]": + self.dispatch = self.dispatch.max(spec) + return self + + def max_await_time_ms(self, max_await_time_ms: int) -> "AsyncCursor[_DocumentType]": + self.dispatch = self.dispatch.max_await_time_ms(max_await_time_ms) + return self + + def max_time_ms(self, max_time_ms: int) -> "AsyncCursor[_DocumentType]": + self.dispatch = self.dispatch.max_time_ms(max_time_ms) + return self + + def min(self, spec: List[Any]) -> "AsyncCursor[_DocumentType]": + self.dispatch = self.dispatch.min(spec) + return self + + def remove_option(self, mask: int) -> "AsyncCursor[_DocumentType]": + self.dispatch = self.dispatch.remove_option(mask) + return self + + def rewind(self) -> "AsyncCursor[_DocumentType]": + self.dispatch = self.dispatch.rewind() + return self + + def skip(self, skip: int) -> "AsyncCursor[_DocumentType]": + self.dispatch = self.dispatch.skip(skip) + return self + + def sort( + self, key: Union[str, List[Tuple[str, Any]]], *, direction: Any = None + ) -> "AsyncCursor[_DocumentType]": + self.dispatch = self.dispatch.sort(key, direction=direction) + return self + + def where(self, code: Code) -> "AsyncCursor[_DocumentType]": + self.dispatch = self.dispatch.where(code) + return self + + def _query_flags(self) -> int: + # skipcq: PYL-W0212 + return self.dispatch._Cursor__query_flags # type: ignore + + def _data(self) -> Deque[Any]: + # skipcq: PYL-W0212 + return self.dispatch._Cursor__data # type: ignore + + def _killed(self) -> bool: + # skipcq: PYL-W0212 + return self.dispatch._Cursor__killed # type: ignore + + +class AsyncRawBatchCursor(AsyncCursor, Generic[_DocumentType]): + pass diff --git a/async_pymongo/cursor_base.py b/async_pymongo/cursor_base.py new file mode 100644 index 0000000..41633f5 --- /dev/null +++ b/async_pymongo/cursor_base.py @@ -0,0 +1,217 @@ +"""async_pymongo database cursor core""" +# Copyright (C) 2020 - 2023 UserbotIndo Team, +# Copyright (C) 2023 Mayuri-Chan, +# +# This program is free software: you can redistribute it and/or modify +# it under the terms of the GNU General Public License as published by +# the Free Software Foundation, either version 3 of the License, or +# (at your option) any later version. +# +# This program is distributed in the hope that it will be useful, +# but WITHOUT ANY WARRANTY; without even the implied warranty of +# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +# GNU General Public License for more details. +# +# You should have received a copy of the GNU General Public License +# along with this program. If not, see . + +import asyncio +import inspect +from functools import partial +from typing import ( + TYPE_CHECKING, + Any, + Coroutine, + Deque, + Generic, + List, + Mapping, + Optional, + Tuple, + Union, +) + +from pymongo.client_session import ClientSession +from pymongo.collection import Collection +from pymongo.cursor import _QUERY_OPTIONS, Cursor, RawBatchCursor +from pymongo.typings import _Address, _DocumentType + +from async_pymongo.async_helper import run_sync + +from .base import AsyncBase +from .errors import InvalidOperation + +if TYPE_CHECKING: + from .collection import AsyncCollection + from .command_cursor import CommandCursor, _LatentCursor + + +class AsyncCursorBase(AsyncBase, Generic[_DocumentType]): + """Base class for Cursor AsyncIOMongoDB instances + + *DEPRECATED* methods are removed in this class. + + :meth:`~each()` is removed because we can iterate directly this class, + And we now have :meth:`~to_list()` so yeah kinda useless + """ + + collection: Optional[Union["AsyncCollection[_DocumentType]", Collection[_DocumentType]]] + dispatch: Union[ + "_LatentCursor[_DocumentType]", + "CommandCursor[_DocumentType]", + Cursor[_DocumentType], + RawBatchCursor[_DocumentType], + ] + loop: asyncio.AbstractEventLoop + + def __init__( + self, + cursor: Union[ + "_LatentCursor[_DocumentType]", + "CommandCursor[_DocumentType]", + Cursor[_DocumentType], + RawBatchCursor[_DocumentType], + ], + collection: "Optional[AsyncCollection[_DocumentType]]" = None, + ) -> None: + super().__init__(cursor) + + if collection: + self.collection = collection + else: + self.collection = cursor.collection + self.started = False + self.closed = False + + self.loop = asyncio.get_event_loop() + + async def __aenter__(self) -> "AsyncCursorBase": + return self + + async def __aexit__(self, exc_type: Any, exc_val: Any, exc_tb: Any) -> None: + if self.dispatch: + await self.close() + + def __aiter__(self) -> "AsyncCursorBase": + return self + + async def __anext__(self) -> Mapping[str, Any]: + return await self.next() + + def _buffer_size(self) -> int: + return len(self._data()) + + def _query_flags(self) -> int: + raise NotImplementedError + + def _data(self) -> Deque[Any]: + raise NotImplementedError + + def _killed(self) -> bool: + raise NotImplementedError + + def _get_more(self) -> Coroutine[Any, Any, int]: + if not self.alive: + raise InvalidOperation( + "Can't call get_more() on a AsyncCursor that has been" " exhausted or killed." + ) + + self.started = True + return self._refresh() + + def _to_list( + self, + length: Optional[int], + the_list: List[Mapping[str, Any]], + future: asyncio.Future[List[Mapping[str, Any]]], + get_more_future: asyncio.Future[int], + ) -> None: + # get_more_future is the result of self._get_more(). + # future will be the result of the user's to_list() call. + try: + result = get_more_future.result() + # Return early if the task was cancelled. + if future.done(): + return + + if length is None: + n = result + else: + n = min(length - len(the_list), result) + + i = 0 + while i < n: + the_list.append(self._data().popleft()) + i += 1 + + reached_length = length is not None and len(the_list) >= length + if reached_length or not self.alive: + future.set_result(the_list) + else: + new_future = self.loop.create_task(self._get_more()) + new_future.add_done_callback( + partial(self.loop.call_soon_threadsafe, self._to_list, length, the_list, future) + ) + except Exception as exc: # skipcq: PYL-W0703 + if not future.done(): + future.set_exception(exc) + + async def _refresh(self) -> int: + return await run_sync(self.dispatch._refresh) # skipcq: PYL-W0212 + + def batch_size(self, batch_size: int) -> "AsyncCursorBase": + self.dispatch.batch_size(batch_size) + return self + + async def close(self) -> None: + if not self.closed: + self.closed = True + await run_sync(self.dispatch.close) + + async def next(self) -> Any: + if self.alive and (self._buffer_size() or await self._get_more()): + return await run_sync(next, self.dispatch) + raise StopAsyncIteration + + def to_list(self, length: Optional[int] = None) -> asyncio.Future[List[Mapping[str, Any]]]: + if length is not None and length < 0: + raise ValueError("length must be non-negative") + + if self._query_flags() & _QUERY_OPTIONS["tailable_cursor"]: + raise InvalidOperation("Can't call to_list on tailable cursor") + + future = self.loop.create_future() + the_list: List[Mapping[str, Any]] = [] + + if not self.alive: + future.set_result(the_list) + return future + + # Ignored the type since some commands are called from command_cursor + get_more_future: Union[asyncio.Future, asyncio.Task] = self._get_more() # type: ignore + if inspect.iscoroutine(get_more_future): + get_more_future = self.loop.create_task(get_more_future) + + get_more_future.add_done_callback( + partial(self.loop.call_soon_threadsafe, self._to_list, length, the_list, future) + ) + + return future + + @property + def address(self) -> Optional[Union[Tuple[str, int], _Address]]: + return self.dispatch.address + + @property + def alive(self) -> bool: + if not self.dispatch: + return True + return self.dispatch.alive + + @property + def cursor_id(self) -> Optional[int]: + return self.dispatch.cursor_id + + @property + def session(self) -> Optional[ClientSession]: + return self.dispatch.session diff --git a/async_pymongo/db.py b/async_pymongo/db.py new file mode 100644 index 0000000..6b96eac --- /dev/null +++ b/async_pymongo/db.py @@ -0,0 +1,286 @@ +"""async_pymongo base database""" +# Copyright (C) 2020 - 2023 UserbotIndo Team, +# Copyright (C) 2023 Mayuri-Chan, +# +# This program is free software: you can redistribute it and/or modify +# it under the terms of the GNU General Public License as published by +# the Free Software Foundation, either version 3 of the License, or +# (at your option) any later version. +# +# This program is distributed in the hope that it will be useful, +# but WITHOUT ANY WARRANTY; without even the implied warranty of +# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +# GNU General Public License for more details. +# +# You should have received a copy of the GNU General Public License +# along with this program. If not, see . + +from typing import TYPE_CHECKING, Any, List, Literal, Mapping, Optional, Union + +from bson.codec_options import CodecOptions +from bson.dbref import DBRef +from bson.son import SON +from bson.timestamp import Timestamp +from pymongo.collation import Collation +from pymongo.database import Database +from pymongo.read_concern import ReadConcern +from pymongo.write_concern import WriteConcern + +from async_pymongo.async_helper import run_sync + +from .base import AsyncBaseProperty +from .change_stream import AsyncChangeStream +from .client_session import AsyncClientSession +from .collection import AsyncCollection +from .command_cursor import AsyncCommandCursor, AsyncLatentCommandCursor, CommandCursor +from .typings import ReadPreferences + +if TYPE_CHECKING: + from .client import AsyncClient + + +class AsyncDatabase(AsyncBaseProperty): + """AsyncIO :obj:`~Database` + + *DEPRECATED* methods are removed in this class. + """ + + _client: "AsyncClient" + + dispatch: Database + + def __init__(self, client: "AsyncClient", database: Database) -> None: + self._client = client + + # Propagate initialization to base + super().__init__(database) + + def __bool__(self) -> bool: + return self.dispatch is not None + + def __getitem__(self, name) -> AsyncCollection: + return AsyncCollection(self, name) + + def __hash__(self) -> int: + return hash((self.client, self.name)) + + def aggregate( + self, + pipeline: List[Mapping[str, Any]], + *args: Any, + session: Optional[AsyncClientSession] = None, + **kwargs: Any, + ) -> AsyncLatentCommandCursor: + return AsyncLatentCommandCursor( + self["$cmd.aggregate"], + self.dispatch.aggregate, + pipeline, + session=session.dispatch if session else session, + *args, + **kwargs, + ) + + async def command( + self, + command: Union[str, Mapping[str, Any]], + *, + value: int = 1, + check: bool = True, + allowable_errors: Optional[str] = None, + read_preference: Optional[ReadPreferences] = None, + codec_options: Optional[CodecOptions] = None, + session: Optional[AsyncClientSession] = None, + **kwargs: Any, + ) -> Mapping[str, Any]: + return await run_sync( + self.dispatch.command, + command, + value=value, + check=check, + allowable_errors=allowable_errors, + read_preference=read_preference, + codec_options=codec_options, + session=session.dispatch if session else session, + **kwargs, + ) + + async def close(self) -> None: + await self._client.close() + + async def create_collection( + self, + name: str, + *, + codec_options: Optional[CodecOptions] = None, + read_preference: Optional[ReadPreferences] = None, + write_concern: Optional[WriteConcern] = None, + read_concern: Optional[ReadConcern] = None, + session: Optional[AsyncClientSession] = None, + check_exists: bool = True, + **kwargs: Any, + ) -> AsyncCollection: + return AsyncCollection( + self, + name, + collection=await run_sync( + self.dispatch.create_collection, + name, + codec_options=codec_options, + read_preference=read_preference, + write_concern=write_concern, + read_concern=read_concern, + session=session.dispatch if session else session, + check_exists=check_exists, + **kwargs, + ), + session=session, + ) + + async def dereference( + self, dbref: DBRef, *, session: Optional[AsyncClientSession] = None, **kwargs: Any + ) -> Optional[Mapping[str, Any]]: + return await run_sync( + self.dispatch.dereference, + dbref, + session=session.dispatch if session else session, + **kwargs, + ) + + async def drop_collection( + self, + name_or_collection: Union[str, AsyncCollection], + session: Optional[AsyncClientSession] = None, + ) -> Mapping[str, Any]: + if isinstance(name_or_collection, AsyncCollection): + name_or_collection = name_or_collection.name + + return await run_sync( + self.dispatch.drop_collection, + name_or_collection, + session=session.dispatch if session else session, + ) + + def get_collection( + self, + name: str, + *, + codec_options: Optional[CodecOptions] = None, + read_preference: Optional[ReadPreferences] = None, + write_concern: Optional[WriteConcern] = None, + read_concern: Optional[ReadConcern] = None, + ) -> AsyncCollection: + return AsyncCollection( + self, + name, + codec_options=codec_options, + read_preference=read_preference, + write_concern=write_concern, + read_concern=read_concern, + ) + + async def list_collection_names( + self, + *, + session: Optional[AsyncClientSession] = None, + query: Optional[Mapping[str, Any]] = None, + **kwargs: Any, + ) -> List[str]: + return await run_sync( + self.dispatch.list_collection_names, + session=session.dispatch if session else session, + filter=query, + **kwargs, + ) + + async def list_collections( + self, + *, + session: Optional[AsyncClientSession] = None, + query: Optional[Mapping[str, Any]] = None, + **kwargs: Any, + ) -> AsyncCommandCursor: + cmd = SON([("listCollections", 1)]) + cmd.update(query, **kwargs) + + res: Mapping[str, Any] = await run_sync( + self.dispatch._retryable_read_command, # skipcq: PYL-W0212 + cmd, + session=session.dispatch if session else session, + ) + return AsyncCommandCursor(CommandCursor(self["$cmd"], res["cursor"], None)) + + async def validate_collection( + self, + name_or_collection: Union[str, AsyncCollection], + *, + scandata: bool = False, + full: bool = False, + session: Optional[AsyncClientSession] = None, + background: Optional[bool] = None, + ) -> Mapping[str, Any]: + if isinstance(name_or_collection, AsyncCollection): + name_or_collection = name_or_collection.name + + return await run_sync( + self.dispatch.validate_collection, + name_or_collection, + scandata=scandata, + full=full, + session=session.dispatch if session else session, + background=background, + ) + + def watch( + self, + pipeline: Optional[List[Mapping[str, Any]]] = None, + *, + full_document: Optional[Literal["updateLookup"]] = None, + resume_after: Optional[Mapping[str, str]] = None, + max_await_time_ms: Optional[int] = None, + batch_size: Optional[int] = None, + collation: Optional[Collation] = None, + start_at_operation_time: Optional[Timestamp] = None, + session: Optional[AsyncClientSession] = None, + start_after: Optional[Mapping[str, str]] = None, + comment: Optional[str] = None, + full_document_before_change: Optional[Literal["required", "whenAvailable"]] = None, + ) -> AsyncChangeStream: + return AsyncChangeStream( + self, + pipeline, + full_document, + resume_after, + max_await_time_ms, + batch_size, + collation, + start_at_operation_time, + session, + start_after, + comment, + full_document_before_change, + ) + + def with_options( + self, + *, + codec_options: Optional[CodecOptions] = None, + read_preference: Optional[ReadPreferences] = None, + write_concern: Optional[WriteConcern] = None, + read_concern: Optional[ReadConcern] = None, + ) -> "AsyncDatabase": + self.dispatch = self.dispatch.with_options( + codec_options=codec_options, + read_preference=read_preference, + write_concern=write_concern, + read_concern=read_concern, + ) + + return self + + @property + def client(self) -> "AsyncClient": + return self._client + + @property + def name(self) -> str: + return self.dispatch.name diff --git a/async_pymongo/errors.py b/async_pymongo/errors.py new file mode 100644 index 0000000..3ff6d76 --- /dev/null +++ b/async_pymongo/errors.py @@ -0,0 +1,22 @@ +"""async_pymongo database errors""" +# Copyright (C) 2020 - 2023 UserbotIndo Team, +# Copyright (C) 2023 Mayuri-Chan, +# +# This program is free software: you can redistribute it and/or modify +# it under the terms of the GNU General Public License as published by +# the Free Software Foundation, either version 3 of the License, or +# (at your option) any later version. +# +# This program is distributed in the hope that it will be useful, +# but WITHOUT ANY WARRANTY; without even the implied warranty of +# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +# GNU General Public License for more details. +# +# You should have received a copy of the GNU General Public License +# along with this program. If not, see . + +from pymongo.errors import ( # skipcq: PY-W2000 + InvalidOperation, + OperationFailure, + PyMongoError, +) diff --git a/async_pymongo/typings.py b/async_pymongo/typings.py new file mode 100644 index 0000000..7f2c5d1 --- /dev/null +++ b/async_pymongo/typings.py @@ -0,0 +1,38 @@ +"""async_pymongo database types""" +# Copyright (C) 2020 - 2023 UserbotIndo Team, +# Copyright (C) 2023 Mayuri-Chan, +# +# This program is free software: you can redistribute it and/or modify +# it under the terms of the GNU General Public License as published by +# the Free Software Foundation, either version 3 of the License, or +# (at your option) any later version. +# +# This program is distributed in the hope that it will be useful, +# but WITHOUT ANY WARRANTY; without even the implied warranty of +# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +# GNU General Public License for more details. +# +# You should have received a copy of the GNU General Public License +# along with this program. If not, see . + +from typing import TypeVar, Union + +from pymongo.operations import ( + DeleteMany, + DeleteOne, + InsertOne, + ReplaceOne, + UpdateMany, + UpdateOne, +) +from pymongo.read_preferences import ( + Nearest, + Primary, + PrimaryPreferred, + Secondary, + SecondaryPreferred, +) + +ReadPreferences = Union[Primary, PrimaryPreferred, Secondary, SecondaryPreferred, Nearest] +Request = TypeVar("Request", DeleteMany, DeleteOne, InsertOne, ReplaceOne, UpdateMany, UpdateOne) +Results = TypeVar("Results") diff --git a/poetry.lock b/poetry.lock new file mode 100644 index 0000000..54bad5b --- /dev/null +++ b/poetry.lock @@ -0,0 +1,122 @@ +# This file is automatically @generated by Poetry 1.4.2 and should not be changed by hand. + +[[package]] +name = "dnspython" +version = "2.3.0" +description = "DNS toolkit" +category = "main" +optional = false +python-versions = ">=3.7,<4.0" +files = [ + {file = "dnspython-2.3.0-py3-none-any.whl", hash = "sha256:89141536394f909066cabd112e3e1a37e4e654db00a25308b0f130bc3152eb46"}, + {file = "dnspython-2.3.0.tar.gz", hash = "sha256:224e32b03eb46be70e12ef6d64e0be123a64e621ab4c0822ff6d450d52a540b9"}, +] + +[package.extras] +curio = ["curio (>=1.2,<2.0)", "sniffio (>=1.1,<2.0)"] +dnssec = ["cryptography (>=2.6,<40.0)"] +doh = ["h2 (>=4.1.0)", "httpx (>=0.21.1)", "requests (>=2.23.0,<3.0.0)", "requests-toolbelt (>=0.9.1,<0.11.0)"] +doq = ["aioquic (>=0.9.20)"] +idna = ["idna (>=2.1,<4.0)"] +trio = ["trio (>=0.14,<0.23)"] +wmi = ["wmi (>=1.5.1,<2.0.0)"] + +[[package]] +name = "pymongo" +version = "4.3.3" +description = "Python driver for MongoDB " +category = "main" +optional = false +python-versions = ">=3.7" +files = [ + {file = "pymongo-4.3.3-cp310-cp310-macosx_10_9_universal2.whl", hash = "sha256:74731c9e423c93cbe791f60c27030b6af6a948cef67deca079da6cd1bb583a8e"}, + {file = "pymongo-4.3.3-cp310-cp310-manylinux1_i686.whl", hash = "sha256:66413c50d510e5bcb0afc79880d1693a2185bcea003600ed898ada31338c004e"}, + {file = "pymongo-4.3.3-cp310-cp310-manylinux2014_aarch64.whl", hash = "sha256:9b87b23570565a6ddaa9244d87811c2ee9cffb02a753c8a2da9c077283d85845"}, + {file = "pymongo-4.3.3-cp310-cp310-manylinux2014_i686.whl", hash = "sha256:695939036a320f4329ccf1627edefbbb67cc7892b8222d297b0dd2313742bfee"}, + {file = "pymongo-4.3.3-cp310-cp310-manylinux2014_ppc64le.whl", hash = "sha256:ffcc8394123ea8d43fff8e5d000095fe7741ce3f8988366c5c919c4f5eb179d3"}, + {file = "pymongo-4.3.3-cp310-cp310-manylinux2014_s390x.whl", hash = "sha256:943f208840777f34312c103a2d1caab02d780c4e9be26b3714acf6c4715ba7e1"}, + {file = "pymongo-4.3.3-cp310-cp310-manylinux2014_x86_64.whl", hash = "sha256:01f7cbe88d22440b6594c955e37312d932fd632ffed1a86d0c361503ca82cc9d"}, + {file = "pymongo-4.3.3-cp310-cp310-manylinux_2_17_aarch64.manylinux2014_aarch64.whl", hash = "sha256:cdb87309de97c63cb9a69132e1cb16be470e58cffdfbad68fdd1dc292b22a840"}, + {file = "pymongo-4.3.3-cp310-cp310-manylinux_2_17_ppc64le.manylinux2014_ppc64le.whl", hash = "sha256:d86c35d94b5499689354ccbc48438a79f449481ee6300f3e905748edceed78e7"}, + {file = "pymongo-4.3.3-cp310-cp310-manylinux_2_17_s390x.manylinux2014_s390x.whl", hash = "sha256:a966d5304b7d90c45c404914e06bbf02c5bf7e99685c6c12f0047ef2aa837142"}, + {file = "pymongo-4.3.3-cp310-cp310-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:be1d2ce7e269215c3ee9a215e296b7a744aff4f39233486d2c4d77f5f0c561a6"}, + {file = "pymongo-4.3.3-cp310-cp310-manylinux_2_5_i686.manylinux1_i686.manylinux_2_17_i686.manylinux2014_i686.whl", hash = "sha256:55b6163dac53ef1e5d834297810c178050bd0548a4136cd4e0f56402185916ca"}, + {file = "pymongo-4.3.3-cp310-cp310-win32.whl", hash = "sha256:dc0cff74cd36d7e1edba91baa09622c35a8a57025f2f2b7a41e3f83b1db73186"}, + {file = "pymongo-4.3.3-cp310-cp310-win_amd64.whl", hash = "sha256:cafa52873ae12baa512a8721afc20de67a36886baae6a5f394ddef0ce9391f91"}, + {file = "pymongo-4.3.3-cp311-cp311-macosx_10_9_universal2.whl", hash = "sha256:599d3f6fbef31933b96e2d906b0f169b3371ff79ea6aaf6ecd76c947a3508a3d"}, + {file = "pymongo-4.3.3-cp311-cp311-manylinux_2_17_aarch64.manylinux2014_aarch64.whl", hash = "sha256:c0640b4e9d008e13956b004d1971a23377b3d45491f87082161c92efb1e6c0d6"}, + {file = "pymongo-4.3.3-cp311-cp311-manylinux_2_17_ppc64le.manylinux2014_ppc64le.whl", hash = "sha256:341221e2f2866a5960e6f8610f4cbac0bb13097f3b1a289aa55aba984fc0d969"}, + {file = "pymongo-4.3.3-cp311-cp311-manylinux_2_17_s390x.manylinux2014_s390x.whl", hash = "sha256:e7fac06a539daef4fcf5d8288d0d21b412f9b750454cd5a3cf90484665db442a"}, + {file = "pymongo-4.3.3-cp311-cp311-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:d3a51901066696c4af38c6c63a1f0aeffd5e282367ff475de8c191ec9609b56d"}, + {file = "pymongo-4.3.3-cp311-cp311-manylinux_2_5_i686.manylinux1_i686.manylinux_2_17_i686.manylinux2014_i686.whl", hash = "sha256:f3055510fdfdb1775bc8baa359783022f70bb553f2d46e153c094dfcb08578ff"}, + {file = "pymongo-4.3.3-cp311-cp311-win32.whl", hash = "sha256:524d78673518dcd352a91541ecd2839c65af92dc883321c2109ef6e5cd22ef23"}, + {file = "pymongo-4.3.3-cp311-cp311-win_amd64.whl", hash = "sha256:b8a03af1ce79b902a43f5f694c4ca8d92c2a4195db0966f08f266549e2fc49bc"}, + {file = "pymongo-4.3.3-cp37-cp37m-macosx_10_6_intel.whl", hash = "sha256:39b03045c71f761aee96a12ebfbc2f4be89e724ff6f5e31c2574c1a0e2add8bd"}, + {file = "pymongo-4.3.3-cp37-cp37m-manylinux1_i686.whl", hash = "sha256:6fcfbf435eebf8a1765c6d1f46821740ebe9f54f815a05c8fc30d789ef43cb12"}, + {file = "pymongo-4.3.3-cp37-cp37m-manylinux1_x86_64.whl", hash = "sha256:7d43ac9c7eeda5100fb0a7152fab7099c9cf9e5abd3bb36928eb98c7d7a339c6"}, + {file = "pymongo-4.3.3-cp37-cp37m-manylinux2014_aarch64.whl", hash = "sha256:3b93043b14ba7eb08c57afca19751658ece1cfa2f0b7b1fb5c7a41452fbb8482"}, + {file = "pymongo-4.3.3-cp37-cp37m-manylinux2014_i686.whl", hash = "sha256:c09956606c08c4a7c6178a04ba2dd9388fcc5db32002ade9c9bc865ab156ab6d"}, + {file = "pymongo-4.3.3-cp37-cp37m-manylinux2014_ppc64le.whl", hash = "sha256:b0cfe925610f2fd59555bb7fc37bd739e4b197d33f2a8b2fae7b9c0c6640318c"}, + {file = "pymongo-4.3.3-cp37-cp37m-manylinux2014_s390x.whl", hash = "sha256:4d00b91c77ceb064c9b0459f0d6ea5bfdbc53ea9e17cf75731e151ef25a830c7"}, + {file = "pymongo-4.3.3-cp37-cp37m-manylinux2014_x86_64.whl", hash = "sha256:c6258a3663780ae47ba73d43eb63c79c40ffddfb764e09b56df33be2f9479837"}, + {file = "pymongo-4.3.3-cp37-cp37m-manylinux_2_17_aarch64.manylinux2014_aarch64.whl", hash = "sha256:c29e758f0e734e1e90357ae01ec9c6daf19ff60a051192fe110d8fb25c62600e"}, + {file = "pymongo-4.3.3-cp37-cp37m-manylinux_2_17_ppc64le.manylinux2014_ppc64le.whl", hash = "sha256:12f3621a46cdc7a9ba8080422262398a91762a581d27e0647746588d3f995c88"}, + {file = "pymongo-4.3.3-cp37-cp37m-manylinux_2_17_s390x.manylinux2014_s390x.whl", hash = "sha256:47f7aa217b25833cd6f0e72b0d224be55393c2692b4f5e0561cb3beeb10296e9"}, + {file = "pymongo-4.3.3-cp37-cp37m-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:2c2fdc855149efe7cdcc2a01ca02bfa24761c640203ea94df467f3baf19078be"}, + {file = "pymongo-4.3.3-cp37-cp37m-manylinux_2_5_i686.manylinux1_i686.manylinux_2_17_i686.manylinux2014_i686.whl", hash = "sha256:5effd87c7d363890259eac16c56a4e8da307286012c076223997f8cc4a8c435b"}, + {file = "pymongo-4.3.3-cp37-cp37m-manylinux_2_5_i686.manylinux1_i686.whl", hash = "sha256:6dd1cf2995fdbd64fc0802313e8323f5fa18994d51af059b5b8862b73b5e53f0"}, + {file = "pymongo-4.3.3-cp37-cp37m-manylinux_2_5_x86_64.manylinux1_x86_64.whl", hash = "sha256:bb869707d8e30645ed6766e44098600ca6cdf7989c22a3ea2b7966bb1d98d4b2"}, + {file = "pymongo-4.3.3-cp37-cp37m-win32.whl", hash = "sha256:49210feb0be8051a64d71691f0acbfbedc33e149f0a5d6e271fddf6a12493fed"}, + {file = "pymongo-4.3.3-cp37-cp37m-win_amd64.whl", hash = "sha256:54c377893f2cbbffe39abcff5ff2e917b082c364521fa079305f6f064e1a24a9"}, + {file = "pymongo-4.3.3-cp38-cp38-macosx_10_9_x86_64.whl", hash = "sha256:c184ec5be465c0319440734491e1aa4709b5f3ba75fdfc9dbbc2ae715a7f6829"}, + {file = "pymongo-4.3.3-cp38-cp38-manylinux1_i686.whl", hash = "sha256:dca34367a4e77fcab0693e603a959878eaf2351585e7d752cac544bc6b2dee46"}, + {file = "pymongo-4.3.3-cp38-cp38-manylinux1_x86_64.whl", hash = "sha256:cd6a4afb20fb3c26a7bfd4611a0bbb24d93cbd746f5eb881f114b5e38fd55501"}, + {file = "pymongo-4.3.3-cp38-cp38-manylinux2014_aarch64.whl", hash = "sha256:0c466710871d0026c190fc4141e810cf9d9affbf4935e1d273fbdc7d7cda6143"}, + {file = "pymongo-4.3.3-cp38-cp38-manylinux2014_i686.whl", hash = "sha256:d07d06dba5b5f7d80f9cc45501456e440f759fe79f9895922ed486237ac378a8"}, + {file = "pymongo-4.3.3-cp38-cp38-manylinux2014_ppc64le.whl", hash = "sha256:711bc52cb98e7892c03e9b669bebd89c0a890a90dbc6d5bb2c47f30239bac6e9"}, + {file = "pymongo-4.3.3-cp38-cp38-manylinux2014_s390x.whl", hash = "sha256:34b040e095e1671df0c095ec0b04fc4ebb19c4c160f87c2b55c079b16b1a6b00"}, + {file = "pymongo-4.3.3-cp38-cp38-manylinux2014_x86_64.whl", hash = "sha256:4ed00f96e147f40b565fe7530d1da0b0f3ab803d5dd5b683834500fa5d195ec4"}, + {file = "pymongo-4.3.3-cp38-cp38-manylinux_2_17_aarch64.manylinux2014_aarch64.whl", hash = "sha256:ef888f48eb9203ee1e04b9fb27429017b290fb916f1e7826c2f7808c88798394"}, + {file = "pymongo-4.3.3-cp38-cp38-manylinux_2_17_ppc64le.manylinux2014_ppc64le.whl", hash = "sha256:316498b642c00401370b2156b5233b256f9b33799e0a8d9d0b8a7da217a20fca"}, + {file = "pymongo-4.3.3-cp38-cp38-manylinux_2_17_s390x.manylinux2014_s390x.whl", hash = "sha256:fa7e202feb683dad74f00dea066690448d0cfa310f8a277db06ec8eb466601b5"}, + {file = "pymongo-4.3.3-cp38-cp38-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:52896e22115c97f1c829db32aa2760b0d61839cfe08b168c2b1d82f31dbc5f55"}, + {file = "pymongo-4.3.3-cp38-cp38-manylinux_2_5_i686.manylinux1_i686.manylinux_2_17_i686.manylinux2014_i686.whl", hash = "sha256:7c051fe37c96b9878f37fa58906cb53ecd13dcb7341d3a85f1e2e2f6b10782d9"}, + {file = "pymongo-4.3.3-cp38-cp38-manylinux_2_5_i686.manylinux1_i686.whl", hash = "sha256:5134d33286c045393c7beb51be29754647cec5ebc051cf82799c5ce9820a2ca2"}, + {file = "pymongo-4.3.3-cp38-cp38-manylinux_2_5_x86_64.manylinux1_x86_64.whl", hash = "sha256:a9c2885b4a8e6e39db5662d8b02ca6dcec796a45e48c2de12552841f061692ba"}, + {file = "pymongo-4.3.3-cp38-cp38-win32.whl", hash = "sha256:a6cd6f1db75eb07332bd3710f58f5fce4967eadbf751bad653842750a61bda62"}, + {file = "pymongo-4.3.3-cp38-cp38-win_amd64.whl", hash = "sha256:d5571b6978750601f783cea07fb6b666837010ca57e5cefa389c1d456f6222e2"}, + {file = "pymongo-4.3.3-cp39-cp39-macosx_10_9_universal2.whl", hash = "sha256:81d1a7303bd02ca1c5be4aacd4db73593f573ba8e0c543c04c6da6275fd7a47e"}, + {file = "pymongo-4.3.3-cp39-cp39-manylinux1_i686.whl", hash = "sha256:016c412118e1c23fef3a1eada4f83ae6e8844fd91986b2e066fc1b0013cdd9ae"}, + {file = "pymongo-4.3.3-cp39-cp39-manylinux1_x86_64.whl", hash = "sha256:8fd6e191b92a10310f5a6cfe10d6f839d79d192fb02480bda325286bd1c7b385"}, + {file = "pymongo-4.3.3-cp39-cp39-manylinux2014_aarch64.whl", hash = "sha256:e2961b05f9c04a53da8bfc72f1910b6aec7205fcf3ac9c036d24619979bbee4b"}, + {file = "pymongo-4.3.3-cp39-cp39-manylinux2014_i686.whl", hash = "sha256:b38a96b3eed8edc515b38257f03216f382c4389d022a8834667e2bc63c0c0c31"}, + {file = "pymongo-4.3.3-cp39-cp39-manylinux2014_ppc64le.whl", hash = "sha256:c1a70c51da9fa95bd75c167edb2eb3f3c4d27bc4ddd29e588f21649d014ec0b7"}, + {file = "pymongo-4.3.3-cp39-cp39-manylinux2014_s390x.whl", hash = "sha256:8a06a0c02f5606330e8f2e2f3b7949877ca7e4024fa2bff5a4506bec66c49ec7"}, + {file = "pymongo-4.3.3-cp39-cp39-manylinux2014_x86_64.whl", hash = "sha256:6c2216d8b6a6d019c6f4b1ad55f890e5e77eb089309ffc05b6911c09349e7474"}, + {file = "pymongo-4.3.3-cp39-cp39-manylinux_2_17_aarch64.manylinux2014_aarch64.whl", hash = "sha256:eac0a143ef4f28f49670bf89cb15847eb80b375d55eba401ca2f777cd425f338"}, + {file = "pymongo-4.3.3-cp39-cp39-manylinux_2_17_ppc64le.manylinux2014_ppc64le.whl", hash = "sha256:08fc250b5552ee97ceeae0f52d8b04f360291285fc7437f13daa516ce38fdbc6"}, + {file = "pymongo-4.3.3-cp39-cp39-manylinux_2_17_s390x.manylinux2014_s390x.whl", hash = "sha256:704d939656e21b073bfcddd7228b29e0e8a93dd27b54240eaafc0b9a631629a6"}, + {file = "pymongo-4.3.3-cp39-cp39-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:1074f1a6f23e28b983c96142f2d45be03ec55d93035b471c26889a7ad2365db3"}, + {file = "pymongo-4.3.3-cp39-cp39-manylinux_2_5_i686.manylinux1_i686.manylinux_2_17_i686.manylinux2014_i686.whl", hash = "sha256:7b16250238de8dafca225647608dddc7bbb5dce3dd53b4d8e63c1cc287394c2f"}, + {file = "pymongo-4.3.3-cp39-cp39-manylinux_2_5_i686.manylinux1_i686.whl", hash = "sha256:7761cacb8745093062695b11574effea69db636c2fd0a9269a1f0183712927b4"}, + {file = "pymongo-4.3.3-cp39-cp39-manylinux_2_5_x86_64.manylinux1_x86_64.whl", hash = "sha256:fd7bb378d82b88387dc10227cfd964f6273eb083e05299e9b97cbe075da12d11"}, + {file = "pymongo-4.3.3-cp39-cp39-win32.whl", hash = "sha256:dc24d245026a72d9b4953729d31813edd4bd4e5c13622d96e27c284942d33f24"}, + {file = "pymongo-4.3.3-cp39-cp39-win_amd64.whl", hash = "sha256:fc28e8d85d392a06434e9a934908d97e2cf453d69488d2bcd0bfb881497fd975"}, + {file = "pymongo-4.3.3.tar.gz", hash = "sha256:34e95ffb0a68bffbc3b437f2d1f25fc916fef3df5cdeed0992da5f42fae9b807"}, +] + +[package.dependencies] +dnspython = ">=1.16.0,<3.0.0" + +[package.extras] +aws = ["pymongo-auth-aws (<2.0.0)"] +encryption = ["pymongo-auth-aws (<2.0.0)", "pymongocrypt (>=1.3.0,<2.0.0)"] +gssapi = ["pykerberos"] +ocsp = ["certifi", "pyopenssl (>=17.2.0)", "requests (<3.0.0)", "service-identity (>=18.1.0)"] +snappy = ["python-snappy"] +zstd = ["zstandard"] + +[metadata] +lock-version = "2.0" +python-versions = "^3.11" +content-hash = "cc653226d480550c20941b031245272d684f5693b0d718cc7bc26c5250dd0da3" diff --git a/pyproject.toml b/pyproject.toml new file mode 100644 index 0000000..d96890e --- /dev/null +++ b/pyproject.toml @@ -0,0 +1,38 @@ +[tool.poetry] +name = "async-pymongo" +version = "0.1.0" +description = "Asynchronous wrapper for pymongo" +license = "GPL-3.0-or-later" +authors = [ + "Adek Maulana ", + "Gaung Ramadhan ", + "wulan17 " +] +readme = "README.md" +repository = "https://github.com/Mayuri-Chan/async_pymongo" +keywords = ["async", "python", "pymongo"] +classifiers = [ + "Environment :: Console", + "Framework :: AsyncIO", + "License :: OSI Approved :: GNU General Public License v3 or later (GPLv3+)", + "Programming Language :: Python", + "Programming Language :: Python :: 3", + "Programming Language :: Python :: 3.7", + "Programming Language :: Python :: 3.8", + "Programming Language :: Python :: 3.9", + "Programming Language :: Python :: 3.10", + "Programming Language :: Python :: 3.11", + "Programming Language :: Python :: 3 :: Only", + "Topic :: Database", +] + +packages = [{include = "async_pymongo"}] + +[tool.poetry.dependencies] +python = "^3.11" +pymongo = "^4.3.3" + + +[build-system] +requires = ["poetry-core"] +build-backend = "poetry.core.masonry.api" diff --git a/tests/__init__.py b/tests/__init__.py new file mode 100644 index 0000000..e69de29