/[svn]/linuxsampler/trunk/src/db/InstrumentsDb.cpp
ViewVC logotype

Annotation of /linuxsampler/trunk/src/db/InstrumentsDb.cpp

Parent Directory Parent Directory | Revision Log Revision Log


Revision 3092 - (hide annotations) (download)
Mon Jan 16 22:02:36 2017 UTC (7 years, 3 months ago) by schoenebeck
File size: 71848 byte(s)
* Instruments DB: Added support for scanning SFZ (.sfz) files.
* Instruments DB: Added support for scanning Sound Font (.sf2) files.
* Bumped version (2.0.0.svn40).

1 iliev 1161 /***************************************************************************
2     * *
3 persson 2427 * Copyright (C) 2007-2013 Grigor Iliev, Benno Senoner *
4 iliev 1161 * *
5     * This program is free software; you can redistribute it and/or modify *
6     * it under the terms of the GNU General Public License as published by *
7     * the Free Software Foundation; either version 2 of the License, or *
8     * (at your option) any later version. *
9     * *
10     * This program is distributed in the hope that it will be useful, *
11     * but WITHOUT ANY WARRANTY; without even the implied warranty of *
12     * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the *
13     * GNU General Public License for more details. *
14     * *
15     * You should have received a copy of the GNU General Public License *
16     * along with this program; if not, write to the Free Software *
17     * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, *
18     * MA 02110-1301 USA *
19     ***************************************************************************/
20    
21     #include "InstrumentsDb.h"
22    
23 iliev 1717 #include "../common/File.h"
24 iliev 1782 #include "../common/Path.h"
25 schoenebeck 1424 #include "../common/global_private.h"
26 iliev 1161
27     #include <iostream>
28     #include <sstream>
29 iliev 1200 #include <vector>
30 persson 1944 #include <algorithm>
31 iliev 1161 #include <errno.h>
32 persson 1908 #ifndef WIN32
33 iliev 1187 #include <fnmatch.h>
34 senoner 1912 #else
35     #include <direct.h>
36 persson 1908 #endif
37 iliev 1161 #include "../common/Exception.h"
38    
39     namespace LinuxSampler {
40    
41 persson 1644 InstrumentsDb InstrumentsDb::instance;
42 iliev 1161
43 iliev 1717 void InstrumentsDb::CreateInstrumentsDb(String FilePath) {
44 schoenebeck 3091 if (FilePath.empty()) {
45     FilePath = GetDefaultDBLocation();
46     dmsg(0,("InstrumentsDb: Creating database at default location '%s'\n", FilePath.c_str()));
47     }
48    
49 iliev 1717 File f = File(FilePath);
50     if (f.Exist()) {
51     throw Exception("File exists: " + FilePath);
52 iliev 1187 }
53    
54 schoenebeck 3091 SetDbFile(FilePath);
55    
56 iliev 1187 String sql =
57     " CREATE TABLE instr_dirs ( "
58     " dir_id INTEGER PRIMARY KEY AUTOINCREMENT, "
59     " parent_dir_id INTEGER DEFAULT 0, "
60     " dir_name TEXT, "
61     " created TIMESTAMP DEFAULT CURRENT_TIMESTAMP, "
62     " modified TIMESTAMP DEFAULT CURRENT_TIMESTAMP, "
63     " description TEXT, "
64     " FOREIGN KEY(parent_dir_id) REFERENCES instr_dirs(dir_id), "
65     " UNIQUE (parent_dir_id,dir_name) "
66     " ); ";
67    
68 schoenebeck 3091 ExecSql(sql);
69 iliev 1187
70 iliev 1350 sql = "INSERT INTO instr_dirs (dir_id, parent_dir_id, dir_name) VALUES (0, -2, '/');";
71 schoenebeck 3091 ExecSql(sql);
72 iliev 1187
73     sql =
74     " CREATE TABLE instruments ( "
75     " instr_id INTEGER PRIMARY KEY AUTOINCREMENT, "
76     " dir_id INTEGER DEFAULT 0, "
77     " instr_name TEXT, "
78     " instr_file TEXT, "
79     " instr_nr INTEGER, "
80     " format_family TEXT, "
81     " format_version TEXT, "
82     " instr_size INTEGER, "
83     " created TIMESTAMP DEFAULT CURRENT_TIMESTAMP, "
84     " modified TIMESTAMP DEFAULT CURRENT_TIMESTAMP, "
85     " description TEXT, "
86     " is_drum INTEGER(1), "
87     " product TEXT, "
88     " artists TEXT, "
89     " keywords TEXT, "
90     " FOREIGN KEY(dir_id) REFERENCES instr_dirs(dir_id), "
91     " UNIQUE (dir_id,instr_name) "
92     " ); ";
93    
94 schoenebeck 3091 ExecSql(sql);
95 iliev 1187 }
96    
97 iliev 1161 InstrumentsDb::InstrumentsDb() {
98     db = NULL;
99 iliev 1187 InTransaction = false;
100 iliev 1161 }
101    
102     InstrumentsDb::~InstrumentsDb() {
103     if (db != NULL) sqlite3_close(db);
104     }
105    
106     void InstrumentsDb::AddInstrumentsDbListener(InstrumentsDb::Listener* l) {
107     llInstrumentsDbListeners.AddListener(l);
108     }
109    
110     void InstrumentsDb::RemoveInstrumentsDbListener(InstrumentsDb::Listener* l) {
111     llInstrumentsDbListeners.RemoveListener(l);
112     }
113    
114     InstrumentsDb* InstrumentsDb::GetInstrumentsDb() {
115 persson 1644 return &instance;
116 iliev 1161 }
117    
118     void InstrumentsDb::SetDbFile(String File) {
119 persson 2427 LockGuard lock(DbInstrumentsMutex);
120 iliev 1161 if (File.empty() || DbFile.length() > 0) {
121     throw Exception("Failed to set the database file");
122     }
123     DbFile = File;
124     }
125    
126 schoenebeck 3091 String InstrumentsDb::GetDefaultDBLocation() {
127     #ifdef WIN32
128     char* userprofile = getenv("USERPROFILE");
129     if (userprofile) {
130     String s = userprofile;
131     s += "\\.linuxsampler\\instruments.db";
132     return s;
133     } else {
134     // in case USERPROFILE is not set (which should not occur)
135     return "instruments.db";
136     }
137     #else // POSIX ...
138     String s = CONFIG_DEFAULT_INSTRUMENTS_DB_LOCATION;
139     # if defined(__APPLE__)
140     if (s.find("~") == 0)
141     s.replace(0, 1, getenv("HOME"));
142     # endif
143     return s;
144     #endif
145     }
146 iliev 1161
147 schoenebeck 3091 void InstrumentsDb::EnsureDBFileExists() {
148     if (DbFile.empty())
149     DbFile = GetDefaultDBLocation();
150 nagata 1642 #if defined(__APPLE__) /* 20071224 Toshi Nagata */
151     if (DbFile.find("~") == 0)
152     DbFile.replace(0, 1, getenv("HOME"));
153     #endif
154 schoenebeck 3091 Path DbPath(DbFile);
155     String DbDir = DbPath.stripLastName();
156     // create directory if it does not exist yet
157     if (!DbPath.nodes().empty()) {
158     File d(DbDir);
159     if (!d.Exist()) {
160     #ifdef WIN32
161     if (_mkdir(DbDir.c_str()))
162     throw Exception("Could not create instruments DB directory '" + DbDir + "'");
163     #else
164     if (mkdir(DbDir.c_str(), S_IRWXU))
165     throw Exception("Could not create instruments DB directory '" + DbDir + "'");
166     #endif
167     }
168     }
169     // create database file if it does not exist yet
170     File f(DbFile);
171     if (!f.Exist()) {
172     // formats the DB, which creates a new instruments.db file
173     Format();
174     }
175     }
176    
177     sqlite3* InstrumentsDb::GetDb() {
178     if ( db != NULL) return db;
179    
180     if (DbFile.empty())
181     DbFile = GetDefaultDBLocation();
182    
183     {
184     // first check if the instruments DB's directory exists, if not give up
185     Path path(DbFile);
186     String sDir = path.stripLastName();
187     File d(sDir);
188     if (!d.Exist())
189     throw Exception("Instruments DB directory '" + sDir + "' does not exist!");
190    
191     // just to give the user a notice about the DB file being created in case it does not exist yet
192     File f(DbFile);
193     if (!f.Exist())
194     dmsg(0,("Instruments DB file '%s' does not exist yet. Trying to create it now.\n", DbFile.c_str()));
195     }
196    
197     dmsg(0,("Opening instruments DB at '%s'\n", DbFile.c_str()));
198 iliev 1161 int rc = sqlite3_open(DbFile.c_str(), &db);
199     if (rc) {
200     sqlite3_close(db);
201     db = NULL;
202     throw Exception("Cannot open instruments database: " + DbFile);
203     }
204 persson 1908 #ifndef WIN32
205 iliev 1187 rc = sqlite3_create_function(db, "regexp", 2, SQLITE_UTF8, NULL, Regexp, NULL, NULL);
206     if (rc) { throw Exception("Failed to add user function for handling regular expressions."); }
207 persson 1908 #endif
208 iliev 1350
209     // TODO: remove this in the next version
210     try {
211     int i = ExecSqlInt("SELECT parent_dir_id FROM instr_dirs WHERE dir_id=0");
212     // The parent ID of the root directory should be -2 now.
213     if(i != -2) ExecSql("UPDATE instr_dirs SET parent_dir_id=-2 WHERE dir_id=0");
214     } catch(Exception e) { }
215     ////////////////////////////////////////
216 iliev 1161
217     return db;
218     }
219    
220     int InstrumentsDb::GetDirectoryCount(int DirId) {
221     dmsg(2,("InstrumentsDb: GetDirectoryCount(DirId=%d)\n", DirId));
222     if(DirId == -1) return -1;
223    
224     std::stringstream sql;
225     sql << "SELECT COUNT(*) FROM instr_dirs WHERE parent_dir_id=" << DirId;
226    
227     int count = ExecSqlInt(sql.str());
228    
229     return count;
230     }
231    
232 iliev 1187 int InstrumentsDb::GetDirectoryCount(String Dir, bool Recursive) {
233     dmsg(2,("InstrumentsDb: GetDirectoryCount(Dir=%s,Recursive=%d)\n", Dir.c_str(), Recursive));
234 iliev 1161 int i;
235    
236 iliev 1187 BeginTransaction();
237     try {
238     if (Recursive) {
239     DirectoryCounter directoryCounter;
240     DirectoryTreeWalk(Dir, &directoryCounter);
241     i = directoryCounter.GetDirectoryCount();
242     } else {
243     i = GetDirectoryCount(GetDirectoryId(Dir));
244     }
245     } catch (Exception e) {
246     EndTransaction();
247 iliev 1161 throw e;
248     }
249 iliev 1187 EndTransaction();
250 iliev 1345 if (i == -1) throw Exception("Unkown DB directory: " + toEscapedPath(Dir));
251 iliev 1161
252     return i;
253     }
254    
255     IntListPtr InstrumentsDb::GetDirectoryIDs(int DirId) {
256     std::stringstream sql;
257     sql << "SELECT dir_id FROM instr_dirs ";
258     sql << "WHERE parent_dir_id=" << DirId << " AND dir_id!=0";
259    
260     return ExecSqlIntList(sql.str());
261     }
262    
263 iliev 1187 StringListPtr InstrumentsDb::GetDirectories(String Dir, bool Recursive) {
264     dmsg(2,("InstrumentsDb: GetDirectories(Dir=%s,Recursive=%d)\n", Dir.c_str(), Recursive));
265 iliev 1161
266 iliev 1187 BeginTransaction();
267 iliev 1161 try {
268     int dirId = GetDirectoryId(Dir);
269 iliev 1345 if(dirId == -1) throw Exception("Unknown DB directory: " + toEscapedPath(Dir));
270 iliev 1161
271 iliev 1187 StringListPtr pDirs;
272     if (Recursive) {
273     SearchQuery q;
274     DirectoryFinder directoryFinder(&q);
275     DirectoryTreeWalk(Dir, &directoryFinder);
276     pDirs = directoryFinder.GetDirectories();
277     } else {
278     pDirs = GetDirectories(dirId);
279     }
280     EndTransaction();
281     return pDirs;
282 iliev 1161 } catch (Exception e) {
283 iliev 1187 EndTransaction();
284 iliev 1161 throw e;
285     }
286     }
287 iliev 1187
288     StringListPtr InstrumentsDb::GetDirectories(int DirId) {
289     std::stringstream sql;
290     sql << "SELECT dir_name FROM instr_dirs ";
291     sql << "WHERE parent_dir_id=" << DirId << " AND dir_id!=0";
292 iliev 1345 StringListPtr dirs = ExecSqlStringList(sql.str());
293    
294     for (int i = 0; i < dirs->size(); i++) {
295     for (int j = 0; j < dirs->at(i).length(); j++) {
296     if (dirs->at(i).at(j) == '/') dirs->at(i).at(j) = '\0';
297     }
298     }
299    
300     return dirs;
301 iliev 1187 }
302 iliev 1161
303     int InstrumentsDb::GetDirectoryId(String Dir) {
304     dmsg(2,("InstrumentsDb: GetDirectoryId(Dir=%s)\n", Dir.c_str()));
305     CheckPathName(Dir);
306    
307     if (Dir.empty() || Dir.at(0) != '/') {
308     return -1;
309     } else if (Dir.length() == 1) {
310     // We expect the root directory id to be always 0.
311     return 0;
312     }
313    
314     int id = 0, i = 1;
315     int j = Dir.find('/', i);
316    
317     while(j != std::string::npos) {
318     id = GetDirectoryId(id, Dir.substr(i, j - i));
319     i = j + 1;
320     if (i >= Dir.length()) return id;
321     j = Dir.find('/', i);
322     }
323    
324     return GetDirectoryId(id, Dir.substr(i));
325     }
326    
327     int InstrumentsDb::GetDirectoryId(int ParentDirId, String DirName) {
328     dmsg(2,("InstrumentsDb: GetDirectoryId(ParentDirId=%d, DirName=%s)\n", ParentDirId, DirName.c_str()));
329 iliev 1345 DirName = toDbName(DirName);
330 iliev 1161 std::stringstream sql;
331     sql << "SELECT dir_id FROM instr_dirs WHERE parent_dir_id=";
332     sql << ParentDirId << " AND dir_name=?";
333     return ExecSqlInt(sql.str(), DirName);
334     }
335    
336 iliev 1727 int InstrumentsDb::GetDirectoryId(int InstrId) {
337     dmsg(2,("InstrumentsDb: GetDirectoryId(InstrId=%d)\n", InstrId));
338     std::stringstream sql;
339     sql << "SELECT dir_id FROM instruments WHERE instr_id=" << InstrId;
340     return ExecSqlInt(sql.str());
341     }
342    
343 iliev 1187 String InstrumentsDb::GetDirectoryName(int DirId) {
344     String sql = "SELECT dir_name FROM instr_dirs WHERE dir_id=" + ToString(DirId);
345     String name = ExecSqlString(sql);
346     if (name.empty()) throw Exception("Directory ID not found");
347     return name;
348     }
349    
350     int InstrumentsDb::GetParentDirectoryId(int DirId) {
351     if (DirId == 0) throw Exception("The root directory is specified");
352     String sql = "SELECT parent_dir_id FROM instr_dirs WHERE dir_id=" + ToString(DirId);
353     int parentId = ExecSqlInt(sql);
354     if (parentId == -1) throw Exception("DB directory not found");
355     return parentId;
356     }
357    
358     String InstrumentsDb::GetDirectoryPath(int DirId) {
359     String path = "";
360     int count = 1000; // used to prevent infinite loops
361    
362     while(--count) {
363     if (DirId == 0) {
364     path = "/" + path;
365     break;
366     }
367 iliev 1727 path = GetDirectoryName(DirId) + "/" + path;
368 iliev 1187 DirId = GetParentDirectoryId(DirId);
369     }
370    
371     if (!count) throw Exception("Possible infinite loop detected");
372    
373     return path;
374     }
375 iliev 1727
376     StringListPtr InstrumentsDb::GetInstrumentsByFile(String File) {
377     dmsg(2,("InstrumentsDb: GetInstrumentsByFile(File=%s)\n", File.c_str()));
378 iliev 1187
379 iliev 1727 StringListPtr instrs(new std::vector<String>);
380    
381     BeginTransaction();
382     try {
383     File = toEscapedFsPath(File);
384     IntListPtr ids = ExecSqlIntList("SELECT instr_id FROM instruments WHERE instr_file=?", File);
385    
386     for (int i = 0; i < ids->size(); i++) {
387     String name = GetInstrumentName(ids->at(i));
388     String dir = GetDirectoryPath(GetDirectoryId(ids->at(i)));
389     instrs->push_back(dir + name);
390     }
391     } catch (Exception e) {
392     EndTransaction();
393     throw e;
394     }
395     EndTransaction();
396    
397     return instrs;
398     }
399    
400 iliev 1161 void InstrumentsDb::AddDirectory(String Dir) {
401     dmsg(2,("InstrumentsDb: AddDirectory(Dir=%s)\n", Dir.c_str()));
402     CheckPathName(Dir);
403     String ParentDir = GetParentDirectory(Dir);
404    
405 iliev 1187 BeginTransaction();
406 iliev 1161 try {
407     if (Dir.length() > 1) {
408     if (Dir.at(Dir.length() - 1) == '/') Dir.erase(Dir.length() - 1);
409     }
410    
411     String dirName = GetFileName(Dir);
412     if(ParentDir.empty() || dirName.empty()) {
413 iliev 1345 throw Exception("Failed to add DB directory: " + toEscapedPath(Dir));
414 iliev 1161 }
415    
416     int id = GetDirectoryId(ParentDir);
417 iliev 1345 if (id == -1) throw Exception("DB directory doesn't exist: " + toEscapedPath(ParentDir));
418 iliev 1161 int id2 = GetDirectoryId(id, dirName);
419 iliev 1345 if (id2 != -1) throw Exception("DB directory already exist: " + toEscapedPath(Dir));
420 iliev 1187 id2 = GetInstrumentId(id, dirName);
421 iliev 1345 if (id2 != -1) throw Exception("Instrument with that name exist: " + toEscapedPath(Dir));
422 iliev 1161
423     std::stringstream sql;
424     sql << "INSERT INTO instr_dirs (parent_dir_id, dir_name) VALUES (";
425     sql << id << ", ?)";
426    
427 iliev 1345 ExecSql(sql.str(), toDbName(dirName));
428 iliev 1161 } catch (Exception e) {
429 iliev 1187 EndTransaction();
430 iliev 1161 throw e;
431     }
432    
433 iliev 1187 EndTransaction();
434 iliev 1161
435     FireDirectoryCountChanged(ParentDir);
436     }
437    
438     void InstrumentsDb::RemoveDirectory(String Dir, bool Force) {
439     dmsg(2,("InstrumentsDb: RemoveDirectory(Dir=%s,Force=%d)\n", Dir.c_str(), Force));
440    
441     String ParentDir = GetParentDirectory(Dir);
442    
443 iliev 1187 BeginTransaction();
444 iliev 1161 try {
445     int dirId = GetDirectoryId(Dir);
446 iliev 1345 if (dirId == -1) throw Exception("Unknown DB directory: " + toEscapedPath(Dir));
447 iliev 1161 if (dirId == 0) throw Exception("Cannot delete the root directory: " + Dir);
448     if(ParentDir.empty()) throw Exception("Unknown parent directory");
449     if (Force) RemoveDirectoryContent(dirId);
450     RemoveDirectory(dirId);
451     } catch (Exception e) {
452 iliev 1187 EndTransaction();
453 iliev 1161 throw e;
454     }
455    
456 iliev 1187 EndTransaction();
457 iliev 1161 FireDirectoryCountChanged(ParentDir);
458     }
459    
460     void InstrumentsDb::RemoveDirectoryContent(int DirId, int Level) {
461     dmsg(2,("InstrumentsDb: RemoveDirectoryContent(DirId=%d,Level=%d)\n", DirId, Level));
462     if (Level > 1000) throw Exception("Directory level too deep: " + ToString(Level));
463     IntListPtr dirIds = GetDirectoryIDs(DirId);
464    
465     for (int i = 0; i < dirIds->size(); i++) {
466     RemoveDirectoryContent(dirIds->at(i), Level + 1);
467     }
468    
469     RemoveAllDirectories(DirId);
470     RemoveAllInstruments(DirId);
471     }
472    
473     void InstrumentsDb::RemoveDirectory(int DirId) {
474     dmsg(2,("InstrumentsDb: RemoveDirectory(DirId=%d)\n", DirId));
475     if (GetInstrumentCount(DirId) > 0 || GetDirectoryCount(DirId) > 0) {
476     throw Exception("The specified DB directory is not empty");
477     }
478    
479     std::stringstream sql;
480     sql << "DELETE FROM instr_dirs WHERE dir_id=" << DirId;
481    
482     ExecSql(sql.str());
483     }
484    
485     void InstrumentsDb::RemoveAllDirectories(int DirId) {
486     dmsg(2,("InstrumentsDb: RemoveAllDirectories(DirId=%d)\n", DirId));
487     IntListPtr dirIds = GetDirectoryIDs(DirId);
488    
489     for (int i = 0; i < dirIds->size(); i++) {
490     if (!IsDirectoryEmpty(dirIds->at(i))) {
491     throw Exception("DB directory not empty!");
492     }
493     }
494     std::stringstream sql;
495     sql << "DELETE FROM instr_dirs WHERE parent_dir_id=" << DirId;
496     sql << " AND dir_id!=0";
497    
498     ExecSql(sql.str());
499     }
500    
501     bool InstrumentsDb::IsDirectoryEmpty(int DirId) {
502     dmsg(2,("InstrumentsDb: IsDirectoryEmpty(DirId=%d)\n", DirId));
503     int dirCount = GetDirectoryCount(DirId);
504     int instrCount = GetInstrumentCount(DirId);
505     dmsg(3,("InstrumentsDb: IsDirectoryEmpty: dirCount=%d,instrCount=%d\n", dirCount, instrCount));
506     if (dirCount == -1 || instrCount == -1) return false;
507     return dirCount == 0 && instrCount == 0;
508     }
509    
510     bool InstrumentsDb::DirectoryExist(String Dir) {
511     dmsg(2,("InstrumentsDb: DirectoryExist(Dir=%s)\n", Dir.c_str()));
512 persson 2427 {
513     LockGuard lock(DbInstrumentsMutex);
514     return GetDirectoryId(Dir) != -1;
515 iliev 1161 }
516     }
517    
518     DbDirectory InstrumentsDb::GetDirectoryInfo(String Dir) {
519     dmsg(2,("InstrumentsDb: GetDirectoryInfo(Dir=%s)\n", Dir.c_str()));
520     DbDirectory d;
521    
522 iliev 1187 BeginTransaction();
523 iliev 1161
524     try {
525     int id = GetDirectoryId(Dir);
526 iliev 1345 if(id == -1) throw Exception("Unknown DB directory: " + toEscapedPath(Dir));
527 iliev 1161
528     sqlite3_stmt *pStmt = NULL;
529     std::stringstream sql;
530     sql << "SELECT created,modified,description FROM instr_dirs ";
531     sql << "WHERE dir_id=" << id;
532    
533     int res = sqlite3_prepare(GetDb(), sql.str().c_str(), -1, &pStmt, NULL);
534     if (res != SQLITE_OK) {
535     throw Exception("DB error: " + ToString(sqlite3_errmsg(db)));
536     }
537    
538     res = sqlite3_step(pStmt);
539     if(res == SQLITE_ROW) {
540     d.Created = ToString(sqlite3_column_text(pStmt, 0));
541     d.Modified = ToString(sqlite3_column_text(pStmt, 1));
542     d.Description = ToString(sqlite3_column_text(pStmt, 2));
543     } else {
544     sqlite3_finalize(pStmt);
545    
546     if (res != SQLITE_DONE) {
547     throw Exception("DB error: " + ToString(sqlite3_errmsg(db)));
548     } else {
549 iliev 1345 throw Exception("Unknown DB directory: " + toEscapedPath(Dir));
550 iliev 1161 }
551     }
552    
553     sqlite3_finalize(pStmt);
554     } catch (Exception e) {
555 iliev 1187 EndTransaction();
556 iliev 1161 throw e;
557     }
558    
559 iliev 1187 EndTransaction();
560 iliev 1161 return d;
561     }
562    
563     void InstrumentsDb::RenameDirectory(String Dir, String Name) {
564     dmsg(2,("InstrumentsDb: RenameDirectory(Dir=%s,Name=%s)\n", Dir.c_str(), Name.c_str()));
565     CheckFileName(Name);
566 iliev 1345 String dbName = toDbName(Name);
567 iliev 1161
568 iliev 1187 BeginTransaction();
569 iliev 1161 try {
570     int dirId = GetDirectoryId(Dir);
571 iliev 1345 if (dirId == -1) throw Exception("Unknown DB directory: " + toEscapedText(Dir));
572 iliev 1161
573     std::stringstream sql;
574     sql << "SELECT parent_dir_id FROM instr_dirs WHERE dir_id=" << dirId;
575    
576     int parent = ExecSqlInt(sql.str());
577 iliev 1345 if (parent == -1) throw Exception("Unknown parent directory: " + toEscapedPath(Dir));
578    
579     if (GetDirectoryId(parent, dbName) != -1) {
580     String s = toEscapedPath(Name);
581     throw Exception("Cannot rename. Directory with that name already exists: " + s);
582 iliev 1161 }
583    
584 iliev 1345 if (GetInstrumentId(parent, dbName) != -1) {
585     throw Exception("Cannot rename. Instrument with that name exist: " + toEscapedPath(Dir));
586 iliev 1187 }
587    
588 iliev 1161 sql.str("");
589     sql << "UPDATE instr_dirs SET dir_name=? WHERE dir_id=" << dirId;
590 iliev 1345 ExecSql(sql.str(), dbName);
591 iliev 1161 } catch (Exception e) {
592 iliev 1187 EndTransaction();
593 iliev 1161 throw e;
594     }
595    
596 iliev 1187 EndTransaction();
597 iliev 1350 FireDirectoryNameChanged(Dir, toAbstractName(Name));
598 iliev 1161 }
599    
600     void InstrumentsDb::MoveDirectory(String Dir, String Dst) {
601     dmsg(2,("InstrumentsDb: MoveDirectory(Dir=%s,Dst=%s)\n", Dir.c_str(), Dst.c_str()));
602    
603 iliev 1187 if(Dir.compare("/") == 0) throw Exception("Cannot move the root directory");
604 iliev 1161 String ParentDir = GetParentDirectory(Dir);
605     if(ParentDir.empty()) throw Exception("Unknown parent directory");
606    
607 iliev 1187 BeginTransaction();
608 iliev 1161 try {
609     int dirId = GetDirectoryId(Dir);
610 iliev 1345 if (dirId == -1) throw Exception("Unknown DB directory: " + toEscapedPath(Dir));
611 iliev 1161 int dstId = GetDirectoryId(Dst);
612 iliev 1345 if (dstId == -1) throw Exception("Unknown DB directory: " + toEscapedPath(Dst));
613 iliev 1161 if (dirId == dstId) {
614     throw Exception("Cannot move directory to itself");
615     }
616    
617     if (Dir.at(Dir.length() - 1) != '/') Dir.append("/");
618     if (Dst.length() > Dir.length()) {
619     if (Dir.compare(Dst.substr(0, Dir.length())) == 0) {
620     throw Exception("Cannot move a directory to a subdirectory of itself.");
621     }
622     }
623 iliev 1187
624     Dir.erase(Dir.length() - 1);
625     String dirName = GetFileName(Dir);
626 iliev 1161
627 iliev 1187 int id2 = GetDirectoryId(dstId, dirName);
628 iliev 1345 if (id2 != -1) throw Exception("DB directory already exist: " + toEscapedPath(dirName));
629 iliev 1187 id2 = GetInstrumentId(dstId, dirName);
630 iliev 1345 if (id2 != -1) throw Exception("Instrument with that name exist: " + toEscapedPath(dirName));
631 iliev 1187
632 iliev 1161 std::stringstream sql;
633     sql << "UPDATE instr_dirs SET parent_dir_id=" << dstId;
634     sql << " WHERE dir_id=" << dirId;
635     ExecSql(sql.str());
636     } catch (Exception e) {
637 iliev 1187 EndTransaction();
638 iliev 1161 throw e;
639     }
640    
641 iliev 1187 EndTransaction();
642 iliev 1161 FireDirectoryCountChanged(ParentDir);
643     FireDirectoryCountChanged(Dst);
644     }
645    
646 iliev 1187 void InstrumentsDb::CopyDirectory(String Dir, String Dst) {
647     dmsg(2,("InstrumentsDb: CopyDirectory(Dir=%s,Dst=%s)\n", Dir.c_str(), Dst.c_str()));
648    
649     if(Dir.compare("/") == 0) throw Exception("Cannot copy the root directory");
650     String ParentDir = GetParentDirectory(Dir);
651     if(ParentDir.empty()) throw Exception("Unknown parent directory");
652    
653     BeginTransaction();
654     try {
655     int dirId = GetDirectoryId(Dir);
656 iliev 1345 if (dirId == -1) throw Exception("Unknown DB directory: " + toEscapedPath(Dir));
657 iliev 1187 int dstId = GetDirectoryId(Dst);
658 iliev 1345 if (dstId == -1) throw Exception("Unknown DB directory: " + toEscapedPath(Dst));
659 iliev 1187 if (dirId == dstId) {
660     throw Exception("Cannot copy directory to itself");
661     }
662    
663     if (Dir.at(Dir.length() - 1) != '/') Dir.append("/");
664     if (Dst.length() > Dir.length()) {
665     if (Dir.compare(Dst.substr(0, Dir.length())) == 0) {
666     throw Exception("Cannot copy a directory to a subdirectory of itself.");
667     }
668     }
669    
670     Dir.erase(Dir.length() - 1);
671     String dirName = GetFileName(Dir);
672    
673     int id2 = GetDirectoryId(dstId, dirName);
674 iliev 1345 if (id2 != -1) throw Exception("DB directory already exist: " + toEscapedPath(dirName));
675 iliev 1187 id2 = GetInstrumentId(dstId, dirName);
676 iliev 1345 if (id2 != -1) throw Exception("Instrument with that name exist: " + toEscapedPath(dirName));
677 iliev 1187
678     DirectoryCopier directoryCopier(ParentDir, Dst);
679     DirectoryTreeWalk(Dir, &directoryCopier);
680     } catch (Exception e) {
681     EndTransaction();
682     throw e;
683     }
684    
685     EndTransaction();
686     }
687    
688 iliev 1161 void InstrumentsDb::SetDirectoryDescription(String Dir, String Desc) {
689     dmsg(2,("InstrumentsDb: SetDirectoryDescription(Dir=%s,Desc=%s)\n", Dir.c_str(), Desc.c_str()));
690    
691 iliev 1187 BeginTransaction();
692 iliev 1161 try {
693     int id = GetDirectoryId(Dir);
694 iliev 1345 if(id == -1) throw Exception("Unknown DB directory: " + toEscapedPath(Dir));
695 iliev 1161
696     std::stringstream sql;
697     sql << "UPDATE instr_dirs SET description=?,modified=CURRENT_TIMESTAMP ";
698     sql << "WHERE dir_id="<< id;
699    
700     ExecSql(sql.str(), Desc);
701     } catch (Exception e) {
702 iliev 1187 EndTransaction();
703 iliev 1161 throw e;
704     }
705 iliev 1187 EndTransaction();
706 iliev 1161
707     FireDirectoryInfoChanged(Dir);
708     }
709    
710 iliev 1781 int InstrumentsDb::AddInstruments(ScanMode Mode, String DbDir, String FsDir, bool bBackground, bool insDir) {
711     dmsg(2,("InstrumentsDb: AddInstruments(Mode=%d,DbDir=%s,FsDir=%s,bBackground=%d,insDir=%d)\n", Mode, DbDir.c_str(), FsDir.c_str(), bBackground, insDir));
712 iliev 1200 if(!bBackground) {
713     switch (Mode) {
714     case NON_RECURSIVE:
715 iliev 1781 AddInstrumentsNonrecursive(DbDir, FsDir, insDir);
716 iliev 1200 break;
717     case RECURSIVE:
718 iliev 1781 AddInstrumentsRecursive(DbDir, FsDir, false, insDir);
719 iliev 1200 break;
720     case FLAT:
721 iliev 1781 AddInstrumentsRecursive(DbDir, FsDir, true, insDir);
722 iliev 1200 break;
723     default:
724     throw Exception("Unknown scan mode");
725     }
726    
727     return -1;
728     }
729    
730     ScanJob job;
731     int jobId = Jobs.AddJob(job);
732 iliev 1781 InstrumentsDbThread.Execute(new AddInstrumentsJob(jobId, Mode, DbDir, FsDir, insDir));
733 iliev 1200
734     return jobId;
735     }
736    
737     int InstrumentsDb::AddInstruments(String DbDir, String FilePath, int Index, bool bBackground) {
738     dmsg(2,("InstrumentsDb: AddInstruments(DbDir=%s,FilePath=%s,Index=%d,bBackground=%d)\n", DbDir.c_str(), FilePath.c_str(), Index, bBackground));
739     if(!bBackground) {
740 iliev 1781 AddInstruments(DbDir, false, FilePath, Index);
741 iliev 1200 return -1;
742     }
743    
744     ScanJob job;
745     int jobId = Jobs.AddJob(job);
746 iliev 1781 InstrumentsDbThread.Execute(new AddInstrumentsFromFileJob(jobId, DbDir, FilePath, Index, false));
747 iliev 1200
748     return jobId;
749 iliev 1781 }
750 iliev 1200
751 iliev 1781 void InstrumentsDb::AddInstruments(String DbDir, bool insDir, String FilePath, int Index, ScanProgress* pProgress) {
752     dmsg(2,("InstrumentsDb: AddInstruments(DbDir=%s,insDir=%d,FilePath=%s,Index=%d)\n", DbDir.c_str(), insDir, FilePath.c_str(), Index));
753 iliev 1161 if (DbDir.empty() || FilePath.empty()) return;
754    
755 persson 2427 {
756     LockGuard lock(DbInstrumentsMutex);
757    
758 iliev 1161 int dirId = GetDirectoryId(DbDir);
759 iliev 1345 if (dirId == -1) throw Exception("Invalid DB directory: " + toEscapedText(DbDir));
760 iliev 1161
761 iliev 1717 File f = File(FilePath);
762     if (!f.Exist()) {
763 iliev 1161 std::stringstream ss;
764 iliev 1717 ss << "Fail to stat `" << FilePath << "`: " << f.GetErrorMsg();
765 iliev 1161 throw Exception(ss.str());
766     }
767    
768 iliev 1717 if (!f.IsFile()) {
769 iliev 1161 std::stringstream ss;
770 iliev 1200 ss << "`" << FilePath << "` is not an instrument file";
771 iliev 1161 throw Exception(ss.str());
772     }
773 iliev 1200
774 iliev 1782 String dir = insDir ? PrepareSubdirectory(DbDir, FilePath) : DbDir;
775     AddInstrumentsFromFile(dir, FilePath, Index, pProgress);
776 iliev 1161 }
777     }
778    
779 iliev 1781 void InstrumentsDb::AddInstrumentsNonrecursive(String DbDir, String FsDir, bool insDir, ScanProgress* pProgress) {
780     dmsg(2,("InstrumentsDb: AddInstrumentsNonrecursive(DbDir=%s,FsDir=%s,insDir=%d)\n", DbDir.c_str(), FsDir.c_str(), insDir));
781 iliev 1161 if (DbDir.empty() || FsDir.empty()) return;
782    
783 persson 2427 {
784     LockGuard lock(DbInstrumentsMutex);
785    
786 iliev 1161 int dirId = GetDirectoryId(DbDir);
787 iliev 1345 if (dirId == -1) throw Exception("Invalid DB directory: " + toEscapedPath(DbDir));
788 iliev 1161
789 iliev 1717 File f = File(FsDir);
790     if (!f.Exist()) {
791 iliev 1161 std::stringstream ss;
792 iliev 1717 ss << "Fail to stat `" << FsDir << "`: " << f.GetErrorMsg();
793 iliev 1161 throw Exception(ss.str());
794     }
795    
796 iliev 1717 if (!f.IsDirectory()) {
797     throw Exception("Directory expected: " + FsDir);
798 iliev 1161 }
799    
800 iliev 1717 if (FsDir.at(FsDir.length() - 1) != File::DirSeparator) {
801     FsDir.push_back(File::DirSeparator);
802     }
803    
804     try {
805     FileListPtr fileList = File::GetFiles(FsDir);
806     for (int i = 0; i < fileList->size(); i++) {
807 iliev 1782 String dir = insDir ? PrepareSubdirectory(DbDir, fileList->at(i)) : DbDir;
808     AddInstrumentsFromFile(dir, FsDir + fileList->at(i), -1, pProgress);
809 iliev 1717 }
810     } catch(Exception e) {
811     e.PrintMessage();
812 iliev 1161 }
813     }
814     }
815    
816 iliev 1781 void InstrumentsDb::AddInstrumentsRecursive(String DbDir, String FsDir, bool Flat, bool insDir, ScanProgress* pProgress) {
817     dmsg(2,("InstrumentsDb: AddInstrumentsRecursive(DbDir=%s,FsDir=%s,Flat=%d,insDir=%d)\n", DbDir.c_str(), FsDir.c_str(), Flat, insDir));
818 iliev 1200 if (pProgress != NULL) {
819 iliev 1717 InstrumentFileCounter c;
820     pProgress->SetTotalFileCount(c.Count(FsDir));
821 iliev 1200 }
822    
823 iliev 1717 DirectoryScanner d;
824 iliev 1781 d.Scan(DbDir, FsDir, Flat, insDir, pProgress);
825 iliev 1161 }
826    
827     int InstrumentsDb::GetInstrumentCount(int DirId) {
828     dmsg(2,("InstrumentsDb: GetInstrumentCount(DirId=%d)\n", DirId));
829     if(DirId == -1) return -1;
830    
831     std::stringstream sql;
832     sql << "SELECT COUNT(*) FROM instruments WHERE dir_id=" << DirId;
833    
834     return ExecSqlInt(sql.str());
835     }
836    
837 iliev 1187 int InstrumentsDb::GetInstrumentCount(String Dir, bool Recursive) {
838     dmsg(2,("InstrumentsDb: GetInstrumentCount(Dir=%s,Recursive=%d)\n", Dir.c_str(), Recursive));
839 iliev 1161 int i;
840    
841 iliev 1187 BeginTransaction();
842     try {
843     if (Recursive) {
844     InstrumentCounter instrumentCounter;
845     DirectoryTreeWalk(Dir, &instrumentCounter);
846     i = instrumentCounter.GetInstrumentCount();
847     } else {
848     i = GetInstrumentCount(GetDirectoryId(Dir));
849     }
850     } catch (Exception e) {
851     EndTransaction();
852 iliev 1161 throw e;
853     }
854 iliev 1187 EndTransaction();
855 iliev 1161
856 iliev 1345 if (i == -1) throw Exception("Unknown Db directory: " + toEscapedPath(Dir));
857 iliev 1161 return i;
858     }
859    
860     IntListPtr InstrumentsDb::GetInstrumentIDs(int DirId) {
861     std::stringstream sql;
862     sql << "SELECT instr_id FROM instruments WHERE dir_id=" << DirId;
863    
864     return ExecSqlIntList(sql.str());
865     }
866    
867 iliev 1187 StringListPtr InstrumentsDb::GetInstruments(String Dir, bool Recursive) {
868     dmsg(2,("InstrumentsDb: GetInstruments(Dir=%s,Recursive=%d)\n", Dir.c_str(), Recursive));
869     BeginTransaction();
870 iliev 1161 try {
871     int dirId = GetDirectoryId(Dir);
872 iliev 1345 if(dirId == -1) throw Exception("Unknown DB directory: " + toEscapedPath(Dir));
873 iliev 1161
874 iliev 1187 StringListPtr pInstrs;
875 iliev 1161
876 iliev 1187 if(Recursive) {
877     SearchQuery q;
878     InstrumentFinder instrumentFinder(&q);
879     DirectoryTreeWalk(Dir, &instrumentFinder);
880     pInstrs = instrumentFinder.GetInstruments();
881     } else {
882     std::stringstream sql;
883     sql << "SELECT instr_name FROM instruments WHERE dir_id=" << dirId;
884    
885     pInstrs = ExecSqlStringList(sql.str());
886 iliev 1350 // Converting to abstract names
887     for (int i = 0; i < pInstrs->size(); i++) {
888     for (int j = 0; j < pInstrs->at(i).length(); j++) {
889     if (pInstrs->at(i).at(j) == '/') pInstrs->at(i).at(j) = '\0';
890     }
891     }
892 iliev 1187 }
893     EndTransaction();
894     return pInstrs;
895 iliev 1161 } catch (Exception e) {
896 iliev 1187 EndTransaction();
897 iliev 1161 throw e;
898     }
899     }
900    
901     int InstrumentsDb::GetInstrumentId(String Instr) {
902     dmsg(2,("InstrumentsDb: GetInstrumentId(Instr=%s)\n", Instr.c_str()));
903     String Dir = GetDirectoryPath(Instr);
904     if (Dir.empty()) return -1;
905    
906     return GetInstrumentId(GetDirectoryId(Dir), GetFileName(Instr));
907     }
908    
909     int InstrumentsDb::GetInstrumentId(int DirId, String InstrName) {
910     dmsg(2,("InstrumentsDb: GetInstrumentId(DirId=%d,InstrName=%s)\n", DirId, InstrName.c_str()));
911     if (DirId == -1 || InstrName.empty()) return -1;
912    
913     std::stringstream sql;
914     sql << "SELECT instr_id FROM instruments WHERE dir_id=";
915     sql << DirId << " AND instr_name=?";
916 iliev 1345 return ExecSqlInt(sql.str(), toDbName(InstrName));
917 iliev 1161 }
918 iliev 1187
919     String InstrumentsDb::GetInstrumentName(int InstrId) {
920     dmsg(2,("InstrumentsDb: GetInstrumentName(InstrId=%d)\n", InstrId));
921     std::stringstream sql;
922     sql << "SELECT instr_name FROM instruments WHERE instr_id=" << InstrId;
923 iliev 1345 return toAbstractName(ExecSqlString(sql.str()));
924 iliev 1187 }
925 iliev 1161
926     void InstrumentsDb::RemoveInstrument(String Instr) {
927     dmsg(2,("InstrumentsDb: RemoveInstrument(Instr=%s)\n", Instr.c_str()));
928     String ParentDir = GetDirectoryPath(Instr);
929     if(ParentDir.empty()) throw Exception("Unknown parent directory");
930    
931 iliev 1187 BeginTransaction();
932 iliev 1161 try {
933     int instrId = GetInstrumentId(Instr);
934     if(instrId == -1) {
935 iliev 1345 throw Exception("The specified instrument does not exist: " + toEscapedPath(Instr));
936 iliev 1161 }
937     RemoveInstrument(instrId);
938     } catch (Exception e) {
939 iliev 1187 EndTransaction();
940 iliev 1161 throw e;
941     }
942 iliev 1187 EndTransaction();
943 iliev 1161 FireInstrumentCountChanged(ParentDir);
944     }
945    
946     void InstrumentsDb::RemoveInstrument(int InstrId) {
947     dmsg(2,("InstrumentsDb: RemoveInstrument(InstrId=%d)\n", InstrId));
948    
949     std::stringstream sql;
950     sql << "DELETE FROM instruments WHERE instr_id=" << InstrId;
951    
952     ExecSql(sql.str());
953     }
954    
955     void InstrumentsDb::RemoveAllInstruments(int DirId) {
956     dmsg(2,("InstrumentsDb: RemoveAllInstruments(DirId=%d)\n", DirId));
957    
958     std::stringstream sql;
959     sql << "DELETE FROM instruments WHERE dir_id=" << DirId;
960     ExecSql(sql.str());
961     }
962    
963     DbInstrument InstrumentsDb::GetInstrumentInfo(String Instr) {
964     dmsg(2,("InstrumentsDb: GetInstrumentInfo(Instr=%s)\n", Instr.c_str()));
965     DbInstrument i;
966    
967 iliev 1187 BeginTransaction();
968 iliev 1161 try {
969     int id = GetInstrumentId(Instr);
970 iliev 1345 if(id == -1) throw Exception("Unknown DB instrument: " + toEscapedPath(Instr));
971 iliev 1187 i = GetInstrumentInfo(id);
972     } catch (Exception e) {
973     EndTransaction();
974     throw e;
975     }
976     EndTransaction();
977 iliev 1161
978 iliev 1187 return i;
979     }
980 iliev 1161
981 iliev 1187 DbInstrument InstrumentsDb::GetInstrumentInfo(int InstrId) {
982     sqlite3_stmt *pStmt = NULL;
983     std::stringstream sql;
984     sql << "SELECT instr_file,instr_nr,format_family,format_version,";
985     sql << "instr_size,created,modified,description,is_drum,product,";
986     sql << "artists,keywords FROM instruments WHERE instr_id=" << InstrId;
987    
988     int res = sqlite3_prepare(GetDb(), sql.str().c_str(), -1, &pStmt, NULL);
989     if (res != SQLITE_OK) {
990     throw Exception("DB error: " + ToString(sqlite3_errmsg(db)));
991     }
992    
993     DbInstrument i;
994     res = sqlite3_step(pStmt);
995     if(res == SQLITE_ROW) {
996     i.InstrFile = ToString(sqlite3_column_text(pStmt, 0));
997     i.InstrNr = sqlite3_column_int(pStmt, 1);
998     i.FormatFamily = ToString(sqlite3_column_text(pStmt, 2));
999     i.FormatVersion = ToString(sqlite3_column_text(pStmt, 3));
1000     i.Size = sqlite3_column_int64(pStmt, 4);
1001     i.Created = ToString(sqlite3_column_text(pStmt, 5));
1002     i.Modified = ToString(sqlite3_column_text(pStmt, 6));
1003     i.Description = ToString(sqlite3_column_text(pStmt, 7));
1004     i.IsDrum = sqlite3_column_int(pStmt, 8);
1005     i.Product = ToString(sqlite3_column_text(pStmt, 9));
1006     i.Artists = ToString(sqlite3_column_text(pStmt, 10));
1007     i.Keywords = ToString(sqlite3_column_text(pStmt, 11));
1008     } else {
1009     sqlite3_finalize(pStmt);
1010    
1011     if (res != SQLITE_DONE) {
1012 iliev 1161 throw Exception("DB error: " + ToString(sqlite3_errmsg(db)));
1013     } else {
1014 iliev 1187 throw Exception("Unknown DB instrument");
1015 iliev 1161 }
1016 iliev 1187 }
1017 iliev 1161
1018 iliev 1187 sqlite3_finalize(pStmt);
1019 iliev 1161 return i;
1020     }
1021    
1022     void InstrumentsDb::RenameInstrument(String Instr, String Name) {
1023     dmsg(2,("InstrumentsDb: RenameInstrument(Instr=%s,Name=%s)\n", Instr.c_str(), Name.c_str()));
1024     CheckFileName(Name);
1025    
1026 iliev 1187 BeginTransaction();
1027 iliev 1161 try {
1028     int dirId = GetDirectoryId(GetDirectoryPath(Instr));
1029 iliev 1345 if (dirId == -1) throw Exception("Unknown DB instrument: " + toEscapedPath(Instr));
1030 iliev 1161
1031     int instrId = GetInstrumentId(dirId, GetFileName(Instr));
1032 iliev 1345 if (instrId == -1) throw Exception("Unknown DB instrument: " + toEscapedPath(Instr));
1033 iliev 1161
1034     if (GetInstrumentId(dirId, Name) != -1) {
1035 iliev 1345 String s = toEscapedPath(Name);
1036     throw Exception("Cannot rename. Instrument with that name already exists: " + s);
1037 iliev 1161 }
1038    
1039 iliev 1187 if (GetDirectoryId(dirId, Name) != -1) {
1040 iliev 1345 String s = toEscapedPath(Name);
1041     throw Exception("Cannot rename. Directory with that name already exists: " + s);
1042 iliev 1187 }
1043    
1044 iliev 1161 std::stringstream sql;
1045     sql << "UPDATE instruments SET instr_name=? WHERE instr_id=" << instrId;
1046 iliev 1345 ExecSql(sql.str(), toDbName(Name));
1047 iliev 1161 } catch (Exception e) {
1048 iliev 1187 EndTransaction();
1049 iliev 1161 throw e;
1050     }
1051 iliev 1187 EndTransaction();
1052 iliev 1350 FireInstrumentNameChanged(Instr, toAbstractName(Name));
1053 iliev 1161 }
1054    
1055     void InstrumentsDb::MoveInstrument(String Instr, String Dst) {
1056     dmsg(2,("InstrumentsDb: MoveInstrument(Instr=%s,Dst=%s)\n", Instr.c_str(), Dst.c_str()));
1057     String ParentDir = GetDirectoryPath(Instr);
1058     if(ParentDir.empty()) throw Exception("Unknown parent directory");
1059    
1060 iliev 1187 BeginTransaction();
1061 iliev 1161 try {
1062 iliev 1345 int dirId = GetDirectoryId(ParentDir);
1063     if (dirId == -1) throw Exception("Unknown DB instrument: " + toEscapedPath(Instr));
1064 iliev 1161
1065     String instrName = GetFileName(Instr);
1066     int instrId = GetInstrumentId(dirId, instrName);
1067 iliev 1345 if (instrId == -1) throw Exception("Unknown DB instrument: " + toEscapedPath(Instr));
1068 iliev 1161
1069     int dstId = GetDirectoryId(Dst);
1070 iliev 1345 if (dstId == -1) throw Exception("Unknown DB directory: " + toEscapedPath(Dst));
1071 iliev 1161 if (dirId == dstId) {
1072 iliev 1187 EndTransaction();
1073 iliev 1161 return;
1074     }
1075    
1076     if (GetInstrumentId(dstId, instrName) != -1) {
1077 iliev 1345 String s = toEscapedPath(instrName);
1078     throw Exception("Cannot move. Instrument with that name already exists: " + s);
1079 iliev 1161 }
1080    
1081 iliev 1187 if (GetDirectoryId(dstId, instrName) != -1) {
1082 iliev 1345 String s = toEscapedPath(instrName);
1083     throw Exception("Cannot move. Directory with that name already exists: " + s);
1084 iliev 1187 }
1085    
1086 iliev 1161 std::stringstream sql;
1087     sql << "UPDATE instruments SET dir_id=" << dstId;
1088     sql << " WHERE instr_id=" << instrId;
1089     ExecSql(sql.str());
1090     } catch (Exception e) {
1091 iliev 1187 EndTransaction();
1092 iliev 1161 throw e;
1093     }
1094 iliev 1187 EndTransaction();
1095 iliev 1161 FireInstrumentCountChanged(ParentDir);
1096     FireInstrumentCountChanged(Dst);
1097     }
1098    
1099 iliev 1187 void InstrumentsDb::CopyInstrument(String Instr, String Dst) {
1100     dmsg(2,("InstrumentsDb: CopyInstrument(Instr=%s,Dst=%s)\n", Instr.c_str(), Dst.c_str()));
1101     String ParentDir = GetDirectoryPath(Instr);
1102     if(ParentDir.empty()) throw Exception("Unknown parent directory");
1103    
1104     BeginTransaction();
1105     try {
1106     int dirId = GetDirectoryId(GetDirectoryPath(Instr));
1107 iliev 1345 if (dirId == -1) throw Exception("Unknown DB instrument: " + toEscapedPath(Instr));
1108 iliev 1187
1109     String instrName = GetFileName(Instr);
1110     int instrId = GetInstrumentId(dirId, instrName);
1111 iliev 1345 if (instrId == -1) throw Exception("Unknown DB instrument: " + toEscapedPath(Instr));
1112 iliev 1187
1113     int dstId = GetDirectoryId(Dst);
1114 iliev 1345 if (dstId == -1) throw Exception("Unknown DB directory: " + toEscapedPath(Dst));
1115 iliev 1187 if (dirId == dstId) {
1116     EndTransaction();
1117     return;
1118     }
1119    
1120     CopyInstrument(instrId, instrName, dstId, Dst);
1121     } catch (Exception e) {
1122     EndTransaction();
1123     throw e;
1124     }
1125     EndTransaction();
1126    
1127     }
1128    
1129     void InstrumentsDb::CopyInstrument(int InstrId, String InstrName, int DstDirId, String DstDir) {
1130 iliev 1350 if (GetInstrumentId(DstDirId, InstrName) != -1) {
1131     String s = toEscapedPath(InstrName);
1132     throw Exception("Cannot copy. Instrument with that name already exists: " + s);
1133     }
1134    
1135     if (GetDirectoryId(DstDirId, InstrName) != -1) {
1136     String s = toEscapedPath(InstrName);
1137     throw Exception("Cannot copy. Directory with that name already exists: " + s);
1138     }
1139    
1140 iliev 1187 DbInstrument i = GetInstrumentInfo(InstrId);
1141     sqlite3_stmt *pStmt = NULL;
1142     std::stringstream sql;
1143     sql << "INSERT INTO instruments (dir_id,instr_name,instr_file,instr_nr,format_family,";
1144     sql << "format_version,instr_size,description,is_drum,product,artists,keywords) ";
1145     sql << "VALUES (" << DstDirId << ",?,?," << i.InstrNr << ",?,?," << i.Size << ",?,";
1146     sql << i.IsDrum << ",?,?,?)";
1147    
1148     int res = sqlite3_prepare(GetDb(), sql.str().c_str(), -1, &pStmt, NULL);
1149     if (res != SQLITE_OK) {
1150     throw Exception("DB error: " + ToString(sqlite3_errmsg(db)));
1151     }
1152    
1153 iliev 1350 String s = toDbName(InstrName);
1154     BindTextParam(pStmt, 1, s);
1155 iliev 1187 BindTextParam(pStmt, 2, i.InstrFile);
1156     BindTextParam(pStmt, 3, i.FormatFamily);
1157     BindTextParam(pStmt, 4, i.FormatVersion);
1158     BindTextParam(pStmt, 5, i.Description);
1159     BindTextParam(pStmt, 6, i.Product);
1160     BindTextParam(pStmt, 7, i.Artists);
1161     BindTextParam(pStmt, 8, i.Keywords);
1162    
1163     res = sqlite3_step(pStmt);
1164     if(res != SQLITE_DONE) {
1165     sqlite3_finalize(pStmt);
1166     throw Exception("DB error: " + ToString(sqlite3_errmsg(db)));
1167     }
1168    
1169     sqlite3_finalize(pStmt);
1170     FireInstrumentCountChanged(DstDir);
1171     }
1172    
1173 iliev 1161 void InstrumentsDb::SetInstrumentDescription(String Instr, String Desc) {
1174     dmsg(2,("InstrumentsDb: SetInstrumentDescription(Instr=%s,Desc=%s)\n", Instr.c_str(), Desc.c_str()));
1175    
1176 iliev 1187 BeginTransaction();
1177 iliev 1161 try {
1178     int id = GetInstrumentId(Instr);
1179 iliev 1345 if(id == -1) throw Exception("Unknown DB instrument: " + toEscapedPath(Instr));
1180 iliev 1161
1181     std::stringstream sql;
1182     sql << "UPDATE instruments SET description=?,modified=CURRENT_TIMESTAMP ";
1183     sql << "WHERE instr_id="<< id;
1184    
1185     ExecSql(sql.str(), Desc);
1186     } catch (Exception e) {
1187 iliev 1187 EndTransaction();
1188 iliev 1161 throw e;
1189     }
1190 iliev 1187 EndTransaction();
1191 iliev 1161 FireInstrumentInfoChanged(Instr);
1192     }
1193    
1194 schoenebeck 3092 void InstrumentsDb::AddInstrumentsFromFile(String DbDir, String file, int Index, ScanProgress* pProgress) {
1195     dmsg(2,("InstrumentsDb: AddInstrumentsFromFile(DbDir=%s,File=%s,Index=%d)\n", DbDir.c_str(), file.c_str(), Index));
1196    
1197     if (!InstrumentFileInfo::isSupportedFile(file)) return;
1198    
1199 iliev 1161 try {
1200 schoenebeck 3092 if (pProgress != NULL) {
1201     pProgress->SetStatus(0);
1202     pProgress->CurrentFile = file;
1203     }
1204 iliev 1200
1205 schoenebeck 3092 int dirId = GetDirectoryId(DbDir);
1206     if (dirId == -1) throw Exception("Invalid DB directory: " + toEscapedPath(DbDir));
1207 iliev 1200
1208 schoenebeck 3092 File f = File(file);
1209     if (!f.Exist()) {
1210     std::stringstream ss;
1211     ss << "Fail to stat `" << file << "`: " << f.GetErrorMsg();
1212     throw Exception(ss.str());
1213 iliev 1161 }
1214 schoenebeck 3092
1215     if (!f.IsFile()) {
1216     std::stringstream ss;
1217     ss << "`" << file << "` is not a regular file";
1218     throw Exception(ss.str());
1219     }
1220    
1221     AddInstrumentsFromFilePriv(DbDir, dirId, file, f, Index, pProgress);
1222    
1223     if (pProgress != NULL) {
1224     pProgress->SetScannedFileCount(pProgress->GetScannedFileCount() + 1);
1225     }
1226 iliev 1161 } catch(Exception e) {
1227 iliev 1717 e.PrintMessage();
1228 iliev 1161 }
1229     }
1230    
1231 schoenebeck 3092 void InstrumentsDb::AddInstrumentsFromFilePriv(String DbDir, const int dirId, String FilePath, File file, int Index, ScanProgress* pProgress) {
1232 iliev 1717 dmsg(2,("InstrumentsDb: AddGigInstruments(DbDir=%s,FilePath=%s,Index=%d)\n", DbDir.c_str(), FilePath.c_str(), Index));
1233 iliev 1161
1234 iliev 1881 bool unlocked = false;
1235 schoenebeck 3092 InstrumentFileInfo* fileInfo = NULL;
1236     sqlite3_stmt* pStmt = NULL;
1237 iliev 1161 try {
1238 schoenebeck 3092 fileInfo = InstrumentFileInfo::getFileInfoFor(FilePath);
1239     if (!fileInfo) return;
1240 iliev 1200
1241 iliev 1161 std::stringstream sql;
1242     sql << "INSERT INTO instruments (dir_id,instr_name,instr_file,";
1243     sql << "instr_nr,format_family,format_version,instr_size,";
1244     sql << "description,is_drum,product,artists,keywords) VALUES (";
1245 schoenebeck 3092 sql << dirId << ",?,?,?,?,?," << file.GetSize() << ",?,?,?,?,?)";
1246 iliev 1161
1247 schoenebeck 3092 // instr_name 1
1248     // instr_file 2
1249     // instr_nr 3
1250     // format_family 4
1251     // format_version 5
1252     // description 6
1253     // is_drum 7
1254     // product 8
1255     // artists 9
1256     // keywords 10
1257 iliev 1161
1258     int res = sqlite3_prepare(GetDb(), sql.str().c_str(), -1, &pStmt, NULL);
1259     if (res != SQLITE_OK) {
1260     throw Exception("DB error: " + ToString(sqlite3_errmsg(db)));
1261     }
1262    
1263 schoenebeck 3092 BindTextParam(pStmt, 2, toEscapedFsPath(FilePath));
1264     BindTextParam(pStmt, 4, fileInfo->formatName());
1265     BindTextParam(pStmt, 5, fileInfo->formatVersion());
1266 iliev 1161
1267 schoenebeck 3092 int instrIndex = (Index == -1) ? 0 : Index;
1268 iliev 1881
1269 schoenebeck 3092 // Assume that it's locked and should be unlocked at this point
1270     // to be able to use the database from another threads
1271     if (!InTransaction) {
1272     DbInstrumentsMutex.Unlock();
1273     unlocked = true;
1274     } else {
1275     std::cerr << "Shouldn't be in transaction when adding instruments." << std::endl;
1276     }
1277 iliev 1881
1278 schoenebeck 3092 optional<InstrumentInfo> info = fileInfo->getInstrumentInfo(0, pProgress);
1279     if (!InTransaction) DbInstrumentsMutex.Lock();
1280     while (info) {
1281     String instrumentName = info->instrumentName;
1282     if (instrumentName.empty())
1283     instrumentName = Path::getBaseName(FilePath);
1284     instrumentName = GetUniqueName(dirId, instrumentName);
1285 iliev 1161
1286 schoenebeck 3092 BindTextParam(pStmt, 8, info->product);
1287     BindTextParam(pStmt, 9, info->artists);
1288     BindTextParam(pStmt, 10, info->keywords);
1289    
1290     std::stringstream sql2;
1291     sql2 << "SELECT COUNT(*) FROM instruments WHERE instr_file=? AND ";
1292     sql2 << "instr_nr=" << instrIndex;
1293     String s = toEscapedFsPath(FilePath);
1294     if (ExecSqlInt(sql2.str(), s) > 0) goto next;
1295    
1296     BindTextParam(pStmt, 1, instrumentName);
1297     BindIntParam(pStmt, 3, instrIndex);
1298    
1299     BindTextParam(pStmt, 6, info->comments);
1300     BindIntParam(pStmt, 7, info->isDrum);
1301    
1302     res = sqlite3_step(pStmt);
1303     if (res != SQLITE_DONE) {
1304     throw Exception("DB error: " + ToString(sqlite3_errmsg(db)));
1305 iliev 1161 }
1306 schoenebeck 3092 res = sqlite3_reset(pStmt);
1307     FireInstrumentCountChanged(DbDir);
1308    
1309     next:
1310     if (Index != -1) break;
1311    
1312     instrIndex++;
1313     info = fileInfo->getInstrumentInfo(instrIndex, pProgress);
1314 iliev 1161 }
1315 schoenebeck 3092 } catch (Exception e) {
1316     if (pStmt) sqlite3_finalize(pStmt);
1317     if (fileInfo) delete fileInfo;
1318 iliev 1881 if (unlocked) DbInstrumentsMutex.Lock();
1319 iliev 1161 std::stringstream ss;
1320 schoenebeck 3092 ss << "Failed to scan `" << FilePath << "`: " << e.Message();
1321 iliev 1161 throw Exception(ss.str());
1322     } catch (...) {
1323 schoenebeck 3092 if (pStmt) sqlite3_finalize(pStmt);
1324     if (fileInfo) delete fileInfo;
1325 iliev 1881 if (unlocked) DbInstrumentsMutex.Lock();
1326 iliev 1717 throw Exception("Failed to scan `" + FilePath + "`");
1327 iliev 1161 }
1328 schoenebeck 3092 if (pStmt) sqlite3_finalize(pStmt);
1329     if (fileInfo) delete fileInfo;
1330     if (unlocked) DbInstrumentsMutex.Lock();
1331 iliev 1161 }
1332    
1333 iliev 1345 void InstrumentsDb::DirectoryTreeWalk(String AbstractPath, DirectoryHandler* pHandler) {
1334     int DirId = GetDirectoryId(AbstractPath);
1335     if(DirId == -1) throw Exception("Unknown DB directory: " + toEscapedPath(AbstractPath));
1336     DirectoryTreeWalk(pHandler, AbstractPath, DirId, 0);
1337 iliev 1187 }
1338    
1339 iliev 1345 void InstrumentsDb::DirectoryTreeWalk(DirectoryHandler* pHandler, String AbstractPath, int DirId, int Level) {
1340 iliev 1187 if(Level == 1000) throw Exception("Possible infinite loop detected");
1341 iliev 1345 pHandler->ProcessDirectory(AbstractPath, DirId);
1342 iliev 1187
1343     String s;
1344     StringListPtr pDirs = GetDirectories(DirId);
1345     for(int i = 0; i < pDirs->size(); i++) {
1346 iliev 1345 if (AbstractPath.length() == 1 && AbstractPath.at(0) == '/') {
1347     s = "/" + pDirs->at(i);
1348     } else {
1349     s = AbstractPath + "/" + pDirs->at(i);
1350     }
1351 iliev 1187 DirectoryTreeWalk(pHandler, s, GetDirectoryId(DirId, pDirs->at(i)), Level + 1);
1352     }
1353     }
1354    
1355     StringListPtr InstrumentsDb::FindDirectories(String Dir, SearchQuery* pQuery, bool Recursive) {
1356     dmsg(2,("InstrumentsDb: FindDirectories(Dir=%s)\n", Dir.c_str()));
1357     DirectoryFinder directoryFinder(pQuery);
1358    
1359     BeginTransaction();
1360     try {
1361     int DirId = GetDirectoryId(Dir);
1362 iliev 1345 if(DirId == -1) throw Exception("Unknown DB directory: " + toEscapedPath(Dir));
1363 iliev 1187
1364     if (Recursive) DirectoryTreeWalk(Dir, &directoryFinder);
1365     else directoryFinder.ProcessDirectory(Dir, DirId);
1366     } catch (Exception e) {
1367     EndTransaction();
1368     throw e;
1369     }
1370     EndTransaction();
1371    
1372     return directoryFinder.GetDirectories();
1373     }
1374    
1375     StringListPtr InstrumentsDb::FindInstruments(String Dir, SearchQuery* pQuery, bool Recursive) {
1376     dmsg(2,("InstrumentsDb: FindInstruments(Dir=%s)\n", Dir.c_str()));
1377     InstrumentFinder instrumentFinder(pQuery);
1378    
1379     BeginTransaction();
1380     try {
1381     int DirId = GetDirectoryId(Dir);
1382 iliev 1345 if(DirId == -1) throw Exception("Unknown DB directory: " + toEscapedPath(Dir));
1383 iliev 1187
1384     if (Recursive) DirectoryTreeWalk(Dir, &instrumentFinder);
1385     else instrumentFinder.ProcessDirectory(Dir, DirId);
1386     } catch (Exception e) {
1387     EndTransaction();
1388     throw e;
1389     }
1390     EndTransaction();
1391    
1392     return instrumentFinder.GetInstruments();
1393     }
1394 iliev 1727
1395     StringListPtr InstrumentsDb::FindLostInstrumentFiles() {
1396     dmsg(2,("InstrumentsDb: FindLostInstrumentFiles()\n"));
1397 iliev 1187
1398 iliev 1727 BeginTransaction();
1399     try {
1400     StringListPtr files = ExecSqlStringList("SELECT DISTINCT instr_file FROM instruments");
1401     StringListPtr result(new std::vector<String>);
1402     for (int i = 0; i < files->size(); i++) {
1403     File f(toNonEscapedFsPath(files->at(i)));
1404     if (!f.Exist()) result->push_back(files->at(i));
1405     }
1406     return result;
1407     } catch (Exception e) {
1408     EndTransaction();
1409     throw e;
1410     }
1411     EndTransaction();
1412     }
1413    
1414     void InstrumentsDb::SetInstrumentFilePath(String OldPath, String NewPath) {
1415     if (OldPath == NewPath) return;
1416     StringListPtr instrs;
1417     BeginTransaction();
1418     try {
1419     std::vector<String> params(2);
1420     params[0] = toEscapedFsPath(NewPath);
1421     params[1] = toEscapedFsPath(OldPath);
1422     instrs = GetInstrumentsByFile(OldPath);
1423     ExecSql("UPDATE instruments SET instr_file=? WHERE instr_file=?", params);
1424     } catch (Exception e) {
1425     EndTransaction();
1426     throw e;
1427     }
1428     EndTransaction();
1429    
1430     for (int i = 0; i < instrs->size(); i++) {
1431     FireInstrumentInfoChanged(instrs->at(i));
1432     }
1433     }
1434    
1435 iliev 1187 void InstrumentsDb::BeginTransaction() {
1436     dmsg(2,("InstrumentsDb: BeginTransaction(InTransaction=%d)\n", InTransaction));
1437     DbInstrumentsMutex.Lock();
1438     if (InTransaction) return;
1439    
1440     if(db == NULL) return;
1441     sqlite3_stmt *pStmt = NULL;
1442    
1443     InTransaction = true;
1444     int res = sqlite3_prepare(db, "BEGIN TRANSACTION", -1, &pStmt, NULL);
1445     if (res != SQLITE_OK) {
1446     std::cerr << ToString(sqlite3_errmsg(db)) << std::endl;
1447     return;
1448     }
1449    
1450     res = sqlite3_step(pStmt);
1451     if(res != SQLITE_DONE) {
1452     sqlite3_finalize(pStmt);
1453     std::cerr << ToString(sqlite3_errmsg(db)) << std::endl;
1454     return;
1455     }
1456    
1457     sqlite3_finalize(pStmt);
1458     }
1459    
1460     void InstrumentsDb::EndTransaction() {
1461     dmsg(2,("InstrumentsDb: EndTransaction(InTransaction=%d)\n", InTransaction));
1462     if (!InTransaction) {
1463     DbInstrumentsMutex.Unlock();
1464     return;
1465     }
1466     InTransaction = false;
1467    
1468 persson 2427 if (db == NULL) {
1469 iliev 1187 DbInstrumentsMutex.Unlock();
1470     return;
1471     }
1472     sqlite3_stmt *pStmt = NULL;
1473    
1474     int res = sqlite3_prepare(db, "END TRANSACTION", -1, &pStmt, NULL);
1475     if (res != SQLITE_OK) {
1476     std::cerr << ToString(sqlite3_errmsg(db)) << std::endl;
1477     DbInstrumentsMutex.Unlock();
1478     return;
1479     }
1480    
1481     res = sqlite3_step(pStmt);
1482     if(res != SQLITE_DONE) {
1483     sqlite3_finalize(pStmt);
1484     std::cerr << ToString(sqlite3_errmsg(db)) << std::endl;
1485     DbInstrumentsMutex.Unlock();
1486     return;
1487     }
1488    
1489     sqlite3_finalize(pStmt);
1490     DbInstrumentsMutex.Unlock();
1491     }
1492    
1493 iliev 1161 void InstrumentsDb::ExecSql(String Sql) {
1494     dmsg(2,("InstrumentsDb: ExecSql(Sql=%s)\n", Sql.c_str()));
1495 iliev 1727 std::vector<String> Params;
1496     ExecSql(Sql, Params);
1497 iliev 1161 }
1498    
1499     void InstrumentsDb::ExecSql(String Sql, String Param) {
1500     dmsg(2,("InstrumentsDb: ExecSql(Sql=%s,Param=%s)\n", Sql.c_str(), Param.c_str()));
1501 iliev 1727 std::vector<String> Params;
1502     Params.push_back(Param);
1503     ExecSql(Sql, Params);
1504     }
1505    
1506     void InstrumentsDb::ExecSql(String Sql, std::vector<String>& Params) {
1507     dmsg(2,("InstrumentsDb: ExecSql(Sql=%s,Params)\n", Sql.c_str()));
1508 iliev 1161 sqlite3_stmt *pStmt = NULL;
1509    
1510     int res = sqlite3_prepare(GetDb(), Sql.c_str(), -1, &pStmt, NULL);
1511     if (res != SQLITE_OK) {
1512     sqlite3_finalize(pStmt);
1513     throw Exception("DB error: " + ToString(sqlite3_errmsg(db)));
1514     }
1515    
1516 iliev 1727 for(int i = 0; i < Params.size(); i++) {
1517     BindTextParam(pStmt, i + 1, Params[i]);
1518     }
1519 iliev 1161
1520     res = sqlite3_step(pStmt);
1521     if (res != SQLITE_DONE) {
1522     sqlite3_finalize(pStmt);
1523     throw Exception("DB error: " + ToString(sqlite3_errmsg(db)));
1524     }
1525    
1526     sqlite3_finalize(pStmt);
1527     }
1528    
1529     int InstrumentsDb::ExecSqlInt(String Sql) {
1530     dmsg(2,("InstrumentsDb: ExecSqlInt(Sql=%s)\n", Sql.c_str()));
1531     sqlite3_stmt *pStmt = NULL;
1532    
1533     int res = sqlite3_prepare(GetDb(), Sql.c_str(), -1, &pStmt, NULL);
1534     if (res != SQLITE_OK) {
1535     throw Exception("DB error: " + ToString(sqlite3_errmsg(db)));
1536     }
1537    
1538     int i = -1;
1539     res = sqlite3_step(pStmt);
1540     if(res == SQLITE_ROW) {
1541     i = sqlite3_column_int(pStmt, 0);
1542     } else if (res != SQLITE_DONE) {
1543     sqlite3_finalize(pStmt);
1544     throw Exception("DB error: " + ToString(sqlite3_errmsg(db)));
1545     }
1546    
1547     sqlite3_finalize(pStmt);
1548    
1549     return i;
1550     }
1551    
1552     int InstrumentsDb::ExecSqlInt(String Sql, String Param) {
1553     dmsg(2,("InstrumentsDb: ExecSqlInt(Sql=%s,Param=%s)\n", Sql.c_str(), Param.c_str()));
1554     sqlite3_stmt *pStmt = NULL;
1555    
1556     int res = sqlite3_prepare(GetDb(), Sql.c_str(), -1, &pStmt, NULL);
1557     if (res != SQLITE_OK) {
1558     throw Exception("DB error: " + ToString(sqlite3_errmsg(db)));
1559     }
1560    
1561     BindTextParam(pStmt, 1, Param);
1562    
1563     int i = -1;
1564     res = sqlite3_step(pStmt);
1565     if(res == SQLITE_ROW) {
1566     i = sqlite3_column_int(pStmt, 0);
1567     } else if (res != SQLITE_DONE) {
1568     sqlite3_finalize(pStmt);
1569     throw Exception("DB error: " + ToString(sqlite3_errmsg(db)));
1570     }
1571    
1572     sqlite3_finalize(pStmt);
1573     return i;
1574     }
1575    
1576     String InstrumentsDb::ExecSqlString(String Sql) {
1577     dmsg(2,("InstrumentsDb: ExecSqlString(Sql=%s)\n", Sql.c_str()));
1578     sqlite3_stmt *pStmt = NULL;
1579    
1580     int res = sqlite3_prepare(GetDb(), Sql.c_str(), -1, &pStmt, NULL);
1581     if (res != SQLITE_OK) {
1582     throw Exception("DB error: " + ToString(sqlite3_errmsg(db)));
1583     }
1584    
1585     String s;
1586     res = sqlite3_step(pStmt);
1587     if(res == SQLITE_ROW) {
1588     s = ToString(sqlite3_column_text(pStmt, 0));
1589     } else if (res != SQLITE_DONE) {
1590     sqlite3_finalize(pStmt);
1591     throw Exception("DB error: " + ToString(sqlite3_errmsg(db)));
1592     }
1593    
1594     sqlite3_finalize(pStmt);
1595    
1596     return s;
1597     }
1598    
1599     IntListPtr InstrumentsDb::ExecSqlIntList(String Sql) {
1600 iliev 1727 dmsg(2,("InstrumentsDb: ExecSqlIntList(Sql=%s)\n", Sql.c_str()));
1601     std::vector<String> Params;
1602     return ExecSqlIntList(Sql, Params);
1603     }
1604    
1605     IntListPtr InstrumentsDb::ExecSqlIntList(String Sql, String Param) {
1606     dmsg(2,("InstrumentsDb: ExecSqlIntList(Sql=%s,Param=%s)\n", Sql.c_str(), Param.c_str()));
1607     std::vector<String> Params;
1608     Params.push_back(Param);
1609     return ExecSqlIntList(Sql, Params);
1610     }
1611    
1612     IntListPtr InstrumentsDb::ExecSqlIntList(String Sql, std::vector<String>& Params) {
1613     dmsg(2,("InstrumentsDb: ExecSqlIntList(Sql=%s)\n", Sql.c_str()));
1614 iliev 1161 IntListPtr intList(new std::vector<int>);
1615    
1616     sqlite3_stmt *pStmt = NULL;
1617    
1618     int res = sqlite3_prepare(GetDb(), Sql.c_str(), -1, &pStmt, NULL);
1619     if (res != SQLITE_OK) {
1620     throw Exception("DB error: " + ToString(sqlite3_errmsg(db)));
1621     }
1622    
1623 iliev 1727 for(int i = 0; i < Params.size(); i++) {
1624     BindTextParam(pStmt, i + 1, Params[i]);
1625     }
1626    
1627 iliev 1161 res = sqlite3_step(pStmt);
1628     while(res == SQLITE_ROW) {
1629     intList->push_back(sqlite3_column_int(pStmt, 0));
1630     res = sqlite3_step(pStmt);
1631     }
1632    
1633     if (res != SQLITE_DONE) {
1634     sqlite3_finalize(pStmt);
1635     throw Exception("DB error: " + ToString(sqlite3_errmsg(db)));
1636     }
1637    
1638     sqlite3_finalize(pStmt);
1639    
1640     return intList;
1641     }
1642    
1643     StringListPtr InstrumentsDb::ExecSqlStringList(String Sql) {
1644 iliev 1727 dmsg(2,("InstrumentsDb: ExecSqlStringList(Sql=%s)\n", Sql.c_str()));
1645 iliev 1161 StringListPtr stringList(new std::vector<String>);
1646    
1647     sqlite3_stmt *pStmt = NULL;
1648    
1649     int res = sqlite3_prepare(GetDb(), Sql.c_str(), -1, &pStmt, NULL);
1650     if (res != SQLITE_OK) {
1651     throw Exception("DB error: " + ToString(sqlite3_errmsg(db)));
1652     }
1653    
1654     res = sqlite3_step(pStmt);
1655     while(res == SQLITE_ROW) {
1656     stringList->push_back(ToString(sqlite3_column_text(pStmt, 0)));
1657     res = sqlite3_step(pStmt);
1658     }
1659    
1660     if (res != SQLITE_DONE) {
1661     sqlite3_finalize(pStmt);
1662     throw Exception("DB error: " + ToString(sqlite3_errmsg(db)));
1663     }
1664    
1665     sqlite3_finalize(pStmt);
1666    
1667     return stringList;
1668     }
1669    
1670     void InstrumentsDb::BindTextParam(sqlite3_stmt* pStmt, int Index, String Text) {
1671     if (pStmt == NULL) return;
1672 schoenebeck 3050 int res = sqlite3_bind_text(pStmt, Index, Text.c_str(), -1, SQLITE_TRANSIENT);
1673 iliev 1161 if (res != SQLITE_OK) {
1674     sqlite3_finalize(pStmt);
1675     throw Exception("DB error: " + ToString(sqlite3_errmsg(db)));
1676     }
1677     }
1678    
1679     void InstrumentsDb::BindIntParam(sqlite3_stmt* pStmt, int Index, int Param) {
1680     if (pStmt == NULL) return;
1681     int res = sqlite3_bind_int(pStmt, Index, Param);
1682     if (res != SQLITE_OK) {
1683     sqlite3_finalize(pStmt);
1684     throw Exception("DB error: " + ToString(sqlite3_errmsg(db)));
1685     }
1686     }
1687    
1688 persson 1908 #ifndef WIN32
1689 iliev 1187 void InstrumentsDb::Regexp(sqlite3_context* pContext, int argc, sqlite3_value** ppValue) {
1690     if (argc != 2) return;
1691    
1692     String pattern = ToString(sqlite3_value_text(ppValue[0]));
1693     String str = ToString(sqlite3_value_text(ppValue[1]));
1694    
1695     if(!fnmatch(pattern.c_str(), str.c_str(), FNM_CASEFOLD)) {
1696     sqlite3_result_int(pContext, 1);
1697     }
1698     }
1699 persson 1908 #endif
1700 iliev 1187
1701 iliev 1161 String InstrumentsDb::GetDirectoryPath(String File) {
1702     if (File.empty()) return String("");
1703     if (File.at(0) != '/') String("");
1704     if (File.length() == 1) return File;
1705     if (File.at(File.length() - 1) == '/') return File.substr(0, File.length() - 1);
1706     int i = File.rfind('/', File.length() - 1);
1707     if(i == std::string::npos) return String("");
1708     if(i == 0) return String("/");
1709     return File.substr(0, i);
1710     }
1711    
1712     String InstrumentsDb::GetFileName(String Path) {
1713     if (Path.length() < 2) return String("");
1714     if (Path.at(0) != '/') String("");
1715     if (Path.at(Path.length() - 1) == '/') return String("");
1716     int i = Path.rfind('/', Path.length() - 1);
1717     return Path.substr(i + 1);
1718     }
1719    
1720     void InstrumentsDb::CheckPathName(String Path) {
1721     if (Path.empty()) return;
1722    
1723     int i = 0, j = Path.find('/', i);
1724    
1725     while(j != std::string::npos) {
1726     if (j + 1 >= Path.length()) return;
1727     if (Path.at(j + 1) == '/') throw Exception("Invalid path name: " + Path);
1728    
1729     i = j + 1;
1730     j = Path.find('/', i);
1731     }
1732     }
1733    
1734     String InstrumentsDb::GetParentDirectory(String Dir) {
1735     if (Dir.length() < 2) return String("");
1736     if (Dir.at(0) != '/') String("");
1737     int i = Dir.rfind('/', Dir.length() - 2);
1738     if (i == 0) return "/";
1739     return Dir.substr(0, i);
1740     }
1741    
1742 iliev 1353 void InstrumentsDb::Format() {
1743 persson 2427 {
1744     LockGuard lock(DbInstrumentsMutex);
1745 iliev 1353
1746 persson 2427 if (db != NULL) {
1747     sqlite3_close(db);
1748     db = NULL;
1749     }
1750    
1751 schoenebeck 3091 if (DbFile.empty()) DbFile = GetDefaultDBLocation();
1752 persson 2427 String bkp = DbFile + ".bkp";
1753     remove(bkp.c_str());
1754     if (rename(DbFile.c_str(), bkp.c_str()) && errno != ENOENT) {
1755     throw Exception(String("Failed to backup database: ") + strerror(errno));
1756     }
1757 iliev 1353
1758 persson 2427 String f = DbFile;
1759     DbFile = "";
1760     CreateInstrumentsDb(f);
1761 iliev 1353 }
1762     FireDirectoryCountChanged("/");
1763     FireInstrumentCountChanged("/");
1764     }
1765    
1766 iliev 1161 void InstrumentsDb::CheckFileName(String File) {
1767     if (File.empty()) throw Exception("Invalid file name: " + File);
1768     }
1769    
1770 iliev 1782 String InstrumentsDb::GetUniqueName(int DirId, String Name) {
1771 iliev 1161 dmsg(2,("InstrumentsDb: GetUniqueInstrumentName(DirId=%d,Name=%s)\n", DirId, Name.c_str()));
1772    
1773 iliev 1187 if (GetInstrumentId(DirId, Name) == -1 && GetDirectoryId(DirId, Name) == -1) return Name;
1774 iliev 1161 std::stringstream ss;
1775     for(int i = 2; i < 1001; i++) {
1776     ss.str("");
1777     ss << Name << '[' << i << ']';
1778 iliev 1187 if (GetInstrumentId(DirId, ss.str()) == -1 && GetInstrumentId(DirId, ss.str()) == -1) {
1779     return ss.str();
1780     }
1781 iliev 1161 }
1782    
1783     throw Exception("Unable to find an unique name: " + Name);
1784     }
1785 iliev 1782
1786     String InstrumentsDb::PrepareSubdirectory(String DbDir, String FsPath) {
1787     std::string dir = Path::getBaseName(FsPath);
1788     dir = toAbstractName(dir);
1789     if(dir.empty()) dir = "New Directory";
1790     dir = GetUniqueName(GetDirectoryId(DbDir), dir);
1791     dir = AppendNode(DbDir, dir);
1792     AddDirectory(dir);
1793     return dir;
1794     }
1795 iliev 1200
1796 iliev 1782 String InstrumentsDb::AppendNode(String DbDir, String Node) {
1797 iliev 1810 if(DbDir.length() == 1 && DbDir.at(0) == '/') return DbDir + Node;
1798     if(DbDir.at(DbDir.length() - 1) == '/') return DbDir + Node;
1799     return DbDir + "/" + Node;
1800 iliev 1782 }
1801    
1802 iliev 1345 String InstrumentsDb::toDbName(String AbstractName) {
1803     for (int i = 0; i < AbstractName.length(); i++) {
1804     if (AbstractName.at(i) == '\0') AbstractName.at(i) = '/';
1805     }
1806     return AbstractName;
1807     }
1808    
1809     String InstrumentsDb::toEscapedPath(String AbstractName) {
1810     for (int i = 0; i < AbstractName.length(); i++) {
1811 iliev 1350 if (AbstractName.at(i) == '\0') AbstractName.replace(i++, 1, "\\x2f");
1812 iliev 1345 else if (AbstractName.at(i) == '\\') AbstractName.replace(i++, 1, "\\\\");
1813     else if (AbstractName.at(i) == '\'') AbstractName.replace(i++, 1, "\\'");
1814     else if (AbstractName.at(i) == '"') AbstractName.replace(i++, 1, "\\\"");
1815     else if (AbstractName.at(i) == '\r') AbstractName.replace(i++, 1, "\\r");
1816     else if (AbstractName.at(i) == '\n') AbstractName.replace(i++, 1, "\\n");
1817     }
1818     return AbstractName;
1819     }
1820    
1821     String InstrumentsDb::toEscapedText(String text) {
1822     for (int i = 0; i < text.length(); i++) {
1823     if (text.at(i) == '\\') text.replace(i++, 1, "\\\\");
1824     else if (text.at(i) == '\'') text.replace(i++, 1, "\\'");
1825     else if (text.at(i) == '"') text.replace(i++, 1, "\\\"");
1826     else if (text.at(i) == '\r') text.replace(i++, 1, "\\r");
1827     else if (text.at(i) == '\n') text.replace(i++, 1, "\\n");
1828     }
1829     return text;
1830     }
1831    
1832 iliev 1727 String InstrumentsDb::toNonEscapedText(String text) {
1833     String sb;
1834     for (int i = 0; i < text.length(); i++) {
1835     char c = text.at(i);
1836     if(c == '\\') {
1837     if(i >= text.length()) {
1838     std::cerr << "Broken escape sequence!" << std::endl;
1839     break;
1840     }
1841     char c2 = text.at(++i);
1842     if(c2 == '\'') sb.push_back('\'');
1843     else if(c2 == '"') sb.push_back('"');
1844     else if(c2 == '\\') sb.push_back('\\');
1845     else if(c2 == 'r') sb.push_back('\r');
1846     else if(c2 == 'n') sb.push_back('\n');
1847     else std::cerr << "Unknown escape sequence \\" << c2 << std::endl;
1848     } else {
1849     sb.push_back(c);
1850     }
1851     }
1852     return sb;
1853     }
1854    
1855 iliev 1350 String InstrumentsDb::toEscapedFsPath(String FsPath) {
1856 persson 1943 #ifdef WIN32
1857     replace(FsPath.begin(), FsPath.end(), '\\', '/');
1858     #endif
1859 iliev 1350 return toEscapedText(FsPath);
1860 iliev 1345 }
1861    
1862 iliev 1727 String InstrumentsDb::toNonEscapedFsPath(String FsPath) {
1863 persson 1943 FsPath = toNonEscapedText(FsPath);
1864     #ifdef WIN32
1865     replace(FsPath.begin(), FsPath.end(), '/', '\\');
1866     #endif
1867     return FsPath;
1868 iliev 1727 }
1869    
1870 iliev 1345 String InstrumentsDb::toAbstractName(String DbName) {
1871     for (int i = 0; i < DbName.length(); i++) {
1872     if (DbName.at(i) == '/') DbName.at(i) = '\0';
1873     }
1874     return DbName;
1875     }
1876    
1877 iliev 1161 void InstrumentsDb::FireDirectoryCountChanged(String Dir) {
1878     for (int i = 0; i < llInstrumentsDbListeners.GetListenerCount(); i++) {
1879     llInstrumentsDbListeners.GetListener(i)->DirectoryCountChanged(Dir);
1880     }
1881     }
1882 iliev 1200
1883 iliev 1161 void InstrumentsDb::FireDirectoryInfoChanged(String Dir) {
1884     for (int i = 0; i < llInstrumentsDbListeners.GetListenerCount(); i++) {
1885     llInstrumentsDbListeners.GetListener(i)->DirectoryInfoChanged(Dir);
1886     }
1887     }
1888 iliev 1200
1889 iliev 1161 void InstrumentsDb::FireDirectoryNameChanged(String Dir, String NewName) {
1890     for (int i = 0; i < llInstrumentsDbListeners.GetListenerCount(); i++) {
1891     llInstrumentsDbListeners.GetListener(i)->DirectoryNameChanged(Dir, NewName);
1892     }
1893     }
1894 iliev 1200
1895 iliev 1161 void InstrumentsDb::FireInstrumentCountChanged(String Dir) {
1896     for (int i = 0; i < llInstrumentsDbListeners.GetListenerCount(); i++) {
1897     llInstrumentsDbListeners.GetListener(i)->InstrumentCountChanged(Dir);
1898     }
1899     }
1900 iliev 1200
1901 iliev 1161 void InstrumentsDb::FireInstrumentInfoChanged(String Instr) {
1902     for (int i = 0; i < llInstrumentsDbListeners.GetListenerCount(); i++) {
1903     llInstrumentsDbListeners.GetListener(i)->InstrumentInfoChanged(Instr);
1904     }
1905     }
1906 iliev 1200
1907 iliev 1161 void InstrumentsDb::FireInstrumentNameChanged(String Instr, String NewName) {
1908     for (int i = 0; i < llInstrumentsDbListeners.GetListenerCount(); i++) {
1909     llInstrumentsDbListeners.GetListener(i)->InstrumentNameChanged(Instr, NewName);
1910     }
1911     }
1912    
1913 iliev 1200 void InstrumentsDb::FireJobStatusChanged(int JobId) {
1914     for (int i = 0; i < llInstrumentsDbListeners.GetListenerCount(); i++) {
1915     llInstrumentsDbListeners.GetListener(i)->JobStatusChanged(JobId);
1916 iliev 1161 }
1917     }
1918    
1919     } // namespace LinuxSampler

  ViewVC Help
Powered by ViewVC