upstream-rs 2.6.0

Fetch package updates directly from the source.
Documentation
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
use std::fs;
use std::path::Path;

use anyhow::{Context, Result, anyhow};
use rusqlite::{Connection, OptionalExtension, Transaction, params};

use crate::models::upstream::Package;

use super::mapping::{
    PACKAGE_COLUMNS, bool_to_db, enum_to_db, optional_path_to_db, row_to_package,
};
use super::patterns::{load_patterns, replace_patterns};

#[derive(Debug)]
pub(crate) struct PackageConnection {
    conn: Connection,
}

impl PackageConnection {
    pub fn open(path: &Path) -> Result<Self> {
        if let Some(parent) = path.parent() {
            fs::create_dir_all(parent).with_context(|| {
                format!(
                    "Failed to create package database directory '{}'",
                    parent.display()
                )
            })?;
        }

        let conn = Connection::open(path)
            .with_context(|| format!("Failed to open package database '{}'", path.display()))?;
        Self::from_connection(conn)
    }

    #[cfg(test)]
    pub fn open_in_memory() -> Result<Self> {
        Self::from_connection(
            Connection::open_in_memory().context("Failed to open package database in memory")?,
        )
    }

    fn from_connection(conn: Connection) -> Result<Self> {
        let mut db = Self { conn };
        db.initialize()?;
        Ok(db)
    }

    pub fn schema_version(&self) -> Result<u32> {
        super::schema_version(&self.conn)
    }

    pub fn package_exists(&self, name: &str) -> Result<bool> {
        self.conn
            .query_row(
                "SELECT EXISTS(SELECT 1 FROM packages WHERE name = ?1)",
                [name],
                |row| row.get::<_, bool>(0),
            )
            .with_context(|| format!("Failed to check package '{}'", name))
    }

    pub fn get_package(&self, name: &str) -> Result<Option<Package>> {
        let package = self
            .conn
            .query_row(&select_package_by_name_query(), [name], row_to_package)
            .optional()
            .with_context(|| format!("Failed to load package '{}'", name))?;

        match package {
            Some(mut package) => {
                load_patterns(&self.conn, &mut package)?;
                Ok(Some(package))
            }
            None => Ok(None),
        }
    }

    pub fn list_packages(&self) -> Result<Vec<Package>> {
        let mut stmt = self
            .conn
            .prepare(&list_packages_query())
            .context("Failed to prepare package list query")?;

        let packages = stmt
            .query_map([], row_to_package)
            .context("Failed to list packages")?
            .collect::<rusqlite::Result<Vec<_>>>()
            .context("Failed to decode package rows")?;
        drop(stmt);

        packages
            .into_iter()
            .map(|mut package| {
                load_patterns(&self.conn, &mut package)?;
                Ok(package)
            })
            .collect()
    }

    pub fn upsert_package(&mut self, package: &Package) -> Result<()> {
        let tx = self
            .conn
            .transaction()
            .context("Failed to start package upsert transaction")?;
        write_package(&tx, package)?;
        tx.commit()
            .with_context(|| format!("Failed to commit package '{}'", package.name))
    }

    pub fn replace_all_packages(&mut self, packages: &[Package]) -> Result<()> {
        let tx = self
            .conn
            .transaction()
            .context("Failed to start package replacement transaction")?;
        tx.execute("DELETE FROM packages", [])
            .context("Failed to clear package database")?;
        for package in packages {
            write_package(&tx, package)?;
        }
        tx.commit()
            .context("Failed to commit package replacement transaction")
    }

    pub fn remove_package(&mut self, name: &str) -> Result<bool> {
        let affected = self
            .conn
            .execute("DELETE FROM packages WHERE name = ?1", [name])
            .with_context(|| format!("Failed to remove package '{}'", name))?;
        Ok(affected > 0)
    }

    pub fn update_package<F>(&mut self, name: &str, update: F) -> Result<()>
    where
        F: FnOnce(&mut Package) -> Result<()>,
    {
        let mut package = self
            .get_package(name)?
            .ok_or_else(|| anyhow!("Package '{}' not found", name))?;
        update(&mut package)?;

        let tx = self
            .conn
            .transaction()
            .context("Failed to start package update transaction")?;
        if package.name != name {
            tx.execute("DELETE FROM packages WHERE name = ?1", [name])
                .with_context(|| format!("Failed to remove renamed package '{}'", name))?;
        }
        write_package(&tx, &package)?;
        tx.commit()
            .with_context(|| format!("Failed to commit package '{}'", package.name))
    }

    fn initialize(&mut self) -> Result<()> {
        super::initialize(&self.conn)
    }
}

fn select_package_by_name_query() -> String {
    format!("SELECT {PACKAGE_COLUMNS} FROM packages WHERE name = ?1")
}

fn list_packages_query() -> String {
    format!("SELECT {PACKAGE_COLUMNS} FROM packages ORDER BY lower(name), name")
}

fn write_package(tx: &Transaction<'_>, package: &Package) -> Result<()> {
    tx.execute(
        "INSERT INTO packages (
            name,
            repo_slug,
            filetype,
            version_major,
            version_minor,
            version_patch,
            version_is_prerelease,
            channel,
            provider,
            base_url,
            install_type,
            build_branch,
            build_commit,
            is_pinned,
            icon_path,
            install_path,
            exec_path,
            last_upgraded
        ) VALUES (
            ?1, ?2, ?3, ?4, ?5, ?6, ?7, ?8, ?9, ?10, ?11, ?12, ?13, ?14, ?15, ?16, ?17, ?18
        )
        ON CONFLICT(name) DO UPDATE SET
            repo_slug = excluded.repo_slug,
            filetype = excluded.filetype,
            version_major = excluded.version_major,
            version_minor = excluded.version_minor,
            version_patch = excluded.version_patch,
            version_is_prerelease = excluded.version_is_prerelease,
            channel = excluded.channel,
            provider = excluded.provider,
            base_url = excluded.base_url,
            install_type = excluded.install_type,
            build_branch = excluded.build_branch,
            build_commit = excluded.build_commit,
            is_pinned = excluded.is_pinned,
            icon_path = excluded.icon_path,
            install_path = excluded.install_path,
            exec_path = excluded.exec_path,
            last_upgraded = excluded.last_upgraded",
        params![
            package.name,
            package.repo_slug,
            enum_to_db(&package.filetype)?,
            package.version.major,
            package.version.minor,
            package.version.patch,
            bool_to_db(package.version.is_prerelease),
            enum_to_db(&package.channel)?,
            enum_to_db(&package.provider)?,
            package.base_url,
            enum_to_db(&package.install_type)?,
            package.build_branch,
            package.build_commit,
            bool_to_db(package.is_pinned),
            optional_path_to_db(&package.icon_path)?,
            optional_path_to_db(&package.install_path)?,
            optional_path_to_db(&package.exec_path)?,
            package.last_upgraded.to_rfc3339(),
        ],
    )
    .with_context(|| format!("Failed to write package '{}'", package.name))?;

    replace_patterns(tx, package)
}

#[cfg(test)]
mod tests {
    use super::PackageConnection;
    use crate::models::{
        common::{
            Version,
            enums::{Channel, Filetype, Provider},
        },
        upstream::{InstallType, Package},
    };
    use crate::providers::pattern_matcher::PatternTable;
    use crate::storage::database::PACKAGE_DB_SCHEMA_VERSION;
    use chrono::{TimeZone, Utc};
    use std::path::PathBuf;

    fn test_package(name: &str) -> Package {
        let mut package = Package::with_defaults(
            name.to_string(),
            format!("owner/{name}"),
            Filetype::Archive,
            None,
            None,
            Channel::Preview,
            Provider::Github,
            Some("https://api.github.com".to_string()),
        );
        package.version = Version::new(1, 2, 3, true);
        package.install_type = InstallType::Build;
        package.build_branch = Some("main".to_string());
        package.build_commit = Some("abcdef".to_string());
        package.is_pinned = true;
        package.match_pattern = PatternTable::from_patterns(["linux", "x86_64"]);
        package.exclude_pattern = PatternTable::from_patterns(["debug", "symbols"]);
        package.icon_path = Some(PathBuf::from("/icons/tool.png"));
        package.install_path = Some(PathBuf::from("/packages/tool"));
        package.exec_path = Some(PathBuf::from("/packages/tool/bin/tool"));
        package.last_upgraded = Utc
            .with_ymd_and_hms(2026, 6, 21, 12, 30, 0)
            .single()
            .expect("valid timestamp");
        package
    }

    #[test]
    fn open_in_memory_initializes_schema() {
        let db = PackageConnection::open_in_memory().expect("open db");

        assert_eq!(
            db.schema_version().expect("schema version"),
            PACKAGE_DB_SCHEMA_VERSION
        );
        assert!(!db.package_exists("missing").expect("exists check"));
    }

    #[test]
    fn upsert_and_get_package_round_trips_all_fields() {
        let mut db = PackageConnection::open_in_memory().expect("open db");
        let package = test_package("tool");

        db.upsert_package(&package).expect("upsert package");
        let stored = db
            .get_package("tool")
            .expect("load package")
            .expect("package exists");

        assert_eq!(stored.name, package.name);
        assert_eq!(stored.repo_slug, package.repo_slug);
        assert_eq!(stored.filetype, package.filetype);
        assert_eq!(stored.version, package.version);
        assert_eq!(stored.channel, package.channel);
        assert_eq!(stored.provider, package.provider);
        assert_eq!(stored.base_url, package.base_url);
        assert_eq!(stored.install_type, package.install_type);
        assert_eq!(stored.build_branch, package.build_branch);
        assert_eq!(stored.build_commit, package.build_commit);
        assert_eq!(stored.is_pinned, package.is_pinned);
        assert_eq!(
            stored.match_pattern.as_slice(),
            package.match_pattern.as_slice()
        );
        assert_eq!(
            stored.exclude_pattern.as_slice(),
            package.exclude_pattern.as_slice()
        );
        assert_eq!(stored.icon_path, package.icon_path);
        assert_eq!(stored.install_path, package.install_path);
        assert_eq!(stored.exec_path, package.exec_path);
        assert_eq!(stored.last_upgraded, package.last_upgraded);
    }

    #[test]
    fn upsert_replaces_package_and_patterns() {
        let mut db = PackageConnection::open_in_memory().expect("open db");
        let mut package = test_package("tool");
        db.upsert_package(&package).expect("upsert package");

        package.version = Version::new(2, 0, 0, false);
        package.match_pattern = PatternTable::from_patterns(["aarch64"]);
        package.exclude_pattern = PatternTable::empty();
        db.upsert_package(&package).expect("replace package");

        let stored = db
            .get_package("tool")
            .expect("load package")
            .expect("package exists");
        assert_eq!(stored.version, Version::new(2, 0, 0, false));
        assert_eq!(stored.match_pattern.as_slice(), &["aarch64".to_string()]);
        assert!(stored.exclude_pattern.is_empty());
    }

    #[test]
    fn list_packages_is_sorted_by_name() {
        let mut db = PackageConnection::open_in_memory().expect("open db");
        db.upsert_package(&test_package("zulu"))
            .expect("upsert zulu");
        db.upsert_package(&test_package("alpha"))
            .expect("upsert alpha");

        let names = db
            .list_packages()
            .expect("list packages")
            .into_iter()
            .map(|package| package.name)
            .collect::<Vec<_>>();

        assert_eq!(names, vec!["alpha", "zulu"]);
    }

    #[test]
    fn remove_package_deletes_package_and_patterns() {
        let mut db = PackageConnection::open_in_memory().expect("open db");
        db.upsert_package(&test_package("tool"))
            .expect("upsert package");

        assert!(db.remove_package("tool").expect("remove package"));
        assert!(!db.remove_package("tool").expect("remove missing package"));
        assert!(db.get_package("tool").expect("load missing").is_none());
        assert!(!db.package_exists("tool").expect("exists check"));
    }

    #[test]
    fn update_package_mutates_one_package() {
        let mut db = PackageConnection::open_in_memory().expect("open db");
        db.upsert_package(&test_package("tool"))
            .expect("upsert package");

        db.update_package("tool", |package| {
            package.is_pinned = false;
            package.exec_path = Some(PathBuf::from("/new/tool"));
            Ok(())
        })
        .expect("update package");

        let stored = db
            .get_package("tool")
            .expect("load package")
            .expect("package exists");
        assert!(!stored.is_pinned);
        assert_eq!(stored.exec_path, Some(PathBuf::from("/new/tool")));
    }

    #[test]
    fn update_package_supports_rename() {
        let mut db = PackageConnection::open_in_memory().expect("open db");
        db.upsert_package(&test_package("old"))
            .expect("upsert package");

        db.update_package("old", |package| {
            package.name = "new".to_string();
            Ok(())
        })
        .expect("rename package");

        assert!(db.get_package("old").expect("load old").is_none());
        assert!(db.get_package("new").expect("load new").is_some());
    }

    #[test]
    fn replace_all_packages_replaces_previous_rows() {
        let mut db = PackageConnection::open_in_memory().expect("open db");
        db.upsert_package(&test_package("old"))
            .expect("upsert old package");

        db.replace_all_packages(&[test_package("new")])
            .expect("replace all packages");

        assert!(db.get_package("old").expect("load old").is_none());
        assert!(db.get_package("new").expect("load new").is_some());
    }
}