diff --git a/AUTHORS b/AUTHORS new file mode 100644 index 0000000..4f9f4dd --- /dev/null +++ b/AUTHORS @@ -0,0 +1,5 @@ +Jeremy Lainé + * Principal developer of QDjango. + +Mathias Hasselmann + * Support for QDjangoQuerySet iterators. diff --git a/CMakeLists.txt b/CMakeLists.txt new file mode 100644 index 0000000..fcbffac --- /dev/null +++ b/CMakeLists.txt @@ -0,0 +1,16 @@ +cmake_minimum_required(VERSION 2.6) + +# Project and version +project(QDjango) +set(QDJANGO_VERSION 0.2.0) + +find_package(Qt4 REQUIRED) +include_directories(${CMAKE_CURRENT_SOURCE_DIR}/src/db) +include_directories(${CMAKE_CURRENT_SOURCE_DIR}/src/http) +include_directories(${CMAKE_CURRENT_SOURCE_DIR}/src/script) + +add_subdirectory(src) +if(NOT QDJANGO_DONT_USE_TESTS) + add_subdirectory(tests) + add_subdirectory(examples) +endif() diff --git a/README b/README new file mode 100644 index 0000000..6de8e6f --- /dev/null +++ b/README @@ -0,0 +1,61 @@ +QDjango + +License +======= + +This program 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 3 of the License, or +(at your option) any later version. + +This program is distributed in the hope that it will be useful, +but WITHOUT ANY WARRANTY; without even the implied warranty of +MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +GNU General Public License for more details. + +You should have received a copy of the GNU Lesser General Public License +along with this program. If not, see . + +Requirements +============ + +On Debian +---------- + +$ sudo aptitude install cmake libqt4-dev libqt4-sql-sqlite + +On Mac OS X +----------- + +$ sudo port install cmake qt4-mac + +Building QDjango +================ + +$ mkdir build +$ cd build +$ cmake .. +$ make + +See platform specific notes for applicable cmake options. + +On Mac OS X +----------- + +If you are running MacOS/X and want to build specifically for i386 on an +x86_64 machine, invoke cmake as: + +$ cmake .. -DCMAKE_CXX_FLAGS="-arch i386" -DLINK_FLAGS="-arch i386" + +Cross compiling for win32 +------------------------- + +To cross compile for win32 on a Debian machine, install the libqt4-mingw32-dev +package from: + + http://dev.jerryweb.org/debian/pool/main/ + +Then invoke cmake as: + +$ cmake .. -DCMAKE_TOOLCHAIN_FILE=../cmake/mingw32.toolchain + diff --git a/cmake/mingw32.toolchain b/cmake/mingw32.toolchain new file mode 100644 index 0000000..8fc8d4b --- /dev/null +++ b/cmake/mingw32.toolchain @@ -0,0 +1,20 @@ +# specify system and cross compiler +set(CMAKE_SYSTEM_NAME Windows) +set(CMAKE_C_COMPILER i586-mingw32msvc-gcc) +set(CMAKE_CXX_COMPILER i586-mingw32msvc-g++) +set(CMAKE_RC_COMPILER i586-mingw32msvc-windres) +set(CMAKE_RC_COMPILE_OBJECT " --input-format rc --output-format coff -i -o ") + +# where is the target environment +set(CMAKE_FIND_ROOT_PATH /usr/i586-mingw32msvc) + +# search for programs in the build host directories +set(CMAKE_FIND_ROOT_PATH_MODE_PROGRAM NEVER) +# for libraries and headers in the target directories +set(CMAKE_FIND_ROOT_PATH_MODE_LIBRARY ONLY) +set(CMAKE_FIND_ROOT_PATH_MODE_INCLUDE ONLY) + +# Qt 4 +set(QT_HEADERS_DIR ${CMAKE_FIND_ROOT_PATH}/include/qt4) +set(QT_LIBRARY_DIR ${CMAKE_FIND_ROOT_PATH}/lib) +set(QT_PLUGINS_DIR ${CMAKE_FIND_ROOT_PATH}/lib/qt4) diff --git a/doc/Doxyfile b/doc/Doxyfile new file mode 100644 index 0000000..f88b3b5 --- /dev/null +++ b/doc/Doxyfile @@ -0,0 +1,1551 @@ +# 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 models.doc queries.doc scripting.doc ../src/db ../src/http ../src/script + +# 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 = *_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 = YES + +# 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 diff --git a/doc/database.doc b/doc/database.doc new file mode 100644 index 0000000..25f04d8 --- /dev/null +++ b/doc/database.doc @@ -0,0 +1,63 @@ +/* + * Copyright (C) 2010-2012 Jeremy Lainé + * Contact: http://code.google.com/p/qdjango/ + * + * This file is part of the QDjango Library. + * + * This program 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 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU Lesser General Public License + * along with this program. If not, see . + */ + +/*! \page database Database configuration + +QDjango relies on the QtSql module +for database access, which supports a wide array of database drivers. + +\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. + +*/ diff --git a/doc/models.doc b/doc/models.doc new file mode 100644 index 0000000..5fd579a --- /dev/null +++ b/doc/models.doc @@ -0,0 +1,135 @@ +/* + * Copyright (C) 2010-2012 Jeremy Lainé + * Contact: http://code.google.com/p/qdjango/ + * + * This file is part of the QDjango Library. + * + * This program 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 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU Lesser General Public License + * along with this program. If not, see . + */ + +/*! \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 + +*/ diff --git a/doc/queries.doc b/doc/queries.doc new file mode 100644 index 0000000..bef65de --- /dev/null +++ b/doc/queries.doc @@ -0,0 +1,112 @@ +/* + * Copyright (C) 2010-2012 Jeremy Lainé + * Contact: http://code.google.com/p/qdjango/ + * + * This file is part of the QDjango Library. + * + * This program 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 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU Lesser General Public License + * along with this program. If not, see . + */ + +/*! \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 + +*/ diff --git a/doc/scripting.doc b/doc/scripting.doc new file mode 100644 index 0000000..10b0ebd --- /dev/null +++ b/doc/scripting.doc @@ -0,0 +1,73 @@ +/* + * Copyright (C) 2010-2012 Jeremy Lainé + * Contact: http://code.google.com/p/qdjango/ + * + * This file is part of the QDjango Library. + * + * This program 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 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU Lesser General Public License + * along with this program. If not, see . + */ + +/*! \page scripting Scripting models + +The QDjangoScript class makes it easy to access your models from QtScript. + +\section making-scriptable Making your models scriptable + +You can register a model with a QScriptEngine instance as follows: + +\code +#include +#include + +Q_DECLARE_METATYPE(QDjangoQuerySet) + +QScriptEngine *engine = new QScriptEngine; +QDjangoScript::registerWhere(engine); +QDjangoScript::registerModel(engine); +\endcode + +\section scripting-models Using your models from a script + +Because QDjango makes use of Qt's property system, all model fields can +automatically be accessed from QtScript. +For instance if you declared a \c User model, you can run the following code: + +\code +// create a user instance and save it to database +user = new User(); +user.username = "someuser"; +user.password = "somepassword"; +user.save(); + +// remove the user from database +user.remove(); +\endcode + +You can also perform database queries: + +\code +// filter users whose username is "foouser" and password is "foopass" +qs = User.objects.filter({'username': 'foouser', 'password': 'foopass'}); + +// iterate over the results +for (var i = 0; i < qs.size(); i++) { + user = qs.at(i); + print("found " + user.username); +} + +// remove all matching users from database +qs.remove(); +\endcode + +*/ diff --git a/examples/CMakeLists.txt b/examples/CMakeLists.txt new file mode 100644 index 0000000..d2dea5c --- /dev/null +++ b/examples/CMakeLists.txt @@ -0,0 +1,2 @@ +add_subdirectory(http-server) +add_subdirectory(script-console) diff --git a/examples/examples.pro b/examples/examples.pro new file mode 100644 index 0000000..024c1b7 --- /dev/null +++ b/examples/examples.pro @@ -0,0 +1,2 @@ +TEMPLATE = subdirs +SUBDIRS = http-server script-console diff --git a/examples/http-server/CMakeLists.txt b/examples/http-server/CMakeLists.txt new file mode 100644 index 0000000..2a0c26d --- /dev/null +++ b/examples/http-server/CMakeLists.txt @@ -0,0 +1,8 @@ +set(QT_DONT_USE_QTGUI 1) +set(QT_USE_QTNETWORK 1) +set(QT_USE_QTSQL 1) +include(${QT_USE_FILE}) + +qt4_add_resources(RCC_SOURCES http-server.qrc) +add_executable(qdjango-http-server http-server.cpp ${RCC_SOURCES}) +target_link_libraries(qdjango-http-server qdjango-http qdjango-models) diff --git a/examples/http-server/base.css b/examples/http-server/base.css new file mode 100644 index 0000000..6adf642 --- /dev/null +++ b/examples/http-server/base.css @@ -0,0 +1,87 @@ +body { + 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; +} diff --git a/examples/http-server/base.html b/examples/http-server/base.html new file mode 100644 index 0000000..c7a4735 --- /dev/null +++ b/examples/http-server/base.html @@ -0,0 +1,2 @@ +{% include "header.html" %} +{% include "footer.html" %} diff --git a/examples/http-server/change_form.html b/examples/http-server/change_form.html new file mode 100644 index 0000000..74eee7d --- /dev/null +++ b/examples/http-server/change_form.html @@ -0,0 +1,16 @@ +{% include "header.html" %} +
+
+{% for field in field_list %} +
+ + +
+{% endfor %} +
+
+ Delete + +
+
+{% include "footer.html" %} diff --git a/examples/http-server/change_list.html b/examples/http-server/change_list.html new file mode 100644 index 0000000..93c0303 --- /dev/null +++ b/examples/http-server/change_list.html @@ -0,0 +1,28 @@ +{% include "header.html" %} + + +
+ + +{% for field in field_list %} + +{% endfor %} + +{% for object in object_list %} + +{% if model_name == "user" %} + + + + +{% endif %} +{% if model_name == "group" %} + +{% endif %} + +{% endfor %} +
{{ field.name }}
{{ object.username }}{{ object.email }}{{ object.first_name }}{{ object.last_name }}{{ object.name }}
+
+{% include "footer.html" %} diff --git a/examples/http-server/delete_confirmation.html b/examples/http-server/delete_confirmation.html new file mode 100644 index 0000000..ac3bddd --- /dev/null +++ b/examples/http-server/delete_confirmation.html @@ -0,0 +1,8 @@ +{% include "header.html" %} +

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

+
+ +
+{% include "footer.html" %} diff --git a/examples/http-server/footer.html b/examples/http-server/footer.html new file mode 100644 index 0000000..9943ff0 --- /dev/null +++ b/examples/http-server/footer.html @@ -0,0 +1,3 @@ + + + diff --git a/examples/http-server/header.html b/examples/http-server/header.html new file mode 100644 index 0000000..350c740 --- /dev/null +++ b/examples/http-server/header.html @@ -0,0 +1,30 @@ + + + + + {{ title }} | Test application +{% comment %} +test +{% endcomment %} + + +
+ +
+ +
+

{{ title }}

diff --git a/examples/http-server/http-server.cpp b/examples/http-server/http-server.cpp new file mode 100644 index 0000000..0f9d9b2 --- /dev/null +++ b/examples/http-server/http-server.cpp @@ -0,0 +1,468 @@ +/* + * Copyright (C) 2010-2012 Jeremy Lainé + * Contact: http://code.google.com/p/qdjango/ + * + * This file is part of the QDjango Library. + * + * This program 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 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU Lesser General Public License + * along with this program. If not, see . + */ + +#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 "../../tests/auth-models.h" + +static QVariantMap dump(const QObject *object) +{ + 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; +} + +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(":/" + 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; +} + +template +class ModelController : public QDjangoHttpController +{ +public: + ModelController(); + QDjangoHttpResponse* respondToRequest(const QDjangoHttpRequest &request); + void setChangeFields(const QList fields) { + m_changeFields = fields; + } + void setListFields(const QList fields) { + m_listFields = fields; + } + +private: + QDjangoHttpResponse* changeList(const QDjangoHttpRequest &request); + QDjangoHttpResponse* changeForm(const QDjangoHttpRequest &request, int objectId); + QDjangoHttpResponse* deleteForm(const QDjangoHttpRequest &request, int objectId); + + QList m_changeFields; + QList m_listFields; + QString m_modelName; + QString m_prefix; +}; + +template +ModelController::ModelController() +{ + m_modelName = QString::fromLatin1(T::staticMetaObject.className()).toLower(); + m_prefix = "/" + m_modelName; + + // initialise fields + const QMetaObject *metaObject = &T::staticMetaObject; + QVariantList fieldList; + for (int i = metaObject->propertyOffset(); i < metaObject->propertyCount(); ++i) { + const char *key = metaObject->property(i).name(); + m_changeFields << key; + } +} + +template +QDjangoHttpResponse* ModelController::changeForm(const QDjangoHttpRequest &request, int objectId) +{ + T *original = 0; + if (objectId) { + original = QDjangoQuerySet().get(QDjangoWhere("pk", QDjangoWhere::Equals, objectId)); + if (!original) + return serveNotFound(request); + } + + // collect fields + QVariantList fieldList; + foreach (const QByteArray &key, m_changeFields) { + QVariantMap props; + props.insert("key", key); + props.insert("name", QByteArray(key).replace("_", " ")); + if (original) + props.insert("value", original->property(key)); + fieldList << props; + } + + if (request.method() == "POST") { + QUrl url; + url.setEncodedQuery(request.body()); + + if (original) { + foreach (const QByteArray &key, m_changeFields) + original->setProperty(key, url.queryItemValue(key)); + original->save(); + } else { + T obj; + foreach (const QByteArray &key, m_changeFields) + obj.setProperty(key, url.queryItemValue(key)); + obj.save(); + } + return serveRedirect(request, QUrl(m_prefix + "/")); + } else { + QVariantMap context; + context.insert("model_name", m_modelName); + context.insert("field_list", fieldList); + if (original) { + context.insert("original", dump(original)); + context.insert("title", QString("Change %1").arg(m_modelName)); + } else { + context.insert("title", QString("Add %1").arg(m_modelName)); + } + return renderToResponse(request, ":/change_form.html", context); + } +} + +template +QDjangoHttpResponse* ModelController::changeList(const QDjangoHttpRequest &request) +{ + QDjangoQuerySet objects; + QVariantList objectList; + foreach (const T &obj, objects) + objectList << dump(&obj); + + QVariantList fieldList; + foreach (const QByteArray &key, m_listFields) { + QVariantMap props; + props.insert("key", key); + props.insert("name", QByteArray(key).replace("_", " ")); + fieldList << props; + } + + QVariantMap context; + context.insert("title", QString("Select %1 to change").arg(m_modelName)); + context.insert("add_link", QString("Add %1").arg(m_modelName)); + context.insert("model_name", m_modelName); + context.insert("field_list", fieldList); + context.insert("object_list", objectList); + return renderToResponse(request, ":/change_list.html", context); +} + +template +QDjangoHttpResponse* ModelController::deleteForm(const QDjangoHttpRequest &request, int objectId) +{ + T *original = QDjangoQuerySet().get(QDjangoWhere("pk", QDjangoWhere::Equals, objectId)); + if (!original) + return serveNotFound(request); + + if (request.method() == "POST") { + original->remove(); + return serveRedirect(request, QUrl(m_prefix + "/")); + } else { + QVariantMap context; + context.insert("model_name", m_modelName); + context.insert("original", dump(original)); + context.insert("title", "Are you sure?"); + return renderToResponse(request, ":/delete_confirmation.html", context); + } +} + +template +QDjangoHttpResponse* ModelController::respondToRequest(const QDjangoHttpRequest &request) +{ + QRegExp changeRx("/([0-9]+)/"); + QRegExp deleteRx("/([0-9]+)/delete/"); + + const QString path = request.path().mid(m_prefix.size()); + if (path == "/") { + return changeList(request); + } else if (path == "/add/") { + return changeForm(request, 0); + } else if (changeRx.exactMatch(path)) { + return changeForm(request, changeRx.cap(1).toInt()); + } else if (deleteRx.exactMatch(path)) { + return deleteForm(request, deleteRx.cap(1).toInt()); + } + return serveNotFound(request); +} + +class RedirectController : public QDjangoHttpController +{ +public: + RedirectController(); + QDjangoHttpResponse* respondToRequest(const QDjangoHttpRequest &request); + +private: + ModelController groupController; + ModelController userController; +}; + +RedirectController::RedirectController() +{ + 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(); + + userController.setListFields(QList() << "username" << "email" << "first_name" << "last_name"); + groupController.setListFields(QList() << "name"); +} + +QDjangoHttpResponse* RedirectController::respondToRequest(const QDjangoHttpRequest &request) +{ + const QString path = request.path(); + if (path == "/") { + QVariantMap context; + context.insert("model_list", QStringList() << "group" << "user"); + context.insert("title", "Administration"); + return renderToResponse(request, ":/index.html", context); + } else if (path == "/large/") { + QDjangoHttpResponse *response = new QDjangoHttpResponse; + response->setHeader("Content-Type", "text/plain"); + const QByteArray line("Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.\n"); + QByteArray data; + for (int i = 0; i < 1000; ++i) { + data += line; + } + response->setBody(data); + return response; + } else if (request.path() == "/media/css/base.css") { + return serveStatic(request, ":/base.css"); + } else if (request.path().startsWith("/group/")) { + return groupController.respondToRequest(request); + } else if (request.path().startsWith("/user/")) { + return userController.respondToRequest(request); + } + return serveNotFound(request); +} + +void usage() +{ + fprintf(stderr, "Usage: command [options]\n\n"); + fprintf(stderr, "Available commands:\n"); + fprintf(stderr, "runfcgi\n"); + fprintf(stderr, "runserver\n"); +} + +int main(int argc, char* argv[]) +{ + QCoreApplication app(argc, argv); + RedirectController controller; + + const quint16 port = 8000; + + if (argc < 2) { + usage(); + return EXIT_FAILURE; + } + + if (!strcmp(argv[1], "runfcgi")) { + QDjangoFastCgiServer *server = new QDjangoFastCgiServer; + server->setController(&controller); + 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; + server->setController(&controller); + 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(); +} + diff --git a/examples/http-server/http-server.pro b/examples/http-server/http-server.pro new file mode 100644 index 0000000..8f6584d --- /dev/null +++ b/examples/http-server/http-server.pro @@ -0,0 +1,15 @@ +include(../../qdjango.pri) + +QT += network sql + +TARGET = qdjango-http-server + +INCLUDEPATH += \ + ../../src/db \ + ../../src/http +LIBS += \ + -L../../src/db -lqdjango-db \ + -L../../src/http -lqdjango-http +RESOURCES += http-server.qrc +HEADERS += ../../tests/auth-models.h +SOURCES += http-server.cpp ../../tests/auth-models.cpp diff --git a/examples/http-server/http-server.qrc b/examples/http-server/http-server.qrc new file mode 100644 index 0000000..bce4465 --- /dev/null +++ b/examples/http-server/http-server.qrc @@ -0,0 +1,12 @@ + + + + base.css + change_form.html + change_list.html + delete_confirmation.html + footer.html + header.html + index.html + + diff --git a/examples/http-server/index.html b/examples/http-server/index.html new file mode 100644 index 0000000..152e7a7 --- /dev/null +++ b/examples/http-server/index.html @@ -0,0 +1,17 @@ +{% include "header.html" %} +
+ + +{% for model in model_list %} + + + + +{% endfor %} + +
{{ model }} + Add + Change +
+
+{% include "footer.html" %} diff --git a/examples/script-console/CMakeLists.txt b/examples/script-console/CMakeLists.txt new file mode 100644 index 0000000..bd1bf54 --- /dev/null +++ b/examples/script-console/CMakeLists.txt @@ -0,0 +1,7 @@ +set(QT_DONT_USE_QTGUI 1) +set(QT_USE_QTSCRIPT 1) +set(QT_USE_QTSQL 1) +include(${QT_USE_FILE}) + +add_executable(qdjango-script-console script-console.cpp) +target_link_libraries(qdjango-script-console qdjango-models qdjango-script) diff --git a/examples/script-console/script-console.cpp b/examples/script-console/script-console.cpp new file mode 100644 index 0000000..7098adc --- /dev/null +++ b/examples/script-console/script-console.cpp @@ -0,0 +1,201 @@ +/* + * Copyright (C) 2010-2012 Jeremy Lainé + * Contact: http://code.google.com/p/qdjango/ + * + * This file is part of the QDjango Library. + * + * This program 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 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU Lesser General Public License + * along with this program. If not, see . + */ + +#include + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +#include "QDjango.h" +#include "QDjangoScript.h" +#include "../../tests/auth-models.h" + +static bool wantsToQuit; + +Q_DECLARE_METATYPE(QDjangoQuerySet) +Q_DECLARE_METATYPE(QDjangoQuerySet) +Q_DECLARE_METATYPE(QDjangoQuerySet) + +static QScriptValue qtscript_dir(QScriptContext *ctx, QScriptEngine *eng) +{ + QObject *obj = ctx->argument(0).toQObject(); + if (obj) + { + const QMetaObject* meta = obj->metaObject(); + for(int i = meta->propertyOffset(); i < meta->propertyCount(); ++i) + qDebug() << meta->property(i).name(); + } + return eng->undefinedValue(); +} + +static QScriptValue qtscript_load(QScriptContext *ctx, QScriptEngine *eng) +{ + QString name = ctx->argument(0).toString(); + eng->importExtension(name); + return eng->undefinedValue(); +} + +static QScriptValue qtscript_quit(QScriptContext *ctx, QScriptEngine *eng) +{ + Q_UNUSED(ctx); + wantsToQuit = true; + return eng->undefinedValue(); +} + +static QScriptValue qtscript_syncdb(QScriptContext *ctx, QScriptEngine *eng) +{ + Q_UNUSED(ctx); + QDjango::createTables(); + return eng->undefinedValue(); +} + +static void interactive(QScriptEngine *eng) +{ + QScriptValue global = eng->globalObject(); + if (!global.property(QLatin1String("dir")).isValid()) + global.setProperty(QLatin1String("dir"), eng->newFunction(qtscript_dir)); + if (!global.property(QLatin1String("load")).isValid()) + global.setProperty(QLatin1String("load"), eng->newFunction(qtscript_load)); + if (!global.property(QLatin1String("quit")).isValid()) + global.setProperty(QLatin1String("quit"), eng->newFunction(qtscript_quit)); + if (!global.property(QLatin1String("syncdb")).isValid()) + global.setProperty(QLatin1String("syncdb"), eng->newFunction(qtscript_syncdb)); + wantsToQuit = false; + + QTextStream qin(stdin, QIODevice::ReadOnly); + + const char *qscript_prompt = "qdjango> "; + const char *dot_prompt = ".... "; + const char *prompt = qscript_prompt; + + QString code; + + printf("Commands:\n" + "\tdir(obj) : print the object's properties\n" + "\tload() : loads a QtScript extension\n" + "\tquit() : exits console\n" + "\tsyncdb() : creates database tables\n"); + + forever { + QString line; + + printf("%s", prompt); + fflush(stdout); + + line = qin.readLine(); + if (line.isNull()) + break; + + code += line; + code += QLatin1Char('\n'); + + if (line.trimmed().isEmpty()) { + continue; + + } else if (! eng->canEvaluate(code)) { + prompt = dot_prompt; + + } else { + QScriptValue result = eng->evaluate(code, QLatin1String("typein")); + + code.clear(); + prompt = qscript_prompt; + + if (! result.isUndefined()) + fprintf(stderr, "%s\n", qPrintable(result.toString())); + + if (wantsToQuit) + break; + } + } +} + +void usage() +{ + fprintf(stderr, "Usage: qdjango-console [options]\n\n"); + fprintf(stderr, "Options:\n"); + fprintf(stderr, "-d use \n"); + fprintf(stderr, "-p add to plugins search path\n"); +} + +int main(int argc, char *argv[]) +{ + QString databaseName(":memory:"); + + /* Create application */ + QCoreApplication app(argc, argv); + + /* Parse command line arguments */ + for (int i = 1; i < argc; i++) + { + if (!strcmp(argv[i], "-h")) + { + usage(); + return EXIT_SUCCESS; + } else if (!strcmp(argv[i], "-d")) { + if (i == argc - 1 || !strlen(argv[i+1]) || argv[i+1][0] == '-') + { + fprintf(stderr, "Option -d requires an argument\n"); + usage(); + return EXIT_FAILURE; + } + databaseName = QString::fromLocal8Bit(argv[++i]); + } else if (!strcmp(argv[i], "-p")) { + if (i == argc - 1 || !strlen(argv[i+1]) || argv[i+1][0] == '-') + { + fprintf(stderr, "Option -p requires an argument\n"); + usage(); + return EXIT_FAILURE; + } + app.setLibraryPaths(app.libraryPaths() << QString::fromLocal8Bit(argv[++i])); + } + } + + /* Open database */ + QSqlDatabase db = QSqlDatabase::addDatabase("QSQLITE"); + db.setDatabaseName(databaseName); + if (!db.open()) + { + fprintf(stderr, "Could not access database '%s'\n", databaseName.toLocal8Bit().constData()); + return EXIT_FAILURE; + } + QDjango::setDatabase(db); + + /* Run interactive shell */ + QScriptEngine *engine = new QScriptEngine(); + QDjangoScript::registerWhere(engine); + QDjangoScript::registerModel(engine); + QDjangoScript::registerModel(engine); + QDjangoScript::registerModel(engine); + + qDebug() << "Available extensions: " << engine->availableExtensions(); + interactive(engine); + + return EXIT_SUCCESS; +} + diff --git a/examples/script-console/script-console.pro b/examples/script-console/script-console.pro new file mode 100644 index 0000000..19c9eb6 --- /dev/null +++ b/examples/script-console/script-console.pro @@ -0,0 +1,14 @@ +include(../../qdjango.pri) + +QT += script sql + +TARGET = qdjango-script-console + +INCLUDEPATH += \ + ../../src/db \ + ../../src/script +LIBS += \ + -L../../src/db -lqdjango-db \ + -L../../src/script -lqdjango-script +HEADERS += ../../tests/auth-models.h +SOURCES += script-console.cpp ../../tests/auth-models.cpp diff --git a/qdjango.pri b/qdjango.pri new file mode 100644 index 0000000..3fd3547 --- /dev/null +++ b/qdjango.pri @@ -0,0 +1,2 @@ +# Common definitions +QDJANGO_VERSION=0.1.0 diff --git a/qdjango.pro b/qdjango.pro new file mode 100644 index 0000000..e628d65 --- /dev/null +++ b/qdjango.pro @@ -0,0 +1,12 @@ +include(qdjango.pri) + +TEMPLATE = subdirs + +SUBDIRS = src + +android { +} else { + SUBDIR += tests examples +} + +CONFIG += ordered diff --git a/src/CMakeLists.txt b/src/CMakeLists.txt new file mode 100644 index 0000000..548e3d4 --- /dev/null +++ b/src/CMakeLists.txt @@ -0,0 +1,21 @@ +set(QT_DONT_USE_QTGUI 1) +set(QT_USE_QTNETWORK 1) +set(QT_USE_QTSCRIPT 1) +set(QT_USE_QTSQL 1) +include(${QT_USE_FILE}) + +# Needed for plugin support +if(UNIX) + if(NOT APPLE) + add_definitions(-fPIC) + endif(NOT APPLE) +endif(UNIX) + +# Until binary stability is reached, build static libraries +if(NOT QDJANGO_LIBRARY_TYPE) + set(QDJANGO_LIBRARY_TYPE SHARED) +endif() + +add_subdirectory(db) +add_subdirectory(http) +add_subdirectory(script) diff --git a/src/db/CMakeLists.txt b/src/db/CMakeLists.txt new file mode 100644 index 0000000..fff5542 --- /dev/null +++ b/src/db/CMakeLists.txt @@ -0,0 +1,38 @@ +set(QT_DONT_USE_QTGUI 1) +set(QT_USE_QTSQL 1) +include(${QT_USE_FILE}) + +# Optional debugging +if(QDJANGO_DEBUG_SQL) + add_definitions(-DQDJANGO_DEBUG_SQL=1) +endif(QDJANGO_DEBUG_SQL) + +# QDjango database library +set(HEADERS + QDjango.h + QDjango_p.h + QDjangoModel.h + QDjangoQuerySet.h + QDjangoQuerySet_p.h + QDjangoWhere.h) +set(SOURCES + QDjango.cpp + QDjangoModel.cpp + QDjangoQuerySet.cpp + QDjangoWhere.cpp) + +set(MOC_HEADERS + QDjango_p.h + QDjangoModel.h) +qt4_wrap_cpp(MOC_SOURCES ${MOC_HEADERS}) +add_library(qdjango-db ${QDJANGO_LIBRARY_TYPE} ${SOURCES} ${MOC_SOURCES}) +set_target_properties(qdjango-db PROPERTIES SOVERSION 0) +target_link_libraries(qdjango-db ${QT_QTSQL_LIBRARY} ${QT_QTCORE_LIBRARY}) + +if(NOT QDJANGO_DONT_INSTALL) + install(FILES ${HEADERS} DESTINATION include/qdjango/db) + install(TARGETS qdjango-db + RUNTIME DESTINATION bin + LIBRARY DESTINATION lib + ARCHIVE DESTINATION lib) +endif() diff --git a/src/db/QDjango.cpp b/src/db/QDjango.cpp new file mode 100644 index 0000000..d585b39 --- /dev/null +++ b/src/db/QDjango.cpp @@ -0,0 +1,654 @@ +/* + * Copyright (C) 2010-2012 Jeremy Lainé + * Contact: http://code.google.com/p/qdjango/ + * + * This file is part of the QDjango Library. + * + * This program 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 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU Lesser General Public License + * along with this program. If not, see . + */ + +#include +#include +#include +#include +#include +#include +#include +#include + +#include "QDjango.h" +#include "QDjangoQuerySet_p.h" +#include "QDjangoModel.h" + +static const char *connectionPrefix = "_qdjango_"; + +QMap globalMetaModels = QMap(); +static QDjangoDatabase *globalDatabase = 0; + +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; +} + +/*! \mainpage + * + * QDjango is a simple yet powerful Object Relation Mapper (ORM) built + * on top of the Qt library. Where possible it tries to follow django's + * ORM API, hence its name. + * + * \sa QDjango + * \sa QDjangoModel + * \sa QDjangoWhere + * \sa QDjangoQuerySet + */ + + +/** 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() +{ + Q_ASSERT(globalDatabase != 0); + QThread *thread = QThread::currentThread(); + + // if we are in the main thread, return reference connection + 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(); + 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) +{ + if (database.driverName() != QLatin1String("QSQLITE") && + database.driverName() != QLatin1String("QSQLITE2") && + database.driverName() != QLatin1String("QMYSQL") && + database.driverName() != QLatin1String("QPSQL")) + { + qWarning() << "Unsupported database driver" << database.driverName(); + } + if (!globalDatabase) + { + globalDatabase = new QDjangoDatabase(); + qAddPostRoutine(closeDatabase); + } + globalDatabase->reference = database; +} + +/** Creates the database tables for all registered models. + */ +bool QDjango::createTables() +{ + bool ret = true; + foreach (const QString &key, globalMetaModels.keys()) + if (!globalMetaModels[key].createTable()) + ret = false; + return ret; +} + +/** Drops the database tables for all registered models. + */ +bool QDjango::dropTables() +{ + bool ret = true; + foreach (const QString &key, globalMetaModels.keys()) + if (!globalMetaModels[key].dropTable()) + ret = false; + return ret; +} + +/** Returns the QDjangoMetaModel with the given name. + * + * \param name + */ +QDjangoMetaModel QDjango::metaModel(const QString &name) +{ + return globalMetaModels.value(name); +} + +QDjangoMetaModel QDjango::registerModel(const QObject *model) +{ + const QString name = model->metaObject()->className(); + if (!globalMetaModels.contains(name)) + globalMetaModels.insert(name, QDjangoMetaModel(model)); + return globalMetaModels[name]; +} + +/** Returns the empty SQL limit clause. + */ +QString QDjango::noLimitSql() +{ + const QString driverName = QDjango::database().driverName(); + if (driverName == QLatin1String("QSQLITE") || + driverName == QLatin1String("QSQLITE2")) + return QLatin1String(" LIMIT -1"); + else if (driverName == QLatin1String("QMYSQL")) + // 2^64 - 1, as recommended by the MySQL documentation + return QLatin1String(" LIMIT 18446744073709551615"); + else + return QString(); +} + +QDjangoMetaField::QDjangoMetaField() + : autoIncrement(false), + index(false), + maxLength(0), + unique(false) +{ +} + +static QMap parseOptions(const char *value) +{ + QMap options; + QStringList items = QString::fromUtf8(value).split(' '); + foreach (const QString &item, items) { + QStringList assign = item.split('='); + if (assign.size() == 2) { + options[assign[0].toLower()] = assign[1]; + } else { + qWarning() << "Could not parse option" << item; + } + } + return options; +} + +/** Constructs a new QDjangoMetaModel by inspecting the given model instance. + * + * \param model + */ +QDjangoMetaModel::QDjangoMetaModel(const QObject *model) +{ + if (!model) + return; + + const QMetaObject* meta = model->metaObject(); + m_table = QString(meta->className()).toLower().toLatin1(); + + // 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() == "db_table") + m_table = option.value(); + } + } + + const int count = meta->propertyCount(); + for(int i = QObject::staticMetaObject.propertyCount(); i < count; ++i) + { + QString typeName = meta->property(i).typeName(); + if (!qstrcmp(meta->property(i).name(), "pk")) + continue; + + // parse field options + bool autoIncrementOption = false; + bool dbIndexOption = false; + bool ignoreFieldOption = false; + int maxLengthOption = 0; + bool primaryKeyOption = false; + bool uniqueOption = false; + 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 value = option.value(); + if (option.key() == "auto_increment") + autoIncrementOption = (value.toLower() == "true" || value == "1"); + else if (option.key() == "db_index") + dbIndexOption = (value.toLower() == "true" || value == "1"); + else if (option.key() == "ignore_field") + ignoreFieldOption = (value.toLower() == "true" || value == "1"); + else if (option.key() == "max_length") + maxLengthOption = value.toInt(); + else if (option.key() == "primary_key") + primaryKeyOption = (value.toLower() == "true" || value == "1"); + else if (option.key() == "unique") + uniqueOption = (value.toLower() == "true" || value == "1"); + } + } + + // ignore field + if (ignoreFieldOption) + continue; + + // foreign field + if (typeName.endsWith("*")) + { + const QByteArray fkName = meta->property(i).name(); + const QString fkModel = typeName.left(typeName.size() - 1); + m_foreignFields.insert(fkName, fkModel); + + QDjangoMetaField field; + field.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.type = QVariant::Int; + field.foreignModel = fkModel; + field.index = true; + m_localFields << field; + continue; + } + + // local field + QDjangoMetaField field; + field.index = dbIndexOption; + field.name = meta->property(i).name(); + field.type = meta->property(i).type(); + field.maxLength = maxLengthOption; + if (primaryKeyOption) { + field.autoIncrement = autoIncrementOption; + field.unique = true; + m_primaryKey = field.name; + } else if (uniqueOption) { + field.unique = true; + } + + m_localFields << field; + } + + // automatic primary key + if (m_primaryKey.isEmpty()) { + QDjangoMetaField field; + field.name = "id"; + field.type = QVariant::Int; + field.autoIncrement = true; + field.unique = true; + m_localFields.prepend(field); + m_primaryKey = field.name; + } + +} + +/** Creates the database table for this QDjangoMetaModel. + */ +bool QDjangoMetaModel::createTable() const +{ + QSqlDatabase db = QDjango::database(); + QSqlDriver *driver = db.driver(); + const QString driverName = db.driverName(); + + QStringList propSql; + const QString quotedTable = db.driver()->escapeIdentifier(m_table, QSqlDriver::TableName); + foreach (const QDjangoMetaField &field, m_localFields) + { + QString fieldSql = driver->escapeIdentifier(field.name, QSqlDriver::FieldName); + if (field.type == QVariant::Bool) + fieldSql += " BOOLEAN"; + else if (field.type == QVariant::ByteArray) + { + if (driverName == QLatin1String("QPSQL")) + fieldSql += " BYTEA"; + else { + fieldSql += " BLOB"; + if (field.maxLength > 0) + fieldSql += QString("(%1)").arg(field.maxLength); + } + } + else if (field.type == QVariant::Date) + fieldSql += " DATE"; + else if (field.type == QVariant::DateTime) + if (driverName == QLatin1String("QPSQL")) + fieldSql += " TIMESTAMP"; + else + fieldSql += " DATETIME"; + else if (field.type == QVariant::Double) + fieldSql += " REAL"; + else if (field.type == QVariant::Int) + fieldSql += " INTEGER"; + else if (field.type == QVariant::LongLong) + fieldSql += " BIGINT"; + else if (field.type == QVariant::String) + { + if (field.maxLength > 0) + fieldSql += QString(" VARCHAR(%1)").arg(field.maxLength); + else + fieldSql += " TEXT"; + } + else if (field.type == QVariant::Time) + fieldSql += " TIME"; + else { + qWarning() << "Unhandled type" << field.type << "for property" << field.name; + continue; + } + + // primary key + if (field.name == m_primaryKey) + fieldSql += " PRIMARY KEY"; + + // auto-increment is backend specific + if (field.autoIncrement) { + if (driverName == QLatin1String("QSQLITE") || + driverName == QLatin1String("QSQLITE2")) + fieldSql += QLatin1String(" AUTOINCREMENT"); + else if (driverName == QLatin1String("QMYSQL")) + fieldSql += QLatin1String(" AUTO_INCREMENT"); + else if (driverName == QLatin1String("QPSQL")) + fieldSql = driver->escapeIdentifier(field.name, QSqlDriver::FieldName) + " SERIAL PRIMARY KEY"; + } + + // foreign key + if (!field.foreignModel.isEmpty()) + { + const QDjangoMetaModel foreignMeta = QDjango::metaModel(field.foreignModel); + fieldSql += QString(" REFERENCES %1 (%2)").arg( + driver->escapeIdentifier(foreignMeta.m_table, QSqlDriver::TableName), + driver->escapeIdentifier(foreignMeta.m_primaryKey, QSqlDriver::FieldName)); + } + propSql << fieldSql; + } + + // create table + QDjangoQuery createQuery(db); + if (!createQuery.exec(QString("CREATE TABLE %1 (%2)").arg( + quotedTable, + propSql.join(", ")))) + return false; + + // create indices + foreach (const QDjangoMetaField &field, m_localFields) { + if (field.index && !field.unique) { + const QString indexName = m_table + "_" + QString::fromLatin1(field.name); + if (!createQuery.exec(QString("CREATE INDEX %1 ON %2 (%3)").arg( + // FIXME : how should we escape an index name? + driver->escapeIdentifier(indexName, QSqlDriver::FieldName), + quotedTable, + driver->escapeIdentifier(field.name, QSqlDriver::FieldName)))) + return false; + } + } + + return true; +} + +/** Drops the database table for this QDjangoMetaModel. + */ +bool QDjangoMetaModel::dropTable() const +{ + QSqlDatabase db = QDjango::database(); + + QDjangoQuery query(db); + return query.exec(QString("DROP TABLE %1").arg( + db.driver()->escapeIdentifier(m_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 +{ + const QByteArray prop(name); + QObject *foreign = model->property(prop + "_ptr").value(); + if (!foreign) + return 0; + + // if the foreign object was not loaded yet, do it now + const QString foreignClass = m_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("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 + * + * \note The \c model will take ownership of the given \c value. + */ +void QDjangoMetaModel::setForeignKey(QObject *model, const char *name, QObject *value) const +{ + const QByteArray prop(name); + QObject *old = model->property(prop + "_ptr").value(); + if (old == value) + return; + if (old) + delete old; + + // store the new pointer and update the foreign key + model->setProperty(prop + "_ptr", qVariantFromValue(value)); + if (value) + { + const QDjangoMetaModel foreignMeta = QDjango::metaModel(m_foreignFields[prop]); + model->setProperty(prop + "_id", value->property(foreignMeta.primaryKey())); + value->setParent(model); + } else { + model->setProperty(prop + "_id", QVariant()); + } +} + + +/** Returns true if the current QDjangoMetaModel is valid, false otherwise. + */ +bool QDjangoMetaModel::isValid() const +{ + return !m_table.isEmpty() && !m_primaryKey.isEmpty(); +} + +/** Loads the given properties into a model instance. + * + * \param model + * \param properties + * \param pos + */ +void QDjangoMetaModel::load(QObject *model, const QVariantList &properties, int &pos) const +{ + // process local fields + foreach (const QDjangoMetaField &field, m_localFields) + model->setProperty(field.name, properties.at(pos++)); + + // process foreign fields + if (pos >= properties.size()) + return; + foreach (const QByteArray &fkName, m_foreignFields.keys()) + { + QObject *object = model->property(fkName + "_ptr").value(); + if (object) + { + const QDjangoMetaModel foreignMeta = QDjango::metaModel(m_foreignFields[fkName]); + foreignMeta.load(object, properties, pos); + } + } +} + +/** Returns the foreign field mapping. + */ +QMap QDjangoMetaModel::foreignFields() const +{ + return m_foreignFields; +} + +/** Returns the list of local fields. + */ +QList QDjangoMetaModel::localFields() const +{ + return m_localFields; +} + +/** Returns the name of the primary key for the current QDjangoMetaModel. + */ +QByteArray QDjangoMetaModel::primaryKey() const +{ + return m_primaryKey; +} + +/** Returns the name of the database table. + */ +QString QDjangoMetaModel::table() const +{ + return m_table; +} + +/** Removes the given QObject from the database. + * + * \param model + */ +bool QDjangoMetaModel::remove(QObject *model) const +{ + QSqlDatabase db = QDjango::database(); + + QDjangoQuery query(db); + query.prepare(QString("DELETE FROM %1 WHERE %2 = ?").arg( + db.driver()->escapeIdentifier(m_table, QSqlDriver::TableName), + db.driver()->escapeIdentifier(m_primaryKey, QSqlDriver::FieldName))); + query.addBindValue(model->property(m_primaryKey)); + return query.exec(); +} + +/** Saves the given QObject to the database. + * + * \param model + * + * \return true if saving succeeded, false otherwise + */ +bool QDjangoMetaModel::save(QObject *model) const +{ + QSqlDatabase db = QDjango::database(); + QSqlDriver *driver = db.driver(); + + QStringList fieldNames; + QDjangoMetaField primaryKey; + foreach (const QDjangoMetaField &field, m_localFields) + { + if (field.name == m_primaryKey) + primaryKey = field; + fieldNames << field.name; + } + + const QString quotedTable = db.driver()->escapeIdentifier(m_table, QSqlDriver::TableName); + const QVariant pk = model->property(primaryKey.name); + if (!pk.isNull() && !(primaryKey.type == QVariant::Int && !pk.toInt())) + { + QDjangoQuery query(db); + query.prepare(QString("SELECT 1 AS a FROM %1 WHERE %2 = ?").arg( + quotedTable, + driver->escapeIdentifier(primaryKey.name, QSqlDriver::FieldName))); + query.addBindValue(pk); + if (query.exec() && query.next()) + { + // remove primary key + fieldNames.removeAll(primaryKey.name); + + // perform update + QStringList fieldAssign; + foreach (const QString &name, fieldNames) + fieldAssign << driver->escapeIdentifier(name, QSqlDriver::FieldName) + " = ?"; + + QDjangoQuery query(db); + query.prepare(QString("UPDATE %1 SET %2 WHERE %3 = ?") + .arg(quotedTable, fieldAssign.join(", "), primaryKey.name)); + foreach (const QString &name, fieldNames) + query.addBindValue(model->property(name.toLatin1())); + query.addBindValue(pk); + return query.exec(); + } + } + + // remove auto-increment column + if (primaryKey.autoIncrement) + fieldNames.removeAll(primaryKey.name); + + // perform insert + QStringList fieldColumns; + QStringList fieldHolders; + foreach (const QString &name, fieldNames) + { + fieldColumns << driver->escapeIdentifier(name, QSqlDriver::FieldName); + fieldHolders << "?"; + } + + QDjangoQuery query(db); + query.prepare(QString("INSERT INTO %1 (%2) VALUES(%3)").arg( + quotedTable, + fieldColumns.join(", "), fieldHolders.join(", "))); + foreach (const QString &name, fieldNames) + query.addBindValue(model->property(name.toLatin1())); + + bool ret = query.exec(); + if (primaryKey.autoIncrement) { + QVariant insertId; + if (db.driverName() == "QPSQL") { + QDjangoQuery query(db); + const QString seqName = driver->escapeIdentifier(m_table + "_" + primaryKey.name + "_seq", QSqlDriver::FieldName); + if (!query.exec("SELECT CURRVAL('" + seqName + "')") || !query.next()) + return false; + insertId = query.value(0); + } else { + insertId = query.lastInsertId(); + } + model->setProperty(primaryKey.name, insertId); + } + return ret; +} + + diff --git a/src/db/QDjango.h b/src/db/QDjango.h new file mode 100644 index 0000000..0acb892 --- /dev/null +++ b/src/db/QDjango.h @@ -0,0 +1,75 @@ +/* + * Copyright (C) 2010-2012 Jeremy Lainé + * Contact: http://code.google.com/p/qdjango/ + * + * This file is part of the QDjango Library. + * + * This program 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 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU Lesser General Public License + * along with this program. If not, see . + */ + +#ifndef QDJANGO_H +#define QDJANGO_H + +#include "QDjango_p.h" + +class QObject; +class QSqlDatabase; +class QSqlQuery; +class QString; + +class QDjangoMetaModel; + +/** \defgroup Database */ + +/** \brief The QDjango class provides a set of static functions. + * + * It is used to access registered QDjangoModel classes. + * + * \ingroup Database + */ +class QDjango +{ +public: + static bool createTables(); + static bool dropTables(); + + static QSqlDatabase database(); + static void setDatabase(QSqlDatabase database); + + template + static QDjangoMetaModel registerModel(); + +private: + // backend specific + static QString noLimitSql(); + + static QDjangoMetaModel registerModel(const QObject *model); + static QDjangoMetaModel metaModel(const QString &name); + + friend class QDjangoCompiler; + friend class QDjangoModel; + friend class QDjangoMetaModel; + friend class QDjangoQuerySetPrivate; +}; + +/** Register a QDjangoModel class with QDjango. + */ +template +QDjangoMetaModel QDjango::registerModel() +{ + T model; + return registerModel(&model); +} + +#endif diff --git a/src/db/QDjangoModel.cpp b/src/db/QDjangoModel.cpp new file mode 100644 index 0000000..69b4209 --- /dev/null +++ b/src/db/QDjangoModel.cpp @@ -0,0 +1,106 @@ +/* + * Copyright (C) 2010-2012 Jeremy Lainé + * Contact: http://code.google.com/p/qdjango/ + * + * This file is part of the QDjango Library. + * + * This program 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 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU Lesser General Public License + * along with this program. If not, see . + */ + +#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 current QDjangoModel will 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("%1(%2=%3)").arg(metaObject()->className(), QString::fromLatin1(pkName), property(pkName).toString()); +} + diff --git a/src/db/QDjangoModel.h b/src/db/QDjangoModel.h new file mode 100644 index 0000000..e2167a8 --- /dev/null +++ b/src/db/QDjangoModel.h @@ -0,0 +1,91 @@ +/* + * Copyright (C) 2010-2012 Jeremy Lainé + * Contact: http://code.google.com/p/qdjango/ + * + * This file is part of the QDjango Library. + * + * This program 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 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU Lesser General Public License + * along with this program. If not, see . + */ + +#ifndef QDJANGO_MODEL_H +#define QDJANGO_MODEL_H + +#include +#include + +/** \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 + * + * 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 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 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. + * + * \ingroup Database + */ +class 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 diff --git a/src/db/QDjangoQuerySet.cpp b/src/db/QDjangoQuerySet.cpp new file mode 100644 index 0000000..443f9eb --- /dev/null +++ b/src/db/QDjangoQuerySet.cpp @@ -0,0 +1,379 @@ +/* + * Copyright (C) 2010-2012 Jeremy Lainé + * Copyright (C) 2011 Mathias Hasselmann + * Contact: http://code.google.com/p/qdjango/ + * + * This file is part of the QDjango Library. + * + * This program 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 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU Lesser General Public License + * along with this program. If not, see . + */ + +#include + +#include "QDjango.h" +#include "QDjangoQuerySet.h" + +QDjangoCompiler::QDjangoCompiler(const QString &modelName, const QSqlDatabase &db) +{ + driver = db.driver(); + baseModel = QDjango::metaModel(modelName); +} + +QString QDjangoCompiler::referenceModel(const QString &modelPath, QDjangoMetaModel *metaModel) +{ + if (modelPath.isEmpty()) + return driver->escapeIdentifier(baseModel.table(), QSqlDriver::TableName); + + if (modelRefs.contains(modelPath)) + return modelRefs.value(modelPath).first; + + const QString modelRef = "T" + QString::number(modelRefs.size()); + modelRefs.insert(modelPath, qMakePair(modelRef, *metaModel)); + return modelRef; +} + +QString QDjangoCompiler::databaseColumn(const QString &name) +{ + QDjangoMetaModel model = baseModel; + QString modelPath; + QString modelRef = referenceModel(QString(), &model); + + QStringList bits = name.split("__"); + while (bits.size() > 1) { + const QByteArray fk = bits.first().toLatin1(); + if (!model.foreignFields().contains(fk)) + break; + + QDjangoMetaModel foreignModel = QDjango::metaModel(model.foreignFields()[fk]); + + // store reference + if (!modelPath.isEmpty()) + modelPath += "__"; + modelPath += bits.first(); + modelRef = referenceModel(modelPath, &foreignModel); + + model = foreignModel; + bits.takeFirst(); + } + + QString fieldName = bits.join("__"); + if (fieldName == QLatin1String("pk")) + fieldName = model.primaryKey(); + + return modelRef + "." + driver->escapeIdentifier(fieldName, QSqlDriver::FieldName); +} + +QStringList QDjangoCompiler::fieldNames(bool recurse, QDjangoMetaModel *metaModel, const QString &modelPath) +{ + QStringList fields; + if (!metaModel) + metaModel = &baseModel; + + // store reference + const QString tableName = referenceModel(modelPath, metaModel); + foreach (const QDjangoMetaField &field, metaModel->localFields()) + fields << tableName + "." + driver->escapeIdentifier(field.name, QSqlDriver::FieldName); + if (!recurse) + return fields; + + // recurse for foreign keys + const QString pathPrefix = modelPath.isEmpty() ? QString() : (modelPath + "__"); + foreach (const QByteArray &fkName, metaModel->foreignFields().keys()) { + QDjangoMetaModel metaForeign = QDjango::metaModel(metaModel->foreignFields()[fkName]); + fields += fieldNames(recurse, &metaForeign, pathPrefix + fkName); + } + return fields; +} + +QString QDjangoCompiler::fromSql() +{ + QString from = driver->escapeIdentifier(baseModel.table(), QSqlDriver::TableName); + foreach (const QString &name, modelRefs.keys()) { + from += QString(" INNER JOIN %1 %2 ON %3.%4 = %5") + .arg(driver->escapeIdentifier(modelRefs[name].second.table(), QSqlDriver::TableName)) + .arg(modelRefs[name].first) + .arg(modelRefs[name].first) + .arg(driver->escapeIdentifier(modelRefs[name].second.primaryKey(), QSqlDriver::FieldName)) + .arg(databaseColumn(name + "_id")); + } + return from; +} + +QString QDjangoCompiler::orderLimitSql(const QStringList orderBy, int lowMark, int highMark) +{ + QString limit; + + // order + QStringList bits; + QString field; + foreach (field, orderBy) { + QString order = "ASC"; + if (field.startsWith("-")) { + order = "DESC"; + field = field.mid(1); + } else if (field.startsWith("+")) { + field = field.mid(1); + } + bits.append(QString("%1 %2").arg(databaseColumn(field), order)); + } + if (!bits.isEmpty()) + limit += " ORDER BY " + bits.join(", "); + + // limits + if (highMark > 0) + limit += QString(" LIMIT %1").arg(highMark - lowMark); + if (lowMark > 0) + { + // no-limit is backend specific + if (highMark <= 0) + limit += QDjango::noLimitSql(); + limit += QString(" OFFSET %1").arg(lowMark); + } + return limit; +} + +void QDjangoCompiler::resolve(QDjangoWhere &where) +{ + // resolve column + if (where.m_operation != QDjangoWhere::None) + where.m_key = databaseColumn(where.m_key); + + // recurse into children + for (int i = 0; i < where.m_children.size(); i++) + resolve(where.m_children[i]); +} + +QDjangoQuerySetPrivate::QDjangoQuerySetPrivate(const QString &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; +} + +int QDjangoQuerySetPrivate::sqlCount() 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 = "SELECT COUNT(*) FROM " + compiler.fromSql(); + if (!where.isEmpty()) + sql += " WHERE " + where; + sql += limit; + QDjangoQuery query(db); + query.prepare(sql); + resolvedWhere.bindValues(query); + + // execute query + if (!query.exec() || !query.next()) + return -1; + return query.value(0).toInt(); +} + +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; + + 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 = "DELETE FROM " + compiler.fromSql(); + if (!where.isEmpty()) + sql += " WHERE " + where; + sql += limit; + QDjangoQuery query(db); + query.prepare(sql); + resolvedWhere.bindValues(query); + + // execute query + if (!query.exec()) + return false; + + // invalidate cache + if (hasResults) + { + properties.clear(); + hasResults = false; + } + return true; +} + +bool QDjangoQuerySetPrivate::sqlFetch() +{ + if (hasResults || whereClause.isNone()) + return true; + + QSqlDatabase db = QDjango::database(); + + // build query + QDjangoCompiler compiler(m_modelName, db); + QDjangoWhere resolvedWhere(whereClause); + compiler.resolve(resolvedWhere); + + const QStringList fields = compiler.fieldNames(selectRelated); + const QString where = resolvedWhere.sql(db); + const QString limit = compiler.orderLimitSql(orderBy, lowMark, highMark); + QString sql = "SELECT " + fields.join(", ") + " FROM " + compiler.fromSql(); + if (!where.isEmpty()) + sql += " WHERE " + where; + sql += limit; + QDjangoQuery query(db); + query.prepare(sql); + resolvedWhere.bindValues(query); + + // execute query + if (!query.exec()) + return false; + + // store results + while (query.next()) { + QVariantList props; + for (int i = 0; i < fields.size(); ++i) + props << query.value(i); + properties.append(props); + } + hasResults = true; + 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; +} + +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(QString::fromAscii(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; +} + diff --git a/src/db/QDjangoQuerySet.h b/src/db/QDjangoQuerySet.h new file mode 100644 index 0000000..40f442a --- /dev/null +++ b/src/db/QDjangoQuerySet.h @@ -0,0 +1,646 @@ +/* + * Copyright (C) 2010-2012 Jeremy Lainé + * Copyright (C) 2011 Mathias Hasselmann + * Contact: http://code.google.com/p/qdjango/ + * + * This file is part of the QDjango Library. + * + * This program 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 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU Lesser General Public License + * along with this program. If not, see . + */ + +#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(); + 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(); + return d->sqlCount(); +} + +/** 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(); +} + +/** 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 diff --git a/src/db/QDjangoQuerySet_p.h b/src/db/QDjangoQuerySet_p.h new file mode 100644 index 0000000..9ab5f4e --- /dev/null +++ b/src/db/QDjangoQuerySet_p.h @@ -0,0 +1,92 @@ +/* + * Copyright (C) 2010-2012 Jeremy Lainé + * Contact: http://code.google.com/p/qdjango/ + * + * This file is part of the QDjango Library. + * + * This program 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 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU Lesser General Public License + * along with this program. If not, see . + */ + +#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 "QDjangoWhere.h" + +class QDjangoMetaModel; + +/** \internal + */ +class QDjangoCompiler +{ +public: + QDjangoCompiler(const QString &modelName, const QSqlDatabase &db); + QString fromSql(); + QStringList fieldNames(bool recurse, QDjangoMetaModel *metaModel = 0, const QString &modelPath = QString()); + 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); + + QSqlDriver *driver; + QDjangoMetaModel baseModel; + QMap > modelRefs; +}; + +/** \internal + */ +class QDjangoQuerySetPrivate +{ +public: + QDjangoQuerySetPrivate(const QString &modelName); + + void addFilter(const QDjangoWhere &where); + QDjangoWhere resolvedWhere(const QSqlDatabase &db) const; + int sqlCount() const; + bool sqlDelete(); + bool sqlFetch(); + bool sqlLoad(QObject *model, int index); + QList sqlValues(const QStringList &fields); + QList sqlValuesList(const QStringList &fields); + + // reference counter + QAtomicInt counter; + + bool hasResults; + int lowMark; + int highMark; + QDjangoWhere whereClause; + QStringList orderBy; + QList properties; + bool selectRelated; + +private: + Q_DISABLE_COPY(QDjangoQuerySetPrivate) + + QString m_modelName; + + friend class QDjangoMetaModel; +}; + +#endif diff --git a/src/db/QDjangoWhere.cpp b/src/db/QDjangoWhere.cpp new file mode 100644 index 0000000..c16cd45 --- /dev/null +++ b/src/db/QDjangoWhere.cpp @@ -0,0 +1,252 @@ +/* + * Copyright (C) 2010-2012 Jeremy Lainé + * Contact: http://code.google.com/p/qdjango/ + * + * This file is part of the QDjango Library. + * + * This program 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 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU Lesser General Public License + * along with this program. If not, see . + */ + +#include + +#include "QDjango.h" +#include "QDjangoWhere.h" + + +/** Constructs an empty QDjangoWhere, which expresses no constraint. + */ +QDjangoWhere::QDjangoWhere() + : m_operation(None), m_combine(NoCombine), m_negate(false) +{ +} + +/** 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) + : m_key(key), m_operation(operation), m_data(value), m_combine(NoCombine) +{ +} + +/** Negates the current QDjangoWhere. + */ +QDjangoWhere QDjangoWhere::operator!() const +{ + QDjangoWhere result; + result.m_key = m_key; + result.m_data = m_data; + result.m_combine = m_combine; + result.m_negate = !m_negate; + if (m_children.isEmpty()) + { + switch (m_operation) + { + case None: + case IsIn: + case StartsWith: + case EndsWith: + case Contains: + result.m_operation = m_operation; + break; + case Equals: + // simplify !(a = b) to a != b + result.m_operation = NotEquals; + result.m_negate = m_negate; + break; + case NotEquals: + // simplify !(a != b) to a = b + result.m_operation = Equals; + result.m_negate = m_negate; + break; + case GreaterThan: + // simplify !(a > b) to a <= b + result.m_operation = LessOrEquals; + result.m_negate = m_negate; + break; + case LessThan: + // simplify !(a < b) to a >= b + result.m_operation = GreaterOrEquals; + result.m_negate = m_negate; + break; + case GreaterOrEquals: + // simplify !(a >= b) to a < b + result.m_operation = LessThan; + result.m_negate = m_negate; + break; + case LessOrEquals: + // simplify !(a <= b) to a > b + result.m_operation = GreaterThan; + result.m_negate = m_negate; + break; + } + } else { + result.m_children = m_children; + result.m_operation = m_operation; + } + + 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; + + QDjangoWhere result; + result.m_combine = AndCombine; + result.m_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; + + QDjangoWhere result; + result.m_combine = OrCombine; + result.m_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 (m_operation == QDjangoWhere::IsIn) + { + const QList values = m_data.toList(); + for (int i = 0; i < values.size(); i++) + query.addBindValue(values[i]); + } + else if (m_operation == QDjangoWhere::StartsWith) + { + QString escaped = m_data.toString(); + escaped.replace("%", "\\%"); + escaped.replace("_", "\\_"); + query.addBindValue(escaped + "%"); + } + else if (m_operation == QDjangoWhere::EndsWith) + { + QString escaped = m_data.toString(); + escaped.replace("%", "\\%"); + escaped.replace("_", "\\_"); + query.addBindValue("%" + escaped); + } + else if (m_operation == QDjangoWhere::Contains) + { + QString escaped = m_data.toString(); + escaped.replace("%", "\\%"); + escaped.replace("_", "\\_"); + query.addBindValue("%" + escaped + "%"); + } + else if (m_operation != QDjangoWhere::None) + query.addBindValue(m_data); + else + foreach (const QDjangoWhere &child, m_children) + child.bindValues(query); +} + +/** Returns true if the current QDjangoWhere does not express any constraint. + */ +bool QDjangoWhere::isAll() const +{ + return m_combine == NoCombine && m_operation == None && m_negate == false; +} + +/** Returns true if the current QDjangoWhere expressed an impossible constraint. + */ +bool QDjangoWhere::isNone() const +{ + return m_combine == NoCombine && m_operation == None && m_negate == true; +} + +/** Returns the SQL code corresponding for the current QDjangoWhere. + */ +QString QDjangoWhere::sql(const QSqlDatabase &db) const +{ + switch (m_operation) + { + case Equals: + return m_key + " = ?"; + case NotEquals: + return m_key + " != ?"; + case GreaterThan: + return m_key + " > ?"; + case LessThan: + return m_key + " < ?"; + case GreaterOrEquals: + return m_key + " >= ?"; + case LessOrEquals: + return m_key + " <= ?"; + case IsIn: + { + QStringList bits; + for (int i = 0; i < m_data.toList().size(); i++) + bits << "?"; + return m_key + " IN (" + bits.join(", ") + ")"; + } + case StartsWith: + case EndsWith: + case Contains: + if (db.driverName() == "QSQLITE" || db.driverName() == "QSQLITE2") + return m_key + " LIKE ? ESCAPE '\\'"; + else + return m_key + " LIKE ?"; + case None: + if (m_combine == NoCombine) + { + return m_negate ? QString("1 != 0") : QString(); + } else { + QStringList bits; + foreach (const QDjangoWhere &child, m_children) + { + QString atom = child.sql(db); + if (child.m_children.isEmpty()) + bits << atom; + else + bits << QString("(%1)").arg(atom); + } + QString combined; + if (m_combine == AndCombine) + combined = bits.join(" AND "); + else if (m_combine == OrCombine) + combined = bits.join(" OR "); + if (m_negate) + combined = QString("NOT (%1)").arg(combined); + return combined; + } + } + return QString(); +} + diff --git a/src/db/QDjangoWhere.h b/src/db/QDjangoWhere.h new file mode 100644 index 0000000..c8e45cc --- /dev/null +++ b/src/db/QDjangoWhere.h @@ -0,0 +1,101 @@ +/* + * Copyright (C) 2010-2012 Jeremy Lainé + * Contact: http://code.google.com/p/qdjango/ + * + * This file is part of the QDjango Library. + * + * This program 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 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU Lesser General Public License + * along with this program. If not, see . + */ + +#ifndef QDJANGO_QUERY_H +#define QDJANGO_QUERY_H + +#include + +class QDjangoMetaModel; +class QDjangoQuery; + +/** \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 QDjangoWhere +{ +public: + /** A comparison operation on a database column value. */ + enum Operation + { + /** No comparison, always returns true. */ + None, + /** Returns true if the column value is equal to the given value. */ + Equals, + /** Returns true if the column value is not equal to the given value. */ + NotEquals, + /** Returns true if the column value is greater than the given value. */ + GreaterThan, + /** Returns true if the column value is less than the given value. */ + LessThan, + /** Returns true if the column value is greater or equal to the given value. */ + GreaterOrEquals, + /** Returns true if the column value is less or equal to the given value. */ + LessOrEquals, + /** Returns true if the column value starts with the given value (strings only). */ + StartsWith, + /** Returns true if the column value ends with the given value (strings only). */ + EndsWith, + /** Returns true if the column value contains the given value (strings only). */ + Contains, + /** Returns true if the column value is one of the given values. */ + IsIn, + }; + + QDjangoWhere(); + QDjangoWhere(const QString &key, QDjangoWhere::Operation operation, QVariant value); + + 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; + +private: + enum Combine + { + NoCombine, + AndCombine, + OrCombine, + }; + + QString m_key; + QDjangoWhere::Operation m_operation; + QVariant m_data; + + QList m_children; + QDjangoWhere::Combine m_combine; + bool m_negate; + + friend class QDjangoCompiler; + friend class QDjangoQuerySetPrivate; +}; + +#endif diff --git a/src/db/QDjango_p.h b/src/db/QDjango_p.h new file mode 100644 index 0000000..e7354b3 --- /dev/null +++ b/src/db/QDjango_p.h @@ -0,0 +1,154 @@ +/* + * Copyright (C) 2010-2012 Jeremy Lainé + * Contact: http://code.google.com/p/qdjango/ + * + * This file is part of the QDjango Library. + * + * This program 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 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU Lesser General Public License + * along with this program. If not, see . + */ + +#ifndef QDJANGO_P_H +#define QDJANGO_P_H + +#include +#include +#include +#include +#include +#include +#include +#include +#include + +/** \brief The QDjangoMetaField class holds the database schema for a field. + * + * \internal + */ +class QDjangoMetaField +{ +public: + QDjangoMetaField(); + + QByteArray name; + QVariant::Type type; + bool autoIncrement; + bool index; + int maxLength; + bool unique; + QString foreignModel; +}; + +/** \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 QDjangoMetaModel +{ +public: + QDjangoMetaModel(const QObject *model = 0); + bool isValid() const; + + bool createTable() 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; + + QList localFields() const; + QMap foreignFields() const; + QByteArray primaryKey() const; + QString table() const; + +private: + QList m_localFields; + QMap m_foreignFields; + QByteArray m_primaryKey; + QString m_table; +}; + +/** \brief The QDjangoDatabase class represents a set of connections to a + * database. + * + * \internal + */ +class QDjangoDatabase : public QObject +{ + Q_OBJECT + +public: + QDjangoDatabase(QObject *parent = 0); + + QSqlDatabase reference; + QMutex mutex; + QMap copies; + qint64 connectionId; + +private slots: + void threadFinished(); +}; + +class QDjangoQuery : public QSqlQuery +{ +public: + QDjangoQuery(QSqlDatabase db) : QSqlQuery(db) + { + } + + void addBindValue(const QVariant &val, QSql::ParamType paramType = QSql::In) + { + // 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); + } + +#ifdef QDJANGO_DEBUG_SQL + bool exec() + { + qDebug() << "SQL query" << lastQuery(); + QMapIterator i(boundValues()); + while (i.hasNext()) { + i.next(); + qDebug() << "SQL " << i.key().toAscii().data() << "=" + << i.value().toString().toAscii().data(); + } + if (!QSqlQuery::exec()) { + qWarning() << "SQL error" << lastError(); + return false; + } + return true; + } + + bool exec(const QString &query) + { + qDebug() << "SQL query" << query; + if (!QSqlQuery::exec(query)) { + qWarning() << "SQL error" << lastError(); + return false; + } + return true; + } +#endif +}; + +#endif diff --git a/src/db/db.pro b/src/db/db.pro new file mode 100644 index 0000000..43ba831 --- /dev/null +++ b/src/db/db.pro @@ -0,0 +1,24 @@ +include(../../qdjango.pri) + +TEMPLATE = lib +CONFIG += staticlib +QT += sql + +TARGET = qdjango-db +VERSION = $$QDJANGO_VERSION +win32 { + DESTDIR = $$OUT_PWD +} + +HEADERS += \ + QDjango.h \ + QDjango_p.h \ + QDjangoModel.h \ + QDjangoQuerySet.h \ + QDjangoQuerySet_p.h \ + QDjangoWhere.h +SOURCES += \ + QDjango.cpp \ + QDjangoModel.cpp \ + QDjangoQuerySet.cpp \ + QDjangoWhere.cpp diff --git a/src/http/CMakeLists.txt b/src/http/CMakeLists.txt new file mode 100644 index 0000000..d5507db --- /dev/null +++ b/src/http/CMakeLists.txt @@ -0,0 +1,38 @@ +set(QT_DONT_USE_QTGUI 1) +set(QT_USE_QTNETWORK 1) +include(${QT_USE_FILE}) + +# QDjango http library +set(HEADERS + QDjangoFastCgiServer.h + QDjangoFastCgiServer_p.h + QDjangoHttpController.h + QDjangoHttpRequest.h + QDjangoHttpResponse.h + QDjangoHttpServer.h + QDjangoHttpServer_p.h) +set(SOURCES + QDjangoFastCgiServer.cpp + QDjangoHttpController.cpp + QDjangoHttpRequest.cpp + QDjangoHttpResponse.cpp + QDjangoHttpServer.cpp) + +set(MOC_HEADERS + QDjangoFastCgiServer.h + QDjangoFastCgiServer_p.h + QDjangoHttpResponse.h + QDjangoHttpServer.h + QDjangoHttpServer_p.h) +qt4_wrap_cpp(MOC_SOURCES ${MOC_HEADERS}) +add_library(qdjango-http ${QDJANGO_LIBRARY_TYPE} ${SOURCES} ${MOC_SOURCES}) +set_target_properties(qdjango-http PROPERTIES SOVERSION 0) +target_link_libraries(qdjango-http ${QT_QTNETWORK_LIBRARY} ${QT_QTCORE_LIBRARY}) + +if(NOT QDJANGO_DONT_INSTALL) + install(FILES ${HEADERS} DESTINATION include/qdjango/http) + install(TARGETS qdjango-http + RUNTIME DESTINATION bin + LIBRARY DESTINATION lib + ARCHIVE DESTINATION lib) +endif() diff --git a/src/http/QDjangoFastCgiServer.cpp b/src/http/QDjangoFastCgiServer.cpp new file mode 100644 index 0000000..eb5c4c5 --- /dev/null +++ b/src/http/QDjangoFastCgiServer.cpp @@ -0,0 +1,436 @@ +/* + * Copyright (C) 2010-2012 Jeremy Lainé + * Contact: http://code.google.com/p/qdjango/ + * + * This file is part of the QDjango Library. + * + * This program 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 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU Lesser General Public License + * along with this program. If not, see . + */ + +#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" + +//#define QDJANGO_DEBUG_FCGI + +#define FCGI_HEADER_LEN 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 + +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; + +#ifdef QDJANGO_DEBUG_FCGI +static void qDebug(FCGI_Header *header, const char *dir) +{ + const quint16 requestId = (header->requestIdB1 << 8) | header->requestIdB0; + const quint16 contentLength = (header->contentLengthB1 << 8) | header->contentLengthB0; + + qDebug("--- FCGI Record %s ---", dir); + qDebug("version: %i", header->version); + qDebug("type: %i", header->type); + qDebug("requestId: %i", requestId); + qDebug("contentLength: %i", contentLength); + qDebug("paddingLength: %i", header->paddingLength); +} +#endif + +class QDjangoFastCgiServerPrivate +{ +public: + QDjangoFastCgiServerPrivate(QDjangoFastCgiServer *qq); + QLocalServer *localServer; + QTcpServer *tcpServer; + QDjangoHttpController *requestHandler; + +private: + QDjangoFastCgiServer *q; +}; + +QDjangoFastCgiConnection::QDjangoFastCgiConnection(QIODevice *device, QDjangoFastCgiServer *server) + : QObject(server), + m_device(device), + m_inputPos(0), + 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 + QByteArray data; + QHttpResponseHeader httpHeader = response->d->header; + httpHeader.setValue("Status", QString("%1 %2").arg(QString::number(httpHeader.statusCode()), httpHeader.reasonPhrase())); + const QList > httpHeaderValues = httpHeader.values(); + QList >::ConstIterator it = httpHeaderValues.constBegin(); + while (it != httpHeaderValues.constEnd()) { + data += (*it).first + QLatin1String(": ") + (*it).second + QLatin1String("\r\n"); + ++it; + } + data += QLatin1String("\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; + header->requestIdB1 = (requestId >> 8) & 0xff; + header->requestIdB0 = (requestId & 0xff); + + for (qint64 bytesRemaining = data.size(); ; ) { + const quint16 contentLength = qMin(bytesRemaining, qint64(32768)); + + header->type = FCGI_STDOUT; + header->contentLengthB1 = (contentLength >> 8) & 0xff; + header->contentLengthB0 = (contentLength & 0xff); + memcpy(m_outputBuffer + FCGI_HEADER_LEN, ptr, contentLength); + m_device->write(m_outputBuffer, FCGI_HEADER_LEN + contentLength); +#ifdef QDJANGO_DEBUG_FCGI + qDebug(header, "sent"); + qDebug("[STDOUT]"); +#endif + + if (contentLength > 0) { + ptr += contentLength; + bytesRemaining -= contentLength; + } else { + break; + } + } + + quint16 contentLength = 8; + header->type = FCGI_END_REQUEST; + header->contentLengthB1 = (contentLength >> 8) & 0xff; + header->contentLengthB0 = (contentLength & 0xff); + memset(m_outputBuffer + FCGI_HEADER_LEN, 0, contentLength); + m_device->write(m_outputBuffer, FCGI_HEADER_LEN + contentLength); +#ifdef QDJANGO_DEBUG_FCGI + qDebug(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_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 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 = (header->contentLengthB1 << 8) | header->contentLengthB0; + 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 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 + qDebug(header, "received"); +#endif + const quint16 requestId = (header->requestIdB1 << 8) | header->requestIdB0; + char *p = m_inputBuffer + FCGI_HEADER_LEN; + switch (header->type) { + case FCGI_BEGIN_REQUEST: { +#ifdef QDJANGO_DEBUG_FCGI + const quint16 role = (p[0] << 8) | p[1]; + qDebug("[BEGIN REQUEST]"); + qDebug("role: %i", role); + qDebug("flags: %i", p[2]); +#endif + if (m_pendingRequest) { + qWarning("Received FCGI_BEGIN_REQUEST inside a request"); + m_device->close(); + emit closed(); + break; + } + m_pendingRequest = new QDjangoHttpRequest; + m_pendingRequestId = requestId; + break; + } + case FCGI_ABORT_REQUEST: + m_device->close(); + emit closed(); + break; + case FCGI_PARAMS: +#ifdef QDJANGO_DEBUG_FCGI + qDebug("[PARAMS]"); +#endif + if (!m_pendingRequest || requestId != m_pendingRequestId) { + qWarning("Received FCGI_PARAMS outside a request"); + m_device->close(); + emit closed(); + break; + } + + while (p < m_inputBuffer + FCGI_HEADER_LEN + contentLength) { + quint32 nameLength; + quint32 valueLength; + if (p[0] >> 7) { + nameLength = ((p[0] & 0x7f) << 24) | (p[1] << 16) | (p[2] << 8) | p[3]; + p += 4; + } else { + nameLength = p[0]; + p++; + } + if (p[0] >> 7) { + valueLength = ((p[0] & 0x7f) << 24) | (p[1] << 16) | (p[2] << 8) | p[3]; + p += 4; + } else { + valueLength = p[0]; + p++; + } + const QByteArray name(p, nameLength); + p += nameLength; + const QByteArray value(p, valueLength); + p += valueLength; + + if (name == "PATH_INFO") { + m_pendingRequest->d->path = value; + } else if (name == "REQUEST_METHOD") { + m_pendingRequest->d->method = value; + } + m_pendingRequest->d->meta.insert(QString::fromLatin1(name), QString::fromUtf8(value)); + } + break; + case FCGI_STDIN: +#ifdef QDJANGO_DEBUG_FCGI + qDebug("[STDIN]"); +#endif + if (!m_pendingRequest || requestId != m_pendingRequestId) { + qWarning("Received FCGI_STDIN outside a request"); + m_device->close(); + emit closed(); + break; + } + + if (contentLength) { + m_pendingRequest->d->buffer.append(p, contentLength); + } else { + QDjangoHttpRequest *request = m_pendingRequest; + const quint16 requestId = m_pendingRequestId; + + m_pendingRequest = 0; + m_pendingRequestId = 0; + + QDjangoHttpController *controller = m_server->controller(); + QDjangoHttpResponse *response = 0; + if (!controller) + response = QDjangoHttpController::serveNotFound(*request); + else + response = controller->respondToRequest(*request); + + writeResponse(requestId, response); + } + break; + default: + qWarning("Unhandled request type %i", header->type); + break; + } + } +} + +QDjangoFastCgiServerPrivate::QDjangoFastCgiServerPrivate(QDjangoFastCgiServer *qq) + : localServer(0), + tcpServer(0), + q(qq) +{ +} + +/** Constructs a new FastCGI server. + */ +QDjangoFastCgiServer::QDjangoFastCgiServer(QObject *parent) + : QObject(parent) +{ + d = new QDjangoFastCgiServerPrivate(this); +} + +/** Destroys the FastCGI server. + */ +QDjangoFastCgiServer::~QDjangoFastCgiServer() +{ + delete d; +} + +/** Returns the controller which serves requests received by the server. + */ +QDjangoHttpController *QDjangoFastCgiServer::controller() const +{ + return d->requestHandler; +} + +/** Sets the \a controller which serves requests received by the server. + */ +void QDjangoFastCgiServer::setController(QDjangoHttpController *controller) +{ + d->requestHandler = controller; +} + +/** 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); +} + +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); + } +} diff --git a/src/http/QDjangoFastCgiServer.h b/src/http/QDjangoFastCgiServer.h new file mode 100644 index 0000000..51af320 --- /dev/null +++ b/src/http/QDjangoFastCgiServer.h @@ -0,0 +1,58 @@ +/* + * Copyright (C) 2010-2012 Jeremy Lainé + * Contact: http://code.google.com/p/qdjango/ + * + * This file is part of the QDjango Library. + * + * This program 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 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU Lesser General Public License + * along with this program. If not, see . + */ + +#ifndef QDJANGO_FASTCGI_SERVER_H +#define QDJANGO_FASTCGI_SERVER_H + +#include +#include + +class QDjangoFastCgiServerPrivate; +class QDjangoHttpController; + +/** \brief The QDjangoFastCgiServer class represents a FastCGI server. + * + * \ingroup Http + */ +class QDjangoFastCgiServer : public QObject +{ + Q_OBJECT + +public: + QDjangoFastCgiServer(QObject *parent = 0); + ~QDjangoFastCgiServer(); + + QDjangoHttpController *controller() const; + void setController(QDjangoHttpController *controller); + + void close(); + bool listen(const QString &name); + bool listen(const QHostAddress &address, quint16 port); + +private slots: + void _q_newLocalConnection(); + void _q_newTcpConnection(); + +private: + Q_DISABLE_COPY(QDjangoFastCgiServer) + QDjangoFastCgiServerPrivate *d; +}; + +#endif diff --git a/src/http/QDjangoFastCgiServer_p.h b/src/http/QDjangoFastCgiServer_p.h new file mode 100644 index 0000000..8240036 --- /dev/null +++ b/src/http/QDjangoFastCgiServer_p.h @@ -0,0 +1,67 @@ +/* + * Copyright (C) 2010-2012 Jeremy Lainé + * Contact: http://code.google.com/p/qdjango/ + * + * This file is part of the QDjango Library. + * + * This program 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 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU Lesser General Public License + * along with this program. If not, see . + */ + +#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 + +#define FCGI_RECORD_SIZE (255*255 + 255 + 8) + +class QDjangoFastCgiServer; +class QDjangoHttpRequest; +class QDjangoHttpResponse; +class QIODevice; + +class 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; + char m_outputBuffer[FCGI_RECORD_SIZE]; + QDjangoHttpRequest *m_pendingRequest; + quint16 m_pendingRequestId; + QDjangoFastCgiServer *m_server; +}; + +#endif diff --git a/src/http/QDjangoHttpController.cpp b/src/http/QDjangoHttpController.cpp new file mode 100644 index 0000000..810412d --- /dev/null +++ b/src/http/QDjangoHttpController.cpp @@ -0,0 +1,197 @@ +/* + * Copyright (C) 2010-2012 Jeremy Lainé + * Contact: http://code.google.com/p/qdjango/ + * + * This file is part of the QDjango Library. + * + * This program 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 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU Lesser General Public License + * along with this program. If not, see . + */ + +#include +#include +#include +#include +#include +#include +#include + +#include "QDjangoHttpController.h" +#include "QDjangoHttpRequest.h" +#include "QDjangoHttpResponse.h" + +QString httpDateTime(const QDateTime &dt) +{ + if (dt.isValid()) + return dt.toUTC().toString("ddd, dd MMM yyyy HH:mm:ss") + " GMT"; + return QString(); +} + +QDateTime httpDateTime(const QString &str) +{ + QDateTime dt = QDateTime::fromString(str.left(25), "ddd, dd MMM yyyy HH:mm:ss"); + dt.setTimeSpec(Qt::UTC); + return dt; +} + +/** 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("^Basic (.+)$"); + const QString authHeader = request.meta("HTTP_AUTHORIZATION"); + if (authRx.exactMatch(authHeader)) { + const QString authValue = QString::fromUtf8(QByteArray::fromBase64(authRx.cap(1).toAscii())); + const QStringList bits = authValue.split(":"); + if (bits.size() == 2 && !bits[0].isEmpty() && !bits[1].isEmpty()) { + username = bits[0]; + password = bits[1]; + return true; + } + } + return false; +} + +QDjangoHttpResponse *QDjangoHttpController::serveError(const QDjangoHttpRequest &request, int code, const QString &text) +{ + Q_UNUSED(request); + + QDjangoHttpResponse *response = new QDjangoHttpResponse; + response->setHeader("Content-Type", "text/html; charset=utf-8"); + response->setStatusCode(code); + response->setBody(QString("" + "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("WWW-Authenticate", QString("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, "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, "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, "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("You are being redirect to %2").arg(urlString, urlString)); + response->setHeader("Location", urlString.toUtf8()); + 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(":/")) + lastModified = QFileInfo(qApp->applicationFilePath()).lastModified(); + if (lastModified.isValid()) + response->setHeader("Last-Modified", httpDateTime(lastModified)); + + // cache expiry + if (expires.isValid()) + response->setHeader("Expires", httpDateTime(expires)); + + // handle if-modified-since + const QDateTime ifModifiedSince = httpDateTime(request.meta("HTTP_IF_MODIFIED_SINCE")); + if (lastModified.isValid() && ifModifiedSince.isValid() && lastModified <= ifModifiedSince) + { + response->setStatusCode(304); + return response; + } + + // determine content type + QString mimeType("application/octet-stream"); + if (fileName.endsWith(".css")) + mimeType = "text/css"; + else if (fileName.endsWith(".html")) + mimeType = "text/html"; + else if (fileName.endsWith(".js")) + mimeType = "application/javascript"; + else if (fileName.endsWith(".png")) + mimeType = "image/png"; + response->setHeader("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("Content-Length", QString::number(file.size())); + else + response->setBody(file.readAll()); + return response; +} + diff --git a/src/http/QDjangoHttpController.h b/src/http/QDjangoHttpController.h new file mode 100644 index 0000000..f536e88 --- /dev/null +++ b/src/http/QDjangoHttpController.h @@ -0,0 +1,62 @@ +/* + * Copyright (C) 2010-2012 Jeremy Lainé + * Contact: http://code.google.com/p/qdjango/ + * + * This file is part of the QDjango Library. + * + * This program 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 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU Lesser General Public License + * along with this program. If not, see . + */ + +#ifndef QDJANGO_HTTP_CONTROLLER_H +#define QDJANGO_HTTP_CONTROLLER_H + +#include +#include + +class QDjangoHttpRequest; +class QDjangoHttpResponse; +class QUrl; + +QString httpDateTime(const QDateTime &dt); +QDateTime httpDateTime(const QString &str); + +/** \brief The QDjangoHttpController class is the base class for HTTP request handlers. + * + * \ingroup Http + */ +class QDjangoHttpController +{ +public: + // get basic authorization credentials + static bool getBasicAuth(const QDjangoHttpRequest &request, QString &username, QString &password); + + // common responses + static QDjangoHttpResponse *serveAuthorizationRequired(const QDjangoHttpRequest &request, const QString &realm = QString("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()); + + /** \brief Responds to an HTTP request. + * + * Reimplement this method when creating a subclass of QDjangoHttpController. + */ + virtual QDjangoHttpResponse *respondToRequest(const QDjangoHttpRequest &request) = 0; + +private: + static QDjangoHttpResponse *serveError(const QDjangoHttpRequest &request, int code, const QString &text); +}; + +#endif diff --git a/src/http/QDjangoHttpRequest.cpp b/src/http/QDjangoHttpRequest.cpp new file mode 100644 index 0000000..4d80c05 --- /dev/null +++ b/src/http/QDjangoHttpRequest.cpp @@ -0,0 +1,68 @@ +/* + * Copyright (C) 2010-2012 Jeremy Lainé + * Contact: http://code.google.com/p/qdjango/ + * + * This file is part of the QDjango Library. + * + * This program 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 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU Lesser General Public License + * along with this program. If not, see . + */ + +#include + +#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 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; +} diff --git a/src/http/QDjangoHttpRequest.h b/src/http/QDjangoHttpRequest.h new file mode 100644 index 0000000..5904c2d --- /dev/null +++ b/src/http/QDjangoHttpRequest.h @@ -0,0 +1,51 @@ +/* + * Copyright (C) 2010-2012 Jeremy Lainé + * Contact: http://code.google.com/p/qdjango/ + * + * This file is part of the QDjango Library. + * + * This program 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 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU Lesser General Public License + * along with this program. If not, see . + */ + +#ifndef QDJANGO_HTTP_REQUEST_H +#define QDJANGO_HTTP_REQUEST_H + +#include + +class QDjangoHttpRequest; +class QDjangoHttpRequestPrivate; + +/** \brief The QDjangoHttpRequest class represents an HTTP request. + * + * \ingroup Http + */ +class QDjangoHttpRequest +{ +public: + QDjangoHttpRequest(); + ~QDjangoHttpRequest(); + + QByteArray body() const; + QString meta(const QString &key) const; + QString method() const; + QString path() const; + +private: + Q_DISABLE_COPY(QDjangoHttpRequest) + QDjangoHttpRequestPrivate* const d; + friend class QDjangoFastCgiConnection; + friend class QDjangoHttpConnection; +}; + +#endif diff --git a/src/http/QDjangoHttpRequest_p.h b/src/http/QDjangoHttpRequest_p.h new file mode 100644 index 0000000..da67557 --- /dev/null +++ b/src/http/QDjangoHttpRequest_p.h @@ -0,0 +1,44 @@ +/* + * Copyright (C) 2010-2012 Jeremy Lainé + * Contact: http://code.google.com/p/qdjango/ + * + * This file is part of the QDjango Library. + * + * This program 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 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU Lesser General Public License + * along with this program. If not, see . + */ + +#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 diff --git a/src/http/QDjangoHttpResponse.cpp b/src/http/QDjangoHttpResponse.cpp new file mode 100644 index 0000000..a6e86ee --- /dev/null +++ b/src/http/QDjangoHttpResponse.cpp @@ -0,0 +1,140 @@ +/* + * Copyright (C) 2010-2012 Jeremy Lainé + * Contact: http://code.google.com/p/qdjango/ + * + * This file is part of the QDjango Library. + * + * This program 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 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU Lesser General Public License + * along with this program. If not, see . + */ + +#include "QDjangoHttpResponse.h" +#include "QDjangoHttpResponse_p.h" + +/** Constructs a new HTTP response. + */ +QDjangoHttpResponse::QDjangoHttpResponse() + : d(new QDjangoHttpResponsePrivate) +{ + setHeader("Content-Length", "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("Content-Length", QString::number(d->body.size())); +} + +/** Returns the specified HTTP response header. + * + * \param key + */ +QString QDjangoHttpResponse::header(const QString &key) const +{ + return d->header.value(key); +} + +/** Sets the specified HTTP response header. + * + * \param key + * \param value + */ +void QDjangoHttpResponse::setHeader(const QString &key, const QString &value) +{ + d->header.setValue(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 code for the HTTP response status line. + */ +int QDjangoHttpResponse::statusCode() const +{ + return d->header.statusCode(); +} + +/** Sets the code for the HTTP response status line. + * + * \param code + */ +void QDjangoHttpResponse::setStatusCode(int code) +{ + switch(code) + { + case OK: + d->header.setStatusLine(code, "OK"); + break; + case MovedPermanently: + d->header.setStatusLine(code, "Moved Permanently"); + break; + case Found: + d->header.setStatusLine(code, "Found"); + break; + case NotModified: + d->header.setStatusLine(code, "Not Modified"); + break; + case BadRequest: + d->header.setStatusLine(code, "Bad Request"); + break; + case AuthorizationRequired: + d->header.setStatusLine(code, "Authorization Required"); + break; + case Forbidden: + d->header.setStatusLine(code, "Forbidden"); + break; + case NotFound: + d->header.setStatusLine(code, "Not Found"); + break; + case MethodNotAllowed: + d->header.setStatusLine(code, "Method Not Allowed"); + break; + case InternalServerError: + d->header.setStatusLine(code, "Internal Server Error"); + break; + default: + d->header.setStatusLine(code); + break; + } +} + diff --git a/src/http/QDjangoHttpResponse.h b/src/http/QDjangoHttpResponse.h new file mode 100644 index 0000000..5ef71f9 --- /dev/null +++ b/src/http/QDjangoHttpResponse.h @@ -0,0 +1,81 @@ +/* + * Copyright (C) 2010-2012 Jeremy Lainé + * Contact: http://code.google.com/p/qdjango/ + * + * This file is part of the QDjango Library. + * + * This program 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 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU Lesser General Public License + * along with this program. If not, see . + */ + +#ifndef QDJANGO_HTTP_RESPONSE_H +#define QDJANGO_HTTP_RESPONSE_H + +#include + +class QDjangoHttpResponsePrivate; + +/** \brief The QDjangoHttpResponse class represents an HTTP response. + * + * \ingroup Http + */ +class 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; + + 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 diff --git a/src/http/QDjangoHttpResponse_p.h b/src/http/QDjangoHttpResponse_p.h new file mode 100644 index 0000000..c290755 --- /dev/null +++ b/src/http/QDjangoHttpResponse_p.h @@ -0,0 +1,42 @@ +/* + * Copyright (C) 2010-2012 Jeremy Lainé + * Contact: http://code.google.com/p/qdjango/ + * + * This file is part of the QDjango Library. + * + * This program 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 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU Lesser General Public License + * along with this program. If not, see . + */ + +#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 + +/** \internal + */ +class QDjangoHttpResponsePrivate +{ +public: + QHttpResponseHeader header; + QByteArray body; +}; + +#endif diff --git a/src/http/QDjangoHttpServer.cpp b/src/http/QDjangoHttpServer.cpp new file mode 100644 index 0000000..ca8a0cf --- /dev/null +++ b/src/http/QDjangoHttpServer.cpp @@ -0,0 +1,315 @@ +/* + * Copyright (C) 2010-2012 Jeremy Lainé + * Contact: http://code.google.com/p/qdjango/ + * + * This file is part of the QDjango Library. + * + * This program 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 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU Lesser General Public License + * along with this program. If not, see . + */ + +#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" + +//#define QDJANGO_DEBUG_HTTP + +// maximum request body size is 10 MB +#define MAX_BODY_SIZE (10 * 1024 * 1024) + +/** 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(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(handleData())); + 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::bytesWritten(qint64 bytes) +{ + Q_UNUSED(bytes); + if (!m_socket->bytesToWrite()) { + if (!m_pendingJobs.isEmpty()) { + 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::handleData() +{ + QDjangoHttpRequest *request = m_pendingRequest; + if (!request) { + request = new QDjangoHttpRequest; + m_requestBytesRemaining = 0; + m_requestHeaderBuffer.clear(); + m_requestHeaderReceived = false; + } + + // Read request header + while (!m_requestHeaderReceived && m_socket->canReadLine()) { + const QByteArray line = m_socket->readLine(); + m_requestHeaderBuffer += line; + if (line == "\r\n") { + m_requestHeader = QHttpRequestHeader(QString::fromUtf8(m_requestHeaderBuffer)); + request->d->method = m_requestHeader.method(); + request->d->path = QUrl(m_requestHeader.path()).path(); + const int bytes = m_requestHeader.value("Content-Length").toInt(); + if (bytes < 0 || bytes > MAX_BODY_SIZE) { + qWarning("Invalid Content-Length"); + m_socket->close(); + return; + } else { + m_requestBytesRemaining = bytes; + } + 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; + foreach (const QString &key, m_requestHeader.keys()) { + if (key == "Content-Length") + metaKey = "CONTENT_LENGTH"; + else if (key == "Content-Type") + metaKey = "CONTENT_TYPE"; + else { + metaKey = "HTTP_" + key.toUpper(); + metaKey.replace('-', '_'); + } + request->d->meta.insert(metaKey, m_requestHeader.value(key)); + } + request->d->meta.insert("QUERY_STRING", QUrl(m_requestHeader.path()).encodedQuery()); + request->d->meta.insert("REMOTE_ADDR", m_socket->peerAddress().toString()); + request->d->meta.insert("REQUEST_METHOD", request->method()); + request->d->meta.insert("SERVER_NAME", m_socket->localAddress().toString()); + request->d->meta.insert("SERVER_PORT", QString::number(m_socket->localPort())); + + /* Process request */ + bool keepAlive = m_requestHeader.majorVersion() >= 1 && m_requestHeader.minorVersion() >= 1; + if (m_requestHeader.value("Connection").toLower() == QLatin1String("keep-alive")) + keepAlive = true; + else if (m_requestHeader.value("Connection").toLower() == QLatin1String("close")) + keepAlive = false; + + QDjangoHttpController *controller = m_server->controller(); + QDjangoHttpResponse *response = 0; + if (!controller) + response = QDjangoHttpController::serveNotFound(*request); + else + response = controller->respondToRequest(*request); + m_pendingJobs << qMakePair(request, response); + + /* Store keep-alive flag */ + if (!keepAlive) + m_closeAfterResponse = true; + + connect(response, SIGNAL(ready()), this, SLOT(writeResponse())); + writeResponse(); +} + +void QDjangoHttpConnection::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("Date", httpDateTime(QDateTime::currentDateTime())); + response->setHeader("Server", QString("%1/%2").arg(qApp->applicationName(), qApp->applicationVersion())); + response->setHeader("Connection", m_closeAfterResponse ? "close" : "keep-alive"); + + /* Send response */ + m_socket->write(response->d->header.toString().toUtf8()); + m_socket->write(response->d->body); + + /* Emit signal */ + emit requestFinished(request, response); + + /* Destroy response */ + delete request; + response->deleteLater(); + } +} + +/** \internal + */ +class QDjangoHttpServerPrivate +{ +public: + int connectionCount; + QDjangoHttpController *requestHandler; + QTcpServer *tcpServer; +}; + +/** Constructs a new HTTP server. + */ +QDjangoHttpServer::QDjangoHttpServer(QObject *parent) + : QObject(parent), + d(new QDjangoHttpServerPrivate) +{ + d->connectionCount = 0; + d->requestHandler = 0; + d->tcpServer = 0; +} + +/** Destroys the HTTP server. + */ +QDjangoHttpServer::~QDjangoHttpServer() +{ + delete d; +} + +/** Returns the controller which serves requests received by the server. + */ +QDjangoHttpController *QDjangoHttpServer::controller() const +{ + return d->requestHandler; +} + +/** Sets the controller which serves requests received by the server. + * + * \param controller + */ +void QDjangoHttpServer::setController(QDjangoHttpController *controller) +{ + d->requestHandler = controller; +} + +/** 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); +} + +/** 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); + } +} diff --git a/src/http/QDjangoHttpServer.h b/src/http/QDjangoHttpServer.h new file mode 100644 index 0000000..ec67d04 --- /dev/null +++ b/src/http/QDjangoHttpServer.h @@ -0,0 +1,66 @@ +/* + * Copyright (C) 2010-2012 Jeremy Lainé + * Contact: http://code.google.com/p/qdjango/ + * + * This file is part of the QDjango Library. + * + * This program 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 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU Lesser General Public License + * along with this program. If not, see . + */ + +#ifndef QDJANGO_HTTP_SERVER_H +#define QDJANGO_HTTP_SERVER_H + +#include +#include + +class QDjangoHttpController; +class QDjangoHttpRequest; +class QDjangoHttpResponse; +class QDjangoHttpServer; +class QDjangoHttpServerPrivate; + +/** \defgroup Http */ + +/** \brief The QDjangoHttpServer class represents an HTTP server. + * + * \ingroup Http + */ +class QDjangoHttpServer : public QObject +{ + Q_OBJECT + +public: + QDjangoHttpServer(QObject *parent = 0); + ~QDjangoHttpServer(); + + QDjangoHttpController *controller() const; + void setController(QDjangoHttpController *controller); + + void close(); + bool listen(const QHostAddress &address, quint16 port); + +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 diff --git a/src/http/QDjangoHttpServer_p.h b/src/http/QDjangoHttpServer_p.h new file mode 100644 index 0000000..5bdf295 --- /dev/null +++ b/src/http/QDjangoHttpServer_p.h @@ -0,0 +1,82 @@ +/* + * Copyright (C) 2010-2012 Jeremy Lainé + * Contact: http://code.google.com/p/qdjango/ + * + * This file is part of the QDjango Library. + * + * This program 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 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU Lesser General Public License + * along with this program. If not, see . + */ + +#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 + +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 bytesWritten(qint64 bytes); + void handleData(); + void 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; + QHttpRequestHeader m_requestHeader; + QByteArray m_requestHeaderBuffer; + bool m_requestHeaderReceived; +}; + +#endif diff --git a/src/http/http.pro b/src/http/http.pro new file mode 100644 index 0000000..d9a4923 --- /dev/null +++ b/src/http/http.pro @@ -0,0 +1,26 @@ +include(../../qdjango.pri) + +TEMPLATE = lib +CONFIG += staticlib +QT += network + +TARGET = qdjango-http +VERSION = $$QDJANGO_VERSION +win32 { + DESTDIR = $$OUT_PWD +} + +HEADERS += \ + QDjangoFastCgiServer.h \ + QDjangoFastCgiServer_p.h \ + QDjangoHttpController.h \ + QDjangoHttpRequest.h \ + QDjangoHttpResponse.h \ + QDjangoHttpServer.h \ + QDjangoHttpServer_p.h +SOURCES += \ + QDjangoFastCgiServer.cpp \ + QDjangoHttpController.cpp \ + QDjangoHttpRequest.cpp \ + QDjangoHttpResponse.cpp \ + QDjangoHttpServer.cpp diff --git a/src/script/CMakeLists.txt b/src/script/CMakeLists.txt new file mode 100644 index 0000000..579a3a2 --- /dev/null +++ b/src/script/CMakeLists.txt @@ -0,0 +1,23 @@ +set(QT_DONT_USE_QTGUI 1) +set(QT_USE_QTSCRIPT 1) +set(QT_USE_QTSQL 1) +include(${QT_USE_FILE}) + +# QDjango script library +set(HEADERS + QDjangoScript.h + QDjangoScript_p.h) +set(SOURCES + QDjangoScript.cpp) + +add_library(qdjango-script ${QDJANGO_LIBRARY_TYPE} ${SOURCES}) +set_target_properties(qdjango-script PROPERTIES SOVERSION 0) +target_link_libraries(qdjango-script qdjango-db ${QT_QTSCRIPT_LIBRARY} ${QT_QTCORE_LIBRARY}) + +if(NOT QDJANGO_DONT_INSTALL) + install(FILES ${HEADERS} DESTINATION include/qdjango/script) + install(TARGETS qdjango-script + RUNTIME DESTINATION bin + LIBRARY DESTINATION lib + ARCHIVE DESTINATION lib) +endif() diff --git a/src/script/QDjangoScript.cpp b/src/script/QDjangoScript.cpp new file mode 100644 index 0000000..9fefb65 --- /dev/null +++ b/src/script/QDjangoScript.cpp @@ -0,0 +1,122 @@ +/* + * Copyright (C) 2010-2012 Jeremy Lainé + * Contact: http://code.google.com/p/qdjango/ + * + * This file is part of the QDjango Library. + * + * This program 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 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU Lesser General Public License + * along with this program. If not, see . + */ + +#include +#include +#include +#include + +#include "QDjangoScript.h" +#include "QDjangoWhere.h" + +QDjangoWhere QDjangoWhereFromScriptValue(QScriptEngine *engine, const QScriptValue &obj) +{ + if (obj.prototype().equals(engine->defaultPrototype(qMetaTypeId()))) { + return engine->fromScriptValue(obj); + } + + QDjangoWhere where; + QScriptValueIterator it(obj); + while (it.hasNext()) { + it.next(); + QString key = it.name(); + QDjangoWhere::Operation op = QDjangoWhere::Equals; + if (key.endsWith("__lt")) { + key.chop(4); + op = QDjangoWhere::LessThan; + } + else if (key.endsWith("__lte")) { + key.chop(5); + op = QDjangoWhere::LessOrEquals; + } + else if (key.endsWith("__gt")) { + key.chop(4); + op = QDjangoWhere::GreaterThan; + } + else if (key.endsWith("__gte")) { + key.chop(5); + op = QDjangoWhere::GreaterOrEquals; + } + else if (key.endsWith("__startswith")) { + key.chop(12); + op = QDjangoWhere::StartsWith; + } + else if (key.endsWith("__endswith")) { + key.chop(10); + op = QDjangoWhere::EndsWith; + } + else if (key.endsWith("__contains")) { + key.chop(10); + op = QDjangoWhere::Contains; + } + else if (key.endsWith("__in")) { + key.chop(4); + op = QDjangoWhere::IsIn; + } + where = where && QDjangoWhere(key, op, it.value().toVariant()); + } + return where; +} + +static QScriptValue newWhere(QScriptContext *context, QScriptEngine *engine) +{ + QDjangoWhere where; + if (context->argumentCount() == 1 && context->argument(0).isObject()) { + where = QDjangoWhereFromScriptValue(engine, context->argument(0)); + } + return engine->toScriptValue(where); +} + +static QScriptValue whereAnd(QScriptContext *context, QScriptEngine *engine) +{ + QDjangoWhere q = engine->fromScriptValue(context->thisObject()); + QDjangoWhere other = QDjangoWhereFromScriptValue(engine, context->argument(0)); + return engine->toScriptValue(q && other); +} + +static QScriptValue whereOr(QScriptContext *context, QScriptEngine *engine) +{ + QDjangoWhere q = engine->fromScriptValue(context->thisObject()); + QDjangoWhere other = QDjangoWhereFromScriptValue(engine, context->argument(0)); + return engine->toScriptValue(q || other); +} + +static QScriptValue whereToString(QScriptContext *context, QScriptEngine *engine) +{ + QDjangoWhere q = engine->fromScriptValue(context->thisObject()); + return engine->toScriptValue("Q(" + q.sql(QDjango::database()) + ")"); +} + +/** Makes the QDjangoWhere class available to the given QScriptEngine. + * + * \param engine + */ +void QDjangoScript::registerWhere(QScriptEngine *engine) +{ + QScriptValue whereProto = engine->newObject(); + whereProto.setProperty("and", engine->newFunction(whereAnd)); + whereProto.setProperty("or", engine->newFunction(whereOr)); + whereProto.setProperty("toString", engine->newFunction(whereToString)); + engine->setDefaultPrototype(qMetaTypeId(), whereProto); + + QScriptValue ctor = engine->newFunction(newWhere); + engine->globalObject().setProperty("Q", ctor, QScriptValue::ReadOnly); +} + diff --git a/src/script/QDjangoScript.h b/src/script/QDjangoScript.h new file mode 100644 index 0000000..10e7683 --- /dev/null +++ b/src/script/QDjangoScript.h @@ -0,0 +1,76 @@ +/* + * Copyright (C) 2010-2012 Jeremy Lainé + * Contact: http://code.google.com/p/qdjango/ + * + * This file is part of the QDjango Library. + * + * This program 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 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU Lesser General Public License + * along with this program. If not, see . + */ + +#ifndef QDJANGO_SCRIPT_H +#define QDJANGO_SCRIPT_H + +#include +#include + +#include "QDjango.h" +#include "QDjangoQuerySet.h" +#include "QDjangoScript_p.h" + +Q_DECLARE_METATYPE(QDjangoWhere) + +/** \defgroup Script */ + +/** \brief The QDjangoScript class provides static methods for making models + * scriptable. + * + * \ingroup Script + */ +class QDjangoScript +{ +public: + template + static void registerModel(QScriptEngine *engine); + static void registerWhere(QScriptEngine *engine); +}; + +/** Makes a QDjangoModel class available to the given QScriptEngine. + * + * \param engine + */ +template +void QDjangoScript::registerModel(QScriptEngine *engine) +{ + QDjango::registerModel(); + + QScriptValue querysetProto = engine->newObject(); + querysetProto.setProperty("all", engine->newFunction(QDjangoQuerySet_all)); + querysetProto.setProperty("at", engine->newFunction(QDjangoQuerySet_at)); + querysetProto.setProperty("count", engine->newFunction(QDjangoQuerySet_count)); + querysetProto.setProperty("exclude", engine->newFunction(QDjangoQuerySet_exclude)); + querysetProto.setProperty("filter", engine->newFunction(QDjangoQuerySet_filter)); + querysetProto.setProperty("get", engine->newFunction(QDjangoQuerySet_get)); + querysetProto.setProperty("limit", engine->newFunction(QDjangoQuerySet_limit)); + querysetProto.setProperty("remove", engine->newFunction(QDjangoQuerySet_remove)); + querysetProto.setProperty("size", engine->newFunction(QDjangoQuerySet_size)); + querysetProto.setProperty("toString", engine->newFunction(QDjangoQuerySet_toString)); + engine->setDefaultPrototype(qMetaTypeId< QDjangoQuerySet >(), querysetProto); + + QDjangoQuerySet qs; + QScriptValue value = engine->newQMetaObject(&T::staticMetaObject, engine->newFunction(QDjangoModel_new)); + value.setProperty("objects", engine->toScriptValue(qs)); + engine->globalObject().setProperty(T::staticMetaObject.className(), value); +} + +#endif diff --git a/src/script/QDjangoScript_p.h b/src/script/QDjangoScript_p.h new file mode 100644 index 0000000..cdb682c --- /dev/null +++ b/src/script/QDjangoScript_p.h @@ -0,0 +1,117 @@ +/* + * Copyright (C) 2010-2012 Jeremy Lainé + * Contact: http://code.google.com/p/qdjango/ + * + * This file is part of the QDjango Library. + * + * This program 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 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU Lesser General Public License + * along with this program. If not, see . + */ + +#ifndef QDJANGO_SCRIPT_P_H +#define QDJANGO_SCRIPT_P_H + +// +// W A R N I N G +// ------------- +// +// This file is not part of the QDjango API. +// + +QDjangoWhere QDjangoWhereFromScriptValue(QScriptEngine *engine, const QScriptValue &obj); + +template +static QScriptValue QDjangoQuerySet_all(QScriptContext *context, QScriptEngine *engine) +{ + QDjangoQuerySet qs = engine->fromScriptValue< QDjangoQuerySet >(context->thisObject()); + return engine->toScriptValue(qs.all()); +} + +template +static QScriptValue QDjangoQuerySet_at(QScriptContext *context, QScriptEngine *engine) +{ + QDjangoQuerySet qs = engine->fromScriptValue< QDjangoQuerySet >(context->thisObject()); + //QDjangoQuerySet qs = context->thisObject().toVariant().value< QDjangoQuerySet >(); + int index = context->argument(0).toInteger(); + return engine->newQObject(qs.at(index), QScriptEngine::ScriptOwnership); +} + +template +static QScriptValue QDjangoQuerySet_count(QScriptContext *context, QScriptEngine *engine) +{ + QDjangoQuerySet qs = engine->fromScriptValue< QDjangoQuerySet >(context->thisObject()); + return QScriptValue(engine, qs.count()); +} + +template +static QScriptValue QDjangoQuerySet_exclude(QScriptContext *context, QScriptEngine *engine) +{ + QDjangoQuerySet qs = engine->fromScriptValue< QDjangoQuerySet >(context->thisObject()); + QDjangoWhere where = QDjangoWhereFromScriptValue(engine, context->argument(0)); + return engine->toScriptValue(qs.exclude(where)); +} + +template +static QScriptValue QDjangoQuerySet_filter(QScriptContext *context, QScriptEngine *engine) +{ + QDjangoQuerySet qs = engine->fromScriptValue< QDjangoQuerySet >(context->thisObject()); + QDjangoWhere where = QDjangoWhereFromScriptValue(engine, context->argument(0)); + return engine->toScriptValue(qs.filter(where)); +} + +template +static QScriptValue QDjangoQuerySet_get(QScriptContext *context, QScriptEngine *engine) +{ + QDjangoQuerySet qs = engine->fromScriptValue< QDjangoQuerySet >(context->thisObject()); + QDjangoWhere where = QDjangoWhereFromScriptValue(engine, context->argument(0)); + return engine->newQObject(qs.get(where), QScriptEngine::ScriptOwnership); +} + +template +static QScriptValue QDjangoQuerySet_limit(QScriptContext *context, QScriptEngine *engine) +{ + QDjangoQuerySet qs = engine->fromScriptValue< QDjangoQuerySet >(context->thisObject()); + const int pos = context->argument(0).toInteger(); + const int limit = (context->argumentCount() > 1) ? context->argument(1).toInteger() : 1; + return engine->toScriptValue(qs.limit(pos, limit)); +} + +template +static QScriptValue QDjangoQuerySet_remove(QScriptContext *context, QScriptEngine *engine) +{ + QDjangoQuerySet qs = engine->fromScriptValue< QDjangoQuerySet >(context->thisObject()); + return QScriptValue(engine, qs.remove()); +} + +template +static QScriptValue QDjangoQuerySet_size(QScriptContext *context, QScriptEngine *engine) +{ + QDjangoQuerySet qs = engine->fromScriptValue< QDjangoQuerySet >(context->thisObject()); + return QScriptValue(engine, qs.size()); +} + +template +static QScriptValue QDjangoQuerySet_toString(QScriptContext *context, QScriptEngine *engine) +{ + QDjangoQuerySet qs = engine->fromScriptValue< QDjangoQuerySet >(context->thisObject()); + return QScriptValue(engine, QString("QuerySet<%1>(%2)").arg(T::staticMetaObject.className(), qs.where().sql(QDjango::database()))); +} + +template +static QScriptValue QDjangoModel_new(QScriptContext *context, QScriptEngine *engine) +{ + Q_UNUSED(context); + return engine->newQObject(new T, QScriptEngine::ScriptOwnership); +} + +#endif diff --git a/src/script/script.pro b/src/script/script.pro new file mode 100644 index 0000000..a0ee896 --- /dev/null +++ b/src/script/script.pro @@ -0,0 +1,15 @@ +include(../../qdjango.pri) + +TEMPLATE = lib +CONFIG += staticlib +QT += script sql + +TARGET = qdjango-script +VERSION = $$QDJANGO_VERSION +win32 { + DESTDIR = $$OUT_PWD +} + +INCLUDEPATH += ../db +HEADERS += QDjangoScript.h +SOURCES += QDjangoScript.cpp diff --git a/src/src.pro b/src/src.pro new file mode 100644 index 0000000..7e1cc35 --- /dev/null +++ b/src/src.pro @@ -0,0 +1,5 @@ +TEMPLATE = subdirs + +SUBDIRS = db http script + +CONFIG += ordered diff --git a/tests/CMakeLists.txt b/tests/CMakeLists.txt new file mode 100644 index 0000000..732bd1e --- /dev/null +++ b/tests/CMakeLists.txt @@ -0,0 +1,35 @@ +set(QT_DONT_USE_QTGUI 1) +set(QT_USE_QTNETWORK 1) +set(QT_USE_QTSQL 1) +set(QT_USE_QTTEST 1) +include(${QT_USE_FILE}) + +include_directories(${CMAKE_CURRENT_SOURCE_DIR}) + +# test models +set(qdjango-models_SOURCES auth-models.cpp shares-models.cpp) +set(qdjango-models_MOC_HEADERS auth-models.h shares-models.h) + +qt4_wrap_cpp(qdjango-models_MOC_SOURCES ${qdjango-models_MOC_HEADERS}) +add_library(qdjango-models STATIC ${qdjango-models_SOURCES} ${qdjango-models_MOC_SOURCES}) +target_link_libraries(qdjango-models qdjango-db) + +# test program +set(qdjango-tests_SOURCES + fields.cpp + http.cpp + main.cpp + script.cpp + auth-tests.cpp + shares-tests.cpp) +set(qdjango-tests_MOC_HEADERS + fields.h + http.h + main.h + script.h + auth-tests.h + shares-tests.h) +qt4_wrap_cpp(qdjango-tests_MOC_SOURCES ${qdjango-tests_MOC_HEADERS}) +add_executable(qdjango-tests ${qdjango-tests_SOURCES} ${qdjango-tests_MOC_SOURCES}) +target_link_libraries(qdjango-tests qdjango-db qdjango-http qdjango-models qdjango-script ${QT_LIBRARIES}) + diff --git a/tests/auth-models.cpp b/tests/auth-models.cpp new file mode 100644 index 0000000..0d37796 --- /dev/null +++ b/tests/auth-models.cpp @@ -0,0 +1,208 @@ +/* + * Copyright (C) 2010-2012 Jeremy Lainé + * Contact: http://code.google.com/p/qdjango/ + * + * This file is part of the QDjango Library. + * + * This program 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 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU Lesser General Public License + * along with this program. If not, see . + */ + +#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*) + diff --git a/tests/auth-models.h b/tests/auth-models.h new file mode 100644 index 0000000..53b155b --- /dev/null +++ b/tests/auth-models.h @@ -0,0 +1,154 @@ +/* + * Copyright (C) 2010-2012 Jeremy Lainé + * Contact: http://code.google.com/p/qdjango/ + * + * This file is part of the QDjango Library. + * + * This program 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 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU Lesser General Public License + * along with this program. If not, see . + */ + +#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 diff --git a/tests/auth-tests.cpp b/tests/auth-tests.cpp new file mode 100644 index 0000000..510beab --- /dev/null +++ b/tests/auth-tests.cpp @@ -0,0 +1,728 @@ +/* + * Copyright (C) 2010-2012 Jeremy Lainé + * Contact: http://code.google.com/p/qdjango/ + * + * This file is part of the QDjango Library. + * + * This program 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 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU Lesser General Public License + * along with this program. If not, see . + */ + +#include + +#include "QDjangoQuerySet.h" +#include "QDjangoWhere.h" + +#include "main.h" +#include "auth-models.h" +#include "auth-tests.h" + +/** Create database table before running tests. + */ +void TestUser::initTestCase() +{ + QCOMPARE(QDjango::registerModel().createTable(), true); +} + +/** Load fixtures consisting of 3 users. + */ +void TestUser::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 TestUser::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 TestUser::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 TestUser::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 TestUser::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 TestUser::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 TestUser::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 TestUser::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 TestUser::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 TestUser::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 TestUser::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 TestUser::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 retrieving maps of values. + */ +void TestUser::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 TestUser::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 TestUser::constIterator() +{ + loadFixtures(); + QVERIFY(not 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 TestUser::cleanup() +{ + QCOMPARE(QDjangoQuerySet().remove(), true); +} + +/** Drop database table after running tests. + */ +void TestUser::cleanupTestCase() +{ + QCOMPARE(QDjango::registerModel().dropTable(), true); +} + +/** Create database tables before running tests. + */ +void TestRelated::initTestCase() +{ + QCOMPARE(QDjango::registerModel().createTable(), true); + QCOMPARE(QDjango::registerModel().createTable(), true); + QCOMPARE(QDjango::registerModel().createTable(), true); + QCOMPARE(QDjango::registerModel().createTable(), true); +} + +/** Set and get foreign key on a Message object. + */ +void TestRelated::testRelated() +{ + const QDjangoQuerySet messages; + // load fixtures + QVariant userPk; + { + User *user = new 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 TestRelated::filterRelated() +{ + const QDjangoQuerySet messages; + // load fixtures + QVariant userPk; + { + User *user = new 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 TestRelated::testGroups() +{ + const QDjangoQuerySet userGroups; + + User *user = new User; + user->setUsername("foouser"); + user->setPassword("foopass"); + QCOMPARE(user->save(), true); + + Group *group = new 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; +} + +/** Clear database tables after each test. + */ +void TestRelated::cleanup() +{ + QCOMPARE(QDjangoQuerySet().remove(), true); + QCOMPARE(QDjangoQuerySet().remove(), true); + QCOMPARE(QDjangoQuerySet().remove(), true); + QCOMPARE(QDjangoQuerySet().remove(), true); +} + +/** Drop database tables after running tests. + */ +void TestRelated::cleanupTestCase() +{ + QCOMPARE(QDjango::registerModel().dropTable(), true); + QCOMPARE(QDjango::registerModel().dropTable(), true); + QCOMPARE(QDjango::registerModel().dropTable(), true); + QCOMPARE(QDjango::registerModel().dropTable(), true); +} + diff --git a/tests/auth-tests.h b/tests/auth-tests.h new file mode 100644 index 0000000..47109e6 --- /dev/null +++ b/tests/auth-tests.h @@ -0,0 +1,64 @@ +/* + * Copyright (C) 2010-2012 Jeremy Lainé + * Contact: http://code.google.com/p/qdjango/ + * + * This file is part of the QDjango Library. + * + * This program 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 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU Lesser General Public License + * along with this program. If not, see . + */ + +#include + +/** Tests for the User class. + */ +class TestUser: 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 values(); + void valuesList(); + void constIterator(); + void cleanup(); + void cleanupTestCase(); + +private: + void loadFixtures(); +}; + +class TestRelated : public QObject +{ + Q_OBJECT + +private slots: + void initTestCase(); + void testGroups(); + void testRelated(); + void filterRelated(); + void cleanup(); + void cleanupTestCase(); +}; + diff --git a/tests/fields.cpp b/tests/fields.cpp new file mode 100644 index 0000000..7ee76a4 --- /dev/null +++ b/tests/fields.cpp @@ -0,0 +1,126 @@ +/* + * Copyright (C) 2010-2012 Jeremy Lainé + * Contact: http://code.google.com/p/qdjango/ + * + * This file is part of the QDjango Library. + * + * This program 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 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU Lesser General Public License + * along with this program. If not, see . + */ + +#include + +#include "QDjango.h" +#include "QDjango_p.h" +#include "QDjangoQuerySet.h" +#include "QDjangoWhere.h" +#include "fields.h" + +#define Q QDjangoWhere + +template +void init() +{ + const QDjangoMetaModel metaModel = QDjango::registerModel(); + QCOMPARE(metaModel.isValid(), true); + QCOMPARE(metaModel.createTable(), true); +} + +template +void setAndGet(const K &value) +{ + T v1; + v1.setValue(value); + QCOMPARE(v1.save(), true); + + T v2; + QVERIFY(QDjangoQuerySet().get(Q("pk", Q::Equals, v1.pk()), &v2) != 0); + QCOMPARE(v2.value(), value); +} + +template +void cleanup() +{ + const QDjangoMetaModel metaModel = QDjango::registerModel(); + QCOMPARE(metaModel.dropTable(), true); +} + +void tst_Bool::testValue() +{ + init(); + setAndGet(true); + setAndGet(false); + cleanup(); +} + +void tst_ByteArray::testValue() +{ + init(); + setAndGet(QByteArray("01234567", 8)); + setAndGet(QByteArray("\x00\x01\x02\x03\x04\x05\x06\x07", 8)); + cleanup(); +} + +void tst_Date::testValue() +{ + init(); + setAndGet(QDate(2012, 1, 8)); + cleanup(); +} + +void tst_DateTime::testValue() +{ + init(); + setAndGet(QDateTime(QDate(2012, 1, 8), QTime(3, 4, 5))); + cleanup(); +} + +void tst_Double::testValue() +{ + init(); + setAndGet(double(3.14159));; + cleanup(); +} + +void tst_Integer::testValue() +{ + init(); + setAndGet(0); + setAndGet(-2147483647); + setAndGet(2147483647); + cleanup(); +} + +void tst_LongLong::testValue() +{ + init(); + setAndGet(qlonglong(0)); + setAndGet(qlonglong(-9223372036854775807ll)); + setAndGet(qlonglong(9223372036854775807ll)); + cleanup(); +} + +void tst_String::testValue() +{ + init(); + setAndGet(QString("foo bar")); + cleanup(); +} + +void tst_Time::testValue() +{ + init(); + setAndGet(QTime(3, 4, 5)); + cleanup(); +} + diff --git a/tests/fields.h b/tests/fields.h new file mode 100644 index 0000000..ae0dd53 --- /dev/null +++ b/tests/fields.h @@ -0,0 +1,169 @@ +/* + * Copyright (C) 2010-2012 Jeremy Lainé + * Contact: http://code.google.com/p/qdjango/ + * + * This file is part of the QDjango Library. + * + * This program 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 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU Lesser General Public License + * along with this program. If not, see . + */ + +#include + +#include "QDjangoModel.h" + +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 slots: + void testValue(); + +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 slots: + void testValue(); + +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 slots: + void testValue(); + +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 slots: + void testValue(); + +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 slots: + void testValue(); + +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 slots: + void testValue(); + +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 slots: + void testValue(); + +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 slots: + void testValue(); + +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 slots: + void testValue(); + +private: + QTime m_value; +}; + diff --git a/tests/http.cpp b/tests/http.cpp new file mode 100644 index 0000000..cc7785f --- /dev/null +++ b/tests/http.cpp @@ -0,0 +1,100 @@ +/* + * Copyright (C) 2010-2012 Jeremy Lainé + * Contact: http://code.google.com/p/qdjango/ + * + * This file is part of the QDjango Library. + * + * This program 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 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU Lesser General Public License + * along with this program. If not, see . + */ + +#include +#include +#include +#include +#include + +#include "QDjangoHttpController.h" +#include "QDjangoHttpRequest.h" +#include "QDjangoHttpResponse.h" +#include "QDjangoHttpServer.h" + +#include "http.h" + +class TestController : public QDjangoHttpController +{ + QDjangoHttpResponse *respondToRequest(const QDjangoHttpRequest &request); +}; + +QDjangoHttpResponse *TestController::respondToRequest(const QDjangoHttpRequest &request) +{ + if (request.path() == "/") { + QDjangoHttpResponse *response = new QDjangoHttpResponse; + response->setHeader("Content-Type", "text/plain"); + response->setBody("hello"); + return response; + } else if (request.path() == "/internal-server-error") { + return serveInternalServerError(request); + } + return serveNotFound(request); +} + +void TestHttp::cleanupTestCase() +{ + delete httpServer; + delete httpController; +} + +void TestHttp::initTestCase() +{ + httpController = new TestController; + httpServer = new QDjangoHttpServer; + httpServer->setController(httpController); + QCOMPARE(httpServer->listen(QHostAddress::LocalHost, 8123), true); +} + +void TestHttp::testGet_data() +{ + QTest::addColumn("path"); + QTest::addColumn("err"); + QTest::addColumn("body"); + + const QString errorTemplate( + "" + "Error" + "

%1

" + ""); + + QTest::newRow("root") << "/" << int(QNetworkReply::NoError) << QByteArray("hello"); + QTest::newRow("not-found") << "/not-found" << int(QNetworkReply::ContentNotFoundError) << errorTemplate.arg("The document you requested was not found.").toUtf8(); + QTest::newRow("internal-server-error") << "/internal-server-error" << int(QNetworkReply::UnknownContentError) << errorTemplate.arg("An internal server error was encountered.").toUtf8(); +} + +void TestHttp::testGet() +{ + QFETCH(QString, path); + QFETCH(int, err); + QFETCH(QByteArray, body); + + QNetworkAccessManager network; + QNetworkReply *reply = network.get(QNetworkRequest(QUrl("http://127.0.0.1:8123" + path))); + + QEventLoop loop; + QObject::connect(reply, SIGNAL(finished()), &loop, SLOT(quit())); + loop.exec(); + + QCOMPARE(int(reply->error()), err); + QCOMPARE(reply->readAll(), body); + delete reply; +} + diff --git a/tests/http.h b/tests/http.h new file mode 100644 index 0000000..6d3d6ab --- /dev/null +++ b/tests/http.h @@ -0,0 +1,42 @@ +/* + * Copyright (C) 2010-2012 Jeremy Lainé + * Contact: http://code.google.com/p/qdjango/ + * + * This file is part of the QDjango Library. + * + * This program 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 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU Lesser General Public License + * along with this program. If not, see . + */ + +#include + +class QDjangoHttpController; +class QDjangoHttpServer; + +/** Test QDjangoServer class. + */ +class TestHttp : public QObject +{ + Q_OBJECT + +private slots: + void cleanupTestCase(); + void initTestCase(); + void testGet_data(); + void testGet(); + +private: + QDjangoHttpController *httpController; + QDjangoHttpServer *httpServer; +}; + diff --git a/tests/main.cpp b/tests/main.cpp new file mode 100644 index 0000000..9378dd5 --- /dev/null +++ b/tests/main.cpp @@ -0,0 +1,771 @@ +/* + * Copyright (C) 2010-2012 Jeremy Lainé + * Contact: http://code.google.com/p/qdjango/ + * + * This file is part of the QDjango Library. + * + * This program 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 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU Lesser General Public License + * along with this program. If not, see . + */ + +#include + +#include +#include +#include +#include +#include + +#include "QDjango.h" +#include "QDjangoQuerySet.h" +#include "QDjangoWhere.h" + +#include "main.h" +#include "auth-models.h" +#include "auth-tests.h" +#include "fields.h" +#include "shares-models.h" +#include "shares-tests.h" +#include "http.h" +#include "script.h" + +static QString escapeField(const QSqlDatabase &db, const QString &name) +{ + return db.driver()->escapeIdentifier(name, QSqlDriver::FieldName); +} + +static QString escapeTable(const QSqlDatabase &db, const QString &name) +{ + return db.driver()->escapeIdentifier(name, QSqlDriver::TableName); +} + +Object::Object(QObject *parent) + : QObject(parent), + m_bar(0), + m_wiz(0), + m_zoo(0) +{ +} + +QString Object::foo() const +{ + return m_foo; +} + +void Object::setFoo(const QString &foo) +{ + m_foo = foo; +} + +int Object::bar() const +{ + return m_bar; +} + +void Object::setBar(int bar) +{ + m_bar = bar; +} + +int Object::wiz() const +{ + return m_wiz; +} + +void Object::setWiz(int wiz) +{ + m_wiz = wiz; +} + +int Object::zoo() const +{ + return m_zoo; +} + +void Object::setZoo(int zoo) +{ + m_zoo = zoo; +} + +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); +} + +void tst_QDjangoCompiler::initTestCase() +{ + QDjango::registerModel(); + QDjango::registerModel(); +} + +void tst_QDjangoCompiler::fieldNames() +{ + QSqlDatabase db = QDjango::database(); + + QDjangoCompiler compiler("Owner", db); + QCOMPARE(compiler.fieldNames(false), QStringList() + << escapeTable(db, "owner") + "." + escapeField(db, "id") + << escapeTable(db, "owner") + "." + escapeField(db, "name") + << escapeTable(db, "owner") + "." + escapeField(db, "item1_id") + << escapeTable(db, "owner") + "." + escapeField(db, "item2_id")); + QCOMPARE(compiler.fromSql(), escapeTable(db, "owner")); +} + +void tst_QDjangoCompiler::fieldNamesRecursive() +{ + QSqlDatabase db = QDjango::database(); + + QDjangoCompiler compiler("Owner", db); + QCOMPARE(compiler.fieldNames(true), QStringList() + << escapeTable(db, "owner") + "." + escapeField(db, "id") + << escapeTable(db, "owner") + "." + escapeField(db, "name") + << escapeTable(db, "owner") + "." + escapeField(db, "item1_id") + << escapeTable(db, "owner") + "." + escapeField(db, "item2_id") + << "T0." + escapeField(db, "id") + << "T0." + escapeField(db, "name") + << "T1." + escapeField(db, "id") + << "T1." + escapeField(db, "name")); + QCOMPARE(compiler.fromSql(), QString("%1 INNER JOIN %2 T0 ON T0.%3 = %4.%5 INNER JOIN %6 T1 ON T1.%7 = %8.%9").arg( + escapeTable(db, "owner"), + escapeTable(db, "item"), + escapeField(db, "id"), + escapeTable(db, "owner"), + escapeField(db, "item1_id"), + escapeTable(db, "item"), + escapeField(db, "id"), + escapeTable(db, "owner"), + escapeField(db, "item2_id"))); +} + +void tst_QDjangoCompiler::orderLimit() +{ + QSqlDatabase db = QDjango::database(); + + QDjangoCompiler compiler("Owner", db); + QCOMPARE(compiler.orderLimitSql(QStringList("name"), 0, 0), QString(" ORDER BY %1.%2 ASC").arg( + escapeTable(db, "owner"), + escapeField(db, "name"))); + QCOMPARE(compiler.fromSql(), escapeTable(db, "owner")); + + compiler = QDjangoCompiler("Owner", db); + QCOMPARE(compiler.orderLimitSql(QStringList("-name"), 0, 0), QString(" ORDER BY %1.%2 DESC").arg( + escapeTable(db, "owner"), + escapeField(db, "name"))); + QCOMPARE(compiler.fromSql(), escapeTable(db, "owner")); + + compiler = QDjangoCompiler("Owner", db); + QCOMPARE(compiler.orderLimitSql(QStringList("item1__name"), 0, 0), QString(" ORDER BY T0.%1 ASC").arg( + escapeField(db, "name"))); + QCOMPARE(compiler.fromSql(), QString("%1 INNER JOIN %2 T0 ON T0.%3 = %4.%5").arg( + escapeTable(db, "owner"), + escapeTable(db, "item"), + escapeField(db, "id"), + escapeTable(db, "owner"), + escapeField(db, "item1_id"))); + compiler = QDjangoCompiler("Owner", db); + QCOMPARE(compiler.orderLimitSql(QStringList() << "item1__name" << "item2__name", 0, 0), QString(" ORDER BY T0.%1 ASC, T1.%2 ASC").arg( + escapeField(db, "name"), + escapeField(db, "name"))); + QCOMPARE(compiler.fromSql(), QString("%1 INNER JOIN %2 T0 ON T0.%3 = %4.%5 INNER JOIN %6 T1 ON T1.%7 = %8.%9").arg( + escapeTable(db, "owner"), + escapeTable(db, "item"), + escapeField(db, "id"), + escapeTable(db, "owner"), + escapeField(db, "item1_id"), + escapeTable(db, "item"), + escapeField(db, "id"), + escapeTable(db, "owner"), + escapeField(db, "item2_id"))); +} + +void tst_QDjangoCompiler::resolve() +{ + QSqlDatabase db = QDjango::database(); + + QDjangoCompiler compiler("Owner", db); + QDjangoWhere where("name", QDjangoWhere::Equals, "foo"); + compiler.resolve(where); + CHECKWHERE(where, QLatin1String("\"owner\".\"name\" = ?"), QVariantList() << "foo"); + QCOMPARE(compiler.fromSql(), escapeTable(db, "owner")); + + compiler = QDjangoCompiler("Owner", db); + where = QDjangoWhere("item1__name", QDjangoWhere::Equals, "foo"); + compiler.resolve(where); + CHECKWHERE(where, QLatin1String("T0.\"name\" = ?"), QVariantList() << "foo"); + QCOMPARE(compiler.fromSql(), QString("%1 INNER JOIN %2 T0 ON T0.%3 = %4.%5").arg( + escapeTable(db, "owner"), + escapeTable(db, "item"), + escapeField(db, "id"), + escapeTable(db, "owner"), + escapeField(db, "item1_id"))); + + compiler = QDjangoCompiler("Owner", db); + where = QDjangoWhere("item1__name", QDjangoWhere::Equals, "foo") + && QDjangoWhere("item2__name", QDjangoWhere::Equals, "bar"); + compiler.resolve(where); + CHECKWHERE(where, QLatin1String("T0.\"name\" = ? AND T1.\"name\" = ?"), QVariantList() << "foo" << "bar"); + QCOMPARE(compiler.fromSql(), QString("%1 INNER JOIN %2 T0 ON T0.%3 = %4.%5 INNER JOIN %6 T1 ON T1.%7 = %8.%9").arg( + escapeTable(db, "owner"), + escapeTable(db, "item"), + escapeField(db, "id"), + escapeTable(db, "owner"), + escapeField(db, "item1_id"), + escapeTable(db, "item"), + escapeField(db, "id"), + escapeTable(db, "owner"), + escapeField(db, "item2_id"))); +} + +void tst_QDjangoMetaModel::initTestCase() +{ + metaModel = QDjango::registerModel(); + QCOMPARE(metaModel.isValid(), true); + QCOMPARE(metaModel.createTable(), true); +} + +void tst_QDjangoMetaModel::options() +{ + const QList localFields = metaModel.localFields(); + QCOMPARE(metaModel.table(), QLatin1String("foo_table")); + QCOMPARE(metaModel.primaryKey(), QByteArray("id")); + QCOMPARE(localFields.size(), 4); + QCOMPARE(localFields[0].name, QByteArray("id")); + QCOMPARE(localFields[0].autoIncrement, true); + QCOMPARE(localFields[0].maxLength, 0); + QCOMPARE(localFields[0].index, false); + QCOMPARE(localFields[0].unique, true); + QCOMPARE(localFields[1].name, QByteArray("foo")); + QCOMPARE(localFields[1].autoIncrement, false); + QCOMPARE(localFields[1].index, false); + QCOMPARE(localFields[1].maxLength, 255); + QCOMPARE(localFields[1].unique, false); + QCOMPARE(localFields[2].name, QByteArray("bar")); + QCOMPARE(localFields[2].autoIncrement, false); + QCOMPARE(localFields[2].index, true); + QCOMPARE(localFields[2].maxLength, 0); + QCOMPARE(localFields[2].unique, false); + QCOMPARE(localFields[3].name, QByteArray("zoo")); + QCOMPARE(localFields[3].autoIncrement, false); + QCOMPARE(localFields[3].index, false); + QCOMPARE(localFields[3].maxLength, 0); + QCOMPARE(localFields[3].unique, true); +} + +void tst_QDjangoMetaModel::save() +{ + Object obj; + obj.setFoo("some string"); + obj.setBar(1234); + QCOMPARE(metaModel.save(&obj), true); + QCOMPARE(obj.property("id"), QVariant(1)); +} + +void tst_QDjangoMetaModel::cleanupTestCase() +{ + metaModel.dropTable(); +} + +/** Create database tables before running tests. + */ +void tst_QDjangoModel::initTestCase() +{ + QCOMPARE(QDjango::registerModel().createTable(), true); + QCOMPARE(QDjango::registerModel().createTable(), true); +} + +/** Perform filtering on foreign keys. + */ +void tst_QDjangoModel::filterRelated() +{ + // load fixtures + { + Item *item1 = new Item; + item1->setName("first"); + QCOMPARE(item1->save(), true); + + Item *item2 = new Item; + item2->setName("second"); + QCOMPARE(item2->save(), true); + + Owner owner; + owner.setName("owner"); + owner.setItem1(item1); + owner.setItem2(item2); + QCOMPARE(owner.save(), true); + } + + // perform filtering + QDjangoQuerySet owners; + + QDjangoQuerySet qs = owners.filter( + QDjangoWhere("item1__name", QDjangoWhere::Equals, "first")); + CHECKWHERE(qs.where(), QLatin1String("T0.\"name\" = ?"), QVariantList() << "first"); + QCOMPARE(qs.count(), 1); + QCOMPARE(qs.size(), 1); + + Owner *owner = qs.at(0); + QVERIFY(owner != 0); + QCOMPARE(owner->name(), QLatin1String("owner")); + delete owner; +} + +/** Test eager loading of foreign keys. + */ +void tst_QDjangoModel::selectRelated() +{ + // load fixtures + { + Item *item1 = new Item; + item1->setName("first"); + QCOMPARE(item1->save(), true); + + Item *item2 = new Item; + item2->setName("second"); + QCOMPARE(item2->save(), true); + + Owner owner; + owner.setName("owner"); + owner.setItem1(item1); + owner.setItem2(item2); + QCOMPARE(owner.save(), true); + } + + // without eager loading + QDjangoQuerySet qs; + Owner *owner = qs.get(QDjangoWhere("name", QDjangoWhere::Equals, "owner")); + QVERIFY(owner != 0); + QCOMPARE(owner->item1()->name(), QLatin1String("first")); + QCOMPARE(owner->item2()->name(), QLatin1String("second")); + delete owner; + + // with eager loading + owner = qs.selectRelated().get(QDjangoWhere("name", QDjangoWhere::Equals, "owner")); + QVERIFY(owner != 0); + QCOMPARE(owner->item1()->name(), QLatin1String("first")); + QCOMPARE(owner->item2()->name(), QLatin1String("second")); + delete owner; +} + +/** Clear database tables after each test. + */ +void tst_QDjangoModel::cleanup() +{ + QCOMPARE(QDjangoQuerySet().remove(), true); + QCOMPARE(QDjangoQuerySet().remove(), true); +} + +/** Drop database tables after running tests. + */ +void tst_QDjangoModel::cleanupTestCase() +{ + QCOMPARE(QDjango::registerModel().dropTable(), true); + QCOMPARE(QDjango::registerModel().dropTable(), true); +} + +/** 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 "!=" 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 ">" 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); +} + +/** Test "startswith" comparison. + */ +void tst_QDjangoWhere::startsWith() +{ + QDjangoWhere testQuery = QDjangoWhere("name", QDjangoWhere::StartsWith, "abc"); + CHECKWHERE(testQuery, QLatin1String("name LIKE ?"), QVariantList() << "abc%"); +} + +/** Test "endswith" comparison. + */ +void tst_QDjangoWhere::endsWith() +{ + QDjangoWhere testQuery = QDjangoWhere("name", QDjangoWhere::EndsWith, "abc"); + CHECKWHERE(testQuery, QLatin1String("name LIKE ?"), QVariantList() << "%abc"); +} + +/** Test "contains" comparison. + */ +void tst_QDjangoWhere::contains() +{ + QDjangoWhere testQuery = QDjangoWhere("name", QDjangoWhere::Contains, "abc"); + CHECKWHERE(testQuery, QLatin1String("name 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"); +} + +/** Display program usage. + */ +static void usage() +{ + fprintf(stderr, "Usage: qdjango-test [-d ] [-h ] [-n ] [-u ] [-p ]\n"); +} + +int main(int argc, char *argv[]) +{ + QCoreApplication app(argc, argv); + + // initialise options + QString databaseDriver = "QSQLITE"; + QString databaseName = ":memory:"; + QString databaseUser; + QString databasePassword; + QString databaseHost; + int count = 1; + + // parse command line arguments + if (!(argc % 2)) + { + usage(); + return EXIT_FAILURE; + } + for (int i = 1; i < argc; i++) + { + if (!strcmp(argv[i], "-c") && i < argc - 1) + count = QString::fromLocal8Bit(argv[++i]).toInt(); + else if (!strcmp(argv[i], "-d") && i < argc - 1) + databaseDriver = QString::fromLocal8Bit(argv[++i]); + else if (!strcmp(argv[i], "-h") && i < argc - 1) + databaseHost = QString::fromLocal8Bit(argv[++i]); + else if (!strcmp(argv[i], "-n") && i < argc - 1) + databaseName = QString::fromLocal8Bit(argv[++i]); + else if (!strcmp(argv[i], "-p") && i < argc - 1) + databasePassword = QString::fromLocal8Bit(argv[++i]); + else if (!strcmp(argv[i], "-u") && i < argc - 1) + databaseUser = QString::fromLocal8Bit(argv[++i]); + else + { + usage(); + return EXIT_FAILURE; + } + } + + // open database + QSqlDatabase db = QSqlDatabase::addDatabase(databaseDriver); + db.setDatabaseName(databaseName); + db.setUserName(databaseUser); + db.setPassword(databasePassword); + db.setHostName(databaseHost); + if (!db.open()) { + fprintf(stderr, "Could not access database\n"); + return EXIT_FAILURE; + } + QDjango::setDatabase(db); + + // declare models + QDjango::registerModel(); + QDjango::registerModel(); + QDjango::registerModel(); + QDjango::registerModel(); + + QDjango::registerModel(); + + // run tests + int errors = 0; + + for (int i = 0; i < count; ++i) + { + tst_QDjangoWhere testWhere; + errors += QTest::qExec(&testWhere); + + tst_QDjangoCompiler testCompiler; + errors += QTest::qExec(&testCompiler); + + tst_QDjangoMetaModel testMetaModel; + errors += QTest::qExec(&testMetaModel); + + tst_QDjangoModel testModel; + errors += QTest::qExec(&testModel); + + // field types + tst_Bool testBool; + errors += QTest::qExec(&testBool); + + tst_ByteArray testByteArray; + errors += QTest::qExec(&testByteArray); + + tst_Date testDate; + errors += QTest::qExec(&testDate); + + tst_DateTime testDateTime; + errors += QTest::qExec(&testDateTime); + + tst_Double testDouble; + errors += QTest::qExec(&testDouble); + + tst_Integer testInteger; + errors += QTest::qExec(&testInteger); + + tst_LongLong testLongLong; + errors += QTest::qExec(&testLongLong); + + tst_String testString; + errors += QTest::qExec(&testString); + + tst_Time testTime; + errors += QTest::qExec(&testTime); + + // models + TestUser testUser; + errors += QTest::qExec(&testUser); + + TestRelated testRelated; + errors += QTest::qExec(&testRelated); + + TestShares testShares; + errors += QTest::qExec(&testShares); + + TestHttp testHttp; + errors += QTest::qExec(&testHttp); + + TestScript testScript; + errors += QTest::qExec(&testScript); + } + + if (errors) + { + qWarning() << "Total failed tests:" << errors; + return EXIT_FAILURE; + } + return EXIT_SUCCESS; +}; + diff --git a/tests/main.h b/tests/main.h new file mode 100644 index 0000000..c005c08 --- /dev/null +++ b/tests/main.h @@ -0,0 +1,179 @@ +/* + * Copyright (C) 2010-2012 Jeremy Lainé + * Contact: http://code.google.com/p/qdjango/ + * + * This file is part of the QDjango Library. + * + * This program 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 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU Lesser General Public License + * along with this program. If not, see . + */ + +#include "QDjango.h" +#include "QDjangoModel.h" + +#include + +#define CHECKWHERE(_where, s, v) { \ + QSqlDatabase _sql_db(QDjango::database()); \ + QDjangoQuery _sql_query(_sql_db); \ + QString _sql_string = _where.sql(_sql_db); \ + if (_sql_db.driverName() == "QMYSQL") \ + _sql_string = _sql_string.replace("`", "\""); \ + else if (_sql_db.driverName() == "QSQLITE" || _sql_db.driverName() == "QSQLITE2") \ + _sql_string = _sql_string.replace("LIKE ? ESCAPE '\\'", "LIKE ?"); \ + const QVariantList _sql_values = v; \ + _where.bindValues(_sql_query); \ + QCOMPARE(_sql_string, 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]); \ + } + +class Object : public QObject +{ + Q_OBJECT + Q_PROPERTY(QString foo READ foo WRITE setFoo) + Q_PROPERTY(int bar READ bar WRITE setBar) + Q_PROPERTY(int wiz READ wiz WRITE setWiz) + Q_PROPERTY(int zoo READ zoo WRITE setZoo) + + Q_CLASSINFO("__meta__", "db_table=foo_table") + Q_CLASSINFO("foo", "max_length=255") + Q_CLASSINFO("bar", "db_index=true") + Q_CLASSINFO("wiz", "ignore_field=true") + Q_CLASSINFO("zoo", "unique=true") + +public: + Object(QObject *parent = 0); + + QString foo() const; + void setFoo(const QString &foo); + + int bar() const; + void setBar(int bar); + + int wiz() const; + void setWiz(int wiz); + + int zoo() const; + void setZoo(int zoo); + +private: + QString m_foo; + int m_bar; + int m_wiz; + int m_zoo; +}; + +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 tst_QDjangoCompiler : public QObject +{ + Q_OBJECT + +private slots: + void initTestCase(); + void fieldNames(); + void fieldNamesRecursive(); + void orderLimit(); + void resolve(); +}; + +/** Test QDjangoMetaModel class. + */ +class tst_QDjangoMetaModel : public QObject +{ + Q_OBJECT + +private slots: + void initTestCase(); + void options(); + void save(); + void cleanupTestCase(); + +private: + QDjangoMetaModel metaModel; +}; + +/** Test QDjangoModel class. + */ +class tst_QDjangoModel : public QObject +{ + Q_OBJECT + +private slots: + void initTestCase(); + void filterRelated(); + void selectRelated(); + void cleanup(); + void cleanupTestCase(); +}; + +/** Test QDjangoWhere class. + */ +class tst_QDjangoWhere : public QObject +{ + Q_OBJECT + +private slots: + void emptyWhere(); + void equalsWhere(); + void notEqualsWhere(); + void greaterThan(); + void greaterOrEquals(); + void lessThan(); + void lessOrEquals(); + void isIn(); + void startsWith(); + void endsWith(); + void contains(); + void andWhere(); + void orWhere(); + void complexWhere(); +}; + diff --git a/tests/main.js b/tests/main.js new file mode 100644 index 0000000..992f70b --- /dev/null +++ b/tests/main.js @@ -0,0 +1,49 @@ +/* + * Copyright (C) 2010-2012 Jeremy Lainé + * Contact: http://code.google.com/p/qdjango/ + * + * This file is part of the QDjango Library. + * + * This program 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 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU Lesser General Public License + * along with this program. If not, see . + */ + +function fail(msg) +{ + print(msg); + quit(); +} + +load("qdjango.test"); +syncdb(); + +/* create a user */ +u = new User(); +u.username = "foouser"; +u.password = "foopass"; +u.save(); + +/* create a message */ +m = new Message(); +m.text = "some message"; +m.user_id = u.pk; +m.save(); + +/* find message */ +qs = Message.objects.filter({"pk": 1}); +if (qs.size() != 1) fail("Wrong number of messages"); +m2 = qs.at(0) +if (m2.text != "some message") fail("Wrong message text"); + +/* quit */ +quit(); diff --git a/tests/script.cpp b/tests/script.cpp new file mode 100644 index 0000000..040fb85 --- /dev/null +++ b/tests/script.cpp @@ -0,0 +1,132 @@ +/* + * Copyright (C) 2010-2012 Jeremy Lainé + * Contact: http://code.google.com/p/qdjango/ + * + * This file is part of the QDjango Library. + * + * This program 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 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU Lesser General Public License + * along with this program. If not, see . + */ + +#include + +#include "QDjangoScript.h" + +#include "auth-models.h" +#include "main.h" +#include "script.h" + +Q_DECLARE_METATYPE(QDjangoQuerySet) + +void TestScript::cleanupTestCase() +{ + metaModel.dropTable(); + + delete engine; +} + +void TestScript::initTestCase() +{ + metaModel = QDjango::registerModel(); + QCOMPARE(metaModel.isValid(), true); + QCOMPARE(metaModel.createTable(), true); + + engine = new QScriptEngine(this); + QDjangoScript::registerWhere(engine); + QDjangoScript::registerModel(engine); +} + +void TestScript::testWhereConstructor() +{ + QScriptValue result; + QDjangoWhere where; + + // equals + result = engine->evaluate("Q({'username': 'foobar'})"); + where = engine->fromScriptValue(result); + CHECKWHERE(where, QLatin1String("username = ?"), QVariantList() << "foobar"); + + // less than + result = engine->evaluate("Q({'username__lt': 'foobar'})"); + where = engine->fromScriptValue(result); + CHECKWHERE(where, QLatin1String("username < ?"), QVariantList() << "foobar"); + + // less than or equal to + result = engine->evaluate("Q({'username__lte': 'foobar'})"); + where = engine->fromScriptValue(result); + CHECKWHERE(where, QLatin1String("username <= ?"), QVariantList() << "foobar"); + + // greater than + result = engine->evaluate("Q({'username__gt': 'foobar'})"); + where = engine->fromScriptValue(result); + CHECKWHERE(where, QLatin1String("username > ?"), QVariantList() << "foobar"); + + // greater than or equal to + result = engine->evaluate("Q({'username__gte': 'foobar'})"); + where = engine->fromScriptValue(result); + CHECKWHERE(where, QLatin1String("username >= ?"), QVariantList() << "foobar"); + + // starts with + result = engine->evaluate("Q({'username__startswith': 'foobar'})"); + where = engine->fromScriptValue(result); + CHECKWHERE(where, QLatin1String("username LIKE ?"), QVariantList() << "foobar%"); + + // ends with + result = engine->evaluate("Q({'username__endswith': 'foobar'})"); + where = engine->fromScriptValue(result); + CHECKWHERE(where, QLatin1String("username LIKE ?"), QVariantList() << "%foobar"); + + // contains + result = engine->evaluate("Q({'username__contains': 'foobar'})"); + where = engine->fromScriptValue(result); + CHECKWHERE(where, QLatin1String("username LIKE ?"), QVariantList() << "%foobar%"); + + // in + result = engine->evaluate("Q({'username__in': ['foobar', 'wiz']})"); + where = engine->fromScriptValue(result); + CHECKWHERE(where, QLatin1String("username IN (?, ?)"), QVariantList() << "foobar" << "wiz"); + + // double constructor + result = engine->evaluate("Q(Q({'username': 'foobar'}))"); + where = engine->fromScriptValue(result); + CHECKWHERE(where, QLatin1String("username = ?"), QVariantList() << "foobar"); +} + +void TestScript::testWhereOperators() +{ + QScriptValue result; + QDjangoWhere where; + + // AND operator + result = engine->evaluate("Q({'username': 'foobar'}).and(Q({'password': 'foopass'}))"); + where = engine->fromScriptValue(result); + CHECKWHERE(where, QLatin1String("username = ? AND password = ?"), QVariantList() << "foobar" << "foopass"); + + // OR operator + result = engine->evaluate("Q({'username': 'foobar'}).or(Q({'password': 'foopass'}))"); + where = engine->fromScriptValue(result); + CHECKWHERE(where, QLatin1String("username = ? OR password = ?"), QVariantList() << "foobar" << "foopass"); +} + +void TestScript::testModel() +{ + // create model instance + QScriptValue result = engine->evaluate("user = User();"); + User *user = qobject_cast(result.toQObject()); + QVERIFY(user != 0); + + // set properties + engine->evaluate("user.username = 'foobar';"); + QCOMPARE(user->username(), QLatin1String("foobar")); +} + diff --git a/tests/script.h b/tests/script.h new file mode 100644 index 0000000..e4c8134 --- /dev/null +++ b/tests/script.h @@ -0,0 +1,44 @@ +/* + * Copyright (C) 2010-2012 Jeremy Lainé + * Contact: http://code.google.com/p/qdjango/ + * + * This file is part of the QDjango Library. + * + * This program 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 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU Lesser General Public License + * along with this program. If not, see . + */ + +#include + +#include "QDjango.h" + +class QScriptEngine; + +/** Test QDjango scripting. + */ +class TestScript : public QObject +{ + Q_OBJECT + +private slots: + void initTestCase(); + void testWhereConstructor(); + void testWhereOperators(); + void testModel(); + void cleanupTestCase(); + +private: + QDjangoMetaModel metaModel; + QScriptEngine *engine; +}; + diff --git a/tests/shares-models.cpp b/tests/shares-models.cpp new file mode 100644 index 0000000..873a611 --- /dev/null +++ b/tests/shares-models.cpp @@ -0,0 +1,67 @@ +/* + * Copyright (C) 2010-2012 Jeremy Lainé + * Contact: http://code.google.com/p/qdjango/ + * + * This file is part of the QDjango Library. + * + * This program 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 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU Lesser General Public License + * along with this program. If not, see . + */ + +#include "shares-models.h" + +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; +} + diff --git a/tests/shares-models.h b/tests/shares-models.h new file mode 100644 index 0000000..fbcbd18 --- /dev/null +++ b/tests/shares-models.h @@ -0,0 +1,61 @@ +/* + * Copyright (C) 2010-2012 Jeremy Lainé + * Contact: http://code.google.com/p/qdjango/ + * + * This file is part of the QDjango Library. + * + * This program 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 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU Lesser General Public License + * along with this program. If not, see . + */ + +#ifndef QDJANGO_SHARES_MODELS_H +#define QDJANGO_SHARES_MODELS_H + +#include + +#include "QDjangoModel.h" + +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; +}; + +#endif diff --git a/tests/shares-tests.cpp b/tests/shares-tests.cpp new file mode 100644 index 0000000..a738517 --- /dev/null +++ b/tests/shares-tests.cpp @@ -0,0 +1,71 @@ +/* + * Copyright (C) 2010-2012 Jeremy Lainé + * Contact: http://code.google.com/p/qdjango/ + * + * This file is part of the QDjango Library. + * + * This program 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 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU Lesser General Public License + * along with this program. If not, see . + */ + +#include + +#include "QDjangoQuerySet.h" + +#include "shares-models.h" +#include "shares-tests.h" + +/** Create database table before running tests. + */ +void TestShares::initTestCase() +{ + QCOMPARE(QDjango::registerModel().createTable(), true); +} + +void TestShares::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 TestShares::cleanup() +{ + QCOMPARE(QDjangoQuerySet().remove(), true); +} + +/** Drop database table after running tests. + */ +void TestShares::cleanupTestCase() +{ + QCOMPARE(QDjango::registerModel().dropTable(), true); +} + diff --git a/tests/shares-tests.h b/tests/shares-tests.h new file mode 100644 index 0000000..3eb5d92 --- /dev/null +++ b/tests/shares-tests.h @@ -0,0 +1,35 @@ +/* + * Copyright (C) 2010-2012 Jeremy Lainé + * Contact: http://code.google.com/p/qdjango/ + * + * This file is part of the QDjango Library. + * + * This program 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 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU Lesser General Public License + * along with this program. If not, see . + */ + +#include + +/** Tests for the File class. + */ +class TestShares : public QObject +{ + Q_OBJECT + +private slots: + void initTestCase(); + void testFile(); + void cleanup(); + void cleanupTestCase(); +}; + diff --git a/tests/tests.pro b/tests/tests.pro new file mode 100644 index 0000000..59b3634 --- /dev/null +++ b/tests/tests.pro @@ -0,0 +1,34 @@ +include(../qdjango.pri) + +QT += script sql network testlib + +TARGET = qdjango-tests + +HEADERS += \ + fields.h \ + http.h \ + main.h \ + script.h \ + auth-models.h \ + auth-tests.h \ + shares-models.h \ + shares-tests.h +SOURCES += \ + fields.cpp \ + http.cpp \ + main.cpp \ + script.cpp \ + auth-models.cpp \ + auth-tests.cpp \ + shares-models.cpp \ + shares-tests.cpp + +INCLUDEPATH += \ + ../src/db \ + ../src/http \ + ../src/script + +LIBS += \ + -L../src/db -lqdjango-db \ + -L../src/http -lqdjango-http \ + -L../src/script -lqdjango-script