SimplySql
repository·master·Indexed 42 days ago
https://github.com/mithrandyr/simplysqlA PowerShell module providing a provider-agnostic way to interact with SQL Server, Oracle, PostgreSQL, MySQL, and SQLite databases. It abstracts vendor-specific complexities through a consistent workflow of Open, Invoke, and Close cmdlets, featuring support for parameterized queries, transactions, and high-performance data movement via Invoke-SqlBulkCopy.
What's inside SimplySql
- SimplySql provides a PowerShell-idiomatic way to interact with relational databases. It offers a suite of cmdlets for managing connections, executing queries (scalar, bulk, and standard), handling transactions, and managing informational messages across multiple database providers including SQL Server, MySQL, Oracle, PostgreSQL, and SQLite.
How to stream query results with Invoke-SqlQuery
masterTo process large result sets efficiently, use the
-Streamswitch. This uses a datareader to emit aPSObjectfor each row to the pipeline as soon as the connection begins returning data.Important Constraints:
- When
-Streamis used, only the first result set is returned, even if multiple are available. - If you use
-Stream, the-AsDataTableswitch is ignored.
- When
The basic SimplySql workflow pattern
masterThe standard workflow for using SimplySql involves three main steps:
- Connect: Use an
Open-*Connectioncmdlet specific to your database provider to establish a connection. - Execute: Use
Invoke-Sql*cmdlets to run your SQL statements. - Disconnect: Use a
Close-*Connectioncmdlet to release the connection.
This pattern abstracts vendor-specific connection logic, allowing you to use consistent cmdlets across different database types.
# Example Workflow Open-SQLiteConnection Invoke-SqlUpdate -Query "CREATE TABLE test (id INT)" Close-SQLiteConnection- Connect: Use an
Configure batching and performance for Invoke-SqlBulkCopy
masterTo optimize the bulk copy operation, you can control how data is batched and how long batches are allowed to run.
-BatchSize: Specifies how many inserts are grouped together in a single batch. The default value is500.-BatchTimeout: Specifies the maximum time (in seconds) a single batch can take. If not specified, it defaults to the command timeout of the source connection.
If the destination provider (like SQL Server) supports a managed bulk copy implementation (e.g.,
SqlBulkCopy), the operation is highly optimized. Otherwise, SimplySql optimizes performance by wrapping multiple inserts into a single transaction.How to query databases with SimplySql
masterSimplySql follows a consistent pattern: open a connection, invoke SQL statements, and then close the connection.
While connection cmdlets are provider-specific (e.g.,
Open-SqlConnectionfor MSSQL,Open-SQLiteConnectionfor SQLite), the execution cmdlets likeInvoke-SqlQueryare provider-agnostic.If you have multiple connections open simultaneously, distinguish them using the
-ConnectionNameparameter. If omitted, it defaults to'default'.# Basic pattern Open-*Connection -DataSource "SomeServer" -InitialCatalog "SomeDB" $data = Invoke-SqlQuery -query "SELECT * FROM someTable" # Using parameters to prevent injection $data = Invoke-SqlQuery -query "SELECT * FROM someTable WHERE someCol = @var" -Parameters @{var = 'a value'} # Close the connection Close-SqlConnectionManage database connections with Open/Close/Show/Test/Set/Get cmdlets
masterSimplySql provides a suite of cmdlets to manage database connections in your PowerShell session:
- Open-
<Provider>Connection: Establishes a connection. Available providers include:Open-SqlConnectionOpen-SQLiteConnectionOpen-OracleConnectionOpen-PostGreConnectionOpen-MySqlConnection
- Close-
<Provider>Connection: Closes the connection for the specified provider. - Show/Test-SqlConnection: View active connections and their details in the current session.
- Set-SqlConnection: Change the default
commandTimeoutor the active database/catalog (if supported by the provider). - Get-SqlConnection: Returns the underlying raw connection object.
- Open-
Connect using a Connection String
masterIf you need to use a specific provider-formatted connection string, use the
connparameter set. This requires the-ConnectionStringparameter.# Example of Connection String Authentication Open-SQLConnection -ConnectionString "Server=myServerAddress;Database=myDataBase;User Id=myUsername;Password=myPassword;"Open an Oracle Database connection with Open-OracleConnection
masterThe
Open-OracleConnectioncmdlet allows you to establish a connection to an Oracle Database using one of three parameter sets:default,tns, orconn. This cmdlet uses the Oracle Managed Data Access provider for .NET.Connection Methods
- Default (Server/Service Name): Use this for standard connections by specifying the server, service name, and port.
- Parameters:
-Server,-ServiceName,-Port,-Credential.
- Parameters:
- TNS (Transparent Network Substrate): Use this to connect via a TNS name.
- Parameters:
-TnsName,-Credential.
- Parameters:
- Connection String: Use this to provide a specific, provider-formatted connection string.
- Parameters:
-ConnectionString(Required).
- Parameters:
Common Configuration Options
-ConnectionName(Alias:cn): A user-defined name for the connection (Default:default).-CommandTimeout: The default timeout in seconds for all commands executed on this connection (Default:30).-Privilege: Sets elevated privileges. Accepted values:None,SYSASM,SYSDBA,SYSOPER(Default:None).-Additional: AHashtableto provide extra connection parameters.
# Example: Default connection method Open-OracleConnection -Server "my-oracle-host" -ServiceName "ORCL" -Port 1521 # Example: TNS connection method Open-OracleConnection -TnsName "MY_TNS_ENTRY" # Example: Connection string method Open-OracleConnection -ConnectionString "Data Source=myServerAddress:1521/myServiceName;User Id=myUsername;Password=myPassword;"- Default (Server/Service Name): Use this for standard connections by specifying the server, service name, and port.
Connect to Azure SQL using Azure AD credentials
masterTo connect to an Azure SQL Database using Azure AD credentials, use the
credentialparameter set. You must provide aPSCredentialobject and include the-AzureADswitch.Parameters:
-Credential: APSCredentialobject.-AzureAD: A switch parameter to indicate Azure AD authentication.-Server: The server address.-Database: The target database.
# Example of Azure AD Authentication $cred = Get-Credential Open-SQLConnection -Server "your-server.database.windows.net" -Database "your-db" -Credential $cred -AzureADList active SqlConnections with Show-SqlConnection
masterUse the
Show-SqlConnectioncmdlet to inspect active SQL connections. By default, it lists information for a single connection. If you provide a connection name, it retrieves details for that specific connection. If you use the-Allswitch, it returns a list of all currently active connection names.# List information for the default connection Show-SqlConnection # List information for a specific connection Show-SqlConnection -ConnectionName "MyDatabaseConnection" # List all active connection names Show-SqlConnection -AllInstall the SimplySql module
masterYou can install SimplySql from the PowerShell Gallery. This module requires PowerShell version 5.0 or greater.
To install it for the current user, use the following command:
Install-Module SimplySql -Scope CurrentUserConnect using an Azure Token
masterIf you have an Azure access token, you can use the
tokenparameter set. Pass the token string to the-AzureTokenparameter. The cmdlet will automatically strip thebearerprefix if present.# Example of Token Authentication Open-SQLConnection -Server "your-server.database.windows.net" -Database "your-db" -AzureToken "bearer YOUR_TOKEN_HERE"