# Elisa - Home multimedia server
# Copyright (C) 2006-2008 Fluendo Embedded S.L. (www.fluendo.com).
# All rights reserved.
#
# This file is available under one of two license agreements.
#
# This file is licensed under the GPL version 3.
# See "LICENSE.GPL" in the root of this distribution including a special
# exception to use Elisa with Fluendo's plugins.
#
# The GPL part of Elisa is also available under a commercial licensing
# agreement from Fluendo.
# See "LICENSE.Elisa" in the root directory of this distribution package
# for details on that license.

from elisa.core.tests.elisa_test_case import ElisaTestCase
from elisa.core import db_backend
from elisa.extern import db_row
import os, unittest, tempfile

SQL_SCHEMA="""\
CREATE TABLE core_meta (
    version INTEGER UNIQUE
);
"""

class TestDBBackend(ElisaTestCase):

    def __init__(self, methodName='runTest'):
        ElisaTestCase.__init__(self, methodName=methodName)
        self._db_file = os.path.join(tempfile.gettempdir(), 'test_db_backend.db')
        
        if os.path.exists(self._db_file):
            os.unlink(self._db_file)
            
        try:
            db = db_backend.DBBackend(db_backend='sqlite',
                                      database=self._db_file)
        except db_backend.DBBackendError, error:
            self.skip = error
        else:
            db.sql_execute(SQL_SCHEMA)
            db.sql_execute("insert into core_meta(version) values(1)")
            db.save_changes()
            
    def setUp(self):
        ElisaTestCase.setUp(self)
        self._db = db_backend.DBBackend(db_backend='sqlite',
                                        database=self._db_file)

    def test_sql_execute(self):

        result = self._db.sql_execute("select * from core_meta")
        self.failUnless(isinstance(result, list))
        self.failUnless(len(result) > 0)
        for row in result:
            self.failUnless(isinstance(row, db_row.DBRow))


        failed = self._db.sql_execute("select * from unknow_table")
        self.assertEqual(failed, [])
