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

Correct CREATE TABLE IF NOT EXISTS syntax for MSSQL #26

Merged
merged 2 commits into from
Dec 4, 2023

Conversation

Mr-Kaos
Copy link
Contributor

@Mr-Kaos Mr-Kaos commented Nov 27, 2023

This pull request fixes changes the syntax present in the Mssql driver's getSchemaVersion() function to be acceptable T-SQL syntax.

T-SQL does not support the CREATE TABLE IF EXISTS syntax so the OBJECT_ID function must be used instead to check if such database object exists.

There were two commits made in this pull request, the first being a bit longer, but guarantees that the ID returned by OBJECT_ID is a table and not another database object such as a view or function.

One thing to keep in mind though is that the provided fix only works for tables in the default dbo database schema. Tables that are in another schema will need to have their schema specified. For example, the schema in the snippet below is prepended before the table name, spearated by a period:

IF (OBJECT_ID('OtherSchema.TableName')) IS NULL
    CREATE TABLE [TableName] ([version] INT DEFAULT '0')

Copy link
Member

@joshmcrae joshmcrae left a comment

Choose a reason for hiding this comment

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

I'm ready to merge, however I'd like to see if we can simplify the syntax (see below).

@@ -135,7 +135,7 @@ public function getLastId()
*/
public function getSchemaVersion()
{
$this->pdo->exec("IF (SELECT [object_id] FROM [sys].[tables] WHERE [object_id] = OBJECT_ID('".$this->schemaTable."')) IS NULL CREATE TABLE [".$this->schemaTable."] ([version] INT DEFAULT '0')");
$this->pdo->exec("IF (OBJECT_ID('".$this->schemaTable."')) IS NULL CREATE TABLE [".$this->schemaTable."] ([version] INT DEFAULT '0')");
Copy link
Member

Choose a reason for hiding this comment

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

@Mr-Kaos are the parens around OBJECT_ID(...) necessary? Other examples I've seen of this approach omit them, e.g.

IF OBJECT_ID("table_name") IS NULL ...

Copy link
Contributor Author

Choose a reason for hiding this comment

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

The parentheses are not required around OBJECT_ID(...). I had only included them to make the contents of the IF statement clear.

@joshmcrae joshmcrae merged commit 4bb5c8b into elvanto:master Dec 4, 2023
8 of 9 checks passed
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Development

Successfully merging this pull request may close these issues.

None yet

3 participants