How to migrate binary field to filestorage

Introduction

By default Tryton stores the data in binary fields in the database, but thanks to the Binary.file_id attribute it is possible to store this data in the FileStore instead. The main goal of doing this is to reduce the size of the database.

Here is a technique you can use to move existing binary data out of the database and into the FileStore.

Configuration

You must first setup the Binary.file_id. Some modules provide a configuration option that can be used to switch on this behavior for their binary fields like the Account Invoice Module.

When changing the configuration, the server must be restarted.

Migration

To move any existing data you can use a trytond-console script which will clean out the database column and add the file to the FileStore.

Here is an example for the invoice report cache that can be pasted into the trytond-console:

from trytond.pool import Pool
from trytond.transaction import Transaction
pool = Pool()
Invoice = pool.get('account.invoice')
transaction = Transaction()
limit = 1000
offset = 0

while True:
    invoices = Invoice.search([('invoice_report_cache', '!=', None)], limit=limit, offset=offset)
    if not invoices:
        break
    for invoice in invoices:
        report = invoice.invoice_report_cache  # backup the data
        invoice.invoice_report_cache = None   # clean the database column
        invoice.save()
        invoice.invoice_report_cache = report  # restore the data
        invoice.save()
        transaction.commit()
    offset += 1
5 Likes