"""gludb.backends.sqlite - backend sqlite database module
"""

# TODO: support indexes

import sqlite3

from uuid import uuid4


def uuid():
    return uuid4().hex


class Backend(object):
    def __init__(self, **kwrds):
        self.filename = kwrds.get('filename', '')
        if not self.filename:
            raise ValueError('sqlite backend requires a filename parameter')

        self.conn = sqlite3.connect(self.filename)

    def ensure_table(self, cls):
        cur = self.conn.cursor()

        cur.execute(
            'create table if not exists ' + cls.get_table_name() +
            ' (id text primary key, value text)'
        )
        self.conn.commit()
        cur.close()

    def find_one(self, cls, id):
        cur = self.conn.cursor()

        cur.execute(
            'select id,value from ' + cls.get_table_name() + ' where id = ?',
            (id,)
        )

        rec = cur.fetchone()
        id, data = rec[0], rec[1]
        obj = cls.from_data(data)
        assert id == obj.id

        cur.close()

        return obj

    def find_all(self, cls):
        cur = self.conn.cursor()

        found = []
        for row in cur.execute('select id,value from ' + cls.get_table_name()):
            id, data = row[0], row[1]
            obj = cls.from_data(data)
            assert id == obj.id
            found.append(obj)

        cur.close()

        return found

    def save(self, obj):
        cur = self.conn.cursor()

        tabname = obj.__class__.get_table_name()

        if not obj.id:
            id = uuid()
            obj.id = id

        cur.execute(
            'insert or replace into ' + tabname + '(id,value) values (?, ?)',
            (obj.id, obj.to_data())
        )
        self.conn.commit()

        cur.close()

@@ -504,137 +504,546 @@
     
-cur.execute(%0A            'create table if not exists ' + cls.get_table_name() +%0A            ' (id text primary key, value text)'%0A
+table_name = cls.get_table_name()%0A        index_names = cls.index_names() or %5B%5D%0A%0A        cols = %5B'id text primary key', 'value text'%5D%0A        for name in index_names:%0A            cols.append(name + ' text')%0A%0A        cur.execute('create table if not exists %25s (%25s)' %25 (%0A            table_name,%0A            ','.join(cols)%0A        ))%0A%0A        for name in index_names:%0A            cur.execute('create index if not exists %25s on %25s(%25s)' %25 (%0A                table_name + '_' + name + '_idx',%0A                table_name,%0A                name%0A    
     
@@ -1039,32 +1039,34 @@
 me%0A            )
+)%0A
 %0A        self.co

index creation in sqlite