Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
9 changes: 7 additions & 2 deletions src/builder/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -22,7 +22,11 @@ function isQuoted(val: string): boolean {
}

function needsQuotes(val: string): boolean {
return !isQuoted(val) && !!val.match(/\[|]|{|}|\|\(|\)|,|;|\?|\*|=|!|@/)?.length;
if (isQuoted(val)) {
return false;
}
// the parser trims unquoted values, and reads a leading `'` or `"` as an opening quote
return val !== val.trim() || /^['"]/.test(val) || !!val.match(/\[|]|{|}|\|\(|\)|,|;|\?|\*|=|!|@/)?.length;
}

function encodeTuple(key: string, value: ValidDataTypes): [string, string] {
Expand All @@ -44,6 +48,7 @@ function encodeTuple(key: string, value: ValidDataTypes): [string, string] {

export function build(data: Record<string, ValidDataTypes>): string {
return Object.entries(data).map(([key, value]) => {
return encodeTuple(key.trim(), value).join('=');
// `=` ends a key, so a literal `=` in a key is escaped as `==`
return encodeTuple(key.trim().replace(/=/g, '=='), value).join('=');
}).join(';');
}
29 changes: 18 additions & 11 deletions src/parser/connection-string-parser.ts
Original file line number Diff line number Diff line change
Expand Up @@ -63,6 +63,11 @@ export default function connectionStringParser(connectionString: string, parserC
return config().terminator === char;
}

function isSkippable(char: string): boolean {
// whitespace before a key or value, or an extra `;` before a key
return !char.trim() || (collectionMode === CollectionMode.key && char === parserConfig.value.terminator);
}

function isStartQuote(char: string): boolean {
return Object.keys(config().quotes).some((val: string) => char === val);
}
Expand Down Expand Up @@ -96,17 +101,16 @@ export default function connectionStringParser(connectionString: string, parserC
while (pointer < connectionString.length) {
const current = connectionString.charAt(pointer);
if (!finished) {
if (!started) {
if (current.trim()) {
start();
if (isStartQuote(current)) {
quoted = true;
quote = current;
} else {
push(current);
}
}
if (!started && isSkippable(current)) {
// nothing to collect yet
} else if (!started && isStartQuote(current)) {
start();
quoted = true;
quote = current;
} else {
// the first character can also be a terminator, for example in an
// empty value (`Key=;`) or in a key that starts with `==`
start();
if (quoted && isEndQuote(current)) {
const next = connectionString.charAt(pointer + 1);
if (current === next) {
Expand All @@ -117,9 +121,12 @@ export default function connectionStringParser(connectionString: string, parserC
}
} else if (!quoted && isTerminator(current)) {
const next = connectionString.charAt(pointer + 1);
if (current === next) {
// `==` is an escaped `=` in a key; a `;` always ends an unquoted value
if (collectionMode === CollectionMode.key && current === next) {
push(current);
pointer++;
} else if (collectionMode === CollectionMode.key && buffer === '') {
throw new Error('Malformed connection string');
} else {
collect();
}
Expand Down
47 changes: 46 additions & 1 deletion test/builder/builder.test.ts
Original file line number Diff line number Diff line change
@@ -1,8 +1,53 @@
import * as assert from 'node:assert';
import { describe, it } from 'node:test';
import { build } from '../../src';
import { build, parse } from '../../src';

describe('builder', () => {
it('quotes values with leading or trailing whitespace', () => {
const built = build({
leading: ' value',
trailing: 'value ',
both: ' value ',
tab: '\tvalue',
newline: 'value\n',
inner: 'a value',
});
assert.equal(built, 'leading={ value};trailing={value };both={ value };tab={\tvalue};newline={value\n};inner=a value');
});

it('quotes values that start with a quote character', () => {
const built = build({
single: '\'value',
double: '"value"',
inner: 'val\'ue"',
});
assert.equal(built, 'single={\'value};double={"value"};inner=val\'ue"');
});

it('builds values that parse back to the same value', () => {
const values = [' secret ', '\'abc', '"x"', '\'', '"', ' ', '\t', 'a value', 'val\'ue"', '{a}}b', 'a;b', 'a=b'];
values.forEach((value) => {
assert.equal(parse(build({ key: value })).get('key'), value, `round trip of ${JSON.stringify(value)}`);
});
});

it('escapes `=` in keys', () => {
const built = build({
'a=b': '1',
'=start': '2',
'end=': '3',
'a==b': '4',
});
assert.equal(built, 'a==b=1;==start=2;end===3;a====b=4');
});

it('builds keys that parse back to the same key', () => {
const keys = ['a=b', '=start', 'end=', 'a==b', '=', 'a;b'];
keys.forEach((key) => {
assert.deepEqual([...parse(build({ [key]: 'value' })).entries()], [[key, 'value']], `round trip of ${JSON.stringify(key)}`);
});
});

it('builds a connection string', () => {
const built = build({
strkey: 'value',
Expand Down
12 changes: 12 additions & 0 deletions test/parser/connection-string.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -40,5 +40,17 @@ describe('parser', () => {
message: 'Connection string terminated unexpectedly',
});
});

it('throws on an empty keyword', () => {
assert.throws(() => parse('=value'), {
message: 'Malformed connection string',
});
});

it('throws on an empty keyword after another pair', () => {
assert.throws(() => parse('key=value; =other'), {
message: 'Malformed connection string',
});
});
});
});
102 changes: 102 additions & 0 deletions test/parser/fixture/connection-strings.json
Original file line number Diff line number Diff line change
Expand Up @@ -13,13 +13,115 @@
"keyword": "Value"
}
},
{
"name": "parses a single value with repeated trailing semicolons",
"connection_string": "Keyword=Value;;",
"expected": {
"keyword": "Value"
}
},
{
"name": "skips repeated semicolons between pairs",
"connection_string": "Server=h;;Database=d;;;User Id=u",
"expected": {
"server": "h",
"database": "d",
"user id": "u"
}
},
{
"name": "skips leading semicolons",
"connection_string": ";; Server=h",
"expected": {
"server": "h"
}
},
{
"name": "skips semicolons separated by whitespace",
"connection_string": "Server=h; ; Database=d",
"expected": {
"server": "h",
"database": "d"
}
},
{
"name": "skips repeated semicolons after a quoted value",
"connection_string": "Password='p;w';;Server=h",
"expected": {
"password": "p;w",
"server": "h"
}
},
{
"name": "parses keywords that contain `;`",
"connection_string": "Key;word=Value",
"expected": {
"key;word": "Value"
}
},
{
"name": "parses keywords that contain `=`",
"connection_string": "Key==word=Value",
"expected": {
"key=word": "Value"
}
},
{
"name": "parses keywords that start with `=`",
"connection_string": "==Key=Value",
"expected": {
"=key": "Value"
}
},
{
"name": "parses keywords that end with `=`",
"connection_string": "Key===Value",
"expected": {
"key=": "Value"
}
},
{
"name": "parses empty values",
"connection_string": "TrustServerCertificate=;Encrypt=true;Server=h",
"expected": {
"trustservercertificate": "",
"encrypt": "true",
"server": "h"
}
},
{
"name": "parses empty values with whitespace",
"connection_string": "Key= ;Other=Value",
"expected": {
"key": "",
"other": "Value"
}
},
{
"name": "parses an empty connection string",
"connection_string": "",
"expected": {}
},
{
"name": "parses a connection string of only whitespace and semicolons",
"connection_string": " ;; ",
"expected": {}
},
{
"name": "parses an empty value with a trailing semicolon",
"connection_string": "Key=;",
"expected": {
"key": ""
}
},
{
"name": "parses values that start with `=`",
"connection_string": "Key= =Value;Other=x",
"expected": {
"key": "=Value",
"other": "x"
}
},
{
"name": "parses values to contain `=`",
"connection_string": "Keyword=Val=ue",
Expand Down
Loading