Skip to content

Commit

Permalink
[model]: Fix tests on sqlite for datetime field, broken when sqlalche…
Browse files Browse the repository at this point in the history
…my changed to 0.7.
  • Loading branch information
David Read committed Nov 16, 2011
1 parent 6744cc9 commit ed81036
Show file tree
Hide file tree
Showing 2 changed files with 23 additions and 5 deletions.
7 changes: 4 additions & 3 deletions ckan/model/package.py
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,7 @@
from meta import metadata, Session
import vdm.sqlalchemy

from types import make_uuid
from types import make_uuid, iso_date_to_datetime_for_sqlite
from core import make_revisioned_table, Revision, State
from license import License, LicenseRegister
from domain_object import DomainObject
Expand Down Expand Up @@ -485,8 +485,9 @@ def last_modified(*av):
conn = model.meta.engine.connect()
result = conn.execute(query).fetchone()
if result:
timestamp = result[0].utctimetuple()
usecs = float(result[0].microsecond) / 1e6
result_datetime = iso_date_to_datetime_for_sqlite(result[0])
timestamp = result_datetime.utctimetuple()
usecs = float(result_datetime.microsecond) / 1e6
else:
timestamp, usecs = gmtime(), 0
# use timegm instead of mktime, because we don't want it localised
Expand Down
21 changes: 19 additions & 2 deletions ckan/model/types.py
Original file line number Diff line number Diff line change
@@ -1,6 +1,10 @@
from sqlalchemy import types
import datetime
import copy

from sqlalchemy import types

from pylons import config

def make_uuid():
return unicode(uuid.uuid4())

Expand Down Expand Up @@ -28,7 +32,7 @@ def default(cls):
class JsonType(types.TypeDecorator):
'''Store data as JSON serializing on save and unserializing on use.
Note that default values don't appear to work correctly with this
Note that default values don\'t appear to work correctly with this
type, a workaround is to instead override ``__init__()`` to explicitly
set any default values you expect.
'''
Expand Down Expand Up @@ -71,3 +75,16 @@ def process_bind_param(self, value, engine):

def copy(self):
return JsonDictType(self.impl.length)

def iso_date_to_datetime_for_sqlite(datetime_or_iso_date_if_sqlite):
# Because sqlite cannot store dates properly (see this:
# http://www.sqlalchemy.org/docs/dialects/sqlite.html#date-and-time-types )
# when you get a result from a date field in the database, you need
# to call this to convert it into a datetime type. When running on
# postgres then you have a datetime anyway, so this function doesn't
# do anything.
if config['sqlalchemy.url'].startswith('sqlite:'):
return datetime.datetime.strptime(datetime_or_iso_date_if_sqlite,
'%Y-%m-%d %H:%M:%S.%f')
else:
return datetime_or_iso_date_if_sqlite

0 comments on commit ed81036

Please sign in to comment.