+ sqlite3_str_appendall(sql, " ");
+ sqlite3_str_appendall(sql, group);
+ sqlite3_str_appendall(sql, " limit 1;");
+
+ if (sqlite3_str_errcode(sql)) {
+ zpm->error = 1;
+ sqlite3_free(sqlite3_str_finish(sql));
+ return 0;
+ }
+
+ query = sqlite3_str_finish(sql);
+
+ pkgid = zpm_db_string(zpm, query);;
+
+ sqlite3_free(query);
+
+ return pkgid;
+}
+
+char *zpm_findpkg_range(struct zpm *zpm, char *minpkg, char *maxpkg, char *where, int wantleast) {
+ int release;
+ char version[32];
+ char package[32];
+
+ char *select = "select pkgid, package, version, release from packages_pkgid";
+ char *last = "order by version collate vercmp desc, cast(release as integer) desc";
+ char *first = "order by version collate vercmp, cast(release as integer)";
+ char *group;
+
+ char *query, *pkgid = 0;
+ sqlite3_str *sql;
+
+ group = wantleast ? first : last;
+ /* null pkgstr find "best" package
+ * best is shortest complete package if any are complete
+ * shortest incomplete if any are incomplete
+ * where more than one version is in those sets, best is
+ * latest as determined by vercmp
+ */
+
+ sql = sqlite3_str_new(zpm->db);
+
+ sqlite3_str_appendall(sql, select);
+ sqlite3_str_appendall(sql, " where true");
+
+ if (minpkg) {
+ sqlite3_str_appendf(sql, " and pkgid >= %Q collate vercmp",
+ minpkg);
+ zpm_parse_package(minpkg, package, version, &release);
+ if (*package != 0) {
+ sqlite3_str_appendf(sql, " and package = %Q",
+ package);
+ }
+ }
+
+ if (maxpkg) {
+ sqlite3_str_appendf(sql, " and pkgid <= %Q collate vercmp",
+ maxpkg);
+ zpm_parse_package(maxpkg, package, version, &release);
+ if (*package != 0) {
+ sqlite3_str_appendf(sql, " and package = %Q",
+ package);
+ }
+ }
+
+ if (where) {
+ sqlite3_str_appendall(sql, " and ");
+ sqlite3_str_appendall(sql, where);
+ }
+