Merge pull request #1 from SRombauts/master

Update SQLiteCpp
This commit is contained in:
Mattes D 2015-04-19 14:53:26 +02:00
commit b17195b8d0
21 changed files with 154964 additions and 137258 deletions

View File

@ -1,5 +1,8 @@
# Copyright (c) 2012-2015 Sebastien Rombauts (sebastien.rombauts@gmail.com)
language: cpp language: cpp
# compilers to add to build matrix
compiler: compiler:
- gcc - gcc
- clang - clang
@ -7,13 +10,14 @@ compiler:
before_install: before_install:
- sudo apt-get update -qq - sudo apt-get update -qq
- sudo apt-get install -qq cppcheck - sudo apt-get install -qq cppcheck
# using a symbolic link to get the "make test" to work as if launched from the root directorys # scripts to run before build
before_script: before_script:
- mkdir build - mkdir build
- cd build - cd build
- cmake .. - cmake -DSQLITECPP_BUILD_EXAMPLES=ON -DSQLITECPP_BUILD_TESTS=ON -DSQLITECPP_RUN_DOXYGEN=OFF ..
- ln -s ../examples examples
script: make && ctest --output-on-failure
# build examples, and run tests (ie make & make test)
script:
- cmake --build .
- ctest --output-on-failure

View File

@ -1,10 +1,25 @@
if (BIICODE)
# biicode doesn't process files bigger than 5Mb
list(APPEND BII_LIB_SRC sqlite3/sqlite3.c)
# Include base block dir
ADD_BIICODE_TARGETS()
# Link target with dl for linux
if (UNIX)
TARGET_LINK_LIBRARIES(${BII_BLOCK_TARGET} INTERFACE pthread)
if(NOT APPLE)
TARGET_LINK_LIBRARIES(${BII_BLOCK_TARGET} INTERFACE dl)
endif()
endif()
else (BIICODE)
# Main CMake file for compiling the library itself, examples and tests. # Main CMake file for compiling the library itself, examples and tests.
# #
# Copyright (c) 2012-2014 Sebastien Rombauts (sebastien.rombauts@gmail.com) # Copyright (c) 2012-2015 Sebastien Rombauts (sebastien.rombauts@gmail.com)
# #
# Distributed under the MIT License (MIT) (See accompanying file LICENSE.txt # Distributed under the MIT License (MIT) (See accompanying file LICENSE.txt
# or copy at http://opensource.org/licenses/MIT) # or copy at http://opensource.org/licenses/MIT)
cmake_minimum_required(VERSION 2.6) cmake_minimum_required(VERSION 2.6)
project(SQLiteCpp) project(SQLiteCpp)
@ -96,21 +111,34 @@ source_group(example1 FILES ${SQLITECPP_EXAMPLES})
# list of doc files of the library # list of doc files of the library
set(SQLITECPP_DOC set(SQLITECPP_DOC
README.md README.md
WRAPPERS.md
LICENSE.txt LICENSE.txt
CHANGELOG.txt
TODO.txt TODO.txt
) )
source_group(doc FILES ${SQLITECPP_DOC}) source_group(doc FILES ${SQLITECPP_DOC})
# list of script files of the library
set(SQLITECPP_SCRIPT
.travis.yml
appveyor.yml
biicode.conf
build.bat
build.sh
cpplint.py
Doxyfile
FindSQLiteCpp.cmake
)
source_group(scripts FILES ${SQLITECPP_SCRIPT})
# All includes are relative to the "include" directory # All includes are relative to the "include" directory
include_directories("${PROJECT_SOURCE_DIR}/include") include_directories("${PROJECT_SOURCE_DIR}/include")
# add sources of the wrapper as a "SQLiteCpp" static library # add sources of the wrapper as a "SQLiteCpp" static library
add_library(SQLiteCpp ${SQLITECPP_SRC} ${SQLITECPP_INC} ${SQLITECPP_DOC}) add_library(SQLiteCpp ${SQLITECPP_SRC} ${SQLITECPP_INC} ${SQLITECPP_DOC} ${SQLITECPP_SCRIPT})
if (UNIX AND (CMAKE_COMPILER_IS_GNUCXX OR "${CMAKE_CXX_COMPILER_ID}" STREQUAL "Clang")) if (UNIX AND (CMAKE_COMPILER_IS_GNUCXX OR ${CMAKE_CXX_COMPILER_ID} STREQUAL "Clang"))
set_target_properties(SQLiteCpp PROPERTIES COMPILE_FLAGS "-fPIC") set_target_properties(SQLiteCpp PROPERTIES COMPILE_FLAGS "-fPIC")
endif (UNIX AND (CMAKE_COMPILER_IS_GNUCXX OR "${CMAKE_CXX_COMPILER_ID}" STREQUAL "Clang")) endif (UNIX AND (CMAKE_COMPILER_IS_GNUCXX OR ${CMAKE_CXX_COMPILER_ID} STREQUAL "Clang"))
# SQLite3 library (Windows only) # SQLite3 library (Windows only)
@ -129,22 +157,30 @@ endif (WIN32)
option(SQLITECPP_RUN_CPPLINT "Run cpplint.py tool for Google C++ StyleGuide." ON) option(SQLITECPP_RUN_CPPLINT "Run cpplint.py tool for Google C++ StyleGuide." ON)
if (SQLITECPP_RUN_CPPLINT) if (SQLITECPP_RUN_CPPLINT)
# add a cpplint target to the "all" target find_package(PythonLibs)
add_custom_target(SQLiteCpp_cpplint if (PYTHONLIBS_FOUND)
ALL # add a cpplint target to the "all" target
COMMAND python ${PROJECT_SOURCE_DIR}/cpplint.py ${CPPLINT_ARG_OUTPUT} ${CPPLINT_ARG_VERBOSE} ${CPPLINT_ARG_LINELENGTH} ${SQLITECPP_SRC} ${SQLITECPP_INC} add_custom_target(SQLiteCpp_cpplint
) ALL
COMMAND python ${PROJECT_SOURCE_DIR}/cpplint.py ${CPPLINT_ARG_OUTPUT} ${CPPLINT_ARG_VERBOSE} ${CPPLINT_ARG_LINELENGTH} ${SQLITECPP_SRC} ${SQLITECPP_INC}
)
endif (PYTHONLIBS_FOUND)
else (SQLITECPP_RUN_CPPLINT) else (SQLITECPP_RUN_CPPLINT)
message(STATUS "SQLITECPP_RUN_CPPLINT OFF") message(STATUS "SQLITECPP_RUN_CPPLINT OFF")
endif (SQLITECPP_RUN_CPPLINT) endif (SQLITECPP_RUN_CPPLINT)
option(SQLITECPP_RUN_CPPCHECK "Run cppcheck C++ static analysis tool." ON) option(SQLITECPP_RUN_CPPCHECK "Run cppcheck C++ static analysis tool." ON)
if (SQLITECPP_RUN_CPPCHECK) if (SQLITECPP_RUN_CPPCHECK)
# add a cppcheck target to the "all" target find_program(CPPCHECK_EXECUTABLE NAMES cppcheck)
add_custom_target(SQLiteCpp_cppcheck if (CPPCHECK_EXECUTABLE)
ALL # add a cppcheck target to the "all" target
COMMAND cppcheck -j 4 cppcheck --enable=style --quiet ${CPPCHECK_ARG_TEMPLATE} ${PROJECT_SOURCE_DIR}/src add_custom_target(SQLiteCpp_cppcheck
) ALL
COMMAND cppcheck -j 4 cppcheck --enable=style --quiet ${CPPCHECK_ARG_TEMPLATE} ${PROJECT_SOURCE_DIR}/src
)
else (CPPCHECK_EXECUTABLE)
message(STATUS "Could NOT find cppcheck")
endif (CPPCHECK_EXECUTABLE)
else (SQLITECPP_RUN_CPPCHECK) else (SQLITECPP_RUN_CPPCHECK)
message(STATUS "SQLITECPP_RUN_CPPCHECK OFF") message(STATUS "SQLITECPP_RUN_CPPCHECK OFF")
endif (SQLITECPP_RUN_CPPCHECK) endif (SQLITECPP_RUN_CPPCHECK)
@ -159,14 +195,12 @@ if (SQLITECPP_RUN_DOXYGEN)
COMMAND doxygen Doxyfile > ${DEV_NULL} COMMAND doxygen Doxyfile > ${DEV_NULL}
WORKING_DIRECTORY ${PROJECT_SOURCE_DIR} WORKING_DIRECTORY ${PROJECT_SOURCE_DIR}
) )
else (DOXYGEN_FOUND)
message(STATUS "Doxygen not found")
endif (DOXYGEN_FOUND) endif (DOXYGEN_FOUND)
else (SQLITECPP_RUN_DOXYGEN) else (SQLITECPP_RUN_DOXYGEN)
message(STATUS "SQLITECPP_RUN_DOXYGEN OFF") message(STATUS "SQLITECPP_RUN_DOXYGEN OFF")
endif (SQLITECPP_RUN_DOXYGEN) endif (SQLITECPP_RUN_DOXYGEN)
option(SQLITECPP_BUILD_EXAMPLES "Build examples." ON) option(SQLITECPP_BUILD_EXAMPLES "Build examples." OFF)
if (SQLITECPP_BUILD_EXAMPLES) if (SQLITECPP_BUILD_EXAMPLES)
# add the basic example executable # add the basic example executable
add_executable(SQLiteCpp_example1 ${SQLITECPP_EXAMPLES}) add_executable(SQLiteCpp_example1 ${SQLITECPP_EXAMPLES})
@ -175,13 +209,13 @@ else(SQLITECPP_BUILD_EXAMPLES)
message(STATUS "SQLITECPP_BUILD_EXAMPLES OFF") message(STATUS "SQLITECPP_BUILD_EXAMPLES OFF")
endif(SQLITECPP_BUILD_EXAMPLES) endif(SQLITECPP_BUILD_EXAMPLES)
option(SQLITECPP_BUILD_TESTS "Build and run tests." ON) option(SQLITECPP_BUILD_TESTS "Build and run tests." OFF)
if (SQLITECPP_BUILD_TESTS) if (SQLITECPP_BUILD_TESTS)
# add the subdirectory containing the CMakeLists.txt for the gtest library # add the subdirectory containing the CMakeLists.txt for the gtest library
if (NOT MSVC) if (NOT MSVC)
add_definitions(-Wno-variadic-macros -Wno-long-long -Wno-conversion -Wno-switch-enum) add_definitions(-Wno-variadic-macros -Wno-long-long -Wno-conversion -Wno-switch-enum)
endif (NOT MSVC) endif (NOT MSVC)
add_subdirectory(googletest) add_subdirectory(googletest)
include_directories("${PROJECT_SOURCE_DIR}/googletest/include") include_directories("${PROJECT_SOURCE_DIR}/googletest/include")
@ -202,3 +236,5 @@ if (SQLITECPP_BUILD_TESTS)
else (SQLITECPP_BUILD_TESTS) else (SQLITECPP_BUILD_TESTS)
message(STATUS "SQLITECPP_BUILD_TESTS OFF") message(STATUS "SQLITECPP_BUILD_TESTS OFF")
endif (SQLITECPP_BUILD_TESTS) endif (SQLITECPP_BUILD_TESTS)
endif (BIICODE)

View File

@ -1801,18 +1801,6 @@ GENERATE_XML = NO
XML_OUTPUT = xml XML_OUTPUT = xml
# The XML_SCHEMA tag can be used to specify a XML schema, which can be used by a
# validating XML parser to check the syntax of the XML files.
# This tag requires that the tag GENERATE_XML is set to YES.
XML_SCHEMA =
# The XML_DTD tag can be used to specify a XML DTD, which can be used by a
# validating XML parser to check the syntax of the XML files.
# This tag requires that the tag GENERATE_XML is set to YES.
XML_DTD =
# If the XML_PROGRAMLISTING tag is set to YES doxygen will dump the program # If the XML_PROGRAMLISTING tag is set to YES doxygen will dump the program
# listings (including syntax highlighting and cross-referencing information) to # listings (including syntax highlighting and cross-referencing information) to
# the XML output. Note that enabling this will significantly increase the size # the XML output. Note that enabling this will significantly increase the size

View File

@ -1,6 +1,6 @@
The MIT License (MIT) The MIT License (MIT)
Copyright (c) 2012-2014 Sebastien Rombauts (sebastien.rombauts@gmail.com) Copyright (c) 2012-2015 Sebastien Rombauts (sebastien.rombauts@gmail.com)
Permission is hereby granted, free of charge, to any person obtaining a copy Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal of this software and associated documentation files (the "Software"), to deal

516
README.md
View File

@ -1,256 +1,260 @@
SQLiteC++ SQLiteC++
--------- ---------
![SQLiteCpp build status](https://api.travis-ci.org/SRombauts/SQLiteCpp.png "SQLiteCpp build status") [![Travis CI Linux Build Status](https://travis-ci.org/SRombauts/SQLiteCpp.svg)](https://travis-ci.org/SRombauts/SQLiteCpp "Travis CI Linux Build Status")
[![AppVeyor Windows Build status](https://ci.appveyor.com/api/projects/status/github/SRombauts/SQLiteCpp?svg=true)](https://ci.appveyor.com/project/SbastienRombauts/SQLiteCpp "AppVeyor Windows Build status")
SQLiteC++ (SQLiteCpp) is a smart and easy to use C++ SQLite3 wrapper. [![Build Status](https://webapi.biicode.com/v1/badges/sqlite/sqlite/sqlite/master)](https://www.biicode.com/sqlite/sqlite)
See SQLiteC++ website http://srombauts.github.com/SQLiteCpp on GitHub.
SQLiteC++ (SQLiteCpp) is a smart and easy to use C++ SQLite3 wrapper.
Keywords: sqlite, sqlite3, C, library, wrapper C++
See SQLiteC++ website http://srombauts.github.com/SQLiteCpp on GitHub.
### About SQLite:
Keywords: sqlite, sqlite3, C, library, wrapper C++
SQLite is a library that implements a serverless transactional SQL database engine.
It is the most widely deployed SQL database engine in the world. ### About SQLite:
The source code for SQLite is in the public domain.
http://www.sqlite.org/about.html SQLite is a library that implements a serverless transactional SQL database engine.
It is the most widely deployed SQL database engine in the world.
### About SQLiteC++: The source code for SQLite is in the public domain.
http://www.sqlite.org/about.html
SQLiteC++ offers an encapsulation arround the native C APIs of sqlite,
with a few intuitive and well documented C++ class. ### About SQLiteC++:
### The goals of SQLiteC++ are: SQLiteC++ offers an encapsulation arround the native C APIs of sqlite,
with a few intuitive and well documented C++ class.
- to offer the best of existing simple C++ SQLite wrappers
- to be elegantly written with good C++ design, STL, exceptions and RAII idiom ### The goals of SQLiteC++ are:
- to keep dependencies to a minimum (STL and SQLite3)
- to be portable - to offer the best of existing simple C++ SQLite wrappers
- to be light and fast - to be elegantly written with good C++ design, STL, exceptions and RAII idiom
- to be thread-safe only as much as SQLite "Multi-thread" mode (see below) - to keep dependencies to a minimum (STL and SQLite3)
- to have a good unit test coverage - to be portable
- to use API names sticking with those of the SQLite library - to be light and fast
- to be well documented with Doxygen tags, and with some good examples - to be thread-safe only as much as SQLite "Multi-thread" mode (see below)
- to be well maintained - to have a good unit test coverage
- to use a permissive MIT license, similar to BSD or Boost, for proprietary/commercial usage - to use API names sticking with those of the SQLite library
- to be well documented with Doxygen tags, and with some good examples
It is designed using the Resource Acquisition Is Initialization (RAII) idom - to be well maintained
(see http://en.wikipedia.org/wiki/Resource_Acquisition_Is_Initialization), - to use a permissive MIT license, similar to BSD or Boost, for proprietary/commercial usage
and throwing exceptions in case of SQLite errors (exept in destructors,
where assert() are used instead). It is designed using the Resource Acquisition Is Initialization (RAII) idom
Each SQLiteC++ object must be constructed with a valid SQLite database connection, (see http://en.wikipedia.org/wiki/Resource_Acquisition_Is_Initialization),
and then is always valid until destroyed. and throwing exceptions in case of SQLite errors (exept in destructors,
where assert() are used instead).
### Supported platforms: Each SQLiteC++ object must be constructed with a valid SQLite database connection,
and then is always valid until destroyed.
Developements and tests are done under the following OSs:
- Debian 7 ### Supported platforms:
- Ubuntu 12.10
- Windows XP/7/8 Developements and tests are done under the following OSs:
And following IDEs/Compilers - Debian 7
- GCC 4.7.2 with a provided Makefile - Ubuntu 12.10
- Eclipse CDT under Linux, using the provided Makefile - Windows XP/7/8
- Visual Studio Express 2008/2010/2012/2013 for testing compatibility purpose And following IDEs/Compilers
- GCC 4.7.2 with a provided Makefile
### Dependencies - Eclipse CDT under Linux, using the provided Makefile
- Visual Studio Express 2008/2010/2012/2013 for testing compatibility purpose
- a STL implementation (even an old one, like the one provided with VC6 should work)
- exception support (the class Exception inherit from std::runtime_error) ### Dependencies
- the SQLite library, either by linking to it dynamicaly or staticaly (install the libsqlite3-dev package under Debian/Ubuntu/Mint Linux),
or by adding its source file in your project code base (source code provided in src/sqlite3 for Windows), - a STL implementation (even an old one, like the one provided with VC6 should work)
with the SQLITE_ENABLE_COLUMN_METADATA macro defined (see http://www.sqlite.org/compile.html#enable_column_metadata). - exception support (the class Exception inherit from std::runtime_error)
- the SQLite library, either by linking to it dynamicaly or staticaly (install the libsqlite3-dev package under Debian/Ubuntu/Mint Linux),
### Installation or by adding its source file in your project code base (source code provided in src/sqlite3 for Windows),
with the SQLITE_ENABLE_COLUMN_METADATA macro defined (see http://www.sqlite.org/compile.html#enable_column_metadata).
To use this wrappers, you need to add the 10 SQLiteC++ source files from the src/ directory
in your project code base, and compile/link against the sqlite library. ### Installation
The easiest way to do this is to add the wrapper as a library. To use this wrappers, you need to add the 10 SQLiteC++ source files from the src/ directory
The proper "CMakeLists.txt" file defining the static library is provided in the src/ subdirectory, in your project code base, and compile/link against the sqlite library.
so you simply have to add_directory(SQLiteCpp/src) to you main CMakeLists.txt
and link to the "SQLiteCpp" wrapper library. The easiest way to do this is to add the wrapper as a library.
Thus this SQLiteCpp repository can directly be used as a Git submoldule. The proper "CMakeLists.txt" file defining the static library is provided in the src/ subdirectory,
so you simply have to add_directory(SQLiteCpp/src) to you main CMakeLists.txt
Under Debian/Ubuntu/Mint Linux, install the libsqlite3-dev package. and link to the "SQLiteCpp" wrapper library.
Thus this SQLiteCpp repository can directly be used as a Git submoldule.
### Building the examples:
Under Debian/Ubuntu/Mint Linux, install the libsqlite3-dev package.
A basic Makefile is provided, tested under Linux/Ubuntu 12.10, requiring the sqlite3 static library (sqlite3-dev Debian/Ubuntu package)
Solutions for Visual Studio 2008 and 2010 are provided in the "msvc/" directory, directly using the sqlite3.c source code for ease of use. ### Building the examples:
#### CMake and test #### CMake and test
A CMake configuration file is also provided for better multiplatform support and testing. A CMake configuration file is also provided for multiplatform support and testing.
Typical generic build (see also "build.bat" or "./build.sh"): Typical generic build (see also "build.bat" or "./build.sh"):
```bash ```bash
mkdir build mkdir build
cd build cd build
cmake .. # cmake .. -G "Visual Studio 10" # for Visual Studio 2010 cmake .. # cmake .. -G "Visual Studio 10" # for Visual Studio 2010
cmake --build . # make cmake --build . # make
ctest . # make test ctest . # make test
``` ```
Generating the Linux Makefile, building in Debug and executing the tests: Generating the Linux Makefile, building in Debug and executing the tests:
```bash ```bash
mkdir Debug mkdir Debug
cd Debug cd Debug
cmake .. -DCMAKE_BUILD_TYPE=Debug cmake .. -DCMAKE_BUILD_TYPE=Debug
cmake --build . # make cmake --build . # make
ln -s ../examples examples ln -s ../examples examples
ctest . # make test ctest . # make test
``` ```
#### Troubleshooting #### Troubleshooting
Under Linux, if you get muliple linker errors like "undefined reference to sqlite3_xxx", Under Linux, if you get muliple linker errors like "undefined reference to sqlite3_xxx",
it's that you lack the "sqlite3" library: install the libsqlite3-dev package. it's that you lack the "sqlite3" library: install the libsqlite3-dev package.
If you get a single linker error "Column.cpp: undefined reference to sqlite3_column_origin_name", If you get a single linker error "Column.cpp: undefined reference to sqlite3_column_origin_name",
it's that your "sqlite3" library was not compiled with it's that your "sqlite3" library was not compiled with
the SQLITE_ENABLE_COLUMN_METADATA macro defined (see http://www.sqlite.org/compile.html#enable_column_metadata). the SQLITE_ENABLE_COLUMN_METADATA macro defined (see http://www.sqlite.org/compile.html#enable_column_metadata).
You can either recompile it yourself (seek help online) or you can comment out the following line in src/Column.h: You can either recompile it yourself (seek help online) or you can comment out the following line in src/Column.h:
```C++ ```C++
#define SQLITE_ENABLE_COLUMN_METADATA #define SQLITE_ENABLE_COLUMN_METADATA
``` ```
### Continuous Integration ### Continuous Integration
This project is continuously tested under Ubuntu Linux with the gcc and clang compilers This project is continuously tested under Ubuntu Linux with the gcc and clang compilers
using the Travis CI community service with the above CMake building and testing procedure. using the Travis CI community service with the above CMake building and testing procedure.
It is also tested in the same way under Windows Server 2012 R2 with Visual Studio 2013 compiler
Detailed results can be seen online: https://travis-ci.org/SRombauts/SQLiteCpp using the AppVeyor countinuous integration service.
### Thread-safety Detailed results can be seen online:
- https://travis-ci.org/SRombauts/SQLiteCpp
SQLite supports three mode of thread safety, as describe in "SQLite And Multiple Threads" : - https://ci.appveyor.com/project/SbastienRombauts/SQLiteCpp
see http://www.sqlite.org/threadsafe.html
### Thread-safety
This SQLiteC++ wrapper does no add any lock (no mutexes) nor any other thread-safety mecanism
above the SQLite library itself, by design, for lightness and speed. SQLite supports three mode of thread safety, as describe in "SQLite And Multiple Threads" :
see http://www.sqlite.org/threadsafe.html
Thus, SQLiteC++ naturally supports the "Multi Thread" mode of SQLite ;
"In this mode, SQLite can be safely used by multiple threads This SQLiteC++ wrapper does no add any lock (no mutexes) nor any other thread-safety mecanism
provided that no single database connection is used simultaneously in two or more threads." above the SQLite library itself, by design, for lightness and speed.
But SQLiteC++ does not support the fully thread-safe "Serialized" mode of SQLite, Thus, SQLiteC++ naturally supports the "Multi Thread" mode of SQLite ;
because of the way it shares the underling SQLite precompiled statement "In this mode, SQLite can be safely used by multiple threads
in a custom shared pointer (See the inner class "Statement::Ptr"). provided that no single database connection is used simultaneously in two or more threads."
### License But SQLiteC++ does not support the fully thread-safe "Serialized" mode of SQLite,
because of the way it shares the underling SQLite precompiled statement
Copyright (c) 2012-2014 Sébastien Rombauts (sebastien.rombauts@gmail.com) in a custom shared pointer (See the inner class "Statement::Ptr").
Distributed under the MIT License (MIT) (See accompanying file LICENSE.txt ### License
or copy at http://opensource.org/licenses/MIT)
Copyright (c) 2012-2015 Sébastien Rombauts (sebastien.rombauts@gmail.com)
## Getting started
### First sample demonstrates how to query a database and get results: Distributed under the MIT License (MIT) (See accompanying file LICENSE.txt
or copy at http://opensource.org/licenses/MIT)
```C++
try ## Getting started
{ ### First sample demonstrates how to query a database and get results:
// Open a database file
SQLite::Database db("example.db3"); ```C++
try
// Compile a SQL query, containing one parameter (index 1) {
SQLite::Statement query(db, "SELECT * FROM test WHERE size > ?"); // Open a database file
SQLite::Database db("example.db3");
// Bind the integer value 6 to the first parameter of the SQL query
query.bind(1, 6); // Compile a SQL query, containing one parameter (index 1)
SQLite::Statement query(db, "SELECT * FROM test WHERE size > ?");
// Loop to execute the query step by step, to get rows of result
while (query.executeStep()) // Bind the integer value 6 to the first parameter of the SQL query
{ query.bind(1, 6);
// Demonstrate how to get some typed column value
int id = query.getColumn(0); // Loop to execute the query step by step, to get rows of result
const char* value = query.getColumn(1); while (query.executeStep())
int size = query.getColumn(2); {
// Demonstrate how to get some typed column value
std::cout << "row: " << id << ", " << value << ", " << size << std::endl; int id = query.getColumn(0);
} const char* value = query.getColumn(1);
} int size = query.getColumn(2);
catch (std::exception& e)
{ std::cout << "row: " << id << ", " << value << ", " << size << std::endl;
std::cout << "exception: " << e.what() << std::endl; }
} }
``` catch (std::exception& e)
{
### Second sample shows how to manage a transaction: std::cout << "exception: " << e.what() << std::endl;
}
```C++ ```
try
{ ### Second sample shows how to manage a transaction:
SQLite::Database db("transaction.db3", SQLITE_OPEN_READWRITE|SQLITE_OPEN_CREATE);
```C++
db.exec("DROP TABLE IF EXISTS test"); try
{
// Begin transaction SQLite::Database db("transaction.db3", SQLITE_OPEN_READWRITE|SQLITE_OPEN_CREATE);
SQLite::Transaction transaction(db);
db.exec("DROP TABLE IF EXISTS test");
db.exec("CREATE TABLE test (id INTEGER PRIMARY KEY, value TEXT)");
// Begin transaction
int nb = db.exec("INSERT INTO test VALUES (NULL, \"test\")"); SQLite::Transaction transaction(db);
std::cout << "INSERT INTO test VALUES (NULL, \"test\")\", returned " << nb << std::endl;
db.exec("CREATE TABLE test (id INTEGER PRIMARY KEY, value TEXT)");
// Commit transaction
transaction.commit(); int nb = db.exec("INSERT INTO test VALUES (NULL, \"test\")");
} std::cout << "INSERT INTO test VALUES (NULL, \"test\")\", returned " << nb << std::endl;
catch (std::exception& e)
{ // Commit transaction
std::cout << "exception: " << e.what() << std::endl; transaction.commit();
} }
``` catch (std::exception& e)
{
### How to handle in assertion in SQLiteC++: std::cout << "exception: " << e.what() << std::endl;
Exceptions shall not be used in destructors, so SQLiteC++ use SQLITECPP_ASSERT() to check for errors in destructors. }
If you don't want assert() to be called, you have to enable and define an assert handler as shown below, ```
and by setting the flag SQLITECPP_ENABLE_ASSERT_HANDLER when compiling the lib.
### How to handle in assertion in SQLiteC++:
```C++ Exceptions shall not be used in destructors, so SQLiteC++ use SQLITECPP_ASSERT() to check for errors in destructors.
#ifdef SQLITECPP_ENABLE_ASSERT_HANDLER If you don't want assert() to be called, you have to enable and define an assert handler as shown below,
namespace SQLite and by setting the flag SQLITECPP_ENABLE_ASSERT_HANDLER when compiling the lib.
{
/// definition of the assertion handler enabled when SQLITECPP_ENABLE_ASSERT_HANDLER is defined in the project (CMakeList.txt) ```C++
void assertion_failed(const char* apFile, const long apLine, const char* apFunc, const char* apExpr, const char* apMsg) #ifdef SQLITECPP_ENABLE_ASSERT_HANDLER
{ namespace SQLite
// Print a message to the standard error output stream, and abort the program. {
std::cerr << apFile << ":" << apLine << ":" << " error: assertion failed (" << apExpr << ") in " << apFunc << "() with message \"" << apMsg << "\"\n"; /// definition of the assertion handler enabled when SQLITECPP_ENABLE_ASSERT_HANDLER is defined in the project (CMakeList.txt)
std::abort(); void assertion_failed(const char* apFile, const long apLine, const char* apFunc, const char* apExpr, const char* apMsg)
} {
} // Print a message to the standard error output stream, and abort the program.
#endif std::cerr << apFile << ":" << apLine << ":" << " error: assertion failed (" << apExpr << ") in " << apFunc << "() with message \"" << apMsg << "\"\n";
``` std::abort();
}
## How to contribute }
### GitHub website #endif
The most efficient way to help and contribute to this wrapper project is to ```
use the tools provided by GitHub:
- please fill bug reports and feature requests here: https://github.com/SRombauts/SQLiteCpp/issues ## How to contribute
- fork the repository, make some small changes and submit them with pull-request ### GitHub website
The most efficient way to help and contribute to this wrapper project is to
### Contact use the tools provided by GitHub:
You can also email me directly, I will answer any questions and requests. - please fill bug reports and feature requests here: https://github.com/SRombauts/SQLiteCpp/issues
- fork the repository, make some small changes and submit them with pull-request
### Coding Style Guidelines
The source code use the CamelCase naming style variant where : ### Contact
- type names (class, struct, typedef, enums...) begins with a capital letter You can also email me directly, I will answer any questions and requests.
- files (.cpp/.h) are named like the class they contains
- function and variable names begins with a lower case letter ### Coding Style Guidelines
- member variables begins with a 'm', function arguments begins with a 'a', boolean with a 'b', pointers with a 'p' The source code use the CamelCase naming style variant where :
- each file, class, method and member variable is documented using Doxygen tags - type names (class, struct, typedef, enums...) begins with a capital letter
See also http://www.appinf.com/download/CppCodingStyleGuide.pdf for good guidelines - files (.cpp/.h) are named like the class they contains
- function and variable names begins with a lower case letter
## See also - Some other simple C++ SQLite wrappers: - member variables begins with a 'm', function arguments begins with a 'a', boolean with a 'b', pointers with a 'p'
- each file, class, method and member variable is documented using Doxygen tags
See also the file WRAPPERS.md offering a more complete comparison of other wrappers. See also http://www.appinf.com/download/CppCodingStyleGuide.pdf for good guidelines
- [sqdbcpp](http://code.google.com/p/sqdbcpp/): RAII design, simple, no depandencies, UTF-8/UTF-16, new BSD license
- [sqlite3cc](http://ed.am/dev/sqlite3cc): uses boost, modern design, LPGPL ## See also - Some other simple C++ SQLite wrappers:
- [sqlite3pp](http://code.google.com/p/sqlite3pp/): uses boost, but never updated since initial publication in may 2012, MIT License
- [SQLite++](http://sqlitepp.berlios.de/): uses boost build system, Boost License 1.0 See bellow a short comparison of other wrappers done at the time of the writting:
- [CppSQLite](http://www.codeproject.com/Articles/6343/CppSQLite-C-Wrapper-for-SQLite/): famous Code Project but old design, BSD License - [sqdbcpp](http://code.google.com/p/sqdbcpp/): RAII design, simple, no dependencies, UTF-8/UTF-16, new BSD license
- [easySQLite](http://code.google.com/p/easysqlite/): manages table as structured objects, complex - [sqlite3cc](http://ed.am/dev/sqlite3cc): uses boost, modern design, LPGPL
- [sqlite_modern_cpp](https://github.com/keramer/sqlite_modern_cpp): modern C++11, all in one file, MIT license - [sqlite3pp](https://github.com/iwongu/sqlite3pp): modern design inspired by boost, MIT License
- [SQLite++](http://sqlitepp.berlios.de/): uses boost build system, Boost License 1.0
- [CppSQLite](http://www.codeproject.com/Articles/6343/CppSQLite-C-Wrapper-for-SQLite/): famous Code Project but old design, BSD License
- [easySQLite](http://code.google.com/p/easysqlite/): manages table as structured objects, complex
- [sqlite_modern_cpp](https://github.com/keramer/sqlite_modern_cpp): modern C++11, all in one file, MIT license

View File

@ -1,83 +0,0 @@
http://www.sqlite.org/cvstrac/wiki?p=SqliteWrappers
http://stackoverflow.com/questions/120295/what-is-a-good-oo-c-wrapper-for-sqlite
http://stackoverflow.com/questions/818155/sqlite-alternatives-for-c
http://www.reddit.com/search?q=sqlite
**sqlite3cc**: http://ed.am/dev/sqlite3cc/
- Nov 2009, Jan 2012 (v0.1)
- (++) modern design, use RAII => can be a source of inspiration for me
- (++) very well documented, in code and with a very good informal presentation
- (+) is maintained (recent), initial release is 0.1.0, January 2012 (started in 2010)
- (+/-) uses boost (some more dependancies...)
- (-) uses boost coding style (I tend to prefer CamelCaps or Java coding style)
- (-) a bit complex: offer many way to do the same thing where I would prefer a clean choice
- (-) thus it does not impose RAII, as it is still possible to open or close a database outside constructor/destructor
- (---) LPGPL: for me, this is a stopper as I would like to be able to use it in commercial products
- bazaar: http://bzr.ed.am/sqlite3cc
- bugtracker: personal: trac is still to be installed to http://dev.ed.am/sqlite3cc
- test suite: a simple main with boost filesystem (build librairy) depandancy
**sqdbcpp**: http://code.google.com/p/sqdbcpp/
- Dec 2009 (no more activity)
- (++) new BSD license
- (++) RAII design, with some good ideas, like the "Convertor" class
- (++) modern design, use RAII
- (+) CamelCaps naming convention
- (+) STL is the only depandancy
- (+) very small code
- (-) not RAII transactions
- (-) some unnecessary complexity to manage copyable objects (RefCount)
- (-) UTF-8/UTF-16: the second is not portable
- (--) Not documented (only a short example
- (---) Not maintained/not finished: contact author !?
- SVN: http://sqdbcpp.googlecode.com/svn/trunk/
- bugtracker: GoogleCode: http://code.google.com/p/sqdbcpp/issues/list
- test suite: with gtest
**sqlite3pp**: http://code.google.com/p/sqlite3pp/
- Sep 2007 to Mar 2009
- (++) MIT License
- (++) modern design, use RAII => can be a source of inspiration for me
- (+/-) uses boost (some more dependancies...)
- (-) complex: offer many way to do the same thing, and advance functionalities
- (--) Not documented in code
- (---) Not maintained, many open issues
- SVN: http://sqlite3pp.googlecode.com/svn/trunk/
- bugtracker: GoogleCode: http://code.google.com/p/sqlite3pp/issues/list
**SQLite++**: http://sqlitepp.berlios.de/
- Jan 2006 until now (Apr 2012)
- (++) still maintained
- (++) Boost License 1.0
- (+) good online introduction
- (+/-) uses boost (some more dependancies...)
- (-) uses boost build system
- (-) come with yet another unicode string library
- (-) too complex and big to dive easily into
- (--) Not documented in code
- SVN: https://svn.berlios.de/svnroot/repos/sqlitepp/trunk/
- bugtracker: no!
- test suite: yes, with bjam
**CppSQLite**: http://www.codeproject.com/Articles/6343/CppSQLite-C-Wrapper-for-SQLite/
- Mar 2004, Jun 2011
- (++??) BSD License? CodeProject License?
- (+) famous CodeProject, good introductory article
- (--) Not documented in code
- (--) old design, no RAII
- (--) unnecessary complex memory allocation for exception
- VCS: no! but cloned twice on GitHub
- bugtracker: no!
- test suite: no, only some demo code.
**easySQLite**: http://code.google.com/p/easysqlite/
- Sep 2010
- (++) new BSD license
- (+/-) Manage table as objects, requiring to define their structure
- (-) not RAII
- (--) complex
- (---) Not maintained, some open issues
- SVN: http://easysqlite.googlecode.com/svn/trunk/
- bugtracker: http://code.google.com/p/easysqlite/source/list
- test suite: yes, a big one, with UnitTest++

26
appveyor.yml Normal file
View File

@ -0,0 +1,26 @@
# Copyright (c) 2012-2015 Sebastien Rombauts (sebastien.rombauts@gmail.com)
# build format
version: "{build}"
# scripts that run after cloning repository
# NOTE : not updating submodule as cloning googletest does not work on AppVeyor
install:
# - git submodule update --init googletest
# configurations to add to build matrix
configuration:
- Debug
- Release
# scripts to run before build
# NOTE : no unit tests as cloning googletest does not work on AppVeyor
before_build:
- mkdir build
- cd build
- cmake -DSQLITECPP_BUILD_EXAMPLES=ON -DSQLITECPP_BUILD_TESTS=OFF -DSQLITECPP_RUN_CPPCHECK=OFF -DSQLITECPP_RUN_DOXYGEN=OFF ..
# build examples, and run tests (ie make & make test)
build_script:
- cmake --build .
# - ctest --output-on-failure

43
biicode.conf Normal file
View File

@ -0,0 +1,43 @@
# Biicode configuration file
[requirements]
# Blocks and versions this block depends on e.g.
google/gtest : 9
[parent]
# The parent version of this block. Must match folder name. E.g.
# user/block # No version number means not published yet
# You can change it to publish to a different track, and change version, e.g.
sqlite/sqlite: 7
[paths]
# Local directories to look for headers (within block)
include
/
sqlite3
[dependencies]
# Manual adjust file implicit dependencies, add (+), remove (-), or overwrite (=)
include/SQLiteCpp/Assertion.h - tests/Database_test.cpp
include/SQLiteCpp/Assertion.h - examples/example1/main.cpp
[mains]
# Manual adjust of files that define an executable
# !main.cpp # Do not build executable from this file
# main2.cpp # Build it (it doesnt have a main() function, but maybe it includes it)
[hooks]
# These are defined equal to [dependencies],files names matching bii*stage*hook.py
# will be launched as python scripts at stage = {post_process, clean}
# CMakeLists.txt + bii/my_post_process1_hook.py bii_clean_hook.py
[includes]
# Mapping of include patterns to external blocks
gtest/gtest.h: google/gtest/include
[data]
# Manually define data files dependencies, that will be copied to bin for execution
# By default they are copied to bin/user/block/... which should be taken into account
# when loading from disk such data
examples/example1/main.cpp + example.db3 logo.png

View File

@ -1,18 +1,17 @@
@REM Copyright (c) 2013 Sébastien Rombauts (sebastien.rombauts@gmail.com) @REM Copyright (c) 2012-2015 Sebastien Rombauts (sebastien.rombauts@gmail.com)
@REM @REM
@REM Distributed under the MIT License (MIT) (See accompanying file LICENSE.txt @REM Distributed under the MIT License (MIT) (See accompanying file LICENSE.txt
@REM or copy at http://opensource.org/licenses/MIT) @REM or copy at http://opensource.org/licenses/MIT)
mkdir build mkdir build
cd build cd build
@REM generate solution for Visual Studio 2010, and build it
cmake .. -G "Visual Studio 10" @REM Generate a Visual Studio solution for latest version found
cmake -DSQLITECPP_BUILD_EXAMPLES=ON -DSQLITECPP_BUILD_TESTS=ON ..
@REM Build default configuration (ie 'Debug')
cmake --build . cmake --build .
@REM prepare and launch tests @REM Build and run tests
mkdir examples
mkdir examples\example1
copy ..\examples\example1\example.db3 examples\example1
copy ..\examples\example1\logo.png examples\example1
ctest --output-on-failure ctest --output-on-failure
cd ..
cd ..

View File

@ -1,16 +1,15 @@
# Copyright (c) 2013 Sébastien Rombauts (sebastien.rombauts@gmail.com) # Copyright (c) 2012-2015 Sébastien Rombauts (sebastien.rombauts@gmail.com)
# #
# Distributed under the MIT License (MIT) (See accompanying file LICENSE.txt # Distributed under the MIT License (MIT) (See accompanying file LICENSE.txt
# or copy at http://opensource.org/licenses/MIT) # or copy at http://opensource.org/licenses/MIT)
mkdir -p build mkdir -p build
cd build cd build
# generate solution for GCC
cmake .. # Generate a Makefile for GCC (or Clang, depanding on CC/CXX envvar)
cmake -DSQLITECPP_BUILD_EXAMPLES=ON -DSQLITECPP_BUILD_TESTS=ON ..
# Build (ie 'make')
cmake --build . cmake --build .
# prepare and launch tests # Build and run unit-tests (ie 'make test')
mkdir -p examples/example1
cp ../examples/example1/example.db3 examples/example1
cp ../examples/example1/logo.png examples/example1
ctest --output-on-failure ctest --output-on-failure

View File

@ -13,8 +13,7 @@
#include <iostream> #include <iostream>
#include <cstdio> #include <cstdio>
#include <cstdlib> #include <cstdlib>
#include <cstdlib> #include <string>
#include <SQLiteCpp/SQLiteCpp.h> #include <SQLiteCpp/SQLiteCpp.h>
@ -31,10 +30,17 @@ void assertion_failed(const char* apFile, const long apLine, const char* apFunc,
} }
#endif #endif
/// Get example path
static inline std::string getExamplePath()
{
std::string filePath(__FILE__);
return filePath.substr( 0, filePath.length() - std::string("main.cpp").length());
}
/// Example Database /// Example Database
static const char* filename_example_db3 = "examples/example1/example.db3"; static const std::string filename_example_db3 = getExamplePath() + "/example.db3";
/// Image /// Image
static const char* filename_logo_png = "examples/example1/logo.png"; static const std::string filename_logo_png = getExamplePath() + "/logo.png";
/// Object Oriented Basic example /// Object Oriented Basic example
@ -307,7 +313,7 @@ int main ()
db.exec("DROP TABLE IF EXISTS test"); db.exec("DROP TABLE IF EXISTS test");
db.exec("CREATE TABLE test (id INTEGER PRIMARY KEY, value BLOB)"); db.exec("CREATE TABLE test (id INTEGER PRIMARY KEY, value BLOB)");
FILE* fp = fopen(filename_logo_png, "rb"); FILE* fp = fopen(filename_logo_png.c_str(), "rb");
if (NULL != fp) if (NULL != fp)
{ {
char buffer[16*1024]; char buffer[16*1024];

@ -1 +1 @@
Subproject commit be1b3b66822cc3929f3da700973cef88bf45849a Subproject commit 4650552ff637bb44ecf7784060091cbed3252211

View File

@ -37,8 +37,6 @@ namespace SQLite
* 2) the SQLite "Serialized" mode is not supported by SQLiteC++, * 2) the SQLite "Serialized" mode is not supported by SQLiteC++,
* because of the way it shares the underling SQLite precompiled statement * because of the way it shares the underling SQLite precompiled statement
* in a custom shared pointer (See the inner class "Statement::Ptr"). * in a custom shared pointer (See the inner class "Statement::Ptr").
*
* @todo inline all simple getters
*/ */
class Column class Column
{ {

View File

@ -3,7 +3,7 @@
* @ingroup SQLiteCpp * @ingroup SQLiteCpp
* @brief Management of a SQLite Database Connection. * @brief Management of a SQLite Database Connection.
* *
* Copyright (c) 2012-2013 Sebastien Rombauts (sebastien.rombauts@gmail.com) * Copyright (c) 2012-2015 Sebastien Rombauts (sebastien.rombauts@gmail.com)
* *
* Distributed under the MIT License (MIT) (See accompanying file LICENSE.txt * Distributed under the MIT License (MIT) (See accompanying file LICENSE.txt
* or copy at http://opensource.org/licenses/MIT) * or copy at http://opensource.org/licenses/MIT)
@ -239,17 +239,25 @@ public:
return sqlite3_total_changes(mpSQLite); return sqlite3_total_changes(mpSQLite);
} }
/** /// @brief Return the filename used to open the database.
* @brief Return the filename used to open the database
*/
inline const std::string& getFilename() const noexcept // nothrow inline const std::string& getFilename() const noexcept // nothrow
{ {
return mFilename; return mFilename;
} }
/** /// @brief Return the numeric result code for the most recent failed API call (if any).
* @brief Return UTF-8 encoded English language explanation of the most recent error. inline int getErrorCode() const noexcept // nothrow
*/ {
return sqlite3_errcode(mpSQLite);
}
/// @brief Return the extended numeric result code for the most recent failed API call (if any).
inline int getExtendedErrorCode() const noexcept // nothrow
{
return sqlite3_extended_errcode(mpSQLite);
}
/// Return UTF-8 encoded English language explanation of the most recent failed API call (if any).
inline const char* errmsg() const noexcept // nothrow inline const char* errmsg() const noexcept // nothrow
{ {
return sqlite3_errmsg(mpSQLite); return sqlite3_errmsg(mpSQLite);

View File

@ -3,7 +3,7 @@
* @ingroup SQLiteCpp * @ingroup SQLiteCpp
* @brief A prepared SQLite Statement is a compiled SQL query ready to be executed, pointing to a row of result. * @brief A prepared SQLite Statement is a compiled SQL query ready to be executed, pointing to a row of result.
* *
* Copyright (c) 2012-2013 Sebastien Rombauts (sebastien.rombauts@gmail.com) * Copyright (c) 2012-2015 Sebastien Rombauts (sebastien.rombauts@gmail.com)
* *
* Distributed under the MIT License (MIT) (See accompanying file LICENSE.txt * Distributed under the MIT License (MIT) (See accompanying file LICENSE.txt
* or copy at http://opensource.org/licenses/MIT) * or copy at http://opensource.org/licenses/MIT)
@ -50,7 +50,7 @@ public:
* @brief Compile and register the SQL query for the provided SQLite Database Connection * @brief Compile and register the SQL query for the provided SQLite Database Connection
* *
* @param[in] aDatabase the SQLite Database Connection * @param[in] aDatabase the SQLite Database Connection
* @param[in] apQuery an UTF-8 encoded query string * @param[in] apQuery an UTF-8 encoded query string
* *
* Exception is thrown in case of error, then the Statement object is NOT constructed. * Exception is thrown in case of error, then the Statement object is NOT constructed.
*/ */
@ -269,7 +269,7 @@ public:
//////////////////////////////////////////////////////////////////////////// ////////////////////////////////////////////////////////////////////////////
/** /**
* @brief Return a copie of the column data specified by its index * @brief Return a copy of the column data specified by its index
* *
* Can be used to access the data of the current row of result when applicable, * Can be used to access the data of the current row of result when applicable,
* while the executeStep() method returns true. * while the executeStep() method returns true.
@ -326,8 +326,18 @@ public:
{ {
return mbDone; return mbDone;
} }
/// @brief Return UTF-8 encoded English language explanation of the most recent error. /// @brief Return the numeric result code for the most recent failed API call (if any).
inline const char* errmsg() const inline int getErrorCode() const noexcept // nothrow
{
return sqlite3_errcode(mStmtPtr);
}
/// @brief Return the extended numeric result code for the most recent failed API call (if any).
inline int getExtendedErrorCode() const noexcept // nothrow
{
return sqlite3_extended_errcode(mStmtPtr);
}
/// Return UTF-8 encoded English language explanation of the most recent failed API call (if any).
inline const char* errmsg() const noexcept // nothrow
{ {
return sqlite3_errmsg(mStmtPtr); return sqlite3_errmsg(mStmtPtr);
} }
@ -368,10 +378,10 @@ public:
/// @} /// @}
private: private:
sqlite3* mpSQLite; //!< Pointer to SQLite Database Connection Handle sqlite3* mpSQLite; //!< Pointer to SQLite Database Connection Handle
sqlite3_stmt* mpStmt; //!< Pointer to SQLite Statement Object sqlite3_stmt* mpStmt; //!< Pointer to SQLite Statement Object
unsigned int* mpRefCount; //!< Pointer to the heap allocated reference counter of the sqlite3_stmt unsigned int* mpRefCount; //!< Pointer to the heap allocated reference counter of the sqlite3_stmt
//!< (to share it with Column objects) //!< (to share it with Column objects)
}; };
private: private:
@ -385,7 +395,7 @@ private:
* *
* @param[in] SQLite return code to test against the SQLITE_OK expected value * @param[in] SQLite return code to test against the SQLITE_OK expected value
*/ */
void check(const int aRet) const; void check(const int aRet);
private: private:
std::string mQuery; //!< UTF-8 SQL Query std::string mQuery; //!< UTF-8 SQL Query

View File

@ -1,4 +1,4 @@
"sqlite3.c" and "sqlite3.h" files from sqlite-amalgamation-3071401.zip (SQLite 3.7.14.1) "sqlite3.c" and "sqlite3.h" files from sqlite-amalgamation-3080803.zip (SQLite 3.8.8.3)
Those files are provided for easy setup under Windows ; they are used by the Visual Studio example solution. Those files are provided for easy setup under Windows ; they are used by the Visual Studio example solution.

File diff suppressed because it is too large Load Diff

File diff suppressed because it is too large Load Diff

View File

@ -3,7 +3,7 @@
* @ingroup SQLiteCpp * @ingroup SQLiteCpp
* @brief A prepared SQLite Statement is a compiled SQL query ready to be executed, pointing to a row of result. * @brief A prepared SQLite Statement is a compiled SQL query ready to be executed, pointing to a row of result.
* *
* Copyright (c) 2012-2013 Sebastien Rombauts (sebastien.rombauts@gmail.com) * Copyright (c) 2012-2015 Sebastien Rombauts (sebastien.rombauts@gmail.com)
* *
* Distributed under the MIT License (MIT) (See accompanying file LICENSE.txt * Distributed under the MIT License (MIT) (See accompanying file LICENSE.txt
* or copy at http://opensource.org/licenses/MIT) * or copy at http://opensource.org/licenses/MIT)
@ -200,7 +200,7 @@ bool Statement::executeStep()
} }
else else
{ {
throw SQLite::Exception("Statement need to be reseted"); throw SQLite::Exception("Statement needs to be reset");
} }
return mbOk; // true only if one row is accessible by getColumn(N) return mbOk; // true only if one row is accessible by getColumn(N)
@ -272,7 +272,7 @@ bool Statement::isColumnNull(const int aIndex) const
} }
// Check if aRet equal SQLITE_OK, else throw a SQLite::Exception with the SQLite error message // Check if aRet equal SQLITE_OK, else throw a SQLite::Exception with the SQLite error message
void Statement::check(const int aRet) const void Statement::check(const int aRet)
{ {
if (SQLITE_OK != aRet) if (SQLITE_OK != aRet)
{ {
@ -337,11 +337,9 @@ Statement::Ptr::~Ptr() noexcept // nothrow
--(*mpRefCount); --(*mpRefCount);
if (0 == *mpRefCount) if (0 == *mpRefCount)
{ {
// If count reaches zero, finalize the sqlite3_stmt, // If count reaches zero, finalize the sqlite3_stmt, as no Statement nor Column objet use it anymore.
// as no Statement not Column objet use it anymore // No need to check the return code, as it is the same as the last statement evaluation.
int ret = sqlite3_finalize(mpStmt); sqlite3_finalize(mpStmt);
// Never throw an exception in a destructor
SQLITECPP_ASSERT(SQLITE_OK == ret, sqlite3_errmsg(mpSQLite)); // See SQLITECPP_ENABLE_ASSERT_HANDLER
// and delete the reference counter // and delete the reference counter
delete mpRefCount; delete mpRefCount;

View File

@ -3,7 +3,7 @@
* @ingroup tests * @ingroup tests
* @brief Test of a SQLiteCpp Database. * @brief Test of a SQLiteCpp Database.
* *
* Copyright (c) 2014 Sebastien Rombauts (sebastien.rombauts@gmail.com) * Copyright (c) 2012-2015 Sebastien Rombauts (sebastien.rombauts@gmail.com)
* *
* Distributed under the MIT License (MIT) (See accompanying file LICENSE.txt * Distributed under the MIT License (MIT) (See accompanying file LICENSE.txt
* or copy at http://opensource.org/licenses/MIT) * or copy at http://opensource.org/licenses/MIT)
@ -146,15 +146,23 @@ TEST(Database, execException) {
{ {
// Create a new database // Create a new database
SQLite::Database db("test.db3", SQLITE_OPEN_READWRITE|SQLITE_OPEN_CREATE); SQLite::Database db("test.db3", SQLITE_OPEN_READWRITE|SQLITE_OPEN_CREATE);
EXPECT_EQ(SQLITE_OK, db.getErrorCode());
EXPECT_EQ(SQLITE_OK, db.getExtendedErrorCode());
// exception with SQL error: "no such table" // exception with SQL error: "no such table"
EXPECT_THROW(db.exec("INSERT INTO test VALUES (NULL, \"first\", 3)"), SQLite::Exception); EXPECT_THROW(db.exec("INSERT INTO test VALUES (NULL, \"first\", 3)"), SQLite::Exception);
EXPECT_EQ(SQLITE_ERROR, db.getErrorCode());
EXPECT_EQ(SQLITE_ERROR, db.getExtendedErrorCode());
// Create a new table // Create a new table
db.exec("CREATE TABLE test (id INTEGER PRIMARY KEY, value TEXT, weight INTEGER)"); db.exec("CREATE TABLE test (id INTEGER PRIMARY KEY, value TEXT, weight INTEGER)");
EXPECT_EQ(SQLITE_OK, db.getErrorCode());
EXPECT_EQ(SQLITE_OK, db.getExtendedErrorCode());
// exception with SQL error: "table test has 3 columns but 2 values were supplied" // exception with SQL error: "table test has 3 columns but 2 values were supplied"
EXPECT_THROW(db.exec("INSERT INTO test VALUES (NULL, 3)"), SQLite::Exception); EXPECT_THROW(db.exec("INSERT INTO test VALUES (NULL, 3)"), SQLite::Exception);
EXPECT_EQ(SQLITE_ERROR, db.getErrorCode());
EXPECT_EQ(SQLITE_ERROR, db.getExtendedErrorCode());
// exception with SQL error: "No row to get a column from" // exception with SQL error: "No row to get a column from"
EXPECT_THROW(db.execAndGet("SELECT weight FROM test WHERE value=\"first\""), SQLite::Exception); EXPECT_THROW(db.execAndGet("SELECT weight FROM test WHERE value=\"first\""), SQLite::Exception);
@ -162,7 +170,6 @@ TEST(Database, execException) {
EXPECT_EQ(1, db.exec("INSERT INTO test VALUES (NULL, \"first\", 3)")); EXPECT_EQ(1, db.exec("INSERT INTO test VALUES (NULL, \"first\", 3)"));
// exception with SQL error: "No row to get a column from" // exception with SQL error: "No row to get a column from"
EXPECT_THROW(db.execAndGet("SELECT weight FROM test WHERE value=\"second\""), SQLite::Exception); EXPECT_THROW(db.execAndGet("SELECT weight FROM test WHERE value=\"second\""), SQLite::Exception);
} // Close DB test.db3 } // Close DB test.db3
remove("test.db3"); remove("test.db3");
} }

View File

@ -3,7 +3,7 @@
* @ingroup tests * @ingroup tests
* @brief Test of a SQLiteCpp Statement. * @brief Test of a SQLiteCpp Statement.
* *
* Copyright (c) 2014 Sebastien Rombauts (sebastien.rombauts@gmail.com) * Copyright (c) 2012-2015 Sebastien Rombauts (sebastien.rombauts@gmail.com)
* *
* Distributed under the MIT License (MIT) (See accompanying file LICENSE.txt * Distributed under the MIT License (MIT) (See accompanying file LICENSE.txt
* or copy at http://opensource.org/licenses/MIT) * or copy at http://opensource.org/licenses/MIT)
@ -22,12 +22,18 @@ TEST(Statement, invalid) {
{ {
// Create a new database // Create a new database
SQLite::Database db("test.db3", SQLITE_OPEN_READWRITE|SQLITE_OPEN_CREATE); SQLite::Database db("test.db3", SQLITE_OPEN_READWRITE|SQLITE_OPEN_CREATE);
EXPECT_EQ(SQLITE_OK, db.getErrorCode());
EXPECT_EQ(SQLITE_OK, db.getExtendedErrorCode());
// Compile a SQL query, but without any table in the database // Compile a SQL query, but without any table in the database
EXPECT_THROW(SQLite::Statement query(db, "SELECT * FROM test"), SQLite::Exception); EXPECT_THROW(SQLite::Statement query(db, "SELECT * FROM test"), SQLite::Exception);
EXPECT_EQ(SQLITE_ERROR, db.getErrorCode());
EXPECT_EQ(SQLITE_ERROR, db.getExtendedErrorCode());
EXPECT_EQ(0, db.exec("CREATE TABLE test (id INTEGER PRIMARY KEY, value TEXT)")); EXPECT_EQ(0, db.exec("CREATE TABLE test (id INTEGER PRIMARY KEY, value TEXT)"));
EXPECT_EQ(SQLITE_OK, db.getErrorCode());
EXPECT_EQ(SQLITE_OK, db.getExtendedErrorCode());
// Compile a SQL query with no parameter // Compile a SQL query with no parameter
SQLite::Statement query(db, "SELECT * FROM test"); SQLite::Statement query(db, "SELECT * FROM test");
EXPECT_STREQ("SELECT * FROM test", query.getQuery().c_str()); EXPECT_STREQ("SELECT * FROM test", query.getQuery().c_str());
@ -61,6 +67,8 @@ TEST(Statement, invalid) {
EXPECT_THROW(query.bind(2, 123), SQLite::Exception); EXPECT_THROW(query.bind(2, 123), SQLite::Exception);
EXPECT_THROW(query.bind(0, "abc"), SQLite::Exception); EXPECT_THROW(query.bind(0, "abc"), SQLite::Exception);
EXPECT_THROW(query.bind(0), SQLite::Exception); EXPECT_THROW(query.bind(0), SQLite::Exception);
EXPECT_EQ(SQLITE_RANGE, db.getErrorCode());
EXPECT_EQ(SQLITE_RANGE, db.getExtendedErrorCode());
query.exec(); query.exec();
EXPECT_THROW(query.isColumnNull(0), SQLite::Exception); EXPECT_THROW(query.isColumnNull(0), SQLite::Exception);