This is really prune to errors due to concurrency, race conditions, etc. There are several ways to do this "The Right Way":
- you can just use LUKS and mount the db storage on top of it. - you can just use built-in encryption at rest [1] - etc.
[1] https://mariadb.com/kb/en/mariadb/data-at-rest-encryption/