@platformatic/sql-mapper 0.46.1 → 0.47.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1,138 +0,0 @@
1
- import { expectType } from 'tsd'
2
- import { SQL, SQLQuery } from '@databases/sql'
3
- import { fastify, FastifyInstance, FastifyReply } from 'fastify'
4
- import { FastifyError } from '@fastify/error'
5
- import {
6
- connect,
7
- plugin,
8
- utils,
9
- Entity,
10
- DBEntityField,
11
- Database,
12
- SQLMapperPluginInterface,
13
- EntityHooks,
14
- createConnectionPool,
15
- Entities,
16
- errors
17
- } from '../../mapper'
18
-
19
- const log = {
20
- trace() { },
21
- error() { },
22
- warn() { }
23
- }
24
-
25
- declare module 'fastify' {
26
- interface FastifyInstance {
27
- platformatic: SQLMapperPluginInterface<Entities>
28
- }
29
- }
30
-
31
- const pluginOptions: SQLMapperPluginInterface<Entities> = await connect<Entities>({ connectionString: '', log })
32
- expectType<Database>(pluginOptions.db)
33
- expectType<SQL>(pluginOptions.sql)
34
- expectType<{ [entityName: string]: Entity }>(pluginOptions.entities)
35
-
36
- expectType<Promise<void>>(pluginOptions.cleanUpAllEntities())
37
-
38
- interface EntityFields {
39
- id: number,
40
- name: string,
41
- }
42
-
43
- const entity: Entity<EntityFields> = pluginOptions.entities.entityName
44
- expectType<string>(entity.name)
45
- expectType<string>(entity.singularName)
46
- expectType<string>(entity.pluralName)
47
- expectType<string>(entity.primaryKey)
48
- expectType<string>(entity.table)
49
- expectType<any[]>(entity.relations)
50
- expectType<{ [columnName: string]: DBEntityField }>(entity.fields)
51
- expectType<{ [columnName: string]: DBEntityField }>(entity.camelCasedFields)
52
- expectType<(input: { [columnName: string]: any }) => { [columnName: string]: any }>(entity.fixInput)
53
- expectType<(input: { [columnName: string]: any }) => { [columnName: string]: any }>(entity.fixOutput)
54
- expectType<Partial<EntityFields>[]>(await entity.find())
55
- expectType<Partial<EntityFields>[]>(await entity.insert({ inputs: [{ id: 1, name: 'test' }] }))
56
- expectType<Partial<EntityFields>>(await entity.save({ input: { id: 1, name: 'test' } }))
57
- expectType<Partial<EntityFields>[]>(await entity.delete())
58
- expectType<number>(await entity.count())
59
-
60
- const entityHooks: EntityHooks = {
61
- async find(originalFind: typeof entity.find, ...options: Parameters<typeof entity.find>): ReturnType<typeof entity.find> { return [] },
62
- async insert(originalInsert: typeof entity.insert, ...options: Parameters<typeof entity.insert>): ReturnType<typeof entity.insert> { return [] },
63
- async save(originalSave: typeof entity.save, ...options: Parameters<typeof entity.save>): ReturnType<typeof entity.save> { return {} },
64
- async delete(originalDelete: typeof entity.delete, ...options: Parameters<typeof entity.delete>): ReturnType<typeof entity.delete> { return [] },
65
- async count(originalCount: typeof entity.count, ...options: Parameters<typeof entity.count>): ReturnType<typeof entity.count> { return 0 },
66
- }
67
- expectType<EntityHooks>(entityHooks)
68
- expectType<SQLMapperPluginInterface<Entities>>(await connect<Entities>({ connectionString: '', log }))
69
- expectType<SQLMapperPluginInterface<Entities>>(await connect<Entities>({ connectionString: '', autoTimestamp: true, log }))
70
- expectType<SQLMapperPluginInterface<Entities>>(await connect<Entities>({ connectionString: '', hooks: {}, log }))
71
- expectType<SQLMapperPluginInterface<Entities>>(await connect<Entities>({
72
- connectionString: '', hooks: {
73
- Page: entityHooks
74
- },
75
- log
76
- }))
77
- expectType<SQLMapperPluginInterface<Entities>>(await connect<Entities>({ connectionString: '', ignore: {}, log }))
78
- expectType<SQLMapperPluginInterface<Entities>>(await connect<Entities>({
79
- connectionString: '', log, onDatabaseLoad(db: Database, sql: SQL) {
80
- expectType<(query: SQLQuery) => Promise<any[]>>(db.query)
81
- expectType<() => Promise<void>>(db.dispose)
82
- expectType<boolean | undefined>(pluginOptions.db.isMySql)
83
- expectType<boolean | undefined>(pluginOptions.db.isMariaDB)
84
- expectType<boolean | undefined>(pluginOptions.db.isSQLite)
85
- expectType<boolean | undefined>(pluginOptions.db.isPg)
86
-
87
- }
88
- }))
89
-
90
- const instance: FastifyInstance = fastify()
91
- instance.register(plugin, { connectionString: '', autoTimestamp: true })
92
- instance.register((instance) => {
93
- expectType<SQLMapperPluginInterface<Entities>>(instance.platformatic)
94
-
95
- instance.platformatic.addEntityHooks<EntityFields>('something', {
96
- async find(originalFind, options) {
97
- expectType<Partial<EntityFields>[]>(await originalFind())
98
- expectType<Parameters<typeof entity.find>[0]>(options)
99
-
100
- return [{
101
- id: 42
102
- }]
103
- }
104
- })
105
-
106
- instance.get('/', async (request, reply) => {
107
- const ctx = request.platformaticContext
108
- expectType<FastifyInstance>(ctx.app)
109
- expectType<FastifyReply>(ctx.reply)
110
- await instance.platformatic.cleanUpAllEntities()
111
- })
112
- })
113
-
114
- expectType<(str: string) => string>(utils.toSingular)
115
-
116
- expectType<Promise<{ db: Database, sql: SQL }>>(createConnectionPool({ connectionString: '', log }))
117
-
118
- // Errors
119
- type ErrorWithNoParams = () => FastifyError
120
- type ErrorWithOneParam = (param: string) => FastifyError
121
- type ErrorWithOneAnyParam = (param: any) => FastifyError
122
- type ErrorWithTwoParams = (param1: string, param2: string) => FastifyError
123
-
124
- expectType<ErrorWithOneParam>(errors.CannotFindEntityError)
125
- expectType<ErrorWithNoParams>(errors.SpecifyProtocolError)
126
- expectType<ErrorWithNoParams>(errors.ConnectionStringRequiredError)
127
- expectType<ErrorWithOneAnyParam>(errors.TableMustBeAStringError)
128
- expectType<ErrorWithOneParam>(errors.UnknownFieldError)
129
- expectType<ErrorWithNoParams>(errors.InputNotProvidedError)
130
- expectType<ErrorWithOneParam>(errors.UnsupportedWhereClauseError)
131
- expectType<ErrorWithNoParams>(errors.UnsupportedOperatorForArrayFieldError)
132
- expectType<ErrorWithNoParams>(errors.UnsupportedOperatorForNonArrayFieldError)
133
- expectType<ErrorWithOneParam>(errors.ParamNotAllowedError)
134
- expectType<ErrorWithTwoParams>(errors.InvalidPrimaryKeyTypeError)
135
- expectType<ErrorWithTwoParams>(errors.ParamLimitNotAllowedError)
136
- expectType<ErrorWithOneParam>(errors.ParamLimitMustBeNotNegativeError)
137
- expectType<ErrorWithOneParam>(errors.MissingValueForPrimaryKeyError)
138
- expectType<ErrorWithNoParams>(errors.SQLiteOnlySupportsAutoIncrementOnOneColumnError)
@@ -1,319 +0,0 @@
1
- 'use strict'
2
-
3
- const { test } = require('tap')
4
- const { connect } = require('..')
5
- const { clear, connInfo, isSQLite, isMysql } = require('./helper')
6
- const { setTimeout } = require('timers/promises')
7
-
8
- const fakeLogger = {
9
- trace: () => {},
10
- error: () => {}
11
- }
12
-
13
- test('updateMany successful', async ({ pass, teardown, same }) => {
14
- const mapper = await connect({
15
- ...connInfo,
16
- log: fakeLogger,
17
- async onDatabaseLoad (db, sql) {
18
- teardown(() => db.dispose())
19
- pass('onDatabaseLoad called')
20
-
21
- await clear(db, sql)
22
-
23
- if (isSQLite) {
24
- await db.query(sql`CREATE TABLE posts (
25
- id INTEGER PRIMARY KEY,
26
- title VARCHAR(42),
27
- long_text TEXT,
28
- counter INTEGER
29
- );`)
30
- } else {
31
- await db.query(sql`CREATE TABLE posts (
32
- id SERIAL PRIMARY KEY,
33
- title VARCHAR(42),
34
- long_text TEXT,
35
- counter INTEGER
36
- );`)
37
- }
38
- }
39
- })
40
-
41
- const entity = mapper.entities.post
42
-
43
- const posts = [{
44
- title: 'Dog',
45
- longText: 'Foo',
46
- counter: 10
47
- }, {
48
- title: 'Cat',
49
- longText: 'Bar',
50
- counter: 20
51
- }, {
52
- title: 'Mouse',
53
- longText: 'Baz',
54
- counter: 30
55
- }, {
56
- title: 'Duck',
57
- longText: 'A duck tale',
58
- counter: 40
59
- }]
60
-
61
- await entity.insert({
62
- inputs: posts
63
- })
64
-
65
- await entity.updateMany({
66
- where: {
67
- counter: {
68
- gte: 30
69
- }
70
- },
71
- input: {
72
- title: 'Updated title'
73
- }
74
- })
75
-
76
- const updatedPosts = await entity.find({})
77
-
78
- same(updatedPosts, [{
79
- id: '1',
80
- title: 'Dog',
81
- longText: 'Foo',
82
- counter: 10
83
- }, {
84
- id: '2',
85
- title: 'Cat',
86
- longText: 'Bar',
87
- counter: 20
88
- }, {
89
- id: '3',
90
- title: 'Updated title',
91
- longText: 'Baz',
92
- counter: 30
93
- }, {
94
- id: '4',
95
- title: 'Updated title',
96
- longText: 'A duck tale',
97
- counter: 40
98
- }])
99
- })
100
-
101
- test('updateMany will return the updated values', async ({ pass, teardown, same }) => {
102
- const mapper = await connect({
103
- ...connInfo,
104
- log: fakeLogger,
105
- async onDatabaseLoad (db, sql) {
106
- teardown(() => db.dispose())
107
- pass('onDatabaseLoad called')
108
-
109
- await clear(db, sql)
110
-
111
- if (isSQLite) {
112
- await db.query(sql`CREATE TABLE posts (
113
- id INTEGER PRIMARY KEY,
114
- title VARCHAR(42),
115
- long_text TEXT,
116
- counter INTEGER
117
- );`)
118
- } else {
119
- await db.query(sql`CREATE TABLE posts (
120
- id SERIAL PRIMARY KEY,
121
- title VARCHAR(42),
122
- long_text TEXT,
123
- counter INTEGER
124
- );`)
125
- }
126
- }
127
- })
128
-
129
- const entity = mapper.entities.post
130
-
131
- const posts = [{
132
- title: 'Dog',
133
- longText: 'Foo',
134
- counter: 10
135
- }, {
136
- title: 'Cat',
137
- longText: 'Bar',
138
- counter: 20
139
- }, {
140
- title: 'Mouse',
141
- longText: 'Baz',
142
- counter: 30
143
- }, {
144
- title: 'Duck',
145
- longText: 'A duck tale',
146
- counter: 40
147
- }]
148
-
149
- await entity.insert({
150
- inputs: posts
151
- })
152
-
153
- const updatedPosts = await entity.updateMany({
154
- where: {
155
- counter: {
156
- gte: 30
157
- }
158
- },
159
- input: {
160
- title: 'Updated title'
161
- },
162
- fields: ['id', 'counter']
163
- })
164
-
165
- same(updatedPosts, [{
166
- id: '3',
167
- counter: 30
168
- }, {
169
- id: '4',
170
- counter: 40
171
- }])
172
- })
173
-
174
- test('updateMany missing input', async ({ pass, teardown, rejects }) => {
175
- const mapper = await connect({
176
- ...connInfo,
177
- log: fakeLogger,
178
- async onDatabaseLoad (db, sql) {
179
- teardown(() => db.dispose())
180
- pass('onDatabaseLoad called')
181
-
182
- await clear(db, sql)
183
-
184
- if (isSQLite) {
185
- await db.query(sql`CREATE TABLE posts (
186
- id INTEGER PRIMARY KEY,
187
- title VARCHAR(42),
188
- long_text TEXT,
189
- counter INTEGER
190
- );`)
191
- } else {
192
- await db.query(sql`CREATE TABLE posts (
193
- id SERIAL PRIMARY KEY,
194
- title VARCHAR(42),
195
- long_text TEXT,
196
- counter INTEGER
197
- );`)
198
- }
199
- }
200
- })
201
-
202
- const entity = mapper.entities.post
203
-
204
- const posts = [{
205
- title: 'Dog',
206
- longText: 'Foo',
207
- counter: 10
208
- }, {
209
- title: 'Cat',
210
- longText: 'Bar',
211
- counter: 20
212
- }, {
213
- title: 'Mouse',
214
- longText: 'Baz',
215
- counter: 30
216
- }, {
217
- title: 'Duck',
218
- longText: 'A duck tale',
219
- counter: 40
220
- }]
221
-
222
- await entity.insert({
223
- inputs: posts
224
- })
225
-
226
- rejects(entity.updateMany({
227
- where: {
228
- counter: {
229
- gte: 30
230
- }
231
- }
232
- }), new Error('Input not provided.'))
233
- })
234
-
235
- test('updateMany successful and update updated_at', async ({ pass, teardown, same, notSame }) => {
236
- const mapper = await connect({
237
- ...connInfo,
238
- autoTimestamp: true,
239
- log: fakeLogger,
240
- async onDatabaseLoad (db, sql) {
241
- teardown(() => db.dispose())
242
- pass('onDatabaseLoad called')
243
-
244
- await clear(db, sql)
245
-
246
- if (isSQLite) {
247
- await db.query(sql`CREATE TABLE posts (
248
- id INTEGER PRIMARY KEY,
249
- title VARCHAR(42),
250
- long_text TEXT,
251
- counter INTEGER,
252
- created_at TIMESTAMP,
253
- updated_at TIMESTAMP
254
- );`)
255
- } else if (isMysql) {
256
- await db.query(sql`CREATE TABLE posts (
257
- id SERIAL PRIMARY KEY,
258
- title VARCHAR(42),
259
- long_text TEXT,
260
- counter INTEGER,
261
- created_at TIMESTAMP NULL DEFAULT NULL,
262
- updated_at TIMESTAMP NULL DEFAULT NULL
263
- );`)
264
- } else {
265
- await db.query(sql`CREATE TABLE posts (
266
- id SERIAL PRIMARY KEY,
267
- title VARCHAR(42),
268
- long_text TEXT,
269
- counter INTEGER,
270
- created_at TIMESTAMP,
271
- updated_at TIMESTAMP
272
- );`)
273
- }
274
- }
275
- })
276
-
277
- const entity = mapper.entities.post
278
-
279
- const posts = [{
280
- title: 'Dog',
281
- longText: 'Foo',
282
- counter: 10
283
- }, {
284
- title: 'Cat',
285
- longText: 'Bar',
286
- counter: 20
287
- }, {
288
- title: 'Mouse',
289
- longText: 'Baz',
290
- counter: 30
291
- }, {
292
- title: 'Duck',
293
- longText: 'A duck tale',
294
- counter: 40
295
- }]
296
-
297
- await entity.insert({
298
- inputs: posts
299
- })
300
- const createdPost3 = (await entity.find({ where: { id: { eq: '3' } } }))[0]
301
-
302
- await setTimeout(1000) // await 1s
303
-
304
- await entity.updateMany({
305
- where: {
306
- counter: {
307
- gte: 30
308
- }
309
- },
310
- input: {
311
- title: 'Updated title'
312
- }
313
- })
314
-
315
- const updatedPost3 = (await entity.find({ where: { id: { eq: '3' } } }))[0]
316
- same(updatedPost3.title, 'Updated title')
317
- same(createdPost3.createdAt, updatedPost3.createdAt)
318
- notSame(createdPost3.updatedAt, updatedPost3.updatedAt)
319
- })