Search code examples
databasematlabflat

Check if connection exists to a flat database in Matlab


I have used Postgres and love its way to handle the database connection. I have to use now Matlab and Physionet's flat database system to retrieve data. However, I do not understand the logic in some cases, like in ptbdb.

How can you check if a connection exists to a database in Matlab?

How can you monitor what the system is doing when connecting to the database? It would be very nice to be able to ping the system or something like that to know what is the problem. I get no information now what is the problem.


Solution

  • My connection was disconnected continuously because it was not secure. The topic is about secure connection between Matlab and PostgreSQL, which is undocumented widely, for instance, discussed here about Secure SSL connection between Matlab and PostgreSQL.

    Summary of the blog post

    Make appropriate changes in

    1. Generate certificate for the server; diseserver.csr, root.crt; postgreSQL directry (diseserver.key, diseserver.crt, and root.crt); please see more precisely here
    2. postgresql.conf
    3. pg_hba.conf
    4. generate client certificates
    5. convert key to pkcs8 format
    6. check correct version of JDBC driver
    7. check client certificate
    8. dbtest.m

    Certificate for the server

    $openssl req -out diseserver.csr -new -newkey rsa:2048 -nodes -keyout diseserver.key
    

    postgresql.conf

    ssl = on
    ssl_cert_file = 'diseserver.crt'  # (change requires restart)
    ssl_key_file  = 'diseserver.key'  # (change requires restart)
    ssl_ca_file   = 'root.crt'        # (change requires restart)
    

    pg_hba.conf

    hostnossl  all    all   0.0.0.0/0   reject
    hostssl  mytable  all   0.0.0.0/0   cert map=ssl clientcert=1
    

    Generate client certificates

    $mkdir ~/.postgresql
    $cd ~/.postgresql
    $openssl req -out postgresql.csr -new -newkey rsa:2048 -nodes -keyout postgresql.key
    

    Convert key to pkcs8 format

    $openssl pkcs8 -topk8 -inform PEM -outform DER -in postgresql.key -out postgresql.pk8 -nocrypt
    

    Check client certificate

    jdbc:postgresql://diseserver.mydomain.org/mytable?ssl=true&sslfactory=org.postgresql.ssl.jdbc4.LibPQFactory&sslmode=verify-full&
    

    dbtest.m matlab function

    function dbtest
       driver = 'org.postgresql.Driver';
       [~,username] = system('whoami');
       url = 'jdbc:postgresql://diseserver.mydomain.org/mytable?ssl=true&sslfactory=org.postgresql.ssl.jdbc4.LibPQFactory&sslmode=verify-full&';
       myconn = database('mytable', username, '', driver, url);
       if ~isempty(myconn.Message)
          fprintf(2,'%s\n', myconn.Message);
       else
          fprintf(1, 'Connected!\n');
       end
    end