File: Init.hs

package info (click to toggle)
git-annex 10.20230126-3
  • links: PTS, VCS
  • area: main
  • in suites: bookworm
  • size: 69,344 kB
  • sloc: haskell: 74,654; javascript: 9,103; sh: 1,304; makefile: 203; perl: 136; ansic: 44
file content (65 lines) | stat: -rw-r--r-- 2,113 bytes parent folder | download
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
{- Persistent sqlite database initialization
 -
 - Copyright 2015-2020 Joey Hess <id@joeyh.name>
 -
 - Licensed under the GNU AGPL version 3 or higher.
 -}

{-# LANGUAGE OverloadedStrings #-}

module Database.Init where

import Annex.Common
import qualified Annex
import Annex.Perms
import Utility.FileMode
import Utility.Directory.Create
import qualified Utility.RawFilePath as R

import Database.Persist.Sqlite
import Lens.Micro
import qualified Data.Text as T
import qualified System.FilePath.ByteString as P

{- Ensures that the database is freshly initialized. Deletes any
 - existing database. Pass the migration action for the database.
 -
 - The permissions of the database are set based on the
 - core.sharedRepository setting. Setting these permissions on the main db
 - file causes Sqlite to always use the same permissions for additional
 - files it writes later on
 -}
initDb :: P.RawFilePath -> SqlPersistM () -> Annex ()
initDb db migration = do
	let dbdir = P.takeDirectory db
	let tmpdbdir = dbdir <> ".tmp"
	let tmpdb = tmpdbdir P.</> "db"
	let tdb = T.pack (fromRawFilePath tmpdb)
	gc <- Annex.getGitConfig
	top <- parentDir <$> fromRepo gitAnnexDir
	let tops = case annexDbDir gc of
		Just topdbdir -> [top, parentDir (parentDir topdbdir)]
		Nothing -> [top]
	liftIO $ do
		createDirectoryUnder tops tmpdbdir
		runSqliteInfo (enableWAL tdb) migration
	setAnnexDirPerm tmpdbdir
	-- Work around sqlite bug that prevents it from honoring
	-- less restrictive umasks.
	liftIO $ R.setFileMode tmpdb =<< defaultFileMode
	setAnnexFilePerm tmpdb
	liftIO $ do
		void $ tryIO $ removeDirectoryRecursive (fromRawFilePath dbdir)
		R.rename tmpdbdir dbdir

{- Make sure that the database uses WAL mode, to prevent readers
 - from blocking writers, and prevent a writer from blocking readers.
 -
 - This is the default in recent persistent-sqlite versions, but 
 - force it on just in case. 
 -
 - Note that once WAL mode is enabled, it will persist whenever the
 - database is opened. -}
enableWAL :: T.Text -> SqliteConnectionInfo
enableWAL db = over walEnabled (const True) $ 
	mkSqliteConnectionInfo db