Folder.cpp 2.58 KB
Newer Older
1
2
3
4
5
6
7
8
#include "Folder.h"
#include "File.h"

#include "SqliteTools.h"

namespace policy
{
    const std::string FolderTable::Name = "Folder";
9
    const std::string FolderTable::CacheColumn = "path";
10
    unsigned int Folder::* const FolderTable::PrimaryKey = &Folder::m_id;
11
12
13
14
15
16
17
18
19
20
21

    const FolderCache::KeyType&FolderCache::key(const std::shared_ptr<Folder>& self)
    {
        return self->path();
    }

    FolderCache::KeyType FolderCache::key( sqlite3_stmt* stmt )
    {
        return Traits<FolderCache::KeyType>::Load( stmt, 1 );
    }

22
23
24
25
26
27
28
}

Folder::Folder( DBConnection dbConnection, sqlite3_stmt* stmt )
    : m_dbConection( dbConnection )
{
    m_id = Traits<unsigned int>::Load( stmt, 0 );
    m_path = Traits<std::string>::Load( stmt, 1 );
29
    m_parent = Traits<unsigned int>::Load( stmt, 2 );
30
31
}

32
Folder::Folder( const std::string& path, unsigned int parent )
33
    : m_path( path )
34
    , m_parent( parent )
35
36
37
38
39
{
}

bool Folder::createTable(DBConnection connection)
{
40
41
42
43
44
45
46
    std::string req = "CREATE TABLE IF NOT EXISTS " + policy::FolderTable::Name +
            "("
            "id_folder INTEGER PRIMARY KEY AUTOINCREMENT,"
            "path TEXT UNIQUE ON CONFLICT FAIL,"
            "id_parent UNSIGNED INTEGER,"
            "FOREIGN KEY (id_parent) REFERENCES " + policy::FolderTable::Name +
            "(id_folder) ON DELETE CASCADE"
47
48
49
50
            ")";
    return SqliteTools::executeRequest( connection, req );
}

51
FolderPtr Folder::create(DBConnection connection, const std::string& path, unsigned int parent )
52
{
53
    auto self = std::make_shared<Folder>( path, parent );
54
    static const std::string req = "INSERT INTO " + policy::FolderTable::Name +
55
56
57
58
59
60
61
62
63
64
65
            "(path, id_parent) VALUES(?, ?)";
    if ( parent == 0 )
    {
        if ( _Cache::insert( connection, self, req, path, nullptr ) == false )
            return nullptr;
    }
    else
    {
        if ( _Cache::insert( connection, self, req, path, parent ) == false )
            return nullptr;
    }
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
    self->m_dbConection = connection;
    return self;
}

unsigned int Folder::id() const
{
    return m_id;
}

const std::string& Folder::path()
{
    return m_path;
}

std::vector<FilePtr> Folder::files()
{
82
83
    static const std::string req = "SELECT * FROM " + policy::FileTable::Name +
        " WHERE folder_id = ?";
84
    return SqliteTools::fetchAll<File, IFile>( m_dbConection, req, m_id );
85
}
86
87
88
89
90
91
92
93

FolderPtr Folder::parent()
{
    //FIXME: use path to be able to fetch from cache?
    static const std::string req = "SELECT * FROM " + policy::FolderTable::Name +
            " WHERE id_folder = ?";
    return SqliteTools::fetchOne<Folder>( m_dbConection, req, m_parent );
}