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
4 changes: 4 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -101,6 +101,10 @@ Output:
}
```

Keys that are not in the connection string are left out. To include them with their `default` value, use `toSchema(schema, { includeMissing: true })`.

An empty value for a `boolean` or `number` key, such as `a number=;`, means that the value is not set. The key is included with its `default` value (or `undefined` if it has no default). An empty value for a `string` key stays an empty string.

## Accessing properties

The parsed connection string object is a readonly `Map` with an overloadded `get()` method allowing
Expand Down
7 changes: 6 additions & 1 deletion src/connection-string.ts
Original file line number Diff line number Diff line change
Expand Up @@ -90,13 +90,18 @@ export class ConnectionString implements ReadonlyMap<string, string> {
});
}

// an empty boolean or number value is not set, so it gets the schema default
#isSet(key: string, type?: CoerceType): boolean {
return (type !== 'boolean' && type !== 'number') || !!this.#parsed.get(key.toLowerCase())?.trim();
}

// a way to extract a formatted object from the connection string
toSchema<T extends SchemaDefinition>(schema: T, { includeMissing }: { includeMissing?: boolean } = {}): InferSchema<T> {
return Object.fromEntries(Object.entries(schema).reduce((props, [key, { type, default: defaultValue, aliases }]) => {
// try to find the property
const prop = [key, ...aliases ?? []].find((k) => this.has(k));
if (prop || includeMissing) {
props.push([key, prop ? this.get(prop.toLowerCase(), type) : defaultValue] as [keyof T, CoerceType]);
props.push([key, prop && this.#isSet(prop, type as CoerceType | undefined) ? this.get(prop.toLowerCase(), type) : defaultValue] as [keyof T, CoerceType]);
}
return props;
}, [] as [keyof T, CoerceType][])) as InferSchema<T>;
Expand Down
45 changes: 44 additions & 1 deletion test/connection-string.test.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
import * as assert from 'node:assert';
import { describe, it } from 'node:test';
import { ConnectionString } from '../src/connection-string';
import { ConnectionString, type SchemaDefinition } from '../src/connection-string';

describe('connection-string', () => {
const connectionString = 'keyword=value;isTrue=true;isYes=yes;isFalse=false;isNo=no;is0=0;is1=1';
Expand Down Expand Up @@ -98,6 +98,49 @@ describe('connection-string', () => {
]);
});
});
describe('.toSchema()', () => {
const schema = {
'a boolean': { type: 'boolean' as const, default: true },
'a number': { type: 'number' as const, default: 15 },
'a string': { type: 'string' as const, default: 'default' },
'no default': { type: 'boolean' as const },
};
it('coerces values that are set', () => {
const parsed = new ConnectionString('a boolean=false;a number=30;a string=value;no default=yes');
assert.deepEqual(parsed.toSchema(schema), {
'a boolean': false,
'a number': 30,
'a string': 'value',
'no default': true,
});
});
it('uses the default for an empty boolean or number value, and keeps the key', () => {
const parsed = new ConnectionString('a boolean=;a number= ;a string=;no default=');
const result = parsed.toSchema(schema);
assert.deepEqual(result, {
'a boolean': true,
'a number': 15,
'a string': '',
'no default': undefined,
});
assert.ok('no default' in result);
});
it('still throws for an empty value with an unsupported type', () => {
const parsed = new ConnectionString('when=');
const badSchema = { when: { type: 'date', default: 'D' } } as unknown as SchemaDefinition;
assert.throws(() => parsed.toSchema(badSchema), { message: 'Coerce type not supported' });
});
it('includes missing keys with their defaults when asked', () => {
const parsed = new ConnectionString('a number=30');
assert.deepEqual(parsed.toSchema(schema), { 'a number': 30 });
assert.deepEqual(parsed.toSchema(schema, { includeMissing: true }), {
'a boolean': true,
'a number': 30,
'a string': 'default',
'no default': undefined,
});
});
});
describe('.toString()', () => {
it('returns the connection string', () => {
const parsed = new ConnectionString(connectionString);
Expand Down
37 changes: 37 additions & 0 deletions test/parser/fixture/sql-strings.json
Original file line number Diff line number Diff line change
Expand Up @@ -27,6 +27,43 @@
}
}
},
{
"name": "uses the default for an empty boolean or number value",
"connection_string": "Server=h;TrustServerCertificate=;Connect Timeout=;Database=d",
"expected": {
"data source": "h",
"trustservercertificate": false,
"connection timeout": 15,
"initial catalog": "d"
}
},
{
"name": "uses the default for a boolean or number value of only whitespace",
"connection_string": "Server=h;TrustServerCertificate={ };MultiSubnetFailover={ };Packet Size=' '",
"expected": {
"data source": "h",
"trustservercertificate": false,
"multisubnetfailover": false,
"packet size": 8000
}
},
{
"name": "keeps an empty string value",
"connection_string": "Server=h;Password=;Application Name={ }",
"expected": {
"data source": "h",
"password": "",
"application name": " "
}
},
{
"name": "uses the default for an empty value given by an alias",
"connection_string": "Server=h;Timeout=",
"expected": {
"data source": "h",
"connection timeout": 15
}
},
{
"name": "parses a string value that starts with numbers",
"connection_string": "client id=1e92dd5a-091f-4b2b-bc1b-8461ced6a177;client secret=55a4ef49-bef5-4669-818b-ff148c0c0db9;tenant id=5dc09092-ee09-4e5c-9515-ba937415e9ff;",
Expand Down
Loading