From 94447c9d587d222080ef6b7a8f6dd6e95cde0128 Mon Sep 17 00:00:00 2001 From: gab Date: Wed, 11 Nov 2026 09:19:57 -0500 Subject: [PATCH] Modernize packaging, CI and tests; release 1.4 - Replace setup.py with pyproject.toml; drop pypandoc build dependency and unused/stdlib deps (PyYAML, argparse); require Python >= 3.10 - CI: test Python 3.10-3.14 against MySQL 8.4 / PostgreSQL 17 service containers, bump actions, use codecov-action, add build + twine check job - Remove stdout temp files after printing (query data was left in /tmp) - Use pymysql `database=` instead of deprecated `db=` - Tests: enable never-collected cursor tests, fix hardcoded home dir, close connections/files, use temp dirs, add main() and JSON coverage Co-Authored-By: Claude Opus 5.5 --- .coveragerc | 7 +-- .github/workflows/ci.yml | 110 ++++++++++++++++++++------------- pyproject.toml | 43 +++++++++++++ setup.py | 36 ----------- src/sql2csv.py | 15 +++-- src/unittest/test_sql2csv.py | 116 ++++++++++++++++++++++++++++++----- 6 files changed, 222 insertions(+), 105 deletions(-) create mode 100644 pyproject.toml delete mode 100644 setup.py diff --git a/.coveragerc b/.coveragerc index 0584985..a6af4a4 100644 --- a/.coveragerc +++ b/.coveragerc @@ -1,12 +1,9 @@ [run] -source=sql2csv +source = src [report] omit = - setup.py src/__main__.py src/unittest/* - venv/* exclude_lines = - if __name__ == '__main__': - main() + if __name__ == .__main__.: diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index 856b59f..fe4845a 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -1,65 +1,89 @@ name: CI -on: [push, pull_request] +on: + push: + branches: [main] + pull_request: + +permissions: + contents: read jobs: - build: + test: runs-on: ubuntu-latest strategy: + fail-fast: false matrix: - python-version: ['3.7', '3.8', '3.9'] + python-version: ['3.10', '3.11', '3.12', '3.13', '3.14'] + + services: + mysql: + image: mysql:8.4 + env: + MYSQL_ROOT_PASSWORD: root + MYSQL_DATABASE: my_db + ports: + - 3306:3306 + options: >- + --health-cmd="mysqladmin ping -h 127.0.0.1 -proot" + --health-interval=5s --health-timeout=5s --health-retries=20 + postgres: + image: postgres:17 + env: + POSTGRES_USER: db_user + POSTGRES_PASSWORD: db_password + POSTGRES_DB: my_db + ports: + - 5432:5432 + options: >- + --health-cmd="pg_isready -U db_user" + --health-interval=5s --health-timeout=5s --health-retries=20 steps: - - uses: actions/checkout@v2 + - uses: actions/checkout@v5 - name: Set up Python - uses: actions/setup-python@v2 + uses: actions/setup-python@v6 with: python-version: ${{ matrix.python-version }} - architecture: x64 - - name: Display Python version - run: python -c "import sys; print(sys.version)" - - name: Set up MySQL - run: | - sudo systemctl start mysql.service - mysql -e 'CREATE DATABASE my_db;' -uroot -proot - - name: Import MySQL schemas - run: | - mysql my_db -uroot -proot < schema/mysql.sql - - name: Start PostgreSQL - run: | - sudo systemctl start postgresql.service - pg_isready - - name: Create PostgreSQL user - run: | - sudo -u postgres psql --command="CREATE USER db_user PASSWORD 'db_password'" --command="\du" - - name: Create PostgreSQL database - run: | - sudo -u postgres createdb --owner=db_user my_db + - name: Import MySQL schema + run: mysql -h 127.0.0.1 -uroot -proot my_db < schema/mysql.sql - name: Import PostgreSQL schema - run: | - psql -h localhost -f schema/postgresql.sql -d my_db -U db_user + run: psql -h 127.0.0.1 -U db_user -d my_db -f schema/postgresql.sql env: PGPASSWORD: db_password - - name: Install deb dependencies - run: | - sudo apt update - sudo apt install pandoc - name: Install dependencies run: | - pip install -U pip - pip install pycodestyle coverage pytest pypandoc - python setup.py install + python -m pip install -U pip + python -m pip install pycodestyle coverage pytest + python -m pip install . - name: Run pycodestyle - run: | - pycodestyle --exclude=venv --ignore=E501 . + run: pycodestyle --exclude=venv,build --ignore=E501 src - name: Run pytest - run: | - coverage run --source=. -m pytest - - name: Generate coverage report + run: coverage run -m pytest + - name: Coverage report run: | coverage report -m - - name: Upload coverage reports to Codecov + coverage xml + - name: Upload coverage to Codecov + if: matrix.python-version == '3.14' + uses: codecov/codecov-action@v5 + with: + files: coverage.xml + token: ${{ secrets.CODECOV_TOKEN }} + + build: + runs-on: ubuntu-latest + steps: + - uses: actions/checkout@v5 + - uses: actions/setup-python@v6 + with: + python-version: '3.14' + - name: Build sdist and wheel run: | - curl -Os https://uploader.codecov.io/latest/linux/codecov - chmod +x codecov - ./codecov -t ${CODECOV_TOKEN} + python -m pip install -U build twine + python -m build + twine check --strict dist/* + - uses: actions/upload-artifact@v4 + with: + name: dist + path: dist/ diff --git a/pyproject.toml b/pyproject.toml new file mode 100644 index 0000000..f176a18 --- /dev/null +++ b/pyproject.toml @@ -0,0 +1,43 @@ +[build-system] +requires = ["setuptools>=77"] +build-backend = "setuptools.build_meta" + +[project] +name = "sql2csv" +version = "1.4" +description = "Run MySQL and PostgreSQL queries and store result in CSV" +readme = "README.md" +license = "MIT" +license-files = ["LICENSE"] +authors = [{ name = "Gabriel Bordeaux", email = "pypi@gab.lc" }] +requires-python = ">=3.10" +dependencies = [ + "PyMySQL>=1.1", + "psycopg2-binary>=2.9.10", +] +classifiers = [ + "Topic :: Database", + "Topic :: Database :: Database Engines/Servers", + "Operating System :: MacOS", + "Operating System :: POSIX :: Linux", + "Natural Language :: English", + "Programming Language :: Python", + "Programming Language :: Python :: 3", + "Programming Language :: Python :: 3 :: Only", + "Programming Language :: Python :: 3.10", + "Programming Language :: Python :: 3.11", + "Programming Language :: Python :: 3.12", + "Programming Language :: Python :: 3.13", + "Programming Language :: Python :: 3.14", + "Development Status :: 4 - Beta", +] + +[project.urls] +Homepage = "https://github.com/gabfl/sql2csv" + +[project.scripts] +sql2csv = "sql2csv.sql2csv:main" + +[tool.setuptools] +packages = ["sql2csv"] +package-dir = { "sql2csv" = "src" } diff --git a/setup.py b/setup.py deleted file mode 100644 index 273e7ce..0000000 --- a/setup.py +++ /dev/null @@ -1,36 +0,0 @@ -from setuptools import setup - -import pypandoc - -setup( - name='sql2csv', - version='1.3', - description='Run MySQL and PostgreSQL queries and store result in CSV', - long_description=pypandoc.convert_file('README.md', 'rst'), - author='Gabriel Bordeaux', - author_email='pypi@gab.lc', - url='https://github.com/gabfl/sql2csv', - license='MIT', - packages=['sql2csv'], - package_dir={'sql2csv': 'src'}, - install_requires=['argparse', 'PyYAML', 'pymysql', - 'psycopg2-binary'], # external dependencies - entry_points={ - 'console_scripts': [ - 'sql2csv = sql2csv.sql2csv:main', - ], - }, - classifiers=[ # see https://pypi.python.org/pypi?%3Aaction=list_classifiers - 'Topic :: Database', - 'Topic :: Database :: Database Engines/Servers', - 'License :: OSI Approved :: MIT License', - 'Operating System :: MacOS', - 'Operating System :: POSIX :: Linux', - 'Natural Language :: English', - # 'Programming Language :: Python :: 2.7', - 'Programming Language :: Python :: 3', - 'Programming Language :: Python', - 'Development Status :: 4 - Beta', - # 'Development Status :: 5 - Production/Stable', - ], -) diff --git a/src/sql2csv.py b/src/sql2csv.py index a85dbca..0a3033d 100644 --- a/src/sql2csv.py +++ b/src/sql2csv.py @@ -3,6 +3,7 @@ import sys import csv import tempfile +import os from os.path import expanduser import json @@ -22,7 +23,7 @@ def get_mysql_connection(host, user, port, password, database): user=user, port=port, password=password, - db=database, + database=database, charset='utf8mb4', client_flag=pymysql.constants.CLIENT.MULTI_STATEMENTS ) @@ -173,12 +174,16 @@ def get_writer(file_, delimiter=',', quotechar='"'): ) -def file_to_stdout(): +def file_to_stdout(remove=False): """ Print file content to stdout """ with open(file_.name) as f: print(f.read()) + # Remove the temporary file once it has been printed + if remove: + os.remove(file_.name) + def stdin_to_csv(delimiter=',', quotechar='"'): """ Parse stdin and return output in a CSV format """ @@ -190,8 +195,6 @@ def stdin_to_csv(delimiter=',', quotechar='"'): # Parse lines and add to file separator = None for line in sys.stdin: - # Strip whitespaces - line.strip() if not discard_line(line): # Get column separator @@ -211,7 +214,7 @@ def stdin_to_csv(delimiter=',', quotechar='"'): # Write row writer.writerow(row) - file_to_stdout() + file_to_stdout(remove=True) def query_to_csv(engine, host, user, port, password, database, query, headers=False, out_type='stdout', destination_file=None, delimiter=',', quotechar='"', print_info=1000): @@ -261,7 +264,7 @@ def query_to_csv(engine, host, user, port, password, database, query, headers=Fa # Print stdout if out_type == 'stdout': - file_to_stdout() + file_to_stdout(remove=True) def main(): diff --git a/src/unittest/test_sql2csv.py b/src/unittest/test_sql2csv.py index 9a1d9a0..c0cb4a6 100644 --- a/src/unittest/test_sql2csv.py +++ b/src/unittest/test_sql2csv.py @@ -1,7 +1,9 @@ import unittest import _io +import os import tempfile import sys +from os.path import expanduser from unittest.mock import patch from io import StringIO @@ -39,7 +41,7 @@ def get_connection(self, engine): ] # Get database connection - return sql2csv.get_connection( + connection = sql2csv.get_connection( engine=engine, host=db_config['host'], user=db_config['user'], @@ -47,6 +49,14 @@ def get_connection(self, engine): password=db_config['password'], database=db_config['db'] ) + self.addCleanup(connection.close) + + return connection + + def setUp(self): + tmp_dir = tempfile.TemporaryDirectory() + self.addCleanup(tmp_dir.cleanup) + self.tmp_dir = tmp_dir.name def test_get_mysql_connection(self): db_config = self.db_configs['mysql'] @@ -54,6 +64,7 @@ def test_get_mysql_connection(self): # Get database connection connection = sql2csv.get_mysql_connection( db_config['host'], db_config['user'], db_config['port'], db_config['password'], db_config['db']) + self.addCleanup(connection.close) self.assertIsInstance(connection, pymysql.connections.Connection) @@ -68,6 +79,7 @@ def test_get_pg_connection(self): password=db_config['password'], database=db_config['db'] ) + self.addCleanup(connection.close) self.assertIsInstance(connection, psycopg2.extensions.connection) @@ -101,7 +113,7 @@ def test_get_connection_engine_invalid_engine(self): database=db_config['db'] ) - def get_cursor_mysql(self): + def test_get_cursor_mysql(self): # Get database connection connection = self.get_connection( engine='mysql' @@ -111,7 +123,7 @@ def get_cursor_mysql(self): self.assertIsInstance(cursor, pymysql.cursors.Cursor) - def get_cursor_postgresql(self): + def test_get_cursor_postgresql(self): # Get database connection connection = self.get_connection( engine='postgresql' @@ -220,21 +232,26 @@ def test_has_stdin_input_2(self): def test_resolve_home_dir(self): assert sql2csv.resolve_home_dir('/tmp/file') == '/tmp/file' - assert sql2csv.resolve_home_dir('~/file') == '/home/runner/file' + assert sql2csv.resolve_home_dir('~/file') == expanduser('~') + '/file' def test_open_file(self): - self.assertIsInstance(sql2csv.open_file( - '/tmp/file1'), _io.TextIOWrapper) + with sql2csv.open_file(os.path.join(self.tmp_dir, 'file1')) as file_: + self.assertIsInstance(file_, _io.TextIOWrapper) def test_open_tempfile(self): - self.assertIsInstance(sql2csv.open_tempfile(), - tempfile._TemporaryFileWrapper) + with sql2csv.open_tempfile() as file_: + self.addCleanup(os.remove, file_.name) + self.assertIsInstance(file_, tempfile._TemporaryFileWrapper) def test_get_writer(self): - file_ = sql2csv.open_tempfile() - writer = sql2csv.get_writer(file_) + with sql2csv.open_tempfile() as file_: + self.addCleanup(os.remove, file_.name) + writer = sql2csv.get_writer(file_, delimiter=';') + writer.writerow(['a', 'b;c']) + file_.flush() - self.assertIsInstance(writer, object) + with open(file_.name) as f: + assert f.read() == 'a;"b;c"\n' def test_file_to_stdout(self): with tempfile.NamedTemporaryFile(mode='w+', newline='') as file_: @@ -273,7 +290,6 @@ def test_stdin_to_csv(self): sql2csv.stdin_to_csv() output = out.getvalue().strip() - print(output) assert output == """id,some_int,some_str,some_date 1,12,hello world,2018-12-01 12:23:12 2,15,hello,2018-12-05 12:18:12 @@ -284,7 +300,7 @@ def test_stdin_to_csv(self): def test_query_to_csv_mysql(self): db_config = self.db_configs['mysql'] - dest_file = '/tmp/file2' + dest_file = os.path.join(self.tmp_dir, 'file2.csv') sql2csv.query_to_csv( engine='mysql', @@ -311,7 +327,7 @@ def test_query_to_csv_mysql(self): def test_query_to_csv_mysql_headers(self): db_config = self.db_configs['mysql'] - dest_file = '/tmp/file2' + dest_file = os.path.join(self.tmp_dir, 'file2.csv') sql2csv.query_to_csv( engine='mysql', @@ -340,7 +356,7 @@ def test_query_to_csv_mysql_headers(self): def test_query_to_csv_postgresql(self): db_config = self.db_configs['pg'] - dest_file = '/tmp/file2' + dest_file = os.path.join(self.tmp_dir, 'file2.csv') sql2csv.query_to_csv( engine='postgresql', @@ -390,3 +406,73 @@ def test_query_to_csv_stdout(self): 3,18,world,2018-12-08 12:17:12""" finally: sys.stdout = saved_stdout + + def test_file_to_stdout_remove(self): + path = os.path.join(self.tmp_dir, 'file3') + with open(path, 'w') as f: + f.write('some line') + + with patch('sys.stdout', new_callable=StringIO) as out: + with open(path) as file_: + sql2csv.file_ = file_ + sql2csv.file_to_stdout(remove=True) + + assert out.getvalue().strip() == 'some line' + assert not os.path.exists(path) + + def test_main_stdin(self): + with patch('sys.stdin', StringIO("a\tb\n1\t2\n")), \ + patch('sys.argv', ['sql2csv', '-D', ';']), \ + patch('sys.stdout', new_callable=StringIO) as out: + sql2csv.main() + + assert out.getvalue().strip() == 'a;b\n1;2' + + @patch.object(sql2csv, 'has_stdin_input', return_value=False) + @patch.object(sql2csv, 'query_to_csv') + def test_main_args_mysql(self, mocked_query_to_csv, mocked_stdin): + with patch('sys.argv', ['sql2csv', '-u', 'root', '-d', 'my_db', + '-q', 'SELECT 1']): + sql2csv.main() + + mocked_query_to_csv.assert_called_once_with( + engine='mysql', host='127.0.0.1', user='root', port=3306, + password='', database='my_db', query='SELECT 1', headers=False, + out_type='stdout', destination_file=None, delimiter=',', + quotechar='"' + ) + + @patch.object(sql2csv, 'has_stdin_input', return_value=False) + @patch.object(sql2csv, 'query_to_csv') + def test_main_args_postgresql_file(self, mocked_query_to_csv, mocked_stdin): + with patch('sys.argv', ['sql2csv', '-e', 'postgresql', '-u', 'db_user', + '-d', 'my_db', '-q', 'SELECT 1', '-t', + '-f', 'out.csv']): + sql2csv.main() + + kwargs = mocked_query_to_csv.call_args.kwargs + assert kwargs['engine'] == 'postgresql' + assert kwargs['port'] == 5432 + assert kwargs['headers'] is True + assert kwargs['out_type'] == 'file' + assert kwargs['destination_file'] == 'out.csv' + + def test_query_to_csv_postgresql_json(self): + db_config = self.db_configs['pg'] + dest_file = os.path.join(self.tmp_dir, 'file4.csv') + + sql2csv.query_to_csv( + engine='postgresql', + host=db_config['host'], + user=db_config['user'], + port=db_config['port'], + password=db_config['password'], + database=db_config['db'], + query="""SELECT 1 AS id, '{"a": 1}'::jsonb AS data""", + headers=True, + out_type='file', + destination_file=dest_file + ) + + with open(dest_file, 'r', newline='') as content_file: + assert content_file.read() == 'id,data\r\n1,"{""a"": 1}"\r\n'