pax_global_header00006660000000000000000000000064126121260540014511gustar00rootroot0000000000000052 comment=dc3d9e51b36eb7edddd8e4db4b1d3a64dbd83d58 qdjango-0.6.2/000077500000000000000000000000001261212605400131415ustar00rootroot00000000000000qdjango-0.6.2/.travis.yml000066400000000000000000000005501261212605400152520ustar00rootroot00000000000000language: cpp cache: apt env: - QT_SELECT=qt4 CONFIG=shared - QT_SELECT=qt4 CONFIG=static - QT_SELECT=qt5 CONFIG=shared - QT_SELECT=qt5 CONFIG=static install: - tests/travis/install-build-depends before_script: - mysql -e 'create database qdjango_test' - psql -c 'create database qdjango_test' -U postgres script: - tests/travis/build-and-test qdjango-0.6.2/AUTHORS000066400000000000000000000002361261212605400142120ustar00rootroot00000000000000Jeremy Lainé * Principal developer of QDjango. Mathias Hasselmann * Support for QDjangoQuerySet iterators. qdjango-0.6.2/ChangeLog000066400000000000000000000033511261212605400147150ustar00rootroot00000000000000QDjango 0.6.2 (2015-10-22) * Make sure HTTP dates are handled using C locale. QDjango 0.6.1 (2015-08-13) * Bump QDJANGO_VERSION, which had stayed at 0.5.0. QDjango 0.6.0 (2015-08-12) * Remove support for QtScript. * Make tests runnable using "make check". * Fix build errors on Windows. * Clarify return values of createTable(s) and dropTable(s). * Fix documentation for setForeignKey concerning object ownership. QDjango 0.5.0 (2014-09-13) * Add support for case-insensitive lookups. * Simplify SQL for multiple OR/AND clauses. * Add support for reverse lookups for many-to-one relations. * Add support QtSql's ODBC driver. * Add support for Microsoft SQL Server. * Improve test coverage. QDjango 0.4.0 (2013-06-27) * Enable foreign key constraints on SQLite (issue #9). * Fix table creation with foreign key constraints on PostgreSQL (issue #10). * Expose QDjangoMetaField's properties (issue #13). * Fix http module build with Qt5. QDjango 0.3.0 (2013-01-11) * Fix and test "unique" field option. * Add a "unique_together" model option. * Don't crash if QDjango::database() is called before QDjango::setDatabase(). * Make index names coincide with those used by django. * Register models without instantiating them. * Improve foreign keys: - Do not take object ownership in QDjangoMetaModel::setForeignKey(). - Fix QDjangoQuerySet::selectRelated() with NULL foreign keys. QDjango 0.2.6 (2012-09-07) * Store 0 integer foreign keys as NULL if field has null option. * Make it possible to build with Qt5: - Stop using deprecated QHttpRequestHeader and QHttpResponseHeader classes. - Use QMetaMethod::name() instead of QMetaMethod::signature() when using Qt5. QDjango 0.2.5 (2012-05-16) * Build a shared library by default. qdjango-0.6.2/LICENSE.LGPL000066400000000000000000000635041261212605400147130ustar00rootroot00000000000000 GNU LESSER GENERAL PUBLIC LICENSE Version 2.1, February 1999 Copyright (C) 1991, 1999 Free Software Foundation, Inc. 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA Everyone is permitted to copy and distribute verbatim copies of this license document, but changing it is not allowed. [This is the first released version of the Lesser GPL. It also counts as the successor of the GNU Library Public License, version 2, hence the version number 2.1.] Preamble The licenses for most software are designed to take away your freedom to share and change it. By contrast, the GNU General Public Licenses are intended to guarantee your freedom to share and change free software--to make sure the software is free for all its users. This license, the Lesser General Public License, applies to some specially designated software packages--typically libraries--of the Free Software Foundation and other authors who decide to use it. You can use it too, but we suggest you first think carefully about whether this license or the ordinary General Public License is the better strategy to use in any particular case, based on the explanations below. When we speak of free software, we are referring to freedom of use, 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 this service if you wish); that you receive source code or can get it if you want it; that you can change the software and use pieces of it in new free programs; and that you are informed that you can do these things. To protect your rights, we need to make restrictions that forbid distributors to deny you these rights or to ask you to surrender these rights. These restrictions translate to certain responsibilities for you if you distribute copies of the library or if you modify it. For example, if you distribute copies of the library, whether gratis or for a fee, you must give the recipients all the rights that we gave you. You must make sure that they, too, receive or can get the source code. If you link other code with the library, you must provide complete object files to the recipients, so that they can relink them with the library after making changes to the library and recompiling it. And you must show them these terms so they know their rights. We protect your rights with a two-step method: (1) we copyright the library, and (2) we offer you this license, which gives you legal permission to copy, distribute and/or modify the library. To protect each distributor, we want to make it very clear that there is no warranty for the free library. Also, if the library is modified by someone else and passed on, the recipients should know that what they have is not the original version, so that the original author's reputation will not be affected by problems that might be introduced by others. Finally, software patents pose a constant threat to the existence of any free program. We wish to make sure that a company cannot effectively restrict the users of a free program by obtaining a restrictive license from a patent holder. Therefore, we insist that any patent license obtained for a version of the library must be consistent with the full freedom of use specified in this license. Most GNU software, including some libraries, is covered by the ordinary GNU General Public License. This license, the GNU Lesser General Public License, applies to certain designated libraries, and is quite different from the ordinary General Public License. We use this license for certain libraries in order to permit linking those libraries into non-free programs. When a program is linked with a library, whether statically or using a shared library, the combination of the two is legally speaking a combined work, a derivative of the original library. The ordinary General Public License therefore permits such linking only if the entire combination fits its criteria of freedom. The Lesser General Public License permits more lax criteria for linking other code with the library. We call this license the "Lesser" General Public License because it does Less to protect the user's freedom than the ordinary General Public License. It also provides other free software developers Less of an advantage over competing non-free programs. These disadvantages are the reason we use the ordinary General Public License for many libraries. However, the Lesser license provides advantages in certain special circumstances. For example, on rare occasions, there may be a special need to encourage the widest possible use of a certain library, so that it becomes a de-facto standard. To achieve this, non-free programs must be allowed to use the library. A more frequent case is that a free library does the same job as widely used non-free libraries. In this case, there is little to gain by limiting the free library to free software only, so we use the Lesser General Public License. In other cases, permission to use a particular library in non-free programs enables a greater number of people to use a large body of free software. For example, permission to use the GNU C Library in non-free programs enables many more people to use the whole GNU operating system, as well as its variant, the GNU/Linux operating system. Although the Lesser General Public License is Less protective of the users' freedom, it does ensure that the user of a program that is linked with the Library has the freedom and the wherewithal to run that program using a modified version of the Library. The precise terms and conditions for copying, distribution and modification follow. Pay close attention to the difference between a "work based on the library" and a "work that uses the library". The former contains code derived from the library, whereas the latter must be combined with the library in order to run. GNU LESSER GENERAL PUBLIC LICENSE TERMS AND CONDITIONS FOR COPYING, DISTRIBUTION AND MODIFICATION 0. This License Agreement applies to any software library or other program which contains a notice placed by the copyright holder or other authorized party saying it may be distributed under the terms of this Lesser General Public License (also called "this License"). Each licensee is addressed as "you". A "library" means a collection of software functions and/or data prepared so as to be conveniently linked with application programs (which use some of those functions and data) to form executables. The "Library", below, refers to any such software library or work which has been distributed under these terms. A "work based on the Library" means either the Library or any derivative work under copyright law: that is to say, a work containing the Library or a portion of it, either verbatim or with modifications and/or translated straightforwardly into another language. (Hereinafter, translation is included without limitation in the term "modification".) "Source code" for a work means the preferred form of the work for making modifications to it. For a library, complete source code means all the source code for all modules it contains, plus any associated interface definition files, plus the scripts used to control compilation and installation of the library. Activities other than copying, distribution and modification are not covered by this License; they are outside its scope. The act of running a program using the Library is not restricted, and output from such a program is covered only if its contents constitute a work based on the Library (independent of the use of the Library in a tool for writing it). Whether that is true depends on what the Library does and what the program that uses the Library does. 1. You may copy and distribute verbatim copies of the Library's complete source code as you receive it, in any medium, provided that you conspicuously and appropriately publish on each copy an appropriate copyright notice and disclaimer of warranty; keep intact all the notices that refer to this License and to the absence of any warranty; and distribute a copy of this License along with the Library. You may charge a fee for the physical act of transferring a copy, and you may at your option offer warranty protection in exchange for a fee. 2. You may modify your copy or copies of the Library or any portion of it, thus forming a work based on the Library, and copy and distribute such modifications or work under the terms of Section 1 above, provided that you also meet all of these conditions: a) The modified work must itself be a software library. b) You must cause the files modified to carry prominent notices stating that you changed the files and the date of any change. c) You must cause the whole of the work to be licensed at no charge to all third parties under the terms of this License. d) If a facility in the modified Library refers to a function or a table of data to be supplied by an application program that uses the facility, other than as an argument passed when the facility is invoked, then you must make a good faith effort to ensure that, in the event an application does not supply such function or table, the facility still operates, and performs whatever part of its purpose remains meaningful. (For example, a function in a library to compute square roots has a purpose that is entirely well-defined independent of the application. Therefore, Subsection 2d requires that any application-supplied function or table used by this function must be optional: if the application does not supply it, the square root function must still compute square roots.) These requirements apply to the modified work as a whole. If identifiable sections of that work are not derived from the Library, and can be reasonably considered independent and separate works in themselves, then this License, and its terms, do not apply to those sections when you distribute them as separate works. But when you distribute the same sections as part of a whole which is a work based on the Library, the distribution of the whole must be on the terms of this License, whose permissions for other licensees extend to the entire whole, and thus to each and every part regardless of who wrote it. Thus, it is not the intent of this section to claim rights or contest your rights to work written entirely by you; rather, the intent is to exercise the right to control the distribution of derivative or collective works based on the Library. In addition, mere aggregation of another work not based on the Library with the Library (or with a work based on the Library) on a volume of a storage or distribution medium does not bring the other work under the scope of this License. 3. You may opt to apply the terms of the ordinary GNU General Public License instead of this License to a given copy of the Library. To do this, you must alter all the notices that refer to this License, so that they refer to the ordinary GNU General Public License, version 2, instead of to this License. (If a newer version than version 2 of the ordinary GNU General Public License has appeared, then you can specify that version instead if you wish.) Do not make any other change in these notices. Once this change is made in a given copy, it is irreversible for that copy, so the ordinary GNU General Public License applies to all subsequent copies and derivative works made from that copy. This option is useful when you wish to copy part of the code of the Library into a program that is not a library. 4. You may copy and distribute the Library (or a portion or derivative of it, under Section 2) in object code or executable form under the terms of Sections 1 and 2 above provided that you accompany it with the complete corresponding machine-readable source code, which must be distributed under the terms of Sections 1 and 2 above on a medium customarily used for software interchange. If distribution of object code is made by offering access to copy from a designated place, then offering equivalent access to copy the source code from the same place satisfies the requirement to distribute the source code, even though third parties are not compelled to copy the source along with the object code. 5. A program that contains no derivative of any portion of the Library, but is designed to work with the Library by being compiled or linked with it, is called a "work that uses the Library". Such a work, in isolation, is not a derivative work of the Library, and therefore falls outside the scope of this License. However, linking a "work that uses the Library" with the Library creates an executable that is a derivative of the Library (because it contains portions of the Library), rather than a "work that uses the library". The executable is therefore covered by this License. Section 6 states terms for distribution of such executables. When a "work that uses the Library" uses material from a header file that is part of the Library, the object code for the work may be a derivative work of the Library even though the source code is not. Whether this is true is especially significant if the work can be linked without the Library, or if the work is itself a library. The threshold for this to be true is not precisely defined by law. If such an object file uses only numerical parameters, data structure layouts and accessors, and small macros and small inline functions (ten lines or less in length), then the use of the object file is unrestricted, regardless of whether it is legally a derivative work. (Executables containing this object code plus portions of the Library will still fall under Section 6.) Otherwise, if the work is a derivative of the Library, you may distribute the object code for the work under the terms of Section 6. Any executables containing that work also fall under Section 6, whether or not they are linked directly with the Library itself. 6. As an exception to the Sections above, you may also combine or link a "work that uses the Library" with the Library to produce a work containing portions of the Library, and distribute that work under terms of your choice, provided that the terms permit modification of the work for the customer's own use and reverse engineering for debugging such modifications. You must give prominent notice with each copy of the work that the Library is used in it and that the Library and its use are covered by this License. You must supply a copy of this License. If the work during execution displays copyright notices, you must include the copyright notice for the Library among them, as well as a reference directing the user to the copy of this License. Also, you must do one of these things: a) Accompany the work with the complete corresponding machine-readable source code for the Library including whatever changes were used in the work (which must be distributed under Sections 1 and 2 above); and, if the work is an executable linked with the Library, with the complete machine-readable "work that uses the Library", as object code and/or source code, so that the user can modify the Library and then relink to produce a modified executable containing the modified Library. (It is understood that the user who changes the contents of definitions files in the Library will not necessarily be able to recompile the application to use the modified definitions.) b) Use a suitable shared library mechanism for linking with the Library. A suitable mechanism is one that (1) uses at run time a copy of the library already present on the user's computer system, rather than copying library functions into the executable, and (2) will operate properly with a modified version of the library, if the user installs one, as long as the modified version is interface-compatible with the version that the work was made with. c) Accompany the work with a written offer, valid for at least three years, to give the same user the materials specified in Subsection 6a, above, for a charge no more than the cost of performing this distribution. d) If distribution of the work is made by offering access to copy from a designated place, offer equivalent access to copy the above specified materials from the same place. e) Verify that the user has already received a copy of these materials or that you have already sent this user a copy. For an executable, the required form of the "work that uses the Library" must include any data and utility programs needed for reproducing the executable from it. However, as a special exception, the materials to be distributed need not include anything that is normally distributed (in either source or binary form) with the major components (compiler, kernel, and so on) of the operating system on which the executable runs, unless that component itself accompanies the executable. It may happen that this requirement contradicts the license restrictions of other proprietary libraries that do not normally accompany the operating system. Such a contradiction means you cannot use both them and the Library together in an executable that you distribute. 7. You may place library facilities that are a work based on the Library side-by-side in a single library together with other library facilities not covered by this License, and distribute such a combined library, provided that the separate distribution of the work based on the Library and of the other library facilities is otherwise permitted, and provided that you do these two things: a) Accompany the combined library with a copy of the same work based on the Library, uncombined with any other library facilities. This must be distributed under the terms of the Sections above. b) Give prominent notice with the combined library of the fact that part of it is a work based on the Library, and explaining where to find the accompanying uncombined form of the same work. 8. You may not copy, modify, sublicense, link with, or distribute the Library except as expressly provided under this License. Any attempt otherwise to copy, modify, sublicense, link with, or distribute the Library is void, and will automatically terminate your rights under this License. However, parties who have received copies, or rights, from you under this License will not have their licenses terminated so long as such parties remain in full compliance. 9. You are not required to accept this License, since you have not signed it. However, nothing else grants you permission to modify or distribute the Library or its derivative works. These actions are prohibited by law if you do not accept this License. Therefore, by modifying or distributing the Library (or any work based on the Library), you indicate your acceptance of this License to do so, and all its terms and conditions for copying, distributing or modifying the Library or works based on it. 10. Each time you redistribute the Library (or any work based on the Library), the recipient automatically receives a license from the original licensor to copy, distribute, link with or modify the Library subject to these terms and conditions. You may not impose any further restrictions on the recipients' exercise of the rights granted herein. You are not responsible for enforcing compliance by third parties with this License. 11. If, as a consequence of a court judgment or allegation of patent infringement or for any other reason (not limited to patent issues), 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 distribute so as to satisfy simultaneously your obligations under this License and any other pertinent obligations, then as a consequence you may not distribute the Library at all. For example, if a patent license would not permit royalty-free redistribution of the Library by all those who receive copies directly or indirectly through you, then the only way you could satisfy both it and this License would be to refrain entirely from distribution of the Library. If any portion of this section is held invalid or unenforceable under any particular circumstance, the balance of the section is intended to apply, and the section as a whole is intended to apply in other circumstances. It is not the purpose of this section to induce you to infringe any patents or other property right claims or to contest validity of any such claims; this section has the sole purpose of protecting the integrity of the free software distribution system which is implemented by public license practices. Many people have made generous contributions to the wide range of software distributed through that system in reliance on consistent application of that system; it is up to the author/donor to decide if he or she is willing to distribute software through any other system and a licensee cannot impose that choice. This section is intended to make thoroughly clear what is believed to be a consequence of the rest of this License. 12. If the distribution and/or use of the Library is restricted in certain countries either by patents or by copyrighted interfaces, the original copyright holder who places the Library under this License may add an explicit geographical distribution limitation excluding those countries, so that distribution is permitted only in or among countries not thus excluded. In such case, this License incorporates the limitation as if written in the body of this License. 13. The Free Software Foundation may publish revised and/or new versions of the Lesser 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 Library specifies a version number of this License which applies to it and "any later version", you have the option of following the terms and conditions either of that version or of any later version published by the Free Software Foundation. If the Library does not specify a license version number, you may choose any version ever published by the Free Software Foundation. 14. If you wish to incorporate parts of the Library into other free programs whose distribution conditions are incompatible with these, write to the author to ask for permission. For software which is copyrighted by the Free Software Foundation, write to the Free Software Foundation; we sometimes make exceptions for this. Our decision will be guided by the two goals of preserving the free status of all derivatives of our free software and of promoting the sharing and reuse of software generally. NO WARRANTY 15. BECAUSE THE LIBRARY IS LICENSED FREE OF CHARGE, THERE IS NO WARRANTY FOR THE LIBRARY, TO THE EXTENT PERMITTED BY APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT HOLDERS AND/OR OTHER PARTIES PROVIDE THE LIBRARY "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 LIBRARY IS WITH YOU. SHOULD THE LIBRARY PROVE DEFECTIVE, YOU ASSUME THE COST OF ALL NECESSARY SERVICING, REPAIR OR CORRECTION. 16. IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MAY MODIFY AND/OR REDISTRIBUTE THE LIBRARY 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 LIBRARY (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 LIBRARY TO OPERATE WITH ANY OTHER SOFTWARE), EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGES. END OF TERMS AND CONDITIONS How to Apply These Terms to Your New Libraries If you develop a new library, and you want it to be of the greatest possible use to the public, we recommend making it free software that everyone can redistribute and change. You can do so by permitting redistribution under these terms (or, alternatively, under the terms of the ordinary General Public License). To apply these terms, attach the following notices to the library. It is safest to attach them to the start of each source file to most effectively convey 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 library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. This library 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 Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this library; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA Also add information on how to contact you by electronic and paper mail. You should also get your employer (if you work as a programmer) or your school, if any, to sign a "copyright disclaimer" for the library, if necessary. Here is a sample; alter the names: Yoyodyne, Inc., hereby disclaims all copyright interest in the library `Frob' (a library for tweaking knobs) written by James Random Hacker. , 1 April 1990 Ty Coon, President of Vice That's all there is to it! qdjango-0.6.2/README.md000066400000000000000000000041261261212605400144230ustar00rootroot00000000000000QDjango - a Qt-based C++ web framework Copyright (c) 2010-2015 Jeremy Lainé [![Build Status](https://travis-ci.org/jlaine/qdjango.png)](https://travis-ci.org/jlaine/qdjango) About ===== _QDjango_ is a web framework written in C++ and built on top of the Qt library. Where possible it tries to follow django's API, hence its name. It is released under the terms of the GNU Lesser General Public License, version 2.1 or later. To learn more about _QDjango_, please read [the online documentation](http://doc.qdjango.org/). Requirements ============ QDjango builds and is auto-tested both with Qt 4 and Qt 5. Qt 4 on Debian: sudo apt-get install libqt4-dev Qt 5 on Debian: sudo apt-get install qtbase5-dev Qt 4 on Mac OS X: sudo port install qt4-mac Building QDjango ================ mkdir build cd build qmake .. make You can pass the following arguments to qmake: PREFIX= to change the install prefix default: unix: /usr/local on unix other: $$[QT_INSTALL_PREFIX] QDJANGO_LIBRARY_TYPE=staticlib to build a static version of QDjango Mailing list ============ If you wish to discuss QDjango, you are welcome to join the [QDjango group](http://groups.google.com/group/qdjango). Notes ====== MSSQL ----- Fast forward cursors are used by default. This greatly improves performance, and has the added benefit of implicitly converting to a static cursor when it [needs to]( http://technet.microsoft.com/en-us/library/aa172573(v=sql.80).aspx). Unfortunately, this also means that these cursors can block a connection to the server. In order to deal properly with this situation, there are a few requirements: - Connection pooling must be enabled in your [ODBC manager](http://www.unixodbc.org/doc/conn_pool.html) - You must enable Multiple Active Result Sets in the QODBC driver using "MARS_Connection=Yes" in the connection string - You must enable connection pooling in the QODBC driver using the "SQL_ATTR_CONNECTION_POOLING" attribute qdjango-0.6.2/doc/000077500000000000000000000000001261212605400137065ustar00rootroot00000000000000qdjango-0.6.2/doc/Doxyfile000066400000000000000000001777171261212605400154400ustar00rootroot00000000000000# Doxyfile 1.6.3 # This file describes the settings to be used by the documentation system # doxygen (www.doxygen.org) for a project # # All text after a hash (#) is considered a comment and will be ignored # The format is: # TAG = value [value, ...] # For lists items can also be appended using: # TAG += value [value, ...] # Values that contain spaces should be placed between quotes (" ") #--------------------------------------------------------------------------- # Project related configuration options #--------------------------------------------------------------------------- # This tag specifies the encoding used for all characters in the config file # that follow. The default is UTF-8 which is also the encoding used for all # text before the first occurrence of this tag. Doxygen uses libiconv (or the # iconv built into libc) for the transcoding. See # http://www.gnu.org/software/libiconv for the list of possible encodings. DOXYFILE_ENCODING = UTF-8 # The PROJECT_NAME tag is a single word (or a sequence of words surrounded # by quotes) that should identify the project. PROJECT_NAME = QDjango # The PROJECT_NUMBER tag can be used to enter a project or revision number. # This could be handy for archiving the generated documentation or # if some version control system is used. PROJECT_NUMBER = # The OUTPUT_DIRECTORY tag is used to specify the (relative or absolute) # base path where the generated documentation will be put. # If a relative path is entered, it will be relative to the location # where doxygen was started. If left blank the current directory will be used. OUTPUT_DIRECTORY = # If the CREATE_SUBDIRS tag is set to YES, then doxygen will create # 4096 sub-directories (in 2 levels) under the output directory of each output # format and will distribute the generated files over these directories. # Enabling this option can be useful when feeding doxygen a huge amount of # source files, where putting all generated files in the same directory would # otherwise cause performance problems for the file system. CREATE_SUBDIRS = NO # The OUTPUT_LANGUAGE tag is used to specify the language in which all # documentation generated by doxygen is written. Doxygen will use this # information to generate all constant output in the proper language. # The default language is English, other supported languages are: # Afrikaans, Arabic, Brazilian, Catalan, Chinese, Chinese-Traditional, # Croatian, Czech, Danish, Dutch, Esperanto, Farsi, Finnish, French, German, # Greek, Hungarian, Italian, Japanese, Japanese-en (Japanese with English # messages), Korean, Korean-en, Lithuanian, Norwegian, Macedonian, Persian, # Polish, Portuguese, Romanian, Russian, Serbian, Serbian-Cyrilic, Slovak, # Slovene, Spanish, Swedish, Ukrainian, and Vietnamese. OUTPUT_LANGUAGE = English # If the BRIEF_MEMBER_DESC tag is set to YES (the default) Doxygen will # include brief member descriptions after the members that are listed in # the file and class documentation (similar to JavaDoc). # Set to NO to disable this. BRIEF_MEMBER_DESC = YES # If the REPEAT_BRIEF tag is set to YES (the default) Doxygen will prepend # the brief description of a member or function before the detailed description. # Note: if both HIDE_UNDOC_MEMBERS and BRIEF_MEMBER_DESC are set to NO, the # brief descriptions will be completely suppressed. REPEAT_BRIEF = YES # This tag implements a quasi-intelligent brief description abbreviator # that is used to form the text in various listings. Each string # in this list, if found as the leading text of the brief description, will be # stripped from the text and the result after processing the whole list, is # used as the annotated text. Otherwise, the brief description is used as-is. # If left blank, the following values are used ("$name" is automatically # replaced with the name of the entity): "The $name class" "The $name widget" # "The $name file" "is" "provides" "specifies" "contains" # "represents" "a" "an" "the" ABBREVIATE_BRIEF = # If the ALWAYS_DETAILED_SEC and REPEAT_BRIEF tags are both set to YES then # Doxygen will generate a detailed section even if there is only a brief # description. ALWAYS_DETAILED_SEC = NO # If the INLINE_INHERITED_MEMB tag is set to YES, doxygen will show all # inherited members of a class in the documentation of that class as if those # members were ordinary class members. Constructors, destructors and assignment # operators of the base classes will not be shown. INLINE_INHERITED_MEMB = NO # If the FULL_PATH_NAMES tag is set to YES then Doxygen will prepend the full # path before files name in the file list and in the header files. If set # to NO the shortest path that makes the file name unique will be used. FULL_PATH_NAMES = NO # If the FULL_PATH_NAMES tag is set to YES then the STRIP_FROM_PATH tag # can be used to strip a user-defined part of the path. Stripping is # only done if one of the specified strings matches the left-hand part of # the path. The tag can be used to show relative paths in the file list. # If left blank the directory from which doxygen is run is used as the # path to strip. STRIP_FROM_PATH = # The STRIP_FROM_INC_PATH tag can be used to strip a user-defined part of # the path mentioned in the documentation of a class, which tells # the reader which header file to include in order to use a class. # If left blank only the name of the header file containing the class # definition is used. Otherwise one should specify the include paths that # are normally passed to the compiler using the -I flag. STRIP_FROM_INC_PATH = # If the SHORT_NAMES tag is set to YES, doxygen will generate much shorter # (but less readable) file names. This can be useful is your file systems # doesn't support long names like on DOS, Mac, or CD-ROM. SHORT_NAMES = NO # If the JAVADOC_AUTOBRIEF tag is set to YES then Doxygen # will interpret the first line (until the first dot) of a JavaDoc-style # comment as the brief description. If set to NO, the JavaDoc # comments will behave just like regular Qt-style comments # (thus requiring an explicit @brief command for a brief description.) JAVADOC_AUTOBRIEF = NO # If the QT_AUTOBRIEF tag is set to YES then Doxygen will # interpret the first line (until the first dot) of a Qt-style # comment as the brief description. If set to NO, the comments # will behave just like regular Qt-style comments (thus requiring # an explicit \brief command for a brief description.) QT_AUTOBRIEF = YES # The MULTILINE_CPP_IS_BRIEF tag can be set to YES to make Doxygen # treat a multi-line C++ special comment block (i.e. a block of //! or /// # comments) as a brief description. This used to be the default behaviour. # The new default is to treat a multi-line C++ comment block as a detailed # description. Set this tag to YES if you prefer the old behaviour instead. MULTILINE_CPP_IS_BRIEF = NO # If the INHERIT_DOCS tag is set to YES (the default) then an undocumented # member inherits the documentation from any documented member that it # re-implements. INHERIT_DOCS = YES # If the SEPARATE_MEMBER_PAGES tag is set to YES, then doxygen will produce # a new page for each member. If set to NO, the documentation of a member will # be part of the file/class/namespace that contains it. SEPARATE_MEMBER_PAGES = NO # The TAB_SIZE tag can be used to set the number of spaces in a tab. # Doxygen uses this value to replace tabs by spaces in code fragments. TAB_SIZE = 8 # This tag can be used to specify a number of aliases that acts # as commands in the documentation. An alias has the form "name=value". # For example adding "sideeffect=\par Side Effects:\n" will allow you to # put the command \sideeffect (or @sideeffect) in the documentation, which # will result in a user-defined paragraph with heading "Side Effects:". # You can put \n's in the value part of an alias to insert newlines. ALIASES = # Set the OPTIMIZE_OUTPUT_FOR_C tag to YES if your project consists of C # sources only. Doxygen will then generate output that is more tailored for C. # For instance, some of the names that are used will be different. The list # of all members will be omitted, etc. OPTIMIZE_OUTPUT_FOR_C = NO # Set the OPTIMIZE_OUTPUT_JAVA tag to YES if your project consists of Java # sources only. Doxygen will then generate output that is more tailored for # Java. For instance, namespaces will be presented as packages, qualified # scopes will look different, etc. OPTIMIZE_OUTPUT_JAVA = NO # Set the OPTIMIZE_FOR_FORTRAN tag to YES if your project consists of Fortran # sources only. Doxygen will then generate output that is more tailored for # Fortran. OPTIMIZE_FOR_FORTRAN = NO # Set the OPTIMIZE_OUTPUT_VHDL tag to YES if your project consists of VHDL # sources. Doxygen will then generate output that is tailored for # VHDL. OPTIMIZE_OUTPUT_VHDL = NO # Doxygen selects the parser to use depending on the extension of the files it parses. # With this tag you can assign which parser to use for a given extension. # Doxygen has a built-in mapping, but you can override or extend it using this tag. # The format is ext=language, where ext is a file extension, and language is one of # the parsers supported by doxygen: IDL, Java, Javascript, C#, C, C++, D, PHP, # Objective-C, Python, Fortran, VHDL, C, C++. For instance to make doxygen treat # .inc files as Fortran files (default is PHP), and .f files as C (default is Fortran), # use: inc=Fortran f=C. Note that for custom extensions you also need to set FILE_PATTERNS otherwise the files are not read by doxygen. EXTENSION_MAPPING = # If you use STL classes (i.e. std::string, std::vector, etc.) but do not want # to include (a tag file for) the STL sources as input, then you should # set this tag to YES in order to let doxygen match functions declarations and # definitions whose arguments contain STL classes (e.g. func(std::string); v.s. # func(std::string) {}). This also make the inheritance and collaboration # diagrams that involve STL classes more complete and accurate. BUILTIN_STL_SUPPORT = NO # If you use Microsoft's C++/CLI language, you should set this option to YES to # enable parsing support. CPP_CLI_SUPPORT = NO # Set the SIP_SUPPORT tag to YES if your project consists of sip sources only. # Doxygen will parse them like normal C++ but will assume all classes use public # instead of private inheritance when no explicit protection keyword is present. SIP_SUPPORT = NO # For Microsoft's IDL there are propget and propput attributes to indicate getter # and setter methods for a property. Setting this option to YES (the default) # will make doxygen to replace the get and set methods by a property in the # documentation. This will only work if the methods are indeed getting or # setting a simple type. If this is not the case, or you want to show the # methods anyway, you should set this option to NO. IDL_PROPERTY_SUPPORT = YES # If member grouping is used in the documentation and the DISTRIBUTE_GROUP_DOC # tag is set to YES, then doxygen will reuse the documentation of the first # member in the group (if any) for the other members of the group. By default # all members of a group must be documented explicitly. DISTRIBUTE_GROUP_DOC = NO # Set the SUBGROUPING tag to YES (the default) to allow class member groups of # the same type (for instance a group of public functions) to be put as a # subgroup of that type (e.g. under the Public Functions section). Set it to # NO to prevent subgrouping. Alternatively, this can be done per class using # the \nosubgrouping command. SUBGROUPING = YES # When TYPEDEF_HIDES_STRUCT is enabled, a typedef of a struct, union, or enum # is documented as struct, union, or enum with the name of the typedef. So # typedef struct TypeS {} TypeT, will appear in the documentation as a struct # with name TypeT. When disabled the typedef will appear as a member of a file, # namespace, or class. And the struct will be named TypeS. This can typically # be useful for C code in case the coding convention dictates that all compound # types are typedef'ed and only the typedef is referenced, never the tag name. TYPEDEF_HIDES_STRUCT = NO # The SYMBOL_CACHE_SIZE determines the size of the internal cache use to # determine which symbols to keep in memory and which to flush to disk. # When the cache is full, less often used symbols will be written to disk. # For small to medium size projects (<1000 input files) the default value is # probably good enough. For larger projects a too small cache size can cause # doxygen to be busy swapping symbols to and from disk most of the time # causing a significant performance penality. # If the system has enough physical memory increasing the cache will improve the # performance by keeping more symbols in memory. Note that the value works on # a logarithmic scale so increasing the size by one will rougly double the # memory usage. The cache size is given by this formula: # 2^(16+SYMBOL_CACHE_SIZE). The valid range is 0..9, the default is 0, # corresponding to a cache size of 2^16 = 65536 symbols SYMBOL_CACHE_SIZE = 0 #--------------------------------------------------------------------------- # Build related configuration options #--------------------------------------------------------------------------- # If the EXTRACT_ALL tag is set to YES doxygen will assume all entities in # documentation are documented, even if no documentation was available. # Private class members and static file members will be hidden unless # the EXTRACT_PRIVATE and EXTRACT_STATIC tags are set to YES EXTRACT_ALL = NO # If the EXTRACT_PRIVATE tag is set to YES all private members of a class # will be included in the documentation. EXTRACT_PRIVATE = NO # If the EXTRACT_STATIC tag is set to YES all static members of a file # will be included in the documentation. EXTRACT_STATIC = NO # If the EXTRACT_LOCAL_CLASSES tag is set to YES classes (and structs) # defined locally in source files will be included in the documentation. # If set to NO only classes defined in header files are included. EXTRACT_LOCAL_CLASSES = NO # This flag is only useful for Objective-C code. When set to YES local # methods, which are defined in the implementation section but not in # the interface are included in the documentation. # If set to NO (the default) only methods in the interface are included. EXTRACT_LOCAL_METHODS = NO # If this flag is set to YES, the members of anonymous namespaces will be # extracted and appear in the documentation as a namespace called # 'anonymous_namespace{file}', where file will be replaced with the base # name of the file that contains the anonymous namespace. By default # anonymous namespace are hidden. EXTRACT_ANON_NSPACES = NO # If the HIDE_UNDOC_MEMBERS tag is set to YES, Doxygen will hide all # undocumented members of documented classes, files or namespaces. # If set to NO (the default) these members will be included in the # various overviews, but no documentation section is generated. # This option has no effect if EXTRACT_ALL is enabled. HIDE_UNDOC_MEMBERS = NO # If the HIDE_UNDOC_CLASSES tag is set to YES, Doxygen will hide all # undocumented classes that are normally visible in the class hierarchy. # If set to NO (the default) these classes will be included in the various # overviews. This option has no effect if EXTRACT_ALL is enabled. HIDE_UNDOC_CLASSES = NO # If the HIDE_FRIEND_COMPOUNDS tag is set to YES, Doxygen will hide all # friend (class|struct|union) declarations. # If set to NO (the default) these declarations will be included in the # documentation. HIDE_FRIEND_COMPOUNDS = NO # If the HIDE_IN_BODY_DOCS tag is set to YES, Doxygen will hide any # documentation blocks found inside the body of a function. # If set to NO (the default) these blocks will be appended to the # function's detailed documentation block. HIDE_IN_BODY_DOCS = NO # The INTERNAL_DOCS tag determines if documentation # that is typed after a \internal command is included. If the tag is set # to NO (the default) then the documentation will be excluded. # Set it to YES to include the internal documentation. INTERNAL_DOCS = NO # If the CASE_SENSE_NAMES tag is set to NO then Doxygen will only generate # file names in lower-case letters. If set to YES upper-case letters are also # allowed. This is useful if you have classes or files whose names only differ # in case and if your file system supports case sensitive file names. Windows # and Mac users are advised to set this option to NO. CASE_SENSE_NAMES = YES # If the HIDE_SCOPE_NAMES tag is set to NO (the default) then Doxygen # will show members with their full class and namespace scopes in the # documentation. If set to YES the scope will be hidden. HIDE_SCOPE_NAMES = NO # If the SHOW_INCLUDE_FILES tag is set to YES (the default) then Doxygen # will put a list of the files that are included by a file in the documentation # of that file. SHOW_INCLUDE_FILES = YES # If the FORCE_LOCAL_INCLUDES tag is set to YES then Doxygen # will list include files with double quotes in the documentation # rather than with sharp brackets. FORCE_LOCAL_INCLUDES = NO # If the INLINE_INFO tag is set to YES (the default) then a tag [inline] # is inserted in the documentation for inline members. INLINE_INFO = YES # If the SORT_MEMBER_DOCS tag is set to YES (the default) then doxygen # will sort the (detailed) documentation of file and class members # alphabetically by member name. If set to NO the members will appear in # declaration order. SORT_MEMBER_DOCS = YES # If the SORT_BRIEF_DOCS tag is set to YES then doxygen will sort the # brief documentation of file, namespace and class members alphabetically # by member name. If set to NO (the default) the members will appear in # declaration order. SORT_BRIEF_DOCS = NO # If the SORT_MEMBERS_CTORS_1ST tag is set to YES then doxygen will sort the (brief and detailed) documentation of class members so that constructors and destructors are listed first. If set to NO (the default) the constructors will appear in the respective orders defined by SORT_MEMBER_DOCS and SORT_BRIEF_DOCS. This tag will be ignored for brief docs if SORT_BRIEF_DOCS is set to NO and ignored for detailed docs if SORT_MEMBER_DOCS is set to NO. SORT_MEMBERS_CTORS_1ST = NO # If the SORT_GROUP_NAMES tag is set to YES then doxygen will sort the # hierarchy of group names into alphabetical order. If set to NO (the default) # the group names will appear in their defined order. SORT_GROUP_NAMES = NO # If the SORT_BY_SCOPE_NAME tag is set to YES, the class list will be # sorted by fully-qualified names, including namespaces. If set to # NO (the default), the class list will be sorted only by class name, # not including the namespace part. # Note: This option is not very useful if HIDE_SCOPE_NAMES is set to YES. # Note: This option applies only to the class list, not to the # alphabetical list. SORT_BY_SCOPE_NAME = NO # The GENERATE_TODOLIST tag can be used to enable (YES) or # disable (NO) the todo list. This list is created by putting \todo # commands in the documentation. GENERATE_TODOLIST = YES # The GENERATE_TESTLIST tag can be used to enable (YES) or # disable (NO) the test list. This list is created by putting \test # commands in the documentation. GENERATE_TESTLIST = YES # The GENERATE_BUGLIST tag can be used to enable (YES) or # disable (NO) the bug list. This list is created by putting \bug # commands in the documentation. GENERATE_BUGLIST = YES # The GENERATE_DEPRECATEDLIST tag can be used to enable (YES) or # disable (NO) the deprecated list. This list is created by putting # \deprecated commands in the documentation. GENERATE_DEPRECATEDLIST= YES # The ENABLED_SECTIONS tag can be used to enable conditional # documentation sections, marked by \if sectionname ... \endif. ENABLED_SECTIONS = # The MAX_INITIALIZER_LINES tag determines the maximum number of lines # the initial value of a variable or define consists of for it to appear in # the documentation. If the initializer consists of more lines than specified # here it will be hidden. Use a value of 0 to hide initializers completely. # The appearance of the initializer of individual variables and defines in the # documentation can be controlled using \showinitializer or \hideinitializer # command in the documentation regardless of this setting. MAX_INITIALIZER_LINES = 30 # Set the SHOW_USED_FILES tag to NO to disable the list of files generated # at the bottom of the documentation of classes and structs. If set to YES the # list will mention the files that were used to generate the documentation. SHOW_USED_FILES = YES # If the sources in your project are distributed over multiple directories # then setting the SHOW_DIRECTORIES tag to YES will show the directory hierarchy # in the documentation. The default is NO. SHOW_DIRECTORIES = NO # Set the SHOW_FILES tag to NO to disable the generation of the Files page. # This will remove the Files entry from the Quick Index and from the # Folder Tree View (if specified). The default is YES. SHOW_FILES = YES # Set the SHOW_NAMESPACES tag to NO to disable the generation of the # Namespaces page. # This will remove the Namespaces entry from the Quick Index # and from the Folder Tree View (if specified). The default is YES. SHOW_NAMESPACES = YES # The FILE_VERSION_FILTER tag can be used to specify a program or script that # doxygen should invoke to get the current version for each file (typically from # the version control system). Doxygen will invoke the program by executing (via # popen()) the command , where is the value of # the FILE_VERSION_FILTER tag, and is the name of an input file # provided by doxygen. Whatever the program writes to standard output # is used as the file version. See the manual for examples. FILE_VERSION_FILTER = # The LAYOUT_FILE tag can be used to specify a layout file which will be parsed by # doxygen. The layout file controls the global structure of the generated output files # in an output format independent way. The create the layout file that represents # doxygen's defaults, run doxygen with the -l option. You can optionally specify a # file name after the option, if omitted DoxygenLayout.xml will be used as the name # of the layout file. LAYOUT_FILE = #--------------------------------------------------------------------------- # configuration options related to warning and progress messages #--------------------------------------------------------------------------- # The QUIET tag can be used to turn on/off the messages that are generated # by doxygen. Possible values are YES and NO. If left blank NO is used. QUIET = NO # The WARNINGS tag can be used to turn on/off the warning messages that are # generated by doxygen. Possible values are YES and NO. If left blank # NO is used. WARNINGS = YES # If WARN_IF_UNDOCUMENTED is set to YES, then doxygen will generate warnings # for undocumented members. If EXTRACT_ALL is set to YES then this flag will # automatically be disabled. WARN_IF_UNDOCUMENTED = YES # If WARN_IF_DOC_ERROR is set to YES, doxygen will generate warnings for # potential errors in the documentation, such as not documenting some # parameters in a documented function, or documenting parameters that # don't exist or using markup commands wrongly. WARN_IF_DOC_ERROR = YES # This WARN_NO_PARAMDOC option can be abled to get warnings for # functions that are documented, but have no documentation for their parameters # or return value. If set to NO (the default) doxygen will only warn about # wrong or incomplete parameter documentation, but not about the absence of # documentation. WARN_NO_PARAMDOC = NO # The WARN_FORMAT tag determines the format of the warning messages that # doxygen can produce. The string should contain the $file, $line, and $text # tags, which will be replaced by the file and line number from which the # warning originated and the warning text. Optionally the format may contain # $version, which will be replaced by the version of the file (if it could # be obtained via FILE_VERSION_FILTER) WARN_FORMAT = "$file:$line: $text" # The WARN_LOGFILE tag can be used to specify a file to which warning # and error messages should be written. If left blank the output is written # to stderr. WARN_LOGFILE = #--------------------------------------------------------------------------- # configuration options related to the input files #--------------------------------------------------------------------------- # The INPUT tag can be used to specify the files and/or directories that contain # documented source files. You may enter file names like "myfile.cpp" or # directories like "/usr/src/myproject". Separate the files or directories # with spaces. INPUT = database.doc http.doc index.doc models.doc queries.doc ../src/db ../src/http # This tag can be used to specify the character encoding of the source files # that doxygen parses. Internally doxygen uses the UTF-8 encoding, which is # also the default input encoding. Doxygen uses libiconv (or the iconv built # into libc) for the transcoding. See http://www.gnu.org/software/libiconv for # the list of possible encodings. INPUT_ENCODING = UTF-8 # If the value of the INPUT tag contains directories, you can use the # FILE_PATTERNS tag to specify one or more wildcard pattern (like *.cpp # and *.h) to filter out the source-files in the directories. If left # blank the following patterns are tested: # *.c *.cc *.cxx *.cpp *.c++ *.java *.ii *.ixx *.ipp *.i++ *.inl *.h *.hh *.hxx # *.hpp *.h++ *.idl *.odl *.cs *.php *.php3 *.inc *.m *.mm *.py *.f90 FILE_PATTERNS = # The RECURSIVE tag can be used to turn specify whether or not subdirectories # should be searched for input files as well. Possible values are YES and NO. # If left blank NO is used. RECURSIVE = NO # The EXCLUDE tag can be used to specify files and/or directories that should # excluded from the INPUT source files. This way you can easily exclude a # subdirectory from a directory tree whose root is specified with the INPUT tag. EXCLUDE = # The EXCLUDE_SYMLINKS tag can be used select whether or not files or # directories that are symbolic links (a Unix filesystem feature) are excluded # from the input. EXCLUDE_SYMLINKS = NO # If the value of the INPUT tag contains directories, you can use the # EXCLUDE_PATTERNS tag to specify one or more wildcard patterns to exclude # certain files from those directories. Note that the wildcards are matched # against the file with absolute path, so to exclude all test directories # for example use the pattern */test/* EXCLUDE_PATTERNS = */moc_* *_p.h # The EXCLUDE_SYMBOLS tag can be used to specify one or more symbol names # (namespaces, classes, functions, etc.) that should be excluded from the # output. The symbol name can be a fully qualified name, a word, or if the # wildcard * is used, a substring. Examples: ANamespace, AClass, # AClass::ANamespace, ANamespace::*Test EXCLUDE_SYMBOLS = # The EXAMPLE_PATH tag can be used to specify one or more files or # directories that contain example code fragments that are included (see # the \include command). EXAMPLE_PATH = # If the value of the EXAMPLE_PATH tag contains directories, you can use the # EXAMPLE_PATTERNS tag to specify one or more wildcard pattern (like *.cpp # and *.h) to filter out the source-files in the directories. If left # blank all files are included. EXAMPLE_PATTERNS = # If the EXAMPLE_RECURSIVE tag is set to YES then subdirectories will be # searched for input files to be used with the \include or \dontinclude # commands irrespective of the value of the RECURSIVE tag. # Possible values are YES and NO. If left blank NO is used. EXAMPLE_RECURSIVE = NO # The IMAGE_PATH tag can be used to specify one or more files or # directories that contain image that are included in the documentation (see # the \image command). IMAGE_PATH = # The INPUT_FILTER tag can be used to specify a program that doxygen should # invoke to filter for each input file. Doxygen will invoke the filter program # by executing (via popen()) the command , where # is the value of the INPUT_FILTER tag, and is the name of an # input file. Doxygen will then use the output that the filter program writes # to standard output. # If FILTER_PATTERNS is specified, this tag will be # ignored. INPUT_FILTER = # The FILTER_PATTERNS tag can be used to specify filters on a per file pattern # basis. # Doxygen will compare the file name with each pattern and apply the # filter if there is a match. # The filters are a list of the form: # pattern=filter (like *.cpp=my_cpp_filter). See INPUT_FILTER for further # info on how filters are used. If FILTER_PATTERNS is empty, INPUT_FILTER # is applied to all files. FILTER_PATTERNS = # If the FILTER_SOURCE_FILES tag is set to YES, the input filter (if set using # INPUT_FILTER) will be used to filter the input files when producing source # files to browse (i.e. when SOURCE_BROWSER is set to YES). FILTER_SOURCE_FILES = NO #--------------------------------------------------------------------------- # configuration options related to source browsing #--------------------------------------------------------------------------- # If the SOURCE_BROWSER tag is set to YES then a list of source files will # be generated. Documented entities will be cross-referenced with these sources. # Note: To get rid of all source code in the generated output, make sure also # VERBATIM_HEADERS is set to NO. SOURCE_BROWSER = NO # Setting the INLINE_SOURCES tag to YES will include the body # of functions and classes directly in the documentation. INLINE_SOURCES = NO # Setting the STRIP_CODE_COMMENTS tag to YES (the default) will instruct # doxygen to hide any special comment blocks from generated source code # fragments. Normal C and C++ comments will always remain visible. STRIP_CODE_COMMENTS = YES # If the REFERENCED_BY_RELATION tag is set to YES # then for each documented function all documented # functions referencing it will be listed. REFERENCED_BY_RELATION = NO # If the REFERENCES_RELATION tag is set to YES # then for each documented function all documented entities # called/used by that function will be listed. REFERENCES_RELATION = NO # If the REFERENCES_LINK_SOURCE tag is set to YES (the default) # and SOURCE_BROWSER tag is set to YES, then the hyperlinks from # functions in REFERENCES_RELATION and REFERENCED_BY_RELATION lists will # link to the source code. # Otherwise they will link to the documentation. REFERENCES_LINK_SOURCE = YES # If the USE_HTAGS tag is set to YES then the references to source code # will point to the HTML generated by the htags(1) tool instead of doxygen # built-in source browser. The htags tool is part of GNU's global source # tagging system (see http://www.gnu.org/software/global/global.html). You # will need version 4.8.6 or higher. USE_HTAGS = NO # If the VERBATIM_HEADERS tag is set to YES (the default) then Doxygen # will generate a verbatim copy of the header file for each class for # which an include is specified. Set to NO to disable this. VERBATIM_HEADERS = YES #--------------------------------------------------------------------------- # configuration options related to the alphabetical class index #--------------------------------------------------------------------------- # If the ALPHABETICAL_INDEX tag is set to YES, an alphabetical index # of all compounds will be generated. Enable this if the project # contains a lot of classes, structs, unions or interfaces. ALPHABETICAL_INDEX = NO # If the alphabetical index is enabled (see ALPHABETICAL_INDEX) then # the COLS_IN_ALPHA_INDEX tag can be used to specify the number of columns # in which this list will be split (can be a number in the range [1..20]) COLS_IN_ALPHA_INDEX = 5 # In case all classes in a project start with a common prefix, all # classes will be put under the same header in the alphabetical index. # The IGNORE_PREFIX tag can be used to specify one or more prefixes that # should be ignored while generating the index headers. IGNORE_PREFIX = #--------------------------------------------------------------------------- # configuration options related to the HTML output #--------------------------------------------------------------------------- # If the GENERATE_HTML tag is set to YES (the default) Doxygen will # generate HTML output. GENERATE_HTML = YES # The HTML_OUTPUT tag is used to specify where the HTML docs will be put. # If a relative path is entered the value of OUTPUT_DIRECTORY will be # put in front of it. If left blank `html' will be used as the default path. HTML_OUTPUT = html # The HTML_FILE_EXTENSION tag can be used to specify the file extension for # each generated HTML page (for example: .htm,.php,.asp). If it is left blank # doxygen will generate files with .html extension. HTML_FILE_EXTENSION = .html # The HTML_HEADER tag can be used to specify a personal HTML header for # each generated HTML page. If it is left blank doxygen will generate a # standard header. HTML_HEADER = # The HTML_FOOTER tag can be used to specify a personal HTML footer for # each generated HTML page. If it is left blank doxygen will generate a # standard footer. HTML_FOOTER = # The HTML_STYLESHEET tag can be used to specify a user-defined cascading # style sheet that is used by each HTML page. It can be used to # fine-tune the look of the HTML output. If the tag is left blank doxygen # will generate a default style sheet. Note that doxygen will try to copy # the style sheet file to the HTML output directory, so don't put your own # stylesheet in the HTML output directory as well, or it will be erased! HTML_STYLESHEET = # If the HTML_TIMESTAMP tag is set to YES then the footer of each generated HTML # page will contain the date and time when the page was generated. Setting # this to NO can help when comparing the output of multiple runs. HTML_TIMESTAMP = NO # If the HTML_ALIGN_MEMBERS tag is set to YES, the members of classes, # files or namespaces will be aligned in HTML using tables. If set to # NO a bullet list will be used. HTML_ALIGN_MEMBERS = YES # If the HTML_DYNAMIC_SECTIONS tag is set to YES then the generated HTML # documentation will contain sections that can be hidden and shown after the # page has loaded. For this to work a browser that supports # JavaScript and DHTML is required (for instance Mozilla 1.0+, Firefox # Netscape 6.0+, Internet explorer 5.0+, Konqueror, or Safari). HTML_DYNAMIC_SECTIONS = NO # If the GENERATE_DOCSET tag is set to YES, additional index files # will be generated that can be used as input for Apple's Xcode 3 # integrated development environment, introduced with OSX 10.5 (Leopard). # To create a documentation set, doxygen will generate a Makefile in the # HTML output directory. Running make will produce the docset in that # directory and running "make install" will install the docset in # ~/Library/Developer/Shared/Documentation/DocSets so that Xcode will find # it at startup. # See http://developer.apple.com/tools/creatingdocsetswithdoxygen.html for more information. GENERATE_DOCSET = NO # When GENERATE_DOCSET tag is set to YES, this tag determines the name of the # feed. A documentation feed provides an umbrella under which multiple # documentation sets from a single provider (such as a company or product suite) # can be grouped. DOCSET_FEEDNAME = "Doxygen generated docs" # When GENERATE_DOCSET tag is set to YES, this tag specifies a string that # should uniquely identify the documentation set bundle. This should be a # reverse domain-name style string, e.g. com.mycompany.MyDocSet. Doxygen # will append .docset to the name. DOCSET_BUNDLE_ID = org.doxygen.Project # If the GENERATE_HTMLHELP tag is set to YES, additional index files # will be generated that can be used as input for tools like the # Microsoft HTML help workshop to generate a compiled HTML help file (.chm) # of the generated HTML documentation. GENERATE_HTMLHELP = NO # If the GENERATE_HTMLHELP tag is set to YES, the CHM_FILE tag can # be used to specify the file name of the resulting .chm file. You # can add a path in front of the file if the result should not be # written to the html output directory. CHM_FILE = # If the GENERATE_HTMLHELP tag is set to YES, the HHC_LOCATION tag can # be used to specify the location (absolute path including file name) of # the HTML help compiler (hhc.exe). If non-empty doxygen will try to run # the HTML help compiler on the generated index.hhp. HHC_LOCATION = # If the GENERATE_HTMLHELP tag is set to YES, the GENERATE_CHI flag # controls if a separate .chi index file is generated (YES) or that # it should be included in the master .chm file (NO). GENERATE_CHI = NO # If the GENERATE_HTMLHELP tag is set to YES, the CHM_INDEX_ENCODING # is used to encode HtmlHelp index (hhk), content (hhc) and project file # content. CHM_INDEX_ENCODING = # If the GENERATE_HTMLHELP tag is set to YES, the BINARY_TOC flag # controls whether a binary table of contents is generated (YES) or a # normal table of contents (NO) in the .chm file. BINARY_TOC = NO # The TOC_EXPAND flag can be set to YES to add extra items for group members # to the contents of the HTML help documentation and to the tree view. TOC_EXPAND = NO # If the GENERATE_QHP tag is set to YES and both QHP_NAMESPACE and QHP_VIRTUAL_FOLDER # are set, an additional index file will be generated that can be used as input for # Qt's qhelpgenerator to generate a Qt Compressed Help (.qch) of the generated # HTML documentation. GENERATE_QHP = NO # If the QHG_LOCATION tag is specified, the QCH_FILE tag can # be used to specify the file name of the resulting .qch file. # The path specified is relative to the HTML output folder. QCH_FILE = # The QHP_NAMESPACE tag specifies the namespace to use when generating # Qt Help Project output. For more information please see # http://doc.trolltech.com/qthelpproject.html#namespace QHP_NAMESPACE = org.doxygen.Project # The QHP_VIRTUAL_FOLDER tag specifies the namespace to use when generating # Qt Help Project output. For more information please see # http://doc.trolltech.com/qthelpproject.html#virtual-folders QHP_VIRTUAL_FOLDER = doc # If QHP_CUST_FILTER_NAME is set, it specifies the name of a custom filter to add. # For more information please see # http://doc.trolltech.com/qthelpproject.html#custom-filters QHP_CUST_FILTER_NAME = # The QHP_CUST_FILT_ATTRS tag specifies the list of the attributes of the custom filter to add.For more information please see # Qt Help Project / Custom Filters. QHP_CUST_FILTER_ATTRS = # The QHP_SECT_FILTER_ATTRS tag specifies the list of the attributes this project's # filter section matches. # Qt Help Project / Filter Attributes. QHP_SECT_FILTER_ATTRS = # If the GENERATE_QHP tag is set to YES, the QHG_LOCATION tag can # be used to specify the location of Qt's qhelpgenerator. # If non-empty doxygen will try to run qhelpgenerator on the generated # .qhp file. QHG_LOCATION = # If the GENERATE_ECLIPSEHELP tag is set to YES, additional index files # will be generated, which together with the HTML files, form an Eclipse help # plugin. To install this plugin and make it available under the help contents # menu in Eclipse, the contents of the directory containing the HTML and XML # files needs to be copied into the plugins directory of eclipse. The name of # the directory within the plugins directory should be the same as # the ECLIPSE_DOC_ID value. After copying Eclipse needs to be restarted before the help appears. GENERATE_ECLIPSEHELP = NO # A unique identifier for the eclipse help plugin. When installing the plugin # the directory name containing the HTML and XML files should also have # this name. ECLIPSE_DOC_ID = org.doxygen.Project # The DISABLE_INDEX tag can be used to turn on/off the condensed index at # top of each HTML page. The value NO (the default) enables the index and # the value YES disables it. DISABLE_INDEX = NO # This tag can be used to set the number of enum values (range [1..20]) # that doxygen will group on one line in the generated HTML documentation. ENUM_VALUES_PER_LINE = 4 # The GENERATE_TREEVIEW tag is used to specify whether a tree-like index # structure should be generated to display hierarchical information. # If the tag value is set to YES, a side panel will be generated # containing a tree-like index structure (just like the one that # is generated for HTML Help). For this to work a browser that supports # JavaScript, DHTML, CSS and frames is required (i.e. any modern browser). # Windows users are probably better off using the HTML help feature. GENERATE_TREEVIEW = NO # By enabling USE_INLINE_TREES, doxygen will generate the Groups, Directories, # and Class Hierarchy pages using a tree view instead of an ordered list. USE_INLINE_TREES = NO # If the treeview is enabled (see GENERATE_TREEVIEW) then this tag can be # used to set the initial width (in pixels) of the frame in which the tree # is shown. TREEVIEW_WIDTH = 250 # Use this tag to change the font size of Latex formulas included # as images in the HTML documentation. The default is 10. Note that # when you change the font size after a successful doxygen run you need # to manually remove any form_*.png images from the HTML output directory # to force them to be regenerated. FORMULA_FONTSIZE = 10 # When the SEARCHENGINE tag is enabled doxygen will generate a search box for the HTML output. The underlying search engine uses javascript # and DHTML and should work on any modern browser. Note that when using HTML help (GENERATE_HTMLHELP), Qt help (GENERATE_QHP), or docsets (GENERATE_DOCSET) there is already a search function so this one should # typically be disabled. For large projects the javascript based search engine # can be slow, then enabling SERVER_BASED_SEARCH may provide a better solution. SEARCHENGINE = YES # When the SERVER_BASED_SEARCH tag is enabled the search engine will be implemented using a PHP enabled web server instead of at the web client using Javascript. Doxygen will generate the search PHP script and index # file to put on the web server. The advantage of the server based approach is that it scales better to large projects and allows full text search. The disadvances is that it is more difficult to setup # and does not have live searching capabilities. SERVER_BASED_SEARCH = NO #--------------------------------------------------------------------------- # configuration options related to the LaTeX output #--------------------------------------------------------------------------- # If the GENERATE_LATEX tag is set to YES (the default) Doxygen will # generate Latex output. GENERATE_LATEX = NO # The LATEX_OUTPUT tag is used to specify where the LaTeX docs will be put. # If a relative path is entered the value of OUTPUT_DIRECTORY will be # put in front of it. If left blank `latex' will be used as the default path. LATEX_OUTPUT = latex # The LATEX_CMD_NAME tag can be used to specify the LaTeX command name to be # invoked. If left blank `latex' will be used as the default command name. # Note that when enabling USE_PDFLATEX this option is only used for # generating bitmaps for formulas in the HTML output, but not in the # Makefile that is written to the output directory. LATEX_CMD_NAME = latex # The MAKEINDEX_CMD_NAME tag can be used to specify the command name to # generate index for LaTeX. If left blank `makeindex' will be used as the # default command name. MAKEINDEX_CMD_NAME = makeindex # If the COMPACT_LATEX tag is set to YES Doxygen generates more compact # LaTeX documents. This may be useful for small projects and may help to # save some trees in general. COMPACT_LATEX = NO # The PAPER_TYPE tag can be used to set the paper type that is used # by the printer. Possible values are: a4, a4wide, letter, legal and # executive. If left blank a4wide will be used. PAPER_TYPE = a4wide # The EXTRA_PACKAGES tag can be to specify one or more names of LaTeX # packages that should be included in the LaTeX output. EXTRA_PACKAGES = # The LATEX_HEADER tag can be used to specify a personal LaTeX header for # the generated latex document. The header should contain everything until # the first chapter. If it is left blank doxygen will generate a # standard header. Notice: only use this tag if you know what you are doing! LATEX_HEADER = # If the PDF_HYPERLINKS tag is set to YES, the LaTeX that is generated # is prepared for conversion to pdf (using ps2pdf). The pdf file will # contain links (just like the HTML output) instead of page references # This makes the output suitable for online browsing using a pdf viewer. PDF_HYPERLINKS = YES # If the USE_PDFLATEX tag is set to YES, pdflatex will be used instead of # plain latex in the generated Makefile. Set this option to YES to get a # higher quality PDF documentation. USE_PDFLATEX = YES # If the LATEX_BATCHMODE tag is set to YES, doxygen will add the \\batchmode. # command to the generated LaTeX files. This will instruct LaTeX to keep # running if errors occur, instead of asking the user for help. # This option is also used when generating formulas in HTML. LATEX_BATCHMODE = NO # If LATEX_HIDE_INDICES is set to YES then doxygen will not # include the index chapters (such as File Index, Compound Index, etc.) # in the output. LATEX_HIDE_INDICES = NO # If LATEX_SOURCE_CODE is set to YES then doxygen will include source code with syntax highlighting in the LaTeX output. Note that which sources are shown also depends on other settings such as SOURCE_BROWSER. LATEX_SOURCE_CODE = NO #--------------------------------------------------------------------------- # configuration options related to the RTF output #--------------------------------------------------------------------------- # If the GENERATE_RTF tag is set to YES Doxygen will generate RTF output # The RTF output is optimized for Word 97 and may not look very pretty with # other RTF readers or editors. GENERATE_RTF = NO # The RTF_OUTPUT tag is used to specify where the RTF docs will be put. # If a relative path is entered the value of OUTPUT_DIRECTORY will be # put in front of it. If left blank `rtf' will be used as the default path. RTF_OUTPUT = rtf # If the COMPACT_RTF tag is set to YES Doxygen generates more compact # RTF documents. This may be useful for small projects and may help to # save some trees in general. COMPACT_RTF = NO # If the RTF_HYPERLINKS tag is set to YES, the RTF that is generated # will contain hyperlink fields. The RTF file will # contain links (just like the HTML output) instead of page references. # This makes the output suitable for online browsing using WORD or other # programs which support those fields. # Note: wordpad (write) and others do not support links. RTF_HYPERLINKS = NO # Load stylesheet definitions from file. Syntax is similar to doxygen's # config file, i.e. a series of assignments. You only have to provide # replacements, missing definitions are set to their default value. RTF_STYLESHEET_FILE = # Set optional variables used in the generation of an rtf document. # Syntax is similar to doxygen's config file. RTF_EXTENSIONS_FILE = #--------------------------------------------------------------------------- # configuration options related to the man page output #--------------------------------------------------------------------------- # If the GENERATE_MAN tag is set to YES (the default) Doxygen will # generate man pages GENERATE_MAN = NO # The MAN_OUTPUT tag is used to specify where the man pages will be put. # If a relative path is entered the value of OUTPUT_DIRECTORY will be # put in front of it. If left blank `man' will be used as the default path. MAN_OUTPUT = man # The MAN_EXTENSION tag determines the extension that is added to # the generated man pages (default is the subroutine's section .3) MAN_EXTENSION = .3 # If the MAN_LINKS tag is set to YES and Doxygen generates man output, # then it will generate one additional man file for each entity # documented in the real man page(s). These additional files # only source the real man page, but without them the man command # would be unable to find the correct page. The default is NO. MAN_LINKS = NO #--------------------------------------------------------------------------- # configuration options related to the XML output #--------------------------------------------------------------------------- # If the GENERATE_XML tag is set to YES Doxygen will # generate an XML file that captures the structure of # the code including all documentation. GENERATE_XML = NO # The XML_OUTPUT tag is used to specify where the XML pages will be put. # If a relative path is entered the value of OUTPUT_DIRECTORY will be # put in front of it. If left blank `xml' will be used as the default path. XML_OUTPUT = xml # The XML_SCHEMA tag can be used to specify an XML schema, # which can be used by a validating XML parser to check the # syntax of the XML files. XML_SCHEMA = # The XML_DTD tag can be used to specify an XML DTD, # which can be used by a validating XML parser to check the # syntax of the XML files. XML_DTD = # If the XML_PROGRAMLISTING tag is set to YES Doxygen will # dump the program listings (including syntax highlighting # and cross-referencing information) to the XML output. Note that # enabling this will significantly increase the size of the XML output. XML_PROGRAMLISTING = YES #--------------------------------------------------------------------------- # configuration options for the AutoGen Definitions output #--------------------------------------------------------------------------- # If the GENERATE_AUTOGEN_DEF tag is set to YES Doxygen will # generate an AutoGen Definitions (see autogen.sf.net) file # that captures the structure of the code including all # documentation. Note that this feature is still experimental # and incomplete at the moment. GENERATE_AUTOGEN_DEF = NO #--------------------------------------------------------------------------- # configuration options related to the Perl module output #--------------------------------------------------------------------------- # If the GENERATE_PERLMOD tag is set to YES Doxygen will # generate a Perl module file that captures the structure of # the code including all documentation. Note that this # feature is still experimental and incomplete at the # moment. GENERATE_PERLMOD = NO # If the PERLMOD_LATEX tag is set to YES Doxygen will generate # the necessary Makefile rules, Perl scripts and LaTeX code to be able # to generate PDF and DVI output from the Perl module output. PERLMOD_LATEX = NO # If the PERLMOD_PRETTY tag is set to YES the Perl module output will be # nicely formatted so it can be parsed by a human reader. # This is useful # if you want to understand what is going on. # On the other hand, if this # tag is set to NO the size of the Perl module output will be much smaller # and Perl will parse it just the same. PERLMOD_PRETTY = YES # The names of the make variables in the generated doxyrules.make file # are prefixed with the string contained in PERLMOD_MAKEVAR_PREFIX. # This is useful so different doxyrules.make files included by the same # Makefile don't overwrite each other's variables. PERLMOD_MAKEVAR_PREFIX = #--------------------------------------------------------------------------- # Configuration options related to the preprocessor #--------------------------------------------------------------------------- # If the ENABLE_PREPROCESSING tag is set to YES (the default) Doxygen will # evaluate all C-preprocessor directives found in the sources and include # files. ENABLE_PREPROCESSING = YES # If the MACRO_EXPANSION tag is set to YES Doxygen will expand all macro # names in the source code. If set to NO (the default) only conditional # compilation will be performed. Macro expansion can be done in a controlled # way by setting EXPAND_ONLY_PREDEF to YES. MACRO_EXPANSION = NO # If the EXPAND_ONLY_PREDEF and MACRO_EXPANSION tags are both set to YES # then the macro expansion is limited to the macros specified with the # PREDEFINED and EXPAND_AS_DEFINED tags. EXPAND_ONLY_PREDEF = NO # If the SEARCH_INCLUDES tag is set to YES (the default) the includes files # in the INCLUDE_PATH (see below) will be search if a #include is found. SEARCH_INCLUDES = YES # The INCLUDE_PATH tag can be used to specify one or more directories that # contain include files that are not input files but should be processed by # the preprocessor. INCLUDE_PATH = # You can use the INCLUDE_FILE_PATTERNS tag to specify one or more wildcard # patterns (like *.h and *.hpp) to filter out the header-files in the # directories. If left blank, the patterns specified with FILE_PATTERNS will # be used. INCLUDE_FILE_PATTERNS = # The PREDEFINED tag can be used to specify one or more macro names that # are defined before the preprocessor is started (similar to the -D option of # gcc). The argument of the tag is a list of macros of the form: name # or name=definition (no spaces). If the definition and the = are # omitted =1 is assumed. To prevent a macro definition from being # undefined via #undef or recursively expanded use the := operator # instead of the = operator. PREDEFINED = # If the MACRO_EXPANSION and EXPAND_ONLY_PREDEF tags are set to YES then # this tag can be used to specify a list of macro names that should be expanded. # The macro definition that is found in the sources will be used. # Use the PREDEFINED tag if you want to use a different macro definition. EXPAND_AS_DEFINED = # If the SKIP_FUNCTION_MACROS tag is set to YES (the default) then # doxygen's preprocessor will remove all function-like macros that are alone # on a line, have an all uppercase name, and do not end with a semicolon. Such # function macros are typically used for boiler-plate code, and will confuse # the parser if not removed. SKIP_FUNCTION_MACROS = YES #--------------------------------------------------------------------------- # Configuration::additions related to external references #--------------------------------------------------------------------------- # The TAGFILES option can be used to specify one or more tagfiles. # Optionally an initial location of the external documentation # can be added for each tagfile. The format of a tag file without # this location is as follows: # # TAGFILES = file1 file2 ... # Adding location for the tag files is done as follows: # # TAGFILES = file1=loc1 "file2 = loc2" ... # where "loc1" and "loc2" can be relative or absolute paths or # URLs. If a location is present for each tag, the installdox tool # does not have to be run to correct the links. # Note that each tag file must have a unique name # (where the name does NOT include the path) # If a tag file is not located in the directory in which doxygen # is run, you must also specify the path to the tagfile here. TAGFILES = # When a file name is specified after GENERATE_TAGFILE, doxygen will create # a tag file that is based on the input files it reads. GENERATE_TAGFILE = # If the ALLEXTERNALS tag is set to YES all external classes will be listed # in the class index. If set to NO only the inherited external classes # will be listed. ALLEXTERNALS = NO # If the EXTERNAL_GROUPS tag is set to YES all external groups will be listed # in the modules index. If set to NO, only the current project's groups will # be listed. EXTERNAL_GROUPS = YES # The PERL_PATH should be the absolute path and name of the perl script # interpreter (i.e. the result of `which perl'). PERL_PATH = /usr/bin/perl #--------------------------------------------------------------------------- # Configuration options related to the dot tool #--------------------------------------------------------------------------- # If the CLASS_DIAGRAMS tag is set to YES (the default) Doxygen will # generate a inheritance diagram (in HTML, RTF and LaTeX) for classes with base # or super classes. Setting the tag to NO turns the diagrams off. Note that # this option is superseded by the HAVE_DOT option below. This is only a # fallback. It is recommended to install and use dot, since it yields more # powerful graphs. CLASS_DIAGRAMS = YES # You can define message sequence charts within doxygen comments using the \msc # command. Doxygen will then run the mscgen tool (see # http://www.mcternan.me.uk/mscgen/) to produce the chart and insert it in the # documentation. The MSCGEN_PATH tag allows you to specify the directory where # the mscgen tool resides. If left empty the tool is assumed to be found in the # default search path. MSCGEN_PATH = # If set to YES, the inheritance and collaboration graphs will hide # inheritance and usage relations if the target is undocumented # or is not a class. HIDE_UNDOC_RELATIONS = YES # If you set the HAVE_DOT tag to YES then doxygen will assume the dot tool is # available from the path. This tool is part of Graphviz, a graph visualization # toolkit from AT&T and Lucent Bell Labs. The other options in this section # have no effect if this option is set to NO (the default) HAVE_DOT = NO # By default doxygen will write a font called FreeSans.ttf to the output # directory and reference it in all dot files that doxygen generates. This # font does not include all possible unicode characters however, so when you need # these (or just want a differently looking font) you can specify the font name # using DOT_FONTNAME. You need need to make sure dot is able to find the font, # which can be done by putting it in a standard location or by setting the # DOTFONTPATH environment variable or by setting DOT_FONTPATH to the directory # containing the font. DOT_FONTNAME = FreeSans # The DOT_FONTSIZE tag can be used to set the size of the font of dot graphs. # The default size is 10pt. DOT_FONTSIZE = 10 # By default doxygen will tell dot to use the output directory to look for the # FreeSans.ttf font (which doxygen will put there itself). If you specify a # different font using DOT_FONTNAME you can set the path where dot # can find it using this tag. DOT_FONTPATH = # If the CLASS_GRAPH and HAVE_DOT tags are set to YES then doxygen # will generate a graph for each documented class showing the direct and # indirect inheritance relations. Setting this tag to YES will force the # the CLASS_DIAGRAMS tag to NO. CLASS_GRAPH = YES # If the COLLABORATION_GRAPH and HAVE_DOT tags are set to YES then doxygen # will generate a graph for each documented class showing the direct and # indirect implementation dependencies (inheritance, containment, and # class references variables) of the class with other documented classes. COLLABORATION_GRAPH = YES # If the GROUP_GRAPHS and HAVE_DOT tags are set to YES then doxygen # will generate a graph for groups, showing the direct groups dependencies GROUP_GRAPHS = YES # If the UML_LOOK tag is set to YES doxygen will generate inheritance and # collaboration diagrams in a style similar to the OMG's Unified Modeling # Language. UML_LOOK = NO # If set to YES, the inheritance and collaboration graphs will show the # relations between templates and their instances. TEMPLATE_RELATIONS = NO # If the ENABLE_PREPROCESSING, SEARCH_INCLUDES, INCLUDE_GRAPH, and HAVE_DOT # tags are set to YES then doxygen will generate a graph for each documented # file showing the direct and indirect include dependencies of the file with # other documented files. INCLUDE_GRAPH = YES # If the ENABLE_PREPROCESSING, SEARCH_INCLUDES, INCLUDED_BY_GRAPH, and # HAVE_DOT tags are set to YES then doxygen will generate a graph for each # documented header file showing the documented files that directly or # indirectly include this file. INCLUDED_BY_GRAPH = YES # If the CALL_GRAPH and HAVE_DOT options are set to YES then # doxygen will generate a call dependency graph for every global function # or class method. Note that enabling this option will significantly increase # the time of a run. So in most cases it will be better to enable call graphs # for selected functions only using the \callgraph command. CALL_GRAPH = NO # If the CALLER_GRAPH and HAVE_DOT tags are set to YES then # doxygen will generate a caller dependency graph for every global function # or class method. Note that enabling this option will significantly increase # the time of a run. So in most cases it will be better to enable caller # graphs for selected functions only using the \callergraph command. CALLER_GRAPH = NO # If the GRAPHICAL_HIERARCHY and HAVE_DOT tags are set to YES then doxygen # will graphical hierarchy of all classes instead of a textual one. GRAPHICAL_HIERARCHY = YES # If the DIRECTORY_GRAPH, SHOW_DIRECTORIES and HAVE_DOT tags are set to YES # then doxygen will show the dependencies a directory has on other directories # in a graphical way. The dependency relations are determined by the #include # relations between the files in the directories. DIRECTORY_GRAPH = YES # The DOT_IMAGE_FORMAT tag can be used to set the image format of the images # generated by dot. Possible values are png, jpg, or gif # If left blank png will be used. DOT_IMAGE_FORMAT = png # The tag DOT_PATH can be used to specify the path where the dot tool can be # found. If left blank, it is assumed the dot tool can be found in the path. DOT_PATH = # The DOTFILE_DIRS tag can be used to specify one or more directories that # contain dot files that are included in the documentation (see the # \dotfile command). DOTFILE_DIRS = # The DOT_GRAPH_MAX_NODES tag can be used to set the maximum number of # nodes that will be shown in the graph. If the number of nodes in a graph # becomes larger than this value, doxygen will truncate the graph, which is # visualized by representing a node as a red box. Note that doxygen if the # number of direct children of the root node in a graph is already larger than # DOT_GRAPH_MAX_NODES then the graph will not be shown at all. Also note # that the size of a graph can be further restricted by MAX_DOT_GRAPH_DEPTH. DOT_GRAPH_MAX_NODES = 50 # The MAX_DOT_GRAPH_DEPTH tag can be used to set the maximum depth of the # graphs generated by dot. A depth value of 3 means that only nodes reachable # from the root by following a path via at most 3 edges will be shown. Nodes # that lay further from the root node will be omitted. Note that setting this # option to 1 or 2 may greatly reduce the computation time needed for large # code bases. Also note that the size of a graph can be further restricted by # DOT_GRAPH_MAX_NODES. Using a depth of 0 means no depth restriction. MAX_DOT_GRAPH_DEPTH = 0 # Set the DOT_TRANSPARENT tag to YES to generate images with a transparent # background. This is disabled by default, because dot on Windows does not # seem to support this out of the box. Warning: Depending on the platform used, # enabling this option may lead to badly anti-aliased labels on the edges of # a graph (i.e. they become hard to read). DOT_TRANSPARENT = NO # Set the DOT_MULTI_TARGETS tag to YES allow dot to generate multiple output # files in one run (i.e. multiple -o and -T options on the command line). This # makes dot run faster, but since only newer versions of dot (>1.8.10) # support this, this feature is disabled by default. DOT_MULTI_TARGETS = YES # If the GENERATE_LEGEND tag is set to YES (the default) Doxygen will # generate a legend page explaining the meaning of the various boxes and # arrows in the dot generated graphs. GENERATE_LEGEND = YES # If the DOT_CLEANUP tag is set to YES (the default) Doxygen will # remove the intermediate dot files that are used to generate # the various graphs. DOT_CLEANUP = YES qdjango-0.6.2/doc/database.doc000066400000000000000000000051121261212605400161400ustar00rootroot00000000000000/* * Copyright (C) 2010-2015 Jeremy Lainé * Contact: https://github.com/jlaine/qdjango * * This file is part of the QDjango Library. * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * This library 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 * Lesser General Public License for more details. */ /*! \defgroup Database \brief Object Relation Mapper (ORM) QDjango's Object Relation Mapper (ORM) strives to be both powerful and simple to use. Where possible it tries to follow django's ORM API, with a similar lazy queryset mechanism. The object relation mapper builds upon Qt's Meta-Object System, so if you are familiar with Qt, you should feel right at home. Features include: \li support for a wide range of database backends thanks to QtSql \li creating and registering database models is easy using Qt's property system \li performing queries using querysets \li QDjango can create and drop database tables and indices for registered models \li thread-aware access to the database \page database Database configuration \section setup Setting the database The first step is to open the database using QSqlDatabase::addDatabase(), for instance for an in-memory SQLite database: \code QSqlDatabase db = QSqlDatabase::addDatabase("QSQLITE"); db.setDatabaseName(":memory:"); db.open(); \endcode You should now tell QDjango to use the database you just opened: \code QDjango::setDatabase(db); \endcode \section creating Creating or dropping database tables Once you have set the database and declared all your models (see \ref models), you can ask QDjango to create the database tables for all models: \code QDjango::createTables(); \endcode Conversely, you can ask QDjango to drop the database tables for all models: \code QDjango::dropTables(); \endcode \section threading Threading support Internally, QDjango calls the QDjango::database() method whenever it needs a handle to the database. This method will clone the database connection as needed if it is invoked from a different thread. */ qdjango-0.6.2/doc/http.doc000066400000000000000000000015701261212605400153570ustar00rootroot00000000000000/* * Copyright (C) 2010-2015 Jeremy Lainé * Contact: https://github.com/jlaine/qdjango * * This file is part of the QDjango Library. * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * This library 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 * Lesser General Public License for more details. */ /*! \defgroup Http \brief HTTP request and response framework QDjango's HTTP request and response framework enables you to write web web applications and deploy them as FastCGI applications or standalone HTTP servers. */ qdjango-0.6.2/doc/index.doc000066400000000000000000000020521261212605400155030ustar00rootroot00000000000000/* * Copyright (C) 2010-2015 Jeremy Lainé * Contact: https://github.com/jlaine/qdjango * * This file is part of the QDjango Library. * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * This library 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 * Lesser General Public License for more details. */ /*! \mainpage QDjango is a web framework written in C++ and built on top of the Qt library (versions 4 or 5). Where possible it tries to follow django's API, hence its name. It is released under the terms of the GNU Lesser General Public License, version 2.1 or later. \sa Database \sa Http */ qdjango-0.6.2/doc/models.doc000066400000000000000000000073071261212605400156670ustar00rootroot00000000000000/* * Copyright (C) 2010-2015 Jeremy Lainé * Contact: https://github.com/jlaine/qdjango * * This file is part of the QDjango Library. * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * This library 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 * Lesser General Public License for more details. */ /*! \page models Database models Database models are usually created by subclassing the QDjangoModel class. The following example defines a \c User model suitable for storing basic account information, and illustrate different types of queries on this model. \section declaring Declaring your model To declare your model, subclass the QDjangoModel class, and define a property using the Q_PROPERTY macro for each database field. You can provide additional information about a field using the Q_CLASSINFO macro: \li \c max_length : the maximum length of the field (used when creating the database table) \li \c primary_key : if set to 'true', this field will be used as the primary key. If no primary key is explicitly defined, an auto-increment integer field will be added. \code #include "QDjangoModel.h" class User : public QDjangoModel { Q_OBJECT Q_PROPERTY(QString username READ username WRITE setUsername) Q_PROPERTY(QString password READ password WRITE setPassword) Q_CLASSINFO("username", "max_length=255") Q_CLASSINFO("password", "max_length=128") public: QString username() const; void setUsername(const QString &username); QString password() const; void setPassword(const QString &password); private: QString m_username; QString m_password; }; \endcode \section implementing Implementing your model \code QString User::username() const { return m_username; } void User::setUsername(const QString &username) { m_username = username; } QString User::password() const { return m_password; } void User::setPassword(const QString &password) { m_password = password; } \endcode \section registering Registering and using your model To make your model available for database operations, you should now register your model using: \code QDjango::registerModel(); \endcode Once you have set the database (see \ref database), you will now be able to create model instances and save them to the database: \code User *user = new User; user->setUsername("someuser"); user->setPassword("somepassword"); user->save(); \endcode .. or remove them from the database: \code user->remove(); \endcode You can also perform operations such as filtering or retrieving model instances as described in \ref queries. \section qobject Using QDjango without QDjangoModel Although it is recommended you make your models inherit QDjangoModel, it is not strictly necessary. QDjango can in fact handle any QObject-derived class, but you will lose some of the syntactic sugar. If for instance you defined a \c SomeObject class which inherits QObject, you can write: \code QDjangoMetaModel meta = QDjango::registerModel(); // prepare a SomeObject instance SomeObject *obj = new SomeObject; obj->setSomeProperty("some value"); obj->setOtherProperty("other value"); // save the object meta.save(obj); // remove the object from database meta.remove(obj); \endcode */ qdjango-0.6.2/doc/queries.doc000066400000000000000000000075241261212605400160620ustar00rootroot00000000000000/* * Copyright (C) 2010-2015 Jeremy Lainé * Contact: https://github.com/jlaine/qdjango * * This file is part of the QDjango Library. * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * This library 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 * Lesser General Public License for more details. */ /*! \page queries Making queries The QDjango object relational mapper (ORM) supports the concept of querysets, borrowed from django's ORM. A queryset is a collection of database objects which match a certain number of user-specified conditions. You can learn more about querysets by reading the QDjangoQuerySet template class documentation. \section creating-queries Creating and filtering querysets Before you can start using querysets, you need to declare your database models as described in \ref models. The most basic queryset matches all the objects for a given model. \code // all users QDjangoQuerySet users; \endcode You can use the QDjangoQuerySet::filter() and QDjangoQuerySet::exclude() methods to add filtering conditions to a querset: \code // find all users whose password is "foo" and whose username is not "bar" QDjangoQuerySet someUsers; someUsers = users.filter(QDjangoWhere("password", QDjangoWhere::Equals, "foo") && QDjangoWhere("username", QDjangoWhere::NotEquals, "bar")); // find all users whose username is "foo" or "bar" someUsers = users.filter(QDjangoWhere("username", QDjangoWhere::Equals, "foo") || QDjangoWhere("username", QDjangoWhere::Equals, "bar")); // find all users whose username starts with "f": someUsers = users.filter(QDjangoWhere("username", QDjangoWhere::StartsWith, "f")); \endcode You can also use the QDjangoQuerySet::limit() method to limit the number of returned rows: \code // limit number of results someUsers = users.limit(0, 100); \endcode \section iterating-queries Iterating over results The easiest way to iterate over results is to use Qt's foreach keyword: \code // iterate over matching users foreach (const User &user, someUsers) { qDebug() << "found user" << user.username; } \endcode Another way of iterating over results is to run over model instances using the QDjangoQuerySet::size() and QDjangoQuerySet::at() methods: \code // iterate over matching users User user; for (int i = 0; i < someUsers.size(); ++i) { if (someUsers.at(i, &user)) { qDebug() << "found user" << user.username; } } \endcode It is also possible to retrieve field data without creating model instances using the QDjangoQuerySet::values() and QDjangoQuerySet::valuesList() methods: \code // retrieve usernames and passwords for matching users as maps QList propertyMaps = someUsers.values(QStringList() << "username" << "password"); foreach (const QVariantMap &propertyMap, propertyMaps) { qDebug() << "username" << propertyList["username"]; qDebug() << "password" << propertyList["password"]; } // retrieve usernames and passwords for matching users as lists QList propertyLists = someUsers.valuesList(QStringList() << "username" << "password"); foreach (const QVariantList &propertyList, propertyLists) { qDebug() << "username" << propertyList[0]; qDebug() << "password" << propertyList[1]; } \endcode \section other-queries Other operations \code // count matching users without retrieving their data int numberOfUsers = someUsers.count(); // delete all the users in the queryset someUsers.remove(); \endcode */ qdjango-0.6.2/examples/000077500000000000000000000000001261212605400147575ustar00rootroot00000000000000qdjango-0.6.2/examples/examples.pro000066400000000000000000000000511261212605400173130ustar00rootroot00000000000000TEMPLATE = subdirs SUBDIRS = http-server qdjango-0.6.2/examples/http-server/000077500000000000000000000000001261212605400172425ustar00rootroot00000000000000qdjango-0.6.2/examples/http-server/base.css000066400000000000000000000033011261212605400206630ustar00rootroot00000000000000body { font-family: "Lucida Grande","DejaVu Sans","Bitstream Vera Sans",Verdana,Arial,sans-serif; font-size 12px; margin: 0; padding: 0; } a:link, a:visited { color: #5B80B2; text-decoration: none; } h1 { color: #666666; font-size: 18px; margin: 0 0 0.2em; padding: 0 6px 0 0; } input[type="text"], input[type="password"], textarea, select { border: 1px solid #CCCCCC; } table { border-collapse: collapse; } td, th { font-size: 11px; line-height: 13px; border-bottom: 1px solid #eee; vertical-align: top; padding: 5px; text-align: left; } th { color: #666; padding: 2px 5px; font-weight: bold; background: #e1e1e1; background-image: linear-gradient(bottom, rgb(255,255,255) 10%, rgb(245,245,245) 100%); background-image: -moz-linear-gradient(top, rgb(255,255,255) 10%, rgb(245,245,245) 100%); background-image: -webkit-linear-gradient(top, rgb(255,255,255) 10%, rgb(245,245,245) 100%); border-left: 1px solid #ddd; border-bottom: 1px solid #ddd; } #header { background: none repeat scroll 0 0 #417690; color: #FFFFCC; overflow: hidden; } #header h1 { color: #F4F379; font-size: 18px; font-weight: normal; margin: 8px 0; padding: 0 10px; } #content { margin: 10px 15px; } .breadcrumbs { background: white; border-bottom: 1px solid #CCCCCC; border-top: 1px solid white; color: #999999; font-size: 11px; padding: 2px 8px 3px; text-align: left; } .module { background: none repeat scroll 0 0 white; border: 1px solid #CCCCCC; margin-bottom: 5px; } .aligned label { display: inline-block; padding: 3px 10px 0 0; width: 8em; } qdjango-0.6.2/examples/http-server/http-server.cpp000066400000000000000000000416041261212605400222360ustar00rootroot00000000000000/* * Copyright (C) 2010-2015 Jeremy Lainé * Contact: https://github.com/jlaine/qdjango * * This file is part of the QDjango Library. * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * This library 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 * Lesser General Public License for more details. */ #include #include #include #include #include #include #include "QDjango.h" #include "QDjangoQuerySet.h" #include "QDjangoFastCgiServer.h" #include "QDjangoHttpController.h" #include "QDjangoHttpRequest.h" #include "QDjangoHttpResponse.h" #include "QDjangoHttpServer.h" #include "QDjangoUrlResolver.h" #include "auth-models.h" #include "http-server.h" class ModelAdminFetcher { public: virtual QDjangoModel *createObject() const = 0; virtual QVariantMap dumpObject(const QObject *object) const = 0; virtual QDjangoModel *getObject(const QString& objectId) const = 0; virtual QVariantList listObjects(const QList &listFields) const = 0; virtual QString modelName() const = 0; }; template class ModelAdminFetcherImpl : public ModelAdminFetcher { public: QDjangoModel *createObject() const { return new T; } QVariantMap dumpObject(const QObject *object) const { const QMetaObject *metaObject = object->metaObject(); QVariantMap props; props.insert("pk", object->property("pk")); for (int i = metaObject->propertyOffset(); i < metaObject->propertyCount(); ++i) { const char *key = metaObject->property(i).name(); props.insert(key, object->property(key)); } return props; } QDjangoModel *getObject(const QString& objectId) const { return QDjangoQuerySet().get(QDjangoWhere("pk", QDjangoWhere::Equals, objectId)); } QVariantList listObjects(const QList &listFields) const { QVariantList objectList; QDjangoQuerySet objects; foreach (const T &obj, objects) { QVariantMap dump = dumpObject(&obj); // get ordered list of properties to show QVariantList propList; foreach (const QByteArray &key, listFields) { propList << dump.value(key); } dump.insert("value_list", propList); objectList << dump; } return objectList; } QString modelName() const { return QString::fromLatin1(T::staticMetaObject.className()).toLower(); } }; static QVariant evaluate(const QString &input, const QVariantMap &context) { const QStringList bits = input.split("."); QVariant value = context; foreach (const QString &bit, bits) { value = value.toMap().value(bit); } //qDebug("evaluate(%s): %s", qPrintable(input), qPrintable(value.toString())); return value; } static QString substitute(const QString &input, const QVariantMap &context) { QRegExp valRx("\\{\\{ +([a-z_\\.]+) +\\}\\}"); QString output; int pos = 0; int lastPos = 0; while ((pos = valRx.indexIn(input, lastPos)) != -1) { output += input.mid(lastPos, pos - lastPos); lastPos = pos + valRx.matchedLength(); output += evaluate(valRx.cap(1), context).toString(); } output += input.mid(lastPos); return output; } typedef QPair Node; static QList tokenize(const QString &input) { QList output; QRegExp tagRx("\\{% +([^%]+) +%\\}"); int pos = 0; int lastPos = 0; while ((pos = tagRx.indexIn(input, lastPos)) != -1) { if (pos > lastPos) output << qMakePair(false, input.mid(lastPos, pos - lastPos)); lastPos = pos + tagRx.matchedLength(); output << qMakePair(true, tagRx.cap(1)); } output << qMakePair(false, input.mid(lastPos)); return output; } static int findBalancing(const QList nodes, const QString &closeTag, int pos, int *elsePos = 0) { const QString openTag = nodes[pos].second.split(" ").first(); int level = 0; if (elsePos) *elsePos = -1; for (pos = pos + 1; pos < nodes.size(); ++pos) { if (nodes[pos].first && nodes[pos].second.startsWith(openTag)) { level++; } else if (nodes[pos].first && nodes[pos].second == closeTag) { if (!level) return pos; level--; } else if (!level && nodes[pos].second == "else") { if (elsePos) *elsePos = pos; } } qWarning("Could not find %s tag", qPrintable(closeTag)); return -1; } QString renderTemplate(const QString &name, const QVariantMap &context); static QString render(const QList &nodes, const QVariantMap &context) { QRegExp forRx("for ([a-z_]+) in ([a-z_\\.]+)"); QRegExp includeRx("include \"([^\"]+)\""); QString output; for (int i = 0; i < nodes.size(); ++i) { const Node &node = nodes[i]; if (node.first) { //qDebug("Processing tag %s", qPrintable(node.second)); QStringList tagArgs = node.second.split(" "); const QString tagName = tagArgs.takeFirst(); if (node.second == "comment") { const int endPos = findBalancing(nodes, "endcomment", i++); if (endPos < 0) return output; i = endPos; } else if (forRx.exactMatch(node.second)) { const int endPos = findBalancing(nodes, "endfor", i++); if (endPos < 0) return output; const QVariantList list = evaluate(forRx.cap(2), context).toList(); QVariantMap forLoop; int counter0 = 0; foreach (const QVariant &val, list) { forLoop.insert("counter", counter0 + 1); forLoop.insert("counter0", counter0); if (!counter0) forLoop.insert("first", true); QVariantMap subContext = context; subContext.insert(forRx.cap(1), val); subContext.insert("forloop", forLoop); output += render(nodes.mid(i, endPos - i), subContext); counter0++; } i = endPos; } else if (tagName == "if") { int elsePos = -1; const int endPos = findBalancing(nodes, "endif", i++, &elsePos); if (endPos < 0) return output; bool isTrue = false; QRegExp ifRx("if ([a-z_\\.]+) (!=|==) \"([^\"]*)\""); if (ifRx.exactMatch(node.second)) { const QVariant value = evaluate(ifRx.cap(1), context); const QString op = ifRx.cap(2); const QString opValue = ifRx.cap(3); if ((op == "==" && value.toString() == opValue) || (op == "!=" && value.toString() != opValue)) { isTrue = true; } } else if (tagArgs.size() == 1) { const QVariant value = evaluate(tagArgs[0], context); if (value.toList().size() || value.toMap().size() || value.toString().size()) isTrue = true; } if (isTrue) { output += render(nodes.mid(i, (elsePos > 0 ? elsePos : endPos) - i), context); } else if (elsePos > 0) { output += render(nodes.mid(elsePos, endPos - elsePos), context); } i = endPos; } else if (includeRx.exactMatch(node.second)) { output += renderTemplate(":/templates/" + includeRx.cap(1), context); } } else { output += substitute(node.second, context); } } return output; } QString renderTemplate(const QString &name, const QVariantMap &context) { QFile templ(name); if (templ.open(QIODevice::ReadOnly)) { const QString data = QString::fromUtf8(templ.readAll()); return render(tokenize(data), context); } return QString(); } static QDjangoHttpResponse *renderToResponse(const QDjangoHttpRequest &request, const QString &name, const QVariantMap &context) { Q_UNUSED(request); QDjangoHttpResponse *response = new QDjangoHttpResponse; response->setHeader("Content-Type", "text/html; charset=utf-8"); response->setBody(renderTemplate(name, context).toUtf8()); return response; } class ModelAdminPrivate { public: QDjangoHttpResponse* redirectHome(const QDjangoHttpRequest &request) { return QDjangoHttpController::serveRedirect(request, QUrl("/" + modelFetcher->modelName() + "/")); } QList changeFields; QList listFields; ModelAdminFetcher *modelFetcher; QDjangoUrlResolver *urlResolver; }; ModelAdmin::ModelAdmin(ModelAdminFetcher *fetcher, QObject *parent) : QObject(parent) { d = new ModelAdminPrivate; d->modelFetcher = fetcher; d->urlResolver = new QDjangoUrlResolver(this); d->urlResolver->set(QRegExp("^$"), this, "changeList"); d->urlResolver->set(QRegExp("^add/$"), this, "addForm"); d->urlResolver->set(QRegExp("^([0-9]+)/"), this, "changeForm"); d->urlResolver->set(QRegExp("^([0-9]+)/delete/"), this, "deleteForm"); } ModelAdmin::~ModelAdmin() { delete d; } QList ModelAdmin::changeFields() const { return d->changeFields; } void ModelAdmin::setChangeFields(const QList fields) { d->changeFields = fields; } QList ModelAdmin::listFields() const { return d->listFields; } void ModelAdmin::setListFields(const QList fields) { d->listFields = fields; } QDjangoHttpResponse* ModelAdmin::addForm(const QDjangoHttpRequest &request) { const QString modelName = d->modelFetcher->modelName(); // collect fields QVariantList fieldList; foreach (const QByteArray &key, d->changeFields) { QVariantMap props; props.insert("key", key); props.insert("name", QByteArray(key).replace("_", " ")); fieldList << props; } if (request.method() == "POST") { QDjangoModel *obj = d->modelFetcher->createObject(); foreach (const QByteArray &key, d->changeFields) obj->setProperty(key, request.post(key)); obj->save(); delete obj; return d->redirectHome(request); } else { QVariantMap context; context.insert("model_name", modelName); context.insert("field_list", fieldList); context.insert("title", QString("Add %1").arg(modelName)); return renderToResponse(request, ":/templates/change_form.html", context); } } QDjangoHttpResponse* ModelAdmin::changeForm(const QDjangoHttpRequest &request, const QString &objectId) { QDjangoModel *original = d->modelFetcher->getObject(objectId); if (!original) return QDjangoHttpController::serveNotFound(request); // collect fields QVariantList fieldList; foreach (const QByteArray &key, d->changeFields) { QVariantMap props; props.insert("key", key); props.insert("name", QByteArray(key).replace("_", " ")); props.insert("value", original->property(key)); fieldList << props; } if (request.method() == "POST") { foreach (const QByteArray &key, d->changeFields) original->setProperty(key, request.post(key)); original->save(); return d->redirectHome(request); } else { const QString modelName = d->modelFetcher->modelName(); QVariantMap context; context.insert("model_name", modelName); context.insert("field_list", fieldList); context.insert("original", d->modelFetcher->dumpObject(original)); context.insert("title", QString("Change %1").arg(modelName)); return renderToResponse(request, ":/templates/change_form.html", context); } } QDjangoHttpResponse* ModelAdmin::changeList(const QDjangoHttpRequest &request) { QVariantList objectList = d->modelFetcher->listObjects(d->listFields); QVariantList fieldList; foreach (const QByteArray &key, d->listFields) { QVariantMap props; props.insert("key", key); props.insert("name", QByteArray(key).replace("_", " ")); fieldList << props; } const QString modelName = d->modelFetcher->modelName(); QVariantMap context; context.insert("title", QString("Select %1 to change").arg(modelName)); context.insert("add_link", QString("Add %1").arg(modelName)); context.insert("edit_link", QString("Edit")); context.insert("delete_link", QString("Remove")); context.insert("model_name", modelName); context.insert("field_list", fieldList); context.insert("object_list", objectList); return renderToResponse(request, ":/templates/change_list.html", context); } QDjangoHttpResponse* ModelAdmin::deleteForm(const QDjangoHttpRequest &request, const QString &objectId) { QDjangoModel *original = d->modelFetcher->getObject(objectId); if (!original) return QDjangoHttpController::serveNotFound(request); if (request.method() == "POST") { original->remove(); return d->redirectHome(request); } else { const QString modelName = d->modelFetcher->modelName(); QVariantMap context; context.insert("model_name", modelName); context.insert("original", d->modelFetcher->dumpObject(original)); context.insert("title", "Are you sure?"); return renderToResponse(request, ":/templates/delete_confirmation.html", context); } } QDjangoUrlResolver *ModelAdmin::urls() const { return d->urlResolver; } class AdminControllerPrivate { public: }; AdminController::AdminController(QObject *parent) : QObject(parent) , d(new AdminControllerPrivate) { const QString databaseName("test.db"); /* Open database */ QSqlDatabase db = QSqlDatabase::addDatabase("QSQLITE"); db.setDatabaseName(databaseName); if (!db.open()) { qWarning("Could not access database '%s'\n", qPrintable(databaseName)); return; } QDjango::setDatabase(db); QDjango::registerModel(); QDjango::registerModel(); QDjango::createTables(); } QDjangoHttpResponse* AdminController::index(const QDjangoHttpRequest &request) { QVariantMap context; context.insert("model_list", QStringList() << "group" << "user"); context.insert("title", "Administration"); return renderToResponse(request, ":/templates/index.html", context); } QDjangoHttpResponse* AdminController::staticFiles(const QDjangoHttpRequest &request, const QString &path) { Q_UNUSED(path); return QDjangoHttpController::serveStatic(request, ":/base.css"); } void usage() { fprintf(stderr, "Usage: command [options]\n\n"); fprintf(stderr, "Available commands:\n"); fprintf(stderr, "runfcgi\n"); fprintf(stderr, "runserver\n"); } void AdminController::setupUrls(QDjangoUrlResolver *urls) { urls->set(QRegExp("^$"), this, "index"); urls->set(QRegExp("^static/admin/(.+)$"), this, "staticFiles"); ModelAdmin *groupAdmin = new ModelAdmin(new ModelAdminFetcherImpl); groupAdmin->setChangeFields(QList() << "name"); groupAdmin->setListFields(QList() << "name"); urls->include(QRegExp("^group/"), groupAdmin->urls()); ModelAdmin *userAdmin = new ModelAdmin(new ModelAdminFetcherImpl); userAdmin->setChangeFields(QList() << "username" << "email" << "first_name" << "last_name"); userAdmin->setListFields(QList() << "username" << "email" << "first_name" << "last_name"); urls->include(QRegExp("^user/"), userAdmin->urls()); } int main(int argc, char* argv[]) { QCoreApplication app(argc, argv); AdminController controller; const quint16 port = 8000; if (argc < 2) { usage(); return EXIT_FAILURE; } QDjangoUrlResolver urls; if (!strcmp(argv[1], "runfcgi")) { QDjangoFastCgiServer *server = new QDjangoFastCgiServer; controller.setupUrls(server->urls()); if (!server->listen(QHostAddress::Any, port)) { qWarning("Could not start listening on port %i", port); return EXIT_FAILURE; } } else if (!strcmp(argv[1], "runserver")) { QDjangoHttpServer *server = new QDjangoHttpServer; controller.setupUrls(server->urls()); if (!server->listen(QHostAddress::Any, port)) { qWarning("Could not start listening on port %i", port); return EXIT_FAILURE; } } else { usage(); return EXIT_FAILURE; } return app.exec(); } qdjango-0.6.2/examples/http-server/http-server.h000066400000000000000000000037041261212605400217020ustar00rootroot00000000000000/* * Copyright (C) 2010-2015 Jeremy Lainé * Contact: https://github.com/jlaine/qdjango * * This file is part of the QDjango Library. * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * This library 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 * Lesser General Public License for more details. */ #include class QDjangoHttpRequest; class QDjangoHttpResponse; class QDjangoUrlResolver; class AdminControllerPrivate; class ModelAdminFetcher; class ModelAdminPrivate; class AdminController : public QObject { Q_OBJECT public: AdminController(QObject* parent = 0); void setupUrls(QDjangoUrlResolver *urls); public slots: QDjangoHttpResponse* index(const QDjangoHttpRequest &request); QDjangoHttpResponse* staticFiles(const QDjangoHttpRequest &request, const QString &path); private: AdminControllerPrivate *d; }; class ModelAdmin : public QObject { Q_OBJECT public: ModelAdmin(ModelAdminFetcher *fetcher, QObject *parent = 0); ~ModelAdmin(); QList changeFields() const; void setChangeFields(const QList fields); QList listFields() const; void setListFields(const QList fields); QDjangoUrlResolver *urls() const; public slots: QDjangoHttpResponse* addForm(const QDjangoHttpRequest &request); QDjangoHttpResponse* changeForm(const QDjangoHttpRequest &request, const QString &objectId); QDjangoHttpResponse* changeList(const QDjangoHttpRequest &request); QDjangoHttpResponse* deleteForm(const QDjangoHttpRequest &request, const QString &objectId); private: ModelAdminPrivate *d; }; qdjango-0.6.2/examples/http-server/http-server.pro000066400000000000000000000005501261212605400222470ustar00rootroot00000000000000include(../../qdjango.pri) QT += network sql TARGET = qdjango-http-server INCLUDEPATH += ../../tests/db $$QDJANGO_INCLUDEPATH LIBS += \ -L../../src/db $$QDJANGO_DB_LIBS \ -L../../src/http $$QDJANGO_HTTP_LIBS RESOURCES += http-server.qrc HEADERS += http-server.h ../../tests/db/auth-models.h SOURCES += http-server.cpp ../../tests/db/auth-models.cpp qdjango-0.6.2/examples/http-server/http-server.qrc000066400000000000000000000005351261212605400222370ustar00rootroot00000000000000 base.css templates/change_form.html templates/change_list.html templates/delete_confirmation.html templates/footer.html templates/header.html templates/index.html qdjango-0.6.2/examples/http-server/templates/000077500000000000000000000000001261212605400212405ustar00rootroot00000000000000qdjango-0.6.2/examples/http-server/templates/base.html000066400000000000000000000000701261212605400230350ustar00rootroot00000000000000{% include "header.html" %} {% include "footer.html" %} qdjango-0.6.2/examples/http-server/templates/change_form.html000066400000000000000000000007561261212605400244060ustar00rootroot00000000000000{% include "header.html" %}
{% for field in field_list %}
{% endfor %}
{% include "footer.html" %} qdjango-0.6.2/examples/http-server/templates/change_list.html000066400000000000000000000014211261212605400244040ustar00rootroot00000000000000{% include "header.html" %}
{% for field in field_list %} {% endfor %} {% for object in object_list %} {% for value in object.value_list %} {% endfor %} {% endfor %}
{{ field.name }}Actions
{% if forloop.counter == "1" %}{{ value }}{% else %}{{ value }}{% endif %} {{ edit_link }} {{ delete_link }}
{% include "footer.html" %} qdjango-0.6.2/examples/http-server/templates/delete_confirmation.html000066400000000000000000000003431261212605400261400ustar00rootroot00000000000000{% include "header.html" %}

Are you sure you want to delete the {{ model_name }} "{{ original.username }}"?

{% include "footer.html" %} qdjango-0.6.2/examples/http-server/templates/footer.html000066400000000000000000000000271261212605400234230ustar00rootroot00000000000000 qdjango-0.6.2/examples/http-server/templates/header.html000066400000000000000000000013771261212605400233660ustar00rootroot00000000000000 {{ title }} | Test application {% comment %} test {% endcomment %}

{{ title }}

qdjango-0.6.2/examples/http-server/templates/index.html000066400000000000000000000006351261212605400232410ustar00rootroot00000000000000{% include "header.html" %}
{% for model in model_list %} {% endfor %}
{{ model }} Add Change
{% include "footer.html" %} qdjango-0.6.2/qdjango.pri000066400000000000000000000016311261212605400153010ustar00rootroot00000000000000# Common definitions QDJANGO_VERSION=0.6.2 # Determine library type (shared or staticlib) isEmpty(QDJANGO_LIBRARY_TYPE) { android { QDJANGO_LIBRARY_TYPE = staticlib } else { QDJANGO_LIBRARY_TYPE = shared } } # Libraries for apps which use QDjango QDJANGO_INCLUDEPATH = $$PWD/src/db $$PWD/src/http QDJANGO_DB_LIBS = -lqdjango-db QDJANGO_HTTP_LIBS = -lqdjango-http contains(QDJANGO_LIBRARY_TYPE,staticlib) { DEFINES += QDJANGO_STATIC } else { # Windows needs the major library version win32 { QDJANGO_DB_LIBS = -lqdjango-db0 QDJANGO_HTTP_LIBS = -lqdjango-http0 } DEFINES += QDJANGO_SHARED } # Installation prefix and library directory isEmpty(PREFIX) { contains(MEEGO_EDITION,harmattan) { PREFIX = /usr } else:unix { PREFIX = /usr/local } else { PREFIX = $$[QT_INSTALL_PREFIX] } } isEmpty(LIBDIR) { LIBDIR=lib } qdjango-0.6.2/qdjango.pro000066400000000000000000000014031261212605400153040ustar00rootroot00000000000000include(qdjango.pri) TEMPLATE = subdirs SUBDIRS = src android { } else { SUBDIRS += tests examples INSTALLS += htmldocs } CONFIG += ordered # Documentation generation docs.commands = cd doc/ && doxygen # Source distribution QDJANGO_ARCHIVE = qdjango-$$QDJANGO_VERSION dist.commands = \ $(DEL_FILE) -r $$QDJANGO_ARCHIVE && \ $(MKDIR) $$QDJANGO_ARCHIVE && \ git archive master | tar -x -C $$QDJANGO_ARCHIVE && \ $(COPY_DIR) doc/html $$QDJANGO_ARCHIVE/doc && \ tar czf $${QDJANGO_ARCHIVE}.tar.gz $$QDJANGO_ARCHIVE && \ $(DEL_FILE) -r $$QDJANGO_ARCHIVE dist.depends = docs # Install rules htmldocs.files = doc/html htmldocs.path = $$PREFIX/share/doc/qdjango htmldocs.CONFIG += no_check_exist directory QMAKE_EXTRA_TARGETS += dist docs qdjango-0.6.2/src/000077500000000000000000000000001261212605400137305ustar00rootroot00000000000000qdjango-0.6.2/src/db/000077500000000000000000000000001261212605400143155ustar00rootroot00000000000000qdjango-0.6.2/src/db/QDjango.cpp000066400000000000000000000224751261212605400163560ustar00rootroot00000000000000/* * Copyright (C) 2010-2015 Jeremy Lainé * Contact: https://github.com/jlaine/qdjango * * This file is part of the QDjango Library. * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * This library 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 * Lesser General Public License for more details. */ #include #include #include #include #include #include #include #include #include #include "QDjango.h" static const char *connectionPrefix = "_qdjango_"; QMap globalMetaModels = QMap(); static QDjangoDatabase *globalDatabase = 0; static QDjangoDatabase::DatabaseType globalDatabaseType = QDjangoDatabase::UnknownDB; static bool globalDebugEnabled = false; /// \cond QDjangoDatabase::QDjangoDatabase(QObject *parent) : QObject(parent), connectionId(0) { } void QDjangoDatabase::threadFinished() { QThread *thread = qobject_cast(sender()); if (!thread) return; // cleanup database connection for the thread QMutexLocker locker(&mutex); disconnect(thread, SIGNAL(finished()), this, SLOT(threadFinished())); const QString connectionName = copies.value(thread).connectionName(); copies.remove(thread); if (connectionName.startsWith(QLatin1String(connectionPrefix))) QSqlDatabase::removeDatabase(connectionName); } static void closeDatabase() { delete globalDatabase; } static QDjangoDatabase::DatabaseType getDatabaseType(QSqlDatabase &db) { const QString driverName = db.driverName(); if (driverName == QLatin1String("QMYSQL") || driverName == QLatin1String("QMYSQL3")) return QDjangoDatabase::MySqlServer; else if (driverName == QLatin1String("QSQLITE") || driverName == QLatin1String("QSQLITE2")) return QDjangoDatabase::SQLite; else if (driverName == QLatin1String("QPSQL")) return QDjangoDatabase::PostgreSQL; else if (driverName == QLatin1String("QODBC")) { QSqlQuery query(db); if (query.exec("SELECT sqlite_version()")) return QDjangoDatabase::SQLite; if (query.exec("SELECT @@version") && query.next() && query.value(0).toString().contains("Microsoft SQL Server")) return QDjangoDatabase::MSSqlServer; if (query.exec("SELECT version()") && query.next()) { if (query.value(0).toString().contains("PostgreSQL")) return QDjangoDatabase::PostgreSQL; else return QDjangoDatabase::MySqlServer; } } return QDjangoDatabase::UnknownDB; } static void initDatabase(QSqlDatabase db) { QDjangoDatabase::DatabaseType databaseType = QDjangoDatabase::databaseType(db); if (databaseType == QDjangoDatabase::SQLite) { // enable foreign key constraint handling QDjangoQuery query(db); query.prepare("PRAGMA foreign_keys=on"); query.exec(); } } QDjangoQuery::QDjangoQuery(QSqlDatabase db) : QSqlQuery(db) { if (QDjangoDatabase::databaseType(db) == QDjangoDatabase::MSSqlServer) { // default to fast-forward cursor setForwardOnly(true); } } void QDjangoQuery::addBindValue(const QVariant &val, QSql::ParamType paramType) { // this hack is required so that we do not store a mix of local // and UTC times if (val.type() == QVariant::DateTime) QSqlQuery::addBindValue(val.toDateTime().toLocalTime(), paramType); else QSqlQuery::addBindValue(val, paramType); } bool QDjangoQuery::exec() { if (globalDebugEnabled) { qDebug() << "SQL query" << lastQuery(); QMapIterator i(boundValues()); while (i.hasNext()) { i.next(); qDebug() << "SQL " << i.key().toLatin1().data() << "=" << i.value().toString().toLatin1().data(); } } if (!QSqlQuery::exec()) { if (globalDebugEnabled) qWarning() << "SQL error" << lastError(); return false; } return true; } bool QDjangoQuery::exec(const QString &query) { if (globalDebugEnabled) qDebug() << "SQL query" << query; if (!QSqlQuery::exec(query)) { if (globalDebugEnabled) qWarning() << "SQL error" << lastError(); return false; } return true; } /// \endcond /*! Returns the database used by QDjango. If you call this method from any thread but the application's main thread, a new connection to the database will be created. The connection will automatically be torn down once the thread finishes. \sa setDatabase() */ QSqlDatabase QDjango::database() { if (!globalDatabase) return QSqlDatabase(); // if we are in the main thread, return reference connection QThread *thread = QThread::currentThread(); if (thread == globalDatabase->thread()) return globalDatabase->reference; // if we have a connection for this thread, return it QMutexLocker locker(&globalDatabase->mutex); if (globalDatabase->copies.contains(thread)) return globalDatabase->copies[thread]; // create a new connection for this thread QObject::connect(thread, SIGNAL(finished()), globalDatabase, SLOT(threadFinished())); QSqlDatabase db = QSqlDatabase::cloneDatabase(globalDatabase->reference, QLatin1String(connectionPrefix) + QString::number(globalDatabase->connectionId++)); db.open(); initDatabase(db); globalDatabase->copies.insert(thread, db); return db; } /*! Sets the database used by QDjango. You must call this method from your application's main thread. \sa database() */ void QDjango::setDatabase(QSqlDatabase database) { globalDatabaseType = getDatabaseType(database); if (globalDatabaseType == QDjangoDatabase::UnknownDB) { qWarning() << "Unsupported database driver" << database.driverName(); } if (!globalDatabase) { globalDatabase = new QDjangoDatabase(); qAddPostRoutine(closeDatabase); } initDatabase(database); globalDatabase->reference = database; } /*! Returns whether debugging information should be printed. \sa setDebugEnabled() */ bool QDjango::isDebugEnabled() { return globalDebugEnabled; } /*! Sets whether debugging information should be printed. \sa isDebugEnabled() */ void QDjango::setDebugEnabled(bool enabled) { globalDebugEnabled = enabled; } static void qdjango_topsort(const QByteArray &modelName, QHash &visited, QStack &stack) { visited[modelName] = true; QDjangoMetaModel model = globalMetaModels[modelName]; foreach (const QByteArray &foreignModel, model.foreignFields().values()) { if (!visited[foreignModel]) qdjango_topsort(foreignModel, visited, stack); } stack.push(model); } static QStack qdjango_sorted_metamodels() { QStack stack; stack.reserve(globalMetaModels.size()); QHash visited; visited.reserve(globalMetaModels.size()); foreach (const QByteArray &model, globalMetaModels.keys()) visited[model] = false; foreach (const QByteArray &model, globalMetaModels.keys()) { if (!visited[model]) qdjango_topsort(model, visited, stack); } return stack; } /*! Creates the database tables for all registered models. \return true if all the tables were created, false otherwise. */ bool QDjango::createTables() { bool result = true; QStack stack = qdjango_sorted_metamodels(); foreach (const QDjangoMetaModel &model, stack) { if (!model.createTable()) result = false; } return result; } /*! Drops the database tables for all registered models. \return true if all the tables were dropped, false otherwise. */ bool QDjango::dropTables() { bool result = true; QStack stack = qdjango_sorted_metamodels(); for (int i = stack.size() - 1; i >= 0; --i) { QDjangoMetaModel model = stack.at(i); if (!model.dropTable()) result = false; } return result; } /*! Returns the QDjangoMetaModel with the given \a name. */ QDjangoMetaModel QDjango::metaModel(const char *name) { if (globalMetaModels.contains(name)) return globalMetaModels.value(name); // otherwise, try to find a model anyway foreach (QByteArray modelName, globalMetaModels.keys()) { if (qstricmp(name, modelName.data()) == 0) return globalMetaModels.value(modelName); } return QDjangoMetaModel(); } QDjangoMetaModel QDjango::registerModel(const QMetaObject *meta) { const QByteArray name = meta->className(); if (!globalMetaModels.contains(name)) globalMetaModels.insert(name, QDjangoMetaModel(meta)); return globalMetaModels[name]; } QDjangoDatabase::DatabaseType QDjangoDatabase::databaseType(const QSqlDatabase &db) { Q_UNUSED(db); return globalDatabaseType; } qdjango-0.6.2/src/db/QDjango.h000066400000000000000000000033271261212605400160160ustar00rootroot00000000000000/* * Copyright (C) 2010-2015 Jeremy Lainé * Contact: https://github.com/jlaine/qdjango * * This file is part of the QDjango Library. * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * This library 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 * Lesser General Public License for more details. */ #ifndef QDJANGO_H #define QDJANGO_H #include "QDjangoMetaModel.h" class QObject; class QSqlDatabase; class QSqlQuery; class QString; /** \brief The QDjango class provides a set of static functions. * * It is used to access registered QDjangoModel classes. * * \ingroup Database */ class QDJANGO_DB_EXPORT QDjango { public: static bool createTables(); static bool dropTables(); static QSqlDatabase database(); static void setDatabase(QSqlDatabase database); static bool isDebugEnabled(); static void setDebugEnabled(bool enabled); template static QDjangoMetaModel registerModel(); private: static QDjangoMetaModel registerModel(const QMetaObject *meta); static QDjangoMetaModel metaModel(const char *name); friend class QDjangoCompiler; friend class QDjangoModel; friend class QDjangoMetaModel; friend class QDjangoQuerySetPrivate; }; /** Register a QDjangoModel class with QDjango. */ template QDjangoMetaModel QDjango::registerModel() { return registerModel(&T::staticMetaObject); } #endif qdjango-0.6.2/src/db/QDjangoMetaModel.cpp000066400000000000000000000653751261212605400201540ustar00rootroot00000000000000/* * Copyright (C) 2010-2015 Jeremy Lainé * Contact: https://github.com/jlaine/qdjango * * This file is part of the QDjango Library. * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * This library 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 * Lesser General Public License for more details. */ #include #include #include #include #include "QDjango.h" #include "QDjangoMetaModel.h" #include "QDjangoQuerySet_p.h" // python-compatible hash static long string_hash(const QString &s) { if (s.isEmpty()) return 0; const QByteArray a = s.toLatin1(); unsigned char *p = (unsigned char *) a.constData(); long x = *p << 7; for (int i = 0; i < a.size(); ++i) x = (1000003*x) ^ *p++; x ^= a.size(); return (x == -1) ? -2 : x; } static long stringlist_hash(const QStringList &l) { long x = 0x345678L; long mult = 1000003L; int len = l.size(); foreach (const QString &s, l) { --len; x = (x ^ string_hash(s)) * mult; mult += (long)(82520L + len + len); } x += 97531L; return (x == -1) ? -2 : x; } // django-compatible digest static QString stringlist_digest(const QStringList &l) { return QString::number(labs(stringlist_hash(l)) % 4294967296UL, 16); } enum ForeignKeyConstraint { NoAction, Restrict, Cascade, SetNull }; class QDjangoMetaFieldPrivate : public QSharedData { public: QDjangoMetaFieldPrivate(); bool autoIncrement; QString db_column; QByteArray foreignModel; bool index; int maxLength; QByteArray name; bool null; QVariant::Type type; bool unique; bool blank; ForeignKeyConstraint deleteConstraint; }; QDjangoMetaFieldPrivate::QDjangoMetaFieldPrivate() : autoIncrement(false) , index(false) , maxLength(0) , null(false) , unique(false) , blank(false) , deleteConstraint(NoAction) { } /*! Constructs a new QDjangoMetaField. */ QDjangoMetaField::QDjangoMetaField() { d = new QDjangoMetaFieldPrivate; } /*! Constructs a copy of \a other. */ QDjangoMetaField::QDjangoMetaField(const QDjangoMetaField &other) : d(other.d) { } /*! Destroys the meta field. */ QDjangoMetaField::~QDjangoMetaField() { } /*! Assigns \a other to this meta field. */ QDjangoMetaField& QDjangoMetaField::operator=(const QDjangoMetaField& other) { d = other.d; return *this; } /*! Returns the database column for this meta field. */ QString QDjangoMetaField::column() const { return d->db_column; } /*! Returns true if this field is nullable. */ bool QDjangoMetaField::isNullable() const { return d->null; } /*! Returns true if this is a valid field. */ bool QDjangoMetaField::isValid() const { return !d->name.isEmpty(); } /*! Returns true if this field is auto incremented. */ bool QDjangoMetaField::isAutoIncrement() const { return d->autoIncrement; } /*! Returns true if this field is unique. */ bool QDjangoMetaField::isUnique() const { return d->unique; } /*! Returns true if this field can be empty. */ bool QDjangoMetaField::isBlank() const { return d->blank; } /*! Returns name of this meta field. */ QString QDjangoMetaField::name() const { return QString::fromLatin1(d->name); } /*! Returns the max length of this field */ int QDjangoMetaField::maxLength() const { return d->maxLength; } /*! Transforms the given field value for database storage. */ QVariant QDjangoMetaField::toDatabase(const QVariant &value) const { if (d->type == QVariant::String && !d->null && value.isNull()) return QLatin1String(""); else if (!d->foreignModel.isEmpty() && d->type == QVariant::Int && d->null && !value.toInt()) { // store 0 foreign key as NULL if the field is NULL return QVariant(); } else return value; } static QMap parseOptions(const char *value) { QMap options; QStringList items = QString::fromLatin1(value).split(QLatin1Char(' ')); foreach (const QString &item, items) { QStringList assign = item.split(QLatin1Char('=')); if (assign.size() == 2) { options[assign[0].toLower()] = assign[1]; } else { qWarning() << "Could not parse option" << item; } } return options; } static bool stringToBool(const QString &value) { return value.toLower() == QLatin1String("true") || value == QLatin1String("1"); } class QDjangoMetaModelPrivate : public QSharedData { public: QString className; QList localFields; QMap foreignFields; QByteArray primaryKey; QString table; QList uniqueTogether; }; /*! Constructs a new QDjangoMetaModel by inspecting the given \a meta model. */ QDjangoMetaModel::QDjangoMetaModel(const QMetaObject *meta) : d(new QDjangoMetaModelPrivate) { if (!meta) return; d->className = meta->className(); d->table = QString::fromLatin1(meta->className()).toLower(); // parse table options const int optionsIndex = meta->indexOfClassInfo("__meta__"); if (optionsIndex >= 0) { QMap options = parseOptions(meta->classInfo(optionsIndex).value()); QMapIterator option(options); while (option.hasNext()) { option.next(); if (option.key() == QLatin1String("db_table")) d->table = option.value(); else if (option.key() == QLatin1String("unique_together")) d->uniqueTogether = option.value().toLatin1().split(','); } } const int count = meta->propertyCount(); for(int i = QObject::staticMetaObject.propertyCount(); i < count; ++i) { const QString typeName = QString::fromLatin1(meta->property(i).typeName()); if (!qstrcmp(meta->property(i).name(), "pk")) continue; // parse field options bool autoIncrementOption = false; QString dbColumnOption; bool dbIndexOption = false; bool ignoreFieldOption = false; int maxLengthOption = 0; bool primaryKeyOption = false; bool nullOption = false; bool uniqueOption = false; bool blankOption = false; ForeignKeyConstraint deleteConstraint = NoAction; const int infoIndex = meta->indexOfClassInfo(meta->property(i).name()); if (infoIndex >= 0) { QMap options = parseOptions(meta->classInfo(infoIndex).value()); QMapIterator option(options); while (option.hasNext()) { option.next(); const QString key = option.key(); const QString value = option.value(); if (key == QLatin1String("auto_increment")) autoIncrementOption = stringToBool(value); else if (key == QLatin1String("db_column")) dbColumnOption = value; else if (key == QLatin1String("db_index")) dbIndexOption = stringToBool(value); else if (key == QLatin1String("ignore_field")) ignoreFieldOption = stringToBool(value); else if (key == QLatin1String("max_length")) maxLengthOption = value.toInt(); else if (key == QLatin1String("null")) nullOption = stringToBool(value); else if (key == QLatin1String("primary_key")) primaryKeyOption = stringToBool(value); else if (key == QLatin1String("unique")) uniqueOption = stringToBool(value); else if (key == QLatin1String("blank")) blankOption = stringToBool(value); else if (option.key() == "on_delete") { if (value.toLower() == "cascade") deleteConstraint = Cascade; else if (value.toLower() == "set_null") deleteConstraint = SetNull; else if (value.toLower() == "restrict") deleteConstraint = Restrict; } } } // ignore field if (ignoreFieldOption) continue; // foreign field if (typeName.endsWith(QLatin1Char('*'))) { const QByteArray fkName = meta->property(i).name(); const QByteArray fkModel = typeName.left(typeName.size() - 1).toLatin1(); d->foreignFields.insert(fkName, fkModel); QDjangoMetaField field; field.d->name = fkName + "_id"; // FIXME : the key is not necessarily an INTEGER field, we should // probably perform a lookup on the foreign model, but are we sure // it is already registered? field.d->type = QVariant::Int; field.d->foreignModel = fkModel; field.d->db_column = dbColumnOption.isEmpty() ? QString::fromLatin1(field.d->name) : dbColumnOption; field.d->index = true; field.d->null = nullOption; field.d->deleteConstraint = deleteConstraint; d->localFields << field; continue; } // local field QDjangoMetaField field; field.d->name = meta->property(i).name(); field.d->type = meta->property(i).type(); field.d->db_column = dbColumnOption.isEmpty() ? QString::fromLatin1(field.d->name) : dbColumnOption; field.d->maxLength = maxLengthOption; field.d->null = nullOption; if (primaryKeyOption) { field.d->autoIncrement = autoIncrementOption; d->primaryKey = field.d->name; } else if (uniqueOption) { field.d->unique = true; } else if (blankOption) { field.d->blank = true; } else if (dbIndexOption) { field.d->index = true; } d->localFields << field; } // automatic primary key if (d->primaryKey.isEmpty()) { QDjangoMetaField field; field.d->name = "id"; field.d->type = QVariant::Int; field.d->db_column = QLatin1String("id"); field.d->autoIncrement = true; d->localFields.prepend(field); d->primaryKey = field.d->name; } } /*! Constructs a copy of \a other. */ QDjangoMetaModel::QDjangoMetaModel(const QDjangoMetaModel &other) : d(other.d) { } /*! Destroys the meta model. */ QDjangoMetaModel::~QDjangoMetaModel() { } QString QDjangoMetaModel::className() const { return d->className; } /*! Determine whether this is a valid model, or just default constructed */ bool QDjangoMetaModel::isValid() const { return !d->table.isNull(); } /*! Assigns \a other to this meta model. */ QDjangoMetaModel& QDjangoMetaModel::operator=(const QDjangoMetaModel& other) { d = other.d; return *this; } /*! Creates the database table for this QDjangoMetaModel. \return true if the table was created, false otherwise. */ bool QDjangoMetaModel::createTable() const { QDjangoQuery createQuery(QDjango::database()); foreach (const QString &sql, createTableSql()) { if (!createQuery.exec(sql)) return false; } return true; } /*! Returns the SQL queries to create the database table for this QDjangoMetaModel. */ QStringList QDjangoMetaModel::createTableSql() const { QSqlDatabase db = QDjango::database(); QSqlDriver *driver = db.driver(); QDjangoDatabase::DatabaseType databaseType = QDjangoDatabase::databaseType(db); QStringList queries; QStringList propSql; QStringList constraintSql; const QString quotedTable = db.driver()->escapeIdentifier(d->table, QSqlDriver::TableName); foreach (const QDjangoMetaField &field, d->localFields) { QString fieldSql = driver->escapeIdentifier(field.column(), QSqlDriver::FieldName); switch (field.d->type) { case QVariant::Bool: if (databaseType == QDjangoDatabase::PostgreSQL) fieldSql += QLatin1String(" boolean"); else if (databaseType == QDjangoDatabase::MSSqlServer) fieldSql += QLatin1String(" bit"); else fieldSql += QLatin1String(" bool"); break; case QVariant::ByteArray: if (databaseType == QDjangoDatabase::PostgreSQL) { fieldSql += QLatin1String(" bytea"); } else if (databaseType == QDjangoDatabase::MSSqlServer) { fieldSql += QLatin1String(" varbinary"); if (field.d->maxLength > 0) fieldSql += QLatin1Char('(') + QString::number(field.d->maxLength) + QLatin1Char(')'); else fieldSql += QLatin1String("(max)"); } else { fieldSql += QLatin1String(" blob"); if (field.d->maxLength > 0) fieldSql += QLatin1Char('(') + QString::number(field.d->maxLength) + QLatin1Char(')'); } break; case QVariant::Date: fieldSql += QLatin1String(" date"); break; case QVariant::DateTime: if (databaseType == QDjangoDatabase::PostgreSQL) fieldSql += QLatin1String(" timestamp"); else fieldSql += QLatin1String(" datetime"); break; case QVariant::Double: fieldSql += QLatin1String(" real"); break; case QVariant::Int: if (databaseType == QDjangoDatabase::MSSqlServer) fieldSql += QLatin1String(" int"); else fieldSql += QLatin1String(" integer"); break; case QVariant::LongLong: fieldSql += QLatin1String(" bigint"); break; case QVariant::String: if (field.d->maxLength > 0) { if (databaseType == QDjangoDatabase::MSSqlServer) fieldSql += QLatin1String(" nvarchar(") + QString::number(field.d->maxLength) + QLatin1Char(')'); else fieldSql += QLatin1String(" varchar(") + QString::number(field.d->maxLength) + QLatin1Char(')'); } else { if (databaseType == QDjangoDatabase::MSSqlServer) fieldSql += QLatin1String(" nvarchar(max)"); else fieldSql += QLatin1String(" text"); } break; case QVariant::Time: fieldSql += QLatin1String(" time"); break; default: qWarning() << "Unhandled type" << field.d->type << "for property" << field.d->name; continue; } if (!field.d->null) fieldSql += QLatin1String(" NOT NULL"); if (field.d->unique) fieldSql += QLatin1String(" UNIQUE"); // primary key if (field.d->name == d->primaryKey) fieldSql += QLatin1String(" PRIMARY KEY"); // auto-increment is backend specific if (field.d->autoIncrement) { if (databaseType == QDjangoDatabase::SQLite) // NOTE: django does not add this option for sqlite, but there // is a ticket asking for it to do so: // https://code.djangoproject.com/ticket/10164 fieldSql += QLatin1String(" AUTOINCREMENT"); else if (databaseType == QDjangoDatabase::MySqlServer) fieldSql += QLatin1String(" AUTO_INCREMENT"); else if (databaseType == QDjangoDatabase::PostgreSQL) fieldSql = driver->escapeIdentifier(field.column(), QSqlDriver::FieldName) + QLatin1String(" serial PRIMARY KEY"); else if (databaseType == QDjangoDatabase::MSSqlServer) fieldSql += QLatin1String(" IDENTITY(1,1)"); } // foreign key if (!field.d->foreignModel.isEmpty()) { const QDjangoMetaModel foreignMeta = QDjango::metaModel(field.d->foreignModel); const QDjangoMetaField foreignField = foreignMeta.localField("pk"); if (databaseType == QDjangoDatabase::MySqlServer) { QString constraintName = QString::fromLatin1("FK_%1_%2").arg( field.column(), stringlist_digest(QStringList() << field.column() << d->table)); QString constraint = QString::fromLatin1("CONSTRAINT %1 FOREIGN KEY (%2) REFERENCES %3 (%4)").arg( driver->escapeIdentifier(constraintName, QSqlDriver::FieldName), driver->escapeIdentifier(field.column(), QSqlDriver::FieldName), driver->escapeIdentifier(foreignMeta.d->table, QSqlDriver::TableName), driver->escapeIdentifier(foreignField.column(), QSqlDriver::FieldName) ); if (field.d->deleteConstraint != NoAction) { constraint += " ON DELETE"; switch (field.d->deleteConstraint) { case Cascade: constraint += " CASCADE"; break; case SetNull: constraint += " SET NULL"; break; case Restrict: constraint += " RESTRICT"; break; default: break; } } constraintSql << constraint; } else { fieldSql += QString::fromLatin1(" REFERENCES %1 (%2)").arg( driver->escapeIdentifier(foreignMeta.d->table, QSqlDriver::TableName), driver->escapeIdentifier(foreignField.column(), QSqlDriver::FieldName)); if (databaseType == QDjangoDatabase::MSSqlServer && field.d->deleteConstraint == Restrict) { qWarning("MSSQL does not support RESTRICT constraints"); break; } if (field.d->deleteConstraint != NoAction) { fieldSql += " ON DELETE"; switch (field.d->deleteConstraint) { case Cascade: fieldSql += " CASCADE"; break; case SetNull: fieldSql += " SET NULL"; break; case Restrict: fieldSql += " RESTRICT"; break; default: break; } } } if (databaseType == QDjangoDatabase::PostgreSQL) fieldSql += " DEFERRABLE INITIALLY DEFERRED"; } propSql << fieldSql; } // add constraints if we need them if (!constraintSql.isEmpty()) propSql << constraintSql.join(QLatin1String(", ")); // unique contraints if (!d->uniqueTogether.isEmpty()) { QStringList columns; foreach (const QByteArray &name, d->uniqueTogether) { columns << driver->escapeIdentifier(localField(name).column(), QSqlDriver::FieldName); } propSql << QString::fromLatin1("UNIQUE (%2)").arg(columns.join(QLatin1String(", "))); } // create table queries << QString::fromLatin1("CREATE TABLE %1 (%2)").arg( quotedTable, propSql.join(QLatin1String(", "))); // create indices foreach (const QDjangoMetaField &field, d->localFields) { if (field.d->index) { const QString indexName = d->table + QLatin1Char('_') + stringlist_digest(QStringList() << field.column()); queries << QString::fromLatin1("CREATE INDEX %1 ON %2 (%3)").arg( // FIXME : how should we escape an index name? driver->escapeIdentifier(indexName, QSqlDriver::FieldName), quotedTable, driver->escapeIdentifier(field.column(), QSqlDriver::FieldName)); } } return queries; } /*! Drops the database table for this QDjangoMetaModel. \return true if the table was dropped or did not exist, false otherwise. */ bool QDjangoMetaModel::dropTable() const { QSqlDatabase db = QDjango::database(); if (!db.tables().contains(d->table)) return true; QDjangoQuery query(db); return query.exec(QLatin1String("DROP TABLE ") + db.driver()->escapeIdentifier(d->table, QSqlDriver::TableName)); } /*! Retrieves the QDjangoModel pointed to by the given foreign-key. \param model \param name */ QObject *QDjangoMetaModel::foreignKey(const QObject *model, const char *name) const { // check the name is valid const QByteArray prop(name); if (!d->foreignFields.contains(prop)) { qWarning("QDjangoMetaModel cannot get foreign model for invalid key '%s'", name); return 0; } QObject *foreign = model->property(prop + "_ptr").value(); if (!foreign) return 0; // if the foreign object was not loaded yet, do it now const QByteArray foreignClass = d->foreignFields[prop]; const QDjangoMetaModel foreignMeta = QDjango::metaModel(foreignClass); const QVariant foreignPk = model->property(prop + "_id"); if (foreign->property(foreignMeta.primaryKey()) != foreignPk) { QDjangoQuerySetPrivate qs(foreignClass); qs.addFilter(QDjangoWhere(QLatin1String("pk"), QDjangoWhere::Equals, foreignPk)); qs.sqlFetch(); if (qs.properties.size() != 1 || !qs.sqlLoad(foreign, 0)) return 0; } return foreign; } /*! Sets the QDjangoModel pointed to by the given foreign-key. \param model \param name \param value */ void QDjangoMetaModel::setForeignKey(QObject *model, const char *name, QObject *value) const { // check the name is valid const QByteArray prop(name); if (!d->foreignFields.contains(prop)) { qWarning("QDjangoMetaModel cannot set foreign model for invalid key '%s'", name); return; } QObject *old = model->property(prop + "_ptr").value(); if (old == value) return; // store the new pointer and update the foreign key model->setProperty(prop + "_ptr", qVariantFromValue(value)); if (value) { const QDjangoMetaModel foreignMeta = QDjango::metaModel(d->foreignFields[prop]); model->setProperty(prop + "_id", value->property(foreignMeta.primaryKey())); } else { model->setProperty(prop + "_id", QVariant()); } } /*! Loads the given properties into a \a model instance. */ void QDjangoMetaModel::load(QObject *model, const QVariantList &properties, int &pos) const { // process local fields foreach (const QDjangoMetaField &field, d->localFields) model->setProperty(field.d->name, properties.at(pos++)); // process foreign fields if (pos >= properties.size()) return; foreach (const QByteArray &fkName, d->foreignFields.keys()) { QObject *object = model->property(fkName + "_ptr").value(); if (object) { const QDjangoMetaModel foreignMeta = QDjango::metaModel(d->foreignFields[fkName]); foreignMeta.load(object, properties, pos); } } } /*! Returns the foreign field mapping. */ QMap QDjangoMetaModel::foreignFields() const { return d->foreignFields; } /*! Return the local field with the specified \a name. */ QDjangoMetaField QDjangoMetaModel::localField(const char *name) const { const QByteArray fieldName = strcmp(name, "pk") ? QByteArray(name) : d->primaryKey; foreach (const QDjangoMetaField &field, d->localFields) { if (field.d->name == fieldName) return field; } return QDjangoMetaField(); } /*! Returns the list of local fields. */ QList QDjangoMetaModel::localFields() const { return d->localFields; } /*! Returns the name of the primary key for the current QDjangoMetaModel. */ QByteArray QDjangoMetaModel::primaryKey() const { return d->primaryKey; } /*! Returns the name of the database table. */ QString QDjangoMetaModel::table() const { return d->table; } /*! Removes the given \a model instance from the database. */ bool QDjangoMetaModel::remove(QObject *model) const { const QVariant pk = model->property(d->primaryKey); QDjangoQuerySetPrivate qs(model->metaObject()->className()); qs.addFilter(QDjangoWhere(QLatin1String("pk"), QDjangoWhere::Equals, pk)); return qs.sqlDelete(); } /*! Saves the given \a model instance to the database. \return true if saving succeeded, false otherwise */ bool QDjangoMetaModel::save(QObject *model) const { // find primary key const QDjangoMetaField primaryKey = localField("pk"); const QVariant pk = model->property(d->primaryKey); if (!pk.isNull() && !(primaryKey.d->type == QVariant::Int && !pk.toInt())) { QSqlDatabase db = QDjango::database(); QDjangoQuery query(db); query.prepare(QString::fromLatin1("SELECT 1 AS a FROM %1 WHERE %2 = ?").arg( db.driver()->escapeIdentifier(d->table, QSqlDriver::FieldName), db.driver()->escapeIdentifier(primaryKey.column(), QSqlDriver::FieldName))); query.addBindValue(pk); if (query.exec() && query.next()) { // prepare data QVariantMap fields; foreach (const QDjangoMetaField &field, d->localFields) { if (field.d->name != d->primaryKey) { const QVariant value = model->property(field.d->name); fields.insert(QString::fromLatin1(field.d->name), field.toDatabase(value)); } } // perform UPDATE QDjangoQuerySetPrivate qs(model->metaObject()->className()); qs.addFilter(QDjangoWhere(QLatin1String("pk"), QDjangoWhere::Equals, pk)); return qs.sqlUpdate(fields) != -1; } } // prepare data QVariantMap fields; foreach (const QDjangoMetaField &field, d->localFields) { if (!field.d->autoIncrement) { const QVariant value = model->property(field.d->name); fields.insert(field.name(), field.toDatabase(value)); } } // perform INSERT QDjangoQuerySetPrivate qs(model->metaObject()->className()); if (primaryKey.d->autoIncrement) { // fetch autoincrement pk QVariant insertId; if (!qs.sqlInsert(fields, &insertId)) return false; model->setProperty(d->primaryKey, insertId); } else { if (!qs.sqlInsert(fields)) return false; } return true; } qdjango-0.6.2/src/db/QDjangoMetaModel.h000066400000000000000000000053531261212605400176070ustar00rootroot00000000000000/* * Copyright (C) 2010-2015 Jeremy Lainé * Contact: https://github.com/jlaine/qdjango * * This file is part of the QDjango Library. * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * This library 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 * Lesser General Public License for more details. */ #ifndef QDJANGOMETAMODEL_H #define QDJANGOMETAMODEL_H #include #include #include #include "QDjango_p.h" class QDjangoMetaFieldPrivate; class QDjangoMetaModelPrivate; /** \brief The QDjangoMetaField class holds the database schema for a field. * * \internal */ class QDJANGO_DB_EXPORT QDjangoMetaField { public: QDjangoMetaField(); QDjangoMetaField(const QDjangoMetaField &other); ~QDjangoMetaField(); QDjangoMetaField& operator=(const QDjangoMetaField &other); QString column() const; bool isAutoIncrement() const; bool isBlank() const; bool isNullable() const; bool isUnique() const; bool isValid() const; QString name() const; int maxLength() const; QVariant toDatabase(const QVariant &value) const; private: QSharedDataPointer d; friend class QDjangoMetaModel; }; /** \brief The QDjangoMetaModel class holds the database schema for a model. * * It manages table creation and deletion operations as well as row * serialisation, deserialisation and deletion operations. * * \internal */ class QDJANGO_DB_EXPORT QDjangoMetaModel { public: QDjangoMetaModel(const QMetaObject *model = 0); QDjangoMetaModel(const QDjangoMetaModel &other); ~QDjangoMetaModel(); QDjangoMetaModel& operator=(const QDjangoMetaModel &other); bool isValid() const; bool createTable() const; QStringList createTableSql() const; bool dropTable() const; void load(QObject *model, const QVariantList &props, int &pos) const; bool remove(QObject *model) const; bool save(QObject *model) const; QObject *foreignKey(const QObject *model, const char *name) const; void setForeignKey(QObject *model, const char *name, QObject *value) const; QString className() const; QDjangoMetaField localField(const char *name) const; QList localFields() const; QMap foreignFields() const; QByteArray primaryKey() const; QString table() const; private: QSharedDataPointer d; }; #endif qdjango-0.6.2/src/db/QDjangoModel.cpp000066400000000000000000000056341261212605400173350ustar00rootroot00000000000000/* * Copyright (C) 2010-2015 Jeremy Lainé * Contact: https://github.com/jlaine/qdjango * * This file is part of the QDjango Library. * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * This library 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 * Lesser General Public License for more details. */ #include #include #include "QDjango.h" #include "QDjangoModel.h" #include "QDjangoQuerySet.h" /** Construct a new QDjangoModel. * * \param parent */ QDjangoModel::QDjangoModel(QObject *parent) : QObject(parent) { } /** Returns the primary key for this QDjangoModel. */ QVariant QDjangoModel::pk() const { const QDjangoMetaModel metaModel = QDjango::metaModel(metaObject()->className()); return property(metaModel.primaryKey()); } /** Sets the primary key for this QDjangoModel. * * \param pk */ void QDjangoModel::setPk(const QVariant &pk) { const QDjangoMetaModel metaModel = QDjango::metaModel(metaObject()->className()); setProperty(metaModel.primaryKey(), pk); } /** Retrieves the QDjangoModel pointed to by the given foreign-key. * * \param name */ QObject *QDjangoModel::foreignKey(const char *name) const { const QDjangoMetaModel metaModel = QDjango::metaModel(metaObject()->className()); return metaModel.foreignKey(this, name); } /** Sets the QDjangoModel pointed to by the given foreign-key. * * \param name * \param value * * \note The QDjangoModel will not take ownership of the given \c value. */ void QDjangoModel::setForeignKey(const char *name, QObject *value) { const QDjangoMetaModel metaModel = QDjango::metaModel(metaObject()->className()); metaModel.setForeignKey(this, name, value); } /** Deletes the QDjangoModel from the database. * * \return true if deletion succeeded, false otherwise */ bool QDjangoModel::remove() { const QDjangoMetaModel metaModel = QDjango::metaModel(metaObject()->className()); return metaModel.remove(this); } /** Saves the QDjangoModel to the database. * * \return true if saving succeeded, false otherwise */ bool QDjangoModel::save() { const QDjangoMetaModel metaModel = QDjango::metaModel(metaObject()->className()); return metaModel.save(this); } /** Returns a string representation of the model instance. */ QString QDjangoModel::toString() const { const QDjangoMetaModel metaModel = QDjango::metaModel(metaObject()->className()); const QByteArray pkName = metaModel.primaryKey(); return QString::fromLatin1("%1(%2=%3)").arg(QString::fromLatin1(metaObject()->className()), QString::fromLatin1(pkName), property(pkName).toString()); } qdjango-0.6.2/src/db/QDjangoModel.h000066400000000000000000000067421261212605400170030ustar00rootroot00000000000000/* * Copyright (C) 2010-2015 Jeremy Lainé * Contact: https://github.com/jlaine/qdjango * * This file is part of the QDjango Library. * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * This library 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 * Lesser General Public License for more details. */ #ifndef QDJANGO_MODEL_H #define QDJANGO_MODEL_H #include #include #include "QDjango_p.h" /** \brief The QDjangoModel class is the base class for all models. * * To declare your own model, create a class which inherits QDjangoModel * and declare the database fields as properties using the Q_PROPERTY * macro. You must then register the class with QDjango using * QDjango::registerModel(). * * You can provide options for the model using the Q_CLASSINFO macro as * follows: * * \code * Q_CLASSINFO("__meta__", "keyword1=value1 .. keywordN=valueN") * \endcode * * The following keywords are recognised for model options: * * \li \c db_table if provided, this is the name of the database table for * the model, otherwise the lowercased class name will be used * \li \c unique_together set of fields that, taken together, must be unique. * If provided, a UNIQUE statement is included in the CREATE TABLE statement. * Example: \c unique_together=some_field,other_field * * You can also provide additional information about a field using the * Q_CLASSINFO macro, in the form: * * \code * Q_CLASSINFO("field_name", "keyword1=value1 .. keywordN=valueN") * \endcode * * The following keywords are recognised for field options: * * \li \c auto_increment if set to 'true', and if this field is the primary * key, it will be marked as auto-increment. * \li \c blank if set to 'true', this field is allowed to be empty. * \li \c db_column if provided, this is the name of the database column for * the field, otherwise the field name will be used * \li \c db_index if set to 'true', an index will be created on this field. * \li \c ignore_field if set to 'true', this field will be ignored * \li \c max_length the maximum length of the field (used when creating * the database table) * \li \c null if set to 'true', empty values will be stored as NULL. The * default value is 'false'. * \li \c primary_key if set to 'true', this field will be used as the primary * key. If no primary key is explicitly defined, an auto-increment integer * field will be added. * \li \c unique if set to 'true', this field must be unique throughout the * table. * \li \c on_delete if provided, create a foreign key constraint on this field. * Accepted values are: 'cascade', 'restrict', and 'set_null' * * \ingroup Database */ class QDJANGO_DB_EXPORT QDjangoModel : public QObject { Q_OBJECT Q_PROPERTY(QVariant pk READ pk WRITE setPk) Q_CLASSINFO("pk", "ignore_field=true") public: QDjangoModel(QObject *parent = 0); QVariant pk() const; void setPk(const QVariant &pk); public slots: bool remove(); bool save(); QString toString() const; protected: QObject *foreignKey(const char *name) const; void setForeignKey(const char *name, QObject *value); }; #endif qdjango-0.6.2/src/db/QDjangoQuerySet.cpp000066400000000000000000000453501261212605400200550ustar00rootroot00000000000000/* * Copyright (C) 2010-2015 Jeremy Lainé * Copyright (C) 2011 Mathias Hasselmann * Contact: https://github.com/jlaine/qdjango * * This file is part of the QDjango Library. * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * This library 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 * Lesser General Public License for more details. */ #include #include #include #include "QDjango.h" #include "QDjango_p.h" #include "QDjangoQuerySet.h" #include "QDjangoWhere_p.h" /// \cond QDjangoCompiler::QDjangoCompiler(const char *modelName, const QSqlDatabase &db) { driver = db.driver(); baseModel = QDjango::metaModel(modelName); } QString QDjangoCompiler::referenceModel(const QString &modelPath, QDjangoMetaModel *metaModel, bool nullable) { if (modelPath.isEmpty()) return driver->escapeIdentifier(baseModel.table(), QSqlDriver::TableName); if (modelRefs.contains(modelPath)) return modelRefs.value(modelPath).tableReference; const QString modelRef = QLatin1String("T") + QString::number(modelRefs.size()); modelRefs.insert(modelPath, QDjangoModelReference(modelRef, *metaModel, nullable)); return modelRef; } QString QDjangoCompiler::databaseColumn(const QString &name) { QDjangoMetaModel model = baseModel; QString modelName; QString modelPath; QString modelRef = referenceModel(QString(), &model, false); QStringList bits = name.split(QLatin1String("__")); while (bits.size() > 1) { const QByteArray fk = bits.first().toLatin1(); QDjangoMetaModel foreignModel; bool foreignNullable = false; if (!modelPath.isEmpty()) modelPath += QLatin1String("__"); modelPath += bits.first(); if (!model.foreignFields().contains(fk)) { // this might be a reverse relation, so look for the model // and if it exists continue foreignModel = QDjango::metaModel(fk); QDjangoReverseReference rev; const QMap foreignFields = foreignModel.foreignFields(); foreach (const QByteArray &foreignKey, foreignFields.keys()) { if (foreignFields[foreignKey] == baseModel.className()) { rev.leftHandKey = foreignModel.localField(foreignKey + "_id").column(); break; } } if (rev.leftHandKey.isEmpty()) { qWarning() << "Invalid field lookup" << name; return QString(); } rev.rightHandKey = foreignModel.primaryKey(); reverseModelRefs[modelPath] = rev; } else { foreignModel = QDjango::metaModel(model.foreignFields()[fk]); foreignNullable = model.localField(fk + QByteArray("_id")).isNullable();; } // store reference modelRef = referenceModel(modelPath, &foreignModel, foreignNullable); modelName = fk; model = foreignModel; bits.takeFirst(); } const QDjangoMetaField field = model.localField(bits.join(QLatin1String("__")).toLatin1()); return modelRef + QLatin1Char('.') + driver->escapeIdentifier(field.column(), QSqlDriver::FieldName); } QStringList QDjangoCompiler::fieldNames(bool recurse, QDjangoMetaModel *metaModel, const QString &modelPath, bool nullable) { QStringList columns; if (!metaModel) metaModel = &baseModel; // store reference const QString tableName = referenceModel(modelPath, metaModel, nullable); foreach (const QDjangoMetaField &field, metaModel->localFields()) columns << tableName + QLatin1Char('.') + driver->escapeIdentifier(field.column(), QSqlDriver::FieldName); if (!recurse) return columns; // recurse for foreign keys const QString pathPrefix = modelPath.isEmpty() ? QString() : (modelPath + QLatin1String("__")); foreach (const QByteArray &fkName, metaModel->foreignFields().keys()) { QDjangoMetaModel metaForeign = QDjango::metaModel(metaModel->foreignFields()[fkName]); bool nullableForeign = metaModel->localField(fkName + QByteArray("_id")).isNullable(); columns += fieldNames(recurse, &metaForeign, pathPrefix + QString::fromLatin1(fkName), nullableForeign); } return columns; } QString QDjangoCompiler::fromSql() { QString from = driver->escapeIdentifier(baseModel.table(), QSqlDriver::TableName); foreach (const QString &name, modelRefs.keys()) { const QDjangoModelReference &ref = modelRefs[name]; QString leftHandColumn, rightHandColumn; if (reverseModelRefs.contains(name)) { const QDjangoReverseReference &rev = reverseModelRefs[name]; leftHandColumn = ref.tableReference + "." + driver->escapeIdentifier(rev.leftHandKey, QSqlDriver::FieldName);; rightHandColumn = databaseColumn(rev.rightHandKey); } else { leftHandColumn = databaseColumn(name + QLatin1String("__pk")); rightHandColumn = databaseColumn(name + QLatin1String("_id")); } from += QString::fromLatin1(" %1 %2 %3 ON %4 = %5") .arg(ref.nullable ? "LEFT OUTER JOIN" : "INNER JOIN") .arg(driver->escapeIdentifier(ref.metaModel.table(), QSqlDriver::TableName)) .arg(ref.tableReference) .arg(leftHandColumn) .arg(rightHandColumn); } return from; } QString QDjangoCompiler::orderLimitSql(const QStringList &orderBy, int lowMark, int highMark) { QString limit; // order QStringList bits; QString field; foreach (field, orderBy) { QString order = QLatin1String("ASC"); if (field.startsWith(QLatin1Char('-'))) { order = QLatin1String("DESC"); field = field.mid(1); } else if (field.startsWith(QLatin1Char('+'))) { field = field.mid(1); } bits.append(databaseColumn(field) + QLatin1Char(' ') + order); } if (!bits.isEmpty()) limit += QLatin1String(" ORDER BY ") + bits.join(QLatin1String(", ")); // limits QDjangoDatabase::DatabaseType databaseType = QDjangoDatabase::databaseType(QDjango::database()); if (databaseType == QDjangoDatabase::MSSqlServer) { if (limit.isEmpty() && (highMark > 0 || lowMark > 0)) limit += QLatin1String(" ORDER BY ") + databaseColumn(baseModel.primaryKey()); if (lowMark > 0 || (lowMark == 0 && highMark > 0)) { limit += QLatin1String(" OFFSET ") + QString::number(lowMark); limit += QLatin1String(" ROWS"); } if (highMark > 0) limit += QString(" FETCH NEXT %1 ROWS ONLY").arg(highMark - lowMark); } else { if (highMark > 0) limit += QLatin1String(" LIMIT ") + QString::number(highMark - lowMark); if (lowMark > 0) { // no-limit is backend specific if (highMark <= 0) { if (databaseType == QDjangoDatabase::SQLite) limit += QLatin1String(" LIMIT -1"); else if (databaseType == QDjangoDatabase::MySqlServer) // 2^64 - 1, as recommended by the MySQL documentation limit += QLatin1String(" LIMIT 18446744073709551615"); } limit += QLatin1String(" OFFSET ") + QString::number(lowMark); } } return limit; } void QDjangoCompiler::resolve(QDjangoWhere &where) { // resolve column if (where.d->operation != QDjangoWhere::None) where.d->key = databaseColumn(where.d->key); // recurse into children for (int i = 0; i < where.d->children.size(); i++) resolve(where.d->children[i]); } QDjangoQuerySetPrivate::QDjangoQuerySetPrivate(const char *modelName) : counter(1), hasResults(false), lowMark(0), highMark(0), selectRelated(false), m_modelName(modelName) { } void QDjangoQuerySetPrivate::addFilter(const QDjangoWhere &where) { // it is not possible to add filters once a limit has been set Q_ASSERT(!lowMark && !highMark); whereClause = whereClause && where; } QDjangoWhere QDjangoQuerySetPrivate::resolvedWhere(const QSqlDatabase &db) const { QDjangoCompiler compiler(m_modelName, db); QDjangoWhere resolvedWhere(whereClause); compiler.resolve(resolvedWhere); return resolvedWhere; } bool QDjangoQuerySetPrivate::sqlDelete() { // DELETE on an empty queryset doesn't need a query if (whereClause.isNone()) return true; // FIXME : it is not possible to remove entries once a limit has been set // because SQLite does not support limits on DELETE unless compiled with the // SQLITE_ENABLE_UPDATE_DELETE_LIMIT option if (lowMark || highMark) return false; // execute query QDjangoQuery query(deleteQuery()); if (!query.exec()) return false; // invalidate cache if (hasResults) { properties.clear(); hasResults = false; } return true; } bool QDjangoQuerySetPrivate::sqlFetch() { if (hasResults || whereClause.isNone()) return true; // execute query QDjangoQuery query(selectQuery()); if (!query.exec()) return false; // store results while (query.next()) { QVariantList props; const int propCount = query.record().count(); for (int i = 0; i < propCount; ++i) props << query.value(i); properties.append(props); } hasResults = true; return true; } bool QDjangoQuerySetPrivate::sqlInsert(const QVariantMap &fields, QVariant *insertId) { // execute query QDjangoQuery query(insertQuery(fields)); if (!query.exec()) return false; // fetch autoincrement pk if (insertId) { QSqlDatabase db = QDjango::database(); QDjangoDatabase::DatabaseType databaseType = QDjangoDatabase::databaseType(db); if (databaseType == QDjangoDatabase::PostgreSQL) { const QDjangoMetaModel metaModel = QDjango::metaModel(m_modelName); QDjangoQuery query(db); const QDjangoMetaField primaryKey = metaModel.localField("pk"); const QString seqName = db.driver()->escapeIdentifier(metaModel.table() + QLatin1Char('_') + primaryKey.column() + QLatin1String("_seq"), QSqlDriver::FieldName); if (!query.exec(QLatin1String("SELECT CURRVAL('") + seqName + QLatin1String("')")) || !query.next()) return false; *insertId = query.value(0); } else { *insertId = query.lastInsertId(); } } // invalidate cache if (hasResults) { properties.clear(); hasResults = false; } return true; } bool QDjangoQuerySetPrivate::sqlLoad(QObject *model, int index) { if (!sqlFetch()) return false; if (index < 0 || index >= properties.size()) { qWarning("QDjangoQuerySet out of bounds"); return false; } const QDjangoMetaModel metaModel = QDjango::metaModel(m_modelName); int pos = 0; metaModel.load(model, properties.at(index), pos); return true; } /** Returns the SQL query to perform a COUNT on the current set. */ QDjangoQuery QDjangoQuerySetPrivate::countQuery() const { QSqlDatabase db = QDjango::database(); // build query QDjangoCompiler compiler(m_modelName, db); QDjangoWhere resolvedWhere(whereClause); compiler.resolve(resolvedWhere); const QString where = resolvedWhere.sql(db); const QString limit = compiler.orderLimitSql(QStringList(), lowMark, highMark); QString sql = QLatin1String("SELECT COUNT(*) FROM ") + compiler.fromSql(); if (!where.isEmpty()) sql += QLatin1String(" WHERE ") + where; sql += limit; QDjangoQuery query(db); query.prepare(sql); resolvedWhere.bindValues(query); return query; } /** Returns the SQL query to perform a DELETE on the current set. */ QDjangoQuery QDjangoQuerySetPrivate::deleteQuery() const { QSqlDatabase db = QDjango::database(); // build query QDjangoCompiler compiler(m_modelName, db); QDjangoWhere resolvedWhere(whereClause); compiler.resolve(resolvedWhere); const QString where = resolvedWhere.sql(db); const QString limit = compiler.orderLimitSql(orderBy, lowMark, highMark); QString sql = QLatin1String("DELETE FROM ") + compiler.fromSql(); if (!where.isEmpty()) sql += QLatin1String(" WHERE ") + where; sql += limit; QDjangoQuery query(db); query.prepare(sql); resolvedWhere.bindValues(query); return query; } /** Returns the SQL query to perform an INSERT for the specified \a fields. */ QDjangoQuery QDjangoQuerySetPrivate::insertQuery(const QVariantMap &fields) const { QSqlDatabase db = QDjango::database(); const QDjangoMetaModel metaModel = QDjango::metaModel(m_modelName); // perform INSERT QStringList fieldColumns; QStringList fieldHolders; foreach (const QString &name, fields.keys()) { const QDjangoMetaField field = metaModel.localField(name.toLatin1()); fieldColumns << db.driver()->escapeIdentifier(field.column(), QSqlDriver::FieldName); fieldHolders << QLatin1String("?"); } QDjangoQuery query(db); query.prepare(QString::fromLatin1("INSERT INTO %1 (%2) VALUES(%3)").arg( db.driver()->escapeIdentifier(metaModel.table(), QSqlDriver::TableName), fieldColumns.join(QLatin1String(", ")), fieldHolders.join(QLatin1String(", ")))); foreach (const QString &name, fields.keys()) query.addBindValue(fields.value(name)); return query; } /** Returns the SQL query to perform a SELECT on the current set. */ QDjangoQuery QDjangoQuerySetPrivate::selectQuery() const { QSqlDatabase db = QDjango::database(); // build query QDjangoCompiler compiler(m_modelName, db); QDjangoWhere resolvedWhere(whereClause); compiler.resolve(resolvedWhere); const QStringList columns = compiler.fieldNames(selectRelated); const QString where = resolvedWhere.sql(db); const QString limit = compiler.orderLimitSql(orderBy, lowMark, highMark); QString sql = QLatin1String("SELECT ") + columns.join(QLatin1String(", ")) + QLatin1String(" FROM ") + compiler.fromSql(); if (!where.isEmpty()) sql += QLatin1String(" WHERE ") + where; sql += limit; QDjangoQuery query(db); query.prepare(sql); resolvedWhere.bindValues(query); return query; } /** Returns the SQL query to perform an UPDATE on the current set for the specified \a fields. */ QDjangoQuery QDjangoQuerySetPrivate::updateQuery(const QVariantMap &fields) const { QSqlDatabase db = QDjango::database(); const QDjangoMetaModel metaModel = QDjango::metaModel(m_modelName); // build query QDjangoCompiler compiler(m_modelName, db); QDjangoWhere resolvedWhere(whereClause); compiler.resolve(resolvedWhere); QString sql = QLatin1String("UPDATE ") + compiler.fromSql(); // add SET QStringList fieldAssign; foreach (const QString &name, fields.keys()) { const QDjangoMetaField field = metaModel.localField(name.toLatin1()); fieldAssign << db.driver()->escapeIdentifier(field.column(), QSqlDriver::FieldName) + QLatin1String(" = ?"); } sql += QLatin1String(" SET ") + fieldAssign.join(QLatin1String(", ")); // add WHERE const QString where = resolvedWhere.sql(db); if (!where.isEmpty()) sql += QLatin1String(" WHERE ") + where; QDjangoQuery query(db); query.prepare(sql); foreach (const QString &name, fields.keys()) query.addBindValue(fields.value(name)); resolvedWhere.bindValues(query); return query; } int QDjangoQuerySetPrivate::sqlUpdate(const QVariantMap &fields) { // UPDATE on an empty queryset doesn't need a query if (whereClause.isNone() || fields.isEmpty()) return 0; // FIXME : it is not possible to update entries once a limit has been set // because SQLite does not support limits on UPDATE unless compiled with the // SQLITE_ENABLE_UPDATE_DELETE_LIMIT option if (lowMark || highMark) return -1; // execute query QDjangoQuery query(updateQuery(fields)); if (!query.exec()) return -1; // invalidate cache if (hasResults) { properties.clear(); hasResults = false; } return query.numRowsAffected(); } QList QDjangoQuerySetPrivate::sqlValues(const QStringList &fields) { QList values; if (!sqlFetch()) return values; const QDjangoMetaModel metaModel = QDjango::metaModel(m_modelName); // build field list const QList localFields = metaModel.localFields(); QMap fieldPos; if (fields.isEmpty()) { for (int i = 0; i < localFields.size(); ++i) fieldPos.insert(localFields[i].name(), i); } else { foreach (const QString &name, fields) { int pos = 0; foreach (const QDjangoMetaField &field, localFields) { if (field.name() == name) break; pos++; } Q_ASSERT_X(pos < localFields.size(), "QDjangoQuerySet::values", "unknown field requested"); fieldPos.insert(name, pos); } } // extract values foreach (const QVariantList &props, properties) { QVariantMap map; QMap::const_iterator i; for (i = fieldPos.constBegin(); i != fieldPos.constEnd(); ++i) map[i.key()] = props[i.value()]; values.append(map); } return values; } QList QDjangoQuerySetPrivate::sqlValuesList(const QStringList &fields) { QList values; if (!sqlFetch()) return values; const QDjangoMetaModel metaModel = QDjango::metaModel(m_modelName); // build field list const QList localFields = metaModel.localFields(); QList fieldPos; if (fields.isEmpty()) { for (int i = 0; i < localFields.size(); ++i) fieldPos << i; } else { foreach (const QString &name, fields) { int pos = 0; foreach (const QDjangoMetaField &field, localFields) { if (field.name() == name) break; pos++; } Q_ASSERT_X(pos < localFields.size(), "QDjangoQuerySet::valuesList", "unknown field requested"); fieldPos << pos; } } // extract values foreach (const QVariantList &props, properties) { QVariantList list; foreach (int pos, fieldPos) list << props.at(pos); values.append(list); } return values; } /// \endcond qdjango-0.6.2/src/db/QDjangoQuerySet.h000066400000000000000000000470661261212605400175300ustar00rootroot00000000000000/* * Copyright (C) 2010-2015 Jeremy Lainé * Copyright (C) 2011 Mathias Hasselmann * Contact: https://github.com/jlaine/qdjango * * This file is part of the QDjango Library. * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * This library 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 * Lesser General Public License for more details. */ #ifndef QDJANGO_QUERYSET_H #define QDJANGO_QUERYSET_H #include "QDjango.h" #include "QDjangoWhere.h" #include "QDjangoQuerySet_p.h" /** \brief The QDjangoQuerySet class is a template class for performing * database queries. * * The QDjangoQuerySet template class allows you to define and manipulate * sets of QDjangoModel objects stored in the database. * * You can chain filter expressions using the filter() and exclude() methods * or apply limits on the number of rows using the limit() method. * * You can retrieve database values using the values() and valuesList() * methods or retrieve model instances using the get() and at() methods. * * You can also delete sets of objects using the remove() method. * * Behinds the scenes, the QDjangoQuerySet class uses implicit sharing to * reduce memory usage and avoid needless copying of data. * * \ingroup Database */ template class QDjangoQuerySet { public: /** \cond declarations for STL-style container algorithms */ typedef int size_type; typedef T value_type; typedef value_type *pointer; typedef const value_type *const_pointer; typedef value_type &reference; typedef const value_type &const_reference; typedef qptrdiff difference_type; /** \endcond */ /** The QDjangoQuerySet::const_iterator class provides an STL-style const iterator * for QDjangoQuerySet. * * QDjangoQuerySet::const_iterator allows you to iterate over a QDjangoQuerySet. * As a const iterator it doesn't permit you to modify the QDjangoQuerySet. * * The default QDjangoQuerySet::const_iterator constructor creates an uninitialized iterator. You must * initialize it using a QDjangoQuerySet function like QDjangoQuerySet::constBegin(), or * QDjangoQuerySet::constEnd() before you can start iterating. Here's a typical loop that * prints all the objects stored in a set: * * \code * QDjangoQuerySet posts; * * foreach(const Weblog::Post &p, posts) { * cout << p << endl; * } * \endcode */ class const_iterator { friend class QDjangoQuerySet; public: /** A synonym for std::bidirectional_iterator_tag indicating this iterator * permits bidirectional access. */ typedef std::bidirectional_iterator_tag iterator_category; /** \cond declarations for STL-style container algorithms */ typedef qptrdiff difference_type; typedef T value_type; typedef T *pointer; typedef T &reference; /** \endcond */ /** Constructs an uninitialized iterator. * * Functions like operator*() and operator++() should not be called on an uninitialized * iterator. Use const_iterator::operator=() to assign a value to it before using it. * * \sa See also QDjangoQuerySet::constBegin() and QDjangoQuerySet::constEnd(). */ const_iterator() : m_querySet(0) , m_fetched(-1) , m_offset(0) { } /** Constructs a copy of \p other. */ const_iterator(const const_iterator &other) : m_querySet(other.m_querySet) , m_fetched(-1) , m_offset(other.m_offset) { } private: const_iterator(const QDjangoQuerySet *querySet, int offset = 0) : m_querySet(querySet) , m_fetched(-1) , m_offset(offset) { } public: /** Returns the current item. * * \sa operator->() */ const T &operator*() const { return *t(); } /** Returns a pointer to the current item. * * \sa operator*() */ const T *operator->() const { return t(); } /** Returns \c true if \p other points to the same item as this iterator; * otherwise returns \c false. * * \sa operator!=() */ bool operator==(const const_iterator &other) const { return m_querySet == other.m_querySet && m_offset == other.m_offset; } /** Returns \c true if \p other points to a different item than this iterator; * otherwise returns \c false. * * \sa operator==() */ bool operator!=(const const_iterator &other) const { return m_querySet != other.m_querySet || m_offset != other.m_offset; } /** Returns \c true if other \p points to a position behind this iterator; * otherwise returns \c false. */ bool operator<(const const_iterator& other) const { return (m_querySet == other.m_querySet && m_offset < other.m_offset) || m_querySet < other.m_querySet; } /** Returns \c true if other \p points to a position behind or equal this iterator; * otherwise returns \c false. */ bool operator<=(const const_iterator& other) const { return (m_querySet == other.m_querySet && m_offset <= other.m_offset) || m_querySet < other.m_querySet; } /** Returns \c true if other \p points to a position before this iterator; * otherwise returns \c false. */ bool operator>(const const_iterator& other) const { return (m_querySet == other.m_querySet && m_offset > other.m_offset) || m_querySet > other.m_querySet; } /** Returns \c true if other \p points to a position before or equal this iterator; * otherwise returns \c false. */ bool operator>=(const const_iterator& other) const { return (m_querySet == other.m_querySet && m_offset >= other.m_offset) || m_querySet > other.m_querySet; } /** The prefix ++ operator (\c ++it) advances the iterator to the next item in the set * and returns an iterator to the new current item. * * Calling this function on QDjangoQuerySet::end() leads to undefined results. * * \sa operator--() */ const_iterator &operator++() { ++m_offset; return *this; } /** The postfix ++ operator (\c it++) advances the iterator to the next item in the set and * returns an iterator to the previously current item. * * Calling this function on QDjangoQuerySet::end() leads to undefined results. * * \sa operator--(int) */ const_iterator operator++(int) { const_iterator n(*this); ++m_offset; return n; } /** Advances the iterator by \p i items. * (If \p i is negative, the iterator goes backward.) * * \sa operator-=() and operator+(). */ const_iterator &operator+=(int i) { m_offset += i; return *this; } /** Returns an iterator to the item at \p i positions forward from this iterator. * (If \p i is negative, the iterator goes backward.) * * \sa operator-() and operator+=() */ const_iterator operator+(int i) const { return const_iterator(m_querySet, m_offset + i); } /** Makes the iterator go back by \p i items. * (If \p i is negative, the iterator goes forward.) * * \sa operator+=() and operator-() */ const_iterator &operator-=(int i) { m_offset -= i; return *this; } /** Returns an iterator to the item at \p i positions backward from this iterator. * (If \p i is negative, the iterator goes forward.) * * \sa operator+() and operator-=() */ const_iterator operator-(int i) const { return const_iterator(m_querySet, m_offset - i); } /** The prefix -- operator (\c --it) makes the preceding item current * and returns an iterator to the new current item. * * Calling this function on QDjangoQuerySet::begin() leads to undefined results. * * \sa operator++(). */ const_iterator &operator--() { --m_offset; return *this; } /** The postfix -- operator (\c it--) makes the preceding item current * and returns an iterator to the previously current item. * * Calling this function on QDjangoQuerySet::begin() leads to undefined results. * * \sa operator++(int). */ const_iterator operator--(int) { const_iterator n(*this); --m_offset; return n; } /** Returns the number of items between the item pointed to by \p other * and the item pointed to by this iterator. */ difference_type operator-(const const_iterator &other) const { return m_offset - other.m_offset; } private: const T *t() const { if (m_fetched != m_offset && m_querySet) { if (const_cast *>(m_querySet)->at(m_offset, &m_object)) { m_fetched = m_offset; } } return m_fetched == m_offset ? &m_object : 0; } private: const QDjangoQuerySet *m_querySet; mutable int m_fetched; mutable T m_object; int m_offset; }; /** Qt-style synonym for QDjangoQuerySet::const_iterator. */ typedef const_iterator ConstIterator; QDjangoQuerySet(); QDjangoQuerySet(const QDjangoQuerySet &other); ~QDjangoQuerySet(); QDjangoQuerySet all() const; QDjangoQuerySet exclude(const QDjangoWhere &where) const; QDjangoQuerySet filter(const QDjangoWhere &where) const; QDjangoQuerySet limit(int pos, int length = -1) const; QDjangoQuerySet none() const; QDjangoQuerySet orderBy(const QStringList &keys) const; QDjangoQuerySet selectRelated() const; int count() const; QDjangoWhere where() const; bool remove(); int size(); int update(const QVariantMap &fields); QList values(const QStringList &fields = QStringList()); QList valuesList(const QStringList &fields = QStringList()); T *get(const QDjangoWhere &where, T *target = 0) const; T *at(int index, T *target = 0); const_iterator constBegin() const; const_iterator begin() const; const_iterator constEnd() const; const_iterator end() const; QDjangoQuerySet &operator=(const QDjangoQuerySet &other); private: QDjangoQuerySetPrivate *d; }; /** Constructs a new queryset. */ template QDjangoQuerySet::QDjangoQuerySet() { d = new QDjangoQuerySetPrivate(T::staticMetaObject.className()); } /** Constructs a copy of \a other. * * \param other */ template QDjangoQuerySet::QDjangoQuerySet(const QDjangoQuerySet &other) { other.d->counter.ref(); d = other.d; } /** Destroys the queryset. */ template QDjangoQuerySet::~QDjangoQuerySet() { if (!d->counter.deref()) delete d; } /** Returns the object in the QDjangoQuerySet at the given index. * * Returns 0 if the index is out of bounds. * * If target is 0, a new object instance will be allocated which * you must free yourself. * * \param index * \param target optional existing model instance. */ template T *QDjangoQuerySet::at(int index, T *target) { T *entry = target ? target : new T; if (!d->sqlLoad(entry, index)) { if (!target) delete entry; return 0; } return entry; } /** Returns a const STL-style iterator pointing to the first object in the QDjangoQuerySet. * * \sa begin() and constEnd(). */ template typename QDjangoQuerySet::const_iterator QDjangoQuerySet::constBegin() const { return const_iterator(this); } /** Returns a const STL-style iterator pointing to the first object in the QDjangoQuerySet. * * \sa constBegin() and end(). */ template typename QDjangoQuerySet::const_iterator QDjangoQuerySet::begin() const { return const_iterator(this); } /** Returns a const STL-style iterator pointing to the imaginary object after the last * object in the QDjangoQuerySet. * * \sa constBegin() and end(). */ template typename QDjangoQuerySet::const_iterator QDjangoQuerySet::constEnd() const { return const_iterator(this, QDjangoQuerySet::count()); } /** Returns a const STL-style iterator pointing to the imaginary object after the last * object in the QDjangoQuerySet. * * \sa begin() and constEnd(). */ template typename QDjangoQuerySet::const_iterator QDjangoQuerySet::end() const { return const_iterator(this, QDjangoQuerySet::count()); } /** Returns a copy of the current QDjangoQuerySet. */ template QDjangoQuerySet QDjangoQuerySet::all() const { QDjangoQuerySet other; other.d->lowMark = d->lowMark; other.d->highMark = d->highMark; other.d->orderBy = d->orderBy; other.d->selectRelated = d->selectRelated; other.d->whereClause = d->whereClause; return other; } /** Counts the number of objects in the queryset using an SQL COUNT query, * or -1 if the query failed. * * If you intend to iterate over the results, you should consider using * size() instead. * * \note If the QDjangoQuerySet is already fully fetched, this simply returns * the number of objects. */ template int QDjangoQuerySet::count() const { if (d->hasResults) return d->properties.size(); // execute COUNT query QDjangoQuery query(d->countQuery()); if (!query.exec() || !query.next()) return -1; return query.value(0).toInt(); } /** Returns a new QDjangoQuerySet containing objects for which the given key * where condition is false. * * You can chain calls to filter() and exclude() to further refine the * filtering conditions. * * \param where QDjangoWhere expressing the exclude condition * * \sa filter() */ template QDjangoQuerySet QDjangoQuerySet::exclude(const QDjangoWhere &where) const { QDjangoQuerySet other = all(); other.d->addFilter(!where); return other; } /** Returns a new QDjangoQuerySet containing objects for which the given * where condition is true. * * You can chain calls to filter() and exclude() to progressively refine * your filtering conditions. * * \param where QDjangoWhere expressing the filter condition * * \sa exclude() */ template QDjangoQuerySet QDjangoQuerySet::filter(const QDjangoWhere &where) const { QDjangoQuerySet other = all(); other.d->addFilter(where); return other; } /** Returns the object in the QDjangoQuerySet for which the given * where condition is true. * * Returns 0 if the number of matching object is not exactly one. * * If target is 0, a new object instance will be allocated which * you must free yourself. * * \param where QDjangoWhere expressing the lookup condition * \param target optional existing model instance. */ template T *QDjangoQuerySet::get(const QDjangoWhere &where, T *target) const { QDjangoQuerySet qs = filter(where); return qs.size() == 1 ? qs.at(0, target) : 0; } /** Returns a new QDjangoQuerySet containing limiting the number of * records to manipulate. * * You can chain calls to limit() to further restrict the number * of returned records. * * However, you cannot apply additional restrictions using filter(), * exclude(), get(), orderBy() or remove() on the returned QDjangoQuerySet. * * \param pos offset of the records * \param length maximum number of records */ template QDjangoQuerySet QDjangoQuerySet::limit(int pos, int length) const { Q_ASSERT(pos >= 0); Q_ASSERT(length >= -1); QDjangoQuerySet other = all(); other.d->lowMark += pos; if (length > 0) { // calculate new high mark other.d->highMark = other.d->lowMark + length; // never exceed the current high mark if (d->highMark > 0 && other.d->highMark > d->highMark) other.d->highMark = d->highMark; } return other; } /** Returns an empty QDjangoQuerySet. */ template QDjangoQuerySet QDjangoQuerySet::none() const { QDjangoQuerySet other; other.d->whereClause = !QDjangoWhere(); return other; } /** Returns a QDjangoQuerySet whose elements are ordered using the given keys. * * By default the elements will by in ascending order. You can prefix the key * names with a "-" (minus sign) to use descending order. * * \param keys */ template QDjangoQuerySet QDjangoQuerySet::orderBy(const QStringList &keys) const { // it is not possible to change ordering once a limit has been set Q_ASSERT(!d->lowMark && !d->highMark); QDjangoQuerySet other = all(); other.d->orderBy << keys; return other; } /** Deletes all objects in the QDjangoQuerySet. * * \return true if deletion succeeded, false otherwise */ template bool QDjangoQuerySet::remove() { return d->sqlDelete(); } /** Returns a QDjangoQuerySet that will automatically "follow" foreign-key * relationships, selecting that additional related-object data when it * executes its query. */ template QDjangoQuerySet QDjangoQuerySet::selectRelated() const { QDjangoQuerySet other = all(); other.d->selectRelated = true; return other; } /** Returns the number of objects in the QDjangoQuerySet, or -1 * if the query failed. * * If you do not plan to access the objects, you should consider using * count() instead. */ template int QDjangoQuerySet::size() { if (!d->sqlFetch()) return -1; return d->properties.size(); } /** Performs an SQL update query for the specified \a fields and returns the * number of rows affected, or -1 if the update failed. */ template int QDjangoQuerySet::update(const QVariantMap &fields) { return d->sqlUpdate(fields); } /** Returns a list of property hashes for the current QDjangoQuerySet. * If no \a fields are specified, all the model's declared fields are returned. * * \param fields */ template QList QDjangoQuerySet::values(const QStringList &fields) { return d->sqlValues(fields); } /** Returns a list of property lists for the current QDjangoQuerySet. * If no \a fields are specified, all the model's fields are returned in the * order they where declared. * * \param fields */ template QList QDjangoQuerySet::valuesList(const QStringList &fields) { return d->sqlValuesList(fields); } /** Returns the QDjangoWhere expressing the WHERE clause of the * QDjangoQuerySet. */ template QDjangoWhere QDjangoQuerySet::where() const { return d->resolvedWhere(QDjango::database()); } /** Assigns the specified queryset to this object. * * \param other */ template QDjangoQuerySet &QDjangoQuerySet::operator=(const QDjangoQuerySet &other) { other.d->counter.ref(); if (!d->counter.deref()) delete d; d = other.d; return *this; } #endif qdjango-0.6.2/src/db/QDjangoQuerySet_p.h000066400000000000000000000065131261212605400200370ustar00rootroot00000000000000/* * Copyright (C) 2010-2015 Jeremy Lainé * Contact: https://github.com/jlaine/qdjango * * This file is part of the QDjango Library. * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * This library 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 * Lesser General Public License for more details. */ #ifndef QDJANGO_QUERYSET_P_H #define QDJANGO_QUERYSET_P_H // // W A R N I N G // ------------- // // This file is not part of the QDjango API. // #include #include "QDjango_p.h" #include "QDjangoWhere.h" class QDjangoMetaModel; class QDJANGO_DB_EXPORT QDjangoModelReference { public: QDjangoModelReference(const QString &tableReference_ = QString(), const QDjangoMetaModel &metaModel_ = QDjangoMetaModel(), bool nullable_ = false) : tableReference(tableReference_) , metaModel(metaModel_) , nullable(nullable_) { }; QString tableReference; QDjangoMetaModel metaModel; bool nullable; }; class QDJANGO_DB_EXPORT QDjangoReverseReference { public: QString leftHandKey; QString rightHandKey; }; /** \internal */ class QDJANGO_DB_EXPORT QDjangoCompiler { public: QDjangoCompiler(const char *modelName, const QSqlDatabase &db); QString fromSql(); QStringList fieldNames(bool recurse, QDjangoMetaModel *metaModel = 0, const QString &modelPath = QString(), bool nullable = false); QString orderLimitSql(const QStringList &orderBy, int lowMark, int highMark); void resolve(QDjangoWhere &where); private: QString databaseColumn(const QString &name); QString referenceModel(const QString &modelPath, QDjangoMetaModel *metaModel, bool nullable); QSqlDriver *driver; QDjangoMetaModel baseModel; QMap modelRefs; QMap reverseModelRefs; QMap fieldColumnCache; }; /** \internal */ class QDJANGO_DB_EXPORT QDjangoQuerySetPrivate { public: QDjangoQuerySetPrivate(const char *modelName); void addFilter(const QDjangoWhere &where); QDjangoWhere resolvedWhere(const QSqlDatabase &db) const; bool sqlDelete(); bool sqlFetch(); bool sqlInsert(const QVariantMap &fields, QVariant *insertId = 0); bool sqlLoad(QObject *model, int index); int sqlUpdate(const QVariantMap &fields); QList sqlValues(const QStringList &fields); QList sqlValuesList(const QStringList &fields); // SQL queries QDjangoQuery countQuery() const; QDjangoQuery deleteQuery() const; QDjangoQuery insertQuery(const QVariantMap &fields) const; QDjangoQuery selectQuery() const; QDjangoQuery updateQuery(const QVariantMap &fields) const; // reference counter QAtomicInt counter; bool hasResults; int lowMark; int highMark; QDjangoWhere whereClause; QStringList orderBy; QList properties; bool selectRelated; private: Q_DISABLE_COPY(QDjangoQuerySetPrivate) QByteArray m_modelName; friend class QDjangoMetaModel; }; #endif qdjango-0.6.2/src/db/QDjangoWhere.cpp000066400000000000000000000360611261212605400173450ustar00rootroot00000000000000/* * Copyright (C) 2010-2015 Jeremy Lainé * Contact: https://github.com/jlaine/qdjango * * This file is part of the QDjango Library. * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * This library 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 * Lesser General Public License for more details. */ #include #include #include "QDjango.h" #include "QDjangoWhere.h" #include "QDjangoWhere_p.h" static QString escapeLike(const QString &data) { QString escaped = data; escaped.replace(QLatin1String("%"), QLatin1String("\\%")); escaped.replace(QLatin1String("_"), QLatin1String("\\_")); return escaped; } /// \cond QDjangoWherePrivate::QDjangoWherePrivate() : operation(QDjangoWhere::None) , combine(NoCombine) , negate(false) { } /// \endcond /*! \enum QDjangoWhere::Operation A comparison operation on a database column value. \var QDjangoWhere::Operation QDjangoWhere::None No comparison, always returns true. \var QDjangoWhere::Operation QDjangoWhere::Equals Returns true if the column value is equal to the given value. \var QDjangoWhere::Operation QDjangoWhere::IEquals Returns true if the column value is equal to the given value (case-insensitive) \var QDjangoWhere::Operation QDjangoWhere::NotEquals Returns true if the column value is not equal to the given value. \var QDjangoWhere::Operation QDjangoWhere::INotEquals Returns true if the column value is not equal to the given value (case-insensitive). \var QDjangoWhere::Operation QDjangoWhere::GreaterThan, Returns true if the column value is greater than the given value. \var QDjangoWhere::Operation QDjangoWhere::LessThan, Returns true if the column value is less than the given value. \var QDjangoWhere::Operation QDjangoWhere::GreaterOrEquals, Returns true if the column value is greater or equal to the given value. \var QDjangoWhere::Operation QDjangoWhere::LessOrEquals, Returns true if the column value is less or equal to the given value. \var QDjangoWhere::Operation QDjangoWhere::StartsWith, Returns true if the column value starts with the given value (strings only). \var QDjangoWhere::Operation QDjangoWhere::IStartsWith, Returns true if the column value starts with the given value (strings only, case-insensitive). \var QDjangoWhere::Operation QDjangoWhere::EndsWith, Returns true if the column value ends with the given value (strings only). \var QDjangoWhere::Operation QDjangoWhere::IEndsWith, Returns true if the column value ends with the given value (strings only, case-insensitive). \var QDjangoWhere::Operation QDjangoWhere::Contains, Returns true if the column value contains the given value (strings only). \var QDjangoWhere::Operation QDjangoWhere::IContains, Returns true if the column value contains the given value (strings only, case-insensitive). \var QDjangoWhere::Operation QDjangoWhere::IsIn, Returns true if the column value is one of the given values. \var QDjangoWhere::Operation QDjangoWhere::IsNull Returns true if the column value is null. */ /** Constructs an empty QDjangoWhere, which expresses no constraint. */ QDjangoWhere::QDjangoWhere() { d = new QDjangoWherePrivate; } /** Constructs a copy of \a other. */ QDjangoWhere::QDjangoWhere(const QDjangoWhere &other) : d(other.d) { } /** Constructs a QDjangoWhere expressing a constraint on a database column. * * \param key * \param operation * \param value */ QDjangoWhere::QDjangoWhere(const QString &key, QDjangoWhere::Operation operation, QVariant value) { d = new QDjangoWherePrivate; d->key = key; d->operation = operation; d->data = value; } /** Destroys a QDjangoWhere. */ QDjangoWhere::~QDjangoWhere() { } /** Assigns \a other to this QDjangoWhere. */ QDjangoWhere& QDjangoWhere::operator=(const QDjangoWhere& other) { d = other.d; return *this; } /** Negates the current QDjangoWhere. */ QDjangoWhere QDjangoWhere::operator!() const { QDjangoWhere result; result.d = d; if (d->children.isEmpty()) { switch (d->operation) { case None: case IsIn: case StartsWith: case IStartsWith: case EndsWith: case IEndsWith: case Contains: case IContains: result.d->negate = !d->negate; break; case IsNull: // simplify !(is null) to is not null result.d->data = !d->data.toBool(); break; case Equals: // simplify !(a = b) to a != b result.d->operation = NotEquals; break; case IEquals: // simplify !(a = b) to a != b result.d->operation = INotEquals; break; case NotEquals: // simplify !(a != b) to a = b result.d->operation = Equals; break; case INotEquals: // simplify !(a != b) to a = b result.d->operation = IEquals; break; case GreaterThan: // simplify !(a > b) to a <= b result.d->operation = LessOrEquals; break; case LessThan: // simplify !(a < b) to a >= b result.d->operation = GreaterOrEquals; break; case GreaterOrEquals: // simplify !(a >= b) to a < b result.d->operation = LessThan; break; case LessOrEquals: // simplify !(a <= b) to a > b result.d->operation = GreaterThan; break; } } else { result.d->negate = !d->negate; } return result; } /** Combines the current QDjangoWhere with the \a other QDjangoWhere using * a logical AND. * * \param other */ QDjangoWhere QDjangoWhere::operator&&(const QDjangoWhere &other) const { if (isAll() || other.isNone()) return other; else if (isNone() || other.isAll()) return *this; if (d->combine == QDjangoWherePrivate::AndCombine) { QDjangoWhere result = *this; result.d->children << other; return result; } QDjangoWhere result; result.d->combine = QDjangoWherePrivate::AndCombine; result.d->children << *this << other; return result; } /** Combines the current QDjangoWhere with the \a other QDjangoWhere using * a logical OR. * * \param other */ QDjangoWhere QDjangoWhere::operator||(const QDjangoWhere &other) const { if (isAll() || other.isNone()) return *this; else if (isNone() || other.isAll()) return other; if (d->combine == QDjangoWherePrivate::OrCombine) { QDjangoWhere result = *this; result.d->children << other; return result; } QDjangoWhere result; result.d->combine = QDjangoWherePrivate::OrCombine; result.d->children << *this << other; return result; } /** Bind the values associated with this QDjangoWhere to the given \a query. * * \param query */ void QDjangoWhere::bindValues(QDjangoQuery &query) const { if (d->operation == QDjangoWhere::IsIn) { const QList values = d->data.toList(); for (int i = 0; i < values.size(); i++) query.addBindValue(values[i]); } else if (d->operation == QDjangoWhere::IsNull) { // no data to bind } else if (d->operation == QDjangoWhere::StartsWith || d->operation == QDjangoWhere::IStartsWith) { query.addBindValue(escapeLike(d->data.toString()) + QLatin1String("%")); } else if (d->operation == QDjangoWhere::EndsWith || d->operation == QDjangoWhere::IEndsWith) { query.addBindValue(QLatin1String("%") + escapeLike(d->data.toString())); } else if (d->operation == QDjangoWhere::Contains || d->operation == QDjangoWhere::IContains) { query.addBindValue(QLatin1String("%") + escapeLike(d->data.toString()) + QLatin1String("%")); } else if (d->operation != QDjangoWhere::None) { query.addBindValue(d->data); } else { foreach (const QDjangoWhere &child, d->children) child.bindValues(query); } } /** Returns true if the current QDjangoWhere does not express any constraint. */ bool QDjangoWhere::isAll() const { return d->combine == QDjangoWherePrivate::NoCombine && d->operation == None && d->negate == false; } /** Returns true if the current QDjangoWhere expressed an impossible constraint. */ bool QDjangoWhere::isNone() const { return d->combine == QDjangoWherePrivate::NoCombine && d->operation == None && d->negate == true; } /** Returns the SQL code corresponding for the current QDjangoWhere. */ /* Note - SQLite is always case-insensitive because it can't figure out case when using non-Ascii charcters: https://docs.djangoproject.com/en/dev/ref/databases/#sqlite-string-matching Note - MySQL is only case-sensitive when the collation is set as such: https://code.djangoproject.com/ticket/9682 */ QString QDjangoWhere::sql(const QSqlDatabase &db) const { QDjangoDatabase::DatabaseType databaseType = QDjangoDatabase::databaseType(db); switch (d->operation) { case Equals: return d->key + QLatin1String(" = ?"); case NotEquals: return d->key + QLatin1String(" != ?"); case GreaterThan: return d->key + QLatin1String(" > ?"); case LessThan: return d->key + QLatin1String(" < ?"); case GreaterOrEquals: return d->key + QLatin1String(" >= ?"); case LessOrEquals: return d->key + QLatin1String(" <= ?"); case IsIn: { QStringList bits; for (int i = 0; i < d->data.toList().size(); i++) bits << QLatin1String("?"); if (d->negate) return d->key + QString::fromLatin1(" NOT IN (%1)").arg(bits.join(QLatin1String(", "))); else return d->key + QString::fromLatin1(" IN (%1)").arg(bits.join(QLatin1String(", "))); } case IsNull: return d->key + QLatin1String(d->data.toBool() ? " IS NULL" : " IS NOT NULL"); case StartsWith: case EndsWith: case Contains: { QString op; if (databaseType == QDjangoDatabase::MySqlServer) op = QLatin1String(d->negate ? "NOT LIKE BINARY" : "LIKE BINARY"); else op = QLatin1String(d->negate ? "NOT LIKE" : "LIKE"); if (databaseType == QDjangoDatabase::SQLite) return d->key + QLatin1String(" ") + op + QLatin1String(" ? ESCAPE '\\'"); else return d->key + QLatin1String(" ") + op + QLatin1String(" ?"); } case IStartsWith: case IEndsWith: case IContains: case IEquals: { const QString op = QLatin1String(d->negate ? "NOT LIKE" : "LIKE"); if (databaseType == QDjangoDatabase::SQLite) return d->key + QLatin1String(" ") + op + QLatin1String(" ? ESCAPE '\\'"); else if (databaseType == QDjangoDatabase::PostgreSQL) return QLatin1String("UPPER(") + d->key + QLatin1String("::text) ") + op + QLatin1String(" UPPER(?)"); else return d->key + QLatin1String(" ") + op + QLatin1String(" ?"); } case INotEquals: { const QString op = QLatin1String(d->negate ? "LIKE" : "NOT LIKE"); if (databaseType == QDjangoDatabase::SQLite) return d->key + QLatin1String(" ") + op + QLatin1String(" ? ESCAPE '\\'"); else if (databaseType == QDjangoDatabase::PostgreSQL) return QLatin1String("UPPER(") + d->key + QLatin1String("::text) ") + op + QLatin1String(" UPPER(?)"); else return d->key + QLatin1String(" ") + op + QLatin1String(" ?"); } case None: if (d->combine == QDjangoWherePrivate::NoCombine) { return d->negate ? QLatin1String("1 != 0") : QString(); } else { QStringList bits; foreach (const QDjangoWhere &child, d->children) { QString atom = child.sql(db); if (child.d->children.isEmpty()) bits << atom; else bits << QString::fromLatin1("(%1)").arg(atom); } QString combined; if (d->combine == QDjangoWherePrivate::AndCombine) combined = bits.join(QLatin1String(" AND ")); else if (d->combine == QDjangoWherePrivate::OrCombine) combined = bits.join(QLatin1String(" OR ")); if (d->negate) combined = QString::fromLatin1("NOT (%1)").arg(combined); return combined; } } return QString(); } QString QDjangoWhere::toString() const { if (d->combine == QDjangoWherePrivate::NoCombine) { return QLatin1String("QDjangoWhere(") + "key=\"" + d->key + "\"" + ", operation=\"" + QDjangoWherePrivate::operationToString(d->operation) + "\"" + ", value=\"" + d->data.toString() + "\"" + ", negate=" + (d->negate ? "true":"false") + ")"; } else { QStringList bits; foreach (const QDjangoWhere &childWhere, d->children) { bits.append(childWhere.toString()); } if (d->combine == QDjangoWherePrivate::OrCombine) { return bits.join(" || "); } else { return bits.join(" && "); } } } QString QDjangoWherePrivate::operationToString(QDjangoWhere::Operation operation) { switch (operation) { case QDjangoWhere::Equals: return QLatin1String("Equals"); case QDjangoWhere::IEquals: return QLatin1String("IEquals"); case QDjangoWhere::NotEquals: return QLatin1String("NotEquals"); case QDjangoWhere::INotEquals: return QLatin1String("INotEquals"); case QDjangoWhere::GreaterThan: return QLatin1String("GreaterThan"); case QDjangoWhere::LessThan: return QLatin1String("LessThan"); case QDjangoWhere::GreaterOrEquals: return QLatin1String("GreaterOrEquals"); case QDjangoWhere::LessOrEquals: return QLatin1String("LessOrEquals"); case QDjangoWhere::StartsWith: return QLatin1String("StartsWith"); case QDjangoWhere::IStartsWith: return QLatin1String("IStartsWith"); case QDjangoWhere::EndsWith: return QLatin1String("EndsWith"); case QDjangoWhere::IEndsWith: return QLatin1String("IEndsWith"); case QDjangoWhere::Contains: return QLatin1String("Contains"); case QDjangoWhere::IContains: return QLatin1String("IContains"); case QDjangoWhere::IsIn: return QLatin1String("IsIn"); case QDjangoWhere::IsNull: return QLatin1String("IsNull"); case QDjangoWhere::None: default: return QLatin1String(""); } return QString(); } qdjango-0.6.2/src/db/QDjangoWhere.h000066400000000000000000000043671261212605400170160ustar00rootroot00000000000000/* * Copyright (C) 2010-2015 Jeremy Lainé * Contact: https://github.com/jlaine/qdjango * * This file is part of the QDjango Library. * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * This library 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 * Lesser General Public License for more details. */ #ifndef QDJANGO_WHERE_H #define QDJANGO_WHERE_H #include #include #include "QDjango_p.h" class QDjangoMetaModel; class QDjangoQuery; class QDjangoWherePrivate; /** \brief The QDjangoWhere class expresses an SQL constraint. * * The QDjangoWhere class is used to build SQL WHERE statements. In its * simplest form a QDjangoWhere expresses a constraint on a column value. * * QDjangoWhere instances can be negated using the "!" unary operator * or combined using the "&&" and "||" boolean operators. * * \ingroup Database */ class QDJANGO_DB_EXPORT QDjangoWhere { public: enum Operation { None, Equals, NotEquals, GreaterThan, LessThan, GreaterOrEquals, LessOrEquals, StartsWith, EndsWith, Contains, IsIn, IsNull, IEquals, INotEquals, IStartsWith, IEndsWith, IContains }; QDjangoWhere(); QDjangoWhere(const QDjangoWhere &other); QDjangoWhere(const QString &key, QDjangoWhere::Operation operation, QVariant value); ~QDjangoWhere(); QDjangoWhere& operator=(const QDjangoWhere &other); QDjangoWhere operator!() const; QDjangoWhere operator&&(const QDjangoWhere &other) const; QDjangoWhere operator||(const QDjangoWhere &other) const; void bindValues(QDjangoQuery &query) const; bool isAll() const; bool isNone() const; QString sql(const QSqlDatabase &db) const; QString toString() const; private: QSharedDataPointer d; friend class QDjangoCompiler; }; #endif qdjango-0.6.2/src/db/QDjangoWhere_p.h000066400000000000000000000024451261212605400173300ustar00rootroot00000000000000/* * Copyright (C) 2010-2015 Jeremy Lainé * Contact: https://github.com/jlaine/qdjango * * This file is part of the QDjango Library. * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * This library 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 * Lesser General Public License for more details. */ #ifndef QDJANGO_WHERE_P_H #define QDJANGO_WHERE_P_H // // W A R N I N G // ------------- // // This file is not part of the QDjango API. // #include #include "QDjangoWhere.h" class QDjangoWherePrivate : public QSharedData { public: static QString operationToString(QDjangoWhere::Operation operation); enum Combine { NoCombine, AndCombine, OrCombine }; static QString combineToString(Combine combine); QDjangoWherePrivate(); QString key; QDjangoWhere::Operation operation; QVariant data; QList children; Combine combine; bool negate; }; #endif qdjango-0.6.2/src/db/QDjango_p.h000066400000000000000000000036311261212605400163330ustar00rootroot00000000000000/* * Copyright (C) 2010-2015 Jeremy Lainé * Contact: https://github.com/jlaine/qdjango * * This file is part of the QDjango Library. * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * This library 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 * Lesser General Public License for more details. */ #ifndef QDJANGO_P_H #define QDJANGO_P_H #include #include #include #include #include #include #include #if defined(QDJANGO_SHARED) # if defined(QDJANGO_DB_BUILD) # define QDJANGO_DB_EXPORT Q_DECL_EXPORT # else # define QDJANGO_DB_EXPORT Q_DECL_IMPORT # endif #else # define QDJANGO_DB_EXPORT #endif /** \brief The QDjangoDatabase class represents a set of connections to a * database. * * \internal */ class QDJANGO_DB_EXPORT QDjangoDatabase : public QObject { Q_OBJECT public: QDjangoDatabase(QObject *parent = 0); enum DatabaseType { UnknownDB, MSSqlServer, MySqlServer, PostgreSQL, Oracle, Sybase, SQLite, Interbase, DB2 }; static DatabaseType databaseType(const QSqlDatabase &db); QSqlDatabase reference; QMutex mutex; QMap copies; qint64 connectionId; private slots: void threadFinished(); }; class QDJANGO_DB_EXPORT QDjangoQuery : public QSqlQuery { public: QDjangoQuery(QSqlDatabase db); void addBindValue(const QVariant &val, QSql::ParamType paramType = QSql::In); bool exec(); bool exec(const QString &query); }; #endif qdjango-0.6.2/src/db/db.pro000066400000000000000000000010651261212605400154260ustar00rootroot00000000000000include(../../qdjango.pri) QT -= gui QT += sql DEFINES += QDJANGO_DB_BUILD TARGET = qdjango-db win32 { DESTDIR = $$OUT_PWD } HEADERS += \ QDjango.h \ QDjango_p.h \ QDjangoMetaModel.h \ QDjangoModel.h \ QDjangoQuerySet.h \ QDjangoQuerySet_p.h \ QDjangoWhere.h \ QDjangoWhere_p.h SOURCES += \ QDjango.cpp \ QDjangoMetaModel.cpp \ QDjangoModel.cpp \ QDjangoQuerySet.cpp \ QDjangoWhere.cpp # Installation include(../src.pri) headers.path = $$PREFIX/include/qdjango/db QMAKE_PKGCONFIG_INCDIR = $$headers.path qdjango-0.6.2/src/http/000077500000000000000000000000001261212605400147075ustar00rootroot00000000000000qdjango-0.6.2/src/http/QDjangoFastCgiServer.cpp000066400000000000000000000327711261212605400214000ustar00rootroot00000000000000/* * Copyright (C) 2010-2015 Jeremy Lainé * Contact: https://github.com/jlaine/qdjango * * This file is part of the QDjango Library. * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * This library 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 * Lesser General Public License for more details. */ #include #include #include #include #include #include #include "QDjangoFastCgiServer.h" #include "QDjangoFastCgiServer_p.h" #include "QDjangoHttpController.h" #include "QDjangoHttpRequest.h" #include "QDjangoHttpRequest_p.h" #include "QDjangoHttpResponse.h" #include "QDjangoHttpResponse_p.h" #include "QDjangoHttpServer.h" #include "QDjangoUrlResolver.h" //#define QDJANGO_DEBUG_FCGI quint16 QDjangoFastCgiHeader::contentLength(FCGI_Header *header) { return (header->contentLengthB1 << 8) | header->contentLengthB0; } quint16 QDjangoFastCgiHeader::requestId(FCGI_Header *header) { return (header->requestIdB1 << 8) | header->requestIdB0; } void QDjangoFastCgiHeader::setContentLength(FCGI_Header *header, quint16 contentLength) { header->contentLengthB1 = (contentLength >> 8) & 0xff; header->contentLengthB0 = (contentLength & 0xff); } void QDjangoFastCgiHeader::setRequestId(FCGI_Header *header, quint16 requestId) { header->requestIdB1 = (requestId >> 8) & 0xff; header->requestIdB0 = (requestId & 0xff); } #ifdef QDJANGO_DEBUG_FCGI static void hDebug(FCGI_Header *header, const char *dir) { qDebug("--- FCGI Record %s ---", dir); qDebug("version: %i", header->version); qDebug("type: %i", header->type); qDebug("requestId: %i", QDjangoFastCgiHeader::requestId(header)); qDebug("contentLength: %i", QDjangoFastCgiHeader::contentLength(header)); qDebug("paddingLength: %i", header->paddingLength); } #endif /// \cond QDjangoFastCgiConnection::QDjangoFastCgiConnection(QIODevice *device, QDjangoFastCgiServer *server) : QObject(server) , m_device(device) , m_inputPos(0) , m_keepConnection(false) , m_pendingRequest(0) , m_pendingRequestId(0) , m_server(server) { bool check; Q_UNUSED(check); m_device->setParent(this); check = connect(m_device, SIGNAL(disconnected()), this, SIGNAL(closed())); Q_ASSERT(check); check = connect(m_device, SIGNAL(bytesWritten(qint64)), this, SLOT(_q_bytesWritten(qint64))); Q_ASSERT(check); check = connect(m_device, SIGNAL(readyRead()), this, SLOT(_q_readyRead())); Q_ASSERT(check); } QDjangoFastCgiConnection::~QDjangoFastCgiConnection() { if (m_pendingRequest) delete m_pendingRequest; } void QDjangoFastCgiConnection::writeResponse(quint16 requestId, QDjangoHttpResponse *response) { // serialise HTTP response QString httpHeader = QString::fromLatin1("Status: %1 %2\r\n").arg(response->d->statusCode).arg(response->d->reasonPhrase); QList >::ConstIterator it = response->d->headers.constBegin(); while (it != response->d->headers.constEnd()) { httpHeader += (*it).first + QLatin1String(": ") + (*it).second + QLatin1String("\r\n"); ++it; } const QByteArray data = httpHeader.toUtf8() + "\r\n" + response->d->body; const char *ptr = data.constData(); FCGI_Header *header = (FCGI_Header*)m_outputBuffer; memset(header, 0, FCGI_HEADER_LEN); header->version = 1; QDjangoFastCgiHeader::setRequestId(header, requestId); for (qint64 bytesRemaining = data.size(); ; ) { const quint16 contentLength = qMin(bytesRemaining, qint64(32768)); header->type = FCGI_STDOUT; QDjangoFastCgiHeader::setContentLength(header, contentLength); memcpy(m_outputBuffer + FCGI_HEADER_LEN, ptr, contentLength); m_device->write(m_outputBuffer, FCGI_HEADER_LEN + contentLength); #ifdef QDJANGO_DEBUG_FCGI hDebug(header, "sent"); qDebug("[STDOUT]"); #endif if (contentLength > 0) { ptr += contentLength; bytesRemaining -= contentLength; } else { break; } } quint16 contentLength = 8; header->type = FCGI_END_REQUEST; QDjangoFastCgiHeader::setContentLength(header, contentLength); memset(m_outputBuffer + FCGI_HEADER_LEN, 0, contentLength); m_device->write(m_outputBuffer, FCGI_HEADER_LEN + contentLength); #ifdef QDJANGO_DEBUG_FCGI hDebug(header, "sent"); qDebug("[END REQUEST]"); #endif } /** When bytes have been written, check whether we need to close * the connection. * * @param bytes */ void QDjangoFastCgiConnection::_q_bytesWritten(qint64 bytes) { Q_UNUSED(bytes); if (!m_device->bytesToWrite() && !m_keepConnection) { #ifdef QDJANGO_DEBUG_FCGI qDebug("Closing connection"); #endif m_device->close(); emit closed(); } } void QDjangoFastCgiConnection::_q_readyRead() { while (m_device->bytesAvailable()) { // read record header if (m_inputPos < FCGI_HEADER_LEN) { const qint64 length = m_device->read(m_inputBuffer + m_inputPos, FCGI_HEADER_LEN - m_inputPos); if (length < 0) { qWarning("Failed to read FastCGI record header from socket"); m_device->close(); emit closed(); return; } m_inputPos += length; if (m_inputPos < FCGI_HEADER_LEN) return; } // read record body FCGI_Header *header = (FCGI_Header*)m_inputBuffer; const quint16 contentLength = QDjangoFastCgiHeader::contentLength(header); const quint16 bodyLength = contentLength + header->paddingLength; const qint64 length = m_device->read(m_inputBuffer + m_inputPos, bodyLength + FCGI_HEADER_LEN - m_inputPos); if (length < 0) { qWarning("Failed to read FastCGI record body from socket"); m_device->close(); emit closed(); return; } m_inputPos += length; if (m_inputPos < FCGI_HEADER_LEN + bodyLength) return; m_inputPos = 0; // process record #ifdef QDJANGO_DEBUG_FCGI hDebug(header, "received"); #endif if (header->version != 1) { qWarning("Received FastCGI record with an invalid version %i", header->version); m_device->close(); emit closed(); return; } const quint16 requestId = QDjangoFastCgiHeader::requestId(header); if (header->type != FCGI_BEGIN_REQUEST && (!m_pendingRequest || requestId != m_pendingRequestId)) { qWarning("Received FastCGI record for an invalid request %i", requestId); m_device->close(); emit closed(); return; } quint8 *d = (quint8*)(m_inputBuffer + FCGI_HEADER_LEN); switch (header->type) { case FCGI_BEGIN_REQUEST: { const quint8 flags = d[2]; #ifdef QDJANGO_DEBUG_FCGI const quint16 role = (d[0] << 8) | d[1]; qDebug("[BEGIN REQUEST]"); qDebug("role: %i", role); qDebug("flags: %i", flags); #endif // we do not support multiplexing if (m_pendingRequest) { qWarning("Received new FastCGI request %i while already handling request %i", requestId, m_pendingRequestId); m_device->close(); emit closed(); return; } m_keepConnection = (flags & FCGI_KEEP_CONN); m_pendingRequest = new QDjangoHttpRequest; m_pendingRequestId = requestId; break; } case FCGI_ABORT_REQUEST: #ifdef QDJANGO_DEBUG_FCGI qDebug("[ABORT]"); #endif m_device->close(); emit closed(); return; case FCGI_PARAMS: #ifdef QDJANGO_DEBUG_FCGI qDebug("[PARAMS]"); #endif while (d < (quint8*)(m_inputBuffer + FCGI_HEADER_LEN + contentLength)) { quint32 nameLength; quint32 valueLength; if (d[0] >> 7) { nameLength = ((d[0] & 0x7f) << 24) | (d[1] << 16) | (d[2] << 8) | d[3]; d += 4; } else { nameLength = d[0]; d++; } if (d[0] >> 7) { valueLength = ((d[0] & 0x7f) << 24) | (d[1] << 16) | (d[2] << 8) | d[3]; d += 4; } else { valueLength = d[0]; d++; } const QByteArray name((char*)d, nameLength); d += nameLength; const QByteArray value((char*)d, valueLength); d += valueLength; #ifdef QDJANGO_DEBUG_FCGI qDebug() << name << ":" << value; #endif if (name == "PATH_INFO") { m_pendingRequest->d->path = QString::fromUtf8(value); } else if (name == "REQUEST_URI") { m_pendingRequest->d->path = QUrl(QString::fromUtf8(value)).path(); } else if (name == "REQUEST_METHOD") { m_pendingRequest->d->method = QString::fromUtf8(value); } m_pendingRequest->d->meta.insert(QString::fromLatin1(name), QString::fromUtf8(value)); } break; case FCGI_STDIN: #ifdef QDJANGO_DEBUG_FCGI qDebug("[STDIN]"); #endif if (contentLength) { m_pendingRequest->d->buffer.append((char*)d, contentLength); } else { // an empty STDIN record signals the end of the request QDjangoHttpRequest *request = m_pendingRequest; const quint16 requestId = m_pendingRequestId; m_pendingRequest = 0; m_pendingRequestId = 0; QDjangoHttpResponse *response = m_server->urls()->respond(*request, request->path()); writeResponse(requestId, response); } break; default: qWarning("Received FastCGI record with an invalid type %i", header->type); m_device->close(); emit closed(); return; } } } /// \endcond class QDjangoFastCgiServerPrivate { public: QDjangoFastCgiServerPrivate(QDjangoFastCgiServer *qq); QLocalServer *localServer; QTcpServer *tcpServer; QDjangoUrlResolver *urlResolver; private: QDjangoFastCgiServer *q; }; QDjangoFastCgiServerPrivate::QDjangoFastCgiServerPrivate(QDjangoFastCgiServer *qq) : localServer(0), tcpServer(0), q(qq) { urlResolver = new QDjangoUrlResolver(q); } /** Constructs a new FastCGI server. */ QDjangoFastCgiServer::QDjangoFastCgiServer(QObject *parent) : QObject(parent) { d = new QDjangoFastCgiServerPrivate(this); } /** Destroys the FastCGI server. */ QDjangoFastCgiServer::~QDjangoFastCgiServer() { delete d; } /** Closes the server. The server will no longer listen for * incoming connections. */ void QDjangoFastCgiServer::close() { if (d->localServer) d->localServer->close(); if (d->tcpServer) d->tcpServer->close(); } /** Tells the server to listen for incoming connections on the given * local socket. */ bool QDjangoFastCgiServer::listen(const QString &name) { if (!d->localServer) { bool check; Q_UNUSED(check); d->localServer = new QLocalServer(this); check = connect(d->localServer, SIGNAL(newConnection()), this, SLOT(_q_newLocalConnection())); Q_ASSERT(check); } return d->localServer->listen(name); } /** Tells the server to listen for incoming TCP connections on the given * \a address and \a port. */ bool QDjangoFastCgiServer::listen(const QHostAddress &address, quint16 port) { if (!d->tcpServer) { bool check; Q_UNUSED(check); d->tcpServer = new QTcpServer(this); check = connect(d->tcpServer, SIGNAL(newConnection()), this, SLOT(_q_newTcpConnection())); Q_ASSERT(check); } return d->tcpServer->listen(address, port); } /** Returns the root URL resolver for the server, which dispatches * requests to handlers. */ QDjangoUrlResolver* QDjangoFastCgiServer::urls() const { return d->urlResolver; } void QDjangoFastCgiServer::_q_newLocalConnection() { bool check; Q_UNUSED(check); QLocalSocket *socket; while ((socket = d->localServer->nextPendingConnection()) != 0) { #ifdef QDJANGO_DEBUG_FCGI qDebug("New local connection"); #endif QDjangoFastCgiConnection *connection = new QDjangoFastCgiConnection(socket, this); check = connect(connection, SIGNAL(closed()), connection, SLOT(deleteLater())); Q_ASSERT(check); } } void QDjangoFastCgiServer::_q_newTcpConnection() { bool check; Q_UNUSED(check); QTcpSocket *socket; while ((socket = d->tcpServer->nextPendingConnection()) != 0) { #ifdef QDJANGO_DEBUG_FCGI qDebug("New TCP connection"); #endif QDjangoFastCgiConnection *connection = new QDjangoFastCgiConnection(socket, this); check = connect(connection, SIGNAL(closed()), connection, SLOT(deleteLater())); Q_ASSERT(check); } } qdjango-0.6.2/src/http/QDjangoFastCgiServer.h000066400000000000000000000032321261212605400210330ustar00rootroot00000000000000/* * Copyright (C) 2010-2015 Jeremy Lainé * Contact: https://github.com/jlaine/qdjango * * This file is part of the QDjango Library. * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * This library 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 * Lesser General Public License for more details. */ #ifndef QDJANGO_FASTCGI_SERVER_H #define QDJANGO_FASTCGI_SERVER_H #include #include #include "QDjangoHttp_p.h" class QDjangoFastCgiServerPrivate; class QDjangoHttpController; class QDjangoUrlResolver; /** \brief The QDjangoFastCgiServer class represents a FastCGI server. * * It allows you to create a FastCGI server which your reverse proxy * (e.g. apache, nginx) will query to serve your web application. * * To register views, see urls(). * * \ingroup Http * \sa QDjangoHttpServer */ class QDJANGO_HTTP_EXPORT QDjangoFastCgiServer : public QObject { Q_OBJECT public: QDjangoFastCgiServer(QObject *parent = 0); ~QDjangoFastCgiServer(); void close(); bool listen(const QString &name); bool listen(const QHostAddress &address, quint16 port); QDjangoUrlResolver *urls() const; private slots: void _q_newLocalConnection(); void _q_newTcpConnection(); private: Q_DISABLE_COPY(QDjangoFastCgiServer) QDjangoFastCgiServerPrivate *d; }; #endif qdjango-0.6.2/src/http/QDjangoFastCgiServer_p.h000066400000000000000000000050101261212605400213460ustar00rootroot00000000000000/* * Copyright (C) 2010-2015 Jeremy Lainé * Contact: https://github.com/jlaine/qdjango * * This file is part of the QDjango Library. * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * This library 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 * Lesser General Public License for more details. */ #ifndef QDJANGO_FASTCGI_SERVER_P_H #define QDJANGO_FASTCGI_SERVER_P_H // // W A R N I N G // ------------- // // This file is not part of the QDjango API. // #include "QDjangoHttp_p.h" #include #define FCGI_HEADER_LEN 8 #define FCGI_RECORD_SIZE (255*255 + 255 + 8) #define FCGI_BEGIN_REQUEST 1 #define FCGI_ABORT_REQUEST 2 #define FCGI_END_REQUEST 3 #define FCGI_PARAMS 4 #define FCGI_STDIN 5 #define FCGI_STDOUT 6 #define FCGI_KEEP_CONN 1 class QDjangoFastCgiServer; class QDjangoHttpRequest; class QDjangoHttpResponse; class QIODevice; typedef struct { unsigned char version; unsigned char type; unsigned char requestIdB1; unsigned char requestIdB0; unsigned char contentLengthB1; unsigned char contentLengthB0; unsigned char paddingLength; unsigned char reserved; } FCGI_Header; class QDJANGO_HTTP_AUTOTEST_EXPORT QDjangoFastCgiHeader { public: static quint16 contentLength(FCGI_Header *header); static quint16 requestId(FCGI_Header *header); static void setContentLength(FCGI_Header *header, quint16 contentLength); static void setRequestId(FCGI_Header *header, quint16 requestId); }; class QDJANGO_HTTP_AUTOTEST_EXPORT QDjangoFastCgiConnection : public QObject { Q_OBJECT public: QDjangoFastCgiConnection(QIODevice *device, QDjangoFastCgiServer *server); ~QDjangoFastCgiConnection(); signals: void closed(); private slots: void _q_bytesWritten(qint64 bytes); void _q_readyRead(); private: void writeResponse(quint16 requestId, QDjangoHttpResponse *response); QIODevice *m_device; char m_inputBuffer[FCGI_RECORD_SIZE]; int m_inputPos; bool m_keepConnection; char m_outputBuffer[FCGI_RECORD_SIZE]; QDjangoHttpRequest *m_pendingRequest; quint16 m_pendingRequestId; QDjangoFastCgiServer *m_server; }; #endif qdjango-0.6.2/src/http/QDjangoHttpController.cpp000066400000000000000000000161021261212605400216420ustar00rootroot00000000000000/* * Copyright (C) 2010-2015 Jeremy Lainé * Contact: https://github.com/jlaine/qdjango * * This file is part of the QDjango Library. * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * This library 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 * Lesser General Public License for more details. */ #include #include #include #include #include #include #include #include #include "QDjangoHttpController.h" #include "QDjangoHttpRequest.h" #include "QDjangoHttpResponse.h" /** Extract basic credentials from an HTTP \a request. * * Returns \b true if credentials were provider, \b false otherwise. */ bool QDjangoHttpController::getBasicAuth(const QDjangoHttpRequest &request, QString &username, QString &password) { QRegExp authRx(QLatin1String("^Basic (.+)$")); const QString authHeader = request.meta(QLatin1String("HTTP_AUTHORIZATION")); if (authRx.exactMatch(authHeader)) { const QString authValue = QString::fromUtf8(QByteArray::fromBase64(authRx.cap(1).toLatin1())); const QStringList bits = authValue.split(QLatin1Char(':')); if (bits.size() == 2 && !bits[0].isEmpty() && !bits[1].isEmpty()) { username = bits[0]; password = bits[1]; return true; } } return false; } /** Converts a QDateTime to an HTTP datetime string. */ QString QDjangoHttpController::httpDateTime(const QDateTime &dt) { if (dt.isValid()) return QLocale("C").toString(dt.toUTC(), QLatin1String("ddd, dd MMM yyyy HH:mm:ss")) + QLatin1String(" GMT"); return QString(); } /** Converts an HTTP datetime string to a QDateTime. */ QDateTime QDjangoHttpController::httpDateTime(const QString &str) { QDateTime dt = QLocale("C").toDateTime(str.left(25), QLatin1String("ddd, dd MMM yyyy HH:mm:ss")); dt.setTimeSpec(Qt::UTC); return dt; } QDjangoHttpResponse *QDjangoHttpController::serveError(const QDjangoHttpRequest &request, int code, const QString &text) { Q_UNUSED(request); QDjangoHttpResponse *response = new QDjangoHttpResponse; response->setHeader(QLatin1String("Content-Type"), QLatin1String("text/html; charset=utf-8")); response->setStatusCode(code); response->setBody(QString::fromLatin1("" "Error" "

%1

" "").arg(text).toUtf8()); return response; } /** Respond to an HTTP \a request with an authorization error. * * \param request * \param realm */ QDjangoHttpResponse *QDjangoHttpController::serveAuthorizationRequired(const QDjangoHttpRequest &request, const QString &realm) { Q_UNUSED(request); QDjangoHttpResponse *response = new QDjangoHttpResponse; response->setStatusCode(QDjangoHttpResponse::AuthorizationRequired); response->setHeader(QLatin1String("WWW-Authenticate"), QString::fromLatin1("Basic realm=\"%1\"").arg(realm)); return response; } /** Respond to a malformed HTTP request. * * \param request */ QDjangoHttpResponse *QDjangoHttpController::serveBadRequest(const QDjangoHttpRequest &request) { return serveError(request, QDjangoHttpResponse::BadRequest, QLatin1String("Your browser sent a malformed request.")); } /** Respond to an HTTP \a request with an internal server error. * * \param request */ QDjangoHttpResponse *QDjangoHttpController::serveInternalServerError(const QDjangoHttpRequest &request) { return serveError(request, QDjangoHttpResponse::InternalServerError, QLatin1String("An internal server error was encountered.")); } /** Respond to an HTTP \a request with a not found error. * * \param request */ QDjangoHttpResponse *QDjangoHttpController::serveNotFound(const QDjangoHttpRequest &request) { return serveError(request, QDjangoHttpResponse::NotFound, QLatin1String("The document you requested was not found.")); } /** Respond to an HTTP \a request with a redirect. * * \param request * \param url The URL to which the user is redirected. * \param permanent Whether the redirect is permanent. */ QDjangoHttpResponse *QDjangoHttpController::serveRedirect(const QDjangoHttpRequest &request, const QUrl &url, bool permanent) { const QString urlString = url.toString(); QDjangoHttpResponse *response = serveError(request, permanent ? QDjangoHttpResponse::MovedPermanently : QDjangoHttpResponse::Found, QString::fromLatin1("You are being redirect to %2").arg(urlString, urlString)); response->setHeader(QLatin1String("Location"), urlString); return response; } /** Respond to an HTTP \a request for a static file. * * \param request * \param docPath The path to the document, such that it can be opened using a QFile. * \param expires An optional expiry date. */ QDjangoHttpResponse *QDjangoHttpController::serveStatic(const QDjangoHttpRequest &request, const QString &docPath, const QDateTime &expires) { QFileInfo info(docPath); if (!info.isFile()) return serveNotFound(request); const QString fileName = info.fileName(); QDjangoHttpResponse *response = new QDjangoHttpResponse; response->setStatusCode(QDjangoHttpResponse::OK); // determine last modified date QDateTime lastModified = info.lastModified(); if (docPath.startsWith(QLatin1String(":/"))) lastModified = QFileInfo(qApp->applicationFilePath()).lastModified(); if (lastModified.isValid()) response->setHeader(QLatin1String("Last-Modified"), httpDateTime(lastModified)); // cache expiry if (expires.isValid()) response->setHeader(QLatin1String("Expires"), httpDateTime(expires)); // handle if-modified-since const QDateTime ifModifiedSince = httpDateTime(request.meta(QLatin1String("HTTP_IF_MODIFIED_SINCE"))); if (lastModified.isValid() && ifModifiedSince.isValid() && lastModified <= ifModifiedSince) { response->setStatusCode(304); return response; } // determine content type QString mimeType; if (fileName.endsWith(QLatin1String(".css"))) mimeType = QLatin1String("text/css"); else if (fileName.endsWith(QLatin1String(".html"))) mimeType = QLatin1String("text/html"); else if (fileName.endsWith(QLatin1String(".js"))) mimeType = QLatin1String("application/javascript"); else mimeType = QLatin1String("application/octet-stream"); response->setHeader(QLatin1String("Content-Type"), mimeType); // read contents QFile file(docPath); if (!file.open(QIODevice::ReadOnly)) { delete response; return serveInternalServerError(request); } if (request.method() == QLatin1String("HEAD")) response->setHeader(QLatin1String("Content-Length"), QString::number(file.size())); else response->setBody(file.readAll()); return response; } qdjango-0.6.2/src/http/QDjangoHttpController.h000066400000000000000000000041621261212605400213120ustar00rootroot00000000000000/* * Copyright (C) 2010-2015 Jeremy Lainé * Contact: https://github.com/jlaine/qdjango * * This file is part of the QDjango Library. * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * This library 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 * Lesser General Public License for more details. */ #ifndef QDJANGO_HTTP_CONTROLLER_H #define QDJANGO_HTTP_CONTROLLER_H #include #include #include "QDjangoHttp_p.h" class QDjangoHttpRequest; class QDjangoHttpResponse; class QUrl; /** \brief The QDjangoHttpController class provides static methods for replying to HTTP requests. * * \ingroup Http */ class QDJANGO_HTTP_EXPORT QDjangoHttpController { public: // get basic authorization credentials static bool getBasicAuth(const QDjangoHttpRequest &request, QString &username, QString &password); // date / time handling static QString httpDateTime(const QDateTime &dt); static QDateTime httpDateTime(const QString &str); // common responses static QDjangoHttpResponse *serveAuthorizationRequired(const QDjangoHttpRequest &request, const QString &realm = QLatin1String("Secure Area")); static QDjangoHttpResponse *serveBadRequest(const QDjangoHttpRequest &request); static QDjangoHttpResponse *serveInternalServerError(const QDjangoHttpRequest &request); static QDjangoHttpResponse *serveNotFound(const QDjangoHttpRequest &request); static QDjangoHttpResponse *serveRedirect(const QDjangoHttpRequest &request, const QUrl &url, bool permanent = false); static QDjangoHttpResponse *serveStatic(const QDjangoHttpRequest &request, const QString &filePath, const QDateTime &expires = QDateTime()); private: static QDjangoHttpResponse *serveError(const QDjangoHttpRequest &request, int code, const QString &text); }; #endif qdjango-0.6.2/src/http/QDjangoHttpRequest.cpp000066400000000000000000000051041261212605400211470ustar00rootroot00000000000000/* * Copyright (C) 2010-2015 Jeremy Lainé * Contact: https://github.com/jlaine/qdjango * * This file is part of the QDjango Library. * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * This library 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 * Lesser General Public License for more details. */ #include #if (QT_VERSION >= QT_VERSION_CHECK(5, 0, 0)) #include #else #include #endif #include "QDjangoHttpRequest.h" #include "QDjangoHttpRequest_p.h" /** Constructs a new HTTP request. */ QDjangoHttpRequest::QDjangoHttpRequest() : d(new QDjangoHttpRequestPrivate) { } /** Destroys the HTTP request. */ QDjangoHttpRequest::~QDjangoHttpRequest() { delete d; } /** Returns the raw body of the HTTP request. */ QByteArray QDjangoHttpRequest::body() const { return d->buffer; } /** Returns the GET data for the given \a key. */ QString QDjangoHttpRequest::get(const QString &key) const { QString queryString = d->meta.value(QLatin1String("QUERY_STRING")); queryString.replace('+', ' '); #if (QT_VERSION >= QT_VERSION_CHECK(5, 0, 0)) QUrlQuery query(queryString); return query.queryItemValue(key, QUrl::FullyDecoded); #else QUrl url; url.setEncodedQuery(queryString.toLatin1()); return url.queryItemValue(key); #endif } /** Returns the specified HTTP request header. * * \param key */ QString QDjangoHttpRequest::meta(const QString &key) const { return d->meta.value(key); } /** Returns the HTTP request's method (e.g. GET, POST). */ QString QDjangoHttpRequest::method() const { return d->method; } /** Returns the HTTP request's path. */ QString QDjangoHttpRequest::path() const { return d->path; } /** Returns the POST data for the given \a key. */ QString QDjangoHttpRequest::post(const QString &key) const { QByteArray buffer = d->buffer; buffer.replace('+', ' '); #if (QT_VERSION >= QT_VERSION_CHECK(5, 0, 0)) QUrlQuery query(QString::fromUtf8(buffer)); return query.queryItemValue(key, QUrl::FullyDecoded); #else QUrl url; url.setEncodedQuery(buffer); return url.queryItemValue(key); #endif } QDjangoHttpTestRequest::QDjangoHttpTestRequest(const QString &method, const QString &path) { d->method = method; d->path = path; } qdjango-0.6.2/src/http/QDjangoHttpRequest.h000066400000000000000000000033631261212605400206210ustar00rootroot00000000000000/* * Copyright (C) 2010-2015 Jeremy Lainé * Contact: https://github.com/jlaine/qdjango * * This file is part of the QDjango Library. * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * This library 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 * Lesser General Public License for more details. */ #ifndef QDJANGO_HTTP_REQUEST_H #define QDJANGO_HTTP_REQUEST_H #include #include "QDjangoHttp_p.h" class QDjangoHttpRequestPrivate; /** \brief The QDjangoHttpRequest class represents an HTTP request. * * \ingroup Http */ class QDJANGO_HTTP_EXPORT QDjangoHttpRequest { public: QDjangoHttpRequest(); ~QDjangoHttpRequest(); QByteArray body() const; QString get(const QString &key) const; QString meta(const QString &key) const; QString method() const; QString path() const; QString post(const QString &key) const; private: Q_DISABLE_COPY(QDjangoHttpRequest) QDjangoHttpRequestPrivate* const d; friend class QDjangoFastCgiConnection; friend class QDjangoHttpConnection; friend class QDjangoHttpTestRequest; friend class tst_QDjangoHttpController; friend class tst_QDjangoHttpRequest; }; /** \cond */ class QDJANGO_HTTP_EXPORT QDjangoHttpTestRequest : public QDjangoHttpRequest { public: QDjangoHttpTestRequest(const QString &method, const QString &path); private: Q_DISABLE_COPY(QDjangoHttpTestRequest) }; /** \endcond */ #endif qdjango-0.6.2/src/http/QDjangoHttpRequest_p.h000066400000000000000000000017531261212605400211410ustar00rootroot00000000000000/* * Copyright (C) 2010-2015 Jeremy Lainé * Contact: https://github.com/jlaine/qdjango * * This file is part of the QDjango Library. * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * This library 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 * Lesser General Public License for more details. */ #ifndef QDJANGO_HTTP_REQUEST_P_H #define QDJANGO_HTTP_REQUEST_P_H // // W A R N I N G // ------------- // // This file is not part of the QDjango API. // #include /** \internal */ class QDjangoHttpRequestPrivate { public: QByteArray buffer; QMap meta; QString method; QString path; }; #endif qdjango-0.6.2/src/http/QDjangoHttpResponse.cpp000066400000000000000000000103501261212605400213140ustar00rootroot00000000000000/* * Copyright (C) 2010-2015 Jeremy Lainé * Contact: https://github.com/jlaine/qdjango * * This file is part of the QDjango Library. * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * This library 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 * Lesser General Public License for more details. */ #include "QDjangoHttpResponse.h" #include "QDjangoHttpResponse_p.h" /** Constructs a new HTTP response. */ QDjangoHttpResponse::QDjangoHttpResponse() : d(new QDjangoHttpResponsePrivate) { setHeader(QLatin1String("Content-Length"), QLatin1String("0")); setStatusCode(QDjangoHttpResponse::OK); } /** Destroys the HTTP response. */ QDjangoHttpResponse::~QDjangoHttpResponse() { delete d; } /** Returns the raw body of the HTTP response. */ QByteArray QDjangoHttpResponse::body() const { return d->body; } /** Sets the raw body of the HTTP response. * * The Content-Length header will be updated to reflect the body size. * * \param body */ void QDjangoHttpResponse::setBody(const QByteArray &body) { d->body = body; setHeader(QLatin1String("Content-Length"), QString::number(d->body.size())); } /** Returns the specified HTTP response header. * * \param key */ QString QDjangoHttpResponse::header(const QString &key) const { QString lowercaseKey = key.toLower(); QList >::ConstIterator it = d->headers.constBegin(); while (it != d->headers.constEnd()) { if ((*it).first.toLower() == lowercaseKey) return (*it).second; ++it; } return QString(); } /** Sets the specified HTTP response header. * * \param key * \param value */ void QDjangoHttpResponse::setHeader(const QString &key, const QString &value) { QString lowercaseKey = key.toLower(); QList >::Iterator it = d->headers.begin(); while (it != d->headers.end()) { if ((*it).first.toLower() == lowercaseKey) { (*it).second = value; return; } ++it; } // not found so add d->headers.append(qMakePair(key, value)); } /** Returns true if the response is ready to be sent. * * The default implementation always returns true. If you subclass * QDjangoHttpResponse to support responses which should only be sent * to the client at a later point, you need to reimplement this method * and emit the ready() signal once the response is ready. */ bool QDjangoHttpResponse::isReady() const { return true; } /** Returns the reason for the HTTP response status line. */ QString QDjangoHttpResponse::reasonPhrase() const { return d->reasonPhrase; } /** Returns the code for the HTTP response status line. */ int QDjangoHttpResponse::statusCode() const { return d->statusCode; } /** Sets the code for the HTTP response status line. * * \param code */ void QDjangoHttpResponse::setStatusCode(int code) { d->statusCode = code; switch(code) { case OK: d->reasonPhrase = QLatin1String("OK"); break; case MovedPermanently: d->reasonPhrase = QLatin1String("Moved Permanently"); break; case Found: d->reasonPhrase = QLatin1String("Found"); break; case NotModified: d->reasonPhrase = QLatin1String("Not Modified"); break; case BadRequest: d->reasonPhrase = QLatin1String("Bad Request"); break; case AuthorizationRequired: d->reasonPhrase = QLatin1String("Authorization Required"); break; case Forbidden: d->reasonPhrase = QLatin1String("Forbidden"); break; case NotFound: d->reasonPhrase = QLatin1String("Not Found"); break; case MethodNotAllowed: d->reasonPhrase = QLatin1String("Method Not Allowed"); break; case InternalServerError: d->reasonPhrase = QLatin1String("Internal Server Error"); break; default: d->reasonPhrase = QLatin1String(""); break; } } qdjango-0.6.2/src/http/QDjangoHttpResponse.h000066400000000000000000000042631261212605400207670ustar00rootroot00000000000000/* * Copyright (C) 2010-2015 Jeremy Lainé * Contact: https://github.com/jlaine/qdjango * * This file is part of the QDjango Library. * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * This library 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 * Lesser General Public License for more details. */ #ifndef QDJANGO_HTTP_RESPONSE_H #define QDJANGO_HTTP_RESPONSE_H #include #include "QDjangoHttp_p.h" class QDjangoHttpResponsePrivate; /** \brief The QDjangoHttpResponse class represents an HTTP response. * * \ingroup Http */ class QDJANGO_HTTP_EXPORT QDjangoHttpResponse : public QObject { Q_OBJECT public: /** \brief Enum representing well-known HTTP status codes. */ enum HttpStatus { OK = 200, MovedPermanently = 301, Found = 302, NotModified = 304, BadRequest = 400, AuthorizationRequired = 401, Forbidden = 403, NotFound = 404, MethodNotAllowed = 405, InternalServerError = 500, }; QDjangoHttpResponse(); ~QDjangoHttpResponse(); QByteArray body() const; void setBody(const QByteArray &body); QString header(const QString &key) const; void setHeader(const QString &key, const QString &value); virtual bool isReady() const; QString reasonPhrase() const; int statusCode() const; void setStatusCode(int code); signals: /** Emit this signal from your QDjangoHttpResponse subclasses once * the response is ready to be sent to the client. * * \sa isReady() */ void ready(); private: Q_DISABLE_COPY(QDjangoHttpResponse) QDjangoHttpResponsePrivate* const d; friend class QDjangoFastCgiConnection; friend class QDjangoHttpConnection; }; #endif qdjango-0.6.2/src/http/QDjangoHttpResponse_p.h000066400000000000000000000020301261212605400212740ustar00rootroot00000000000000/* * Copyright (C) 2010-2015 Jeremy Lainé * Contact: https://github.com/jlaine/qdjango * * This file is part of the QDjango Library. * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * This library 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 * Lesser General Public License for more details. */ #ifndef QDJANGO_HTTP_RESPONSE_P_H #define QDJANGO_HTTP_RESPONSE_P_H // // W A R N I N G // ------------- // // This file is not part of the QDjango API. // #include #include /** \internal */ class QDjangoHttpResponsePrivate { public: int statusCode; QString reasonPhrase; QList > headers; QByteArray body; }; #endif qdjango-0.6.2/src/http/QDjangoHttpServer.cpp000066400000000000000000000271351261212605400207750ustar00rootroot00000000000000/* * Copyright (C) 2010-2015 Jeremy Lainé * Contact: https://github.com/jlaine/qdjango * * This file is part of the QDjango Library. * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * This library 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 * Lesser General Public License for more details. */ #include #include #include #include #include #include #include "QDjangoHttpController.h" #include "QDjangoHttpRequest.h" #include "QDjangoHttpRequest_p.h" #include "QDjangoHttpResponse.h" #include "QDjangoHttpResponse_p.h" #include "QDjangoHttpServer.h" #include "QDjangoHttpServer_p.h" #include "QDjangoUrlResolver.h" //#define QDJANGO_DEBUG_HTTP // maximum request body size is 10 MB #define MAX_BODY_SIZE (10 * 1024 * 1024) /// \cond /** Constructs a new HTTP connection. */ QDjangoHttpConnection::QDjangoHttpConnection(QTcpSocket *device, QDjangoHttpServer *server) : QObject(server), m_closeAfterResponse(false), m_pendingRequest(0), m_requestCount(0), m_server(server), m_socket(device) { bool check; Q_UNUSED(check); m_socket->setParent(this); check = connect(m_socket, SIGNAL(bytesWritten(qint64)), this, SLOT(_q_bytesWritten(qint64))); Q_ASSERT(check); check = connect(m_socket, SIGNAL(disconnected()), this, SIGNAL(closed())); Q_ASSERT(check); check = connect(m_socket, SIGNAL(readyRead()), this, SLOT(_q_readyRead())); Q_ASSERT(check); } /** Destroys the HTTP connection. */ QDjangoHttpConnection::~QDjangoHttpConnection() { if (m_pendingRequest) delete m_pendingRequest; foreach (const QDjangoHttpJob &job, m_pendingJobs) { delete job.first; delete job.second; } } /** When bytes have been written, check whether we need to close * the connection. * * @param bytes */ void QDjangoHttpConnection::_q_bytesWritten(qint64 bytes) { Q_UNUSED(bytes); if (!m_socket->bytesToWrite()) { if (!m_pendingJobs.isEmpty()) { _q_writeResponse(); } else if (m_closeAfterResponse) { #ifdef QDJANGO_DEBUG_HTTP qDebug("Closing connection"); #endif m_socket->close(); emit closed(); } } } /** Handle incoming data on the socket. */ void QDjangoHttpConnection::_q_readyRead() { QDjangoHttpRequest *request = m_pendingRequest; if (!request) { request = new QDjangoHttpRequest; m_requestBytesRemaining = 0; m_requestHeaderLine = 0; m_requestHeaderReceived = false; m_requestHeaders.clear(); m_requestMajorVersion = 0; m_requestMinorVersion = 0; m_requestPath.clear(); } // Read request header while (!m_requestHeaderReceived && m_socket->canReadLine()) { const QString line = QString::fromUtf8(m_socket->readLine()); if (!m_requestHeaderLine++) { bool ok = false; QStringList lst = line.simplified().split(QLatin1String(" ")); if (lst.count() > 0) { request->d->method = lst[0]; if (lst.count() > 1) { m_requestPath = lst[1]; request->d->path = QUrl(m_requestPath).path(); if (lst.count() > 2) { QString v = lst[2]; if (v.length() >= 8 && v.left(5) == QLatin1String("HTTP/") && v[5].isDigit() && v[6] == QLatin1Char('.') && v[7].isDigit()) { m_requestMajorVersion = v[5].toLatin1() - '0'; m_requestMinorVersion = v[7].toLatin1() - '0'; ok = true; } } } } if (!ok) { qWarning("Invalid HTTP request"); m_socket->close(); return; } } else if (line != QLatin1String("\r\n")) { int i = line.indexOf(QLatin1Char(':')); if (i == -1) { qWarning("Invalid HTTP request header"); m_socket->close(); return; } const QString key = line.left(i).trimmed(); const QString value = line.mid(i + 1).trimmed(); m_requestHeaders.append(qMakePair(key, value)); if (key.toLower() == QLatin1String("content-length")) { m_requestBytesRemaining = value.toInt(); } } else { if (m_requestBytesRemaining < 0 || m_requestBytesRemaining > MAX_BODY_SIZE) { qWarning("Invalid Content-Length"); m_socket->close(); return; } m_requestHeaderReceived = true; } } if (!m_requestHeaderReceived) { m_pendingRequest = request; return; } // Read request body if (m_requestBytesRemaining > 0) { const QByteArray chunk = m_socket->read(m_requestBytesRemaining); request->d->buffer += chunk; m_requestBytesRemaining -= chunk.size(); } if (m_requestBytesRemaining) { m_pendingRequest = request; return; } m_pendingRequest = 0; #ifdef QDJANGO_DEBUG_HTTP qDebug("Handling request %i", d->requestCount++); #endif /* Map meta-information */ QString metaKey; QList >::ConstIterator it = m_requestHeaders.constBegin(); while (it != m_requestHeaders.constEnd()) { if (it->first == QLatin1String("Content-Length")) metaKey = QLatin1String("CONTENT_LENGTH"); else if (it->first == QLatin1String("Content-Type")) metaKey = QLatin1String("CONTENT_TYPE"); else { metaKey = QLatin1String("HTTP_") + it->first.toUpper(); metaKey.replace(QLatin1Char('-'), QLatin1Char('_')); } request->d->meta.insert(metaKey, it->second); ++it; } #if (QT_VERSION >= QT_VERSION_CHECK(5, 0, 0)) request->d->meta.insert(QLatin1String("QUERY_STRING"), QUrl(m_requestPath).query()); #else request->d->meta.insert(QLatin1String("QUERY_STRING"), QString::fromLatin1(QUrl(m_requestPath).encodedQuery())); #endif request->d->meta.insert(QLatin1String("REMOTE_ADDR"), m_socket->peerAddress().toString()); request->d->meta.insert(QLatin1String("REQUEST_METHOD"), request->method()); request->d->meta.insert(QLatin1String("SERVER_NAME"), m_socket->localAddress().toString()); request->d->meta.insert(QLatin1String("SERVER_PORT"), QString::number(m_socket->localPort())); /* Process request */ bool keepAlive = m_requestMajorVersion >= 1 && m_requestMinorVersion >= 1; if (request->d->meta.value(QLatin1String("HTTP_CONNECTION")).toLower() == QLatin1String("keep-alive")) keepAlive = true; else if (request->d->meta.value(QLatin1String("HTTP_CONNECTION")).toLower() == QLatin1String("close")) keepAlive = false; QDjangoHttpResponse *response = m_server->urls()->respond(*request, request->path()); m_pendingJobs << qMakePair(request, response); /* Store keep-alive flag */ if (!keepAlive) m_closeAfterResponse = true; connect(response, SIGNAL(ready()), this, SLOT(_q_writeResponse())); _q_writeResponse(); } void QDjangoHttpConnection::_q_writeResponse() { while (!m_pendingJobs.isEmpty() && m_pendingJobs.first().second->isReady()) { const QDjangoHttpJob job = m_pendingJobs.takeFirst(); QDjangoHttpRequest *request = job.first; QDjangoHttpResponse *response = job.second; if (!response->isReady()) return; /* Finalise response */ response->setHeader(QLatin1String("Date"), QDjangoHttpController::httpDateTime(QDateTime::currentDateTime())); response->setHeader(QLatin1String("Server"), QString::fromLatin1("%1/%2").arg(qApp->applicationName(), qApp->applicationVersion())); response->setHeader(QLatin1String("Connection"), QLatin1String(m_closeAfterResponse ? "close" : "keep-alive")); /* Send response */ QString httpHeader = QString::fromLatin1("HTTP/1.1 %1 %2\r\n").arg(response->d->statusCode).arg(response->d->reasonPhrase); QList >::ConstIterator it = response->d->headers.constBegin(); while (it != response->d->headers.constEnd()) { httpHeader += (*it).first + QLatin1String(": ") + (*it).second + QLatin1String("\r\n"); ++it; } m_socket->write(httpHeader.toUtf8() + "\r\n" + response->d->body); /* Emit signal */ emit requestFinished(request, response); /* Destroy response */ delete request; response->deleteLater(); } } /// \endcond class QDjangoHttpServerPrivate { public: int connectionCount; QTcpServer *tcpServer; QDjangoUrlResolver *urlResolver; }; /** Constructs a new HTTP server. */ QDjangoHttpServer::QDjangoHttpServer(QObject *parent) : QObject(parent), d(new QDjangoHttpServerPrivate) { d->connectionCount = 0; d->tcpServer = 0; d->urlResolver = new QDjangoUrlResolver(this); } /** Destroys the HTTP server. */ QDjangoHttpServer::~QDjangoHttpServer() { delete d; } /** Closes the server. The server will no longer listen for * incoming connections. */ void QDjangoHttpServer::close() { if (d->tcpServer) d->tcpServer->close(); } /** Tells the server to listen for incoming TCP connections on the given * \a address and \a port. */ bool QDjangoHttpServer::listen(const QHostAddress &address, quint16 port) { if (!d->tcpServer) { bool check; Q_UNUSED(check); d->tcpServer = new QTcpServer(this); check = connect(d->tcpServer, SIGNAL(newConnection()), this, SLOT(_q_newTcpConnection())); Q_ASSERT(check); } return d->tcpServer->listen(address, port); } /** Returns the server's address if the server is listening for connections; * otherwise returns QHostAddress::Null. */ QHostAddress QDjangoHttpServer::serverAddress() const { if (!d->tcpServer) return QHostAddress::Null; return d->tcpServer->serverAddress(); } /** Returns the server's port if the server is listening for connections; * otherwise returns 0. */ quint16 QDjangoHttpServer::serverPort() const { if (!d->tcpServer) return 0; return d->tcpServer->serverPort(); } /** Returns the root URL resolver for the server, which dispatches * requests to handlers. */ QDjangoUrlResolver* QDjangoHttpServer::urls() const { return d->urlResolver; } /** Handles the creation of new HTTP connections. */ void QDjangoHttpServer::_q_newTcpConnection() { bool check; Q_UNUSED(check); QTcpSocket *socket; while ((socket = d->tcpServer->nextPendingConnection()) != 0) { QDjangoHttpConnection *connection = new QDjangoHttpConnection(socket, this); #ifdef QDJANGO_DEBUG_HTTP qDebug("Handling connection %i", d->connectionCount++); #endif check = connect(connection, SIGNAL(closed()), connection, SLOT(deleteLater())); Q_ASSERT(check); check = connect(connection, SIGNAL(requestFinished(QDjangoHttpRequest*,QDjangoHttpResponse*)), this, SIGNAL(requestFinished(QDjangoHttpRequest*,QDjangoHttpResponse*))); Q_ASSERT(check); } } qdjango-0.6.2/src/http/QDjangoHttpServer.h000066400000000000000000000034571261212605400204430ustar00rootroot00000000000000/* * Copyright (C) 2010-2015 Jeremy Lainé * Contact: https://github.com/jlaine/qdjango * * This file is part of the QDjango Library. * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * This library 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 * Lesser General Public License for more details. */ #ifndef QDJANGO_HTTP_SERVER_H #define QDJANGO_HTTP_SERVER_H #include #include #include "QDjangoHttp_p.h" class QDjangoHttpRequest; class QDjangoHttpResponse; class QDjangoHttpServer; class QDjangoHttpServerPrivate; class QDjangoUrlResolver; /** \brief The QDjangoHttpServer class represents an HTTP server. * * It allows you to create a standalone HTTP server which will * serve your web application. * * To register views, see urls(). * * \ingroup Http * \sa QDjangoFastCgiServer */ class QDJANGO_HTTP_EXPORT QDjangoHttpServer : public QObject { Q_OBJECT public: QDjangoHttpServer(QObject *parent = 0); ~QDjangoHttpServer(); void close(); bool listen(const QHostAddress &address, quint16 port); QHostAddress serverAddress() const; quint16 serverPort() const; QDjangoUrlResolver *urls() const; signals: /** This signal is emitted when a request completes. */ void requestFinished(QDjangoHttpRequest *request, QDjangoHttpResponse *response); private slots: void _q_newTcpConnection(); private: Q_DISABLE_COPY(QDjangoHttpServer) QDjangoHttpServerPrivate* const d; }; #endif qdjango-0.6.2/src/http/QDjangoHttpServer_p.h000066400000000000000000000041341261212605400207530ustar00rootroot00000000000000/* * Copyright (C) 2010-2015 Jeremy Lainé * Contact: https://github.com/jlaine/qdjango * * This file is part of the QDjango Library. * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * This library 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 * Lesser General Public License for more details. */ #ifndef QDJANGO_HTTP_SERVER_P_H #define QDJANGO_HTTP_SERVER_P_H // // W A R N I N G // ------------- // // This file is not part of the QDjango API. // #include #include #include #include class QDjangoHttpRequest; class QDjangoHttpResponse; class QDjangoHttpServer; class QTcpSocket; typedef QPair QDjangoHttpJob; /** \internal */ class QDjangoHttpConnection : public QObject { Q_OBJECT public: QDjangoHttpConnection(QTcpSocket *device, QDjangoHttpServer *server); ~QDjangoHttpConnection(); signals: /** This signal is emitted when the connection is closed. */ void closed(); /** This signal is emitted when a request completes. */ void requestFinished(QDjangoHttpRequest *request, QDjangoHttpResponse *response); private slots: void _q_bytesWritten(qint64 bytes); void _q_readyRead(); void _q_writeResponse(); private: Q_DISABLE_COPY(QDjangoHttpConnection) bool m_closeAfterResponse; QList m_pendingJobs; QDjangoHttpRequest *m_pendingRequest; int m_requestCount; QDjangoHttpServer *m_server; QTcpSocket *m_socket; // request parsing qint64 m_requestBytesRemaining; int m_requestHeaderLine; bool m_requestHeaderReceived; QList > m_requestHeaders; int m_requestMajorVersion; int m_requestMinorVersion; QString m_requestPath; }; #endif qdjango-0.6.2/src/http/QDjangoHttp_p.h000066400000000000000000000020751261212605400175660ustar00rootroot00000000000000/* * Copyright (C) 2010-2015 Jeremy Lainé * Contact: https://github.com/jlaine/qdjango * * This file is part of the QDjango Library. * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * This library 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 * Lesser General Public License for more details. */ #ifndef QDJANGO_HTTP_P_H #define QDJANGO_HTTP_P_H #if defined(QDJANGO_SHARED) # if defined(QDJANGO_HTTP_BUILD) # define QDJANGO_HTTP_EXPORT Q_DECL_EXPORT # define QDJANGO_HTTP_AUTOTEST_EXPORT Q_DECL_EXPORT # else # define QDJANGO_HTTP_EXPORT Q_DECL_IMPORT # define QDJANGO_HTTP_AUTOTEST_EXPORT Q_DECL_IMPORT # endif #else # define QDJANGO_HTTP_EXPORT # define QDJANGO_HTTP_AUTOTEST_EXPORT #endif #endif qdjango-0.6.2/src/http/QDjangoUrlResolver.cpp000066400000000000000000000164701261212605400211530ustar00rootroot00000000000000/* * Copyright (C) 2010-2015 Jeremy Lainé * Contact: https://github.com/jlaine/qdjango * * This file is part of the QDjango Library. * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * This library 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 * Lesser General Public License for more details. */ #include #include #include #include #include "QDjangoHttpController.h" #include "QDjangoHttpRequest.h" #include "QDjangoHttpResponse.h" #include "QDjangoUrlResolver.h" class QDjangoUrlResolverRoute { public: QDjangoUrlResolverRoute() : receiver(0) , urls(0) { } QRegExp path; QObject *receiver; QByteArray member; QDjangoUrlResolver *urls; }; class QDjangoUrlResolverPrivate { public: QDjangoHttpResponse* respond(const QDjangoHttpRequest &request, const QString &path) const; QString reverse(QObject *receiver, const char *member, const QVariantList &args = QVariantList()) const; QList routes; }; QDjangoHttpResponse* QDjangoUrlResolverPrivate::respond(const QDjangoHttpRequest &request, const QString &path) const { QList::const_iterator it; for (it = routes.constBegin(); it != routes.constEnd(); ++it) { if (it->urls && it->path.indexIn(path) == 0) { // try recursing QString subPath = path.mid(it->path.capturedTexts().first().size()); QDjangoHttpResponse *response = it->urls->d->respond(request, subPath); if (response) return response; } else if (it->receiver && it->path.exactMatch(path)) { // collect arguments QStringList caps = it->path.capturedTexts(); caps.takeFirst(); QList args; args << Q_ARG(QDjangoHttpRequest, request); for (int i = 0; i < caps.size(); ++i) { args << Q_ARG(QString, caps[i]); } while (args.size() < 10) { args << QGenericArgument(); } QDjangoHttpResponse *response = 0; if (!QMetaObject::invokeMethod(it->receiver, it->member.constData(), Qt::DirectConnection, Q_RETURN_ARG(QDjangoHttpResponse*, response), args[0], args[1], args[2], args[3], args[4], args[5], args[6], args[7], args[8], args[9]) || !response) { return QDjangoHttpController::serveInternalServerError(request); } return response; } } return 0; } QString QDjangoUrlResolverPrivate::reverse(QObject *receiver, const char *member, const QVariantList &args) const { QList::const_iterator it; for (it = routes.constBegin(); it != routes.constEnd(); ++it) { // recurse if (it->urls) { QString path = it->urls->d->reverse(receiver, member, args); if (!path.isNull()) { QString prefix = it->path.pattern(); if (prefix.startsWith(QLatin1Char('^'))) prefix.remove(0, 1); if (prefix.endsWith(QLatin1Char('$'))) prefix.chop(1); return prefix + path; } } else if (it->receiver == receiver && it->member == member) { QString path = it->path.pattern(); if (path.startsWith(QLatin1Char('^'))) path.remove(0, 1); if (path.endsWith(QLatin1Char('$'))) path.chop(1); // replace parameters QVariantList arguments(args); int pos = 0; QRegExp rx(QLatin1String("\\([^)]+\\)")); while ((pos = rx.indexIn(path, pos)) != -1) { if (arguments.isEmpty()) { qWarning("Too few arguments for '%s'", member); return QString(); } const QString str = arguments.takeFirst().toString(); path.replace(pos, rx.matchedLength(), str); pos += str.size(); } if (!arguments.isEmpty()) { qWarning("Too many arguments for '%s'", member); return QString(); } if (path.isEmpty()) return QLatin1String(""); else return path; } } // not found return QString(); } /** Constructs a new URL resolver with the given \a parent. */ QDjangoUrlResolver::QDjangoUrlResolver(QObject *parent) : QObject(parent) , d(new QDjangoUrlResolverPrivate) { } QDjangoUrlResolver::~QDjangoUrlResolver() { delete d; } /** Adds a URL mapping for the given \a path. */ bool QDjangoUrlResolver::set(const QRegExp &path, QObject *receiver, const char *member) { Q_ASSERT(receiver); Q_ASSERT(member); const QMetaObject *metaObject = receiver->metaObject(); QByteArray needle(member); needle += '('; for (int i = metaObject->methodOffset(); i < metaObject->methodCount(); ++i) { #if (QT_VERSION >= QT_VERSION_CHECK(5, 0, 0)) if (metaObject->method(i).name() == member) { #else const QByteArray signature = metaObject->method(i).signature(); if (signature.startsWith(needle)) { #endif // check parameter types const QList ptypes = metaObject->method(i).parameterTypes(); if (ptypes.isEmpty() || ptypes[0] != "QDjangoHttpRequest") { qWarning("First argument of '%s' should be a QDjangoHttpRequest", member); return false; } // register route QDjangoUrlResolverRoute route; route.path = path; route.receiver = receiver; route.member = member; d->routes << route; return true; } } qWarning("Could not find '%s' in receiver", member); return false; } /** Adds a URL mapping for the given \a path. */ bool QDjangoUrlResolver::include(const QRegExp &path, QDjangoUrlResolver *urls) { Q_ASSERT(urls); // register route QDjangoUrlResolverRoute route; route.path = path; route.urls = urls; d->routes << route; return true; } /** Responds to the given HTTP \a request for the given \a path. */ QDjangoHttpResponse* QDjangoUrlResolver::respond(const QDjangoHttpRequest &request, const QString &path) const { QString fixedPath(path); if (fixedPath.startsWith(QLatin1Char('/'))) fixedPath.remove(0, 1); QDjangoHttpResponse *response = d->respond(request, fixedPath); if (response) return response; else return QDjangoHttpController::serveNotFound(request); } /** Returns the URL for the member \a member of \a receiver with * \a args as arguments. */ QString QDjangoUrlResolver::reverse(QObject *receiver, const char *member, const QVariantList &args) const { QString path = d->reverse(receiver, member, args); if (path.isNull()) return QString(); else return QLatin1String("/") + path; } qdjango-0.6.2/src/http/QDjangoUrlResolver.h000066400000000000000000000031231261212605400206070ustar00rootroot00000000000000/* * Copyright (C) 2010-2015 Jeremy Lainé * Contact: https://github.com/jlaine/qdjango * * This file is part of the QDjango Library. * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * This library 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 * Lesser General Public License for more details. */ #ifndef QDJANGO_URL_RESOLVER_H #define QDJANGO_URL_RESOLVER_H #include #include #include "QDjangoHttp_p.h" class QDjangoHttpRequest; class QDjangoHttpResponse; class QDjangoUrlResolverPrivate; class QRegExp; /** \brief The QDjangoUrlResolver class maps incoming HTTP requests to handlers. * * \ingroup Http */ class QDJANGO_HTTP_EXPORT QDjangoUrlResolver : public QObject { Q_OBJECT public: QDjangoUrlResolver(QObject *parent = 0); ~QDjangoUrlResolver(); bool include(const QRegExp &path, QDjangoUrlResolver *urls); bool set(const QRegExp &path, QObject *receiver, const char *member); QString reverse(QObject *receiver, const char *member, const QVariantList &args = QVariantList()) const; public slots: QDjangoHttpResponse* respond(const QDjangoHttpRequest &request, const QString &path) const; private: QDjangoUrlResolverPrivate *d; friend class QDjangoUrlResolverPrivate; }; #endif qdjango-0.6.2/src/http/http.pro000066400000000000000000000013071261212605400164110ustar00rootroot00000000000000include(../../qdjango.pri) QT -= gui QT += network DEFINES += QDJANGO_HTTP_BUILD TARGET = qdjango-http win32 { DESTDIR = $$OUT_PWD } HEADERS += \ QDjangoFastCgiServer.h \ QDjangoFastCgiServer_p.h \ QDjangoHttp_p.h \ QDjangoHttpController.h \ QDjangoHttpRequest.h \ QDjangoHttpResponse.h \ QDjangoHttpServer.h \ QDjangoHttpServer_p.h \ QDjangoUrlResolver.h SOURCES += \ QDjangoFastCgiServer.cpp \ QDjangoHttpController.cpp \ QDjangoHttpRequest.cpp \ QDjangoHttpResponse.cpp \ QDjangoHttpServer.cpp \ QDjangoUrlResolver.cpp # Installation include(../src.pri) headers.path = $$PREFIX/include/qdjango/http QMAKE_PKGCONFIG_INCDIR = $$headers.path qdjango-0.6.2/src/src.pri000066400000000000000000000012571261212605400152400ustar00rootroot00000000000000TEMPLATE = lib CONFIG += $$QDJANGO_LIBRARY_TYPE VERSION = $$QDJANGO_VERSION # Installation headers.files = $$HEADERS target.path = $$PREFIX/$$LIBDIR INSTALLS += headers target # pkg-config support CONFIG += create_pc create_prl no_install_prl QMAKE_PKGCONFIG_DESTDIR = pkgconfig QMAKE_PKGCONFIG_LIBDIR = $$target.path equals(QDJANGO_LIBRARY_TYPE,staticlib) { QMAKE_PKGCONFIG_CFLAGS = -DQDJANGO_STATIC } else { QMAKE_PKGCONFIG_CFLAGS = -DQDJANGO_SHARED } unix:QMAKE_CLEAN += -r pkgconfig lib$${TARGET}.prl # profiling support equals(QDJANGO_PROFILE,true) { QMAKE_CXXFLAGS += -fprofile-arcs -ftest-coverage QMAKE_LIBS += -lgcov QMAKE_CLEAN += *.gcda *.gcov *.gcno } qdjango-0.6.2/src/src.pro000066400000000000000000000000711261212605400152370ustar00rootroot00000000000000TEMPLATE = subdirs SUBDIRS = db http CONFIG += ordered qdjango-0.6.2/tests/000077500000000000000000000000001261212605400143035ustar00rootroot00000000000000qdjango-0.6.2/tests/db/000077500000000000000000000000001261212605400146705ustar00rootroot00000000000000qdjango-0.6.2/tests/db/auth-models.cpp000066400000000000000000000067161261212605400176300ustar00rootroot00000000000000/* * Copyright (C) 2010-2015 Jeremy Lainé * Contact: https://github.com/jlaine/qdjango * * This file is part of the QDjango Library. * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * This library 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 * Lesser General Public License for more details. */ #include "QDjangoQuerySet.h" #include "auth-models.h" User::User(QObject *parent) : QDjangoModel(parent), m_isActive(true), m_isStaff(false), m_isSuperUser(false) { // initialise dates m_dateJoined = QDateTime::currentDateTime(); m_lastLogin = QDateTime::currentDateTime(); } QString User::username() const { return m_username; } void User::setUsername(const QString &username) { m_username = username; } QString User::firstName() const { return m_firstName; } void User::setFirstName(const QString &firstName) { m_firstName = firstName; } QString User::lastName() const { return m_lastName; } void User::setLastName(const QString &lastName) { m_lastName = lastName; } QString User::email() const { return m_email; } void User::setEmail(const QString &email) { m_email = email; } QString User::password() const { return m_password; } void User::setPassword(const QString &password) { m_password = password; } bool User::isActive() const { return m_isActive; } void User::setIsActive(bool isActive) { m_isActive = isActive; } bool User::isStaff() const { return m_isStaff; } void User::setIsStaff(bool isStaff) { m_isStaff = isStaff; } bool User::isSuperUser() const { return m_isSuperUser; } void User::setIsSuperUser(bool isSuperUser) { m_isSuperUser = isSuperUser; } QDateTime User::dateJoined() const { return m_dateJoined; } void User::setDateJoined(const QDateTime &dateJoined) { m_dateJoined = dateJoined; } QDateTime User::lastLogin() const { return m_lastLogin; } void User::setLastLogin(const QDateTime &lastLogin) { m_lastLogin = lastLogin; } Group::Group(QObject *parent) : QDjangoModel(parent) { } QString Group::name() const { return m_name; } void Group::setName(const QString &name) { m_name = name; } UserGroups::UserGroups(QObject *parent) : QDjangoModel(parent) { setForeignKey("user", new User(this)); setForeignKey("group", new Group(this)); } User *UserGroups::user() const { return qobject_cast(foreignKey("user")); } void UserGroups::setUser(User *user) { setForeignKey("user", user); } Group *UserGroups::group() const { return qobject_cast(foreignKey("group")); } void UserGroups::setGroup(Group *group) { setForeignKey("group", group); } Message::Message(QObject *parent) : QDjangoModel(parent) { setForeignKey("user", new User(this)); } /** Returns the User associated with this Message. */ User *Message::user() const { return qobject_cast(foreignKey("user")); } void Message::setUser(User *user) { setForeignKey("user", user); } QString Message::message() const { return m_message; } void Message::setMessage(const QString &message) { m_message = message; } Q_DECLARE_METATYPE(Group*) Q_DECLARE_METATYPE(User*) qdjango-0.6.2/tests/db/auth-models.h000066400000000000000000000076761261212605400173030ustar00rootroot00000000000000/* * Copyright (C) 2010-2015 Jeremy Lainé * Contact: https://github.com/jlaine/qdjango * * This file is part of the QDjango Library. * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * This library 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 * Lesser General Public License for more details. */ #ifndef QDJANGO_AUTH_MODELS_H #define QDJANGO_AUTH_MODELS_H #include #include "QDjangoModel.h" /** The User class represents a user in the authentication system. * * It has a many-to-many relationship with the Group class. */ class User : public QDjangoModel { Q_OBJECT Q_PROPERTY(QString username READ username WRITE setUsername) Q_PROPERTY(QString first_name READ firstName WRITE setFirstName) Q_PROPERTY(QString last_name READ lastName WRITE setLastName) Q_PROPERTY(QString email READ email WRITE setEmail) Q_PROPERTY(QString password READ password WRITE setPassword) Q_PROPERTY(bool is_active READ isActive WRITE setIsActive) Q_PROPERTY(bool is_staff READ isStaff WRITE setIsStaff) Q_PROPERTY(bool is_superuser READ isSuperUser WRITE setIsSuperUser) Q_PROPERTY(QDateTime date_joined READ dateJoined WRITE setDateJoined) Q_PROPERTY(QDateTime last_login READ lastLogin WRITE setLastLogin) Q_CLASSINFO("username", "max_length=30") Q_CLASSINFO("first_name", "max_length=30") Q_CLASSINFO("last_name", "max_length=30") Q_CLASSINFO("password", "max_length=128") public: User(QObject *parent = 0); QString username() const; void setUsername(const QString &username); QString firstName() const; void setFirstName(const QString &firstName); QString lastName() const; void setLastName(const QString &lastName); QString email() const; void setEmail(const QString &email); QString password() const; void setPassword(const QString &password); // flags bool isActive() const; void setIsActive(bool isActive); bool isStaff() const; void setIsStaff(bool isStaff); bool isSuperUser() const; void setIsSuperUser(bool isSuperUser); // dates QDateTime dateJoined() const; void setDateJoined(const QDateTime &dateJoined); QDateTime lastLogin() const; void setLastLogin(const QDateTime &lastLogin); private: QString m_username; QString m_firstName; QString m_lastName; QString m_email; QString m_password; bool m_isActive; bool m_isStaff; bool m_isSuperUser; QDateTime m_dateJoined; QDateTime m_lastLogin; }; /** The Group class represents a group in the authentication system. * * It has a many-to-many relationship with the User class. */ class Group : public QDjangoModel { Q_OBJECT Q_PROPERTY(QString name READ name WRITE setName) public: Group(QObject *parent = 0); QString name() const; void setName(const QString &name); private: QString m_name; }; class UserGroups : public QDjangoModel { Q_OBJECT Q_PROPERTY(User* user READ user WRITE setUser); Q_PROPERTY(Group* group READ group WRITE setGroup); public: UserGroups(QObject *parent = 0); User *user() const; void setUser(User *user); Group *group() const; void setGroup(Group *group); }; /** The Message class represents a message for a given User. */ class Message : public QDjangoModel { Q_OBJECT Q_PROPERTY(User* user READ user WRITE setUser); Q_PROPERTY(QString message READ message WRITE setMessage) public: Message(QObject *parent = 0); User *user() const; void setUser(User *user); QString message() const; void setMessage(const QString &message); private: QString m_message; }; #endif qdjango-0.6.2/tests/db/auth/000077500000000000000000000000001261212605400156315ustar00rootroot00000000000000qdjango-0.6.2/tests/db/auth/auth.pro000066400000000000000000000001551261212605400173150ustar00rootroot00000000000000include(../db.pri) TARGET = tst_auth HEADERS += ../auth-models.h SOURCES += ../auth-models.cpp tst_auth.cpp qdjango-0.6.2/tests/db/auth/tst_auth.cpp000066400000000000000000000566701261212605400202060ustar00rootroot00000000000000/* * Copyright (C) 2010-2015 Jeremy Lainé * Contact: https://github.com/jlaine/qdjango * * This file is part of the QDjango Library. * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * This library 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 * Lesser General Public License for more details. */ #include "QDjangoQuerySet.h" #include "QDjangoWhere.h" #include "auth-models.h" #include "util.h" /** Tests for the User class. */ class tst_Auth: public QObject { Q_OBJECT private slots: void initTestCase(); void create(); void remove(); void removeFilter(); void removeLimit(); void get(); void filter(); void filterLike(); void exclude(); void limit(); void subLimit(); void orderBy(); void update(); void values(); void valuesList(); void constIterator(); void testGroups(); void testRelated(); void filterRelated(); void cleanup(); void cleanupTestCase(); private: void loadFixtures(); }; /** Create database table before running tests. */ void tst_Auth::initTestCase() { QVERIFY(initialiseDatabase()); QDjango::registerModel(); QDjango::registerModel(); QDjango::registerModel(); QDjango::registerModel(); QVERIFY(QDjango::createTables()); } /** Load fixtures consisting of 3 users. */ void tst_Auth::loadFixtures() { User foo; foo.setUsername("foouser"); foo.setPassword("foopass"); foo.setLastLogin(QDateTime(QDate(2010, 6, 1), QTime(10, 5, 14))); QCOMPARE(foo.save(), true); User bar; bar.setUsername("baruser"); bar.setPassword("barpass"); bar.setLastLogin(QDateTime(QDate(2010, 6, 1), QTime(10, 6, 31))); QCOMPARE(bar.save(), true); User wiz; wiz.setUsername("wizuser"); wiz.setPassword("wizpass"); wiz.setLastLogin(QDateTime(QDate(2010, 6, 1), QTime(10, 7, 18))); QCOMPARE(wiz.save(), true); QCOMPARE(QDjangoQuerySet().count(), 3); QCOMPARE(QDjangoQuerySet().size(), 3); } void tst_Auth::create() { const QDjangoQuerySet users; User *other; // create User user; user.setUsername("foouser"); user.setPassword("foopass"); user.setLastLogin(QDateTime(QDate(2010, 6, 1), QTime(10, 5, 14))); QCOMPARE(user.save(), true); QCOMPARE(users.all().size(), 1); // get by id other = users.get(QDjangoWhere("id", QDjangoWhere::Equals, 1)); QVERIFY(other != 0); QCOMPARE(other->pk(), QVariant(1)); QCOMPARE(other->username(), QLatin1String("foouser")); QCOMPARE(other->password(), QLatin1String("foopass")); delete other; // get by pk other = users.get(QDjangoWhere("pk", QDjangoWhere::Equals, 1)); QVERIFY(other != 0); QCOMPARE(other->pk(), QVariant(1)); QCOMPARE(other->username(), QLatin1String("foouser")); QCOMPARE(other->password(), QLatin1String("foopass")); delete other; // get by username other = users.get(QDjangoWhere("username", QDjangoWhere::Equals, "foouser")); QVERIFY(other != 0); QCOMPARE(other->pk(), QVariant(1)); QCOMPARE(other->username(), QLatin1String("foouser")); QCOMPARE(other->password(), QLatin1String("foopass")); QCOMPARE(other->lastLogin(), QDateTime(QDate(2010, 6, 1), QTime(10, 5, 14))); delete other; // update user.setPassword("foopass2"); QCOMPARE(user.save(), true); QCOMPARE(users.all().size(), 1); other = users.get(QDjangoWhere("username", QDjangoWhere::Equals, "foouser")); QVERIFY(other != 0); QCOMPARE(other->pk(), QVariant(1)); QCOMPARE(other->username(), QLatin1String("foouser")); QCOMPARE(other->password(), QLatin1String("foopass2")); delete other; User user2; user2.setUsername("baruser"); user2.setPassword("barpass"); user2.setLastLogin(QDateTime(QDate(2010, 6, 1), QTime(10, 6, 31))); QCOMPARE(user2.save(), true); QCOMPARE(users.all().size(), 2); other = users.get(QDjangoWhere("username", QDjangoWhere::Equals, "baruser")); QVERIFY(other != 0); QCOMPARE(other->pk(), QVariant(2)); QCOMPARE(other->username(), QLatin1String("baruser")); QCOMPARE(other->password(), QLatin1String("barpass")); QCOMPARE(other->lastLogin(), QDateTime(QDate(2010, 6, 1), QTime(10, 6, 31))); delete other; } /** Test removing a single user. */ void tst_Auth::remove() { const QDjangoQuerySet users; User user; user.setUsername("foouser"); user.setPassword("foopass"); QCOMPARE(user.save(), true); QCOMPARE(users.all().size(), 1); QCOMPARE(user.remove(), true); QCOMPARE(users.all().size(), 0); } /** Test removing multiple users. */ void tst_Auth::removeFilter() { loadFixtures(); // remove "foouser" and "baruser" const QDjangoQuerySet users; QDjangoQuerySet qs = users.filter(QDjangoWhere("username", QDjangoWhere::IsIn, QStringList() << "foouser" << "baruser")); QCOMPARE(qs.remove(), true); // check remaining user qs = users.all(); QCOMPARE(qs.size(), 1); User *other = qs.at(0); QVERIFY(other != 0); QCOMPARE(other->username(), QLatin1String("wizuser")); delete other; } /** Test removing multiple users with a LIMIT clause. */ void tst_Auth::removeLimit() { loadFixtures(); // FIXME : remove the first two entries fails const QDjangoQuerySet users; QCOMPARE(users.limit(0, 2).remove(), false); QCOMPARE(users.all().size(), 3); } /** Test retrieving a single user. */ void tst_Auth::get() { loadFixtures(); // get an inexistent user const QDjangoQuerySet users; User *other = users.get(QDjangoWhere("username", QDjangoWhere::Equals, "does_not_exist")); QVERIFY(other == 0); // get multiple users other = users.get(QDjangoWhere()); QVERIFY(other == 0); // get an existing user other = users.get(QDjangoWhere("username", QDjangoWhere::Equals, "foouser")); QVERIFY(other != 0); QCOMPARE(other->username(), QLatin1String("foouser")); QCOMPARE(other->password(), QLatin1String("foopass")); delete other; } /** Test filtering users with a "=" comparison. */ void tst_Auth::filter() { loadFixtures(); // all users const QDjangoQuerySet users; QDjangoQuerySet qs = users.all(); CHECKWHERE(qs.where(), QString(), QVariantList()); QCOMPARE(qs.size(), 3); // invalid username qs = users.filter(QDjangoWhere("username", QDjangoWhere::Equals, "doesnotexist")); CHECKWHERE(qs.where(), QLatin1String("\"user\".\"username\" = ?"), QVariantList() << "doesnotexist"); QCOMPARE(qs.size(), 0); // valid username qs = users.filter(QDjangoWhere("username", QDjangoWhere::Equals, "foouser")); CHECKWHERE(qs.where(), QLatin1String("\"user\".\"username\" = ?"), QVariantList() << "foouser"); QCOMPARE(qs.size(), 1); User *other = qs.at(0); QVERIFY(other != 0); QCOMPARE(other->username(), QLatin1String("foouser")); QCOMPARE(other->password(), QLatin1String("foopass")); delete other; // chain filters qs = qs.filter(QDjangoWhere("password", QDjangoWhere::Equals, "foopass")); CHECKWHERE(qs.where(), QLatin1String("\"user\".\"username\" = ? AND \"user\".\"password\" = ?"), QVariantList() << "foouser" << "foopass"); QCOMPARE(qs.size(), 1); // username in list qs = users.filter(QDjangoWhere("username", QDjangoWhere::IsIn, QVariantList() << "foouser" << "wizuser")); CHECKWHERE(qs.where(), QLatin1String("\"user\".\"username\" IN (?, ?)"), QVariantList() << "foouser" << "wizuser"); QCOMPARE(qs.size(), 2); // two tests on username qs = users.filter(QDjangoWhere("username", QDjangoWhere::Equals, "foouser") || QDjangoWhere("username", QDjangoWhere::Equals, "baruser")); CHECKWHERE(qs.where(), QLatin1String("\"user\".\"username\" = ? OR \"user\".\"username\" = ?"), QVariantList() << "foouser" << "baruser"); QCOMPARE(qs.size(), 2); } /** Test filtering users with a "like" condition. */ void tst_Auth::filterLike() { loadFixtures(); // username starts with "foo" const QDjangoQuerySet users; QDjangoQuerySet qs = users.filter(QDjangoWhere("username", QDjangoWhere::StartsWith, "foo")); QCOMPARE(qs.size(), 1); User *other = qs.at(0); QVERIFY(other != 0); QCOMPARE(other->username(), QLatin1String("foouser")); QCOMPARE(other->password(), QLatin1String("foopass")); delete other; // username ends with "ouser" qs = users.filter(QDjangoWhere("username", QDjangoWhere::EndsWith, "ouser")); QCOMPARE(qs.size(), 1); other = qs.at(0); QVERIFY(other != 0); QCOMPARE(other->username(), QLatin1String("foouser")); QCOMPARE(other->password(), QLatin1String("foopass")); delete other; // username contains "ou" qs = users.filter(QDjangoWhere("username", QDjangoWhere::Contains, "ou")); QCOMPARE(qs.size(), 1); other = qs.at(0); QVERIFY(other != 0); QCOMPARE(other->username(), QLatin1String("foouser")); QCOMPARE(other->password(), QLatin1String("foopass")); delete other; } /** Test excluding users with an "=" condition. */ void tst_Auth::exclude() { loadFixtures(); const QDjangoQuerySet users; QDjangoQuerySet qs = users.all(); CHECKWHERE(qs.where(), QString(), QVariantList()); QCOMPARE(users.all().size(), 3); qs = users.exclude(QDjangoWhere("username", QDjangoWhere::Equals, "doesnotexist")); CHECKWHERE(qs.where(), QLatin1String("\"user\".\"username\" != ?"), QVariantList() << "doesnotexist"); QCOMPARE(qs.size(), 3); qs = users.exclude(QDjangoWhere("username", QDjangoWhere::Equals, "baruser")); CHECKWHERE(qs.where(), QLatin1String("\"user\".\"username\" != ?"), QVariantList() << "baruser"); QCOMPARE(qs.size(), 2); User *other = qs.at(0); QVERIFY(other != 0); QCOMPARE(other->username(), QLatin1String("foouser")); QCOMPARE(other->password(), QLatin1String("foopass")); delete other; qs = qs.exclude(QDjangoWhere("password", QDjangoWhere::Equals, "barpass")); CHECKWHERE(qs.where(), QLatin1String("\"user\".\"username\" != ? AND \"user\".\"password\" != ?"), QVariantList() << "baruser" << "barpass"); QCOMPARE(qs.size(), 2); } /** Test limiting user results. */ void tst_Auth::limit() { const QDjangoQuerySet users; for (int i = 0; i < 10; i++) { User user; user.setUsername(QString("foouser%1").arg(i)); user.setPassword(QString("foopass%1").arg(i)); QCOMPARE(user.save(), true); } // all results QDjangoQuerySet qs = users.limit(0, -1); QCOMPARE(qs.size(), 10); // all results from offset 1 qs = users.limit(1, -1); QCOMPARE(qs.size(), 9); User *other = qs.at(0); QCOMPARE(other->username(), QLatin1String("foouser1")); delete other; other = qs.at(8); QCOMPARE(other->username(), QLatin1String("foouser9")); delete other; // 5 results from offset 0 qs = users.limit(0, 5); QCOMPARE(qs.size(), 5); other = qs.at(0); QCOMPARE(other->username(), QLatin1String("foouser0")); delete other; other = qs.at(4); QCOMPARE(other->username(), QLatin1String("foouser4")); delete other; // 6 results from offset 1 qs = users.limit(1, 8); QCOMPARE(qs.size(), 8); other = qs.at(0); QCOMPARE(other->username(), QLatin1String("foouser1")); delete other; other = qs.at(7); QCOMPARE(other->username(), QLatin1String("foouser8")); delete other; } /** Test chaining limit statements. */ void tst_Auth::subLimit() { const QDjangoQuerySet users; for (int i = 0; i < 10; i++) { User user; user.setUsername(QString("foouser%1").arg(i)); user.setPassword(QString("foopass%1").arg(i)); QCOMPARE(user.save(), true); } // base query : 8 results from offset 1 QDjangoQuerySet refQs = users.limit(1, 8); // all sub-results from offset 2 QDjangoQuerySet qs = refQs.limit(2, -1); QCOMPARE(qs.size(), 6); User *other = qs.at(0); QCOMPARE(other->username(), QLatin1String("foouser3")); delete other; other = qs.at(5); QCOMPARE(other->username(), QLatin1String("foouser8")); delete other; // 4 sub-results from offset 0 qs = refQs.limit(0, 4); QCOMPARE(qs.size(), 4); other = qs.at(0); QCOMPARE(other->username(), QLatin1String("foouser1")); delete other; other = qs.at(3); QCOMPARE(other->username(), QLatin1String("foouser4")); delete other; // 3 sub-results from offset 2 qs = refQs.limit(2, 3); QCOMPARE(qs.size(), 3); other = qs.at(0); QCOMPARE(other->username(), QLatin1String("foouser3")); delete other; other = qs.at(2); QCOMPARE(other->username(), QLatin1String("foouser5")); delete other; } /** Test ordering. */ void tst_Auth::orderBy() { loadFixtures(); User user; const QDjangoQuerySet users; // sort ascending QDjangoQuerySet qs = users.orderBy(QStringList() << "username"); QCOMPARE(qs.count(), 3); QCOMPARE(qs.size(), 3); QVERIFY(qs.at(0, &user)); QCOMPARE(user.username(), QLatin1String("baruser")); QVERIFY(qs.at(1, &user)); QCOMPARE(user.username(), QLatin1String("foouser")); QVERIFY(qs.at(2, &user)); QCOMPARE(user.username(), QLatin1String("wizuser")); // sort descending qs = users.orderBy(QStringList() << "-username"); QCOMPARE(qs.count(), 3); QCOMPARE(qs.size(), 3); QVERIFY(qs.at(0, &user)); QCOMPARE(user.username(), QLatin1String("wizuser")); QVERIFY(qs.at(1, &user)); QCOMPARE(user.username(), QLatin1String("foouser")); QVERIFY(qs.at(2, &user)); QCOMPARE(user.username(), QLatin1String("baruser")); } /** Test updating. */ void tst_Auth::update() { loadFixtures(); QVariantMap fields; fields.insert("password", "xxx"); // update no fields QCOMPARE(QDjangoQuerySet().update(QVariantMap()), 0); // update none QCOMPARE(QDjangoQuerySet().none().update(fields), 0); // update all QDjangoQuerySet qs; QCOMPARE(qs.update(fields), 3); QDjangoQuerySet all; foreach (const User &user, all) QCOMPARE(user.password(), QLatin1String("xxx")); // update one fields.insert("password", "yyy"); qs = qs.filter(QDjangoWhere("username", QDjangoWhere::Equals, "baruser")); QCOMPARE(qs.update(fields), 1); all = QDjangoQuerySet(); foreach (const User &user, all) { if (user.username() == "baruser") QCOMPARE(user.password(), QLatin1String("yyy")); else QCOMPARE(user.password(), QLatin1String("xxx")); } } /** Test retrieving maps of values. */ void tst_Auth::values() { loadFixtures(); const QDjangoQuerySet users; // FIXME : test last_login QList< QMap > map = users.all().values(); QCOMPARE(map.size(), 3); QCOMPARE(map[0].keys(), QList() << "date_joined" << "email" << "first_name" << "id" << "is_active" << "is_staff" << "is_superuser" << "last_login" << "last_name" << "password" << "username"); QCOMPARE(map[0]["username"], QVariant("foouser")); QCOMPARE(map[0]["password"], QVariant("foopass")); QCOMPARE(map[1].keys(), QList() << "date_joined" << "email" << "first_name" << "id" << "is_active" << "is_staff" << "is_superuser" << "last_login" << "last_name" << "password" << "username"); QCOMPARE(map[1]["username"], QVariant("baruser")); QCOMPARE(map[1]["password"], QVariant("barpass")); QCOMPARE(map[2].keys(), QList() << "date_joined" << "email" << "first_name" << "id" << "is_active" << "is_staff" << "is_superuser" << "last_login" << "last_name" << "password" << "username"); QCOMPARE(map[2]["username"], QVariant("wizuser")); QCOMPARE(map[2]["password"], QVariant("wizpass")); // FIXME : test last_login map = users.all().values(QStringList() << "username" << "password"); QCOMPARE(map.size(), 3); QCOMPARE(map[0].keys(), QList() << "password" << "username"); QCOMPARE(map[0]["username"], QVariant("foouser")); QCOMPARE(map[0]["password"], QVariant("foopass")); QCOMPARE(map[1].keys(), QList() << "password" << "username"); QCOMPARE(map[1]["username"], QVariant("baruser")); QCOMPARE(map[1]["password"], QVariant("barpass")); QCOMPARE(map[2].keys(), QList() << "password" << "username"); QCOMPARE(map[2]["username"], QVariant("wizuser")); QCOMPARE(map[2]["password"], QVariant("wizpass")); } /** Test retrieving lists of values. */ void tst_Auth::valuesList() { loadFixtures(); const QDjangoQuerySet users; // FIXME : test last_login QList< QVariantList > list = users.all().valuesList(); QCOMPARE(list.size(), 3); QCOMPARE(list[0].size(), 11); QCOMPARE(list[0][1], QVariant("foouser")); QCOMPARE(list[0][5], QVariant("foopass")); QCOMPARE(list[1].size(), 11); QCOMPARE(list[1][1], QVariant("baruser")); QCOMPARE(list[1][5], QVariant("barpass")); QCOMPARE(list[2].size(), 11); QCOMPARE(list[2][1], QVariant("wizuser")); QCOMPARE(list[2][5], QVariant("wizpass")); // FIXME : test last_login list = users.all().valuesList(QStringList() << "username" << "password"); QCOMPARE(list.size(), 3); QCOMPARE(list[0].size(), 2); QCOMPARE(list[0][0], QVariant("foouser")); QCOMPARE(list[0][1], QVariant("foopass")); QCOMPARE(list[1].size(), 2); QCOMPARE(list[1][0], QVariant("baruser")); QCOMPARE(list[1][1], QVariant("barpass")); QCOMPARE(list[2].size(), 2); QCOMPARE(list[2][0], QVariant("wizuser")); QCOMPARE(list[2][1], QVariant("wizpass")); } void tst_Auth::constIterator() { loadFixtures(); QVERIFY(!QTest::currentTestFailed()); const QDjangoQuerySet users = QDjangoQuerySet().orderBy(QStringList("username")); const QDjangoQuerySet::ConstIterator first = users.constBegin(); const QDjangoQuerySet::ConstIterator last = users.constEnd(); QVERIFY(first != last); QVERIFY(first < last); QVERIFY(first <= last); QVERIFY(last >= first); QVERIFY(last > first); QCOMPARE(int(last - first), +3); QCOMPARE(int(first - last), -3); QDjangoQuerySet::ConstIterator it = first; QVERIFY(it != last); QVERIFY(it == first); QCOMPARE(int(last - it), 3); QCOMPARE(int(it - first), 0); QCOMPARE(it->username(), QLatin1String("baruser")); QCOMPARE((++it)->username(), QLatin1String("foouser")); QCOMPARE(it->username(), QLatin1String("foouser")); QCOMPARE((it++)->username(), QLatin1String("foouser")); QCOMPARE(it->username(), QLatin1String("wizuser")); QVERIFY((it - 2) == first); QCOMPARE(int(it - first), 2); QCOMPARE(int(last - it), 1); QVERIFY((it -= 2) == first); QCOMPARE(int(it - first), 0); QCOMPARE(int(last - it), 3); QCOMPARE((*it).username(), QLatin1String("baruser")); QCOMPARE((*(it + 2)).username(), QLatin1String("wizuser")); QVERIFY(it == first); QCOMPARE((*(it += 1)).username(), QLatin1String("foouser")); QCOMPARE(int(it - first), 1); QTest::ignoreMessage(QtWarningMsg, "QDjangoQuerySet out of bounds"); QVERIFY(&*(it += 2) == 0); QCOMPARE(int(last - it), 0); QVERIFY(it == last); QCOMPARE((it += -3)->username(), QLatin1String("baruser")); QVERIFY(it == first); QCOMPARE((it -= -2)->username(), QLatin1String("wizuser")); QCOMPARE(int(last - it), 1); QCOMPARE((it--)->username(), QLatin1String("wizuser")); QCOMPARE(it->username(), QLatin1String("foouser")); QCOMPARE(int(last - it), 2); QCOMPARE((--it)->username(), QLatin1String("baruser")); QCOMPARE(it->username(), QLatin1String("baruser")); QCOMPARE(int(last - it), 3); } /** Clear database table after each test. */ void tst_Auth::cleanup() { QCOMPARE(QDjangoQuerySet().remove(), true); QCOMPARE(QDjangoQuerySet().remove(), true); QCOMPARE(QDjangoQuerySet().remove(), true); QCOMPARE(QDjangoQuerySet().remove(), true); } /** Drop database table after running tests. */ void tst_Auth::cleanupTestCase() { QVERIFY(QDjango::dropTables()); } /** Set and get foreign key on a Message object. */ void tst_Auth::testRelated() { const QDjangoQuerySet messages; // load fixtures QVariant userPk; { User user; user.setUsername("foouser"); user.setPassword("foopass"); QCOMPARE(user.save(), true); userPk = user.pk(); Message message; message.setUser(&user); message.setMessage("test message"); QCOMPARE(message.save(), true); } // retrieve message, then user (2 SQL queries) Message *uncached = messages.get( QDjangoWhere("id", QDjangoWhere::Equals, 1)); QVERIFY(uncached != 0); QCOMPARE(uncached->property("user_id"), userPk); // check related user User *uncachedUser = uncached->user(); QVERIFY(uncachedUser != 0); QCOMPARE(uncachedUser->pk(), userPk); QCOMPARE(uncachedUser->username(), QLatin1String("foouser")); QCOMPARE(uncachedUser->password(), QLatin1String("foopass")); delete uncached; // retrieve message and user (1 SQL query) Message *cached = messages.selectRelated().get( QDjangoWhere("id", QDjangoWhere::Equals, 1)); QVERIFY(cached != 0); QCOMPARE(cached->property("user_id"), userPk); // check related user User *cachedUser = cached->user(); QVERIFY(cachedUser != 0); QCOMPARE(cachedUser->pk(), userPk); QCOMPARE(cachedUser->username(), QLatin1String("foouser")); QCOMPARE(cachedUser->password(), QLatin1String("foopass")); delete cached; } /** Perform filtering on a foreign field. */ void tst_Auth::filterRelated() { const QDjangoQuerySet messages; // load fixtures QVariant userPk; { User user; user.setUsername("foouser"); user.setPassword("foopass"); QCOMPARE(user.save(), true); userPk = user.pk(); Message message; message.setUser(&user); message.setMessage("test message"); QCOMPARE(message.save(), true); } // perform filtering QDjangoQuerySet qs = messages.filter( QDjangoWhere("user__username", QDjangoWhere::Equals, "foouser")); CHECKWHERE(qs.where(), QLatin1String("T0.\"username\" = ?"), QVariantList() << "foouser"); QCOMPARE(qs.size(), 1); Message *msg = qs.at(0); QVERIFY(msg != 0); QCOMPARE(msg->message(), QLatin1String("test message")); QCOMPARE(msg->property("user_id"), userPk); delete msg; } /** Test many-to-many relationships using an intermediate table. */ void tst_Auth::testGroups() { const QDjangoQuerySet userGroups; User user; user.setUsername("foouser"); user.setPassword("foopass"); QCOMPARE(user.save(), true); Group group; group.setName("foogroup"); QCOMPARE(group.save(), true); UserGroups userGroup; userGroup.setUser(&user); userGroup.setGroup(&group); QCOMPARE(userGroup.save(), true); UserGroups *ug = userGroups.selectRelated().get( QDjangoWhere("id", QDjangoWhere::Equals, 1)); QVERIFY(ug != 0); QCOMPARE(ug->property("user_id"), user.pk()); QCOMPARE(ug->property("group_id"), group.pk()); delete ug; } QTEST_MAIN(tst_Auth) #include "tst_auth.moc" qdjango-0.6.2/tests/db/db.pri000066400000000000000000000002261261212605400157710ustar00rootroot00000000000000include(../tests.pri) QT += sql HEADERS += $$PWD/util.h SOURCES += $$PWD/util.cpp INCLUDEPATH += $$PWD LIBS += -L../../../src/db $$QDJANGO_DB_LIBS qdjango-0.6.2/tests/db/db.pro000066400000000000000000000002551261212605400160010ustar00rootroot00000000000000TEMPLATE = subdirs SUBDIRS = \ qdjango \ qdjangocompiler \ qdjangometamodel \ qdjangomodel \ qdjangoqueryset \ qdjangowhere \ auth \ shares qdjango-0.6.2/tests/db/qdjango/000077500000000000000000000000001261212605400163135ustar00rootroot00000000000000qdjango-0.6.2/tests/db/qdjango/qdjango.pro000066400000000000000000000001031261212605400204520ustar00rootroot00000000000000include(../db.pri) TARGET = tst_qdjango SOURCES += tst_qdjango.cpp qdjango-0.6.2/tests/db/qdjango/tst_qdjango.cpp000066400000000000000000000065721261212605400213460ustar00rootroot00000000000000/* * Copyright (C) 2010-2015 Jeremy Lainé * Contact: https://github.com/jlaine/qdjango * * This file is part of the QDjango Library. * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * This library 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 * Lesser General Public License for more details. */ #include #include #include #include "QDjango.h" #include "QDjangoModel.h" #include "QDjangoQuerySet.h" #include "util.h" class Author : public QDjangoModel { Q_OBJECT Q_PROPERTY(QString name READ name WRITE setName) public: Author(QObject *parent = 0) : QDjangoModel(parent) {} QString name() const { return m_name; } void setName(const QString &name) { m_name = name; } private: QString m_name; }; class Worker : public QObject { Q_OBJECT public slots: void doIt(); signals: void done(); }; void Worker::doIt() { Author author; author.setName("someone"); QVERIFY(author.save()); emit done(); } class tst_QDjango : public QObject { Q_OBJECT private slots: void initTestCase(); void init(); void databaseThreaded(); void debugEnabled(); void debugQuery(); void cleanup(); }; void tst_QDjango::initTestCase() { QCOMPARE(QDjango::database().isOpen(), false); QVERIFY(initialiseDatabase()); QCOMPARE(QDjango::database().isOpen(), true); } void tst_QDjango::init() { QDjango::registerModel(); QSqlDatabase db = QDjango::database(); QVERIFY(db.tables().indexOf("author") == -1); QVERIFY(QDjango::createTables()); QVERIFY(db.tables().indexOf("author") != -1); } void tst_QDjango::cleanup() { QSqlDatabase db = QDjango::database(); QVERIFY(QDjango::dropTables()); QVERIFY(db.tables().indexOf("author") == -1); } void tst_QDjango::databaseThreaded() { if (QDjango::database().databaseName() == QLatin1String(":memory:")) #if (QT_VERSION >= QT_VERSION_CHECK(5, 0, 0)) QSKIP("Threaded test cannot work with in-memory SQLite database."); #else QSKIP("Threaded test cannot work with in-memory SQLite database.", SkipAll); #endif QDjangoQuerySet qs; QCOMPARE(qs.count(), 0); QEventLoop loop; Worker worker; QThread workerThread; // fire up worker worker.moveToThread(&workerThread); connect(&worker, SIGNAL(done()), &loop, SLOT(quit())); workerThread.start(); QTimer::singleShot(0, &worker, SLOT(doIt())); loop.exec(); // check database QCOMPARE(qs.count(), 1); // stop thread workerThread.quit(); workerThread.wait(); } void tst_QDjango::debugEnabled() { QCOMPARE(QDjango::isDebugEnabled(), false); QDjango::setDebugEnabled(true); QCOMPARE(QDjango::isDebugEnabled(), true); QDjango::setDebugEnabled(false); QCOMPARE(QDjango::isDebugEnabled(), false); } void tst_QDjango::debugQuery() { QDjangoQuery query(QDjango::database()); QDjango::setDebugEnabled(true); QVERIFY(!query.exec("SELECT foo")); QDjango::setDebugEnabled(false); } QTEST_MAIN(tst_QDjango) #include "tst_qdjango.moc" qdjango-0.6.2/tests/db/qdjangocompiler/000077500000000000000000000000001261212605400200465ustar00rootroot00000000000000qdjango-0.6.2/tests/db/qdjangocompiler/qdjangocompiler.pro000066400000000000000000000001231261212605400237420ustar00rootroot00000000000000include(../db.pri) TARGET = tst_qdjangocompiler SOURCES += tst_qdjangocompiler.cpp qdjango-0.6.2/tests/db/qdjangocompiler/tst_qdjangocompiler.cpp000066400000000000000000000420651261212605400246310ustar00rootroot00000000000000/* * Copyright (C) 2010-2015 Jeremy Lainé * Contact: https://github.com/jlaine/qdjango * * This file is part of the QDjango Library. * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * This library 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 * Lesser General Public License for more details. */ #include #include "QDjango.h" #include "QDjangoQuerySet.h" #include "QDjangoWhere.h" #include "util.h" static QStringList normalizeNames(const QSqlDatabase &db, const QStringList &rawNames) { QStringList normalizedNames; foreach (const QString &rawName, rawNames) { normalizedNames << normalizeSql(db, rawName); } return normalizedNames; } class Item : public QDjangoModel { Q_OBJECT Q_PROPERTY(QString name READ name WRITE setName) public: Item(QObject *parent = 0); QString name() const; void setName(const QString &name); private: QString m_name; }; class Owner : public QDjangoModel { Q_OBJECT Q_PROPERTY(QString name READ name WRITE setName) Q_PROPERTY(Item* item1 READ item1 WRITE setItem1) Q_PROPERTY(Item* item2 READ item2 WRITE setItem2) public: Owner(QObject *parent = 0); QString name() const; void setName(const QString &name); Item *item1() const; void setItem1(Item *item1); Item *item2() const; void setItem2(Item *item2); private: QString m_name; }; class OwnerWithNullableItem : public QDjangoModel { Q_OBJECT Q_PROPERTY(QString name READ name WRITE setName) Q_PROPERTY(Item* item1 READ item1 WRITE setItem1) Q_PROPERTY(Item* item2 READ item2 WRITE setItem2) Q_CLASSINFO("item2", "null=true") public: OwnerWithNullableItem(QObject *parent = 0); QString name() const; void setName(const QString &name); Item *item1() const; void setItem1(Item *item1); Item *item2() const; void setItem2(Item *item2); private: QString m_name; }; class Top : public QDjangoModel { Q_OBJECT Q_PROPERTY(QString name READ name WRITE setName) Q_PROPERTY(Owner *owner READ owner WRITE setOwner) public: Top(QObject *parent = 0); QString name() const; void setName(const QString &name); Owner *owner() const; void setOwner(Owner *owner); private: QString m_name; }; class TopWithNullableItem : public QDjangoModel { Q_OBJECT Q_PROPERTY(QString name READ name WRITE setName) Q_PROPERTY(OwnerWithNullableItem *owner READ owner WRITE setOwner) public: TopWithNullableItem(QObject *parent = 0); QString name() const; void setName(const QString &name); OwnerWithNullableItem *owner() const; void setOwner(OwnerWithNullableItem *owner); private: QString m_name; }; class tst_QDjangoCompiler : public QObject { Q_OBJECT private slots: void initTestCase(); void fieldNames_data(); void fieldNames(); void orderLimitSql_data(); void orderLimitSql(); }; Item::Item(QObject *parent) : QDjangoModel(parent) { } QString Item::name() const { return m_name; } void Item::setName(const QString &name) { m_name = name; } Owner::Owner(QObject *parent) : QDjangoModel(parent) { setForeignKey("item1", new Item(this)); setForeignKey("item2", new Item(this)); } QString Owner::name() const { return m_name; } void Owner::setName(const QString &name) { m_name = name; } Item* Owner::item1() const { return qobject_cast(foreignKey("item1")); } void Owner::setItem1(Item *item1) { setForeignKey("item1", item1); } Item* Owner::item2() const { return qobject_cast(foreignKey("item2")); } void Owner::setItem2(Item *item2) { setForeignKey("item2", item2); } OwnerWithNullableItem::OwnerWithNullableItem(QObject *parent) : QDjangoModel(parent) { setForeignKey("item1", new Item(this)); setForeignKey("item2", new Item(this)); } QString OwnerWithNullableItem::name() const { return m_name; } void OwnerWithNullableItem::setName(const QString &name) { m_name = name; } Item* OwnerWithNullableItem::item1() const { return qobject_cast(foreignKey("item1")); } void OwnerWithNullableItem::setItem1(Item *item1) { setForeignKey("item1", item1); } Item* OwnerWithNullableItem::item2() const { return qobject_cast(foreignKey("item2")); } void OwnerWithNullableItem::setItem2(Item *item2) { setForeignKey("item2", item2); } Top::Top(QObject *parent) : QDjangoModel(parent) { } QString Top::name() const { return m_name; } void Top::setName(const QString &name) { m_name = name; } Owner* Top::owner() const { return qobject_cast(foreignKey("owner")); } void Top::setOwner(Owner *owner) { setForeignKey("owner", owner); } TopWithNullableItem::TopWithNullableItem(QObject *parent) : QDjangoModel(parent) { } QString TopWithNullableItem::name() const { return m_name; } void TopWithNullableItem::setName(const QString &name) { m_name = name; } OwnerWithNullableItem* TopWithNullableItem::owner() const { return qobject_cast(foreignKey("owner")); } void TopWithNullableItem::setOwner(OwnerWithNullableItem *owner) { setForeignKey("owner", owner); } void tst_QDjangoCompiler::initTestCase() { QVERIFY(initialiseDatabase()); QDjango::registerModel(); QDjango::registerModel(); QDjango::registerModel(); QDjango::registerModel(); QDjango::registerModel(); } void tst_QDjangoCompiler::fieldNames_data() { QSqlDatabase db = QDjango::database(); QTest::addColumn("modelName"); QTest::addColumn("recursive"); QTest::addColumn("fieldNames"); QTest::addColumn("where"); QTest::addColumn("whereSql"); QTest::addColumn("whereValues"); QTest::addColumn("orderBy"); QTest::addColumn("orderSql"); QTest::addColumn("fromSql"); QTest::newRow("non recursive") << QByteArray("Owner") << false << (QStringList() << "\"owner\".\"id\"" << "\"owner\".\"name\"" << "\"owner\".\"item1_id\"" << "\"owner\".\"item2_id\"") // filtering << QDjangoWhere() << "" << QVariantList() // ordering << QStringList() << "" << "\"owner\""; QTest::newRow("recurse one level") << QByteArray("Owner") << true << (QStringList() << "\"owner\".\"id\"" << "\"owner\".\"name\"" << "\"owner\".\"item1_id\"" << "\"owner\".\"item2_id\"" << "T0.\"id\"" << "T0.\"name\"" << "T1.\"id\"" << "T1.\"name\"") // filtering << QDjangoWhere() << "" << QVariantList() // ordering << QStringList() << "" << "\"owner\"" " INNER JOIN \"item\" T0 ON T0.\"id\" = \"owner\".\"item1_id\"" " INNER JOIN \"item\" T1 ON T1.\"id\" = \"owner\".\"item2_id\""; QTest::newRow("recurse with nullable") << QByteArray("OwnerWithNullableItem") << true << (QStringList() << "\"ownerwithnullableitem\".\"id\"" << "\"ownerwithnullableitem\".\"name\"" << "\"ownerwithnullableitem\".\"item1_id\"" << "\"ownerwithnullableitem\".\"item2_id\"" << "T0.\"id\"" << "T0.\"name\"" << "T1.\"id\"" << "T1.\"name\"") // filtering << QDjangoWhere() << "" << QVariantList() // ordering << QStringList() << "" << "\"ownerwithnullableitem\"" " INNER JOIN \"item\" T0 ON T0.\"id\" = \"ownerwithnullableitem\".\"item1_id\"" " LEFT OUTER JOIN \"item\" T1 ON T1.\"id\" = \"ownerwithnullableitem\".\"item2_id\""; QTest::newRow("recurse two levels") << QByteArray("Top") << true << (QStringList() << "\"top\".\"id\"" << "\"top\".\"name\"" << "\"top\".\"owner_id\"" << "T0.\"id\"" << "T0.\"name\"" << "T0.\"item1_id\"" << "T0.\"item2_id\"" << "T1.\"id\"" << "T1.\"name\"" << "T2.\"id\"" << "T2.\"name\"") // filtering << QDjangoWhere() << "" << QVariantList() // ordering << QStringList() << "" << "\"top\"" " INNER JOIN \"owner\" T0 ON T0.\"id\" = \"top\".\"owner_id\"" " INNER JOIN \"item\" T1 ON T1.\"id\" = T0.\"item1_id\"" " INNER JOIN \"item\" T2 ON T2.\"id\" = T0.\"item2_id\""; QTest::newRow("recurse two levels with nullable item") << QByteArray("TopWithNullableItem") << true << (QStringList() << "\"topwithnullableitem\".\"id\"" << "\"topwithnullableitem\".\"name\"" << "\"topwithnullableitem\".\"owner_id\"" << "T0.\"id\"" << "T0.\"name\"" << "T0.\"item1_id\"" << "T0.\"item2_id\"" << "T1.\"id\"" << "T1.\"name\"" << "T2.\"id\"" << "T2.\"name\"") // filtering << QDjangoWhere() << "" << QVariantList() // ordering << QStringList() << "" << "\"topwithnullableitem\"" " INNER JOIN \"ownerwithnullableitem\" T0 ON T0.\"id\" = \"topwithnullableitem\".\"owner_id\"" " INNER JOIN \"item\" T1 ON T1.\"id\" = T0.\"item1_id\"" " LEFT OUTER JOIN \"item\" T2 ON T2.\"id\" = T0.\"item2_id\""; QTest::newRow("order ascending") << QByteArray("Owner") << false << (QStringList() << "\"owner\".\"id\"" << "\"owner\".\"name\"" << "\"owner\".\"item1_id\"" << "\"owner\".\"item2_id\"") // filtering << QDjangoWhere() << "" << QVariantList() // ordering << QStringList("name") << QString(" ORDER BY \"owner\".\"name\" ASC") << QString("\"owner\""); QTest::newRow("order ascending explicit") << QByteArray("Owner") << false << (QStringList() << "\"owner\".\"id\"" << "\"owner\".\"name\"" << "\"owner\".\"item1_id\"" << "\"owner\".\"item2_id\"") // filtering << QDjangoWhere() << "" << QVariantList() // ordering << QStringList("+name") << QString(" ORDER BY \"owner\".\"name\" ASC") << QString("\"owner\""); QTest::newRow("order ascending foreign") << QByteArray("Owner") << false << (QStringList() << "\"owner\".\"id\"" << "\"owner\".\"name\"" << "\"owner\".\"item1_id\"" << "\"owner\".\"item2_id\"") // filtering << QDjangoWhere() << "" << QVariantList() // ordering << QStringList("item1__name") << QString(" ORDER BY T0.\"name\" ASC") << "\"owner\"" " INNER JOIN \"item\" T0 ON T0.\"id\" = \"owner\".\"item1_id\""; QTest::newRow("order ascending foreign double") << QByteArray("Owner") << false << (QStringList() << "\"owner\".\"id\"" << "\"owner\".\"name\"" << "\"owner\".\"item1_id\"" << "\"owner\".\"item2_id\"") // filtering << QDjangoWhere() << "" << QVariantList() // ordering << (QStringList() << "item1__name" << "item2__name") << QString(" ORDER BY T0.\"name\" ASC, T1.\"name\" ASC") << "\"owner\"" " INNER JOIN \"item\" T0 ON T0.\"id\" = \"owner\".\"item1_id\"" " INNER JOIN \"item\" T1 ON T1.\"id\" = \"owner\".\"item2_id\""; QTest::newRow("order descending") << QByteArray("Owner") << false << (QStringList() << "\"owner\".\"id\"" << "\"owner\".\"name\"" << "\"owner\".\"item1_id\"" << "\"owner\".\"item2_id\"") // filtering << QDjangoWhere() << "" << QVariantList() // ordering << QStringList("-name") << QString(" ORDER BY \"owner\".\"name\" DESC") << QString("\"owner\""); QTest::newRow("filter local field") << QByteArray("Owner") << false << (QStringList() << "\"owner\".\"id\"" << "\"owner\".\"name\"" << "\"owner\".\"item1_id\"" << "\"owner\".\"item2_id\"") // filtering << QDjangoWhere("name", QDjangoWhere::Equals, "foo") << "\"owner\".\"name\" = ?" << (QVariantList() << "foo") // ordering << QStringList() << "" << "\"owner\""; QTest::newRow("filter foreign field") << QByteArray("Owner") << false << (QStringList() << "\"owner\".\"id\"" << "\"owner\".\"name\"" << "\"owner\".\"item1_id\"" << "\"owner\".\"item2_id\"") // filtering << QDjangoWhere("item1__name", QDjangoWhere::Equals, "foo") << "T0.\"name\" = ?" << (QVariantList() << "foo") // ordering << QStringList() << "" << "\"owner\"" " INNER JOIN \"item\" T0 ON T0.\"id\" = \"owner\".\"item1_id\""; QTest::newRow("filter reverse field") << QByteArray("Owner") << false << (QStringList() << "\"owner\".\"id\"" << "\"owner\".\"name\"" << "\"owner\".\"item1_id\"" << "\"owner\".\"item2_id\"") // filtering << QDjangoWhere("top__name", QDjangoWhere::Equals, "foo") << "T0.\"name\" = ?" << (QVariantList() << "foo") // ordering << QStringList() << "" << "\"owner\"" " INNER JOIN \"top\" T0 ON T0.\"owner_id\" = \"owner\".\"id\""; QTest::newRow("filter multiple fields") << QByteArray("Owner") << false << (QStringList() << "\"owner\".\"id\"" << "\"owner\".\"name\"" << "\"owner\".\"item1_id\"" << "\"owner\".\"item2_id\"") // filtering << (QDjangoWhere("item1__name", QDjangoWhere::Equals, "foo") && QDjangoWhere("item2__name", QDjangoWhere::Equals, "bar")) << "T0.\"name\" = ? AND T1.\"name\" = ?" << (QVariantList() << "foo" << "bar") // ordering << QStringList() << "" << "\"owner\"" " INNER JOIN \"item\" T0 ON T0.\"id\" = \"owner\".\"item1_id\"" " INNER JOIN \"item\" T1 ON T1.\"id\" = \"owner\".\"item2_id\""; } void tst_QDjangoCompiler::fieldNames() { QFETCH(QByteArray, modelName); QFETCH(bool, recursive); QFETCH(QStringList, fieldNames); QFETCH(QDjangoWhere, where); QFETCH(QString, whereSql); QFETCH(QVariantList, whereValues); QFETCH(QStringList, orderBy); QFETCH(QString, orderSql); QFETCH(QString, fromSql); QSqlDatabase db = QDjango::database(); QDjangoCompiler compiler(modelName, db); compiler.resolve(where); CHECKWHERE(where, whereSql, whereValues); QCOMPARE(normalizeNames(db, compiler.fieldNames(recursive)), fieldNames); QCOMPARE(normalizeSql(db, compiler.orderLimitSql(orderBy, 0, 0)), orderSql); QCOMPARE(normalizeSql(db, compiler.fromSql()), fromSql); } void tst_QDjangoCompiler::orderLimitSql_data() { QTest::addColumn("orderBy"); QTest::addColumn("lowMark"); QTest::addColumn("highMark"); QTest::addColumn("sql"); QDjangoDatabase::DatabaseType databaseType = QDjangoDatabase::databaseType(QDjango::database()); QString sql; // no order, from 0 QTest::newRow("no order, from 0") << QStringList() << 0 << 0 << ""; // no order, from 0 to 3 if (databaseType == QDjangoDatabase::MSSqlServer) sql = " ORDER BY \"owner\".\"id\" OFFSET 0 ROWS FETCH NEXT 3 ROWS ONLY"; else sql = " LIMIT 3"; QTest::newRow("no order, from 0 to 3") << QStringList() << 0 << 3 << sql; // no order, from 1 if (databaseType == QDjangoDatabase::MySqlServer) sql = " LIMIT 18446744073709551615 OFFSET 1"; else if (databaseType == QDjangoDatabase::SQLite) sql = " LIMIT -1 OFFSET 1"; else if (databaseType == QDjangoDatabase::MSSqlServer) sql = " ORDER BY \"owner\".\"id\" OFFSET 1 ROWS"; else sql = " OFFSET 1"; QTest::newRow("no order, from 1") << QStringList() << 1 << 0 << sql; // no order, from 1 to 3 if (databaseType == QDjangoDatabase::MSSqlServer) sql = " ORDER BY \"owner\".\"id\" OFFSET 1 ROWS FETCH NEXT 2 ROWS ONLY"; else sql = " LIMIT 2 OFFSET 1"; QTest::newRow("no order, from 1 to 3") << QStringList() << 1 << 3 << sql; } void tst_QDjangoCompiler::orderLimitSql() { QFETCH(QStringList, orderBy); QFETCH(int, lowMark); QFETCH(int, highMark); QFETCH(QString, sql); QSqlDatabase db = QDjango::database(); QDjangoCompiler compiler("Owner", db); QCOMPARE(compiler.orderLimitSql(orderBy, lowMark, highMark), sql); } Q_DECLARE_METATYPE(QDjangoWhere) QTEST_MAIN(tst_QDjangoCompiler) #include "tst_qdjangocompiler.moc" qdjango-0.6.2/tests/db/qdjangometamodel/000077500000000000000000000000001261212605400202035ustar00rootroot00000000000000qdjango-0.6.2/tests/db/qdjangometamodel/qdjangometamodel.pro000066400000000000000000000002341261212605400242370ustar00rootroot00000000000000include(../db.pri) TARGET = tst_qdjangometamodel HEADERS += ../auth-models.h tst_qdjangometamodel.h SOURCES += ../auth-models.cpp tst_qdjangometamodel.cpp qdjango-0.6.2/tests/db/qdjangometamodel/tst_qdjangometamodel.cpp000066400000000000000000000546441261212605400251310ustar00rootroot00000000000000/* * Copyright (C) 2010-2015 Jeremy Lainé * Contact: https://github.com/jlaine/qdjango * * This file is part of the QDjango Library. * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * This library 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 * Lesser General Public License for more details. */ #include "QDjango.h" #include "QDjango_p.h" #include "QDjangoModel.h" #include "QDjangoQuerySet.h" #include "QDjangoWhere.h" #include "tst_qdjangometamodel.h" #include "util.h" #define Q QDjangoWhere template void init(const QStringList &sql) { const QDjangoMetaModel metaModel = QDjango::registerModel(); QCOMPARE(metaModel.createTableSql(), sql); QCOMPARE(metaModel.createTable(), true); } template void setAndGet(const K &value) { // save object T v1; v1.setValue(value); QCOMPARE(v1.save(), true); QVERIFY(!v1.pk().isNull()); // save again QCOMPARE(v1.save(), true); // get object T v2; QVERIFY(QDjangoQuerySet().get(Q(QLatin1String("pk"), Q::Equals, v1.pk()), &v2) != 0); QCOMPARE(v2.value(), value); } template void cleanup() { const QDjangoMetaModel metaModel = QDjango::registerModel(); QCOMPARE(metaModel.dropTable(), true); } tst_FkConstraint::tst_FkConstraint(QObject *parent) : QDjangoModel(parent) { setForeignKey("noConstraint", new User(this)); setForeignKey("cascadeConstraint", new User(this)); setForeignKey("nullConstraint", new Group(this)); } User *tst_FkConstraint::noConstraint() const { return qobject_cast(foreignKey("noConstraint")); } void tst_FkConstraint::setNoConstraint(User *user) { setForeignKey("noConstraint", user); } User *tst_FkConstraint::cascadeConstraint() const { return qobject_cast(foreignKey("cascadeConstraint")); } void tst_FkConstraint::setCascadeConstraint(User *user) { setForeignKey("cascadeConstraint", user); } Group *tst_FkConstraint::nullConstraint() const { return qobject_cast(foreignKey("nullConstraint")); } void tst_FkConstraint::setNullConstraint(Group *group) { setForeignKey("nullConstraint", group); } tst_FkConstraintWithRestrict::tst_FkConstraintWithRestrict(QObject *parent) : tst_FkConstraint(parent) { setForeignKey("restrictConstraint", new User(this)); } User *tst_FkConstraintWithRestrict::restrictConstraint() const { return qobject_cast(foreignKey("restrictConstraint")); } void tst_FkConstraintWithRestrict::setRestrictConstraint(User *user) { setForeignKey("restrictConstraint", user); } void tst_QDjangoMetaModel::initTestCase() { QVERIFY(initialiseDatabase()); } void tst_QDjangoMetaModel::testBool() { QStringList sql; QDjangoDatabase::DatabaseType databaseType = QDjangoDatabase::databaseType(QDjango::database()); if (databaseType == QDjangoDatabase::PostgreSQL) sql << QLatin1String("CREATE TABLE \"tst_bool\" (\"id\" serial PRIMARY KEY, \"value\" boolean NOT NULL)"); else if (databaseType == QDjangoDatabase::MySqlServer) sql << QLatin1String("CREATE TABLE `tst_bool` (`id` integer NOT NULL PRIMARY KEY AUTO_INCREMENT, `value` bool NOT NULL)"); else if (databaseType == QDjangoDatabase::MSSqlServer) sql << QLatin1String("CREATE TABLE \"tst_bool\" (\"id\" int NOT NULL PRIMARY KEY IDENTITY(1,1), \"value\" bit NOT NULL)"); else sql << QLatin1String("CREATE TABLE \"tst_bool\" (\"id\" integer NOT NULL PRIMARY KEY AUTOINCREMENT, \"value\" bool NOT NULL)"); init(sql); setAndGet(true); setAndGet(false); cleanup(); } void tst_QDjangoMetaModel::testByteArray() { QStringList sql; QDjangoDatabase::DatabaseType databaseType = QDjangoDatabase::databaseType(QDjango::database()); if (databaseType == QDjangoDatabase::PostgreSQL) sql << QLatin1String("CREATE TABLE \"tst_bytearray\" (\"id\" serial PRIMARY KEY, \"value\" bytea NOT NULL)"); else if (databaseType == QDjangoDatabase::MySqlServer) sql << QLatin1String("CREATE TABLE `tst_bytearray` (`id` integer NOT NULL PRIMARY KEY AUTO_INCREMENT, `value` blob NOT NULL)"); else if (databaseType == QDjangoDatabase::MSSqlServer) sql << QLatin1String("CREATE TABLE \"tst_bytearray\" (\"id\" int NOT NULL PRIMARY KEY IDENTITY(1,1), \"value\" varbinary(max) NOT NULL)"); else sql << QLatin1String("CREATE TABLE \"tst_bytearray\" (\"id\" integer NOT NULL PRIMARY KEY AUTOINCREMENT, \"value\" blob NOT NULL)"); init(sql); setAndGet(QByteArray("01234567", 8)); setAndGet(QByteArray("\x00\x01\x02\x03\x04\x05\x06\x07", 8)); cleanup(); } void tst_QDjangoMetaModel::testDate() { QStringList sql; QDjangoDatabase::DatabaseType databaseType = QDjangoDatabase::databaseType(QDjango::database()); if (databaseType == QDjangoDatabase::PostgreSQL) sql << QLatin1String("CREATE TABLE \"tst_date\" (\"id\" serial PRIMARY KEY, \"value\" date NOT NULL)"); else if (databaseType == QDjangoDatabase::MySqlServer) sql << QLatin1String("CREATE TABLE `tst_date` (`id` integer NOT NULL PRIMARY KEY AUTO_INCREMENT, `value` date NOT NULL)"); else if (databaseType == QDjangoDatabase::MSSqlServer) sql << QLatin1String("CREATE TABLE \"tst_date\" (\"id\" int NOT NULL PRIMARY KEY IDENTITY(1,1), \"value\" date NOT NULL)"); else sql << QLatin1String("CREATE TABLE \"tst_date\" (\"id\" integer NOT NULL PRIMARY KEY AUTOINCREMENT, \"value\" date NOT NULL)"); init(sql); setAndGet(QDate(2012, 1, 8)); cleanup(); } void tst_QDjangoMetaModel::testDateTime() { QStringList sql; QDjangoDatabase::DatabaseType databaseType = QDjangoDatabase::databaseType(QDjango::database()); if (databaseType == QDjangoDatabase::PostgreSQL) sql << QLatin1String("CREATE TABLE \"tst_datetime\" (\"id\" serial PRIMARY KEY, \"value\" timestamp NOT NULL)"); else if (databaseType == QDjangoDatabase::MySqlServer) sql << QLatin1String("CREATE TABLE `tst_datetime` (`id` integer NOT NULL PRIMARY KEY AUTO_INCREMENT, `value` datetime NOT NULL)"); else if (databaseType == QDjangoDatabase::MSSqlServer) sql << QLatin1String("CREATE TABLE \"tst_datetime\" (\"id\" int NOT NULL PRIMARY KEY IDENTITY(1,1), \"value\" datetime NOT NULL)"); else sql << QLatin1String("CREATE TABLE \"tst_datetime\" (\"id\" integer NOT NULL PRIMARY KEY AUTOINCREMENT, \"value\" datetime NOT NULL)"); init(sql); setAndGet(QDateTime(QDate(2012, 1, 8), QTime(3, 4, 5))); cleanup(); } void tst_QDjangoMetaModel::testDouble() { QStringList sql; QDjangoDatabase::DatabaseType databaseType = QDjangoDatabase::databaseType(QDjango::database()); if (databaseType == QDjangoDatabase::PostgreSQL) sql << QLatin1String("CREATE TABLE \"tst_double\" (\"id\" serial PRIMARY KEY, \"value\" real NOT NULL)"); else if (databaseType == QDjangoDatabase::MySqlServer) sql << QLatin1String("CREATE TABLE `tst_double` (`id` integer NOT NULL PRIMARY KEY AUTO_INCREMENT, `value` real NOT NULL)"); else if (databaseType == QDjangoDatabase::MSSqlServer) sql << QLatin1String("CREATE TABLE \"tst_double\" (\"id\" int NOT NULL PRIMARY KEY IDENTITY(1,1), \"value\" real NOT NULL)"); else sql << QLatin1String("CREATE TABLE \"tst_double\" (\"id\" integer NOT NULL PRIMARY KEY AUTOINCREMENT, \"value\" real NOT NULL)"); init(sql); if (databaseType == QDjangoDatabase::MSSqlServer) { double value = 3.14159; // save object tst_Double v1; v1.setValue(value); QCOMPARE(v1.save(), true); QVERIFY(!v1.pk().isNull()); // save again QCOMPARE(v1.save(), true); // get object tst_Double v2; QVERIFY(QDjangoQuerySet().get(Q(QLatin1String("pk"), Q::Equals, v1.pk()), &v2) != 0); double p1 = v2.value(); double p2 = value; QVERIFY(qAbs(p1 - p2) * 10000000. <= qMin(qAbs(p1), qAbs(p2))); } else { setAndGet(double(3.14159)); } cleanup(); } void tst_QDjangoMetaModel::testInteger() { QStringList sql; QDjangoDatabase::DatabaseType databaseType = QDjangoDatabase::databaseType(QDjango::database()); if (databaseType == QDjangoDatabase::PostgreSQL) sql << QLatin1String("CREATE TABLE \"tst_integer\" (\"id\" serial PRIMARY KEY, \"value\" integer NOT NULL)"); else if (databaseType == QDjangoDatabase::MySqlServer) sql << QLatin1String("CREATE TABLE `tst_integer` (`id` integer NOT NULL PRIMARY KEY AUTO_INCREMENT, `value` integer NOT NULL)"); else if (databaseType == QDjangoDatabase::MSSqlServer) sql << QLatin1String("CREATE TABLE \"tst_integer\" (\"id\" int NOT NULL PRIMARY KEY IDENTITY(1,1), \"value\" int NOT NULL)"); else sql << QLatin1String("CREATE TABLE \"tst_integer\" (\"id\" integer NOT NULL PRIMARY KEY AUTOINCREMENT, \"value\" integer NOT NULL)"); init(sql); setAndGet(0); setAndGet(-2147483647); setAndGet(2147483647); cleanup(); } void tst_QDjangoMetaModel::testLongLong() { QStringList sql; QDjangoDatabase::DatabaseType databaseType = QDjangoDatabase::databaseType(QDjango::database()); if (databaseType == QDjangoDatabase::PostgreSQL) sql << QLatin1String("CREATE TABLE \"tst_longlong\" (\"id\" serial PRIMARY KEY, \"value\" bigint NOT NULL)"); else if (databaseType == QDjangoDatabase::MySqlServer) sql << QLatin1String("CREATE TABLE `tst_longlong` (`id` integer NOT NULL PRIMARY KEY AUTO_INCREMENT, `value` bigint NOT NULL)"); else if (databaseType == QDjangoDatabase::MSSqlServer) sql << QLatin1String("CREATE TABLE \"tst_longlong\" (\"id\" int NOT NULL PRIMARY KEY IDENTITY(1,1), \"value\" bigint NOT NULL)"); else sql << QLatin1String("CREATE TABLE \"tst_longlong\" (\"id\" integer NOT NULL PRIMARY KEY AUTOINCREMENT, \"value\" bigint NOT NULL)"); init(sql); setAndGet(qlonglong(0)); setAndGet(qlonglong(-9223372036854775807ll)); setAndGet(qlonglong(9223372036854775807ll)); cleanup(); } void tst_QDjangoMetaModel::testString() { QStringList sql; QDjangoDatabase::DatabaseType databaseType = QDjangoDatabase::databaseType(QDjango::database()); if (databaseType == QDjangoDatabase::PostgreSQL) sql << QLatin1String("CREATE TABLE \"tst_string\" (\"id\" serial PRIMARY KEY, \"value\" varchar(255) NOT NULL)"); else if (databaseType == QDjangoDatabase::MySqlServer) sql << QLatin1String("CREATE TABLE `tst_string` (`id` integer NOT NULL PRIMARY KEY AUTO_INCREMENT, `value` varchar(255) NOT NULL)"); else if (databaseType == QDjangoDatabase::MSSqlServer) sql << QLatin1String("CREATE TABLE \"tst_string\" (\"id\" int NOT NULL PRIMARY KEY IDENTITY(1,1), \"value\" nvarchar(255) NOT NULL)"); else sql << QLatin1String("CREATE TABLE \"tst_string\" (\"id\" integer NOT NULL PRIMARY KEY AUTOINCREMENT, \"value\" varchar(255) NOT NULL)"); init(sql); setAndGet(QLatin1String("foo bar")); cleanup(); } void tst_QDjangoMetaModel::testTime() { QStringList sql; QDjangoDatabase::DatabaseType databaseType = QDjangoDatabase::databaseType(QDjango::database()); if (databaseType == QDjangoDatabase::MSSqlServer) #if (QT_VERSION >= QT_VERSION_CHECK(5, 0, 0)) QSKIP("Currently broken in QODBC driver"); #else QSKIP("Currently broken in QODBC driver", SkipAll); #endif if (databaseType == QDjangoDatabase::PostgreSQL) sql << QLatin1String("CREATE TABLE \"tst_time\" (\"id\" serial PRIMARY KEY, \"value\" time NOT NULL)"); else if (databaseType == QDjangoDatabase::MySqlServer) sql << QLatin1String("CREATE TABLE `tst_time` (`id` integer NOT NULL PRIMARY KEY AUTO_INCREMENT, `value` time NOT NULL)"); else if (databaseType == QDjangoDatabase::MSSqlServer) sql << QLatin1String("CREATE TABLE \"tst_time\" (\"id\" int NOT NULL PRIMARY KEY IDENTITY(1,1), \"value\" time NOT NULL)"); else sql << QLatin1String("CREATE TABLE \"tst_time\" (\"id\" integer NOT NULL PRIMARY KEY AUTOINCREMENT, \"value\" time NOT NULL)"); init(sql); setAndGet(QTime(3, 4, 5)); cleanup(); } void tst_QDjangoMetaModel::testOptions() { QStringList sql; QDjangoDatabase::DatabaseType databaseType = QDjangoDatabase::databaseType(QDjango::database()); if (databaseType == QDjangoDatabase::PostgreSQL) { sql << QLatin1String( "CREATE TABLE \"some_table\" (" "\"id\" serial PRIMARY KEY, " "\"aField\" integer NOT NULL, " "\"b_field\" integer NOT NULL, " "\"blankField\" integer NOT NULL, " "\"indexField\" integer NOT NULL, " "\"nullField\" integer, " "\"uniqueField\" integer NOT NULL UNIQUE, " "UNIQUE (\"aField\", \"b_field\")" ")"); sql << QLatin1String("CREATE INDEX \"some_table_ac243651\" ON \"some_table\" (\"indexField\")"); } else if (databaseType == QDjangoDatabase::MySqlServer) { sql << QLatin1String( "CREATE TABLE `some_table` (" "`id` integer NOT NULL PRIMARY KEY AUTO_INCREMENT, " "`aField` integer NOT NULL, " "`b_field` integer NOT NULL, " "`blankField` integer NOT NULL, " "`indexField` integer NOT NULL, " "`nullField` integer, " "`uniqueField` integer NOT NULL UNIQUE, " "UNIQUE (`aField`, `b_field`)" ")"); sql << QLatin1String("CREATE INDEX `some_table_ac243651` ON `some_table` (`indexField`)"); } else if (databaseType == QDjangoDatabase::MSSqlServer) { sql << QLatin1String( "CREATE TABLE \"some_table\" (" "\"id\" int NOT NULL PRIMARY KEY IDENTITY(1,1), " "\"aField\" int NOT NULL, " "\"b_field\" int NOT NULL, " "\"blankField\" int NOT NULL, " "\"indexField\" int NOT NULL, " "\"nullField\" int, " "\"uniqueField\" int NOT NULL UNIQUE, " "UNIQUE (\"aField\", \"b_field\")" ")"); sql << QLatin1String("CREATE INDEX \"some_table_ac243651\" ON \"some_table\" (\"indexField\")"); } else { sql << QLatin1String( "CREATE TABLE \"some_table\" (" "\"id\" integer NOT NULL PRIMARY KEY AUTOINCREMENT, " "\"aField\" integer NOT NULL, " "\"b_field\" integer NOT NULL, " "\"blankField\" integer NOT NULL, " "\"indexField\" integer NOT NULL, " "\"nullField\" integer, " "\"uniqueField\" integer NOT NULL UNIQUE, " "UNIQUE (\"aField\", \"b_field\")" ")"); sql << QLatin1String("CREATE INDEX \"some_table_ac243651\" ON \"some_table\" (\"indexField\")"); } init(sql); QDjangoMetaField metaField; const QDjangoMetaModel metaModel = QDjango::registerModel(); metaField = metaModel.localField("aField"); QCOMPARE(metaField.isAutoIncrement(), false); QCOMPARE(metaField.isBlank(), false); QCOMPARE(metaField.isNullable(), false); QCOMPARE(metaField.isUnique(), false); QCOMPARE(metaField.isValid(), true); metaField = metaModel.localField("bField"); QCOMPARE(metaField.isAutoIncrement(), false); QCOMPARE(metaField.isBlank(), false); QCOMPARE(metaField.isNullable(), false); QCOMPARE(metaField.isUnique(), false); QCOMPARE(metaField.isValid(), true); metaField = metaModel.localField("blankField"); QCOMPARE(metaField.isAutoIncrement(), false); QCOMPARE(metaField.isBlank(), true); QCOMPARE(metaField.isNullable(), false); QCOMPARE(metaField.isUnique(), false); QCOMPARE(metaField.isValid(), true); metaField = metaModel.localField("nullField"); QCOMPARE(metaField.isAutoIncrement(), false); QCOMPARE(metaField.isBlank(), false); QCOMPARE(metaField.isNullable(), true); QCOMPARE(metaField.isUnique(), false); QCOMPARE(metaField.isValid(), true); metaField = metaModel.localField("uniqueField"); QCOMPARE(metaField.isAutoIncrement(), false); QCOMPARE(metaField.isBlank(), false); QCOMPARE(metaField.isNullable(), false); QCOMPARE(metaField.isUnique(), true); QCOMPARE(metaField.isValid(), true); cleanup(); } /** Test foreign key constraint sql generation */ void tst_QDjangoMetaModel::testConstraints() { QStringList sql; QDjangoDatabase::DatabaseType databaseType = QDjangoDatabase::databaseType(QDjango::database()); if (databaseType == QDjangoDatabase::PostgreSQL) { sql << QLatin1String("CREATE TABLE \"tst_fkconstraint\" (" "\"id\" serial PRIMARY KEY, " "\"noConstraint_id\" integer NOT NULL REFERENCES \"user\" (\"id\") DEFERRABLE INITIALLY DEFERRED, " "\"cascadeConstraint_id\" integer NOT NULL REFERENCES \"user\" (\"id\") ON DELETE CASCADE DEFERRABLE INITIALLY DEFERRED, " "\"nullConstraint_id\" integer REFERENCES \"group\" (\"id\") ON DELETE SET NULL DEFERRABLE INITIALLY DEFERRED, " "\"restrictConstraint_id\" integer NOT NULL REFERENCES \"user\" (\"id\") ON DELETE RESTRICT DEFERRABLE INITIALLY DEFERRED" ")"); sql << QLatin1String("CREATE INDEX \"tst_fkconstraint_f388fc3c\" ON \"tst_fkconstraint\" (\"noConstraint_id\")"); sql << QLatin1String("CREATE INDEX \"tst_fkconstraint_4634d592\" ON \"tst_fkconstraint\" (\"cascadeConstraint_id\")"); sql << QLatin1String("CREATE INDEX \"tst_fkconstraint_44c71620\" ON \"tst_fkconstraint\" (\"nullConstraint_id\")"); sql << QLatin1String("CREATE INDEX \"tst_fkconstraint_728cefe1\" ON \"tst_fkconstraint\" (\"restrictConstraint_id\")"); } else if (databaseType == QDjangoDatabase::MySqlServer) { sql << QLatin1String("CREATE TABLE `tst_fkconstraint` (" "`id` integer NOT NULL PRIMARY KEY AUTO_INCREMENT, " "`noConstraint_id` integer NOT NULL, " "`cascadeConstraint_id` integer NOT NULL, " "`nullConstraint_id` integer, " "`restrictConstraint_id` integer NOT NULL, " "CONSTRAINT `FK_noConstraint_id_8049d4ec` FOREIGN KEY (`noConstraint_id`) REFERENCES `user` (`id`), " "CONSTRAINT `FK_cascadeConstraint_id_d2686b82` FOREIGN KEY (`cascadeConstraint_id`) REFERENCES `user` (`id`) ON DELETE CASCADE, " "CONSTRAINT `FK_nullConstraint_id_b4eac280` FOREIGN KEY (`nullConstraint_id`) REFERENCES `group` (`id`) ON DELETE SET NULL, " "CONSTRAINT `FK_restrictConstraint_id_99b64be3` FOREIGN KEY (`restrictConstraint_id`) REFERENCES `user` (`id`) ON DELETE RESTRICT" ")"); sql << QLatin1String("CREATE INDEX `tst_fkconstraint_f388fc3c` ON `tst_fkconstraint` (`noConstraint_id`)"); sql << QLatin1String("CREATE INDEX `tst_fkconstraint_4634d592` ON `tst_fkconstraint` (`cascadeConstraint_id`)"); sql << QLatin1String("CREATE INDEX `tst_fkconstraint_44c71620` ON `tst_fkconstraint` (`nullConstraint_id`)"); sql << QLatin1String("CREATE INDEX `tst_fkconstraint_728cefe1` ON `tst_fkconstraint` (`restrictConstraint_id`)"); } else if (databaseType == QDjangoDatabase::MSSqlServer) { sql << QLatin1String("CREATE TABLE \"tst_fkconstraint\" (" "\"id\" int NOT NULL PRIMARY KEY IDENTITY(1,1), " "\"noConstraint_id\" int NOT NULL REFERENCES \"user\" (\"id\"), " "\"cascadeConstraint_id\" int NOT NULL REFERENCES \"user\" (\"id\") ON DELETE CASCADE, " "\"nullConstraint_id\" int REFERENCES \"group\" (\"id\") ON DELETE SET NULL" ")"); sql << QLatin1String("CREATE INDEX \"tst_fkconstraint_f388fc3c\" ON \"tst_fkconstraint\" (\"noConstraint_id\")"); sql << QLatin1String("CREATE INDEX \"tst_fkconstraint_4634d592\" ON \"tst_fkconstraint\" (\"cascadeConstraint_id\")"); sql << QLatin1String("CREATE INDEX \"tst_fkconstraint_44c71620\" ON \"tst_fkconstraint\" (\"nullConstraint_id\")"); } else { sql << QLatin1String("CREATE TABLE \"tst_fkconstraint\" (" "\"id\" integer NOT NULL PRIMARY KEY AUTOINCREMENT, " "\"noConstraint_id\" integer NOT NULL REFERENCES \"user\" (\"id\"), " "\"cascadeConstraint_id\" integer NOT NULL REFERENCES \"user\" (\"id\") ON DELETE CASCADE, " "\"nullConstraint_id\" integer REFERENCES \"group\" (\"id\") ON DELETE SET NULL, " "\"restrictConstraint_id\" integer NOT NULL REFERENCES \"user\" (\"id\") ON DELETE RESTRICT" ")"); sql << QLatin1String("CREATE INDEX \"tst_fkconstraint_f388fc3c\" ON \"tst_fkconstraint\" (\"noConstraint_id\")"); sql << QLatin1String("CREATE INDEX \"tst_fkconstraint_4634d592\" ON \"tst_fkconstraint\" (\"cascadeConstraint_id\")"); sql << QLatin1String("CREATE INDEX \"tst_fkconstraint_44c71620\" ON \"tst_fkconstraint\" (\"nullConstraint_id\")"); sql << QLatin1String("CREATE INDEX \"tst_fkconstraint_728cefe1\" ON \"tst_fkconstraint\" (\"restrictConstraint_id\")"); } // create tables QDjangoMetaModel userModel = QDjango::registerModel(); QCOMPARE(userModel.createTable(), true); QDjangoMetaModel groupModel = QDjango::registerModel(); QCOMPARE(groupModel.createTable(), true); QDjangoMetaModel metaModel = (databaseType == QDjangoDatabase::MSSqlServer) ? QDjango::registerModel() : QDjango::registerModel(); QCOMPARE(metaModel.createTableSql(), sql); QCOMPARE(metaModel.createTable(), true); // drop tables QCOMPARE(metaModel.dropTable(), true); QCOMPARE(userModel.dropTable(), true); QCOMPARE(groupModel.dropTable(), true); } void tst_QDjangoMetaModel::testIsValid() { QDjangoMetaModel metaModel; QVERIFY(!metaModel.isValid()); metaModel = QDjango::registerModel(); QVERIFY(metaModel.isValid()); } QTEST_MAIN(tst_QDjangoMetaModel) qdjango-0.6.2/tests/db/qdjangometamodel/tst_qdjangometamodel.h000066400000000000000000000145271261212605400245720ustar00rootroot00000000000000/* * Copyright (C) 2010-2015 Jeremy Lainé * Contact: https://github.com/jlaine/qdjango * * This file is part of the QDjango Library. * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * This library 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 * Lesser General Public License for more details. */ #include #include "QDjangoModel.h" #include "auth-models.h" class tst_QDjangoMetaModel : public QObject { Q_OBJECT private slots: void initTestCase(); void testBool(); void testByteArray(); void testDate(); void testDateTime(); void testDouble(); void testInteger(); void testLongLong(); void testString(); void testTime(); void testOptions(); void testConstraints(); void testIsValid(); }; class tst_Bool : public QDjangoModel { Q_OBJECT Q_PROPERTY(bool value READ value WRITE setValue) public: bool value() const { return m_value; } void setValue(bool value) { m_value = value; } private: bool m_value; }; class tst_ByteArray : public QDjangoModel { Q_OBJECT Q_PROPERTY(QByteArray value READ value WRITE setValue) public: QByteArray value() const { return m_value; } void setValue(const QByteArray &value) { m_value = value; } private: QByteArray m_value; }; class tst_Date : public QDjangoModel { Q_OBJECT Q_PROPERTY(QDate value READ value WRITE setValue) public: QDate value() const { return m_value; } void setValue(const QDate &value) { m_value = value; } private: QDate m_value; }; class tst_DateTime : public QDjangoModel { Q_OBJECT Q_PROPERTY(QDateTime value READ value WRITE setValue) public: QDateTime value() const { return m_value; } void setValue(const QDateTime &value) { m_value = value; } private: QDateTime m_value; }; class tst_Double : public QDjangoModel { Q_OBJECT Q_PROPERTY(double value READ value WRITE setValue) public: double value() const { return m_value; } void setValue(double value) { m_value = value; } private: double m_value; }; class tst_Integer : public QDjangoModel { Q_OBJECT Q_PROPERTY(int value READ value WRITE setValue) public: int value() const { return m_value; } void setValue(int value) { m_value = value; } private: int m_value; }; class tst_LongLong : public QDjangoModel { Q_OBJECT Q_PROPERTY(qlonglong value READ value WRITE setValue) public: qlonglong value() const { return m_value; } void setValue(qlonglong value) { m_value = value; } private: qlonglong m_value; }; class tst_String : public QDjangoModel { Q_OBJECT Q_PROPERTY(QString value READ value WRITE setValue) Q_CLASSINFO("value", "max_length=255") public: QString value() const { return m_value; } void setValue(const QString &value) { m_value = value; } private: QString m_value; }; class tst_Time : public QDjangoModel { Q_OBJECT Q_PROPERTY(QTime value READ value WRITE setValue) public: QTime value() const { return m_value; } void setValue(const QTime &value) { m_value = value; } private: QTime m_value; }; class tst_Options : public QDjangoModel { Q_OBJECT Q_PROPERTY(int aField READ aField WRITE setAField) Q_PROPERTY(int bField READ bField WRITE setBField) Q_PROPERTY(int blankField READ blankField WRITE setBlankField) Q_PROPERTY(int ignoredField READ ignoredField WRITE setIgnoredField) Q_PROPERTY(int indexField READ indexField WRITE setIndexField) Q_PROPERTY(int nullField READ nullField WRITE setNullField) Q_PROPERTY(int uniqueField READ uniqueField WRITE setUniqueField) Q_CLASSINFO("__meta__", "db_table=some_table unique_together=aField,bField") Q_CLASSINFO("bField", "db_column=b_field") Q_CLASSINFO("blankField", "blank=true") Q_CLASSINFO("ignoredField", "ignore_field=true") Q_CLASSINFO("indexField", "db_index=true") Q_CLASSINFO("nullField", "null=true") Q_CLASSINFO("uniqueField", "unique=true") public: int aField() const { return m_aField; } void setAField(int value) { m_aField = value; } int bField() const { return m_bField; } void setBField(int value) { m_bField = value; } int blankField() const { return m_blankField; } void setBlankField(int value) { m_blankField = value; } int ignoredField() const { return m_ignoredField; } void setIgnoredField(int value) { m_ignoredField = value; } int indexField() const { return m_indexField; } void setIndexField(int value) { m_indexField = value; } int nullField() const { return m_nullField; } void setNullField(int value) { m_nullField = value; } int uniqueField() const { return m_uniqueField; } void setUniqueField(int value) { m_uniqueField = value; } private: int m_aField; int m_bField; int m_blankField; int m_ignoredField; int m_indexField; int m_nullField; int m_uniqueField; }; class tst_FkConstraint : public QDjangoModel { Q_OBJECT Q_PROPERTY(User *noConstraint READ noConstraint WRITE setNoConstraint) Q_PROPERTY(User *cascadeConstraint READ cascadeConstraint WRITE setCascadeConstraint) Q_PROPERTY(Group *nullConstraint READ nullConstraint WRITE setNullConstraint) Q_CLASSINFO("cascadeConstraint", "on_delete=cascade") Q_CLASSINFO("restrictConstraint", "on_delete=restrict") Q_CLASSINFO("nullConstraint", "null=true on_delete=set_null") public: tst_FkConstraint(QObject *parent = 0); User *noConstraint() const; void setNoConstraint(User *user); User *cascadeConstraint() const; void setCascadeConstraint(User *user); Group *nullConstraint() const; void setNullConstraint(Group *group); }; class tst_FkConstraintWithRestrict : public tst_FkConstraint { Q_OBJECT Q_PROPERTY(User *restrictConstraint READ restrictConstraint WRITE setRestrictConstraint) Q_CLASSINFO("__meta__", "db_table=tst_fkconstraint") Q_CLASSINFO("restrictConstraint", "on_delete=restrict") public: tst_FkConstraintWithRestrict(QObject *parent = 0); User *restrictConstraint() const; void setRestrictConstraint(User *user); }; qdjango-0.6.2/tests/db/qdjangomodel/000077500000000000000000000000001261212605400173345ustar00rootroot00000000000000qdjango-0.6.2/tests/db/qdjangomodel/qdjangomodel.pro000066400000000000000000000001161261212605400225200ustar00rootroot00000000000000include(../db.pri) TARGET = tst_qdjangomodel SOURCES += tst_qdjangomodel.cpp qdjango-0.6.2/tests/db/qdjangomodel/tst_qdjangomodel.cpp000066400000000000000000000211741261212605400234030ustar00rootroot00000000000000/* * Copyright (C) 2010-2015 Jeremy Lainé * Contact: https://github.com/jlaine/qdjango * * This file is part of the QDjango Library. * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * This library 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 * Lesser General Public License for more details. */ #include "QDjango.h" #include "QDjangoModel.h" #include "QDjangoQuerySet.h" #include "QDjangoWhere.h" #include "util.h" class TestModel : public QDjangoModel { public: TestModel(QObject *parent = 0) : QDjangoModel(parent) {} // expose foreign key methods so they can be tested QObject *foreignKey(const char *name) const { return QDjangoModel::foreignKey(name); } void setForeignKey(const char *name, QObject *value) { QDjangoModel::setForeignKey(name, value); } }; class Author : public TestModel { Q_OBJECT Q_PROPERTY(QString name READ name WRITE setName) public: Author(QObject *parent = 0) : TestModel(parent) {} QString name() const { return m_name; } void setName(const QString &name) { m_name = name; } private: QString m_name; }; class Book : public TestModel { Q_OBJECT Q_PROPERTY(Author* author READ author WRITE setAuthor) Q_PROPERTY(QString title READ title WRITE setTitle) Q_CLASSINFO("author", "on_delete=cascade") public: Book(QObject *parent = 0) : TestModel(parent) { setForeignKey("author", new Author(this)); } Author *author() const { return qobject_cast(foreignKey("author")); } void setAuthor(Author *author) { setForeignKey("author", author); } QString title() const { return m_title; } void setTitle(const QString &title) { m_title = title; } private: QString m_title; }; class BookWithNullAuthor : public TestModel { Q_OBJECT Q_PROPERTY(Author* author READ author WRITE setAuthor) Q_PROPERTY(QString title READ title WRITE setTitle) Q_CLASSINFO("author", "null=true on_delete=cascade") public: BookWithNullAuthor(QObject *parent = 0) : TestModel(parent) {} Author *author() const { return qobject_cast(foreignKey("author")); } void setAuthor(Author *author) { setForeignKey("author", author); } QString title() const { return m_title; } void setTitle(const QString &title) { m_title = title; } private: QString m_title; }; /** Test QDjangoModel class. */ class tst_QDjangoModel : public QObject { Q_OBJECT private slots: void initTestCase(); void init(); void deleteCascade(); void foreignKey(); void foreignKey_null(); void setForeignKey(); void filterRelated(); void filterRelatedReverse(); void filterRelatedReverse_null(); void primaryKey(); void selectRelated(); void selectRelated_null(); void toString(); void cleanup(); void cleanupTestCase(); }; /** Create database tables before running tests. */ void tst_QDjangoModel::initTestCase() { QVERIFY(initialiseDatabase()); QDjango::registerModel(); QDjango::registerModel(); QDjango::registerModel(); } /** Load fixtures. */ void tst_QDjangoModel::init() { QVERIFY(QDjango::createTables()); Author author1; author1.setName("First author"); QCOMPARE(author1.save(), true); Author author2; author2.setName("Second author"); QCOMPARE(author2.save(), true); Book book; book.setAuthor(&author1); book.setTitle("Some book"); QCOMPARE(book.save(), true); Book book2; book2.setAuthor(&author2); book2.setTitle("Other book"); QCOMPARE(book2.save(), true); BookWithNullAuthor book3; book3.setTitle("Book with null author"); QCOMPARE(book3.save(), true); BookWithNullAuthor book4; book4.setAuthor(&author1); book4.setTitle("Some book"); QCOMPARE(book4.save(), true); } void tst_QDjangoModel::deleteCascade() { const QDjangoQuerySet authors; const QDjangoQuerySet books; QCOMPARE(authors.count(), 2); QCOMPARE(books.count(), 2); QVERIFY(authors.filter(QDjangoWhere("name", QDjangoWhere::Equals, "First author")).remove()); QCOMPARE(authors.count(), 1); QCOMPARE(books.count(), 1); } void tst_QDjangoModel::foreignKey() { QTest::ignoreMessage(QtWarningMsg, "QDjangoMetaModel cannot get foreign model for invalid key 'bad'"); Book book; QVERIFY(!book.foreignKey("bad")); QVERIFY(book.foreignKey("author")); } void tst_QDjangoModel::foreignKey_null() { QTest::ignoreMessage(QtWarningMsg, "QDjangoMetaModel cannot get foreign model for invalid key 'bad'"); BookWithNullAuthor book; QVERIFY(!book.foreignKey("bad")); QVERIFY(!book.foreignKey("author")); } void tst_QDjangoModel::setForeignKey() { QTest::ignoreMessage(QtWarningMsg, "QDjangoMetaModel cannot set foreign model for invalid key 'bad'"); Book book; book.setForeignKey("bad", 0); book.setForeignKey("author", 0); } /** Perform filtering on foreign keys. */ void tst_QDjangoModel::filterRelated() { QDjangoQuerySet books; QDjangoQuerySet qs = books.filter( QDjangoWhere("author__name", QDjangoWhere::Equals, "First author")); CHECKWHERE(qs.where(), QLatin1String("T0.\"name\" = ?"), QVariantList() << "First author"); QCOMPARE(qs.count(), 1); QCOMPARE(qs.size(), 1); Book *book = qs.at(0); QVERIFY(book != 0); QCOMPARE(book->title(), QLatin1String("Some book")); delete book; } void tst_QDjangoModel::filterRelatedReverse() { QDjangoQuerySet authors; QDjangoQuerySet qs = authors.filter( QDjangoWhere("book__title", QDjangoWhere::Equals, "Some book")); QVERIFY(!qs.values().isEmpty()); QCOMPARE(qs.count(), 1); QCOMPARE(qs.size(), 1); Author *author = qs.at(0); QVERIFY(author != 0); QCOMPARE(author->name(), QLatin1String("First author")); delete author; } void tst_QDjangoModel::filterRelatedReverse_null() { QDjangoQuerySet authors; QDjangoQuerySet qs = authors.filter( QDjangoWhere("bookwithnullauthor__title", QDjangoWhere::Equals, "Some book")); QVERIFY(!qs.values().isEmpty()); QCOMPARE(qs.count(), 1); QCOMPARE(qs.size(), 1); Author *author = qs.at(0); QVERIFY(author != 0); QCOMPARE(author->name(), QLatin1String("First author")); delete author; } void tst_QDjangoModel::primaryKey() { Author author; QCOMPARE(author.pk(), QVariant()); author.setPk(1); QCOMPARE(author.pk(), QVariant(1)); } /** Test eager loading of foreign keys. */ void tst_QDjangoModel::selectRelated() { // without eager loading QDjangoQuerySet qs; Book *book = qs.get(QDjangoWhere("title", QDjangoWhere::Equals, "Some book")); QVERIFY(book != 0); QCOMPARE(book->title(), QLatin1String("Some book")); QVERIFY(book->author() != 0); QCOMPARE(book->author()->name(), QLatin1String("First author")); delete book; // with eager loading book = qs.selectRelated().get(QDjangoWhere("title", QDjangoWhere::Equals, "Some book")); QVERIFY(book != 0); QCOMPARE(book->title(), QLatin1String("Some book")); QVERIFY(book->author() != 0); QCOMPARE(book->author()->name(), QLatin1String("First author")); delete book; } void tst_QDjangoModel::selectRelated_null() { // without eager loading QDjangoQuerySet qs; BookWithNullAuthor *book = qs.get(QDjangoWhere("title", QDjangoWhere::Equals, "Book with null author")); QVERIFY(book != 0); QCOMPARE(book->title(), QLatin1String("Book with null author")); QVERIFY(!book->author()); delete book; // with eager loading book = qs.selectRelated().get(QDjangoWhere("title", QDjangoWhere::Equals, "Book with null author")); QVERIFY(book != 0); QCOMPARE(book->title(), QLatin1String("Book with null author")); QVERIFY(!book->author()); delete book; } void tst_QDjangoModel::toString() { QDjangoQuerySet qs; Book *book = qs.get(QDjangoWhere("title", QDjangoWhere::Equals, "Some book")); QVERIFY(book != 0); QCOMPARE(book->toString(), QLatin1String("Book(id=1)")); delete book; } /** Clear database tables after each test. */ void tst_QDjangoModel::cleanup() { QVERIFY(QDjango::dropTables()); } /** Drop database tables after running tests. */ void tst_QDjangoModel::cleanupTestCase() { } QTEST_MAIN(tst_QDjangoModel) #include "tst_qdjangomodel.moc" qdjango-0.6.2/tests/db/qdjangoqueryset/000077500000000000000000000000001261212605400201155ustar00rootroot00000000000000qdjango-0.6.2/tests/db/qdjangoqueryset/qdjangoqueryset.pro000066400000000000000000000001241261212605400240610ustar00rootroot00000000000000include(../db.pri) TARGET = tst_qdjangoqueryset SOURCES += tst_qdjangoqueryset.cpp qdjango-0.6.2/tests/db/qdjangoqueryset/tst_qdjangoqueryset.cpp000066400000000000000000000125611261212605400247450ustar00rootroot00000000000000/* * Copyright (C) 2010-2015 Jeremy Lainé * Contact: https://github.com/jlaine/qdjango * * This file is part of the QDjango Library. * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * This library 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 * Lesser General Public License for more details. */ #include "QDjango.h" #include "QDjangoQuerySet.h" #include "QDjangoWhere.h" #include "auth-models.h" #include "util.h" class Object : public QObject { Q_OBJECT Q_PROPERTY(QString foo READ foo WRITE setFoo) Q_PROPERTY(int bar READ bar WRITE setBar) Q_CLASSINFO("__meta__", "db_table=foo_table") Q_CLASSINFO("foo", "max_length=255") Q_CLASSINFO("bar", "db_column=bar_column") public: QString foo() const { return m_foo; }; void setFoo(const QString &foo) { m_foo = foo; }; int bar() const { return m_bar; }; void setBar(int bar) { m_bar = bar; }; private: QString m_foo; int m_bar; }; /** Test QDjangoQuerySetPrivate class. */ class tst_QDjangoQuerySetPrivate : public QObject { Q_OBJECT private slots: void initTestCase(); void countQuery(); void deleteQuery(); void insertQuery(); void selectQuery(); void updateQuery(); void cleanupTestCase(); private: QDjangoMetaModel metaModel; }; void tst_QDjangoQuerySetPrivate::initTestCase() { QVERIFY(initialiseDatabase()); metaModel = QDjango::registerModel(); QCOMPARE(metaModel.createTable(), true); } void tst_QDjangoQuerySetPrivate::countQuery() { QDjangoQuerySetPrivate qs("Object"); qs.addFilter(QDjangoWhere("pk", QDjangoWhere::Equals, 1)); QDjangoQuery query = qs.countQuery(); QCOMPARE(normalizeSql(QDjango::database(), query.lastQuery()), QLatin1String("SELECT COUNT(*) FROM \"foo_table\" WHERE \"foo_table\".\"id\" = ?")); QCOMPARE(query.boundValues().size(), 1); QCOMPARE(query.boundValue(0), QVariant(1)); } void tst_QDjangoQuerySetPrivate::deleteQuery() { QDjangoQuerySetPrivate qs("Object"); qs.addFilter(QDjangoWhere("pk", QDjangoWhere::Equals, 1)); QDjangoQuery query = qs.deleteQuery(); QCOMPARE(normalizeSql(QDjango::database(), query.lastQuery()), QLatin1String("DELETE FROM \"foo_table\" WHERE \"foo_table\".\"id\" = ?")); QCOMPARE(query.boundValues().size(), 1); QCOMPARE(query.boundValue(0), QVariant(1)); } void tst_QDjangoQuerySetPrivate::insertQuery() { QVariantMap data; data.insert("foo", "abc"); QDjangoQuerySetPrivate qs("Object"); QDjangoQuery query = qs.insertQuery(data); QCOMPARE(normalizeSql(QDjango::database(), query.lastQuery()), QLatin1String("INSERT INTO \"foo_table\" (\"foo\") VALUES(?)")); QCOMPARE(query.boundValues().size(), 1); QCOMPARE(query.boundValue(0), QVariant("abc")); } void tst_QDjangoQuerySetPrivate::selectQuery() { QVariantMap data; data.insert("foo", "abc"); { QDjangoQuerySetPrivate qs("Object"); qs.addFilter(QDjangoWhere("pk", QDjangoWhere::Equals, 1)); QDjangoQuery query = qs.selectQuery(); QCOMPARE(normalizeSql(QDjango::database(), query.lastQuery()), QLatin1String("SELECT \"foo_table\".\"id\", \"foo_table\".\"foo\", \"foo_table\".\"bar_column\" FROM \"foo_table\" WHERE \"foo_table\".\"id\" = ?")); QCOMPARE(query.boundValues().size(), 1); QCOMPARE(query.boundValue(0), QVariant(1)); } { QDjangoQuerySetPrivate qs("Object"); qs.addFilter(QDjangoWhere("bar", QDjangoWhere::Equals, 3)); QDjangoQuery query = qs.selectQuery(); QCOMPARE(normalizeSql(QDjango::database(), query.lastQuery()), QLatin1String("SELECT \"foo_table\".\"id\", \"foo_table\".\"foo\", \"foo_table\".\"bar_column\" FROM \"foo_table\" WHERE \"foo_table\".\"bar_column\" = ?")); QCOMPARE(query.boundValues().size(), 1); QCOMPARE(query.boundValue(0), QVariant(3)); } } void tst_QDjangoQuerySetPrivate::updateQuery() { QVariantMap data; data.insert("foo", "abc"); { QDjangoQuerySetPrivate qs("Object"); qs.addFilter(QDjangoWhere("pk", QDjangoWhere::Equals, 1)); QDjangoQuery query = qs.updateQuery(data); QCOMPARE(normalizeSql(QDjango::database(), query.lastQuery()), QLatin1String("UPDATE \"foo_table\" SET \"foo\" = ? WHERE \"foo_table\".\"id\" = ?")); QCOMPARE(query.boundValues().size(), 2); QCOMPARE(query.boundValue(0), QVariant("abc")); QCOMPARE(query.boundValue(1), QVariant(1)); } { QDjangoQuerySetPrivate qs("Object"); qs.addFilter(QDjangoWhere("bar", QDjangoWhere::Equals, 3)); QDjangoQuery query = qs.updateQuery(data); QCOMPARE(normalizeSql(QDjango::database(), query.lastQuery()), QLatin1String("UPDATE \"foo_table\" SET \"foo\" = ? WHERE \"foo_table\".\"bar_column\" = ?")); QCOMPARE(query.boundValues().size(), 2); QCOMPARE(query.boundValue(0), QVariant("abc")); QCOMPARE(query.boundValue(1), QVariant(3)); } } void tst_QDjangoQuerySetPrivate::cleanupTestCase() { metaModel.dropTable(); } QTEST_MAIN(tst_QDjangoQuerySetPrivate) #include "tst_qdjangoqueryset.moc" qdjango-0.6.2/tests/db/qdjangowhere/000077500000000000000000000000001261212605400173465ustar00rootroot00000000000000qdjango-0.6.2/tests/db/qdjangowhere/qdjangowhere.pro000066400000000000000000000001161261212605400225440ustar00rootroot00000000000000include(../db.pri) TARGET = tst_qdjangowhere SOURCES += tst_qdjangowhere.cpp qdjango-0.6.2/tests/db/qdjangowhere/tst_qdjangowhere.cpp000066400000000000000000000420171261212605400234260ustar00rootroot00000000000000/* * Copyright (C) 2010-2015 Jeremy Lainé * Contact: https://github.com/jlaine/qdjango * * This file is part of the QDjango Library. * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * This library 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 * Lesser General Public License for more details. */ #include "QDjangoWhere.h" #include "util.h" /** Test QDjangoWhere class. */ class tst_QDjangoWhere : public QObject { Q_OBJECT private slots: void initTestCase(); void emptyWhere(); void equalsWhere(); void iEqualsWhere(); void notEqualsWhere(); void iNotEqualsWhere(); void greaterThan(); void greaterOrEquals(); void lessThan(); void lessOrEquals(); void isIn(); void isNull(); void startsWith(); void iStartsWith(); void endsWith(); void iEndsWith(); void contains(); void iContains(); void andWhere(); void orWhere(); void complexWhere(); void toString(); }; void tst_QDjangoWhere::initTestCase() { QVERIFY(initialiseDatabase()); } /** Test empty where clause. */ void tst_QDjangoWhere::emptyWhere() { // construct empty where clause QDjangoWhere testQuery; QCOMPARE(testQuery.isAll(), true); QCOMPARE(testQuery.isNone(), false); CHECKWHERE(testQuery, QString(), QVariantList()); // negate the where clause testQuery = !QDjangoWhere(); QCOMPARE(testQuery.isAll(), false); QCOMPARE(testQuery.isNone(), true); CHECKWHERE(testQuery, QLatin1String("1 != 0"), QVariantList()); } /** Test "=" comparison. */ void tst_QDjangoWhere::equalsWhere() { QDjangoWhere testQuery; // construct an "equals" where clause testQuery = QDjangoWhere("id", QDjangoWhere::Equals, 1); CHECKWHERE(testQuery, QLatin1String("id = ?"), QVariantList() << 1); // negate the where clause testQuery = !QDjangoWhere("id", QDjangoWhere::Equals, 1); CHECKWHERE(testQuery, QLatin1String("id != ?"), QVariantList() << 1); } /** Test case-insensitive "=" comparison. */ void tst_QDjangoWhere::iEqualsWhere() { QDjangoDatabase::DatabaseType databaseType = QDjangoDatabase::databaseType(QDjango::database()); if (databaseType == QDjangoDatabase::PostgreSQL) { QDjangoWhere testQuery = QDjangoWhere("name", QDjangoWhere::IEquals, "abc"); CHECKWHERE(testQuery, QLatin1String("UPPER(name::text) LIKE UPPER(?)"), QVariantList() << "abc"); testQuery = !QDjangoWhere("name", QDjangoWhere::IEquals, "abc"); CHECKWHERE(testQuery, QLatin1String("UPPER(name::text) NOT LIKE UPPER(?)"), QVariantList() << "abc"); } else { QDjangoWhere testQuery = QDjangoWhere("name", QDjangoWhere::IEquals, "abc"); CHECKWHERE(testQuery, QLatin1String("name LIKE ?"), QVariantList() << "abc"); testQuery = !QDjangoWhere("name", QDjangoWhere::IEquals, "abc"); CHECKWHERE(testQuery, QLatin1String("name NOT LIKE ?"), QVariantList() << "abc"); } } /** Test "!=" comparison. */ void tst_QDjangoWhere::notEqualsWhere() { QDjangoWhere testQuery; // construct a "not equals" where clause testQuery = QDjangoWhere("id", QDjangoWhere::NotEquals, 1); CHECKWHERE(testQuery, QLatin1String("id != ?"), QVariantList() << 1); // negate the where clause testQuery = !QDjangoWhere("id", QDjangoWhere::NotEquals, 1); CHECKWHERE(testQuery, QLatin1String("id = ?"), QVariantList() << 1); } /** Test case-insensitive "!=" comparison. */ void tst_QDjangoWhere::iNotEqualsWhere() { QDjangoDatabase::DatabaseType databaseType = QDjangoDatabase::databaseType(QDjango::database()); if (databaseType == QDjangoDatabase::PostgreSQL) { QDjangoWhere testQuery = QDjangoWhere("name", QDjangoWhere::INotEquals, "abc"); CHECKWHERE(testQuery, QLatin1String("UPPER(name::text) NOT LIKE UPPER(?)"), QVariantList() << "abc"); testQuery = !QDjangoWhere("name", QDjangoWhere::INotEquals, "abc"); CHECKWHERE(testQuery, QLatin1String("UPPER(name::text) LIKE UPPER(?)"), QVariantList() << "abc"); } else { QDjangoWhere testQuery = QDjangoWhere("name", QDjangoWhere::INotEquals, "abc"); CHECKWHERE(testQuery, QLatin1String("name NOT LIKE ?"), QVariantList() << "abc"); testQuery = !QDjangoWhere("name", QDjangoWhere::INotEquals, "abc"); CHECKWHERE(testQuery, QLatin1String("name LIKE ?"), QVariantList() << "abc"); } } /** Test ">" comparison. */ void tst_QDjangoWhere::greaterThan() { QDjangoWhere testQuery; testQuery = QDjangoWhere("id", QDjangoWhere::GreaterThan, 1); CHECKWHERE(testQuery, QLatin1String("id > ?"), QVariantList() << 1); testQuery = !QDjangoWhere("id", QDjangoWhere::GreaterThan, 1); CHECKWHERE(testQuery, QLatin1String("id <= ?"), QVariantList() << 1); } /** Test ">=" comparison. */ void tst_QDjangoWhere::greaterOrEquals() { QDjangoWhere testQuery; testQuery = QDjangoWhere("id", QDjangoWhere::GreaterOrEquals, 1); CHECKWHERE(testQuery, QLatin1String("id >= ?"), QVariantList() << 1); testQuery = !QDjangoWhere("id", QDjangoWhere::GreaterOrEquals, 1); CHECKWHERE(testQuery, QLatin1String("id < ?"), QVariantList() << 1); } /** Test "<" comparison. */ void tst_QDjangoWhere::lessThan() { QDjangoWhere testQuery; testQuery = QDjangoWhere("id", QDjangoWhere::LessThan, 1); CHECKWHERE(testQuery, QLatin1String("id < ?"), QVariantList() << 1); testQuery = !QDjangoWhere("id", QDjangoWhere::LessThan, 1); CHECKWHERE(testQuery, QLatin1String("id >= ?"), QVariantList() << 1); } /** Test "<=" comparison. */ void tst_QDjangoWhere::lessOrEquals() { QDjangoWhere testQuery; testQuery = QDjangoWhere("id", QDjangoWhere::LessOrEquals, 1); CHECKWHERE(testQuery, QLatin1String("id <= ?"), QVariantList() << 1); testQuery = !QDjangoWhere("id", QDjangoWhere::LessOrEquals, 1); CHECKWHERE(testQuery, QLatin1String("id > ?"), QVariantList() << 1); } /** Test "in" comparison. */ void tst_QDjangoWhere::isIn() { QDjangoWhere testQuery = QDjangoWhere("id", QDjangoWhere::IsIn, QVariantList() << 1 << 2); CHECKWHERE(testQuery, QLatin1String("id IN (?, ?)"), QVariantList() << 1 << 2); testQuery = !QDjangoWhere("id", QDjangoWhere::IsIn, QVariantList() << 1 << 2); CHECKWHERE(testQuery, QLatin1String("id NOT IN (?, ?)"), QVariantList() << 1 << 2); } /** Test "isnull" comparison. */ void tst_QDjangoWhere::isNull() { QDjangoWhere testQuery = QDjangoWhere("id", QDjangoWhere::IsNull, true); CHECKWHERE(testQuery, QLatin1String("id IS NULL"), QVariantList()); testQuery = QDjangoWhere("id", QDjangoWhere::IsNull, false); CHECKWHERE(testQuery, QLatin1String("id IS NOT NULL"), QVariantList()); testQuery = !QDjangoWhere("id", QDjangoWhere::IsNull, true); CHECKWHERE(testQuery, QLatin1String("id IS NOT NULL"), QVariantList()); } /** Test "startswith" comparison. */ void tst_QDjangoWhere::startsWith() { QDjangoDatabase::DatabaseType databaseType = QDjangoDatabase::databaseType(QDjango::database()); if (databaseType == QDjangoDatabase::MySqlServer) { QDjangoWhere testQuery = QDjangoWhere("name", QDjangoWhere::StartsWith, "abc"); CHECKWHERE(testQuery, QLatin1String("name LIKE BINARY ?"), QVariantList() << "abc%"); testQuery = !QDjangoWhere("name", QDjangoWhere::StartsWith, "abc"); CHECKWHERE(testQuery, QLatin1String("name NOT LIKE BINARY ?"), QVariantList() << "abc%"); } else { QDjangoWhere testQuery = QDjangoWhere("name", QDjangoWhere::StartsWith, "abc"); CHECKWHERE(testQuery, QLatin1String("name LIKE ?"), QVariantList() << "abc%"); testQuery = !QDjangoWhere("name", QDjangoWhere::StartsWith, "abc"); CHECKWHERE(testQuery, QLatin1String("name NOT LIKE ?"), QVariantList() << "abc%"); } } /** Test "istartswith" comparison. */ void tst_QDjangoWhere::iStartsWith() { QDjangoDatabase::DatabaseType databaseType = QDjangoDatabase::databaseType(QDjango::database()); if (databaseType == QDjangoDatabase::PostgreSQL) { QDjangoWhere testQuery = QDjangoWhere("name", QDjangoWhere::IStartsWith, "abc"); CHECKWHERE(testQuery, QLatin1String("UPPER(name::text) LIKE UPPER(?)"), QVariantList() << "abc%"); testQuery = !QDjangoWhere("name", QDjangoWhere::IStartsWith, "abc"); CHECKWHERE(testQuery, QLatin1String("UPPER(name::text) NOT LIKE UPPER(?)"), QVariantList() << "abc%"); } else { QDjangoWhere testQuery = QDjangoWhere("name", QDjangoWhere::IStartsWith, "abc"); CHECKWHERE(testQuery, QLatin1String("name LIKE ?"), QVariantList() << "abc%"); testQuery = !QDjangoWhere("name", QDjangoWhere::IStartsWith, "abc"); CHECKWHERE(testQuery, QLatin1String("name NOT LIKE ?"), QVariantList() << "abc%"); } } /** Test "endswith" comparison. */ void tst_QDjangoWhere::endsWith() { QDjangoDatabase::DatabaseType databaseType = QDjangoDatabase::databaseType(QDjango::database()); if (databaseType == QDjangoDatabase::MySqlServer) { QDjangoWhere testQuery = QDjangoWhere("name", QDjangoWhere::EndsWith, "abc"); CHECKWHERE(testQuery, QLatin1String("name LIKE BINARY ?"), QVariantList() << "%abc"); testQuery = !QDjangoWhere("name", QDjangoWhere::EndsWith, "abc"); CHECKWHERE(testQuery, QLatin1String("name NOT LIKE BINARY ?"), QVariantList() << "%abc"); } else { QDjangoWhere testQuery = QDjangoWhere("name", QDjangoWhere::EndsWith, "abc"); CHECKWHERE(testQuery, QLatin1String("name LIKE ?"), QVariantList() << "%abc"); testQuery = !QDjangoWhere("name", QDjangoWhere::EndsWith, "abc"); CHECKWHERE(testQuery, QLatin1String("name NOT LIKE ?"), QVariantList() << "%abc"); } } /** Test "iendswith" comparison. */ void tst_QDjangoWhere::iEndsWith() { QDjangoDatabase::DatabaseType databaseType = QDjangoDatabase::databaseType(QDjango::database()); if (databaseType == QDjangoDatabase::PostgreSQL) { QDjangoWhere testQuery = QDjangoWhere("name", QDjangoWhere::IEndsWith, "abc"); CHECKWHERE(testQuery, QLatin1String("UPPER(name::text) LIKE UPPER(?)"), QVariantList() << "%abc"); testQuery = !QDjangoWhere("name", QDjangoWhere::IEndsWith, "abc"); CHECKWHERE(testQuery, QLatin1String("UPPER(name::text) NOT LIKE UPPER(?)"), QVariantList() << "%abc"); } else { QDjangoWhere testQuery = QDjangoWhere("name", QDjangoWhere::IEndsWith, "abc"); CHECKWHERE(testQuery, QLatin1String("name LIKE ?"), QVariantList() << "%abc"); testQuery = !QDjangoWhere("name", QDjangoWhere::IEndsWith, "abc"); CHECKWHERE(testQuery, QLatin1String("name NOT LIKE ?"), QVariantList() << "%abc"); } } /** Test "contains" comparison. */ void tst_QDjangoWhere::contains() { QDjangoDatabase::DatabaseType databaseType = QDjangoDatabase::databaseType(QDjango::database()); if (databaseType == QDjangoDatabase::MySqlServer) { QDjangoWhere testQuery = QDjangoWhere("name", QDjangoWhere::Contains, "abc"); CHECKWHERE(testQuery, QLatin1String("name LIKE BINARY ?"), QVariantList() << "%abc%"); testQuery = !QDjangoWhere("name", QDjangoWhere::Contains, "abc"); CHECKWHERE(testQuery, QLatin1String("name NOT LIKE BINARY ?"), QVariantList() << "%abc%"); } else { QDjangoWhere testQuery = QDjangoWhere("name", QDjangoWhere::Contains, "abc"); CHECKWHERE(testQuery, QLatin1String("name LIKE ?"), QVariantList() << "%abc%"); testQuery = !QDjangoWhere("name", QDjangoWhere::Contains, "abc"); CHECKWHERE(testQuery, QLatin1String("name NOT LIKE ?"), QVariantList() << "%abc%"); } } /** Test "icontains" comparison" */ void tst_QDjangoWhere::iContains() { QDjangoDatabase::DatabaseType databaseType = QDjangoDatabase::databaseType(QDjango::database()); if (databaseType == QDjangoDatabase::PostgreSQL) { QDjangoWhere testQuery = QDjangoWhere("name", QDjangoWhere::IContains, "abc"); CHECKWHERE(testQuery, QLatin1String("UPPER(name::text) LIKE UPPER(?)"), QVariantList() << "%abc%"); testQuery = !QDjangoWhere("name", QDjangoWhere::IContains, "abc"); CHECKWHERE(testQuery, QLatin1String("UPPER(name::text) NOT LIKE UPPER(?)"), QVariantList() << "%abc%"); } else { QDjangoWhere testQuery = QDjangoWhere("name", QDjangoWhere::IContains, "abc"); CHECKWHERE(testQuery, QLatin1String("name LIKE ?"), QVariantList() << "%abc%"); testQuery = !QDjangoWhere("name", QDjangoWhere::IContains, "abc"); CHECKWHERE(testQuery, QLatin1String("name NOT LIKE ?"), QVariantList() << "%abc%"); } } /** Test compound where clause, using the AND operator. */ void tst_QDjangoWhere::andWhere() { QDjangoWhere testQuery; const QDjangoWhere queryId("id", QDjangoWhere::Equals, 1); const QDjangoWhere queryUsername("username", QDjangoWhere::Equals, "foo"); testQuery = queryId && queryUsername; CHECKWHERE(testQuery, QLatin1String("id = ? AND username = ?"), QVariantList() << 1 << "foo"); // and with "all" queryset testQuery = QDjangoWhere() && queryId; CHECKWHERE(testQuery, QLatin1String("id = ?"), QVariantList() << 1); testQuery = queryId && QDjangoWhere(); CHECKWHERE(testQuery, QLatin1String("id = ?"), QVariantList() << 1); // and with "none" queryset testQuery = !QDjangoWhere() && queryId; QCOMPARE(testQuery.isNone(), true); CHECKWHERE(testQuery, QLatin1String("1 != 0"), QVariantList()); testQuery = queryId && !QDjangoWhere(); QCOMPARE(testQuery.isNone(), true); CHECKWHERE(testQuery, QLatin1String("1 != 0"), QVariantList()); // negation testQuery = !(queryId && queryUsername); CHECKWHERE(testQuery, QLatin1String("NOT (id = ? AND username = ?)"), QVariantList() << 1 << "foo"); } /** Test compound where clause, using the OR operator. */ void tst_QDjangoWhere::orWhere() { QDjangoWhere testQuery; const QDjangoWhere queryId("id", QDjangoWhere::Equals, 1); const QDjangoWhere queryUsername("username", QDjangoWhere::Equals, "foo"); testQuery = queryId || queryUsername; CHECKWHERE(testQuery, QLatin1String("id = ? OR username = ?"), QVariantList() << 1 << "foo"); // or with "all" queryset testQuery = QDjangoWhere() || queryId; QCOMPARE(testQuery.isAll(), true); CHECKWHERE(testQuery, QString(), QVariantList()); testQuery = queryId || QDjangoWhere(); QCOMPARE(testQuery.isAll(), true); CHECKWHERE(testQuery, QString(), QVariantList()); // or with "none" queryset testQuery = !QDjangoWhere() || queryId; CHECKWHERE(testQuery, QLatin1String("id = ?"), QVariantList() << 1); testQuery = queryId || !QDjangoWhere(); CHECKWHERE(testQuery, QLatin1String("id = ?"), QVariantList() << 1); // negation testQuery = !(queryId || queryUsername); CHECKWHERE(testQuery, QLatin1String("NOT (id = ? OR username = ?)"), QVariantList() << 1 << "foo"); } /** Test compound where clause, using both the AND and the OR operators. */ void tst_QDjangoWhere::complexWhere() { QDjangoWhere testQuery; const QDjangoWhere queryId("id", QDjangoWhere::Equals, 1); const QDjangoWhere queryUsername("username", QDjangoWhere::Equals, "foouser"); const QDjangoWhere queryPassword("password", QDjangoWhere::Equals, "foopass"); testQuery = (queryId || queryUsername) && queryPassword; CHECKWHERE(testQuery, QLatin1String("(id = ? OR username = ?) AND password = ?"), QVariantList() << 1 << "foouser" << "foopass"); testQuery = queryId || (queryUsername && queryPassword); CHECKWHERE(testQuery, QLatin1String("id = ? OR (username = ? AND password = ?)"), QVariantList() << 1 << "foouser" << "foopass"); testQuery = queryId && queryUsername && queryPassword; CHECKWHERE(testQuery, QLatin1String("id = ? AND username = ? AND password = ?"), QVariantList() << 1 << "foouser" << "foopass"); testQuery = queryId || queryUsername || queryPassword; CHECKWHERE(testQuery, QLatin1String("id = ? OR username = ? OR password = ?"), QVariantList() << 1 << "foouser" << "foopass"); } void tst_QDjangoWhere::toString() { QDjangoWhere testQuery; const QDjangoWhere queryId("id", QDjangoWhere::Equals, 1); const QDjangoWhere queryUsername("username", QDjangoWhere::Equals, "foo"); testQuery = queryId; QCOMPARE(testQuery.toString(), QLatin1String("QDjangoWhere(key=\"id\", operation=\"Equals\", value=\"1\", negate=false)")); testQuery = queryId || queryUsername; QCOMPARE(testQuery.toString(), QLatin1String("QDjangoWhere(key=\"id\", operation=\"Equals\", value=\"1\", negate=false) || QDjangoWhere(key=\"username\", operation=\"Equals\", value=\"foo\", negate=false)")); testQuery = queryId && queryUsername; QCOMPARE(testQuery.toString(), QLatin1String("QDjangoWhere(key=\"id\", operation=\"Equals\", value=\"1\", negate=false) && QDjangoWhere(key=\"username\", operation=\"Equals\", value=\"foo\", negate=false)")); } QTEST_MAIN(tst_QDjangoWhere) #include "tst_qdjangowhere.moc" qdjango-0.6.2/tests/db/shares/000077500000000000000000000000001261212605400161555ustar00rootroot00000000000000qdjango-0.6.2/tests/db/shares/shares.pro000066400000000000000000000001021261212605400201550ustar00rootroot00000000000000include(../db.pri) TARGET = tst_shares SOURCES += tst_shares.cpp qdjango-0.6.2/tests/db/shares/tst_shares.cpp000066400000000000000000000065751261212605400210550ustar00rootroot00000000000000/* * Copyright (C) 2010-2015 Jeremy Lainé * Contact: https://github.com/jlaine/qdjango * * This file is part of the QDjango Library. * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * This library 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 * Lesser General Public License for more details. */ #include "QDjangoQuerySet.h" #include "util.h" /** Tests for the File class. */ class tst_Shares : public QObject { Q_OBJECT private slots: void initTestCase(); void testFile(); void cleanup(); void cleanupTestCase(); }; class File : public QDjangoModel { Q_OBJECT Q_PROPERTY(QDateTime date READ date WRITE setDate) Q_PROPERTY(QByteArray hash READ hash WRITE setHash) Q_PROPERTY(QString path READ path WRITE setPath) Q_PROPERTY(qint64 size READ size WRITE setSize) Q_CLASSINFO("path", "max_length=255 primary_key=true") Q_CLASSINFO("hash", "max_length=32") public: File(QObject *parent = 0); QDateTime date() const; void setDate(const QDateTime &date); QByteArray hash() const; void setHash(const QByteArray &hash); QString path() const; void setPath(const QString &path); qint64 size() const; void setSize(qint64 size); private: QDateTime m_date; QByteArray m_hash; QString m_path; qint64 m_size; }; File::File(QObject *parent) : QDjangoModel(parent), m_size(0) { } QDateTime File::date() const { return m_date; } void File::setDate(const QDateTime &date) { m_date = date; } QByteArray File::hash() const { return m_hash; } void File::setHash(const QByteArray &hash) { m_hash = hash; } QString File::path() const { return m_path; } void File::setPath(const QString &path) { m_path = path; } qint64 File::size() const { return m_size; } void File::setSize(qint64 size) { m_size = size; } /** Create database table before running tests. */ void tst_Shares::initTestCase() { QVERIFY(initialiseDatabase()); QDjango::registerModel(); QVERIFY(QDjango::createTables()); } void tst_Shares::testFile() { // create a file File file; file.setDate(QDateTime(QDate(2010, 6, 1), QTime(10, 5, 14))); file.setHash(QByteArray("\0\1\2\3\4", 5)); file.setPath("foo/bar.txt"); file.setSize(1234); QCOMPARE(file.save(), true); File *other = QDjangoQuerySet().get(QDjangoWhere("path", QDjangoWhere::Equals, "foo/bar.txt")); QVERIFY(other != 0); QCOMPARE(other->date(), QDateTime(QDate(2010, 6, 1), QTime(10, 5, 14))); QCOMPARE(other->hash(), QByteArray("\0\1\2\3\4", 5)); QCOMPARE(other->path(), QLatin1String("foo/bar.txt")); QCOMPARE(other->size(), qint64(1234)); delete other; // update the file file.setSize(5678); QCOMPARE(file.save(), true); } /** Clear database table after each test. */ void tst_Shares::cleanup() { QCOMPARE(QDjangoQuerySet().remove(), true); } /** Drop database table after running tests. */ void tst_Shares::cleanupTestCase() { QVERIFY(QDjango::dropTables()); } QTEST_MAIN(tst_Shares) #include "tst_shares.moc" qdjango-0.6.2/tests/db/util.cpp000066400000000000000000000040611261212605400163520ustar00rootroot00000000000000/* * Copyright (C) 2010-2015 Jeremy Lainé * Contact: https://github.com/jlaine/qdjango * * This file is part of the QDjango Library. * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * This library 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 * Lesser General Public License for more details. */ #include #include "QDjango.h" #include "util.h" bool initialiseDatabase() { char *p; // enable SQL debugging if ((p = getenv("QDJANGO_DB_DEBUG")) != 0) QDjango::setDebugEnabled(true); // open database QString databaseDriver = "QSQLITE"; if ((p = getenv("QDJANGO_DB_DRIVER")) != 0) databaseDriver = QString::fromLocal8Bit(p); QSqlDatabase db = QSqlDatabase::addDatabase(databaseDriver); if ((p = getenv("QDJANGO_DB_NAME")) != 0) db.setDatabaseName(QString::fromLocal8Bit(p)); else if (databaseDriver == "QSQLITE") db.setDatabaseName(":memory:"); if ((p = getenv("QDJANGO_DB_USER")) != 0) db.setUserName(QString::fromLocal8Bit(p)); if ((p = getenv("QDJANGO_DB_PASSWORD")) != 0) db.setPassword(QString::fromLocal8Bit(p)); if ((p = getenv("QDJANGO_DB_HOST")) != 0) db.setHostName(QString::fromLocal8Bit(p)); if (db.open()) { QDjango::setDatabase(db); return true; } else { return false; } } QString normalizeSql(const QSqlDatabase &db, const QString &sql) { QDjangoDatabase::DatabaseType databaseType = QDjangoDatabase::databaseType(db); QString modSql(sql); if (databaseType == QDjangoDatabase::MySqlServer) modSql.replace("`", "\""); else if (databaseType == QDjangoDatabase::SQLite) modSql.replace("? ESCAPE '\\'", "?"); return modSql; } qdjango-0.6.2/tests/db/util.h000066400000000000000000000025541261212605400160240ustar00rootroot00000000000000/* * Copyright (C) 2010-2015 Jeremy Lainé * Contact: https://github.com/jlaine/qdjango * * This file is part of the QDjango Library. * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * This library 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 * Lesser General Public License for more details. */ #include #include "QDjango.h" #include "QDjangoModel.h" bool initialiseDatabase(); QString normalizeSql(const QSqlDatabase &db, const QString &sql); #define CHECKWHERE(_where, s, v) { \ QSqlDatabase _sql_db(QDjango::database()); \ QDjangoQuery _sql_query(_sql_db); \ QString _sql_stmt = _where.sql(_sql_db); \ if (!_sql_stmt.isEmpty()) _sql_query.prepare(_sql_stmt); \ _where.bindValues(_sql_query); \ const QVariantList _sql_values = v; \ QCOMPARE(normalizeSql(_sql_db, _sql_query.lastQuery()), s); \ QCOMPARE(_sql_query.boundValues().size(), _sql_values.size()); \ for(int _i = 0; _i < _sql_values.size(); ++_i) QCOMPARE(_sql_query.boundValue(_i), _sql_values[_i]); \ } qdjango-0.6.2/tests/http/000077500000000000000000000000001261212605400152625ustar00rootroot00000000000000qdjango-0.6.2/tests/http/http.pri000066400000000000000000000001261261212605400167540ustar00rootroot00000000000000include(../tests.pri) QT += network LIBS += -L../../../src/http $$QDJANGO_HTTP_LIBS qdjango-0.6.2/tests/http/http.pro000066400000000000000000000002701261212605400167620ustar00rootroot00000000000000TEMPLATE = subdirs SUBDIRS = \ qdjangofastcgiserver \ qdjangohttpcontroller \ qdjangohttprequest \ qdjangohttpresponse \ qdjangohttpserver \ qdjangourlresolver qdjango-0.6.2/tests/http/qdjangofastcgiserver/000077500000000000000000000000001261212605400214755ustar00rootroot00000000000000qdjango-0.6.2/tests/http/qdjangofastcgiserver/qdjangofastcgiserver.pro000066400000000000000000000001401261212605400264250ustar00rootroot00000000000000include(../http.pri) TARGET = tst_qdjangofastcgiserver SOURCES += tst_qdjangofastcgiserver.cpp qdjango-0.6.2/tests/http/qdjangofastcgiserver/tst_qdjangofastcgiserver.cpp000066400000000000000000000413461261212605400273160ustar00rootroot00000000000000/* * Copyright (C) 2010-2015 Jeremy Lainé * Contact: https://github.com/jlaine/qdjango * * This file is part of the QDjango Library. * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * This library 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 * Lesser General Public License for more details. */ #include #include #include #include #include "QDjangoFastCgiServer.h" #include "QDjangoFastCgiServer_p.h" #include "QDjangoHttpController.h" #include "QDjangoHttpRequest.h" #include "QDjangoHttpResponse.h" #include "QDjangoFastCgiServer.h" #include "QDjangoUrlResolver.h" #define ERROR_DATA QByteArray("Status: 500 Internal Server Error\r\n" \ "Content-Length: 107\r\n" \ "Content-Type: text/html; charset=utf-8\r\n" \ "\r\n" \ "Error

An internal server error was encountered.

") #define NOT_FOUND_DATA QByteArray("Status: 404 Not Found\r\n" \ "Content-Length: 107\r\n" \ "Content-Type: text/html; charset=utf-8\r\n" \ "\r\n" \ "Error

The document you requested was not found.

") #define POST_DATA QByteArray("Status: 200 OK\r\n" \ "Content-Length: 27\r\n" \ "Content-Type: text/plain\r\n" \ "\r\n" \ "method=POST|path=/|post=bar") #define ROOT_DATA QByteArray("Status: 200 OK\r\n" \ "Content-Length: 17\r\n" \ "Content-Type: text/plain\r\n" \ "\r\n" \ "method=GET|path=/") #define QUERY_STRING_DATA QByteArray("Status: 200 OK\r\n" \ "Content-Length: 25\r\n" \ "Content-Type: text/plain\r\n" \ "\r\n" \ "method=GET|path=/|get=bar") static QByteArray encodeSize(quint32 size) { QByteArray ba; if (size < 128) { ba.append(char(size & 0x7f)); } else { ba.append(char((size >> 24) | 0x80)); ba.append(char((size >> 16) & 0xff)); ba.append(char((size >> 8) & 0xff)); ba.append(char(size & 0xff)); } return ba; } class QDjangoFastCgiReply : public QObject { Q_OBJECT public: QDjangoFastCgiReply(QObject *parent = 0) : QObject(parent) {}; QByteArray data; signals: void finished(); }; class QDjangoFastCgiClient : public QObject { Q_OBJECT public: QDjangoFastCgiClient(QIODevice *socket); QDjangoFastCgiReply* request(const QString &method, const QUrl &url, const QByteArray &data); private slots: void _q_readyRead(); private: QIODevice *m_device; QMap m_replies; quint16 m_requestId; }; QDjangoFastCgiClient::QDjangoFastCgiClient(QIODevice *socket) : m_device(socket) , m_requestId(0) { connect(socket, SIGNAL(readyRead()), this, SLOT(_q_readyRead())); }; QDjangoFastCgiReply* QDjangoFastCgiClient::request(const QString &method, const QUrl &url, const QByteArray &data) { const quint16 requestId = ++m_requestId; QDjangoFastCgiReply *reply = new QDjangoFastCgiReply(this); m_replies[requestId] = reply; QByteArray headerBuffer(FCGI_HEADER_LEN, '\0'); FCGI_Header *header = (FCGI_Header*)headerBuffer.data(); QByteArray ba; // BEGIN REQUEST ba = QByteArray("\x01\x00\x00\x00\x00\x00\x00\x00", 8); header->version = 1; QDjangoFastCgiHeader::setRequestId(header, requestId); header->type = FCGI_BEGIN_REQUEST; QDjangoFastCgiHeader::setContentLength(header, ba.size()); m_device->write(headerBuffer + ba); QMap params; params["PATH_INFO"] = url.path().toUtf8(); #if (QT_VERSION >= QT_VERSION_CHECK(5, 0, 0)) params["QUERY_STRING"] = url.query().toUtf8(); #else params["QUERY_STRING"] = url.encodedQuery(); #endif params["REQUEST_URI"] = url.toString().toUtf8(); params["REQUEST_METHOD"] = method.toUtf8(); params["aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa"] = "bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb"; ba.clear(); foreach (const QByteArray &key, params.keys()) { const QByteArray value = params.value(key); ba.append(encodeSize(key.size())); ba.append(encodeSize(value.size())); ba.append(key); ba.append(value); } // FAST CGI PARAMS header->type = FCGI_PARAMS; QDjangoFastCgiHeader::setContentLength(header, ba.size()); m_device->write(headerBuffer + ba); // STDIN if (data.size() > 0) { header->type = FCGI_STDIN; QDjangoFastCgiHeader::setContentLength(header, data.size()); m_device->write(headerBuffer + data); } header->type = FCGI_STDIN; QDjangoFastCgiHeader::setContentLength(header, 0); m_device->write(headerBuffer); return reply; } void QDjangoFastCgiClient::_q_readyRead() { char inputBuffer[FCGI_RECORD_SIZE]; FCGI_Header *header = (FCGI_Header*)inputBuffer; while (m_device->bytesAvailable()) { if (m_device->read(inputBuffer, FCGI_HEADER_LEN) != FCGI_HEADER_LEN) { qWarning("header read fail"); return; } const quint16 contentLength = QDjangoFastCgiHeader::contentLength(header); const quint16 requestId = QDjangoFastCgiHeader::requestId(header); const quint16 bodyLength = contentLength + header->paddingLength; if (m_device->read(inputBuffer + FCGI_HEADER_LEN, bodyLength) != bodyLength) { qWarning("body read fail"); return; } if (!m_replies.contains(requestId)) { qWarning() << "unknown request" << requestId; return; } if (header->type == FCGI_STDOUT) { const QByteArray data = QByteArray(inputBuffer + FCGI_HEADER_LEN, contentLength); m_replies[requestId]->data += data; } else if (header->type == FCGI_END_REQUEST) { QMetaObject::invokeMethod(m_replies[requestId], "finished"); } } } /** Test QDjangoFastCgiServer class. */ class tst_QDjangoFastCgiServer : public QObject { Q_OBJECT private slots: void cleanup(); void init(); void testAbort(); void testBadBegin(); void testBadRequestId(); void testBadRequestType(); void testBadVersion(); void testLocal_data(); void testLocal(); void testTcp_data(); void testTcp(); QDjangoHttpResponse* _q_index(const QDjangoHttpRequest &request); QDjangoHttpResponse* _q_error(const QDjangoHttpRequest &request); private: QDjangoFastCgiServer *server; }; void tst_QDjangoFastCgiServer::cleanup() { server->close(); delete server; } void tst_QDjangoFastCgiServer::init() { server = new QDjangoFastCgiServer; server->urls()->set(QRegExp(QLatin1String(QLatin1String("^$"))), this, "_q_index"); server->urls()->set(QRegExp(QLatin1String("^internal-server-error$")), this, "_q_error"); } void tst_QDjangoFastCgiServer::testAbort() { const QString name("/tmp/qdjangofastcgi.socket"); QCOMPARE(server->listen(name), true); QLocalSocket socket; socket.connectToServer(name); QByteArray headerBuffer(FCGI_HEADER_LEN, '\0'); FCGI_Header *header = (FCGI_Header*)headerBuffer.data(); header->version = 1; QDjangoFastCgiHeader::setRequestId(header, 1); // check socket is connected QCOMPARE(socket.state(), QLocalSocket::ConnectedState); // BEGIN REQUEST const QByteArray ba("\x01\x00\x00\x00\x00\x00\x00\x00", 8); header->type = FCGI_BEGIN_REQUEST; QDjangoFastCgiHeader::setContentLength(header, ba.size()); socket.write(headerBuffer + ba); // ABORT REQUEST header->type = FCGI_ABORT_REQUEST; QDjangoFastCgiHeader::setContentLength(header, 0); socket.write(headerBuffer); // wait for connection to close QEventLoop loop; QObject::connect(&socket, SIGNAL(disconnected()), &loop, SLOT(quit())); loop.exec(); QCOMPARE(socket.state(), QLocalSocket::UnconnectedState); } void tst_QDjangoFastCgiServer::testBadBegin() { const QString name("/tmp/qdjangofastcgi.socket"); QCOMPARE(server->listen(name), true); QLocalSocket socket; socket.connectToServer(name); QByteArray headerBuffer(FCGI_HEADER_LEN, '\0'); FCGI_Header *header = (FCGI_Header*)headerBuffer.data(); header->version = 1; QDjangoFastCgiHeader::setRequestId(header, 1); // check socket is connected QCOMPARE(socket.state(), QLocalSocket::ConnectedState); QTest::ignoreMessage(QtWarningMsg, "Received new FastCGI request 2 while already handling request 1"); // BEGIN REQUEST const QByteArray ba("\x01\x00\x00\x00\x00\x00\x00\x00", 8); header->type = FCGI_BEGIN_REQUEST; QDjangoFastCgiHeader::setContentLength(header, ba.size()); socket.write(headerBuffer + ba); // BEGIN REQUEST again QDjangoFastCgiHeader::setRequestId(header, 2); QDjangoFastCgiHeader::setContentLength(header, ba.size()); socket.write(headerBuffer + ba); // wait for connection to close QEventLoop loop; QObject::connect(&socket, SIGNAL(disconnected()), &loop, SLOT(quit())); loop.exec(); QCOMPARE(socket.state(), QLocalSocket::UnconnectedState); } void tst_QDjangoFastCgiServer::testBadRequestId() { const QString name("/tmp/qdjangofastcgi.socket"); QCOMPARE(server->listen(name), true); QLocalSocket socket; socket.connectToServer(name); QByteArray headerBuffer(FCGI_HEADER_LEN, '\0'); FCGI_Header *header = (FCGI_Header*)headerBuffer.data(); header->version = 1; QDjangoFastCgiHeader::setRequestId(header, 1); // check socket is connected QCOMPARE(socket.state(), QLocalSocket::ConnectedState); QTest::ignoreMessage(QtWarningMsg, "Received FastCGI record for an invalid request 1"); // ABORT REQUEST header->type = FCGI_ABORT_REQUEST; QDjangoFastCgiHeader::setContentLength(header, 0); socket.write(headerBuffer); // wait for connection to close QEventLoop loop; QObject::connect(&socket, SIGNAL(disconnected()), &loop, SLOT(quit())); loop.exec(); QCOMPARE(socket.state(), QLocalSocket::UnconnectedState); } void tst_QDjangoFastCgiServer::testBadRequestType() { const QString name("/tmp/qdjangofastcgi.socket"); QCOMPARE(server->listen(name), true); QLocalSocket socket; socket.connectToServer(name); QByteArray headerBuffer(FCGI_HEADER_LEN, '\0'); FCGI_Header *header = (FCGI_Header*)headerBuffer.data(); header->version = 1; QDjangoFastCgiHeader::setRequestId(header, 1); // check socket is connected QCOMPARE(socket.state(), QLocalSocket::ConnectedState); QTest::ignoreMessage(QtWarningMsg, "Received FastCGI record with an invalid type 7"); // BEGIN REQUEST const QByteArray ba("\x01\x00\x00\x00\x00\x00\x00\x00", 8); header->type = FCGI_BEGIN_REQUEST; QDjangoFastCgiHeader::setContentLength(header, ba.size()); socket.write(headerBuffer + ba); // bogus request type header->type = 7; QDjangoFastCgiHeader::setContentLength(header, 0); socket.write(headerBuffer); // wait for connection to close QEventLoop loop; QObject::connect(&socket, SIGNAL(disconnected()), &loop, SLOT(quit())); loop.exec(); QCOMPARE(socket.state(), QLocalSocket::UnconnectedState); } void tst_QDjangoFastCgiServer::testBadVersion() { const QString name("/tmp/qdjangofastcgi.socket"); QCOMPARE(server->listen(name), true); QLocalSocket socket; socket.connectToServer(name); QByteArray headerBuffer(FCGI_HEADER_LEN, '\0'); FCGI_Header *header = (FCGI_Header*)headerBuffer.data(); header->version = 2; QDjangoFastCgiHeader::setRequestId(header, 1); // check socket is connected QCOMPARE(socket.state(), QLocalSocket::ConnectedState); QTest::ignoreMessage(QtWarningMsg, "Received FastCGI record with an invalid version 2"); // BEGIN REQUEST const QByteArray ba("\x01\x00\x00\x00\x00\x00\x00\x00", 8); header->type = FCGI_BEGIN_REQUEST; QDjangoFastCgiHeader::setContentLength(header, ba.size()); socket.write(headerBuffer + ba); // wait for connection to close QEventLoop loop; QObject::connect(&socket, SIGNAL(disconnected()), &loop, SLOT(quit())); loop.exec(); QCOMPARE(socket.state(), QLocalSocket::UnconnectedState); } void tst_QDjangoFastCgiServer::testLocal_data() { QTest::addColumn("method"); QTest::addColumn("path"); QTest::addColumn("data"); QTest::addColumn("response"); QTest::newRow("root") << "GET" << "/" << QByteArray() << ROOT_DATA; QTest::newRow("query-string") << "GET" << "/?message=bar" << QByteArray() << QUERY_STRING_DATA; QTest::newRow("not-found") << "GET" << "/not-found" << QByteArray() << NOT_FOUND_DATA; QTest::newRow("internal-server-error") << "GET" << "/internal-server-error" << QByteArray() << ERROR_DATA; QTest::newRow("post") << "POST" << "/" << QByteArray("message=bar") << POST_DATA; } void tst_QDjangoFastCgiServer::testLocal() { QFETCH(QString, method); QFETCH(QString, path); QFETCH(QByteArray, data); QFETCH(QByteArray, response); const QString name("/tmp/qdjangofastcgi.socket"); QCOMPARE(server->listen(name), true); QLocalSocket socket; socket.connectToServer(name); QEventLoop loop; QDjangoFastCgiClient client(&socket); // check socket is connected QCOMPARE(socket.state(), QLocalSocket::ConnectedState); // wait for reply QDjangoFastCgiReply *reply = client.request(method, path, data); QObject::connect(reply, SIGNAL(finished()), &loop, SLOT(quit())); loop.exec(); QCOMPARE(socket.state(), QLocalSocket::ConnectedState); QCOMPARE(reply->data, response); // wait for connection to close QObject::connect(&socket, SIGNAL(disconnected()), &loop, SLOT(quit())); loop.exec(); QCOMPARE(socket.state(), QLocalSocket::UnconnectedState); } void tst_QDjangoFastCgiServer::testTcp_data() { QTest::addColumn("method"); QTest::addColumn("path"); QTest::addColumn("data"); QTest::addColumn("response"); QTest::newRow("root") << "GET" << "/" << QByteArray() << ROOT_DATA; QTest::newRow("query-string") << "GET" << "/?message=bar" << QByteArray() << QUERY_STRING_DATA; QTest::newRow("not-found") << "GET" << "/not-found" << QByteArray() << NOT_FOUND_DATA; QTest::newRow("internal-server-error") << "GET" << "/internal-server-error" << QByteArray() << ERROR_DATA; QTest::newRow("post") << "POST" << "/" << QByteArray("message=bar") << POST_DATA; } void tst_QDjangoFastCgiServer::testTcp() { QFETCH(QString, method); QFETCH(QString, path); QFETCH(QByteArray, data); QFETCH(QByteArray, response); QCOMPARE(server->listen(QHostAddress::LocalHost, 8123), true); QTcpSocket socket; socket.connectToHost("127.0.0.1", 8123); QEventLoop loop; QDjangoFastCgiClient client(&socket); // wait for socket to connect QObject::connect(&socket, SIGNAL(connected()), &loop, SLOT(quit())); loop.exec(); QCOMPARE(socket.state(), QAbstractSocket::ConnectedState); // wait for reply QDjangoFastCgiReply *reply = client.request(method, path, data); QObject::connect(reply, SIGNAL(finished()), &loop, SLOT(quit())); loop.exec(); QCOMPARE(socket.state(), QAbstractSocket::ConnectedState); QCOMPARE(reply->data, response); // wait for connection to close QObject::connect(&socket, SIGNAL(disconnected()), &loop, SLOT(quit())); loop.exec(); QCOMPARE(socket.state(), QAbstractSocket::UnconnectedState); } QDjangoHttpResponse *tst_QDjangoFastCgiServer::_q_index(const QDjangoHttpRequest &request) { QDjangoHttpResponse *response = new QDjangoHttpResponse; response->setHeader(QLatin1String("Content-Type"), QLatin1String("text/plain")); QString output = QLatin1String("method=") + request.method(); output += QLatin1String("|path=") + request.path(); const QString getValue = request.get(QLatin1String("message")); if (!getValue.isEmpty()) output += QLatin1String("|get=") + getValue; const QString postValue = request.post(QLatin1String("message")); if (!postValue.isEmpty()) output += QLatin1String("|post=") + postValue; response->setBody(output.toUtf8()); return response; } QDjangoHttpResponse *tst_QDjangoFastCgiServer::_q_error(const QDjangoHttpRequest &request) { Q_UNUSED(request); return QDjangoHttpController::serveInternalServerError(request); } QTEST_MAIN(tst_QDjangoFastCgiServer) #include "tst_qdjangofastcgiserver.moc" qdjango-0.6.2/tests/http/qdjangohttpcontroller/000077500000000000000000000000001261212605400217115ustar00rootroot00000000000000qdjango-0.6.2/tests/http/qdjangohttpcontroller/qdjangohttpcontroller.pro000066400000000000000000000002151261212605400270600ustar00rootroot00000000000000include(../http.pri) TARGET = tst_qdjangohttpcontroller SOURCES += tst_qdjangohttpcontroller.cpp RESOURCES += tst_qdjangohttpcontroller.qrc qdjango-0.6.2/tests/http/qdjangohttpcontroller/test.bin000066400000000000000000000000061261212605400233560ustar00rootroot00000000000000DATA! qdjango-0.6.2/tests/http/qdjangohttpcontroller/test.css000066400000000000000000000000331261212605400233760ustar00rootroot00000000000000body { color: 'red'; } qdjango-0.6.2/tests/http/qdjangohttpcontroller/test.html000066400000000000000000000000601261212605400235520ustar00rootroot00000000000000

Hello!

qdjango-0.6.2/tests/http/qdjangohttpcontroller/test.js000066400000000000000000000000251261212605400232230ustar00rootroot00000000000000console.log("foo!"); qdjango-0.6.2/tests/http/qdjangohttpcontroller/tst_qdjangohttpcontroller.cpp000066400000000000000000000176271261212605400277530ustar00rootroot00000000000000/* * Copyright (C) 2010-2015 Jeremy Lainé * Contact: https://github.com/jlaine/qdjango * * This file is part of the QDjango Library. * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * This library 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 * Lesser General Public License for more details. */ #include #include #include "QDjangoHttpController.h" #include "QDjangoHttpRequest.h" #include "QDjangoHttpRequest_p.h" #include "QDjangoHttpResponse.h" /** Test QDjangoHttpController class. */ class tst_QDjangoHttpController : public QObject { Q_OBJECT private slots: void testBasicAuth(); void testDateTime(); void testServeAuthorizationRequired(); void testServeBadRequest(); void testServeInternalServerError(); void testServeNotFound(); void testServeRedirect(); void testServeStatic(); void testServeStaticHead(); void testServeStaticIfModifiedSince(); }; void tst_QDjangoHttpController::testBasicAuth() { QDjangoHttpRequest request; QString username, password; QCOMPARE(QDjangoHttpController::getBasicAuth(request, username, password), false); QCOMPARE(username, QString()); QCOMPARE(password, QString()); request.d->meta.insert("HTTP_AUTHORIZATION", "Basic bad"); QCOMPARE(QDjangoHttpController::getBasicAuth(request, username, password), false); QCOMPARE(username, QString()); QCOMPARE(password, QString()); request.d->meta.insert("HTTP_AUTHORIZATION", "Basic Zm9vOmJhcg=="); QCOMPARE(QDjangoHttpController::getBasicAuth(request, username, password), true); QCOMPARE(username, QString("foo")); QCOMPARE(password, QString("bar")); } void tst_QDjangoHttpController::testDateTime() { const QDateTime dt(QDate(2014, 7, 14), QTime(11, 22, 33), Qt::UTC); QCOMPARE(QDjangoHttpController::httpDateTime(dt), QString("Mon, 14 Jul 2014 11:22:33 GMT")); QCOMPARE(QDjangoHttpController::httpDateTime("Mon, 14 Jul 2014 11:22:33 GMT"), dt); } void tst_QDjangoHttpController::testServeAuthorizationRequired() { QDjangoHttpRequest request; QDjangoHttpResponse *response = QDjangoHttpController::serveAuthorizationRequired(request); QCOMPARE(response->statusCode(), 401); QCOMPARE(response->header("www-authenticate"), QString("Basic realm=\"Secure Area\"")); delete response; } void tst_QDjangoHttpController::testServeBadRequest() { QDjangoHttpRequest request; QDjangoHttpResponse *response = QDjangoHttpController::serveBadRequest(request); QCOMPARE(response->statusCode(), 400); delete response; } void tst_QDjangoHttpController::testServeInternalServerError() { QDjangoHttpRequest request; QDjangoHttpResponse *response = QDjangoHttpController::serveInternalServerError(request); QCOMPARE(response->statusCode(), 500); delete response; } void tst_QDjangoHttpController::testServeNotFound() { QDjangoHttpRequest request; QDjangoHttpResponse *response = QDjangoHttpController::serveNotFound(request); QCOMPARE(response->statusCode(), 404); delete response; } void tst_QDjangoHttpController::testServeRedirect() { QDjangoHttpRequest request; QDjangoHttpResponse *response = QDjangoHttpController::serveRedirect(request, QUrl("/bye"), false); QCOMPARE(response->statusCode(), 302); QCOMPARE(response->header("location"), QString("/bye")); delete response; response = QDjangoHttpController::serveRedirect(request, QUrl("/bye"), true); QCOMPARE(response->statusCode(), 301); QCOMPARE(response->header("location"), QString("/bye")); delete response; } void tst_QDjangoHttpController::testServeStatic() { QDjangoHttpRequest request; QDjangoHttpResponse *response; request.d->method = "GET"; response = QDjangoHttpController::serveStatic(request, ":/not-found"); QCOMPARE(response->statusCode(), 404); QCOMPARE(response->header("content-type"), QString("text/html; charset=utf-8")); QCOMPARE(response->header("content-length"), QString("107")); QCOMPARE(response->header("expires"), QString()); QVERIFY(response->header("last-modified").isEmpty()); delete response; response = QDjangoHttpController::serveStatic(request, ":/test.bin"); QCOMPARE(response->statusCode(), 200); QCOMPARE(response->header("content-type"), QString("application/octet-stream")); QCOMPARE(response->header("content-length"), QString("6")); QCOMPARE(response->header("expires"), QString()); QVERIFY(!response->header("last-modified").isEmpty()); delete response; response = QDjangoHttpController::serveStatic(request, ":/test.css"); QCOMPARE(response->statusCode(), 200); QCOMPARE(response->header("content-type"), QString("text/css")); QCOMPARE(response->header("content-length"), QString("27")); QCOMPARE(response->header("expires"), QString()); QVERIFY(!response->header("last-modified").isEmpty()); QCOMPARE(response->body().size(), 27); delete response; response = QDjangoHttpController::serveStatic(request, ":/test.js"); QCOMPARE(response->statusCode(), 200); QCOMPARE(response->header("content-type"), QString("application/javascript")); QCOMPARE(response->header("content-length"), QString("21")); QCOMPARE(response->header("expires"), QString()); QVERIFY(!response->header("last-modified").isEmpty()); QCOMPARE(response->body().size(), 21); delete response; response = QDjangoHttpController::serveStatic(request, ":/test.html"); QCOMPARE(response->statusCode(), 200); QCOMPARE(response->header("content-type"), QString("text/html")); QCOMPARE(response->header("content-length"), QString("48")); QCOMPARE(response->header("expires"), QString()); QVERIFY(!response->header("last-modified").isEmpty()); QCOMPARE(response->body().size(), 48); delete response; // expires const QDateTime expires(QDate(2014, 7, 14), QTime(11, 22, 33), Qt::UTC); response = QDjangoHttpController::serveStatic(request, ":/test.html", expires); QCOMPARE(response->statusCode(), 200); QCOMPARE(response->header("content-type"), QString("text/html")); QCOMPARE(response->header("content-length"), QString("48")); QCOMPARE(response->header("expires"), QString("Mon, 14 Jul 2014 11:22:33 GMT")); QVERIFY(!response->header("last-modified").isEmpty()); QCOMPARE(response->body().size(), 48); delete response; } void tst_QDjangoHttpController::testServeStaticHead() { QDjangoHttpRequest request; request.d->method = "HEAD"; QDjangoHttpResponse *response = QDjangoHttpController::serveStatic(request, ":/test.html"); QCOMPARE(response->statusCode(), 200); QCOMPARE(response->header("content-type"), QString("text/html")); QCOMPARE(response->header("content-length"), QString("48")); QCOMPARE(response->header("expires"), QString()); QVERIFY(!response->header("last-modified").isEmpty()); QCOMPARE(response->body().size(), 0); delete response; } void tst_QDjangoHttpController::testServeStaticIfModifiedSince() { QDjangoHttpRequest request; request.d->method = "GET"; request.d->meta.insert("HTTP_IF_MODIFIED_SINCE", "Tue, 14 Jul 2054 11:22:33 GMT"); QDjangoHttpResponse *response = QDjangoHttpController::serveStatic(request, ":/test.html"); QCOMPARE(response->statusCode(), 304); QCOMPARE(response->header("content-type"), QString()); QCOMPARE(response->header("content-length"), QString("0")); QCOMPARE(response->header("expires"), QString()); QVERIFY(!response->header("last-modified").isEmpty()); QCOMPARE(response->body().size(), 0); delete response; } QTEST_MAIN(tst_QDjangoHttpController) #include "tst_qdjangohttpcontroller.moc" qdjango-0.6.2/tests/http/qdjangohttpcontroller/tst_qdjangohttpcontroller.qrc000066400000000000000000000002531261212605400277410ustar00rootroot00000000000000 test.bin test.css test.js test.html qdjango-0.6.2/tests/http/qdjangohttprequest/000077500000000000000000000000001261212605400212165ustar00rootroot00000000000000qdjango-0.6.2/tests/http/qdjangohttprequest/qdjangohttprequest.pro000066400000000000000000000001341261212605400256720ustar00rootroot00000000000000include(../http.pri) TARGET = tst_qdjangohttprequest SOURCES += tst_qdjangohttprequest.cpp qdjango-0.6.2/tests/http/qdjangohttprequest/tst_qdjangohttprequest.cpp000066400000000000000000000072731261212605400265610ustar00rootroot00000000000000/* * Copyright (C) 2010-2015 Jeremy Lainé * Contact: https://github.com/jlaine/qdjango * * This file is part of the QDjango Library. * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * This library 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 * Lesser General Public License for more details. */ #include #include "QDjangoHttpRequest.h" #include "QDjangoHttpRequest_p.h" /** Test QDjangoHttpServer class. */ class tst_QDjangoHttpRequest : public QObject { Q_OBJECT private slots: void testBody(); void testGet(); void testPost(); }; void tst_QDjangoHttpRequest::testBody() { QDjangoHttpRequest request; QCOMPARE(request.body(), QByteArray()); request.d->buffer = QByteArray("foo=bar"); QCOMPARE(request.body(), QByteArray("foo=bar")); } void tst_QDjangoHttpRequest::testGet() { QDjangoHttpRequest request; // plain request.d->meta.insert("QUERY_STRING", "foo=bar&baz=qux"); QCOMPARE(request.get(QLatin1String("foo")), QLatin1String("bar")); QCOMPARE(request.get(QLatin1String("baz")), QLatin1String("qux")); // space encoded as plus request.d->meta.insert("QUERY_STRING", "foo=bar+more&baz=qux"); QCOMPARE(request.get(QLatin1String("foo")), QLatin1String("bar more")); QCOMPARE(request.get(QLatin1String("baz")), QLatin1String("qux")); // plus encoded as %2B request.d->meta.insert("QUERY_STRING", "foo=bar%2Bmore&baz=qux"); QCOMPARE(request.get(QLatin1String("foo")), QLatin1String("bar+more")); QCOMPARE(request.get(QLatin1String("baz")), QLatin1String("qux")); // plus encoded as %2b request.d->meta.insert("QUERY_STRING", "foo=bar%2bmore&baz=qux"); QCOMPARE(request.get(QLatin1String("foo")), QLatin1String("bar+more")); QCOMPARE(request.get(QLatin1String("baz")), QLatin1String("qux")); // at encoded as %40 request.d->meta.insert("QUERY_STRING", "foo=bar%40example.com&baz=qux"); QCOMPARE(request.get(QLatin1String("foo")), QLatin1String("bar@example.com")); QCOMPARE(request.get(QLatin1String("baz")), QLatin1String("qux")); } void tst_QDjangoHttpRequest::testPost() { QDjangoHttpRequest request; // plain request.d->buffer = QByteArray("foo=bar&baz=qux"); QCOMPARE(request.post(QLatin1String("foo")), QLatin1String("bar")); QCOMPARE(request.post(QLatin1String("baz")), QLatin1String("qux")); // space encoded as plus request.d->buffer = QByteArray("foo=bar+more&baz=qux"); QCOMPARE(request.post(QLatin1String("foo")), QLatin1String("bar more")); QCOMPARE(request.post(QLatin1String("baz")), QLatin1String("qux")); // plus encoded as %2B request.d->buffer = QByteArray("foo=bar%2Bmore&baz=qux"); QCOMPARE(request.post(QLatin1String("foo")), QLatin1String("bar+more")); QCOMPARE(request.post(QLatin1String("baz")), QLatin1String("qux")); // plus encoded as %2b request.d->buffer = QByteArray("foo=bar%2bmore&baz=qux"); QCOMPARE(request.post(QLatin1String("foo")), QLatin1String("bar+more")); QCOMPARE(request.post(QLatin1String("baz")), QLatin1String("qux")); // at encoded as %40 request.d->buffer = QByteArray("foo=bar%40example.com&baz=qux"); QCOMPARE(request.post(QLatin1String("foo")), QLatin1String("bar@example.com")); QCOMPARE(request.post(QLatin1String("baz")), QLatin1String("qux")); } QTEST_MAIN(tst_QDjangoHttpRequest) #include "tst_qdjangohttprequest.moc" qdjango-0.6.2/tests/http/qdjangohttpresponse/000077500000000000000000000000001261212605400213645ustar00rootroot00000000000000qdjango-0.6.2/tests/http/qdjangohttpresponse/qdjangohttpresponse.pro000066400000000000000000000001361261212605400262100ustar00rootroot00000000000000include(../http.pri) TARGET = tst_qdjangohttpresponse SOURCES += tst_qdjangohttpresponse.cpp qdjango-0.6.2/tests/http/qdjangohttpresponse/tst_qdjangohttpresponse.cpp000066400000000000000000000052461261212605400270730ustar00rootroot00000000000000/* * Copyright (C) 2010-2015 Jeremy Lainé * Contact: https://github.com/jlaine/qdjango * * This file is part of the QDjango Library. * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * This library 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 * Lesser General Public License for more details. */ #include #include "QDjangoHttpResponse.h" /** Test QDjangoHttpServer class. */ class tst_QDjangoHttpResponse : public QObject { Q_OBJECT private slots: void testBody(); void testHeader(); void testStatusCode_data(); void testStatusCode(); }; void tst_QDjangoHttpResponse::testBody() { QDjangoHttpResponse response; QCOMPARE(response.body(), QByteArray()); response.setBody("foo=bar"); QCOMPARE(response.body(), QByteArray("foo=bar")); } void tst_QDjangoHttpResponse::testHeader() { QDjangoHttpResponse response; QCOMPARE(response.header("Content-Type"), QString()); response.setHeader("Content-Type", "application/json"); QCOMPARE(response.header("Content-Type"), QString("application/json")); QCOMPARE(response.header("content-type"), QString("application/json")); } void tst_QDjangoHttpResponse::testStatusCode_data() { QTest::addColumn("statusCode"); QTest::addColumn("reasonPhrase"); QTest::newRow("200") << int(200) << QString("OK"); QTest::newRow("301") << int(301) << QString("Moved Permanently"); QTest::newRow("302") << int(302) << QString("Found"); QTest::newRow("304") << int(304) << QString("Not Modified"); QTest::newRow("400") << int(400) << QString("Bad Request"); QTest::newRow("401") << int(401) << QString("Authorization Required"); QTest::newRow("403") << int(403) << QString("Forbidden"); QTest::newRow("403") << int(404) << QString("Not Found"); QTest::newRow("405") << int(405) << QString("Method Not Allowed"); QTest::newRow("500") << int(500) << QString("Internal Server Error"); QTest::newRow("501") << int(501) << QString(); } void tst_QDjangoHttpResponse::testStatusCode() { QFETCH(int, statusCode); QFETCH(QString, reasonPhrase); QDjangoHttpResponse response; response.setStatusCode(statusCode); QCOMPARE(response.statusCode(), statusCode); QCOMPARE(response.reasonPhrase(), reasonPhrase); } QTEST_MAIN(tst_QDjangoHttpResponse) #include "tst_qdjangohttpresponse.moc" qdjango-0.6.2/tests/http/qdjangohttpserver/000077500000000000000000000000001261212605400210345ustar00rootroot00000000000000qdjango-0.6.2/tests/http/qdjangohttpserver/qdjangohttpserver.pro000066400000000000000000000001321261212605400253240ustar00rootroot00000000000000include(../http.pri) TARGET = tst_qdjangohttpserver SOURCES += tst_qdjangohttpserver.cpp qdjango-0.6.2/tests/http/qdjangohttpserver/tst_qdjangohttpserver.cpp000066400000000000000000000144711261212605400262130ustar00rootroot00000000000000/* * Copyright (C) 2010-2015 Jeremy Lainé * Contact: https://github.com/jlaine/qdjango * * This file is part of the QDjango Library. * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * This library 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 * Lesser General Public License for more details. */ #include #include #include #include #include #include "QDjangoHttpController.h" #include "QDjangoHttpRequest.h" #include "QDjangoHttpResponse.h" #include "QDjangoHttpServer.h" #include "QDjangoUrlResolver.h" /** Test QDjangoHttpServer class. */ class tst_QDjangoHttpServer : public QObject { Q_OBJECT private slots: void cleanupTestCase(); void initTestCase(); void testCloseConnection(); void testGet_data(); void testGet(); void testPost_data(); void testPost(); QDjangoHttpResponse* _q_index(const QDjangoHttpRequest &request); QDjangoHttpResponse* _q_error(const QDjangoHttpRequest &request); private: QDjangoHttpServer *httpServer; }; void tst_QDjangoHttpServer::cleanupTestCase() { httpServer->close(); delete httpServer; } void tst_QDjangoHttpServer::initTestCase() { httpServer = new QDjangoHttpServer; httpServer->urls()->set(QRegExp(QLatin1String("^$")), this, "_q_index"); httpServer->urls()->set(QRegExp(QLatin1String("^internal-server-error$")), this, "_q_error"); QCOMPARE(httpServer->serverAddress(), QHostAddress(QHostAddress::Null)); QCOMPARE(httpServer->serverPort(), quint16(0)); QCOMPARE(httpServer->listen(QHostAddress::LocalHost, 8123), true); QCOMPARE(httpServer->serverAddress(), QHostAddress(QHostAddress::LocalHost)); QCOMPARE(httpServer->serverPort(), quint16(8123)); } void tst_QDjangoHttpServer::testCloseConnection() { QNetworkAccessManager network; QNetworkRequest req(QUrl("http://127.0.0.1:8123/")); req.setRawHeader("Connection", "close"); QNetworkReply *reply = network.get(req); QEventLoop loop; QObject::connect(reply, SIGNAL(finished()), &loop, SLOT(quit())); loop.exec(); QVERIFY(reply); QCOMPARE(reply->error(), QNetworkReply::NoError); //QCOMPARE(reply->readAll(), body); delete reply; } void tst_QDjangoHttpServer::testGet_data() { QTest::addColumn("path"); QTest::addColumn("err"); QTest::addColumn("body"); const QString errorTemplate = QLatin1String( "" "Error" "

%1

" ""); #if (QT_VERSION >= QT_VERSION_CHECK(5, 3, 0)) int internalServerError = int(QNetworkReply::InternalServerError); #else int internalServerError = int(QNetworkReply::UnknownContentError); #endif QTest::newRow("root") << "/" << int(QNetworkReply::NoError) << QByteArray("method=GET|path=/"); QTest::newRow("query-string") << "/?message=bar" << int(QNetworkReply::NoError) << QByteArray("method=GET|path=/|get=bar"); QTest::newRow("not-found") << "/not-found" << int(QNetworkReply::ContentNotFoundError) << errorTemplate.arg(QLatin1String("The document you requested was not found.")).toUtf8(); QTest::newRow("internal-server-error") << "/internal-server-error" << internalServerError << errorTemplate.arg(QLatin1String("An internal server error was encountered.")).toUtf8(); } void tst_QDjangoHttpServer::testGet() { QFETCH(QString, path); QFETCH(int, err); QFETCH(QByteArray, body); QNetworkAccessManager network; QNetworkReply *reply = network.get(QNetworkRequest(QUrl(QLatin1String("http://127.0.0.1:8123") + path))); QEventLoop loop; QObject::connect(reply, SIGNAL(finished()), &loop, SLOT(quit())); loop.exec(); QVERIFY(reply); QCOMPARE(int(reply->error()), err); QCOMPARE(reply->readAll(), body); delete reply; } void tst_QDjangoHttpServer::testPost_data() { QTest::addColumn("path"); QTest::addColumn("data"); QTest::addColumn("err"); QTest::addColumn("body"); QTest::newRow("empty") << "/" << QByteArray() << int(QNetworkReply::NoError) << QByteArray("method=POST|path=/"); QTest::newRow("simple") << "/" << QByteArray("message=bar") << int(QNetworkReply::NoError) << QByteArray("method=POST|path=/|post=bar"); QTest::newRow("multi") << "/" << QByteArray("bob=wiz&message=bar&zoo=wow") << int(QNetworkReply::NoError) << QByteArray("method=POST|path=/|post=bar"); } void tst_QDjangoHttpServer::testPost() { QFETCH(QString, path); QFETCH(QByteArray, data); QFETCH(int, err); QFETCH(QByteArray, body); QNetworkAccessManager network; QNetworkRequest req(QUrl(QLatin1String("http://127.0.0.1:8123") + path)); req.setRawHeader("Content-Type", "application/x-www-form-urlencoded"); QNetworkReply *reply = network.post(req, data); QEventLoop loop; QObject::connect(reply, SIGNAL(finished()), &loop, SLOT(quit())); loop.exec(); QVERIFY(reply); QCOMPARE(int(reply->error()), err); QCOMPARE(reply->readAll(), body); delete reply; } QDjangoHttpResponse *tst_QDjangoHttpServer::_q_index(const QDjangoHttpRequest &request) { QDjangoHttpResponse *response = new QDjangoHttpResponse; response->setHeader(QLatin1String("Content-Type"), QLatin1String("text/plain")); QString output = QLatin1String("method=") + request.method(); output += QLatin1String("|path=") + request.path(); const QString getValue = request.get(QLatin1String("message")); if (!getValue.isEmpty()) output += QLatin1String("|get=") + getValue; const QString postValue = request.post(QLatin1String("message")); if (!postValue.isEmpty()) output += QLatin1String("|post=") + postValue; response->setBody(output.toUtf8()); return response; } QDjangoHttpResponse *tst_QDjangoHttpServer::_q_error(const QDjangoHttpRequest &request) { Q_UNUSED(request); return QDjangoHttpController::serveInternalServerError(request); } QTEST_MAIN(tst_QDjangoHttpServer) #include "tst_qdjangohttpserver.moc" qdjango-0.6.2/tests/http/qdjangourlresolver/000077500000000000000000000000001261212605400212125ustar00rootroot00000000000000qdjango-0.6.2/tests/http/qdjangourlresolver/qdjangourlresolver.pro000066400000000000000000000001341261212605400256620ustar00rootroot00000000000000include(../http.pri) TARGET = tst_qdjangourlresolver SOURCES += tst_qdjangourlresolver.cpp qdjango-0.6.2/tests/http/qdjangourlresolver/tst_qdjangourlresolver.cpp000066400000000000000000000152271261212605400265470ustar00rootroot00000000000000/* * Copyright (C) 2010-2015 Jeremy Lainé * Contact: https://github.com/jlaine/qdjango * * This file is part of the QDjango Library. * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * This library 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 * Lesser General Public License for more details. */ #include #include #include #include #include #include "QDjangoHttpController.h" #include "QDjangoHttpRequest.h" #include "QDjangoHttpResponse.h" #include "QDjangoUrlResolver.h" class tst_QDjangoUrlHelper : public QObject { Q_OBJECT private slots: QDjangoHttpResponse* _q_index(const QDjangoHttpRequest &request); QDjangoHttpResponse* _q_test(const QDjangoHttpRequest &request); }; class tst_QDjangoUrlResolver : public QObject { Q_OBJECT private slots: void cleanupTestCase(); void initTestCase(); void testRespond_data(); void testRespond(); void testReverse_data(); void testReverse(); QDjangoHttpResponse* _q_index(const QDjangoHttpRequest &request); QDjangoHttpResponse* _q_noArgs(const QDjangoHttpRequest &request); QDjangoHttpResponse* _q_oneArg(const QDjangoHttpRequest &request, const QString &id); QDjangoHttpResponse* _q_twoArgs(const QDjangoHttpRequest &request, const QString &id, const QString &action); private: tst_QDjangoUrlHelper *urlHelper; QDjangoUrlResolver *urlResolver; QDjangoUrlResolver *urlSub; }; QDjangoHttpResponse* tst_QDjangoUrlHelper::_q_index(const QDjangoHttpRequest &request) { Q_UNUSED(request); QDjangoHttpResponse *response = new QDjangoHttpResponse; response->setHeader(QLatin1String("Content-Type"), QLatin1String("text/plain")); response->setBody("sub index"); return response; } QDjangoHttpResponse* tst_QDjangoUrlHelper::_q_test(const QDjangoHttpRequest &request) { Q_UNUSED(request); QDjangoHttpResponse *response = new QDjangoHttpResponse; response->setHeader(QLatin1String("Content-Type"), QLatin1String("text/plain")); response->setBody("sub test"); return response; } void tst_QDjangoUrlResolver::cleanupTestCase() { delete urlResolver; } void tst_QDjangoUrlResolver::initTestCase() { urlHelper = new tst_QDjangoUrlHelper; urlSub = new QDjangoUrlResolver; QVERIFY(urlSub->set(QRegExp(QLatin1String("^$")), urlHelper, "_q_index")); QVERIFY(urlSub->set(QRegExp(QLatin1String("^test/$")), urlHelper, "_q_test")); urlResolver = new QDjangoUrlResolver; QVERIFY(urlResolver->set(QRegExp(QLatin1String("^$")), this, "_q_index")); QVERIFY(urlResolver->set(QRegExp(QLatin1String("^test/$")), this, "_q_noArgs")); QVERIFY(urlResolver->set(QRegExp(QLatin1String("^test/([0-9]+)/$")), this, "_q_oneArg")); QVERIFY(urlResolver->set(QRegExp(QLatin1String("^test/([0-9]+)/([a-z]+)/$")), this, "_q_twoArgs")); QVERIFY(urlResolver->include(QRegExp(QLatin1String("^recurse/")), urlSub)); } void tst_QDjangoUrlResolver::testRespond_data() { QTest::addColumn("path"); QTest::addColumn("err"); QTest::addColumn("body"); QTest::newRow("root") << "/" << 200 << ""; QTest::newRow("not-found") << "/non-existent/" << 404 << ""; QTest::newRow("no-args") << "/test/" << 200 << ""; QTest::newRow("one-args") << "/test/123/" << 200 << ""; QTest::newRow("two-args") << "/test/123/delete/" << 200 << ""; QTest::newRow("three-args") << "/test/123/delete/zoo/" << 404 << ""; QTest::newRow("recurse-not-found") << "/recurse/non-existent/" << 404 << ""; QTest::newRow("recurse-index") << "/recurse/" << 200 << ""; QTest::newRow("recurse-test") << "/recurse/test/" << 200 << ""; } void tst_QDjangoUrlResolver::testRespond() { QFETCH(QString, path); QFETCH(int, err); QFETCH(QString, body); QDjangoHttpTestRequest request(QLatin1String("GET"), path); QDjangoHttpResponse *response = urlResolver->respond(request, path); QVERIFY(response); QCOMPARE(int(response->statusCode()), err); } void tst_QDjangoUrlResolver::testReverse_data() { QTest::addColumn("path"); QTest::addColumn("receiver"); QTest::addColumn("member"); QTest::addColumn("args"); QTest::addColumn("warning"); QObject *receiver = this; QTest::newRow("root") << "/" << receiver << "_q_index" << "" << ""; QTest::newRow("no-args") << "/test/" << receiver << "_q_noArgs" << "" << ""; QTest::newRow("one-arg") << "/test/123/" << receiver << "_q_oneArg" << "123" << ""; QTest::newRow("two-args") << "/test/123/delete/" << receiver << "_q_twoArgs" << "123|delete" << ""; QTest::newRow("too-few-args") << "" << receiver << "_q_oneArg" << "" << "Too few arguments for '_q_oneArg'"; QTest::newRow("too-many-args") << "" << receiver << "_q_noArgs" << "123" << "Too many arguments for '_q_noArgs'"; receiver = urlHelper; QTest::newRow("recurse-index") << "/recurse/" << receiver << "_q_index" << "" << ""; QTest::newRow("recurse-test") << "/recurse/test/" << receiver << "_q_test" << "" << ""; } void tst_QDjangoUrlResolver::testReverse() { QFETCH(QString, path); QFETCH(QObject*, receiver); QFETCH(QString, member); QFETCH(QString, args); QFETCH(QString, warning); QVariantList varArgs; if (!args.isEmpty()) { foreach (const QString &bit, args.split(QLatin1Char('|'))) varArgs << bit; } if (!warning.isEmpty()) QTest::ignoreMessage(QtWarningMsg, warning.toLatin1()); QCOMPARE(urlResolver->reverse(receiver, member.toLatin1(), varArgs), path); } QDjangoHttpResponse* tst_QDjangoUrlResolver::_q_index(const QDjangoHttpRequest &request) { Q_UNUSED(request); return new QDjangoHttpResponse; } QDjangoHttpResponse* tst_QDjangoUrlResolver::_q_noArgs(const QDjangoHttpRequest &request) { Q_UNUSED(request); return new QDjangoHttpResponse; } QDjangoHttpResponse* tst_QDjangoUrlResolver::_q_oneArg(const QDjangoHttpRequest &request, const QString &id) { Q_UNUSED(request); Q_UNUSED(id); return new QDjangoHttpResponse; } QDjangoHttpResponse* tst_QDjangoUrlResolver::_q_twoArgs(const QDjangoHttpRequest &request, const QString &id, const QString &action) { Q_UNUSED(request); Q_UNUSED(id); Q_UNUSED(action); return new QDjangoHttpResponse; } QTEST_MAIN(tst_QDjangoUrlResolver) #include "tst_qdjangourlresolver.moc" qdjango-0.6.2/tests/tests.pri000066400000000000000000000003151261212605400161600ustar00rootroot00000000000000include(../qdjango.pri) QT -= gui QT += testlib CONFIG -= app_bundle CONFIG += testcase QMAKE_RPATHDIR += $$OUT_PWD/../../../src/db $$OUT_PWD/../../../src/http INCLUDEPATH += $$PWD $$QDJANGO_INCLUDEPATH qdjango-0.6.2/tests/tests.pro000066400000000000000000000000451261212605400161660ustar00rootroot00000000000000TEMPLATE = subdirs SUBDIRS = db http qdjango-0.6.2/tests/travis/000077500000000000000000000000001261212605400156135ustar00rootroot00000000000000qdjango-0.6.2/tests/travis/build-and-test000077500000000000000000000014261261212605400203600ustar00rootroot00000000000000#!/bin/sh set -e QMAKE_ARGS="QDJANGO_PROFILE=true" case "$CONFIG" in *static) QMAKE_ARGS="$QMAKE_ARGS QDJANGO_LIBRARY_TYPE=staticlib" ;; esac # compile qmake $QMAKE_ARGS make # run tests QDJANGO_DB_DRIVER=QSQLITE QDJANGO_DB_NAME=:memory: make check QDJANGO_DB_DRIVER=QSQLITE QDJANGO_DB_NAME=/tmp/qdjango_test.db make check QDJANGO_DB_DRIVER=QMYSQL QDJANGO_DB_NAME=qdjango_test QDJANGO_DB_USER=travis make check QDJANGO_DB_DRIVER=QPSQL QDJANGO_DB_NAME=qdjango_test QDJANGO_DB_USER=postgres make check exit 0 # generate coverage report TRACEFILE=coverage.info rm -f $TRACEFILE lcov --capture --directory src -o $TRACEFILE --no-external lcov --remove $TRACEFILE \*moc_\* -o $TRACEFILE.clean mv $TRACEFILE.clean $TRACEFILE rm -rf coverage genhtml -o coverage $TRACEFILE echo "ok" qdjango-0.6.2/tests/travis/install-build-depends000077500000000000000000000006571261212605400217340ustar00rootroot00000000000000#!/bin/sh set -e if [ "$QT_SELECT" = "qt4" ]; then sudo apt-get update sudo apt-get install libqt4-dev libqt4-sql-mysql libqt4-sql-odbc libqt4-sql-psql libqt4-sql-sqlite else sudo add-apt-repository -y ppa:ubuntu-sdk-team/ppa sudo apt-get update sudo apt-get install qtbase5-dev libqt5sql5-mysql libqt5sql5-odbc libqt5sql5-psql libqt5sql5-sqlite fi sudo apt-get install lcov odbcinst libmyodbc odbc-postgresql