2 ;;; BongoDB, an embedded document-based engine
3 ;;; Copyright (C) 2016 by Javier Sancho Fernandez <jsf at jsancho dot org>
5 ;;; This program is free software: you can redistribute it and/or modify
6 ;;; it under the terms of the GNU General Public License as published by
7 ;;; the Free Software Foundation, either version 3 of the License, or
8 ;;; (at your option) any later version.
10 ;;; This program is distributed in the hope that it will be useful,
11 ;;; but WITHOUT ANY WARRANTY; without even the implied warranty of
12 ;;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13 ;;; GNU General Public License for more details.
15 ;;; You should have received a copy of the GNU General Public License
16 ;;; along with this program. If not, see <http://www.gnu.org/licenses/>.
19 (define-module (bongodb)
20 #:use-module (ice-9 receive)
21 #:use-module (ice-9 vlist)
22 #:use-module (srfi srfi-9)
23 #:use-module (srfi srfi-9 gnu))
26 ;;; Collection Definition
28 (define-record-type collection
29 (make-collection-record table)
33 (define (make-collection)
34 (make-collection-record vlist-null))
36 (set-record-type-printer! collection
39 "#<collection with ~a documents>"
40 (vlist-length (get-table record)))))
43 ;;; Working with documents
45 (define (format-document document)
46 "Return a vhash document ready to store in a collection"
48 (cond ((vhash? document)
51 (alist->vhash document)))))
53 (define (document-with-id document)
54 "Return always a document with an id"
55 (or (and (vhash-assoc '_id document)
57 (vhash-cons '_id (gensym) document)))
59 (define (insert col . documents)
60 "Insert documents into the collection and return the new collection"
61 (cond ((null? documents)
64 (let* ((document (format-document (car documents)))
65 (docid (cdr (vhash-assoc '_id document)))
66 (newcol (make-collection-record (vhash-cons docid document (get-table col)))))
67 (receive (rescol docids)
68 (apply insert (cons newcol (cdr documents)))
69 (values rescol (cons docid docids)))))))
71 (define (find col filter)
72 "Query the collection and return the documents that match with filter"
73 (let ((table (get-table col)))
75 (lambda (key value result) (cons (vhash->alist value) result))
82 (define (vhash->alist vhash)
84 (lambda (key value result) (assoc-set! result key value))
92 (let ((col (make-collection)))
93 (format #t "1 New collection: ~a~%" col)
94 (set! col (insert col '((a . 1) (b . 2)) '((a . 10) (b . 20)) '((a . 1) (b . "hello world"))))
95 (format #t "2 Insert 3 documents: ~a~%" col)
96 (format #t "3 Search (a . 1): ~a~%" (find col '((a . 1))))))