/********************************************************
 * mysql_util.c
 *
 * Author: Thomas Wana <wana@ycom.at>
 * Date  : 1999/08/06
 * L.M.  : 1999/08/06
 *
 * Contains routines making life with MySQL easy :)
 * 
 * int mysql_util_printquery(MYSQL *mysql, char *query, FILE *fp);
 * Sends a query to the server (pointed to by *mysql) and prints the
 * result in a typical box like mysql-client does to the file *fp. 
 * Should work with MySQL 3.21.x too.
 * Return Value: 0 = Error
 *               1 = OK
 *
 ********************************************************/

#include <stdio.h>
#include <mysql.h>

int mysql_util_printquery(MYSQL *mysql, char *query, FILE *fp)
{
   MYSQL_ROW row;
   MYSQL_RES *result;
   MYSQL_FIELD *field;
   char hilf[200],hilf2[500],printf_string[50],hr[500];
   int rval=0,anz_fields,i,j,column_lengths[200];
   if(mysql_query(mysql,query)==0)
   {
      result=mysql_store_result(mysql);
      if(mysql_num_rows(result)>0)
      {
         strcpy(hilf2,"");
         for(i=0;(field=mysql_fetch_field(result))!=NULL;i++)
         {
            if(strlen(field->name) > field->max_length)
               column_lengths[i]=strlen(field->name);
            else
               column_lengths[i]=field->max_length;
            if(column_lengths[i]<4) column_lengths[i]=4;
            sprintf(printf_string,"| %%-%ds ",column_lengths[i]);
            sprintf(hilf,printf_string,field->name);
            strcat(hilf2,hilf);
         }
         strcat(hilf2,"|");
         anz_fields=i;
         strcpy(hr,"");
         for(i=0;i<anz_fields;i++)
         {
            strcat(hr,"+");
            for(j=0;j<column_lengths[i]+2;j++)
               strcat(hr,"-");
         }
         strcat(hr,"+");
         fprintf(fp,"%s\n%s\n%s\n",hr,hilf2,hr);
         while((row=mysql_fetch_row(result))!=NULL)
         {
            strcpy(hilf2,"");
            for(i=0;i<anz_fields;i++)
            {
               sprintf(printf_string,"| %%-%ds ",column_lengths[i]);
               if(row[i]==NULL)
                  sprintf(hilf,printf_string,"NULL");
               else 
                  sprintf(hilf,printf_string,row[i]);
               strcat(hilf2,hilf); 
            }
            strcat(hilf2,"|");
            fprintf(fp,"%s\n",hilf2);
         }
         fprintf(fp,"%s\n",hr); 
         rval=1;
      }
      else
      { 
         fprintf(fp,"Empty set.\n");
         rval=1;
      }
      mysql_free_result(result);
   }
}
