Make `tcbdboptimizeimpl` more safe

I believe the `tcbdboptimizeimpl` procedure, as-is, can happily replace a source database with a partial clone when something goes wrong while copying data from source to destination. If `tcbdbputdup` fails in the copy loop, `err` will be `true`, but despite this, the source would be unlinked and the temporary (partial) DB renamed to the source.

Next to this, in the above scenario, the new file wouldn't be opened, the (unlinked) source would be kept as the target file, and any modificatoins on it would be lost whenever the database is closed, leaving the user with nothing but the partially-constructed 'optimized' version.

Next to fixing the issue described above, this change also adds an explicit `sync` of the temporary database before replacing the source.