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

Implement GTID tracking. #1633

Open
wants to merge 3 commits into
base: master
Choose a base branch
from

Conversation

arthurschreiber
Copy link

@arthurschreiber arthurschreiber commented Oct 2, 2024

Description

This implements GTID tracking when GTID mode is enabled on the server, TrackSessionState connection config is enabled, and session_track_gtids is set to either ALL_GTIDS or OWN_GTID.

To access the GTID, sql.Conn.Raw() has to be used like this:

conn, _ := db.Conn(ctx)
conn.Raw(func(conn any) error {
  ex := conn.(driver.Execer)
  res, err := ex.Exec(`UPDATE point SET x = 1 WHERE y = 2`, nil)
  log.Print(res.(mysql.Result).LastGTID())
})

There's also AllLastGTIDs on mysql.Result for use with multi-statement queries.

Checklist

  • Code compiles correctly
  • Created tests which fail without the change (if possible)
  • All tests passing
  • Extended the README / documentation, if necessary
  • Added myself / the copyright holder to the AUTHORS file

Summary by CodeRabbit

  • New Features

    • Introduced session state tracking for MySQL connections, allowing for better management of session attributes.
    • Added methods to access Global Transaction Identifiers (GTIDs) in the result interface, enhancing data retrieval capabilities.
  • Bug Fixes

    • Improved error handling for connection issues and malformed packets.
  • Tests

    • Added tests for GTID tracking and result state management to ensure reliability and correctness in handling multiple result sets.

Co-authored-by: Daniel Joos <[email protected]>
Copy link

coderabbitai bot commented Oct 2, 2024

Walkthrough

The changes introduce enhancements to the MySQL driver for Go, focusing on session tracking and GTID management. New constants for session tracking types are defined, and a boolean field TrackSessionState is added to the Config struct. The driver tests are expanded with functions to validate GTID tracking and result set handling. Modifications to packet handling logic improve session state management and error handling. Additionally, the Result interface is updated to include methods for accessing GTID information, thereby enriching the driver's functionality.

Changes

File Change Summary
const.go Added new constants for session tracking: sessionTrackSystemVariables, sessionTrackSchema, sessionTrackStateChange, sessionTrackGtids, sessionTrackTransactionCharacteristics, sessionTrackTransactionState.
driver_test.go Added test functions: TestGTIDTracking for GTID behavior verification and TestSkipResults for maintaining row state with ignored results.
dsn.go Added boolean field TrackSessionState to Config struct. Updated FormatDSN to include trackSessionState in DSN string and modified parseDSNParams to handle it.
packets.go Enhanced MySQL connection packet handling with session state tracking logic. Added TrackSessionState to client flags, updated okHandler for GTID storage, and refined error handling.
result.go Updated Result interface and mysqlResult struct with new methods: LastGTID() and AllLastGTIDs(), and added a field gtids []string to store GTIDs.

Poem

In the land of code, where rabbits hop,
New constants and tests make our hearts stop!
With GTIDs tracked and sessions in line,
Our MySQL driver is simply divine! 🐇✨
Let’s celebrate changes, both big and small,
In the world of Go, we’re having a ball!


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: 7

🧹 Outside diff range and nitpick comments (2)
result.go (1)

42-42: Add a comment for the gtids field in mysqlResult struct.

Consider adding a comment to explain the purpose of the gtids field to improve code readability and maintainability.

driver_test.go (1)

2621-2682: Modifying global server variables may affect other tests

Changing global server variables like gtid_mode and enforce_gtid_consistency within a test can impact other tests running concurrently or subsequently, leading to flaky or unpredictable test results. Consider isolating these changes by running the test in a separate environment or serializing tests that depend on global state.

📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL

📥 Commits

Files that changed from the base of the PR and between 00dc21a and 55420ba.

📒 Files selected for processing (5)
  • const.go (1 hunks)
  • driver_test.go (1 hunks)
  • dsn.go (3 hunks)
  • packets.go (5 hunks)
  • result.go (3 hunks)
🔇 Additional comments (10)
const.go (2)

191-199: Summary: New session tracking constants added

The changes in this file are focused on adding new constants for session tracking, including GTID tracking. These additions align well with the PR objectives and enhance the driver's capability to handle various session tracking types.

The new constants provide a solid foundation for implementing GTID tracking and other session-related features. Ensure that these constants are utilized effectively in the implementation of the GTID tracking functionality.


191-199: LGTM! Consider adding a descriptive comment.

The new session tracking constants are well-defined and align with the PR objectives. The use of iota is appropriate for this set of related constants.

Consider adding a comment above this constant block to explain its purpose and relation to MySQL session tracking types. For example:

// Session tracking types as defined by MySQL
// https://dev.mysql.com/doc/dev/mysql-server/latest/group__group__cs__session__track__type.html
const (
    sessionTrackSystemVariables = iota
    // ... (rest of the constants)
)

Let's verify if these constants are used correctly in the implementation:

✅ Verification successful

Verified:

The usage of sessionTrackGtids in packets.go is correct and aligns with the intended session tracking implementation.

🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Description: Check for the usage of new session tracking constants

# Test: Search for usage of session tracking constants
rg --type go -e 'sessionTrack\w+' -g '!const.go'

Length of output: 100

dsn.go (4)

73-73: LGTM: TrackSessionState field added correctly

The addition of the TrackSessionState boolean field to the Config struct is well-placed and properly documented. This aligns with the PR objective of implementing GTID tracking functionality.


327-330: LGTM: FormatDSN method updated correctly

The FormatDSN method has been properly updated to include the TrackSessionState parameter in the DSN string when it's set to true. The implementation is consistent with other boolean parameters and is correctly placed within the method.


589-595: LGTM: parseDSNParams function updated correctly

The parseDSNParams function has been properly updated to handle the "trackSessionState" parameter. The implementation is consistent with other boolean parameters, includes appropriate error handling, and maintains consistency with the FormatDSN method.


Line range hint 1-695: Overall assessment: GTID tracking implementation looks good

The changes made to implement GTID tracking functionality in the dsn.go file are well-executed and consistent. The new TrackSessionState field has been properly added to the Config struct, and the necessary updates have been made to the FormatDSN method and parseDSNParams function. These changes align well with the PR objectives and maintain the existing code style and patterns.

To further validate the implementation:

This script will help ensure that the new TrackSessionState field is being used correctly in other parts of the codebase, that DSN strings are being constructed properly with the new parameter, and that appropriate tests have been added for the new functionality.

✅ Verification successful

Verification Complete: GTID Tracking Implementation Confirmed

The TrackSessionState field is properly utilized in packets.go, DSN strings include the necessary parameter in driver_test.go, and relevant tests (TestGTIDTracking) have been added. All aspects align with the PR objectives and maintain codebase integrity.

🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Verify that the TrackSessionState field is used correctly throughout the codebase

# Check for any usage of TrackSessionState
echo "Checking for usage of TrackSessionState:"
rg --type go "TrackSessionState" --glob "!dsn.go"

# Check for any references to trackSessionState in DSN strings
echo "Checking for trackSessionState in DSN strings:"
rg --type go 'trackSessionState=true'

# Check for any new tests related to GTID tracking
echo "Checking for new GTID tracking tests:"
rg --type go "TestGTID" --glob "*_test.go"

Length of output: 583

packets.go (3)

293-295: Correctly enable session state tracking when configured

The addition of the clientSessionTrack flag when TrackSessionState is enabled ensures that the client can receive session state change information from the server as intended.


550-550: Initializing GTID slice for result tracking

Appending an empty string to mc.result.gtids in readResultSetHeaderPacket initializes the GTID slice properly, aligning the GTID tracking with each result set.


Line range hint 659-736: Verify the correctness of session state parsing in handleOkPacket

The implementation for parsing session state changes and extracting GTIDs appears thorough. However, please verify that the loop correctly processes all session state changes without misalignment.

To confirm the loop processes the session states accurately, you can run the following script:

This script checks that the handleOkPacket function contains the correct loop structure for parsing session state changes.

driver_test.go (1)

2621-2682: Handle insufficient privileges when changing global variables

Executing SET GLOBAL commands requires appropriate privileges. The test may fail if the user lacks these permissions. Consider adding checks to verify if the necessary privileges are available and skip the test or handle the error gracefully if they are not.

To confirm whether the current user has the required permissions, run the following script:

// LastGTID returns the GTID of the last result, if available.
LastGTID() (string, error)

// AllLastGTIDs returns a slice containing
Copy link

Choose a reason for hiding this comment

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

⚠️ Potential issue

Incomplete method comment for AllLastGTIDs().

The comment for AllLastGTIDs() is incomplete:

// AllLastGTIDs returns a slice containing

Please complete the comment to accurately describe what the method returns.

Comment on lines +53 to +55
func (res *mysqlResult) LastGTID() (string, error) {
return res.gtids[len(res.gtids)-1], nil
}
Copy link

Choose a reason for hiding this comment

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

⚠️ Potential issue

Potential panic in LastGTID() due to empty gtids slice.

If res.gtids is empty, accessing res.gtids[len(res.gtids)-1] will cause an index out of range panic.

Consider adding a check to ensure res.gtids is not empty before accessing the last element:

func (res *mysqlResult) LastGTID() (string, error) {
+	if len(res.gtids) == 0 {
+		return "", errors.New("no GTIDs available")
+	}
	return res.gtids[len(res.gtids)-1], nil
}

Alternatively, define the expected behavior when gtids is empty and handle it appropriately.

📝 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
func (res *mysqlResult) LastGTID() (string, error) {
return res.gtids[len(res.gtids)-1], nil
}
func (res *mysqlResult) LastGTID() (string, error) {
if len(res.gtids) == 0 {
return "", errors.New("no GTIDs available")
}
return res.gtids[len(res.gtids)-1], nil
}

Comment on lines +2693 to +2694
c := conn.(*mysqlConn)

Copy link

Choose a reason for hiding this comment

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

⚠️ Potential issue

Check type assertion when casting to *mysqlConn

The type assertion conn.(*mysqlConn) may panic if conn is not of the expected type. It's safer to check the assertion and handle the error gracefully.

Suggested fix:

-        c := conn.(*mysqlConn)
+        c, ok := conn.(*mysqlConn)
+        if !ok {
+            return fmt.Errorf("expected *mysqlConn, got %T", conn)
+        }
📝 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
c := conn.(*mysqlConn)
c, ok := conn.(*mysqlConn)
if !ok {
return fmt.Errorf("expected *mysqlConn, got %T", conn)
}

Comment on lines +2697 to +2726
t.Fatal(err)
}

gtid, err = res.(Result).LastGTID()
if err != nil {
t.Fatal(err)
}

if gtid != "" {
t.Fatalf("expected empty gtid, got %v", gtid)
}

_, err = c.Exec("SET SESSION session_track_gtids = ALL_GTIDS", nil)
if err != nil {
t.Fatal(err)
}

res, err = c.Exec("INSERT INTO test (value) VALUES ('a'), ('b')", nil)
if err != nil {
t.Fatal(err)
}

gtid, err = res.(Result).LastGTID()
if err != nil {
t.Fatal(err)
}

if gtid == "" {
t.Fatal("expected non-empty gtid")
}
Copy link

Choose a reason for hiding this comment

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

⚠️ Potential issue

Avoid calling t.Fatal inside conn.Raw callbacks

Calling t.Fatal inside the conn.Raw callback can cause unexpected behavior because it might not correctly terminate the test when called from a nested function. Instead, return the error from the callback and handle it after the conn.Raw call.

Suggested fix:

 conn.Raw(func(conn any) error {
     c, ok := conn.(*mysqlConn)
     if !ok {
         return fmt.Errorf("expected *mysqlConn, got %T", conn)
     }

     res, err := c.Exec("INSERT INTO test (value) VALUES ('a'), ('b')", nil)
     if err != nil {
-        t.Fatal(err)
+        return err
     }

     gtid, err = res.(Result).LastGTID()
     if err != nil {
-        t.Fatal(err)
+        return err
     }

     if gtid != "" {
-        t.Fatalf("expected empty gtid, got %v", gtid)
+        return fmt.Errorf("expected empty gtid, got %v", gtid)
     }

     _, err = c.Exec("SET SESSION session_track_gtids = ALL_GTIDS", nil)
     if err != nil {
-        t.Fatal(err)
+        return err
     }

     res, err = c.Exec("INSERT INTO test (value) VALUES ('a'), ('b')", nil)
     if err != nil {
-        t.Fatal(err)
+        return err
     }

     gtid, err = res.(Result).LastGTID()
     if err != nil {
-        t.Fatal(err)
+        return err
     }

     if gtid == "" {
-        t.Fatal("expected non-empty gtid")
+        return fmt.Errorf("expected non-empty gtid")
     }

     return nil
 })
+if err != nil {
+    t.Fatal(err)
+}

Committable suggestion was skipped due to low confidence.

Comment on lines +2642 to +2646
_, err := dbt.db.Exec("SET GLOBAL gtid_mode = OFF_PERMISSIVE")
if err != nil {
t.Fatalf("failed while trying to reset gtid_mode: %v", err)
}
}()
Copy link

Choose a reason for hiding this comment

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

⚠️ Potential issue

Avoid calling t.Fatalf inside deferred functions

Similar to the previous instance, replace t.Fatalf with t.Errorf inside deferred functions to prevent improper test termination.

Suggested fix:

 defer func() {
     _, err := dbt.db.Exec("SET GLOBAL gtid_mode = OFF_PERMISSIVE")
     if err != nil {
-        t.Fatalf("failed while trying to reset gtid_mode: %v", err)
+        t.Errorf("failed while trying to reset gtid_mode: %v", err)
     }
 }()
📝 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
_, err := dbt.db.Exec("SET GLOBAL gtid_mode = OFF_PERMISSIVE")
if err != nil {
t.Fatalf("failed while trying to reset gtid_mode: %v", err)
}
}()
_, err := dbt.db.Exec("SET GLOBAL gtid_mode = OFF_PERMISSIVE")
if err != nil {
t.Errorf("failed while trying to reset gtid_mode: %v", err)
}
}()

Comment on lines +2627 to +2631
_, err := dbt.db.Exec("SET GLOBAL gtid_mode = OFF")
if err != nil {
t.Fatalf("failed while trying to reset gtid_mode: %v", err)
}
}()
Copy link

Choose a reason for hiding this comment

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

⚠️ Potential issue

Avoid calling t.Fatalf inside deferred functions

Using t.Fatalf inside a deferred function can lead to unexpected behavior because it may not stop the test execution as intended. Instead, use t.Errorf to report the error and ensure the test fails by checking for errors after the deferred function executes.

Suggested fix:

 defer func() {
     _, err := dbt.db.Exec("SET GLOBAL gtid_mode = OFF")
     if err != nil {
-        t.Fatalf("failed while trying to reset gtid_mode: %v", err)
+        t.Errorf("failed while trying to reset gtid_mode: %v", err)
     }
 }()
📝 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
_, err := dbt.db.Exec("SET GLOBAL gtid_mode = OFF")
if err != nil {
t.Fatalf("failed while trying to reset gtid_mode: %v", err)
}
}()
_, err := dbt.db.Exec("SET GLOBAL gtid_mode = OFF")
if err != nil {
t.Errorf("failed while trying to reset gtid_mode: %v", err)
}
}()

Comment on lines +2675 to +2679
_, err := dbt.db.Exec("SET GLOBAL gtid_mode = ON_PERMISSIVE")
if err != nil {
t.Fatalf("failed while trying to reset gtid_mode: %v", err)
}
}()
Copy link

Choose a reason for hiding this comment

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

⚠️ Potential issue

Avoid calling t.Fatalf inside deferred functions

Using t.Fatalf in deferred functions can cause interference with the test flow. Replace it with t.Errorf and handle the error appropriately after the deferred function.

Suggested fix:

 defer func() {
     _, err := dbt.db.Exec("SET GLOBAL gtid_mode = ON_PERMISSIVE")
     if err != nil {
-        t.Fatalf("failed while trying to reset gtid_mode: %v", err)
+        t.Errorf("failed while trying to reset gtid_mode: %v", err)
     }
 }()
📝 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
_, err := dbt.db.Exec("SET GLOBAL gtid_mode = ON_PERMISSIVE")
if err != nil {
t.Fatalf("failed while trying to reset gtid_mode: %v", err)
}
}()
_, err := dbt.db.Exec("SET GLOBAL gtid_mode = ON_PERMISSIVE")
if err != nil {
t.Errorf("failed while trying to reset gtid_mode: %v", err)
}
}()

@methane
Copy link
Member

methane commented Oct 7, 2024

How important this feature is?

I want to implement compression protocol support in next version. I don't want to merge any new features until next version is released.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

Successfully merging this pull request may close these issues.

2 participants