{"id":24629500,"url":"https://github.com/sharpjs/psql","last_synced_at":"2025-05-07T22:13:37.225Z","repository":{"id":55522915,"uuid":"49025546","full_name":"sharpjs/PSql","owner":"sharpjs","description":"Cmdlets for SQL Server and Azure SQL databases.","archived":false,"fork":false,"pushed_at":"2025-03-05T16:31:55.000Z","size":1223,"stargazers_count":9,"open_issues_count":0,"forks_count":3,"subscribers_count":3,"default_branch":"main","last_synced_at":"2025-05-07T22:13:31.059Z","etag":null,"topics":["azure-sql-database","powershell","powershell-module","sql","sql-server"],"latest_commit_sha":null,"homepage":"","language":"C#","has_issues":true,"has_wiki":null,"has_pages":null,"mirror_url":null,"source_name":null,"license":"mit","status":null,"scm":"git","pull_requests_enabled":true,"icon_url":"https://github.com/sharpjs.png","metadata":{"files":{"readme":"README.md","changelog":"CHANGES.md","contributing":null,"funding":null,"license":"LICENSE.txt","code_of_conduct":null,"threat_model":null,"audit":null,"citation":null,"codeowners":null,"security":null,"support":null,"governance":null,"roadmap":null,"authors":null,"dei":null,"publiccode":null,"codemeta":null}},"created_at":"2016-01-04T21:54:24.000Z","updated_at":"2025-03-05T16:31:58.000Z","dependencies_parsed_at":"2023-12-23T21:45:39.223Z","dependency_job_id":"421e8ea0-3228-48e3-8ce3-b21271207112","html_url":"https://github.com/sharpjs/PSql","commit_stats":null,"previous_names":[],"tags_count":36,"template":false,"template_full_name":null,"repository_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/sharpjs%2FPSql","tags_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/sharpjs%2FPSql/tags","releases_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/sharpjs%2FPSql/releases","manifests_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/sharpjs%2FPSql/manifests","owner_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners/sharpjs","download_url":"https://codeload.github.com/sharpjs/PSql/tar.gz/refs/heads/main","host":{"name":"GitHub","url":"https://github.com","kind":"github","repositories_count":252961843,"owners_count":21832199,"icon_url":"https://github.com/github.png","version":null,"created_at":"2022-05-30T11:31:42.601Z","updated_at":"2022-07-04T15:15:14.044Z","host_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub","repositories_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories","repository_names_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repository_names","owners_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners"}},"keywords":["azure-sql-database","powershell","powershell-module","sql","sql-server"],"created_at":"2025-01-25T06:13:07.744Z","updated_at":"2025-05-07T22:13:37.199Z","avatar_url":"https://github.com/sharpjs.png","language":"C#","readme":"# PSql\n\nCmdlets for SQL Server and Azure SQL databases.\n\n![SELECT * FROM YourTable;](https://raw.githubusercontent.com/sharpjs/PSql/main/misc/what-does-it-do.png)\n\n## Status\n\n[![Build](https://github.com/sharpjs/PSql/workflows/Build/badge.svg)](https://github.com/sharpjs/PSql/actions)\n[![NuGet](https://img.shields.io/powershellgallery/v/PSql.svg)](https://www.powershellgallery.com/packages/PSql)\n[![NuGet](https://img.shields.io/powershellgallery/dt/PSql.svg)](https://www.powershellgallery.com/packages/PSql)\n\nPSql 2.x is a C# rewrite of what previously was a script module.  The script\nmodule was used for for years in production code.  PSql 2.x has seen two years\nof production use too.\n\n## Installation\n\nPSql requires PowerShell 7.2 or later and should work on any platform where\nPowerShell runs.\n\nTo install PSql from [PowerShell Gallery](https://www.powershellgallery.com/packages/PSql),\nrun this PowerShell command:\n\n```powershell\nInstall-Module PSql\n```\n\nTo update PSql, run this PowerShell command:\n\n```powershell\nUpdate-Module PSql\n```\n\nTo check what version(s) of PSql you have installed, run this PowerShell command:\n\n```powershell\nGet-Module PSql -ListAvailable | Format-List\n```\n\n## Usage\n\nPSql provides these cmdlets:\n\nName                      | Description\n:-------------------------|:---------------------------------------------------\n`New-SqlContext`          | Sets up connection options.\n`Connect-Sql`             | Opens connections to database servers.\n`Disconnect-Sql`          | Closes connections to database servers.\n`Invoke-Sql`              | Runs SQL scripts.\n`Expand-SqlCmdDirectives` | Preprocesses SQL scripts.\n\nEvery PSql cmdlet has built-in documentation.  To view that documentation, run\na PowerShell command like this:\n\n```powershell\nGet-Help Invoke-Sql -Full\n```\n\nThe core function of PSql is to run T-SQL scripts.  It can be this easy:\n\n```powershell\nInvoke-Sql \"PRINT 'Hello, world.'\" -Database master\n```\n\nOr, using a pipe:\n\n```powershell\n\"SELECT * FROM sys.schemas\" | Invoke-Sql -Database master\n```\n\nIn its simplest form, `Invoke-Sql` assumes that the machine has a local\ninstallation of SQL Server (or compatible product), that the installation is\nregistered as the [default instance](https://docs.microsoft.com/en-us/sql/database-engine/configure-windows/database-engine-instances-sql-server),\nand that the current user can connect using [integrated authentication](https://docs.microsoft.com/en-us/sql/relational-databases/security/choose-an-authentication-mode).\nIf your situation is different, you need to prepare a **SQL context** object\nthat specifies how to connect to a database server.\n\n```powershell\n$login = Get-Credential pgibbons\n\n$context = New-SqlContext `\n    -ServerName      initech1 `\n    -DatabaseName    TpsReports `\n    -Credential      $login `\n    -ApplicationName \"TPS Report Generator\"\n```\n\nWhen connecting to Azure SQL Database (or compatible product), use the `-Azure`\nswitch, which enables some Azure-specific parameters, like resource group name\nand Azure Active Directory authentication modes.\n\n```powershell\n$login = Get-Credential pgibbons\n\n$context = New-SqlContext -Azure `\n    -ResourceGroupName  initech `\n    -ServerResourceName initech-db01 `\n    -DatabaseName       TpsReports `\n    -AuthenticationMode AadPassword `\n    -Credential         $login `\n    -ApplicationName    \"TPS Report Generator\"\n```\n\n`New-SqlContext` supports a number of other parameters that generally\ncorrespond to settings commonly specified in connection strings.  Most of them\nare optional.  See the built-in help for `New-SqlContext` for details.\n\nOnce a SQL context is prepared, using (and reusing) it is easy:\n\n```powershell\nInvoke-Sql \"EXEC dbo.GenerateTpsReport\" -Context $context\n```\n\nWhen used as above, `Invoke-Sql` opens a new connection for each invocation and\ncloses the connection once the invocation completes.  In many situations, that\nis adequate.  However, some items, like temporary tables, disappear when their\nconnection closes.  When those must persist across multiple uses of\n`Invoke-Sql`, it is necessary to explicitly open and close a connection.\n\n```powershell\n$connection = Connect-Sql -Context $context\ntry {\n    Invoke-Sql \"...\" -Connection $connection\n}\nfinally {\n    Disconnect-Sql $connection\n}\n```\n\n### SQLCMD Compatibility\n\n`Invoke-Sql` supports a limited set of preprocessing features intended to be\ncompatible with the [`sqlcmd`](https://docs.microsoft.com/en-us/sql/tools/sqlcmd-utility)\nutility:\n\nExample | Description\n:-- | :--\n`GO` | Ends the current SQL batch and begins a new one.\n`$(Foo)` | Replaced with the value of the sqlcmd variable `Foo`.\n`:setvar Foo Bar`\u003cbr/\u003e`:setvar Foo \"Bar\"` | Sets the value of the sqlcmd variable `Foo` to `Bar`.\u003cbr/\u003eEnclose the value in double-quotes (`\"`) if it contains whitespace.\n`:r Foo.sql`\u003cbr/\u003e`:r \"Foo.sql\"` | Replaced with the preprocessed contents of the file `Foo.sql`.\u003cbr/\u003eEnclose the path in double-quotes (`\"`) if it contains whitespace.\u003cbr/\u003ePaths are relative to the current directory.\n\nPreprocessor directives are case-insensitive.  The `GO`, `:setvar`, and `:r`\ndirectives must appear at the beginning of a line, and no other content may\nappear on that line.  `$(…)` may appear anywhere, including inside other\npreprocessor directives.\n\nTo disable `Invoke-Sql` preprocessing, use the `-NoPreprocessing` switch.\n\n### Error Handling\n\nBy default, `Invoke-Sql` wraps SQL batches in [an error-handling shim](https://github.com/sharpjs/PSql/blob/main/PSql/_Utilities/SqlErrorHandling.cs#L67-L120).\nThe wrapper improves the diagnostic experience by printing the batch that\ncaused an error.  Here is an example:\n\n![Example showing a divide-by-zero error](https://raw.githubusercontent.com/sharpjs/PSql/main/misc/psql-error-handling.png)\n\nThere are a few known scenarios in which the error-handling wrapper can *cause*\nan error, requiring the use of a workaround.  The scenarios are:\n\n- **Multi-batch transactions.**  Transactions cannot span batches.  If a batch\n  begins a transaction but does not commit it (or vice versa), the batch will\n  fail with an error.\n\n  ![Example of BEGIN TRANSACTION without COMMIT TRANSACTION](https://raw.githubusercontent.com/sharpjs/PSql/main/misc/begin-transaction-error.png)\n\n- **Multi-batch temporary tables.**  If a batch creates a temporary table, the\n  temporary table is destroyed at the end of the batch.  The temporary table is\n  not visible to subsequent batches.\n\n  ![Example of temporary table not found in subsequent batch](https://raw.githubusercontent.com/sharpjs/PSql/main/misc/temp-table-error.png)\n\nThere are two ways to work around these known issues:\n\n- **Pass the `-NoErrorHandling` switch** to `Invoke-Sql`.  When this switch is\n  used, the error-handling wrapper is omitted.  SQL batches are executed bare.\n  No enhanced error-handling is performed.\n\n- **Include this magic comment** on any line in the batch:\n\n  ```sql\n  --# NOWRAP\n  ```\n\n  The magic comment must appear at the beginning of the line, and no other\n  content may appear on that line.  The comment causes `Invoke-Sql` to place\n  the batch's code verbatim into the error-handling wrapper's `TRY`/`CATCH`\n  block, rather than within an `EXECUTE` statement.  This prevents the issues\n  described above while preserving the enhanced diagnostics provided by the\n  wrapper.  The drawback is that script hygiene is no longer perfect: an error\n  in the batch might interfere with the wrapper itself, preventing the\n  error-handling from working as intended.\n\n  To prevent nasty surprises with `--# NOWRAP`, use it only when required, and\n  keep the batches using it as small as possible.  Examples:\n\n  ```sql\n  --# NOWRAP\n  BEGIN TRANSACTION;\n  GO\n  ```\n\n  ```sql\n  --# NOWRAP\n  CREATE TABLE #T (X int NOT NULL);\n  GO\n  ```\n\n## Contributors\n\nMany thanks to the following contributors:\n\n**@Jezour**:\n  [#1](https://github.com/sharpjs/PSql/pull/1)\n","funding_links":[],"categories":[],"sub_categories":[],"project_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fsharpjs%2Fpsql","html_url":"https://awesome.ecosyste.ms/projects/github.com%2Fsharpjs%2Fpsql","lists_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fsharpjs%2Fpsql/lists"}