How to implement template file that would reside in database?
You can register a loader, see Drupal\Core\Template\Loader for the implementations that drupal core uses and their parent classes/interfaces.

See also how they're registered in core.services.yml, for example:

twig.loader.filesystem:
    class: Drupal\Core\Template\Loader\FilesystemLoader
    arguments: ['@app.root', '@module_handler', '@theme_handler']
    tags:
      - { name: twig.loader, priority: 100 }


So, it's certainly possible to do it, if it's a good idea is another question ;)