DEV Community

Cover image for My ER diagram tool silently dropped a table: SQL Server brackets and GO
devtoolkits
devtoolkits

Posted on

My ER diagram tool silently dropped a table: SQL Server brackets and GO

I build a browser-only tool that turns CREATE TABLE statements into an ER diagram. It handled PostgreSQL, MySQL and SQLite dumps, so I added SQL Server output and, while I was at it, pasted a SQL Server DDL to see what happened:

CREATE TABLE [dbo].[users] (
  [id] INT IDENTITY(1,1) NOT NULL PRIMARY KEY,
  [name] NVARCHAR(100) NOT NULL
)
GO
CREATE TABLE dbo.orders (
  id BIGINT IDENTITY PRIMARY KEY,
  user_id INT NOT NULL,
  CONSTRAINT FK_o_u FOREIGN KEY (user_id) REFERENCES [dbo].[users]([id])
)
GO
Enter fullscreen mode Exit fullscreen mode

The diagram showed orders only. users was gone, and so were the primary key and the foreign key. No error. Silently missing things is the worst way for a parser to fail.

Three causes

  1. Quoted identifiers were only " and `. [dbo].[users] didn't read as a table name, so the whole table was skipped.
  2. Statements were split on ;, but SQL Server DDL ends batches with GO. Without a ;, the tables around a GO merged into one statement.
  3. IDENTITY wasn't recognised as auto-increment (I only checked AUTO_INCREMENT).

I didn't change the parser itself. I added a pass in front of it that rewrites the input into the standard form.

Normalise first, without touching strings

function normalizeTsql(sql: string): string {
  let out = '';
  let quote: string | null = null;
  for (let i = 0; i < sql.length; i++) {
    const ch = sql[i];
    if (quote) {                         // inside a string or quoted name: copy as is
      out += ch;
      if (ch === quote) {
        if (sql[i + 1] === quote) out += sql[++i];
        else quote = null;
      }
      continue;
    }
    if (ch === "'" || ch === '"' || ch === '`') { quote = ch; out += ch; continue; }
    if (ch === '[' && !/[\w\]]$/.test(out)) {   // after a word it's an array type, e.g. int[3]
      const m = /^\[((?:[^\]]|\]\])+)\]/.exec(sql.slice(i));
      if (m && !/^\s*\d+\s*$/.test(m[1])) {      // [] and [3] are array subscripts
        const name = m[1].replace(/\]\]/g, ']').trim();
        out += `"${name.replace(/"/g, '""')}"`;
        i += m[0].length - 1;
        continue;
      }
    }
    out += ch;
  }
  return out.replace(/^[ \t]*GO[ \t]*;?[ \t]*$/gim, ';');   // a lone GO line becomes ;
}
Enter fullscreen mode Exit fullscreen mode

Two things I cared about:

  • Never touch the inside of a string. DEFAULT '[x]' must not turn into DEFAULT '"x"'. Walking one character at a time and remembering whether you're inside quotes is easy; a single regex replace can't do it.
  • Don't break PostgreSQL array types like int[] or text[3]. If the character before [ is a word character it's a subscript and stays. Empty or digits-only brackets also stay.

GO becomes ; only when it's the entire line, so CATEGORY and a GO in the middle of a statement are untouched. IDENTITY just joins the existing check:

/\b(?:AUTO_?INCREMENT|IDENTITY)\b/i.test(tail)
Enter fullscreen mode Exit fullscreen mode

Follow-up: a reader found more

The first version of that regex only accepted names starting with a letter or _ followed by word characters and spaces. A reader ran my snippet and reported that [dbo].[注文] and [order-items] kept their brackets, and [a]]b] (an escaped ]) became "a"]b]. They were right: SQL Server allows all of those as delimited identifiers.

The code above is the fixed version: the content can be anything except ], and ]] means one ]. Fixing the regex wasn't enough, though. The code that reads column definitions can't handle spaces, dots, commas, semicolons or parentheses inside a name. So the pass hides those characters behind private-use characters while parsing and puts the original name back at the end. The name is never changed in the output.

Tests now include a Japanese table name, order-items, a]b, full name, a.b and x,y.

The Mermaid export needed a similar check. I ran the generated text through the real Mermaid (v11) parser to see what it accepts: Japanese and hyphens are fine, but a space in an attribute name isn't (even in quotes), and a table name with a space or dot must be quoted. So table names are quoted when needed and attribute names get _ for the characters Mermaid refuses. That is the one place a displayed name changes.

Takeaways

  • Implicit assumptions ("split on ;", "quotes are " and `") break when you add a dialect, and they break by dropping things instead of failing.
  • Rewriting into a standard form in front of the parser is safer than changing the parser, for the dialects you already support.
  • Walk character by character with quote state when you must leave strings alone.
  • Test with the unglamorous names too: Unicode, hyphens, escaped delimiters.

Try it

Runs entirely in your browser: SQL to ER Diagram.

Top comments (0)