File size: 1,818 Bytes
0bfe2e3
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
import { URL } from 'url';
import { createLogger } from '../utils/logger';
import path from 'path';

type BaseConnectionURI = {
  url: URL;
  driverName: string;
};

type PostgresConnectionURI = BaseConnectionURI & {
  dialect: 'postgres';
};

type SQLiteConnectionURI = BaseConnectionURI & {
  filename: string;
  dialect: 'sqlite';
};

export type ConnectionURI = PostgresConnectionURI | SQLiteConnectionURI;

type DBDialect = 'postgres' | 'sqlite';

type DSNModifier = (url: URL, query: URLSearchParams) => void;
const logger = createLogger('database');

function parseConnectionURI(uri: string): ConnectionURI {
  const url = new URL(uri);
  let driverName: string;
  let dialect: DBDialect;

  switch (url.protocol) {
    case 'sqlite:': {
      driverName = 'sqlite3';
      dialect = 'sqlite';
      let filename = url.pathname;
      if (url.hostname && url.hostname !== '.') {
        throw new Error("Invalid path, must start with '/' or './'");
      }
      if (!url.pathname) {
        throw new Error('Invalid path, must be absolute');
      }
      if (url.hostname === '.') {
        // resolve relative path using process.cwd()
        filename = path.join(process.cwd(), url.pathname.replace(/^\//, ''));
      }
      return {
        url,
        driverName,
        filename: filename,
        dialect,
      };
    }
    case 'postgres:': {
      driverName = 'pg';
      dialect = 'postgres';
      return {
        url,

        driverName,
        dialect,
      };
    }
    default:
      throw new Error('Unsupported scheme: ' + url.protocol);
  }
}

function adaptQuery(query: string, dialect: DBDialect): string {
  if (dialect === 'sqlite') {
    return query;
  }

  let position = 1;
  return query.replace(/\?/g, () => `$${position++}`);
}

export { parseConnectionURI, adaptQuery };