Catmandu-Store-MongoDB-0.0802000755001750001750 013427316535 16532 5ustar00nsteenlansteenla000000000000README100644001750001750 1313413427316535 17515 0ustar00nsteenlansteenla000000000000Catmandu-Store-MongoDB-0.0802NAME Catmandu::Store::MongoDB - A searchable store backed by MongoDB SYNOPSIS # On the command line $ catmandu import -v JSON --multiline 1 to MongoDB --database_name bibliography --bag books < books.json $ catmandu export MongoDB --database_name bibliography --bag books to YAML $ catmandu count MongoDB --database_name bibliography --bag books --query '{"PublicationYear": "1937"}' # In perl use Catmandu::Store::MongoDB; my $store = Catmandu::Store::MongoDB->new(database_name => 'test'); my $obj1 = $store->bag->add({ name => 'Patrick' }); printf "obj1 stored as %s\n" , $obj1->{_id}; # Force an id in the store my $obj2 = $store->bag->add({ _id => 'test123' , name => 'Nicolas' }); my $obj3 = $store->bag->get('test123'); $store->bag->delete('test123'); $store->bag->delete_all; # All bags are iterators $store->bag->each(sub { ... }); $store->bag->take(10)->each(sub { ... }); # Search my $hits = $store->bag->search(query => '{"name":"Patrick"}'); my $hits = $store->bag->search(query => '{"name":"Patrick"}' , sort => { age => -1} ); my $hits = $store->bag->search(query => {name => "Patrick"} , start => 0 , limit => 100); my $hits = $store->bag->search(query => {name => "Patrick"} , fields => {_id => 0, name => 1}); my $next_page = $hits->next_page; my $hits = $store->bag->search(query => '{"name":"Patrick"}' , page => $next_page); my $iterator = $store->bag->searcher(query => {name => "Patrick"}); my $iterator = $store->bag->searcher(query => {name => "Patrick"}, fields => {_id => 0, name => 1}); # Catmandu::Store::MongoDB supports CQL... my $hits = $store->bag->search(cql_query => 'name any "Patrick"'); DESCRIPTION A Catmandu::Store::MongoDB is a Perl package that can store data into MongoDB databases. The database as a whole is called a 'store'. Databases also have compartments (e.g. tables) called Catmandu::Bag-s. METHODS new(database_name => $name, %connection_opts) new(database_name => $name , bags => { data => { cql_mapping => $cql_mapping } }) Create a new Catmandu::Store::MongoDB store with name $name. Optionally provide connection parameters (see MongoDB::MongoClient for possible options). The store supports CQL searches when a cql_mapping is provided. This hash contains a translation of CQL fields into MongoDB searchable fields. # Example mapping $cql_mapping = { indexes => { title => { op => { 'any' => 1 , 'all' => 1 , '=' => 1 , '<>' => 1 , 'exact' => {field => [qw(mytitle.exact myalttitle.exact)]} } , sort => 1, field => 'mytitle', cb => ['Biblio::Search', 'normalize_title'] } } } The CQL mapping above will support for the 'title' field the CQL operators: any, all, =, <> and exact. The 'title' field will be mapped into the MongoDB field 'mytitle', except for the 'exact' operator. In case of 'exact' both the 'mytitle.exact' and 'myalttitle.exact' fields will be searched. The CQL mapping allows for sorting on the 'title' field. If, for instance, we would like to use a special MongoDB field for sorting we could have written "sort => { field => 'mytitle.sort' }". The CQL has an optional callback field 'cb' which contains a reference to subroutines to rewrite or augment the search query. In this case, in the Biblio::Search package contains a normalize_title subroutine which returns a string or an ARRAY of string with augmented title(s). E.g. package Biblio::Search; sub normalize_title { my ($self,$title) = @_; # delete all bad characters my $new_title =~ s{[^A-Z0-9]+}{}g; $new_title; } 1; bag($name) Create or retieve a bag with name $name. Returns a Catmandu::Bag. client Return the MongoDB::MongoClient instance. database Return a MongoDB::Database instance. drop Delete the store and all it's bags. transaction(\&sub) Execute $sub within a transaction. See Catmandu::Transactional. Note that only MongoDB databases with feature compatibility >= 4.0 and in a replica set have support for transactions. See https://docs.mongodb.com/manual/reference/command/setFeatureCompatibilityVersion/#view-fcv and https://docs.mongodb.com/manual/tutorial/convert-standalone-to-replica-set/ for more info. Search Search the database: see Catmandu::Searchable and Catmandu::CQLSearchable. This module supports an additional search parameter: - fields => { => <0|1> } : limit fields to return from a query (see L) SEE ALSO Catmandu::Bag, Catmandu::CQLSearchable, Catmandu::Droppable, Catmandu::Transactional, MongoDB::MongoClient AUTHOR Nicolas Steenlant, CONTRIBUTORS Johann Rolschewski, LICENSE AND COPYRIGHT This program is free software; you can redistribute it and/or modify it under the terms of either: the GNU General Public License as published by the Free Software Foundation; or the Artistic License. See http://dev.perl.org/licenses/ for more information. Changes100644001750001750 257113427316535 20113 0ustar00nsteenlansteenla000000000000Catmandu-Store-MongoDB-0.0802Revision history for Catmandu-Store-MongoDB 0.0802 2019-02-08 16:16:42 CET - transaction method is now list/scalar context aware 0.0801 2019-02-08 14:01:49 CET - fix bug in get method 0.08 2019-02-05 15:44:53 CET - support for MongoDB 4.0 transactions 0.0701 2019-01-18 15:04:24 CET - use count_documents instead of deprecated count method 0.07 2017-03-23 14:38:15 CET - use the new Catmandu::CQLSearchable role 0.06 2017-01-13 14:02:30 CET - remove deprecated options - replace deprecated driver method calls 0.0501 2016-12-21 08:23:49 CET - add missing dependency 0.05 2016-12-20 11:03:10 CET - CQL support - new fields option 0.0403 2016-01-12 10:36:31 CET - drop support 0.0402 2015-09-30 10:08:35 CEST - fix MongoDBTest 0.0401 2015-09-29 10:04:42 CEST - require JSON::MaybeXS 0.04 2015-09-22 11:05:30 CEST - MongoDB 1.0.0 driver support 0.0303 2014-10-17 14:20:13 CEST - use Dist::Milla - retry reconnect option 0.0302 2014-04-25 - more pod - more tests 0.0301 2013-04-22 - fix Bag delete_by_query 0.03 2013-04-19 - Searcher support 0.0202 2013-02-26 - import confess 0.0201 2013-02-07 - fix manifest 0.02 2013-02-07 - many optimized versions of the Iterable methods - basic search support (no CQL support, no Searcher) 0.0101 2012-05-29 - safe save and delete 0.01 2012-05-04 - initial release LICENSE100644001750001750 4367413427316535 17656 0ustar00nsteenlansteenla000000000000Catmandu-Store-MongoDB-0.0802This software is copyright (c) 2019 by Nicolas Steenlant. This is free software; you can redistribute it and/or modify it under the same terms as the Perl 5 programming language system itself. Terms of the Perl programming language system itself a) the GNU General Public License as published by the Free Software Foundation; either version 1, or (at your option) any later version, or b) the "Artistic License" --- The GNU General Public License, Version 1, February 1989 --- This software is Copyright (c) 2019 by Nicolas Steenlant. This is free software, licensed under: The GNU General Public License, Version 1, February 1989 GNU GENERAL PUBLIC LICENSE Version 1, February 1989 Copyright (C) 1989 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. Preamble The license agreements of most software companies try to keep users at the mercy of those companies. By contrast, our General Public License is intended to guarantee your freedom to share and change free software--to make sure the software is free for all its users. The General Public License applies to the Free Software Foundation's software and to any other program whose authors commit to using it. You can use it for your programs, too. When we speak of free software, we are referring to freedom, not price. Specifically, the General Public License is designed to make sure that you have the freedom to give away or sell copies of free software, that you receive source code or can get it if you want it, that you can change the software or use pieces of it in new free programs; and that you know you can do these things. To protect your rights, we need to make restrictions that forbid anyone to deny you these rights or to ask you to surrender the rights. These restrictions translate to certain responsibilities for you if you distribute copies of the software, or if you modify it. For example, if you distribute copies of a such a program, whether gratis or for a fee, you must give the recipients all the rights that you have. You must make sure that they, too, receive or can get the source code. And you must tell them their rights. We protect your rights with two steps: (1) copyright the software, and (2) offer you this license which gives you legal permission to copy, distribute and/or modify the software. Also, for each author's protection and ours, we want to make certain that everyone understands that there is no warranty for this free software. If the software is modified by someone else and passed on, we want its recipients to know that what they have is not the original, so that any problems introduced by others will not reflect on the original authors' reputations. The precise terms and conditions for copying, distribution and modification follow. GNU GENERAL PUBLIC LICENSE TERMS AND CONDITIONS FOR COPYING, DISTRIBUTION AND MODIFICATION 0. This License Agreement applies to any program or other work which contains a notice placed by the copyright holder saying it may be distributed under the terms of this General Public License. The "Program", below, refers to any such program or work, and a "work based on the Program" means either the Program or any work containing the Program or a portion of it, either verbatim or with modifications. Each licensee is addressed as "you". 1. You may copy and distribute verbatim copies of the Program's 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 General Public License and to the absence of any warranty; and give any other recipients of the Program a copy of this General Public License along with the Program. You may charge a fee for the physical act of transferring a copy. 2. You may modify your copy or copies of the Program or any portion of it, and copy and distribute such modifications under the terms of Paragraph 1 above, provided that you also do the following: a) cause the modified files to carry prominent notices stating that you changed the files and the date of any change; and b) cause the whole of any work that you distribute or publish, that in whole or in part contains the Program or any part thereof, either with or without modifications, to be licensed at no charge to all third parties under the terms of this General Public License (except that you may choose to grant warranty protection to some or all third parties, at your option). c) If the modified program normally reads commands interactively when run, you must cause it, when started running for such interactive use in the simplest and most usual way, to print or display an announcement including an appropriate copyright notice and a notice that there is no warranty (or else, saying that you provide a warranty) and that users may redistribute the program under these conditions, and telling the user how to view a copy of this General Public License. d) 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. Mere aggregation of another independent work with the Program (or its derivative) on a volume of a storage or distribution medium does not bring the other work under the scope of these terms. 3. You may copy and distribute the Program (or a portion or derivative of it, under Paragraph 2) in object code or executable form under the terms of Paragraphs 1 and 2 above provided that you also do one of the following: a) accompany it with the complete corresponding machine-readable source code, which must be distributed under the terms of Paragraphs 1 and 2 above; or, b) accompany it with a written offer, valid for at least three years, to give any third party free (except for a nominal charge for the cost of distribution) a complete machine-readable copy of the corresponding source code, to be distributed under the terms of Paragraphs 1 and 2 above; or, c) accompany it with the information you received as to where the corresponding source code may be obtained. (This alternative is allowed only for noncommercial distribution and only if you received the program in object code or executable form alone.) Source code for a work means the preferred form of the work for making modifications to it. For an executable file, complete source code means all the source code for all modules it contains; but, as a special exception, it need not include source code for modules which are standard libraries that accompany the operating system on which the executable file runs, or for standard header files or definitions files that accompany that operating system. 4. You may not copy, modify, sublicense, distribute or transfer the Program except as expressly provided under this General Public License. Any attempt otherwise to copy, modify, sublicense, distribute or transfer the Program is void, and will automatically terminate your rights to use the Program under this License. However, parties who have received copies, or rights to use copies, from you under this General Public License will not have their licenses terminated so long as such parties remain in full compliance. 5. By copying, distributing or modifying the Program (or any work based on the Program) you indicate your acceptance of this license to do so, and all its terms and conditions. 6. Each time you redistribute the Program (or any work based on the Program), the recipient automatically receives a license from the original licensor to copy, distribute or modify the Program subject to these terms and conditions. You may not impose any further restrictions on the recipients' exercise of the rights granted herein. 7. The Free Software Foundation may publish revised and/or new versions of the 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 Program specifies a version number of the 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 Program does not specify a version number of the license, you may choose any version ever published by the Free Software Foundation. 8. If you wish to incorporate parts of the Program into other free programs whose distribution conditions are different, 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 9. BECAUSE THE PROGRAM IS LICENSED FREE OF CHARGE, THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "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 PROGRAM IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF ALL NECESSARY SERVICING, REPAIR OR CORRECTION. 10. 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 PROGRAM 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 PROGRAM (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 PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS), EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGES. END OF TERMS AND CONDITIONS Appendix: How to Apply These Terms to Your New Programs If you develop a new program, and you want it to be of the greatest possible use to humanity, the best way to achieve this is to make it free software which everyone can redistribute and change under these terms. To do so, attach the following notices to the program. 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) 19yy This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 1, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; 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. If the program is interactive, make it output a short notice like this when it starts in an interactive mode: Gnomovision version 69, Copyright (C) 19xx name of author Gnomovision comes with ABSOLUTELY NO WARRANTY; for details type `show w'. This is free software, and you are welcome to redistribute it under certain conditions; type `show c' for details. The hypothetical commands `show w' and `show c' should show the appropriate parts of the General Public License. Of course, the commands you use may be called something other than `show w' and `show c'; they could even be mouse-clicks or menu items--whatever suits your program. You should also get your employer (if you work as a programmer) or your school, if any, to sign a "copyright disclaimer" for the program, if necessary. Here a sample; alter the names: Yoyodyne, Inc., hereby disclaims all copyright interest in the program `Gnomovision' (a program to direct compilers to make passes at assemblers) written by James Hacker. , 1 April 1989 Ty Coon, President of Vice That's all there is to it! --- The Artistic License 1.0 --- This software is Copyright (c) 2019 by Nicolas Steenlant. This is free software, licensed under: The Artistic License 1.0 The Artistic License Preamble The intent of this document is to state the conditions under which a Package may be copied, such that the Copyright Holder maintains some semblance of artistic control over the development of the package, while giving the users of the package the right to use and distribute the Package in a more-or-less customary fashion, plus the right to make reasonable modifications. Definitions: - "Package" refers to the collection of files distributed by the Copyright Holder, and derivatives of that collection of files created through textual modification. - "Standard Version" refers to such a Package if it has not been modified, or has been modified in accordance with the wishes of the Copyright Holder. - "Copyright Holder" is whoever is named in the copyright or copyrights for the package. - "You" is you, if you're thinking about copying or distributing this Package. - "Reasonable copying fee" is whatever you can justify on the basis of media cost, duplication charges, time of people involved, and so on. (You will not be required to justify it to the Copyright Holder, but only to the computing community at large as a market that must bear the fee.) - "Freely Available" means that no fee is charged for the item itself, though there may be fees involved in handling the item. It also means that recipients of the item may redistribute it under the same conditions they received it. 1. You may make and give away verbatim copies of the source form of the Standard Version of this Package without restriction, provided that you duplicate all of the original copyright notices and associated disclaimers. 2. You may apply bug fixes, portability fixes and other modifications derived from the Public Domain or from the Copyright Holder. A Package modified in such a way shall still be considered the Standard Version. 3. You may otherwise modify your copy of this Package in any way, provided that you insert a prominent notice in each changed file stating how and when you changed that file, and provided that you do at least ONE of the following: a) place your modifications in the Public Domain or otherwise make them Freely Available, such as by posting said modifications to Usenet or an equivalent medium, or placing the modifications on a major archive site such as ftp.uu.net, or by allowing the Copyright Holder to include your modifications in the Standard Version of the Package. b) use the modified Package only within your corporation or organization. c) rename any non-standard executables so the names do not conflict with standard executables, which must also be provided, and provide a separate manual page for each non-standard executable that clearly documents how it differs from the Standard Version. d) make other distribution arrangements with the Copyright Holder. 4. You may distribute the programs of this Package in object code or executable form, provided that you do at least ONE of the following: a) distribute a Standard Version of the executables and library files, together with instructions (in the manual page or equivalent) on where to get the Standard Version. b) accompany the distribution with the machine-readable source of the Package with your modifications. c) accompany any non-standard executables with their corresponding Standard Version executables, giving the non-standard executables non-standard names, and clearly documenting the differences in manual pages (or equivalent), together with instructions on where to get the Standard Version. d) make other distribution arrangements with the Copyright Holder. 5. You may charge a reasonable copying fee for any distribution of this Package. You may charge any fee you choose for support of this Package. You may not charge a fee for this Package itself. However, you may distribute this Package in aggregate with other (possibly commercial) programs as part of a larger (possibly commercial) software distribution provided that you do not advertise this Package as a product of your own. 6. The scripts and library files supplied as input to or produced as output from the programs of this Package do not automatically fall under the copyright of this Package, but belong to whomever generated them, and may be sold commercially, and may be aggregated with this Package. 7. C or perl subroutines supplied by you and linked into this Package shall not be considered part of this Package. 8. The name of the Copyright Holder may not be used to endorse or promote products derived from this software without specific prior written permission. 9. THIS PACKAGE IS PROVIDED "AS IS" AND WITHOUT ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, WITHOUT LIMITATION, THE IMPLIED WARRANTIES OF MERCHANTIBILITY AND FITNESS FOR A PARTICULAR PURPOSE. The End cpanfile100644001750001750 64213427316535 20301 0ustar00nsteenlansteenla000000000000Catmandu-Store-MongoDB-0.0802requires 'perl', 'v5.10.1'; on 'test', sub { requires 'Test::Exception', '0.32'; requires 'Test::More', '1.001003'; requires 'Test::Warn', 0; requires 'Test::Pod', 0; requires 'Software::License','0.103010'; }; requires 'Catmandu', '>=1.04'; requires 'CQL::Parser', '1.12'; requires 'Cpanel::JSON::XS', '3.0213'; requires 'MongoDB', '1.6.1'; requires 'Moo','1.006000'; requires 'namespace::clean', '0.24'; dist.ini100644001750001750 12213427316535 20232 0ustar00nsteenlansteenla000000000000Catmandu-Store-MongoDB-0.0802name = Catmandu-Store-MongoDB [@Milla] installer = ModuleBuild [ExecDir] dir = binBuild.PL100644001750001750 267413427316535 20120 0ustar00nsteenlansteenla000000000000Catmandu-Store-MongoDB-0.0802 # This file was automatically generated by Dist::Zilla::Plugin::ModuleBuild v6.012. use strict; use warnings; use Module::Build 0.28; my %module_build_args = ( "build_requires" => { "Module::Build" => "0.28" }, "configure_requires" => { "Module::Build" => "0.28" }, "dist_abstract" => "A searchable store backed by MongoDB", "dist_author" => [ "Nicolas Steenlant, C<< >>" ], "dist_name" => "Catmandu-Store-MongoDB", "dist_version" => "0.0802", "license" => "perl", "module_name" => "Catmandu::Store::MongoDB", "recursive_test_files" => 1, "requires" => { "CQL::Parser" => "1.12", "Catmandu" => "1.04", "Cpanel::JSON::XS" => "3.0213", "MongoDB" => "v1.6.1", "Moo" => "1.006000", "namespace::clean" => "0.24", "perl" => "v5.10.1" }, "test_requires" => { "Software::License" => "0.103010", "Test::Exception" => "0.32", "Test::More" => "1.001003", "Test::Pod" => 0, "Test::Warn" => 0 } ); my %fallback_build_requires = ( "Module::Build" => "0.28", "Software::License" => "0.103010", "Test::Exception" => "0.32", "Test::More" => "1.001003", "Test::Pod" => 0, "Test::Warn" => 0 ); unless ( eval { Module::Build->VERSION(0.4004) } ) { delete $module_build_args{test_requires}; $module_build_args{build_requires} = \%fallback_build_requires; } my $build = Module::Build->new(%module_build_args); $build->create_build_script; META.yml100644001750001750 263713427316535 20074 0ustar00nsteenlansteenla000000000000Catmandu-Store-MongoDB-0.0802--- abstract: 'A searchable store backed by MongoDB' author: - 'Nicolas Steenlant, C<< >>' build_requires: Module::Build: '0.28' Software::License: '0.103010' Test::Exception: '0.32' Test::More: '1.001003' Test::Pod: '0' Test::Warn: '0' configure_requires: Module::Build: '0.28' dynamic_config: 0 generated_by: 'Dist::Milla version v1.0.20, Dist::Zilla version 6.012, CPAN::Meta::Converter version 2.150010' license: perl meta-spec: url: http://module-build.sourceforge.net/META-spec-v1.4.html version: '1.4' name: Catmandu-Store-MongoDB no_index: directory: - eg - examples - inc - share - t - xt requires: CQL::Parser: '1.12' Catmandu: '1.04' Cpanel::JSON::XS: '3.0213' MongoDB: v1.6.1 Moo: '1.006000' namespace::clean: '0.24' perl: v5.10.1 resources: bugtracker: https://github.com/LibreCat/Catmandu-Store-MongoDB/issues homepage: https://github.com/LibreCat/Catmandu-Store-MongoDB repository: https://github.com/LibreCat/Catmandu-Store-MongoDB.git version: '0.0802' x_contributors: - 'Johann Rolschewski ' - 'Nicolas Franck ' - 'Nicolas Steenlant ' - 'Nicolas Steenlant ' - 'Patrick Hochstenbach ' x_generated_by_perl: v5.28.1 x_serialization_backend: 'YAML::Tiny version 1.73' x_static_install: 0 MANIFEST100644001750001750 61513427316535 17726 0ustar00nsteenlansteenla000000000000Catmandu-Store-MongoDB-0.0802# This file was automatically generated by Dist::Zilla::Plugin::Manifest v6.012. Build.PL Changes LICENSE MANIFEST META.json META.yml README cpanfile dist.ini lib/Catmandu/Store/MongoDB.pm lib/Catmandu/Store/MongoDB/Bag.pm lib/Catmandu/Store/MongoDB/CQL.pm lib/Catmandu/Store/MongoDB/Searcher.pm t/00-load.t t/01-store.t t/02-connect.t t/03-cql-parser.t t/author-pod-syntax.t t/lib/MongoDBTest.pm META.json100644001750001750 461413427316535 20241 0ustar00nsteenlansteenla000000000000Catmandu-Store-MongoDB-0.0802{ "abstract" : "A searchable store backed by MongoDB", "author" : [ "Nicolas Steenlant, C<< >>" ], "dynamic_config" : 0, "generated_by" : "Dist::Milla version v1.0.20, Dist::Zilla version 6.012, CPAN::Meta::Converter version 2.150010", "license" : [ "perl_5" ], "meta-spec" : { "url" : "http://search.cpan.org/perldoc?CPAN::Meta::Spec", "version" : 2 }, "name" : "Catmandu-Store-MongoDB", "no_index" : { "directory" : [ "eg", "examples", "inc", "share", "t", "xt" ] }, "prereqs" : { "build" : { "requires" : { "Module::Build" : "0.28" } }, "configure" : { "requires" : { "Module::Build" : "0.28" } }, "develop" : { "requires" : { "Dist::Milla" : "v1.0.20", "Test::Pod" : "1.41" } }, "runtime" : { "requires" : { "CQL::Parser" : "1.12", "Catmandu" : "1.04", "Cpanel::JSON::XS" : "3.0213", "MongoDB" : "v1.6.1", "Moo" : "1.006000", "namespace::clean" : "0.24", "perl" : "v5.10.1" } }, "test" : { "requires" : { "Software::License" : "0.103010", "Test::Exception" : "0.32", "Test::More" : "1.001003", "Test::Pod" : "0", "Test::Warn" : "0" } } }, "release_status" : "stable", "resources" : { "bugtracker" : { "web" : "https://github.com/LibreCat/Catmandu-Store-MongoDB/issues" }, "homepage" : "https://github.com/LibreCat/Catmandu-Store-MongoDB", "repository" : { "type" : "git", "url" : "https://github.com/LibreCat/Catmandu-Store-MongoDB.git", "web" : "https://github.com/LibreCat/Catmandu-Store-MongoDB" } }, "version" : "0.0802", "x_contributors" : [ "Johann Rolschewski ", "Nicolas Franck ", "Nicolas Steenlant ", "Nicolas Steenlant ", "Patrick Hochstenbach " ], "x_generated_by_perl" : "v5.28.1", "x_serialization_backend" : "Cpanel::JSON::XS version 4.08", "x_static_install" : 0 } t000755001750001750 013427316535 16716 5ustar00nsteenlansteenla000000000000Catmandu-Store-MongoDB-0.080200-load.t100644001750001750 34113427316535 20355 0ustar00nsteenlansteenla000000000000Catmandu-Store-MongoDB-0.0802/t#!/usr/bin/env perl use strict; use warnings; use Test::More; my @pkgs = qw( Catmandu::Store::MongoDB Catmandu::Store::MongoDB::Bag Catmandu::Store::MongoDB::Searcher ); require_ok $_ for @pkgs; done_testing; 01-store.t100644001750001750 213713427316535 20620 0ustar00nsteenlansteenla000000000000Catmandu-Store-MongoDB-0.0802/tuse strict; use warnings; use lib "t/lib"; use Test::More; use Test::Exception; use Catmandu::Store::MongoDB; use MongoDBTest '$conn'; ok $conn; my $db = $conn->get_database('test_database'); my $store = Catmandu::Store::MongoDB->new(database_name => 'test_database'); ok $store; my $obj1 = $store->bag->add({_id => '123', name => 'Patrick'}); ok $obj1; is $obj1->{_id}, 123; my $obj2 = $store->bag->get('123'); ok $obj2; is_deeply $obj2 , {_id => '123', name => 'Patrick'}; $store->bag->add({_id => '456', name => 'Nicolas'}); is $store->bag->count, 2; is $store->bag->search(query => '{"name":"Nicolas"}')->total, 1; $store->bag->delete('123'); is $store->bag->count, 1; $store->bag->delete_all; is $store->bag->count, 0; my $obj3 = $store->bag->add({_id => '789', char => 'ABC', num => '123'}); is_deeply $store->bag->searcher( query => {char => "ABC"}, fields => {num => 1, _id => 0} )->first, {num => '123'}; is_deeply $store->bag->search(query => {char => "ABC"}, fields => {_id => 1}) ->first, {_id => '789'}; END { if ($db) { $db->drop; } } done_testing; 02-connect.t100644001750001750 67613427316535 21104 0ustar00nsteenlansteenla000000000000Catmandu-Store-MongoDB-0.0802/t#!/usr/bin/env perl use strict; use warnings; use Test::More; use Test::Exception; my @pkgs = qw( Catmandu::Store::MongoDB Catmandu::Store::MongoDB::Bag Catmandu::Store::MongoDB::Searcher ); require_ok $_ for @pkgs; # Connect to a non-existing host my $store = Catmandu->store( 'MongoDB', database_name => 'test', host => 'mongodb://localhost:0' ); dies_ok {$store->first} 'expecting to die'; done_testing; 03-cql-parser.t100644001750001750 1432213427316535 21556 0ustar00nsteenlansteenla000000000000Catmandu-Store-MongoDB-0.0802/tuse strict; use warnings; use Test::More; use Test::Exception; require_ok "Catmandu::Store::MongoDB::CQL"; my $cql_mapping = +{ default_relation => 'exact', default_index => "all", indexes => { subject_1 => {filter => ["lowercase"], op => {'=' => 1}}, subject_2 => {op => {'=' => {filter => ["lowercase"]}}}, subject_3 => {cb => ["T", "filter_subject"], op => {'=' => 1}}, subject_4 => {op => {'=' => {cb => ["T", "filter_subject"]}}}, all => { op => { '=' => 1, 'exact' => 1, '<>' => 1, 'any' => 1, 'all' => 1, within => 1 } }, first_name => { op => { '=' => 1, 'exact' => 1, '<>' => 1, 'any' => 1, 'all' => 1, within => 1 } }, last_name => { field => "ln", op => { '=' => 1, 'exact' => 1, '<>' => {field => "ln2"}, 'any' => 1, 'all' => 1, within => 1 } }, year => { op => { '=' => 1, exact => 1, '<>' => 1, '>' => 1, '<' => 1, '>=' => 1, '<=' => 1, 'within' => 1 } } } }; my $parser; lives_ok( sub { $parser = Catmandu::Store::MongoDB::CQL->new(mapping => $cql_mapping); }, "CQL parser created" ); dies_ok( sub { $parser->parse(qq(first_name < "a")); }, "cql - term query on unpermitted relation must die" ); dies_ok( sub { $parser->parse(qq(my_index = "Nicolas")); }, "cql - term query on unpermitted index must die" ); is_deeply( $parser->parse(qq(first_name = "Nicolas")), {first_name => "Nicolas"}, "cql - term query - relation =" ); #fails for some reason #is_deeply( # $parser->parse(qq(first_name scr "Nicolas")), # { first_name => "Nicolas" }, # "cql - term query - relation scr" #); is_deeply( $parser->parse(qq("Nicolas")), {all => "Nicolas"}, "cql - term query - default index" ); is_deeply( $parser->parse(qq(first_name <> "Nicolas")), {first_name => {'$ne' => "Nicolas"}}, "cql - term query - <>" ); is_deeply( $parser->parse(qq(first_name exact "Nicolas")), {first_name => "Nicolas"}, "cql - term query - exact" ); is_deeply( $parser->parse(qq(first_name any "a b c")), {first_name => {'$in' => [qr(a), qr(b), qr(c)]}}, "cql - term query - any" ); is_deeply( $parser->parse(qq(first_name any "^a b ^c^")), {first_name => {'$in' => [qr(^a), qr(b), qr(^c$)]}}, "cql - term query - any with wildcard" ); is_deeply( $parser->parse(qq(first_name any/cql.unmasked "^a b ^c^")), {first_name => {'$in' => [qr(\^a), qr(b), qr(\^c\^)]}}, "cql - term query - any unmasked" ); is_deeply( $parser->parse(qq(first_name all "a b c")), {first_name => {'$all' => [qr(a), qr(b), qr(c)]}}, "cql - term query - all" ); is_deeply( $parser->parse(qq(first_name all "^a b ^c^")), {first_name => {'$all' => [qr(^a), qr(b), qr(^c$)]}}, "cql - term query - all with wildcard" ); is_deeply( $parser->parse(qq(first_name all/cql.unmasked "^a b ^c^")), {first_name => {'$all' => [qr(\^a), qr(b), qr(\^c\^)]}}, "cql - term query - all unmasked" ); is_deeply( $parser->parse(qq(last_name exact "Franck")), {ln => "Franck"}, "cql - term query - field mapping 1" ); is_deeply( $parser->parse(qq(last_name <> "Franck")), {ln2 => {'$ne' => "Franck"}}, "cql - term query - field mapping 2" ); is_deeply( $parser->parse(qq(year > 2009)), {year => {'$gt' => 2009}}, "cql - term query - >" ); is_deeply( $parser->parse(qq(year < 2009)), {year => {'$lt' => 2009}}, "cql - term query - <" ); is_deeply( $parser->parse(qq(year >= 2009)), {year => {'$gte' => 2009}}, "cql - term query - >=" ); is_deeply( $parser->parse(qq(year <= 2009)), {year => {'$lte' => 2009}}, "cql - term query - <=" ); is_deeply( $parser->parse(qq(year within "2009 2016")), {year => {'$gte' => 2009, '$lte' => "2016"}}, "cql - term query - within" ); is_deeply( $parser->parse(qq(year exact "2009" and first_name = "Nicolas")), {'$and' => [{year => 2009}, {first_name => "Nicolas"}]}, "cql - boolean query - and" ); is_deeply( $parser->parse(qq(year exact "2009" or first_name = "Nicolas")), {'$or' => [{year => 2009}, {first_name => "Nicolas"}]}, "cql - boolean query - or" ); is_deeply( $parser->parse(qq(year exact "2009" not first_name = "Nicolas")), {'$nor' => [{'$and' => [{'first_name' => 'Nicolas'}]}], year => 2009}, "cql - boolean query - not" ); is_deeply( $parser->parse(qq(year exact "2009" not "Nicolas")), {'$nor' => [{'$and' => [{'all' => 'Nicolas'}]}], year => 2009}, "cql - boolean query - not all" ); is_deeply( $parser->parse( qq(year exact "2009" not( first_name = "Nicolas" or last_name = "Franck" )) ), {'$nor' => [{first_name => "Nicolas"}, {ln => "Franck"}], year => 2009}, "cql - boolean query - not boolean or" ); is_deeply( $parser->parse( qq(year exact "2009" not( first_name = "Nicolas" and last_name = "Franck" )) ), { '$nor' => [{'$and' => [{first_name => 'Nicolas'}, {ln => 'Franck'}]}], year => 2009 }, "cql - boolean query - not boolean and" ); is_deeply( $parser->parse(qq(subject_1 = "AIRPLANES")), {subject_1 => "airplanes"}, "cql - filter term field 1" ); is_deeply( $parser->parse(qq(subject_2 = "AIRPLANES")), {subject_2 => "airplanes"}, "cql - filter term field 2" ); is_deeply( $parser->parse(qq(subject_3 = "airplanes")), {subject_3 => "AIRPLANES"}, "cql - cb term field 1" ); is_deeply( $parser->parse(qq(subject_4 = "airplanes")), {subject_4 => "AIRPLANES"}, "cql - cb term field 2" ); done_testing 31; package T; use strict; use warnings; sub filter_subject { uc($_[1]); } 1; lib000755001750001750 013427316535 17464 5ustar00nsteenlansteenla000000000000Catmandu-Store-MongoDB-0.0802/tMongoDBTest.pm100644001750001750 431713427316535 22314 0ustar00nsteenlansteenla000000000000Catmandu-Store-MongoDB-0.0802/t/lib# # Copyright 2009-2013 10gen, Inc. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # package MongoDBTest; use strict; use warnings; use Exporter 'import'; use MongoDB; use Test::More; our @EXPORT_OK = ('$conn'); our $conn; # set up connection if we can BEGIN { eval { my $host = exists $ENV{MONGOD} ? $ENV{MONGOD} : 'localhost'; $conn = MongoDB->connect( $host, { ssl => $ENV{MONGO_SSL}, socket_timeout_ms => 60000, server_selection_timeout_ms => 2000, } ); my $topo = $conn->_topology; $topo->scan_all_servers; my $link; eval {$link = $topo->get_writable_link} or die "couldn't connect"; $conn->get_database("admin")->run_command({serverStatus => 1}) or die "Database has auth enabled\n"; my $server = $link->server; if ( !$ENV{MONGOD} && $topo->type eq 'Single' && $server->type =~ /^RS/) { # direct connection to RS member on default, so add set name # via MONGOD environment variable for subsequent use $ENV{MONGOD} = "mongodb://localhost/?replicaSet=" . $server->set_name; } }; if ($@) { (my $err = $@) =~ s/\n//g; if ($err =~ /couldn't connect|connection refused/i) { $err = "no mongod on " . ($ENV{MONGOD} || "localhost:27017"); $err .= ' and $ENV{MONGOD} not set' unless $ENV{MONGOD}; } plan skip_all => "$err"; exit 0; } } # clean up any detritus from failed tests END { return unless $conn; $conn->get_database('test_database')->drop; } 1; author-pod-syntax.t100644001750001750 45413427316535 22634 0ustar00nsteenlansteenla000000000000Catmandu-Store-MongoDB-0.0802/t#!perl BEGIN { unless ($ENV{AUTHOR_TESTING}) { print qq{1..0 # SKIP these tests are for testing by the author\n}; exit } } # This file was automatically generated by Dist::Zilla::Plugin::PodSyntaxTests. use strict; use warnings; use Test::More; use Test::Pod 1.41; all_pod_files_ok(); Store000755001750001750 013427316535 22051 5ustar00nsteenlansteenla000000000000Catmandu-Store-MongoDB-0.0802/lib/CatmanduMongoDB.pm100644001750001750 1670413427316535 24064 0ustar00nsteenlansteenla000000000000Catmandu-Store-MongoDB-0.0802/lib/Catmandu/Storepackage Catmandu::Store::MongoDB; use Catmandu::Sane; our $VERSION = '0.0802'; use Moo; use Catmandu::Store::MongoDB::Bag; use MongoDB; use namespace::clean; with 'Catmandu::Store'; with 'Catmandu::Transactional'; has client => (is => 'lazy'); has database_name => (is => 'ro', required => 1); has database => (is => 'lazy', handles => [qw(drop)]); has session => (is => 'rw', predicate => 1, clearer => 1, writer => 'set_session'); with 'Catmandu::Droppable'; sub _build_client { my $self = shift; my $args = delete $self->{_args}; my $host = $self->{_args}->{host} // 'mongodb://localhost:27017'; $self->log->debug("Build MongoClient for $host"); my $client = MongoDB::MongoClient->new($args); return $client; } sub _build_database { my $self = shift; my $database_name = $self->database_name; $self->log->debug("Build or get database $database_name"); my $database = $self->client->get_database($database_name); return $database; } sub BUILD { my ($self, $args) = @_; $self->{_args} = {}; for my $key (keys %$args) { next if $key eq 'client' || $key eq 'database_name' || $key eq 'database'; $self->{_args}{$key} = $args->{$key}; } } sub transaction { my ($self, $sub) = @_; if ($self->has_session) { return $sub->(); } my $session = $self->client->start_session; my @res; eval { $self->set_session($session); $session->start_transaction; @res = $sub->(); COMMIT: { eval { $session->commit_transaction; 1; } // do { my $err = $@; if ($err->has_error_label("UnknownTransactionCommitResult")) { redo COMMIT; } else { die $err; } }; } $self->clear_session; 1; } // do { my $err = $@; $session->abort_transaction; $self->clear_session; die $err; }; wantarray ? @res : $res[0]; } 1; __END__ =pod =head1 NAME Catmandu::Store::MongoDB - A searchable store backed by MongoDB =head1 SYNOPSIS # On the command line $ catmandu import -v JSON --multiline 1 to MongoDB --database_name bibliography --bag books < books.json $ catmandu export MongoDB --database_name bibliography --bag books to YAML $ catmandu count MongoDB --database_name bibliography --bag books --query '{"PublicationYear": "1937"}' # In perl use Catmandu::Store::MongoDB; my $store = Catmandu::Store::MongoDB->new(database_name => 'test'); my $obj1 = $store->bag->add({ name => 'Patrick' }); printf "obj1 stored as %s\n" , $obj1->{_id}; # Force an id in the store my $obj2 = $store->bag->add({ _id => 'test123' , name => 'Nicolas' }); my $obj3 = $store->bag->get('test123'); $store->bag->delete('test123'); $store->bag->delete_all; # All bags are iterators $store->bag->each(sub { ... }); $store->bag->take(10)->each(sub { ... }); # Search my $hits = $store->bag->search(query => '{"name":"Patrick"}'); my $hits = $store->bag->search(query => '{"name":"Patrick"}' , sort => { age => -1} ); my $hits = $store->bag->search(query => {name => "Patrick"} , start => 0 , limit => 100); my $hits = $store->bag->search(query => {name => "Patrick"} , fields => {_id => 0, name => 1}); my $next_page = $hits->next_page; my $hits = $store->bag->search(query => '{"name":"Patrick"}' , page => $next_page); my $iterator = $store->bag->searcher(query => {name => "Patrick"}); my $iterator = $store->bag->searcher(query => {name => "Patrick"}, fields => {_id => 0, name => 1}); # Catmandu::Store::MongoDB supports CQL... my $hits = $store->bag->search(cql_query => 'name any "Patrick"'); =head1 DESCRIPTION A Catmandu::Store::MongoDB is a Perl package that can store data into L databases. The database as a whole is called a 'store'. Databases also have compartments (e.g. tables) called Catmandu::Bag-s. =head1 METHODS =head2 new(database_name => $name, %connection_opts) =head2 new(database_name => $name , bags => { data => { cql_mapping => $cql_mapping } }) Create a new Catmandu::Store::MongoDB store with name $name. Optionally provide connection parameters (see L for possible options). The store supports CQL searches when a cql_mapping is provided. This hash contains a translation of CQL fields into MongoDB searchable fields. # Example mapping $cql_mapping = { indexes => { title => { op => { 'any' => 1 , 'all' => 1 , '=' => 1 , '<>' => 1 , 'exact' => {field => [qw(mytitle.exact myalttitle.exact)]} } , sort => 1, field => 'mytitle', cb => ['Biblio::Search', 'normalize_title'] } } } The CQL mapping above will support for the 'title' field the CQL operators: any, all, =, <> and exact. The 'title' field will be mapped into the MongoDB field 'mytitle', except for the 'exact' operator. In case of 'exact' both the 'mytitle.exact' and 'myalttitle.exact' fields will be searched. The CQL mapping allows for sorting on the 'title' field. If, for instance, we would like to use a special MongoDB field for sorting we could have written "sort => { field => 'mytitle.sort' }". The CQL has an optional callback field 'cb' which contains a reference to subroutines to rewrite or augment the search query. In this case, in the Biblio::Search package contains a normalize_title subroutine which returns a string or an ARRAY of string with augmented title(s). E.g. package Biblio::Search; sub normalize_title { my ($self,$title) = @_; # delete all bad characters my $new_title =~ s{[^A-Z0-9]+}{}g; $new_title; } 1; =head2 bag($name) Create or retieve a bag with name $name. Returns a L. =head2 client Return the L instance. =head2 database Return a L instance. =head2 drop Delete the store and all it's bags. =head2 transaction(\&sub) Execute C<$sub> within a transaction. See L. Note that only MongoDB databases with feature compatibility >= 4.0 and in a replica set have support for transactions. See L and L for more info. =head1 Search Search the database: see L and L. This module supports an additional search parameter: - fields => { => <0|1> } : limit fields to return from a query (see L) =head1 SEE ALSO L, L, L, L, L =head1 AUTHOR Nicolas Steenlant, C<< >> =head1 CONTRIBUTORS Johann Rolschewski, C<< >> =head1 LICENSE AND COPYRIGHT This program is free software; you can redistribute it and/or modify it under the terms of either: the GNU General Public License as published by the Free Software Foundation; or the Artistic License. See http://dev.perl.org/licenses/ for more information. =cut MongoDB000755001750001750 013427316535 23336 5ustar00nsteenlansteenla000000000000Catmandu-Store-MongoDB-0.0802/lib/Catmandu/StoreBag.pm100644001750001750 1720413427316535 24551 0ustar00nsteenlansteenla000000000000Catmandu-Store-MongoDB-0.0802/lib/Catmandu/Store/MongoDBpackage Catmandu::Store::MongoDB::Bag; use Catmandu::Sane; our $VERSION = '0.0802'; use Catmandu::Util qw(:is); use Catmandu::Store::MongoDB::Searcher; use Catmandu::Hits; use Cpanel::JSON::XS qw(decode_json); use Moo; use Catmandu::Store::MongoDB::CQL; use namespace::clean; with 'Catmandu::Bag'; with 'Catmandu::Droppable'; with 'Catmandu::CQLSearchable'; has collection => ( is => 'ro', init_arg => undef, lazy => 1, builder => '_build_collection', ); has cql_mapping => (is => 'ro'); sub _build_collection { my ($self) = @_; $self->store->database->get_collection($self->name); } sub _options { my ($self, $opts) = @_; $opts //= {}; $opts->{session} = $self->store->session if $self->store->has_session; $opts; } sub _cursor { my ($self, $filter, $opts) = @_; $self->collection->find($filter // {}, $self->_options($opts)); } sub generator { my ($self) = @_; sub { state $cursor = do { my $c = $self->_cursor; $c->immortal(1); $c; }; $cursor->next; }; } sub to_array { my ($self) = @_; my @all = $self->_cursor->all; \@all; } sub each { my ($self, $sub) = @_; my $cursor = $self->_cursor; my $n = 0; while (my $data = $cursor->next) { $sub->($data); $n++; } $n; } sub count { my ($self) = @_; $self->collection->count_documents({}, $self->_options); } # efficiently handle: # $bag->detect('foo' => 'bar') # $bag->detect('foo' => /bar/) # $bag->detect('foo' => ['bar', 'baz']) around detect => sub { my ($orig, $self, $arg1, $arg2) = @_; if (is_string($arg1)) { if (is_value($arg2) || is_regex_ref($arg2)) { return $self->collection->find_one({$arg1 => $arg2}, {}, $self->_options); } if (is_array_ref($arg2)) { return $self->collection->find_one({$arg1 => {'$in' => $arg2}}, {}, $self->_options); } } $self->$orig($arg1, $arg2); }; # efficiently handle: # $bag->select('foo' => 'bar') # $bag->select('foo' => /bar/) # $bag->select('foo' => ['bar', 'baz']) around select => sub { my ($orig, $self, $arg1, $arg2) = @_; if (is_string($arg1)) { if (is_value($arg2) || is_regex_ref($arg2)) { return Catmandu::Iterator->new( sub { sub { state $cursor = $self->_cursor({$arg1 => $arg2}); $cursor->next; } } ); } if (is_array_ref($arg2)) { return Catmandu::Iterator->new( sub { sub { state $cursor = $self->_cursor({$arg1 => {'$in' => $arg2}}); $cursor->next; } } ); } } $self->$orig($arg1, $arg2); }; # efficiently handle: # $bag->reject('foo' => 'bar') # $bag->reject('foo' => ['bar', 'baz']) around reject => sub { my ($orig, $self, $arg1, $arg2) = @_; if (is_string($arg1)) { if (is_value($arg2)) { return Catmandu::Iterator->new( sub { sub { state $cursor = $self->_cursor({$arg1 => {'$ne' => $arg2}}); $cursor->next; } } ); } if (is_array_ref($arg2)) { return Catmandu::Iterator->new( sub { sub { state $cursor = $self->_cursor({$arg1 => {'$nin' => $arg2}}); $cursor->next; } } ); } } $self->$orig($arg1, $arg2); }; sub pluck { my ($self, $key) = @_; Catmandu::Iterator->new( sub { sub { state $cursor = $self->_cursor({}, {projection => {$key => 1}}); ($cursor->next || return)->{$key}; } } ); } sub get { my ($self, $id) = @_; $self->collection->find_one({_id => $id}, {}, $self->_options); } sub add { my ($self, $data) = @_; $self->collection->replace_one({_id => $data->{_id}}, $data, $self->_options({upsert => 1})); } sub delete { my ($self, $id) = @_; $self->collection->delete_one({_id => $id}, $self->_options); } sub delete_all { my ($self) = @_; $self->collection->delete_many({}, $self->_options); } sub delete_by_query { my ($self, %args) = @_; $self->collection->delete_many($args{query}, $self->_options); } sub search { my ($self, %args) = @_; my $query = $args{query}; my $start = $args{start}; my $limit = $args{limit}; my $bag = $args{reify}; my $fields = $args{fields}; my $cursor = $self->_cursor($query)->skip($start)->limit($limit); if ($bag) { # only retrieve _id $cursor->fields({}); } elsif ($fields) { # only retrieve specified fields $cursor->fields($fields); } if (my $sort = $args{sort}) { $cursor->sort($sort); } my @hits = $cursor->all; if ($bag) { @hits = map {$bag->get($_->{_id})} @hits; } Catmandu::Hits->new( { start => $start, limit => $limit, total => $self->collection->count_documents($query, $self->_options), hits => \@hits, } ); } sub searcher { my ($self, %args) = @_; Catmandu::Store::MongoDB::Searcher->new(%args, bag => $self); } sub translate_sru_sortkeys { my ($self, $sortkeys) = @_; my $keys = [ grep {defined $_} map {$self->_translate_sru_sortkey($_)} split /\s+/, $sortkeys ]; my $mongo_sort = []; # flatten sortkeys for (@$keys) { push @$mongo_sort, @$_; } $self->log->debugf("translating sortkeys '$sortkeys' to mongo sort: %s", $mongo_sort); $mongo_sort; } sub _translate_sru_sortkey { my ($self, $sortkey) = @_; my ($field, $schema, $asc) = split /,/, $sortkey; $field || return; ($asc && ($asc == 1 || $asc == -1)) || return; if (my $map = $self->cql_mapping) { $field = lc $field; $field =~ s/(?<=[^_])_(?=[^_])//g if $map->{strip_separating_underscores}; $map = $map->{indexes} || return; $map = $map->{$field} || return; $map->{sort} || return; if (ref $map->{sort} && $map->{sort}{field}) { $field = $map->{sort}{field}; } elsif (ref $map->{field}) { $field = $map->{field}->[0]; } elsif ($map->{field}) { $field = $map->{field}; } } # Use a bad trick to force $asc interpreted as an integer [$field => $asc + 0]; } sub translate_cql_query { my ($self, $query) = @_; my $mongo_query = Catmandu::Store::MongoDB::CQL->new(mapping => $self->cql_mapping) ->parse($query); $self->log->debugf("translating cql '$query' to mongo query: %s", $mongo_query); $mongo_query; } # assume a string query is a JSON encoded MongoDB query sub normalize_query { my ($self, $query) = @_; return $query if ref $query; return {} if !$query; decode_json($query); } sub drop { $_[0]->collection->drop; } 1; __END__ =pod =head1 NAME Catmandu::Store::MongoDB::Bag - Catmandu::Bag implementation for MongoDB =head1 DESCRIPTION This class isn't normally used directly. Instances are constructed using the store's C method. =head1 SEE ALSO L, L, L =cut CQL.pm100644001750001750 2340213427316535 24474 0ustar00nsteenlansteenla000000000000Catmandu-Store-MongoDB-0.0802/lib/Catmandu/Store/MongoDBpackage Catmandu::Store::MongoDB::CQL; use Catmandu::Sane; use CQL::Parser; use Carp qw(confess); use Catmandu::Util qw(:is array_includes require_package); use Data::Dumper; use Moo; with 'Catmandu::Logger'; has parser => (is => 'ro', lazy => 1, builder => '_build_parser'); has mapping => (is => 'ro'); my $any_field = qr'^(srw|cql)\.(serverChoice|anywhere)$'i; my $match_all = qr'^(srw|cql)\.allRecords$'i; sub _build_parser { CQL::Parser->new; } sub parse { my ($self, $query) = @_; my $node = eval {$self->parser->parse($query)} or do { my $error = $@; die "cql error: $error"; }; my $mongo_query = $self->visit($node); if ($self->log->is_debug()) { $self->log->debug("CQL query: $query, translated into mongo query: " . Dumper($mongo_query)); } $mongo_query; } sub visit { my ($self, $node) = @_; my $indexes = $self->mapping ? $self->mapping->{indexes} : undef; confess "no cql_mapping.indexes defined" unless $indexes; if ($node->isa('CQL::TermNode')) { my $term = $node->getTerm; if ($term =~ $match_all) { return +{}; } my $qualifier = $node->getQualifier; my $relation = $node->getRelation; my @modifiers = $relation->getModifiers; my $base = lc $relation->getBase; my $search_field; my $search_clause; if ($base eq 'scr') { if ($self->mapping && $self->mapping->{default_relation}) { $base = $self->mapping->{default_relation}; } else { $base = '='; } } #fields to search for if ($qualifier =~ $any_field) { #set default field explicitely if ($self->mapping && $self->mapping->{default_index}) { $search_field = $self->mapping->{default_index}; } else { $search_field = '_all'; } } else { $search_field = $qualifier; #change search field $search_field =~ s/(?<=[^_])_(?=[^_])//g if $self->mapping && $self->mapping->{strip_separating_underscores}; my $q_mapping = $indexes->{$search_field} or confess "cql error: unknown index $search_field"; $q_mapping->{op}->{$base} or confess "cql error: relation $base not allowed"; my $op = $q_mapping->{op}->{$base}; if (ref $op && $op->{field}) { $search_field = $op->{field}; } elsif ($q_mapping->{field}) { $search_field = $q_mapping->{field}; } #change term using filters my $filters; if (ref $op && $op->{filter}) { $filters = $op->{filter}; } elsif ($q_mapping->{filter}) { $filters = $q_mapping->{filter}; } if ($filters) { for my $filter (@$filters) { if ($filter eq 'lowercase') { $term = lc $term; } } } #change term using callbacks if (ref $op && $op->{cb}) { my ($pkg, $sub) = @{$op->{cb}}; $term = require_package($pkg)->$sub($term); } elsif ($q_mapping->{cb}) { my ($pkg, $sub) = @{$q_mapping->{cb}}; $term = require_package($pkg)->$sub($term); } } #field search my $unmasked = array_includes([map {$_->[1]} @modifiers], "cql.unmasked"); # trick to force numeric values interpreted as integers $term = $term + 0 if ($term =~ /^[1-9]\d*$/); if ($base eq '=' or $base eq 'scr') { unless ($unmasked) { $term = _is_wildcard($term) ? _wildcard_to_regex($term) : $term; } $search_clause = +{$search_field => $term}; } elsif ($base eq '<') { $search_clause = +{$search_field => {'$lt' => $term}}; } elsif ($base eq '>') { $search_clause = +{$search_field => {'$gt' => $term}}; } elsif ($base eq '<=') { $search_clause = +{$search_field => {'$lte' => $term}}; } elsif ($base eq '>=') { $search_clause = +{$search_field => {'$gte' => $term}}; } elsif ($base eq '<>') { $search_clause = +{$search_field => {'$ne' => $term}}; } elsif ($base eq 'exact') { $search_clause = +{$search_field => $term}; } elsif ($base eq 'all') { my @terms = split /\s+/, $term; #query $all in mongo means exact matching, so we always need regular expressions here for (my $i = 0; $i < scalar(@terms); $i++) { my $term = $terms[$i]; if ($unmasked) { $term = _quote_wildcard($term); $term = qr($term); } elsif (_is_wildcard($term)) { $term = _wildcard_to_regex($term); } else { $term = qr($term); } $terms[$i] = $term; } $search_clause = +{$search_field => {'$all' => \@terms}}; } elsif ($base eq 'any') { my @terms = split /\s+/, $term; #query $in in mongo means exact matching, so we always need regular expressions here for (my $i = 0; $i < scalar(@terms); $i++) { my $term = $terms[$i]; if ($unmasked) { $term = _quote_wildcard($term); $term = qr($term); } elsif (_is_wildcard($term)) { $term = _wildcard_to_regex($term); } else { $term = qr($term); } $terms[$i] = $term; } $search_clause = +{$search_field => {'$in' => \@terms}}; } elsif ($base eq 'within') { my @range = split /\s+/, $term; if (@range == 1) { $search_clause = +{$search_field => $term}; } else { $search_clause = +{$search_field => {'$gte' => $range[0], '$lte' => $range[1]} }; } } #as $base is always set, this code should be removed? else { unless ($unmasked) { $term = _is_wildcard($term) ? _wildcard_to_regex($term) : $term; } $search_clause = +{$search_field => $term}; } return $search_clause; } elsif ($node->isa('CQL::ProxNode')) { # TODO: apply cql_mapping confess "not supported"; } elsif ($node->isa('CQL::BooleanNode')) { my $lft = $node->left; my $rgt = $node->right; my $lft_q = $self->visit($lft); my $rgt_q = $self->visit($rgt); my $op = '$' . lc($node->op); if ($op eq '$and' || $op eq '$or') { return +{$op => [$lft_q, $rgt_q]}; } elsif ($op eq '$not') { my ($k, $v) = each(%$rgt_q); if ($k eq '$or') { return +{%$lft_q, '$nor' => $v}; } elsif ($k eq '$and') { #$nand not implemented yet (https://jira.mongodb.org/browse/SERVER-15577) return +{%$lft_q, '$nor' => [{'$and' => $v}]}; } else { return +{%$lft_q, '$nor' => [{'$and' => [{$k => $v}]}]}; } } } } sub _is_wildcard { my $value = $_[0]; (index($value, '^') == 0) || (rindex($value, '^') == length($value) - 1) || (index($value, '*') >= 0) || (index($value, '?') >= 0); } sub _wildcard_to_regex { my $value = $_[0]; my $regex = $value; $regex =~ s/\*/.*/go; $regex =~ s/\?/.?/go; $regex =~ s/\^$/\$/o; qr/$regex/; } sub _quote_wildcard { my $value = $_[0]; $value =~ s/\*/\\*/go; $value =~ s/\?/\\?/go; $value =~ s/\^/\\^/go; $value; } 1; __END__ =head1 NAME Catmandu::Store::MongoDB::CQL - Converts a CQL query string to a MongoDB query string =head1 SYNOPSIS $mongo_query = Catmandu::Store::ElasticSearch::CQL ->new(mapping => $cql_mapping) ->parse($cql_query_string); =head1 DESCRIPTION This package currently parses most of CQL 1.1: and or not srw.allRecords srw.serverChoice srw.anywhere cql.allRecords cql.serverChoice cql.anywhere = scr < > <= >= <> exact all any within See L for more information on the CQL query language. =head1 LIMITATIONS MongoDB is not a full-text search engine. All queries will try to find exact matches in the database, except for the 'any' and 'all' relations which will translate queries into wildcard queries (which are slow!): title any 'funny cats' will be treated internally as something like: title : { $regex : /funny/ } OR title : { $regex : /cats/ } And, title all 'funny cats' as title : { $regex : /funny/ } AND title : { $regex : /cats/ } This makes the 'any' and 'all' not as efficient (fast) as exact matches '==','exact'. =head1 METHODS =head2 parse Parses the given CQL query string with L and converts it to a Mongo query string. =head2 visit Converts the given L to a Mongo query string. =head1 REMARKS no support for fuzzy search, search modifiers, sortBy and encloses =head1 SEE ALSO L. =cut Searcher.pm100644001750001750 256613427316535 25601 0ustar00nsteenlansteenla000000000000Catmandu-Store-MongoDB-0.0802/lib/Catmandu/Store/MongoDBpackage Catmandu::Store::MongoDB::Searcher; use Catmandu::Sane; our $VERSION = '0.0802'; use Moo; use namespace::clean; with 'Catmandu::Iterable'; has bag => (is => 'ro', required => 1); has query => (is => 'ro', required => 1); has start => (is => 'ro', required => 1); has limit => (is => 'ro', required => 1); has total => (is => 'ro'); has sort => (is => 'ro'); has fields => (is => 'ro'); sub generator { my ($self) = @_; sub { state $cursor = do { my $c = $self->bag->_cursor($self->query); $c->fields($self->fields) if defined $self->fields; # limit is unused because the perl driver doesn't expose batchSize $c->limit($self->total) if defined $self->total; $c->sort($self->sort) if defined $self->sort; $c->immortal(1); $c; }; $cursor->next; }; } sub slice { # TODO constrain total? my ($self, $start, $total) = @_; $start //= 0; $self->new( bag => $self->bag, query => $self->query, start => $self->start + $start, limit => $self->limit, total => $total, sort => $self->sort, fields => $self->fields, ); } sub count { # TODO constrain on start, total? my ($self) = @_; $self->bag->collection->count_documents($self->query, $self->bag->_options); } 1;