### LazySQL CLI Examples Source: https://github.com/jorgerojas26/lazysql/blob/main/_autodocs/README.md Examples of using the lazysql command-line interface with custom configurations, direct database connections, and logging. ```bash # Use custom config lazysql -config ~/my_config.toml ``` ```bash # Connect directly to database lazysql postgres://localhost/mydb ``` ```bash # Debug mode with logging lazysql -loglevel debug -logfile /tmp/lazysql.log ``` -------------------------------- ### Connection URL Examples Source: https://github.com/jorgerojas26/lazysql/blob/main/_autodocs/configuration.md Examples of various database connection URLs supported, including different providers and parameters. ```text postgres://user:pass@localhost/dbname pg://user:pass@localhost/dbname?sslmode=disable mysql://user:pass@localhost/dbname mysql:/var/run/mysqld/mysqld.sock sqlserver://user:pass@remote-host.com/dbname mssql://user:pass@remote-host.com/instance/dbname ms://user:pass@remote-host.com:port/instance/dbname?keepAlive=10 file:myfile.sqlite3?loc=auto /path/to/sqlite/file/test.db ``` -------------------------------- ### Example Connection URLs for Databases Source: https://github.com/jorgerojas26/lazysql/blob/main/README.md These examples demonstrate connection URL formats for PostgreSQL, MySQL, SQL Server, Oracle, SAP, SQLite, and ODBC. ```plaintext postgres://user:pass@localhost/dbname pg://user:pass@localhost/dbname?sslmode=disable mysql://user:pass@localhost/dbname mysql:/var/run/mysqld/mysqld.sock sqlserver://user:pass@remote-host.com/dbname mssql://user:pass@remote-host.com/instance/dbname ms://user:pass@remote-host.com:port/instance/dbname?keepAlive=10 oracle://user:pass@somehost.com/sid sap://user:pass@localhost/dbname file:myfile.sqlite3?loc=auto /path/to/sqlite/file/test.db odbc+postgres://user:pass@localhost:port/dbname?option1= ``` -------------------------------- ### Key Examples Source: https://github.com/jorgerojas26/lazysql/blob/main/_autodocs/types.md Illustrates how to create Key structs for different types of input, including letters, Enter, and Ctrl+S. ```go Key{Char: 'q'} ``` ```go Key{Code: tcell.KeyEnter} ``` ```go Key{Code: tcell.KeyCtrlS} ``` -------------------------------- ### Complete Global Configuration Example Source: https://github.com/jorgerojas26/lazysql/blob/main/_autodocs/configuration.md This TOML snippet shows all available configuration options for application settings, database connections, and keymaps. ```toml [application] DefaultPageSize = 500 DisableSidebar = false SidebarOverlay = false MaxQueryHistoryPerConnection = 150 TreeWidth = 35 JSONViewerWordWrap = true EnterOpensJSONViewer = false ConfirmOnQuit = true [[database]] Name = 'Local Development' Provider = 'postgres' URL = 'postgres://postgres:password@localhost:5432/dev_db' ReadOnly = false [[database]] Name = 'Production (Read-Only)' Provider = 'postgres' URL = 'postgres://${env:PROD_USER}:${env:PROD_PASS}@prod.example.com:5432/prod_db' ReadOnly = true Schemas = ['public', 'analytics'] Commands = [ { Command = 'ssh -tt bastion.example.com -L ${port}:prod.internal:5432', WaitForPort = '${port}', Timeout = 15 } ] [[database]] Name = 'Local SQLite' Provider = 'sqlite' URL = 'file:~/data/local.db?loc=auto' [keymap.Home] Quit = "q" SwitchToEditorView = "Ctrl-E" MoveRight = "L" MoveLeft = "H" SwitchToConnectionsView = "Backspace" ToggleQueryHistory = "Ctrl-_" [keymap.Table] Edit = "c" Delete = "d" Copy = "y" Search = "/" AppendNewRow = "o" DuplicateRow = "O" SortAsc = "K" SortDesc = "J" RefreshTable = "R" ExportCSV = "E" [keymap.Editor] Execute = "Ctrl-R" UnfocusEditor = "Esc" OpenInExternalEditor = "Ctrl-Space" ``` -------------------------------- ### Custom Application Settings Example Source: https://github.com/jorgerojas26/lazysql/blob/main/_autodocs/configuration.md An example of overriding default application settings in a local configuration file. This allows for personalized UI and behavior. ```toml [application] DefaultPageSize = 500 DisableSidebar = true JSONViewerWordWrap = true EnterOpensJSONViewer = true ``` -------------------------------- ### Install Lazysql with Go Source: https://github.com/jorgerojas26/lazysql/blob/main/README.md Install Lazysql using the Go package manager. Ensure you have Go installed and configured. ```bash go install github.com/jorgerojas26/lazysql@latest ``` -------------------------------- ### Example of Setting Environment Variables for LazySQL Source: https://github.com/jorgerojas26/lazysql/blob/main/_autodocs/errors.md Demonstrates the bash commands to export environment variables before starting the LazySQL application, ensuring that configuration values like DB_USER and DB_PASSWORD are correctly set. ```bash export DB_USER=admin export DB_PASSWORD=secret lazysql ``` -------------------------------- ### Global Configuration Example (TOML) Source: https://github.com/jorgerojas26/lazysql/blob/main/_autodocs/README.md Example of global configuration settings for LazySQL, including application defaults and database connection details. This file is typically located in user configuration directories. ```toml # ~/.config/lazysql/config.toml (Linux/macOS) # %APPDATA%\lazysql\config.toml (Windows) [application] DefaultPageSize = 300 TreeWidth = 30 [[database]] Name = "Local Dev" Provider = "postgres" URL = "postgres://user:pass@localhost/mydb" [keymap.Table] Edit = "c" Delete = "d" ``` -------------------------------- ### Manual Installation from AUR Source: https://github.com/jorgerojas26/lazysql/blob/main/README.md Manually install Lazysql from the AUR by cloning the repository and using makepkg. ```bash git clone https://aur.archlinux.org/lazysql.git cd lazysql makepkg -si ``` -------------------------------- ### Example TOML for Keymap Configuration Source: https://github.com/jorgerojas26/lazysql/blob/main/_autodocs/types.md Demonstrates the TOML structure for defining keymap configurations, organized by view (e.g., Home, Table) and specific actions. ```toml [keymap.Home] SwitchToEditorView = "Ctrl-E" Quit = "q" [keymap.Table] Edit = "c" Delete = "d" Copy = "y" ``` -------------------------------- ### Install Lazysql from AUR (yay) Source: https://github.com/jorgerojas26/lazysql/blob/main/README.md For Arch Linux users, install Lazysql using the AUR helper 'yay'. ```bash yay -S lazysql ``` -------------------------------- ### Example TOML for Pre-connection Commands Source: https://github.com/jorgerojas26/lazysql/blob/main/_autodocs/types.md Shows how to configure pre-connection commands in TOML, including SSH tunneling with port forwarding and saving command output. ```toml Commands = [ { Command = "ssh -tt bastion -L ${port}:localhost:5432", WaitForPort = "${port}" }, { Command = "whoami", SaveOutputTo = "user" } ] ``` -------------------------------- ### Run() Source: https://github.com/jorgerojas26/lazysql/blob/main/_autodocs/api-reference/application.md Starts the TUI application and blocks until stopped. ```APIDOC ## Run() ### Description Starts the TUI application and blocks until stopped. ### Method `Run` ### Parameters #### Request Body - root (`*tview.Pages`) - Required - Root pages container for the TUI - configFile (`string`) - Required - Path to the config file being used ### Return - error (`error`) - Non-nil if application fails during execution ### Example ```go mainPages := components.MainPages() err := app.App.Run(mainPages, "/path/to/config.toml") if err != nil { log.Fatal(err) } ``` ``` -------------------------------- ### Complete Query History Workflow Example Source: https://github.com/jorgerojas26/lazysql/blob/main/_autodocs/api-reference/history.md Demonstrates adding a query to history, retrieving the history file path, reading the history, and displaying the stored queries for a given connection. Handles potential errors during these operations. ```go package main import ( "fmt" "log" "github.com/jorgerojas26/lazysql/internal/history" ) func main() { connectionID := "my_postgres_db" // Execute a query (in real app) query := "SELECT id, name FROM users WHERE active = true" // Add to history if err := history.AddQueryToHistory(connectionID, query); err != nil { log.Fatal(err) } // Read all history historyPath, err := history.GetHistoryFilePath(connectionID) if err != nil { log.Fatal(err) } items, err := history.ReadHistory(historyPath, 0) if err != nil { log.Fatal(err) } // Display history fmt.Printf("Last %d queries for %s:\n", len(items), connectionID) for i, item := range items { fmt.Printf("%d. [%s] %s\n", i+1, item.Timestamp.Format("15:04:05"), item.QueryText) } } ``` -------------------------------- ### Connect with Failed Authentication - Go Source: https://github.com/jorgerojas26/lazysql/blob/main/_autodocs/errors.md This example demonstrates attempting a database connection with incorrect credentials. It's useful for diagnosing authentication or network issues. ```go err := driver.Connect("postgres://baduser:wrongpass@localhost/db") // err: "connection refused" or "role does not exist" ``` -------------------------------- ### Install Lazysql with Homebrew Source: https://github.com/jorgerojas26/lazysql/blob/main/README.md Use this command to install Lazysql on macOS or Linux systems with Homebrew. ```bash brew install lazysql ``` -------------------------------- ### Example Global Configuration Source: https://github.com/jorgerojas26/lazysql/blob/main/README.md Defines multiple database connections and application settings in a TOML file. Supports environment variables for sensitive information like passwords and ports. ```toml [[database]] Name = 'Production database' Provider = 'postgres' DBName = 'foo' URL = 'postgres://${user}:urlencodedpassword@localhost:${port}/foo' ReadOnly = true Commands = [ { Command = 'ssh -tt remote-bastion -L ${port}:localhost:5432', WaitForPort = '${port}' }, { Command = 'whoami', SaveOutputTo = 'user' }, ] [[database]] Name = 'Development database' Provider = 'postgres' DBName = 'foo' URL = 'postgres://postgres:urlencodedpassword@localhost:5432/foo' [application] DefaultPageSize = 300 DisableSidebar = false SidebarOverlay = false JSONViewerWordWrap = false EnterOpensJSONViewer = false ``` -------------------------------- ### SSH Tunnel Command Example Source: https://github.com/jorgerojas26/lazysql/blob/main/README.md Example of an SSH command to establish a tunnel. This command should be run in a separate terminal before connecting to the database. ```bash ssh remote-bastion -L 5432:localhost:5432 ``` -------------------------------- ### Get Application Configuration Source: https://github.com/jorgerojas26/lazysql/blob/main/_autodocs/api-reference/application.md Fetches the application's configuration, which includes settings like default page size and sidebar behavior. ```go pageSize := app.App.Config().DefaultPageSize if app.App.Config().DisableSidebar { // Hide sidebar } ``` -------------------------------- ### Install Lazysql from AUR (paru) Source: https://github.com/jorgerojas26/lazysql/blob/main/README.md For Arch Linux users, install Lazysql using the AUR helper 'paru'. ```bash paru -S lazysql ``` -------------------------------- ### Example TOML for Database Connection Source: https://github.com/jorgerojas26/lazysql/blob/main/_autodocs/types.md Illustrates how to configure a database connection using TOML format, including read-only mode and schema filtering. ```toml [[database]] Name = "Production" Provider = "postgres" URL = "postgres://user:pass@localhost:5432/proddb" ReadOnly = true Schemas = ["public", "analytics"] Commands = [ { Command = "ssh -tt bastion -L 5432:localhost:5432", WaitForPort = "5432" } ] ``` -------------------------------- ### Example Local Configuration Override Source: https://github.com/jorgerojas26/lazysql/blob/main/README.md Overrides global application settings and replaces database connections with project-specific values. Supports environment variables. ```toml [application] DefaultPageSize = 500 [[database]] Name = 'Local development' Provider = 'postgres' URL = 'postgres://localhost/myproject_dev' ``` -------------------------------- ### Custom Keybinding Example Source: https://github.com/jorgerojas26/lazysql/blob/main/_autodocs/README.md Define custom keybindings by editing the `[keymap.*]` sections in your TOML configuration file. This example shows how to bind a custom key to an action. ```toml [keymap.Table] MyCustomKey = "X" ``` -------------------------------- ### Example DBDMLChange for Update Source: https://github.com/jorgerojas26/lazysql/blob/main/_autodocs/types.md Illustrates how to construct a DBDMLChange object for an UPDATE operation on a user's email. ```go change := DBDMLChange{ Database: "mydb", Table: "users", Type: DMLUpdateType, PrimaryKeyInfo: []PrimaryKeyInfo{ {Name: "id", Value: "42"}, }, Values: []CellValue{ { Column: "email", Value: "new@example.com", Type: String, }, }, } ``` -------------------------------- ### Customize Keybindings for Home and Tree Views Source: https://github.com/jorgerojas26/lazysql/blob/main/_autodocs/configuration.md Configure keybindings for different UI modes using [keymap.*] sections. This example shows bindings for the Home and Tree views. ```toml [keymap.Home] Quit = "q" SwitchToEditorView = "Ctrl-E" MoveRight = "L" MoveLeft = "H" [keymap.Tree] GotoTop = "g" GotoBottom = "G" Search = "/" ExpandAll = "e" CollapseAll = "c" ``` -------------------------------- ### TOML Configuration Example Source: https://github.com/jorgerojas26/lazysql/blob/main/_autodocs/types.md This TOML snippet demonstrates how to configure application settings, database connections, and keymaps for LazySQL. It includes settings for default page size, sidebar visibility, database details, and keybindings for different views. ```toml [application] DefaultPageSize = 500 DisableSidebar = false [[database]] Name = "Production" Provider = "postgres" URL = "postgres://user:pass@localhost/db" ReadOnly = true [keymap.Home] Quit = "q" SwitchToEditorView = "Ctrl-E" ``` -------------------------------- ### LazySQL Configuration with Chained Commands Source: https://github.com/jorgerojas26/lazysql/blob/main/README.md Example demonstrating how to chain multiple commands, including SSH tunneling and Kubernetes port-forwarding, to connect to a remote database container. It utilizes dynamic port assignment and waits for ports to become available. ```toml [[database]] Name = 'container' Provider = 'postgres' DBName = 'foo' URL = 'postgres://postgres:password@localhost:${port}/foo' Commands = [ { Command = 'ssh -tt remote-bastion -L 6443:localhost:6443', WaitForPort = '6443' }, { Command = 'kubectl port-forward service/postgres ${port}:5432 --kubeconfig /path/to/kube.conf', WaitForPort = '${port}' } ] ``` -------------------------------- ### Run TUI Application Source: https://github.com/jorgerojas26/lazysql/blob/main/_autodocs/api-reference/application.md Starts the TUI application, blocking until it is stopped. Requires the root TUI pages container and the configuration file path. ```go mainPages := components.MainPages() err := app.App.Run(mainPages, "/path/to/config.toml") if err != nil { log.Fatal(err) } ``` -------------------------------- ### Get Databases Source: https://github.com/jorgerojas26/lazysql/blob/main/_autodocs/api-reference/drivers.md Retrieves a list of all database names accessible to the current user. Use this to enumerate available databases before performing operations. ```go dbs, err := driver.GetDatabases() if err != nil { log.Fatal(err) } for _, db := range dbs { fmt.Println(db) } ``` -------------------------------- ### Local Configuration Override Example Source: https://github.com/jorgerojas26/lazysql/blob/main/_autodocs/configuration.md Use a `.lazysql.toml` file in your project directory to override global settings. Local values take precedence for application settings and keymaps. Local database connections replace all global connections. ```toml [application] DefaultPageSize = 100 # Override global 500 to 100 [[database]] Name = 'Project Database' Provider = 'postgres' URL = 'postgres://dev:devpass@localhost:5432/project_db' [keymap.Table] Edit = "e" # Override global binding from "c" to "e" ``` -------------------------------- ### Customize Keybindings for Editor View Source: https://github.com/jorgerojas26/lazysql/blob/main/_autodocs/configuration.md Configure keybindings for the SQL editor view to control execution, saving, and other editor-specific actions. This example defines custom bindings for these actions. ```toml [keymap.Editor] Execute = "Ctrl-R" UnfocusEditor = "Esc" OpenInExternalEditor = "Ctrl-Space" ``` -------------------------------- ### Pre-Connection Commands Configuration Source: https://github.com/jorgerojas26/lazysql/blob/main/_autodocs/README.md Configure commands to run before establishing a database connection, such as setting up SSH tunnels. The `WaitForPort` option ensures the command has started listening on a specific port. ```toml Commands = [ { Command = "ssh -tt bastion -L ${port}:db:5432", WaitForPort = "${port}" } ] ``` -------------------------------- ### Example of Environment Variable Usage in Config Source: https://github.com/jorgerojas26/lazysql/blob/main/_autodocs/errors.md Shows how environment variables can be referenced within a TOML configuration file for dynamic settings like database credentials. If an environment variable is not set, it results in an empty string. ```toml URL = 'postgres://${env:DB_USER}:${env:DB_PASSWORD}@localhost/db' ``` -------------------------------- ### Get Default Configuration File Path Source: https://github.com/jorgerojas26/lazysql/blob/main/_autodocs/api-reference/application.md Retrieves the platform-specific default configuration file path for the application. Handles different OS conventions for user configuration directories. ```go func DefaultConfigFile() (string, error) ``` ```go defaultPath, err := app.DefaultConfigFile() if err != nil { log.Fatal(err) } configFile := flag.String("config", defaultPath, "config file to use") ``` -------------------------------- ### Write Text to Clipboard Source: https://github.com/jorgerojas26/lazysql/blob/main/_autodocs/api-reference/utilities.md Copies provided text to the system clipboard. Ensure necessary command-line tools like 'xclip' or 'xsel' are installed on Linux systems. ```go cb := lib.NewClipboard() if err := cb.Write("SELECT * FROM users"); err != nil { log.Fatal(err) // Usually "command not found" on Linux without xclip } ``` -------------------------------- ### Get Application Configuration Directory Source: https://github.com/jorgerojas26/lazysql/blob/main/_autodocs/api-reference/saved-queries.md Retrieves the application's configuration directory path. It respects the `$XDG_CONFIG_HOME` environment variable on Linux/macOS and uses platform-specific defaults for other operating systems. ```go func GetAppConfigDir() (string, error) ``` -------------------------------- ### Initialize and Use Clipboard Source: https://github.com/jorgerojas26/lazysql/blob/main/_autodocs/api-reference/utilities.md Demonstrates the creation of a Clipboard instance. ```go cb := lib.NewClipboard() ``` -------------------------------- ### Override and Define Keybindings for Home and Table Views Source: https://github.com/jorgerojas26/lazysql/blob/main/_autodocs/configuration.md Customize keybindings, overriding defaults or defining new ones. This example shows overriding the 'Quit' binding for the Home view and defining several new bindings for the Table view. ```toml [keymap.Home] Quit = "q" Quit = "Ctrl-C" # Error: duplicate key SwitchToEditorView = "i" # Override default Ctrl-E [keymap.Table] Edit = "c" Delete = "d" Copy = "y" AppendNewRow = "o" DuplicateRow = "O" SortAsc = "K" SortDesc = "J" PageNext = ">" PagePrev = "<" RefreshTable = "R" ``` -------------------------------- ### Resolve Keybinding Event Source: https://github.com/jorgerojas26/lazysql/blob/main/_autodocs/api-reference/keymaps.md Example of how to resolve a key event against a keymap group in a table view handler. This demonstrates matching user input to predefined commands like Quit or Edit. ```go event := tcell.EventKey{ /* user pressed 'q' */ } bindings := app.Keymaps.Group(TableGroup) cmd := bindings.Resolve(event) switch cmd { case commands.Quit: // Handle quit case commands.Edit: // Handle edit case commands.Noop: // No binding, ignore } ``` -------------------------------- ### Create New Clipboard Instance Source: https://github.com/jorgerojas26/lazysql/blob/main/_autodocs/api-reference/utilities.md Instantiates a new Clipboard wrapper for system clipboard access. ```go func NewClipboard() *Clipboard ``` -------------------------------- ### Connect to a Database with Postgres Driver Source: https://github.com/jorgerojas26/lazysql/blob/main/_autodocs/README.md Instantiate a driver and connect to a PostgreSQL database using a connection URL. This is the first step before performing any database operations. ```go driver := &drivers.Postgres{} err := driver.Connect("postgres://user:pass@localhost/mydb") if err != nil { log.Fatal(err) } dbs, err := driver.GetDatabases() ``` -------------------------------- ### Pagination in Go Source: https://github.com/jorgerojas26/lazysql/blob/main/_autodocs/README.md Demonstrates efficient data fetching using pagination with the driver. Use this for large tables to avoid timeouts. ```go // Good: fetch in pages driver.GetRecords(db, table, "", "", 0, 300) driver.GetRecords(db, table, "", "", 300, 300) // Poor: fetch entire table driver.ExecuteQuery("SELECT * FROM large_table") // May timeout ``` -------------------------------- ### Get Database Connections Source: https://github.com/jorgerojas26/lazysql/blob/main/_autodocs/api-reference/application.md Retrieves a list of all database connections that have been saved in the application's configuration. ```go for _, conn := range app.App.Connections() { fmt.Println(conn.Name, conn.URL) } ``` -------------------------------- ### FindLocalConfig Source: https://github.com/jorgerojas26/lazysql/blob/main/_autodocs/api-reference/application.md Searches for a local `.lazysql.toml` configuration file starting from the current directory up to the git repository root. ```APIDOC ## FindLocalConfig() ### Description Searches for `.lazysql.toml` starting from current working directory and walking up to the git repository root. ### Behavior: - Starts in current directory - Checks each parent directory for `.lazysql.toml` - Stops at the git repository root (where `.git` exists) - Returns empty string if no local config found ### Return #### Success Response - **path** (`string`) - Full path to `.lazysql.toml`, or empty string if not found - **error** (`error`) - Non-nil if directory walk fails ### Request Example ```go localPath, err := app.FindLocalConfig() if localPath != "" { fmt.Println("Using local config:", localPath) } ``` ``` -------------------------------- ### Load Application Configuration Source: https://github.com/jorgerojas26/lazysql/blob/main/_autodocs/README.md Load application configuration from a default file path. Ensures application settings are properly initialized. ```go configPath, err := app.DefaultConfigFile() if err != nil { log.Fatal(err) } if err := app.LoadConfig(configPath); err != nil { log.Fatal(err) } // Configuration now available via app.App.Config() ``` -------------------------------- ### Get History File Path Source: https://github.com/jorgerojas26/lazysql/blob/main/_autodocs/INDEX.md Use to construct the file path for storing query history for a specific connection. ```go GetHistoryFilePath(connectionId) → (string, error) ``` -------------------------------- ### Configure Pre-Connection Commands Source: https://github.com/jorgerojas26/lazysql/blob/main/_autodocs/configuration.md Execute custom shell commands before establishing a database connection, useful for setting up SSH tunnels or bastion hosts. Supports variable substitution. ```toml Commands = [ { Command = 'ssh -tt bastion-host -L ${port}:database-host:5432', WaitForPort = '${port}' }, { Command = 'whoami', SaveOutputTo = 'user' } ] ``` ```toml Commands = [ { Command = 'ssh -tt remote-bastion -L ${port}:localhost:5432', WaitForPort = '${port}', Timeout = 10 } ] ``` -------------------------------- ### Get Application Context Source: https://github.com/jorgerojas26/lazysql/blob/main/_autodocs/api-reference/application.md Retrieves the application's context, which is essential for managing cancellation and timeouts across operations. ```go ctx := app.App.Context() select { case <-ctx.Done(): // Application is shutting down } ``` -------------------------------- ### Clipboard.Write() Source: https://github.com/jorgerojas26/lazysql/blob/main/_autodocs/api-reference/utilities.md Copies the provided text content to the system clipboard. This method is supported on macOS, Windows, and Linux/Unix (with xclip/xsel installed). ```APIDOC ## Clipboard.Write(text string) ### Description Copies text to the system clipboard. ### Signature ```go func (c *Clipboard) Write(text string) error ``` ### Parameters #### Path Parameters - None #### Query Parameters - None #### Request Body - **text** (`string`): Required - Text to copy to clipboard. ### Returns - error (`error`): Non-nil if clipboard operation fails. ### Example ```go cb := lib.NewClipboard() if err := cb.Write("SELECT * FROM users"); err != nil { log.Fatal(err) // Usually "command not found" on Linux without xclip } ``` ``` -------------------------------- ### Get Saved Queries File Path Source: https://github.com/jorgerojas26/lazysql/blob/main/_autodocs/INDEX.md Use to construct the file path for storing saved queries for a specific connection. ```go GetSavedQueriesFilePath(connectionId) → (string, error) ``` -------------------------------- ### Get Database Provider Name Source: https://github.com/jorgerojas26/lazysql/blob/main/_autodocs/api-reference/drivers.md Retrieves the name of the database provider configured for the driver. This is useful for identifying the target database system. ```go provider := driver.GetProvider() ``` -------------------------------- ### Connect to Database using URL Source: https://github.com/jorgerojas26/lazysql/blob/main/_autodocs/api-reference/drivers.md Establishes a persistent connection to a database using a provided connection URL. Ensure the URL is correctly formatted. ```go driver := &drivers.Postgres{} err := driver.Connect("postgres://user:pass@localhost:5432/mydb") if err != nil { log.Fatal(err) } ``` -------------------------------- ### Application Constructor Source: https://github.com/jorgerojas26/lazysql/blob/main/_autodocs/api-reference/application.md Initializes the global `App` variable with default configuration, theme, and signal handlers. Called automatically on package import. ```APIDOC ## init() ### Description Initializes the global `App` variable with default configuration, theme, and signal handlers. Called automatically on package import. **Side effects:** - Registers signal handlers for SIGINT and SIGTERM - Initializes default theme (`Styles`) - Enables mouse and paste support - Initializes configuration with defaults ``` -------------------------------- ### Get Indexes Source: https://github.com/jorgerojas26/lazysql/blob/main/_autodocs/api-reference/drivers.md Retrieves index metadata for a specified table. The output is a 2D string array, with the first row containing headers. ```go indexes, err := driver.GetIndexes("mydb", "users") if err != nil { log.Fatal(err) } // Process indexes data ``` -------------------------------- ### Application Initialization Source: https://github.com/jorgerojas26/lazysql/blob/main/_autodocs/api-reference/application.md Initializes the global App variable with default settings. This function is called automatically on package import and sets up signal handlers, default theme, and mouse/paste support. ```go func init() ``` -------------------------------- ### Global Application and Styles Variables Source: https://github.com/jorgerojas26/lazysql/blob/main/_autodocs/api-reference/application.md Declares the global `App` and `Styles` variables, representing the application instance and theme, respectively. Both are initialized upon package import. ```go var ( App *Application // Global application instance Styles *Theme // Global theme instance ) ``` -------------------------------- ### Load Configuration from TOML File Source: https://github.com/jorgerojas26/lazysql/blob/main/_autodocs/api-reference/application.md Loads application configuration from a specified TOML file, merging it with local configuration if found. Supports environment variable expansion and keymap application. ```go func LoadConfig(configFile string) error ``` ```go if err := app.LoadConfig("/home/user/.config/lazysql/config.toml"); err != nil { log.Fatal(err) } ``` -------------------------------- ### Set Environment Variables for Lazysql Source: https://github.com/jorgerojas26/lazysql/blob/main/_autodocs/configuration.md Export environment variables before running Lazysql to provide configuration values. This example sets the database user and password. ```bash export DB_USER=admin export DB_PASSWORD=supersecret lazysql ``` -------------------------------- ### Config() Source: https://github.com/jorgerojas26/lazysql/blob/main/_autodocs/api-reference/application.md Returns the application configuration containing display settings and defaults. ```APIDOC ## Config() ### Description Returns the application configuration containing display settings and defaults. ### Method `Config` ### Return - config (`*models.AppConfig`) - Application settings (DefaultPageSize, SidebarOverlay, etc.) ### Example ```go pagesize := app.App.Config().DefaultPageSize if app.App.Config().DisableSidebar { // Hide sidebar } ``` ``` -------------------------------- ### Configure Database URL with Environment Variables Source: https://github.com/jorgerojas26/lazysql/blob/main/README.md Use environment variables in the configuration file for sensitive information like passwords. Undefined variables are replaced with an empty string. ```toml [[database]] Name = 'Production' Provider = 'postgres' URL = 'postgres://${env:DB_USER}:${env:DB_PASSWORD}@localhost:5432/mydb' ``` -------------------------------- ### Get Foreign Keys Source: https://github.com/jorgerojas26/lazysql/blob/main/_autodocs/api-reference/drivers.md Retrieves foreign key relationships for a specified table. The result is a 2D string array, with the first row containing headers. ```go foreignKeys, err := driver.GetForeignKeys("mydb", "users") if err != nil { log.Fatal(err) } // Process foreignKeys data ``` -------------------------------- ### Application Configuration Loading Source: https://github.com/jorgerojas26/lazysql/blob/main/_autodocs/INDEX.md Use to load application configuration. Supports default configuration files and merging behavior. ```go LoadConfig(configFile) → error ``` ```go DefaultConfigFile() → (string, error) ``` ```go FindLocalConfig() → (string, error) ``` ```go GetConfigPath() → (string, error) ``` -------------------------------- ### Get Primary Key Column Names Source: https://github.com/jorgerojas26/lazysql/blob/main/_autodocs/api-reference/drivers.md Retrieves the names of columns that constitute the primary key for a given table. Use this to identify the primary key columns. ```go pkCols, err := driver.GetPrimaryKeyColumnNames("mydb", "users") if err != nil { log.Fatal(err) } fmt.Println("PK columns:", pkCols) // ["id"] or ["org_id", "user_id"] ``` -------------------------------- ### Structured Logging: Good vs. Poor Attribute Keys Source: https://github.com/jorgerojas26/lazysql/blob/main/_autodocs/api-reference/utilities.md Demonstrates the use of descriptive attribute keys for better readability and maintainability in structured logs. Avoid short, ambiguous keys. ```go // Good logger.Info("Query executed", map[string]any{ "database": "mydb", "table": "users", "rows_affected": 42, }) // Poor logger.Info("Query executed", map[string]any{ "db": "mydb", "t": "users", "n": 42, }) ``` -------------------------------- ### Get Tables by Database Source: https://github.com/jorgerojas26/lazysql/blob/main/_autodocs/api-reference/drivers.md Retrieves tables and views, grouped by schema or owner. The return format varies slightly between database systems (PostgreSQL/MSSQL vs. MySQL/SQLite). ```go tables, err := driver.GetTables("mydb") if err != nil { log.Fatal(err) } for schema, tableList := range tables { fmt.Printf("Schema %s:\n", schema) for _, table := range tableList { fmt.Printf(" %s\n", table) } } ``` -------------------------------- ### Bind String() Method Source: https://github.com/jorgerojas26/lazysql/blob/main/_autodocs/api-reference/keymaps.md Returns a string representation of a Bind in the format "key = command". ```go Bind{Key: Key{Char: 'q'}, Cmd: commands.Quit, Description: "Quit"}.String() // "q = Quit" ``` -------------------------------- ### Define Application Configuration Structure Source: https://github.com/jorgerojas26/lazysql/blob/main/_autodocs/types.md Defines the application-wide configuration settings. Used for managing application behavior and defaults. ```go type AppConfig struct { DefaultPageSize int DisableSidebar bool SidebarOverlay bool MaxQueryHistoryPerConnection int TreeWidth int JSONViewerWordWrap bool EnterOpensJSONViewer bool ConfirmOnQuit bool } ``` -------------------------------- ### Connect() Source: https://github.com/jorgerojas26/lazysql/blob/main/_autodocs/api-reference/drivers.md Establishes a connection to a database using a connection URL. This method is used to initiate a persistent connection. ```APIDOC ## Connect() ### Description Establishes a connection to a database using a connection URL. ### Signature ```go func (d Driver) Connect(urlstr string) error ``` ### Parameters #### Path Parameters - **urlstr** (string) - Required - Database connection URL (e.g., `postgres://user:pass@localhost/dbname`) ### Return - **error** (error) - Non-nil if connection fails (invalid URL, network error, auth failure) ### Example ```go driver := &drivers.Postgres{} err := driver.Connect("postgres://user:pass@localhost:5432/mydb") if err != nil { log.Fatal(err) } ``` ``` -------------------------------- ### Customize Keybindings for Table View Source: https://github.com/jorgerojas26/lazysql/blob/main/_autodocs/configuration.md Configure keybindings for the Table view to control actions like editing, deleting, and sorting. This example defines custom bindings for these actions. ```toml [keymap.Table] Edit = "c" Delete = "d" Copy = "y" Search = "/" ``` -------------------------------- ### Define Pre-connection Command Structure Source: https://github.com/jorgerojas26/lazysql/blob/main/_autodocs/types.md Defines a command to be executed before establishing a database connection, such as setting up an SSH tunnel. ```go type Command struct { Command string WaitForPort string SaveOutputTo string Timeout int } ``` -------------------------------- ### Example of Invalid TOML Syntax Error Source: https://github.com/jorgerojas26/lazysql/blob/main/_autodocs/errors.md Illustrates a typical error message when a configuration file contains invalid TOML syntax, such as bare keys with invalid characters. ```text Error loading config: (1, 1): bare keys cannot contain # ``` -------------------------------- ### Get Constraints Source: https://github.com/jorgerojas26/lazysql/blob/main/_autodocs/api-reference/drivers.md Retrieves constraint metadata (e.g., PRIMARY KEY, UNIQUE, CHECK) for a given table. The output is a 2D string array with headers in the first row. ```go constraints, err := driver.GetConstraints("mydb", "users") if err != nil { log.Fatal(err) } // Process constraints data ``` -------------------------------- ### Application Lifecycle Management Source: https://github.com/jorgerojas26/lazysql/blob/main/_autodocs/INDEX.md Use to manage the application lifecycle, including context, configuration, and stopping the application. ```go Context() → context.Context ``` ```go Config() → *AppConfig ``` ```go Connections() → []Connection ``` ```go SaveConnections(connections) → error ``` ```go Register() → func() ``` ```go Run(root, configFile) → error ``` ```go Stop() ``` ```go SetOnQuitRequest(fn) ``` -------------------------------- ### Launch Lazysql TUI Source: https://github.com/jorgerojas26/lazysql/blob/main/README.md Open the Lazysql Text User Interface. ```console $ lazysql ``` -------------------------------- ### Get Table Columns Source: https://github.com/jorgerojas26/lazysql/blob/main/_autodocs/api-reference/drivers.md Retrieves column metadata for a specified table, returned as a 2D string array with headers in the first row. Headers and detailed column information vary by driver. ```go columns, err := driver.GetTableColumns("mydb", "users") if err != nil { log.Fatal(err) } for i, row := range columns { if i == 0 { fmt.Println("Headers:", row) } else { fmt.Printf("Column: %s, Type: %s\n", row[0], row[1]) } } ``` -------------------------------- ### Keymap System Structure Source: https://github.com/jorgerojas26/lazysql/blob/main/_autodocs/INDEX.md Outlines the KeymapSystem, which manages different keymap groups and provides a global fallback for command resolution. ```Go KeymapSystem: - Groups: map[string]Map - Global: Map fallback - Group(name) → Map - Resolve(event) → Command ``` -------------------------------- ### Application Struct Definition Source: https://github.com/jorgerojas26/lazysql/blob/main/_autodocs/api-reference/application.md Defines the Application struct, which wraps tview.Application and includes fields for configuration, context, and synchronization. ```go type Application struct { *tview.Application config *Config context context.Context cancelFn context.CancelFunc waitGroup sync.WaitGroup onQuitRequestMu sync.RWMutex onQuitRequest func() } ``` -------------------------------- ### Launch Lazysql in Read-Only Mode Source: https://github.com/jorgerojas26/lazysql/blob/main/README.md Launch Lazysql and connect to a database at the specified URL in read-only mode. ```console $ lazysql --read-only [connection_url] ``` -------------------------------- ### Key String() Method Source: https://github.com/jorgerojas26/lazysql/blob/main/_autodocs/api-reference/keymaps.md Returns a human-readable string representation of a Key. Use for character keys or special keys like Enter or Ctrl+E. ```go Key{Char: 'q'}.String() // "q" Key{Char: 'G'}.String() // "G" Key{Code: tcell.KeyEnter}.String() // "" Key{Code: tcell.KeyCtrlE}.String() // "" ``` -------------------------------- ### LazySQL CLI Usage Source: https://github.com/jorgerojas26/lazysql/blob/main/_autodocs/README.md Basic command-line syntax for lazysql. Specify options and connection URLs. ```bash lazysql [options] [connection_url] Options: -config string Config file to use -version Show version -loglevel string Log level (debug, info, warn, error) -logfile string Log file path -read-only Enable read-only mode ``` -------------------------------- ### NewClipboard() Source: https://github.com/jorgerojas26/lazysql/blob/main/_autodocs/api-reference/utilities.md Creates a new instance of the Clipboard wrapper, which provides methods for interacting with the system clipboard. ```APIDOC ## NewClipboard() ### Description Creates a new Clipboard instance. ### Signature ```go func NewClipboard() *Clipboard ``` ### Returns - clipboard (`*Clipboard`): A new clipboard wrapper instance. ### Example ```go cb := lib.NewClipboard() ``` ``` -------------------------------- ### Configuration Loading Source: https://github.com/jorgerojas26/lazysql/blob/main/_autodocs/INDEX.md Handles loading, finding, and defining default configuration files for the application. Supports merging configurations from multiple sources. ```APIDOC ## Configuration Loading ### Description Handles loading, finding, and defining default configuration files for the application. Supports merging configurations from multiple sources. ### Methods - `LoadConfig(configFile) → error`: Loads configuration from the specified file. - `DefaultConfigFile() → (string, error)`: Returns the default configuration file path. - `FindLocalConfig() → (string, error)`: Finds the local configuration file. - `GetConfigPath() → (string, error)`: Retrieves the configuration file path. ``` -------------------------------- ### Complete Saved Queries Workflow in Go Source: https://github.com/jorgerojas26/lazysql/blob/main/_autodocs/api-reference/saved-queries.md Demonstrates saving, reading, and deleting queries using the saved queries package. Ensure the connection ID is valid and the necessary file permissions are in place. ```go package main import ( "fmt" "log" "github.com/jorgerojas26/lazysql/internal/saved" ) func main() { connectionID := "analytics_db" // Save a useful query query1 := "SELECT DATE(created_at), COUNT(*) FROM events GROUP BY DATE(created_at)" if err := saved.SaveQuery(connectionID, "Daily Event Counts", query1); err != nil { log.Fatal(err) } query2 := "SELECT * FROM users WHERE last_login < NOW() - INTERVAL 30 DAY" if err := saved.SaveQuery(connectionID, "Inactive Users", query2); err != nil { log.Fatal(err) } // Read all saved queries queries, err := saved.ReadSavedQueries(connectionID) if err != nil { log.Fatal(err) } fmt.Printf("Saved queries for %s:\n", connectionID) for i, q := range queries { fmt.Printf("%d. %s\n", i+1, q.Name) } // Use a saved query for _, q := range queries { if q.Name == "Daily Event Counts" { fmt.Printf("Executing: %s\n", q.Query) // Execute q.Query against the database break } } // Delete a query if err := saved.DeleteSavedQuery(connectionID, "Inactive Users"); err != nil { log.Fatal(err) } } ``` -------------------------------- ### Custom Database Driver Interface Source: https://github.com/jorgerojas26/lazysql/blob/main/_autodocs/README.md Implement the `Driver` interface to add support for new database types. This interface defines methods for connecting, retrieving databases, and tables, among others. ```go type Driver interface { Connect(url string) error GetDatabases() ([]string, error) GetTables(database string) (map[string][]string, error) // ... 30+ methods } ``` -------------------------------- ### Execute a SQL Query Source: https://github.com/jorgerojas26/lazysql/blob/main/_autodocs/README.md Execute a SQL query against the connected database. The result includes headers and data rows. ```go rows, count, err := driver.ExecuteQuery("SELECT * FROM users LIMIT 10") if err != nil { log.Fatal(err) } // rows[0] contains headers // rows[1:] contain data rows ``` -------------------------------- ### Find Local Configuration File Source: https://github.com/jorgerojas26/lazysql/blob/main/_autodocs/api-reference/application.md Searches for a local `.lazysql.toml` configuration file by traversing parent directories up to the Git repository root. Returns the path if found, otherwise an empty string. ```go func FindLocalConfig() (string, error) ``` ```go localPath, err := app.FindLocalConfig() if localPath != "" { fmt.Println("Using local config:", localPath) } ``` -------------------------------- ### LoadConfig Source: https://github.com/jorgerojas26/lazysql/blob/main/_autodocs/api-reference/application.md Loads configuration from TOML files, merging global and local settings, and expanding environment variables. ```APIDOC ## LoadConfig() ### Description Loads configuration from TOML files. Merges global config with local `.lazysql.toml` if found. ### Behavior: - Reads global config from specified path - Searches for `.lazysql.toml` in current directory up to git root - Merges local config into global config (see merge rules below) - Expands environment variables with `${env:VAR}` syntax - Applies loaded keymaps ### Merge rules: - `[application]`: deep merge (local overrides global) - `[[database]]`: replace (local list replaces global) - `[keymap.*]`: deep merge (local bindings override global) ### Parameters #### Path Parameters - **configFile** (`string`) - Required - Path to global config.toml ### Return #### Success Response - **error** (`error`) - Non-nil if config parsing fails ### Request Example ```go if err := app.LoadConfig("/home/user/.config/lazysql/config.toml"); err != nil { log.Fatal(err) } ``` ``` -------------------------------- ### Launch Lazysql with Saved Connections Source: https://github.com/jorgerojas26/lazysql/blob/main/README.md Launch Lazysql and pick from saved connections. ```console $ lazysql [connection_url] ``` -------------------------------- ### LazySQL Package Structure Source: https://github.com/jorgerojas26/lazysql/blob/main/_autodocs/README.md Overview of the directory structure for the lazysql project, indicating the purpose of each top-level directory. ```go app/ → Application lifecycle, config, keymaps components/ → UI components (tree, table, modals) drivers/ → Database driver implementations models/ → Data structures and types commands/ → User command enumeration keymap/ → Key binding core logic lib/ → Utility libraries (clipboard) helpers/ → Helper utilities (logging) internal/ ├─ history/ → Query history management └─ saved/ → Saved queries management ```