Skip to content
database.py 1.92 KiB
Newer Older
# -*- python -*-
# -*- coding: utf-8 -*-
# Started 24/05/2011 by Seblu <seblu@seblu.net>

'''
Database stuff
'''

import os
Seblu's avatar
Seblu committed
import sqlite3
import installsystems.tools as istools
Seblu's avatar
Seblu committed
import installsystems.template as istemplate
from installsystems.tarball import Tarball
from installsystems.printer import *

class Database(object):
    '''
    Abstract repo database stuff
Seblu's avatar
Seblu committed
    It needs to be local cause of sqlite3 which need to open a file
    '''

    db_format = "1"

    @classmethod
Seblu's avatar
Seblu committed
    def create(cls, path):
        arrow("Creating repository database")
        # check locality
        if not istools.isfile(path):
Seblu's avatar
Seblu committed
            raise Exception("Database creation must be local")
Seblu's avatar
Seblu committed
        path = os.path.abspath(path)
        if os.path.exists(path):
            raise Exception("Database already exists. Remove it before")
Seblu's avatar
Seblu committed
            conn = sqlite3.connect(path, isolation_level=None)
            conn.execute("PRAGMA foreign_keys = ON")
            conn.executescript(istemplate.createdb)
            conn.commit()
            conn.close()
        except Exception as e:
            raise Exception("Create database failed: %s" % e)
Seblu's avatar
Seblu committed
        return cls(path)
Seblu's avatar
Seblu committed
    def __init__(self, path):
Seblu's avatar
Seblu committed
        # check locality
        if not istools.isfile(path):
Seblu's avatar
Seblu committed
            raise Exception("Database must be local")
Seblu's avatar
Seblu committed
        self.path = os.path.abspath(path)
Sebastien Luttringer's avatar
Sebastien Luttringer committed
        if not os.path.exists(self.path):
            raise Exception("Database not exists")
Seblu's avatar
Seblu committed
        self.conn = sqlite3.connect(self.path, isolation_level=None)
        self.conn.execute("PRAGMA foreign_keys = ON")
Seblu's avatar
Seblu committed
    def begin(self):
        '''
        Start a db transaction
        '''
        self.conn.execute("BEGIN TRANSACTION")

    def commit(self):
        '''
        Commit current db transaction
        '''
        self.conn.execute("COMMIT TRANSACTION")

Seblu's avatar
Seblu committed
    def ask(self, sql, args=()):
Seblu's avatar
Seblu committed
        '''
        Ask question to db
        '''
Seblu's avatar
Seblu committed
        return self.conn.execute(sql, args)