Product Help

Systems Connectivity

This project provides a Go-based library for connecting to and querying multiple database types, including PostgreSQL, MySQL, SQLite, and SQL Server. It features a SystemDatabase struct to manage database connections and execute queries, with an output format defined by the OutputData struct for agnostic key-value pair handling.

Table of Contents

  1. Installation

  2. Usage

  3. Code Structure

  4. Database Support

Installation

  1. Ensure Go is installed on your system (1.16+ recommended).

  2. Install required dependencies:

    go mod tidy
  3. Import the library in your Go project:

    get "github.com/jvetereaoh/systemsConnectivity/v2"

Usage

Initialize a Database Connection

To connect to a database, provide a context and credentials using the CreateSystemDatabase function:

ctx := context.Background() credentials := map[string]string{ "username": "postgres", "password": "password", "name": "testdb", "host": "localhost", "port": "5432", "sslmode": "disable", "type": "postgres", } db, err := systemDatabase.CreateSystemDatabase(ctx, credentials) if err != nil { log.Fatal("Failed to create database:", err) } defer db.Close()

Setting and Executing Queries

You can set a query and retrieve results using Select. The results are returned as a slice of OutputData, where each row is stored as a key-value map.

db.SetQuery("SELECT * FROM test_table") results, err := db.Select() if err != nil { log.Fatal("Failed to execute select query:", err) } for _, row := range results { fmt.Println("Name:", row.Get("name")) fmt.Println("Email:", row.Get("email")) }

Code Structure

  • SystemDatabase (in systemDatabase package): Manages database connections and queries.

    • CreateSystemDatabase(ctx context.Context, credentials map[string]string): Establishes a database connection.

    • Close(): Closes the database connection.

    • SetQuery(query string): Sets the SQL query to execute.

    • Select() ([]data.OutputData, error): Executes the query and returns the result as a slice of OutputData.

  • OutputData (in data package): A flexible struct for storing query results as key-value pairs.

    • NewOutputData(): Initializes OutputData.

    • Get(key string): Retrieves the value for a given key.

    • Set(key, value string): Sets a key-value pair in the OutputData.

Database Support

Supported databases include:

  • PostgreSQL (postgres): Uses github.com/lib/pq driver.

  • MySQL (mysql): Requires github.com/go-sql-driver/mysql driver.

  • SQLite (sqlite3): Uses github.com/mattn/go-sqlite3.

Last modified: 28 January 2025