Skip to content

Commit

Permalink
Browse files Browse the repository at this point in the history
  • Loading branch information
flaper87 committed Oct 18, 2010
1 parent dfad91a commit 01e90d6
Show file tree
Hide file tree
Showing 43 changed files with 1,998 additions and 334 deletions.
4 changes: 4 additions & 0 deletions CONTRIBUTORS
Original file line number Diff line number Diff line change
@@ -0,0 +1,4 @@
* kryton (http://github.com/kryton)

For an up-to-date list of contributors, see
http://github.com/django-mongodb-engine/mongodb-engine/contributors.
19 changes: 10 additions & 9 deletions django_mongodb_engine/__init__.py
Original file line number Diff line number Diff line change
@@ -1,13 +1,14 @@
#!/usr/bin/python
# -*- coding: utf-8 -*-

import logging
logger = logging.getLogger(__name__)
__version__ = (0, 2, 0)
__author__ = "Flavio Percoco Premoli, Alberto Paro, Jonas Haag and contributors"
__contact__ = "django-non-relational@googlegroups.com"
__homepage__ = "http://github.com/django-mongodb-engine/mongodb-engine"
__docformat__ = "restructuredtext"

VERSION = (0, 1, 1)

__version__ = ".".join(map(str, VERSION[0:3])) + "".join(VERSION[3:])
__author__ = "Flavio Percoco Premoli"
__contact__ = "flaper87@flaper87.org"
__homepage__ = "http://github.com/FlaPer87/django-mongodb-engine/"
__docformat__ = "restructuredtext"
try:
from django.conf import settings
import _bootstrap
except ImportError:
pass
10 changes: 10 additions & 0 deletions django_mongodb_engine/_bootstrap.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,10 @@
from django.db import models

def class_prepared_mongodb_signal(sender, *args, **kwargs):
mongo_meta = getattr(sender, 'MongoMeta', None)
if mongo_meta is not None:
for attr, value in mongo_meta.items():
if not attr.startswith('_'):
setattr(model._meta, attr, value)

models.signals.class_prepared.connect(class_prepared_mongodb_signal)
141 changes: 141 additions & 0 deletions django_mongodb_engine/base.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,141 @@
from django.core.exceptions import ImproperlyConfigured

import pymongo
from .creation import DatabaseCreation
from .client import DatabaseClient

from djangotoolbox.db.base import (
NonrelDatabaseFeatures, NonrelDatabaseWrapper,
NonrelDatabaseClient, NonrelDatabaseValidation,
NonrelDatabaseIntrospection, NonrelDatabaseOperations
)

class ImproperlyConfiguredWarning(Warning):
pass

class DatabaseFeatures(NonrelDatabaseFeatures):
string_based_auto_field = True


class DatabaseOperations(NonrelDatabaseOperations):
compiler_module = __name__.rsplit('.', 1)[0] + '.compiler'

def max_name_length(self):
return 254

def check_aggregate_support(self, aggregate):
from django.db.models.sql.aggregates import Max, Count
if not isinstance(aggregate, (Count)):
raise NotImplementedError("This database does not support %r "
"aggregates" % type(aggregate))

def sql_flush(self, style, tables, sequence_list):
"""
Returns a list of SQL statements that have to be executed to drop
all `tables`. No SQL in MongoDB, so just drop all tables here and
return an empty list.
"""
tables = self.connection.db_connection.collection_names()
for table in tables:
if table.startswith('system.'):
# no do not system collections
continue
self.connection.db_connection.drop_collection(table)
return []

class DatabaseValidation(NonrelDatabaseValidation):
pass

class DatabaseIntrospection(NonrelDatabaseIntrospection):
"""Database Introspection"""

def table_names(self):
""" Show defined models """
return self.connection.db_connection.collection_names()

def sequence_list(self):
# Only required for backends that support ManyToMany relations
pass

class DatabaseWrapper(NonrelDatabaseWrapper):
safe_inserts = False
wait_for_slaves = 0
_connected = False

def __init__(self, *args, **kwargs):
super(DatabaseWrapper, self).__init__(*args, **kwargs)
self.features = DatabaseFeatures(self)
self.ops = DatabaseOperations(self)
self.client = DatabaseClient(self)
self.creation = DatabaseCreation(self)
self.validation = DatabaseValidation(self)
self.introspection = DatabaseIntrospection(self)

def _cursor(self):
self._connect()
return self._connection

@property
def db_connection(self):
"""
Returns the db_connection instance (a :class:`pymongo.database.Database`)
"""
self._connect()
return self._db_connection

def _connect(self):
if not self._connected:
host = self.settings_dict['HOST'] or None
port = self.settings_dict['PORT'] or None
user = self.settings_dict.get('USER', None)
password = self.settings_dict.get('PASSWORD')
self.db_name = self.settings_dict['NAME']
self.safe_inserts = self.settings_dict.get('SAFE_INSERTS', False)
self.wait_for_slaves = self.settings_dict.get('WAIT_FOR_SLAVES', 0)
slave_okay = self.settings_dict.get('SLAVE_OKAY', False)

try:
if host is not None:
if pymongo.version >= '1.8':
assert isinstance(host, (basestring, list)), \
'If set, HOST must be a string or a list of strings'
else:
assert isinstance(host, basestring), 'If set, HOST must be a string'

if port:
if isinstance(host, basestring) and host.startswith('mongodb://'):
# If host starts with mongodb:// the port will be
# ignored so lets make sure it is None
port = None
import warnings
warnings.warn(
"If 'HOST' is a mongodb:// URL, the 'PORT' setting "
"will be ignored", ImproperlyConfiguredWarning
)
else:
try:
port = int(port)
except ValueError:
raise ImproperlyConfigured('If set, PORT must be an integer')

assert isinstance(self.safe_inserts, bool), 'If set, SAFE_INSERTS must be True or False'
assert isinstance(self.wait_for_slaves, int), 'If set, WAIT_FOR_SLAVES must be an integer'
except AssertionError, e:
raise ImproperlyConfigured(e)

self._connection = pymongo.Connection(host=host, port=port, slave_okay=slave_okay)

if user and password:
auth = self._connection[self.db_name].authenticate(user, password)
if not auth:
raise ImproperlyConfigured("Username and/or password for "
"the MongoDB are not correct")

self._db_connection = self._connection[self.db_name]

from .serializer import TransformDjango
self._db_connection.add_son_manipulator(TransformDjango())
# We're done!
self._connected = True

# TODO: signal! (see Alex' backend)
4 changes: 4 additions & 0 deletions django_mongodb_engine/client.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,4 @@
from django.db.backends import BaseDatabaseClient

class DatabaseClient(BaseDatabaseClient):
executable_name = 'mongo'
Loading

0 comments on commit 01e90d6

Please sign in to comment.