Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

✨ added a --mysql-socket option to connect to MySQL using a Unix socket #129

Draft
wants to merge 4 commits into
base: master
Choose a base branch
from

Conversation

mackuba
Copy link
Contributor

@mackuba mackuba commented Oct 23, 2024

Description

This adds a --mysql-socket option to the CLI which passes a unix_socket parameter to the MySQL Connector, which lets you connect using a Unix socket instead of a TCP port.

Type of change

  • Bug fix (non-breaking change which fixes an issue)
  • New feature (non-breaking change which adds functionality)
  • Breaking change (fix or feature that would cause existing functionality to not work as expected)
  • This change requires a documentation update

How Has This Been Tested?

Tested with my local database with disabled networking (MacPorts default), with and without the option --mysql-socket /opt/local/var/run/mysql8/mysqld.sock.

Checklist:

  • My code follows the style guidelines of this project
  • I have performed a self-review of my own code
  • I have commented my code, particularly in hard-to-understand areas
  • I have made corresponding changes to the documentation
  • My changes generate no new warnings
  • I have added tests that prove my fix is effective or that my feature works
  • New and existing unit tests pass locally with my changes
  • Any dependent changes have been merged and published in downstream modules

Copy link

coderabbitai bot commented Oct 24, 2024

Important

Review skipped

Draft detected.

Please check the settings in the CodeRabbit UI or the .coderabbit.yaml file in this repository. To trigger a single review, invoke the @coderabbitai review command.

You can disable this status message by setting the reviews.review_status to false in the CodeRabbit configuration file.

Walkthrough

The changes introduced in this pull request add a new command-line option, --mysql-socket TEXT, to the sqlite3mysql tool, allowing users to specify the path to the MySQL Unix socket file. This update is reflected in the command-line interface, relevant documentation, and associated code, enhancing the tool's flexibility for MySQL database connections. The modifications include updates to the cli function, the SQLite3toMySQL class, and the documentation, ensuring that the new option is properly integrated and documented without altering existing functionalities.

Changes

File Change Summary
README.md, docs/README.rst Added new command-line option --mysql-socket TEXT for specifying MySQL Unix socket path.
src/sqlite3_to_mysql/cli.py Introduced --mysql-socket option in cli function and updated method signature accordingly.
src/sqlite3_to_mysql/transporter.py Added _mysql_socket instance variable to SQLite3toMySQL class for handling Unix socket in MySQL connection.
src/sqlite3_to_mysql/types.py Added mysql_socket field to SQLite3toMySQLParams and _mysql_socket attribute to SQLite3toMySQLAttributes.

Possibly related PRs

Poem

🐇 In the realm of code, a socket's new path,
A command-line option, to ease the user's math.
With --mysql-socket, connections now flow,
To MySQL's heart, where data can grow.
Hopping through changes, we celebrate bright,
A tool more flexible, oh what a delight! 🌟


Thank you for using CodeRabbit. We offer it for free to the OSS community and would appreciate your support in helping us grow. If you find it useful, would you consider giving us a shout-out on your favorite social media?

❤️ Share
🪧 Tips

Chat

There are 3 ways to chat with CodeRabbit:

  • Review comments: Directly reply to a review comment made by CodeRabbit. Example:
    • I pushed a fix in commit <commit_id>, please review it.
    • Generate unit testing code for this file.
    • Open a follow-up GitHub issue for this discussion.
  • Files and specific lines of code (under the "Files changed" tab): Tag @coderabbitai in a new review comment at the desired location with your query. Examples:
    • @coderabbitai generate unit testing code for this file.
    • @coderabbitai modularize this function.
  • PR comments: Tag @coderabbitai in a new PR comment to ask questions about the PR branch. For the best results, please provide a very specific query, as very limited context is provided in this mode. Examples:
    • @coderabbitai gather interesting stats about this repository and render them as a table. Additionally, render a pie chart showing the language distribution in the codebase.
    • @coderabbitai read src/utils.ts and generate unit testing code.
    • @coderabbitai read the files in the src/scheduler package and generate a class diagram using mermaid and a README in the markdown format.
    • @coderabbitai help me debug CodeRabbit configuration file.

Note: Be mindful of the bot's finite context window. It's strongly recommended to break down tasks such as reading entire modules into smaller chunks. For a focused discussion, use review comments to chat about specific files and their changes, instead of using the PR comments.

CodeRabbit Commands (Invoked using PR comments)

  • @coderabbitai pause to pause the reviews on a PR.
  • @coderabbitai resume to resume the paused reviews.
  • @coderabbitai review to trigger an incremental review. This is useful when automatic reviews are disabled for the repository.
  • @coderabbitai full review to do a full review from scratch and review all the files again.
  • @coderabbitai summary to regenerate the summary of the PR.
  • @coderabbitai resolve resolve all the CodeRabbit review comments.
  • @coderabbitai configuration to show the current CodeRabbit configuration for the repository.
  • @coderabbitai help to get help.

Other keywords and placeholders

  • Add @coderabbitai ignore anywhere in the PR description to prevent this PR from being reviewed.
  • Add @coderabbitai summary to generate the high-level summary at a specific location in the PR description.
  • Add @coderabbitai anywhere in the PR title to generate the title automatically.

CodeRabbit Configuration File (.coderabbit.yaml)

  • You can programmatically configure CodeRabbit by adding a .coderabbit.yaml file to the root of your repository.
  • Please see the configuration documentation for more information.
  • If your editor has YAML language server enabled, you can add the path at the top of this file to enable auto-completion and validation: # yaml-language-server: $schema=https://coderabbit.ai/integrations/schema.v2.json

Documentation and Community

  • Visit our Documentation for detailed information on how to use CodeRabbit.
  • Join our Discord Community to get help, request features, and share feedback.
  • Follow us on X/Twitter for updates and announcements.

Copy link

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 3

🧹 Outside diff range and nitpick comments (4)
docs/README.rst (2)

32-32: Documentation needs more details about the socket option.

Whilst the basic documentation is correct, consider enhancing it with:

  • A brief description of when to use socket connections
  • The default socket path if any
  • Example usage in the command-line examples section

Apply this diff to improve the documentation:

-- ``--mysql-socket TEXT``: Path to MySQL unix socket file.
+- ``--mysql-socket TEXT``: Path to MySQL Unix socket file (e.g., '/var/run/mysqld/mysqld.sock'). Use this instead of host/port for local connections with better performance. Common paths include '/tmp/mysql.sock' on macOS and '/var/run/mysqld/mysqld.sock' on Linux.

32-32: Update Docker documentation for socket connections.

The Docker section should explain how to use Unix sockets, as it requires additional volume mounting.

Add this section after the existing Docker example:

+Socket Connections in Docker
+'''''''''''''''''''''''''''
+
+To use MySQL socket connections with Docker, you need to mount the socket file from the host:
+
+.. code:: bash
+
+   docker run -it \
+       --workdir $(pwd) \
+       --volume $(pwd):$(pwd) \
+       --volume /var/run/mysqld/mysqld.sock:/var/run/mysqld/mysqld.sock \
+       --rm ghcr.io/techouse/sqlite3-to-mysql:latest \
+       --sqlite-file baz.db \
+       --mysql-user foo \
+       --mysql-password bar \
+       --mysql-database baz \
+       --mysql-socket /var/run/mysqld/mysqld.sock
+
+Note: The socket path may vary depending on your MySQL installation and operating system.
README.md (1)

54-54: Documentation could be more comprehensive

The addition of the --mysql-socket option is well-placed and formatted consistently. However, consider enhancing the documentation with:

  1. Default behaviour (if any)
  2. Platform-specific information (Unix/Linux systems only)
  3. Example usage in the command-line examples section

Apply this diff to enhance the documentation:

-  --mysql-socket TEXT             Path to MySQL unix socket file.
+  --mysql-socket TEXT             Path to MySQL Unix socket file. Only available
+                                  on Unix-like systems. Takes precedence over
+                                  host/port if specified.

Consider adding this example to the usage section:

# Connect using Unix socket
sqlite3mysql -f database.db -d mydb -u myuser --mysql-socket /var/run/mysqld/mysqld.sock
src/sqlite3_to_mysql/cli.py (1)

65-65: Enhance the --mysql-socket option documentation and validation

The help text could be more descriptive. Consider expanding it to clarify:

  • This is specifically for Unix socket connections
  • Common socket path locations
  • That this is an alternative to host/port connection

Consider updating the help text:

-@click.option("--mysql-socket", default=None, help="Path to MySQL unix socket file.")
+@click.option("--mysql-socket", default=None, help="Path to MySQL Unix socket file (e.g., /var/run/mysqld/mysqld.sock). When specified, takes precedence over host/port.")
📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL

📥 Commits

Files that changed from the base of the PR and between d5e5626 and 25a9cd7.

📒 Files selected for processing (5)
  • README.md (1 hunks)
  • docs/README.rst (1 hunks)
  • src/sqlite3_to_mysql/cli.py (3 hunks)
  • src/sqlite3_to_mysql/transporter.py (2 hunks)
  • src/sqlite3_to_mysql/types.py (2 hunks)
🔇 Additional comments (4)
src/sqlite3_to_mysql/types.py (2)

23-23: LGTM: Proper type annotation for MySQL socket parameter

The mysql_socket parameter is correctly typed as Optional[str] and well-positioned amongst other connection-related parameters.


23-23: Verify socket parameter handling in connection logic

Let's ensure the socket parameter is properly handled in the connection establishment code.

Also applies to: 53-53

✅ Verification successful

Based on the search results, I can see that the MySQL socket parameter (unix_socket) is properly handled in the connection logic within src/sqlite3_to_mysql/transporter.py. Specifically, it's used in the MySQL connection setup:

_mysql_connection = mysql.connector.connect(
    user=self._mysql_user,
    password=self._mysql_password,
    host=self._mysql_host,
    port=self._mysql_port,
    unix_socket=self._mysql_socket,  # Socket parameter is properly used here
    ssl_disabled=self._mysql_ssl_disabled,
    use_pure=True,
    charset=self._mysql_charset,
    collation=self._mysql_collation,
)

Socket parameter is properly handled in MySQL connection logic

The mysql_socket parameter from the configuration is correctly passed through to the MySQL connector's connection setup as unix_socket.

🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Description: Check how the socket parameter is used in connection logic

# Search for MySQL connection setup code
rg -A 10 "MySQLConnection|connect" src/

Length of output: 16993

src/sqlite3_to_mysql/cli.py (1)

188-188: Add validation for MySQL socket configuration

Consider adding validation to handle these scenarios:

  1. Verify socket file existence before attempting connection
  2. Clarify behaviour when both socket and host/port are specified
  3. Add warning logs for unused connection parameters

Let's check if similar validation exists in other files:

Consider adding validation before instantiation:

if mysql_socket and not os.path.exists(mysql_socket):
    raise click.ClickException(f"MySQL socket file not found: {mysql_socket}")

if mysql_socket and (mysql_host != "localhost" or mysql_port != 3306):
    click.echo("Warning: MySQL socket connection will ignore host/port settings")
src/sqlite3_to_mysql/transporter.py (1)

77-78: LGTM! Clean implementation of the socket path handling.

The implementation properly handles type conversion and fallback to None, following the class's naming conventions.

@@ -49,6 +50,7 @@ class SQLite3toMySQLAttributes:
_mysql_password: t.Optional[str]
_mysql_host: str
_mysql_port: int
_mysql_socket: str
Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

⚠️ Potential issue

Type inconsistency between parameter and attribute definitions

The mysql_socket is defined as Optional[str] in SQLite3toMySQLParams but as a required str in SQLite3toMySQLAttributes. This could lead to runtime errors if the socket parameter isn't provided.

Apply this change to maintain consistency:

-    _mysql_socket: str
+    _mysql_socket: t.Optional[str]
📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
_mysql_socket: str
_mysql_socket: t.Optional[str]

@@ -137,6 +138,7 @@ def cli(
mysql_database: str,
mysql_host: str,
mysql_port: int,
mysql_socket: str,
Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

⚠️ Potential issue

Update type annotation for mysql_socket parameter

The parameter should be marked as optional since it has a None default value.

-    mysql_socket: str,
+    mysql_socket: t.Optional[str],
📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
mysql_socket: str,
mysql_socket: t.Optional[str],

@@ -143,6 +145,7 @@ def __init__(self, **kwargs: tx.Unpack[SQLite3toMySQLParams]):
password=self._mysql_password,
host=self._mysql_host,
port=self._mysql_port,
unix_socket=self._mysql_socket,
Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🛠️ Refactor suggestion

Consider adding socket path validation.

While the implementation is correct, consider validating the socket path's existence before attempting the connection to provide a more user-friendly error message.

+                unix_socket=(
+                    self._mysql_socket
+                    if self._mysql_socket and os.path.exists(self._mysql_socket)
+                    else None
+                ),
-                unix_socket=self._mysql_socket,

This change would help users identify socket path issues before MySQL Connector attempts the connection.

📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
unix_socket=self._mysql_socket,
unix_socket=(
self._mysql_socket
if self._mysql_socket and os.path.exists(self._mysql_socket)
else None
),

@techouse
Copy link
Owner

Good idea 😇

Could you please look at the comments CodeRabbit made? They seem quite valid.

Also, since this is a new feature, could you please add some tests?

@techouse techouse self-assigned this Oct 24, 2024
@techouse techouse added the enhancement New feature or request label Oct 24, 2024
@techouse techouse changed the title added a --mysql-socket option to connect to MySQL using a Unix socket ✨ added a --mysql-socket option to connect to MySQL using a Unix socket Oct 24, 2024
@techouse techouse marked this pull request as draft October 26, 2024 12:51
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
enhancement New feature or request
Projects
None yet
Development

Successfully merging this pull request may close these issues.

2 participants