-
-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathfoo1.js
194 lines (177 loc) · 8.83 KB
/
foo1.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
/**
* @imports
*/
import pg from 'pg';
import mariadb from 'mariadb';
import { SQLClient } from '../src/index.js';
let driver, dialect = 'postgres', dbPublic;
// ---------------------------------
if (dialect === 'mysql') {
// JSON support: MariaDB 10.2.7, MySQL 5.7.8
// DEFAULT (uuid()) support: MariaDB 10.3, MySQL 8.0
driver = await mariadb.createConnection({
host: '127.0.0.1',
user: 'root',
port: 3306,
// -------
database: 'test',
multipleStatements: true,
bitOneIsBoolean: true, // default
trace: true,
});
dbPublic = 'test';
} else {
driver = new pg.Client({
host: 'localhost',
port: 5432,
});
await driver.connect();
dbPublic = 'public';
}
// ---------------------------------
let inspect = false;
const client = new SQLClient({
query(...args) {
//if (!args[0].includes('tbl.table_schema')) console.log(args[0]);
//console.log(args[0]);
return driver.query(...args)
},
on(...args) { return driver.on(...args) }
}, { dialect });
/*
*/
console.log('---DATABSES BEFORE:', (await client.schema()).databases(false));
console.log('---PUBLIC TABLES BEFORE:', (await client.schema({ depth: 1 })).database(dbPublic).tables(false));
const linkedDB = await client.linkedDB(true);
if (0) {
await linkedDB.uninstall(true);
process.exit();
}
console.log('DROP 5', await client.query(`DROP SCHEMA if exists test_db${ dialect === 'mysql' ? '' : ' CASCADE' } RETURNING SCHEMA`));
console.log('DROP 3', await client.query(`DROP TABLE if exists ${ dbPublic }.books${ dialect === 'mysql' ? '' : ' CASCADE' } RETURNING SCHEMA`));
console.log('DROP 2', await client.query(`DROP TABLE if exists ${ dbPublic }.users${ dialect === 'mysql' ? '' : ' CASCADE RETURNING SAVEPOINT' }`));
console.log('DROP 1', await client.query(`DROP TABLE if exists ${ dbPublic }.roles${ dialect === 'mysql' ? '' : ' CASCADE' }`));
console.log('DROP 1', await client.query(`DROP TABLE if exists ${ dbPublic }.savepoints${ dialect === 'mysql' ? '' : ' CASCADE' }`));
await linkedDB.table('savepoints').delete(true);
console.log('....create roles......', await client.query(`CREATE TABLE roles (
id int primary key generated always as identity,
name varchar(100),
created_time timestamp
)`, { desc: 'Created roles' }));
const savepoint1 = await client.database(dbPublic).savepoint();
console.log('.....create users.....', await client.query(`CREATE TABLE users (
id int primary key generated always as identity,
title varchar(100) default '...',
name varchar(100) unique,
role int references roles (id),
parent int references users (id),
created_time timestamp
)`, { desc: 'Created users' }));
const savepoint2 = await client.database(dbPublic).savepoint();
console.log(savepoint2.jsonfy());
console.table(savepoint2.jsonfy());
console.log('.....create test_db.....', await client.query(`CREATE SCHEMA test_db`));
const savepoint2b = await client.database('test_db').savepoint();
console.log('.....create test_db.users.....', await client.query(`CREATE TABLE test_db.test_users (
id int primary key generated always as identity,
title varchar(100),
name varchar(100),
created_time timestamp
)`, { desc: 'Created users' }));
const savepoint2c = await client.database('test_db').savepoint();
console.log('.....create books.....', await client.query(`CREATE TABLE books (
id int primary key generated by default as identity,
title varchar(100),
content varchar(100),
author int references users (id),
created_timeeee timestamp (3)
)`, { desc: 'Created books' }));
const savepoint3 = await client.database(dbPublic).savepoint();
console.log('\n\n\n\n\n\ntables---------', (await client.schema({ depth: 1 })).database(dbPublic).tables(false));
console.log('\n\n\n\n\n\nAll savepoints now-----', ...(await linkedDB.table('savepoints').select()));
console.log('rollback 3', await savepoint3.rollback());
console.log('rollback 2', await savepoint2.rollback());
console.log('rollback 1', await savepoint1.rollback());
let spliceForwardHistories = false;
if (spliceForwardHistories) {
console.log('.....create publications.....', await client.query(`CREATE TABLE publications (
id int primary key generated always as identity,
title varchar(100),
content varchar(100),
created_time timestamp
)`, { desc: 'Created publications' }));
const savepoint4 = await client.database(dbPublic).savepoint();
// Should see: 1,2,3,7
console.log('\n\n\n\n\n\nall savepoints-----', ...(await linkedDB.table('savepoints').select()));
} else {
// Roll forward
for (let i = 0; i < 3; i ++) {
await (await client.database(dbPublic).savepoint({ lookAhead: true })).recommit();
}
// Should see: 1,2,3
console.log('\n\n\n\n\n\nAll ===== savepoints-----', ...(await linkedDB.table('savepoints').select()));
console.log('\n\n\n\n\n\n\n-----------------------------withSchemaAwareness---------------------------\n\n\n\n\n\n\n');
await client.withSchema(async () => {
await client.query(`INSERT INTO public.roles (name, created_time) VALUES ('admin', now()), ('guest', now())`);
await client.query(`INSERT INTO users (title, name, role, parent, created_time) VALUES ('Mr.', 'Ox-Harris', 1, null, now()), ('Mrs.', 'Jane', 2, 1, now()), ('Mrs.', 'Jane2', 2, 2, now())`);
const numRows = await client.query(`
INSERT INTO books
(title, content, author: (name, role), created_timeeee)
VALUES
('Rich Dad & Poor Dad - part 1' || $1, 'content...1', ('Oxford Himself1' || $1, 1), now()),
('Rich Dad & Poor Dad - part 2' || $1, 'content...1', ('Oxford Himself2' || $1, 2), now()),
('Beauty & the Beast', 'content...2' || $2, ('Oxford Himself3' || $2, 1), now())
`, { values: ['(a)', '(b)'], inspect: true });
console.log('INSERT INTO BOOKS:', numRows);
const numRows2 = await client.query(`
INSERT INTO users (name, role, author <~ books: (title, content))
VALUES
(
'New User 1',
2,
VALUES (
('Rich Dad & Poor Dad - part 4', 'content...4')
)
),
(
'New User 2',
2,
VALUES (
('Rich Dad & Poor Dad - part 5', 'content...5')
)
),
(
'New User 3',
2,
VALUES (
('Beauty & the Beast - part 6', 'content...6')
)
)
RETURNING id
`, { inspect: true });
console.log('INSERT INTO USERS: ', numRows2);
console.log('All books', await client.database('public').table('books').select());
console.log('All roles', await client.database('public').table('roles').select());
console.log('All users', await client.database('public').table('users').select());
//const ww = await client.query(`SELECT title, content, author ~> name, author ~> role ~> name role_name FROM books as BBBBB where author ~> role ~> name = 'admin'`);
const structure = await client.query(`SELECT name, role <~ author <~ books: { title, author: { name, role: { name } } }[] as posts FROM roles as r`, { inspect: true });
//const ww = await client.query(`SELECT users.name, roles.name as role_name FROM users LEFT JOIN roles ON roles.id = users.role where roles.name = ${ dialect === 'mysql' ? '?' : '$1' }`, { values: ['admin'] });
console.table(structure);
console.log(await client.database('public').table('users').upsert({ data: { title: 'Untitled', name: 'Jude' }, returning: '*' }));
console.log(await client.database('public').table('users').upsert({ data: { title: 'Untitled', name: 'Jude' }, returning: '*' }));
console.log(await client.database('public').table('users').select({ where: 2 }));
});
}
/*
// Clean up
console.log('DROP 3', await client.query(`DROP TABLE if exists ${ dbPublic }.books${ dialect === 'mysql' ? '' : ' CASCADE' }`));
console.log('DROP 2', await client.query(`DROP TABLE if exists ${ dbPublic }.users${ dialect === 'mysql' ? '' : ' CASCADE' }`));
console.log('DROP 1', await client.query(`DROP TABLE if exists ${ dbPublic }.roles${ dialect === 'mysql' ? '' : ' CASCADE' }`));
console.log('DROP 5', await client.query(`DROP SCHEMA if exists test_db${ dialect === 'mysql' ? '' : ' CASCADE' }`));
console.log('---PUBLIC TABLES AFTER:', (await client.rootSchema({ depth: 1 })).database(dbPublic).tables(false));
console.log('---DATABSES AFTER:', (await client.rootSchema()).databases(false));
*/
console.log('\n\n\n\n\n\n\n');
await linkedDB.table('savepoints').delete(true);
console.log('the end.');
process.exit();