Repository navigation
Expand file tree
/
Copy pathsql-string.ts
More file actions
72 lines (57 loc) · 2.01 KB
/
Copy pathsql-string.ts
File metadata and controls
72 lines (57 loc) · 2.01 KB
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
import type { AbstractDataType } from './abstract-dialect/data-types.js';
import type { AbstractDialect } from './abstract-dialect/dialect.js';
import * as DataTypes from './data-types';
import { logger } from './utils/logger';
const textDataTypeMap = new Map<string, AbstractDataType<any>>();
export function getTextDataTypeForDialect(dialect: AbstractDialect): AbstractDataType<any> {
let type = textDataTypeMap.get(dialect.name);
if (type == null) {
type = new DataTypes.STRING().toDialectDataType(dialect);
textDataTypeMap.set(dialect.name, type);
}
return type;
}
export function bestGuessDataTypeOfVal(
val: unknown,
dialect: AbstractDialect,
): AbstractDataType<any> {
// TODO: cache simple types
switch (typeof val) {
case 'bigint':
return new DataTypes.BIGINT().toDialectDataType(dialect);
case 'number': {
if (Number.isSafeInteger(val)) {
return new DataTypes.INTEGER().toDialectDataType(dialect);
}
return new DataTypes.FLOAT().toDialectDataType(dialect);
}
case 'boolean':
return new DataTypes.BOOLEAN().toDialectDataType(dialect);
case 'object':
if (Array.isArray(val)) {
if (val.length === 0) {
throw new Error(
`Could not guess type of value ${logger.inspect(val)} because it is an empty array`,
);
}
return new DataTypes.ARRAY(bestGuessDataTypeOfVal(val[0], dialect)).toDialectDataType(
dialect,
);
}
if (val instanceof Date) {
return new DataTypes.DATE(3).toDialectDataType(dialect);
}
if (Buffer.isBuffer(val)) {
// TODO: remove dialect-specific hack
if (dialect.name === 'ibmi') {
return new DataTypes.STRING().toDialectDataType(dialect);
}
return new DataTypes.BLOB().toDialectDataType(dialect);
}
break;
case 'string':
return getTextDataTypeForDialect(dialect);
default:
}
throw new TypeError(`Could not guess type of value ${logger.inspect(val)}`);
}