File: SafeConnection.h

package info (click to toggle)
audacity 3.7.7%2Bdfsg-1
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid
  • size: 134,800 kB
  • sloc: cpp: 366,277; ansic: 198,323; lisp: 7,761; sh: 3,414; python: 1,501; xml: 1,385; perl: 854; makefile: 125
file content (83 lines) | stat: -rw-r--r-- 2,357 bytes parent folder | download | duplicates (2)
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
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
/*
 * SPDX-License-Identifier: GPL-2.0-or-later
 * SPDX-FileName: SafeConnection.h
 * SPDX-FileContributor: Dmitry Vedenko
 */

#pragma once

#include <memory>
#include <mutex>

#include "Connection.h"

namespace audacity::sqlite
{
//! A class representing a safe connection to SQLite
/*!
 * This class is a wrapper around the Connection class that provides a thread-safe
 * access to the connection.
 */
class SQLITE_HELPERS_API SafeConnection final :
    public std::enable_shared_from_this<SafeConnection>
{
   struct Tag final
   {
   };

   using MutexType = std::recursive_mutex;

public:
   SafeConnection(Tag, Connection connection);

   static std::shared_ptr<SafeConnection> Open(
      std::string_view path, OpenMode mode = OpenMode::ReadWriteCreate,
      ThreadMode threadMode = ThreadMode::Serialized,
      Error* openError      = nullptr);

   static std::shared_ptr<SafeConnection> Reopen(
      const Connection& connection, OpenMode mode = OpenMode::ReadWriteCreate,
      ThreadMode threadMode = ThreadMode::Serialized,
      Error* openError      = nullptr);

   static std::shared_ptr<SafeConnection> Reopen(
      sqlite3* connection, OpenMode mode = OpenMode::ReadWriteCreate,
      ThreadMode threadMode = ThreadMode::Serialized,
      Error* openError      = nullptr);

   static std::shared_ptr<SafeConnection> Reopen(
      SafeConnection& connection, OpenMode mode = OpenMode::ReadWriteCreate,
      ThreadMode threadMode = ThreadMode::Serialized,
      Error* openError      = nullptr);

   struct SQLITE_HELPERS_API Lock final
   {
      explicit Lock(std::shared_ptr<SafeConnection> connection);
      ~Lock() = default;

      Lock(const Lock&)            = delete;
      Lock& operator=(const Lock&) = delete;
      Lock(Lock&&)                 = default;
      Lock& operator=(Lock&&)      = default;

      Connection* operator->() noexcept;
      const Connection* operator->() const noexcept;

      Connection& operator*() noexcept;
      const Connection& operator*() const noexcept;

      explicit operator bool() const noexcept;
      bool IsValid() const noexcept;

   private:
      std::shared_ptr<SafeConnection> mSafeConnection;
      std::unique_lock<MutexType> mLock;
   };

   Lock Acquire() noexcept;

private:
   Connection mConnection;
   MutexType mConnectionMutex;
};
} // namespace audacity::sqlite