Commit ac19703d authored by Grant, Josh's avatar Grant, Josh
Browse files

Merge branch 'feature/pymssql' into 'develop'

Feature/pymssql

See merge request nset-utilities/common-package!8
parents 736fc86f 3d2ccb72
Loading
Loading
Loading
Loading
+1 −0
Original line number Diff line number Diff line
@@ -7,6 +7,7 @@ services:
      - ./src/:/tmp/src
      - ./test/:/test/
    env_file:
      #- ./envfile_mssql
      - ./envfile
    #command: ["sh", "-c", "pytest --cov=common /test/test.py"]
    command: ["sh", "-c", "test-db-conn && pytest -v --cov=common /test/test.py"]
+31 −0
Original line number Diff line number Diff line
version: '3.7'

networks:
  com:

services:
  package:
    build: .
    volumes:
      - ./src/:/tmp/src
      - ./test/:/test/
    env_file:
      - ./envfile_mssql
    command: ["sh", "-c", "/test/mssql_test_server/test-mssql-conn && pytest -v --cov=common /test/test_mssql.py"]
    depends_on:
      - mssql
    networks:
      - com

  mssql:
    build: ./test/mssql_test_server
    environment:
      - ACCEPT_EULA=Y
      - SA_PASSWORD=5nowDog5
      - MSSQL_PID=Developer
    ports:
      - "1433:1433"
    networks:
      - com

  
 No newline at end of file

envfile_mssql

0 → 100644
+10 −0
Original line number Diff line number Diff line
DATABASE_HOST=mssql
DATABASE_DB=CommonDB
DATABASE_PORT=1433
DATABASE_USER=sa
DATABASE_PW=5nowDog5
DATABASE_TIMEOUT=60
DATABASE_LOG_FILE=/tmp/test.log
DATABASE_LOG_MODE=w
DATABASE_LOG_ENCODING=utf-8
LOGLEVEL=debug
 No newline at end of file
+67 −0
Original line number Diff line number Diff line
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""Allow opening with a pymssql connection."""

import pymssql
import traceback

class MSSQLMixin():
    """Provides a convenient API-like interface to Microsoft SQL databases.
    The database object is the interface to the database.
    """

    def __del__(self):
        """ Close the connection to database.
        Ensure function call is superior to Database i.e:
        class MSSQLDB(MSSQLMixin, Database):"""
        self.close()

    def open(self):
        """Open the connection to the database.
        :return: True if connection established, else false"""
        self.logger.debug('Opening Database Object')
        try:
            msg = "\nConnecting information\n" + \
                  f"Database: {self.connection_info['dbName']}\n" + \
                  f"Host: {self.connection_info['dbHost']}\n" + \
                      f"User: {self.connection_info['dbUser']}\n"
            self.logger.debug(msg)
            self.connection = pymssql.connect(
                database=self.connection_info['dbName'],
                user=self.connection_info['dbUser'],
                password=self.connection_info['dbPassword'],
                host=self.connection_info['dbHost'])
                #connect_timeout=self.connection_info['dbTimeout'])
                #application_name='ongpy')
            self.logger.debug('Successfully opened database connection')
            self.cursor = self.connection.cursor()
            self.logger.debug('Successfully created database cursor')
            # self.cur.execute("SET search_path TO covidb;")
            return True
        except pymssql.OperationalError as e:
            self.logger.error(f'Database error: {e}')
            return False

    def close(self):
        """Close the database connection. No logging. """
        if hasattr(self, 'cursor') and self.cursor is not None:
            self.cursor.close()
            self.cursor = None
        if hasattr(self, 'connnection') and self.connection is not None:
            self.connection.commit()
            self.connection.close()
            self.connection = None
        if hasattr(self, 'engine') and self.engine is not None:
            self.engine.dispose()

    def query(self, query):
        """Send a query to the database and retrieve the results."""
        self.logger.debug(f'Initiating query: {query}')
        try:
            self.cursor.execute(query)
            res = self.cursor.fetchall()
        except Exception as e:
            traceback.print_stack()
            self.logger.error(f'Problem querying database: {e}')
            res = None
        return res
+1 −0
Original line number Diff line number Diff line
rich==10.11.0
pandas==1.3.3
psycopg2-binary==2.9.1
pymssql==2.2.4
 No newline at end of file
Loading