]> git.sur5r.net Git - bacula/bacula/blobdiff - bacula/src/cats/sql_find.c
Integrate patch into latest version, which fixes bug #1882
[bacula/bacula] / bacula / src / cats / sql_find.c
index ef3d89f2b8dd646851775389cef8f4f281cd136e..0a0878cd21ca64d6877dbb45c902cc04cd9e509d 100644 (file)
@@ -1,47 +1,39 @@
 /*
- * Bacula Catalog Database Find record interface routines
- *
- *  Note, generally, these routines are more complicated
- *       that a simple search by name or id. Such simple
- *       request are in get.c
- * 
- *    Kern Sibbald, December 2000
- *
- *    Version $Id$
- */
+   Bacula(R) - The Network Backup Solution
 
-/*
-   Copyright (C) 2000, 2001, 2002 Kern Sibbald and John Walker
+   Copyright (C) 2000-2015 Kern Sibbald
+   Copyright (C) 2000-2014 Free Software Foundation Europe e.V.
 
-   This program is free software; you can redistribute it and/or
-   modify it under the terms of the GNU General Public License as
-   published by the Free Software Foundation; either version 2 of
-   the License, or (at your option) any later version.
+   The original author of Bacula is Kern Sibbald, with contributions
+   from many others, a complete list can be found in the file AUTHORS.
 
-   This program is distributed in the hope that it will be useful,
-   but WITHOUT ANY WARRANTY; without even the implied warranty of
-   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
-   General Public License for more details.
+   You may use this file and others of this release according to the
+   license defined in the LICENSE file, which includes the Affero General
+   Public License, v3.0 ("AGPLv3") and some additional permissions and
+   terms pursuant to its AGPLv3 Section 7.
 
-   You should have received a copy of the GNU General Public
-   License along with this program; if not, write to the Free
-   Software Foundation, Inc., 59 Temple Place - Suite 330, Boston,
-   MA 02111-1307, USA.
+   This notice must be preserved when any source code is 
+   conveyed and/or propagated.
 
+   Bacula(R) is a registered trademark of Kern Sibbald.
+*/
+/*
+ * Bacula Catalog Database Find record interface routines
+ *
+ *  Note, generally, these routines are more complicated
+ *        that a simple search by name or id. Such simple
+ *        request are in get.c
+ *
+ *    Written by Kern Sibbald, December 2000
+ *
  */
 
-/* *****FIXME**** fix fixed length of select_cmd[] and insert_cmd[] */
+#include  "bacula.h"
 
-/* The following is necessary so that we do not include
- * the dummy external definition of DB.
- */
-#define __SQL_C                      /* indicate that this is sql.c */
+#if HAVE_SQLITE3 || HAVE_MYSQL || HAVE_POSTGRESQL
 
-#include "bacula.h"
 #include "cats.h"
 
-#if    HAVE_MYSQL || HAVE_SQLITE
-
 /* -----------------------------------------------------------------------
  *
  *   Generic Routines (or almost generic)
  * -----------------------------------------------------------------------
  */
 
-/* Imported subroutines */
-extern void print_result(B_DB *mdb);
-extern int QueryDB(char *file, int line, B_DB *db, char *select_cmd);
+/*
+ * Find the most recent successful real end time for a job given.
+ *
+ *  RealEndTime is returned in etime
+ *  Job name is returned in job (MAX_NAME_LENGTH)
+ *
+ * Returns: false on failure
+ *          true  on success, jr is unchanged, but etime and job are set
+ */
+bool BDB::bdb_find_last_job_end_time(JCR *jcr, JOB_DBR *jr, POOLMEM **etime, 
+          char *job)
+{
+   SQL_ROW row;
+   char ed1[50], ed2[50];
+   char esc_name[MAX_ESCAPE_NAME_LENGTH];
+
+   bdb_lock();
+   bdb_escape_string(jcr, esc_name, jr->Name, strlen(jr->Name));
+   pm_strcpy(etime, "0000-00-00 00:00:00");   /* default */
+   job[0] = 0;
+
+   Mmsg(cmd,
+        "SELECT RealEndTime, Job FROM Job WHERE JobStatus IN ('T','W') AND Type='%c' AND "
+        "Level IN ('%c','%c','%c') AND Name='%s' AND ClientId=%s AND FileSetId=%s "
+        "ORDER BY RealEndTime DESC LIMIT 1", jr->JobType, 
+        L_FULL, L_DIFFERENTIAL, L_INCREMENTAL, esc_name, 
+        edit_int64(jr->ClientId, ed1), edit_int64(jr->FileSetId, ed2));
+
+   if (!QueryDB(jcr, cmd)) {
+      Mmsg2(&errmsg, _("Query error for end time request: ERR=%s\nCMD=%s\n"),
+         sql_strerror(), cmd);
+      goto bail_out;
+   }
+   if ((row = sql_fetch_row()) == NULL) {
+      sql_free_result();
+      Mmsg(errmsg, _("No prior backup Job record found.\n"));
+      goto bail_out;
+   }
+   Dmsg1(100, "Got end time: %s\n", row[0]);
+   pm_strcpy(etime, row[0]);
+   bstrncpy(job, row[1], MAX_NAME_LENGTH);
 
+   sql_free_result();
+   bdb_unlock();
+   return true;
 
-/* Find job start time. Used to find last full save
- * for Incremental and Differential saves.
- *     
- * Returns: 0 on failure
- *         1 on success, jr is unchanged, but stime is set
+bail_out:
+   bdb_unlock();
+   return false;
+}
+
+
+/*
+ * Find job start time if JobId specified, otherwise
+ * find last Job start time Incremental and Differential saves.
+ *
+ *  StartTime is returned in stime
+ *  Job name is returned in job (MAX_NAME_LENGTH)
+ *
+ * Returns: false on failure
+ *          true  on success, jr is unchanged, but stime and job are set
  */
-int
-db_find_job_start_time(B_DB *mdb, JOB_DBR *jr, char *stime)
+bool BDB::bdb_find_job_start_time(JCR *jcr, JOB_DBR *jr, POOLMEM **stime, char *job)
 {
    SQL_ROW row;
-   int JobId;
+   char ed1[50], ed2[50];
+   char esc_name[MAX_ESCAPE_NAME_LENGTH];
+
+   bdb_lock();
+   bdb_escape_string(jcr, esc_name, jr->Name, strlen(jr->Name));
+   pm_strcpy(stime, "0000-00-00 00:00:00");   /* default */
+   job[0] = 0;
 
-   strcpy(stime, "0000-00-00 00:00:00");   /* default */
-   P(mdb->mutex);
    /* If no Id given, we must find corresponding job */
    if (jr->JobId == 0) {
       /* Differential is since last Full backup */
-      if (jr->Level == L_DIFFERENTIAL) {
-        Mmsg(&mdb->cmd, 
-"SELECT JobId from Job WHERE JobStatus='T' and Type='%c' and \
-Level='%c' and Name=\"%s\" and ClientId=%d and FileSetId=%d \
-ORDER by StartTime DESC LIMIT 1",
-          jr->Type, L_FULL, jr->Name, jr->ClientId, jr->FileSetId);
+      Mmsg(cmd,
+"SELECT StartTime, Job FROM Job WHERE JobStatus IN ('T','W') AND Type='%c' AND "
+"Level='%c' AND Name='%s' AND ClientId=%s AND FileSetId=%s "
+"ORDER BY StartTime DESC LIMIT 1",
+           jr->JobType, L_FULL, esc_name,
+           edit_int64(jr->ClientId, ed1), edit_int64(jr->FileSetId, ed2));
+
+      if (jr->JobLevel == L_DIFFERENTIAL) {
+         /* SQL cmd for Differential backup already edited above */
+
       /* Incremental is since last Full, Incremental, or Differential */
-      } else if (jr->Level == L_INCREMENTAL) {
-        Mmsg(&mdb->cmd, 
-"SELECT JobId from Job WHERE JobStatus='T' and Type='%c' and \
-(Level='%c' or Level='%c' or Level='%c') and Name=\"%s\" and ClientId=%d \
-ORDER by StartTime DESC LIMIT 1",
-          jr->Type, L_INCREMENTAL, L_DIFFERENTIAL, L_FULL, jr->Name,
-          jr->ClientId);
+      } else if (jr->JobLevel == L_INCREMENTAL) {
+         /*
+          * For an Incremental job, we must first ensure
+          *  that a Full backup was done (cmd edited above)
+          *  then we do a second look to find the most recent
+          *  backup
+          */
+         if (!QueryDB(jcr, cmd)) {
+            Mmsg2(&errmsg, _("Query error for start time request: ERR=%s\nCMD=%s\n"),
+               sql_strerror(), cmd);
+            goto bail_out;
+         }
+         if ((row = sql_fetch_row()) == NULL) {
+            sql_free_result();
+            Mmsg(errmsg, _("No prior Full backup Job record found.\n"));
+            goto bail_out;
+         }
+         sql_free_result();
+         /* Now edit SQL command for Incremental Job */
+         Mmsg(cmd,
+"SELECT StartTime, Job FROM Job WHERE JobStatus IN ('T','W') AND Type='%c' AND "
+"Level IN ('%c','%c','%c') AND Name='%s' AND ClientId=%s "
+"AND FileSetId=%s ORDER BY StartTime DESC LIMIT 1",
+            jr->JobType, L_INCREMENTAL, L_DIFFERENTIAL, L_FULL, esc_name,
+            edit_int64(jr->ClientId, ed1), edit_int64(jr->FileSetId, ed2));
       } else {
-         Mmsg1(&mdb->errmsg, _("Unknown level=%d\n"), jr->Level);
-        Emsg0(M_ERROR, 0, mdb->errmsg);
-        V(mdb->mutex);
-        return 0;
-      }
-      Dmsg1(100, "Submitting: %s\n", mdb->cmd);
-      if (!QUERY_DB(mdb, mdb->cmd)) {
-         Emsg1(M_ERROR, 0, _("Query error for start time request: %s\n"), mdb->cmd);
-        V(mdb->mutex);
-        return 0;
+         Mmsg1(errmsg, _("Unknown level=%d\n"), jr->JobLevel);
+         goto bail_out;
       }
-      if ((row = sql_fetch_row(mdb)) == NULL) {
-        sql_free_result(mdb);
-        V(mdb->mutex);
-        return 0;
-      }
-      JobId = atoi(row[0]);
-      sql_free_result(mdb);
    } else {
-      JobId = jr->JobId;             /* search for particular id */
+      Dmsg1(100, "Submitting: %s\n", cmd);
+      Mmsg(cmd, "SELECT StartTime, Job FROM Job WHERE Job.JobId=%s",
+           edit_int64(jr->JobId, ed1));
    }
 
-   Dmsg1(100, "Submitting: %s\n", mdb->cmd);
-   Mmsg(&mdb->cmd, "SELECT StartTime from Job WHERE Job.JobId=%d", JobId);
+   if (!QueryDB(jcr, cmd)) {
+      pm_strcpy(stime, "");                   /* set EOS */
+      Mmsg2(&errmsg, _("Query error for start time request: ERR=%s\nCMD=%s\n"),
+         sql_strerror(),  cmd);
+      goto bail_out;
+   }
 
-   if (!QUERY_DB(mdb, mdb->cmd)) {
-      Emsg1(M_ERROR, 0, _("Query error for start time request: %s\n"), mdb->cmd);
-      V(mdb->mutex);
-      return 0;
+   if ((row = sql_fetch_row()) == NULL) {
+      Mmsg2(&errmsg, _("No Job record found: ERR=%s\nCMD=%s\n"),
+         sql_strerror(),  cmd);
+      sql_free_result();
+      goto bail_out;
    }
+   Dmsg2(100, "Got start time: %s, job: %s\n", row[0], row[1]);
+   pm_strcpy(stime, row[0]);
+   bstrncpy(job, row[1], MAX_NAME_LENGTH);
 
-   if ((row = sql_fetch_row(mdb)) == NULL) {
-      *stime = 0;                    /* set EOS */
-      Emsg2(M_ERROR, 0, _("No Job found for JobId=%d: %s\n"), JobId, sql_strerror(mdb));
-      sql_free_result(mdb);
-      V(mdb->mutex);
-      return 0;
+   sql_free_result();
+
+   bdb_unlock();
+   return true;
+
+bail_out:
+   bdb_unlock();
+   return false;
+}
+
+
+/*
+ * Find the last job start time for the specified JobLevel
+ *
+ *  StartTime is returned in stime
+ *  Job name is returned in job (MAX_NAME_LENGTH)
+ *
+ * Returns: false on failure
+ *          true  on success, jr is unchanged, but stime and job are set
+ */
+bool BDB::bdb_find_last_job_start_time(JCR *jcr, JOB_DBR *jr,
+                            POOLMEM **stime, char *job, int JobLevel)
+{
+   SQL_ROW row;
+   char ed1[50], ed2[50];
+   char esc_name[MAX_ESCAPE_NAME_LENGTH];
+
+   bdb_lock();
+   bdb_escape_string(jcr, esc_name, jr->Name, strlen(jr->Name));
+   pm_strcpy(stime, "0000-00-00 00:00:00");   /* default */
+   job[0] = 0;
+
+   Mmsg(cmd,
+"SELECT StartTime, Job FROM Job WHERE JobStatus IN ('T','W') AND Type='%c' AND "
+"Level='%c' AND Name='%s' AND ClientId=%s AND FileSetId=%s "
+"ORDER BY StartTime DESC LIMIT 1",
+      jr->JobType, JobLevel, esc_name,
+      edit_int64(jr->ClientId, ed1), edit_int64(jr->FileSetId, ed2));
+   if (!QueryDB(jcr, cmd)) {
+      Mmsg2(&errmsg, _("Query error for start time request: ERR=%s\nCMD=%s\n"),
+         sql_strerror(), cmd);
+      goto bail_out;
+   }
+   if ((row = sql_fetch_row()) == NULL) {
+      sql_free_result();
+      Mmsg(errmsg, _("No prior Full backup Job record found.\n"));
+      goto bail_out;
    }
    Dmsg1(100, "Got start time: %s\n", row[0]);
-   strcpy(stime, row[0]);
+   pm_strcpy(stime, row[0]);
+   bstrncpy(job, row[1], MAX_NAME_LENGTH);
 
-   sql_free_result(mdb);
+   sql_free_result();
+   bdb_unlock();
+   return true;
 
-   V(mdb->mutex);
-   return 1;
+bail_out:
+   bdb_unlock();
+   return false;
 }
 
-/* 
- * Find JobId of last full verify 
- * Returns: 1 on success
- *         0 on failure
+/*
+ * Find last failed job since given start-time
+ *   it must be either Full or Diff.
+ *
+ * Returns: false on failure
+ *          true  on success, jr is unchanged and stime unchanged
+ *                level returned in JobLevel
  */
-int
-db_find_last_full_verify(B_DB *mdb, JOB_DBR *jr)
+bool BDB::bdb_find_failed_job_since(JCR *jcr, JOB_DBR *jr, POOLMEM *stime, int &JobLevel)
 {
    SQL_ROW row;
+   char ed1[50], ed2[50];
+   char esc_name[MAX_ESCAPE_NAME_LENGTH];
+
+   bdb_lock();
+   bdb_escape_string(jcr, esc_name, jr->Name, strlen(jr->Name));
+
+   /* Differential is since last Full backup */
+   Mmsg(cmd,
+   "SELECT Level FROM Job WHERE JobStatus IN ('%c','%c', '%c', '%c') AND "
+      "Type='%c' AND Level IN ('%c','%c') AND Name='%s' AND ClientId=%s "
+      "AND FileSetId=%s AND StartTime>'%s' "
+      "ORDER BY StartTime DESC LIMIT 1",
+         JS_Canceled, JS_ErrorTerminated, JS_Error, JS_FatalError,
+         jr->JobType, L_FULL, L_DIFFERENTIAL, esc_name,
+         edit_int64(jr->ClientId, ed1), edit_int64(jr->FileSetId, ed2),
+         stime);
+   if (!QueryDB(jcr, cmd)) {
+      bdb_unlock();
+      return false;
+   }
 
-   /* Find last full */
-   P(mdb->mutex);
-   if (jr->Level != L_VERIFY_CATALOG) {
-      Emsg2(M_FATAL, 0, _("Expecting Level=%c, got %c\n"), L_VERIFY_CATALOG, jr->Level);
-      return 0;
+   if ((row = sql_fetch_row()) == NULL) {
+      sql_free_result();
+      bdb_unlock();
+      return false;
    }
-   Mmsg(&mdb->cmd, 
-"SELECT JobId from Job WHERE Type='%c' and Level='%c' and Name=\"%s\" and \
-ClientId=%d ORDER by StartTime DESC LIMIT 1",
-          JT_VERIFY, L_VERIFY_INIT, jr->Name, jr->ClientId);
+   JobLevel = (int)*row[0];
+   sql_free_result();
 
-   if (!QUERY_DB(mdb, mdb->cmd)) {
-      V(mdb->mutex);
-      return 0;
+   bdb_unlock();
+   return true;
+}
+
+
+/*
+ * Find JobId of last job that ran.  E.g. for
+ *   VERIFY_CATALOG we want the JobId of the last INIT.
+ *   For VERIFY_VOLUME_TO_CATALOG, we want the JobId of the last Job.
+ *
+ * Returns: true  on success
+ *          false on failure
+ */
+bool BDB::bdb_find_last_jobid(JCR *jcr, const char *Name, JOB_DBR *jr)
+{
+   SQL_ROW row;
+   char ed1[50];
+   char esc_name[MAX_ESCAPE_NAME_LENGTH];
+
+   bdb_lock();
+   /* Find last full */
+   Dmsg2(100, "JobLevel=%d JobType=%d\n", jr->JobLevel, jr->JobType);
+   if (jr->JobLevel == L_VERIFY_CATALOG) {
+      bdb_escape_string(jcr, esc_name, jr->Name, strlen(jr->Name));
+      Mmsg(cmd,
+"SELECT JobId FROM Job WHERE Type='V' AND Level='%c' AND "
+" JobStatus IN ('T','W') AND Name='%s' AND "
+"ClientId=%s ORDER BY StartTime DESC LIMIT 1",
+           L_VERIFY_INIT, esc_name,
+           edit_int64(jr->ClientId, ed1));
+   } else if (jr->JobLevel == L_VERIFY_VOLUME_TO_CATALOG ||
+              jr->JobLevel == L_VERIFY_DISK_TO_CATALOG ||
+              jr->JobLevel == L_VERIFY_DATA ||
+              jr->JobType == JT_BACKUP) {
+      if (Name) {
+         bdb_escape_string(jcr, esc_name, (char*)Name,
+                               MIN(strlen(Name), sizeof(esc_name)));
+         Mmsg(cmd,
+"SELECT JobId FROM Job WHERE Type='B' AND JobStatus IN ('T','W') AND "
+"Name='%s' ORDER BY StartTime DESC LIMIT 1", esc_name);
+      } else {
+         Mmsg(cmd,
+"SELECT JobId FROM Job WHERE Type='B' AND JobStatus IN ('T','W') AND "
+"ClientId=%s ORDER BY StartTime DESC LIMIT 1",
+           edit_int64(jr->ClientId, ed1));
+      }
+   } else {
+      Mmsg1(&errmsg, _("Unknown Job level=%d\n"), jr->JobLevel);
+      bdb_unlock();
+      return false;
    }
-   if ((row = sql_fetch_row(mdb)) == NULL) {
-      Emsg0(M_FATAL, 0, _("No Job found for last full verify.\n"));
-      sql_free_result(mdb);
-      V(mdb->mutex);
-      return 0;
+   Dmsg1(100, "Query: %s\n", cmd);
+   if (!QueryDB(jcr, cmd)) {
+      bdb_unlock();
+      return false;
+   }
+   if ((row = sql_fetch_row()) == NULL) {
+      Mmsg1(&errmsg, _("No Job found for: %s.\n"), cmd);
+      sql_free_result();
+      bdb_unlock();
+      return false;
    }
 
-   jr->JobId = atoi(row[0]);
-   sql_free_result(mdb);
+   jr->JobId = str_to_int64(row[0]);
+   sql_free_result();
 
-   Dmsg1(100, "db_get_last_full_verify: got JobId=%d\n", jr->JobId);
+   Dmsg1(100, "db_get_last_jobid: got JobId=%d\n", jr->JobId);
    if (jr->JobId <= 0) {
-      Emsg1(M_FATAL, 0, _("No Verify Job found for: %s\n"), mdb->cmd);
-      V(mdb->mutex);
-      return 0;
+      Mmsg1(&errmsg, _("No Job found for: %s\n"), cmd);
+      bdb_unlock();
+      return false;
    }
 
-   V(mdb->mutex);
-   return 1;
+   bdb_unlock();
+   return true;
 }
 
-/* 
+/*
  * Find Available Media (Volume) for Pool
  *
  * Find a Volume for a given PoolId, MediaType, and Status.
  *
  * Returns: 0 on failure
- *         numrows on success
+ *          numrows on success
  */
-int
-db_find_next_volume(B_DB *mdb, int item, MEDIA_DBR *mr) 
+int BDB::bdb_find_next_volume(JCR *jcr, int item, bool InChanger, MEDIA_DBR *mr)
 {
-   SQL_ROW row;
+   SQL_ROW row = NULL;
    int numrows;
-
-   P(mdb->mutex);
-   Mmsg(&mdb->cmd, "SELECT MediaId,VolumeName,VolJobs,VolFiles,VolBlocks,\
-VolBytes,VolMounts,VolErrors,VolWrites,VolMaxBytes,VolCapacityBytes \
-FROM Media WHERE PoolId=%d AND MediaType=\"%s\" AND VolStatus=\"%s\" \
-ORDER BY MediaId", mr->PoolId, mr->MediaType, mr->VolStatus); 
-
-   if (!QUERY_DB(mdb, mdb->cmd)) {
-      V(mdb->mutex);
+   const char *order;
+   char esc_type[MAX_ESCAPE_NAME_LENGTH];
+   char esc_status[MAX_ESCAPE_NAME_LENGTH];
+   char ed1[50];
+
+   bdb_lock();
+   bdb_escape_string(jcr, esc_type, mr->MediaType, strlen(mr->MediaType));
+   bdb_escape_string(jcr, esc_status, mr->VolStatus, strlen(mr->VolStatus));
+
+   if (item == -1) {       /* find oldest volume */
+      /* Find oldest volume */
+      Mmsg(cmd, "SELECT MediaId,VolumeName,VolJobs,VolFiles,VolBlocks,"
+         "VolBytes,VolMounts,VolErrors,VolWrites,MaxVolBytes,VolCapacityBytes,"
+         "MediaType,VolStatus,PoolId,VolRetention,VolUseDuration,MaxVolJobs,"
+         "MaxVolFiles,Recycle,Slot,FirstWritten,LastWritten,InChanger,"
+         "EndFile,EndBlock,VolParts,LabelType,LabelDate,StorageId,"
+         "Enabled,LocationId,RecycleCount,InitialWrite,"
+         "ScratchPoolId,RecyclePoolId,VolReadTime,VolWriteTime,ActionOnPurge "
+         "FROM Media WHERE PoolId=%s AND MediaType='%s' AND VolStatus IN ('Full',"
+         "'Recycle','Purged','Used','Append') AND Enabled=1 "
+         "ORDER BY LastWritten LIMIT 1",
+         edit_int64(mr->PoolId, ed1), esc_type);
+     item = 1;
+   } else {
+      POOL_MEM changer(PM_FNAME);
+      POOL_MEM voltype(PM_FNAME);
+      POOL_MEM exclude(PM_FNAME);
+      /* Find next available volume */
+      if (InChanger) {
+         Mmsg(changer, " AND InChanger=1 AND StorageId=%s ",
+                 edit_int64(mr->StorageId, ed1));
+      }
+      /* Volumes will be automatically excluded from the query, we just take the
+       * first one of the list 
+       */
+      if (mr->exclude_list && *mr->exclude_list) {
+         item = 1;
+         Mmsg(exclude, " AND MediaId NOT IN (%s) ", mr->exclude_list);
+      }
+      if (strcmp(mr->VolStatus, "Recycle") == 0 ||
+          strcmp(mr->VolStatus, "Purged") == 0) {
+         order = "AND Recycle=1 ORDER BY LastWritten ASC,MediaId";  /* take oldest that can be recycled */
+      } else {
+         order = sql_media_order_most_recently_written[bdb_get_type_index()];    /* take most recently written */
+      }
+      Mmsg(cmd, "SELECT MediaId,VolumeName,VolJobs,VolFiles,VolBlocks,"
+         "VolBytes,VolMounts,VolErrors,VolWrites,MaxVolBytes,VolCapacityBytes,"
+         "MediaType,VolStatus,PoolId,VolRetention,VolUseDuration,MaxVolJobs,"
+         "MaxVolFiles,Recycle,Slot,FirstWritten,LastWritten,InChanger,"
+         "EndFile,EndBlock,VolParts,LabelType,LabelDate,StorageId,"
+         "Enabled,LocationId,RecycleCount,InitialWrite,"
+         "ScratchPoolId,RecyclePoolId,VolReadTime,VolWriteTime,ActionOnPurge "
+         "FROM Media WHERE PoolId=%s AND MediaType='%s' AND Enabled=1 "
+         "AND VolStatus='%s' "
+         "%s "
+         "%s "
+         "%s "
+         "%s LIMIT %d",
+         edit_int64(mr->PoolId, ed1), esc_type,
+         esc_status,
+         voltype.c_str(),
+         changer.c_str(), exclude.c_str(), order, item);
+   }
+   Dmsg1(100, "fnextvol=%s\n", cmd);
+   if (!QueryDB(jcr, cmd)) {
+      bdb_unlock();
       return 0;
    }
 
-   numrows = sql_num_rows(mdb);
-   if (item > numrows) {
-      V(mdb->mutex);
+   numrows = sql_num_rows();
+   if (item > numrows || item < 1) {
+      Dmsg2(050, "item=%d got=%d\n", item, numrows);
+      Mmsg2(&errmsg, _("Request for Volume item %d greater than max %d or less than 1\n"),
+         item, numrows);
+      bdb_unlock();
       return 0;
    }
-   
-   /* Seek to desired item 
-    * Note, we use base 1; SQL uses base 0
-    */
-   sql_data_seek(mdb, item-1);
 
-   if ((row = sql_fetch_row(mdb)) == NULL) {
-      Emsg1(M_ERROR, 0, _("No media record found for item %d.\n"), item);
-      sql_free_result(mdb);
-      V(mdb->mutex);
-      return 0;
+   /* Note, we previously seeked to the row using:
+    *  sql_data_seek(item-1);
+    * but this failed on PostgreSQL, so now we loop
+    * over all the records.  This should not be too horrible since
+    * the maximum Volumes we look at in any case is 20.
+    */
+   while (item-- > 0) {
+      if ((row = sql_fetch_row()) == NULL) {
+         Dmsg1(050, "Fail fetch item=%d\n", item+1);
+         Mmsg1(&errmsg, _("No Volume record found for item %d.\n"), item);
+         sql_free_result();
+         bdb_unlock();
+         return 0;
+      }
    }
 
    /* Return fields in Media Record */
-   mr->MediaId = atoi(row[0]);
-   strcpy(mr->VolumeName, row[1]);
-   mr->VolJobs = atoi(row[2]);
-   mr->VolFiles = atoi(row[3]);
-   mr->VolBlocks = atoi(row[4]);
-   mr->VolBytes = (uint64_t)strtod(row[5], NULL);
-   mr->VolMounts = atoi(row[6]);
-   mr->VolErrors = atoi(row[7]);
-   mr->VolWrites = atoi(row[8]);
-   mr->VolMaxBytes = (uint64_t)strtod(row[9], NULL);
-   mr->VolCapacityBytes = (uint64_t)strtod(row[10], NULL);
-
-   sql_free_result(mdb);
-
-   V(mdb->mutex);
+   mr->MediaId = str_to_int64(row[0]);
+   bstrncpy(mr->VolumeName, row[1]!=NULL?row[1]:"", sizeof(mr->VolumeName));
+   mr->VolJobs = str_to_int64(row[2]);
+   mr->VolFiles = str_to_int64(row[3]);
+   mr->VolBlocks = str_to_int64(row[4]);
+   mr->VolBytes = str_to_uint64(row[5]);
+   mr->VolMounts = str_to_int64(row[6]);
+   mr->VolErrors = str_to_int64(row[7]);
+   mr->VolWrites = str_to_int64(row[8]);
+   mr->MaxVolBytes = str_to_uint64(row[9]);
+   mr->VolCapacityBytes = str_to_uint64(row[10]);
+   bstrncpy(mr->MediaType, row[11]!=NULL?row[11]:"", sizeof(mr->MediaType));
+   bstrncpy(mr->VolStatus, row[12]!=NULL?row[12]:"", sizeof(mr->VolStatus));
+   mr->PoolId = str_to_int64(row[13]);
+   mr->VolRetention = str_to_uint64(row[14]);
+   mr->VolUseDuration = str_to_uint64(row[15]);
+   mr->MaxVolJobs = str_to_int64(row[16]);
+   mr->MaxVolFiles = str_to_int64(row[17]);
+   mr->Recycle = str_to_int64(row[18]);
+   mr->Slot = str_to_int64(row[19]);
+   bstrncpy(mr->cFirstWritten, row[20]!=NULL?row[20]:"", sizeof(mr->cFirstWritten));
+   mr->FirstWritten = (time_t)str_to_utime(mr->cFirstWritten);
+   bstrncpy(mr->cLastWritten, row[21]!=NULL?row[21]:"", sizeof(mr->cLastWritten));
+   mr->LastWritten = (time_t)str_to_utime(mr->cLastWritten);
+   mr->InChanger = str_to_uint64(row[22]);
+   mr->EndFile = str_to_uint64(row[23]);
+   mr->EndBlock = str_to_uint64(row[24]);
+   mr->VolType = str_to_int64(row[25]);   /* formerly VolParts */
+   mr->LabelType = str_to_int64(row[26]);
+   bstrncpy(mr->cLabelDate, row[27]!=NULL?row[27]:"", sizeof(mr->cLabelDate));
+   mr->LabelDate = (time_t)str_to_utime(mr->cLabelDate);
+   mr->StorageId = str_to_int64(row[28]);
+   mr->Enabled = str_to_int64(row[29]);
+   mr->LocationId = str_to_int64(row[30]);
+   mr->RecycleCount = str_to_int64(row[31]);
+   bstrncpy(mr->cInitialWrite, row[32]!=NULL?row[32]:"", sizeof(mr->cInitialWrite));
+   mr->InitialWrite = (time_t)str_to_utime(mr->cInitialWrite);
+   mr->ScratchPoolId = str_to_int64(row[33]);
+   mr->RecyclePoolId = str_to_int64(row[34]);
+   mr->VolReadTime = str_to_int64(row[35]);
+   mr->VolWriteTime = str_to_int64(row[36]);
+   mr->ActionOnPurge = str_to_int64(row[37]);
+
+   sql_free_result();
+
+   bdb_unlock();
+   Dmsg1(050, "Rtn numrows=%d\n", numrows);
    return numrows;
 }
 
-
-#endif /* HAVE_MYSQL || HAVE_SQLITE */
+#endif /* HAVE_SQLITE3 || HAVE_MYSQL || HAVE_POSTGRESQL */