#!/usr/bin/env python3
# -*- coding: utf-8 -*-
#
#*******************************************************************************
#
#  Copyright 2025 RIEGL Laser Measurement Systems
#
#  Licensed under the Apache License, Version 2.0 (the "License");
#  you may not use this file except in compliance with the License.
#  You may obtain a copy of the License at
#
#      http://www.apache.org/licenses/LICENSE-2.0
#
#  Unless required by applicable law or agreed to in writing, software
#  distributed under the License is distributed on an "AS IS" BASIS,
#  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
#  See the License for the specific language governing permissions and
#  limitations under the License.
#
#  SPDX-License-Identifier: Apache-2.0
#
#*******************************************************************************
#
"""
rdb-example-09-cleanup-database.py

This example shows how to open an existing database and how to dismiss
the database history, i.e. to delete all transactions except the first
(database creation) and the current transaction (last committed or
restored).

Afterwards we vacuum the database which reorganizes the data blocks in
the database file so that there are no (or as few as possible) unused
blocks (gaps).

Please note, that both database operations cannot be reverted!
"""

import riegl.rdb

# Access existing database
with riegl.rdb.rdb_open("pointcloud.rdbx") as rdb:
    # First we delete the history (see comments in header)
    rdb.management.finalize()

    #____________________________________________________________________#
    #                                                                    #
    #   At this point, there might be many unused data blocks in the     #
    #   database file which were occupied by the transactions we have    #
    #   just deleted. These data blocks will be re-used when we create   #
    #   new transactions to insert, update or remove points or make      #
    #   other changes to e.g. meta data items.                           #
    #   So the following vacuum step is optional but might be a good     #
    #   idea before archiving or transferring the database file.         #
    #____________________________________________________________________#
    #                                                                    #

    # Now we reorganize and shrink the database file:
    rdb.management.vacuum(
        # As this might be a lengthy operation, vacuum() accepts
        # an optional callback function to notify the user about
        # the (coarse) progress. However there is no function to
        # cancel this process.
        lambda progress: print("progress:", progress)
    )
