Source

ryshcate / ryshcate / database.py

# -*- coding: utf-8 -*-
"""
ryshcate.database
=================
This has the DB models, views, and the like used by Ryshcate.

:copyright: 2010 Matthew "LeafStorm" Frazier
:license:   MIT/X11, see LICENSE for details
"""
import datetime
import uuid
from flaskext.couchdb import (CouchDBManager, Document, ViewField, TextField,
                              BooleanField, DateTimeField, ListField)
from couchdb.client import Row

manager = CouchDBManager(auto_sync=False)


def create_id():
    return hex(uuid.uuid4().time)[2:-1]


class Paste(Document):
    title = TextField()
    code = TextField()
    language = TextField()
    created = DateTimeField(default=datetime.datetime.utcnow)
    tags = ListField(TextField())
    private = BooleanField(default=False)
    
    public = ViewField('pastes', '''\
        function (doc) {
            if (!doc.private) {
                emit(doc.created, doc);
            };
        }''')
    by_language = ViewField('pastes', '''\
        function (doc) {
            if (!doc.private) {
                emit(doc.language, doc);
            };
        }''')
    tagged = ViewField('pastes', '''\
        function (doc) {
            if (!doc.private) {
                doc.tags.forEach(function (tag) {
                    emit(tag, doc);
                });
            };
        }''')
    tag_counts = ViewField('pastes', '''\
        function (doc) {
            if (!doc.private) {
                doc.tags.forEach(function (tag) {
                    emit(tag, 1);
                });
            };
        }''', '''\
        function (keys, values, rereduce) {
            return sum(values);
        }''', group=True, wrapper=Row)
    language_counts = ViewField('pastes', '''\
        function (doc) {
            if (!doc.private) {
                emit(doc.language, 1);
            };
        }''', '''\
        function (keys, values, rereduce) {
            return sum(values);
        }''', group=True, wrapper=Row)

manager.add_document(Paste)