postgresql_extensions/
extensions.rs

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
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
use crate::model::AvailableExtension;
use crate::repository::registry;
use crate::repository::registry::get_repositories;
use crate::{InstalledConfiguration, InstalledExtension, Result};
use postgresql_commands::pg_config::PgConfigBuilder;
use postgresql_commands::postgres::PostgresBuilder;
#[cfg(feature = "tokio")]
use postgresql_commands::AsyncCommandExecutor;
use postgresql_commands::CommandBuilder;
#[cfg(not(feature = "tokio"))]
use postgresql_commands::CommandExecutor;
use postgresql_commands::Settings;
use regex::Regex;
use semver::VersionReq;
use std::path::PathBuf;
use tracing::{debug, instrument};

const CONFIGURATION_FILE: &str = "postgresql_extensions.json";

/// Gets the available extensions.
///
/// # Errors
/// * If an error occurs while getting the extensions.
#[instrument(level = "debug")]
pub async fn get_available_extensions() -> Result<Vec<AvailableExtension>> {
    let mut extensions = Vec::new();
    for repository in get_repositories()? {
        for extension in repository.get_available_extensions().await? {
            extensions.push(extension);
        }
    }
    Ok(extensions)
}

/// Gets the installed extensions.
///
/// # Errors
/// * If an error occurs while getting the installed extensions.
#[instrument(level = "debug", skip(settings))]
pub async fn get_installed_extensions(settings: &impl Settings) -> Result<Vec<InstalledExtension>> {
    let configuration_file = get_configuration_file(settings).await?;
    if !configuration_file.exists() {
        debug!("No configuration file found: {configuration_file:?}");
        return Ok(Vec::new());
    }

    let configuration = InstalledConfiguration::read(configuration_file).await?;
    let extensions = configuration.extensions();
    Ok(extensions.clone())
}

/// Installs the extension with the specified `namespace`, `name`, and `version`.
///
/// # Errors
/// * If an error occurs while installing the extension.
#[instrument(level = "debug", skip(settings))]
pub async fn install(
    settings: &impl Settings,
    namespace: &str,
    name: &str,
    version: &VersionReq,
) -> Result<()> {
    let extensions = get_installed_extensions(settings).await?;
    if extensions
        .iter()
        .any(|extension| extension.namespace() == namespace && extension.name() == name)
    {
        // Attempt to uninstall the extension first
        uninstall(settings, namespace, name).await?;
    };

    let postgresql_version = get_postgresql_version(settings).await?;
    let repository = registry::get(namespace)?;
    let (version, archive) = repository
        .get_archive(postgresql_version.as_str(), name, version)
        .await?;
    let library_dir = get_library_path(settings).await?;
    let extension_dir = get_extension_path(settings).await?;
    let files = repository
        .install(name, library_dir, extension_dir, &archive)
        .await?;

    let configuration_file = get_configuration_file(settings).await?;
    let mut configuration = if configuration_file.exists() {
        InstalledConfiguration::read(&configuration_file).await?
    } else {
        debug!("No configuration file found: {configuration_file:?}; creating new file");
        InstalledConfiguration::default()
    };
    let installed_extension = InstalledExtension::new(namespace, name, version, files);
    configuration.extensions_mut().push(installed_extension);
    configuration.write(configuration_file).await?;
    Ok(())
}

/// Uninstalls the extension with the specified `namespace` and `name`.
///
/// # Errors
/// * If an error occurs while uninstalling the extension.
#[instrument(level = "debug", skip(settings))]
pub async fn uninstall(settings: &impl Settings, namespace: &str, name: &str) -> Result<()> {
    let configuration_file = get_configuration_file(settings).await?;
    if !configuration_file.exists() {
        debug!("No configuration file found: {configuration_file:?}; nothing to uninstall");
        return Ok(());
    }

    let configuration = &mut InstalledConfiguration::read(&configuration_file).await?;
    let mut extensions = Vec::new();
    for extension in configuration.extensions() {
        if extension.namespace() != namespace || extension.name() != name {
            extensions.push(extension.clone());
        }

        for file in extension.files() {
            if file.exists() {
                debug!("Removing file: {file:?}");
                #[cfg(feature = "tokio")]
                tokio::fs::remove_file(file).await?;
                #[cfg(not(feature = "tokio"))]
                std::fs::remove_file(file)?;
            }
        }
    }

    let configuration = InstalledConfiguration::new(extensions);
    configuration.write(configuration_file).await?;

    Ok(())
}

/// Gets the configuration file.
///
/// # Errors
/// * If an error occurs while getting the configuration file.
async fn get_configuration_file(settings: &dyn Settings) -> Result<PathBuf> {
    let shared_path = get_shared_path(settings).await?;
    let file = shared_path.join(CONFIGURATION_FILE);
    Ok(file)
}

/// Gets the library path.
///
/// # Errors
/// * If an error occurs while getting the library path.
async fn get_library_path(settings: &dyn Settings) -> Result<PathBuf> {
    let command = PgConfigBuilder::from(settings).libdir();
    match execute_command(command).await {
        Ok((stdout, _stderr)) => Ok(PathBuf::from(stdout.trim())),
        Err(error) => {
            debug!("Failed to get library path using pg_config: {error:?}");
            let binary_dir = settings.get_binary_dir();
            let install_dir = if let Some(parent) = binary_dir.parent() {
                parent.to_path_buf()
            } else {
                debug!("Failed to get parent directory of binary directory; defaulting to current directory");
                PathBuf::from(".")
            };
            let library_dir = install_dir.join("lib");
            debug!("Using library directory: {library_dir:?}");
            Ok(library_dir)
        }
    }
}

/// Gets the shared path.
///
/// # Errors
/// * If an error occurs while getting the shared path.
async fn get_shared_path(settings: &dyn Settings) -> Result<PathBuf> {
    let command = PgConfigBuilder::from(settings).sharedir();
    match execute_command(command).await {
        Ok((stdout, _stderr)) => Ok(PathBuf::from(stdout.trim())),
        Err(error) => {
            debug!("Failed to get shared path using pg_config: {error:?}");
            let binary_dir = settings.get_binary_dir();
            let install_dir = if let Some(parent) = binary_dir.parent() {
                parent.to_path_buf()
            } else {
                debug!("Failed to get parent directory of binary directory; defaulting to current directory");
                PathBuf::from(".")
            };
            let share_dir = install_dir.join("share");
            debug!("Using share directory: {share_dir:?}");
            Ok(share_dir)
        }
    }
}

/// Gets the extension path.
///
/// # Errors
/// * If an error occurs while getting the extension path.
async fn get_extension_path(settings: &dyn Settings) -> Result<PathBuf> {
    let shared_path = get_shared_path(settings).await?;
    let extension_path = shared_path.join("extension");
    Ok(extension_path)
}

/// Gets the PostgreSQL version.
///
/// # Errors
/// * If an error occurs while getting the PostgreSQL version.
async fn get_postgresql_version(settings: &dyn Settings) -> Result<String> {
    let command = PostgresBuilder::new()
        .program_dir(settings.get_binary_dir())
        .version();
    let (stdout, _stderr) = execute_command(command).await?;
    let re = Regex::new(r"PostgreSQL\)\s(\d+\.\d+)")?;
    let Some(captures) = re.captures(&stdout) else {
        return Err(regex::Error::Syntax(format!(
            "Failed to obtain postgresql version from {stdout}"
        ))
        .into());
    };
    let Some(version) = captures.get(1) else {
        return Err(regex::Error::Syntax(format!(
            "Failed to match postgresql version from {stdout}"
        ))
        .into());
    };
    let version = version.as_str();
    debug!("Obtained PostgreSQL version from postgres command: {version}");
    Ok(version.to_string())
}

#[cfg(not(feature = "tokio"))]
/// Execute a command and return the stdout and stderr as strings.
#[instrument(level = "debug", skip(command_builder), fields(program = ?command_builder.get_program()))]
async fn execute_command<B: CommandBuilder>(
    command_builder: B,
) -> postgresql_commands::Result<(String, String)> {
    let mut command = command_builder.build();
    command.execute()
}

#[cfg(feature = "tokio")]
/// Execute a command and return the stdout and stderr as strings.
#[instrument(level = "debug", skip(command_builder), fields(program = ?command_builder.get_program()))]
async fn execute_command<B: CommandBuilder>(
    command_builder: B,
) -> postgresql_commands::Result<(String, String)> {
    let mut command = command_builder.build_tokio();
    command.execute(None).await
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::TestSettings;

    #[tokio::test]
    async fn test_get_installed_extensions() -> Result<()> {
        let extensions = get_installed_extensions(&TestSettings).await?;
        assert!(extensions.is_empty());
        Ok(())
    }
}