pax_global_header00006660000000000000000000000064132274710260014516gustar00rootroot0000000000000052 comment=29167093b2294deb480ebbcec80143e7246597e7 hoel-1.3.1/000077500000000000000000000000001322747102600124475ustar00rootroot00000000000000hoel-1.3.1/.gitignore000066400000000000000000000001471322747102600144410ustar00rootroot00000000000000*.o *.so *.so.*.* example_sqlite3 example_mariadb example_pgsql example_mariadb_json core valgrind.txt hoel-1.3.1/LICENSE000066400000000000000000000635361322747102600134710ustar00rootroot00000000000000 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.3.1/Makefile000066400000000000000000000022541322747102600141120ustar00rootroot00000000000000# # Example program # # Makefile used to build all programs # # 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. # LIBHOEL_LOCATION=./src EXAMPLE_LOCATION=./examples TEST_LOCATION=./test all: libhoel.so example_sqlite3 example_mariadb example_pgsql debug: cd $(EXAMPLE_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 libhoel.so: 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 test: cd $(TEST_LOCATION) && $(MAKE) test hoel-1.3.1/README.md000066400000000000000000000365341322747102600137410ustar00rootroot00000000000000# Hoel Database abstraction library written in C. Simple and easy to use database access library. Works with SQLite 3, MariaDB/Mysql and PostgreSQL databases. Uses a JSON-based language with `jansson` to execute simples queries based on one table. # Installation ## Debian-ish distribution package [![Packaging status](https://repology.org/badge/vertical-allrepos/hoel.svg)](https://repology.org/metapackage/hoel) Hoel is now available in Debian Buster (testing) and some Debian based distributions. To install the development package on your system, run the command as root: ```shell # apt install libhoel-dev ``` ## Install from the source Clone, compile and install [Orcania](https://github.com/babelouest/orcania) and [Yder](https://github.com/babelouest/yder) libraries. ### Orcania (Miscellaneous functions) ```shell $ git clone https://github.com/babelouest/orcania.git $ cd orcania/src $ make && sudo make install ``` ### Yder (simple logs library) ```shell $ git clone https://github.com/babelouest/yder.git $ cd yder/src $ make $ sudo make install ``` ### Jansson Install [Jansson](http://www.digip.org/jansson/) library for JSON manipulation. On a debian-based platform, run the following command: ```shell $ sudo apt-get install libjansson-dev ``` ### Hoel Install Hoel dependencies: - SQLite3: Install the package `libsqlite3-dev` - MariaDB/Mysql: Install the package `libmysqlclient-dev` or `libmariadbclient-dev` - PostgreSQL: Install the package `libpq-dev` Download hoel from github repository. ```shell $ git clone https://github.com/babelouest/hoel.git $ 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/Mysql 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 `PREFIX` value in the `src/Makefile`. # API Documentation ## Header files and compilation To use hoel in your code, you must use the `#define` corresponding to the backend you use before including the file `hoel.h`. For example: ```c #define _HOEL_SQLITE #include ``` If you want to use different backends in your source code, just add its `#define` before including `hoel.h`. ```c #define _HOEL_SQLITE #define _HOEL_MARIADB #define _HOEL_PGSQL #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 sucess, NULL on error */ struct _h_connection * h_connect_mariadb(char * host, char * user, char * passwd, char * db, unsigned int port, 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 function `h_escape_string`, the returned value must be h_free'd after use. ```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); ``` ### 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 "order_by": "col_name [asc|desc]" // String, available for h_select, specify the order by clause, optional "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%'" }, "col7": { "operator": "IN", // Generates col7 IN ('value1',42,4.2) "value": [ // Values can be string, real or integer "value1", 42, 4.2 ] } } } ``` #### 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 axample, 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.3.1/_config.yml000066400000000000000000000000331322747102600145720ustar00rootroot00000000000000theme: jekyll-theme-minimalhoel-1.3.1/examples/000077500000000000000000000000001322747102600142655ustar00rootroot00000000000000hoel-1.3.1/examples/Makefile000066400000000000000000000037061322747102600157330ustar00rootroot00000000000000# # 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 CFLAGS=-c -Wall -D_REENTRANT -I$(PREFIX)/include $(ADDITIONALFLAGS) HOEL_LOCATION=../src LIBS=-lc -lhoel -ljansson -lyder -L$(HOEL_LOCATION) ADDITIONALFLAGS=-O3 all: libhoel.so example_sqlite3 example_mariadb example_pgsql example_mariadb_json clean: rm -f *.o example_sqlite3 example_mariadb example_pgsql example_mariadb_json 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) 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 hoel-1.3.1/examples/example_mariadb.c000066400000000000000000000132371322747102600175510ustar00rootroot00000000000000#include #include #include #define _HOEL_MARIADB #include "../src/hoel.h" /** * Implementation of sprintf that return a malloc'd char * with the string construction * because life is too short to use 3 lines instead of 1 * but don't forget to free the returned value after use! */ char * cur_msprintf(const char * message, ...) { va_list argp, argp_cpy; size_t out_len = 0; char * out = NULL; va_start(argp, message); va_copy(argp_cpy, argp); out_len = vsnprintf(NULL, 0, message, argp); out = malloc(out_len+sizeof(char)); if (out == NULL) { return NULL; } vsnprintf(out, (out_len+sizeof(char)), message, argp_cpy); va_end(argp); va_end(argp_cpy); return out; } void print_result(struct _h_result result) { int col, row; char buf[64]; int i; printf("rows: %d, col: %d\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; query = cur_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); sanitized = h_escape_string(conn, "Hodor son of H'rtp'ss"); query = cur_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 = cur_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 = cur_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)); printf("COIN COIN COIN\n"); free(sanitized); free(query); query = cur_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 = cur_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 = cur_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 = cur_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 = cur_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 = cur_msprintf("delete from %s where id=%d", table, last_id); printf("delete result: %d\n", h_query_delete(conn, query)); free(query); query = cur_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.3.1/examples/example_mariadb.sql000066400000000000000000000002061322747102600201160ustar00rootroot00000000000000CREATE TABLE other_test ( id INTEGER PRIMARY KEY AUTO_INCREMENT, name VARCHAR(128), age INTEGER, temperature FLOAT ); hoel-1.3.1/examples/example_mariadb_json.c000066400000000000000000000106451322747102600206020ustar00rootroot00000000000000#include #include #include #define _HOEL_MARIADB #include "../src/hoel.h" void unit_tests(struct _h_connection * conn) { json_t * j_result, * j_where, * j_array, * j_set, * j_data, * j_query; char * table = "other_test", * dump; int res; j_where = json_object(); json_object_set_new(j_where, "age", json_pack("{sssi}", "operator", ">", "value", 46)); json_object_set_new(j_where, "name", json_pack("{ssss}", "operator", "LIKE", "value", "Hodor%")); j_query = json_object(); json_object_set_new(j_query, "table", json_string(table)); json_object_set_new(j_query, "where", j_where); res = h_select(conn, j_query, &j_result, NULL); if (res == H_OK) { dump = json_dumps(j_result, JSON_INDENT(2)); printf("json select result is\n%s\n", dump); json_decref(j_result); free(dump); } else { printf("Error executing select query: %d\n", res); } json_decref(j_query); j_data = json_object(); json_object_set_new(j_data, "name", json_string("Ned Stark Winter is coming")); json_object_set_new(j_data, "age", json_integer(45)); json_object_set_new(j_data, "temperature", json_real(30.1)); json_object_set_new(j_data, "birthdate", json_string("1408-06-01 03:05:11")); j_query = json_object(); json_object_set_new(j_query, "table", json_string(table)); json_object_set_new(j_query, "values", j_data); printf("insert result: %d\n", h_insert(conn, j_query, NULL)); json_decref(j_query); j_array = json_array(); json_array_append_new(j_array, json_string("name")); json_array_append_new(j_array, json_string("age")); json_array_append_new(j_array, json_string("birthdate")); j_where = json_object(); json_object_set_new(j_where, "name", json_string("Ned Stark Winter is coming")); j_query = json_object(); json_object_set_new(j_query, "table", json_string(table)); json_object_set_new(j_query, "columns", j_array); json_object_set_new(j_query, "where", j_where); if (h_select(conn, j_query, &j_result, NULL) == H_OK) { dump = json_dumps(j_result, JSON_INDENT(2)); printf("json select result is\n%s\n", dump); json_decref(j_result); free(dump); } else { printf("Error executing select query\n"); } json_decref(j_query); j_where = json_object(); json_object_set_new(j_where, "age", json_integer(45)); j_set = json_object(); json_object_set_new(j_set, "age", json_integer(47)); j_query = json_object(); json_object_set_new(j_query, "table", json_string(table)); json_object_set_new(j_query, "set", j_set); json_object_set_new(j_query, "where", j_where); if (h_update(conn, j_query, NULL) == H_OK) { printf("Update query OK\n"); json_decref(j_query); j_query = json_object(); json_object_set_new(j_query, "table", json_string(table)); if (h_select(conn, j_query, &j_result, NULL) == H_OK) { dump = json_dumps(j_result, JSON_INDENT(2)); printf("json select result is\n%s\n", dump); json_decref(j_result); free(dump); } else { printf("Error executing select query\n"); } json_decref(j_query); } else { json_decref(j_query); printf("Error executing update query\n"); } j_where = json_object(); json_object_set_new(j_where, "age", json_pack("{sssi}", "operator", ">", "value", 46)); j_query = json_object(); json_object_set_new(j_query, "table", json_string(table)); json_object_set_new(j_query, "where", j_where); if (h_delete(conn, j_query, NULL) == H_OK) { printf("Delete query OK\n"); json_decref(j_query); j_query = json_object(); json_object_set_new(j_query, "table", json_string(table)); if (h_select(conn, j_query, &j_result, NULL) == H_OK) { dump = json_dumps(j_result, JSON_INDENT(2)); printf("json select result is\n%s\n", dump); json_decref(j_result); free(dump); } else { printf("Error executing select query\n"); } } else { json_decref(j_query); printf("Error executing delete query\n"); } } int main(int argc, char ** argv) { struct _h_connection * conn; y_init_logs("test_hoel_mariadb_json", Y_LOG_MODE_CONSOLE, Y_LOG_LEVEL_DEBUG, NULL, "Starting test_hoel_mariadb_json"); 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); y_close_logs(); return h_clean_connection(conn); } hoel-1.3.1/examples/example_pgsql.c000066400000000000000000000056671322747102600173100ustar00rootroot00000000000000#include #include #include #define _HOEL_PGSQL #include "../src/hoel.h" 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=girflet 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.3.1/examples/example_sqlite3.c000066400000000000000000000126111322747102600175310ustar00rootroot00000000000000#include #include #include #include #define _HOEL_SQLITE #include "../src/hoel.h" /** * Implementation of sprintf that return a malloc'd char * with the string construction * because life is too short to use 3 lines instead of 1 * but don't forget to free the returned value after use! */ char * msprintf(const char * message, ...) { va_list argp, argp_cpy; size_t out_len = 0; char * out = NULL; va_start(argp, message); va_copy(argp_cpy, argp); out_len = vsnprintf(NULL, 0, message, argp); out = malloc(out_len+sizeof(char)); if (out == NULL) { return NULL; } vsnprintf(out, (out_len+sizeof(char)), message, argp_cpy); va_end(argp); va_end(argp_cpy); return out; } void print_result(struct _h_result result) { int col, row, i; printf("rows: %d, col: %d\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 = "/home/pi/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.3.1/examples/example_sqlite3.sql000066400000000000000000000001751322747102600201100ustar00rootroot00000000000000CREATE TABLE other_test ( id INTEGER PRIMARY KEY AUTOINCREMENT, name TEXT, age INTEGER, temperature FLOAT ); hoel-1.3.1/src/000077500000000000000000000000001322747102600132365ustar00rootroot00000000000000hoel-1.3.1/src/Makefile000066400000000000000000000051561322747102600147050ustar00rootroot00000000000000# # Hoel Framework # # 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 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 FLAGS_SQLITE=-D_HOEL_SQLITE LIBS_SQLITE=-lsqlite3 endif ifndef DISABLE_MARIADB FLAGS_MARIADB=-D_HOEL_MARIADB $(shell mysql_config --cflags) LIBS_MARIADB=$(shell mysql_config --libs_r) endif ifndef DISABLE_POSTGRESQL FLAGS_PGSQL=-D_HOEL_PGSQL -I/usr/include/postgresql/ LIBS_PGSQL=-lpq endif PREFIX=/usr/local CFLAGS=-c -fPIC -Wall -I$(PREFIX)/include $(FLAGS_SQLITE) $(FLAGS_MARIADB) $(FLAGS_PGSQL) -D_REENTRANT $(ADDITIONALFLAGS) LIBS=-L$(PREFIX)/lib -lc -ljansson -lyder -lorcania $(LIBS_SQLITE) $(LIBS_PGSQL) $(LIBS_MARIADB) OUTPUT=libhoel.so VERSION=1.3.1 all: release hoel.o: hoel.c hoel.h $(CC) $(CFLAGS) hoel.c hoel-sqlite.o: hoel-sqlite.c hoel.h $(CC) $(CFLAGS) hoel-sqlite.c hoel-mariadb.o: hoel-mariadb.c hoel.h $(CC) $(CFLAGS) hoel-mariadb.c hoel-pgsql.o: hoel-pgsql.c hoel.h $(CC) $(CFLAGS) hoel-pgsql.c hoel-simple-json.o: hoel-simple-json.c hoel.h $(CC) $(CFLAGS) hoel-simple-json.c libhoel.so: hoel-sqlite.o hoel-mariadb.o hoel-pgsql.o hoel-simple-json.o hoel.o $(CC) -shared -Wl,-soname,$(OUTPUT) -o $(OUTPUT).$(VERSION) hoel-sqlite.o hoel-mariadb.o hoel-pgsql.o hoel-simple-json.o hoel.o $(LIBS) ln -sf $(OUTPUT).$(VERSION) $(OUTPUT) libhoel.a: hoel-sqlite.o hoel-mariadb.o hoel-pgsql.o hoel-simple-json.o hoel.o ar rcs libhoel.a hoel-sqlite.o hoel-mariadb.o hoel-pgsql.o hoel-simple-json.o hoel.o clean: rm -f *.o *.so *.a $(OUTPUT) $(OUTPUT).* install: all cp $(OUTPUT).$(VERSION) $(PREFIX)/lib cp hoel.h $(PREFIX)/include /sbin/ldconfig static-install: static cp libhoel.a $(PREFIX)/lib cp hoel.h $(PREFIX)/include uninstall: rm -f $(PREFIX)/lib/$(OUTPUT) $(PREFIX)/lib/libhoel.a rm -f $(PREFIX)/lib/$(OUTPUT).* rm -f $(PREFIX)/include/hoel.h 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.3.1/src/h-private.h000066400000000000000000000031451322747102600153110ustar00rootroot00000000000000 #ifndef __H_PRIVATE_H_ #define __H_PRIVATE_H_ /** * 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 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); /** * 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.3.1/src/hoel-mariadb.c000066400000000000000000000344631322747102600157400ustar00rootroot00000000000000/** * * Hoel database abstraction library * * hoel-mariadb.c: Maria DB/Mysql specific functions * * Copyright 2015-2016 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; my_bool reconnect = 1; if (host != NULL && db != NULL) { conn = 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 = malloc(sizeof(struct _h_mariadb)); if (conn->connection == NULL) { y_log_message(Y_LOG_LEVEL_ERROR, "Hoel - Error allocating memory for conn->connection"); free(conn); return NULL; } if (mysql_library_init(0, NULL, NULL)) { y_log_message(Y_LOG_LEVEL_ERROR, "mysql_library_init error, aborting"); 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"); 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); 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 = malloc(2 * strlen(unsafe) + sizeof(char)); if (escaped == NULL) { y_log_message(Y_LOG_LEVEL_ERROR, "Hoel - Error allocating memory for escaped"); return NULL; } mysql_real_escape_string(((struct _h_mariadb *)conn->connection)->db_handle, escaped, unsafe, strlen(unsafe)); return escaped; } /** * Return the id of the last inserted value */ int h_last_insert_id_mariadb(const struct _h_connection * conn) { int id = 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)); } 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, 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[20]; 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), "%FT%TZ", &((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; 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 = strtol(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, "%F", &tm_value) == NULL) { data = h_new_data_null(); } else { data = h_new_data_datetime(&tm_value); } break; case FIELD_TYPE_TIME: if (strptime(value, "%T", &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, "%F %T", &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); 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) { y_log_message(Y_LOG_LEVEL_ERROR, "Hoel was not compiled with MariaDB backend"); return NULL; } void h_close_mariadb(struct _h_connection * conn) { y_log_message(Y_LOG_LEVEL_ERROR, "Hoel was not compiled with MariaDB backend"); } #endif hoel-1.3.1/src/hoel-pgsql.c000066400000000000000000000330611322747102600154600ustar00rootroot00000000000000/** * * Hoel database abstraction library * * hoel-pgsql.c: Postgre SQL specific functions * * Copyright 2015-2016 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; }; /** * 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) { struct _h_connection * conn = NULL; struct _h_result result_types; int res_types, row; char * cur_type_name, * endptr = NULL; Oid cur_type_oid; if (conninfo != NULL) { conn = malloc(sizeof(struct _h_connection)); if (conn == NULL) { y_log_message(Y_LOG_LEVEL_ERROR, "Hoel - Error allocating memory for conn"); } conn->type = HOEL_DB_TYPE_PGSQL; conn->connection = malloc(sizeof(struct _h_pgsql)); if (conn->connection == NULL) { y_log_message(Y_LOG_LEVEL_ERROR, "Hoel - Error allocating memory for conn->connection"); free(conn); conn = 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); free(conn->connection); free(conn); conn = NULL; } else { res_types = h_execute_query_pgsql(conn, "select oid, typname from pg_type", &result_types); if (res_types == H_OK) { if (result_types.nb_columns == 2) { for (row=0; rowvalue, &endptr, 10); cur_type_name = ((struct _h_type_text *)result_types.data[row][1].t_data)->value; if (*endptr == '\0' && endptr != ((struct _h_type_text *)result_types.data[row][0].t_data)->value) { ((struct _h_pgsql *)conn->connection)->list_type = o_realloc(((struct _h_pgsql *)conn->connection)->list_type, (((struct _h_pgsql *)conn->connection)->nb_type + 1) * sizeof(struct _h_pg_type)); if (((struct _h_pgsql *)conn->connection)->list_type != NULL) { ((struct _h_pgsql *)conn->connection)->list_type[((struct _h_pgsql *)conn->connection)->nb_type].pg_type = cur_type_oid; if (o_strcmp(cur_type_name, "bool") == 0) { ((struct _h_pgsql *)conn->connection)->list_type[((struct _h_pgsql *)conn->connection)->nb_type].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[((struct _h_pgsql *)conn->connection)->nb_type].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[((struct _h_pgsql *)conn->connection)->nb_type].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[((struct _h_pgsql *)conn->connection)->nb_type].h_type = HOEL_COL_TYPE_DATE; } else if (o_strcmp(cur_type_name, "bytea") == 0) { ((struct _h_pgsql *)conn->connection)->list_type[((struct _h_pgsql *)conn->connection)->nb_type].h_type = HOEL_COL_TYPE_BLOB; } else if (o_strcmp(cur_type_name, "bool") == 0) { ((struct _h_pgsql *)conn->connection)->list_type[((struct _h_pgsql *)conn->connection)->nb_type].h_type = HOEL_COL_TYPE_BOOL; } else { ((struct _h_pgsql *)conn->connection)->list_type[((struct _h_pgsql *)conn->connection)->nb_type].h_type = HOEL_COL_TYPE_TEXT; } ((struct _h_pgsql *)conn->connection)->nb_type++; } else { y_log_message(Y_LOG_LEVEL_ERROR, "Hoel - Error allocating resources for list_type"); } } else { y_log_message(Y_LOG_LEVEL_ERROR, "Hoel - Error converting pg_type.oid to integer"); } } } else { y_log_message(Y_LOG_LEVEL_ERROR, "Hoel - Error pg_type result"); PQfinish(((struct _h_pgsql *)conn->connection)->db_handle); free(conn->connection); free(conn); conn = NULL; } h_clean_result(&result_types); } else { y_log_message(Y_LOG_LEVEL_ERROR, "Hoel - Error getting pg_type"); PQfinish(((struct _h_pgsql *)conn->connection)->db_handle); free(conn->connection); free(conn); conn = NULL; } } } return conn; } /** * close a pgsql connection */ void h_close_pgsql(struct _h_connection * conn) { PQfinish(((struct _h_pgsql *)conn->connection)->db_handle); o_free(((struct _h_pgsql *)conn->connection)->list_type); ((struct _h_pgsql *)conn->connection)->list_type = NULL; ((struct _h_pgsql *)conn->connection)->nb_type = 0; } /** * escape a string * returned value must be free'd after use */ char * h_escape_string_pgsql(const struct _h_connection * conn, const char * unsafe) { return PQescapeLiteral(((struct _h_pgsql *)conn->connection)->db_handle, unsafe, strlen(unsafe)); } /** * 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) { 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; struct _h_data * data, * cur_row = NULL; 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); return H_ERROR_QUERY; } nfields = PQnfields(res); ntuples = PQntuples(res); if (result != NULL) { result->nb_rows = 0; result->nb_columns = nfields; result->data = NULL; for(i = 0; i < ntuples; i++) { cur_row = NULL; for(j = 0; 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(PQgetvalue(res, i, j), NULL, 10)); break; case HOEL_COL_TYPE_DOUBLE: data = h_new_data_double(strtod(PQgetvalue(res, i, j), NULL)); break; case HOEL_COL_TYPE_BLOB: data = h_new_data_blob(PQgetvalue(res, i, j), PQfsize(res, i)); break; case HOEL_COL_TYPE_BOOL: if (o_strcasecmp(PQgetvalue(res, i, j), "t") == 0) { data = h_new_data_int(1); } else if (o_strcasecmp(PQgetvalue(res, i, j), "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(PQgetvalue(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); return h_res; } } h_res = h_result_add_row(result, cur_row, i); if (h_res != H_OK) { PQclear(res); return h_res; } } } PQclear(res); return H_OK; } /** * 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; json_t * j_data; if (j_result == NULL) { 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"); return H_ERROR_MEMORY; } 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); return H_ERROR_QUERY; } nfields = PQnfields(res); ntuples = PQntuples(res); for(i = 0; 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); return H_ERROR_MEMORY; } for(j = 0; j < nfields; j++) { char * val = PQgetvalue(res, i, j); if (val == NULL || strlen(val) == 0) { 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(strtol(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), PQfsize(res, i))); 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); return H_OK; } /** * Return the id of the last inserted value * Assuming you use sequences for automatically generated ids */ int h_last_insert_id_pgsql(const struct _h_connection * conn) { PGresult *res; int int_res = 0; char * str_res, * endptr = NULL; 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); return int_res; } #else /** * Dummy functions when Hoel is not built with PostgreSQL */ struct _h_connection * h_connect_pgsql(char * 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) { y_log_message(Y_LOG_LEVEL_ERROR, "Hoel was not compiled with PostgreSQL backend"); } #endif hoel-1.3.1/src/hoel-simple-json.c000066400000000000000000000633771322747102600166070ustar00rootroot00000000000000/** * * Hoel database abstraction library * * hoel-simple-json.c: hoel simple Json query functions * * Copyright 2015-2016 Nicolas Mora * * This program is o_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" /** * Builds an insert query from a json object and a table name * Returned value must be o_free'd after use */ static char * h_get_insert_query_from_json_object(const struct _h_connection * conn, const json_t * data, const char * table) { char * insert_cols = NULL, * insert_data = NULL, * new_data = NULL, * to_return, * tmp, * escape; int i = 0; json_t * value, * raw; const char * key; json_object_foreach((json_t *)data, key, value) { switch (json_typeof(value)) { case JSON_STRING: escape = h_escape_string(conn, json_string_value(value)); if (escape == NULL) { y_log_message(Y_LOG_LEVEL_ERROR, "Hoel - Error escape"); new_data = NULL; } else { new_data = msprintf("'%s'", escape); o_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_DEBUG, "Error decoding value %s, inserting NULL value", tmp); o_free(tmp); new_data = o_strdup("NULL"); break; } if (new_data == NULL) { y_log_message(Y_LOG_LEVEL_ERROR, "Hoel - Error allocating memory for new_data"); return NULL; } if (i == 0) { insert_cols = msprintf("`%s`", key); if (insert_cols == NULL) { y_log_message(Y_LOG_LEVEL_DEBUG, "Hoel/h_get_insert_query_from_json_object - Error allocating insert_cols"); return NULL; } insert_data = new_data; i = 1; } else { tmp = msprintf("%s,%s", insert_data, new_data); if (tmp == NULL) { y_log_message(Y_LOG_LEVEL_DEBUG, "Hoel/h_get_insert_query_from_json_object - Error allocating tmp"); o_free(insert_data); o_free(new_data); return NULL; } o_free(insert_data); o_free(new_data); insert_data = tmp; tmp = msprintf("%s,`%s`", insert_cols, key); o_free(insert_cols); if (tmp == NULL) { y_log_message(Y_LOG_LEVEL_DEBUG, "Hoel/h_get_insert_query_from_json_object - Error allocating insert_cols"); o_free(insert_data); return NULL; } insert_cols = tmp; } } to_return = msprintf("INSERT INTO `%s` (%s) VALUES (%s)", table, insert_cols, insert_data); o_free(insert_cols); o_free(insert_data); if (to_return == NULL) { y_log_message(Y_LOG_LEVEL_ERROR, "Hoel - Error allocating memory for h_get_insert_query_from_json_object"); } 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 o_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; json_t * value, * ope, * val, * j_element; char * where_clause = NULL, * dump = NULL, * escape = NULL, * tmp, * clause = NULL, * dump2 = NULL; int i = 0; size_t index; 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); o_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); o_free(dump); o_free(dump2); o_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)) { o_free(clause); o_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(conn, json_string_value(j_element)); if (escape == NULL) { y_log_message(Y_LOG_LEVEL_ERROR, "Hoel - Error escape"); o_free(clause); o_free(where_clause); return NULL; } dump = msprintf("'%s'", escape); o_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); o_free(clause); clause = tmp; } o_free(dump); } } tmp = msprintf("%s)", clause); o_free(clause); clause = tmp; } else { o_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(conn, json_string_value(val)); if (escape == NULL) { y_log_message(Y_LOG_LEVEL_ERROR, "Hoel - Error escape"); o_free(where_clause); return NULL; } clause = msprintf("%s %s '%s'", key, json_string_value(ope), escape); o_free(escape); } } if (clause == NULL) { y_log_message(Y_LOG_LEVEL_ERROR, "Hoel - Error allocating memory for clause"); o_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(conn, json_string_value(value)); if (escape == NULL) { y_log_message(Y_LOG_LEVEL_ERROR, "Hoel - Error escape"); o_free(where_clause); return NULL; } clause = msprintf("%s='%s'", key, escape); o_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"); o_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"); o_free(clause); o_free(where_clause); return NULL; } o_free(clause); i = 1; } else { tmp = msprintf("%s AND %s", where_clause, clause); o_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"); o_free(clause); o_free(where_clause); return NULL; } o_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 o_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; json_t * value, * 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); o_free(tmp); o_free(where_clause); return NULL; } else { if (json_is_string(value)) { tmp = h_escape_string(conn, json_string_value(value)); escape = msprintf("'%s'", tmp); o_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); } o_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; } o_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 o_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; json_int_t limit, offset; char * query, * columns = NULL, * where_clause = NULL, * tmp, * str_where_limit, * str_order_by; const char * col; size_t index; 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"))) { 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"); 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"); o_free(where_clause); o_free(columns); return H_ERROR_MEMORY; } } else { y_log_message(Y_LOG_LEVEL_DEBUG, "Hoel/h_select Error column not string"); o_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"); o_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"); o_free(where_clause); o_free(columns); return H_ERROR_MEMORY; } o_free(columns); columns = tmp; } } } else { y_log_message(Y_LOG_LEVEL_DEBUG, "Hoel/h_select Error cols not array"); o_free(where_clause); return H_ERROR_PARAMS; } if (columns == NULL) { y_log_message(Y_LOG_LEVEL_ERROR, "Hoel - Error allocating memory for columns"); o_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); } if (str_where_limit == NULL) { y_log_message(Y_LOG_LEVEL_ERROR, "Hoel - Error allocating memory for str_where_limit"); o_free(columns); o_free(where_clause); return H_ERROR_MEMORY; } } else { str_where_limit = o_strdup(""); } if (order_by != NULL && json_is_string(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"); o_free(columns); o_free(where_clause); o_free(str_where_limit); return H_ERROR_MEMORY; } if (str_order_by == NULL) { y_log_message(Y_LOG_LEVEL_ERROR, "Hoel - Error allocating memory for str_order_by"); o_free(columns); o_free(where_clause); o_free(str_where_limit); o_free(str_order_by); return H_ERROR_MEMORY; } query = msprintf("SELECT %s FROM `%s` WHERE %s %s %s", columns, table, where_clause, str_order_by, str_where_limit); if (query == NULL) { y_log_message(Y_LOG_LEVEL_DEBUG, "Hoel/h_select Error allocating query"); o_free(columns); o_free(where_clause); o_free(str_where_limit); o_free(str_order_by); return H_ERROR_MEMORY; } else { if (generated_query != NULL) { *generated_query = o_strdup(query); } res = h_query_select_json(conn, query, j_result); o_free(columns); o_free(where_clause); o_free(str_where_limit); o_free(str_order_by); o_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 o_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; size_t index; json_t * values, * j_row; 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, (json_t *)values, table); if (query != NULL) { if (generated_query != NULL) { *generated_query = o_strdup(query); } res = h_query_insert(conn, query); o_free(query); return res; } else { y_log_message(Y_LOG_LEVEL_DEBUG, "Hoel/h_insert - Error allocating query"); return H_ERROR_MEMORY; } break; case JSON_ARRAY: json_array_foreach(values, index, j_row) { query = h_get_insert_query_from_json_object(conn, j_row, table); if (query != NULL) { if (generated_query != NULL && index == 0) { /* Export just the first query */ *generated_query = o_strdup(query); } res = h_query_insert(conn, query); o_free(query); if (res != H_OK) { y_log_message(Y_LOG_LEVEL_DEBUG, "Hoel/h_insert - Error executing query"); return H_ERROR_QUERY; } } else { y_log_message(Y_LOG_LEVEL_DEBUG, "Hoel/h_insert - Error allocating query"); return H_ERROR_MEMORY; } } return H_OK; 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) { 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) { 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) { 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 o_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); o_free(where_clause); } else { query = msprintf("UPDATE `%s` SET %s", table, set_clause); } o_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); o_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 o_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); o_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); o_free(query); return res; } hoel-1.3.1/src/hoel-sqlite.c000066400000000000000000000237201322747102600156340ustar00rootroot00000000000000/** * * Hoel database abstraction library * * hoel-sqlite.c: Sqlite3 specific functions * * Copyright 2015-2016 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; if (db_path != NULL) { conn = 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 = malloc(sizeof(struct _h_sqlite)); if (conn->connection == NULL) { y_log_message(Y_LOG_LEVEL_ERROR, "h_connect_sqlite - Error allocating resources"); free(conn); return NULL; } if (sqlite3_open_v2(db_path, &((struct _h_sqlite *)conn->connection)->db_handle, SQLITE_OPEN_READWRITE, 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); 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; } /** * Return the id of the last inserted value */ 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, 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 = 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_int(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), sqlite3_column_bytes(stmt, col)); break; case SQLITE3_TEXT: data = h_new_data_text((char*)sqlite3_column_text(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_exec_query_sqlite * Execute a query on a sqlite connection * 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 * return H_OK on success */ int h_exec_query_sqlite(const struct _h_connection * conn, const char * query) { return ((sqlite3_exec(((struct _h_sqlite *)conn->connection)->db_handle, query, NULL, NULL, NULL) == SQLITE_OK)?H_OK:H_ERROR_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, 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_int(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), 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) { y_log_message(Y_LOG_LEVEL_ERROR, "Hoel was not compiled with SQLite backend"); return NULL; } void h_close_sqlite(struct _h_connection * conn) { y_log_message(Y_LOG_LEVEL_ERROR, "Hoel was not compiled with SQLite backend"); } #endif hoel-1.3.1/src/hoel.c000066400000000000000000000444031322747102600143360ustar00rootroot00000000000000/** * * Hoel database abstraction library * * hoel.c: main functions * * Copyright 2015-2016 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 */ #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 */ #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_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) { if (conn != NULL && conn->connection != NULL && query != NULL) { if (0) { /* Not happening */ #ifdef _HOEL_SQLITE } else if (conn->type == HOEL_DB_TYPE_SQLITE) { if (options & H_OPTION_EXEC) { return h_exec_query_sqlite(conn, query); } else { return h_select_query_sqlite(conn, query, result); } #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 */ #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, (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(strlen(((struct _h_type_text *)data->t_data)->value)+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"); o_free(tmp[cols].t_data); return H_ERROR_MEMORY; } strncpy(((struct _h_type_text *)tmp[cols].t_data)->value, ((struct _h_type_text *)data->t_data)->value, (strlen(((struct _h_type_text *)data->t_data)->value)+1)); 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"); o_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, (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) { 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) { 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) { 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) { 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; } } o_free(result->data[row]); } o_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) { o_free(((struct _h_type_text *)data->t_data)->value); } else if (data->type == HOEL_COL_TYPE_BLOB) { o_free(((struct _h_type_blob *)data->t_data)->value); } if (data->t_data != NULL) { o_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); o_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 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"); o_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"); o_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) { 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"); o_free(data); return NULL; } data->type = HOEL_COL_TYPE_TEXT; ((struct _h_type_text *)data->t_data)->value = o_malloc(strlen(value)+sizeof(char)); 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"); o_free(data); return NULL; } else { strncpy(((struct _h_type_text *)data->t_data)->value, value, (strlen(value)+sizeof(char))); } } 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 = 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"); o_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"); o_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"); } 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"); o_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) { o_free(conn->connection); o_free(conn); return H_OK; } else { return H_ERROR_PARAMS; } } hoel-1.3.1/src/hoel.h000066400000000000000000000352401322747102600143420ustar00rootroot00000000000000/** * * Hoel database abstraction library * * hoel.h: structures and functions declarations * * Copyright 2015-2016 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__ #define HOEL_VERSION 1.3.1 #include #define __USE_XOPEN #include #include /** Angharad libraries **/ #include #include #ifdef _HOEL_SQLITE #define HOEL_DB_TYPE_SQLITE 0 #endif #ifdef _HOEL_MARIADB #define HOEL_DB_TYPE_MARIADB 1 #endif #ifdef _HOEL_PGSQL #define HOEL_DB_TYPE_PGSQL 2 #endif #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 */ /** * handle container */ struct _h_connection { int type; void * connection; }; /** * 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; }; /** * 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; }; /** * Close a database connection * return H_OK on success */ int h_close_db(struct _h_connection * conn); /** * free data allocated by hoel functions */ void h_free(void * data); /** * 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); /** * 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); /** * 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_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); /** * 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_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); /** * 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); /** * 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); /** * 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 free'd after use * The query execution result is returned by the function * * A j_query has the following form * { * "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 * "order_by": "col_name [asc|desc]" // String, available for h_select, specify the order by clause, optional * "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 * Duplicate the generated query in generated_query if specified, must be 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 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 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 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_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); /** * 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); /** * h_clean_connection * free memory allocated by the struct _h_connection * return H_OK on success */ int h_clean_connection(struct _h_connection * conn); #ifdef _HOEL_SQLITE /** * 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); /** * close a sqlite3 connection */ void h_close_sqlite(struct _h_connection * conn); /** * escape a string * returned value must be free'd after use */ char * h_escape_string_sqlite(const struct _h_connection * conn, const char * unsafe); /** * Return the id of the last inserted value */ int h_last_insert_id_sqlite(const struct _h_connection * conn); /** * 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); /** * h_exec_query_sqlite * Execute a query on a sqlite connection * 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 * return H_OK on success */ int h_exec_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 * 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); #endif #ifdef _HOEL_MARIADB /** * 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); /** * close connection to database */ void h_close_mariadb(struct _h_connection * conn); /** * escape a string * returned value must be free'd after use */ char * h_escape_string_mariadb(const struct _h_connection * conn, const char * unsafe); /** * Return the id of the last inserted value */ int h_last_insert_id_mariadb(const struct _h_connection * conn); /** * 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 * result); /** * 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); /** * 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); #endif #ifdef _HOEL_PGSQL /** * 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); /** * 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); /** * 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); /** * close a pgsql connection */ void h_close_pgsql(struct _h_connection * conn); /** * escape a string * returned value must be free'd after use */ char * h_escape_string_pgsql(const struct _h_connection * conn, const char * unsafe); /** * Return the id of the last inserted value * Assuming you use sequences for automatically generated ids */ int h_last_insert_id_pgsql(const struct _h_connection * conn); #endif #endif /* __HOEL_H__ */ hoel-1.3.1/test/000077500000000000000000000000001322747102600134265ustar00rootroot00000000000000hoel-1.3.1/test/Makefile000066400000000000000000000021461322747102600150710ustar00rootroot00000000000000# # Hoel library # # Makefile used to build the tests # # Copyright 2017 Nicolas Mora # # This program is free software; you can redistribute it and/or # modify it under the terms of the GNU GENERAL PUBLIC LICENSE # License as published by the Free Software Foundation; # version 3 of the License. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU GENERAL PUBLIC LICENSE for more details. # # You should have received a copy of the GNU General Public # License along with this program. If not, see . # CC=gcc CFLAGS=-Wall -D_REENTRANT -DDEBUG -g -O0 HOEL_LOCATION=../src LIBS=-lc -lyder -lhoel -ljansson -lcheck -lpthread -lm -lrt -lsubunit -L$(HOEL_LOCATION) all: test clean: rm -f *.o core valgrind.txt libhoel.so: cd $(HOEL_LOCATION) && $(MAKE) debug core: core.c $(CC) $(CFLAGS) core.c -o core $(LIBS) test_core: libhoel.so core -LD_LIBRARY_PATH=$(HOEL_LOCATION):${LD_LIBRARY_PATH} ./core test: test_core hoel-1.3.1/test/core.c000066400000000000000000000615371322747102600145360ustar00rootroot00000000000000/* 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 #define _HOEL_SQLITE #include "../src/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`, `string_col`, `date_col` FROM `test_table` WHERE `integer_col` = 1" #define SELECT_DATA_2 "SELECT `integer_col`, `string_col`, `date_col` FROM `test_table` WHERE `integer_col` = 2" #define SELECT_DATA_ERROR "SELECT `integer_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`, `string_col`, `date_col`) VALUES (1, 'value1', date('now'))" #define INSERT_DATA_2 "INSERT INTO `test_table` (`integer_col`, `string_col`, `date_col`) VALUES (2, 'value2', strftime('%s','2016-06-22 00:52:56'))" #define INSERT_DATA_ERROR "INSERT INTO `test_table` (`integer_col`, `string_col`, `date_col`) VALUES ('error', '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' WHERE `integer_col` = 1" const char * db_path; void print_result(struct _h_result result) { int col, row, i; printf("rows: %d, col: %d\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(db_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(db_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_insert) { struct _h_connection * conn; struct _h_result result; struct _h_data * last_id; conn = h_connect_sqlite(db_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, 3); 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_TEXT); ck_assert_str_eq(((struct _h_type_text *)result.data[0][1].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, 3); 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(db_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, 3); ck_assert_int_eq(((struct _h_type_int *)result.data[0][0].t_data)->value, 1); ck_assert_str_eq(((struct _h_type_text *)result.data[0][1].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, 3); ck_assert_int_eq(((struct _h_type_int *)result.data[0][0].t_data)->value, 1); ck_assert_str_eq(((struct _h_type_text *)result.data[0][1].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(db_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, 3); 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_TEXT); ck_assert_str_eq(((struct _h_type_text *)result.data[0][1].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, 3); 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_TEXT); ck_assert_str_eq(((struct _h_type_text *)result.data[0][1].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}}}", "table", "test_table", "values", "integer_col", 1, "string_col", "value1", "date_col", "raw", "date('now')"), * j_result = NULL; conn = h_connect_sqlite(db_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); json_decref(j_result); ck_assert_int_eq(strlen(str_query), strlen("INSERT INTO `test_table` (`integer_col`,`string_col`,`date_col`) VALUES (1,'value1',date('now'))")); 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}}}", "table", "test_table", "values", "integer_col", 1, "string_col", "value1", "date_col", "raw", "date('now')"), * j_result = NULL; conn = h_connect_sqlite(db_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); json_decref(j_result); j_query = json_pack("{sss{ss}s{si}}", "table", "test_table", "set", "string_col", "new value1", "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(strlen(str_query), strlen("UPDATE `test_table` SET `string_col`='new value1' 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); 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}}}", "table", "test_table", "values", "integer_col", 1, "string_col", "value1", "date_col", "raw", "date('now')"), * j_result = NULL; conn = h_connect_sqlite(db_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}}}", "table", "test_table", "values", "integer_col", 2, "string_col", "value2", "date_col", "raw", "strftime('%s','2016-06-22 00:52:56')"); 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(strlen(str_query), 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); 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); ck_assert_int_eq(json_array_size(j_result), 0); 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}}}", "table", "test_table", "values", "integer_col", 1, "string_col", "value1", "date_col", "raw", "date('now')"), * j_result = NULL; conn = h_connect_sqlite(db_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}}}", "table", "test_table", "values", "integer_col", 2, "string_col", "value2", "date_col", "raw", "strftime('%s','2016-06-22 00:52:56')"); 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(strlen(str_query), 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); 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(strlen(str_query), 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); 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(strlen(str_query), 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); 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(strlen(str_query), 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(strlen(str_query), 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); 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(strlen(str_query), 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(strlen(str_query), 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); 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(strlen(str_query), 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(strlen(str_query), 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); ck_assert_int_eq(json_array_size(j_result), 0); 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 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_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(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"); if (argc > 1) { db_path = argv[1]; } else { db_path = DEFAULT_BD_PATH; } 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.3.1/test/test.sql000066400000000000000000000002661322747102600151320ustar00rootroot00000000000000DROP TABLE IF EXISTS `test_table`; CREATE TABLE `test_table` ( `id_col` INTEGER PRIMARY KEY AUTOINCREMENT, `integer_col` INTEGER, `string_col` TEXT, `date_col` TIMESTAMP );