PageRenderTime 56ms CodeModel.GetById 22ms RepoModel.GetById 1ms app.codeStats 0ms

/storm/variables.py

https://github.com/quodt/storm
Python | 714 lines | 680 code | 9 blank | 25 comment | 11 complexity | 6cb36718d327275ce835af3a1cb3ae95 MD5 | raw file
Possible License(s): LGPL-2.1
  1. #
  2. # Copyright (c) 2006, 2007 Canonical
  3. #
  4. # Written by Gustavo Niemeyer <gustavo@niemeyer.net>
  5. #
  6. # This file is part of Storm Object Relational Mapper.
  7. #
  8. # Storm is free software; you can redistribute it and/or modify
  9. # it under the terms of the GNU Lesser General Public License as
  10. # published by the Free Software Foundation; either version 2.1 of
  11. # the License, or (at your option) any later version.
  12. #
  13. # Storm is distributed in the hope that it will be useful,
  14. # but WITHOUT ANY WARRANTY; without even the implied warranty of
  15. # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  16. # GNU Lesser General Public License for more details.
  17. #
  18. # You should have received a copy of the GNU Lesser General Public License
  19. # along with this program. If not, see <http://www.gnu.org/licenses/>.
  20. #
  21. from datetime import datetime, date, time, timedelta
  22. from decimal import Decimal
  23. import cPickle as pickle
  24. import re
  25. try:
  26. import uuid
  27. except ImportError:
  28. uuid = None
  29. from storm.exceptions import NoneError
  30. from storm import Undef, has_cextensions
  31. __all__ = [
  32. "VariableFactory",
  33. "Variable",
  34. "LazyValue",
  35. "BoolVariable",
  36. "IntVariable",
  37. "FloatVariable",
  38. "DecimalVariable",
  39. "RawStrVariable",
  40. "UnicodeVariable",
  41. "DateTimeVariable",
  42. "DateVariable",
  43. "TimeVariable",
  44. "TimeDeltaVariable",
  45. "EnumVariable",
  46. "UUIDVariable",
  47. "PickleVariable",
  48. "ListVariable",
  49. ]
  50. class LazyValue(object):
  51. """Marker to be used as a base class on lazily evaluated values."""
  52. __slots__ = ()
  53. def raise_none_error(column):
  54. if not column:
  55. raise NoneError("None isn't acceptable as a value")
  56. else:
  57. from storm.expr import compile, CompileError
  58. name = column.name
  59. if column.table is not Undef:
  60. try:
  61. table = compile(column.table)
  62. name = "%s.%s" % (table, name)
  63. except CompileError:
  64. pass
  65. raise NoneError("None isn't acceptable as a value for %s" % name)
  66. def VariableFactory(cls, **old_kwargs):
  67. """Build cls with kwargs of constructor updated by kwargs of call.
  68. This is really an implementation of partial/curry functions, and
  69. is replaced by 'partial' when 2.5+ is in use.
  70. """
  71. def variable_factory(**new_kwargs):
  72. kwargs = old_kwargs.copy()
  73. kwargs.update(new_kwargs)
  74. return cls(**kwargs)
  75. return variable_factory
  76. try:
  77. from functools import partial as VariableFactory
  78. except ImportError:
  79. pass
  80. class Variable(object):
  81. """Basic representation of a database value in Python.
  82. @type column: L{storm.expr.Column}
  83. @ivar column: The column this variable represents.
  84. @type event: L{storm.event.EventSystem}
  85. @ivar event: The event system on which to broadcast events. If
  86. None, no events will be emitted.
  87. """
  88. _value = Undef
  89. _lazy_value = Undef
  90. _checkpoint_state = Undef
  91. _allow_none = True
  92. _validator = None
  93. _validator_object_factory = None
  94. _validator_attribute = None
  95. column = None
  96. event = None
  97. def __init__(self, value=Undef, value_factory=Undef, from_db=False,
  98. allow_none=True, column=None, event=None, validator=None,
  99. validator_object_factory=None, validator_attribute=None):
  100. """
  101. @param value: The initial value of this variable. The default
  102. behavior is for the value to stay undefined until it is
  103. set with L{set}.
  104. @param value_factory: If specified, this will immediately be
  105. called to get the initial value.
  106. @param from_db: A boolean value indicating where the initial
  107. value comes from, if C{value} or C{value_factory} are
  108. specified.
  109. @param allow_none: A boolean indicating whether None should be
  110. allowed to be set as the value of this variable.
  111. @param validator: Validation function called whenever trying to
  112. set the variable to a non-db value. The function should
  113. look like validator(object, attr, value), where the first and
  114. second arguments are the result of validator_object_factory()
  115. (or None, if this parameter isn't provided) and the value of
  116. validator_attribute, respectively. When called, the function
  117. should raise an error if the value is unacceptable, or return
  118. the value to be used in place of the original value otherwise.
  119. @type column: L{storm.expr.Column}
  120. @param column: The column that this variable represents. It's
  121. used for reporting better error messages.
  122. @type event: L{EventSystem}
  123. @param event: The event system to broadcast messages with. If
  124. not specified, then no events will be broadcast.
  125. """
  126. if not allow_none:
  127. self._allow_none = False
  128. if value is not Undef:
  129. self.set(value, from_db)
  130. elif value_factory is not Undef:
  131. self.set(value_factory(), from_db)
  132. if validator is not None:
  133. self._validator = validator
  134. self._validator_object_factory = validator_object_factory
  135. self._validator_attribute = validator_attribute
  136. self.column = column
  137. self.event = event
  138. def get_lazy(self, default=None):
  139. """Get the current L{LazyValue} without resolving its value.
  140. @param default: If no L{LazyValue} was previously specified,
  141. return this value. Defaults to None.
  142. """
  143. if self._lazy_value is Undef:
  144. return default
  145. return self._lazy_value
  146. def get(self, default=None, to_db=False):
  147. """Get the value, resolving it from a L{LazyValue} if necessary.
  148. If the current value is an instance of L{LazyValue}, then the
  149. C{resolve-lazy-value} event will be emitted, to give third
  150. parties the chance to resolve the lazy value to a real value.
  151. @param default: Returned if no value has been set.
  152. @param to_db: A boolean flag indicating whether this value is
  153. destined for the database.
  154. """
  155. if self._lazy_value is not Undef and self.event is not None:
  156. self.event.emit("resolve-lazy-value", self, self._lazy_value)
  157. value = self._value
  158. if value is Undef:
  159. return default
  160. if value is None:
  161. return None
  162. return self.parse_get(value, to_db)
  163. def set(self, value, from_db=False):
  164. """Set a new value.
  165. Generally this will be called when an attribute was set in
  166. Python, or data is being loaded from the database.
  167. If the value is different from the previous value (or it is a
  168. L{LazyValue}), then the C{changed} event will be emitted.
  169. @param value: The value to set. If this is an instance of
  170. L{LazyValue}, then later calls to L{get} will try to
  171. resolve the value.
  172. @param from_db: A boolean indicating whether this value has
  173. come from the database.
  174. """
  175. # FASTPATH This method is part of the fast path. Be careful when
  176. # changing it (try to profile any changes).
  177. if isinstance(value, LazyValue):
  178. self._lazy_value = value
  179. self._checkpoint_state = new_value = Undef
  180. else:
  181. if not from_db and self._validator is not None:
  182. # We use a factory rather than the object itself to prevent
  183. # the cycle object => obj_info => variable => object
  184. value = self._validator(self._validator_object_factory and
  185. self._validator_object_factory(),
  186. self._validator_attribute, value)
  187. self._lazy_value = Undef
  188. if value is None:
  189. if self._allow_none is False:
  190. raise_none_error(self.column)
  191. new_value = None
  192. else:
  193. new_value = self.parse_set(value, from_db)
  194. if from_db:
  195. # Prepare it for being used by the hook below.
  196. value = self.parse_get(new_value, False)
  197. old_value = self._value
  198. self._value = new_value
  199. if (self.event is not None and
  200. (self._lazy_value is not Undef or new_value != old_value)):
  201. if old_value is not None and old_value is not Undef:
  202. old_value = self.parse_get(old_value, False)
  203. self.event.emit("changed", self, old_value, value, from_db)
  204. def delete(self):
  205. """Delete the internal value.
  206. If there was a value set, then emit the C{changed} event.
  207. """
  208. old_value = self._value
  209. if old_value is not Undef:
  210. self._value = Undef
  211. if self.event is not None:
  212. if old_value is not None and old_value is not Undef:
  213. old_value = self.parse_get(old_value, False)
  214. self.event.emit("changed", self, old_value, Undef, False)
  215. def is_defined(self):
  216. """Check whether there is currently a value.
  217. @return: boolean indicating whether there is currently a value
  218. for this variable. Note that if a L{LazyValue} was
  219. previously set, this returns False; it only returns True if
  220. there is currently a real value set.
  221. """
  222. return self._value is not Undef
  223. def has_changed(self):
  224. """Check whether the value has changed.
  225. @return: boolean indicating whether the value has changed
  226. since the last call to L{checkpoint}.
  227. """
  228. return (self._lazy_value is not Undef or
  229. self.get_state() != self._checkpoint_state)
  230. def get_state(self):
  231. """Get the internal state of this object.
  232. @return: A value which can later be passed to L{set_state}.
  233. """
  234. return (self._lazy_value, self._value)
  235. def set_state(self, state):
  236. """Set the internal state of this object.
  237. @param state: A result from a previous call to
  238. L{get_state}. The internal state of this variable will be set
  239. to the state of the variable which get_state was called on.
  240. """
  241. self._lazy_value, self._value = state
  242. def checkpoint(self):
  243. """"Checkpoint" the internal state.
  244. See L{has_changed}.
  245. """
  246. self._checkpoint_state = self.get_state()
  247. def copy(self):
  248. """Make a new copy of this Variable with the same internal state."""
  249. variable = self.__class__.__new__(self.__class__)
  250. variable.set_state(self.get_state())
  251. return variable
  252. def parse_get(self, value, to_db):
  253. """Convert the internal value to an external value.
  254. Get a representation of this value either for Python or for
  255. the database. This method is only intended to be overridden
  256. in subclasses, not called from external code.
  257. @param value: The value to be converted.
  258. @param to_db: Whether or not this value is destined for the
  259. database.
  260. """
  261. return value
  262. def parse_set(self, value, from_db):
  263. """Convert an external value to an internal value.
  264. A value is being set either from Python code or from the
  265. database. Parse it into its internal representation. This
  266. method is only intended to be overridden in subclasses, not
  267. called from external code.
  268. @param value: The value, either from Python code setting an
  269. attribute or from a column in a database.
  270. @param from_db: A boolean flag indicating whether this value
  271. is from the database.
  272. """
  273. return value
  274. if has_cextensions:
  275. from storm.cextensions import Variable
  276. class BoolVariable(Variable):
  277. __slots__ = ()
  278. def parse_set(self, value, from_db):
  279. if not isinstance(value, (int, long, float, Decimal)):
  280. raise TypeError("Expected bool, found %r: %r"
  281. % (type(value), value))
  282. return bool(value)
  283. class IntVariable(Variable):
  284. __slots__ = ()
  285. def parse_set(self, value, from_db):
  286. if not isinstance(value, (int, long, float, Decimal)):
  287. raise TypeError("Expected int, found %r: %r"
  288. % (type(value), value))
  289. return int(value)
  290. class FloatVariable(Variable):
  291. __slots__ = ()
  292. def parse_set(self, value, from_db):
  293. if not isinstance(value, (int, long, float, Decimal)):
  294. raise TypeError("Expected float, found %r: %r"
  295. % (type(value), value))
  296. return float(value)
  297. class DecimalVariable(Variable):
  298. __slots__ = ()
  299. @staticmethod
  300. def parse_set(value, from_db):
  301. if (from_db and isinstance(value, basestring) or
  302. isinstance(value, (int, long))):
  303. value = Decimal(value)
  304. elif not isinstance(value, Decimal):
  305. raise TypeError("Expected Decimal, found %r: %r"
  306. % (type(value), value))
  307. return value
  308. @staticmethod
  309. def parse_get(value, to_db):
  310. if to_db:
  311. return unicode(value)
  312. return value
  313. class RawStrVariable(Variable):
  314. __slots__ = ()
  315. def parse_set(self, value, from_db):
  316. if isinstance(value, buffer):
  317. value = str(value)
  318. elif not isinstance(value, str):
  319. raise TypeError("Expected str, found %r: %r"
  320. % (type(value), value))
  321. return value
  322. class UnicodeVariable(Variable):
  323. __slots__ = ()
  324. def parse_set(self, value, from_db):
  325. if not isinstance(value, unicode):
  326. raise TypeError("Expected unicode, found %r: %r"
  327. % (type(value), value))
  328. return value
  329. class DateTimeVariable(Variable):
  330. __slots__ = ("_tzinfo",)
  331. def __init__(self, *args, **kwargs):
  332. self._tzinfo = kwargs.pop("tzinfo", None)
  333. super(DateTimeVariable, self).__init__(*args, **kwargs)
  334. def parse_set(self, value, from_db):
  335. if from_db:
  336. if isinstance(value, datetime):
  337. pass
  338. elif isinstance(value, (str, unicode)):
  339. if " " not in value:
  340. raise ValueError("Unknown date/time format: %r" % value)
  341. date_str, time_str = value.split(" ")
  342. value = datetime(*(_parse_date(date_str) +
  343. _parse_time(time_str)))
  344. else:
  345. raise TypeError("Expected datetime, found %s" % repr(value))
  346. if self._tzinfo is not None:
  347. if value.tzinfo is None:
  348. value = value.replace(tzinfo=self._tzinfo)
  349. else:
  350. value = value.astimezone(self._tzinfo)
  351. else:
  352. if type(value) in (int, long, float):
  353. value = datetime.utcfromtimestamp(value)
  354. elif not isinstance(value, datetime):
  355. raise TypeError("Expected datetime, found %s" % repr(value))
  356. if self._tzinfo is not None:
  357. value = value.astimezone(self._tzinfo)
  358. return value
  359. class DateVariable(Variable):
  360. __slots__ = ()
  361. def parse_set(self, value, from_db):
  362. if from_db:
  363. if value is None:
  364. return None
  365. if isinstance(value, date):
  366. return value
  367. if not isinstance(value, (str, unicode)):
  368. raise TypeError("Expected date, found %s" % repr(value))
  369. if " " in value:
  370. value, time_str = value.split(" ")
  371. return date(*_parse_date(value))
  372. else:
  373. if isinstance(value, datetime):
  374. return value.date()
  375. if not isinstance(value, date):
  376. raise TypeError("Expected date, found %s" % repr(value))
  377. return value
  378. class TimeVariable(Variable):
  379. __slots__ = ()
  380. def parse_set(self, value, from_db):
  381. if from_db:
  382. # XXX Can None ever get here, considering that set() checks for it?
  383. if value is None:
  384. return None
  385. if isinstance(value, time):
  386. return value
  387. if not isinstance(value, (str, unicode)):
  388. raise TypeError("Expected time, found %s" % repr(value))
  389. if " " in value:
  390. date_str, value = value.split(" ")
  391. return time(*_parse_time(value))
  392. else:
  393. if isinstance(value, datetime):
  394. return value.time()
  395. if not isinstance(value, time):
  396. raise TypeError("Expected time, found %s" % repr(value))
  397. return value
  398. class TimeDeltaVariable(Variable):
  399. __slots__ = ()
  400. def parse_set(self, value, from_db):
  401. if from_db:
  402. # XXX Can None ever get here, considering that set() checks for it?
  403. if value is None:
  404. return None
  405. if isinstance(value, timedelta):
  406. return value
  407. if not isinstance(value, (str, unicode)):
  408. raise TypeError("Expected timedelta, found %s" % repr(value))
  409. return _parse_interval(value)
  410. else:
  411. if not isinstance(value, timedelta):
  412. raise TypeError("Expected timedelta, found %s" % repr(value))
  413. return value
  414. class UUIDVariable(Variable):
  415. __slots__ = ()
  416. def parse_set(self, value, from_db):
  417. assert uuid is not None, "The uuid module was not found."
  418. if from_db and isinstance(value, basestring):
  419. value = uuid.UUID(value)
  420. elif not isinstance(value, uuid.UUID):
  421. raise TypeError("Expected UUID, found %r: %r"
  422. % (type(value), value))
  423. return value
  424. def parse_get(self, value, to_db):
  425. if to_db:
  426. return str(value)
  427. return value
  428. class EnumVariable(Variable):
  429. __slots__ = ("_get_map", "_set_map")
  430. def __init__(self, get_map, set_map, *args, **kwargs):
  431. self._get_map = get_map
  432. self._set_map = set_map
  433. Variable.__init__(self, *args, **kwargs)
  434. def parse_set(self, value, from_db):
  435. if from_db:
  436. return value
  437. try:
  438. return self._set_map[value]
  439. except KeyError:
  440. raise ValueError("Invalid enum value: %s" % repr(value))
  441. def parse_get(self, value, to_db):
  442. if to_db:
  443. return value
  444. try:
  445. return self._get_map[value]
  446. except KeyError:
  447. raise ValueError("Invalid enum value: %s" % repr(value))
  448. class MutableValueVariable(Variable):
  449. """
  450. A variable which contains a reference to mutable content. For this kind
  451. of variable, we can't simply detect when a modification has been made, so
  452. we have to synchronize the content of the variable when the store is
  453. flushing current objects, to check if the state has changed.
  454. """
  455. __slots__ = ("_event_system")
  456. def __init__(self, *args, **kwargs):
  457. self._event_system = None
  458. Variable.__init__(self, *args, **kwargs)
  459. if self.event is not None:
  460. self.event.hook("start-tracking-changes", self._start_tracking)
  461. self.event.hook("object-deleted", self._detect_changes_and_stop)
  462. def _start_tracking(self, obj_info, event_system):
  463. self._event_system = event_system
  464. self.event.hook("stop-tracking-changes", self._stop_tracking)
  465. def _stop_tracking(self, obj_info, event_system):
  466. event_system.unhook("flush", self._detect_changes)
  467. self._event_system = None
  468. def _detect_changes(self, obj_info):
  469. if (self._checkpoint_state is not Undef and
  470. self.get_state() != self._checkpoint_state):
  471. self.event.emit("changed", self, None, self._value, False)
  472. def _detect_changes_and_stop(self, obj_info):
  473. self._detect_changes(obj_info)
  474. if self._event_system is not None:
  475. self._stop_tracking(obj_info, self._event_system)
  476. def get(self, default=None, to_db=False):
  477. if self._event_system is not None:
  478. self._event_system.hook("flush", self._detect_changes)
  479. return super(MutableValueVariable, self).get(default, to_db)
  480. def set(self, value, from_db=False):
  481. if self._event_system is not None:
  482. if isinstance(value, LazyValue):
  483. self._event_system.unhook("flush", self._detect_changes)
  484. else:
  485. self._event_system.hook("flush", self._detect_changes)
  486. super(MutableValueVariable, self).set(value, from_db)
  487. class PickleVariable(MutableValueVariable):
  488. __slots__ = ()
  489. def parse_set(self, value, from_db):
  490. if from_db:
  491. if isinstance(value, buffer):
  492. value = str(value)
  493. return pickle.loads(value)
  494. else:
  495. return value
  496. def parse_get(self, value, to_db):
  497. if to_db:
  498. return pickle.dumps(value, -1)
  499. else:
  500. return value
  501. def get_state(self):
  502. return (self._lazy_value, pickle.dumps(self._value, -1))
  503. def set_state(self, state):
  504. self._lazy_value = state[0]
  505. self._value = pickle.loads(state[1])
  506. class ListVariable(MutableValueVariable):
  507. __slots__ = ("_item_factory",)
  508. def __init__(self, item_factory, *args, **kwargs):
  509. self._item_factory = item_factory
  510. MutableValueVariable.__init__(self, *args, **kwargs)
  511. def parse_set(self, value, from_db):
  512. if from_db:
  513. item_factory = self._item_factory
  514. return [item_factory(value=val, from_db=from_db).get()
  515. for val in value]
  516. else:
  517. return value
  518. def parse_get(self, value, to_db):
  519. if to_db:
  520. item_factory = self._item_factory
  521. return [item_factory(value=val, from_db=False) for val in value]
  522. else:
  523. return value
  524. def get_state(self):
  525. return (self._lazy_value, pickle.dumps(self._value, -1))
  526. def set_state(self, state):
  527. self._lazy_value = state[0]
  528. self._value = pickle.loads(state[1])
  529. def _parse_time(time_str):
  530. # TODO Add support for timezones.
  531. colons = time_str.count(":")
  532. if not 1 <= colons <= 2:
  533. raise ValueError("Unknown time format: %r" % time_str)
  534. if colons == 2:
  535. hour, minute, second = time_str.split(":")
  536. else:
  537. hour, minute = time_str.split(":")
  538. second = "0"
  539. if "." in second:
  540. second, microsecond = second.split(".")
  541. second = int(second)
  542. microsecond = int(int(microsecond) * 10 ** (6 - len(microsecond)))
  543. return int(hour), int(minute), second, microsecond
  544. return int(hour), int(minute), int(second), 0
  545. def _parse_date(date_str):
  546. if "-" not in date_str:
  547. raise ValueError("Unknown date format: %r" % date_str)
  548. year, month, day = date_str.split("-")
  549. return int(year), int(month), int(day)
  550. def _parse_interval_table():
  551. table = {}
  552. for units, delta in (
  553. ("d day days", timedelta),
  554. ("h hour hours", lambda x: timedelta(hours=x)),
  555. ("m min minute minutes", lambda x: timedelta(minutes=x)),
  556. ("s sec second seconds", lambda x: timedelta(seconds=x)),
  557. ("ms millisecond milliseconds", lambda x: timedelta(milliseconds=x)),
  558. ("microsecond microseconds", lambda x: timedelta(microseconds=x))
  559. ):
  560. for unit in units.split():
  561. table[unit] = delta
  562. return table
  563. _parse_interval_table = _parse_interval_table()
  564. _parse_interval_re = re.compile(r"[\s,]*"
  565. r"([-+]?(?:\d\d?:\d\d?(?::\d\d?)?(?:\.\d+)?"
  566. r"|\d+(?:\.\d+)?))"
  567. r"[\s,]*")
  568. def _parse_interval(interval):
  569. result = timedelta(0)
  570. value = None
  571. for token in _parse_interval_re.split(interval):
  572. if not token:
  573. pass
  574. elif ":" in token:
  575. if value is not None:
  576. result += timedelta(days=value)
  577. value = None
  578. h, m, s, ms = _parse_time(token)
  579. result += timedelta(hours=h, minutes=m, seconds=s, microseconds=ms)
  580. elif value is None:
  581. try:
  582. value = float(token)
  583. except ValueError:
  584. raise ValueError("Expected an interval value rather than "
  585. "%r in interval %r" % (token, interval))
  586. else:
  587. unit = _parse_interval_table.get(token)
  588. if unit is None:
  589. raise ValueError("Unsupported interval unit %r in interval %r"
  590. % (token, interval))
  591. result += unit(value)
  592. value = None
  593. if value is not None:
  594. result += timedelta(seconds=value)
  595. return result