Beispiel #1
0
 def _query_with_database_and_expression(
     self,
     expression: str,
 ) -> ClientQuery:
     query = DatabaseQuery(self, SEARCH)
     query.utf(expression)
     return query
Beispiel #2
0
    def _unlock_records(
        self,
        records: 'List[int]',
        database: 'Optional[str]' = None,
    ):
        database = self._get_database(database)
        query = DatabaseQuery(self, UNLOCK_RECORDS, database)
        for mfn in records:
            query.add(mfn)

        return query
Beispiel #3
0
    def read_terms(self,
                   parameters: 'Union[TermParameters, str, Tuple[str, int]]') \
            -> 'List[TermInfo]':
        """
        Получение термов поискового словаря.

        :param parameters: Параметры термов или терм
            или кортеж "терм, количество"
        :return: Список термов
        """
        if not self.check_connection():
            return []

        if isinstance(parameters, tuple):
            parameters2 = TermParameters(parameters[0])
            parameters2.number = parameters[1]
            parameters = parameters2

        if isinstance(parameters, str):
            parameters = TermParameters(parameters)
            parameters.number = 10

        assert isinstance(parameters, TermParameters)

        command = READ_TERMS_REVERSE if parameters.reverse else READ_TERMS
        query = DatabaseQuery(self, command, parameters.database)
        query.utf(parameters.start)
        query.add(parameters.number)
        query.ansi(parameters.format)

        with self.execute(query) as response:
            response.check_return_code(READ_TERMS_CODES)
            lines = response.utf_remaining_lines()
            result = TermInfo.parse(lines)
            return result
Beispiel #4
0
    def read_postings(self,
                      parameters: 'Union[PostingParameters, str]',
                      fmt: 'Optional[str]' = None) -> 'List[TermPosting]':
        """
        Считывание постингов для указанных термов из поискового словаря.

        :param parameters: Параметры постингов или терм
        :param fmt: Опциональный формат
        :return: Список постингов
        """
        if not self.check_connection():
            return []

        if isinstance(parameters, str):
            parameters = PostingParameters(parameters)
            parameters.fmt = fmt

        query = DatabaseQuery(self, READ_POSTINGS, parameters.database)
        query.add(parameters.number)
        query.add(parameters.first).ansi(parameters.fmt)
        for term in parameters.terms:
            query.utf(term)
        with self.execute(query) as response:
            result: 'List[TermPosting]' = []
            if not response.check_return_code(READ_TERMS_CODES):
                return result

            while True:
                line = response.utf()
                if not line:
                    break
                posting = TermPosting()
                posting.parse(line)
                result.append(posting)
            return result
Beispiel #5
0
    def actualize_record(self,
                         mfn: int,
                         database: 'Optional[str]' = None) -> bool:
        """
        Актуализация записи с указанным MFN.

        :param mfn: MFN записи.
        :param database: База данных.
        :return: Признак успешности операции.
        """
        if not self.check_connection():
            return False

        assert isinstance(mfn, int)

        query = DatabaseQuery(self, ACTUALIZE_RECORD, database)
        query.add(mfn)
        return self._execute_with_bool_result(query)
Beispiel #6
0
    def create_database(self,
                        database: 'Optional[str]' = None,
                        description: 'Optional[str]' = None,
                        reader_access: bool = True) -> bool:
        """
        Создание базы данных.

        :param database: Имя создаваемой базы.
        :param description: Описание в свободной форме.
        :param reader_access: Читатель будет иметь доступ?
        :return: Признак успешности операции.
        """
        if not self.check_connection():
            return False

        description = description or ''
        assert isinstance(description, str)

        query = DatabaseQuery(self, CREATE_DATABASE, database)
        query.ansi(description).add(int(reader_access))
        return self._execute_with_bool_result(query)
Beispiel #7
0
    def read_record_postings(self, mfn: int, prefix: str) \
            -> 'List[TermPosting]':
        """
        Получение постингов для указанных записи и префикса.

        :param mfn: MFN записи.
        :param prefix: Префикс в виде "A=$".
        :return: Список постингов.
        """
        if not self.check_connection():
            return []

        assert mfn > 0

        query = DatabaseQuery(self, 'V')
        query.add(mfn)
        query.utf(prefix)

        lines = self._some_one_method(query)
        result = []
        for line in lines:
            one: TermPosting = TermPosting()
            one.parse(line)
            result.append(one)
        return result
Beispiel #8
0
    async def get_max_mfn_async(self, database: 'Optional[str]' = None) -> int:
        """
        Асинхронное получение максимального MFN.

        :param database: База данных.
        :return: MFN, который будет присвоен следующей записи.
        """
        query = DatabaseQuery(self, GET_MAX_MFN, database)
        response = await self.execute_async(query)
        response.check_return_code()
        result = response.return_code
        response.close()
        return result
Beispiel #9
0
    def _read_record_begin(self, mfn: int, version: int = 0) -> ClientQuery:
        assert isinstance(mfn, int)

        query = DatabaseQuery(self, READ_RECORD)
        query.add(mfn)
        if version:
            query.add(version)
        return query
Beispiel #10
0
    def _format_record_begin(self, script, record) -> ClientQuery:
        if not record:
            raise ValueError()

        assert isinstance(script, str)
        assert isinstance(record, (Record, int))

        query = DatabaseQuery(self, FORMAT_RECORD)
        query.format(script)

        if isinstance(record, int):
            query.add(1).add(record)
        else:
            query.add(-2).utf(IRBIS_DELIMITER.join(record.encode()))

        return query
Beispiel #11
0
    def _write_record_begin(
        self,
        record: 'AbstractRecord',
        lock: bool,
        actualize: bool,
        record_type: 'Type[AbstractRecord]',
    ) -> 'Tuple[ClientQuery, str]':
        if not record:
            raise ValueError()

        assert isinstance(record, record_type)

        database = self._get_database(record.database)
        query = DatabaseQuery(self, UPDATE_RECORD, record.database)
        query.add(int(lock))
        query.add(int(actualize))
        query.utf(IRBIS_DELIMITER.join(record.encode()))
        return query, database
Beispiel #12
0
    def format_records(self, script: str, records: 'List[int]') -> 'List[str]':
        """
        Форматирование группы записей по MFN.

        :param script: Текст формата
        :param records: Список MFN
        :return: Список строк
        """
        if not self.check_connection():
            return []

        if not records:
            return []

        script = script or throw_value_error()

        assert isinstance(script, str)
        assert isinstance(records, list)

        if not script:
            return [''] * len(records)

        if len(records) > MAX_POSTINGS:
            raise IrbisError()

        query = DatabaseQuery(self, FORMAT_RECORD)
        query.format(script)

        query.add(len(records))
        for mfn in records:
            query.add(mfn)

        lines = self._some_one_method(query)
        result = []
        for line in lines:
            result.append(line.split('#', 1)[1])
        return result
Beispiel #13
0
    def print_table(self, definition: TableDefinition) -> str:
        """
        Расформатирование таблицы.

        :param definition: Определение таблицы
        :return: Результат расформатирования
        """
        if not self.check_connection():
            return ''

        query = DatabaseQuery(self, PRINT, definition.database)
        query.ansi(definition.table)
        query.ansi('')  # instead of the headers
        query.ansi(definition.mode).utf(definition.search)
        query.add(definition.min_mfn).add(definition.max_mfn)
        query.utf(definition.sequential)
        query.ansi('')  # instead of the MFN list
        with self.execute(query) as response:
            result = response.utf_remaining_text()
            return result