1 ;;; BongoDB, an embedded document-based engine
2 ;;; Copyright (C) 2016 by Javier Sancho Fernandez <jsf at jsancho dot org>
4 ;;; This program is free software: you can redistribute it and/or modify
5 ;;; it under the terms of the GNU General Public License as published by
6 ;;; the Free Software Foundation, either version 3 of the License, or
7 ;;; (at your option) any later version.
9 ;;; This program is distributed in the hope that it will be useful,
10 ;;; but WITHOUT ANY WARRANTY; without even the implied warranty of
11 ;;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
12 ;;; GNU General Public License for more details.
14 ;;; You should have received a copy of the GNU General Public License
15 ;;; along with this program. If not, see <http://www.gnu.org/licenses/>.
18 (define-module (bongodb)
19 #:use-module (ice-9 receive)
20 #:use-module (ice-9 vlist)
21 #:use-module (srfi srfi-9)
22 #:use-module (srfi srfi-9 gnu)
23 #:export (make-collection
30 ;;; Collection Definition
32 (define-record-type collection
33 (make-collection-record table)
37 (define (make-collection)
38 (make-collection-record vlist-null))
41 (vlist-length (get-table col)))
43 (set-record-type-printer! collection
46 "#<collection with ~a documents>"
50 ;;; Working with documents
52 (define (format-document document)
53 "Return a vhash document ready to store in a collection"
55 (cond ((vhash? document)
58 (alist->vhash document)))))
60 (define (document-with-id document)
61 "Return always a document with an id"
62 (or (and (vhash-assoc '_id document)
64 (vhash-cons '_id (gensym) document)))
66 (define (insert col . documents)
67 "Insert documents into the collection and return the new collection"
68 (cond ((null? documents)
71 (let* ((document (format-document (car documents)))
72 (docid (cdr (vhash-assoc '_id document)))
73 (newcol (make-collection-record (vhash-cons docid document (get-table col)))))
74 (receive (rescol docids)
75 (apply insert (cons newcol (cdr documents)))
76 (values rescol (cons docid docids)))))))
78 (define (find col filter)
79 "Query the collection and return the documents that match with filter"
80 (let ((table (get-table col)))
82 (lambda (key document result)
83 (cond ((match-document? document filter)
84 (cons (vhash->alist document) result))
90 (define (match-document? document filter)
91 "Try to match the given document with a list of conditions"
96 (equal? (vhash-assoc (caar filter) document) (car filter))
97 (match-document? document (cdr filter))))))
102 (define (vhash->alist vhash)
104 (lambda (key value result) (assoc-set! result key value))