cargo-pgx 0.5.0-beta.1

Cargo subcommand for 'pgx' to make Postgres extension development easy
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
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
/*
Portions Copyright 2019-2021 ZomboDB, LLC.
Portions Copyright 2021-2022 Technology Concepts & Design, Inc. <support@tcdi.com>

All rights reserved.

Use of this source code is governed by the MIT license that can be found in the LICENSE file.
*/

use crate::{
    command::get::{find_control_file, get_property},
    CommandExecute,
};
use cargo_toml::Manifest;
use eyre::{eyre, WrapErr};
use owo_colors::OwoColorize;
use pgx_pg_config::{get_target_dir, PgConfig};
use std::{
    io::BufReader,
    path::{Path, PathBuf},
    process::{Command, Stdio},
};

/// Install the extension from the current crate to the Postgres specified by whatever `pg_config` is currently on your $PATH
#[derive(clap::Args, Debug)]
#[clap(author)]
pub(crate) struct Install {
    /// Package to build (see `cargo help pkgid`)
    #[clap(long, short)]
    package: Option<String>,
    /// Path to Cargo.toml
    #[clap(long, parse(from_os_str))]
    manifest_path: Option<PathBuf>,
    /// Compile for release mode (default is debug)
    #[clap(env = "PROFILE", long, short)]
    release: bool,
    /// Build in test mode (for `cargo pgx test`)
    #[clap(long)]
    test: bool,
    /// The `pg_config` path (default is first in $PATH)
    #[clap(long, short = 'c')]
    pg_config: Option<String>,
    #[clap(flatten)]
    features: clap_cargo::Features,
    #[clap(from_global, parse(from_occurrences))]
    verbose: usize,
}

impl CommandExecute for Install {
    #[tracing::instrument(level = "error", skip(self))]
    fn execute(self) -> eyre::Result<()> {
        let metadata = crate::metadata::metadata(&self.features, self.manifest_path.as_ref())
            .wrap_err("couldn't get cargo metadata")?;
        crate::metadata::validate(&metadata)?;
        let package_manifest_path =
            crate::manifest::manifest_path(&metadata, self.package.as_ref())
                .wrap_err("Couldn't get manifest path")?;
        let package_manifest =
            Manifest::from_path(&package_manifest_path).wrap_err("Couldn't parse manifest")?;

        let pg_config = match self.pg_config {
            None => PgConfig::from_path(),
            Some(config) => PgConfig::new(PathBuf::from(config)),
        };
        let pg_version = format!("pg{}", pg_config.major_version()?);

        let features =
            crate::manifest::features_for_version(self.features, &package_manifest, &pg_version);

        install_extension(
            self.manifest_path.as_ref(),
            self.package.as_ref(),
            package_manifest_path,
            &pg_config,
            self.release,
            self.test,
            None,
            &features,
        )
    }
}

#[tracing::instrument(skip_all, fields(
    pg_version = %pg_config.version()?,
    release = is_release,
    test = is_test,
    base_directory = tracing::field::Empty,
    features = ?features.features,
))]
pub(crate) fn install_extension(
    user_manifest_path: Option<impl AsRef<Path>>,
    user_package: Option<&String>,
    package_manifest_path: impl AsRef<Path>,
    pg_config: &PgConfig,
    is_release: bool,
    is_test: bool,
    base_directory: Option<PathBuf>,
    features: &clap_cargo::Features,
) -> eyre::Result<()> {
    let base_directory = base_directory.unwrap_or("/".into());
    tracing::Span::current().record(
        "base_directory",
        &tracing::field::display(&base_directory.display()),
    );

    let manifest = Manifest::from_path(&package_manifest_path)?;
    let (control_file, extname) = find_control_file(&package_manifest_path)?;

    if get_property(&package_manifest_path, "relocatable")? != Some("false".into()) {
        return Err(eyre!(
            "{}:  The `relocatable` property MUST be `false`.  Please update your .control file.",
            control_file.display()
        ));
    }

    let versioned_so = get_property(&package_manifest_path, "module_pathname")?.is_none();

    let build_command_output = build_extension(
        user_manifest_path.as_ref(),
        user_package,
        is_release,
        &features,
    )?;
    let build_command_bytes = build_command_output.stdout;
    let build_command_reader = BufReader::new(build_command_bytes.as_slice());
    let build_command_stream = cargo_metadata::Message::parse_stream(build_command_reader);
    let build_command_messages =
        build_command_stream.collect::<Result<Vec<_>, std::io::Error>>()?;

    println!("{} extension", "  Installing".bold().green(),);
    let pkgdir = make_relative(pg_config.pkglibdir()?);
    let extdir = make_relative(pg_config.extension_dir()?);
    let shlibpath = find_library_file(&manifest, &build_command_messages)?;

    {
        let mut dest = base_directory.clone();
        dest.push(&extdir);
        dest.push(
            &control_file
                .file_name()
                .ok_or_else(|| eyre!("Could not get filename for `{}`", control_file.display()))?,
        );
        copy_file(
            &control_file,
            &dest,
            "control file",
            true,
            &package_manifest_path,
        )?;
    }

    {
        let mut dest = base_directory.clone();
        dest.push(&pkgdir);
        let so_name = if versioned_so {
            let extver = get_version(&package_manifest_path)?;
            // note: versioned so-name format must agree with pgx-utils
            format!("{}-{}", &extname, &extver)
        } else {
            extname.clone()
        };
        dest.push(format!("{}.so", so_name));

        if cfg!(target_os = "macos") {
            // Remove the existing .so if present. This is a workaround for an
            // issue highlighted by the following apple documentation:
            // https://developer.apple.com/documentation/security/updating_mac_software
            if dest.exists() {
                std::fs::remove_file(&dest).wrap_err_with(|| {
                    format!("unable to remove existing file {}", dest.display())
                })?;
            }
        }
        copy_file(
            &shlibpath,
            &dest,
            "shared library",
            false,
            &package_manifest_path,
        )?;
    }

    copy_sql_files(
        user_manifest_path,
        user_package,
        &package_manifest_path,
        pg_config,
        is_release,
        is_test,
        features,
        &extdir,
        &base_directory,
        true,
    )?;

    println!("{} installing {}", "    Finished".bold().green(), extname);
    Ok(())
}

fn copy_file(
    src: &PathBuf,
    dest: &PathBuf,
    msg: &str,
    do_filter: bool,
    package_manifest_path: impl AsRef<Path>,
) -> eyre::Result<()> {
    if !dest.parent().unwrap().exists() {
        std::fs::create_dir_all(dest.parent().unwrap()).wrap_err_with(|| {
            format!(
                "failed to create destination directory {}",
                dest.parent().unwrap().display()
            )
        })?;
    }

    println!(
        "{} {} to {}",
        "     Copying".bold().green(),
        msg,
        format_display_path(&dest)?.cyan()
    );

    if do_filter {
        // we want to filter the contents of the file we're to copy
        let input = std::fs::read_to_string(&src)
            .wrap_err_with(|| format!("failed to read `{}`", src.display()))?;
        let input = filter_contents(package_manifest_path, input)?;

        std::fs::write(&dest, &input).wrap_err_with(|| {
            format!("failed writing `{}` to `{}`", src.display(), dest.display())
        })?;
    } else {
        std::fs::copy(&src, &dest).wrap_err_with(|| {
            format!("failed copying `{}` to `{}`", src.display(), dest.display())
        })?;
    }

    Ok(())
}

pub(crate) fn build_extension(
    user_manifest_path: Option<impl AsRef<Path>>,
    user_package: Option<&String>,
    is_release: bool,
    features: &clap_cargo::Features,
) -> eyre::Result<std::process::Output> {
    let flags = std::env::var("PGX_BUILD_FLAGS").unwrap_or_default();

    let mut command = Command::new("cargo");
    command.arg("build");

    if let Some(user_manifest_path) = user_manifest_path {
        command.arg("--manifest-path");
        command.arg(user_manifest_path.as_ref());
    }

    if let Some(user_package) = user_package {
        command.arg("--package");
        command.arg(user_package);
    }

    if is_release {
        command.arg("--release");
    }

    let features_arg = features.features.join(" ");
    if !features_arg.trim().is_empty() {
        command.arg("--features");
        command.arg(&features_arg);
    }

    if features.no_default_features {
        command.arg("--no-default-features");
    }

    if features.all_features {
        command.arg("--all-features");
    }

    command.arg("--message-format=json-render-diagnostics");

    for arg in flags.split_ascii_whitespace() {
        command.arg(arg);
    }

    let command = command.stderr(Stdio::inherit());
    let command_str = format!("{:?}", command);
    println!(
        "{} extension with features {}",
        "    Building".bold().green(),
        features_arg.cyan()
    );
    println!(
        "{} command {}",
        "     Running".bold().green(),
        command_str.cyan()
    );
    let cargo_output = command
        .output()
        .wrap_err_with(|| format!("failed to spawn cargo: {}", command_str))?;
    if !cargo_output.status.success() {
        // We explicitly do not want to return a spantraced error here.
        std::process::exit(1)
    } else {
        Ok(cargo_output)
    }
}

fn get_target_sql_file(
    manifest_path: impl AsRef<Path>,
    extdir: &PathBuf,
    base_directory: &PathBuf,
) -> eyre::Result<PathBuf> {
    let mut dest = base_directory.clone();
    dest.push(extdir);

    let (_, extname) = find_control_file(&manifest_path)?;
    let version = get_version(&manifest_path)?;
    dest.push(format!("{}--{}.sql", extname, version));

    Ok(dest)
}

fn copy_sql_files(
    user_manifest_path: Option<impl AsRef<Path>>,
    user_package: Option<&String>,
    package_manifest_path: impl AsRef<Path>,
    pg_config: &PgConfig,
    is_release: bool,
    is_test: bool,
    features: &clap_cargo::Features,
    extdir: &PathBuf,
    base_directory: &PathBuf,
    skip_build: bool,
) -> eyre::Result<()> {
    let dest = get_target_sql_file(&package_manifest_path, extdir, base_directory)?;
    let (_, extname) = find_control_file(&package_manifest_path)?;

    crate::command::schema::generate_schema(
        pg_config,
        user_manifest_path,
        user_package,
        &package_manifest_path,
        is_release,
        is_test,
        features,
        Some(&dest),
        Option::<String>::None,
        None,
        skip_build,
    )?;

    // now copy all the version upgrade files too
    if let Ok(dir) = std::fs::read_dir("sql/") {
        for sql in dir {
            if let Ok(sql) = sql {
                let filename = sql.file_name().into_string().unwrap();

                if filename.starts_with(&format!("{}--", extname)) && filename.ends_with(".sql") {
                    let mut dest = base_directory.clone();
                    dest.push(extdir);
                    dest.push(filename);

                    copy_file(
                        &sql.path(),
                        &dest,
                        "extension schema upgrade file",
                        true,
                        &package_manifest_path,
                    )?;
                }
            }
        }
    }
    Ok(())
}

#[tracing::instrument(level = "error", skip_all)]
pub(crate) fn find_library_file(
    manifest: &cargo_toml::Manifest,
    build_command_messages: &Vec<cargo_metadata::Message>,
) -> eyre::Result<PathBuf> {
    let crate_name = if let Some(ref package) = manifest.package {
        &package.name
    } else {
        return Err(eyre!("Could not get crate name from manifest."));
    };

    let mut library_file = None;
    for message in build_command_messages {
        match message {
            cargo_metadata::Message::CompilerArtifact(artifact) => {
                if artifact.target.name != *crate_name {
                    continue;
                }
                for filename in &artifact.filenames {
                    let so_extension = if cfg!(target_os = "macos") {
                        "dylib"
                    } else {
                        "so"
                    };
                    if filename.extension() == Some(so_extension) {
                        library_file = Some(filename.to_string());
                        break;
                    }
                }
            }
            cargo_metadata::Message::CompilerMessage(_)
            | cargo_metadata::Message::BuildScriptExecuted(_)
            | cargo_metadata::Message::BuildFinished(_)
            | _ => (),
        }
    }
    let library_file =
        library_file.ok_or(eyre!("Could not get shared object file from Cargo output."))?;
    let library_file_path = PathBuf::from(library_file);

    Ok(library_file_path)
}

pub(crate) fn get_version(manifest_path: impl AsRef<Path>) -> eyre::Result<String> {
    match get_property(&manifest_path, "default_version")? {
        Some(v) => {
            if v == "@CARGO_VERSION@" {
                let metadata = crate::metadata::metadata(&Default::default(), Some(&manifest_path))
                    .wrap_err("couldn't get cargo metadata")?;
                crate::metadata::validate(&metadata)?;
                let manifest_path = crate::manifest::manifest_path(&metadata, None)
                    .wrap_err("Couldn't get manifest path")?;
                let manifest = Manifest::from_path(&manifest_path)
                    .wrap_err("Couldn't parse manifest")?;

                let version = manifest.package.ok_or(eyre!("no `[package]` section found"))?.version;
                Ok(version.to_string())
            } else {
                Ok(v)
            }
        },
        None => Err(eyre!("cannot determine extension version number.  Is the `default_version` property declared in the control file?")),
    }
}

fn get_git_hash(manifest_path: impl AsRef<Path>) -> eyre::Result<String> {
    match get_property(manifest_path, "git_hash")? {
        Some(hash) => Ok(hash),
        None => Err(eyre!(
            "unable to determine git hash.  Is git installed and is this project a git repository?"
        )),
    }
}

fn make_relative(path: PathBuf) -> PathBuf {
    if path.is_relative() {
        return path;
    }
    let mut relative = PathBuf::new();
    let mut components = path.components();
    components.next(); // skip the root
    while let Some(part) = components.next() {
        relative.push(part)
    }
    relative
}

pub(crate) fn format_display_path(path: impl AsRef<Path>) -> eyre::Result<String> {
    let path = path.as_ref();
    let out = path
        .strip_prefix(get_target_dir()?.parent().unwrap())
        .unwrap_or(&path)
        .display()
        .to_string();
    Ok(out)
}

fn filter_contents(manifest_path: impl AsRef<Path>, mut input: String) -> eyre::Result<String> {
    if input.contains("@GIT_HASH@") {
        // avoid doing this if we don't actually have the token
        // the project might not be a git repo so running `git`
        // would fail
        input = input.replace("@GIT_HASH@", &get_git_hash(&manifest_path)?);
    }

    input = input.replace("@CARGO_VERSION@", &get_version(&manifest_path)?);

    Ok(input)
}