pax_global_header00006660000000000000000000000064145245356170014526gustar00rootroot0000000000000052 comment=33598d2c8defc4eeff208249b5bed67c7ed62e48 hoel-1.4.29/000077500000000000000000000000001452453561700125525ustar00rootroot00000000000000hoel-1.4.29/.github/000077500000000000000000000000001452453561700141125ustar00rootroot00000000000000hoel-1.4.29/.github/workflows/000077500000000000000000000000001452453561700161475ustar00rootroot00000000000000hoel-1.4.29/.github/workflows/ccpp.yml000066400000000000000000000052641452453561700176260ustar00rootroot00000000000000on: [push, pull_request] jobs: build: runs-on: ubuntu-latest steps: - uses: actions/checkout@v1 - name: install dependencies run: | sudo apt-get update sudo apt-get install -y cmake pkg-config check libsubunit-dev cppcheck libsystemd-dev libsqlite3-dev default-libmysqlclient-dev libpq-dev libjansson-dev sqlite3 - name: cppcheck run: cppcheck --force --enable=warning,missingInclude --error-exitcode=1 . - name: dependencies run: | cd /opt git clone https://github.com/babelouest/orcania.git git clone https://github.com/babelouest/yder.git mkdir build cd build cmake -DCMAKE_INSTALL_PREFIX=/usr -DCMAKE_INSTALL_LIBDIR=lib ../orcania make sudo make install rm -rf * cmake -DCMAKE_INSTALL_PREFIX=/usr -DCMAKE_INSTALL_LIBDIR=lib ../yder make sudo make install rm -rf * - name: build run: | mkdir build && cd build cmake -DBUILD_HOEL_TESTING=on .. make sqlite3 /tmp/test.db < ../test/test.sqlite3.sql make test package sudo make install rm -rf * && cmake -DWITH_SQLITE3=off -DWITH_MARIADB=off -DWITH_PGSQL=on .. make package rm -rf * && cmake -DWITH_SQLITE3=off -DWITH_MARIADB=on -DWITH_PGSQL=off .. make package rm -rf * && cmake -DWITH_SQLITE3=off -DWITH_MARIADB=on -DWITH_PGSQL=on .. make package rm -rf * && cmake -DWITH_SQLITE3=on -DWITH_MARIADB=off -DWITH_PGSQL=off .. make package rm -rf * && cmake -DWITH_SQLITE3=on -DWITH_MARIADB=off -DWITH_PGSQL=on .. make package rm -rf * && cmake -DWITH_SQLITE3=on -DWITH_MARIADB=on -DWITH_PGSQL=off .. make package rm -rf * && cmake -DWITH_SQLITE3=on -DWITH_MARIADB=on -DWITH_PGSQL=on .. make package rm -rf * if $(cmake -DWITH_SQLITE3=off -DWITH_MARIADB=off -DWITH_PGSQL=off .. 1>/dev/null 2>&1); then echo "CMake build with no DB fail" && false; else echo "Build with no DB success"; fi cd ../ make clean debug make clean debug DISABLE_SQLITE=1 DISABLE_MARIADB=1 make clean debug DISABLE_SQLITE=1 DISABLE_POSTGRESQL=1 make clean debug DISABLE_SQLITE=1 make clean debug DISABLE_MARIADB=1 DISABLE_POSTGRESQL=1 make clean debug DISABLE_MARIADB=1 make clean debug DISABLE_POSTGRESQL=1 if $(make clean debug DISABLE_SQLITE=1 DISABLE_MARIADB=1 DISABLE_POSTGRESQL=1 1>/dev/null 2>&1); then echo "Make build with no DB fail" && false; else echo "Build with no DB success"; fi sqlite3 /tmp/test.db < test/test.sqlite3.sql make clean check hoel-1.4.29/.github/workflows/codeql-analysis.yml000066400000000000000000000046141452453561700217670ustar00rootroot00000000000000name: "CodeQL" on: push: branches: [master, ] pull_request: # The branches below must be a subset of the branches above branches: [master] schedule: - cron: '0 8 * * 2' jobs: analyse: name: Analyse runs-on: ubuntu-latest steps: - name: Checkout repository uses: actions/checkout@v2 with: # We must fetch at least the immediate parents so that if this is # a pull request then we can checkout the head. fetch-depth: 2 # If this run was triggered by a pull request event, then checkout # the head of the pull request instead of the merge commit. - run: git checkout HEAD^2 if: ${{ github.event_name == 'pull_request' }} # Initializes the CodeQL tools for scanning. - name: Initialize CodeQL uses: github/codeql-action/init@v1 # Override language selection by uncommenting this and choosing your languages # with: # languages: go, javascript, csharp, python, cpp, java # Autobuild attempts to build any compiled languages (C/C++, C#, or Java). # If this step fails, then you should remove it and run the build manually (see below) #- name: Autobuild # uses: github/codeql-action/autobuild@v1 # â„šī¸ Command-line programs to run using the OS shell. # 📚 https://git.io/JvXDl # âœī¸ If the Autobuild fails above, remove it and uncomment the following three lines # and modify them (or add more) to build your code if your project # uses a compiled language - name: dependencies run: | sudo apt-get update sudo apt-get install -y cmake pkg-config libsystemd-dev libsqlite3-dev default-libmysqlclient-dev libpq-dev libjansson-dev doxygen cd /opt git clone https://github.com/babelouest/orcania.git git clone https://github.com/babelouest/yder.git mkdir build cd build cmake -DCMAKE_INSTALL_PREFIX=/usr -DCMAKE_INSTALL_LIBDIR=lib ../orcania make sudo make install rm -rf * cmake -DCMAKE_INSTALL_PREFIX=/usr -DCMAKE_INSTALL_LIBDIR=lib ../yder make sudo make install rm -rf * - run: | mkdir build cd build cmake -DBUILD_HOEL_DOCUMENTATION=on .. make make doc sudo make install - name: Perform CodeQL Analysis uses: github/codeql-action/analyze@v1 hoel-1.4.29/.gitignore000066400000000000000000000002461452453561700145440ustar00rootroot00000000000000*.o *.so *.so.*.* example_sqlite3 example_mariadb example_pgsql example_mariadb_json example_multi_mariadb core multi valgrind-test_*.txt hoel-cfg.h libhoel.pc *.log hoel-1.4.29/CHANGELOG.md000066400000000000000000000063161452453561700143710ustar00rootroot00000000000000# Hoel Changelog ## 1.4.29 - Add option `group_by` for `h_select` - cmake: split package build options in 3 (tar.gz, deb and rpm), and set all packages build to off by default ## 1.4.28 - Improve cmake script - cmake: remove `DownloadProject` feature, now dependencies must be previously installed ## 1.4.27 - Add `h_build_where_clause` - Build with flag `-Wconversion` ## 1.4.26 - Minor bugfixes ## 1.4.25 - Fix `CMAKE_MODULE_PATH` who was used as single value (for real) ## 1.4.24 - Fix pkg-config file with absolute path for `CMAKE_INSTALL_{INCLUDE,LIB}DIR` - Fix `CMAKE_MODULE_PATH` who was used as single value ## 1.4.23 - Add missing `pthread_mutex_lock` for MariaDB and PostgreSQL in respective `h_last_insert_id` ## 1.4.22 - Fix `h_escape_string_mariadb` ## 1.4.21 - Replace `#define h_exec_query_sqlite` with a redefinition of `h_exec_query_sqlite` as a function - Create or delete test db file for unit tests - Small bugfixes or improvements ## 1.4.20 - Rename `h_exec_query_sqlite` to `h_execute_query_sqlite`, add `h_exec_query_sqlite` that redirects to `h_execute_query_sqlite` - Implement all dummy functions when a database backend is not supported ## 1.4.19 - Use `o_strlen` instead of `strlen` ## 1.4.18 - Remove Travis CI tests ## 1.4.17 - Code cleaning - Increase dependencies version required ## 1.4.16 - Use stdbool instead of `my_bool` which is deprecated - Uppdate package dependencies in cmake script ## 1.4.15 - Fix memory leak - Update doc ## 1.4.14 - Fix yet another set of bugs in the PostgreSQL backend - Add multi-backend test suite ## 1.4.13 - Fix build when databases are disabled - Fix ldconfig command in Makefile - Add doxygen documentation ## 1.4.12 - Update SQlite `sqlite3_open_v2` optparameters to add `SQLITE_OPEN_FULLMUTEX` flag ## 1.4.11 - Add `h_escape_string_with_quotes` to help using escape strings with PostgreSQL - Add mutex in pgsql connection because libpq isn't thread safe, like libmysql... - Change struct _h_type_int value type from int to long long int ## 1.4.10 - Fix mysql package name dependency when build deb package ## 1.4.9 - Fix h_connect_pgsql to accept const char * parameter instead of char * - Remove backquotes because Postgre seems not to like them - minor bugfixes - Install pkgconfig file when using Makefile ## 1.4.8 - Fix mariadb bug when empty column was returned as NULL ## 1.4.7 - Add support for binary columns in `struct _h_data` by adding length parameter in `struct _h_type_text` - Code cleaning and bug fixes thanks to clang static analyzer ## 1.4.6 - CMake scripts improvements ## 1.4.5 - Add config file hoel-cfg.h dynamically built with the options - Improve CI ## 1.4.4 - Add Travis CI - Change cmake option BUILD_TESTING to BUILD_HOEL_TESTING - Add RPM in CMake script package ## 1.4.3 - Fix memory leak - Fix pkg-config information, add requires fields as mentionned in babelouest/ulfius#62 - Improve example_mariadb_json.c to make it more readable and understandable, clean code - Removing the my_global.h include in hoel-mariadb.c - Fix static library output file name babelouest/ulfius#55 ## 1.4.2 - Fix Makefile soname ## 1.4.1 - Add Debian hardening patch on Makefile ## 1.4 - Add CMake installation script - Various bugfixes hoel-1.4.29/CMakeLists.txt000066400000000000000000000403711452453561700153170ustar00rootroot00000000000000# # Hoel library # # CMake file used to build all programs # # Copyright 2018 Silvio Clecio # Copyright 2018-2023 Nicolas Mora # # This program is free software; you can redistribute it and/or # modify it under the terms of the MIT License # # This library is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. # cmake_minimum_required(VERSION 3.14) project(hoel C) set(CMAKE_C_STANDARD 99) set(CMAKE_C_FLAGS "${CMAKE_C_FLAGS} -Wall -Werror") # library info set(HOEL_LIBS ) set(PROJECT_DESCRIPTION "C Database abstraction library with json based language") set(PROJECT_HOMEPAGE_URL "https://github.com/babelouest/hoel/") set(PROJECT_BUGREPORT_PATH "https://github.com/babelouest/hoel/issues") set(LIBRARY_VERSION_MAJOR "1") set(LIBRARY_VERSION_MINOR "4") set(LIBRARY_VERSION_PATCH "29") set(ORCANIA_VERSION_REQUIRED "2.3.3") set(YDER_VERSION_REQUIRED "1.4.20") set(JANSSON_VERSION_REQUIRED "2.4") set(PROJECT_VERSION "${LIBRARY_VERSION_MAJOR}.${LIBRARY_VERSION_MINOR}.${LIBRARY_VERSION_PATCH}") set(PROJECT_VERSION_MAJOR ${LIBRARY_VERSION_MAJOR}) set(PROJECT_VERSION_MINOR ${LIBRARY_VERSION_MINOR}) set(PROJECT_VERSION_PATCH ${LIBRARY_VERSION_PATCH}) if (${LIBRARY_VERSION_MAJOR} VERSION_LESS 10) set (LIBRARY_VERSION_MAJOR_PAD "0${LIBRARY_VERSION_MAJOR}") else () set (LIBRARY_VERSION_MAJOR_PAD "${LIBRARY_VERSION_MAJOR}") endif () if (${LIBRARY_VERSION_MINOR} VERSION_LESS 10) set (LIBRARY_VERSION_MINOR_PAD "0${LIBRARY_VERSION_MINOR}") else () set (LIBRARY_VERSION_MINOR_PAD "${LIBRARY_VERSION_MINOR}") endif () if (${LIBRARY_VERSION_PATCH} VERSION_LESS 10) set (LIBRARY_VERSION_PATCH_PAD "0${LIBRARY_VERSION_PATCH}") else () set (LIBRARY_VERSION_PATCH_PAD "${LIBRARY_VERSION_PATCH}") endif () set(PROJECT_VERSION_NUMBER "${LIBRARY_VERSION_MAJOR_PAD}${LIBRARY_VERSION_MINOR_PAD}${LIBRARY_VERSION_PATCH_PAD}") set(LIBRARY_VERSION "${LIBRARY_VERSION_MAJOR}.${LIBRARY_VERSION_MINOR}.${LIBRARY_VERSION_PATCH}") set(LIBRARY_SOVERSION "${LIBRARY_VERSION_MAJOR}.${LIBRARY_VERSION_MINOR}") # cmake modules set(H_CMAKE_MODULE_PATH ${CMAKE_CURRENT_SOURCE_DIR}/cmake-modules) list(APPEND CMAKE_MODULE_PATH "${H_CMAKE_MODULE_PATH}") include(GNUInstallDirs) include(CheckSymbolExists) include(CMakeDependentOption) include(CMakePackageConfigHelpers) # check if _GNU_SOURCE is available if (NOT _GNU_SOURCE) check_symbol_exists(__GNU_LIBRARY__ "features.h" _GNU_SOURCE) if (NOT _GNU_SOURCE) unset(_GNU_SOURCE CACHE) check_symbol_exists(_GNU_SOURCE "features.h" _GNU_SOURCE) endif () endif () if (_GNU_SOURCE) add_definitions(-D_GNU_SOURCE) endif () # directories and source set(INC_DIR ${CMAKE_CURRENT_SOURCE_DIR}/include) set(SRC_DIR ${CMAKE_CURRENT_SOURCE_DIR}/src) include_directories(${INC_DIR}) set(LIB_SRC ${INC_DIR}/hoel.h ${INC_DIR}/h-private.h ${SRC_DIR}/hoel-simple-json.c ${SRC_DIR}/hoel-mariadb.c ${SRC_DIR}/hoel-pgsql.c ${SRC_DIR}/hoel-sqlite.c ${SRC_DIR}/hoel.c) # dependencies # pthread libraries find_package (Threads) list(APPEND HOEL_LIBS ${CMAKE_THREAD_LIBS_INIT}) include(FindJansson) set(JANSSON_MIN_VERSION 2.4) find_package(Jansson ${JANSSON_MIN_VERSION} REQUIRED) list(APPEND HOEL_LIBS Jansson::Jansson) option(WITH_SQLITE3 "Use SQLite3 library" ON) if (WITH_SQLITE3) include(FindSQLite3) find_package(SQLite3 REQUIRED) if (SQLite3_FOUND) list(APPEND HOEL_LIBS SQLite::SQLite3) include_directories(${SQLite3_INCLUDE_DIRS}) set(_HOEL_SQLITE ON) else () message("SQLite3 not found") set(_HOEL_SQLITE OFF) endif () else () set(_HOEL_SQLITE OFF) endif () option(WITH_MARIADB "Use MariaDB library" ON) if (WITH_MARIADB) include(FindMYSQL) find_package(MYSQL REQUIRED) if (MYSQL_FOUND) list(APPEND HOEL_LIBS MysqlDBClient::MysqlDBClient) include_directories(${MYSQL_INCLUDE_DIRS}) set(_HOEL_MARIADB ON) else () message("MariaDB not found") set(_HOEL_MARIADB OFF) endif () else () set(_HOEL_MARIADB OFF) endif () option(WITH_PGSQL "Use PostgreSQL library" ON) if (WITH_PGSQL) include(FindLibPQ) find_package(LibPQ REQUIRED) if(LIBPQ_FOUND) list(APPEND HOEL_LIBS PostgreSQL::PostgreSQL) include_directories(${LIBPQ_INCLUDE_DIRS}) set(_HOEL_PGSQL ON) else () message("LibPQ not found") set(_HOEL_PGSQL OFF) endif() else () set(_HOEL_PGSQL OFF) endif () # build hoel-cfg.h file configure_file(${INC_DIR}/hoel-cfg.h.in ${PROJECT_BINARY_DIR}/hoel-cfg.h) set (CMAKE_EXTRA_INCLUDE_FILES ${PROJECT_BINARY_DIR}) include_directories(${PROJECT_BINARY_DIR}) if (NOT WITH_PGSQL AND NOT WITH_MARIADB AND NOT WITH_SQLITE3) MESSAGE(FATAL_ERROR "You must enable at least one database backend: Sqlite3, MariaDB or PostgreSQL") endif () set (PKGCONF_REQ "") set (PKGCONF_REQ_PRIVATE "liborcania, libyder") if (WITH_SQLITE3) set (PKGCONF_REQ_PRIVATE "${PKGCONF_REQ_PRIVATE}, sqlite3") endif () if (WITH_MARIADB) set (PKGCONF_REQ_PRIVATE "${PKGCONF_REQ_PRIVATE}, mariadb") endif () if (WITH_PGSQL) set (PKGCONF_REQ_PRIVATE "${PKGCONF_REQ_PRIVATE}, libpq") endif () option(BUILD_STATIC "Build static library." OFF) # static library if (BUILD_STATIC) add_library(hoel_static STATIC ${LIB_SRC}) add_library(Hoel::Hoel-static ALIAS hoel_static) target_include_directories(hoel_static PUBLIC "$" PUBLIC "$" PUBLIC "$") target_link_libraries(hoel_static PUBLIC ${HOEL_LIBS}) target_compile_definitions(hoel_static PUBLIC O_STATIC_LIBRARY) set_target_properties(hoel_static PROPERTIES PUBLIC_HEADER "${INC_DIR}/hoel.h;${PROJECT_BINARY_DIR}/hoel-cfg.h" OUTPUT_NAME hoel EXPORT_NAME Hoel-static) if (MSVC) set_target_properties(hoel_static PROPERTIES OUTPUT_NAME hoel-static) endif () if (NOT MSVC) target_compile_options(hoel_static PRIVATE -Wextra -Wconversion) endif () set(hoel_lib hoel_static) endif () # shared library add_library(hoel SHARED ${LIB_SRC}) add_library(Hoel::Hoel ALIAS hoel) target_include_directories(hoel PUBLIC "$" PUBLIC "$" PUBLIC "$") target_link_libraries(hoel PUBLIC ${HOEL_LIBS}) set_target_properties(hoel PROPERTIES PUBLIC_HEADER "${INC_DIR}/hoel.h;${PROJECT_BINARY_DIR}/hoel-cfg.h" VERSION "${LIBRARY_VERSION}" SOVERSION "${LIBRARY_SOVERSION}" WINDOWS_EXPORT_ALL_SYMBOLS TRUE EXPORT_NAME Hoel) if (WIN32) set_target_properties(hoel PROPERTIES SUFFIX "-${LIBRARY_VERSION_MAJOR}.dll") endif () if (NOT MSVC) target_compile_options(hoel PRIVATE -Wextra -Wconversion) endif() set(hoel_lib hoel) # documentation option(BUILD_HOEL_DOCUMENTATION "Build the documentation." OFF) if (BUILD_HOEL_DOCUMENTATION) find_package(Doxygen) if (DOXYGEN_FOUND) set(doxyfile_in ${CMAKE_CURRENT_SOURCE_DIR}/doc/doxygen.cfg) set(doxyfile ${CMAKE_CURRENT_BINARY_DIR}/doxyfile) configure_file(${doxyfile_in} ${doxyfile} @ONLY) add_custom_target(doc COMMAND ${DOXYGEN_EXECUTABLE} ${doxyfile_in} WORKING_DIRECTORY ${CMAKE_CURRENT_SOURCE_DIR} COMMENT "Generating documentation with Doxygen" VERBATIM) else () message(FATAL_ERROR "Doxygen is needed to build the documentation.") endif () endif () # dependencies find_package(Orcania ${ORCANIA_VERSION_REQUIRED} REQUIRED) if ("${ORCANIA_VERSION_STRING}" VERSION_GREATER_EQUAL "${ORCANIA_VERSION_REQUIRED}") message(STATUS "Orcania found: ${ORCANIA_VERSION_STRING}") else () message( FATAL_ERROR "Orcania version required: ${ORCANIA_VERSION_REQUIRED} - version installed: ${ORCANIA_VERSION_STRING}") endif () if (BUILD_STATIC) if(TARGET Orcania::Orcania-static) target_link_libraries(hoel_static PUBLIC $) else() target_link_libraries(hoel_static PUBLIC $) endif() else() target_link_libraries(hoel PUBLIC $) endif () find_package(Yder ${YDER_VERSION_REQUIRED} REQUIRED) if ("${YDER_VERSION_STRING}" VERSION_GREATER_EQUAL "${YDER_VERSION_REQUIRED}") message(STATUS "Yder found: ${YDER_VERSION_STRING}") else () message( FATAL_ERROR "Yder version required: ${YDER_VERSION_REQUIRED} - version installed: ${YDER_VERSION_STRING}") endif () if (BUILD_STATIC) if(TARGET Yder::Yder-static) target_link_libraries(hoel_static PUBLIC $) else() target_link_libraries(hoel_static PUBLIC $) endif() else() target_link_libraries(hoel PUBLIC $) endif () # tests option(BUILD_HOEL_TESTING "Build the testing tree." OFF) # because we don not use include(CTest) if (BUILD_HOEL_TESTING) find_package(Check REQUIRED) if (CHECK_FOUND) if (NOT WIN32 AND NOT APPLE) include(FindSubunit) find_package(Subunit REQUIRED) endif () enable_testing() set(CMAKE_CTEST_COMMAND ctest -V) set(TST_DIR ${CMAKE_CURRENT_SOURCE_DIR}/test) set(TEST_LIBS hoel Check::Check ${HOEL_LIBS}) if (NOT WIN32) find_package(Threads REQUIRED) list(APPEND TEST_LIBS ${CMAKE_THREAD_LIBS_INIT} m) endif () if (NOT APPLE AND NOT WIN32) list(APPEND TEST_LIBS rt) endif () if (NOT WIN32 AND NOT APPLE) list(APPEND TEST_LIBS Subunit::Subunit) endif () set(TESTS core multi) configure_file( "${H_CMAKE_MODULE_PATH}/CTestCustom.cmake.in" "${CMAKE_CURRENT_BINARY_DIR}/CTestCustom.cmake" @ONLY) foreach (t ${TESTS}) add_executable(${t} EXCLUDE_FROM_ALL ${TST_DIR}/${t}.c) target_include_directories(${t} PUBLIC ${TST_DIR}) target_link_libraries(${t} PRIVATE ${TEST_LIBS}) add_test(NAME ${t} WORKING_DIRECTORY ${TST_DIR} COMMAND ${t}) endforeach () endif () endif () # install target option(INSTALL_HEADER "Install the header files" ON) # Install hoel.h or not if(IS_ABSOLUTE "${CMAKE_INSTALL_INCLUDEDIR}") set(PKGCONFIG_TARGET_INCLUDES "${CMAKE_INSTALL_INCLUDEDIR}") else() set(PKGCONFIG_TARGET_INCLUDES "\${prefix}/${CMAKE_INSTALL_INCLUDEDIR}") endif() if(IS_ABSOLUTE "${CMAKE_INSTALL_LIBDIR}") set(PKGCONFIG_TARGET_LIBDIR "${CMAKE_INSTALL_LIBDIR}") else() set(PKGCONFIG_TARGET_LIBDIR "\${prefix}/${CMAKE_INSTALL_LIBDIR}") endif() configure_file(libhoel.pc.in libhoel.pc @ONLY) install(FILES ${CMAKE_CURRENT_BINARY_DIR}/libhoel.pc DESTINATION ${CMAKE_INSTALL_LIBDIR}/pkgconfig) set(TARGETS hoel) if (BUILD_STATIC) list(APPEND TARGETS hoel_static) endif () if (INSTALL_HEADER) install(TARGETS ${TARGETS} EXPORT HoelExports RUNTIME DESTINATION ${CMAKE_INSTALL_BINDIR} LIBRARY DESTINATION ${CMAKE_INSTALL_LIBDIR} ARCHIVE DESTINATION ${CMAKE_INSTALL_LIBDIR} PUBLIC_HEADER DESTINATION ${CMAKE_INSTALL_INCLUDEDIR}) install(DIRECTORY examples/ DESTINATION ${CMAKE_INSTALL_DOCDIR}/examples/ COMPONENT runtime) install(FILES README.md DESTINATION ${CMAKE_INSTALL_DOCDIR} COMPONENT runtime) else () install(TARGETS ${TARGETS} EXPORT HoelExports RUNTIME DESTINATION ${CMAKE_INSTALL_BINDIR} LIBRARY DESTINATION ${CMAKE_INSTALL_LIBDIR} ARCHIVE DESTINATION ${CMAKE_INSTALL_LIBDIR} PUBLIC_HEADER DESTINATION ${CMAKE_INSTALL_INCLUDEDIR}) endif () if (INSTALL_HEADER) set(HOEL_INSTALL_CMAKEDIR_DEFAULT "${CMAKE_INSTALL_LIBDIR}/cmake/Hoel") if (WIN32 AND NOT MINGW) set(HOEL_INSTALL_CMAKEDIR_DEFAULT "cmake") endif () set(HOEL_INSTALL_CMAKEDIR ${HOEL_INSTALL_CMAKEDIR_DEFAULT} CACHE STRING "Location where to install the cmake config files") install(EXPORT HoelExports DESTINATION "${HOEL_INSTALL_CMAKEDIR}" NAMESPACE "Hoel::" FILE "HoelTargets.cmake") configure_package_config_file(cmake-modules/HoelConfig.cmake.in HoelConfig.cmake INSTALL_DESTINATION "${HOEL_INSTALL_CMAKEDIR}") write_basic_package_version_file(HoelConfigVersion.cmake COMPATIBILITY AnyNewerVersion) install(FILES cmake-modules/FindMYSQL.cmake cmake-modules/FindLibPQ.cmake cmake-modules/FindJansson.cmake "${PROJECT_BINARY_DIR}/HoelConfig.cmake" "${PROJECT_BINARY_DIR}/HoelConfigVersion.cmake" DESTINATION "${HOEL_INSTALL_CMAKEDIR}") endif () # uninstall target if (NOT TARGET uninstall) configure_file( "${H_CMAKE_MODULE_PATH}/CMakeUninstall.cmake.in" "${CMAKE_CURRENT_BINARY_DIR}/cmake_uninstall.cmake" IMMEDIATE @ONLY) add_custom_target(uninstall COMMAND ${CMAKE_COMMAND} -P ${CMAKE_CURRENT_BINARY_DIR}/cmake_uninstall.cmake) endif () # packaging set(CPACK_PACKAGE_VERSION_MAJOR ${LIBRARY_VERSION_MAJOR}) set(CPACK_PACKAGE_VERSION_MINOR ${LIBRARY_VERSION_MINOR}) set(CPACK_PACKAGE_VERSION_PATCH ${LIBRARY_VERSION_PATCH}) if (INSTALL_HEADER) set(PACKAGE_FILE_NAME "lib${CMAKE_PROJECT_NAME}-dev_${CPACK_PACKAGE_VERSION_MAJOR}.${CPACK_PACKAGE_VERSION_MINOR}.${CPACK_PACKAGE_VERSION_PATCH}") else () set(PACKAGE_FILE_NAME "lib${CMAKE_PROJECT_NAME}_${CPACK_PACKAGE_VERSION_MAJOR}.${CPACK_PACKAGE_VERSION_MINOR}.${CPACK_PACKAGE_VERSION_PATCH}") endif () set(PACKAGE_IGNORED_FILES "${CMAKE_CURRENT_BINARY_DIR}/;/.git/;.gitignore;~$;${CPACK_SOURCE_IGNORE_FILES}") set(CPACK_GENERATOR ) set(CPACK_PACKAGE_NAME "libhoel") set(CPACK_PACKAGE_DESCRIPTION_SUMMARY "Database abstraction library in C") set(CPACK_PACKAGE_VERSION_MAJOR ${LIBRARY_VERSION_MAJOR}) set(CPACK_PACKAGE_VERSION_MINOR ${LIBRARY_VERSION_MINOR}) set(CPACK_PACKAGE_VERSION_PATCH ${LIBRARY_VERSION_PATCH}) set(CPACK_PACKAGE_FILE_NAME ${PACKAGE_FILE_NAME}) option(BUILD_TGZ "Build a TAR.GZ for your system" OFF) if (BUILD_TGZ) list(APPEND CPACK_GENERATOR TGZ) set(CPACK_SOURCE_GENERATOR "TGZ") set(CPACK_SOURCE_PACKAGE_FILE_NAME ${PACKAGE_FILE_NAME}) set(CPACK_SOURCE_IGNORE_FILES ${PACKAGE_IGNORED_FILES}) endif () option(BUILD_DEB "Build a DEB for your system" OFF) if (BUILD_DEB) list(APPEND CPACK_GENERATOR DEB) set(CPACK_DEBIAN_PACKAGE_MAINTAINER "mail@babelouest.org") set(CPACK_DEBIAN_PACKAGE_DESCRIPTION ${PROJECT_DESCRIPTION}) set(CPACK_DEBIAN_PACKAGE_HOMEPAGE "https://github.com/babelouest/hoel") set(CPACK_DEBIAN_PACKAGE_DEPENDS "libc6 (>= 2.14), liborcania (>= ${ORCANIA_VERSION_REQUIRED}), libyder (>= ${YDER_VERSION_REQUIRED})") if (WITH_SQLITE3) set(CPACK_DEBIAN_PACKAGE_DEPENDS "${CPACK_DEBIAN_PACKAGE_DEPENDS}, libsqlite3-dev|libsqlite3-0 (>= 3.5.9)") endif () if (WITH_MARIADB) set(CPACK_DEBIAN_PACKAGE_DEPENDS "${CPACK_DEBIAN_PACKAGE_DEPENDS}, default-libmysqlclient-dev|libmariadb-dev|default-mysql-client|libmariadb3|libmariadb2") endif () if (WITH_PGSQL) set(CPACK_DEBIAN_PACKAGE_DEPENDS "${CPACK_DEBIAN_PACKAGE_DEPENDS}, libpq-dev|libpq5 (>= 9.0~)") endif () endif () option(BUILD_RPM "Build a RPM for your system" OFF) if (BUILD_RPM) list(APPEND CPACK_GENERATOR RPM) set(CPACK_RPM_PACKAGE_LICENSE "LGPL") set(CPACK_RPM_PACKAGE_URL "http://babelouest.github.io/hoel/") endif () include(CPack) add_custom_target(dist_h COMMAND ${CMAKE_MAKE_PROGRAM} package_source) message(STATUS "SQLITE3 library support: ${WITH_SQLITE3}") message(STATUS "MariaDB library support: ${WITH_MARIADB}") message(STATUS "PostgreSQL library support: ${WITH_PGSQL}") message(STATUS "Build static library: ${BUILD_STATIC}") message(STATUS "Build testing tree: ${BUILD_HOEL_TESTING}") message(STATUS "Install the header files: ${INSTALL_HEADER}") message(STATUS "Build TAR.GZ package: ${BUILD_TGZ}") message(STATUS "Build DEB package: ${BUILD_DEB}") message(STATUS "Build RPM package: ${BUILD_RPM}") message(STATUS "Build documentation: ${BUILD_HOEL_DOCUMENTATION}") hoel-1.4.29/LICENSE000066400000000000000000000635361452453561700135740ustar00rootroot00000000000000 GNU LESSER GENERAL PUBLIC LICENSE Version 2.1, February 1999 Copyright (C) 1991, 1999 Free Software Foundation, Inc. 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA Everyone is permitted to copy and distribute verbatim copies of this license document, but changing it is not allowed. (This is the first released version of the Lesser GPL. It also counts as the successor of the GNU Library Public License, version 2, hence the version number 2.1.) Preamble The licenses for most software are designed to take away your freedom to share and change it. By contrast, the GNU General Public Licenses are intended to guarantee your freedom to share and change free software--to make sure the software is free for all its users. This license, the Lesser General Public License, applies to some specially designated software packages--typically libraries--of the Free Software Foundation and other authors who decide to use it. You can use it too, but we suggest you first think carefully about whether this license or the ordinary General Public License is the better strategy to use in any particular case, based on the explanations below. When we speak of free software, we are referring to freedom of use, not price. Our General Public Licenses are designed to make sure that you have the freedom to distribute copies of free software (and charge for this service if you wish); that you receive source code or can get it if you want it; that you can change the software and use pieces of it in new free programs; and that you are informed that you can do these things. To protect your rights, we need to make restrictions that forbid distributors to deny you these rights or to ask you to surrender these rights. These restrictions translate to certain responsibilities for you if you distribute copies of the library or if you modify it. For example, if you distribute copies of the library, whether gratis or for a fee, you must give the recipients all the rights that we gave you. You must make sure that they, too, receive or can get the source code. If you link other code with the library, you must provide complete object files to the recipients, so that they can relink them with the library after making changes to the library and recompiling it. And you must show them these terms so they know their rights. We protect your rights with a two-step method: (1) we copyright the library, and (2) we offer you this license, which gives you legal permission to copy, distribute and/or modify the library. To protect each distributor, we want to make it very clear that there is no warranty for the free library. Also, if the library is modified by someone else and passed on, the recipients should know that what they have is not the original version, so that the original author's reputation will not be affected by problems that might be introduced by others. Finally, software patents pose a constant threat to the existence of any free program. We wish to make sure that a company cannot effectively restrict the users of a free program by obtaining a restrictive license from a patent holder. Therefore, we insist that any patent license obtained for a version of the library must be consistent with the full freedom of use specified in this license. Most GNU software, including some libraries, is covered by the ordinary GNU General Public License. This license, the GNU Lesser General Public License, applies to certain designated libraries, and is quite different from the ordinary General Public License. We use this license for certain libraries in order to permit linking those libraries into non-free programs. When a program is linked with a library, whether statically or using a shared library, the combination of the two is legally speaking a combined work, a derivative of the original library. The ordinary General Public License therefore permits such linking only if the entire combination fits its criteria of freedom. The Lesser General Public License permits more lax criteria for linking other code with the library. We call this license the "Lesser" General Public License because it does Less to protect the user's freedom than the ordinary General Public License. It also provides other free software developers Less of an advantage over competing non-free programs. These disadvantages are the reason we use the ordinary General Public License for many libraries. However, the Lesser license provides advantages in certain special circumstances. For example, on rare occasions, there may be a special need to encourage the widest possible use of a certain library, so that it becomes a de-facto standard. To achieve this, non-free programs must be allowed to use the library. A more frequent case is that a free library does the same job as widely used non-free libraries. In this case, there is little to gain by limiting the free library to free software only, so we use the Lesser General Public License. In other cases, permission to use a particular library in non-free programs enables a greater number of people to use a large body of free software. For example, permission to use the GNU C Library in non-free programs enables many more people to use the whole GNU operating system, as well as its variant, the GNU/Linux operating system. Although the Lesser General Public License is Less protective of the users' freedom, it does ensure that the user of a program that is linked with the Library has the freedom and the wherewithal to run that program using a modified version of the Library. The precise terms and conditions for copying, distribution and modification follow. Pay close attention to the difference between a "work based on the library" and a "work that uses the library". The former contains code derived from the library, whereas the latter must be combined with the library in order to run. GNU LESSER GENERAL PUBLIC LICENSE TERMS AND CONDITIONS FOR COPYING, DISTRIBUTION AND MODIFICATION 0. This License Agreement applies to any software library or other program which contains a notice placed by the copyright holder or other authorized party saying it may be distributed under the terms of this Lesser General Public License (also called "this License"). Each licensee is addressed as "you". A "library" means a collection of software functions and/or data prepared so as to be conveniently linked with application programs (which use some of those functions and data) to form executables. The "Library", below, refers to any such software library or work which has been distributed under these terms. A "work based on the Library" means either the Library or any derivative work under copyright law: that is to say, a work containing the Library or a portion of it, either verbatim or with modifications and/or translated straightforwardly into another language. (Hereinafter, translation is included without limitation in the term "modification".) "Source code" for a work means the preferred form of the work for making modifications to it. For a library, complete source code means all the source code for all modules it contains, plus any associated interface definition files, plus the scripts used to control compilation and installation of the library. Activities other than copying, distribution and modification are not covered by this License; they are outside its scope. The act of running a program using the Library is not restricted, and output from such a program is covered only if its contents constitute a work based on the Library (independent of the use of the Library in a tool for writing it). Whether that is true depends on what the Library does and what the program that uses the Library does. 1. You may copy and distribute verbatim copies of the Library's complete source code as you receive it, in any medium, provided that you conspicuously and appropriately publish on each copy an appropriate copyright notice and disclaimer of warranty; keep intact all the notices that refer to this License and to the absence of any warranty; and distribute a copy of this License along with the Library. You may charge a fee for the physical act of transferring a copy, and you may at your option offer warranty protection in exchange for a fee. 2. You may modify your copy or copies of the Library or any portion of it, thus forming a work based on the Library, and copy and distribute such modifications or work under the terms of Section 1 above, provided that you also meet all of these conditions: a) The modified work must itself be a software library. b) You must cause the files modified to carry prominent notices stating that you changed the files and the date of any change. c) You must cause the whole of the work to be licensed at no charge to all third parties under the terms of this License. d) If a facility in the modified Library refers to a function or a table of data to be supplied by an application program that uses the facility, other than as an argument passed when the facility is invoked, then you must make a good faith effort to ensure that, in the event an application does not supply such function or table, the facility still operates, and performs whatever part of its purpose remains meaningful. (For example, a function in a library to compute square roots has a purpose that is entirely well-defined independent of the application. Therefore, Subsection 2d requires that any application-supplied function or table used by this function must be optional: if the application does not supply it, the square root function must still compute square roots.) These requirements apply to the modified work as a whole. If identifiable sections of that work are not derived from the Library, and can be reasonably considered independent and separate works in themselves, then this License, and its terms, do not apply to those sections when you distribute them as separate works. But when you distribute the same sections as part of a whole which is a work based on the Library, the distribution of the whole must be on the terms of this License, whose permissions for other licensees extend to the entire whole, and thus to each and every part regardless of who wrote it. Thus, it is not the intent of this section to claim rights or contest your rights to work written entirely by you; rather, the intent is to exercise the right to control the distribution of derivative or collective works based on the Library. In addition, mere aggregation of another work not based on the Library with the Library (or with a work based on the Library) on a volume of a storage or distribution medium does not bring the other work under the scope of this License. 3. You may opt to apply the terms of the ordinary GNU General Public License instead of this License to a given copy of the Library. To do this, you must alter all the notices that refer to this License, so that they refer to the ordinary GNU General Public License, version 2, instead of to this License. (If a newer version than version 2 of the ordinary GNU General Public License has appeared, then you can specify that version instead if you wish.) Do not make any other change in these notices. Once this change is made in a given copy, it is irreversible for that copy, so the ordinary GNU General Public License applies to all subsequent copies and derivative works made from that copy. This option is useful when you wish to copy part of the code of the Library into a program that is not a library. 4. You may copy and distribute the Library (or a portion or derivative of it, under Section 2) in object code or executable form under the terms of Sections 1 and 2 above provided that you accompany it with the complete corresponding machine-readable source code, which must be distributed under the terms of Sections 1 and 2 above on a medium customarily used for software interchange. If distribution of object code is made by offering access to copy from a designated place, then offering equivalent access to copy the source code from the same place satisfies the requirement to distribute the source code, even though third parties are not compelled to copy the source along with the object code. 5. A program that contains no derivative of any portion of the Library, but is designed to work with the Library by being compiled or linked with it, is called a "work that uses the Library". Such a work, in isolation, is not a derivative work of the Library, and therefore falls outside the scope of this License. However, linking a "work that uses the Library" with the Library creates an executable that is a derivative of the Library (because it contains portions of the Library), rather than a "work that uses the library". The executable is therefore covered by this License. Section 6 states terms for distribution of such executables. When a "work that uses the Library" uses material from a header file that is part of the Library, the object code for the work may be a derivative work of the Library even though the source code is not. Whether this is true is especially significant if the work can be linked without the Library, or if the work is itself a library. The threshold for this to be true is not precisely defined by law. If such an object file uses only numerical parameters, data structure layouts and accessors, and small macros and small inline functions (ten lines or less in length), then the use of the object file is unrestricted, regardless of whether it is legally a derivative work. (Executables containing this object code plus portions of the Library will still fall under Section 6.) Otherwise, if the work is a derivative of the Library, you may distribute the object code for the work under the terms of Section 6. Any executables containing that work also fall under Section 6, whether or not they are linked directly with the Library itself. 6. As an exception to the Sections above, you may also combine or link a "work that uses the Library" with the Library to produce a work containing portions of the Library, and distribute that work under terms of your choice, provided that the terms permit modification of the work for the customer's own use and reverse engineering for debugging such modifications. You must give prominent notice with each copy of the work that the Library is used in it and that the Library and its use are covered by this License. You must supply a copy of this License. If the work during execution displays copyright notices, you must include the copyright notice for the Library among them, as well as a reference directing the user to the copy of this License. Also, you must do one of these things: a) Accompany the work with the complete corresponding machine-readable source code for the Library including whatever changes were used in the work (which must be distributed under Sections 1 and 2 above); and, if the work is an executable linked with the Library, with the complete machine-readable "work that uses the Library", as object code and/or source code, so that the user can modify the Library and then relink to produce a modified executable containing the modified Library. (It is understood that the user who changes the contents of definitions files in the Library will not necessarily be able to recompile the application to use the modified definitions.) b) Use a suitable shared library mechanism for linking with the Library. A suitable mechanism is one that (1) uses at run time a copy of the library already present on the user's computer system, rather than copying library functions into the executable, and (2) will operate properly with a modified version of the library, if the user installs one, as long as the modified version is interface-compatible with the version that the work was made with. c) Accompany the work with a written offer, valid for at least three years, to give the same user the materials specified in Subsection 6a, above, for a charge no more than the cost of performing this distribution. d) If distribution of the work is made by offering access to copy from a designated place, offer equivalent access to copy the above specified materials from the same place. e) Verify that the user has already received a copy of these materials or that you have already sent this user a copy. For an executable, the required form of the "work that uses the Library" must include any data and utility programs needed for reproducing the executable from it. However, as a special exception, the materials to be distributed need not include anything that is normally distributed (in either source or binary form) with the major components (compiler, kernel, and so on) of the operating system on which the executable runs, unless that component itself accompanies the executable. It may happen that this requirement contradicts the license restrictions of other proprietary libraries that do not normally accompany the operating system. Such a contradiction means you cannot use both them and the Library together in an executable that you distribute. 7. You may place library facilities that are a work based on the Library side-by-side in a single library together with other library facilities not covered by this License, and distribute such a combined library, provided that the separate distribution of the work based on the Library and of the other library facilities is otherwise permitted, and provided that you do these two things: a) Accompany the combined library with a copy of the same work based on the Library, uncombined with any other library facilities. This must be distributed under the terms of the Sections above. b) Give prominent notice with the combined library of the fact that part of it is a work based on the Library, and explaining where to find the accompanying uncombined form of the same work. 8. You may not copy, modify, sublicense, link with, or distribute the Library except as expressly provided under this License. Any attempt otherwise to copy, modify, sublicense, link with, or distribute the Library is void, and will automatically terminate your rights under this License. However, parties who have received copies, or rights, from you under this License will not have their licenses terminated so long as such parties remain in full compliance. 9. You are not required to accept this License, since you have not signed it. However, nothing else grants you permission to modify or distribute the Library or its derivative works. These actions are prohibited by law if you do not accept this License. Therefore, by modifying or distributing the Library (or any work based on the Library), you indicate your acceptance of this License to do so, and all its terms and conditions for copying, distributing or modifying the Library or works based on it. 10. Each time you redistribute the Library (or any work based on the Library), the recipient automatically receives a license from the original licensor to copy, distribute, link with or modify the Library subject to these terms and conditions. You may not impose any further restrictions on the recipients' exercise of the rights granted herein. You are not responsible for enforcing compliance by third parties with this License. 11. If, as a consequence of a court judgment or allegation of patent infringement or for any other reason (not limited to patent issues), conditions are imposed on you (whether by court order, agreement or otherwise) that contradict the conditions of this License, they do not excuse you from the conditions of this License. If you cannot distribute so as to satisfy simultaneously your obligations under this License and any other pertinent obligations, then as a consequence you may not distribute the Library at all. For example, if a patent license would not permit royalty-free redistribution of the Library by all those who receive copies directly or indirectly through you, then the only way you could satisfy both it and this License would be to refrain entirely from distribution of the Library. If any portion of this section is held invalid or unenforceable under any particular circumstance, the balance of the section is intended to apply, and the section as a whole is intended to apply in other circumstances. It is not the purpose of this section to induce you to infringe any patents or other property right claims or to contest validity of any such claims; this section has the sole purpose of protecting the integrity of the free software distribution system which is implemented by public license practices. Many people have made generous contributions to the wide range of software distributed through that system in reliance on consistent application of that system; it is up to the author/donor to decide if he or she is willing to distribute software through any other system and a licensee cannot impose that choice. This section is intended to make thoroughly clear what is believed to be a consequence of the rest of this License. 12. If the distribution and/or use of the Library is restricted in certain countries either by patents or by copyrighted interfaces, the original copyright holder who places the Library under this License may add an explicit geographical distribution limitation excluding those countries, so that distribution is permitted only in or among countries not thus excluded. In such case, this License incorporates the limitation as if written in the body of this License. 13. The Free Software Foundation may publish revised and/or new versions of the Lesser General Public License from time to time. Such new versions will be similar in spirit to the present version, but may differ in detail to address new problems or concerns. Each version is given a distinguishing version number. If the Library specifies a version number of this License which applies to it and "any later version", you have the option of following the terms and conditions either of that version or of any later version published by the Free Software Foundation. If the Library does not specify a license version number, you may choose any version ever published by the Free Software Foundation. 14. If you wish to incorporate parts of the Library into other free programs whose distribution conditions are incompatible with these, write to the author to ask for permission. For software which is copyrighted by the Free Software Foundation, write to the Free Software Foundation; we sometimes make exceptions for this. Our decision will be guided by the two goals of preserving the free status of all derivatives of our free software and of promoting the sharing and reuse of software generally. NO WARRANTY 15. BECAUSE THE LIBRARY IS LICENSED FREE OF CHARGE, THERE IS NO WARRANTY FOR THE LIBRARY, TO THE EXTENT PERMITTED BY APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT HOLDERS AND/OR OTHER PARTIES PROVIDE THE LIBRARY "AS IS" WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE LIBRARY IS WITH YOU. SHOULD THE LIBRARY PROVE DEFECTIVE, YOU ASSUME THE COST OF ALL NECESSARY SERVICING, REPAIR OR CORRECTION. 16. IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MAY MODIFY AND/OR REDISTRIBUTE THE LIBRARY AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE USE OR INABILITY TO USE THE LIBRARY (INCLUDING BUT NOT LIMITED TO LOSS OF DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD PARTIES OR A FAILURE OF THE LIBRARY TO OPERATE WITH ANY OTHER SOFTWARE), EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGES. END OF TERMS AND CONDITIONS How to Apply These Terms to Your New Libraries If you develop a new library, and you want it to be of the greatest possible use to the public, we recommend making it free software that everyone can redistribute and change. You can do so by permitting redistribution under these terms (or, alternatively, under the terms of the ordinary General Public License). To apply these terms, attach the following notices to the library. It is safest to attach them to the start of each source file to most effectively convey the exclusion of warranty; and each file should have at least the "copyright" line and a pointer to where the full notice is found. {description} Copyright (C) {year} {fullname} This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this library; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA Also add information on how to contact you by electronic and paper mail. You should also get your employer (if you work as a programmer) or your school, if any, to sign a "copyright disclaimer" for the library, if necessary. Here is a sample; alter the names: Yoyodyne, Inc., hereby disclaims all copyright interest in the library `Frob' (a library for tweaking knobs) written by James Random Hacker. {signature of Ty Coon}, 1 April 1990 Ty Coon, President of Vice That's all there is to it! hoel-1.4.29/Makefile000066400000000000000000000026611452453561700142170ustar00rootroot00000000000000# # Example program # # Makefile used to build all programs # # Copyright 2014-2020 Nicolas Mora # # 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; # version 2.1 of the License. # # This library is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU GENERAL PUBLIC LICENSE for more details. # # You should have received a copy of the GNU General Public # License along with this library. If not, see . # LIBHOEL_LOCATION=./src EXAMPLE_LOCATION=./examples TEST_LOCATION=./test all: release debug: cd $(LIBHOEL_LOCATION) && $(MAKE) debug $* install: cd $(EXAMPLE_LOCATION) && $(MAKE) install $* clean: cd $(LIBHOEL_LOCATION) && $(MAKE) clean cd $(EXAMPLE_LOCATION) && $(MAKE) clean cd $(TEST_LOCATION) && $(MAKE) clean rm -rf doc/html/ release: cd $(LIBHOEL_LOCATION) && $(MAKE) $* simple_example: cd $(EXAMPLE_LOCATION) && $(MAKE) $* example_sqlite3: cd $(EXAMPLE_LOCATION) && $(MAKE) example_sqlite3 $* example_mariadb: cd $(EXAMPLE_LOCATION) && $(MAKE) example_mariadb $* example_pgsql: cd $(EXAMPLE_LOCATION) && $(MAKE) example_pgsql $* check: cd $(TEST_LOCATION) && $(MAKE) test $* doxygen: doxygen doc/doxygen.cfg hoel-1.4.29/README.md000066400000000000000000000532411452453561700140360ustar00rootroot00000000000000# Hoel ![.github/workflows/ccpp.yml](https://github.com/babelouest/hoel/workflows/.github/workflows/ccpp.yml/badge.svg) Database abstraction library written in C. Simple and easy to use database access library. Works with SQLite 3, MariaDB and PostgreSQL databases. Uses a JSON-based language with `jansson` to execute simple queries based on one table. # Online documentation See the [online documentation](https://babelouest.github.io/hoel/) for a doxygen format of the API documentation. # Installation ## Prerequisites ### Jansson Install [Jansson](http://www.digip.org/jansson/) library for JSON manipulation, minimum version 2.4. On a Debian-based platform, run the following command: ```shell $ sudo apt-get install libjansson-dev ``` ### Database libraries Install Hoel database dependencies based on your requirements: - SQLite3: Install the package `libsqlite3-dev` - MariaDB: Install the package `libmariadb-dev` - PostgreSQL: Install the package `libpq-dev` ### Distribution packages [![Packaging status](https://repology.org/badge/vertical-allrepos/hoel.svg)](https://repology.org/metapackage/hoel) Hoel is available in multiple distributions as official package. Check out your distribution documentation to install the package automatically. ```shell $ # Example for Debian testing $ sudo apt install libhoel-dev ``` ### Pre-compiled packages You can install Hoel with a pre-compiled package available in the [release pages](https://github.com/babelouest/hoel/releases/latest/). `jansson`, `sqlite3`, `libmariadb-client` and `libpq` development files packages are required to install Hoel. The packages files `hoel-dev-full_*` contain the libraries `orcania`, `yder` and `hoel`. It's also compiled with all the database backends. For example, to install Hoel with the `hoel-dev-full_2.3.0_Debian_stretch_x86_64.tar.gz` package downloaded on the `releases` page, you must execute the following commands: ```shell $ sudo apt install -y libjansson-dev libmariadb-dev libsqlite3-dev libpq-dev libsystemd-dev $ wget https://github.com/babelouest/hoel/releases/download/v1.4.0/hoel-dev-full_1.4.0_Debian_stretch_x86_64.tar.gz $ tar xf hoel-dev-full_1.4.0_Debian_stretch_x86_64.tar.gz $ sudo dpkg -i liborcania-dev_1.2.0_Debian_stretch_x86_64.deb $ sudo dpkg -i libyder-dev_1.2.0_Debian_stretch_x86_64.deb $ sudo dpkg -i libhoel-dev_1.4.0_Debian_stretch_x86_64.deb ``` If there's no package available for your distribution, you can recompile it manually using `CMake` or `Makefile`. ## Install from the source ### CMake - Multi architecture [CMake](https://cmake.org/download/) minimum 3.5 is required. Last Hoel release: [https://github.com/babelouest/hoel/releases/latest/](https://github.com/babelouest/hoel/releases/latest/) Run the CMake script in a sub-directory, example: ```shell $ cd $ mkdir build $ cd build $ cmake .. $ make && sudo make install ``` The available options for CMake are: - `-DWITH_SQLITE3=[on|off]` (default `on`): Enable/disable SQLite3 database backend - `-DWITH_MARIADB=[on|off]` (default `on`): Enable/disable MariaDB database backend - `-DWITH_PGSQL=[on|off]` (default `on`): Enable/disable PostgreSQL database backend - `-DWITH_JOURNALD=[on|off]` (default `on`): Build with journald (SystemD) support for logging - `-DBUILD_STATIC=[on|off]` (default `off`): Build the static archive in addition to the shared library - `-DBUILD_HOEL_TESTING=[on|off]` (default `off`): Build unit tests - `-DBUILD_HOEL_DOCUMENTATION=[on|off]` (default `off`): Build the documentation, doxygen is required - `-DINSTALL_HEADER=[on|off]` (default `on`): Install header file `hoel.h` - `-DBUILD_RPM=[on|off]` (default `off`): Build RPM package when running `make package` - `-DCMAKE_BUILD_TYPE=[Debug|Release]` (default `Release`): Compile with debugging symbols or not ### Good ol' Makefile Clone, compile and install [Orcania](https://github.com/babelouest/orcania) and [Yder](https://github.com/babelouest/yder) libraries. ### Orcania (Miscellaneous functions) Last Orcania release: [https://github.com/babelouest/orcania/releases/latest/](https://github.com/babelouest/orcania/releases/latest/) ```shell $ cd orcania/src $ make && sudo make install ``` ### Yder (simple logs library) Last Yder release: [https://github.com/babelouest/yder/releases/latest/](https://github.com/babelouest/yder/releases/latest/) ```shell $ cd yder/src $ make $ sudo make install ``` ### Hoel Last Hoel release: [https://github.com/babelouest/hoel/releases/latest/](https://github.com/babelouest/hoel/releases/latest/) ```shell $ cd hoel/src $ make $ sudo make install ``` By default, Hoel is compiled with the 3 databases support. If you don't need one or more database, follow these instructions #### SQLite 3 Add DISABLE_SQLITE=1 to the `make` command: ```shell $ cd hoel/src $ make DISABLE_SQLITE=1 $ sudo make install ``` #### MariaDB Add DISABLE_MARIADB=1 to the `make` command: ```shell $ cd hoel/src $ make DISABLE_MARIADB=1 $ sudo make install ``` #### Postgre SQL Add DISABLE_POSTGRESQL=1 to the `make` command: ```shell $ cd hoel/src $ make DISABLE_POSTGRESQL=1 $ sudo make install ``` ### Disable 2 backends You can disable 2 databases backends to keep just one, simply add both parameters to the `make` command: ```shell $ cd hoel/src $ make DISABLE_MARIADB=1 DISABLE_POSTGRESQL=1 $ sudo make install ``` ### Installation folder By default, the shared library and the header file will be installed in the `/usr/local` location. To change this setting, you can modify the `DESTDIR` value in the `src/Makefile`. # API Documentation ## Header files and compilation To use Hoel in your code, include the file `hoel.h`. ```c #include ``` Use the flag `-lhoel` to include Hoel library in the linking process. ### Return values When specified, some functions return `H_OK` on success, and other values otherwise. `H_OK` is 0, other values are non-0 values. The defined errors list is the following: ```c #define H_OK 0 // No error #define H_ERROR 1 // Generic error #define H_ERROR_PARAMS 2 // Error in input parameters #define H_ERROR_CONNECTION 3 // Error in database connection #define H_ERROR_DISABLED 4 // Database connection is disabled #define H_ERROR_QUERY 5 // Error executing query #define H_ERROR_MEMORY 99 // Error allocating memory ``` ### Memory allocation Some function return allocated values. When the value is not a structure, you must use the function `h_free` to clean it. Otherwise, use the dedicated functions. ```c /** * free data allocated by hoel functions */ void h_free(void * data); ``` ### Initialization To create a connection to a database, use its dedicated function ```c /** * h_connect_sqlite * Opens a database connection to a sqlite3 db file * return pointer to a struct _h_connection * on sucess, NULL on error */ struct _h_connection * h_connect_sqlite(const char * db_path); /** * h_connect_mariadb * Opens a database connection to a mariadb server * return pointer to a struct _h_connection * on success, NULL on error */ struct _h_connection * h_connect_mariadb(const char * host, const char * user, const char * passwd, const char * db, const unsigned int port, const char * unix_socket); /** * h_connect_pgsql * Opens a database connection to a PostgreSQL server * return pointer to a struct _h_connection * on sucess, NULL on error */ struct _h_connection * h_connect_pgsql(char * conninfo); ``` All these functions return a struct _h_connection * on success. This pointer will be needed on every call to Hoel functions. When you no longer need your connection, close it using the function `h_close_db`. This will close the connection to the database and free the memory allocated by the connection. ```c /** * Close a database connection * return H_OK on success */ int h_close_db(struct _h_connection * conn); ``` The connection must be cleaned when it's no longer needed. ```c /** * h_clean_connection * free memory allocated by the struct _h_connection * return H_OK on success */ int h_clean_connection(struct _h_connection * conn); ``` ### Escape string If you need to escape parameters, you can use the functions `h_escape_string`, the returned value must be h_free'd after use. The meaning of existence of the function `h_escape_string_with_quotes` is because of PostgreSQL ways to escape an unsafe string. TL;DR: - Use `h_escape_string_with_quotes` only if you use a PostgreSQL database. - You can use both `h_escape_string_with_quotes` and `h_escape_string` if you use only SQLite3 and/or MariaDB databases. If the unsafe string contains backslashes `"\"`, the escaped string will have the pattern `E''`, otherwise it will have the pattern `''`. Since the function `h_escape_string` must return the safe string only, without surroundings quotes `'`, the format `E''` is incompatible with Hoel API. Therefore, using `h_escape_string` with PostgreSQL could lead to undefined behaviour and more importantly exploitable bugs. To avoid this, on a PostgreSQL database, an escaped string using `h_escape_string` that should return the format `E''` will return `NULL`, and an escaped string using `h_escape_string_with_quotes` will return the format `E''`. ```c /** * h_escape_string * Escapes a string * returned value must be h_free'd after use */ char * h_escape_string(const struct _h_connection * conn, const char * unsafe); /** * h_escape_string_with_quotes * Escapes a string and returns it ready to be inserted in the query * returned value must be h_h_free'd after use */ char * h_escape_string_with_quotes(const struct _h_connection * conn, const char * unsafe); ``` ### Build a more complicated where clause When you need to run a query with a where clause using multiple parameters, such as `WHERE col1='a' AND (col2='b' OR col3=5) AND col4=42.3`, you can use the operator `raw`: ```JSON { "table": "table1", "columns": ["col1", "col2"] "where": { " ": { "operator", "raw", "value", "col1='a' AND (col2='b' or col3='c') AND col4=5" } } } ``` In some cases, you may need to build the where clause with multiple variables. In hoel 1.4.27, the function `h_build_where_clause` was introduced to help that. Please note that this function is still in Beta. ```C /** * h_build_where_clause * Generates a where clause based on the pattern and the values given * @param conn the connection to the database * @param pattern the pattern to build the where clause * the pattern variables available are the following: * - %s: a string value to escape with quotes * - %S: a string value to escape without quotes * - %c: a string value not to escape with quotes * - %C: a string value not to escape without quotes * - %d: an integer value in json_int_t format * - %f: a double value * - %j: a json_t value, the value must be of the type JSON_INTEGER, JSON_REAL or JSON_STRING, string values will be escaped with quotes * - %%: the value '%' * @return a heap-allocated string * returned value must be h_free'd after use */ char * h_build_where_clause(const struct _h_connection * conn, const char * pattern, ...); ``` Then, to build the where clause above using `h_build_where_clause`, you can use the following code: ```C const char col1[] = "a", col2[] = "b"; json_int_t col3 = 5; double col4 = 42.3; char * where_clause = h_build_where_clause("col1=%s AND (col2='S' OR col3=%d) AND col4=%f", col1, col2, col3, col4); json_t * j_query = json_pack("{sss[ss]s{s{ssss}}}", "table", "table1", "columns", "col1", "col2", "where", " ", "operator", "raw", "value", where_clause); h_free(where_clause); // Execute j_query ``` Note that if you use constant litteral for integer or double values, you should cast them first: ```C const char col1[] = "a", col2[] = "b"; char * where_clause = h_build_where_clause("col1=%s AND (col2='S' OR col3=%d) AND col4=%f", col1, col2, (json_int_t)5, (double)42.3); ``` ### Execute a SQL query To execute a SQL query, you can use the function `h_execute_query` which will run the query in the database specified by the parameter `conn`. If a `result` parameter is specified, the result of the query (if any) will be stored in the `result` structure. ```c /** * h_execute_query * Execute a query, set the result structure with the returned values if available * if result is NULL, the query is executed but no value will be returned * options available * H_OPTION_NONE (0): no option * H_OPTION_SELECT: Execute a prepare statement (sqlite only) * H_OPTION_EXEC: Execute an exec statement (sqlite only) * return H_OK on success */ int h_execute_query(const struct _h_connection * conn, const char * query, struct _h_result * result, int options); ``` ### Result structure The `struct _h_result` is a structure containing the values returned by a query. The definition of the structure is: ```c /** * sql result structure */ struct _h_result { unsigned int nb_rows; unsigned int nb_columns; struct _h_data ** data; }; ``` The data value is a 2 dimensional array with `struct _h_data` variables. A `struct _h_data` is defined as: ```c /** * sql data container */ struct _h_data { int type; void * t_data; }; ``` where `type` can be the following values: ```c #define HOEL_COL_TYPE_INT 0 #define HOEL_COL_TYPE_DOUBLE 1 #define HOEL_COL_TYPE_TEXT 2 #define HOEL_COL_TYPE_DATE 3 #define HOEL_COL_TYPE_BLOB 4 #define HOEL_COL_TYPE_NULL 5 ``` `t_data` will point to a `struct _h_type_*` corresponding to the type. The `struct _h_type_*` available are: ```c /** * sql value integer type */ struct _h_type_int { int value; }; /** * sql value double type */ struct _h_type_double { double value; }; /** * sql value date/time type */ struct _h_type_datetime { struct tm value; }; /** * sql value string type */ struct _h_type_text { char * value; }; /** * sql value blob type */ struct _h_type_blob { size_t length; void * value; }; ``` ### Clean results or data To clean a result or a data structure, you can use its dedicated functions: ```c /** * h_clean_result * Free all the memory allocated by the struct _h_result * return H_OK on success */ int h_clean_result(struct _h_result * result); /** * h_clean_data * Free memory allocated by the struct _h_data * return H_OK on success */ int h_clean_data(struct _h_data * data); ``` ### Get last id inserted If you need the last id generated after an insert query, you can use the following function: ```c /** * h_query_last_insert_id * return the id of the last inserted value * return a pointer to `struct _h_data *` on success, NULL otherwise. */ struct _h_data * h_query_last_insert_id(const struct _h_connection * conn); ``` ### Additional query functions You can use additional functions for specific needs. All these function will use `h_execute_query` but check input parameters before. ```c /** * h_query_insert * Execute an insert query * return H_OK on success */ int h_query_insert(const struct _h_connection * conn, const char * query); /** * h_query_update * Execute an update query * return H_OK on success */ int h_query_update(const struct _h_connection * conn, const char * query); /** * h_query_delete * Execute an delete query * return H_OK on success */ int h_query_delete(const struct _h_connection * conn, const char * query); /** * h_execute_query * Execute a select query, set the result structure with the returned values * return H_OK on success */ int h_query_select(const struct _h_connection * conn, const char * query, struct _h_result * result); ``` ### Simple JSON queries Hoel allows to use JSON objects for simple queries with `jansson` library. In the simple JSON queries, a JSON object called `json_t * j_query` is used to generate the query. All `json_t *` returned and updated values must be free after use. A `j_query` has the following form: ```javascript * { * "table": "table_name" // String, mandatory, the table name where the query is executed * "columns": ["col1", "col2"] // Array of strings, available for h_select, optional. If not specified, * will be used, the columns values are not escaped by the library * "order_by": "col_name [asc|desc]" // String, available for h_select, specify the order by clause, optional, the value is not escaped by the library * "limit": integer_value // Integer, available for h_select, specify the limit value, optional * "offset" // Integer, available for h_select, specify the limit value, optional but available only if limit is set * "values": [{ // json object or json array of json objects, available for h_insert, mandatory, specify the values to update * "col1": "value1", // Generates col1='value1' for an update query * "col2": value_integer, // Generates col2=value_integer for an update query * "col3", "value3", // Generates col3='value3' for an update query * "col4", null // Generates col4=NULL for an update query * }] * "set": { // json object, available for h_update, mandatory, specify the values to update * "col1": "value1", // Generates col1='value1' for an update query * "col2": value_integer, // Generates col2=value_integer for an update query * "col3", "value3", // Generates col3='value3' for an update query * "col4", null // Generates col4=NULL for an update query * } * "where": { // json object, available for h_select, h_update and h_delete, mandatory, specify the where clause. All clauses are separated with an AND operator * "col1": "value1", // Generates col1='value1' * "col2": value_integer, // Generates col2=value_integer * "col3": null, // Generates col3=NULL * "col4", { // Generates col4<12 * "operator": "<", * "value": 12 * }, * "col5", { // Generates col5 IS NOT NULL * "operator": "NOT NULL" * }, * "col6", { // Generates col6 LIKE '%value6%' * "operator": "raw", * "value": "LIKE '%value6%'" * } * } * } ``` #### Where clause construction A `where` clause is a JSON object containing a series of clauses. A clause can have 2 different forms: - `col_name: value` - `col_name: {operator: "operator_value", value: value}` In the first case, `col_name: value`, the clause becomes `col_name = value`. Value is always escaped. In the second case, `col_name: {operator: "operator_value", value: value}`, depending on the `operator` value, the clause can have different forms: - `operator: "NOT NULL"`, the clause becomes `col_name IS NOT NULL` - `operator: "raw"`, the `value` value becomes the clause itself, not escaped, for example in `{ "operator": "raw", "value": "LIKE '%value6%'" }`, the clause becomes `col6 LIKE '%value6%'` - otherwise, the clause becomes `col_name operator value`, value is escaped All clauses are separated by an `AND` operator. As en example, here is a JSON object and its generated where clause: JSON object: ```javascript { "col1": "value1", "col2": 42, "col3": { "operator": ">=", "value": 55.5 }, "col4": { "operator": "raw", "value": "LIKE '%alu%'" } } ``` SQL Where clause: ```sql WHERE col1 = 'value1' AND col2 = 42 AND col3 >= 55.5 AND col4 LIKE '%alu%' ``` If you need less simple clauses, you can build it on your own and use the `h_execute_query` or the `h_execute_query_json` functions. The simple JSON queries functions are: ```c /** * h_select * Execute a select query * Uses a json_t * parameter for the query parameters * Store the result of the query in j_result if specified. j_result must be decref'd after use * Duplicate the generated query in generated_query if specified, must be h_free'd after use * return H_OK on success */ int h_select(const struct _h_connection * conn, const json_t * j_query, json_t ** j_result, char ** generated_query); /** * h_insert * Execute an insert query * Uses a json_t * parameter for the query parameters * Duplicate the generated query in generated_query if specified, must be h_free'd after use * return H_OK on success */ int h_insert(const struct _h_connection * conn, const json_t * j_query, char ** generated_query); /** * h_last_insert_id * return the id of the last inserted value * return a pointer to `json_t *` on success, NULL otherwise. * The returned value is of type JSON_INTEGER */ json_t * h_last_insert_id(const struct _h_connection * conn); /** * h_update * Execute an update query * Uses a json_t * parameter for the query parameters * Duplicate the generated query in generated_query if specified, must be h_free'd after use * return H_OK on success */ int h_update(const struct _h_connection * conn, const json_t * j_query, char ** generated_query); /** * h_delete * Execute a delete query * Uses a json_t * parameter for the query parameters * Duplicate the generated query in generated_query if specified, must be h_free'd after use * return H_OK on success */ int h_delete(const struct _h_connection * conn, const json_t * j_query, char ** generated_query); ``` #### JSON last insert id The function `h_last_insert_id` returns the last inserted id in a `json_t *` format. ```c /** * h_last_insert_id * return the id of the last inserted value * return a pointer to `json_t *` on success, NULL otherwise. * The returned value is of type JSON_INTEGER */ json_t * h_last_insert_id(const struct _h_connection * conn); ``` ### Example source code See `examples` folder for detailed sample source codes. hoel-1.4.29/_config.yml000066400000000000000000000000331452453561700146750ustar00rootroot00000000000000theme: jekyll-theme-minimalhoel-1.4.29/cmake-modules/000077500000000000000000000000001452453561700153005ustar00rootroot00000000000000hoel-1.4.29/cmake-modules/CMakeUninstall.cmake.in000066400000000000000000000020641452453561700215630ustar00rootroot00000000000000if (NOT EXISTS "@CMAKE_BINARY_DIR@/install_manifest.txt") message(FATAL_ERROR "Cannot find install manifest: @CMAKE_BINARY_DIR@/install_manifest.txt") endif (NOT EXISTS "@CMAKE_BINARY_DIR@/install_manifest.txt") file(READ "@CMAKE_BINARY_DIR@/install_manifest.txt" files) string(REGEX REPLACE "\n" ";" files "${files}") foreach (file ${files}) message(STATUS "Uninstalling $ENV{DESTDIR}${file}") if (IS_SYMLINK "$ENV{DESTDIR}${file}" OR EXISTS "$ENV{DESTDIR}${file}") exec_program( "@CMAKE_COMMAND@" ARGS "-E remove \"$ENV{DESTDIR}${file}\"" OUTPUT_VARIABLE rm_out RETURN_VALUE rm_retval ) if (NOT "${rm_retval}" STREQUAL 0) message(FATAL_ERROR "Problem when removing $ENV{DESTDIR}${file}") endif (NOT "${rm_retval}" STREQUAL 0) else (IS_SYMLINK "$ENV{DESTDIR}${file}" OR EXISTS "$ENV{DESTDIR}${file}") message(STATUS "File $ENV{DESTDIR}${file} does not exist.") endif (IS_SYMLINK "$ENV{DESTDIR}${file}" OR EXISTS "$ENV{DESTDIR}${file}") endforeach (file) hoel-1.4.29/cmake-modules/CTestCustom.cmake.in000066400000000000000000000001421452453561700211210ustar00rootroot00000000000000string(REPLACE ";" " " TESTS "@TESTS@") set(CTEST_CUSTOM_PRE_TEST "@CMAKE_MAKE_PROGRAM@ ${TESTS}")hoel-1.4.29/cmake-modules/FindCheck.cmake000066400000000000000000000054641452453561700201310ustar00rootroot00000000000000#.rst: # FindCheck # ----------- # # Find Check # # Find Check headers and libraries. # # :: # # CHECK_FOUND - True if Check found. # CHECK_INCLUDE_DIRS - Where to find check.h. # CHECK_LIBRARIES - List of libraries when using Check. # CHECK_VERSION_STRING - The version of Check found. #============================================================================= # Copyright 2018 Silvio Clecio # # 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; # version 2.1 of the License. # # This library is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU GENERAL PUBLIC LICENSE for more details. # # You should have received a copy of the GNU General Public # License along with this library. If not, see . #============================================================================= # Sat Jan 20 23:33:47 -03 2018 find_package(PkgConfig QUIET) pkg_check_modules(PC_CHECK QUIET check) find_path(CHECK_INCLUDE_DIR NAMES check.h HINTS ${PC_CHECK_INCLUDEDIR} ${PC_CHECK_INCLUDE_DIRS}) find_library(CHECK_LIBRARY NAMES check libcheck HINTS ${PC_CHECK_LIBDIR} ${PC_CHECK_LIBRARY_DIRS}) if (PC_CHECK_VERSION) set(CHECK_VERSION_STRING ${PC_CHECK_VERSION}) elseif (CHECK_INCLUDE_DIR AND EXISTS "${CHECK_INCLUDE_DIR}/check.h") set(check_version_list MAJOR MINOR MICRO) foreach (v ${check_version_list}) set(regex_check_version "^#define CHECK_${v}_VERSION +\\(?([0-9]+)\\)?$") file(STRINGS "${CHECK_INCLUDE_DIR}/check.h" check_version_${v} REGEX "${regex_check_version}") string(REGEX REPLACE "${regex_check_version}" "\\1" check_version_${v} "${check_version_${v}}") unset(regex_check_version) endforeach () set(CHECK_VERSION_STRING "${check_version_MAJOR}.${check_version_MINOR}.${check_version_MICRO}") foreach (v check_version_list) unset(check_version_${v}) endforeach () unset(check_version_list) endif () include(FindPackageHandleStandardArgs) find_package_handle_standard_args(Check REQUIRED_VARS CHECK_LIBRARY CHECK_INCLUDE_DIR VERSION_VAR CHECK_VERSION_STRING) if (CHECK_FOUND) set(CHECK_LIBRARIES ${CHECK_LIBRARY}) set(CHECK_INCLUDE_DIRS ${CHECK_INCLUDE_DIR}) if (NOT TARGET Check::Check) add_library(Check::Check UNKNOWN IMPORTED) set_target_properties(Check::Check PROPERTIES IMPORTED_LOCATION "${CHECK_LIBRARY}" INTERFACE_INCLUDE_DIRECTORIES "${CHECK_INCLUDE_DIR}") endif () endif () mark_as_advanced(CHECK_INCLUDE_DIR CHECK_LIBRARY) hoel-1.4.29/cmake-modules/FindJansson.cmake000066400000000000000000000051521452453561700205210ustar00rootroot00000000000000#.rst: # FindJansson # ----------- # # Find Jansson # # Find Jansson headers and libraries. # # :: # # JANSSON_FOUND - True if Jansson found. # JANSSON_INCLUDE_DIRS - Where to find jansson.h. # JANSSON_LIBRARIES - List of libraries when using Jansson. # JANSSON_VERSION_STRING - The version of Jansson found. #============================================================================= # Copyright 2018 Silvio Clecio # # 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; # version 2.1 of the License. # # This library is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU GENERAL PUBLIC LICENSE for more details. # # You should have received a copy of the GNU General Public # License along with this library. If not, see . #============================================================================= # Sat Jan 20 12:32:26 -03 2018 find_package(PkgConfig QUIET) pkg_check_modules(PC_JANSSON QUIET jansson) find_path(JANSSON_INCLUDE_DIR NAMES jansson.h HINTS ${PC_JANSSON_INCLUDEDIR} ${PC_JANSSON_INCLUDE_DIRS}) find_library(JANSSON_LIBRARY NAMES jansson libjansson HINTS ${PC_JANSSON_LIBDIR} ${PC_JANSSON_LIBRARY_DIRS}) if (PC_JANSSON_VERSION) set(JANSSON_VERSION_STRING ${PC_JANSSON_VERSION}) elseif (JANSSON_INCLUDE_DIR AND EXISTS "${JANSSON_INCLUDE_DIR}/jansson.h") set(regex_jansson_version "^#define[ \t]+JANSSON_VERSION[ \t]+\"([^\"]+)\".*") file(STRINGS "${JANSSON_INCLUDE_DIR}/jansson.h" jansson_version REGEX "${regex_jansson_version}") string(REGEX REPLACE "${regex_jansson_version}" "\\1" JANSSON_VERSION_STRING "${jansson_version}") unset(regex_jansson_version) unset(jansson_version) endif () include(FindPackageHandleStandardArgs) find_package_handle_standard_args(Jansson REQUIRED_VARS JANSSON_LIBRARY JANSSON_INCLUDE_DIR VERSION_VAR JANSSON_VERSION_STRING) if (JANSSON_FOUND) set(JANSSON_LIBRARIES ${JANSSON_LIBRARY}) set(JANSSON_INCLUDE_DIRS ${JANSSON_INCLUDE_DIR}) if (NOT TARGET Jansson::Jansson) add_library(Jansson::Jansson UNKNOWN IMPORTED) set_target_properties(Jansson::Jansson PROPERTIES IMPORTED_LOCATION "${JANSSON_LIBRARY}" INTERFACE_INCLUDE_DIRECTORIES "${JANSSON_INCLUDE_DIR}") endif () endif () mark_as_advanced(JANSSON_INCLUDE_DIR JANSSON_LIBRARY) hoel-1.4.29/cmake-modules/FindLibPQ.cmake000066400000000000000000000053321452453561700200550ustar00rootroot00000000000000######################################## # BEGIN_COPYRIGHT # # Copyright (C) 2008-2015 SciDB, Inc. # All Rights Reserved. # # SciDB is free software: you can redistribute it and/or modify # it under the terms of the AFFERO GNU General Public License as published by # the Free Software Foundation. # # SciDB is distributed "AS-IS" AND WITHOUT ANY WARRANTY OF ANY KIND, # INCLUDING ANY IMPLIED WARRANTY OF MERCHANTABILITY, # NON-INFRINGEMENT, OR FITNESS FOR A PARTICULAR PURPOSE. See # the AFFERO GNU General Public License for the complete license terms. # # You should have received a copy of the AFFERO GNU General Public License # along with SciDB. If not, see # # END_COPYRIGHT ######################################## # # Try to find libpq # # Once done this will define # LIBPQ_FOUND - TRUE if libpq found # LIBPQ_INCLUDE_DIRS - Where to find libpq include sub-directory # LIBPQ_LIBRARIES_DIRS - Where to find libpq library sub-directory # LIBPQ_LIBRARIES - List of libraries when using libpq # # check cache if(LIBPQ_INCLUDE_DIRS) set(LIBPQ_INCLUDE_DIRS TRUE) endif(LIBPQ_INCLUDE_DIRS) find_program(PG_CONFIG_EXECUTABLE NAMES pg_config DOC "pg_config - retrieve information about the installed version of PostgreSQL") include(FindPackageHandleStandardArgs) find_package_handle_standard_args(LibPQ DEFAULT_MSG PG_CONFIG_EXECUTABLE) if(PG_CONFIG_EXECUTABLE) execute_process( COMMAND ${PG_CONFIG_EXECUTABLE} "--includedir" OUTPUT_VARIABLE LIBPQ_INCLUDE_DIRS) string(REGEX REPLACE "[\r\n]" " " LIBPQ_INCLUDE_DIRS ${LIBPQ_INCLUDE_DIRS}) string(REGEX REPLACE " +$" "" LIBPQ_INCLUDE_DIRS ${LIBPQ_INCLUDE_DIRS}) execute_process( COMMAND ${PG_CONFIG_EXECUTABLE} "--libdir" OUTPUT_VARIABLE LIBPQ_LIBRARIES_DIRS) string(REGEX REPLACE "[\r\n]" " " LIBPQ_LIBRARIES_DIRS ${LIBPQ_LIBRARIES_DIRS}) string(REGEX REPLACE " +$" "" LIBPQ_LIBRARIES_DIRS ${LIBPQ_LIBRARIES_DIRS}) find_library(LIBPQ_LIBRARY pq ${LIBPQ_LIBRARIES_DIRS}) set(LIBPQ_LIBRARIES ${LIBPQ_LIBRARY}) find_package_handle_standard_args(LibPQ DEFAULT_MSG LIBPQ_LIBRARIES_DIRS LIBPQ_LIBRARIES LIBPQ_INCLUDE_DIRS) else(PG_CONFIG_EXECUTABLE) message(SEND_ERROR "pg_config not found. Do you have PostgreSQL development package installed?") endif(PG_CONFIG_EXECUTABLE) if (LIBPQ_FOUND) set(LIBPQ_LIBRARIES ${LIBPQ_LIBRARY}) if (NOT TARGET PostgreSQL::PostgreSQL) add_library(PostgreSQL::PostgreSQL UNKNOWN IMPORTED) set_target_properties(PostgreSQL::PostgreSQL PROPERTIES IMPORTED_LOCATION "${LIBPQ_LIBRARY}" INTERFACE_INCLUDE_DIRECTORIES "${LIBPQ_INCLUDE_DIR}") endif () endif () # mark cache mark_as_advanced(LIBPQ_LIBRARIES_DIRS LIBPQ_LIBRARIES LIBPQ_INCLUDE_DIRS) hoel-1.4.29/cmake-modules/FindMYSQL.cmake000066400000000000000000000064551452453561700200220ustar00rootroot00000000000000# - Try to find MySQL. # Once done this will define: # MYSQL_FOUND - If false, do not try to use MySQL. # MYSQL_INCLUDE_DIRS - Where to find mysql.h, etc. # MYSQL_LIBRARIES - The libraries to link against. # MYSQL_VERSION_STRING - Version in a string of MySQL. # # Created by RenatoUtsch based on eAthena implementation. # # Please note that this module only supports Windows and Linux officially, but # should work on all UNIX-like operational systems too. # #============================================================================= # Copyright 2012 RenatoUtsch # Copyright 2018 Nicolas Mora # # Distributed under the OSI-approved BSD License (the "License"); # see accompanying file Copyright.txt for details. # # This software is distributed WITHOUT ANY WARRANTY; without even the # implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. # See the License for more information. #============================================================================= # (To distribute this file outside of CMake, substitute the full # License text for the above reference.) if( WIN32 ) find_path( MYSQL_INCLUDE_DIR NAMES "mysql.h" PATHS "$ENV{PROGRAMFILES}/MySQL/*/include" "$ENV{PROGRAMFILES(x86)}/MySQL/*/include" "$ENV{SYSTEMDRIVE}/MySQL/*/include" ) find_library( MYSQL_LIBRARY NAMES "mysqlclient" "mysqlclient_r" PATHS "$ENV{PROGRAMFILES}/MySQL/*/lib" "$ENV{PROGRAMFILES(x86)}/MySQL/*/lib" "$ENV{SYSTEMDRIVE}/MySQL/*/lib" ) else() find_path( MYSQL_INCLUDE_DIR NAMES "mysql.h" PATHS "/usr/include/mysql" "/usr/local/include/mysql" "/usr/mysql/include/mysql" ) find_library( MYSQL_LIBRARY NAMES "mysqlclient" "mysqlclient_r" "mariadbclient" "mariadbclient_r" PATHS "/lib/mysql" "/lib/arm-linux-gnueabihf" "/lib64/mysql" "/usr/lib/mysql" "/usr/lib64/mysql" "/usr/lib/arm-linux-gnueabihf" "/usr/local/lib/mysql" "/usr/local/lib64/mysql" "/usr/local/lib/arm-linux-gnueabihf" "/usr/mysql/lib/mysql" "/usr/mysql/lib64/mysql" ) endif() set(MYSQL_VERSION_STRING "0.0.0") if( MYSQL_INCLUDE_DIR AND EXISTS "${MYSQL_INCLUDE_DIR}/mysql_version.h" ) set(regex_version "^#define[ \t]+MYSQL_SERVER_VERSION[ \t]+\"([^\"]+)\".*") file(STRINGS "${MYSQL_INCLUDE_DIR}/mysql_version.h" mysql_version REGEX "${regex_version}") string(REGEX REPLACE "${regex_version}" "\\1" MYSQL_VERSION_STRING "${mysql_version}") unset(regex_version) unset(mysql_version) endif() # handle the QUIETLY and REQUIRED arguments and set MYSQL_FOUND to TRUE if # all listed variables are TRUE include( FindPackageHandleStandardArgs ) find_package_handle_standard_args( MYSQL REQUIRED_VARS MYSQL_LIBRARY MYSQL_INCLUDE_DIR VERSION_VAR MYSQL_VERSION_STRING ) set( MYSQL_INCLUDE_DIRS ${MYSQL_INCLUDE_DIR} ) set( MYSQL_LIBRARIES ${MYSQL_LIBRARY} ) if (MYSQL_FOUND) set(MYSQL_LIBRARIES ${MYSQL_LIBRARY}) set(MYSQL_INCLUDE_DIRS ${MYSQL_INCLUDE_DIR}) if (NOT TARGET MysqlDBClient::MysqlDBClient) add_library(MysqlDBClient::MysqlDBClient UNKNOWN IMPORTED) set_target_properties(MysqlDBClient::MysqlDBClient PROPERTIES IMPORTED_LOCATION "${MYSQL_LIBRARY}" INTERFACE_INCLUDE_DIRECTORIES "${MYSQL_INCLUDE_DIR}") endif () endif () mark_as_advanced( MYSQL_INCLUDE_DIR MYSQL_LIBRARY ) hoel-1.4.29/cmake-modules/FindSubunit.cmake000066400000000000000000000043051452453561700205360ustar00rootroot00000000000000#.rst: # FindSubunit # ----------- # # Find Subunit # # Find Subunit headers and libraries. # # :: # # SUBUNIT_FOUND - True if Subunit found. # SUBUNIT_INCLUDE_DIRS - Where to find subunit/child.h. # SUBUNIT_LIBRARIES - List of libraries when using Subunit. # SUBUNIT_VERSION_STRING - The version of Subunit found. #============================================================================= # Copyright 2018 Silvio Clecio # # 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; # version 2.1 of the License. # # This library is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU GENERAL PUBLIC LICENSE for more details. # # You should have received a copy of the GNU General Public # License along with this library. If not, see . #============================================================================= # Fri Jan 19 22:27:51 -03 2018 find_package(PkgConfig QUIET) pkg_check_modules(PC_SUBUNIT QUIET libsubunit) set(SUBUNIT_VERSION_STRING "${PC_SUBUNIT_VERSION}") find_path(SUBUNIT_INCLUDE_DIR NAMES child.h HINTS ${PC_SUBUNIT_INCLUDEDIR} ${PC_SUBUNIT_INCLUDE_DIRS} PATH_SUFFIXES subunit) find_library(SUBUNIT_LIBRARY NAMES subunit libsubunit HINTS ${PC_SUBUNIT_LIBDIR} ${PC_SUBUNIT_LIBRARY_DIRS}) include(FindPackageHandleStandardArgs) find_package_handle_standard_args(Subunit REQUIRED_VARS SUBUNIT_LIBRARY SUBUNIT_INCLUDE_DIR VERSION_VAR SUBUNIT_VERSION_STRING) if (SUBUNIT_FOUND) set(SUBUNIT_LIBRARIES ${SUBUNIT_LIBRARY}) set(SUBUNIT_INCLUDE_DIRS ${SUBUNIT_INCLUDE_DIR}) if (NOT TARGET Subunit::Subunit) add_library(Subunit::Subunit UNKNOWN IMPORTED) set_target_properties(Subunit::Subunit PROPERTIES IMPORTED_LOCATION "${SUBUNIT_LIBRARY}" INTERFACE_INCLUDE_DIRECTORIES "${SUBUNIT_INCLUDE_DIR}") endif () endif () mark_as_advanced(SUBUNIT_INCLUDE_DIR SUBUNIT_LIBRARY) hoel-1.4.29/cmake-modules/HoelConfig.cmake.in000066400000000000000000000025261452453561700207310ustar00rootroot00000000000000@PACKAGE_INIT@ include("${CMAKE_CURRENT_LIST_DIR}/HoelTargets.cmake") set(WITH_SQLITE3 @WITH_SQLITE3@) set(WITH_MARIADB @WITH_MARIADB@) set(WITH_PGSQL @WITH_PGSQL@) set(CMAKE_CURRENT_LIST_DIR ${_original_cmake_module_path}) if(TARGET Yder::Yder-static) set(ORCANIA_INCLUDE_DIRS $) set(ORCANIA_LIBRARIES Yder::Yder-static) endif() if(TARGET Yder::Yder) set(ORCANIA_INCLUDE_DIRS $) set(ORCANIA_LIBRARIES Yder::Yder) endif() include(CMakeFindDependencyMacro) set(_original_cmake_module_path ${CMAKE_MODULE_PATH}) list(APPEND CMAKE_MODULE_PATH "${CMAKE_CURRENT_LIST_DIR}") find_dependency(Orcania) find_dependency(Jansson) if (WITH_SQLITE3) find_dependency(SQLite3) if(SQLite3_FOUND AND NOT TARGET SQLite::SQLite3) add_library(SQLite::SQLite3 UNKNOWN IMPORTED) set_target_properties(SQLite::SQLite3 PROPERTIES INTERFACE_LINK_LIBRARIES "${SQLite3_LIBRARIES}" INTERFACE_INCLUDE_DIRECTORIES "${SQLite3_INCLUDE_DIRS}") endif() endif() if (WITH_MARIADB) find_dependency(MYSQL) endif() if (WITH_PGSQL) find_dependency(LibPQ) endif() set(CMAKE_MODULE_PATH ${_original_cmake_module_path}) set(HOEL_VERSION_STRING "@PROJECT_VERSION@") set(Hoel_FOUND TRUE) hoel-1.4.29/doc/000077500000000000000000000000001452453561700133175ustar00rootroot00000000000000hoel-1.4.29/doc/doxygen.cfg000066400000000000000000000051021452453561700154530ustar00rootroot00000000000000# Doxyfile 1.9.1 PROJECT_NAME = "Hoel" PROJECT_BRIEF = "C Database abstraction library with json based language" INPUT = README.md \ ./src/ \ ./include/ USE_MDFILE_AS_MAINPAGE = README.md #--------------------------------------------------------------------------- # Project related configuration options #--------------------------------------------------------------------------- DOXYFILE_ENCODING = UTF-8 OUTPUT_DIRECTORY = doc CREATE_SUBDIRS = NO ALLOW_UNICODE_NAMES = NO OUTPUT_LANGUAGE = English BRIEF_MEMBER_DESC = YES REPEAT_BRIEF = YES ABBREVIATE_BRIEF = "The $name class" \ "The $name widget" \ "The $name file" \ is \ provides \ specifies \ contains \ represents \ a \ an \ the TAB_SIZE = 4 OPTIMIZE_OUTPUT_FOR_C = YES OPTIMIZE_OUTPUT_JAVA = NO OPTIMIZE_FOR_FORTRAN = NO OPTIMIZE_OUTPUT_VHDL = NO OPTIMIZE_OUTPUT_SLICE = NO #--------------------------------------------------------------------------- # Build related configuration options #--------------------------------------------------------------------------- EXTRACT_ALL = YES EXTRACT_PRIVATE = NO #--------------------------------------------------------------------------- # Configuration options related to the input files #--------------------------------------------------------------------------- INPUT_ENCODING = UTF-8 FILE_PATTERNS = *.c \ *.h \ *.md RECURSIVE = YES #--------------------------------------------------------------------------- # Configuration options related to the HTML output #--------------------------------------------------------------------------- GENERATE_HTML = YES HTML_OUTPUT = html HTML_FILE_EXTENSION = .html HTML_COLORSTYLE_HUE = 220 HTML_COLORSTYLE_SAT = 100 HTML_COLORSTYLE_GAMMA = 80 HTML_DYNAMIC_MENUS = YES HTML_DYNAMIC_SECTIONS = NO GENERATE_LATEX = NO GENERATE_RTF = NO GENERATE_MAN = NO GENERATE_XML = NO GENERATE_DOCBOOK = NO GENERATE_AUTOGEN_DEF = NO GENERATE_PERLMOD = NO ENABLE_PREPROCESSING = YES MACRO_EXPANSION = NO EXPAND_ONLY_PREDEF = NO SEARCH_INCLUDES = YES HAVE_DOT = NO hoel-1.4.29/examples/000077500000000000000000000000001452453561700143705ustar00rootroot00000000000000hoel-1.4.29/examples/Makefile000066400000000000000000000045041452453561700160330ustar00rootroot00000000000000# # Example program # # Makefile used to build the software # # Copyright 2014-2015 Nicolas Mora # # This program is free software; you can redistribute it and/or # modify it under the terms of the MIT License # # This library is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU GENERAL PUBLIC LICENSE for more details. # CC=gcc HOEL_INCLUDE=../include CFLAGS=-c -Wall -I$(HOEL_INCLUDE) -D_REENTRANT -I$(PREFIX)/include $(ADDITIONALFLAGS) HOEL_LOCATION=../src LIBS=-lc -lhoel -ljansson -lyder -lorcania -L$(HOEL_LOCATION) ADDITIONALFLAGS=-O3 all: libhoel.so example_sqlite3 example_mariadb example_pgsql example_mariadb_json example_mariadb_binary clean: rm -f *.o example_sqlite3 example_mariadb example_pgsql example_mariadb_json example_mariadb_binary debug: ADDITIONALFLAGS=-DDEBUG -g -O0 debug: libhoel.so example_sqlite3 example_mariadb example_pgsql example_mariadb_json libhoel.so: cd $(HOEL_LOCATION) && $(MAKE) debug example_sqlite3: example_sqlite3.c $(CC) -c $(CFLAGS) example_sqlite3.c $(CC) -o example_sqlite3 example_sqlite3.o $(LIBS) example_mariadb: example_mariadb.c $(CC) -c $(CFLAGS) example_mariadb.c $(CC) -o example_mariadb example_mariadb.o $(LIBS) example_pgsql: example_pgsql.c $(CC) -c $(CFLAGS) example_pgsql.c $(CC) -o example_pgsql example_pgsql.o $(LIBS) example_mariadb_json: example_mariadb_json.c $(CC) -c $(CFLAGS) example_mariadb_json.c $(CC) -o example_mariadb_json example_mariadb_json.o $(LIBS) example_mariadb_binary: example_mariadb_binary.c $(CC) -c $(CFLAGS) example_mariadb_binary.c $(CC) -o example_mariadb_binary example_mariadb_binary.o $(LIBS) test: test_pgsql test_mariadb test_sqlite3 test_mariadb_json test_pgsql: example_pgsql LD_LIBRARY_PATH=$(HOEL_LOCATION):${LD_LIBRARY_PATH} ./example_pgsql test_mariadb: example_mariadb LD_LIBRARY_PATH=$(HOEL_LOCATION):${LD_LIBRARY_PATH} ./example_mariadb test_sqlite3: example_sqlite3 LD_LIBRARY_PATH=$(HOEL_LOCATION):${LD_LIBRARY_PATH} ./example_sqlite3 test_mariadb_json: example_mariadb_json LD_LIBRARY_PATH=$(HOEL_LOCATION):${LD_LIBRARY_PATH} ./example_mariadb_json test_mariadb_binary: example_mariadb_binary LD_LIBRARY_PATH=$(HOEL_LOCATION):${LD_LIBRARY_PATH} ./example_mariadb_binary hoel-1.4.29/examples/example_mariadb.c000066400000000000000000000123251452453561700176510ustar00rootroot00000000000000/** * * Example program using MariaDB to execute SQL statements * * Copyright 2016-2018 Nicolas Mora * * License: MIT * */ #include #include #include #define _HOEL_MARIADB #include void print_result(struct _h_result result) { int col, row; char buf[64]; int i; printf("rows: %u, col: %u\n", result.nb_rows, result.nb_columns); for (row = 0; rowvalue); break; case HOEL_COL_TYPE_DOUBLE: printf("| %f ", ((struct _h_type_double *)result.data[row][col].t_data)->value); break; case HOEL_COL_TYPE_TEXT: printf("| %s ", ((struct _h_type_text *)result.data[row][col].t_data)->value); break; case HOEL_COL_TYPE_BLOB: for (i=0; i<((struct _h_type_blob *)result.data[row][col].t_data)->length; i++) { printf("%c", *((char*)(((struct _h_type_blob *)result.data[row][col].t_data)->value+i))); if (i%80 == 0 && i>0) { printf("\n"); } } break; case HOEL_COL_TYPE_DATE: strftime(buf, 64, "%Y-%m-%d %H:%M:%S", &((struct _h_type_datetime *)result.data[row][col].t_data)->value); printf("| %s ", buf); case HOEL_COL_TYPE_NULL: printf("| [null] "); break; } } printf("|\n"); } } void unit_tests(struct _h_connection * conn) { json_t * j_result; struct _h_result result; struct _h_data * data; char * query = NULL, * sanitized = NULL, * dump, * table = "other_test"; int last_id = -1; // Execute a sql query and retrieve results in a json structure query = msprintf("select * from %s", table); if (h_query_select_json(conn, query, &j_result) == H_OK) { dump = json_dumps(j_result, JSON_INDENT(2)); printf("json result is\n%s\n", dump); json_decref(j_result); free(dump); } else { printf("Error executing query\n"); } free(query); // insert escaped string sanitized = h_escape_string(conn, "Hodor son of H'rtp'ss"); query = msprintf("insert into %s (name, age, temperature, birthdate) values ('%s', %d, %f, '%s')", table, sanitized, 33, 37.2, "1412-03-08 12:00:22"); printf("insert result: %d\n", h_query_insert(conn, query)); free(sanitized); free(query); query = msprintf("select * from %s", table); if (h_query_select(conn, query, &result) == H_OK) { print_result(result); h_clean_result(&result); } else { printf("Error executing query\n"); } free(query); sanitized = h_escape_string(conn, "Ygritte you know nothing"); query = msprintf("insert into %s (name, age, temperature, birthdate) values ('%s', %d, %f, '%s')", table, sanitized, 25, 30.1, "1424-06-01 03:05:11"); printf("insert result: %d\n", h_query_insert(conn, query)); free(sanitized); free(query); query = msprintf("select * from %s", table); if (h_query_select(conn, query, &result) == H_OK) { print_result(result); h_clean_result(&result); } else { printf("Error executing query\n"); } free(query); sanitized = h_escape_string(conn, "Littlefinger I will betray you"); query = msprintf("insert into %s (name, age, temperature, birthdate) values ('%s', %d, %f, '%s')", table, sanitized, 44, 40.5, "1410-10-25 14:30:00"); printf("insert result: %d\n", h_query_insert(conn, query)); free(sanitized); free(query); data = h_query_last_insert_id(conn); if (data->type == HOEL_COL_TYPE_INT) { last_id = ((struct _h_type_int *)data->t_data)->value; } h_clean_data_full(data); printf("last id is %d\n", last_id); query = msprintf("select * from %s", table); if (h_query_select(conn, query, &result) == H_OK) { print_result(result); h_clean_result(&result); } else { printf("Error executing query\n"); } free(query); sanitized = h_escape_string(conn, "Littlefinger I am nothing"); query = msprintf("update %s set name='%s' where id=%d", table, sanitized, last_id); printf("update result: %d\n", h_query_update(conn, query)); free(sanitized); free(query); query = msprintf("select * from %s", table); if (h_query_select(conn, query, &result) == H_OK) { print_result(result); h_clean_result(&result); } else { printf("Error executing query\n"); } free(query); query = msprintf("delete from %s where id=%d", table, last_id); printf("delete result: %d\n", h_query_delete(conn, query)); free(query); query = msprintf("select * from %s", table); if (h_query_select_json(conn, query, &j_result) == H_OK) { dump = json_dumps(j_result, JSON_INDENT(2)); printf("json result is\n%s\n", dump); json_decref(j_result); free(dump); } else { printf("Error executing query\n"); } free(query); } int main(int argc, char ** argv) { struct _h_connection * conn; conn = h_connect_mariadb("localhost", "test_hoel", "test_hoel", "test_hoel", 0, NULL); if (conn != NULL) { unit_tests(conn); } else { printf("Error connecting to database\n"); } h_close_db(conn); return h_clean_connection(conn); } hoel-1.4.29/examples/example_mariadb.sql000066400000000000000000000003141452453561700202210ustar00rootroot00000000000000-- License: MIT DROP TABLE IF EXISTS other_test; CREATE TABLE other_test ( id INTEGER PRIMARY KEY AUTO_INCREMENT, name VARCHAR(128), age INTEGER, birthdate DATE, temperature FLOAT ); hoel-1.4.29/examples/example_mariadb_binary.c000066400000000000000000000040601452453561700212120ustar00rootroot00000000000000/** * * Example program using MariaDB to execute SQL statements * * Copyright 2016-2018 Nicolas Mora * * License: MIT * */ #include #include // The table structure is: 'create table test( integer_col int(10), string_col varchar(128), blob_col blob, binary_col binary(16));' int main() { struct _h_connection * conn = h_connect_mariadb("localhost", "test", "test", "test_binary", 0, NULL); y_init_logs("test binary", Y_LOG_MODE_CONSOLE, Y_LOG_LEVEL_DEBUG, NULL, "Starting test binary"); if (conn != NULL) { struct _h_result result; char * query = "insert into test (integer_col, string_col, blob_col, binary_col) values (42, 'nope', 'contribution', 'a')"; y_log_message(Y_LOG_LEVEL_DEBUG, "Insert result: %d", h_query_insert(conn, query)); query = "select * from test"; if (h_query_select(conn, query, &result) == H_OK) { int row, col; for (row=0; rowvalue); } else if (result.data[row][col].type == HOEL_COL_TYPE_TEXT) { y_log_message(Y_LOG_LEVEL_DEBUG, "text value: %.*s", ((struct _h_type_text *)result.data[row][col].t_data)->length, ((struct _h_type_text *)result.data[row][col].t_data)->value); } else if (result.data[row][col].type == HOEL_COL_TYPE_BLOB) { y_log_message(Y_LOG_LEVEL_DEBUG, "blob value: %.*s", ((struct _h_type_blob *)result.data[row][col].t_data)->length, ((struct _h_type_blob *)result.data[row][col].t_data)->value); } } } } else { y_log_message(Y_LOG_LEVEL_DEBUG, "Error executing select"); } query = "delete from test"; y_log_message(Y_LOG_LEVEL_DEBUG, "Delete result: %d", h_query_delete(conn, query)); } else { y_log_message(Y_LOG_LEVEL_DEBUG, "Error connecting to database"); } y_close_logs(); h_close_db(conn); } hoel-1.4.29/examples/example_mariadb_json.c000066400000000000000000000163621452453561700207070ustar00rootroot00000000000000/** * * Example program using json-based queries to execute SQL statements * * Copyright 2016-2018 Nicolas Mora * * License: MIT * */ #include #include #include #define _HOEL_MARIADB #include void hoel_json_tests(struct _h_connection * conn) { json_t * j_result, * j_query; char * table = "other_test", * dump; int res; /* * * First select query * * The JSON query object is: * { * table: "other_test", * columns: [ * "name", * "age", * "temperature" * ], * where: { * age: { * operator: ">", * value: 46 * }, * name: { * operator: "LIKE", * value: "Hodor%" * } * } * } * * The generated SQL query will be: * SELECT name,age,temperature FROM other_test WHERE age>46 AND name LIKE 'Hodor%'; * */ j_query = json_pack("{sss[sss]s{s{sssi}s{ssss}}}", "table", table, "columns", "name", "age", "temperature", "where", "age", "operator", ">", "value", 46, "name", "operator", "LIKE", "value", "Hodor%"); // Execute the query res = h_select(conn, j_query, &j_result, NULL); // Deallocate j_query since it won't be needed anymore json_decref(j_query); // Test query execution result if (res == H_OK) { // Print result dump = json_dumps(j_result, JSON_INDENT(2)); y_log_message(Y_LOG_LEVEL_DEBUG, "json select result is\n%s", dump); // Deallocate data result json_decref(j_result); free(dump); } else { y_log_message(Y_LOG_LEVEL_DEBUG, "Error executing select query: %d", res); } /* * * Insert query * * The JSON query object is: * { * table: "other_test", * values: { * name: "Ned Stark Winter is coming", * age: 45, * temperature: 30.1, * birthdate: "1408-06-01 03:05:11" * } * } * * The generated SQL query will be: * INSERT INTO other_test (name,age,temperature,birthdate) VALUES ('Ned Stark Winter is coming',45,30.1,'1408-06-01 03:05:11'); * */ j_query = json_pack("{sss{sssisfss}}", "table", table, "values", "name", "Ned Stark Winter is coming", "age", 45, "temperature", 30.1, "birthdate", "1408-06-01 03:05:11"); y_log_message(Y_LOG_LEVEL_DEBUG, "insert result: %d", h_insert(conn, j_query, NULL)); // Expected result: H_OK (0) json_decref(j_query); /* * * Second select query * * The JSON query object is: * { * table: "other_test", * columns: [ * "name", * "age", * "birthdate" * ], * where: { * name: "Ned Stark Winter is coming" * } * } * * The generated SQL query will be: * SELECT name,age,temperature FROM other_test WHERE name='Ned Stark Winter is coming'; * * This select query is supposed to return at least one result * */ j_query = json_pack("{sss[sss]s{ss}}", "table", table, "columns", "name", "age", "birthdate", "where", "name", "Ned Stark Winter is coming"); if (h_select(conn, j_query, &j_result, NULL) == H_OK) { dump = json_dumps(j_result, JSON_INDENT(2)); y_log_message(Y_LOG_LEVEL_DEBUG, "json select result is\n%s", dump); json_decref(j_result); free(dump); } else { y_log_message(Y_LOG_LEVEL_DEBUG, "Error executing select query"); } json_decref(j_query); /* * * Update query * * The JSON query object is: * { * table: "other_test", * set: { * age: 47 * }, * where: { * age: 45 * } * } * * The generated SQL query will be: * UPDATE other_test SET age=47 WHERE age=45; * */ j_query = json_pack("{sss{si}s{si}}", "table", table, "set", "age", 47, "where", "age", 45); if (h_update(conn, j_query, NULL) == H_OK) { y_log_message(Y_LOG_LEVEL_DEBUG, "Update query OK"); json_decref(j_query); j_query = json_pack("{ss}", "table", table); if (h_select(conn, j_query, &j_result, NULL) == H_OK) { dump = json_dumps(j_result, JSON_INDENT(2)); y_log_message(Y_LOG_LEVEL_DEBUG, "json select result is\n%s", dump); json_decref(j_result); free(dump); } else { y_log_message(Y_LOG_LEVEL_DEBUG, "Error executing select query"); } json_decref(j_query); } else { json_decref(j_query); y_log_message(Y_LOG_LEVEL_DEBUG, "Error executing update query"); } /* * * Delete query * * The JSON query object is: * { * table: "other_test", * where: { * age: { * operator: ">", * value: 46 * } * } * } * * The generated SQL query will be: * DELETE FROM other_test WHERE age>46; * */ j_query = json_pack("{sss{s{sssi}}}", "table", table, "where", "age", "operator", ">", "value", 46); if (h_delete(conn, j_query, NULL) == H_OK) { y_log_message(Y_LOG_LEVEL_DEBUG, "Delete query OK"); json_decref(j_query); j_query = json_pack("{ss}", "table", table); if (h_select(conn, j_query, &j_result, NULL) == H_OK) { dump = json_dumps(j_result, JSON_INDENT(2)); y_log_message(Y_LOG_LEVEL_DEBUG, "json select result is\n%s", dump); json_decref(j_result); free(dump); } else { y_log_message(Y_LOG_LEVEL_DEBUG, "Error executing select query"); } } else { json_decref(j_query); y_log_message(Y_LOG_LEVEL_DEBUG, "Error executing delete query"); } } int main() { struct _h_connection * conn; // Initialize logs manager to console output y_init_logs("test_hoel_mariadb_json", Y_LOG_MODE_CONSOLE, Y_LOG_LEVEL_DEBUG, NULL, "Starting test_hoel_mariadb_json"); // Create hoel connection conn = h_connect_mariadb("lamorak", "test_hoel", "test_hoel", "test_hoel", 0, NULL); if (conn != NULL) { // Execute hoel_json_tests function that will run the tests themselves hoel_json_tests(conn); } else { y_log_message(Y_LOG_LEVEL_DEBUG, "Error connecting to database"); } // Close database connection h_close_db(conn); // Close logs manager y_close_logs(); // Clear hoel connection return h_clean_connection(conn); } hoel-1.4.29/examples/example_pgsql.c000066400000000000000000000061201452453561700173740ustar00rootroot00000000000000/** * * Example program using PostgreSQL to execute SQL statements * * Copyright 2016-2018 Nicolas Mora * * License: MIT * */ #include #include #include #define _HOEL_PGSQL #include void print_result(struct _h_result result) { int col, row, i; char buf[64]; y_log_message(Y_LOG_LEVEL_DEBUG, "rows: %d, col: %d", result.nb_rows, result.nb_columns); for (row = 0; rowvalue); break; case HOEL_COL_TYPE_DOUBLE: printf("| %f ", ((struct _h_type_double *)result.data[row][col].t_data)->value); break; case HOEL_COL_TYPE_TEXT: printf("| %s ", ((struct _h_type_text *)result.data[row][col].t_data)->value); break; case HOEL_COL_TYPE_BLOB: for (i=0; i<((struct _h_type_blob *)result.data[row][col].t_data)->length; i++) { printf("%c", *((char*)(((struct _h_type_blob *)result.data[row][col].t_data)->value+i))); if (i%80 == 0 && i>0) { printf("\n"); } } break; case HOEL_COL_TYPE_DATE: strftime(buf, 64, "%Y-%m-%d %H:%M:%S", &((struct _h_type_datetime *)result.data[row][col].t_data)->value); printf("| %s ", buf); case HOEL_COL_TYPE_NULL: printf("| [null] "); break; } } printf("|\n"); } } int main(int argc, char ** argv) { struct _h_result result; struct _h_connection * conn; char * query = "select * from test", * insert_query = "insert into test (name, age, birthdate) values ('bob', 21, '1997-05-09')", * connectionstring = "host=localhost dbname=test user=test password=test", * dump = NULL; int res; json_t * j_result; y_init_logs("example_pgsql", Y_LOG_MODE_CONSOLE, Y_LOG_LEVEL_DEBUG, NULL, "Starting example_pgsql"); conn = h_connect_pgsql(connectionstring); res = h_query_insert(conn, insert_query); if (res == H_OK) { y_log_message(Y_LOG_LEVEL_DEBUG, "insert query executed"); j_result = h_last_insert_id(conn); dump = json_dumps(j_result, JSON_ENCODE_ANY); y_log_message(Y_LOG_LEVEL_DEBUG, "last id is %s", dump); free(dump); json_decref(j_result); } else { y_log_message(Y_LOG_LEVEL_ERROR, "Error executing query: %d", res); } res = h_query_select(conn, query, &result); if (res == H_OK) { print_result(result); h_clean_result(&result); } else { y_log_message(Y_LOG_LEVEL_ERROR, "Error executing query: %d", res); } res = h_execute_query_json(conn, query, &j_result); if (res == H_OK) { dump = json_dumps(j_result, JSON_INDENT(2)); y_log_message(Y_LOG_LEVEL_DEBUG, "json result is\n%s", dump); json_decref(j_result); free(dump); } else { y_log_message(Y_LOG_LEVEL_ERROR, "Error executing json query: %d", res); } h_close_db(conn); y_close_logs(); return h_clean_connection(conn); } hoel-1.4.29/examples/example_sqlite3.c000066400000000000000000000116541452453561700176420ustar00rootroot00000000000000/** * * Example program using SQLite3 to execute SQL statements * * Copyright 2016-2018 Nicolas Mora * * License: MIT * */ #include #include #include #include #define _HOEL_SQLITE #include void print_result(struct _h_result result) { int col, row, i; printf("rows: %u, col: %u\n", result.nb_rows, result.nb_columns); for (row = 0; rowvalue); break; case HOEL_COL_TYPE_DOUBLE: printf("| %f ", ((struct _h_type_double *)result.data[row][col].t_data)->value); break; case HOEL_COL_TYPE_TEXT: printf("| %s ", ((struct _h_type_text *)result.data[row][col].t_data)->value); break; case HOEL_COL_TYPE_BLOB: for (i=0; i<((struct _h_type_blob *)result.data[row][col].t_data)->length; i++) { printf("%c", *((char*)(((struct _h_type_blob *)result.data[row][col].t_data)->value+i))); if (i%80 == 0 && i>0) { printf("\n"); } } break; case HOEL_COL_TYPE_NULL: printf("| null "); break; } } printf("|\n"); } } void unit_tests(struct _h_connection * conn) { struct _h_result result; struct _h_data * data; char * query = NULL, * sanitized = NULL, * table = "other_test"; int last_id = -1; query = msprintf("select * from %s", table); if (h_query_select(conn, query, &result) == H_OK) { printf("\n\nIteration 1, initial status\n"); print_result(result); h_clean_result(&result); } else { printf("Error executing query\n"); } free(query); sanitized = h_escape_string(conn, "Hodor"); query = msprintf("insert into %s (name, age, temperature) values ('%s', %d, %f)", table, sanitized, 33, 37.2); printf("insert result: %d\n", h_query_insert(conn, query)); free(sanitized); free(query); query = msprintf("select * from %s", table); if (h_query_select(conn, query, &result) == H_OK) { printf("\n\nIteration 2, after insert\n"); print_result(result); h_clean_result(&result); } else { printf("Error executing query\n"); } free(query); sanitized = h_escape_string(conn, "Ygritte"); query = msprintf(NULL, 0, "insert into %s (name, age, temperature) values ('%s', %d, %f)", table, sanitized, 25, 30.1); printf("insert result: %d\n", h_query_insert(conn, query)); free(sanitized); free(query); query = msprintf("select * from %s", table); if (h_query_select(conn, query, &result) == H_OK) { printf("\n\nIteration 3, after insert\n"); print_result(result); h_clean_result(&result); } else { printf("Error executing query\n"); } free(query); sanitized = h_escape_string(conn, "Littlefinger"); query = msprintf("insert into %s (name, age, temperature) values ('%s', %d, %f)", table, sanitized, 44, 40.5); printf("insert result: %d\n", h_query_insert(conn, query)); free(sanitized); free(query); data = h_query_last_insert_id(conn); if (data->type == HOEL_COL_TYPE_INT) { last_id = ((struct _h_type_int *)data->t_data)->value; } h_clean_data_full(data); printf("last id is %d\n", last_id); query = msprintf("select * from %s", table); if (h_query_select(conn, query, &result) == H_OK) { printf("\n\nIteration 4, after inserts and last id\n"); print_result(result); h_clean_result(&result); } else { printf("Error executing query\n"); } free(query); sanitized = h_escape_string(conn, "Littlefingers"); query = msprintf("update %s set name='%s' where id=%d", table, sanitized, last_id); printf("update result: %d\n", h_query_update(conn, query)); free(sanitized); free(query); query = msprintf("select * from %s", table); if (h_query_select(conn, query, &result) == H_OK) { printf("\n\nIteration 5, after update\n"); print_result(result); h_clean_result(&result); } else { printf("Error executing query\n"); } free(query); query = msprintf("delete from %s where id=%d", table, last_id); printf("delete result: %d\n", h_query_delete(conn, query)); free(query); query = msprintf("select * from %s", table); if (h_query_select(conn, query, &result) == H_OK) { printf("\n\nIteration 6, after delete\n"); print_result(result); h_clean_result(&result); } else { printf("Error executing query\n"); } free(query); } int main(int argc, char ** argv) { struct _h_connection * conn; char * db_file = "/tmp/test.db"; y_init_logs("test_hoel_sqlite3", Y_LOG_MODE_CONSOLE, Y_LOG_LEVEL_DEBUG, NULL, "Starting test_hoel_sqlite3"); conn = h_connect_sqlite(db_file); if (conn != NULL) { unit_tests(conn); } h_close_db(conn); y_close_logs(); return h_clean_connection(conn); } hoel-1.4.29/examples/example_sqlite3.sql000066400000000000000000000002151452453561700202060ustar00rootroot00000000000000-- License: MIT CREATE TABLE other_test ( id INTEGER PRIMARY KEY AUTOINCREMENT, name TEXT, age INTEGER, temperature FLOAT ); hoel-1.4.29/include/000077500000000000000000000000001452453561700141755ustar00rootroot00000000000000hoel-1.4.29/include/h-private.h000066400000000000000000000050201452453561700162420ustar00rootroot00000000000000/** * * Hoel database abstraction library * * h-private.h: private structures and functions declarations * * Copyright 2018-2020 Nicolas Mora * * 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; * version 2.1 of the License. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU GENERAL PUBLIC LICENSE for more details. * * You should have received a copy of the GNU General Public * License along with this library. If not, see . * */ #ifndef __H_PRIVATE_H_ #define __H_PRIVATE_H_ /** Macro to avoid compiler warning when some parameters are unused and that's ok **/ #define UNUSED(x) (void)(x) /** * Add a new struct _h_data * to an array of struct _h_data *, which already has cols columns * return H_OK on success */ int h_row_add_data(struct _h_data ** result, struct _h_data * data, int cols); /** * Add a new row of struct _h_data * in a struct _h_result * * return H_OK on success */ int h_result_add_row(struct _h_result * result, struct _h_data * row, int rows); /** * Allocate memory for a new struct _h_data * containing an int * return pointer to the new structure * return NULL on error */ struct _h_data * h_new_data_int(const long long int value); /** * Allocate memory for a new struct _h_data * containing a double * return pointer to the new structure * return NULL on error */ struct _h_data * h_new_data_double(const double value); /** * Allocate memory for a new struct _h_data * containing a text * return pointer to the new structure * return NULL on error */ struct _h_data * h_new_data_text(const char * value, const size_t length); /** * Allocate memory for a new struct _h_data * containing a blob * return pointer to the new structure * return NULL on error */ struct _h_data * h_new_data_blob(const void * value, const size_t length); /** * Allocate memory for a new struct _h_data * containing a date time structure * return pointer to the new structure * return NULL on error */ struct _h_data * h_new_data_datetime(const struct tm * datetime); /** * Allocate memory for a new struct _h_data * containing a null value * return pointer to the new structure * return NULL on error */ struct _h_data * h_new_data_null(); #endif /* __H_PRIVATE_H_ */ hoel-1.4.29/include/hoel-cfg.h.in000066400000000000000000000024071452453561700164420ustar00rootroot00000000000000/** * * Hoel database abstraction library * * hoel.h: structures and functions declarations * * Copyright 2015-2020 Nicolas Mora * * 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; * version 2.1 of the License. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU GENERAL PUBLIC LICENSE for more details. * * You should have received a copy of the GNU General Public * License along with this library. If not, see . * */ #ifndef _HOEL_CFG_H_ #define _HOEL_CFG_H_ #define HOEL_VERSION ${PROJECT_VERSION} #define HOEL_VERSION_STR "${PROJECT_VERSION}" #define HOEL_VERSION_MAJOR ${PROJECT_VERSION_MAJOR} #define HOEL_VERSION_MINOR ${PROJECT_VERSION_MINOR} #define HOEL_VERSION_PATCH ${PROJECT_VERSION_PATCH} #define HOEL_VERSION_NUMBER ((HOEL_VERSION_MAJOR << 16) | (HOEL_VERSION_MINOR << 8) | (HOEL_VERSION_PATCH << 0)) #cmakedefine _HOEL_SQLITE #cmakedefine _HOEL_MARIADB #cmakedefine _HOEL_PGSQL #endif /* _HOEL_CFG_H_ */ hoel-1.4.29/include/hoel.h000066400000000000000000000624631452453561700153100ustar00rootroot00000000000000/** * * @file hoel.h * @brief Hoel database abstraction library * * hoel.h: structures and functions declarations * * Copyright 2015-2020 Nicolas Mora * * 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; * version 2.1 of the License. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU GENERAL PUBLIC LICENSE for more details. * * You should have received a copy of the GNU General Public * License along with this library. If not, see . * */ #ifndef __HOEL_H__ #define __HOEL_H__ #ifdef __cplusplus extern "C" { #endif #include "hoel-cfg.h" #include #ifndef __USE_XOPEN #define __USE_XOPEN #endif #include #include /** Angharad libraries **/ #include #include /** * @defgroup const Constants * @{ */ #define HOEL_DB_TYPE_SQLITE 0 #define HOEL_DB_TYPE_MARIADB 1 #define HOEL_DB_TYPE_PGSQL 2 #define HOEL_COL_TYPE_INT 0 #define HOEL_COL_TYPE_DOUBLE 1 #define HOEL_COL_TYPE_TEXT 2 #define HOEL_COL_TYPE_DATE 3 #define HOEL_COL_TYPE_BLOB 4 #define HOEL_COL_TYPE_BOOL 5 #define HOEL_COL_TYPE_NULL 5 #define H_OK 0 /* No error */ #define H_ERROR 1 /* Generic error */ #define H_ERROR_PARAMS 2 /* Error in input parameters */ #define H_ERROR_CONNECTION 3 /* Error in database connection */ #define H_ERROR_QUERY 4 /* Error executing query */ #define H_ERROR_MEMORY 99 /* Error allocating memory */ #define H_OPTION_NONE 0x0000 /* Nothing whatsoever */ #define H_OPTION_SELECT 0x0001 /* Execute a SELECT statement */ #define H_OPTION_EXEC 0x0010 /* Execute an INSERT, UPDATE or DELETE statement */ /** * @} */ /** * @defgroup struct struct _h_data * @{ */ /** * handle container */ struct _h_connection { int type; void * connection; }; /** * sql value integer type */ struct _h_type_int { long long int value; }; /** * sql value double type */ struct _h_type_double { double value; }; /** * sql value date/time type */ struct _h_type_datetime { struct tm value; }; /** * sql value string type */ struct _h_type_text { size_t length; char * value; }; /** * sql value blob type */ struct _h_type_blob { size_t length; void * value; }; /** * sql data container */ struct _h_data { int type; void * t_data; }; /** * sql result structure */ struct _h_result { unsigned int nb_rows; unsigned int nb_columns; struct _h_data ** data; }; /** * @} */ /** * @defgroup init Initialize and cosing connection functions * @{ */ /** * Close a database connection * @param conn the connection to the database * @return H_OK on success */ int h_close_db(struct _h_connection * conn); /** * @} */ /** * @defgroup memory Memory management functions * @{ */ /** * free data allocated by hoel functions * @param data the data to free */ void h_free(void * data); /** * @} */ /** * @defgroup escape Escape string functions * @{ */ /** * h_escape_string * Escapes a string * @param conn the connection to the database * @param unsafe the string to escape * @return a heap-allocated string * returned value must be h_free'd after use */ char * h_escape_string(const struct _h_connection * conn, const char * unsafe); /** * h_escape_string_with_quotes * Escapes a string and returns it ready to be inserted in the query * @param conn the connection to the database * @param unsafe the string to escape * @return a heap-allocated string * returned value must be h_free'd after use */ char * h_escape_string_with_quotes(const struct _h_connection * conn, const char * unsafe); /** * @} */ /** * @defgroup h_result _h_result SQL query management functions * SQL query management for struct _h_result format * @{ */ /** * h_execute_query * Execute a query, set the result structure with the returned values if available * if result is NULL, the query is executed but no value will be returned * @param conn the connection to the database * @param query the SQL query to execute * @param result the result structure to fill the result data * @param options option to pass to the database engine * options available * H_OPTION_NONE (0): no option * H_OPTION_SELECT: Execute a prepare statement (sqlite only) * H_OPTION_EXEC: Execute an exec statement (sqlite only) * @return H_OK on success */ int h_execute_query(const struct _h_connection * conn, const char * query, struct _h_result * result, int options); /** * h_query_insert * Execute an insert query * @param conn the connection to the database * @param query the SQL query to execute * @return H_OK on success */ int h_query_insert(const struct _h_connection * conn, const char * query); /** * h_query_last_insert_id * return the id of the last inserted value * @param conn the connection to the database * @return a pointer to `struct _h_data *` on success, NULL otherwise. */ struct _h_data * h_query_last_insert_id(const struct _h_connection * conn); /** * h_query_update * Execute an update query * @param conn the connection to the database * @param query the SQL query to execute * @return H_OK on success */ int h_query_update(const struct _h_connection * conn, const char * query); /** * h_query_delete * Execute an delete query * @param conn the connection to the database * @param query the SQL query to execute * @return H_OK on success */ int h_query_delete(const struct _h_connection * conn, const char * query); /** * h_query_select * Execute a select query, set the result structure with the returned values * @param conn the connection to the database * @param query the SQL query to execute * @param result the result structure to fill the result data * @return H_OK on success */ int h_query_select(const struct _h_connection * conn, const char * query, struct _h_result * result); /** * @} */ /** * @defgroup json JSON SQL query management functions * SQL query management for JSON format * @{ */ /** * h_execute_query_json * Execute a query, set the returned values in the json result * @param conn the connection to the database * @param query the SQL query to execute * @param j_result a json_t * reference that will be allocated and filled with the result * if the query succeeds and is a SELECT query * @return H_OK on success */ int h_execute_query_json(const struct _h_connection * conn, const char * query, json_t ** j_result); /** * h_query_select_json * Execute a select query, set the returned values in the json results * @param conn the connection to the database * @param query the SQL query to execute * @param j_result a json_t * reference that will be allocated and filled with the result if the query succeeds * @return H_OK on success */ int h_query_select_json(const struct _h_connection * conn, const char * query, json_t ** j_result); /** * json queries * The following functions run a sql query based on a json_t * object for input parameters * The input parameter is called j_query * If the j_query is well-formed, the query is executed and if available and specified, the result is stored into the j_result object. j_result must be decref'd after use * Also, the sql query generated is stored into generated_query if specified, generated_query must be h_free'd after use * The query execution result is returned by the function * * A j_query has the following form * { * "table": "table_name" // Non empty string, mandatory, the table name where the query is executed * "columns": ["col1", "col2"] // Array of strings, available for h_select, optional. If not specified, * will be used, the columns values are not escaped by the library * "order_by": "col_name [asc|desc]" // Non empty string, available for h_select, specify the order by clause, optional, the value is not escaped by the library * "group_by": "col_name" // Non empty string, available for h_select, specify the group by clause, optional, the value is not escaped by the library * "limit": integer_value // Integer, available for h_select, specify the limit value, optional * "offset" // Integer, available for h_select, specify the limit value, optional but available only if limit is set * "values": [{ // json object or json array of json objects, available for h_insert, mandatory, specify the values to update * "col1": "value1", // Generates col1='value1' for an update query * "col2": value_integer, // Generates col2=value_integer for an update query * "col3", "value3", // Generates col3='value3' for an update query * "col4", null // Generates col4=NULL for an update query * }] * "set": { // json object, available for h_update, mandatory, specify the values to update * "col1": "value1", // Generates col1='value1' for an update query * "col2": value_integer, // Generates col2=value_integer for an update query * "col3", "value3", // Generates col3='value3' for an update query * "col4", null // Generates col4=NULL for an update query * } * "where": { // json object, available for h_select, h_update and h_delete, mandatory, specify the where clause. All clauses are separated with an AND operator * "col1": "value1", // Generates col1='value1' * "col2": value_integer, // Generates col2=value_integer * "col3": null, // Generates col3=NULL * "col4", { // Generates col4<12 * "operator": "<", * "value": 12 * }, * "col5", { // Generates col5 IS NOT NULL * "operator": "NOT NULL" * }, * "col6", { // Generates col6 LIKE '%value6%' * "operator": "raw", * "value": "LIKE '%value6%'" * } * } * } */ /** * h_select * Execute a select query * Uses a json_t * parameter for the query parameters * Store the result of the query in j_result if specified. j_result must be decref'd after use * @param conn the connection to the database * @param j_query the query encapsulated ina JSON object to execute * @param j_result a json_t * reference that will be allocated and filled with the result if the query succeeds * @param generated_query a char * reference that will be allocated by the library and will contain the generated SQL query, * optional, must be h_free'd after use * @return H_OK on success */ int h_select(const struct _h_connection * conn, const json_t * j_query, json_t ** j_result, char ** generated_query); /** * h_insert * Execute an insert query * Uses a json_t * parameter for the query parameters * @param conn the connection to the database * @param j_query the query encapsulated ina JSON object to execute * @param generated_query a char * reference that will be allocated by the library and will contain the generated SQL query, * optional, must be h_free'd after use * @return H_OK on success */ int h_insert(const struct _h_connection * conn, const json_t * j_query, char ** generated_query); /** * h_last_insert_id * return the id of the last inserted value * return a pointer to `json_t *` on success, NULL otherwise. * The returned value is of type JSON_INTEGER * @param conn the connection to the database * @return a json_t * containing the last insert id in integer format */ json_t * h_last_insert_id(const struct _h_connection * conn); /** * h_update * Execute an update query * Uses a json_t * parameter for the query parameters * @param conn the connection to the database * @param j_query the query encapsulated ina JSON object to execute * @param generated_query a char * reference that will be allocated by the library and will contain the generated SQL query, * optional, must be h_free'd after use * @return H_OK on success */ int h_update(const struct _h_connection * conn, const json_t * j_query, char ** generated_query); /** * h_delete * Execute a delete query * Uses a json_t * parameter for the query parameters * @param conn the connection to the database * @param j_query the query encapsulated ina JSON object to execute * @param generated_query a char * reference that will be allocated by the library and will contain the generated SQL query, * optional, must be h_free'd after use * @return H_OK on success */ int h_delete(const struct _h_connection * conn, const json_t * j_query, char ** generated_query); /** * h_build_where_clause * Generates a where clause based on the pattern and the values given * @param conn the connection to the database * @param pattern the pattern to build the where clause * the pattern variables available are the following: * - %s: a string value to escape with quotes * - %S: a string value to escape without quotes * - %c: a string value not to escape with quotes * - %C: a string value not to escape without quotes * - %d: an integer value in json_int_t format * - %f: a double value * - %j: a json_t value, the value must be of the type JSON_INTEGER, JSON_REAL or JSON_STRING, string values will be escaped with quotes * - %%: the value '%' * @return a heap-allocated string * returned value must be h_free'd after use */ char * h_build_where_clause(const struct _h_connection * conn, const char * pattern, ...); /** * @} */ /** * @defgroup h_result _h_result SQL query management functions * SQL query management for struct _h_result format * @{ */ /** * h_clean_result * Free all the memory allocated by the struct _h_result * @param result the result to free * @return H_OK on success */ int h_clean_result(struct _h_result * result); /** * h_clean_data * Free memory allocated by the struct _h_data * @param data the data to free * @return H_OK on success */ int h_clean_data(struct _h_data * data); /** * h_clean_data_full * Free memory allocated by the struct _h_data and the struct _h_data pointer * @param data the data to free * @return H_OK on success */ int h_clean_data_full(struct _h_data * data); /** * @} */ /** * @defgroup init Initialize and cosing connection functions * @{ */ /** * h_clean_connection * free memory allocated by the struct _h_connection * @param conn the connection to the database * @return H_OK on success */ int h_clean_connection(struct _h_connection * conn); /** * h_connect_sqlite * Opens a database connection to a sqlite3 db file * @param db_path the path to the sqlite db file * @return pointer to a struct _h_connection * on sucess, NULL on error */ struct _h_connection * h_connect_sqlite(const char * db_path); /** * close a sqlite3 connection * @param conn the connection to the database */ void h_close_sqlite(struct _h_connection * conn); /** * @} */ /** * @defgroup escape Escape string functions * @{ */ /** * escape a string * returned value must be h_free'd after use * This is an internal function, you should use h_escape_string instead * @param conn the connection to the database * @param unsafe the string to escape * @return a heap-allocated string */ char * h_escape_string_sqlite(const struct _h_connection * conn, const char * unsafe); /** * escape a string * returned value must be h_free'd after use * This is an internal function, you should use h_escape_string_with_quotes instead * @param conn the connection to the database * @param unsafe the string to escape * @return a heap-allocated string */ char * h_escape_string_with_quotes_sqlite(const struct _h_connection * conn, const char * unsafe); /** * @} */ /** * @defgroup json JSON SQL query management functions * SQL query management for JSON format * @{ */ /** * Return the id of the last inserted value * This is an internal function, you should use h_last_insert_id instead * @param conn the connection to the database * @return a long long int value */ long long int h_last_insert_id_sqlite(const struct _h_connection * conn); /** * h_exec_query_sqlite * legacy function name, didn't realize the typo until now... * redirect to h_execute_query_sqlite * @param conn the connection to the database * @param query the SQL query to execute * @return H_OK on success */ int h_exec_query_sqlite(const struct _h_connection * conn, const char * query); /** * h_execute_query_sqlite * Execute a query on a sqlite connection * This is an internal function, you should use h_exec_query instead * Should not be executed by the user because all parameters are supposed to be correct * No result is returned, useful for single INSERT, UPDATE or DELETE statements * @param conn the connection to the database * @param query the SQL query to execute * @return H_OK on success */ int h_execute_query_sqlite(const struct _h_connection * conn, const char * query); /** * h_execute_query_json_sqlite * Execute a query on a sqlite connection, set the returned values in the json result * This is an internal function, you should use h_execute_query_json instead * Should not be executed by the user because all parameters are supposed to be correct * @param conn the connection to the database * @param query the SQL query to execute * @param j_result a json_t * reference that will be allocated and filled with the result * @return H_OK on success */ int h_execute_query_json_sqlite(const struct _h_connection * conn, const char * query, json_t ** j_result); /** * @} */ /** * @defgroup h_result _h_result SQL query management functions * SQL query management for struct _h_result format * @{ */ /** * h_select_query_sqlite * Execute a select query on a sqlite connection, set the result structure with the returned values * This is an internal function, you should use h_select_query instead * Should not be executed by the user because all parameters are supposed to be correct * if result is NULL, the query is executed but no value will be returned * Useful for SELECT statements * @param conn the connection to the database * @param query the SQL query to execute * @param result a _h_result that will be filled with the result * return H_OK on success */ int h_select_query_sqlite(const struct _h_connection * conn, const char * query, struct _h_result * result); /** * @} */ /** * @defgroup init Initialize and cosing connection functions * @{ */ /** * h_connect_mariadb * Opens a database connection to a mariadb server * @param host the hostname of the database server * @param user the username to connect to the database * @param passwd the password to connect to the database * @param db the database name * @param port the TCP port number for the database connection, 0 means system default * @param unix_socket a UNIX socket to use for the connection, optional * @return pointer to a struct _h_connection * on success, NULL on error */ struct _h_connection * h_connect_mariadb(const char * host, const char * user, const char * passwd, const char * db, const unsigned int port, const char * unix_socket); /** * close connection to database */ void h_close_mariadb(struct _h_connection * conn); /** * @} */ /** * @defgroup escape Escape string functions * @{ */ /** * escape a string * This is an internal function, you should use h_escape_string instead * returned value must be h_free'd after use * @param conn the connection to the database * @param unsafe the string to escape * @return a heap-allocated string */ char * h_escape_string_mariadb(const struct _h_connection * conn, const char * unsafe); /** * escape a string * This is an internal function, you should use h_escape_string_with_quotes instead * returned value must be h_free'd after use * @param conn the connection to the database * @param unsafe the string to escape * @return a heap-allocated string */ char * h_escape_string_with_quotes_mariadb(const struct _h_connection * conn, const char * unsafe); /** * @} */ /** * @defgroup json JSON SQL query management functions * SQL query management for JSON format * @{ */ /** * Return the id of the last inserted value * This is an internal function, you should use h_last_insert_id instead * @param conn the connection to the database * @return a long long int value */ long long int h_last_insert_id_mariadb(const struct _h_connection * conn); /** * Execute a query on a mariadb connection, set the returned values in the json result * This is an internal function, you should use h_execute_query_json instead * Should not be executed by the user because all parameters are supposed to be correct * @param conn the connection to the database * @param query the SQL query to execute * @param j_result a json_t * reference that will be allocated and filled with the result * @return H_OK on success */ int h_execute_query_json_mariadb(const struct _h_connection * conn, const char * query, json_t ** j_result); /** * @} */ /** * @defgroup h_result _h_result SQL query management functions * SQL query management for struct _h_result format * @{ */ /** * h_execute_query_mariadb * Execute a select query on a mariadb connection, set the result structure with the returned values * This is an internal function, you should use h_select_query instead * Should not be executed by the user because all parameters are supposed to be correct * if result is NULL, the query is executed but no value will be returned * Useful for SELECT statements * @param conn the connection to the database * @param query the SQL query to execute * @param result a _h_result that will be filled with the result * @return H_OK on success */ int h_execute_query_mariadb(const struct _h_connection * conn, const char * query, struct _h_result * result); /** * h_get_mariadb_value * convert value into a struct _h_data * depening on the m_type given * This is an internal function, you should not use it * returned value must be h_free'd with h_clean_data_full after use * @param value the value to convert * @param length the length of the value * @param m_type the data type * @return a _h_data * contaning the converted value */ struct _h_data * h_get_mariadb_value(const char * value, const unsigned long length, const int m_type); /** * @} */ /** * @defgroup init Initialize and cosing connection functions * @{ */ /** * h_connect_pgsql * Opens a database connection to a PostgreSQL server * @param conninfo the connection info to connect to the pgsql database * @return pointer to a struct _h_connection * on sucess, NULL on error */ struct _h_connection * h_connect_pgsql(const char * conninfo); /** * close a pgsql connection * @param conn the connection to the database */ void h_close_pgsql(struct _h_connection * conn); /** * @} */ /** * @defgroup escape Escape string functions * @{ */ /** * escape a string * This is an internal function, you should use h_escape_string instead * returned value must be h_free'd after use * @param conn the connection to the database * @param unsafe the string to escape * @return a heap-allocated string */ char * h_escape_string_pgsql(const struct _h_connection * conn, const char * unsafe); /** * escape a string * This is an internal function, you should use h_escape_string_with_quotes instead * returned value must be h_free'd after use * @param conn the connection to the database * @param unsafe the string to escape * @return a heap-allocated string */ char * h_escape_string_with_quotes_pgsql(const struct _h_connection * conn, const char * unsafe); /** * @} */ /** * @defgroup json JSON SQL query management functions * SQL query management for JSON format * @{ */ /** * h_execute_query_json_pgsql * Execute a query on a pgsql connection, set the returned values in the json results * This is an internal function, you should use h_execute_query_json instead * Should not be executed by the user because all parameters are supposed to be correct * @param conn the connection to the database * @param query the SQL query to execute * @param j_result a json_t * reference that will be allocated and filled with the result * @return H_OK on success */ int h_execute_query_json_pgsql(const struct _h_connection * conn, const char * query, json_t ** j_result); /** * Return the id of the last inserted value * This is an internal function, you should use h_last_insert_id instead * @param conn the connection to the database * @return a long long int value */ long long int h_last_insert_id_pgsql(const struct _h_connection * conn); /** * @} */ /** * @defgroup h_result _h_result SQL query management functions * SQL query management for struct _h_result format * @{ */ /** * h_execute_query_pgsql * Execute a select query on a pgsql connection, set the result structure with the returned values * This is an internal function, you should use h_select_query instead * Should not be executed by the user because all parameters are supposed to be correct * if result is NULL, the query is executed but no value will be returned * Useful for SELECT statements * @param conn the connection to the database * @param query the SQL query to execute * @param result a _h_result that will be filled with the result * return H_OK on success */ int h_execute_query_pgsql(const struct _h_connection * conn, const char * query, struct _h_result * result); /** * @} */ #ifdef __cplusplus } #endif #endif /* __HOEL_H__ */ hoel-1.4.29/libhoel.pc.in000066400000000000000000000005751452453561700151300ustar00rootroot00000000000000prefix=@CMAKE_INSTALL_PREFIX@ exec_prefix=@CMAKE_INSTALL_PREFIX@ libdir=@PKGCONFIG_TARGET_LIBDIR@ includedir=@PKGCONFIG_TARGET_INCLUDES@ Name: @PROJECT_NAME@ Description: @PROJECT_DESCRIPTION@ URL: @PROJECT_BUGREPORT_PATH@ Version: @LIBRARY_VERSION@ Requires: @PKGCONF_REQ@ Requires.private: @PKGCONF_REQ_PRIVATE@ Libs: -L${libdir} -lhoel -lorcania -lyder Cflags: -I${includedir} hoel-1.4.29/src/000077500000000000000000000000001452453561700133415ustar00rootroot00000000000000hoel-1.4.29/src/Makefile000066400000000000000000000137001452453561700150020ustar00rootroot00000000000000# # Hoel Framework # # Makefile used to build the software # # Copyright 2014-2020 Nicolas Mora # # 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; # version 2.1 of the License. # # This library is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU GENERAL PUBLIC LICENSE for more details. # # You should have received a copy of the GNU General Public # License along with this library. If not, see . # CC=gcc ifndef DISABLE_SQLITE ENABLE_SQLITE=1 LIBS_SQLITE=-lsqlite3 else ENABLE_SQLITE=0 endif ifndef DISABLE_MARIADB ENABLE_MARIADB=1 FLAGS_MARIADB=$(shell mysql_config --cflags) LIBS_MARIADB=$(shell mysql_config --libs_r) else ENABLE_MARIADB=0 endif ifndef DISABLE_POSTGRESQL ENABLE_PGSQL=1 FLAGS_PGSQL=$(shell pkg-config --cflags libpq) LIBS_PGSQL=$(shell pkg-config --libs libpq) else ENABLE_PGSQL=0 endif PROJECT_NAME=hoel PROJECT_DESCRIPTION=C Database abstraction library with json based language PROJECT_BUGREPORT_PATH=https://github.com/babelouest/hoel/issues PKGCONF_REQ= PKGCONF_REQ_PRIVATE= HOEL_INCLUDE=../include DESTDIR=/usr/local CONFIG_TEMPLATE=$(HOEL_INCLUDE)/hoel-cfg.h.in CONFIG_FILE=$(HOEL_INCLUDE)/hoel-cfg.h PKGCONFIG_FILE=../libhoel.pc PKGCONFIG_TEMPLATE=../libhoel.pc.in CFLAGS+=-c -fPIC -Wall -Werror -Wextra -Wconversion -I$(HOEL_INCLUDE) $(FLAGS_MARIADB) $(FLAGS_PGSQL) -D_REENTRANT $(ADDITIONALFLAGS) $(CPPFLAGS) LIBS=-L$(DESTDIR)/lib -lc -ljansson -lyder -lorcania $(LIBS_SQLITE) $(LIBS_PGSQL) $(LIBS_MARIADB) OBJECTS=hoel-sqlite.o hoel-mariadb.o hoel-pgsql.o hoel-simple-json.o hoel.o OUTPUT=libhoel.so VERSION_MAJOR=1 VERSION_MINOR=4 VERSION_PATCH=29 all: release $(CONFIG_FILE): @if [ "$(ENABLE_SQLITE)" = "0" ] && [ "$(ENABLE_MARIADB)" = "0" ] && [ "$(ENABLE_PGSQL)" = "0" ]; then \ echo "You must enable at least one database backend: Sqlite3, MariaDB or PostgreSQL"; \ exit 1; \ fi @cp $(CONFIG_TEMPLATE) $(CONFIG_FILE) @echo Config file $(CONFIG_FILE) generated @sed -i -e 's/$${PROJECT_VERSION}/$(VERSION_MAJOR).$(VERSION_MINOR).$(VERSION_PATCH)/g' $(CONFIG_FILE) @sed -i -e 's/$${PROJECT_VERSION_MAJOR}/$(VERSION_MAJOR)/g' $(CONFIG_FILE) @sed -i -e 's/$${PROJECT_VERSION_MINOR}/$(VERSION_MINOR)/g' $(CONFIG_FILE) @sed -i -e 's/$${PROJECT_VERSION_PATCH}/$(VERSION_PATCH)/g' $(CONFIG_FILE) @sed -i -e 's/$${PROJECT_VERSION_NUMBER}/$(shell printf '%02d' $(VERSION_MAJOR))$(shell printf '%02d' $(VERSION_MINOR))$(shell printf '%02d' $(VERSION_PATCH))/g' $(CONFIG_FILE) @if [ "$(ENABLE_SQLITE)" = "1" ]; then \ sed -i -e 's/\#cmakedefine _HOEL_SQLITE/\#define _HOEL_SQLITE/g' $(CONFIG_FILE); \ echo "SQLITE SUPPORT ENABLED"; \ else \ sed -i -e 's/\#cmakedefine _HOEL_SQLITE/\/* #undef _HOEL_SQLITE *\//g' $(CONFIG_FILE); \ echo "SQLITE SUPPORT DISABLED"; \ fi @if [ "$(ENABLE_MARIADB)" = "1" ]; then \ sed -i -e 's/\#cmakedefine _HOEL_MARIADB/\#define _HOEL_MARIADB/g' $(CONFIG_FILE); \ echo "MARIADB SUPPORT ENABLED"; \ else \ sed -i -e 's/\#cmakedefine _HOEL_MARIADB/\/* #undef _HOEL_MARIADB *\//g' $(CONFIG_FILE); \ echo "MARIADB SUPPORT DISABLED"; \ fi @if [ "$(ENABLE_PGSQL)" = "1" ]; then \ sed -i -e 's/\#cmakedefine _HOEL_PGSQL/\#define _HOEL_PGSQL/g' $(CONFIG_FILE); \ echo "PGSQL SUPPORT ENABLED"; \ else \ sed -i -e 's/\#cmakedefine _HOEL_PGSQL/\/* #undef _HOEL_PGSQL *\//g' $(CONFIG_FILE); \ echo "PGSQL SUPPORT DISABLED"; \ fi $(PKGCONFIG_FILE): @cp $(PKGCONFIG_TEMPLATE) $(PKGCONFIG_FILE) @echo Pkgconfig file $(PKGCONFIG_FILE) generated @sed -i -e 's#@CMAKE_INSTALL_PREFIX@#$(DESTDIR)#g' $(PKGCONFIG_FILE) @sed -i -e 's#@PKGCONFIG_TARGET_LIBDIR@#$${prefix}/lib#g' $(PKGCONFIG_FILE) @sed -i -e 's#@PKGCONFIG_TARGET_INCLUDES@#$${prefix}/include#g' $(PKGCONFIG_FILE) @sed -i -e 's/@PROJECT_NAME@/$(PROJECT_NAME)/g' $(PKGCONFIG_FILE) @sed -i -e 's/@PROJECT_DESCRIPTION@/$(PROJECT_DESCRIPTION)/g' $(PKGCONFIG_FILE) @sed -i -e 's|@PROJECT_BUGREPORT_PATH@|$(PROJECT_BUGREPORT_PATH)|g' $(PKGCONFIG_FILE) @sed -i -e 's/@LIBRARY_VERSION@/$(VERSION_MAJOR).$(VERSION_MINOR).$(VERSION_PATCH)/g' $(PKGCONFIG_FILE) @sed -i -e 's/@PKGCONF_REQ@/$(PKGCONF_REQ)/g' $(PKGCONFIG_FILE) @sed -i -e 's/@PKGCONF_REQ_PRIVATE@/$(PKGCONF_REQ_PRIVATE)/g' $(PKGCONFIG_FILE) libhoel.so: $(OBJECTS) $(CC) -shared -fPIC -Wl,-soname,$(OUTPUT) -o $(OUTPUT).$(VERSION_MAJOR).$(VERSION_MINOR).$(VERSION_PATCH) $(OBJECTS) $(LIBS) $(LDFLAGS) ln -sf $(OUTPUT).$(VERSION_MAJOR).$(VERSION_MINOR).$(VERSION_PATCH) $(OUTPUT) libhoel.a: $(OBJECTS) ar rcs libhoel.a $(OBJECTS) %.o: %.c $(CONFIG_FILE) $(HOEL_INCLUDE)/hoel.h $(HOEL_INCLUDE)/h-private.h $(CC) $(CFLAGS) $< clean: rm -f *.o *.so *.a $(OUTPUT) $(OUTPUT).* $(CONFIG_FILE) $(PKGCONFIG_FILE) install: all $(PKGCONFIG_FILE) install $(OUTPUT).$(VERSION_MAJOR).$(VERSION_MINOR).$(VERSION_PATCH) $(DESTDIR)/lib mkdir -p $(DESTDIR)/lib/pkgconfig/ $(DESTDIR)/include install -m644 $(PKGCONFIG_FILE) $(DESTDIR)/lib/pkgconfig/ install -m644 $(HOEL_INCLUDE)/hoel.h $(DESTDIR)/include install -m644 $(CONFIG_FILE) $(DESTDIR)/include -ldconfig $(DESTDIR)/lib static-install: static cp libhoel.a $(DESTDIR)/lib mkdir -p $(DESTDIR)/lib/pkgconfig/ $(DESTDIR)/include install -m644 $(PKGCONFIG_FILE) $(DESTDIR)/lib/pkgconfig install -m644 $(HOEL_INCLUDE)/hoel.h $(DESTDIR)/include install -m644 $(CONFIG_FILE) $(DESTDIR)/include uninstall: rm -f $(DESTDIR)/lib/$(OUTPUT) $(DESTDIR)/lib/libhoel.a rm -f $(DESTDIR)/lib/$(OUTPUT).* rm -f $(DESTDIR)/include/hoel.h rm -f $(DESTDIR)/include/$(CONFIG_FILE) rm -f $(DESTDIR)/lib/pkgconfig/$(PKGCONFIG_FILE) debug: ADDITIONALFLAGS=-DDEBUG -g -O0 debug: libhoel.so release: ADDITIONALFLAGS=-O3 release: libhoel.so static-debug: ADDITIONALFLAGS=-DDEBUG -g -O0 static-debug: libhoel.a static: ADDITIONALFLAGS=-O3 static: libhoel.a hoel-1.4.29/src/hoel-mariadb.c000066400000000000000000000417611452453561700160420ustar00rootroot00000000000000/** * * Hoel database abstraction library * * hoel-mariadb.c: Maria DB/Mysql specific functions * * Copyright 2015-2020 Nicolas Mora * * 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; * version 2.1 of the License. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU GENERAL PUBLIC LICENSE for more details. * * You should have received a copy of the GNU General Public * License along with this library. If not, see . * */ #include "hoel.h" #include "h-private.h" #ifdef _HOEL_MARIADB /* MariaDB library Includes */ #include #include #include /** * MariaDB handle */ struct _h_mariadb { char * host; char * user; char * passwd; char * db; unsigned int port; char * unix_socket; unsigned long flags; MYSQL * db_handle; pthread_mutex_t lock; }; /** * h_connect_mariadb * Opens a database connection to a mariadb server * return pointer to a struct _h_connection * on sucess, NULL on error */ struct _h_connection * h_connect_mariadb(const char * host, const char * user, const char * passwd, const char * db, const unsigned int port, const char * unix_socket) { struct _h_connection * conn = NULL; pthread_mutexattr_t mutexattr; bool reconnect = 1; o_malloc_t malloc_fn; o_free_t free_fn; o_get_alloc_funcs(&malloc_fn, NULL, &free_fn); json_set_alloc_funcs((json_malloc_t)malloc_fn, (json_free_t)free_fn); if (host != NULL && db != NULL) { conn = o_malloc(sizeof(struct _h_connection)); if (conn == NULL) { y_log_message(Y_LOG_LEVEL_ERROR, "Hoel - Error allocating memory for conn"); return NULL; } conn->type = HOEL_DB_TYPE_MARIADB; conn->connection = o_malloc(sizeof(struct _h_mariadb)); if (conn->connection == NULL) { y_log_message(Y_LOG_LEVEL_ERROR, "Hoel - Error allocating memory for conn->connection"); h_free(conn); return NULL; } if (mysql_library_init(0, NULL, NULL)) { y_log_message(Y_LOG_LEVEL_ERROR, "mysql_library_init error, aborting"); h_free(conn); return NULL; } ((struct _h_mariadb *)conn->connection)->db_handle = mysql_init(NULL); if (((struct _h_mariadb *)conn->connection)->db_handle == NULL) { y_log_message(Y_LOG_LEVEL_ERROR, "mysql_init error, aborting"); h_free(conn); return NULL; } if (mysql_real_connect(((struct _h_mariadb *)conn->connection)->db_handle, host, user, passwd, db, port, unix_socket, CLIENT_COMPRESS) == NULL) { y_log_message(Y_LOG_LEVEL_ERROR, "Error connecting to mariadb database %s", db); y_log_message(Y_LOG_LEVEL_DEBUG, "Error message: \"%s\"", mysql_error(((struct _h_mariadb *)conn->connection)->db_handle)); mysql_close(((struct _h_mariadb *)conn->connection)->db_handle); h_free(conn); return NULL; } else { /* Set MYSQL_OPT_RECONNECT to true to reconnect automatically when connection is closed by the server (to avoid CR_SERVER_GONE_ERROR) */ mysql_options(((struct _h_mariadb *)conn->connection)->db_handle, MYSQL_OPT_RECONNECT, &reconnect); /* Initialize MUTEX for connection */ pthread_mutexattr_init ( &mutexattr ); pthread_mutexattr_settype( &mutexattr, PTHREAD_MUTEX_RECURSIVE ); if (pthread_mutex_init(&(((struct _h_mariadb *)conn->connection)->lock), &mutexattr) != 0) { y_log_message(Y_LOG_LEVEL_ERROR, "Impossible to initialize Mutex Lock for MariaDB connection"); } pthread_mutexattr_destroy( &mutexattr ); return conn; } } return conn; } /** * close connection to database */ void h_close_mariadb(struct _h_connection * conn) { mysql_close(((struct _h_mariadb *)conn->connection)->db_handle); mysql_library_end(); pthread_mutex_destroy(&((struct _h_mariadb *)conn->connection)->lock); } /** * escape a string * returned value must be free'd after use */ char * h_escape_string_mariadb(const struct _h_connection * conn, const char * unsafe) { char * escaped = o_malloc(2 * o_strlen(unsafe) + 1), * to_return = NULL; if (escaped == NULL) { y_log_message(Y_LOG_LEVEL_ERROR, "Hoel - Error allocating memory for escaped"); return NULL; } escaped[0] = '\0'; mysql_real_escape_string(((struct _h_mariadb *)conn->connection)->db_handle, escaped, unsafe, o_strlen(unsafe)); to_return = o_strdup(escaped); h_free(escaped); return to_return; } /** * Escapes a string and returns it ready to be inserted in the query * returned value must be free'd after use */ char * h_escape_string_with_quotes_mariadb(const struct _h_connection * conn, const char * unsafe) { char * escaped = h_escape_string_mariadb(conn, unsafe), * escaped_returned = NULL; if (escaped == NULL) { y_log_message(Y_LOG_LEVEL_ERROR, "Hoel - Error h_escape_string_mariadb"); return NULL; } escaped_returned = msprintf("'%s'", escaped); h_free(escaped); return escaped_returned; } /** * Return the id of the last inserted value */ long long int h_last_insert_id_mariadb(const struct _h_connection * conn) { long long int id = 0; if (pthread_mutex_lock(&(((struct _h_mariadb *)conn->connection)->lock))) { y_log_message(Y_LOG_LEVEL_ERROR, "Error h_last_insert_id - lock error"); } else { id = (long long int)mysql_insert_id(((struct _h_mariadb *)conn->connection)->db_handle); if (id <= 0) { y_log_message(Y_LOG_LEVEL_ERROR, "Error executing mysql_insert_id"); y_log_message(Y_LOG_LEVEL_DEBUG, "Error message: \"%s\"", mysql_error(((struct _h_mariadb *)conn->connection)->db_handle)); } pthread_mutex_unlock(&(((struct _h_mariadb *)conn->connection)->lock)); } return id; } /** * h_execute_query_mariadb * Execute a query on a mariadb connection, set the result structure with the returned values * Should not be executed by the user because all parameters are supposed to be correct * if result is NULL, the query is executed but no value will be returned * return H_OK on success */ int h_execute_query_mariadb(const struct _h_connection * conn, const char * query, struct _h_result * h_result) { MYSQL_RES * result; uint num_fields, col, row; MYSQL_ROW m_row; MYSQL_FIELD * fields; struct _h_data * data, * cur_row = NULL; unsigned long * lengths; int res; if (pthread_mutex_lock(&(((struct _h_mariadb *)conn->connection)->lock))) { return H_ERROR_QUERY; } if (mysql_query(((struct _h_mariadb *)conn->connection)->db_handle, query)) { y_log_message(Y_LOG_LEVEL_ERROR, "Error executing sql query"); y_log_message(Y_LOG_LEVEL_DEBUG, "Error message: \"%s\"", mysql_error(((struct _h_mariadb *)conn->connection)->db_handle)); y_log_message(Y_LOG_LEVEL_DEBUG, "Query: \"%s\"", query); pthread_mutex_unlock(&(((struct _h_mariadb *)conn->connection)->lock)); return H_ERROR_QUERY; } if (h_result != NULL) { result = mysql_store_result(((struct _h_mariadb *)conn->connection)->db_handle); if (result == NULL) { y_log_message(Y_LOG_LEVEL_ERROR, "Error executing mysql_store_result"); y_log_message(Y_LOG_LEVEL_DEBUG, "Error message: \"%s\"", mysql_error(((struct _h_mariadb *)conn->connection)->db_handle)); pthread_mutex_unlock(&(((struct _h_mariadb *)conn->connection)->lock)); return H_ERROR_QUERY; } num_fields = mysql_num_fields(result); fields = mysql_fetch_fields(result); h_result->nb_rows = 0; h_result->nb_columns = num_fields; h_result->data = NULL; for (row = 0; (m_row = mysql_fetch_row(result)) != NULL; row++) { cur_row = NULL; lengths = mysql_fetch_lengths(result); for (col=0; colconnection)->lock)); return res; } } res = h_result_add_row(h_result, cur_row, (int)row); if (res != H_OK) { mysql_free_result(result); pthread_mutex_unlock(&(((struct _h_mariadb *)conn->connection)->lock)); return res; } } mysql_free_result(result); } pthread_mutex_unlock(&(((struct _h_mariadb *)conn->connection)->lock)); return H_OK; } /** * h_execute_query_json_mariadb * Execute a query on a mariadb connection, set the returned values in the json result * Should not be executed by the user because all parameters are supposed to be correct * return H_OK on success */ int h_execute_query_json_mariadb(const struct _h_connection * conn, const char * query, json_t ** j_result) { MYSQL_RES * result; uint num_fields, col, row; MYSQL_ROW m_row; MYSQL_FIELD * fields; unsigned long * lengths; json_t * j_data; struct _h_data * h_data; char date_stamp[64] = {0}; if (pthread_mutex_lock(&(((struct _h_mariadb *)conn->connection)->lock))) { return H_ERROR_QUERY; } if (j_result == NULL) { pthread_mutex_unlock(&(((struct _h_mariadb *)conn->connection)->lock)); return H_ERROR_PARAMS; } *j_result = json_array(); if (*j_result == NULL) { y_log_message(Y_LOG_LEVEL_ERROR, "Hoel - Error allocating memory for *j_result"); pthread_mutex_unlock(&(((struct _h_mariadb *)conn->connection)->lock)); return H_ERROR_MEMORY; } if (mysql_query(((struct _h_mariadb *)conn->connection)->db_handle, query)) { y_log_message(Y_LOG_LEVEL_ERROR, "Error executing sql query"); y_log_message(Y_LOG_LEVEL_DEBUG, "Error message: \"%s\"", mysql_error(((struct _h_mariadb *)conn->connection)->db_handle)); y_log_message(Y_LOG_LEVEL_DEBUG, "Query: \"%s\"", query); pthread_mutex_unlock(&(((struct _h_mariadb *)conn->connection)->lock)); json_decref(*j_result); return H_ERROR_QUERY; } result = mysql_store_result(((struct _h_mariadb *)conn->connection)->db_handle); if (result == NULL) { y_log_message(Y_LOG_LEVEL_ERROR, "Error executing mysql_store_result"); y_log_message(Y_LOG_LEVEL_DEBUG, "Error message: \"%s\"", mysql_error(((struct _h_mariadb *)conn->connection)->db_handle)); pthread_mutex_unlock(&(((struct _h_mariadb *)conn->connection)->lock)); json_decref(*j_result); return H_ERROR_QUERY; } num_fields = mysql_num_fields(result); fields = mysql_fetch_fields(result); for (row = 0; (m_row = mysql_fetch_row(result)) != NULL; row++) { j_data = json_object(); if (j_data == NULL) { y_log_message(Y_LOG_LEVEL_ERROR, "Hoel - Error allocating memory for j_data"); json_decref(*j_result); pthread_mutex_unlock(&(((struct _h_mariadb *)conn->connection)->lock)); json_decref(*j_result); return H_ERROR_MEMORY; } lengths = mysql_fetch_lengths(result); for (col=0; coltype) { case HOEL_COL_TYPE_INT: json_object_set_new(j_data, fields[col].name, json_integer(((struct _h_type_int *)h_data->t_data)->value)); break; case HOEL_COL_TYPE_DOUBLE: json_object_set_new(j_data, fields[col].name, json_real(((struct _h_type_double *)h_data->t_data)->value)); break; case HOEL_COL_TYPE_TEXT: json_object_set_new(j_data, fields[col].name, json_string(((struct _h_type_text *)h_data->t_data)->value)); break; case HOEL_COL_TYPE_DATE: strftime (date_stamp, sizeof(date_stamp), "%Y-%m-%dT%H:%M:%S", &((struct _h_type_datetime *)h_data->t_data)->value); json_object_set_new(j_data, fields[col].name, json_string(date_stamp)); break; case HOEL_COL_TYPE_BLOB: json_object_set_new(j_data, fields[col].name, json_stringn(((struct _h_type_blob *)h_data->t_data)->value, ((struct _h_type_blob *)h_data->t_data)->length)); break; case HOEL_COL_TYPE_NULL: json_object_set_new(j_data, fields[col].name, json_null()); break; } h_clean_data_full(h_data); } json_array_append_new(*j_result, j_data); j_data = NULL; } mysql_free_result(result); pthread_mutex_unlock(&(((struct _h_mariadb *)conn->connection)->lock)); return H_OK; } /** * h_get_mariadb_value * convert value into a struct _h_data * depening on the m_type given * returned value must be free'd with h_clean_data_full after use */ struct _h_data * h_get_mariadb_value(const char * value, const unsigned long length, const int m_type) { struct _h_data * data = NULL; long long int i_value; double d_value; struct tm tm_value; char * endptr; if (value != NULL) { switch (m_type) { case FIELD_TYPE_DECIMAL: case FIELD_TYPE_NEWDECIMAL: case FIELD_TYPE_TINY: case FIELD_TYPE_SHORT: case FIELD_TYPE_LONG: case FIELD_TYPE_LONGLONG: case FIELD_TYPE_INT24: case FIELD_TYPE_YEAR: i_value = strtoll(value, &endptr, 10); if (endptr != value) { data = h_new_data_int(i_value); } else { data = h_new_data_null(); } break; case FIELD_TYPE_BIT: i_value = strtol(value, &endptr, 2); if (endptr != value) { data = h_new_data_int(i_value); } else { data = h_new_data_null(); } break; case FIELD_TYPE_FLOAT: case FIELD_TYPE_DOUBLE: d_value = strtod(value, &endptr); if (endptr != value) { data = h_new_data_double(d_value); } else { data = h_new_data_null(); } break; case FIELD_TYPE_NULL: data = h_new_data_null(); break; case FIELD_TYPE_DATE: if (strptime(value, "%Y-%m-%d", &tm_value) == NULL) { data = h_new_data_null(); } else { data = h_new_data_datetime(&tm_value); } break; case FIELD_TYPE_TIME: if (strptime(value, "%H:%M:%S", &tm_value) == NULL) { data = h_new_data_null(); } else { data = h_new_data_datetime(&tm_value); } break; case FIELD_TYPE_TIMESTAMP: case FIELD_TYPE_DATETIME: case FIELD_TYPE_NEWDATE: if (strptime(value, "%Y-%m-%d %H:%M:%S", &tm_value) == NULL) { data = h_new_data_null(); } else { data = h_new_data_datetime(&tm_value); } break; case FIELD_TYPE_TINY_BLOB: case FIELD_TYPE_MEDIUM_BLOB: case FIELD_TYPE_LONG_BLOB: case FIELD_TYPE_BLOB: if (length > 0) { data = h_new_data_blob(value, length); } else { data = h_new_data_null(); } break; case FIELD_TYPE_VAR_STRING: case FIELD_TYPE_ENUM: case FIELD_TYPE_SET: case FIELD_TYPE_GEOMETRY: default: data = h_new_data_text(value, length); break; } } else { data = h_new_data_null(); } return data; } #else /** * Dummy functions when Hoel is not built with MariaDB */ struct _h_connection * h_connect_mariadb(const char * host, const char * user, const char * passwd, const char * db, const unsigned int port, const char * unix_socket) { UNUSED(host); UNUSED(user); UNUSED(passwd); UNUSED(db); UNUSED(port); UNUSED(unix_socket); y_log_message(Y_LOG_LEVEL_ERROR, "Hoel was not compiled with MariaDB backend"); return NULL; } void h_close_mariadb(struct _h_connection * conn) { UNUSED(conn); y_log_message(Y_LOG_LEVEL_ERROR, "Hoel was not compiled with MariaDB backend"); } char * h_escape_string_mariadb(const struct _h_connection * conn, const char * unsafe) { UNUSED(conn); UNUSED(unsafe); y_log_message(Y_LOG_LEVEL_ERROR, "Hoel was not compiled with MariaDB backend"); return NULL; } char * h_escape_string_with_quotes_mariadb(const struct _h_connection * conn, const char * unsafe) { UNUSED(conn); UNUSED(unsafe); y_log_message(Y_LOG_LEVEL_ERROR, "Hoel was not compiled with MariaDB backend"); return NULL; } long long int h_last_insert_id_mariadb(const struct _h_connection * conn) { UNUSED(conn); y_log_message(Y_LOG_LEVEL_ERROR, "Hoel was not compiled with MariaDB backend"); return 0; } int h_execute_query_mariadb(const struct _h_connection * conn, const char * query, struct _h_result * h_result) { UNUSED(conn); UNUSED(query); UNUSED(h_result); y_log_message(Y_LOG_LEVEL_ERROR, "Hoel was not compiled with MariaDB backend"); return H_ERROR; } int h_execute_query_json_mariadb(const struct _h_connection * conn, const char * query, json_t ** j_result) { UNUSED(conn); UNUSED(query); UNUSED(j_result); y_log_message(Y_LOG_LEVEL_ERROR, "Hoel was not compiled with MariaDB backend"); return H_ERROR; } struct _h_data * h_get_mariadb_value(const char * value, const unsigned long length, const int m_type) { UNUSED(value); UNUSED(length); UNUSED(m_type); y_log_message(Y_LOG_LEVEL_ERROR, "Hoel was not compiled with MariaDB backend"); return NULL; } #endif hoel-1.4.29/src/hoel-pgsql.c000066400000000000000000000432161452453561700155660ustar00rootroot00000000000000/** * * Hoel database abstraction library * * hoel-pgsql.c: Postgre SQL specific functions * * Copyright 2015-2020 Nicolas Mora * * 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; * version 2.1 of the License. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU GENERAL PUBLIC LICENSE for more details. * * You should have received a copy of the GNU General Public * License along with this library. If not, see . * */ #include "hoel.h" #include "h-private.h" #ifdef _HOEL_PGSQL /* PostgreSQL library includes */ #include #include struct _h_pg_type { Oid pg_type; unsigned short h_type; }; /** * Postgre SQL handle */ struct _h_pgsql { char * conninfo; PGconn * db_handle; unsigned int nb_type; struct _h_pg_type * list_type; pthread_mutex_t lock; }; /** * h_connect_pgsql * Opens a database connection to a PostgreSQL server * return pointer to a struct _h_connection * on sucess, NULL on error */ struct _h_connection * h_connect_pgsql(const char * conninfo) { struct _h_connection * conn = NULL; int ntuples, i; PGresult *res; pthread_mutexattr_t mutexattr; o_malloc_t malloc_fn; o_free_t free_fn; o_get_alloc_funcs(&malloc_fn, NULL, &free_fn); json_set_alloc_funcs((json_malloc_t)malloc_fn, (json_free_t)free_fn); if (conninfo != NULL) { conn = o_malloc(sizeof(struct _h_connection)); if (conn == NULL) { y_log_message(Y_LOG_LEVEL_ERROR, "Hoel - Error allocating memory for conn"); return NULL; } conn->type = HOEL_DB_TYPE_PGSQL; conn->connection = o_malloc(sizeof(struct _h_pgsql)); if (conn->connection == NULL) { y_log_message(Y_LOG_LEVEL_ERROR, "Hoel - Error allocating memory for conn->connection"); h_free(conn); return NULL; } ((struct _h_pgsql *)conn->connection)->db_handle = PQconnectdb(conninfo); ((struct _h_pgsql *)conn->connection)->nb_type = 0; ((struct _h_pgsql *)conn->connection)->list_type = NULL; if (PQstatus(((struct _h_pgsql *)conn->connection)->db_handle) != CONNECTION_OK) { y_log_message(Y_LOG_LEVEL_ERROR, "Hoel - Error connecting to PostgreSQL Database"); y_log_message(Y_LOG_LEVEL_DEBUG, "Hoel - Error message: \"%s\"", PQerrorMessage(((struct _h_pgsql *)conn->connection)->db_handle)); PQfinish(((struct _h_pgsql *)conn->connection)->db_handle); h_free(conn->connection); h_free(conn); conn = NULL; } else { res = PQexec(((struct _h_pgsql *)conn->connection)->db_handle, "select oid, typname from pg_type"); if (PQresultStatus(res) != PGRES_TUPLES_OK && PQresultStatus(res) != PGRES_COMMAND_OK && PQnfields(res) == 2) { y_log_message(Y_LOG_LEVEL_ERROR, "Error executing sql query"); y_log_message(Y_LOG_LEVEL_DEBUG, "Error message: \"%s\"", PQerrorMessage(((struct _h_pgsql *)conn->connection)->db_handle)); y_log_message(Y_LOG_LEVEL_DEBUG, "Query: \"select oid, typname from pg_type\""); PQfinish(((struct _h_pgsql *)conn->connection)->db_handle); h_free(conn->connection); h_free(conn); conn = NULL; } else { ntuples = PQntuples(res); ((struct _h_pgsql *)conn->connection)->list_type = o_malloc(((size_t)ntuples+1)*sizeof(struct _h_pg_type)); if (((struct _h_pgsql *)conn->connection)->list_type != NULL) { ((struct _h_pgsql *)conn->connection)->nb_type = (unsigned int)ntuples; for(i = 0; i < ntuples; i++) { char * cur_type_name = PQgetvalue(res, i, 1); ((struct _h_pgsql *)conn->connection)->list_type[i].pg_type = (Oid)strtol(PQgetvalue(res, i, 0), NULL, 10); if (o_strcmp(cur_type_name, "bool") == 0) { ((struct _h_pgsql *)conn->connection)->list_type[i].h_type = HOEL_COL_TYPE_BOOL; } else if (o_strncmp(cur_type_name, "int", 3) == 0 || (o_strncmp(cur_type_name+1, "id", 2) == 0 && o_strlen(cur_type_name) == 3)) { ((struct _h_pgsql *)conn->connection)->list_type[i].h_type = HOEL_COL_TYPE_INT; } else if (o_strcmp(cur_type_name, "numeric") == 0 || o_strncmp(cur_type_name, "float", 5) == 0) { ((struct _h_pgsql *)conn->connection)->list_type[i].h_type = HOEL_COL_TYPE_DOUBLE; } else if (o_strcmp(cur_type_name, "date") == 0 || o_strncmp(cur_type_name, "time", 4) == 0) { ((struct _h_pgsql *)conn->connection)->list_type[i].h_type = HOEL_COL_TYPE_DATE; } else if (o_strcmp(cur_type_name, "bytea") == 0) { ((struct _h_pgsql *)conn->connection)->list_type[i].h_type = HOEL_COL_TYPE_BLOB; } else if (o_strcmp(cur_type_name, "bool") == 0) { ((struct _h_pgsql *)conn->connection)->list_type[i].h_type = HOEL_COL_TYPE_BOOL; } else { ((struct _h_pgsql *)conn->connection)->list_type[i].h_type = HOEL_COL_TYPE_TEXT; } } /* Initialize MUTEX for connection */ pthread_mutexattr_init ( &mutexattr ); pthread_mutexattr_settype( &mutexattr, PTHREAD_MUTEX_RECURSIVE ); if (pthread_mutex_init(&(((struct _h_pgsql *)conn->connection)->lock), &mutexattr) != 0) { y_log_message(Y_LOG_LEVEL_ERROR, "Impossible to initialize Mutex Lock for PostgreSQL connection"); } pthread_mutexattr_destroy( &mutexattr ); } else { y_log_message(Y_LOG_LEVEL_ERROR, "Error allocating resources for list_type"); PQfinish(((struct _h_pgsql *)conn->connection)->db_handle); h_free(conn->connection); h_free(conn); conn = NULL; } PQclear(res); } } } return conn; } /** * close a pgsql connection */ void h_close_pgsql(struct _h_connection * conn) { PQfinish(((struct _h_pgsql *)conn->connection)->db_handle); h_free(((struct _h_pgsql *)conn->connection)->list_type); ((struct _h_pgsql *)conn->connection)->list_type = NULL; ((struct _h_pgsql *)conn->connection)->nb_type = 0; pthread_mutex_destroy(&((struct _h_pgsql *)conn->connection)->lock); } /** * escape a string * returned value must be free'd after use */ char * h_escape_string_pgsql(const struct _h_connection * conn, const char * unsafe) { char * escaped = PQescapeLiteral(((struct _h_pgsql *)conn->connection)->db_handle, unsafe, o_strlen(unsafe)), * to_return = NULL; if (escaped != NULL) { if (escaped[0] == '\'' && escaped[o_strlen(escaped)-1] == '\'') { to_return = o_strndup((escaped+1), o_strlen((escaped+1))-1); } PQfreemem(escaped); } return to_return; } /** * Escapes a string and returns it ready to be inserted in the query * returned value must be free'd after use */ char * h_escape_string_with_quotes_pgsql(const struct _h_connection * conn, const char * unsafe) { char * escaped = PQescapeLiteral(((struct _h_pgsql *)conn->connection)->db_handle, unsafe, o_strlen(unsafe)), * to_return = NULL; if (escaped != NULL) { to_return = o_strdup(escaped); PQfreemem(escaped); } return to_return; } /** * Return the hoel type of a column given its Oid * If type is not found, return HOEL_COL_TYPE_TEXT */ static unsigned short h_get_type_from_oid(const struct _h_connection * conn, Oid pg_type) { unsigned int i; for (i = 0; i < ((struct _h_pgsql *)conn->connection)->nb_type; i++) { if (((struct _h_pgsql *)conn->connection)->list_type[i].pg_type == pg_type) { return ((struct _h_pgsql *)conn->connection)->list_type[i].h_type; } } return HOEL_COL_TYPE_TEXT; } /** * h_execute_query_pgsql * Execute a query on a pgsql connection, set the result structure with the returned values * Should not be executed by the user because all parameters are supposed to be correct * if result is NULL, the query is executed but no value will be returned * return H_OK on success */ int h_execute_query_pgsql(const struct _h_connection * conn, const char * query, struct _h_result * result) { PGresult * res; int nfields, ntuples, i, j, h_res, ret = H_OK; struct _h_data * data, * cur_row = NULL; if (pthread_mutex_lock(&(((struct _h_pgsql *)conn->connection)->lock))) { ret = H_ERROR_QUERY; } else { res = PQexec(((struct _h_pgsql *)conn->connection)->db_handle, query); if (PQresultStatus(res) != PGRES_TUPLES_OK && PQresultStatus(res) != PGRES_COMMAND_OK) { y_log_message(Y_LOG_LEVEL_ERROR, "Error executing sql query"); y_log_message(Y_LOG_LEVEL_DEBUG, "Error message: \"%s\"", PQerrorMessage(((struct _h_pgsql *)conn->connection)->db_handle)); y_log_message(Y_LOG_LEVEL_DEBUG, "Query: \"%s\"", query); PQclear(res); ret = H_ERROR_QUERY; } else { nfields = PQnfields(res); ntuples = PQntuples(res); if (result != NULL) { result->nb_rows = 0; result->nb_columns = (unsigned int)nfields; result->data = NULL; for(i = 0; ret == H_OK && i < ntuples; i++) { cur_row = NULL; for(j = 0; ret == H_OK && j < nfields; j++) { char * val = PQgetvalue(res, i, j); if (val == NULL) { data = h_new_data_null(); } else { switch (h_get_type_from_oid(conn, PQftype(res, j))) { case HOEL_COL_TYPE_INT: data = h_new_data_int(strtol(val, NULL, 10)); break; case HOEL_COL_TYPE_DOUBLE: data = h_new_data_double(strtod(val, NULL)); break; case HOEL_COL_TYPE_BLOB: data = h_new_data_blob(val, (size_t)PQgetlength(res, i, j)); break; case HOEL_COL_TYPE_BOOL: if (o_strcasecmp(val, "t") == 0) { data = h_new_data_int(1); } else if (o_strcasecmp(val, "f") == 0) { data = h_new_data_int(0); } else { data = h_new_data_null(); } break; case HOEL_COL_TYPE_DATE: case HOEL_COL_TYPE_TEXT: default: data = h_new_data_text(val, (size_t)PQgetlength(res, i, j)); break; } } h_res = h_row_add_data(&cur_row, data, j); h_clean_data_full(data); if (h_res != H_OK) { PQclear(res); ret = h_res; } } h_res = h_result_add_row(result, cur_row, i); if (h_res != H_OK) { PQclear(res); ret = h_res; } } } PQclear(res); } pthread_mutex_unlock(&(((struct _h_pgsql *)conn->connection)->lock)); } return ret; } /** * h_execute_query_json_pgsql * Execute a query on a pgsql connection, set the returned values in the json results * Should not be executed by the user because all parameters are supposed to be correct * return H_OK on success */ int h_execute_query_json_pgsql(const struct _h_connection * conn, const char * query, json_t ** j_result) { PGresult *res; int nfields, ntuples, i, j, ret = H_OK; json_t * j_data; if (pthread_mutex_lock(&(((struct _h_pgsql *)conn->connection)->lock))) { ret = H_ERROR_QUERY; } else { if (j_result == NULL) { ret = H_ERROR_PARAMS; } else { *j_result = json_array(); if (*j_result == NULL) { y_log_message(Y_LOG_LEVEL_ERROR, "Hoel - Error allocating memory for *j_result"); ret = H_ERROR_MEMORY; } else { res = PQexec(((struct _h_pgsql *)conn->connection)->db_handle, query); if (PQresultStatus(res) != PGRES_TUPLES_OK && PQresultStatus(res) != PGRES_COMMAND_OK) { y_log_message(Y_LOG_LEVEL_ERROR, "Error executing sql query"); y_log_message(Y_LOG_LEVEL_DEBUG, "Error message: \"%s\"", PQerrorMessage(((struct _h_pgsql *)conn->connection)->db_handle)); y_log_message(Y_LOG_LEVEL_DEBUG, "Query: \"%s\"", query); PQclear(res); ret = H_ERROR_QUERY; } else { nfields = PQnfields(res); ntuples = PQntuples(res); for(i = 0; ret == H_OK && i < ntuples; i++) { j_data = json_object(); if (j_data == NULL) { y_log_message(Y_LOG_LEVEL_ERROR, "Hoel - Error allocating memory for j_data"); PQclear(res); ret = H_ERROR_MEMORY; } else { for(j = 0; ret == H_OK && j < nfields; j++) { char * val = PQgetvalue(res, i, j); if (val == NULL || PQgetisnull(res, i, j)) { json_object_set_new(j_data, PQfname(res, j), json_null()); } else { switch (h_get_type_from_oid(conn, PQftype(res, j))) { case HOEL_COL_TYPE_INT: json_object_set_new(j_data, PQfname(res, j), json_integer(strtoll(PQgetvalue(res, i, j), NULL, 10))); break; case HOEL_COL_TYPE_DOUBLE: json_object_set_new(j_data, PQfname(res, j), json_real(strtod(PQgetvalue(res, i, j), NULL))); break; case HOEL_COL_TYPE_BLOB: json_object_set_new(j_data, PQfname(res, j), json_stringn(PQgetvalue(res, i, j), (size_t)PQgetlength(res, i, j))); break; case HOEL_COL_TYPE_BOOL: if (o_strcasecmp(PQgetvalue(res, i, j), "t") == 0) { json_object_set_new(j_data, PQfname(res, j), json_integer(1)); } else if (o_strcasecmp(PQgetvalue(res, i, j), "f") == 0) { json_object_set_new(j_data, PQfname(res, j), json_integer(0)); } else { json_object_set_new(j_data, PQfname(res, j), json_null()); } break; case HOEL_COL_TYPE_DATE: case HOEL_COL_TYPE_TEXT: default: json_object_set_new(j_data, PQfname(res, j), json_string(PQgetvalue(res, i, j))); break; } } } } json_array_append_new(*j_result, j_data); j_data = NULL; } } PQclear(res); } } pthread_mutex_unlock(&(((struct _h_pgsql *)conn->connection)->lock)); } return ret; } /** * Return the id of the last inserted value * Assuming you use sequences for automatically generated ids */ long long int h_last_insert_id_pgsql(const struct _h_connection * conn) { PGresult *res; long long int int_res = 0; char * str_res, * endptr = NULL; if (pthread_mutex_lock(&(((struct _h_pgsql *)conn->connection)->lock))) { y_log_message(Y_LOG_LEVEL_ERROR, "Error h_last_insert_id - lock error"); } else { res = PQexec(((struct _h_pgsql *)conn->connection)->db_handle, "SELECT lastval()"); if (PQresultStatus(res) != PGRES_TUPLES_OK && PQresultStatus(res) != PGRES_COMMAND_OK) { y_log_message(Y_LOG_LEVEL_ERROR, "Error executing h_last_insert_id"); y_log_message(Y_LOG_LEVEL_DEBUG, "Error message: \"%s\"", PQerrorMessage(((struct _h_pgsql *)conn->connection)->db_handle)); return H_ERROR_QUERY; } if (PQnfields(res) && PQntuples(res)) { str_res = PQgetvalue(res, 0, 0); if (str_res != NULL) { int_res = strtol(str_res, &endptr, 10); if (*endptr != '\0' || endptr == str_res) { y_log_message(Y_LOG_LEVEL_ERROR, "Error h_last_insert_id, returned value can't be converted to numeric"); int_res = 0; } } else { y_log_message(Y_LOG_LEVEL_ERROR, "Error h_last_insert_id, returned value is NULL"); } } else { y_log_message(Y_LOG_LEVEL_ERROR, "Error h_last_insert_id, returned value has no data available"); } PQclear(res); pthread_mutex_unlock(&(((struct _h_pgsql *)conn->connection)->lock)); } return int_res; } #else /** * Dummy functions when Hoel is not built with PostgreSQL */ struct _h_connection * h_connect_pgsql(const char * conninfo) { UNUSED(conninfo); y_log_message(Y_LOG_LEVEL_ERROR, "Hoel was not compiled with PostgreSQL backend"); return NULL; } void h_close_pgsql(struct _h_connection * conn) { UNUSED(conn); y_log_message(Y_LOG_LEVEL_ERROR, "Hoel was not compiled with PostgreSQL backend"); } char * h_escape_string_pgsql(const struct _h_connection * conn, const char * unsafe) { UNUSED(conn); UNUSED(unsafe); y_log_message(Y_LOG_LEVEL_ERROR, "Hoel was not compiled with PostgreSQL backend"); return NULL; } char * h_escape_string_with_quotes_pgsql(const struct _h_connection * conn, const char * unsafe) { UNUSED(conn); UNUSED(unsafe); y_log_message(Y_LOG_LEVEL_ERROR, "Hoel was not compiled with PostgreSQL backend"); return NULL; } long long int h_last_insert_id_pgsql(const struct _h_connection * conn) { UNUSED(conn); y_log_message(Y_LOG_LEVEL_ERROR, "Hoel was not compiled with PostgreSQL backend"); return 0; } int h_execute_query_pgsql(const struct _h_connection * conn, const char * query, struct _h_result * h_result) { UNUSED(conn); UNUSED(query); UNUSED(h_result); y_log_message(Y_LOG_LEVEL_ERROR, "Hoel was not compiled with PostgreSQL backend"); return H_ERROR; } int h_execute_query_json_pgsql(const struct _h_connection * conn, const char * query, json_t ** j_result) { UNUSED(conn); UNUSED(query); UNUSED(j_result); y_log_message(Y_LOG_LEVEL_ERROR, "Hoel was not compiled with PostgreSQL backend"); return H_ERROR; } #endif hoel-1.4.29/src/hoel-simple-json.c000066400000000000000000001031171452453561700166750ustar00rootroot00000000000000/** * * Hoel database abstraction library * * hoel-simple-json.c: hoel simple Json query functions * * Copyright 2015-2020 Nicolas Mora * * 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; * version 2.1 of the License. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU GENERAL PUBLIC LICENSE for more details. * * You should have received a copy of the GNU General Public * License along with this library. If not, see . * */ #include #include #include "hoel.h" #include "h-private.h" static char * h_get_insert_values_from_json_object(const struct _h_connection * conn, json_t * data) { char * new_data = NULL, * escape, * insert_data = NULL, * tmp; const char * key = NULL; json_t * value = NULL, * raw; int i = 0; json_object_foreach((json_t *)data, key, value) { switch (json_typeof(value)) { case JSON_STRING: escape = h_escape_string_with_quotes(conn, json_string_value(value)); if (escape == NULL) { y_log_message(Y_LOG_LEVEL_ERROR, "Hoel/h_get_insert_values_from_json_object - Error escape"); h_free(new_data); new_data = NULL; } else { new_data = o_strdup(escape); h_free(escape); } break; case JSON_INTEGER: new_data = msprintf("%"JSON_INTEGER_FORMAT, json_integer_value(value)); break; case JSON_REAL: new_data = msprintf("%f", json_real_value(value)); break; case JSON_TRUE: new_data = o_strdup("1"); break; case JSON_FALSE: new_data = o_strdup("0"); break; case JSON_NULL: new_data = o_strdup("NULL"); break; case JSON_OBJECT: raw = json_object_get(value, "raw"); if (raw != NULL && json_is_string(raw)) { new_data = o_strdup(json_string_value(raw)); } else { new_data = o_strdup("NULL"); } break; default: tmp = json_dumps(value, JSON_ENCODE_ANY); y_log_message(Y_LOG_LEVEL_ERROR, "Hoel/h_get_insert_values_from_json_object - Error decoding value %s, inserting NULL value", tmp); h_free(tmp); new_data = o_strdup("NULL"); break; } if (new_data == NULL) { y_log_message(Y_LOG_LEVEL_ERROR, "Hoel/h_get_insert_values_from_json_object - Error allocating memory for new_data"); return NULL; } if (i == 0) { insert_data = msprintf("(%s", new_data); if (insert_data == NULL) { y_log_message(Y_LOG_LEVEL_ERROR, "Hoel/h_get_insert_values_from_json_object - Error allocating insert_data"); } i = 1; h_free(new_data); } else { tmp = msprintf("%s,%s", insert_data, new_data); if (tmp == NULL) { y_log_message(Y_LOG_LEVEL_ERROR, "Hoel/h_get_insert_values_from_json_object - Error allocating tmp"); h_free(insert_data); h_free(new_data); return NULL; } h_free(insert_data); h_free(new_data); insert_data = tmp; } } tmp = msprintf("%s)", insert_data); h_free(insert_data); if (tmp == NULL) { y_log_message(Y_LOG_LEVEL_ERROR, "Hoel/h_get_insert_values_from_json_object - Error final allocation for tmp"); } return tmp; } static char * h_get_insert_columns_from_json_object(json_t * data) { char * insert_cols = NULL, * tmp; const char * key = NULL; json_t * value = NULL; int i = 0; json_object_foreach((json_t *)data, key, value) { if (i == 0) { insert_cols = msprintf("%s", key); if (insert_cols == NULL) { y_log_message(Y_LOG_LEVEL_ERROR, "Hoel/h_get_insert_columns_from_json_object - Error allocating insert_cols"); return NULL; } i = 1; } else { tmp = msprintf("%s,%s", insert_cols, key); h_free(insert_cols); if (tmp == NULL) { y_log_message(Y_LOG_LEVEL_ERROR, "Hoel/h_get_insert_columns_from_json_object - Error allocating insert_cols"); return NULL; } insert_cols = tmp; } } return insert_cols; } /** * Builds an insert query from a json object and a table name * Returned value must be h_free'd after use */ static char * h_get_insert_query_from_json_object(const struct _h_connection * conn, json_t * data, const char * table) { char * to_return = NULL, * insert_cols, * insert_data; insert_cols = h_get_insert_columns_from_json_object(data); insert_data = h_get_insert_values_from_json_object(conn, data); if (insert_cols == NULL || insert_data == NULL) { y_log_message(Y_LOG_LEVEL_ERROR, "Hoel/h_get_insert_query_from_json_object - Error h_get_insert_columns_from_json_object or h_get_insert_values_from_json_object"); } else { to_return = msprintf("INSERT INTO %s (%s) VALUES %s", table, insert_cols, insert_data); } h_free(insert_cols); h_free(insert_data); if (to_return == NULL) { y_log_message(Y_LOG_LEVEL_ERROR, "Hoel/h_get_insert_query_from_json_object - Error allocating memory for h_get_insert_query_from_json_object"); } return to_return; } /** * Builds an insert query from a json object and a table name * Returned value must be h_free'd after use */ static char * h_get_insert_query_from_json_array(const struct _h_connection * conn, json_t * j_array, const char * table) { json_t * j_row = NULL; size_t index = 0; char * to_return = NULL, * insert_cols, * insert_data, * tmp; json_array_foreach(j_array, index, j_row) { insert_data = h_get_insert_values_from_json_object(conn, j_row); if (!index) { insert_cols = h_get_insert_columns_from_json_object(j_row); to_return = msprintf("INSERT INTO %s (%s) VALUES %s", table, insert_cols, insert_data); h_free(insert_cols); if (to_return == NULL) { y_log_message(Y_LOG_LEVEL_ERROR, "Hoel/h_get_insert_query_from_json_array - Error allocating to_return"); h_free(insert_data); return NULL; } } else { tmp = msprintf("%s,%s", to_return, insert_data); if (tmp == NULL) { y_log_message(Y_LOG_LEVEL_ERROR, "Hoel/h_get_insert_query_from_json_array - Error allocating tmp"); h_free(insert_data); return NULL; } h_free(to_return); to_return = tmp; } h_free(insert_data); } return to_return; } /** * Generates a where clause based on a json object * the where object is a simple object like * { * col1: "value1", * col2: "value2" * } * the output is a WHERE query will use only '=' and 'AND' keywords * col1='value1' AND col2='value2' * return a char * containing the WHERE clause, NULL on error * the returned value must be h_free'd after use */ static char * h_get_where_clause_from_json_object(const struct _h_connection * conn, const json_t * where) { const char * key = NULL; json_t * value = NULL, * ope, * val, * j_element; char * where_clause = NULL, * dump = NULL, * escape = NULL, * tmp, * clause = NULL, * dump2 = NULL; int i = 0; size_t index = 0; if (conn == NULL) { y_log_message(Y_LOG_LEVEL_DEBUG, "Hoel/h_get_where_clause_from_json_object - Error conn is NULL"); return NULL; } else if (where == NULL || (json_is_object(where) && json_object_size(where) == 0)) { return o_strdup("1=1"); } else { json_object_foreach((json_t *)where, key, value) { if (!json_is_string(value) && !json_is_real(value) && !json_is_integer(value) && !json_is_object(value) && !json_is_null(value)) { dump = json_dumps(value, JSON_ENCODE_ANY); y_log_message(Y_LOG_LEVEL_DEBUG, "Hoel/h_get_where_clause_from_json_object - Error where value is invalid: %s", dump); h_free(dump); return NULL; } else { if (json_is_object(value)) { ope = json_object_get(value, "operator"); val = json_object_get(value, "value"); if (ope == NULL || !json_is_string(ope) || (val == NULL && 0 != o_strcasecmp("NOT NULL", json_string_value(ope))) || (!json_is_string(val) && !json_is_real(val) && !json_is_integer(val) && 0 != o_strcasecmp("NOT NULL", json_string_value(ope)) && 0 != o_strcasecmp("IN", json_string_value(ope)))) { dump = json_dumps(val, JSON_ENCODE_ANY); dump2 = json_dumps(ope, JSON_ENCODE_ANY); y_log_message(Y_LOG_LEVEL_DEBUG, "Hoel/h_get_where_clause_from_json_object - Error where object value is invalid: %s %s", dump, dump2); h_free(dump); h_free(dump2); h_free(where_clause); return NULL; } else { if (0 == o_strcasecmp("NOT NULL", json_string_value(ope))) { clause = msprintf("%s IS NOT NULL", key); } else if (0 == o_strcasecmp("raw", json_string_value(ope)) && json_is_string(val)) { clause = msprintf("%s %s", key, json_string_value(val)); } else if (0 == o_strcasecmp("IN", json_string_value(ope))) { if (json_is_array(val) && json_array_size(val) > 0) { clause = NULL, tmp = NULL; json_array_foreach(val, index, j_element) { if (!json_is_string(j_element) && !json_is_real(j_element) && !json_is_integer(j_element)) { h_free(clause); h_free(where_clause); y_log_message(Y_LOG_LEVEL_ERROR, "Hoel - Error element value in IN statement array must be real, integer or string"); return NULL; } else { if (json_is_string(j_element)) { escape = h_escape_string_with_quotes(conn, json_string_value(j_element)); if (escape == NULL) { y_log_message(Y_LOG_LEVEL_ERROR, "Hoel - Error escape"); h_free(clause); h_free(where_clause); return NULL; } dump = msprintf("%s", escape); h_free(escape); } else if (json_is_real(j_element)) { dump = msprintf("%f", json_real_value(j_element)); } else { dump = msprintf("%" JSON_INTEGER_FORMAT, json_integer_value(j_element)); } if (clause == NULL) { clause = msprintf("%s IN (%s", key, dump); } else { tmp = msprintf("%s,%s", clause, dump); h_free(clause); clause = tmp; } h_free(dump); } } tmp = msprintf("%s)", clause); h_free(clause); clause = tmp; } else { h_free(where_clause); y_log_message(Y_LOG_LEVEL_ERROR, "Hoel - Error value in IN statement must be a non empty JSON array"); return NULL; } } else { if (json_is_real(val)) { clause = msprintf("%s %s %f", key, json_string_value(ope), json_real_value(val)); } else if (json_is_integer(val)) { clause = msprintf("%s %s %" JSON_INTEGER_FORMAT, key, json_string_value(ope), json_integer_value(val)); } else { escape = h_escape_string_with_quotes(conn, json_string_value(val)); if (escape == NULL) { y_log_message(Y_LOG_LEVEL_ERROR, "Hoel - Error escape"); h_free(where_clause); return NULL; } clause = msprintf("%s %s %s", key, json_string_value(ope), escape); h_free(escape); } } if (clause == NULL) { y_log_message(Y_LOG_LEVEL_ERROR, "Hoel - Error allocating memory for clause"); h_free(where_clause); return NULL; } } } else { if (json_is_null(value)) { clause = msprintf("%s IS NULL", key); } else if (json_is_string(value)) { escape = h_escape_string_with_quotes(conn, json_string_value(value)); if (escape == NULL) { y_log_message(Y_LOG_LEVEL_ERROR, "Hoel - Error escape"); h_free(where_clause); return NULL; } clause = msprintf("%s=%s", key, escape); h_free(escape); } else if (json_is_integer(value)) { clause = msprintf("%s='%"JSON_INTEGER_FORMAT"'", key, json_integer_value(value)); } else if (json_is_real(value)) { clause = msprintf("%s='%f'", key, json_real_value(value)); } else if (json_is_true(value)) { clause = msprintf("%s=1"); } else if (json_is_false(value)) { clause = msprintf("%s=0"); } if (clause == NULL) { y_log_message(Y_LOG_LEVEL_ERROR, "Hoel - Error allocating memory for clause"); h_free(where_clause); return NULL; } } if (i == 0) { where_clause = o_strdup(clause); if (where_clause == NULL) { y_log_message(Y_LOG_LEVEL_DEBUG, "Hoel/h_get_where_clause_from_json_object - Error where_clause"); h_free(clause); h_free(where_clause); return NULL; } h_free(clause); i = 1; } else { tmp = msprintf("%s AND %s", where_clause, clause); h_free(where_clause); if (tmp == NULL) { y_log_message(Y_LOG_LEVEL_DEBUG, "Hoel/h_get_where_clause_from_json_object - Error tmp where_clause"); h_free(clause); h_free(where_clause); return NULL; } h_free(clause); where_clause = tmp; } } } return where_clause; } } /** * Generates a set clause based on a json object * the where object is a simple object like * { * col1: "value1", * col2: "value2" * } * the output is a WHERE query will use only '=' and 'AND' keywords * col1='value1', col2='value2' * return a char * containing the WHERE clause, NULL on error * the returned value must be h_free'd after use */ static char * h_get_set_clause_from_json_object(const struct _h_connection * conn, const json_t * set) { const char * key = NULL; json_t * value = NULL, * raw; char * where_clause = NULL, * escape = NULL, * tmp; int i = 0; if (conn == NULL || set == NULL || !json_is_object(set)) { y_log_message(Y_LOG_LEVEL_DEBUG, "Hoel/h_get_set_clause_from_json_object - Error null input parameters"); return NULL; } else { json_object_foreach((json_t *)set, key, value) { if (!json_is_string(value) && !json_is_real(value) && !json_is_integer(value) && !json_is_null(value) && !json_is_object(value)) { tmp = json_dumps(value, JSON_ENCODE_ANY); y_log_message(Y_LOG_LEVEL_DEBUG, "Hoel/h_get_set_clause_from_json_object - Error value invalid: %s", tmp); h_free(tmp); h_free(where_clause); return NULL; } else { if (json_is_string(value)) { tmp = h_escape_string_with_quotes(conn, json_string_value(value)); escape = msprintf("%s", tmp); h_free(tmp); } else if (json_is_real(value)) { escape = msprintf("%f", json_real_value(value)); } else if (json_is_integer(value)) { escape = msprintf("%" JSON_INTEGER_FORMAT, json_integer_value(value)); } else if (json_is_object(value)) { raw = json_object_get(value, "raw"); if (raw != NULL && json_is_string(raw)) { escape = o_strdup(json_string_value(raw)); } else { escape = o_strdup("NULL"); } } else { escape = o_strdup(""); } if (escape == NULL) { y_log_message(Y_LOG_LEVEL_ERROR, "Hoel - Error escape"); return NULL; } if (i == 0) { if (!json_is_null(value)) { where_clause = msprintf("%s=%s", key, escape); } else { where_clause = msprintf("%s=NULL", key); } if (where_clause == NULL) { y_log_message(Y_LOG_LEVEL_DEBUG, "Hoel/h_get_set_clause_from_json_object - Error where_clause"); return NULL; } i = 1; } else { if (!json_is_null(value)) { tmp = msprintf("%s, %s=%s", where_clause, key, escape); } else { tmp = msprintf("%s, %s=NULL", where_clause, key); } h_free(where_clause); if (tmp == NULL) { y_log_message(Y_LOG_LEVEL_DEBUG, "Hoel/h_get_set_clause_from_json_object - Error tmp where_clause"); return NULL; } where_clause = tmp; } h_free(escape); } } return where_clause; } } /** * h_select * Execute a select query * Uses a json_t * parameter for the query parameters * Store the result of the query in j_result if specified. j_result must be decref'd after use * Duplicate the generated query in generated_query if specified, must be h_free'd after use * return H_OK on success */ int h_select(const struct _h_connection * conn, const json_t * j_query, json_t ** j_result, char ** generated_query) { const char * table; const json_t * cols, * where, * order_by, * group_by; json_int_t limit, offset; char * query = NULL, * columns = NULL, * where_clause = NULL, * tmp = NULL, * str_where_limit = NULL, * str_order_by = NULL, * str_group_by = NULL; const char * col; size_t index = 0; json_t * value; int res; if (conn == NULL || j_result == NULL || j_query == NULL || !json_is_object(j_query) || json_object_get(j_query, "table") == NULL || !json_is_string(json_object_get(j_query, "table")) || o_strnullempty(json_string_value(json_object_get(j_query, "table")))) { y_log_message(Y_LOG_LEVEL_DEBUG, "Hoel/h_select Error invalid input parameters"); return H_ERROR_PARAMS; } table = json_string_value((const json_t *)json_object_get(j_query, "table")); cols = json_object_get(j_query, "columns"); where = json_object_get(j_query, "where"); order_by = json_object_get(j_query, "order_by"); group_by = json_object_get(j_query, "group_by"); limit = json_is_integer(json_object_get(j_query, "limit"))?json_integer_value(json_object_get(j_query, "limit")):0; offset = json_is_integer(json_object_get(j_query, "offset"))?json_integer_value(json_object_get(j_query, "offset")):0; where_clause = h_get_where_clause_from_json_object(conn, (json_t *)where); if (where_clause == NULL) { y_log_message(Y_LOG_LEVEL_DEBUG, "Hoel/h_select Error where_clause construction"); return H_ERROR_PARAMS; } if (cols == NULL) { columns = o_strdup("*"); } else if (json_is_array(cols)) { json_array_foreach(cols, index, value) { if (json_is_string(value)) { col = json_string_value(value); if (col == NULL) { y_log_message(Y_LOG_LEVEL_DEBUG, "Hoel/h_select Error col"); h_free(where_clause); h_free(columns); return H_ERROR_MEMORY; } } else { y_log_message(Y_LOG_LEVEL_DEBUG, "Hoel/h_select Error column not string"); h_free(where_clause); return H_ERROR_PARAMS; } if (index == 0) { columns = o_strdup(col); if (columns == NULL) { y_log_message(Y_LOG_LEVEL_DEBUG, "Hoel/h_select Error allocating columns"); h_free(where_clause); return H_ERROR_MEMORY; } } else { tmp = msprintf("%s, %s", columns, col); if (tmp == NULL) { y_log_message(Y_LOG_LEVEL_DEBUG, "Hoel/h_select Error allocating clause"); h_free(where_clause); h_free(columns); return H_ERROR_MEMORY; } h_free(columns); columns = tmp; } } } else { y_log_message(Y_LOG_LEVEL_DEBUG, "Hoel/h_select Error cols not array"); h_free(where_clause); return H_ERROR_PARAMS; } if (columns == NULL) { y_log_message(Y_LOG_LEVEL_ERROR, "Hoel - Error allocating memory for columns"); h_free(where_clause); return H_ERROR_MEMORY; } if (limit > 0) { if (offset > 0) { str_where_limit = msprintf(" LIMIT %" JSON_INTEGER_FORMAT " OFFSET %" JSON_INTEGER_FORMAT, limit, offset); } else { str_where_limit = msprintf(" LIMIT %" JSON_INTEGER_FORMAT, limit); } } else { str_where_limit = o_strdup(""); } if (str_where_limit == NULL) { y_log_message(Y_LOG_LEVEL_ERROR, "Hoel - Error allocating memory for str_where_limit"); h_free(columns); h_free(where_clause); return H_ERROR_MEMORY; } if (order_by != NULL && json_is_string(order_by) && !o_strnullempty(json_string_value(order_by))) { str_order_by = msprintf(" ORDER BY %s", json_string_value(order_by)); } else { str_order_by = o_strdup(""); } if (str_order_by == NULL) { y_log_message(Y_LOG_LEVEL_ERROR, "Hoel - Error allocating memory for str_order_by"); h_free(columns); h_free(where_clause); h_free(str_where_limit); return H_ERROR_MEMORY; } if (group_by != NULL && json_is_string(group_by) && !o_strnullempty(json_string_value(group_by))) { str_group_by = msprintf(" GROUP BY %s", json_string_value(group_by)); } else { str_group_by = o_strdup(""); } if (str_group_by == NULL) { y_log_message(Y_LOG_LEVEL_ERROR, "Hoel - Error allocating memory for str_order_by"); h_free(columns); h_free(where_clause); h_free(str_where_limit); h_free(str_order_by); return H_ERROR_MEMORY; } query = msprintf("SELECT %s FROM %s WHERE %s%s%s%s", columns, table, where_clause, str_group_by, str_order_by, str_where_limit); h_free(columns); h_free(where_clause); h_free(str_where_limit); h_free(str_order_by); h_free(str_group_by); if (query == NULL) { y_log_message(Y_LOG_LEVEL_DEBUG, "Hoel/h_select Error allocating query"); return H_ERROR_MEMORY; } else { if (generated_query != NULL) { *generated_query = o_strdup(query); } res = h_query_select_json(conn, query, j_result); h_free(query); return res; } } /** * h_insert * Execute an insert query * Uses a json_t * parameter for the query parameters * Duplicate the generated query in generated_query if specified, must be h_free'd after use * return H_OK on success */ int h_insert(const struct _h_connection * conn, const json_t * j_query, char ** generated_query) { const char * table; char * query; json_t * values; int res; if (conn != NULL && j_query != NULL && json_is_object(j_query) && json_is_string(json_object_get(j_query, "table")) && (json_is_object(json_object_get(j_query, "values")) || json_is_array(json_object_get(j_query, "values")))) { /* Construct query */ table = json_string_value((const json_t *)json_object_get(j_query, "table")); values = json_object_get(j_query, "values"); switch (json_typeof(values)) { case JSON_OBJECT: query = h_get_insert_query_from_json_object(conn, values, table); if (query != NULL) { if (generated_query != NULL) { *generated_query = o_strdup(query); } res = h_query_insert(conn, query); h_free(query); if (res != H_OK) { y_log_message(Y_LOG_LEVEL_DEBUG, "Hoel/h_insert - Error executing query (1)"); return H_ERROR_QUERY; } return res; } else { y_log_message(Y_LOG_LEVEL_DEBUG, "Hoel/h_insert - Error allocating query (1)"); return H_ERROR_MEMORY; } break; case JSON_ARRAY: if (json_array_size(values)) { query = h_get_insert_query_from_json_array(conn, values, table); if (query != NULL) { if (generated_query != NULL) { /* Export just the first query */ *generated_query = o_strdup(query); } res = h_query_insert(conn, query); h_free(query); if (res != H_OK) { y_log_message(Y_LOG_LEVEL_DEBUG, "Hoel/h_insert - Error executing query (2)"); return H_ERROR_QUERY; } return res; } else { y_log_message(Y_LOG_LEVEL_DEBUG, "Hoel/h_insert - Error allocating query (2)"); return H_ERROR_MEMORY; } } else { y_log_message(Y_LOG_LEVEL_DEBUG, "Hoel/h_insert - Error no values to insert"); return H_ERROR_QUERY; } break; default: y_log_message(Y_LOG_LEVEL_DEBUG, "Hoel/h_insert - Error unknown object type for values"); return H_ERROR_PARAMS; break; } } else { y_log_message(Y_LOG_LEVEL_DEBUG, "Hoel/h_insert - Error null input parameters"); return H_ERROR_PARAMS; } } /** * h_last_insert_id * return the id of the last inserted value * return a pointer to json_t * on success, NULL otherwise. * The returned value is of type JSON_INTEGER */ json_t * h_last_insert_id(const struct _h_connection * conn) { json_t * j_data = NULL; if (conn != NULL && conn->connection != NULL) { if (0) { /* Not happening */ #ifdef _HOEL_SQLITE } else if (conn->type == HOEL_DB_TYPE_SQLITE) { long long int last_id = h_last_insert_id_sqlite(conn); if (last_id > 0) { j_data = json_integer(last_id); } #endif #ifdef _HOEL_MARIADB } else if (conn->type == HOEL_DB_TYPE_MARIADB) { long long int last_id = h_last_insert_id_mariadb(conn); if (last_id > 0) { j_data = json_integer(last_id); } #endif #ifdef _HOEL_PGSQL } else if (conn->type == HOEL_DB_TYPE_PGSQL) { long long int last_id = h_last_insert_id_pgsql(conn); if (last_id > 0) { j_data = json_integer(last_id); } #endif } } return j_data; } /** * h_update * Execute an update query * Uses a json_t * parameter for the query parameters * Duplicate the generated query in generated_query if specified, must be h_free'd after use * return H_OK on success */ int h_update(const struct _h_connection * conn, const json_t * j_query, char ** generated_query) { char * set_clause, * where_clause, * query; const char * table; int res; json_t * set, * where; if (j_query == NULL || !json_is_object(j_query) || !json_is_string(json_object_get(j_query, "table")) || !json_is_object(json_object_get(j_query, "set"))) { y_log_message(Y_LOG_LEVEL_DEBUG, "Hoel/h_update - Error invalid input parameters"); return H_ERROR_PARAMS; } table = json_string_value((const json_t *)json_object_get(j_query, "table")); set = json_object_get(j_query, "set"); set_clause = h_get_set_clause_from_json_object(conn, set); if (set_clause == NULL) { y_log_message(Y_LOG_LEVEL_DEBUG, "Hoel/h_update - Error generating set clause"); return H_ERROR_PARAMS; } if (json_is_object(json_object_get(j_query, "where")) && json_object_size(json_object_get(j_query, "where")) > 0) { where = json_object_get(j_query, "where"); where_clause = h_get_where_clause_from_json_object(conn, where); query = msprintf("UPDATE %s SET %s WHERE %s", table, set_clause, where_clause); h_free(where_clause); } else { query = msprintf("UPDATE %s SET %s", table, set_clause); } h_free(set_clause); if (query == NULL) { y_log_message(Y_LOG_LEVEL_DEBUG, "Hoel/h_update - Error allocating query"); return H_ERROR_MEMORY; } if (generated_query != NULL) { *generated_query = o_strdup(query); } res = h_query_update(conn, query); h_free(query); return res; } /** * h_delete * Execute a delete query * Uses a json_t * parameter for the query parameters * Duplicate the generated query in generated_query if specified, must be h_free'd after use * return H_OK on success */ int h_delete(const struct _h_connection * conn, const json_t * j_query, char ** generated_query) { char * where_clause, * query; const char * table; int res; json_t * where; if (j_query == NULL || !json_is_object(j_query) || !json_is_string(json_object_get(j_query, "table"))) { y_log_message(Y_LOG_LEVEL_DEBUG, "Hoel/h_delete - Error invalid input parameters"); return H_ERROR_PARAMS; } table = json_string_value((json_t *)json_object_get(j_query, "table")); if (json_is_object(json_object_get(j_query, "where")) && json_object_size(json_object_get(j_query, "where")) > 0) { where = json_object_get(j_query, "where"); where_clause = h_get_where_clause_from_json_object(conn, where); if (where_clause == NULL) { y_log_message(Y_LOG_LEVEL_DEBUG, "Hoel/h_delete - Error invalid input parameters"); return H_ERROR_PARAMS; } query = msprintf("DELETE FROM %s WHERE %s", table, where_clause); h_free(where_clause); } else { query = msprintf("DELETE FROM %s", table); } if (query == NULL) { y_log_message(Y_LOG_LEVEL_DEBUG, "Hoel/h_delete - Error allocating query"); return H_ERROR_MEMORY; } if (generated_query != NULL) { *generated_query = o_strdup(query); } res = h_query_delete(conn, query); h_free(query); return res; } /** * h_build_where_clause * Generates a where clause based on the pattern and the values given * return a heap-allocated string * returned value must be h_free'd after use */ char * h_build_where_clause(const struct _h_connection * conn, const char * pattern, ...) { char * where_clause = NULL, * pattern_pos = NULL, * escaped = NULL, * prefix = NULL; const char * pattern_save = pattern, * unescaped = NULL; int has_error = 0; json_t * j_value = NULL; json_int_t i_value = 0; double d_value = 0.0; va_list vl; size_t prefix_len; if (conn == NULL || o_strnullempty(pattern)) { y_log_message(Y_LOG_LEVEL_DEBUG, "Hoel/h_build_where_clause - Error invalid input parameters"); return NULL; } va_start(vl, pattern); while ((pattern_pos = o_strchr(pattern_save, '%')) != NULL && !has_error) { if (*(pattern_pos+1) != '\0') { prefix_len = (size_t)(pattern_pos - pattern_save); prefix = o_strndup(pattern_save, prefix_len); where_clause = mstrcatf(where_clause, "%s", prefix); h_free(prefix); pattern_save += prefix_len; switch (*(pattern_pos+1)) { case 's': unescaped = va_arg(vl, const char *); if ((escaped = h_escape_string_with_quotes(conn, unescaped)) != NULL) { if ((where_clause = mstrcatf(where_clause, "%s", escaped)) != NULL) { h_free(escaped); pattern_save += 2; } else { has_error = 1; } } else { has_error = 1; } break; case 'S': unescaped = va_arg(vl, const char *); if ((escaped = h_escape_string(conn, unescaped)) != NULL) { if ((where_clause = mstrcatf(where_clause, "%s", escaped)) != NULL) { h_free(escaped); pattern_save += 2; } else { has_error = 1; } } else { has_error = 1; } break; case 'c': unescaped = va_arg(vl, const char *); if ((where_clause = mstrcatf(where_clause, "'%s'", unescaped)) != NULL) { pattern_save += 2; } else { has_error = 1; } break; case 'C': unescaped = va_arg(vl, const char *); if ((where_clause = mstrcatf(where_clause, "%s", unescaped)) != NULL) { pattern_save += 2; } else { has_error = 1; } break; case 'd': i_value = va_arg(vl, json_int_t); if ((where_clause = mstrcatf(where_clause, "%"JSON_INTEGER_FORMAT, i_value)) != NULL) { pattern_save += 2; } else { has_error = 1; } break; case 'f': d_value = va_arg(vl, double); if ((where_clause = mstrcatf(where_clause, "%f", d_value)) != NULL) { pattern_save += 2; } else { has_error = 1; } break; case 'j': j_value = va_arg(vl, json_t *); if (j_value != NULL) { if (json_is_string(j_value)) { if ((escaped = h_escape_string_with_quotes(conn, json_string_value(j_value))) != NULL) { if ((where_clause = mstrcatf(where_clause, "%s", escaped)) != NULL) { h_free(escaped); pattern_save += 2; } else { has_error = 1; } } else { has_error = 1; } } else if (json_is_integer(j_value)) { if ((where_clause = mstrcatf(where_clause, "%"JSON_INTEGER_FORMAT, json_integer_value(j_value))) != NULL) { pattern_save += 2; } else { has_error = 1; } } else if (json_is_real(j_value)) { if ((where_clause = mstrcatf(where_clause, "%f", json_real_value(j_value))) != NULL) { pattern_save += 2; } else { has_error = 1; } } else { has_error = 1; } } else { has_error = 1; } break; case '%': if ((where_clause = mstrcatf(where_clause, "%%")) != NULL) { pattern_save += 2; } else { has_error = 1; } break; default: has_error = 1; break; } escaped = NULL; j_value = NULL; } else { has_error = 1; } } va_end(vl); if (!has_error) { where_clause = mstrcatf(where_clause, "%s", pattern_save); } else { h_free(where_clause); where_clause = NULL; } return where_clause; } hoel-1.4.29/src/hoel-sqlite.c000066400000000000000000000315351452453561700157420ustar00rootroot00000000000000/** * * Hoel database abstraction library * * hoel-sqlite.c: Sqlite3 specific functions * * Copyright 2015-2020 Nicolas Mora * * 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; * version 2.1 of the License. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU GENERAL PUBLIC LICENSE for more details. * * You should have received a copy of the GNU General Public * License along with this library. If not, see . * */ #include "hoel.h" #include "h-private.h" #ifdef _HOEL_SQLITE #include #include /** * SQLite handle */ struct _h_sqlite { sqlite3 * db_handle; }; /** * h_connect_sqlite * Opens a database connection to a sqlite3 db file * return pointer to a struct _h_connection * on sucess, NULL on error */ struct _h_connection * h_connect_sqlite(const char * db_path) { struct _h_connection * conn = NULL; o_malloc_t malloc_fn; o_free_t free_fn; o_get_alloc_funcs(&malloc_fn, NULL, &free_fn); json_set_alloc_funcs((json_malloc_t)malloc_fn, (json_free_t)free_fn); if (db_path != NULL) { conn = o_malloc(sizeof(struct _h_connection)); if (conn == NULL) { y_log_message(Y_LOG_LEVEL_ERROR, "h_connect_sqlite - Error allocating resources"); return NULL; } conn->type = HOEL_DB_TYPE_SQLITE; conn->connection = o_malloc(sizeof(struct _h_sqlite)); if (conn->connection == NULL) { y_log_message(Y_LOG_LEVEL_ERROR, "h_connect_sqlite - Error allocating resources"); h_free(conn); return NULL; } if (sqlite3_open_v2(db_path, &((struct _h_sqlite *)conn->connection)->db_handle, SQLITE_OPEN_READWRITE|SQLITE_OPEN_FULLMUTEX, NULL) != SQLITE_OK) { y_log_message(Y_LOG_LEVEL_ERROR, "Error connecting to sqlite3 database, path: %s", db_path); y_log_message(Y_LOG_LEVEL_DEBUG, "Error code: %d, message: \"%s\"", sqlite3_errcode(((struct _h_sqlite *)conn->connection)->db_handle), sqlite3_errmsg(((struct _h_sqlite *)conn->connection)->db_handle)); sqlite3_close(((struct _h_sqlite *)conn->connection)->db_handle); h_free(conn->connection); h_free(conn); return NULL; } else { return conn; } } return conn; } /** * close a sqlite3 connection */ void h_close_sqlite(struct _h_connection * conn) { sqlite3_close(((struct _h_sqlite *)conn->connection)->db_handle); } /** * escape a string * returned value must be free'd after use */ char * h_escape_string_sqlite(const struct _h_connection * conn, const char * unsafe) { char * tmp = sqlite3_mprintf("%q", unsafe), * ret; if (tmp == NULL) { y_log_message(Y_LOG_LEVEL_ERROR, "Error escaping string: %s", unsafe); y_log_message(Y_LOG_LEVEL_DEBUG, "Error code: %d, message: \"%s\"", sqlite3_errcode(((struct _h_sqlite *)conn->connection)->db_handle), sqlite3_errmsg(((struct _h_sqlite *)conn->connection)->db_handle)); return NULL; } ret = o_strdup(tmp); sqlite3_free(tmp); if (ret == NULL) { y_log_message(Y_LOG_LEVEL_ERROR, "Error escaping (o_strdup)"); } return ret; } /** * Escapes a string and returns it ready to be inserted in the query * returned value must be free'd after use */ char * h_escape_string_with_quotes_sqlite(const struct _h_connection * conn, const char * unsafe) { char * tmp = h_escape_string_sqlite(conn, unsafe), * ret; if (tmp == NULL) { return NULL; } ret = msprintf("'%s'", tmp); h_free(tmp); if (ret == NULL) { y_log_message(Y_LOG_LEVEL_ERROR, "Error escaping with quotes (o_strdup)"); } return ret; } /** * Return the id of the last inserted value */ long long int h_last_insert_id_sqlite(const struct _h_connection * conn) { return sqlite3_last_insert_rowid(((struct _h_sqlite *)conn->connection)->db_handle); } /** * h_select_query_sqlite * Execute a select query on a sqlite connection, set the result structure with the returned values * Should not be executed by the user because all parameters are supposed to be correct * if result is NULL, the query is executed but no value will be returned * Useful for SELECT statements * return H_OK on success */ int h_select_query_sqlite(const struct _h_connection * conn, const char * query, struct _h_result * result) { sqlite3_stmt *stmt; int sql_result, row_result, nb_columns, col, row, res; struct _h_data * data = NULL, * cur_row = NULL; sql_result = sqlite3_prepare_v2(((struct _h_sqlite *)conn->connection)->db_handle, query, (int)o_strlen(query)+1, &stmt, NULL); if (sql_result == SQLITE_OK) { nb_columns = sqlite3_column_count(stmt); row = 0; if (result != NULL) { row_result = sqlite3_step(stmt); /* Filling result object with results in array format */ result->nb_rows = 0; result->nb_columns = (unsigned int)nb_columns; result->data = NULL; while (row_result == SQLITE_ROW) { cur_row = NULL; for (col = 0; col < nb_columns; col++) { data = NULL; switch (sqlite3_column_type(stmt, col)) { case SQLITE_INTEGER: data = h_new_data_int(sqlite3_column_int64(stmt, col)); break; case SQLITE_FLOAT: data = h_new_data_double(sqlite3_column_double(stmt, col)); break; case SQLITE_BLOB: data = h_new_data_blob(sqlite3_column_blob(stmt, col), (size_t)sqlite3_column_bytes(stmt, col)); break; case SQLITE3_TEXT: data = h_new_data_text((char*)sqlite3_column_text(stmt, col), (size_t)sqlite3_column_bytes(stmt, col)); break; case SQLITE_NULL: data = h_new_data_null(); default: break; } if (data == NULL) { sqlite3_finalize(stmt); h_clean_data_full(data); return H_ERROR_MEMORY; } res = h_row_add_data(&cur_row, data, col); h_clean_data_full(data); if (res != H_OK) { sqlite3_finalize(stmt); return res; } } res = h_result_add_row(result, cur_row, row); cur_row = NULL; if (res != H_OK) { sqlite3_finalize(stmt); return res; } row_result = sqlite3_step(stmt); row++; } } sqlite3_finalize(stmt); return H_OK; } else { y_log_message(Y_LOG_LEVEL_ERROR, "Error executing sql query"); y_log_message(Y_LOG_LEVEL_DEBUG, "Error code: %d, message: \"%s\"", sqlite3_errcode(((struct _h_sqlite *)conn->connection)->db_handle), sqlite3_errmsg(((struct _h_sqlite *)conn->connection)->db_handle)); y_log_message(Y_LOG_LEVEL_DEBUG, "Query: \"%s\"", query); sqlite3_finalize(stmt); return H_ERROR_QUERY; } } /** * h_execute_query_sqlite * Execute a query on a sqlite connection * This is an internal function, you should use h_exec_query instead * Should not be executed by the user because all parameters are supposed to be correct * No result is returned, useful for single INSERT, UPDATE or DELETE statements * @param conn the connection to the database * @param query the SQL query to execute * @return H_OK on success */ int h_execute_query_sqlite(const struct _h_connection * conn, const char * query) { if (sqlite3_exec(((struct _h_sqlite *)conn->connection)->db_handle, query, NULL, NULL, NULL) == SQLITE_OK) { return H_OK; } else { y_log_message(Y_LOG_LEVEL_ERROR, "Error executing sql query"); y_log_message(Y_LOG_LEVEL_DEBUG, "Error code: %d, message: \"%s\"", sqlite3_errcode(((struct _h_sqlite *)conn->connection)->db_handle), sqlite3_errmsg(((struct _h_sqlite *)conn->connection)->db_handle)); y_log_message(Y_LOG_LEVEL_DEBUG, "Query: \"%s\"", query); return H_ERROR_QUERY; } } /** * h_exec_query_sqlite * legacy function name, didn't realize the typo until now... * redirect to h_execute_query_sqlite * @param conn the connection to the database * @param query the SQL query to execute * @return H_OK on success */ int h_exec_query_sqlite(const struct _h_connection * conn, const char * query) { return h_execute_query_sqlite(conn, query); } /** * h_execute_query_json_sqlite * Execute a query on a sqlite connection, set the returned values in the json result * Should not be executed by the user because all parameters are supposed to be correct * return H_OK on success */ int h_execute_query_json_sqlite(const struct _h_connection * conn, const char * query, json_t ** j_result) { sqlite3_stmt *stmt; int sql_result, row_result, nb_columns, col; json_t * j_data; if (j_result == NULL) { return H_ERROR_PARAMS; } sql_result = sqlite3_prepare_v2(((struct _h_sqlite *)conn->connection)->db_handle, query, (int)o_strlen(query)+1, &stmt, NULL); if (sql_result == SQLITE_OK) { nb_columns = sqlite3_column_count(stmt); /* Filling j_result with results in json format */ *j_result = json_array(); if (*j_result == NULL) { y_log_message(Y_LOG_LEVEL_ERROR, "Hoel - Error allocating memory for *j_result"); sqlite3_finalize(stmt); return H_ERROR_MEMORY; } row_result = sqlite3_step(stmt); while (row_result == SQLITE_ROW) { j_data = json_object(); if (j_data == NULL) { y_log_message(Y_LOG_LEVEL_ERROR, "Hoel - Error allocating memory for j_data"); json_decref(*j_result); return H_ERROR_MEMORY; } for (col = 0; col < nb_columns; col++) { switch (sqlite3_column_type(stmt, col)) { case SQLITE_INTEGER: json_object_set_new(j_data, sqlite3_column_name(stmt, col), json_integer(sqlite3_column_int64(stmt, col))); break; case SQLITE_FLOAT: json_object_set_new(j_data, sqlite3_column_name(stmt, col), json_real(sqlite3_column_double(stmt, col))); break; case SQLITE_BLOB: json_object_set_new(j_data, sqlite3_column_name(stmt, col), json_stringn(sqlite3_column_blob(stmt, col), (size_t)sqlite3_column_bytes(stmt, col))); break; case SQLITE3_TEXT: json_object_set_new(j_data, sqlite3_column_name(stmt, col), json_string((char*)sqlite3_column_text(stmt, col))); break; case SQLITE_NULL: json_object_set_new(j_data, sqlite3_column_name(stmt, col), json_null()); default: break; } } json_array_append_new(*j_result, j_data); j_data = NULL; row_result = sqlite3_step(stmt); } sqlite3_finalize(stmt); return H_OK; } else { y_log_message(Y_LOG_LEVEL_ERROR, "Error executing sql query"); y_log_message(Y_LOG_LEVEL_DEBUG, "Error code: %d, message: \"%s\"", sqlite3_errcode(((struct _h_sqlite *)conn->connection)->db_handle), sqlite3_errmsg(((struct _h_sqlite *)conn->connection)->db_handle)); y_log_message(Y_LOG_LEVEL_DEBUG, "Query: \"%s\"", query); sqlite3_finalize(stmt); return H_ERROR_QUERY; } } #else /** * Dummy functions when Hoel is not built with SQLite */ struct _h_connection * h_connect_sqlite(const char * db_path) { UNUSED(db_path); y_log_message(Y_LOG_LEVEL_ERROR, "Hoel was not compiled with SQLite backend"); return NULL; } void h_close_sqlite(struct _h_connection * conn) { UNUSED(conn); y_log_message(Y_LOG_LEVEL_ERROR, "Hoel was not compiled with SQLite backend"); } char * h_escape_string_sqlite(const struct _h_connection * conn, const char * unsafe) { UNUSED(conn); UNUSED(unsafe); y_log_message(Y_LOG_LEVEL_ERROR, "Hoel was not compiled with SQLite backend"); return NULL; } char * h_escape_string_with_quotes_sqlite(const struct _h_connection * conn, const char * unsafe) { UNUSED(conn); UNUSED(unsafe); y_log_message(Y_LOG_LEVEL_ERROR, "Hoel was not compiled with SQLite backend"); return NULL; } long long int h_last_insert_id_sqlite(const struct _h_connection * conn) { UNUSED(conn); y_log_message(Y_LOG_LEVEL_ERROR, "Hoel was not compiled with SQLite backend"); return 0; } int h_execute_query_sqlite(const struct _h_connection * conn, const char * query) { UNUSED(conn); UNUSED(query); y_log_message(Y_LOG_LEVEL_ERROR, "Hoel was not compiled with SQLite backend"); return H_ERROR; } int h_execute_query_json_sqlite(const struct _h_connection * conn, const char * query, json_t ** j_result) { UNUSED(conn); UNUSED(query); UNUSED(j_result); y_log_message(Y_LOG_LEVEL_ERROR, "Hoel was not compiled with SQLite backend"); return H_ERROR; } #endif hoel-1.4.29/src/hoel.c000066400000000000000000000473221452453561700144440ustar00rootroot00000000000000/** * * Hoel database abstraction library * * hoel.c: main functions * * Copyright 2015-2020 Nicolas Mora * * 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; * version 2.1 of the License. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU GENERAL PUBLIC LICENSE for more details. * * You should have received a copy of the GNU General Public * License along with this library. If not, see . * */ #include #include #include "hoel.h" #include "h-private.h" /** * free data allocated by hoel functions */ void h_free(void * data) { o_free(data); } /** * Close a database connection * return H_OK on success */ int h_close_db(struct _h_connection * conn) { if (conn != NULL && conn->connection != NULL) { if (0) { /* Not happening */ return H_ERROR_PARAMS; #ifdef _HOEL_SQLITE } else if (conn->type == HOEL_DB_TYPE_SQLITE) { h_close_sqlite(conn); return H_OK; #endif #ifdef _HOEL_MARIADB } else if (conn->type == HOEL_DB_TYPE_MARIADB) { h_close_mariadb(conn); return H_OK; #endif #ifdef _HOEL_PGSQL } else if (conn->type == HOEL_DB_TYPE_PGSQL) { h_close_pgsql(conn); return H_OK; #endif } else { return H_ERROR_PARAMS; } } else { return H_ERROR_PARAMS; } } /** * h_escape_string * Escapes a string * returned value must be free'd after use */ char * h_escape_string(const struct _h_connection * conn, const char * unsafe) { if (conn != NULL && conn->connection != NULL && unsafe != NULL) { if (0) { /* Not happening */ return NULL; #ifdef _HOEL_SQLITE } else if (conn->type == HOEL_DB_TYPE_SQLITE) { return h_escape_string_sqlite(conn, unsafe); #endif #ifdef _HOEL_MARIADB } else if (conn->type == HOEL_DB_TYPE_MARIADB) { return h_escape_string_mariadb(conn, unsafe); #endif #ifdef _HOEL_PGSQL } else if (conn->type == HOEL_DB_TYPE_PGSQL) { return h_escape_string_pgsql(conn, unsafe); #endif } else { return NULL; } } else { return NULL; } } /** * h_escape_string_with_quotes * Escapes a string and returns it ready to be inserted in the query * returned value must be h_h_free'd after use */ char * h_escape_string_with_quotes(const struct _h_connection * conn, const char * unsafe) { if (conn != NULL && conn->connection != NULL && unsafe != NULL) { if (0) { /* Not happening */ return NULL; #ifdef _HOEL_SQLITE } else if (conn->type == HOEL_DB_TYPE_SQLITE) { return h_escape_string_with_quotes_sqlite(conn, unsafe); #endif #ifdef _HOEL_MARIADB } else if (conn->type == HOEL_DB_TYPE_MARIADB) { return h_escape_string_with_quotes_mariadb(conn, unsafe); #endif #ifdef _HOEL_PGSQL } else if (conn->type == HOEL_DB_TYPE_PGSQL) { return h_escape_string_with_quotes_pgsql(conn, unsafe); #endif } else { return NULL; } } else { return NULL; } } /** * h_execute_query * Execute a query, set the result structure with the returned values if available * if result is NULL, the query is executed but no value will be returned * options available * H_OPTION_NONE (0): no option * H_OPTION_SELECT: Execute a prepare statement (sqlite only) * H_OPTION_EXEC: Execute an exec statement (sqlite only) * return H_OK on success */ int h_execute_query(const struct _h_connection * conn, const char * query, struct _h_result * result, int options) { UNUSED(result); if (conn != NULL && conn->connection != NULL && query != NULL) { if (0) { /* Not happening */ return H_ERROR_PARAMS; #ifdef _HOEL_SQLITE } else if (conn->type == HOEL_DB_TYPE_SQLITE) { if (options & H_OPTION_EXEC) { return h_execute_query_sqlite(conn, query); } else { return h_select_query_sqlite(conn, query, result); } #else UNUSED(options); #endif #ifdef _HOEL_MARIADB } else if (conn->type == HOEL_DB_TYPE_MARIADB) { return h_execute_query_mariadb(conn, query, result); #endif #ifdef _HOEL_PGSQL } else if (conn->type == HOEL_DB_TYPE_PGSQL) { return h_execute_query_pgsql(conn, query, result); #endif } else { return H_ERROR_PARAMS; } } else { return H_ERROR_PARAMS; } } /** * h_execute_query_json * Execute a query, set the returned values in the json result * return H_OK on success */ int h_execute_query_json(const struct _h_connection * conn, const char * query, json_t ** j_result) { if (conn != NULL && conn->connection != NULL && query != NULL && j_result != NULL) { if (0) { /* Not happening */ return H_ERROR_PARAMS; #ifdef _HOEL_SQLITE } else if (conn->type == HOEL_DB_TYPE_SQLITE) { return h_execute_query_json_sqlite(conn, query, j_result); #endif #ifdef _HOEL_MARIADB } else if (conn->type == HOEL_DB_TYPE_MARIADB) { return h_execute_query_json_mariadb(conn, query, j_result); #endif #ifdef _HOEL_PGSQL } else if (conn->type == HOEL_DB_TYPE_PGSQL) { return h_execute_query_json_pgsql(conn, query, j_result); #endif } else { return H_ERROR_PARAMS; } } else { return H_ERROR_PARAMS; } } /** * Add a new struct _h_data * to an array of struct _h_data *, which already has cols columns * return H_OK on success */ int h_row_add_data(struct _h_data ** row, struct _h_data * data, int cols) { struct _h_data * tmp = o_realloc(*row, ((size_t)cols+1)*sizeof(struct _h_data)); * row = tmp; if (tmp == NULL) { y_log_message(Y_LOG_LEVEL_ERROR, "Hoel - Error allocating memory for h_row_add_data"); return H_ERROR_MEMORY; } else { switch (data->type) { case HOEL_COL_TYPE_INT: tmp[cols].type = HOEL_COL_TYPE_INT; tmp[cols].t_data = o_malloc(sizeof(struct _h_type_int)); if (tmp[cols].t_data == NULL) { y_log_message(Y_LOG_LEVEL_ERROR, "Hoel - Error allocating memory for tmp[cols].t_data"); return H_ERROR_MEMORY; } else { ((struct _h_type_int *)tmp[cols].t_data)->value = ((struct _h_type_int *)data->t_data)->value; return H_OK; } break; case HOEL_COL_TYPE_DOUBLE: tmp[cols].type = HOEL_COL_TYPE_DOUBLE; tmp[cols].t_data = o_malloc(sizeof(struct _h_type_double)); if (tmp[cols].t_data == NULL) { y_log_message(Y_LOG_LEVEL_ERROR, "Hoel - Error allocating memory for tmp[cols].t_data"); return H_ERROR_MEMORY; } else { ((struct _h_type_double *)tmp[cols].t_data)->value = ((struct _h_type_double *)data->t_data)->value; return H_OK; } break; case HOEL_COL_TYPE_TEXT: tmp[cols].type = HOEL_COL_TYPE_TEXT; tmp[cols].t_data = o_malloc(sizeof(struct _h_type_text)); if (tmp[cols].t_data == NULL) { y_log_message(Y_LOG_LEVEL_ERROR, "Hoel - Error allocating memory for tmp[cols].t_data"); return H_ERROR_MEMORY; } else { ((struct _h_type_text *)tmp[cols].t_data)->value = o_malloc(((struct _h_type_text *)data->t_data)->length+sizeof(char)); if (((struct _h_type_text *)tmp[cols].t_data)->value == NULL) { y_log_message(Y_LOG_LEVEL_ERROR, "Hoel - Error allocating memory for ((struct _h_type_text *)tmp[cols].t_data)->value"); h_free(tmp[cols].t_data); return H_ERROR_MEMORY; } memcpy(((struct _h_type_text *)tmp[cols].t_data)->value, ((struct _h_type_text *)data->t_data)->value, (((struct _h_type_text *)data->t_data)->length+1)); ((struct _h_type_text *)tmp[cols].t_data)->length = ((struct _h_type_text *)data->t_data)->length; return H_OK; } break; case HOEL_COL_TYPE_BLOB: tmp[cols].type = HOEL_COL_TYPE_BLOB; tmp[cols].t_data = o_malloc(sizeof(struct _h_type_blob)); if (tmp[cols].t_data == NULL) { y_log_message(Y_LOG_LEVEL_ERROR, "Hoel - Error allocating memory for tmp[cols].t_data"); return H_ERROR_MEMORY; } else { ((struct _h_type_blob *)tmp[cols].t_data)->length = ((struct _h_type_blob *)data->t_data)->length; ((struct _h_type_blob *)tmp[cols].t_data)->value = o_malloc(((struct _h_type_blob *)data->t_data)->length); if (((struct _h_type_blob *)tmp[cols].t_data)->value == NULL) { y_log_message(Y_LOG_LEVEL_ERROR, "Hoel - Error allocating memory for ((struct _h_type_blob *)tmp[cols].t_data)->value"); h_free(tmp[cols].t_data); return H_ERROR_MEMORY; } memcpy(((struct _h_type_blob *)tmp[cols].t_data)->value, ((struct _h_type_blob *)data->t_data)->value, ((struct _h_type_blob *)data->t_data)->length); return H_OK; } break; case HOEL_COL_TYPE_DATE: tmp[cols].type = HOEL_COL_TYPE_DATE; tmp[cols].t_data = o_malloc(sizeof(struct _h_type_datetime)); if (tmp[cols].t_data == NULL) { y_log_message(Y_LOG_LEVEL_ERROR, "Hoel - Error allocating memory for tmp[cols].t_data"); return H_ERROR_MEMORY; } else { ((struct _h_type_datetime *)tmp[cols].t_data)->value = ((struct _h_type_datetime *)data->t_data)->value; return H_OK; } break; case HOEL_COL_TYPE_NULL: tmp[cols].type = HOEL_COL_TYPE_NULL; tmp[cols].t_data = NULL; break; default: return H_ERROR_PARAMS; break; } return H_OK; } } /** * Add a new row of struct _h_data * in a struct _h_result * * return H_OK on success */ int h_result_add_row(struct _h_result * result, struct _h_data * row, int rows) { result->data = o_realloc(result->data, ((size_t)rows+1)*sizeof(struct _h_data *)); if (result->data == NULL) { y_log_message(Y_LOG_LEVEL_ERROR, "Hoel - Error allocating memory for result->data"); return H_ERROR_MEMORY; } else { result->data[rows] = row; result->nb_rows++; return H_OK; } } /** * h_query_insert * Execute an insert query * return H_OK on success */ int h_query_insert(const struct _h_connection * conn, const char * query) { if (conn != NULL && conn->connection != NULL && query != NULL && o_strcasestr(query, "insert") != NULL) { return h_execute_query(conn, query, NULL, H_OPTION_EXEC); } else { return H_ERROR_PARAMS; } } /** * h_query_last_insert_id * return the id of the last inserted value * return H_OK on success */ struct _h_data * h_query_last_insert_id(const struct _h_connection * conn) { struct _h_data * data = NULL; if (conn != NULL && conn->connection != NULL) { if (0) { /* Not happening */ #ifdef _HOEL_SQLITE } else if (conn->type == HOEL_DB_TYPE_SQLITE) { long long int last_id = h_last_insert_id_sqlite(conn); if (last_id > 0) { data = h_new_data_int(last_id); } else { data = h_new_data_null(); } #endif #ifdef _HOEL_MARIADB } else if (conn->type == HOEL_DB_TYPE_MARIADB) { long long int last_id = h_last_insert_id_mariadb(conn); if (last_id > 0) { data = h_new_data_int(last_id); } else { data = h_new_data_null(); } #endif #ifdef _HOEL_PGSQL } else if (conn->type == HOEL_DB_TYPE_PGSQL) { long long int last_id = h_last_insert_id_pgsql(conn); if (last_id > 0) { data = h_new_data_int(last_id); } else { data = h_new_data_null(); } #endif } else { data = h_new_data_null(); } } return data; } /** * h_query_update * Execute an update query * return H_OK on success */ int h_query_update(const struct _h_connection * conn, const char * query) { if (conn != NULL && conn->connection != NULL && query != NULL && o_strcasestr(query, "update") != NULL) { return h_execute_query(conn, query, NULL, H_OPTION_EXEC); } else { return H_ERROR_PARAMS; } } /** * h_query_delete * Execute an delete query * return H_OK on success */ int h_query_delete(const struct _h_connection * conn, const char * query) { if (conn != NULL && conn->connection != NULL && query != NULL && o_strcasestr(query, "delete") != NULL) { return h_execute_query(conn, query, NULL, H_OPTION_EXEC); } else { return H_ERROR_PARAMS; } } /** * h_query_select * Execute a select query, set the result structure with the returned values * return H_OK on success */ int h_query_select(const struct _h_connection * conn, const char * query, struct _h_result * result) { if (conn != NULL && conn->connection != NULL && query != NULL && o_strcasestr(query, "select") != NULL) { return h_execute_query(conn, query, result, H_OPTION_SELECT); } else { return H_ERROR_PARAMS; } } /** * h_query_select_json * Execute a select query, set the returned values in the json results * return H_OK on success */ int h_query_select_json(const struct _h_connection * conn, const char * query, json_t ** j_result) { if (conn != NULL && conn->connection != NULL && query != NULL && o_strcasestr(query, "select") != NULL) { return h_execute_query_json(conn, query, j_result); } else { return H_ERROR_PARAMS; } } /** * h_clean_result * Free all the memory allocated by the struct _h_result */ int h_clean_result(struct _h_result * result) { unsigned int col, row; if (result != NULL) { for (row=0; rownb_rows; row++) { for (col=0; colnb_columns; col++) { if (h_clean_data(&result->data[row][col]) != H_OK) { return H_ERROR_MEMORY; } } h_free(result->data[row]); } h_free(result->data); return H_OK; } else { return H_ERROR_PARAMS; } } /** * h_clean_data * Free memory allocated by the struct _h_data * return H_OK on success */ int h_clean_data(struct _h_data * data) { if (data != NULL) { if (data->type == HOEL_COL_TYPE_TEXT) { h_free(((struct _h_type_text *)data->t_data)->value); } else if (data->type == HOEL_COL_TYPE_BLOB) { h_free(((struct _h_type_blob *)data->t_data)->value); } if (data->t_data != NULL) { h_free(data->t_data); } return H_OK; } else { return H_ERROR_PARAMS; } } /** * h_clean_data_full * Free memory allocated by the struct _h_data and the struct _h_data pointer * return H_OK on success */ int h_clean_data_full(struct _h_data * data) { if (data != NULL) { h_clean_data(data); h_free(data); return H_OK; } else { return H_ERROR_PARAMS; } } /** * Allocate memory for a new struct _h_data * containing an int * return pointer to the new structure * return NULL on error */ struct _h_data * h_new_data_int(const long long int value) { struct _h_data * data = o_malloc(sizeof(struct _h_data)); if (data != NULL) { data->t_data = o_malloc(sizeof(struct _h_type_int)); if (data->t_data == NULL) { y_log_message(Y_LOG_LEVEL_ERROR, "Hoel - Error allocating memory for data->t_data"); h_free(data); return NULL; } data->type = HOEL_COL_TYPE_INT; ((struct _h_type_int *)data->t_data)->value = value; } else { y_log_message(Y_LOG_LEVEL_ERROR, "Hoel - Error allocating memory for data"); } return data; } /** * Allocate memory for a new struct _h_data * containing a double * return pointer to the new structure * return NULL on error */ struct _h_data * h_new_data_double(const double value) { struct _h_data * data = o_malloc(sizeof(struct _h_data)); if (data != NULL) { data->t_data = o_malloc(sizeof(struct _h_type_double)); if (data->t_data == NULL) { y_log_message(Y_LOG_LEVEL_ERROR, "Hoel - Error allocating memory for data->t_data"); h_free(data); return NULL; } data->type = HOEL_COL_TYPE_DOUBLE; ((struct _h_type_double *)data->t_data)->value = value; } else { y_log_message(Y_LOG_LEVEL_ERROR, "Hoel - Error allocating memory for data"); } return data; } /** * Allocate memory for a new struct _h_data * containing a text * return pointer to the new structure * return NULL on error */ struct _h_data * h_new_data_text(const char * value, const size_t length) { struct _h_data * data = o_malloc(sizeof(struct _h_data)); if (data != NULL) { data->t_data = o_malloc(sizeof(struct _h_type_text)); if (data->t_data == NULL) { y_log_message(Y_LOG_LEVEL_ERROR, "Hoel - Error allocating memory for data->t_data"); h_free(data); return NULL; } data->type = HOEL_COL_TYPE_TEXT; ((struct _h_type_text *)data->t_data)->value = o_malloc(length+1); if (((struct _h_type_text *)data->t_data)->value == NULL) { y_log_message(Y_LOG_LEVEL_ERROR, "Hoel - Error allocating memory for data->t_data->value"); h_free(data); return NULL; } else { memcpy(((struct _h_type_text *)data->t_data)->value, value, length); ((struct _h_type_text *)data->t_data)->length = length; ((struct _h_type_text *)data->t_data)->value[length] = '\0'; } } else { y_log_message(Y_LOG_LEVEL_ERROR, "Hoel - Error allocating memory for data"); } return data; } /** * Allocate memory for a new struct _h_data * containing a blob * return pointer to the new structure * return NULL on error */ struct _h_data * h_new_data_blob(const void * value, const size_t length) { struct _h_data * data = NULL; if (value != NULL && length) { data = o_malloc(sizeof(struct _h_data)); if (data != NULL) { data->t_data = o_malloc(sizeof(struct _h_type_blob)); if (data->t_data == NULL) { y_log_message(Y_LOG_LEVEL_ERROR, "Hoel - Error allocating memory for data"); h_free(data); return NULL; } data->type = HOEL_COL_TYPE_BLOB; ((struct _h_type_blob *)data->t_data)->length = length; ((struct _h_type_blob *)data->t_data)->value = o_malloc(length); if (((struct _h_type_blob *)data->t_data)->value == NULL) { y_log_message(Y_LOG_LEVEL_ERROR, "Hoel - Error allocating memory for t_data->value"); h_free(data); return NULL; } else { memcpy(((struct _h_type_blob *)data->t_data)->value, value, length); } } else { y_log_message(Y_LOG_LEVEL_ERROR, "Hoel - Error allocating memory for data"); } } else { y_log_message(Y_LOG_LEVEL_ERROR, "Hoel - h_new_data_blob - Invalid parameters"); } return data; } /** * Allocate memory for a new struct _h_data * containing a null value * return pointer to the new structure * return NULL on error */ struct _h_data * h_new_data_null() { struct _h_data * data = o_malloc(sizeof(struct _h_data)); if (data != NULL) { data->type = HOEL_COL_TYPE_NULL; data->t_data = NULL; } else { y_log_message(Y_LOG_LEVEL_ERROR, "Hoel - Error allocating memory for data"); } return data; } /** * Allocate memory for a new struct _h_data * containing a date time structure * return pointer to the new structure * return NULL on error */ struct _h_data * h_new_data_datetime(const struct tm * datetime) { struct _h_data * data = NULL; if (datetime != NULL) { data = o_malloc(sizeof(struct _h_data)); if (data != NULL) { data->type = HOEL_COL_TYPE_DATE; data->t_data = o_malloc(sizeof(struct _h_type_datetime)); if (data->t_data == NULL) { y_log_message(Y_LOG_LEVEL_ERROR, "Hoel - Error allocating memory for data->t_data"); h_free(data); return NULL; } ((struct _h_type_datetime *)data->t_data)->value = * datetime; } else { y_log_message(Y_LOG_LEVEL_ERROR, "Hoel - Error allocating memory for data"); } } return data; } /** * h_clean_connection * free memory allocated by the struct _h_connection * return H_OK on success */ int h_clean_connection(struct _h_connection * conn) { if (conn != NULL) { h_free(conn->connection); h_free(conn); return H_OK; } else { return H_ERROR_PARAMS; } } hoel-1.4.29/test/000077500000000000000000000000001452453561700135315ustar00rootroot00000000000000hoel-1.4.29/test/Makefile000066400000000000000000000027401452453561700151740ustar00rootroot00000000000000# # Hoel library # # Makefile used to build the tests # # Public domain, no copyright. Use at your own risk # HOEL_INCLUDE=../include HOEL_LOCATION=../src HOEL_LIBRARY=$(HOEL_LOCATION)/libhoel.so CC=gcc CFLAGS=-Wall -I$(HOEL_INCLUDE) -D_REENTRANT -DDEBUG -g -O0 HOEL_DB_TEST=/tmp/test.db LDFLAGS=-lc $(shell pkg-config --libs liborcania) $(shell pkg-config --libs libyder) $(shell pkg-config --libs libhoel) $(shell pkg-config --libs jansson) -L$(HOEL_LIBRARY) $(shell pkg-config --libs check) VALGRIND_COMMAND=valgrind --tool=memcheck --leak-check=full --show-leak-kinds=all TARGET=core multi VERBOSE=0 MEMCHECK=0 all: test clean: rm -f *.o $(TARGET) $(HOEL_DB_TEST) valgrind-*.txt *.log $(HOEL_DB_TEST): sqlite3 $(HOEL_DB_TEST) < test.sqlite3.sql $(HOEL_LIBRARY): $(HOEL_INCLUDE)/hoel.h $(HOEL_LOCATION)/hoel.c $(HOEL_LOCATION)/hoel-mariadb.c $(HOEL_LOCATION)/hoel-pgsql.c $(HOEL_LOCATION)/hoel-sqlite.c $(HOEL_LOCATION)/hoel-simple-json.c cd $(HOEL_LOCATION) && $(MAKE) debug %: $(HOEL_LIBRARY) %.c $(CC) $(CFLAGS) $^ -o $@ $(LDFLAGS) test_%: % $(HOEL_LIBRARY) $(HOEL_DB_TEST) @if [ "$(VERBOSE)" = "0" ] && [ "$(MEMCHECK)" = "0" ]; then \ LD_LIBRARY_PATH=$(HOEL_LOCATION):${LD_LIBRARY_PATH} ./run_test.sh ./$^; \ elif [ "$(MEMCHECK)" = "0" ]; then \ LD_LIBRARY_PATH=$(HOEL_LOCATION):${LD_LIBRARY_PATH} ./$^; \ else \ CK_FORK=no LD_LIBRARY_PATH=$(HOEL_LOCATION):${LD_LIBRARY_PATH} $(VALGRIND_COMMAND) ./$^ 2>valgrind-$@.txt; \ fi test: $(TARGET) test_core test_multi check: test hoel-1.4.29/test/core.c000066400000000000000000001337631452453561700146420ustar00rootroot00000000000000/* Public domain, no copyright. Use at your own risk. */ /* only sqlite3 backend is tested, I will assume the */ /* behaviour is the same with other backends */ #include #include #include #include #include #include #ifndef _HOEL_SQLITE #define _HOEL_SQLITE #endif #include "hoel.h" #define DEFAULT_BD_PATH "/tmp/test.db" #define WRONG_BD_PATH "nope.db" #define UNSAFE_STRING "un'safe' (\"string\")#!/$%*];" #define SELECT_DATA_1 "SELECT integer_col, double_col, string_col, date_col FROM test_table WHERE integer_col = 1" #define SELECT_DATA_2 "SELECT integer_col, double_col, string_col, date_col FROM test_table WHERE integer_col = 2" #define SELECT_DATA_ERROR "SELECT integer_col, double_col, string_col, date_col FROM test_table WHERE integer_col = 'error'" #define SELECT_DATA_ALL "SELECT * FROM test_table" #define INSERT_DATA_1 "INSERT INTO test_table (integer_col, double_col, string_col, date_col) VALUES (1, 4.2, 'value1', date('now'))" #define INSERT_DATA_2 "INSERT INTO test_table (integer_col, double_col, string_col, date_col) VALUES (2, 5.4, 'value2', strftime('%s','2016-06-22 00:52:56'))" #define INSERT_DATA_ERROR "INSERT INTO test_table (integer_col, double_col, string_col, date_col) VALUES ('error', 'error_double', 'value error', date('now'))" #define DELETE_DATA_1 "DELETE FROM test_table WHERE integer_col = 1" #define DELETE_DATA_2 "DELETE FROM test_table WHERE integer_col = 2" #define DELETE_DATA_ERROR "DELETE FROM test_table WHERE wrong_table = 1" #define DELETE_DATA_ALL "DELETE FROM test_table" #define UPDATE_DATA_1 "UPDATE test_table SET string_col='new value1', double_col=5.4 WHERE integer_col = 1" #define WHERE_CLAUSE_NO_FORMAT "And then, nothing happened" void print_result(struct _h_result result) { size_t col, row, i; printf("rows: %u, col: %u\n", result.nb_rows, result.nb_columns); for (row = 0; rowvalue); break; case HOEL_COL_TYPE_DOUBLE: printf("| %f ", ((struct _h_type_double *)result.data[row][col].t_data)->value); break; case HOEL_COL_TYPE_TEXT: printf("| %s ", ((struct _h_type_text *)result.data[row][col].t_data)->value); break; case HOEL_COL_TYPE_BLOB: for (i=0; i<((struct _h_type_blob *)result.data[row][col].t_data)->length; i++) { printf("%c", *((char*)(((struct _h_type_blob *)result.data[row][col].t_data)->value+i))); if (i%80 == 0 && i>0) { printf("\n"); } } break; case HOEL_COL_TYPE_NULL: printf("| null "); break; } } printf("|\n"); } } START_TEST(test_hoel_init) { struct _h_connection * conn; conn = h_connect_sqlite(DEFAULT_BD_PATH); ck_assert_ptr_ne(conn, NULL); ck_assert_ptr_eq(h_connect_sqlite(WRONG_BD_PATH), NULL); ck_assert_int_eq(h_close_db(conn), H_OK); ck_assert_int_ne(h_close_db(NULL), H_OK); ck_assert_int_eq(h_clean_connection(conn), H_OK); ck_assert_int_ne(h_clean_connection(NULL), H_OK); } END_TEST START_TEST(test_hoel_escape_string) { struct _h_connection * conn; char * escaped; json_t * j_query, * j_result; int res; conn = h_connect_sqlite(DEFAULT_BD_PATH); ck_assert_ptr_ne(conn, NULL); escaped = h_escape_string(conn, "value"); ck_assert_str_eq(escaped, "value"); h_free(escaped); escaped = h_escape_string(conn, "unsafe ' value\"!"); ck_assert_str_eq(escaped, "unsafe '' value\"!"); h_free(escaped); j_query = json_pack("{sss{siss}}", "table", "test_table", "values", "integer_col", 666, "string_col", UNSAFE_STRING); res = h_insert(conn, j_query, NULL); json_decref(j_query); ck_assert_int_eq(res, H_OK); j_query = json_pack("{sss[s]s{si}}", "table", "test_table", "columns", "string_col", "where", "integer_col", 666); res = h_select(conn, j_query, &j_result, NULL); json_decref(j_query); ck_assert_int_eq(res, H_OK); ck_assert_str_eq(UNSAFE_STRING, json_string_value(json_object_get(json_array_get(j_result, 0), "string_col"))); json_decref(j_result); ck_assert_int_eq(h_close_db(conn), H_OK); ck_assert_int_eq(h_clean_connection(conn), H_OK); } END_TEST START_TEST(test_hoel_escape_string_with_quotes) { struct _h_connection * conn; char * escaped; json_t * j_query, * j_result; int res; conn = h_connect_sqlite(DEFAULT_BD_PATH); ck_assert_ptr_ne(conn, NULL); escaped = h_escape_string_with_quotes(conn, "value"); ck_assert_str_eq(escaped, "'value'"); h_free(escaped); escaped = h_escape_string_with_quotes(conn, "unsafe ' value\"!"); ck_assert_str_eq(escaped, "'unsafe '' value\"!'"); h_free(escaped); j_query = json_pack("{sss{siss}}", "table", "test_table", "values", "integer_col", 666, "string_col", UNSAFE_STRING); res = h_insert(conn, j_query, NULL); json_decref(j_query); ck_assert_int_eq(res, H_OK); j_query = json_pack("{sss[s]s{si}}", "table", "test_table", "columns", "string_col", "where", "integer_col", 666); res = h_select(conn, j_query, &j_result, NULL); json_decref(j_query); ck_assert_int_eq(res, H_OK); ck_assert_str_eq(UNSAFE_STRING, json_string_value(json_object_get(json_array_get(j_result, 0), "string_col"))); json_decref(j_result); ck_assert_int_eq(h_close_db(conn), H_OK); ck_assert_int_eq(h_clean_connection(conn), H_OK); } END_TEST START_TEST(test_hoel_insert) { struct _h_connection * conn; struct _h_result result; struct _h_data * last_id; conn = h_connect_sqlite(DEFAULT_BD_PATH); ck_assert_ptr_ne(conn, NULL); ck_assert_int_eq(h_query_delete(conn, DELETE_DATA_ALL), H_OK); ck_assert_int_eq(h_query_insert(conn, INSERT_DATA_1), H_OK); last_id = h_query_last_insert_id(conn); ck_assert_int_eq(last_id->type, HOEL_COL_TYPE_INT); ck_assert_int_gt(((struct _h_type_int *)last_id->t_data)->value, 0); ck_assert_int_eq(h_clean_data(last_id), H_OK); h_free(last_id); ck_assert_ptr_ne(last_id, NULL); ck_assert_int_eq(h_query_insert(conn, NULL), H_ERROR_PARAMS); ck_assert_int_eq(h_query_select(conn, SELECT_DATA_1, &result), H_OK); ck_assert_int_eq(result.nb_rows, 1); ck_assert_int_eq(result.nb_columns, 4); ck_assert_int_eq(result.data[0][0].type, HOEL_COL_TYPE_INT); ck_assert_int_eq(((struct _h_type_int *)result.data[0][0].t_data)->value, 1); ck_assert_int_eq(result.data[0][1].type, HOEL_COL_TYPE_DOUBLE); ck_assert_double_eq(((struct _h_type_double *)result.data[0][1].t_data)->value, 4.2); ck_assert_int_eq(result.data[0][2].type, HOEL_COL_TYPE_TEXT); ck_assert_str_eq(((struct _h_type_text *)result.data[0][2].t_data)->value, "value1"); ck_assert_int_eq(h_clean_result(&result), H_OK); ck_assert_int_eq(h_query_select(conn, SELECT_DATA_ERROR, &result), H_OK); ck_assert_int_eq(result.nb_rows, 0); ck_assert_int_eq(result.nb_columns, 4); ck_assert_int_eq(h_clean_result(&result), H_OK); ck_assert_int_eq(h_query_delete(conn, DELETE_DATA_1), H_OK); ck_assert_int_eq(h_close_db(conn), H_OK); ck_assert_int_eq(h_clean_connection(conn), H_OK); } END_TEST START_TEST(test_hoel_update) { struct _h_connection * conn; struct _h_result result; conn = h_connect_sqlite(DEFAULT_BD_PATH); ck_assert_ptr_ne(conn, NULL); ck_assert_int_eq(h_query_insert(conn, INSERT_DATA_1), H_OK); ck_assert_int_eq(h_query_insert(conn, NULL), H_ERROR_PARAMS); ck_assert_int_eq(h_query_select(conn, SELECT_DATA_1, &result), H_OK); ck_assert_int_eq(result.nb_rows, 1); ck_assert_int_eq(result.nb_columns, 4); ck_assert_int_eq(((struct _h_type_int *)result.data[0][0].t_data)->value, 1); ck_assert_double_eq(((struct _h_type_double *)result.data[0][1].t_data)->value, 4.2); ck_assert_str_eq(((struct _h_type_text *)result.data[0][2].t_data)->value, "value1"); ck_assert_int_eq(h_clean_result(&result), H_OK); ck_assert_int_eq(h_query_update(conn, UPDATE_DATA_1), H_OK); ck_assert_int_eq(h_query_select(conn, SELECT_DATA_1, &result), H_OK); ck_assert_int_eq(result.nb_rows, 1); ck_assert_int_eq(result.nb_columns, 4); ck_assert_int_eq(((struct _h_type_int *)result.data[0][0].t_data)->value, 1); ck_assert_double_eq(((struct _h_type_double *)result.data[0][1].t_data)->value, 5.4); ck_assert_str_eq(((struct _h_type_text *)result.data[0][2].t_data)->value, "new value1"); ck_assert_int_eq(h_clean_result(&result), H_OK); ck_assert_int_eq(h_query_delete(conn, DELETE_DATA_1), H_OK); ck_assert_int_eq(h_close_db(conn), H_OK); ck_assert_int_eq(h_clean_connection(conn), H_OK); } END_TEST START_TEST(test_hoel_delete) { struct _h_connection * conn; struct _h_result result; conn = h_connect_sqlite(DEFAULT_BD_PATH); ck_assert_ptr_ne(conn, NULL); ck_assert_int_eq(h_query_insert(conn, INSERT_DATA_1), H_OK); ck_assert_int_eq(h_query_insert(conn, INSERT_DATA_2), H_OK); ck_assert_int_eq(h_query_select(conn, SELECT_DATA_1, &result), H_OK); ck_assert_int_eq(result.nb_rows, 1); ck_assert_int_eq(result.nb_columns, 4); ck_assert_int_eq(result.data[0][0].type, HOEL_COL_TYPE_INT); ck_assert_int_eq(((struct _h_type_int *)result.data[0][0].t_data)->value, 1); ck_assert_int_eq(result.data[0][1].type, HOEL_COL_TYPE_DOUBLE); ck_assert_double_eq(((struct _h_type_double *)result.data[0][1].t_data)->value, 4.2); ck_assert_int_eq(result.data[0][2].type, HOEL_COL_TYPE_TEXT); ck_assert_str_eq(((struct _h_type_text *)result.data[0][2].t_data)->value, "value1"); ck_assert_int_eq(h_clean_result(&result), H_OK); ck_assert_int_eq(h_query_select(conn, SELECT_DATA_2, &result), H_OK); ck_assert_int_eq(result.nb_rows, 1); ck_assert_int_eq(result.nb_columns, 4); ck_assert_int_eq(result.data[0][0].type, HOEL_COL_TYPE_INT); ck_assert_int_eq(((struct _h_type_int *)result.data[0][0].t_data)->value, 2); ck_assert_int_eq(result.data[0][1].type, HOEL_COL_TYPE_DOUBLE); ck_assert_double_eq(((struct _h_type_double *)result.data[0][1].t_data)->value, 5.4); ck_assert_int_eq(result.data[0][2].type, HOEL_COL_TYPE_TEXT); ck_assert_str_eq(((struct _h_type_text *)result.data[0][2].t_data)->value, "value2"); ck_assert_int_eq(h_clean_result(&result), H_OK); ck_assert_int_eq(h_query_delete(conn, DELETE_DATA_1), H_OK); ck_assert_int_eq(h_query_select(conn, SELECT_DATA_ALL, &result), H_OK); ck_assert_int_eq(result.nb_rows, 1); ck_assert_int_eq(h_clean_result(&result), H_OK); ck_assert_int_eq(h_query_delete(conn, DELETE_DATA_2), H_OK); ck_assert_int_eq(h_query_select(conn, SELECT_DATA_ALL, &result), H_OK); ck_assert_int_eq(result.nb_rows, 0); ck_assert_int_eq(h_clean_result(&result), H_OK); ck_assert_int_eq(h_close_db(conn), H_OK); ck_assert_int_eq(h_clean_connection(conn), H_OK); } END_TEST START_TEST(test_hoel_json_insert) { struct _h_connection * conn; char * str_query = NULL; json_t * j_query = json_pack("{sss{sisss{ss}sf}}", "table", "test_table", "values", "integer_col", 1, "string_col", "value1", "date_col", "raw", "date('now')", "double_col", 4.2), * j_result = NULL; conn = h_connect_sqlite(DEFAULT_BD_PATH); ck_assert_ptr_ne(conn, NULL); ck_assert_int_eq(h_insert(conn, j_query, &str_query), H_OK); json_decref(j_query); j_query = json_pack("{sss{si}}", "table", "test_table", "where", "integer_col", 1); ck_assert_int_eq(h_select(conn, j_query, &j_result, NULL), H_OK); ck_assert_ptr_ne(j_result, NULL); ck_assert_int_eq(json_is_array(j_result), 1); ck_assert_int_eq(json_array_size(j_result), 1); ck_assert_str_eq(json_string_value(json_object_get(json_array_get(j_result, 0), "string_col")), "value1"); ck_assert_int_eq(json_integer_value(json_object_get(json_array_get(j_result, 0), "integer_col")), 1); ck_assert_double_eq(json_real_value(json_object_get(json_array_get(j_result, 0), "double_col")), 4.2); json_decref(j_result); ck_assert_int_eq(o_strlen(str_query), o_strlen("INSERT INTO test_table (integer_col,string_col,date_col,double_col) VALUES (1,'value1',date('now'),4.200000)")); h_free(str_query); ck_assert_int_eq(h_delete(conn, j_query, NULL), H_OK); json_decref(j_query); ck_assert_int_eq(h_close_db(conn), H_OK); ck_assert_int_eq(h_clean_connection(conn), H_OK); } END_TEST START_TEST(test_hoel_json_update) { struct _h_connection * conn; char * str_query = NULL; json_t * j_query = json_pack("{sss{sisss{ss}sf}}", "table", "test_table", "values", "integer_col", 1, "string_col", "value1", "date_col", "raw", "date('now')", "double_col", 4.2), * j_result = NULL; conn = h_connect_sqlite(DEFAULT_BD_PATH); ck_assert_ptr_ne(conn, NULL); ck_assert_int_eq(h_insert(conn, j_query, NULL), H_OK); json_decref(j_query); j_query = json_pack("{sss{si}}", "table", "test_table", "where", "integer_col", 1); ck_assert_int_eq(h_select(conn, j_query, &j_result, NULL), H_OK); json_decref(j_query); ck_assert_ptr_ne(j_result, NULL); ck_assert_int_eq(json_is_array(j_result), 1); ck_assert_int_eq(json_array_size(j_result), 1); ck_assert_str_eq(json_string_value(json_object_get(json_array_get(j_result, 0), "string_col")), "value1"); ck_assert_int_eq(json_integer_value(json_object_get(json_array_get(j_result, 0), "integer_col")), 1); ck_assert_double_eq(json_real_value(json_object_get(json_array_get(j_result, 0), "double_col")), 4.2); json_decref(j_result); j_query = json_pack("{sss{sssf}s{si}}", "table", "test_table", "set", "string_col", "new value1", "double_col", 5.4, "where", "integer_col", 1); ck_assert_int_eq(h_update(conn, j_query, &str_query), H_OK); json_decref(j_query); ck_assert_int_eq(o_strlen(str_query), o_strlen("UPDATE test_table SET string_col='new value1', double_col=5.400000 WHERE integer_col='1'")); h_free(str_query); j_query = json_pack("{sss{si}}", "table", "test_table", "where", "integer_col", 1); ck_assert_int_eq(h_select(conn, j_query, &j_result, NULL), H_OK); ck_assert_ptr_ne(j_result, NULL); ck_assert_int_eq(json_array_size(j_result), 1); ck_assert_str_eq(json_string_value(json_object_get(json_array_get(j_result, 0), "string_col")), "new value1"); ck_assert_int_eq(json_integer_value(json_object_get(json_array_get(j_result, 0), "integer_col")), 1); ck_assert_double_eq(json_real_value(json_object_get(json_array_get(j_result, 0), "double_col")), 5.4); json_decref(j_result); ck_assert_int_eq(h_delete(conn, j_query, NULL), H_OK); json_decref(j_query); ck_assert_int_eq(h_close_db(conn), H_OK); ck_assert_int_eq(h_clean_connection(conn), H_OK); } END_TEST START_TEST(test_hoel_json_delete) { struct _h_connection * conn; char * str_query = NULL; json_t * j_query = json_pack("{sss{sisss{ss}sf}}", "table", "test_table", "values", "integer_col", 1, "string_col", "value1", "date_col", "raw", "date('now')", "double_col", 4.2), * j_result = NULL; conn = h_connect_sqlite(DEFAULT_BD_PATH); ck_assert_ptr_ne(conn, NULL); ck_assert_int_eq(h_insert(conn, j_query, NULL), H_OK); json_decref(j_query); j_query = json_pack("{sss{sisss{ss}sf}}", "table", "test_table", "values", "integer_col", 2, "string_col", "value2", "date_col", "raw", "strftime('%s','2016-06-22 00:52:56')", "double_col", 5.4); ck_assert_int_eq(h_insert(conn, j_query, NULL), H_OK); json_decref(j_query); j_query = json_pack("{ss}", "table", "test_table"); ck_assert_int_eq(h_select(conn, j_query, &j_result, NULL), H_OK); json_decref(j_query); ck_assert_ptr_ne(j_result, NULL); ck_assert_int_eq(json_is_array(j_result), 1); ck_assert_int_eq(json_array_size(j_result), 2); json_decref(j_result); j_query = json_pack("{sss{si}}", "table", "test_table", "where", "integer_col", 1); ck_assert_int_eq(h_delete(conn, j_query, &str_query), H_OK); ck_assert_int_eq(o_strlen(str_query), o_strlen("DELETE FROM test_table WHERE integer_col='1'")); h_free(str_query); json_decref(j_query); j_query = json_pack("{ss}", "table", "test_table"); ck_assert_int_eq(h_select(conn, j_query, &j_result, NULL), H_OK); json_decref(j_query); ck_assert_int_eq(json_array_size(j_result), 1); ck_assert_str_eq(json_string_value(json_object_get(json_array_get(j_result, 0), "string_col")), "value2"); ck_assert_int_eq(json_integer_value(json_object_get(json_array_get(j_result, 0), "integer_col")), 2); ck_assert_int_eq(json_integer_value(json_object_get(json_array_get(j_result, 0), "date_col")), 1466556776); ck_assert_double_eq(json_real_value(json_object_get(json_array_get(j_result, 0), "double_col")), 5.4); json_decref(j_result); j_query = json_pack("{ss}", "table", "test_table"); ck_assert_int_eq(h_delete(conn, j_query, NULL), H_OK); ck_assert_int_eq(h_select(conn, j_query, &j_result, NULL), H_OK); ck_assert_int_eq(json_array_size(j_result), 0); json_decref(j_result); json_decref(j_query); ck_assert_int_eq(h_close_db(conn), H_OK); ck_assert_int_eq(h_clean_connection(conn), H_OK); } END_TEST START_TEST(test_hoel_json_select) { struct _h_connection * conn; char * str_query = NULL; json_t * j_query = json_pack("{sss{sisss{ss}sf}}", "table", "test_table", "values", "integer_col", 1, "string_col", "value1", "date_col", "raw", "date('now')", "double_col", 4.2), * j_result = NULL; conn = h_connect_sqlite(DEFAULT_BD_PATH); ck_assert_ptr_ne(conn, NULL); ck_assert_int_eq(h_insert(conn, j_query, NULL), H_OK); json_decref(j_query); j_query = json_pack("{sss{sisss{ss}sf}}", "table", "test_table", "values", "integer_col", 2, "string_col", "value2", "date_col", "raw", "strftime('%s','2016-06-22 00:52:56')", "double_col", 5.4); ck_assert_int_eq(h_insert(conn, j_query, NULL), H_OK); json_decref(j_query); j_query = json_pack("{ss}", "table", "test_table"); ck_assert_int_eq(h_select(conn, j_query, &j_result, &str_query), H_OK); ck_assert_int_eq(o_strlen(str_query), o_strlen("SELECT * FROM test_table WHERE 1=1")); ck_assert_int_eq(json_array_size(j_result), 2); ck_assert_str_eq(json_string_value(json_object_get(json_array_get(j_result, 0), "string_col")), "value1"); ck_assert_int_eq(json_integer_value(json_object_get(json_array_get(j_result, 0), "integer_col")), 1); ck_assert_double_eq(json_real_value(json_object_get(json_array_get(j_result, 0), "double_col")), 4.2); json_decref(j_query); json_decref(j_result); h_free(str_query); j_query = json_pack("{sss{si}}", "table", "test_table", "where", "integer_col", 1); ck_assert_int_eq(h_select(conn, j_query, &j_result, &str_query), H_OK); ck_assert_int_eq(o_strlen(str_query), o_strlen("SELECT * FROM test_table WHERE integer_col='1'")); ck_assert_int_eq(json_array_size(j_result), 1); ck_assert_str_eq(json_string_value(json_object_get(json_array_get(j_result, 0), "string_col")), "value1"); ck_assert_int_eq(json_integer_value(json_object_get(json_array_get(j_result, 0), "integer_col")), 1); ck_assert_double_eq(json_real_value(json_object_get(json_array_get(j_result, 0), "double_col")), 4.2); json_decref(j_query); json_decref(j_result); h_free(str_query); j_query = json_pack("{sss{ss}}", "table", "test_table", "where", "string_col", "value1"); ck_assert_int_eq(h_select(conn, j_query, &j_result, &str_query), H_OK); ck_assert_int_eq(o_strlen(str_query), o_strlen("SELECT * FROM test_table WHERE string_col='value1'")); ck_assert_int_eq(json_array_size(j_result), 1); ck_assert_str_eq(json_string_value(json_object_get(json_array_get(j_result, 0), "string_col")), "value1"); ck_assert_int_eq(json_integer_value(json_object_get(json_array_get(j_result, 0), "integer_col")), 1); ck_assert_double_eq(json_real_value(json_object_get(json_array_get(j_result, 0), "double_col")), 4.2); json_decref(j_query); json_decref(j_result); h_free(str_query); j_query = json_pack("{sss{ss}}", "table", "test_table", "where", "string_col", "value'to'escape"); ck_assert_int_eq(h_select(conn, j_query, &j_result, &str_query), H_OK); ck_assert_int_eq(o_strlen(str_query), o_strlen("SELECT * FROM test_table WHERE string_col='value''to''escape'")); ck_assert_int_eq(json_array_size(j_result), 0); json_decref(j_query); json_decref(j_result); h_free(str_query); j_query = json_pack("{sss{s{ss}}}", "table", "test_table", "where", "integer_col", "operator", "NOT NULL"); ck_assert_int_eq(h_select(conn, j_query, &j_result, &str_query), H_OK); ck_assert_int_eq(o_strlen(str_query), o_strlen("SELECT * FROM test_table WHERE integer_col IS NOT NULL")); ck_assert_int_eq(json_array_size(j_result), 2); ck_assert_str_eq(json_string_value(json_object_get(json_array_get(j_result, 0), "string_col")), "value1"); ck_assert_int_eq(json_integer_value(json_object_get(json_array_get(j_result, 0), "integer_col")), 1); ck_assert_double_eq(json_real_value(json_object_get(json_array_get(j_result, 0), "double_col")), 4.2); json_decref(j_query); json_decref(j_result); h_free(str_query); j_query = json_pack("{sss{s{ssss}}}", "table", "test_table", "where", "integer_col", "operator", "raw", "value", ">6"); ck_assert_int_eq(h_select(conn, j_query, &j_result, &str_query), H_OK); ck_assert_int_eq(o_strlen(str_query), o_strlen("SELECT * FROM test_table WHERE integer_col >6")); ck_assert_int_eq(json_array_size(j_result), 0); json_decref(j_query); json_decref(j_result); h_free(str_query); j_query = json_pack("{sss{s{ss}s{ssss}}}", "table", "test_table", "where", "string_col", "operator", "NOT NULL", "integer_col", "operator", "raw", "value", ">=1"); ck_assert_int_eq(h_select(conn, j_query, &j_result, &str_query), H_OK); ck_assert_int_eq(o_strlen(str_query), o_strlen("SELECT * FROM test_table WHERE string_col IS NOT NULL AND integer_col >=1")); ck_assert_int_eq(json_array_size(j_result), 2); ck_assert_str_eq(json_string_value(json_object_get(json_array_get(j_result, 0), "string_col")), "value1"); ck_assert_int_eq(json_integer_value(json_object_get(json_array_get(j_result, 0), "integer_col")), 1); ck_assert_double_eq(json_real_value(json_object_get(json_array_get(j_result, 0), "double_col")), 4.2); json_decref(j_query); json_decref(j_result); h_free(str_query); j_query = json_pack("{sss{so}}", "table", "test_table", "where", "integer_col", json_null()); ck_assert_int_eq(h_select(conn, j_query, &j_result, &str_query), H_OK); ck_assert_int_eq(o_strlen(str_query), o_strlen("SELECT * FROM test_table WHERE integer_col IS NULL")); ck_assert_int_eq(json_array_size(j_result), 0); json_decref(j_query); json_decref(j_result); h_free(str_query); str_query = NULL; j_result = NULL; j_query = json_pack("{sss{s{sss[ii]}}}", "table", "test_table", "where", "integer_col", "operator", "IN", "value", 42, 66); ck_assert_int_eq(h_select(conn, j_query, &j_result, &str_query), H_OK); ck_assert_int_eq(o_strlen(str_query), o_strlen("SELECT * FROM test_table WHERE integer_col IN (42,66)")); ck_assert_int_eq(json_array_size(j_result), 0); json_decref(j_query); json_decref(j_result); h_free(str_query); j_query = json_pack("{ss}", "table", "test_table"); ck_assert_int_eq(h_delete(conn, j_query, NULL), H_OK); ck_assert_int_eq(h_select(conn, j_query, &j_result, NULL), H_OK); ck_assert_int_eq(json_array_size(j_result), 0); json_decref(j_result); json_decref(j_query); ck_assert_int_eq(h_close_db(conn), H_OK); ck_assert_int_eq(h_clean_connection(conn), H_OK); } END_TEST START_TEST(test_hoel_json_escape) { struct _h_connection * conn; char * str_query = NULL, * escaped, * str_query_wip; json_t * j_query, * j_result = NULL; conn = h_connect_sqlite(DEFAULT_BD_PATH); ck_assert_ptr_ne(conn, NULL); ck_assert_ptr_ne(NULL, escaped = h_escape_string(conn, UNSAFE_STRING)); j_query = json_pack("{sss{sisss{ss}}}", "table", "test_table", "values", "integer_col", 43, "string_col", UNSAFE_STRING, "date_col", "raw", "date('now')"); ck_assert_int_eq(h_insert(conn, j_query, &str_query), H_OK); json_decref(j_query); j_query = json_pack("{sss{si}}", "table", "test_table", "where", "integer_col", 43); ck_assert_int_eq(h_select(conn, j_query, &j_result, NULL), H_OK); ck_assert_ptr_ne(j_result, NULL); ck_assert_int_eq(json_is_array(j_result), 1); ck_assert_int_eq(json_array_size(j_result), 1); ck_assert_str_eq(json_string_value(json_object_get(json_array_get(j_result, 0), "string_col")), UNSAFE_STRING); ck_assert_int_eq(json_integer_value(json_object_get(json_array_get(j_result, 0), "integer_col")), 43); json_decref(j_result); ck_assert_ptr_ne(NULL, o_strstr(str_query, escaped)); ck_assert_ptr_eq(NULL, o_strstr(str_query, UNSAFE_STRING)); h_free(str_query); json_decref(j_query); j_query = json_pack("{sss{ss}}", "table", "test_table", "where", "string_col", UNSAFE_STRING); ck_assert_int_eq(h_select(conn, j_query, &j_result, &str_query), H_OK); ck_assert_ptr_ne(NULL, o_strstr(str_query, escaped)); ck_assert_ptr_eq(NULL, o_strstr(str_query, UNSAFE_STRING)); h_free(str_query); ck_assert_ptr_ne(j_result, NULL); ck_assert_int_eq(json_is_array(j_result), 1); ck_assert_int_eq(json_array_size(j_result), 1); ck_assert_str_eq(json_string_value(json_object_get(json_array_get(j_result, 0), "string_col")), UNSAFE_STRING); ck_assert_int_eq(json_integer_value(json_object_get(json_array_get(j_result, 0), "integer_col")), 43); json_decref(j_result); json_decref(j_query); j_query = json_pack("{sss{sssi}s{siss}}", "table", "test_table", "set", "string_col", UNSAFE_STRING " - updated", "integer_col", 44, "where", "integer_col", 43, "string_col", UNSAFE_STRING); ck_assert_int_eq(h_update(conn, j_query, &str_query), H_OK); ck_assert_ptr_ne(NULL, o_strstr(str_query, escaped)); str_query_wip = o_strstr(str_query, escaped)+o_strlen(escaped); ck_assert_ptr_ne(NULL, o_strstr(str_query_wip, escaped)); ck_assert_ptr_eq(NULL, o_strstr(str_query, UNSAFE_STRING)); h_free(str_query); json_decref(j_query); j_query = json_pack("{sss{siss}}", "table", "test_table", "where", "integer_col", 44, "string_col", UNSAFE_STRING " - updated"); ck_assert_int_eq(h_select(conn, j_query, &j_result, &str_query), H_OK); ck_assert_ptr_ne(NULL, o_strstr(str_query, escaped)); ck_assert_ptr_eq(NULL, o_strstr(str_query, UNSAFE_STRING)); h_free(str_query); ck_assert_ptr_ne(j_result, NULL); ck_assert_int_eq(json_is_array(j_result), 1); ck_assert_int_eq(json_array_size(j_result), 1); ck_assert_str_eq(json_string_value(json_object_get(json_array_get(j_result, 0), "string_col")), UNSAFE_STRING " - updated"); ck_assert_int_eq(json_integer_value(json_object_get(json_array_get(j_result, 0), "integer_col")), 44); json_decref(j_result); ck_assert_int_eq(h_delete(conn, j_query, NULL), H_OK); json_decref(j_query); // Test multiple escape j_query = json_pack("{sss[{sissss}{sissss}{sissss}]}", "table", "test_table", "values", "integer_col", 48, "string_col", UNSAFE_STRING " - 2", "string_col ", UNSAFE_STRING, "integer_col", 48, "string_col", UNSAFE_STRING " - updated12", "string_col ", UNSAFE_STRING " - updated1", "integer_col", 48, "string_col", UNSAFE_STRING " - updated22", "string_col ", UNSAFE_STRING " - updated2"); ck_assert_int_eq(h_insert(conn, j_query, &str_query), H_OK); ck_assert_ptr_ne(NULL, o_strstr(str_query, escaped)); str_query_wip = o_strstr(str_query, escaped)+o_strlen(escaped); ck_assert_ptr_ne(NULL, o_strstr(str_query_wip, escaped)); str_query_wip = o_strstr(str_query, escaped)+o_strlen(escaped); ck_assert_ptr_ne(NULL, o_strstr(str_query_wip, escaped)); str_query_wip = o_strstr(str_query, escaped)+o_strlen(escaped); ck_assert_ptr_ne(NULL, o_strstr(str_query_wip, escaped)); str_query_wip = o_strstr(str_query, escaped)+o_strlen(escaped); ck_assert_ptr_ne(NULL, o_strstr(str_query_wip, escaped)); str_query_wip = o_strstr(str_query, escaped)+o_strlen(escaped); ck_assert_ptr_ne(NULL, o_strstr(str_query_wip, escaped)); str_query_wip = o_strstr(str_query, escaped)+o_strlen(escaped); ck_assert_ptr_ne(NULL, o_strstr(str_query_wip, escaped)); ck_assert_ptr_eq(NULL, o_strstr(str_query, UNSAFE_STRING)); json_decref(j_query); h_free(str_query); j_query = json_pack("{sss{si}}", "table", "test_table", "where", "integer_col", 48); ck_assert_int_eq(h_select(conn, j_query, &j_result, NULL), H_OK); json_decref(j_query); ck_assert_ptr_ne(j_result, NULL); ck_assert_int_eq(json_is_array(j_result), 1); ck_assert_int_eq(json_array_size(j_result), 3); ck_assert_str_eq(json_string_value(json_object_get(json_array_get(j_result, 0), "string_col")), UNSAFE_STRING " - 2"); ck_assert_str_eq(json_string_value(json_object_get(json_array_get(j_result, 1), "string_col")), UNSAFE_STRING " - updated12"); ck_assert_str_eq(json_string_value(json_object_get(json_array_get(j_result, 2), "string_col")), UNSAFE_STRING " - updated22"); json_decref(j_result); j_query = json_pack("{sss{ssssss}}", "table", "test_table", "where", "string_col", UNSAFE_STRING, "string_col ", UNSAFE_STRING " - updated1", "string_col ", UNSAFE_STRING " - updated2"); ck_assert_int_eq(h_select(conn, j_query, &j_result, &str_query), H_OK); json_decref(j_query); ck_assert_ptr_ne(NULL, o_strstr(str_query, escaped)); ck_assert_ptr_ne(NULL, o_strstr(o_strstr(str_query, escaped)+o_strlen(escaped), escaped)); str_query_wip = o_strstr(str_query, escaped)+o_strlen(escaped); ck_assert_ptr_ne(NULL, o_strstr(str_query_wip, escaped)); str_query_wip = o_strstr(str_query, escaped)+o_strlen(escaped); ck_assert_ptr_ne(NULL, o_strstr(str_query_wip, escaped)); ck_assert_ptr_eq(NULL, o_strstr(str_query, UNSAFE_STRING)); ck_assert_ptr_ne(j_result, NULL); ck_assert_int_eq(json_is_array(j_result), 1); ck_assert_int_eq(json_array_size(j_result), 0); json_decref(j_result); h_free(str_query); j_query = json_pack("{sss{ssssss}s{sissssss}}", "table", "test_table", "set", "string_col", UNSAFE_STRING " - updated", "string_col ", UNSAFE_STRING " - updated14", "string_col ", UNSAFE_STRING " - updated24", "where", "integer_col", 48, "string_col", UNSAFE_STRING, "string_col ", UNSAFE_STRING " - updated1", "string_col ", UNSAFE_STRING " - updated2"); ck_assert_int_eq(h_update(conn, j_query, &str_query), H_OK); ck_assert_ptr_ne(NULL, o_strstr(str_query, escaped)); str_query_wip = o_strstr(str_query, escaped)+o_strlen(escaped); ck_assert_ptr_ne(NULL, o_strstr(str_query_wip, escaped)); str_query_wip = o_strstr(str_query, escaped)+o_strlen(escaped); ck_assert_ptr_ne(NULL, o_strstr(str_query_wip, escaped)); str_query_wip = o_strstr(str_query, escaped)+o_strlen(escaped); ck_assert_ptr_ne(NULL, o_strstr(str_query_wip, escaped)); str_query_wip = o_strstr(str_query, escaped)+o_strlen(escaped); ck_assert_ptr_ne(NULL, o_strstr(str_query_wip, escaped)); str_query_wip = o_strstr(str_query, escaped)+o_strlen(escaped); ck_assert_ptr_ne(NULL, o_strstr(str_query_wip, escaped)); ck_assert_ptr_eq(NULL, o_strstr(str_query, UNSAFE_STRING)); h_free(str_query); json_decref(j_query); j_query = json_pack("{sss{si}}", "table", "test_table", "where", "integer_col", 48); ck_assert_int_eq(h_delete(conn, j_query, NULL), H_OK); json_decref(j_query); h_free(escaped); ck_assert_int_eq(h_close_db(conn), H_OK); ck_assert_int_eq(h_clean_connection(conn), H_OK); } END_TEST START_TEST(test_hoel_json_generate_where_clause) { struct _h_connection * conn; char * where_clause = NULL; json_t * j_query = json_pack("{sss{sisss{ss}}}", "table", "test_table", "values", "integer_col", 55, "string_col", "value1", "date_col", "raw", "date('now')"), * j_result = NULL, * j_string = json_string(UNSAFE_STRING), * j_integer = json_integer(22), * j_real = json_real(9.9); conn = h_connect_sqlite(DEFAULT_BD_PATH); ck_assert_ptr_ne(conn, NULL); ck_assert_int_eq(h_insert(conn, j_query, NULL), H_OK); json_decref(j_query); where_clause = h_build_where_clause(conn, "integer_col = %d AND string_col = %s", (json_int_t)55, "value1"); j_query = json_pack("{sss{s{ssss}}}", "table", "test_table", "where", "", "operator", "raw", "value", where_clause); ck_assert_int_eq(h_select(conn, j_query, &j_result, NULL), H_OK); ck_assert_ptr_ne(j_result, NULL); ck_assert_int_eq(json_is_array(j_result), 1); ck_assert_int_eq(json_array_size(j_result), 1); json_decref(j_query); json_decref(j_result); h_free(where_clause); where_clause = h_build_where_clause(conn, "0.0 = %f AND '%%lol' = '%%lol' AND string_col = %s", (double)0.0, UNSAFE_STRING); j_query = json_pack("{sss{s{ssss}}}", "table", "test_table", "where", "", "operator", "raw", "value", where_clause); ck_assert_int_eq(h_select(conn, j_query, &j_result, NULL), H_OK); ck_assert_ptr_ne(j_result, NULL); ck_assert_int_eq(json_is_array(j_result), 1); ck_assert_int_eq(json_array_size(j_result), 0); json_decref(j_query); json_decref(j_result); h_free(where_clause); where_clause = h_build_where_clause(conn, "0.0 = %f AND '%%lol' = '%%lol' AND string_col = '%S'", (double)0.0, UNSAFE_STRING); j_query = json_pack("{sss{s{ssss}}}", "table", "test_table", "where", "", "operator", "raw", "value", where_clause); ck_assert_int_eq(h_select(conn, j_query, &j_result, NULL), H_OK); ck_assert_ptr_ne(j_result, NULL); ck_assert_int_eq(json_is_array(j_result), 1); ck_assert_int_eq(json_array_size(j_result), 0); json_decref(j_query); json_decref(j_result); h_free(where_clause); where_clause = h_build_where_clause(conn, "string_col = '%S' OR string_col = '%S' OR string_col = '%S'", UNSAFE_STRING, UNSAFE_STRING " - updated1", UNSAFE_STRING " - updated2"); j_query = json_pack("{sss{s{ssss}}}", "table", "test_table", "where", "", "operator", "raw", "value", where_clause); ck_assert_int_eq(h_select(conn, j_query, &j_result, NULL), H_OK); ck_assert_ptr_ne(j_result, NULL); ck_assert_int_eq(json_is_array(j_result), 1); ck_assert_int_eq(json_array_size(j_result), 0); json_decref(j_query); json_decref(j_result); h_free(where_clause); where_clause = h_build_where_clause(conn, "string_col = '%S' OR string_col = %s OR string_col = %c OR string_col = '%C'", UNSAFE_STRING, UNSAFE_STRING " - updated1", "value1", "value2"); j_query = json_pack("{sss{s{ssss}}}", "table", "test_table", "where", "", "operator", "raw", "value", where_clause); ck_assert_int_eq(h_select(conn, j_query, &j_result, NULL), H_OK); ck_assert_ptr_ne(j_result, NULL); ck_assert_int_eq(json_is_array(j_result), 1); ck_assert_int_eq(json_array_size(j_result), 1); json_decref(j_query); json_decref(j_result); h_free(where_clause); where_clause = h_build_where_clause(conn, "0.0 = %f AND '%%lol' = '%%lol' AND string_col = %c", (double)0.0, "value1"); j_query = json_pack("{sss{s{ssss}}}", "table", "test_table", "where", "", "operator", "raw", "value", where_clause); ck_assert_int_eq(h_select(conn, j_query, &j_result, NULL), H_OK); ck_assert_ptr_ne(j_result, NULL); ck_assert_int_eq(json_is_array(j_result), 1); ck_assert_int_eq(json_array_size(j_result), 1); json_decref(j_query); json_decref(j_result); h_free(where_clause); where_clause = h_build_where_clause(conn, "0.0 = %f AND '%%lol' = '%%lol' AND string_col = '%C'", (double)0.0, "value1"); j_query = json_pack("{sss{s{ssss}}}", "table", "test_table", "where", "", "operator", "raw", "value", where_clause); ck_assert_int_eq(h_select(conn, j_query, &j_result, NULL), H_OK); ck_assert_ptr_ne(j_result, NULL); ck_assert_int_eq(json_is_array(j_result), 1); ck_assert_int_eq(json_array_size(j_result), 1); json_decref(j_query); json_decref(j_result); h_free(where_clause); where_clause = h_build_where_clause(conn, "0.0 = %f AND '%%lol' = '%%lol' AND string_col = %c", (double)0.0, UNSAFE_STRING); j_query = json_pack("{sss{s{ssss}}}", "table", "test_table", "where", "", "operator", "raw", "value", where_clause); j_result = NULL; ck_assert_int_eq(h_select(conn, j_query, &j_result, NULL), H_ERROR_QUERY); ck_assert_ptr_eq(j_result, NULL); json_decref(j_query); h_free(where_clause); j_query = json_pack("{sss{si}}", "table", "test_table", "where", "integer_col", 55); ck_assert_int_eq(h_delete(conn, j_query, NULL), H_OK); json_decref(j_query); where_clause = h_build_where_clause(conn, "0.0 = %j AND integer_col = %j AND string_col = %j AND string_col = %s", j_real, j_integer, j_string, UNSAFE_STRING); j_query = json_pack("{sss{s{ssss}}}", "table", "test_table", "where", "", "operator", "raw", "value", where_clause); ck_assert_int_eq(h_select(conn, j_query, &j_result, NULL), H_OK); ck_assert_ptr_ne(j_result, NULL); ck_assert_int_eq(json_is_array(j_result), 1); ck_assert_int_eq(json_array_size(j_result), 0); json_decref(j_query); json_decref(j_result); h_free(where_clause); where_clause = h_build_where_clause(conn, WHERE_CLAUSE_NO_FORMAT); ck_assert_str_eq(where_clause, WHERE_CLAUSE_NO_FORMAT); h_free(where_clause); ck_assert_ptr_eq(NULL, h_build_where_clause(NULL, "0.0 = %f AND '%%lol' = '%%lol' AND string_col = '%S'", (double)0.0, UNSAFE_STRING)); ck_assert_ptr_eq(NULL, h_build_where_clause(conn, "error = %j", json_null())); ck_assert_ptr_eq(NULL, h_build_where_clause(conn, NULL, (double)0.0, UNSAFE_STRING)); ck_assert_ptr_eq(NULL, h_build_where_clause(conn, "", (double)0.0, UNSAFE_STRING)); ck_assert_ptr_eq(NULL, h_build_where_clause(conn, "this is an error %", (double)0.0, UNSAFE_STRING)); ck_assert_ptr_eq(NULL, h_build_where_clause(conn, "this is another error %n to test", (double)0.0, UNSAFE_STRING)); json_decref(j_real); json_decref(j_integer); json_decref(j_string); ck_assert_int_eq(h_close_db(conn), H_OK); ck_assert_int_eq(h_clean_connection(conn), H_OK); } END_TEST static Suite *hoel_suite(void) { Suite *s; TCase *tc_core; s = suite_create("Hoel core tests"); tc_core = tcase_create("test_hoel_core"); tcase_add_test(tc_core, test_hoel_init); tcase_add_test(tc_core, test_hoel_escape_string); tcase_add_test(tc_core, test_hoel_escape_string_with_quotes); tcase_add_test(tc_core, test_hoel_insert); tcase_add_test(tc_core, test_hoel_update); tcase_add_test(tc_core, test_hoel_delete); tcase_add_test(tc_core, test_hoel_json_insert); tcase_add_test(tc_core, test_hoel_json_update); tcase_add_test(tc_core, test_hoel_json_delete); tcase_add_test(tc_core, test_hoel_json_select); tcase_add_test(tc_core, test_hoel_json_escape); tcase_add_test(tc_core, test_hoel_json_generate_where_clause); tcase_set_timeout(tc_core, 30); suite_add_tcase(s, tc_core); return s; } int main(int argc, char *argv[]) { int number_failed; Suite *s; SRunner *sr; //y_init_logs("Hoel", Y_LOG_MODE_CONSOLE, Y_LOG_LEVEL_DEBUG, NULL, "Starting Hoel core tests"); s = hoel_suite(); sr = srunner_create(s); srunner_run_all(sr, CK_VERBOSE); number_failed = srunner_ntests_failed(sr); srunner_free(sr); //y_close_logs(); return (number_failed == 0) ? EXIT_SUCCESS : EXIT_FAILURE; } hoel-1.4.29/test/multi.c000066400000000000000000001160641452453561700150370ustar00rootroot00000000000000/* Public domain, no copyright. Use at your own risk. */ /* This program tests the behavior is correct in all supported backends */ #include #include #include #include #include #include #include "hoel.h" /**************************************************/ /* Set the database backend you want to test here */ /**************************************************/ #define SQLITE //#define MARIADB //#define PGSQL #ifdef SQLITE #define SQLITE_BD_PATH "/tmp/test.db" #define NOW "date('now')" #define DATE_FIXED "strftime('%s','2016-06-22 00:52:56')" #define SAFE "unsafe '' value\"!" #define SAFE_QUOTE "'unsafe '' value\"!'" #endif #ifdef MARIADB #define MARIADB_HOST "localhost" #define MARIADB_USER "test" #define MARIADB_PASSWD "test" #define MARIADB_DB "test" #define MARIADB_PORT 0 #define NOW "NOW()" #define DATE_FIXED "STR_TO_DATE('2016-06-22 00:52:56','%Y-%m-%d %H:%i:%s')" #define SAFE "unsafe \\' value\\\"!" #define SAFE_QUOTE "'unsafe \\' value\\\"!'" #endif #ifdef PGSQL #define PGSQL_CONNINFO "host=localhost dbname=test user=test password=test" #define NOW "NOW()" #define DATE_FIXED "to_date('2016-06-22 00:52:56','YYYY-MM-DD HH24:MI:SS')" #define SAFE "unsafe '' value\"!" #define SAFE_QUOTE "'unsafe '' value\"!'" #endif #define UNSAFE_STRING "un'safe' (\"string\")#!/$%*];" #define SELECT_DATA_1 "SELECT integer_col, double_col, string_col, date_col FROM test_table WHERE integer_col = 1" #define SELECT_DATA_2 "SELECT integer_col, double_col, string_col, date_col FROM test_table WHERE integer_col = 2" #define SELECT_DATA_ERROR "SELECT integer_col, double_col, string_col, date_col FROM test_table WHERE integer_col = 'error'" #define SELECT_DATA_ALL "SELECT * FROM test_table" #define INSERT_DATA_1 "INSERT INTO test_table (integer_col, double_col, string_col, date_col) VALUES (1, 4.2, 'value1', "NOW")" #define INSERT_DATA_2 "INSERT INTO test_table (integer_col, double_col, string_col, date_col) VALUES (2, 5.4, 'value2', "DATE_FIXED")" #define INSERT_DATA_ERROR "INSERT INTO test_table (integer_col, double_col, string_col, date_col) VALUES ('error', 'error_double', 'value error', "NOW")" #define DELETE_DATA_1 "DELETE FROM test_table WHERE integer_col = 1" #define DELETE_DATA_2 "DELETE FROM test_table WHERE integer_col = 2" #define DELETE_DATA_ERROR "DELETE FROM test_table WHERE wrong_table = 1" #define DELETE_DATA_ALL "DELETE FROM test_table" #define UPDATE_DATA_1 "UPDATE test_table SET string_col='new value1', double_col=5.4 WHERE integer_col = 1" START_TEST(test_hoel_escape_string) { json_t * j_query, * j_result; char * str_query = NULL, * escaped; int res; struct _h_connection * conn = NULL; #ifdef SQLITE // Sqlite3 conn = h_connect_sqlite(SQLITE_BD_PATH); #endif #ifdef MARIADB // Mysql conn = h_connect_mariadb(MARIADB_HOST, MARIADB_USER, MARIADB_PASSWD, MARIADB_DB, MARIADB_PORT, NULL); #endif #ifdef PGSQL // PostgreSQL conn = h_connect_pgsql(PGSQL_CONNINFO); #endif escaped = h_escape_string(conn, "value"); ck_assert_str_eq(escaped, "value"); h_free(escaped); escaped = h_escape_string(conn, "'"); ck_assert_ptr_ne(escaped, NULL); h_free(escaped); escaped = h_escape_string(conn, ""); ck_assert_str_eq(escaped, ""); h_free(escaped); escaped = h_escape_string(conn, "unsafe ' value\"!"); ck_assert_str_eq(escaped, SAFE); h_free(escaped); j_query = json_pack("{sss{siss}}", "table", "test_table", "values", "integer_col", 666, "string_col", UNSAFE_STRING); res = h_insert(conn, j_query, NULL); json_decref(j_query); ck_assert_int_eq(res, H_OK); j_query = json_pack("{sss[s]s{si}}", "table", "test_table", "columns", "string_col", "where", "integer_col", 666); res = h_select(conn, j_query, &j_result, NULL); ck_assert_int_eq(res, H_OK); ck_assert_str_eq(UNSAFE_STRING, json_string_value(json_object_get(json_array_get(j_result, 0), "string_col"))); json_decref(j_result); res = h_delete(conn, j_query, NULL); json_decref(j_query); j_query = json_pack("{sss{siss}}", "table", "test_table", "values", "integer_col", 43, "string_col", UNSAFE_STRING); ck_assert_ptr_ne(NULL, escaped = h_escape_string(conn, UNSAFE_STRING)); ck_assert_int_eq(h_insert(conn, j_query, &str_query), H_OK); json_decref(j_query); j_query = json_pack("{sss{si}}", "table", "test_table", "where", "integer_col", 43); ck_assert_int_eq(h_select(conn, j_query, &j_result, NULL), H_OK); ck_assert_ptr_ne(j_result, NULL); ck_assert_int_eq(json_is_array(j_result), 1); ck_assert_int_eq(json_array_size(j_result), 1); ck_assert_str_eq(json_string_value(json_object_get(json_array_get(j_result, 0), "string_col")), UNSAFE_STRING); ck_assert_int_eq(json_integer_value(json_object_get(json_array_get(j_result, 0), "integer_col")), 43); json_decref(j_result); ck_assert_ptr_ne(NULL, o_strstr(str_query, escaped)); ck_assert_ptr_eq(NULL, o_strstr(str_query, UNSAFE_STRING)); h_free(str_query); json_decref(j_query); j_query = json_pack("{sss{ss}}", "table", "test_table", "where", "string_col", UNSAFE_STRING); ck_assert_int_eq(h_select(conn, j_query, &j_result, &str_query), H_OK); ck_assert_ptr_ne(NULL, o_strstr(str_query, escaped)); ck_assert_ptr_eq(NULL, o_strstr(str_query, UNSAFE_STRING)); h_free(str_query); ck_assert_ptr_ne(j_result, NULL); ck_assert_int_eq(json_is_array(j_result), 1); ck_assert_int_eq(json_array_size(j_result), 1); ck_assert_str_eq(json_string_value(json_object_get(json_array_get(j_result, 0), "string_col")), UNSAFE_STRING); ck_assert_int_eq(json_integer_value(json_object_get(json_array_get(j_result, 0), "integer_col")), 43); json_decref(j_result); json_decref(j_query); j_query = json_pack("{sss{sssi}s{siss}}", "table", "test_table", "set", "string_col", UNSAFE_STRING " - updated", "integer_col", 44, "where", "integer_col", 43, "string_col", UNSAFE_STRING); ck_assert_int_eq(h_update(conn, j_query, &str_query), H_OK); ck_assert_ptr_ne(NULL, o_strstr(str_query, escaped)); ck_assert_ptr_ne(NULL, o_strstr(o_strstr(str_query, escaped)+o_strlen(escaped), escaped)); ck_assert_ptr_eq(NULL, o_strstr(str_query, UNSAFE_STRING)); h_free(str_query); json_decref(j_query); j_query = json_pack("{sss{siss}}", "table", "test_table", "where", "integer_col", 44, "string_col", UNSAFE_STRING " - updated"); ck_assert_int_eq(h_select(conn, j_query, &j_result, &str_query), H_OK); json_decref(j_query); ck_assert_ptr_ne(NULL, o_strstr(str_query, escaped)); ck_assert_ptr_eq(NULL, o_strstr(str_query, UNSAFE_STRING)); h_free(str_query); ck_assert_ptr_ne(j_result, NULL); ck_assert_int_eq(json_is_array(j_result), 1); ck_assert_int_eq(json_array_size(j_result), 1); ck_assert_str_eq(json_string_value(json_object_get(json_array_get(j_result, 0), "string_col")), UNSAFE_STRING " - updated"); ck_assert_int_eq(json_integer_value(json_object_get(json_array_get(j_result, 0), "integer_col")), 44); json_decref(j_result); j_query = json_pack("{sss{sis{sss[ss]}}}", "table", "test_table", "where", "integer_col", 44, "string_col", "operator", "IN", "value", UNSAFE_STRING " - updated", "42"); ck_assert_int_eq(h_select(conn, j_query, &j_result, &str_query), H_OK); ck_assert_ptr_ne(NULL, o_strstr(str_query, escaped)); ck_assert_ptr_eq(NULL, o_strstr(str_query, UNSAFE_STRING)); h_free(str_query); ck_assert_ptr_ne(j_result, NULL); ck_assert_int_eq(json_is_array(j_result), 1); ck_assert_int_eq(json_array_size(j_result), 1); ck_assert_str_eq(json_string_value(json_object_get(json_array_get(j_result, 0), "string_col")), UNSAFE_STRING " - updated"); ck_assert_int_eq(json_integer_value(json_object_get(json_array_get(j_result, 0), "integer_col")), 44); json_decref(j_result); json_decref(j_query); // Test that a unsafe string is unsafe j_query = json_pack("{sss{s{ssss}}}", "table", "test_table", "where", "string_col", "operator", "raw", "value", UNSAFE_STRING); ck_assert_ptr_ne(NULL, j_query); ck_assert_int_ne(h_select(conn, j_query, NULL, NULL), H_OK); json_decref(j_query); j_query = json_pack("{sss{si}}", "table", "test_table", "where", "integer_col", 44); ck_assert_int_eq(h_delete(conn, j_query, NULL), H_OK); json_decref(j_query); h_free(escaped); h_close_db(conn); h_clean_connection(conn); } END_TEST START_TEST(test_hoel_escape_string_with_quotes) { char * escaped; json_t * j_query, * j_result; int res; struct _h_connection * conn = NULL; #ifdef SQLITE // Sqlite3 conn = h_connect_sqlite(SQLITE_BD_PATH); #endif #ifdef MARIADB // Mysql conn = h_connect_mariadb(MARIADB_HOST, MARIADB_USER, MARIADB_PASSWD, MARIADB_DB, MARIADB_PORT, NULL); #endif #ifdef PGSQL // PostgreSQL conn = h_connect_pgsql(PGSQL_CONNINFO); #endif escaped = h_escape_string_with_quotes(conn, "value"); ck_assert_str_eq(escaped, "'value'"); h_free(escaped); escaped = h_escape_string_with_quotes(conn, ""); ck_assert_str_eq(escaped, "''"); h_free(escaped); escaped = h_escape_string_with_quotes(conn, "'"); ck_assert_ptr_ne(escaped, NULL); h_free(escaped); escaped = h_escape_string_with_quotes(conn, "unsafe ' value\"!"); ck_assert_str_eq(escaped, SAFE_QUOTE); h_free(escaped); j_query = json_pack("{sss{siss}}", "table", "test_table", "values", "integer_col", 666, "string_col", UNSAFE_STRING); res = h_insert(conn, j_query, NULL); json_decref(j_query); ck_assert_int_eq(res, H_OK); j_query = json_pack("{sss[s]s{si}}", "table", "test_table", "columns", "string_col", "where", "integer_col", 666); res = h_select(conn, j_query, &j_result, NULL); json_decref(j_query); ck_assert_int_eq(res, H_OK); ck_assert_str_eq(UNSAFE_STRING, json_string_value(json_object_get(json_array_get(j_result, 0), "string_col"))); json_decref(j_result); h_close_db(conn); h_clean_connection(conn); } END_TEST START_TEST(test_hoel_insert) { struct _h_result result; struct _h_data * last_id; struct _h_connection * conn = NULL; #ifdef SQLITE // Sqlite3 conn = h_connect_sqlite(SQLITE_BD_PATH); #endif #ifdef MARIADB // Mysql conn = h_connect_mariadb(MARIADB_HOST, MARIADB_USER, MARIADB_PASSWD, MARIADB_DB, MARIADB_PORT, NULL); #endif #ifdef PGSQL // PostgreSQL conn = h_connect_pgsql(PGSQL_CONNINFO); #endif ck_assert_int_eq(h_query_delete(conn, DELETE_DATA_ALL), H_OK); ck_assert_int_eq(h_query_insert(conn, INSERT_DATA_1), H_OK); last_id = h_query_last_insert_id(conn); ck_assert_int_eq(last_id->type, HOEL_COL_TYPE_INT); ck_assert_int_gt(((struct _h_type_int *)last_id->t_data)->value, 0); ck_assert_int_eq(h_clean_data(last_id), H_OK); h_free(last_id); ck_assert_ptr_ne(last_id, NULL); ck_assert_int_eq(h_query_insert(conn, NULL), H_ERROR_PARAMS); ck_assert_int_eq(h_query_select(conn, SELECT_DATA_1, &result), H_OK); ck_assert_int_eq(result.nb_rows, 1); ck_assert_int_eq(result.nb_columns, 4); ck_assert_int_eq(result.data[0][0].type, HOEL_COL_TYPE_INT); ck_assert_int_eq(((struct _h_type_int *)result.data[0][0].t_data)->value, 1); ck_assert_int_eq(result.data[0][1].type, HOEL_COL_TYPE_DOUBLE); ck_assert_double_eq(((struct _h_type_double *)result.data[0][1].t_data)->value, 4.2); ck_assert_int_eq(result.data[0][2].type, HOEL_COL_TYPE_TEXT); ck_assert_str_eq(((struct _h_type_text *)result.data[0][2].t_data)->value, "value1"); ck_assert_int_eq(h_clean_result(&result), H_OK); #ifdef PGSQL ck_assert_int_eq(h_query_select(conn, SELECT_DATA_ERROR, &result), H_ERROR_QUERY); #else ck_assert_int_eq(h_query_select(conn, SELECT_DATA_ERROR, &result), H_OK); ck_assert_int_eq(result.nb_rows, 0); ck_assert_int_eq(result.nb_columns, 4); ck_assert_int_eq(h_clean_result(&result), H_OK); #endif ck_assert_int_eq(h_query_delete(conn, DELETE_DATA_1), H_OK); h_close_db(conn); h_clean_connection(conn); } END_TEST START_TEST(test_hoel_update) { struct _h_result result; struct _h_connection * conn = NULL; #ifdef SQLITE // Sqlite3 conn = h_connect_sqlite(SQLITE_BD_PATH); #endif #ifdef MARIADB // Mysql conn = h_connect_mariadb(MARIADB_HOST, MARIADB_USER, MARIADB_PASSWD, MARIADB_DB, MARIADB_PORT, NULL); #endif #ifdef PGSQL // PostgreSQL conn = h_connect_pgsql(PGSQL_CONNINFO); #endif ck_assert_int_eq(h_query_insert(conn, INSERT_DATA_1), H_OK); ck_assert_int_eq(h_query_insert(conn, NULL), H_ERROR_PARAMS); ck_assert_int_eq(h_query_select(conn, SELECT_DATA_1, &result), H_OK); ck_assert_int_eq(result.nb_rows, 1); ck_assert_int_eq(result.nb_columns, 4); ck_assert_int_eq(((struct _h_type_int *)result.data[0][0].t_data)->value, 1); ck_assert_double_eq(((struct _h_type_double *)result.data[0][1].t_data)->value, 4.2); ck_assert_str_eq(((struct _h_type_text *)result.data[0][2].t_data)->value, "value1"); ck_assert_int_eq(h_clean_result(&result), H_OK); ck_assert_int_eq(h_query_update(conn, UPDATE_DATA_1), H_OK); ck_assert_int_eq(h_query_select(conn, SELECT_DATA_1, &result), H_OK); ck_assert_int_eq(result.nb_rows, 1); ck_assert_int_eq(result.nb_columns, 4); ck_assert_int_eq(((struct _h_type_int *)result.data[0][0].t_data)->value, 1); ck_assert_double_eq(((struct _h_type_double *)result.data[0][1].t_data)->value, 5.4); ck_assert_str_eq(((struct _h_type_text *)result.data[0][2].t_data)->value, "new value1"); ck_assert_int_eq(h_clean_result(&result), H_OK); ck_assert_int_eq(h_query_delete(conn, DELETE_DATA_1), H_OK); h_close_db(conn); h_clean_connection(conn); } END_TEST START_TEST(test_hoel_delete) { struct _h_result result; struct _h_connection * conn = NULL; #ifdef SQLITE // Sqlite3 conn = h_connect_sqlite(SQLITE_BD_PATH); #endif #ifdef MARIADB // Mysql conn = h_connect_mariadb(MARIADB_HOST, MARIADB_USER, MARIADB_PASSWD, MARIADB_DB, MARIADB_PORT, NULL); #endif #ifdef PGSQL // PostgreSQL conn = h_connect_pgsql(PGSQL_CONNINFO); #endif ck_assert_int_eq(h_query_insert(conn, INSERT_DATA_1), H_OK); ck_assert_int_eq(h_query_insert(conn, INSERT_DATA_2), H_OK); ck_assert_int_eq(h_query_select(conn, SELECT_DATA_1, &result), H_OK); ck_assert_int_eq(result.nb_rows, 1); ck_assert_int_eq(result.nb_columns, 4); ck_assert_int_eq(result.data[0][0].type, HOEL_COL_TYPE_INT); ck_assert_int_eq(((struct _h_type_int *)result.data[0][0].t_data)->value, 1); ck_assert_int_eq(result.data[0][1].type, HOEL_COL_TYPE_DOUBLE); ck_assert_double_eq(((struct _h_type_double *)result.data[0][1].t_data)->value, 4.2); ck_assert_int_eq(result.data[0][2].type, HOEL_COL_TYPE_TEXT); ck_assert_str_eq(((struct _h_type_text *)result.data[0][2].t_data)->value, "value1"); ck_assert_int_eq(h_clean_result(&result), H_OK); ck_assert_int_eq(h_query_select(conn, SELECT_DATA_2, &result), H_OK); ck_assert_int_eq(result.nb_rows, 1); ck_assert_int_eq(result.nb_columns, 4); ck_assert_int_eq(result.data[0][0].type, HOEL_COL_TYPE_INT); ck_assert_int_eq(((struct _h_type_int *)result.data[0][0].t_data)->value, 2); ck_assert_int_eq(result.data[0][1].type, HOEL_COL_TYPE_DOUBLE); ck_assert_double_eq(((struct _h_type_double *)result.data[0][1].t_data)->value, 5.4); ck_assert_int_eq(result.data[0][2].type, HOEL_COL_TYPE_TEXT); ck_assert_str_eq(((struct _h_type_text *)result.data[0][2].t_data)->value, "value2"); ck_assert_int_eq(h_clean_result(&result), H_OK); ck_assert_int_eq(h_query_delete(conn, DELETE_DATA_1), H_OK); ck_assert_int_eq(h_query_select(conn, SELECT_DATA_ALL, &result), H_OK); ck_assert_int_eq(result.nb_rows, 1); ck_assert_int_eq(h_clean_result(&result), H_OK); ck_assert_int_eq(h_query_delete(conn, DELETE_DATA_2), H_OK); ck_assert_int_eq(h_query_select(conn, SELECT_DATA_ALL, &result), H_OK); ck_assert_int_eq(result.nb_rows, 0); ck_assert_int_eq(h_clean_result(&result), H_OK); h_close_db(conn); h_clean_connection(conn); } END_TEST START_TEST(test_hoel_json_insert) { struct _h_connection * conn = NULL; #ifdef SQLITE // Sqlite3 conn = h_connect_sqlite(SQLITE_BD_PATH); #endif #ifdef MARIADB // Mysql conn = h_connect_mariadb(MARIADB_HOST, MARIADB_USER, MARIADB_PASSWD, MARIADB_DB, MARIADB_PORT, NULL); #endif #ifdef PGSQL // PostgreSQL conn = h_connect_pgsql(PGSQL_CONNINFO); #endif char * str_query = NULL; json_t * j_query = json_pack("{sss{sisss{ss}sf}}", "table", "test_table", "values", "integer_col", 1, "string_col", "value1", "date_col", "raw", NOW, "double_col", 4.2), * j_result = NULL; ck_assert_int_eq(h_insert(conn, j_query, &str_query), H_OK); json_decref(j_query); j_query = json_pack("{sss{si}}", "table", "test_table", "where", "integer_col", 1); ck_assert_int_eq(h_select(conn, j_query, &j_result, NULL), H_OK); ck_assert_ptr_ne(j_result, NULL); ck_assert_int_eq(json_is_array(j_result), 1); ck_assert_int_eq(json_array_size(j_result), 1); ck_assert_str_eq(json_string_value(json_object_get(json_array_get(j_result, 0), "string_col")), "value1"); ck_assert_int_eq(json_integer_value(json_object_get(json_array_get(j_result, 0), "integer_col")), 1); ck_assert_double_eq(json_real_value(json_object_get(json_array_get(j_result, 0), "double_col")), 4.2); json_decref(j_result); ck_assert_int_eq(o_strlen(str_query), o_strlen("INSERT INTO test_table (integer_col,string_col,date_col,double_col) VALUES (1,'value1',"NOW",4.200000)")); h_free(str_query); ck_assert_int_eq(h_delete(conn, j_query, NULL), H_OK); json_decref(j_query); h_close_db(conn); h_clean_connection(conn); } END_TEST START_TEST(test_hoel_json_update) { struct _h_connection * conn = NULL; #ifdef SQLITE // Sqlite3 conn = h_connect_sqlite(SQLITE_BD_PATH); #endif #ifdef MARIADB // Mysql conn = h_connect_mariadb(MARIADB_HOST, MARIADB_USER, MARIADB_PASSWD, MARIADB_DB, MARIADB_PORT, NULL); #endif #ifdef PGSQL // PostgreSQL conn = h_connect_pgsql(PGSQL_CONNINFO); #endif char * str_query = NULL; json_t * j_query = json_pack("{sss{sisss{ss}sf}}", "table", "test_table", "values", "integer_col", 1, "string_col", "value1", "date_col", "raw", NOW, "double_col", 4.2), * j_result = NULL; ck_assert_int_eq(h_insert(conn, j_query, NULL), H_OK); json_decref(j_query); j_query = json_pack("{sss{si}}", "table", "test_table", "where", "integer_col", 1); ck_assert_int_eq(h_select(conn, j_query, &j_result, NULL), H_OK); json_decref(j_query); ck_assert_ptr_ne(j_result, NULL); ck_assert_int_eq(json_is_array(j_result), 1); ck_assert_int_eq(json_array_size(j_result), 1); ck_assert_str_eq(json_string_value(json_object_get(json_array_get(j_result, 0), "string_col")), "value1"); ck_assert_int_eq(json_integer_value(json_object_get(json_array_get(j_result, 0), "integer_col")), 1); ck_assert_double_eq(json_real_value(json_object_get(json_array_get(j_result, 0), "double_col")), 4.2); json_decref(j_result); j_query = json_pack("{sss{sssf}s{si}}", "table", "test_table", "set", "string_col", "new value1", "double_col", 5.4, "where", "integer_col", 1); ck_assert_int_eq(h_update(conn, j_query, &str_query), H_OK); json_decref(j_query); ck_assert_int_eq(o_strlen(str_query), o_strlen("UPDATE test_table SET string_col='new value1', double_col=5.400000 WHERE integer_col='1'")); h_free(str_query); j_query = json_pack("{sss{si}}", "table", "test_table", "where", "integer_col", 1); ck_assert_int_eq(h_select(conn, j_query, &j_result, NULL), H_OK); ck_assert_ptr_ne(j_result, NULL); ck_assert_int_eq(json_array_size(j_result), 1); ck_assert_str_eq(json_string_value(json_object_get(json_array_get(j_result, 0), "string_col")), "new value1"); ck_assert_int_eq(json_integer_value(json_object_get(json_array_get(j_result, 0), "integer_col")), 1); ck_assert_double_eq(json_real_value(json_object_get(json_array_get(j_result, 0), "double_col")), 5.4); json_decref(j_result); ck_assert_int_eq(h_delete(conn, j_query, NULL), H_OK); json_decref(j_query); h_close_db(conn); h_clean_connection(conn); } END_TEST START_TEST(test_hoel_json_delete) { struct _h_connection * conn = NULL; #ifdef SQLITE // Sqlite3 conn = h_connect_sqlite(SQLITE_BD_PATH); #endif #ifdef MARIADB // Mysql conn = h_connect_mariadb(MARIADB_HOST, MARIADB_USER, MARIADB_PASSWD, MARIADB_DB, MARIADB_PORT, NULL); #endif #ifdef PGSQL // PostgreSQL conn = h_connect_pgsql(PGSQL_CONNINFO); #endif char * str_query = NULL; json_t * j_query = json_pack("{sss{sisss{ss}sf}}", "table", "test_table", "values", "integer_col", 1, "string_col", "value1", "date_col", "raw", NOW, "double_col", 4.2), * j_result = NULL; ck_assert_int_eq(h_insert(conn, j_query, NULL), H_OK); json_decref(j_query); j_query = json_pack("{sss{sisss{ss}sf}}", "table", "test_table", "values", "integer_col", 2, "string_col", "value2", "date_col", "raw", DATE_FIXED, "double_col", 5.4); ck_assert_int_eq(h_insert(conn, j_query, NULL), H_OK); json_decref(j_query); j_query = json_pack("{ss}", "table", "test_table"); ck_assert_int_eq(h_select(conn, j_query, &j_result, NULL), H_OK); json_decref(j_query); ck_assert_ptr_ne(j_result, NULL); ck_assert_int_eq(json_is_array(j_result), 1); ck_assert_int_eq(json_array_size(j_result), 2); json_decref(j_result); j_query = json_pack("{sss{si}}", "table", "test_table", "where", "integer_col", 1); ck_assert_int_eq(h_delete(conn, j_query, &str_query), H_OK); ck_assert_int_eq(o_strlen(str_query), o_strlen("DELETE FROM test_table WHERE integer_col='1'")); h_free(str_query); json_decref(j_query); j_query = json_pack("{ss}", "table", "test_table"); ck_assert_int_eq(h_select(conn, j_query, &j_result, NULL), H_OK); json_decref(j_query); ck_assert_int_eq(json_array_size(j_result), 1); ck_assert_str_eq(json_string_value(json_object_get(json_array_get(j_result, 0), "string_col")), "value2"); ck_assert_int_eq(json_integer_value(json_object_get(json_array_get(j_result, 0), "integer_col")), 2); ck_assert_double_eq(json_real_value(json_object_get(json_array_get(j_result, 0), "double_col")), 5.4); #ifdef SQLITE ck_assert_int_eq(json_integer_value(json_object_get(json_array_get(j_result, 0), "date_col")), 1466556776); #endif #ifdef MARIADB ck_assert_str_eq(json_string_value(json_object_get(json_array_get(j_result, 0), "date_col")), "2016-06-22T00:52:56"); #endif json_decref(j_result); j_query = json_pack("{ss}", "table", "test_table"); ck_assert_int_eq(h_delete(conn, j_query, NULL), H_OK); ck_assert_int_eq(h_select(conn, j_query, &j_result, NULL), H_OK); ck_assert_int_eq(json_array_size(j_result), 0); json_decref(j_result); json_decref(j_query); h_close_db(conn); h_clean_connection(conn); } END_TEST START_TEST(test_hoel_json_select) { struct _h_connection * conn = NULL; #ifdef SQLITE // Sqlite3 conn = h_connect_sqlite(SQLITE_BD_PATH); #endif #ifdef MARIADB // Mysql conn = h_connect_mariadb(MARIADB_HOST, MARIADB_USER, MARIADB_PASSWD, MARIADB_DB, MARIADB_PORT, NULL); #endif #ifdef PGSQL // PostgreSQL conn = h_connect_pgsql(PGSQL_CONNINFO); #endif char * str_query = NULL; json_t * j_query = json_pack("{sss{sisss{ss}sf}}", "table", "test_table", "values", "integer_col", 1, "string_col", "value1", "date_col", "raw", NOW, "double_col", 4.2), * j_result = NULL; ck_assert_ptr_ne(conn, NULL); ck_assert_int_eq(h_insert(conn, j_query, NULL), H_OK); json_decref(j_query); j_query = json_pack("{sss{sisss{ss}sf}}", "table", "test_table", "values", "integer_col", 2, "string_col", "value2", "date_col", "raw", DATE_FIXED, "double_col", 5.4); ck_assert_int_eq(h_insert(conn, j_query, NULL), H_OK); json_decref(j_query); j_query = json_pack("{ss}", "table", "test_table"); ck_assert_int_eq(h_select(conn, j_query, &j_result, &str_query), H_OK); ck_assert_int_eq(o_strlen(str_query), o_strlen("SELECT * FROM test_table WHERE 1=1")); ck_assert_int_eq(json_array_size(j_result), 2); ck_assert_str_eq(json_string_value(json_object_get(json_array_get(j_result, 0), "string_col")), "value1"); ck_assert_int_eq(json_integer_value(json_object_get(json_array_get(j_result, 0), "integer_col")), 1); ck_assert_double_eq(json_real_value(json_object_get(json_array_get(j_result, 0), "double_col")), 4.2); json_decref(j_query); json_decref(j_result); h_free(str_query); j_query = json_pack("{ssss}", "table", "test_table", "order_by", "integer_col"); ck_assert_int_eq(h_select(conn, j_query, &j_result, &str_query), H_OK); ck_assert_int_eq(0, o_strcmp(str_query, "SELECT * FROM test_table WHERE 1=1 ORDER BY integer_col")); ck_assert_int_eq(json_array_size(j_result), 2); ck_assert_str_eq(json_string_value(json_object_get(json_array_get(j_result, 0), "string_col")), "value1"); ck_assert_int_eq(json_integer_value(json_object_get(json_array_get(j_result, 0), "integer_col")), 1); ck_assert_double_eq(json_real_value(json_object_get(json_array_get(j_result, 0), "double_col")), 4.2); json_decref(j_query); json_decref(j_result); h_free(str_query); #ifdef PGSQL j_query = json_pack("{sss[s]ss}", "table", "test_table", "columns", "integer_col", "group_by", "integer_col"); #else j_query = json_pack("{ssss}", "table", "test_table", "group_by", "integer_col"); #endif ck_assert_int_eq(h_select(conn, j_query, &j_result, &str_query), H_OK); #ifdef PGSQL ck_assert_str_eq(str_query, "SELECT integer_col FROM test_table WHERE 1=1 GROUP BY integer_col"); #else ck_assert_str_eq(str_query, "SELECT * FROM test_table WHERE 1=1 GROUP BY integer_col"); #endif ck_assert_int_eq(json_array_size(j_result), 2); ck_assert_int_eq(json_integer_value(json_object_get(json_array_get(j_result, 0), "integer_col")), 1); #ifndef PGSQL ck_assert_str_eq(json_string_value(json_object_get(json_array_get(j_result, 0), "string_col")), "value1"); ck_assert_double_eq(json_real_value(json_object_get(json_array_get(j_result, 0), "double_col")), 4.2); #endif json_decref(j_query); json_decref(j_result); h_free(str_query); #ifdef PGSQL j_query = json_pack("{sss[s]ssss}", "table", "test_table", "columns", "integer_col", "order_by", "integer_col", "group_by", "integer_col"); #else j_query = json_pack("{ssssss}", "table", "test_table", "order_by", "integer_col", "group_by", "integer_col"); #endif ck_assert_int_eq(h_select(conn, j_query, &j_result, &str_query), H_OK); #ifdef PGSQL ck_assert_str_eq(str_query, "SELECT integer_col FROM test_table WHERE 1=1 GROUP BY integer_col ORDER BY integer_col"); #else ck_assert_str_eq(str_query, "SELECT * FROM test_table WHERE 1=1 GROUP BY integer_col ORDER BY integer_col"); #endif ck_assert_int_eq(json_array_size(j_result), 2); ck_assert_int_eq(json_integer_value(json_object_get(json_array_get(j_result, 0), "integer_col")), 1); #ifndef PGSQL ck_assert_str_eq(json_string_value(json_object_get(json_array_get(j_result, 0), "string_col")), "value1"); ck_assert_double_eq(json_real_value(json_object_get(json_array_get(j_result, 0), "double_col")), 4.2); #endif json_decref(j_query); json_decref(j_result); h_free(str_query); j_query = json_pack("{sss{si}}", "table", "test_table", "where", "integer_col", 1); ck_assert_int_eq(h_select(conn, j_query, &j_result, &str_query), H_OK); ck_assert_int_eq(o_strlen(str_query), o_strlen("SELECT * FROM test_table WHERE integer_col='1'")); ck_assert_int_eq(json_array_size(j_result), 1); ck_assert_str_eq(json_string_value(json_object_get(json_array_get(j_result, 0), "string_col")), "value1"); ck_assert_int_eq(json_integer_value(json_object_get(json_array_get(j_result, 0), "integer_col")), 1); ck_assert_double_eq(json_real_value(json_object_get(json_array_get(j_result, 0), "double_col")), 4.2); json_decref(j_query); json_decref(j_result); h_free(str_query); j_query = json_pack("{sss{ss}}", "table", "test_table", "where", "string_col", "value1"); ck_assert_int_eq(h_select(conn, j_query, &j_result, &str_query), H_OK); ck_assert_int_eq(o_strlen(str_query), o_strlen("SELECT * FROM test_table WHERE string_col='value1'")); ck_assert_int_eq(json_array_size(j_result), 1); ck_assert_str_eq(json_string_value(json_object_get(json_array_get(j_result, 0), "string_col")), "value1"); ck_assert_int_eq(json_integer_value(json_object_get(json_array_get(j_result, 0), "integer_col")), 1); ck_assert_double_eq(json_real_value(json_object_get(json_array_get(j_result, 0), "double_col")), 4.2); json_decref(j_query); json_decref(j_result); h_free(str_query); j_query = json_pack("{sss{ss}}", "table", "test_table", "where", "string_col", "value'to'escape"); ck_assert_int_eq(h_select(conn, j_query, &j_result, &str_query), H_OK); ck_assert_int_eq(o_strlen(str_query), o_strlen("SELECT * FROM test_table WHERE string_col='value''to''escape'")); ck_assert_int_eq(json_array_size(j_result), 0); json_decref(j_query); json_decref(j_result); h_free(str_query); j_query = json_pack("{sss{s{ss}}}", "table", "test_table", "where", "integer_col", "operator", "NOT NULL"); ck_assert_int_eq(h_select(conn, j_query, &j_result, &str_query), H_OK); ck_assert_int_eq(o_strlen(str_query), o_strlen("SELECT * FROM test_table WHERE integer_col IS NOT NULL")); ck_assert_int_eq(json_array_size(j_result), 2); ck_assert_str_eq(json_string_value(json_object_get(json_array_get(j_result, 0), "string_col")), "value1"); ck_assert_int_eq(json_integer_value(json_object_get(json_array_get(j_result, 0), "integer_col")), 1); ck_assert_double_eq(json_real_value(json_object_get(json_array_get(j_result, 0), "double_col")), 4.2); json_decref(j_query); json_decref(j_result); h_free(str_query); j_query = json_pack("{sss{s{ssss}}}", "table", "test_table", "where", "integer_col", "operator", "raw", "value", ">6"); ck_assert_int_eq(h_select(conn, j_query, &j_result, &str_query), H_OK); ck_assert_int_eq(o_strlen(str_query), o_strlen("SELECT * FROM test_table WHERE integer_col >6")); ck_assert_int_eq(json_array_size(j_result), 0); json_decref(j_query); json_decref(j_result); h_free(str_query); j_query = json_pack("{sss{s{ss}s{ssss}}}", "table", "test_table", "where", "string_col", "operator", "NOT NULL", "integer_col", "operator", "raw", "value", ">=1"); ck_assert_int_eq(h_select(conn, j_query, &j_result, &str_query), H_OK); ck_assert_int_eq(o_strlen(str_query), o_strlen("SELECT * FROM test_table WHERE string_col IS NOT NULL AND integer_col >=1")); ck_assert_int_eq(json_array_size(j_result), 2); ck_assert_str_eq(json_string_value(json_object_get(json_array_get(j_result, 0), "string_col")), "value1"); ck_assert_int_eq(json_integer_value(json_object_get(json_array_get(j_result, 0), "integer_col")), 1); ck_assert_double_eq(json_real_value(json_object_get(json_array_get(j_result, 0), "double_col")), 4.2); json_decref(j_query); json_decref(j_result); h_free(str_query); j_query = json_pack("{sss{so}}", "table", "test_table", "where", "integer_col", json_null()); ck_assert_int_eq(h_select(conn, j_query, &j_result, &str_query), H_OK); ck_assert_int_eq(o_strlen(str_query), o_strlen("SELECT * FROM test_table WHERE integer_col IS NULL")); ck_assert_int_eq(json_array_size(j_result), 0); json_decref(j_query); json_decref(j_result); h_free(str_query); str_query = NULL; j_result = NULL; j_query = json_pack("{sss{s{sss[ii]}}}", "table", "test_table", "where", "integer_col", "operator", "IN", "value", 42, 66); ck_assert_int_eq(h_select(conn, j_query, &j_result, &str_query), H_OK); ck_assert_int_eq(o_strlen(str_query), o_strlen("SELECT * FROM test_table WHERE integer_col IN (42,66)")); ck_assert_int_eq(json_array_size(j_result), 0); json_decref(j_query); json_decref(j_result); h_free(str_query); j_query = json_pack("{ss}", "table", "test_table"); ck_assert_int_eq(h_delete(conn, j_query, NULL), H_OK); ck_assert_int_eq(h_select(conn, j_query, &j_result, NULL), H_OK); json_decref(j_result); json_decref(j_query); j_query = json_pack("{sss[{sisss{ss}}{sisos{ss}}]}", "table", "test_table", "values", "integer_col", 1, "string_col", "", "date_col", "raw", NOW, "integer_col", 1, "string_col", json_null(), "date_col", "raw", NOW); ck_assert_int_eq(h_insert(conn, j_query, NULL), H_OK); json_decref(j_query); j_query = json_pack("{ss}", "table", "test_table"); ck_assert_int_eq(h_select(conn, j_query, &j_result, NULL), H_OK); ck_assert_int_eq(json_array_size(j_result), 2); ck_assert_str_eq(json_string_value(json_object_get(json_array_get(j_result, 0), "string_col")), ""); ck_assert_ptr_eq(json_object_get(json_array_get(j_result, 1), "string_col"), json_null()); json_decref(j_query); json_decref(j_result); j_query = json_pack("{ss}", "table", "test_table"); ck_assert_int_eq(h_delete(conn, j_query, NULL), H_OK); ck_assert_int_eq(h_select(conn, j_query, &j_result, NULL), H_OK); json_decref(j_result); json_decref(j_query); h_close_db(conn); h_clean_connection(conn); } END_TEST static Suite *hoel_suite(void) { Suite *s; TCase *tc_core; s = suite_create("Hoel multi-backend tests"); tc_core = tcase_create("test_hoel_multi_backend"); tcase_add_test(tc_core, test_hoel_escape_string); tcase_add_test(tc_core, test_hoel_escape_string_with_quotes); tcase_add_test(tc_core, test_hoel_insert); tcase_add_test(tc_core, test_hoel_update); tcase_add_test(tc_core, test_hoel_delete); tcase_add_test(tc_core, test_hoel_json_insert); tcase_add_test(tc_core, test_hoel_json_update); tcase_add_test(tc_core, test_hoel_json_delete); tcase_add_test(tc_core, test_hoel_json_select); tcase_set_timeout(tc_core, 30); suite_add_tcase(s, tc_core); return s; } int main(void) { int number_failed; Suite *s; SRunner *sr; //y_init_logs("Hoel", Y_LOG_MODE_CONSOLE, Y_LOG_LEVEL_DEBUG, NULL, "Starting Hoel multi-backend tests"); s = hoel_suite(); sr = srunner_create(s); srunner_run_all(sr, CK_VERBOSE); number_failed = srunner_ntests_failed(sr); srunner_free(sr); //y_close_logs(); return (number_failed == 0) ? EXIT_SUCCESS : EXIT_FAILURE; } hoel-1.4.29/test/run_test.sh000077500000000000000000000005751452453561700157420ustar00rootroot00000000000000#!/bin/bash printf_new() { str=$1 num=$2 v=$(printf "%-${num}s" "$str") printf "${v// / }" } RED='\033[0;31m' GREEN='\033[0;32m' NC='\033[0m' # No Color COMMAND=$1 CHRLEN=${#COMMAND} NBSP=$((32-$CHRLEN)) printf "Run $1" printf_new " " $NBSP $1 $2 $3 $4 $5 $6 $7 $8 $9 1>$1.log 2>&1 if [ $? -ne 0 ] then printf "${RED}FAIL${NC}\n" else printf "${GREEN}SUCCESS${NC}\n" fi hoel-1.4.29/test/test.mariadb.sql000066400000000000000000000004021452453561700166230ustar00rootroot00000000000000-- Public domain, no copyright. Use at your own risk DROP TABLE IF EXISTS test_table; CREATE TABLE test_table ( id_col INT(11) PRIMARY KEY AUTO_INCREMENT, integer_col INT(11), double_col FLOAT(9,2), string_col VARCHAR(256), date_col TIMESTAMP ); hoel-1.4.29/test/test.pgsql.sql000066400000000000000000000003701452453561700163560ustar00rootroot00000000000000-- Public domain, no copyright. Use at your own risk DROP TABLE IF EXISTS test_table; CREATE TABLE test_table ( id_col SERIAL PRIMARY KEY, integer_col INTEGER, double_col NUMERIC(10, 2), string_col VARCHAR(256), date_col TIMESTAMPTZ ); hoel-1.4.29/test/test.sqlite3.sql000066400000000000000000000003631452453561700166160ustar00rootroot00000000000000-- Public domain, no copyright. Use at your own risk DROP TABLE IF EXISTS test_table; CREATE TABLE test_table ( id_col INTEGER PRIMARY KEY AUTOINCREMENT, integer_col INTEGER, double_col REAL, string_col TEXT, date_col TIMESTAMP );