/[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 1727 - (hide annotations) (download)
Tue Apr 29 15:44:09 2008 UTC (15 years, 11 months ago) by iliev
File size: 69567 byte(s)
* added support for handling lost files in the instruments database
* added new LSCP commands: FIND LOST DB_INSTRUMENT_FILES and
  SET DB_INSTRUMENT FILE_PATH

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

  ViewVC Help
Powered by ViewVC