pax_global_header00006660000000000000000000000064141735514070014521gustar00rootroot0000000000000052 comment=41fb04ffd69bcd1f05d88c10b2e8e8e1d32d2388 ocsipersist-1.1.0/000077500000000000000000000000001417355140700140675ustar00rootroot00000000000000ocsipersist-1.1.0/.github/000077500000000000000000000000001417355140700154275ustar00rootroot00000000000000ocsipersist-1.1.0/.github/workflows/000077500000000000000000000000001417355140700174645ustar00rootroot00000000000000ocsipersist-1.1.0/.github/workflows/deploy-doc.yml000066400000000000000000000012021417355140700222410ustar00rootroot00000000000000name: Deploy odoc on: push: branches: - master jobs: deploy-doc: runs-on: ubuntu-latest steps: - name: Install system packages run: sudo apt-get install -y libgdbm-compat-dev - name: Checkout code uses: actions/checkout@v2 - name: Use OCaml 4.12.x uses: ocaml/setup-ocaml@v2 with: ocaml-compiler: 4.12.x opam-pin: false opam-depext: false dune-cache: true - name: Install libgdbm-dev run: sudo apt-get install libgdbm-dev - name: Deploy odoc to GitHub Pages uses: ocaml/setup-ocaml/deploy-doc@v2 ocsipersist-1.1.0/.gitignore000066400000000000000000000000101417355140700160460ustar00rootroot00000000000000_build/ ocsipersist-1.1.0/.ocamlformat000066400000000000000000000015551417355140700164020ustar00rootroot00000000000000version=0.19.0 break-cases = fit break-collection-expressions = fit-or-vertical break-fun-decl = wrap break-fun-sig = wrap break-infix = wrap break-infix-before-func = false break-sequences = false break-separators = before break-string-literals = never break-struct = force cases-matching-exp-indent = compact doc-comments = after-when-possible dock-collection-brackets = false indicate-multiline-delimiters = no infix-precedence = indent let-and = compact let-binding-spacing = compact module-item-spacing = compact parens-tuple = multi-line-only parens-tuple-patterns = multi-line-only sequence-style = terminator sequence-blank-line = compact single-case = compact type-decl = compact if-then-else = keyword-first field-space = loose space-around-arrays = false space-around-records = false space-around-lists = false space-around-variants = false ocp-indent-compat = true ocsipersist-1.1.0/LICENSE000066400000000000000000000654331417355140700151070ustar00rootroot00000000000000This program is released under the LGPL version 2.1 (see the text below) with the additional exemption that compiling, linking, and/or using OpenSSL is allowed. As a special exception to the GNU Lesser General Public License, you may also link, statically or dynamically, a "work that uses the Library" with a publicly distributed version of the Library to produce an executable file containing portions of the Library, and distribute that executable file under terms of your choice, without any of the additional requirements listed in clause 6 of the GNU Lesser General Public License. By "a publicly distributed version of the Library", we mean either the unmodified Library, or a modified version of the Library that is distributed under the conditions defined in clause 3 of the GNU Lesser General Public License. This exception does not however invalidate any other reasons why the executable file might be covered by the GNU Lesser General Public License. GNU LESSER GENERAL PUBLIC LICENSE Version 2.1, February 1999 Copyright (C) 1991, 1999 Free Software Foundation, Inc. 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA Everyone is permitted to copy and distribute verbatim copies of this license document, but changing it is not allowed. [This is the first released version of the Lesser GPL. It also counts as the successor of the GNU Library Public License, version 2, hence the version number 2.1.] Preamble The licenses for most software are designed to take away your freedom to share and change it. By contrast, the GNU General Public Licenses are intended to guarantee your freedom to share and change free software--to make sure the software is free for all its users. This license, the Lesser General Public License, applies to some specially designated software packages--typically libraries--of the Free Software Foundation and other authors who decide to use it. You can use it too, but we suggest you first think carefully about whether this license or the ordinary General Public License is the better strategy to use in any particular case, based on the explanations below. When we speak of free software, we are referring to freedom of use, not price. Our General Public Licenses are designed to make sure that you have the freedom to distribute copies of free software (and charge for this service if you wish); that you receive source code or can get it if you want it; that you can change the software and use pieces of it in new free programs; and that you are informed that you can do these things. To protect your rights, we need to make restrictions that forbid distributors to deny you these rights or to ask you to surrender these rights. These restrictions translate to certain responsibilities for you if you distribute copies of the library or if you modify it. For example, if you distribute copies of the library, whether gratis or for a fee, you must give the recipients all the rights that we gave you. You must make sure that they, too, receive or can get the source code. If you link other code with the library, you must provide complete object files to the recipients, so that they can relink them with the library after making changes to the library and recompiling it. And you must show them these terms so they know their rights. We protect your rights with a two-step method: (1) we copyright the library, and (2) we offer you this license, which gives you legal permission to copy, distribute and/or modify the library. To protect each distributor, we want to make it very clear that there is no warranty for the free library. Also, if the library is modified by someone else and passed on, the recipients should know that what they have is not the original version, so that the original author's reputation will not be affected by problems that might be introduced by others. Finally, software patents pose a constant threat to the existence of any free program. We wish to make sure that a company cannot effectively restrict the users of a free program by obtaining a restrictive license from a patent holder. Therefore, we insist that any patent license obtained for a version of the library must be consistent with the full freedom of use specified in this license. Most GNU software, including some libraries, is covered by the ordinary GNU General Public License. This license, the GNU Lesser General Public License, applies to certain designated libraries, and is quite different from the ordinary General Public License. We use this license for certain libraries in order to permit linking those libraries into non-free programs. When a program is linked with a library, whether statically or using a shared library, the combination of the two is legally speaking a combined work, a derivative of the original library. The ordinary General Public License therefore permits such linking only if the entire combination fits its criteria of freedom. The Lesser General Public License permits more lax criteria for linking other code with the library. We call this license the "Lesser" General Public License because it does Less to protect the user's freedom than the ordinary General Public License. It also provides other free software developers Less of an advantage over competing non-free programs. These disadvantages are the reason we use the ordinary General Public License for many libraries. However, the Lesser license provides advantages in certain special circumstances. For example, on rare occasions, there may be a special need to encourage the widest possible use of a certain library, so that it becomes a de-facto standard. To achieve this, non-free programs must be allowed to use the library. A more frequent case is that a free library does the same job as widely used non-free libraries. In this case, there is little to gain by limiting the free library to free software only, so we use the Lesser General Public License. In other cases, permission to use a particular library in non-free programs enables a greater number of people to use a large body of free software. For example, permission to use the GNU C Library in non-free programs enables many more people to use the whole GNU operating system, as well as its variant, the GNU/Linux operating system. Although the Lesser General Public License is Less protective of the users' freedom, it does ensure that the user of a program that is linked with the Library has the freedom and the wherewithal to run that program using a modified version of the Library. The precise terms and conditions for copying, distribution and modification follow. Pay close attention to the difference between a "work based on the library" and a "work that uses the library". The former contains code derived from the library, whereas the latter must be combined with the library in order to run. GNU LESSER GENERAL PUBLIC LICENSE TERMS AND CONDITIONS FOR COPYING, DISTRIBUTION AND MODIFICATION 0. This License Agreement applies to any software library or other program which contains a notice placed by the copyright holder or other authorized party saying it may be distributed under the terms of this Lesser General Public License (also called "this License"). Each licensee is addressed as "you". A "library" means a collection of software functions and/or data prepared so as to be conveniently linked with application programs (which use some of those functions and data) to form executables. The "Library", below, refers to any such software library or work which has been distributed under these terms. A "work based on the Library" means either the Library or any derivative work under copyright law: that is to say, a work containing the Library or a portion of it, either verbatim or with modifications and/or translated straightforwardly into another language. (Hereinafter, translation is included without limitation in the term "modification".) "Source code" for a work means the preferred form of the work for making modifications to it. For a library, complete source code means all the source code for all modules it contains, plus any associated interface definition files, plus the scripts used to control compilation and installation of the library. Activities other than copying, distribution and modification are not covered by this License; they are outside its scope. The act of running a program using the Library is not restricted, and output from such a program is covered only if its contents constitute a work based on the Library (independent of the use of the Library in a tool for writing it). Whether that is true depends on what the Library does and what the program that uses the Library does. 1. You may copy and distribute verbatim copies of the Library's complete source code as you receive it, in any medium, provided that you conspicuously and appropriately publish on each copy an appropriate copyright notice and disclaimer of warranty; keep intact all the notices that refer to this License and to the absence of any warranty; and distribute a copy of this License along with the Library. You may charge a fee for the physical act of transferring a copy, and you may at your option offer warranty protection in exchange for a fee. 2. You may modify your copy or copies of the Library or any portion of it, thus forming a work based on the Library, and copy and distribute such modifications or work under the terms of Section 1 above, provided that you also meet all of these conditions: a) The modified work must itself be a software library. b) You must cause the files modified to carry prominent notices stating that you changed the files and the date of any change. c) You must cause the whole of the work to be licensed at no charge to all third parties under the terms of this License. d) If a facility in the modified Library refers to a function or a table of data to be supplied by an application program that uses the facility, other than as an argument passed when the facility is invoked, then you must make a good faith effort to ensure that, in the event an application does not supply such function or table, the facility still operates, and performs whatever part of its purpose remains meaningful. (For example, a function in a library to compute square roots has a purpose that is entirely well-defined independent of the application. Therefore, Subsection 2d requires that any application-supplied function or table used by this function must be optional: if the application does not supply it, the square root function must still compute square roots.) These requirements apply to the modified work as a whole. If identifiable sections of that work are not derived from the Library, and can be reasonably considered independent and separate works in themselves, then this License, and its terms, do not apply to those sections when you distribute them as separate works. But when you distribute the same sections as part of a whole which is a work based on the Library, the distribution of the whole must be on the terms of this License, whose permissions for other licensees extend to the entire whole, and thus to each and every part regardless of who wrote it. Thus, it is not the intent of this section to claim rights or contest your rights to work written entirely by you; rather, the intent is to exercise the right to control the distribution of derivative or collective works based on the Library. In addition, mere aggregation of another work not based on the Library with the Library (or with a work based on the Library) on a volume of a storage or distribution medium does not bring the other work under the scope of this License. 3. You may opt to apply the terms of the ordinary GNU General Public License instead of this License to a given copy of the Library. To do this, you must alter all the notices that refer to this License, so that they refer to the ordinary GNU General Public License, version 2, instead of to this License. (If a newer version than version 2 of the ordinary GNU General Public License has appeared, then you can specify that version instead if you wish.) Do not make any other change in these notices. Once this change is made in a given copy, it is irreversible for that copy, so the ordinary GNU General Public License applies to all subsequent copies and derivative works made from that copy. This option is useful when you wish to copy part of the code of the Library into a program that is not a library. 4. You may copy and distribute the Library (or a portion or derivative of it, under Section 2) in object code or executable form under the terms of Sections 1 and 2 above provided that you accompany it with the complete corresponding machine-readable source code, which must be distributed under the terms of Sections 1 and 2 above on a medium customarily used for software interchange. If distribution of object code is made by offering access to copy from a designated place, then offering equivalent access to copy the source code from the same place satisfies the requirement to distribute the source code, even though third parties are not compelled to copy the source along with the object code. 5. A program that contains no derivative of any portion of the Library, but is designed to work with the Library by being compiled or linked with it, is called a "work that uses the Library". Such a work, in isolation, is not a derivative work of the Library, and therefore falls outside the scope of this License. However, linking a "work that uses the Library" with the Library creates an executable that is a derivative of the Library (because it contains portions of the Library), rather than a "work that uses the library". The executable is therefore covered by this License. Section 6 states terms for distribution of such executables. When a "work that uses the Library" uses material from a header file that is part of the Library, the object code for the work may be a derivative work of the Library even though the source code is not. Whether this is true is especially significant if the work can be linked without the Library, or if the work is itself a library. The threshold for this to be true is not precisely defined by law. If such an object file uses only numerical parameters, data structure layouts and accessors, and small macros and small inline functions (ten lines or less in length), then the use of the object file is unrestricted, regardless of whether it is legally a derivative work. (Executables containing this object code plus portions of the Library will still fall under Section 6.) Otherwise, if the work is a derivative of the Library, you may distribute the object code for the work under the terms of Section 6. Any executables containing that work also fall under Section 6, whether or not they are linked directly with the Library itself. 6. As an exception to the Sections above, you may also combine or link a "work that uses the Library" with the Library to produce a work containing portions of the Library, and distribute that work under terms of your choice, provided that the terms permit modification of the work for the customer's own use and reverse engineering for debugging such modifications. You must give prominent notice with each copy of the work that the Library is used in it and that the Library and its use are covered by this License. You must supply a copy of this License. If the work during execution displays copyright notices, you must include the copyright notice for the Library among them, as well as a reference directing the user to the copy of this License. Also, you must do one of these things: a) Accompany the work with the complete corresponding machine-readable source code for the Library including whatever changes were used in the work (which must be distributed under Sections 1 and 2 above); and, if the work is an executable linked with the Library, with the complete machine-readable "work that uses the Library", as object code and/or source code, so that the user can modify the Library and then relink to produce a modified executable containing the modified Library. (It is understood that the user who changes the contents of definitions files in the Library will not necessarily be able to recompile the application to use the modified definitions.) b) Use a suitable shared library mechanism for linking with the Library. A suitable mechanism is one that (1) uses at run time a copy of the library already present on the user's computer system, rather than copying library functions into the executable, and (2) will operate properly with a modified version of the library, if the user installs one, as long as the modified version is interface-compatible with the version that the work was made with. c) Accompany the work with a written offer, valid for at least three years, to give the same user the materials specified in Subsection 6a, above, for a charge no more than the cost of performing this distribution. d) If distribution of the work is made by offering access to copy from a designated place, offer equivalent access to copy the above specified materials from the same place. e) Verify that the user has already received a copy of these materials or that you have already sent this user a copy. For an executable, the required form of the "work that uses the Library" must include any data and utility programs needed for reproducing the executable from it. However, as a special exception, the materials to be distributed need not include anything that is normally distributed (in either source or binary form) with the major components (compiler, kernel, and so on) of the operating system on which the executable runs, unless that component itself accompanies the executable. It may happen that this requirement contradicts the license restrictions of other proprietary libraries that do not normally accompany the operating system. Such a contradiction means you cannot use both them and the Library together in an executable that you distribute. 7. You may place library facilities that are a work based on the Library side-by-side in a single library together with other library facilities not covered by this License, and distribute such a combined library, provided that the separate distribution of the work based on the Library and of the other library facilities is otherwise permitted, and provided that you do these two things: a) Accompany the combined library with a copy of the same work based on the Library, uncombined with any other library facilities. This must be distributed under the terms of the Sections above. b) Give prominent notice with the combined library of the fact that part of it is a work based on the Library, and explaining where to find the accompanying uncombined form of the same work. 8. You may not copy, modify, sublicense, link with, or distribute the Library except as expressly provided under this License. Any attempt otherwise to copy, modify, sublicense, link with, or distribute the Library is void, and will automatically terminate your rights under this License. However, parties who have received copies, or rights, from you under this License will not have their licenses terminated so long as such parties remain in full compliance. 9. You are not required to accept this License, since you have not signed it. However, nothing else grants you permission to modify or distribute the Library or its derivative works. These actions are prohibited by law if you do not accept this License. Therefore, by modifying or distributing the Library (or any work based on the Library), you indicate your acceptance of this License to do so, and all its terms and conditions for copying, distributing or modifying the Library or works based on it. 10. Each time you redistribute the Library (or any work based on the Library), the recipient automatically receives a license from the original licensor to copy, distribute, link with or modify the Library subject to these terms and conditions. You may not impose any further restrictions on the recipients' exercise of the rights granted herein. You are not responsible for enforcing compliance by third parties with this License. 11. If, as a consequence of a court judgment or allegation of patent infringement or for any other reason (not limited to patent issues), conditions are imposed on you (whether by court order, agreement or otherwise) that contradict the conditions of this License, they do not excuse you from the conditions of this License. If you cannot distribute so as to satisfy simultaneously your obligations under this License and any other pertinent obligations, then as a consequence you may not distribute the Library at all. For example, if a patent license would not permit royalty-free redistribution of the Library by all those who receive copies directly or indirectly through you, then the only way you could satisfy both it and this License would be to refrain entirely from distribution of the Library. If any portion of this section is held invalid or unenforceable under any particular circumstance, the balance of the section is intended to apply, and the section as a whole is intended to apply in other circumstances. It is not the purpose of this section to induce you to infringe any patents or other property right claims or to contest validity of any such claims; this section has the sole purpose of protecting the integrity of the free software distribution system which is implemented by public license practices. Many people have made generous contributions to the wide range of software distributed through that system in reliance on consistent application of that system; it is up to the author/donor to decide if he or she is willing to distribute software through any other system and a licensee cannot impose that choice. This section is intended to make thoroughly clear what is believed to be a consequence of the rest of this License. 12. If the distribution and/or use of the Library is restricted in certain countries either by patents or by copyrighted interfaces, the original copyright holder who places the Library under this License may add an explicit geographical distribution limitation excluding those countries, so that distribution is permitted only in or among countries not thus excluded. In such case, this License incorporates the limitation as if written in the body of this License. 13. The Free Software Foundation may publish revised and/or new versions of the Lesser General Public License from time to time. Such new versions will be similar in spirit to the present version, but may differ in detail to address new problems or concerns. Each version is given a distinguishing version number. If the Library specifies a version number of this License which applies to it and "any later version", you have the option of following the terms and conditions either of that version or of any later version published by the Free Software Foundation. If the Library does not specify a license version number, you may choose any version ever published by the Free Software Foundation. 14. If you wish to incorporate parts of the Library into other free programs whose distribution conditions are incompatible with these, write to the author to ask for permission. For software which is copyrighted by the Free Software Foundation, write to the Free Software Foundation; we sometimes make exceptions for this. Our decision will be guided by the two goals of preserving the free status of all derivatives of our free software and of promoting the sharing and reuse of software generally. NO WARRANTY 15. BECAUSE THE LIBRARY IS LICENSED FREE OF CHARGE, THERE IS NO WARRANTY FOR THE LIBRARY, TO THE EXTENT PERMITTED BY APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT HOLDERS AND/OR OTHER PARTIES PROVIDE THE LIBRARY "AS IS" WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE LIBRARY IS WITH YOU. SHOULD THE LIBRARY PROVE DEFECTIVE, YOU ASSUME THE COST OF ALL NECESSARY SERVICING, REPAIR OR CORRECTION. 16. IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MAY MODIFY AND/OR REDISTRIBUTE THE LIBRARY AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE USE OR INABILITY TO USE THE LIBRARY (INCLUDING BUT NOT LIMITED TO LOSS OF DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD PARTIES OR A FAILURE OF THE LIBRARY TO OPERATE WITH ANY OTHER SOFTWARE), EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGES. END OF TERMS AND CONDITIONS How to Apply These Terms to Your New Libraries If you develop a new library, and you want it to be of the greatest possible use to the public, we recommend making it free software that everyone can redistribute and change. You can do so by permitting redistribution under these terms (or, alternatively, under the terms of the ordinary General Public License). To apply these terms, attach the following notices to the library. It is safest to attach them to the start of each source file to most effectively convey the exclusion of warranty; and each file should have at least the "copyright" line and a pointer to where the full notice is found. Copyright (C) This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this library; if not, write to the Free Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA Also add information on how to contact you by electronic and paper mail. You should also get your employer (if you work as a programmer) or your school, if any, to sign a "copyright disclaimer" for the library, if necessary. Here is a sample; alter the names: Yoyodyne, Inc., hereby disclaims all copyright interest in the library `Frob' (a library for tweaking knobs) written by James Random Hacker. , 1 April 1990 Ty Coon, President of Vice That's all there is to it! ocsipersist-1.1.0/README.md000066400000000000000000000007431417355140700153520ustar00rootroot00000000000000Ocsipersist =========== Description ----------- Ocsipersist is a collection of libraries defining a unified frontend for a number of key/value storage implementations. Ocsipersist is used pervasively in Eliom/Ocsigen to handle sessions and references. It can be used as an extension for ocsigenserver or as a library. Implementations of the following backends currently exist: DBM, PostgreSQL, SQLite. API Reference ------------- https://ocsigen.github.io/ocsipersist/index.html ocsipersist-1.1.0/dune-project000066400000000000000000000000431417355140700164060ustar00rootroot00000000000000(lang dune 2.9) (name ocsipersist) ocsipersist-1.1.0/ocsipersist-dbm.opam000066400000000000000000000017141417355140700200570ustar00rootroot00000000000000opam-version: "2.0" name: "ocsipersist-dbm" version: "1.1.0" authors: "The Ocsigen team " maintainer: "Jan Rochel " license: "LGPL-2.1-only with OCaml-LGPL-linking-exception" synopsis: "Persistent key/value storage (for Ocsigen) using DBM" description: "This library provides a DBM backend for the unified key/value storage frontend as defined in the ocsipersist package. Ocsipersist is used pervasively in Eliom/Ocsigen to handle sessions and references. It can be used as an extension for ocsigenserver or as a library." homepage: "https://github.com/ocsigen/ocsipersist" bug-reports: "https://github.com/ocsigen/ocsipersist/issues" dev-repo: "git+https://github.com/ocsigen/ocsipersist.git" build: [ "dune" "build" "-p" name "-j" jobs ] depends: [ "dune" {>= "2.9"} "lwt" {>= "4.2.0"} "lwt_log" "xml-light" "ocsigenserver" {>= "3.0.0"} "ocsipersist-lib" {>= "1.1.0" & < "1.2.0"} "dbm" ] ocsipersist-1.1.0/ocsipersist-lib.opam000066400000000000000000000017051417355140700200630ustar00rootroot00000000000000opam-version: "2.0" name: "ocsipersist-lib" version: "1.1.0" authors: "The Ocsigen team " maintainer: "Jan Rochel " license: "LGPL-2.1-only with OCaml-LGPL-linking-exception" synopsis: "Persistent key/value storage (for Ocsigen) - support library" description: "This library defines signatures and auxiliary tools for defining backends for the Ocsipersist frontent. Ocsipersist is used pervasively in Eliom/Ocsigen to handle sessions and references. It can be used as an extension for ocsigenserver or as a library. Implementations of the following backends currently exist: DBM, PostgreSQL, SQLite." homepage: "https://github.com/ocsigen/ocsipersist" bug-reports: "https://github.com/ocsigen/ocsipersist/issues" dev-repo: "git+https://github.com/ocsigen/ocsipersist.git" build: [ "dune" "build" "-p" name "-j" jobs ] depends: [ "dune" {>= "2.9"} "lwt" {>= "4.2.0"} "lwt_ppx" {>= "2.0.0"} ] ocsipersist-1.1.0/ocsipersist-pgsql.opam000066400000000000000000000017401417355140700204420ustar00rootroot00000000000000opam-version: "2.0" name: "ocsipersist-pgsql" version: "1.1.0" authors: "The Ocsigen team " maintainer: "Jan Rochel " license: "LGPL-2.1-only with OCaml-LGPL-linking-exception" synopsis: "Persistent key/value storage (for Ocsigen) using PostgreSQL" description: "This library provides a PostgreSQL backend for the unified key/value storage frontend as defined in the ocsipersist package. Ocsipersist is used pervasively in Eliom/Ocsigen to handle sessions and references. It can be used as an extension for ocsigenserver or as a library." homepage: "https://github.com/ocsigen/ocsipersist" bug-reports: "https://github.com/ocsigen/ocsipersist/issues" dev-repo: "git+https://github.com/ocsigen/ocsipersist.git" build: [ "dune" "build" "-p" name "-j" jobs ] depends: [ "dune" {>= "2.9"} "lwt" {>= "4.2.0"} "lwt_log" "xml-light" "ocsigenserver" {>= "3.0.0"} "ocsipersist-lib" {>= "1.1.0" & < "1.2.0"} "pgocaml" ] ocsipersist-1.1.0/ocsipersist-sqlite.opam000066400000000000000000000017311417355140700206150ustar00rootroot00000000000000opam-version: "2.0" name: "ocsipersist-sqlite" version: "1.1.0" authors: "The Ocsigen team " maintainer: "Jan Rochel " license: "LGPL-2.1-only with OCaml-LGPL-linking-exception" synopsis: "Persistent key/value storage (for Ocsigen) using SQLite" description: "This library provides a SQLite backend for the unified key/value storage frontend as defined in the ocsipersist package. Ocsipersist is used pervasively in Eliom/Ocsigen to handle sessions and references. It can be used as an extension for ocsigenserver or as a library." homepage: "https://github.com/ocsigen/ocsipersist" bug-reports: "https://github.com/ocsigen/ocsipersist/issues" dev-repo: "git+https://github.com/ocsigen/ocsipersist.git" build: [ "dune" "build" "-p" name "-j" jobs ] depends: [ "dune" {>= "2.9"} "lwt" {>= "4.2.0"} "lwt_log" "xml-light" "ocsigenserver" {>= "3.0.0"} "ocsipersist-lib" {>= "1.1.0" & < "1.2.0"} "sqlite3" ] ocsipersist-1.1.0/ocsipersist.opam000066400000000000000000000023411417355140700173140ustar00rootroot00000000000000opam-version: "2.0" name: "ocsipersist" version: "1.1.0" authors: "The Ocsigen team " maintainer: "Jan Rochel " license: "LGPL-2.1-only with OCaml-LGPL-linking-exception" synopsis: "Persistent key/value storage (for Ocsigen) using multiple backends" description: "This is an virtual library defining a unified frontend for a number of key/value storage implementations. Ocsipersist is used pervasively in Eliom/Ocsigen to handle sessions and references. It can be used as an extension for ocsigenserver or as a library. Implementations of the following backends currently exist: DBM, PostgreSQL, SQLite." homepage: "https://github.com/ocsigen/ocsipersist" bug-reports: "https://github.com/ocsigen/ocsipersist/issues" dev-repo: "git+https://github.com/ocsigen/ocsipersist.git" build: [ "dune" "build" "-p" name "-j" jobs ] depends: [ "dune" {>= "2.9"} "lwt" {>= "4.2.0"} "ocsigenserver" {>= "3.0.0"} "ocsipersist-lib" {>= "1.1.0" & < "1.2.0"} ] depopts: [ "ocsipersist-dbm" "ocsipersist-pgsql" "ocsipersist-sqlite" ] conflicts: [ "ocsipersist-dbm" {< "1.1.0" | >= "1.2.0"} "ocsipersist-pgsql" {< "1.1.0" | >= "1.2.0"} "ocsipersist-sqlite" {< "1.1.0" | >= "1.2.0"} ] ocsipersist-1.1.0/src/000077500000000000000000000000001417355140700146565ustar00rootroot00000000000000ocsipersist-1.1.0/src/dbm/000077500000000000000000000000001417355140700154205ustar00rootroot00000000000000ocsipersist-1.1.0/src/dbm/dune000066400000000000000000000011221417355140700162720ustar00rootroot00000000000000(library (name ocsipersist_dbmtypes) (package ocsipersist-dbm) (modules_without_implementation ocsidbmtypes) (wrapped false) (modules ocsidbmtypes)) (library (name ocsipersist_dbm) (public_name ocsipersist.dbm) (implements ocsipersist) (modules ocsipersist) (libraries dbm lwt_log xml-light ocsipersist_dbmtypes ocsigenserver ocsipersist_lib) (optional)) (executable (public_name ocsidbm) (package ocsipersist-dbm) (modules ocsidbm) (libraries lwt lwt.unix dbm ocsipersist_dbmtypes) (modes byte exe)) (documentation (package ocsipersist-dbm) (mld_files index)) ocsipersist-1.1.0/src/dbm/index.mld000066400000000000000000000005401417355140700172240ustar00rootroot00000000000000{0 ocsipersist-dbm} For the API documentation see OPAM package [ocsipersist]. Here we document the configuration options of the ocsigenserver extension. All sub-tags of the [extension] tag are optional. {[ ]} ocsipersist-1.1.0/src/dbm/ocsidbm.ml000066400000000000000000000231521417355140700173750ustar00rootroot00000000000000(* Ocsigen * http://www.ocsigen.org * Module ocsidbm.ml * Copyright (C) 2007 Vincent Balat * * 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, with linking exception; * either version 2.1 of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. *) (** Module Ocsidbm: persistent data server for Ocsigen *) open Dbm open Ocsidbmtypes open Lwt.Infix let directory = Sys.argv.(1) exception Ocsidbm_error let socketname = "socket" let suffix = ".otbl" (*****************************************************************************) (* error messages *) let errlog s = let date = let t = Unix.localtime (Unix.time ()) in Printf.sprintf "%02d-%02d-%04d %02d:%02d:%02d" t.Unix.tm_mday (t.Unix.tm_mon + 1) (1900 + t.Unix.tm_year) t.Unix.tm_hour t.Unix.tm_min t.Unix.tm_sec in let s = date ^ " Ocsidbm - " ^ s ^ "\n" in prerr_endline s (*****************************************************************************) (** Internal functions: storage in files using DBM *) module Tableoftables = Map.Make (struct type t = string let compare = compare end) let tableoftables = ref Tableoftables.empty let list_tables () = let d = try Unix.opendir directory with Unix.Unix_error (error, _, _) -> failwith (Printf.sprintf "Ocsidbm: can't open directory %s: %s" directory (Unix.error_message error)) in let rec aux () = try let n = Unix.readdir d in if Filename.check_suffix n suffix then Filename.chop_extension n :: aux () else if Filename.check_suffix n (suffix ^ ".pag") (* depending on the version of dbm, there may be a .pag suffix *) then Filename.chop_extension (Filename.chop_extension n) :: aux () else aux () with End_of_file -> Unix.closedir d; [] in aux () (* try to create the directory if it does not exist *) let _ = try Unix.access directory [Unix.R_OK; Unix.W_OK; Unix.X_OK; Unix.F_OK] with | Unix.Unix_error (Unix.ENOENT, _, _) -> ( try Unix.mkdir directory 0o750 with Unix.Unix_error (error, _, _) -> failwith (Printf.sprintf "Ocsidbm: can't create directory %s: %s" directory (Unix.error_message error))) | Unix.Unix_error (error, _, _) -> failwith (Printf.sprintf "Ocsidbm: can't access directory %s: %s" directory (Unix.error_message error)) let open_db name = let t = opendbm (directory ^ "/" ^ name ^ suffix) [Dbm_rdwr; Dbm_create] 0o640 in tableoftables := Tableoftables.add name t !tableoftables; t let open_db_if_exists name = try let t = opendbm (directory ^ "/" ^ name ^ suffix) [Dbm_rdwr] 0o640 in tableoftables := Tableoftables.add name t !tableoftables; t with Unix.Unix_error (Unix.ENOENT, _, _) | Dbm.Dbm_error _ -> raise Not_found (* open all files and register them in the table of tables *) (* let _ = List.iter (fun a -> try ignore (open_db a) with ... -> errlog ("Error while openning database "^a)) (list_tables ()) si je remets ça, ça doit être après la création de la socket car si je n'arrive pas à créer la socket, c'est peut-être que les tables sont déjà ouvertes *) let find_create_table name = try Tableoftables.find name !tableoftables with Not_found -> open_db name let find_dont_create_table name = try Tableoftables.find name !tableoftables with Not_found -> open_db_if_exists name let db_get store name = find (find_dont_create_table store) name let db_remove store name = try remove (find_dont_create_table store) name with | Not_found -> () | Dbm.Dbm_error "dbm_delete" -> () let db_replace store name value = replace (find_create_table store) name value let db_firstkey t = Dbm.firstkey (find_dont_create_table t) let db_nextkey t = Dbm.nextkey (find_dont_create_table t) let db_length t = let table = find_dont_create_table t in let rec aux f n = Lwt.catch (fun () -> ignore (f table); Lwt.pause () >>= fun () -> aux Dbm.nextkey (n + 1)) (function Not_found -> Lwt.return n | e -> Lwt.fail e) in aux Dbm.firstkey 0 (* Because of Dbm implementation, the result may be less than the expected result in some case *) (*****************************************************************************) (* signals *) let close_all i _ = Unix.unlink (directory ^ "/" ^ socketname); Tableoftables.iter (fun _k t -> Dbm.close t) !tableoftables; exit i let the_end i = exit i open Sys let sigs = [ sigabrt ; sigalrm ; sigfpe ; sighup ; sigill ; sigint ; sigquit ; sigsegv ; sigterm ; sigusr1 ; sigusr2 ; sigchld ; sigttin ; sigttou ; sigvtalrm ; sigprof ] let _ = List.iter (fun s -> Sys.set_signal s (Signal_handle (close_all 0))) sigs let _ = Sys.set_signal Sys.sigpipe Sys.Signal_ignore let _ = Unix.setsid () (*****************************************************************************) (** Communication functions: *) let send outch v = Lwt_io.write_value outch v >>= fun () -> Lwt_io.flush outch let execute outch = let handle_errors f = try f () with e -> send outch (Error e) in function | Get (t, k) -> handle_errors (fun () -> try send outch (Value (db_get t k)) with Not_found -> send outch Dbm_not_found) | Remove (t, k) -> handle_errors (fun () -> db_remove t k; send outch Ok) | Replace (t, k, v) -> handle_errors (fun () -> db_replace t k v; send outch Ok) | Replace_if_exists (t, k, v) -> handle_errors (fun () -> try ignore (db_get t k); db_replace t k v; send outch Ok with Not_found -> send outch Dbm_not_found) | Firstkey t -> handle_errors (fun () -> try send outch (Key (db_firstkey t)) with Not_found -> send outch End) | Nextkey t -> handle_errors (fun () -> try send outch (Key (db_nextkey t)) with Not_found -> send outch End) | Length t -> handle_errors (fun () -> Lwt.catch (fun () -> db_length t >>= fun i -> send outch (Value (Marshal.to_string i []))) (function | Not_found -> send outch Dbm_not_found | e -> send outch (Error e))) let nb_clients = ref 0 let rec listen_client inch outch = Lwt_io.read_value inch >>= fun v -> execute outch v >>= fun () -> listen_client inch outch let finish _ = nb_clients := !nb_clients - 1; if !nb_clients = 0 then close_all 0 (); Lwt.return () let b = ref false let rec loop socket = Lwt_unix.accept socket >>= fun (indescr, _) -> ignore (b := true; nb_clients := !nb_clients + 1; let inch = Lwt_io.of_fd ~mode:Lwt_io.input indescr in let outch = Lwt_io.of_fd ~mode:Lwt_io.output indescr in Lwt.catch (fun () -> listen_client inch outch >>= finish) finish); loop socket let _ = Lwt_main.run (let socket = Lwt_unix.socket Unix.PF_UNIX Unix.SOCK_STREAM 0 in Lwt.catch (fun () -> Lwt_unix.bind socket (Unix.ADDR_UNIX (directory ^ "/" ^ socketname))) (fun _exn -> errlog ("Please make sure that the directory " ^ directory ^ " exists, writable for ocsidbm, and no other ocsidbm process is running on the same directory. If not, remove the file " ^ directory ^ "/" ^ socketname); the_end 1) >>= fun () -> Lwt_unix.listen socket 20; (* Done in ocsipersist.ml let devnull = Unix.openfile "/dev/null" [Unix.O_WRONLY] 0 in Unix.dup2 devnull Unix.stdout; Unix.dup2 devnull Unix.stderr; Unix.close devnull; Unix.close Unix.stdin; *) ignore ( Lwt_unix.sleep 4.1 >>= fun () -> if not !b then close_all 0 (); Lwt.return () ); (* If nothing happened during 5 seconds, I quit *) loop socket) (*****************************************************************************) (** Garbage collection of expired data *) (* Experimental exception Exn1 let dbm_fold f t beg = let rec aux nextkey beg = try let k = try nextkey t with Not_found -> raise Exn1 in let v = try Dbm.find k t with Not_found -> raise Exn1 in aux Dbm.nextkey (f k v beg) with Exn1 -> beg in aux Dbm.firstkey beg let _ = match sessiongcfrequency with None -> () (* No garbage collection *) | Some t -> let rec f () = Lwt_unix.sleep t >>= (fun () -> let now = Unix.time () in print_endline "GC of persistent data"; Tableoftables.fold (fun name t thr -> thr >>= (fun () -> dbm_fold (fun k v thr -> thr >>= (fun () -> (match fst (Marshal.from_string v 0) with | Some exp when exp < now -> try Dbm.remove t k with _ -> ()); Lwt.pause () ) ) t (Lwt.return ())) ) !tableoftables (Lwt.return ()) ) >>= f in ignore (f ()) *) ocsipersist-1.1.0/src/dbm/ocsidbmtypes.mli000066400000000000000000000022531417355140700206320ustar00rootroot00000000000000(* Ocsigen * http://www.ocsigen.org * Copyright (C) 2007 Vincent Balat * * 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, with linking exception; * either version 2.1 of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. *) exception Ocsidbm_error type query = | Get of string * string | Remove of string * string | Replace of string * string * string | Replace_if_exists of string * string * string | Nextkey of string | Firstkey of string | Length of string type answer = | Ok | Dbm_not_found | Value of string | End | Key of string | Error of exn ocsipersist-1.1.0/src/dbm/ocsipersist.ml000066400000000000000000000272721417355140700203330ustar00rootroot00000000000000(* FIX: the log file is never reopened *) open Ocsidbmtypes open Lwt.Infix module type TABLE = Ocsipersist_lib.Sigs.TABLE let section = Lwt_log.Section.make "ocsigen:ocsipersist:dbm" exception Ocsipersist_error let socketname = "socket" module Config = struct let directory, ocsidbm = ref (Ocsigen_config.get_datadir () ^ "/ocsipersist"), ref "ocsidbm" let inch = ref (Lwt.fail (Failure "Ocsipersist not initialised")) let outch = ref (Lwt.fail (Failure "Ocsipersist not initialised")) end module Aux = struct external sys_exit : int -> 'a = "caml_sys_exit" end module Db = struct let try_connect sname = Lwt.catch (fun () -> let socket = Lwt_unix.socket Unix.PF_UNIX Unix.SOCK_STREAM 0 in Lwt_unix.connect socket (Unix.ADDR_UNIX sname) >>= fun () -> Lwt.return socket) (fun _ -> Lwt_log.ign_warning_f ~section "Launching a new Ocsidbm process: %s on directory %s." !Config.ocsidbm !Config.directory; let param = [|!Config.ocsidbm; !Config.directory|] in let child () = let log = Unix.openfile (Ocsigen_messages.error_log_path ()) [Unix.O_WRONLY; Unix.O_CREAT; Unix.O_APPEND] 0o640 in Unix.dup2 log Unix.stderr; Unix.close log; let devnull = Unix.openfile "/dev/null" [Unix.O_WRONLY] 0 in Unix.dup2 devnull Unix.stdout; Unix.close devnull; Unix.close Unix.stdin; Unix.execvp !Config.ocsidbm param in let pid = Lwt_unix.fork () in if pid = 0 then if (* double fork *) Lwt_unix.fork () = 0 then child () else Aux.sys_exit 0 else Lwt_unix.waitpid [] pid >>= fun _ -> Lwt_unix.sleep 1.1 >>= fun () -> let socket = Lwt_unix.socket Unix.PF_UNIX Unix.SOCK_STREAM 0 in Lwt_unix.connect socket (Unix.ADDR_UNIX sname) >>= fun () -> Lwt.return socket) let rec get_indescr i = Lwt.catch (fun () -> try_connect (!Config.directory ^ "/" ^ socketname)) (fun e -> if i = 0 then ( Lwt_log.ign_error_f ~section "Cannot connect to Ocsidbm. Will continue without persistent session support. Error message is: %s .Have a look at the logs to see if there is an error message from the Ocsidbm process." (match e with | Unix.Unix_error (a, b, c) -> Printf.sprintf "%a in %s(%s)" (fun () -> Unix.error_message) a b c | _ -> Printexc.to_string e); Lwt.fail e) else Lwt_unix.sleep 2.1 >>= fun () -> get_indescr (i - 1)) let send = let previous = ref (Lwt.return Ok) in fun v -> Lwt.catch (fun () -> !previous) (fun _ -> Lwt.return Ok) >>= fun _ -> !Config.inch >>= fun inch -> !Config.outch >>= fun outch -> (previous := Lwt_io.write_value outch v >>= fun () -> Lwt_io.flush outch >>= fun () -> Lwt_io.read_value inch); !previous let get (store, name) = send (Get (store, name)) >>= function | Value v -> Lwt.return v | Dbm_not_found -> Lwt.fail Not_found | Error e -> Lwt.fail e | _ -> Lwt.fail Ocsipersist_error let remove (store, name) = send (Remove (store, name)) >>= function | Ok -> Lwt.return () | Error e -> Lwt.fail e | _ -> Lwt.fail Ocsipersist_error let replace (store, name) value = send (Replace (store, name, value)) >>= function | Ok -> Lwt.return () | Error e -> Lwt.fail e | _ -> Lwt.fail Ocsipersist_error let replace_if_exists (store, name) value = send (Replace_if_exists (store, name, value)) >>= function | Ok -> Lwt.return () | Dbm_not_found -> Lwt.fail Not_found | Error e -> Lwt.fail e | _ -> Lwt.fail Ocsipersist_error let firstkey store = send (Firstkey store) >>= function | Key k -> Lwt.return (Some k) | Error e -> Lwt.fail e | _ -> Lwt.return None let nextkey store = send (Nextkey store) >>= function | Key k -> Lwt.return (Some k) | Error e -> Lwt.fail e | _ -> Lwt.return None let length store = send (Length store) >>= function | Value v -> Lwt.return (Marshal.from_string v 0) | Dbm_not_found -> Lwt.return 0 | Error e -> Lwt.fail e | _ -> Lwt.fail Ocsipersist_error end module Store = struct type store = string type 'a t = store * string (** Type of persistent data *) let open_store name = Lwt.return name let make_persistent_lazy_lwt ~store ~name ~default = let pvname = store, name in Lwt.catch (fun () -> Db.get pvname >>= fun _ -> Lwt.return ()) (function | Not_found -> default () >>= fun def -> Db.replace pvname (Marshal.to_string def []) | e -> Lwt.fail e) >>= fun () -> Lwt.return pvname let make_persistent_lazy ~store ~name ~default = let default () = Lwt.wrap default in make_persistent_lazy_lwt ~store ~name ~default let make_persistent ~store ~name ~default = make_persistent_lazy ~store ~name ~default:(fun () -> default) let get (pvname : 'a t) : 'a = Db.get pvname >>= fun r -> Lwt.return (Marshal.from_string r 0) let set pvname v = let data = Marshal.to_string v [] in Db.replace pvname data end type store = Store.store type 'a variable = 'a Store.t module Functorial = struct type internal = string module type COLUMN = sig type t val column_type : string val encode : t -> string val decode : string -> t end module Table (T : sig val name : string end) (Key : COLUMN) (Value : COLUMN) : Ocsipersist_lib.Sigs.TABLE with type key = Key.t and type value = Value.t = struct type key = Key.t type value = Value.t let name = T.name let find key = Lwt.map Value.decode @@ Db.get (name, Key.encode key) let add key value = Db.replace (name, Key.encode key) (Value.encode value) let replace_if_exists key value = Db.replace_if_exists (name, Key.encode key) (Value.encode value) let remove key = Db.remove (name, Key.encode key) let fold ?count ?gt ?geq ?lt ?leq f beg = let i = ref 0L in let rec aux nextkey beg = match count with | Some c when !i >= c -> Lwt.return beg | _ -> ( nextkey name >>= function | None -> Lwt.return beg | Some k -> ( let k = Key.decode k in match gt, geq, lt, leq with | _, _, Some lt, _ when k >= lt -> Lwt.return beg | _, _, _, Some le when k > le -> Lwt.return beg | Some gt, _, _, _ when k <= gt -> aux Db.nextkey beg | _, Some ge, _, _ when k < ge -> aux Db.nextkey beg | _ -> i := Int64.succ !i; find k >>= fun r -> f k r beg >>= aux Db.nextkey)) in aux Db.firstkey beg let iter ?count ?gt ?geq ?lt ?leq f = fold ?count ?gt ?geq ?lt ?leq (fun k v () -> f k v) () let iter_batch ?count:_ ?gt:_ ?geq:_ ?lt:_ ?leq:_ _ = failwith "Ocsipersist.iter_batch not implemented for DBM" let iter_block ?count:_ ?gt:_ ?geq:_ ?lt:_ ?leq:_ _ = failwith "iter_block not implemented for DBM. Please use Ocsipersist with sqlite" let modify_opt key f = Lwt.catch (fun () -> find key >>= fun v -> Lwt.return_some v) (function Not_found -> Lwt.return_none | _ -> assert false) >>= fun old_value -> match f old_value with | None -> remove key | Some new_value -> replace_if_exists key new_value let length () = (* for DBM the result may be less than the actual lengeth *) Db.length name module Variable = Ocsipersist_lib.Variable (struct type k = key type v = value let find = find let add = add end) end module Column = struct module String : COLUMN with type t = string = struct type t = string let column_type = "_" let encode s = s let decode s = s end module Float : COLUMN with type t = float = struct type t = float let column_type = "_" let encode = string_of_float let decode = float_of_string end module Marshal (C : sig type t end) : COLUMN with type t = C.t = struct type t = C.t let column_type = "_" let encode v = Marshal.to_string v [] let decode v = Marshal.from_string v 0 end end end module Polymorphic = Ocsipersist_lib.Polymorphic (Functorial) type 'value table = 'value Polymorphic.table (* iterator: with a separate connexion: exception Exn1 let iter_table f table = let first = Marshal.to_string (Firstkey table) [] in let firstl = String.length first in let next = Marshal.to_string (Nextkey table) [] in let nextl = String.length next in (Lwt_unix.socket Unix.PF_UNIX Unix.SOCK_STREAM 0 >>= (fun socket -> Lwt_unix.connect (Lwt_unix.Plain socket) (Unix.ADDR_UNIX (Config.directory^"/"^socketname)) >>= (fun () -> return (Lwt_unix.Plain socket)) >>= (fun indescr -> let inch = Lwt_unix.in_channel_of_descr indescr in let nextkey next nextl = Lwt_unix.write indescr next 0 nextl >>= (fun l2 -> if l2 <> nextl then Lwt.fail Ocsipersist_error else (Lwt_unix.input_line inch >>= fun answ -> return (Marshal.from_string answ 0))) in let rec aux n l = nextkey n l >>= (function | End -> return () | Key k -> find table k >>= f k | Error e -> Lwt.fail e | _ -> Lwt.fail Ocsipersist_error) >>= (fun () -> aux next nextl) in catch (fun () -> aux first firstl >>= (fun () -> Unix.close socket; return ())) (fun e -> Unix.close socket; Lwt.fail e)))) *) module Registration = struct (** getting the directory from config file *) let rec parse_global_config ((store, ocsidbm, delayloading) as d) = function | [] -> d | Xml.Element ("delayloading", [("val", ("true" | "1"))], []) :: ll -> parse_global_config (store, ocsidbm, true) ll | Xml.Element ("store", [("dir", s)], []) :: ll -> if store = None then parse_global_config (Some s, ocsidbm, delayloading) ll else Ocsigen_extensions.badconfig "Ocsipersist: Duplicate tag" | Xml.Element ("ocsidbm", [("name", s)], []) :: ll -> if ocsidbm = None then parse_global_config (store, Some s, delayloading) ll else Ocsigen_extensions.badconfig "Ocsipersist: Duplicate tag" | Xml.Element (s, _, _) :: _ll -> Ocsigen_extensions.badconfig "Bad tag %s" s | _ -> Ocsigen_extensions.badconfig "Unexpected content inside Ocsipersist config" let init_fun config = let store, ocsidbmconf, delay_loading = parse_global_config (None, None, false) config in (match store with None -> () | Some d -> Config.directory := d); (match ocsidbmconf with None -> () | Some d -> Config.ocsidbm := d); if delay_loading then Lwt_log.ign_warning ~section "Asynchronuous initialization (may fail later)" else Lwt_log.ign_warning ~section "Initializing ..."; let indescr = Db.get_indescr 2 in if delay_loading then ( Config.inch := Lwt.map (Lwt_io.of_fd ~mode:Lwt_io.input) indescr; Config.outch := Lwt.map (Lwt_io.of_fd ~mode:Lwt_io.output) indescr) else let r = Lwt_main.run indescr in Config.inch := Lwt.return (Lwt_io.of_fd ~mode:Lwt_io.input r); Config.outch := Lwt.return (Lwt_io.of_fd ~mode:Lwt_io.output r); Lwt_log.ign_warning ~section "...Initialization complete" let _ = Ocsigen_extensions.register ~name:"ocsipersist" ~init_fun () end ocsipersist-1.1.0/src/dune000066400000000000000000000005311417355140700155330ustar00rootroot00000000000000(library (name ocsipersist_lib) (public_name ocsipersist-lib) (modules ocsipersist_lib) (wrapped false) (libraries lwt) (preprocess (pps lwt_ppx))) (library (public_name ocsipersist) (virtual_modules ocsipersist) (modules ocsipersist) (wrapped false) (libraries ocsipersist_lib lwt)) (env (_ (flags (:standard -w -9-37-39)))) ocsipersist-1.1.0/src/ocsipersist.mli000066400000000000000000000025631417355140700177360ustar00rootroot00000000000000(** Library (and extension for ocsigenserver) for storing and retrieving key/value data in a persistent manner. This module defines a unified frontend for a number of different backends. *) module Functorial : Ocsipersist_lib.Sigs.FUNCTORIAL (** Functorial frontent. Allows for custom (de)serialisation functions, which keeps data human-readable in the backend. *) module type TABLE = Ocsipersist_lib.Sigs.TABLE (** Table representation as generated by the functor {!Functorial.Table} *) module Polymorphic : Ocsipersist_lib.Sigs.POLYMORPHIC (** Polymorphic frontent. Relies on {!Marshal} for (de)serialisation, which means that data will be stored in the backend in a fashion that is not necessarily easily readable by non-OCaml-based life forms. If this is an issue for you, you can rely on the functorial frontend instead. *) type 'value table = 'value Polymorphic.table (** Table representation as generated by the function {!Polymorphic.open_table} *) module Store : Ocsipersist_lib.Sigs.STORE (** The variable store allows for the persistent storage of individual variables. Relies on {!Stdlib.Marshal} for (de)serialisation, which entails the same limitations as for the {!Polymorphic} frontend. If this is an issue you can rely on {!Functorial} frontend instead (see {!TABLE.Variable}). *) type store = Store.store type 'a variable = 'a Store.t ocsipersist-1.1.0/src/ocsipersist_lib.ml000066400000000000000000000172101417355140700204060ustar00rootroot00000000000000(** This modules provides tools for creating more implementations of the {!Ocsipersist} virtual module. *) module Sigs = struct module type TABLE = sig type key type value val name : string val find : key -> value Lwt.t val add : key -> value -> unit Lwt.t val replace_if_exists : key -> value -> unit Lwt.t val remove : key -> unit Lwt.t val modify_opt : key -> (value option -> value option) -> unit Lwt.t val length : unit -> int Lwt.t val iter : ?count:int64 -> ?gt:key -> ?geq:key -> ?lt:key -> ?leq:key -> (key -> value -> unit Lwt.t) -> unit Lwt.t val fold : ?count:int64 -> ?gt:key -> ?geq:key -> ?lt:key -> ?leq:key -> (key -> value -> 'a -> 'a Lwt.t) -> 'a -> 'a Lwt.t val iter_block : ?count:int64 -> ?gt:key -> ?geq:key -> ?lt:key -> ?leq:key -> (key -> value -> unit) -> unit Lwt.t val iter_batch : ?count:int64 -> ?gt:key -> ?geq:key -> ?lt:key -> ?leq:key -> ((key * value) list -> unit Lwt.t) -> unit Lwt.t module Variable : sig type t val make : name:key -> default:value -> t val make_lazy : name:key -> default:(unit -> value) -> t val make_lazy_lwt : name:key -> default:(unit -> value Lwt.t) -> t val get : t -> value Lwt.t val set : t -> value -> unit Lwt.t end end module type FUNCTORIAL = sig type internal module type COLUMN = sig type t val column_type : string val encode : t -> internal val decode : internal -> t end module Table (T : sig val name : string end) (Key : COLUMN) (Value : COLUMN) : TABLE with type key = Key.t and type value = Value.t module Column : sig module String : COLUMN with type t = string module Float : COLUMN with type t = float module Marshal (C : sig type t end) : COLUMN with type t = C.t end end module type POLYMORPHIC = sig type 'value table (** Type of persistent table *) val table_name : 'value table -> string Lwt.t (** returns the name of the table *) val open_table : string -> 'value table Lwt.t (** Open a table (and create it if it does not exist) *) val find : 'value table -> string -> 'value Lwt.t (** [find table key] gives the value associated to [key]. Fails with [Not_found] if not found. *) val add : 'value table -> string -> 'value -> unit Lwt.t (** [add table key value] associates [value] to [key]. If the database already contains data associated with [key], that data is discarded and silently replaced by the new data. *) val replace_if_exists : 'value table -> string -> 'value -> unit Lwt.t (** [replace_if_exists table key value] associates [value] to [key] only if [key] is already bound. If the database does not contain any data associated with [key], fails with [Not_found]. *) val remove : 'value table -> string -> unit Lwt.t (** [remove table key] removes the entry in the table if it exists *) val length : 'value table -> int Lwt.t (** Size of a table. *) val iter_step : (string -> 'a -> unit Lwt.t) -> 'a table -> unit Lwt.t (** Important warning: this iterator may not iter on all data of the table if another thread is modifying it in the same time. Nonetheless, it should not miss more than a very few data from time to time, except if the table is very old (at least 9 223 372 036 854 775 807 insertions). *) val fold_step : (string -> 'a -> 'b -> 'b Lwt.t) -> 'a table -> 'b -> 'b Lwt.t (** Important warning: this iterator may not iter on all data of the table if another thread is modifying it in the same time. Nonetheless, it should not miss more than a very few data from time to time, except if the table is very old (at least 9 223 372 036 854 775 807 insertions). *) val iter_block : (string -> 'a -> unit) -> 'a table -> unit Lwt.t (** MAJOR WARNING: Unlike iter_step, this iterator won't miss any entry and will run in one shot. It is therefore more efficient, BUT: it will lock the WHOLE database during its execution, thus preventing ANYBODY from accessing it (including the function f which is iterated). As a consequence: you MUST NOT use any function from ocsipersist in f, otherwise you would lock yourself and everybody else! Be VERY cautious. *) end module type STORE = sig type 'a t (** Type of persistent data *) type store (** Data are divided into stores. Create one store for your project, where you will save all your data. *) val open_store : string -> store Lwt.t (** Open a store (and create it if it does not exist) *) val make_persistent : store:store -> name:string -> default:'a -> 'a t Lwt.t (** [make_persistent store name default] find a persistent value named [name] in store [store] from database, or create it with the default value [default] if it does not exist. *) val make_persistent_lazy : store:store -> name:string -> default:(unit -> 'a) -> 'a t Lwt.t (** Same as make_persistent but the default value is evaluated only if needed *) val make_persistent_lazy_lwt : store:store -> name:string -> default:(unit -> 'a Lwt.t) -> 'a t Lwt.t (** Lwt version of make_persistent_lazy. *) val get : 'a t -> 'a Lwt.t (** [get pv] gives the value of [pv] *) val set : 'a t -> 'a -> unit Lwt.t (** [set pv value] sets a persistent value [pv] to [value] *) end end open Sigs open Lwt.Infix (** deriving polymorphic interface from the functorial one *) module Polymorphic (Functorial : FUNCTORIAL) : POLYMORPHIC = struct module type POLYMORPHIC = TABLE with type key = string type 'value table = (module POLYMORPHIC with type value = 'value) let open_table (type a) name = let open Functorial in let module T = Table (struct let name = name end) (Column.String) (Column.Marshal (struct type t = a end)) in Lwt.return (module T : POLYMORPHIC with type value = a) let table_name (type a) (module T : POLYMORPHIC with type value = a) = Lwt.return T.name let find (type a) (module T : POLYMORPHIC with type value = a) = T.find let add (type a) (module T : POLYMORPHIC with type value = a) = T.add let replace_if_exists (type a) (module T : POLYMORPHIC with type value = a) = T.replace_if_exists let remove (type a) (module T : POLYMORPHIC with type value = a) = T.remove let length (type a) (module T : POLYMORPHIC with type value = a) = T.length () let iter_step (type a) f (module T : POLYMORPHIC with type value = a) = T.iter f let fold_step (type a) f (module T : POLYMORPHIC with type value = a) = T.fold f let iter_block (type a) f (module T : POLYMORPHIC with type value = a) = T.iter_block f end module Variable (T : sig type k type v val find : k -> v Lwt.t val add : k -> v -> unit Lwt.t end) = struct type t = {name : T.k; default : unit -> T.v Lwt.t} let make_lazy_lwt ~name ~default = {name; default} let make_lazy ~name ~default = {name; default = (fun () -> Lwt.return @@ default ())} let make ~name ~default = {name; default = (fun () -> Lwt.return default)} let get {name; default} = try%lwt T.find name with Not_found -> default () >>= fun d -> T.add name d >>= fun () -> Lwt.return d let set {name} = T.add name end ocsipersist-1.1.0/src/pgsql/000077500000000000000000000000001417355140700160045ustar00rootroot00000000000000ocsipersist-1.1.0/src/pgsql/dune000066400000000000000000000003611417355140700166620ustar00rootroot00000000000000(library (name ocsipersist_pgsql) (public_name ocsipersist.pgsql) (implements ocsipersist) (libraries pgocaml lwt_log xml-light ocsigenserver ocsipersist_lib) (optional)) (documentation (package ocsipersist-pgsql) (mld_files index)) ocsipersist-1.1.0/src/pgsql/index.mld000066400000000000000000000012471417355140700176150ustar00rootroot00000000000000{0 ocsipersist-pgsql} For the API documentation see OPAM package [ocsipersist]. Here we document the configuration options of the ocsigenserver extension. All attributes of the [database] tag are optional. One can either define a host to connect to: {[ ]} Or a UNIX domain socket: {[ ]} ocsipersist-1.1.0/src/pgsql/ocsipersist.ml000066400000000000000000000346441417355140700207200ustar00rootroot00000000000000(** PostgreSQL (>= 9.5) backend for Ocsipersist. *) module type TABLE = Ocsipersist_lib.Sigs.TABLE let section = Lwt_log.Section.make "ocsigen:ocsipersist:pgsql" module Lwt_thread = struct include Lwt let close_in = Lwt_io.close let really_input = Lwt_io.read_into_exactly let input_binary_int = Lwt_io.BE.read_int let input_char = Lwt_io.read_char let output_string = Lwt_io.write let output_binary_int = Lwt_io.BE.write_int let output_char = Lwt_io.write_char let flush = Lwt_io.flush let open_connection x = Lwt_io.open_connection x type out_channel = Lwt_io.output_channel type in_channel = Lwt_io.input_channel end module PGOCaml = PGOCaml_generic.Make (Lwt_thread) open Lwt.Infix open Printf exception Ocsipersist_error module Config = struct let host = ref None let port = ref None let user = ref None let password = ref None let database = ref "ocsipersist" let unix_domain_socket_dir = ref None let size_conn_pool = ref 16 end let connect () = PGOCaml.connect ?host:!Config.host ?port:!Config.port ?user:!Config.user ?password:!Config.password ?database:(Some !Config.database) ?unix_domain_socket_dir:!Config.unix_domain_socket_dir () >>= fun dbhandle -> PGOCaml.set_private_data dbhandle @@ Hashtbl.create 8; Lwt.return dbhandle let ( >> ) f g = f >>= fun _ -> g let conn_pool : (string, unit) Hashtbl.t PGOCaml.t Lwt_pool.t ref = let dispose db = Lwt.catch (fun () -> PGOCaml.close db) (fun _ -> Lwt.return_unit) in (* This connection pool will be overwritten by init_fun! *) ref (Lwt_pool.create !Config.size_conn_pool ~validate:PGOCaml.alive ~dispose connect) let use_pool f = Lwt_pool.use !conn_pool @@ fun db -> Lwt.catch (fun () -> f db) (function | PGOCaml.Error msg as e -> Lwt_log.ign_error_f ~section "postgresql protocol error: %s" msg; PGOCaml.close db >>= fun () -> Lwt.fail e | Lwt.Canceled as e -> Lwt_log.ign_error ~section "thread canceled"; PGOCaml.close db >>= fun () -> Lwt.fail e | e -> Lwt.fail e) (* escapes characters that are not in the range of 0x20..0x7e; this is to meet PostgreSQL's format requirements for text fields while keeping the key column readable whenever possible. *) let escape_string s = let len = String.length s in let buf = Buffer.create (len * 2) in for i = 0 to len - 1 do let c = s.[i] in let cc = Char.code c in if cc < 0x20 || cc > 0x7e then Buffer.add_string buf (sprintf "\\%03o" cc) (* non-print -> \ooo *) else if c = '\\' then Buffer.add_string buf "\\\\" (* \ -> \\ *) else Buffer.add_char buf c done; Buffer.contents buf let unescape_string str = let is_first_oct_digit c = c >= '0' && c <= '3' and is_oct_digit c = c >= '0' && c <= '7' and oct_val c = Char.code c - 0x30 in let len = String.length str in let buf = Buffer.create len in let i = ref 0 in while !i < len do let c = str.[!i] in if c = '\\' then ( incr i; if !i < len && str.[!i] = '\\' then (Buffer.add_char buf '\\'; incr i) else if !i + 2 < len && is_first_oct_digit str.[!i] && is_oct_digit str.[!i + 1] && is_oct_digit str.[!i + 2] then ( let byte = oct_val str.[!i] in incr i; let byte = (byte lsl 3) + oct_val str.[!i] in incr i; let byte = (byte lsl 3) + oct_val str.[!i] in incr i; Buffer.add_char buf (Char.chr byte))) else (incr i; Buffer.add_char buf c) done; Buffer.contents buf type 'a parameter = Key of string | Value of 'a let pack = function | Key k -> escape_string k | Value v -> PGOCaml.string_of_bytea @@ Marshal.to_string v [] let unpack_value value = Marshal.from_string (PGOCaml.bytea_of_string value) 0 let rec list_last l = match l with [x] -> x | _ :: r -> list_last r | [] -> raise Not_found (* get one value from the result of a query *) let one_value = function | [Some value] :: _xs -> unpack_value value | _ -> raise Not_found let prepare db query = let hashtbl = PGOCaml.private_data db in (* Get a unique name for this query using an MD5 digest. *) let name = Digest.to_hex (Digest.string query) in (* Have we prepared this statement already? If not, do so. *) let is_prepared = Hashtbl.mem hashtbl name in (if is_prepared then Lwt.return () else PGOCaml.prepare db ~name ~query () >> Lwt.return @@ Hashtbl.add hashtbl name ()) >>= fun () -> Lwt.return name let exec db query params = prepare db query >>= fun name -> let params = List.map (fun x -> Some (pack x)) params in PGOCaml.execute db ~name ~params () let exec_ db query params = exec db query params >> Lwt.return_unit module Functorial = struct type internal = string module type COLUMN = sig type t val column_type : string val encode : t -> internal val decode : internal -> t end module Table (T : sig val name : string end) (Key : COLUMN) (Value : COLUMN) : TABLE with type key = Key.t and type value = Value.t = struct type key = Key.t type value = Value.t let name = T.name module Aux = struct let exec_opt db query params = prepare db query >>= fun name -> PGOCaml.execute db ~name ~params () let exec db query params = prepare db query >>= fun name -> let params = List.map (fun x -> Some x) params in PGOCaml.execute db ~name ~params () let exec_ db query params = exec db query params >> Lwt.return_unit let encode_pair key value = [Key.encode key; Value.encode value] end let init = let create_table table db = let query = sprintf "CREATE TABLE IF NOT EXISTS %s (key %s, value %s, PRIMARY KEY (key))" table Key.column_type Value.column_type in Aux.exec_ db query [] in lazy (use_pool @@ create_table T.name) let with_table f = Lazy.force init >>= fun () -> use_pool f let find key = with_table @@ fun db -> let query = sprintf "SELECT value FROM %s WHERE key = $1 " name in Aux.exec db query [Key.encode key] >>= function | [Some value] :: _ -> Lwt.return (Value.decode value) | _ -> Lwt.fail Not_found let add key value = with_table @@ fun db -> let query = sprintf "INSERT INTO %s VALUES ($1, $2) ON CONFLICT (key) DO UPDATE SET value = $2" name in Aux.exec_ db query @@ Aux.encode_pair key value let replace_if_exists key value = with_table @@ fun db -> let query = sprintf "UPDATE %s SET value = $2 WHERE key = $1 RETURNING 0" name in Aux.exec db query (Aux.encode_pair key value) >>= function | [] -> raise Not_found | _ -> Lwt.return_unit let remove key = with_table @@ fun db -> let query = sprintf "DELETE FROM %s WHERE key = $1" name in Aux.exec_ db query [Key.encode key] let modify_opt key f = with_table @@ fun db -> let query = sprintf "SELECT value FROM %s WHERE key = $1" name in Aux.exec db query [Key.encode key] >>= fun value -> let old_value = match value with [Some v] :: _ -> Some (Value.decode v) | _ -> None in let new_value = f old_value in match new_value = old_value, new_value with | true, _ -> Lwt.return_unit | false, Some new_value -> let query = sprintf "INSERT INTO %s VALUES ($1, $2) ON CONFLICT (key) DO UPDATE SET value = $2" name in Aux.exec_ db query @@ Aux.encode_pair key new_value | false, None -> let query = sprintf "DELETE FROM %s WHERE key = $1" name in Aux.exec_ db query [Key.encode key] let length () = with_table @@ fun db -> let query = sprintf "SELECT count (1) FROM %s" name in Lwt.map one_value @@ Aux.exec db query [] let max_iter_block_size = 1000L let rec iter_rec last ?count ?gt ?geq ?lt ?leq f = match count with | Some c when c <= 0L -> Lwt.return_unit | _ -> let key_value_of_row = function | [Some key; Some value] -> Key.decode key, Value.decode value | _ -> raise Ocsipersist_error in let query = sprintf "SELECT * FROM %s WHERE ($1 :: %s IS NULL OR key > $1) AND ($2 :: %s IS NULL OR key > $2) AND ($3 :: %s IS NULL OR key >= $3) AND ($4 :: %s IS NULL OR key < $4) AND ($5 :: %s IS NULL OR key <= $5) ORDER BY key LIMIT $6" name Key.column_type Key.column_type Key.column_type Key.column_type Key.column_type in let limit = match count with | Some c when c <= max_iter_block_size -> c | _ -> max_iter_block_size in let args = [ Option.map Key.encode last ; Option.map Key.encode gt ; Option.map Key.encode geq ; Option.map Key.encode lt ; Option.map Key.encode leq ; Some (Int64.to_string limit) ] in with_table (fun db -> Aux.exec_opt db query args) >>= fun l -> let key_values = List.map key_value_of_row l in f key_values >>= fun () -> if Int64.of_int (List.length l) < limit then Lwt.return_unit else let last, _ = list_last key_values in let count = Option.map Int64.(fun c -> sub c @@ of_int @@ List.length key_values) count in iter_rec (Some last) ?count f ?gt ?geq ?lt ?leq let iter_batch = iter_rec None let iter ?count ?gt ?geq ?lt ?leq f = let f key_values = Lwt_list.iter_s (fun (k, v) -> f k v) key_values in iter_rec None ?count ?gt ?geq ?lt ?leq f let fold ?count ?gt ?geq ?lt ?leq f x = let res = ref x in let g key value = f key value !res >>= fun res' -> res := res'; Lwt.return_unit in iter ?count ?gt ?geq ?lt ?leq g >> Lwt.return !res let iter_block ?count:_ ?gt:_ ?geq:_ ?lt:_ ?leq:_ _ = failwith "Ocsipersist.iter_block: not implemented" module Variable = Ocsipersist_lib.Variable (struct type k = key type v = value let find = find let add = add end) end module Column = struct module String : COLUMN with type t = string = struct type t = string let column_type = "text" let encode = escape_string let decode = unescape_string end module Float : COLUMN with type t = float = struct type t = float let column_type = "float" let encode = Printf.sprintf "%.16f" let decode = Stdlib.float_of_string end module Marshal (C : sig type t end) : COLUMN with type t = C.t = struct type t = C.t let column_type = "bytea" let encode v = PGOCaml.string_of_bytea @@ Marshal.to_string v [] let decode v = Marshal.from_string (PGOCaml.bytea_of_string v) 0 end end end module Polymorphic = Ocsipersist_lib.Polymorphic (Functorial) type 'value table = 'value Polymorphic.table module Store = struct type store = string type 'a t = {store : string; name : string} let open_store store = use_pool @@ fun db -> let create_table db table = let query = sprintf "CREATE TABLE IF NOT EXISTS %s (key TEXT, value BYTEA, PRIMARY KEY(key))" table in exec_ db query [] in create_table db store >> Lwt.return store let make_persistent_worker ~store ~name ~default db = let query = sprintf "INSERT INTO %s VALUES ( $1 , $2 ) ON CONFLICT ( key ) DO NOTHING" store in (* NOTE: incompatible with < 9.5 *) exec_ db query [Key name; Value default] >> Lwt.return {store; name} let make_persistent ~store ~name ~default = use_pool @@ fun db -> make_persistent_worker ~store ~name ~default db let make_persistent_lazy_lwt ~store ~name ~default = use_pool @@ fun db -> let query = sprintf "SELECT 1 FROM %s WHERE key = $1 " store in exec db query [Key name] >>= function | [] -> default () >>= fun default -> make_persistent_worker ~store ~name ~default db | _ -> Lwt.return {store; name} let make_persistent_lazy ~store ~name ~default = let default () = Lwt.wrap default in make_persistent_lazy_lwt ~store ~name ~default let get p = use_pool @@ fun db -> let query = sprintf "SELECT value FROM %s WHERE key = $1 " p.store in Lwt.map one_value (exec db query [Key p.name]) let set p v = use_pool @@ fun db -> let query = sprintf "UPDATE %s SET value = $2 WHERE key = $1 " p.store in exec db query [Key p.name; Value v] >> Lwt.return () end type store = Store.store type 'a variable = 'a Store.t module Registration = struct let parse_global_config = function | [] -> () | [Xml.Element ("database", attrs, [])] -> let parse_attr = function | "host", h -> Config.host := Some h | "port", p -> ( try Config.port := Some (int_of_string p) with Failure _ -> raise @@ Ocsigen_extensions.Error_in_config_file "port is not an integer") | "user", u -> Config.user := Some u | "password", pw -> Config.password := Some pw | "database", db -> Config.database := db | "unix_domain_socket_dir", udsd -> Config.unix_domain_socket_dir := Some udsd | "size_conn_pool", scp -> ( try Config.size_conn_pool := int_of_string scp with Failure _ -> raise @@ Ocsigen_extensions.Error_in_config_file "size_conn_pool is not an integer") | _ -> raise @@ Ocsigen_extensions.Error_in_config_file "Unexpected attribute for in Ocsipersist config" in ignore @@ List.map parse_attr attrs; () | _ -> raise @@ Ocsigen_extensions.Error_in_config_file "Unexpected content inside Ocsipersist config" let init_fun config = parse_global_config config; conn_pool := Lwt_pool.create !Config.size_conn_pool ~validate:PGOCaml.alive connect let _ = Ocsigen_extensions.register ~name:"ocsipersist" ~init_fun () end ocsipersist-1.1.0/src/sqlite/000077500000000000000000000000001417355140700161575ustar00rootroot00000000000000ocsipersist-1.1.0/src/sqlite/dune000066400000000000000000000003641417355140700170400ustar00rootroot00000000000000(library (name ocsipersist_sqlite) (public_name ocsipersist.sqlite) (implements ocsipersist) (libraries sqlite3 lwt_log xml-light ocsigenserver ocsipersist_lib) (optional)) (documentation (package ocsipersist-sqlite) (mld_files index)) ocsipersist-1.1.0/src/sqlite/index.mld000066400000000000000000000004661417355140700177720ustar00rootroot00000000000000{0 ocsipersist-sqlite} For the API documentation see OPAM package [ocsipersist]. Here we document the configuration options of the ocsigenserver extension. All sub-tags of the [extension] tag are optional. {[ ]} ocsipersist-1.1.0/src/sqlite/ocsipersist.ml000066400000000000000000000325721417355140700210710ustar00rootroot00000000000000module type TABLE = Ocsipersist_lib.Sigs.TABLE let section = Lwt_log.Section.make "ocsigen:ocsipersist:sqlite" open Lwt.Infix open Sqlite3 open Printf module Aux = struct (* This reference is overwritten when the init function (at the end of the file) is run, which occurs when the extension is loaded *) let db_file = ref (Ocsigen_config.get_datadir () ^ "/ocsidb") let yield () = Thread.yield () let rec bind_safely stmt = function | [] -> stmt | (value, name) :: q as l -> ( match Sqlite3.bind stmt (bind_parameter_index stmt name) value with | Rc.OK -> bind_safely stmt q | Rc.BUSY | Rc.LOCKED -> yield (); bind_safely stmt l | rc -> ignore (finalize stmt); failwith (Rc.to_string rc)) let close_safely db = if not (db_close db) then Lwt_log.ign_error ~section "Couldn't close database" let m = Mutex.create () let exec_safely f = let aux () = let db = Mutex.lock m; try db_open !db_file with e -> Mutex.unlock m; raise e in try let r = f db in close_safely db; Mutex.unlock m; r with e -> close_safely db; Mutex.unlock m; raise e in Lwt_preemptive.detach aux () (* Référence indispensable pour les codes de retours et leur signification : * http://sqlite.org/capi3ref.html * Langage compris par SQLite : http://www.sqlite.org/lang.html *) let db_create table = let sql = sprintf "CREATE TABLE IF NOT EXISTS %s (key TEXT, value BLOB, PRIMARY KEY(key) ON CONFLICT REPLACE)" table in let create db = let stmt = prepare db sql in let rec aux () = match step stmt with | Rc.DONE -> ignore (finalize stmt) | Rc.BUSY | Rc.LOCKED -> yield (); aux () | rc -> ignore (finalize stmt); failwith (Rc.to_string rc) in aux () in exec_safely create >>= fun () -> Lwt.return table let db_get, db_replace = let get (table, key) db = let sqlget = sprintf "SELECT value FROM %s WHERE key = :key " table in let stmt = bind_safely (prepare db sqlget) [Data.TEXT key, ":key"] in let rec aux () = match step stmt with | Rc.ROW -> let value = match column stmt 0 with Data.BLOB s -> s | _ -> assert false in ignore (finalize stmt); value | Rc.DONE -> ignore (finalize stmt); raise Not_found | Rc.BUSY | Rc.LOCKED -> yield (); aux () | rc -> ignore (finalize stmt); failwith (Rc.to_string rc) in aux () in let replace (table, key) value db = let sqlreplace = sprintf "INSERT INTO %s VALUES ( :key , :value )" table in let stmt = bind_safely (prepare db sqlreplace) [Data.TEXT key, ":key"; Data.BLOB value, ":value"] in let rec aux () = match step stmt with | Rc.DONE -> ignore (finalize stmt) | Rc.BUSY | Rc.LOCKED -> yield (); aux () | rc -> ignore (finalize stmt); failwith (Rc.to_string rc) in aux () in ( (fun tablekey -> exec_safely (get tablekey)) , fun tablekey value -> exec_safely (replace tablekey value) ) end module Store = struct type store = string type 'a t = store * string let open_store name = let s = "store___" ^ name in Aux.db_create s let make_persistent_lazy_lwt ~store ~name ~default = let pvname = store, name in Lwt.catch (fun () -> Aux.db_get pvname >>= fun _ -> Lwt.return ()) (function | Not_found -> default () >>= fun def -> Aux.db_replace pvname (Marshal.to_string def []) | e -> Lwt.fail e) >>= fun () -> Lwt.return pvname let make_persistent_lazy ~store ~name ~default = let default () = Lwt.wrap default in make_persistent_lazy_lwt ~store ~name ~default let make_persistent ~store ~name ~default = make_persistent_lazy ~store ~name ~default:(fun () -> default) let get (pvname : 'a t) : 'a = Aux.db_get pvname >>= fun r -> Lwt.return (Marshal.from_string r 0) let set pvname v = let data = Marshal.to_string v [] in Aux.db_replace pvname data end type store = Store.store type 'a variable = 'a Store.t module Functorial = struct type internal = Data.t module type COLUMN = sig type t val column_type : string val encode : t -> internal val decode : internal -> t end module Table (T : sig val name : string end) (Key : COLUMN) (Value : COLUMN) : Ocsipersist_lib.Sigs.TABLE with type key = Key.t and type value = Value.t = struct type key = Key.t type value = Value.t let name = "store___" ^ T.name let init = let create db = let sql = sprintf "CREATE TABLE IF NOT EXISTS %s (key %s, value %s, PRIMARY KEY (key) ON CONFLICT REPLACE)" name Key.column_type Value.column_type in let stmt = prepare db sql in let rec aux () = match step stmt with | Rc.DONE -> ignore (finalize stmt) | Rc.BUSY | Rc.LOCKED -> Aux.yield (); aux () | rc -> ignore (finalize stmt); failwith (Rc.to_string rc) in aux () in lazy (Aux.exec_safely create) let with_table f = Lazy.force init >>= fun () -> Aux.exec_safely f let db_get key db = let sqlget = sprintf "SELECT value FROM %s WHERE key = :key" name in let stmt = Aux.bind_safely (prepare db sqlget) [Key.encode key, ":key"] in let rec aux () = match step stmt with | Rc.ROW -> let value = column stmt 0 in ignore (finalize stmt); value | Rc.DONE -> ignore (finalize stmt); raise Not_found | Rc.BUSY | Rc.LOCKED -> Aux.yield (); aux () | rc -> ignore (finalize stmt); failwith (Rc.to_string rc) in Value.decode @@ aux () let db_replace key value db = let sqlreplace = sprintf "INSERT INTO %s VALUES (:key, :value)" name in let stmt = Aux.bind_safely (prepare db sqlreplace) [Key.encode key, ":key"; Value.encode value, ":value"] in let rec aux () = match step stmt with | Rc.DONE -> ignore (finalize stmt) | Rc.BUSY | Rc.LOCKED -> Aux.yield (); aux () | rc -> ignore (finalize stmt); failwith (Rc.to_string rc) in aux () let db_remove key db = let sql = sprintf "DELETE FROM %s WHERE key = :key " name in let stmt = Aux.bind_safely (prepare db sql) [Key.encode key, ":key"] in let rec aux () = match step stmt with | Rc.DONE -> ignore (finalize stmt) | Rc.BUSY | Rc.LOCKED -> Aux.yield (); aux () | rc -> ignore (finalize stmt); failwith (Rc.to_string rc) in aux () let db_length table db = let sql = sprintf "SELECT count (1) FROM %s " table in let stmt = prepare db sql in let rec aux () = match step stmt with | Rc.ROW -> let value = match column stmt 0 with | Data.INT s -> Int64.to_int s | _ -> assert false in ignore (finalize stmt); value | Rc.DONE -> ignore (finalize stmt); raise Not_found | Rc.BUSY | Rc.LOCKED -> Aux.yield (); aux () | rc -> ignore (finalize stmt); failwith (Rc.to_string rc) in aux () let db_iter ?gt ?geq ?lt ?leq table rowid db = let sql = sprintf "SELECT key, value, ROWID FROM %s WHERE ROWID > :rowid AND coalesce (key > :gt, true) AND coalesce (key >= :geq, true) AND coalesce (key < :lt, true) AND coalesce (key <= :leq, true)" table in let encode_key_opt = function | Some k -> Key.encode k | None -> Data.NULL in let gt_sql = encode_key_opt gt and geq_sql = encode_key_opt geq and lt_sql = encode_key_opt lt and leq_sql = encode_key_opt leq in let stmt = Aux.bind_safely (prepare db sql) [ Data.INT rowid, ":rowid" ; gt_sql, ":gt" ; geq_sql, ":geq" ; lt_sql, ":lt" ; leq_sql, ":leq" ] in let rec aux () = match step stmt with | Rc.ROW -> ( match column stmt 0, column stmt 1, column stmt 2 with | k, v, Data.INT rowid -> ignore (finalize stmt); Some (k, v, rowid) | _ -> assert false) | Rc.DONE -> ignore (finalize stmt); None | Rc.BUSY | Rc.LOCKED -> Aux.yield (); aux () | rc -> ignore (finalize stmt); failwith (Rc.to_string rc) in aux () let find k = with_table @@ db_get k let add k v = with_table @@ db_replace k v let replace_if_exists k v = with_table @@ fun db -> ignore (db_get k db); db_replace k v db let remove key = with_table @@ db_remove key let modify_opt key f = with_table @@ fun db -> let old_value = try Some (db_get key db) with Not_found -> None in match f old_value with | Some new_value -> db_replace key new_value db | None -> db_remove key db let fold ?count ?gt ?geq ?lt ?leq f beg = let i = ref 0L in let rec aux rowid beg = match count with | Some c when !i >= c -> Lwt.return beg | _ -> ( i := Int64.succ !i; with_table (db_iter ?gt ?geq ?lt ?leq name rowid) >>= function | None -> Lwt.return beg | Some (k, v, rowid') -> f (Key.decode k) (Value.decode v) beg >>= aux rowid') in aux Int64.zero beg let iter ?count ?gt ?geq ?lt ?leq f = fold ?count ?gt ?geq ?lt ?leq (fun k v () -> f k v) () let iter_batch ?count:_ ?gt:_ ?geq:_ ?lt:_ ?leq:_ _ = failwith "Ocsipersist.iter_batch not implemented for SQLite" let iter_block ?count ?gt ?geq ?lt ?leq f = let sql = sprintf "SELECT key, value FROM %s WHERE coalesce (key > :gt, true) AND coalesce (key >= :geq, true) AND coalesce (key < :lt, true) AND coalesce (key <= :leq, true) LIMIT coalesce (:count, -1)" name in let encode_key_opt = function | Some k -> Key.encode k | None -> Data.NULL in let gt_sql = encode_key_opt gt and geq_sql = encode_key_opt geq and lt_sql = encode_key_opt lt and leq_sql = encode_key_opt leq in let count_sql = match count with Some c -> Data.INT c | None -> Data.NULL in let iter db = let stmt = Aux.bind_safely (prepare db sql) [ gt_sql, ":gt" ; geq_sql, ":geq" ; lt_sql, ":lt" ; leq_sql, ":leq" ; count_sql, ":count" ] in let rec aux () = match step stmt with | Rc.ROW -> f (Key.decode @@ column stmt 0) (Value.decode @@ column stmt 1); aux () | Rc.DONE -> ignore (finalize stmt) | Rc.BUSY | Rc.LOCKED -> Aux.yield (); aux () | rc -> ignore (finalize stmt); failwith (Rc.to_string rc) in aux () in with_table iter let length () = with_table @@ db_length name module Variable = Ocsipersist_lib.Variable (struct type k = key type v = value let find = find let add = add end) end module Column = struct module String : COLUMN with type t = string = struct type t = string let column_type = "text" let encode s = Data.TEXT s let decode = function Data.TEXT f -> f | _ -> assert false end module Float : COLUMN with type t = float = struct type t = float let column_type = "float" let encode f = Data.FLOAT f let decode = function Data.FLOAT f -> f | _ -> assert false end module Marshal (C : sig type t end) : COLUMN with type t = C.t = struct type t = C.t let column_type = "blob" let encode v = Data.BLOB (Marshal.to_string v []) let decode = function | Data.BLOB v -> Marshal.from_string v 0 | _ -> assert false end end end module Polymorphic = Ocsipersist_lib.Polymorphic (Functorial) type 'value table = 'value Polymorphic.table module Registration = struct let parse_global_config = function | [] -> None | [Xml.Element ("database", [("file", s)], [])] -> Some s | _ -> raise (Ocsigen_extensions.Error_in_config_file "Unexpected content inside Ocsipersist config") let init config = Aux.db_file := Ocsigen_config.get_datadir () ^ "/ocsidb"; (match parse_global_config config with | None -> () | Some d -> Aux.db_file := d); (* We check that we can access the database *) try Lwt_main.run (Aux.exec_safely (fun _ -> ())) with e -> Ocsigen_messages.errlog (Printf.sprintf "Error opening database file '%s' when registering Ocsipersist. Check that the directory exists, and that Ocsigen has enough rights" !Aux.db_file); raise e let _ = Ocsigen_extensions.register ~name:"ocsipersist" ~init_fun:init () end