/* connleak.c - private bytes of the process over repeated ODBC connects.

   Reproduction without luasql of the memory growth per connect seen
   with MariaDB Connector/ODBC 3.2.10 on Windows when TLS is used.
   Plain ODBC API: SQLAllocHandle(DBC), SQLConnect, SQLDisconnect,
   SQLFreeHandle(DBC) in a loop on one environment handle.  The private
   bytes (GetProcessMemoryInfo, PrivateUsage) are printed every EVERY
   connects; the first report is the baseline.

   Usage: connleak DSN [-n COUNT] [-e EVERY] [-l] [-k] [-p]
     -n COUNT  number of connects, default 20000
     -e EVERY  report interval, default 1000
     -l        luasql sequence: SQLSetConnectAttr(SQL_ATTR_AUTOCOMMIT,
               SQL_AUTOCOMMIT_ON) after the connect and
               SQLEndTran(SQL_ROLLBACK) before the disconnect
     -k        keep one more connection open during the loop, so the
               driver stays loaded in the Driver Manager
     -p        wait for Enter after the baseline and after the loop
               (for heap snapshots with UMDH)

   User and password come from the environment variables
   MYSQL_TEST_USER and MYSQL_TEST_PASSWORD and are never printed.

   Build (x64 Native Tools prompt with oneAPI):
     icx /nologo /W4 /O2 connleak.c odbc32.lib psapi.lib  */

#define _CRT_SECURE_NO_WARNINGS
#include <windows.h>
#include <sql.h>
#include <sqlext.h>
#include <psapi.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>

static SIZE_T
private_bytes (void)
{
  PROCESS_MEMORY_COUNTERS_EX pmc;

  memset (&pmc, 0, sizeof (pmc));
  pmc.cb = sizeof (pmc);
  if (!GetProcessMemoryInfo (GetCurrentProcess (),
                             (PROCESS_MEMORY_COUNTERS *) &pmc,
                             sizeof (pmc)))
    return 0;
  return pmc.PrivateUsage;
}

/* Print the diagnostic records of a handle.  Connector/ODBC does not
   repeat the password in its messages.  */
static void
print_diag (const char *what, SQLSMALLINT type, SQLHANDLE handle)
{
  SQLCHAR state[6];
  SQLCHAR msg[SQL_MAX_MESSAGE_LENGTH];
  SQLINTEGER native;
  SQLSMALLINT len;
  SQLSMALLINT rec;

  for (rec = 1;
       SQL_SUCCEEDED (SQLGetDiagRecA (type, handle, rec, state, &native,
                                      msg, (SQLSMALLINT) sizeof (msg),
                                      &len));
       rec++)
    fprintf (stderr, "%s: [%s] (%ld) %s\n", what, (char *) state,
             (long) native, (char *) msg);
}

static void
wait_enter (const char *when)
{
  char line[16];

  printf ("%s: press Enter to continue\n", when);
  fflush (stdout);
  if (!fgets (line, sizeof (line), stdin))
    return;
}

/* Connect a new connection handle.  Returns SQL_NULL_HDBC on error.  */
static SQLHDBC
open_conn (SQLHENV env, const char *dsn, const char *user,
           const char *pwd, int luasql)
{
  SQLHDBC dbc = SQL_NULL_HDBC;
  SQLRETURN rc;

  rc = SQLAllocHandle (SQL_HANDLE_DBC, env, &dbc);
  if (!SQL_SUCCEEDED (rc))
    {
      print_diag ("SQLAllocHandle(DBC)", SQL_HANDLE_ENV, env);
      return SQL_NULL_HDBC;
    }
  rc = SQLConnectA (dbc, (SQLCHAR *) dsn, SQL_NTS, (SQLCHAR *) user,
                    SQL_NTS, (SQLCHAR *) pwd, SQL_NTS);
  if (!SQL_SUCCEEDED (rc))
    {
      print_diag ("SQLConnect", SQL_HANDLE_DBC, dbc);
      SQLFreeHandle (SQL_HANDLE_DBC, dbc);
      return SQL_NULL_HDBC;
    }
  if (luasql)
    {
      rc = SQLSetConnectAttrA (dbc, SQL_ATTR_AUTOCOMMIT,
                               (SQLPOINTER) SQL_AUTOCOMMIT_ON, 0);
      if (!SQL_SUCCEEDED (rc))
        print_diag ("SQLSetConnectAttr", SQL_HANDLE_DBC, dbc);
    }
  return dbc;
}

static void
close_conn (SQLHDBC dbc, int luasql)
{
  if (luasql)
    SQLEndTran (SQL_HANDLE_DBC, dbc, SQL_ROLLBACK);
  if (!SQL_SUCCEEDED (SQLDisconnect (dbc)))
    print_diag ("SQLDisconnect", SQL_HANDLE_DBC, dbc);
  SQLFreeHandle (SQL_HANDLE_DBC, dbc);
}

static void
usage (const char *prog)
{
  fprintf (stderr,
           "usage: %s DSN [-n COUNT] [-e EVERY] [-l] [-k] [-p]\n", prog);
}

int
main (int argc, char **argv)
{
  const char *dsn;
  const char *user = getenv ("MYSQL_TEST_USER");
  const char *pwd = getenv ("MYSQL_TEST_PASSWORD");
  long count = 20000;
  long every = 1000;
  int luasql = 0;
  int keep = 0;
  int pause = 0;
  SQLHENV env = SQL_NULL_HENV;
  SQLHDBC keeper = SQL_NULL_HDBC;
  SIZE_T base = 0;
  double sx = 0, sy = 0, sxx = 0, sxy = 0;
  long npts = 0;
  long i;
  int a;

  if (argc < 2 || argv[1][0] == '-')
    {
      usage (argv[0]);
      return 2;
    }
  dsn = argv[1];
  for (a = 2; a < argc; a++)
    {
      if (strcmp (argv[a], "-n") == 0 && a + 1 < argc)
        count = strtol (argv[++a], NULL, 10);
      else if (strcmp (argv[a], "-e") == 0 && a + 1 < argc)
        every = strtol (argv[++a], NULL, 10);
      else if (strcmp (argv[a], "-l") == 0)
        luasql = 1;
      else if (strcmp (argv[a], "-k") == 0)
        keep = 1;
      else if (strcmp (argv[a], "-p") == 0)
        pause = 1;
      else
        {
          usage (argv[0]);
          return 2;
        }
    }
  if (!user || !pwd)
    {
      fprintf (stderr, "set MYSQL_TEST_USER and MYSQL_TEST_PASSWORD\n");
      return 2;
    }
  if (every < 1)
    every = 1000;
  if (count < 2 * every)
    count = 2 * every;

  if (!SQL_SUCCEEDED (SQLAllocHandle (SQL_HANDLE_ENV, SQL_NULL_HANDLE,
                                      &env))
      || !SQL_SUCCEEDED (SQLSetEnvAttr (env, SQL_ATTR_ODBC_VERSION,
                                        (SQLPOINTER) SQL_OV_ODBC3, 0)))
    {
      fprintf (stderr, "cannot allocate the environment handle\n");
      return 1;
    }

  printf ("DSN %s, %ld connects, report every %ld%s%s\n", dsn, count,
          every, luasql ? ", luasql sequence" : "",
          keep ? ", one connection kept open" : "");

  if (keep)
    {
      keeper = open_conn (env, dsn, user, pwd, luasql);
      if (keeper == SQL_NULL_HDBC)
        return 1;
    }

  for (i = 1; i <= count; i++)
    {
      SQLHDBC dbc = open_conn (env, dsn, user, pwd, luasql);

      if (dbc == SQL_NULL_HDBC)
        {
          fprintf (stderr, "connect %ld failed\n", i);
          return 1;
        }
      close_conn (dbc, luasql);

      if (i % every == 0)
        {
          SIZE_T now = private_bytes ();

          if (i == every)
            {
              base = now;
              printf ("%8ld  private %10zu  (baseline)\n", i, now);
              fflush (stdout);
              if (pause)
                wait_enter ("after the baseline");
            }
          else
            {
              double x = (double) (i - every);
              double y = (double) now - (double) base;

              printf ("%8ld  private %10zu  %+10.0f  %+8.1f B/connect\n",
                      i, now, y, y / x);
              fflush (stdout);
            }
          /* least squares over all reports from the baseline on */
          {
            double x = (double) (i - every);
            double y = (double) now - (double) base;

            sx += x;
            sy += y;
            sxx += x * x;
            sxy += x * y;
            npts++;
          }
        }
    }

  if (npts > 1 && (npts * sxx - sx * sx) != 0)
    printf ("slope (least squares): %+.1f bytes per connect\n",
            (npts * sxy - sx * sy) / (npts * sxx - sx * sx));

  if (pause)
    wait_enter ("after the loop");

  if (keeper != SQL_NULL_HDBC)
    close_conn (keeper, luasql);
  SQLFreeHandle (SQL_HANDLE_ENV, env);
  return 0;
}
