File mysql-xml-to-csv-1.0.1.obscpio of Package mysql-xml-to-csv

07070100000000000081A400000000000000000000000166E9B1B600000029000000000000000000000000000000000000001F00000000mysql-xml-to-csv-1.0.1/AUTHORSArchie L. Cobbs <archie.cobbs@gmail.com>
07070100000001000081A400000000000000000000000166E9B1B600000129000000000000000000000000000000000000001F00000000mysql-xml-to-csv-1.0.1/CHANGESVersion 1.0.1 Released September 17, 2024

    - Added "-s" flag to specify alternate column separator
    - Added "-E" flag to specify output if there are zero rows
    - Added "-n" flag to specify alternate value for NULL columns

Version 1.0.0 Released September 2, 2021

    - Initial release
07070100000002000081A400000000000000000000000166E9B1B600000052000000000000000000000000000000000000001F00000000mysql-xml-to-csv-1.0.1/INSTALLSimplified instructions:

    1. ./configure
    2. make
    3. sudo make install
07070100000003000081A400000000000000000000000166E9B1B600002C5D000000000000000000000000000000000000001F00000000mysql-xml-to-csv-1.0.1/LICENSE                                 Apache License
                           Version 2.0, January 2004
                        http://www.apache.org/licenses/

   TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION

   1. Definitions.

      "License" shall mean the terms and conditions for use, reproduction,
      and distribution as defined by Sections 1 through 9 of this document.

      "Licensor" shall mean the copyright owner or entity authorized by
      the copyright owner that is granting the License.

      "Legal Entity" shall mean the union of the acting entity and all
      other entities that control, are controlled by, or are under common
      control with that entity. For the purposes of this definition,
      "control" means (i) the power, direct or indirect, to cause the
      direction or management of such entity, whether by contract or
      otherwise, or (ii) ownership of fifty percent (50%) or more of the
      outstanding shares, or (iii) beneficial ownership of such entity.

      "You" (or "Your") shall mean an individual or Legal Entity
      exercising permissions granted by this License.

      "Source" form shall mean the preferred form for making modifications,
      including but not limited to software source code, documentation
      source, and configuration files.

      "Object" form shall mean any form resulting from mechanical
      transformation or translation of a Source form, including but
      not limited to compiled object code, generated documentation,
      and conversions to other media types.

      "Work" shall mean the work of authorship, whether in Source or
      Object form, made available under the License, as indicated by a
      copyright notice that is included in or attached to the work
      (an example is provided in the Appendix below).

      "Derivative Works" shall mean any work, whether in Source or Object
      form, that is based on (or derived from) the Work and for which the
      editorial revisions, annotations, elaborations, or other modifications
      represent, as a whole, an original work of authorship. For the purposes
      of this License, Derivative Works shall not include works that remain
      separable from, or merely link (or bind by name) to the interfaces of,
      the Work and Derivative Works thereof.

      "Contribution" shall mean any work of authorship, including
      the original version of the Work and any modifications or additions
      to that Work or Derivative Works thereof, that is intentionally
      submitted to Licensor for inclusion in the Work by the copyright owner
      or by an individual or Legal Entity authorized to submit on behalf of
      the copyright owner. For the purposes of this definition, "submitted"
      means any form of electronic, verbal, or written communication sent
      to the Licensor or its representatives, including but not limited to
      communication on electronic mailing lists, source code control systems,
      and issue tracking systems that are managed by, or on behalf of, the
      Licensor for the purpose of discussing and improving the Work, but
      excluding communication that is conspicuously marked or otherwise
      designated in writing by the copyright owner as "Not a Contribution."

      "Contributor" shall mean Licensor and any individual or Legal Entity
      on behalf of whom a Contribution has been received by Licensor and
      subsequently incorporated within the Work.

   2. Grant of Copyright License. Subject to the terms and conditions of
      this License, each Contributor hereby grants to You a perpetual,
      worldwide, non-exclusive, no-charge, royalty-free, irrevocable
      copyright license to reproduce, prepare Derivative Works of,
      publicly display, publicly perform, sublicense, and distribute the
      Work and such Derivative Works in Source or Object form.

   3. Grant of Patent License. Subject to the terms and conditions of
      this License, each Contributor hereby grants to You a perpetual,
      worldwide, non-exclusive, no-charge, royalty-free, irrevocable
      (except as stated in this section) patent license to make, have made,
      use, offer to sell, sell, import, and otherwise transfer the Work,
      where such license applies only to those patent claims licensable
      by such Contributor that are necessarily infringed by their
      Contribution(s) alone or by combination of their Contribution(s)
      with the Work to which such Contribution(s) was submitted. If You
      institute patent litigation against any entity (including a
      cross-claim or counterclaim in a lawsuit) alleging that the Work
      or a Contribution incorporated within the Work constitutes direct
      or contributory patent infringement, then any patent licenses
      granted to You under this License for that Work shall terminate
      as of the date such litigation is filed.

   4. Redistribution. You may reproduce and distribute copies of the
      Work or Derivative Works thereof in any medium, with or without
      modifications, and in Source or Object form, provided that You
      meet the following conditions:

      (a) You must give any other recipients of the Work or
          Derivative Works a copy of this License; and

      (b) You must cause any modified files to carry prominent notices
          stating that You changed the files; and

      (c) You must retain, in the Source form of any Derivative Works
          that You distribute, all copyright, patent, trademark, and
          attribution notices from the Source form of the Work,
          excluding those notices that do not pertain to any part of
          the Derivative Works; and

      (d) If the Work includes a "NOTICE" text file as part of its
          distribution, then any Derivative Works that You distribute must
          include a readable copy of the attribution notices contained
          within such NOTICE file, excluding those notices that do not
          pertain to any part of the Derivative Works, in at least one
          of the following places: within a NOTICE text file distributed
          as part of the Derivative Works; within the Source form or
          documentation, if provided along with the Derivative Works; or,
          within a display generated by the Derivative Works, if and
          wherever such third-party notices normally appear. The contents
          of the NOTICE file are for informational purposes only and
          do not modify the License. You may add Your own attribution
          notices within Derivative Works that You distribute, alongside
          or as an addendum to the NOTICE text from the Work, provided
          that such additional attribution notices cannot be construed
          as modifying the License.

      You may add Your own copyright statement to Your modifications and
      may provide additional or different license terms and conditions
      for use, reproduction, or distribution of Your modifications, or
      for any such Derivative Works as a whole, provided Your use,
      reproduction, and distribution of the Work otherwise complies with
      the conditions stated in this License.

   5. Submission of Contributions. Unless You explicitly state otherwise,
      any Contribution intentionally submitted for inclusion in the Work
      by You to the Licensor shall be under the terms and conditions of
      this License, without any additional terms or conditions.
      Notwithstanding the above, nothing herein shall supersede or modify
      the terms of any separate license agreement you may have executed
      with Licensor regarding such Contributions.

   6. Trademarks. This License does not grant permission to use the trade
      names, trademarks, service marks, or product names of the Licensor,
      except as required for reasonable and customary use in describing the
      origin of the Work and reproducing the content of the NOTICE file.

   7. Disclaimer of Warranty. Unless required by applicable law or
      agreed to in writing, Licensor provides the Work (and each
      Contributor provides its Contributions) on an "AS IS" BASIS,
      WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
      implied, including, without limitation, any warranties or conditions
      of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
      PARTICULAR PURPOSE. You are solely responsible for determining the
      appropriateness of using or redistributing the Work and assume any
      risks associated with Your exercise of permissions under this License.

   8. Limitation of Liability. In no event and under no legal theory,
      whether in tort (including negligence), contract, or otherwise,
      unless required by applicable law (such as deliberate and grossly
      negligent acts) or agreed to in writing, shall any Contributor be
      liable to You for damages, including any direct, indirect, special,
      incidental, or consequential damages of any character arising as a
      result of this License or out of the use or inability to use the
      Work (including but not limited to damages for loss of goodwill,
      work stoppage, computer failure or malfunction, or any and all
      other commercial damages or losses), even if such Contributor
      has been advised of the possibility of such damages.

   9. Accepting Warranty or Additional Liability. While redistributing
      the Work or Derivative Works thereof, You may choose to offer,
      and charge a fee for, acceptance of support, warranty, indemnity,
      or other liability obligations and/or rights consistent with this
      License. However, in accepting such obligations, You may act only
      on Your own behalf and on Your sole responsibility, not on behalf
      of any other Contributor, and only if You agree to indemnify,
      defend, and hold each Contributor harmless for any liability
      incurred by, or claims asserted against, such Contributor by reason
      of your accepting any such warranty or additional liability.

   END OF TERMS AND CONDITIONS

   APPENDIX: How to apply the Apache License to your work.

      To apply the Apache License to your work, attach the following
      boilerplate notice, with the fields enclosed by brackets "[]"
      replaced with your own identifying information. (Don't include
      the brackets!)  The text should be enclosed in the appropriate
      comment syntax for the file format. We also recommend that a
      file or class name and description of purpose be included on the
      same "printed page" as the copyright notice for easier
      identification within third-party archives.

   Copyright [yyyy] [name of copyright owner]

   Licensed under the Apache License, Version 2.0 (the "License");
   you may not use this file except in compliance with the License.
   You may obtain a copy of the License at

       http://www.apache.org/licenses/LICENSE-2.0

   Unless required by applicable law or agreed to in writing, software
   distributed under the License is distributed on an "AS IS" BASIS,
   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
   See the License for the specific language governing permissions and
   limitations under the License.
07070100000004000081A400000000000000000000000166E9B1B6000003FD000000000000000000000000000000000000002300000000mysql-xml-to-csv-1.0.1/Makefile.am#
# mysql-xml-to-csv - Convert MySQL XML output to CSV
#
# Copyright (C) 2021 Archie L. Cobbs. All rights reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
#     http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
#

bin_PROGRAMS=		mysql-xml-to-csv

man_MANS=		mysql-xml-to-csv.1

docdir=			$(datadir)/doc/packages/$(PACKAGE)

doc_DATA=		CHANGES LICENSE README.md INSTALL AUTHORS

EXTRA_DIST=		CHANGES LICENSE README.md

mysql_xml_to_csv_SOURCES=	main.c \
				gitrev.c

gitrev.c:
			printf 'const char *const mysql_xml_to_csv_version = "%s";\n' "`git describe`" > gitrev.c
07070100000005000081A400000000000000000000000166E9B1B600000709000000000000000000000000000000000000002100000000mysql-xml-to-csv-1.0.1/README.md```
MYSQL-XML-TO-CSV(1)         BSD General Commands Manual         MYSQL-XML-TO-CSV(1)

NAME
     mysql-xml-to-csv -- Convert MySQL XML output to CSV

SYNOPSIS
     mysql-xml-to-csv [-E line] [-n value] [-N] [-s separator] [input.xml]

DESCRIPTION
     mysql-xml-to-csv converts MySQL XML query results (i.e., produced using the
     mysql(1) command when given the --xml flag) into a CSV file.

     The XML input is read from input.xml, if specified, otherwise standard input.
     The CSV output is written to standard output.

     The first row of the CSV output contains column names unless the -N flag is
     given.

     If the query result set contains zero rows, then by default nothing is output;
     this behavior can be altered using the -E flag.

     By default NULL column values are converted into the empty string; this behav-
     ior can be altered using the -n flag.

     The character encoding used for the CVS output is UTF-8.

OPTIONS
     -E      If the result set contains zero rows, output line followed by a new-
             line character instead of outputting nothing.  No validation of line
             is performed.

     -n      Output value instead of the empty string for NULL values.

     -N      Do not output the column names in the first row of the output file.

     -s      Specify an alternate column separator (default is comma).

RETURN VALUES
     mysql-xml-to-csv exits with one of the following values:

     0       Input was successfully processed.

     1       An error occurred.

SEE ALSO
     mysql-xml-to-csv: Convert MySQL XML output to CSV,
     https://github.com/archiecobbs/mysql-xml-to-csv.

AUTHOR
     Archie L. Cobbs <archie.cobbs@gmail.com>

BSD                              September 16, 2024                             BSD
```
07070100000006000081ED00000000000000000000000166E9B1B6000003C2000000000000000000000000000000000000002200000000mysql-xml-to-csv-1.0.1/autogen.sh#!/bin/bash

#
# Script to regenerate all the GNU auto* gunk.
# Run this from the top directory of the source tree.
#
# If it looks like I don't know what I'm doing here, you're right.
#

set -e

echo "cleaning up"
rm -rf autom4te*.cache scripts aclocal.m4 configure config.log config.status .deps stamp-h1
rm -f config.h.in config.h.in~ config.h
rm -rf scripts
find . \( -name Makefile -o -name Makefile.in \) -print0 | xargs -0 rm -f
rm -f *.o mysql-xml-to-csv mysql-xml-to-csv.1 mysql-xml-to-csv-*.tar.gz gitrev.c
rm -rf a.out.* tags
if [ "${1}" = '-C' ]; then
    exit 0
fi

ACLOCAL="aclocal"
AUTOHEADER="autoheader"
AUTOMAKE="automake"
AUTOCONF="autoconf"

echo "running aclocal"
mkdir scripts
${ACLOCAL} ${ACLOCAL_ARGS} -I scripts

echo "running autoheader"
${AUTOHEADER}

echo "running automake"
${AUTOMAKE} --add-missing -c --foreign

echo "running autoconf"
${AUTOCONF} -f -i

if [ "${1}" = '-c' ]; then
    echo "running configure"
    ./configure
fi

07070100000007000081A400000000000000000000000166E9B1B6000009D3000000000000000000000000000000000000002400000000mysql-xml-to-csv-1.0.1/configure.ac#
# mysql-xml-to-csv - Convert MySQL XML output to CSV
#
# Copyright (C) 2021 Archie L. Cobbs. All rights reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
#     http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
#

AC_INIT([mysql-xml-to-csv Convert MySQL XML output to CSV], [1.0.1], [https://github.com/archiecobbs/mysql-xml-to-csv/], [mysql-xml-to-csv])
AC_CONFIG_AUX_DIR(scripts)
AM_INIT_AUTOMAKE
dnl AM_MAINTAINER_MODE
AC_PREREQ(2.59)
AC_PREFIX_DEFAULT(/usr)
AC_PROG_MAKE_SET

[CFLAGS="-g -O3 -pipe -Wall -Waggregate-return -Wcast-align -Wchar-subscripts -Wcomment -Wformat -Wimplicit -Wmissing-declarations -Wmissing-prototypes -Wnested-externs -Wno-long-long -Wparentheses -Wpointer-arith -Wredundant-decls -Wreturn-type -Wswitch -Wtrigraphs -Wuninitialized -Wunused -Wwrite-strings -Wshadow -Wstrict-prototypes -Wcast-qual $CFLAGS"]
AC_SUBST(CFLAGS)

# Compile flags for Linux
AC_DEFINE(_DEFAULT_SOURCE, 1, Default functions)
AC_DEFINE(_GNU_SOURCE, 1, GNU functions)
AC_DEFINE(_BSD_SOURCE, 1, BSD functions)
AC_DEFINE(_XOPEN_SOURCE, 500, XOpen functions)

# Compile flags for Mac OS
AC_DEFINE(_DARWIN_C_SOURCE, 1, MacOS functions)

# Check for required programs
AC_PROG_INSTALL
AC_PROG_CC
AC_PATH_PROG([CAT], [cat], [], [])
if test "x${CAT}" = "x"; then
    AC_MSG_ERROR[cat not found]
fi
AC_PATH_PROG([SED], [sed], [], [])
if test "x${SED}" = "x"; then
    AC_MSG_ERROR[sed not found]
fi

# Check for required header files
AC_HEADER_STDC
AC_CHECK_HEADERS(ctype.h errno.h stdio.h stdlib.h string.h unistd.h sys/stat.h sys/types.h, [],
        [AC_MSG_ERROR([required header file '$ac_header' missing])])

# Check for required libraries
AC_CHECK_LIB(expat, XML_ParserCreate,,
	[AC_MSG_ERROR([required library expat missing])])

# Optional features
AC_ARG_ENABLE(Werror,
    AC_HELP_STRING([--enable-Werror],
        [enable compilation with -Werror flag (default NO)]),
    [test x"$enableval" = "xyes" && CFLAGS="${CFLAGS} -Werror"])

# Generated files
AC_CONFIG_FILES(Makefile)
AC_CONFIG_FILES(mysql-xml-to-csv.1)
AM_CONFIG_HEADER(config.h)

# Go
AC_OUTPUT
07070100000008000081A400000000000000000000000166E9B1B6000027D0000000000000000000000000000000000000001E00000000mysql-xml-to-csv-1.0.1/main.c#include <assert.h>
#include <ctype.h>
#include <err.h>
#include <expat.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>

/* Sanity check expat gives us UTF-8 characters */
#ifdef XML_UNICODE
#error "Only UTF-8 encoding is supported"
#endif

#define COPYRIGHT   "\xc2\xa9"

/*
    Example of MySQL XML output:

    <?xml version="1.0"?>

    <resultset xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" statement="SELECT id as IdNum, lastName, firstName FROM User">
        <row>
            <field name="IdNum">100040</field>
            <field name="lastName" xsi:nil="true"/>
            <field name="firsttName">Cher</field>
        </row>
    </resultset>
*/

#define BUFFER_SIZE                 (1 << 16)
#define DEFAULT_COLUMN_SEPARATOR    ","

// Version string
extern const char *const mysql_xml_to_csv_version;

// These accumulate the first row column names and values until first row is entirely read (unless the "-N" flag is given)
static XML_Char **column_names;
static size_t num_column_names;
static XML_Char **first_row_values;
static size_t num_first_row_values;

// Column separator
static const char *column_separator = DEFAULT_COLUMN_SEPARATOR;

// This accumulates one column's value
static XML_Char *elem_text;                     // note: not nul-terminated
static size_t elem_text_len;

// Flags
static int first_column;                        // the current column is the first column
static int reading_value;                       // we are reading the current column's value
static int num_rows_seen;                       // the number of rows we have seen so far
static int value_is_null;                       // the current column value is null
static const char *null_value;                  // string to output for null values (default empty)

// Expat callback functions
static void handle_elem_start(void *data, const XML_Char *el, const XML_Char **attrs);
static void handle_elem_text(void *data, const XML_Char *s, int len);
static void handle_elem_end(void *data, const XML_Char *el);

// Helper functions
static const XML_Char *find_attribute(const XML_Char **const attrs, const char *name);
static void output_csv_row(XML_Char **values, size_t num);
static void output_csv_text(const char *s, size_t len);
static void add_string(XML_Char ***arrayp, size_t *lengthp, const XML_Char *string, size_t len);
static void add_chars(XML_Char **strp, size_t *lenp, const XML_Char *string, size_t nchars);
static size_t xml_strlen(const XML_Char *string);
static void free_strings(XML_Char ***arrayp, size_t *lengthp);
static void usage(void);

int
main(int argc, char **argv)
{
    char buf[BUFFER_SIZE];
    int want_column_names = 1;                  // output column names as the first CSV row
    const char *empty_output = NULL;            // what to print if there are zero rows
    XML_Parser p;
    FILE *fp;
    size_t r;
    int i;

    // Parse command line
    while ((i = getopt(argc, argv, "E:hn:Ns:v")) != -1) {
        switch (i) {
        case 'E':
            empty_output = optarg;
            break;
        case 'n':
            null_value = optarg;
            break;
        case 'N':
            want_column_names = 0;
            break;
        case 'h':
            usage();
            exit(0);
       case 's':
            if (*optarg == '\0' || *optarg == '"')
                errx(1, "invalid separator: %s", optarg);
            column_separator = optarg;
            break;
        case 'v':
            fprintf(stderr, "mysql-xml-to-csv %s\n", mysql_xml_to_csv_version);
            fprintf(stderr, "Copyright %s Archie L. Cobbs. All rights reserved.\n", COPYRIGHT);
            exit(0);
        case '?':
        default:
            usage();
            exit(1);
        }
    }
    argv += optind;
    argc -= optind;
    switch (argc) {
    case 0:
        fp = stdin;
        break;
    case 1:
        if (strcmp(argv[0], "-") == 0)
            fp = stdin;
        else if ((fp = fopen(argv[0], "r")) == NULL)
            err(1, "%s", argv[0]);
        break;
    default:
        usage();
        exit(1);
    }

    // Initialize arrays for column names and first row values
    if (want_column_names) {
        if ((column_names = malloc(10 * sizeof(*column_names))) == NULL)
            err(1, "malloc");
        if ((first_row_values = malloc(10 * sizeof(*first_row_values))) == NULL)
            err(1, "malloc");
    }

    // Initialize parser
    if ((p = XML_ParserCreate(NULL)) == NULL)
        errx(1, "can't initialize parser");
    XML_SetElementHandler(p, handle_elem_start, handle_elem_end);
    XML_SetCharacterDataHandler(p, handle_elem_text);

    // Process file
    while (1) {
        if ((r = fread(buf, 1, sizeof(buf), fp)) == 0 && ferror(fp))
            errx(1, "error reading input");
        if (XML_Parse(p, buf, r, r == 0) == XML_STATUS_ERROR)
            errx(1, "line %u: %s", (unsigned int)XML_GetCurrentLineNumber(p), XML_ErrorString(XML_GetErrorCode(p)));
        if (r == 0)
            break;
    }

    // Any rows encountered?
    if (num_rows_seen == 0 && empty_output != NULL)
        printf("%s\n", empty_output);

    // Clean up
    XML_ParserFree(p);
    fclose(fp);

    // Done
    return 0;
}

static void
handle_elem_start(void *data, const XML_Char *name, const XML_Char **attrs)
{
    const XML_Char *field_name;
    const XML_Char *nil_status;

    if (strcmp(name, "row") == 0) {
        first_column = 1;
        num_rows_seen++;
    } else if (strcmp(name, "field") == 0) {
        if (column_names != NULL) {
            if ((field_name = find_attribute(attrs, "name")) == NULL)
                errx(1, "row %d: \"%s\" element is missing \"%s\" attribute", num_rows_seen, "field", "name");
            add_string(&column_names, &num_column_names, field_name, xml_strlen(field_name));
        } else {
            if (!first_column)
                fputs(column_separator, stdout);
            putchar('"');
        }
        value_is_null = (nil_status = find_attribute(attrs, "xsi:nil")) != NULL && strcmp(nil_status, "true") == 0;
        reading_value = 1;
    }
}

static const XML_Char *
find_attribute(const XML_Char **attrs, const char *target)
{
    const XML_Char *name;
    const XML_Char *value;

    while (*attrs != NULL) {
        name = attrs[0];
        value = attrs[1];
        if (strcmp(name, target) == 0)
            return value;
        attrs += 2;
    }
    return NULL;
}

static void
handle_elem_text(void *data, const XML_Char *s, int len)
{
    if (!reading_value)
        return;
    if (value_is_null) {
//       if (len > 0)
//           errx(1, "row %d: non-empty value for field with xsi:nil=\"true\"", num_rows_seen);
        if (null_value != NULL)
            return;
    }
    if (column_names != NULL)
        add_chars(&elem_text, &elem_text_len, s, len);
    else
        output_csv_text(s, len);
}

static void
handle_elem_end(void *data, const XML_Char *name)
{
    if (strcmp(name, "row") == 0) {
        if (column_names != NULL) {
            output_csv_row(column_names, num_column_names);
            output_csv_row(first_row_values, num_first_row_values);
            free_strings(&column_names, &num_column_names);
            free_strings(&first_row_values, &num_first_row_values);
        } else
            putchar('\n');
    } else if (strcmp(name, "field") == 0) {
        if (value_is_null && null_value != NULL) {      // pretend "null_value" was the text content
            value_is_null = 0;
            handle_elem_text(data, null_value, strlen(null_value));
        }
        if (column_names != NULL) {
            add_string(&first_row_values, &num_first_row_values, elem_text, elem_text_len);
            free(elem_text);
            elem_text = NULL;
            elem_text_len = 0;
        } else
            putchar('"');
        first_column = 0;
        reading_value = 0;
    }
}

static void
output_csv_row(XML_Char **values, size_t num_columns)
{
    int i;

    for (i = 0; i < num_columns; i++) {
        if (i > 0)
            fputs(column_separator, stdout);
        putchar('"');
        output_csv_text(values[i], xml_strlen(values[i]));
        putchar('"');
    }
    putchar('\n');
}

static void
output_csv_text(const XML_Char *s, size_t len)
{
    while (len-- > 0) {
        if (*s == '"')
            putchar('"');
        putchar(*s);
        s++;
    }
}

static void
add_string(XML_Char ***arrayp, size_t *lengthp, const XML_Char *string, size_t nchars)
{
    char **new_array;

    if ((new_array = realloc(*arrayp, (*lengthp + 1) * sizeof(**arrayp))) == NULL)
        err(1, "malloc");
    *arrayp = new_array;
    if (((*arrayp)[*lengthp] = malloc((nchars + 1) * sizeof(XML_Char))) == NULL)
        err(1, "malloc");
    memcpy((*arrayp)[*lengthp], string, nchars * sizeof(XML_Char));
    (*arrayp)[*lengthp][nchars] = (XML_Char)0;
    (*lengthp)++;
}

static void
add_chars(XML_Char **strp, size_t *lenp, const XML_Char *string, size_t nchars)
{
    XML_Char *new_array;

    if ((new_array = realloc(*strp, (*lenp + nchars) * sizeof(XML_Char))) == NULL)
        err(1, "malloc");
    *strp = new_array;
    memcpy(*strp + *lenp, string, nchars * sizeof(XML_Char));
    *lenp += nchars;
}

static size_t
xml_strlen(const XML_Char *string)
{
    size_t len;

    len = 0;
    while (string[len] != (XML_Char)0)
        len++;
    return len;
}

static void
free_strings(char ***arrayp, size_t *lengthp)
{
    while (*lengthp > 0)
        free((*arrayp)[--*lengthp]);
    free(*arrayp);
    *arrayp = NULL;
}

static void
usage(void)
{
    fprintf(stderr, "Usage: mysql-xml-to-csv [options] [file.xml]\n");
    fprintf(stderr, "Options:\n");
    fprintf(stderr, "  -E line\tOutput \"line\" if result has zero rows (default output nothing)\n");
    fprintf(stderr, "  -n value\tOutput \"value\" for NULL values (default empty string)\n");
    fprintf(stderr, "  -N\t\tDo not output column names as the first CSV row\n");
    fprintf(stderr, "  -s char\tSpecify column separator (default \"%s\")\n", DEFAULT_COLUMN_SEPARATOR);
    fprintf(stderr, "  -h\t\tShow this usage info\n");
    fprintf(stderr, "  -v\t\tShow program version\n");
}
07070100000009000081A400000000000000000000000166E9B1B600000964000000000000000000000000000000000000002D00000000mysql-xml-to-csv-1.0.1/mysql-xml-to-csv.1.in.\"  -*- nroff -*-
.\"
.\" mysql-xml-to-csv - Convert MySQL XML output to CSV
.\"
.\" Copyright (C) 2021 Archie L. Cobbs. All rights reserved.
.\"
.\" Licensed under the Apache License, Version 2.0 (the "License");
.\" you may not use this file except in compliance with the License.
.\" You may obtain a copy of the License at
.\"
.\"     http://www.apache.org/licenses/LICENSE-2.0
.\"
.\" Unless required by applicable law or agreed to in writing, software
.\" distributed under the License is distributed on an "AS IS" BASIS,
.\" WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
.\" See the License for the specific language governing permissions and
.\" limitations under the License.
.\"
.Dd September 16, 2024
.Dt MYSQL-XML-TO-CSV 1
.Os
.Sh NAME
.Nm mysql-xml-to-csv
.Nd Convert MySQL XML output to CSV
.Sh SYNOPSIS
.Nm mysql-xml-to-csv
.Op Fl E Ar line
.Op Fl n Ar value
.Op Fl N
.Op Fl s Ar separator
.Op Ar input.xml
.Bk -words
.Ek
.Sh DESCRIPTION
.Nm
converts MySQL XML query results (i.e., produced using the
.Xr mysql 1
command when given the
.Fl \-xml
flag) into a CSV file.
.Pp
The XML input is read from
.Pa input.xml ,
if specified, otherwise standard input.
The CSV output is written to standard output.
.Pp
The first row of the CSV output contains column names unless the
.Fl N
flag is given.
.Pp
If the query result set contains zero rows, then by default nothing is output;
this behavior can be altered using the
.Fl E
flag.
.Pp
By default NULL column values are converted into the empty string;
this behavior can be altered using the
.Fl n
flag.
.Pp
The character encoding used for the CVS output is UTF-8.
.Sh OPTIONS
.Bl -tag -width Ds
.It Fl E
If the result set contains zero rows, output
.Ar line
followed by a newline character instead of outputting nothing.
No validation of
.Ar line
is performed.
.It Fl n
Output
.Ar value
instead of the empty string for NULL values.
.It Fl N
Do not output the column names in the first row of the output file.
.It Fl s
Specify an alternate column separator (default is comma).
.El
.Sh RETURN VALUES
.Nm
exits with one of the following values:
.Bl -tag -width Ds
.It 0
Input was successfully processed.
.It 1
An error occurred.
.El
.Sh SEE ALSO
.Rs
.%T "mysql-xml-to-csv: Convert MySQL XML output to CSV"
.%O https://github.com/archiecobbs/mysql-xml-to-csv
.Re
.Sh AUTHOR
.An Archie L. Cobbs Aq archie.cobbs@gmail.com
07070100000000000000000000000000000000000000010000000000000000000000000000000000000000000000000000000B00000000TRAILER!!!64 blocks
openSUSE Build Service is sponsored by