/usr/lib/python3/dist-packages/radicale/storage/database.py is in python3-radicale 1.1.1+20160115-4.
This file is owned by root:root, with mode 0o644.
The actual contents of the file can be viewed below.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 | # -*- coding: utf-8 -*-
#
# This file is part of Radicale Server - Calendar Server
# Copyright © 2013 Guillaume Ayoub
#
# This library 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 3 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 General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with Radicale. If not, see <http://www.gnu.org/licenses/>.
"""
SQLAlchemy storage backend.
"""
import time
from datetime import datetime
from contextlib import contextmanager
from sqlalchemy import create_engine, Column, Unicode, Integer, ForeignKey
from sqlalchemy import func
from sqlalchemy.orm import sessionmaker, relationship
from sqlalchemy.ext.declarative import declarative_base
from .. import config, ical
# These are classes, not constants
# pylint: disable=C0103
Base = declarative_base()
Session = sessionmaker()
Session.configure(bind=create_engine(config.get("storage", "database_url")))
# pylint: enable=C0103
class DBCollection(Base):
"""Table of collections."""
__tablename__ = "collection"
path = Column(Unicode, primary_key=True)
parent_path = Column(Unicode, ForeignKey("collection.path"))
parent = relationship(
"DBCollection", backref="children", remote_side=[path])
class DBItem(Base):
"""Table of collection's items."""
__tablename__ = "item"
name = Column(Unicode, primary_key=True)
tag = Column(Unicode)
collection_path = Column(Unicode, ForeignKey("collection.path"))
collection = relationship("DBCollection", backref="items")
class DBHeader(Base):
"""Table of item's headers."""
__tablename__ = "header"
name = Column(Unicode, primary_key=True)
value = Column(Unicode)
collection_path = Column(
Unicode, ForeignKey("collection.path"), primary_key=True)
collection = relationship("DBCollection", backref="headers")
class DBLine(Base):
"""Table of item's lines."""
__tablename__ = "line"
name = Column(Unicode)
value = Column(Unicode)
item_name = Column(Unicode, ForeignKey("item.name"))
timestamp = Column(
Integer, default=lambda: time.time() * 10 ** 6, primary_key=True)
item = relationship("DBItem", backref="lines", order_by=timestamp)
class DBProperty(Base):
"""Table of collection's properties."""
__tablename__ = "property"
name = Column(Unicode, primary_key=True)
value = Column(Unicode)
collection_path = Column(
Unicode, ForeignKey("collection.path"), primary_key=True)
collection = relationship(
"DBCollection", backref="properties", cascade="delete")
class Collection(ical.Collection):
"""Collection stored in a database."""
def __init__(self, path, principal=False):
self.session = Session()
super(Collection, self).__init__(path, principal)
def __del__(self):
self.session.commit()
def _query(self, item_types):
"""Get collection's items matching ``item_types``."""
item_objects = []
for item_type in item_types:
items = (
self.session.query(DBItem)
.filter_by(collection_path=self.path, tag=item_type.tag)
.order_by(DBItem.name).all())
for item in items:
text = "\n".join(
"%s:%s" % (line.name, line.value) for line in item.lines)
item_objects.append(item_type(text, item.name))
return item_objects
@property
def _modification_time(self):
"""Collection's last modification time."""
timestamp = (
self.session.query(func.max(DBLine.timestamp))
.join(DBItem).filter_by(collection_path=self.path).first()[0])
if timestamp:
return datetime.fromtimestamp(float(timestamp) / 10 ** 6)
else:
return datetime.now()
@property
def _db_collection(self):
"""Collection's object mapped to the table line."""
return self.session.query(DBCollection).get(self.path)
def write(self):
if self._db_collection:
for item in self._db_collection.items:
for line in item.lines:
self.session.delete(line)
self.session.delete(item)
for header in self._db_collection.headers:
self.session.delete(header)
else:
db_collection = DBCollection()
db_collection.path = self.path
db_collection.parent_path = "/".join(self.path.split("/")[:-1])
self.session.add(db_collection)
for header in self.headers:
db_header = DBHeader()
db_header.name, db_header.value = header.text.split(":", 1)
db_header.collection_path = self.path
self.session.add(db_header)
for item in self.items.values():
db_item = DBItem()
db_item.name = item.name
db_item.tag = item.tag
db_item.collection_path = self.path
self.session.add(db_item)
for line in ical.unfold(item.text):
db_line = DBLine()
db_line.name, db_line.value = line.split(":", 1)
db_line.item_name = item.name
self.session.add(db_line)
def delete(self):
self.session.delete(self._db_collection)
@property
def text(self):
return ical.serialize(self.tag, self.headers, self.components)
@property
def etag(self):
return '"%s"' % hash(self._modification_time)
@property
def headers(self):
headers = (
self.session.query(DBHeader)
.filter_by(collection_path=self.path)
.order_by(DBHeader.name).all())
return [
ical.Header("%s:%s" % (header.name, header.value))
for header in headers]
@classmethod
def children(cls, path):
session = Session()
children = (
session.query(DBCollection)
.filter_by(parent_path=path or "").all())
collections = [cls(child.path) for child in children]
session.close()
return collections
@classmethod
def is_node(cls, path):
if not path:
return True
session = Session()
result = (
session.query(DBCollection)
.filter_by(parent_path=path or "").count() > 0)
session.close()
return result
@classmethod
def is_leaf(cls, path):
if not path:
return False
session = Session()
result = (
session.query(DBItem)
.filter_by(collection_path=path or "").count() > 0)
session.close()
return result
@property
def last_modified(self):
return time.strftime(
"%a, %d %b %Y %H:%M:%S +0000", self._modification_time.timetuple())
@property
@contextmanager
def props(self):
# On enter
properties = {}
db_properties = (
self.session.query(DBProperty)
.filter_by(collection_path=self.path).all())
for prop in db_properties:
properties[prop.name] = prop.value
old_properties = properties.copy()
yield properties
# On exit
if old_properties != properties:
for prop in db_properties:
self.session.delete(prop)
for name, value in properties.items():
prop = DBProperty(name=name, value=value or '',
collection_path=self.path)
self.session.add(prop)
@property
def components(self):
return self._query((ical.Event, ical.Todo, ical.Journal, ical.Card))
@property
def events(self):
return self._query((ical.Event,))
@property
def todos(self):
return self._query((ical.Todo,))
@property
def journals(self):
return self._query((ical.Journal,))
@property
def timezones(self):
return self._query((ical.Timezone,))
@property
def cards(self):
return self._query((ical.Card,))
def save(self):
"""Save the text into the collection.
This method is not used for databases.
"""
|