##############################################################################
from cursor import Cursor
-import uuid
+from objectid import ObjectId
class Collection(object):
def __init__(self, database, table_name):
else:
docs = doc_or_docs
for doc in docs:
- doc_id = uuid.uuid4().hex
+ doc_id = str(ObjectId())
if not '_id' in doc:
doc['_id'] = doc_id
self._insert_document(doc_id, doc)
--- /dev/null
+# -*- coding: utf-8 -*-
+##############################################################################
+#
+# mojo, a Python library for implementing document based databases
+# Copyright (C) 2013-2014 by Javier Sancho Fernandez <jsf at jsancho dot org>
+#
+# This program 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 program 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 this program. If not, see <http://www.gnu.org/licenses/>.
+#
+##############################################################################
+
+import binascii
+import hashlib
+import os
+import random
+import socket
+import struct
+import time
+import threading
+
+class ObjectId(object):
+ _inc = random.randint(0, 0xFFFFFF)
+ _inc_lock = threading.Lock()
+
+ __id = ""
+
+ def __init__(self):
+ self.__generate()
+
+ def __generate(self):
+ oid = ""
+ # Secons since the Unix epoch
+ oid += struct.pack(">i", int(time.time()))
+ # Machine Identifier
+ machine_hash = hashlib.md5()
+ machine_hash.update(socket.gethostname())
+ oid += machine_hash.digest()[0:3]
+ # Process Id
+ oid += struct.pack(">H", os.getpid() % 0xFFFF)
+ # Counter
+ ObjectId._inc_lock.acquire()
+ oid += struct.pack(">i", ObjectId._inc)[1:4]
+ ObjectId._inc += 1
+ ObjectId._inc_lock.release()
+
+ self.__id = oid
+
+ def __str__(self):
+ return binascii.hexlify(self.__id)
+
+ def __repr__(self):
+ return "ObjectId('%s')" % (str(self),)