-
Notifications
You must be signed in to change notification settings - Fork 59
/
sql-data-types.js
280 lines (246 loc) · 8.99 KB
/
sql-data-types.js
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
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
/*
* Copyright (c) 2008-2022, Hazelcast, Inc. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
'use strict';
const { Client, SqlColumnType, HazelcastSqlException } = require('hazelcast-client');
const long = require('long');
// Portable class
class Student {
constructor(age, height) {
this.age = age;
this.height = height;
this.factoryId = 23;
this.classId = 1;
}
readPortable(reader) {
this.age = reader.readInt('age');
this.height = reader.readDouble('height');
}
writePortable(writer) {
writer.writeInt('age', this.age);
writer.writeDouble('height', this.height);
}
}
class Employee {
constructor(age, id) {
this.age = age;
this.id = id;
}
}
class EmployeeSerializer {
getClass() {
return Employee;
}
getTypeName() {
return 'Employee';
}
read(reader) {
const age = reader.readInt32('age');
const id = reader.readInt64('id');
return new Employee(age, id);
}
write(writer, value) {
writer.writeInt32('age', value.age);
writer.writeInt64('id', value.id);
}
}
const varcharExample = async (client) => {
console.log('----------VARCHAR Example----------');
const mapName = 'varcharMap';
const someMap = await client.getMap(mapName);
// In order to use the map in SQL a mapping should be created.
const createMappingQuery = `
CREATE OR REPLACE MAPPING ${mapName} (
__key DOUBLE,
this VARCHAR
)
TYPE IMAP
OPTIONS (
'keyFormat' = 'double',
'valueFormat' = 'varchar'
)
`;
await client.getSql().execute(createMappingQuery);
for (let key = 0; key < 10; key++) {
await someMap.set(key, key.toString());
}
try {
const result = await client.getSql().execute(`SELECT * FROM ${mapName} WHERE this = ? OR this = ?`, ['7', '2']);
const rowMetadata = result.rowMetadata;
const columnIndex = rowMetadata.findColumn('this');
const columnMetadata = rowMetadata.getColumn(columnIndex);
console.log(`Column type: ${SqlColumnType[columnMetadata.type]}`); // Column type: VARCHAR
for await (const row of result) {
console.log(row);
}
} catch (e) {
if (e instanceof HazelcastSqlException) {
// HazelcastSqlException is thrown if an error occurs during SQL execution.
console.log(`An SQL error occurred while running SQL: ${e}`);
} else {
// for all other errors
console.log(`An error occurred while running SQL: ${e}`);
}
}
};
/*
Since Node.js client sends all numbers as double by default, giving a number as parameter
will not work for `BIGINT` type. Instead, you can use `long` objects or you can use explicit
casting which can convert doubles to other integer types.
*/
const bigintExample = async (client) => {
console.log('\n---------- BIGINT Example----------');
const mapName = 'bigintMap';
const someMap = await client.getMap(mapName);
// In order to use the map in SQL a mapping should be created.
const createMappingQuery = `
CREATE OR REPLACE MAPPING ${mapName} (
__key DOUBLE,
this BIGINT
)
TYPE IMAP
OPTIONS (
'keyFormat' = 'double',
'valueFormat' = 'bigint'
)
`;
await client.getSql().execute(createMappingQuery);
for (let key = 0; key < 10; key++) {
await someMap.set(key, long.fromNumber(key * 2));
}
const result = await client.getSql().execute(
`SELECT * FROM ${mapName} WHERE this > ? AND this < ?`,
[long.fromNumber(10), long.fromNumber(18)]
);
const rowMetadata = result.rowMetadata;
const columnIndex = rowMetadata.findColumn('this');
const columnMetadata = rowMetadata.getColumn(columnIndex);
console.log(`Column type: ${SqlColumnType[columnMetadata.type]}`); // Column type: BIGINT
for await (const row of result) {
console.log(row);
}
// Casting example. Casting to other integer types is also possible.
const result2 = await client.getSql().execute(
`SELECT * FROM ${mapName} WHERE this > CAST(? AS BIGINT) AND this < CAST(? AS BIGINT)`,
[10, 18]
);
for await (const row of result2) {
console.log(row);
}
};
const portableExample = async (client, classId, factoryId) => {
console.log('\n----------OBJECT Example(Portable)----------');
const mapName = 'studentMap';
const someMap = await client.getMap(mapName);
// In order to use the map in SQL a mapping should be created.
const createMappingQuery = `
CREATE OR REPLACE MAPPING ${mapName} (
__key DOUBLE,
age INT,
height DOUBLE
)
TYPE IMAP
OPTIONS (
'keyFormat' = 'double',
'valueFormat' = 'portable',
'valuePortableFactoryId' = '${factoryId}',
'valuePortableClassId' = '${classId}'
)
`;
await client.getSql().execute(createMappingQuery);
for (let key = 0; key < 10; key++) {
await someMap.set(key, new Student(long.fromNumber(key), 1.1));
}
// Note: If you do not specify `this` and use *, by default, `age` and `height` columns will be fetched
// instead of `this`.
// This is true only for complex custom objects like portable and identified serializable.
const result = await client.getSql().execute(
`SELECT __key, this FROM ${mapName} WHERE age > CAST(? AS INTEGER) AND age < CAST(? AS INTEGER)`,
[3, 8]
);
const rowMetadata = result.rowMetadata;
const columnIndex = rowMetadata.findColumn('this');
const columnMetadata = rowMetadata.getColumn(columnIndex);
console.log(`Column type: ${SqlColumnType[columnMetadata.type]}`); // Column type: OBJECT
for await (const row of result) {
const student = row['this'];
console.log(student);
}
};
const compactExample = async (client, typeName) => {
console.log('\n----------OBJECT Example(Compact)----------');
const mapName = 'employeeMap';
const someMap = await client.getMap(mapName);
// To be able to use our map in SQL, we need to create mapping for it.
const createMappingQuery = `
CREATE OR REPLACE MAPPING ${mapName} (
__key DOUBLE,
age INTEGER,
id BIGINT
)
TYPE IMap
OPTIONS (
'keyFormat' = 'double',
'valueFormat' = 'compact',
'valueCompactTypeName' = '${typeName}'
)
`;
await client.getSql().execute(createMappingQuery);
for (let key = 0; key < 10; key++) {
await someMap.set(key, new Employee(key, long.fromNumber(key)));
}
const result = await client.getSql().execute(
'SELECT * FROM employeeMap WHERE id > ? AND id < ?',
[long.fromNumber(3), long.fromNumber(8)]
);
const rowMetadata = result.rowMetadata;
const columnIndex = rowMetadata.findColumn('age');
const columnMetadata = rowMetadata.getColumn(columnIndex);
console.log(`1st column type: ${SqlColumnType[columnMetadata.type]}`); // 1st column type: INTEGER
const columnIndex2 = rowMetadata.findColumn('id');
const columnMetadata2 = rowMetadata.getColumn(columnIndex2);
console.log(`2nd column type: ${SqlColumnType[columnMetadata2.type]}`); // 2nd column type: BIGINT
for await (const row of result) {
console.log(`Id: ${row['id']} Age: ${row['age']}`);
}
};
(async () => {
// Since we will use a portable, we register it:
const portableFactory = (classId) => {
if (classId === 1) {
return new Student();
}
return null;
};
const employeeSerializer = new EmployeeSerializer();
const client = await Client.newHazelcastClient({
serialization: {
portableFactories: {
23: portableFactory
},
compact: {
serializers: [employeeSerializer]
}
}
});
await varcharExample(client);
await bigintExample(client);
await portableExample(client, 1, 23);
await compactExample(client, employeeSerializer.getTypeName());
await client.shutdown();
})().catch(err => {
console.error('Error occurred:', err);
process.exit(1);
});