Backend trash and container/object purge.
[pithos] / pithos / backends / simple.py
index f93d5b6..220bca2 100644 (file)
@@ -65,6 +65,10 @@ class SimpleBackend(BaseBackend):
             os.makedirs(basepath)
         
         self.con = sqlite3.connect(db, check_same_thread=False)
+        
+        sql = '''pragma foreign_keys = on'''
+        self.con.execute(sql)
+        
         sql = '''create table if not exists versions (
                     version_id integer primary key,
                     name text,
@@ -74,22 +78,37 @@ class SimpleBackend(BaseBackend):
                     hide integer default 0)'''
         self.con.execute(sql)
         sql = '''create table if not exists metadata (
-                    version_id integer, key text, value text, primary key (version_id, key))'''
+                    version_id integer,
+                    key text,
+                    value text,
+                    primary key (version_id, key)
+                    foreign key (version_id) references versions(version_id)
+                    on delete cascade)'''
+        self.con.execute(sql)
+        sql = '''create table if not exists hashmaps (
+                    version_id integer,
+                    pos integer,
+                    block_id text,
+                    primary key (version_id, pos)
+                    foreign key (version_id) references versions(version_id)
+                    on delete cascade)'''
         self.con.execute(sql)
         sql = '''create table if not exists blocks (
                     block_id text, data blob, primary key (block_id))'''
         self.con.execute(sql)
-        sql = '''create table if not exists hashmaps (
-                    version_id integer, pos integer, block_id text, primary key (version_id, pos))'''
+        
+        sql = '''create table if not exists policy (
+                    name text, key text, value text, primary key (name, key))'''
         self.con.execute(sql)
+        
         sql = '''create table if not exists groups (
                     account text, name text, users text, primary key (account, name))'''
         self.con.execute(sql)
         sql = '''create table if not exists permissions (
                     name text, read text, write text, primary key (name))'''
         self.con.execute(sql)
-        sql = '''create table if not exists policy (
-                    name text, key text, value text, primary key (name, key))'''
+        sql = '''create table if not exists public (
+                    name text, primary key (name))'''
         self.con.execute(sql)
         self.con.commit()
     
@@ -167,16 +186,34 @@ class SimpleBackend(BaseBackend):
                 self.con.execute(sql, (account, k, ','.join(v)))
         self.con.commit()
     
+    def put_account(self, user, account):
+        """Create a new account with the given name."""
+        
+        logger.debug("put_account: %s", account)
+        if user != account:
+            raise NotAllowedError
+        try:
+            version_id, mtime = self._get_accountinfo(account)
+        except NameError:
+            pass
+        else:
+            raise NameError('Account already exists')
+        version_id = self._put_version(account, user)
+        self.con.commit()
+    
     def delete_account(self, user, account):
         """Delete the account with the given name."""
         
         logger.debug("delete_account: %s", account)
         if user != account:
             raise NotAllowedError
-        count, bytes, tstamp = self._get_pathstats(account)
-        if count > 0:
+        if self._get_pathcount(account) > 0:
             raise IndexError('Account is not empty')
-        self._del_path(account) # Point of no return.
+        sql = 'delete from versions where name = ?'
+        self.con.execute(sql, (path,))
+        sql = 'delete from groups where name = ?'
+        self.con.execute(sql, (account,))
+        self.con.commit()
     
     def list_containers(self, user, account, marker=None, limit=10000, until=None):
         """Return a list of containers existing under an account."""
@@ -268,18 +305,33 @@ class SimpleBackend(BaseBackend):
             self.con.execute(sql, (path, k, v))
         self.con.commit()
     
-    def delete_container(self, user, account, container):
+    def delete_container(self, user, account, container, until=None):
         """Delete the container with the given name."""
         
-        logger.debug("delete_container: %s %s", account, container)
+        logger.debug("delete_container: %s %s %s", account, container, until)
         if user != account:
             raise NotAllowedError
         path, version_id, mtime = self._get_containerinfo(account, container)
-        count, bytes, tstamp = self._get_pathstats(path)
-        if count > 0:
+        
+        if until is not None:
+            sql = '''select version_id from versions where name like ? and tstamp <= datetime(%s, 'unixepoch')'''
+            c = self.con.execute(sql, (path + '/%', until))
+            versions = [x[0] for x in c.fetchall()]
+            for v in versions:
+                sql = 'delete from hashmaps where version_id = ?'
+                self.con.execute(sql, (v,))
+                sql = 'delete from versions where version_id = ?'
+                self.con.execute(sql, (v,))
+            self.con.commit()
+            return
+        
+        if self._get_pathcount(path) > 0:
             raise IndexError('Container is not empty')
-        self._del_path(path) # Point of no return.
-        self._copy_version(user, account, account, True, True) # New account version.
+        sql = 'delete from versions where name = ?'
+        self.con.execute(sql, (path,))
+        sql = 'delete from policy where name = ?'
+        self.con.execute(sql, (path,))
+        self._copy_version(user, account, account, True, True) # New account version (for timestamp update).
     
     def list_objects(self, user, account, container, prefix='', delimiter=None, marker=None, limit=10000, virtual=True, keys=[], until=None):
         """Return a list of objects existing under a container."""
@@ -351,13 +403,19 @@ class SimpleBackend(BaseBackend):
         """Return the public URL of the object if applicable."""
         
         logger.debug("get_object_public: %s %s %s", account, container, name)
+        self._can_read(user, account, container, name)
+        path = self._get_objectinfo(account, container, name)[0]
+        if self._get_public(path):
+            return '/public/' + path
         return None
     
     def update_object_public(self, user, account, container, name, public):
         """Update the public status of the object."""
         
         logger.debug("update_object_public: %s %s %s %s", account, container, name, public)
-        return
+        self._can_write(user, account, container, name)
+        path = self._get_objectinfo(account, container, name)[0]
+        self._put_public(path, public)
     
     def get_object_hashmap(self, user, account, container, name, version=None):
         """Return the object's size and a list with partial hashes."""
@@ -439,18 +497,57 @@ class SimpleBackend(BaseBackend):
         self.copy_object(user, account, src_container, src_name, dest_container, dest_name, dest_meta, replace_meta, permissions, None)
         self.delete_object(user, account, src_container, src_name)
     
-    def delete_object(self, user, account, container, name):
+    def delete_object(self, user, account, container, name, until=None):
         """Delete an object."""
         
-        logger.debug("delete_object: %s %s %s", account, container, name)
+        logger.debug("delete_object: %s %s %s %s", account, container, name, until)
         if user != account:
             raise NotAllowedError
-        path = self._get_objectinfo(account, container, name)[0]
-        self._put_version(path, user, 0, 1)
-        sql = 'delete from permissions where name = ?'
-        self.con.execute(sql, (path,))
+        if until is None:
+            path = self._get_objectinfo(account, container, name)[0]
+            sql = 'select version_id from versions where name = ?'
+            c = self.con.execute(sql, (path,))
+        else:
+            path = os.path.join(account, container, name)
+            sql = '''select version_id from versions where name = ? and tstamp <= datetime(%s, 'unixepoch')'''
+            c = self.con.execute(sql, (path, until))
+        versions = [x[0] for x in c.fetchall()]
+        for v in versions:
+            sql = 'delete from hashmaps where version_id = ?'
+            self.con.execute(sql, (v,))
+            sql = 'delete from versions where version_id = ?'
+            self.con.execute(sql, (v,))
+        
+        # If no more versions exist, delete permissions/public.
+        sql = 'select version_id from versions where name = ?'
+        row = self.con.execute(sql, (path,)).fetchone()
+        if row is None:
+            self._del_sharing(path)
         self.con.commit()
     
+    def update_object_trash(self, user, account, container, name, trash=True):
+        """Trash/untrash an object."""
+        
+        logger.debug("trash_object: %s %s %s", account, container, name)
+        if user != account:
+            raise NotAllowedError
+        if trash:
+            path, version_id, muser, mtime, size = self._get_objectinfo(account, container, name)
+            self._del_sharing(path)
+        else:
+            path = os.path.join(account, container, name)
+            sql = '''select version_id, hide from versions where name = ?
+                        order by version_id desc limit 1'''
+            c = self.con.execute(sql, (path,))
+            row = c.fetchone()
+            if not row or not int(row[1]):
+                raise NameError('Object not in trash')
+            version_id = row[0]
+        hide = 1 if trash else 0
+        sql = 'update versions set hide = ? where version_id = ?'
+        self.con.execute(sql, (hide, version_id,))
+        seld.con.commit()
+    
     def list_versions(self, user, account, container, name):
         """Return a list of all (version, version_timestamp) tuples for an object."""
         
@@ -458,7 +555,7 @@ class SimpleBackend(BaseBackend):
         self._can_read(user, account, container, name)
         # This will even show deleted versions.
         path = os.path.join(account, container, name)
-        sql = '''select distinct version_id, strftime('%s', tstamp) from versions where name = ? and hide = 0'''
+        sql = '''select distinct version_id, strftime('%s', tstamp) from versions where name = ?'''
         c = self.con.execute(sql, (path,))
         return [(int(x[0]), int(x[1])) for x in c.fetchall()]
     
@@ -509,7 +606,7 @@ class SimpleBackend(BaseBackend):
         return sql % ('%s', until)
     
     def _get_pathstats(self, path, until=None):
-        """Return count and sum of size of everything under path and latest timestamp."""
+        """Return count, sum of size and latest timestamp of everything under path (latest versions/no trash)."""
         
         sql = 'select count(version_id), total(size), max(tstamp) from (%s) where name like ?'
         sql = sql % self._sql_until(until)
@@ -518,6 +615,14 @@ class SimpleBackend(BaseBackend):
         tstamp = row[2] if row[2] is not None else 0
         return int(row[0]), int(row[1]), int(tstamp)
     
+    def _get_pathcount(self, path):
+        """Return count of everything under path (including versions/trash)."""
+        
+        sql = 'select count(version_id) from versions where name like ?'
+        c = self.con.execute(sql, (path + '/%',))
+        row = c.fetchone()
+        return int(row[0])
+    
     def _get_version(self, path, version=None):
         if version is None:
             sql = '''select version_id, user, strftime('%s', tstamp), size, hide from versions where name = ?
@@ -536,9 +641,9 @@ class SimpleBackend(BaseBackend):
                 raise IndexError('Version does not exist')
         return str(row[0]), str(row[1]), int(row[2]), int(row[3])
     
-    def _put_version(self, path, user, size=0, hide=0):
-        sql = 'insert into versions (name, user, size, hide) values (?, ?, ?, ?)'
-        id = self.con.execute(sql, (path, user, size, hide)).lastrowid
+    def _put_version(self, path, user, size=0):
+        sql = 'insert into versions (name, user, size) values (?, ?, ?)'
+        id = self.con.execute(sql, (path, user, size)).lastrowid
         self.con.commit()
         return str(id)
     
@@ -649,18 +754,19 @@ class SimpleBackend(BaseBackend):
         if user == account:
             return True
         path = os.path.join(account, container, name)
+        if op == 'read' and self._get_public(path):
+            return True
         perm_path, perms = self._get_permissions(path)
         
         # Expand groups.
         for x in ('read', 'write'):
             g_perms = []
             for y in perms.get(x, []):
-                if ':' in y:
-                    g_account, g_name = y.split(':', 1)
-                    groups = self._get_groups(g_account)
-                    if g_name in groups:
-                        g_perms += groups[g_name]
-                else:
+                groups = self._get_groups(account)
+                if y in groups: #it's a group
+                    for g_name in groups[y]:
+                        g_perms.append(g_name)
+                else: #it's a user
                     g_perms.append(y)
             perms[x] = g_perms
         
@@ -683,9 +789,11 @@ class SimpleBackend(BaseBackend):
         sql = '''select name from permissions
                     where name != ? and (name like ? or ? like name || ?)'''
         c = self.con.execute(sql, (path, path + '%', path, '%'))
-        rows = c.fetchall()
-        if rows:
-            raise AttributeError('Permissions already set')
+        row = c.fetchone()
+        if row:
+            ae = AttributeError()
+            ae.data = row[0]
+            raise ae
         
         # Format given permissions.
         if len(permissions) == 0:
@@ -723,6 +831,29 @@ class SimpleBackend(BaseBackend):
             self.con.execute(sql, (path, r, w))
         self.con.commit()
     
+    def _get_public(self, path):
+        sql = 'select name from public where name = ?'
+        c = self.con.execute(sql, (path,))
+        row = c.fetchone()
+        if not row:
+            return False
+        return True
+    
+    def _put_public(self, path, public):
+        if not public:
+            sql = 'delete from public where name = ?'
+        else:
+            sql = 'insert or replace into public (name) values (?)'
+        self.con.execute(sql, (path,))
+        self.con.commit()
+    
+    def _del_sharing(self, path):
+        sql = 'delete from permissions where name = ?'
+        self.con.execute(sql, (path,))
+        sql = 'delete from public where name = ?'
+        self.con.execute(sql, (path,))
+        self.con.commit()
+    
     def _list_objects(self, path, prefix='', delimiter=None, marker=None, limit=10000, virtual=True, keys=[], until=None):
         cont_prefix = path + '/'
         if keys and len(keys) > 0:
@@ -766,16 +897,3 @@ class SimpleBackend(BaseBackend):
         if not limit or limit > 10000:
             limit = 10000
         return objects[start:start + limit]
-    
-    def _del_path(self, path):
-        sql = '''delete from hashmaps where version_id in
-                    (select version_id from versions where name = ?)'''
-        self.con.execute(sql, (path,))
-        sql = '''delete from metadata where version_id in
-                    (select version_id from versions where name = ?)'''
-        self.con.execute(sql, (path,))
-        sql = '''delete from versions where name = ?'''
-        self.con.execute(sql, (path,))
-        sql = '''delete from permissions where name like ?'''
-        self.con.execute(sql, (path + '%',)) # Redundant.
-        self.con.commit()