finished work on contacts search
[meabook] / database / SQLite.py
index b5e9514..a38a706 100644 (file)
@@ -1,3 +1,7 @@
+#!/usr/bin/python
+# -*- coding: utf-8 -*-
+
+
 import os
 import sqlite3
 
@@ -15,31 +19,28 @@ SCHEMA = """
         field_id text,
         value text
     );
+    create index i_data on data (id);
 
     create table fields(
         id integer primary key,
         name text
     );
+    create index i_fields on fields (id);
 
     create table relation(
         data_id integer,
         struct_id integer
     );
+    create index i_relation_data on relation(data_id);
 
     create table struct(
         id integer primary key,
         name text,
         parent integer
     );
-
+    create index i_struct_id on struct(parent);
     commit;
 
-    create index i_fields on fields (id);
-    create index i_data on data (id);
-    create index i_struct_id on parent struct(id);
-    create index i_relation_data on relation(data_id);
-
-    commit;
 """
 
 
@@ -50,19 +51,22 @@ class SQLite:
         if not os.path.exists(self._path):
             self.new()
         else:
-            self.conn = sqlite3.connect(self._path)
+            self.connect()
+
+    def connect(self):
+        """Connects to database."""
+
+        self.conn = sqlite3.connect(self._path, isolation_level="EXCLUSIVE")
 
     def new(self):
         """Creates new databse."""
 
-        self.conn = sqlite3.connect(self._path)
+        self.connect()
         self.conn.executescript(SCHEMA)
-        self.conn.commit()
 
     def close(self):
         """Closes connection with database."""
 
-        self.conn.commit()
         self.conn.close()
 
     def save(self):
@@ -83,8 +87,8 @@ class SQLite:
     def get_fields(self):
         """Returns all fields from FIELDS table."""
 
-        return [item[0] for item in self.conn.execute( \
-            "SELECT name FROM fields").fetchall()]
+        return [item[0] for item in self.conn.execute("SELECT name FROM \
+            fields").fetchall() if item[0]!='image']
 
     # operations with DATA table
     def add_entry(self, entry):
@@ -169,6 +173,17 @@ class SQLite:
                 items_dict[data_id][field_name] = field_value
         return items_dict
 
+    def get_files_by_pattern(self, pattern):
+        """Returns list of all files, matched pattern string."""
+
+        if not pattern:
+            return []
+        execute = self.conn.execute
+        field_id = execute("SELECT id FROM fields WHERE name=?", \
+            ('cn',)).fetchone()[0]
+        return execute("SELECT id, value FROM data WHERE value LIKE '%%%s%%' \
+            AND field_id=? LIMIT 50" % pattern, (field_id,)).fetchall()
+
     def get_entry(self, _id):
         """Returns full entry by it id."""