]> git.phdru.name Git - m_librarian.git/commitdiff
Multidatabase - every script can open a database by pathname or DB URI
authorOleg Broytman <phd@phdru.name>
Mon, 30 May 2016 22:10:07 +0000 (01:10 +0300)
committerOleg Broytman <phd@phdru.name>
Mon, 30 May 2016 22:10:07 +0000 (01:10 +0300)
ChangeLog
TODO
docs-ru/command_line.rst
docs/command_line.rst
m_librarian/db.py
scripts/ml-import.py
scripts/ml-initdb.py
scripts/ml-search.py

index 2e8040a588067b5a6086a0a7578f019c08f30e72..93c54c66e604e1000edd29582126c4c3df05d176 100644 (file)
--- a/ChangeLog
+++ b/ChangeLog
@@ -1,20 +1,22 @@
 Version 0.0.10 (2016-05-??)
 
 Version 0.0.10 (2016-05-??)
 
-   Print count after the list
+   Multidatabase - every script can open a database by pathname or DB URI.
 
 
-   Rename -d/--details options to -v/--verbose
+   Print count after the list.
+
+   Rename -d/--details options to -v/--verbose.
 
 Version 0.0.9 (2016-05-30)
 
 
 Version 0.0.9 (2016-05-30)
 
-   Search authors/extensions/genres/languages by database id
+   Search authors/extensions/genres/languages by database id.
 
 Version 0.0.8 (2016-05-29)
 
 
 Version 0.0.8 (2016-05-29)
 
-    Search by author's, book's, extension's, language's id
+    Search by author's, book's, extension's, language's id.
 
 
-    Output count of found objects
+    Output count of found objects.
 
 
-    Use option -d to output database id
+    Use option -d to output database id.
 
 Version 0.0.7 (2016-05-25)
 
 
 Version 0.0.7 (2016-05-25)
 
diff --git a/TODO b/TODO
index bbb7c9c0a3d7b1c10b81d5b7759bc658b5793b24..759ee916bc791f8689eb4056cadcfd7bdd7079fe 100644 (file)
--- a/TODO
+++ b/TODO
@@ -1,10 +1,6 @@
 Web interface for listing authors, books, series, etc.
 
 
 Web interface for listing authors, books, series, etc.
 
 
-Multidatabase: LRE FB2, Flibusta FB2, LRE all, Flibusta all,
-LRE+Flibusta FB2, LRE+Flibusta all.
-
-
 Import from SQL instead of INPX. Import annotations and illustrations.
 
 
 Import from SQL instead of INPX. Import annotations and illustrations.
 
 
index 974e81a6609f3646b392b0ac017507b60ae0e9e0..185505d25a327d55023bbddfd05f8cd68f85eb29 100644 (file)
 ml-initdb.py
 ------------
 
 ml-initdb.py
 ------------
 
+Использование::
+
+    ml-initdb.py [-d]
+
+Опции::
+
+    -d, --database database  Использовать указанную БД
+
 Инициализирует базу данных и импортирует список жанров. Этот скрипт не
 очень-то нужен, так как следующий скрипт делает всё указанное.
 
 Инициализирует базу данных и импортирует список жанров. Этот скрипт не
 очень-то нужен, так как следующий скрипт делает всё указанное.
 
@@ -19,7 +27,11 @@ ml-import.py
 
 Использование::
 
 
 Использование::
 
-    ml-import.py [file.inpx ...]
+    ml-import.py [-d] [file.inpx ...]
+
+Опции::
+
+    -d, --database database  Использовать указанную БД
 
 Инициализирует базу данных, импортирует список жанров и список файлов
 INPX, перечисленных в командной строке. При повторных запусках не
 
 Инициализирует базу данных, импортирует список жанров и список файлов
 INPX, перечисленных в командной строке. При повторных запусках не
@@ -32,24 +44,25 @@ ml-search.py
 
 Использование::
 
 
 Использование::
 
-    ml-search.py [-i] [-I] [-t] [-s] [-f] [-d] [-c] ...
+    ml-search.py [-d] [-i] [-I] [-t] [-s] [-f] [-v] [-c] ...
 
 Программа выполняет поиск по базе данных и показывает список
 результатов. В настоящее время может искать только в списке авторов.
 
 Глобальные опции::
 
 
 Программа выполняет поиск по базе данных и показывает список
 результатов. В настоящее время может искать только в списке авторов.
 
 Глобальные опции::
 
-    -i, --ignore-case     независимо от регистра (по умолчанию: угадать)
-    -I, --case-sensitive  с учётом регистра
-    -t, --start           тип поиска: подстрока в начале строки
-                          (это тип поиска по умолчанию)
-    -s, --substring       тип поиска: подстрока в любом месте
-    -f, --full            тип поиска: полное совпадение всей строки
-    -c, --count           Выводить число найденных объектов, а не сами
-                          объекты
-    -v, --verbose         Выводить больше информации о найденных
-                          объектах; повторите эту опцию несколько раз,
-                          чтобы получить ещё больше деталей
+    -d, --database database  Использовать указанную БД
+    -i, --ignore-case        независимо от регистра (по умолчанию: угадать)
+    -I, --case-sensitive     с учётом регистра
+    -t, --start              тип поиска: подстрока в начале строки
+                             (это тип поиска по умолчанию)
+    -s, --substring          тип поиска: подстрока в любом месте
+    -f, --full               тип поиска: полное совпадение всей строки
+    -c, --count              Выводить число найденных объектов, а не сами
+                             объекты
+    -v, --verbose            Выводить больше информации о найденных
+                             объектах; повторите эту опцию несколько раз,
+                             чтобы получить ещё больше деталей
 
 Опции ``-i/-I`` не могут использованы одновременно, поскольку означают
 противоположные команды. В случае, если ни одна из них не использована,
 
 Опции ``-i/-I`` не могут использованы одновременно, поскольку означают
 противоположные команды. В случае, если ни одна из них не использована,
@@ -73,7 +86,7 @@ ml-search.py
 
 Использование::
 
 
 Использование::
 
-    ml-search.py [-i/-I] [-t/-s/-f] author [-s surname] [-n name] [-m misc-name] [--id id] [fullname]
+    ml-search.py author [-s surname] [-n name] [-m misc-name] [--id id] [fullname]
 
 Искать и печатать список авторов по фамилии, имени, доп. имени (обычно
 отчеству) или полному имени.
 
 Искать и печатать список авторов по фамилии, имени, доп. имени (обычно
 отчеству) или полному имени.
@@ -100,7 +113,7 @@ ml-search.py
 Искать и печатать список авторов, чья фамилия начинается на "друг" и имя
 начинается на "в", без учёта регистра.
 
 Искать и печатать список авторов, чья фамилия начинается на "друг" и имя
 начинается на "в", без учёта регистра.
 
-При использовании опции `-d` также выводится id из БД.
+При использовании опции `-v` также выводится id из БД.
 
 
 Поиск книг
 
 
 Поиск книг
@@ -108,7 +121,7 @@ ml-search.py
 
 Использование::
 
 
 Использование::
 
-    ml-search.py [-i/-I] [-t/-s/-f] books [-t title] [-s series] [-a archive] [-f file] [--id id] [--surname name] [--name name] [--misc-name name] [--fullname name] [--aid aid] [-e ext] [--eid eid] [--gname name] [--gtitle title] [--gid gid] [-l lang] [--lid lid]
+    ml-search.py books [-t title] [-s series] [-a archive] [-f file] [--id id] [--surname name] [--name name] [--misc-name name] [--fullname name] [--aid aid] [-e ext] [--eid eid] [--gname name] [--gtitle title] [--gid gid] [-l lang] [--lid lid]
 
 Искать и печатать список книг по заголовку, серии, архиву, имени файла.
 
 
 Искать и печатать список книг по заголовку, серии, архиву, имени файла.
 
@@ -133,10 +146,10 @@ ml-search.py
     --lid lid              Искать по id языка
 
 По умолчанию программы выводит список заголовков найденных книг. При
     --lid lid              Искать по id языка
 
 По умолчанию программы выводит список заголовков найденных книг. При
-использовании опции `-d` также выводится id из БД, список авторов и
+использовании опции `-v` также выводится id из БД, список авторов и
 жанров, а также серия, к которой принадлежит книга (если принадлежит) и
 жанров, а также серия, к которой принадлежит книга (если принадлежит) и
-порядковый номер книги в этой серии. С двумя опциями `-d` (`-d -d` или
-просто `-dd`) программа выводит дату файла и язык. С тремя `-d`
+порядковый номер книги в этой серии. С двумя опциями `-v` (`-v -v` или
+просто `-vv`) программа выводит дату файла и язык. С тремя `-v`
 выводятся имя архива, имя файла, расширение и размер файла, и признак,
 была ли книга помечена как удалённая.
 
 выводятся имя архива, имя файла, расширение и размер файла, и признак,
 была ли книга помечена как удалённая.
 
@@ -146,7 +159,7 @@ ml-search.py
 
 Использование::
 
 
 Использование::
 
-    ml-search.py [-i/-I] [-t/-s/-f] ext [name] [--id id]
+    ml-search.py ext [name] [--id id]
 
 Опции::
 
 
 Опции::
 
@@ -154,7 +167,7 @@ ml-search.py
 
 Искать и печатать список расширений имён файлов по имени.
 
 
 Искать и печатать список расширений имён файлов по имени.
 
-При использовании опции `-d` также выводится id из БД.
+При использовании опции `-v` также выводится id из БД.
 
 
 Поиск жанров
 
 
 Поиск жанров
@@ -162,7 +175,7 @@ ml-search.py
 
 Использование::
 
 
 Использование::
 
-    ml-search.py [-i/-I] [-t/-s/-f] genres [-n name] [-t title] [--id id]
+    ml-search.py genres [-n name] [-t title] [--id id]
 
 Искать и печатать список жанров по имени и заголовку.
 
 
 Искать и печатать список жанров по имени и заголовку.
 
@@ -172,7 +185,7 @@ ml-search.py
     -t, --title заголовок  Искать по заголовку
     --id id                Искать по id жанра
 
     -t, --title заголовок  Искать по заголовку
     --id id                Искать по id жанра
 
-При использовании опции `-d` также выводится id из БД.
+При использовании опции `-v` также выводится id из БД.
 
 
 Поиск языков
 
 
 Поиск языков
@@ -180,7 +193,7 @@ ml-search.py
 
 Использование::
 
 
 Использование::
 
-    ml-search.py [-i/-I] [-t/-s/-f] lang [name] [--id id]
+    ml-search.py lang [name] [--id id]
 
 Опции::
 
 
 Опции::
 
@@ -188,6 +201,6 @@ ml-search.py
 
 Искать и печатать список языков по имени.
 
 
 Искать и печатать список языков по имени.
 
-При использовании опции `-d` также выводится id из БД.
+При использовании опции `-v` также выводится id из БД.
 
 .. vim: set tw=72 :
 
 .. vim: set tw=72 :
index e33992ae129baaa8f4e0714514e4c8126ce7d3bc..da05ed2ba537dd95ada4953d536d0b63eb2384b0 100644 (file)
@@ -10,6 +10,14 @@ Command-line scripts
 ml-initdb.py
 ------------
 
 ml-initdb.py
 ------------
 
+Usage::
+
+    ml-initdb.py [-d]
+
+Options::
+
+    -d, --database database  Open this database by pathname/db uri
+
 Initialize database and import genres list. Isn’t really needed as
 the next script does all that too.
 
 Initialize database and import genres list. Isn’t really needed as
 the next script does all that too.
 
@@ -19,7 +27,11 @@ ml-import.py
 
 Usage::
 
 
 Usage::
 
-    ml-import.py [file.inpx ...]
+    ml-import.py [-d] [file.inpx ...]
+
+Options::
+
+    -d, --database database  Open this database by pathname/db uri
 
 Initialize database, import genres list and import a list of INPX files
 listed in the command line. On subsequent runs doesn’t destroy DB or
 
 Initialize database, import genres list and import a list of INPX files
 listed in the command line. On subsequent runs doesn’t destroy DB or
@@ -31,22 +43,23 @@ ml-search.py
 
 Usage::
 
 
 Usage::
 
-    ml-search.py [-i] [-I] [-t] [-s] [-f] [-d] [-c] ...
+    ml-search.py [-d] [-i] [-I] [-t] [-s] [-f] [-v] [-c] ...
 
 Search through the database and display results. Currently can only
 search authors by name.
 
 Global options::
 
 
 Search through the database and display results. Currently can only
 search authors by name.
 
 Global options::
 
-    -i, --ignore-case     ignore case (default is to guess)
-    -I, --case-sensitive  don’t ignore case
-    -t, --start           search type: substring at the start
-                          (this is the default)
-    -s, --substring       search type: substring anywhere
-    -f, --full            search type: match the full string
-    -c, --count           Output count of found objects
-    -v, --verbose         Output more details about found objects;
-                          repeat for even more details
+    -d, --database database  Open this database by pathname/db uri
+    -i, --ignore-case        ignore case (default is to guess)
+    -I, --case-sensitive     don’t ignore case
+    -t, --start              search type: substring at the start
+                             (this is the default)
+    -s, --substring          search type: substring anywhere
+    -f, --full               search type: match the full string
+    -c, --count              Output count of found objects
+    -v, --verbose            Output more details about found objects;
+                             repeat for even more details
 
 Options ``-i/-I`` cannot be used together as they are the opposite. In
 case none of them are used the program guesses case-sensitivity by
 
 Options ``-i/-I`` cannot be used together as they are the opposite. In
 case none of them are used the program guesses case-sensitivity by
@@ -71,7 +84,7 @@ Author search
 
 Usage::
 
 
 Usage::
 
-    ml-search.py [-i/-I] [-t/-s/-f] author [-s surname] [-n name] [-m misc-name] [--id id] [fullname]
+    ml-search.py author [-s surname] [-n name] [-m misc-name] [--id id] [fullname]
 
 Search and print a list of authors by surname/name/misc name/full name.
 
 
 Search and print a list of authors by surname/name/misc name/full name.
 
@@ -97,7 +110,7 @@ Example::
 Search and print a list of authors whose surname starts with "duck" and
 name starts with "mack", case insensitive.
 
 Search and print a list of authors whose surname starts with "duck" and
 name starts with "mack", case insensitive.
 
-With one option `-d` it also prints database id.
+With one option `-v` it also prints database id.
 
 
 Book search
 
 
 Book search
@@ -105,7 +118,7 @@ Book search
 
 Usage::
 
 
 Usage::
 
-    ml-search.py [-i/-I] [-t/-s/-f] books [-t title] [-s series] [-a archive] [-f file] [--id id] [--surname name] [--name name] [--misc-name name] [--fullname name] [--aid aid] [-e ext] [--eid eid] [--gname name] [--gtitle title] [--gid gid] [-l lang] [--lid lid]
+    ml-search.py books [-t title] [-s series] [-a archive] [-f file] [--id id] [--surname name] [--name name] [--misc-name name] [--fullname name] [--aid aid] [-e ext] [--eid eid] [--gname name] [--gtitle title] [--gid gid] [-l lang] [--lid lid]
 
 Search and print a list of books by title, series, archive or file name.
 
 
 Search and print a list of books by title, series, archive or file name.
 
@@ -130,10 +143,10 @@ Options::
     --lid lid              Search by language’s id
 
 By default the program prints only titles of the found book. With one
     --lid lid              Search by language’s id
 
 By default the program prints only titles of the found book. With one
-option `-d` it also prints database id, the list of authors and genres,
+option `-v` it also prints database id, the list of authors and genres,
 and also series the book belongs to (if any) and the serial number of
 and also series the book belongs to (if any) and the serial number of
-the book in the series. With two options `-d` (`-d -d` or simply `-dd`)
-it also prints the file date and language. With three `-d` it prints
+the book in the series. With two options `-v` (`-v -v` or simply `-vv`)
+it also prints the file date and language. With three `-v` it prints
 archive name, file name, extension and size, and flag if the book is
 marked to be deleted.
 
 archive name, file name, extension and size, and flag if the book is
 marked to be deleted.
 
@@ -143,7 +156,7 @@ Extension search
 
 Usage::
 
 
 Usage::
 
-    ml-search.py [-i/-I] [-t/-s/-f] ext [name] [--id id]
+    ml-search.py ext [name] [--id id]
 
 Options::
 
 
 Options::
 
@@ -151,7 +164,7 @@ Options::
 
 Search and print a list of extensions by name.
 
 
 Search and print a list of extensions by name.
 
-With one option `-d` it also prints database id.
+With one option `-v` it also prints database id.
 
 
 Genres search
 
 
 Genres search
@@ -159,7 +172,7 @@ Genres search
 
 Usage::
 
 
 Usage::
 
-    ml-search.py [-i/-I] [-t/-s/-f] genres [-n name] [-t title] [--id id]
+    ml-search.py genres [-n name] [-t title] [--id id]
 
 Search and print a list of genres by name and title.
 
 
 Search and print a list of genres by name and title.
 
@@ -169,7 +182,7 @@ Options::
     -t, --title title  Search by title
     --id id            Search by database id
 
     -t, --title title  Search by title
     --id id            Search by database id
 
-With one option `-d` it also prints database id.
+With one option `-v` it also prints database id.
 
 
 Language search
 
 
 Language search
@@ -177,7 +190,7 @@ Language search
 
 Usage::
 
 
 Usage::
 
-    ml-search.py [-i/-I] [-t/-s/-f] lang [name] [--id id]
+    ml-search.py lang [name] [--id id]
 
 Search and print a list of languages by name.
 
 
 Search and print a list of languages by name.
 
@@ -185,6 +198,6 @@ Options::
 
     --id id                Search by database id
 
 
     --id id                Search by database id
 
-With one option `-d` it also prints database id.
+With one option `-v` it also prints database id.
 
 .. vim: set tw=72 :
 
 .. vim: set tw=72 :
index 9a48caa8fdade56f6ca38f86f393ad410ef98b5d..0da18a4676ab8679bcc99664705a252ea50c043b 100755 (executable)
@@ -142,11 +142,11 @@ def open_db(db_uri=None):
         except:
             db_uri = find_sqlite_dburi()
 
         except:
             db_uri = find_sqlite_dburi()
 
-    if db_uri.startswith(os.sep) or db_uri.startswith(os.altsep) \
+    if db_uri.startswith(os.sep) or os.altsep and db_uri.startswith(os.altsep) \
             or db_uri.startswith(os.pardir + os.sep) \
             or db_uri.startswith(os.pardir + os.sep) \
-            or db_uri.startswith(os.pardir + os.altsep):
+            or os.altsep and db_uri.startswith(os.pardir + os.altsep):
         if db_uri.startswith(os.pardir + os.sep) \
         if db_uri.startswith(os.pardir + os.sep) \
-        or db_uri.startswith(os.pardir + os.altsep):
+        or os.altsep and db_uri.startswith(os.pardir + os.altsep):
             db_uri = os.path.abspath(db_uri)
         db_uri = 'sqlite://' + db_uri.replace(os.sep, '/')
 
             db_uri = os.path.abspath(db_uri)
         db_uri = 'sqlite://' + db_uri.replace(os.sep, '/')
 
index 530e4a05651f3a3b34cbc5cc57353e7d1a75d0ee..066c5ccb6bf51bb1069c8487dc7e07571761b7aa 100755 (executable)
@@ -1,16 +1,19 @@
 #! /usr/bin/env python
 
 #! /usr/bin/env python
 
-import sys
+import argparse
 from m_librarian.db import open_db, init_db, update_counters
 from m_librarian.glst import import_glst
 from m_librarian.inp import import_inpx
 
 if __name__ == '__main__':
 from m_librarian.db import open_db, init_db, update_counters
 from m_librarian.glst import import_glst
 from m_librarian.inp import import_inpx
 
 if __name__ == '__main__':
-    if len(sys.argv) < 2:
-        sys.exit("Usage: %s file.inpx..." % sys.argv[0])
-    open_db()
+    parser = argparse.ArgumentParser(description='Import')
+    parser.add_argument('-d', '--database', help='database URI')
+    parser.add_argument('inpx', nargs='+', help='INPX files to import')
+    args = parser.parse_args()
+
+    open_db(args.database)
     init_db()
     import_glst()
     init_db()
     import_glst()
-    for inpx in sys.argv[1:]:
+    for inpx in args.inpx:
         import_inpx(inpx)
     update_counters()
         import_inpx(inpx)
     update_counters()
index 4445fc6f951ddac6dac3e4cfd7f995cbb554205a..4dc71b5f9cb24ee5d223c6e455d7bbaed78f6270 100755 (executable)
@@ -1,10 +1,15 @@
 #! /usr/bin/env python
 
 #! /usr/bin/env python
 
+import argparse
 from m_librarian.db import open_db, init_db
 from m_librarian.glst import import_glst
 
 if __name__ == '__main__':
 from m_librarian.db import open_db, init_db
 from m_librarian.glst import import_glst
 
 if __name__ == '__main__':
-    open_db()
+    parser = argparse.ArgumentParser(description='Init')
+    parser.add_argument('-d', '--database', help='database URI')
+    args = parser.parse_args()
+
+    open_db(args.database)
     init_db()
     old, new = import_glst()
     if old:
     init_db()
     old, new = import_glst()
     if old:
index d9074813164515269704c398e750886e3a7923ae..1cda3f55eb8fd1aad326178677e86674caba48e1 100755 (executable)
@@ -236,6 +236,7 @@ def _search_languages(case_sensitive, search_type, args):
 
 if __name__ == '__main__':
     main_parser = argparse.ArgumentParser(description='Search')
 
 if __name__ == '__main__':
     main_parser = argparse.ArgumentParser(description='Search')
+    main_parser.add_argument('-d', '--database', help='database URI')
     main_parser.add_argument('-i', '--ignore-case', action='store_true',
                              help='ignore case '
                              '(default is to guess)')
     main_parser.add_argument('-i', '--ignore-case', action='store_true',
                              help='ignore case '
                              '(default is to guess)')
@@ -330,5 +331,5 @@ if __name__ == '__main__':
     else:
         search_type = 'start'
 
     else:
         search_type = 'start'
 
-    open_db()
+    open_db(args.database)
     args.func(case_sensitive, search_type, args)
     args.func(case_sensitive, search_type, args)