@starbemtech/star-db-query-builder 1.0.38 → 1.2.1

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.
Files changed (85) hide show
  1. package/.github/workflows/publish.yml +118 -0
  2. package/ARCHITECTURE.md +313 -0
  3. package/CHANGELOG.md +65 -0
  4. package/README.md +1309 -129
  5. package/coverage/base.css +224 -0
  6. package/coverage/block-navigation.js +87 -0
  7. package/coverage/favicon.png +0 -0
  8. package/coverage/index.html +131 -0
  9. package/coverage/lcov-report/block-navigation.js +1 -1
  10. package/coverage/lcov-report/index.html +41 -11
  11. package/coverage/lcov-report/mysqlClient.ts.html +685 -0
  12. package/coverage/lcov-report/pgClient.ts.html +823 -0
  13. package/coverage/lcov-report/sorter.js +21 -7
  14. package/coverage/lcov.info +533 -0
  15. package/coverage/mysqlClient.ts.html +685 -0
  16. package/coverage/pgClient.ts.html +823 -0
  17. package/coverage/prettify.css +1 -0
  18. package/coverage/prettify.js +2 -0
  19. package/coverage/sort-arrow-sprite.png +0 -0
  20. package/coverage/sorter.js +210 -0
  21. package/dist/index.d.ts +5 -4
  22. package/dist/index.js +1 -1
  23. package/dist/index.js.map +1 -1
  24. package/dist/src/core/repository.d.ts +374 -0
  25. package/dist/src/core/repository.js +677 -0
  26. package/dist/src/core/repository.js.map +1 -0
  27. package/dist/src/{default → core}/types.d.ts +9 -1
  28. package/dist/src/{default → core}/types.js.map +1 -1
  29. package/dist/src/core/utils.d.ts +133 -0
  30. package/dist/src/{default → core}/utils.js +167 -0
  31. package/dist/src/core/utils.js.map +1 -0
  32. package/dist/src/db/IDatabaseClient.d.ts +10 -1
  33. package/dist/src/db/initDb.d.ts +120 -1
  34. package/dist/src/db/initDb.js +119 -0
  35. package/dist/src/db/initDb.js.map +1 -1
  36. package/dist/src/db/mysqlClient.d.ts +23 -1
  37. package/dist/src/db/mysqlClient.js +115 -0
  38. package/dist/src/db/mysqlClient.js.map +1 -1
  39. package/dist/src/db/pgClient.d.ts +22 -1
  40. package/dist/src/db/pgClient.js +127 -0
  41. package/dist/src/db/pgClient.js.map +1 -1
  42. package/dist/src/monitor/monitor.d.ts +6 -1
  43. package/dist/src/monitor/monitor.js +5 -0
  44. package/dist/src/monitor/monitor.js.map +1 -1
  45. package/dist/src/setupTests.d.ts +26 -0
  46. package/dist/src/setupTests.js +43 -0
  47. package/dist/src/setupTests.js.map +1 -0
  48. package/docs/INDEX.md +145 -0
  49. package/docs/methods/findFirst.md +394 -0
  50. package/docs/methods/findMany.md +587 -0
  51. package/docs/methods/insert.md +536 -0
  52. package/docs/methods/insertMany.md +627 -0
  53. package/docs/methods/joins.md +781 -0
  54. package/docs/methods/rawQuery.md +284 -0
  55. package/docs/methods/transactions.md +737 -0
  56. package/eslint.config.mjs +77 -0
  57. package/index.ts +5 -4
  58. package/jest.config.ts +23 -28
  59. package/package.json +52 -29
  60. package/scripts/release.sh +123 -0
  61. package/src/core/repository.ts +865 -0
  62. package/src/{default → core}/types.ts +11 -2
  63. package/src/{default → core}/utils.ts +168 -0
  64. package/src/db/IDatabaseClient.ts +11 -1
  65. package/src/db/__tests__/mysqlClient.test.ts +262 -0
  66. package/src/db/__tests__/pgClient.test.ts +260 -0
  67. package/src/db/initDb.ts +120 -1
  68. package/src/db/mysqlClient.ts +119 -3
  69. package/src/db/pgClient.ts +131 -3
  70. package/src/monitor/monitor.ts +5 -0
  71. package/src/setupTests.ts +45 -0
  72. package/tsconfig.test.json +21 -0
  73. package/.eslintignore +0 -4
  74. package/.eslintrc.json +0 -32
  75. package/coverage/clover.xml +0 -6
  76. package/coverage/coverage-final.json +0 -1
  77. package/dist/.eslintrc.json +0 -32
  78. package/dist/src/default/genericRepository.d.ts +0 -20
  79. package/dist/src/default/genericRepository.js +0 -192
  80. package/dist/src/default/genericRepository.js.map +0 -1
  81. package/dist/src/default/utils.d.ts +0 -9
  82. package/dist/src/default/utils.js.map +0 -1
  83. package/index.d.ts +0 -60
  84. package/src/default/genericRepository.ts +0 -320
  85. /package/dist/src/{default → core}/types.js +0 -0
@@ -0,0 +1,118 @@
1
+ name: Publish to NPM
2
+
3
+ on:
4
+ push:
5
+ tags:
6
+ - 'v*'
7
+ branches:
8
+ - main
9
+ pull_request:
10
+ branches:
11
+ - main
12
+
13
+ jobs:
14
+ test:
15
+ runs-on: ubuntu-latest
16
+
17
+ strategy:
18
+ matrix:
19
+ node-version: [18, 20, 22]
20
+
21
+ steps:
22
+ - name: Checkout code
23
+ uses: actions/checkout@v4
24
+
25
+ - name: Setup pnpm
26
+ uses: pnpm/action-setup@v4
27
+ with:
28
+ version: 8.6.2
29
+
30
+ - name: Setup Node.js ${{ matrix.node-version }}
31
+ uses: actions/setup-node@v4
32
+ with:
33
+ node-version: ${{ matrix.node-version }}
34
+
35
+ - name: Install dependencies
36
+ run: |
37
+ pnpm install
38
+
39
+ - name: Run linting
40
+ run: |
41
+ pnpm run lint
42
+
43
+ - name: Run tests
44
+ run: |
45
+ pnpm run test:ci
46
+
47
+ - name: Build package
48
+ run: |
49
+ pnpm run build
50
+
51
+ publish:
52
+ needs: test
53
+ runs-on: ubuntu-latest
54
+ if: startsWith(github.ref, 'refs/tags/v')
55
+
56
+ steps:
57
+ - name: Checkout code
58
+ uses: actions/checkout@v4
59
+
60
+ - name: Setup pnpm
61
+ uses: pnpm/action-setup@v4
62
+ with:
63
+ version: 8.6.2
64
+
65
+ - name: Setup Node.js
66
+ uses: actions/setup-node@v4
67
+ with:
68
+ node-version: '20'
69
+ registry-url: 'https://registry.npmjs.org'
70
+
71
+ - name: Install dependencies
72
+ run: |
73
+ pnpm install
74
+
75
+ - name: Build package
76
+ run: |
77
+ pnpm run build
78
+
79
+ - name: Publish to NPM
80
+ run: |
81
+ npm publish --access public
82
+ env:
83
+ NODE_AUTH_TOKEN: ${{ secrets.NPM_TOKEN }}
84
+
85
+ - name: Create GitHub Release
86
+ uses: actions/create-release@v1
87
+ env:
88
+ GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
89
+ with:
90
+ tag_name: ${{ github.ref }}
91
+ release_name: Release ${{ github.ref }}
92
+ body: |
93
+ ## 🚀 New Release: ${{ github.ref }}
94
+
95
+ ### 📦 Published to NPM
96
+ Package: `star-db-query-builder@${{ github.ref_name }}`
97
+
98
+ ### 🔗 Links
99
+ - [NPM Package](https://www.npmjs.com/package/@starbemtech/star-db-query-builder)
100
+ - [Documentation](https://github.com/starbem/star-db-query-builder#readme)
101
+
102
+ ### 📋 What's Changed
103
+ ${{ github.event.head_commit.message }}
104
+
105
+ ### 🏗️ Build Info
106
+ - Node.js Version: 20
107
+ - Build Date: ${{ github.event.head_commit.timestamp }}
108
+ - Commit: ${{ github.sha }}
109
+
110
+ ### 📥 Installation
111
+ ```bash
112
+ npm install star-db-query-builder@${{ github.ref_name }}
113
+ ```
114
+
115
+ ### 🔍 Changelog
116
+ Check the [CHANGELOG.md](https://github.com/starbem/star-db-query-builder/blob/main/CHANGELOG.md) for detailed changes.
117
+ draft: false
118
+ prerelease: false
@@ -0,0 +1,313 @@
1
+ # 🏗️ Star DB Query Builder Architecture
2
+
3
+ This document describes the internal architecture of the Star DB Query Builder library, explaining how components relate to each other and how the library works internally.
4
+
5
+ ## 📋 Overview
6
+
7
+ The library is structured in well-defined layers, following single responsibility principles and low coupling. Each module has a specific responsibility and communicates with other modules through well-defined interfaces.
8
+
9
+ ```
10
+ ┌─────────────────────────────────────────────────────────────┐
11
+ │ Star DB Query Builder │
12
+ ├─────────────────────────────────────────────────────────────┤
13
+ │ 📚 Public API (index.ts) │
14
+ ├─────────────────────────────────────────────────────────────┤
15
+ │ 🔧 Generic Repository (default/) │
16
+ │ ├── genericRepository.ts - CRUD Methods │
17
+ │ ├── types.ts - TypeScript Types │
18
+ │ └── utils.ts - Query Utilities │
19
+ ├─────────────────────────────────────────────────────────────┤
20
+ │ 🗄️ Database Clients (db/) │
21
+ │ ├── initDb.ts - Connection Initialization │
22
+ │ ├── pgClient.ts - PostgreSQL Client │
23
+ │ ├── mysqlClient.ts - MySQL Client │
24
+ │ └── IDatabaseClient.ts - Client Interface │
25
+ ├─────────────────────────────────────────────────────────────┤
26
+ │ 📊 Monitoring (monitor/) │
27
+ │ └── monitor.ts - Event System │
28
+ └─────────────────────────────────────────────────────────────┘
29
+ ```
30
+
31
+ ## 🔧 Main Components
32
+
33
+ ### 1. Public API (`index.ts`)
34
+
35
+ **Responsibility**: Entry point of the library, exports all public functionalities.
36
+
37
+ **Features**:
38
+
39
+ - Exports initialization configurations
40
+ - Exports generic repository methods
41
+ - Exports monitoring system
42
+ - Exports TypeScript types
43
+
44
+ ```typescript
45
+ // Configs
46
+ export * from './src/db/initDb'
47
+
48
+ // Generic Repository
49
+ export * from './src/default/genericRepository'
50
+
51
+ // Monitor
52
+ export * from './src/monitor/monitor'
53
+
54
+ // Types Definition
55
+ export type { PgPoolConfig, MySqlPoolOptions, TypeConditions }
56
+ ```
57
+
58
+ ### 2. Database Clients (`db/`)
59
+
60
+ **Responsibility**: Manage connections with different types of databases.
61
+
62
+ #### `initDb.ts`
63
+
64
+ - Initializes connection pools for PostgreSQL and MySQL
65
+ - Manages multiple named connections
66
+ - Configures retry options
67
+ - Installs necessary extensions (e.g., unaccent)
68
+
69
+ #### `IDatabaseClient.ts`
70
+
71
+ - Interface that defines the contract for database clients
72
+ - Ensures consistency between different implementations
73
+
74
+ #### `pgClient.ts`
75
+
76
+ - Specific implementation for PostgreSQL
77
+ - Support for extensions like unaccent
78
+ - Management of placeholders ($1, $2, etc.)
79
+ - Handling of PostgreSQL-specific types
80
+
81
+ #### `mysqlClient.ts`
82
+
83
+ - Specific implementation for MySQL
84
+ - Management of placeholders (?)
85
+ - Handling of MySQL-specific types
86
+
87
+ ### 3. Generic Repository (`default/`)
88
+
89
+ **Responsibility**: Provide generic and type-safe CRUD methods.
90
+
91
+ #### `genericRepository.ts`
92
+
93
+ Contains all main methods:
94
+
95
+ - **`findFirst<T>`**: Finds the first record that matches the criteria
96
+ - **`findMany<T>`**: Finds multiple records with pagination
97
+ - **`insert<P, R>`**: Inserts a new record
98
+ - **`insertMany<P, R>`**: Inserts multiple records in batch
99
+ - **`update<P, R>`**: Updates a specific record
100
+ - **`updateMany<P, R>`**: Updates multiple records
101
+ - **`deleteOne<T>`**: Removes a record (soft/hard delete)
102
+ - **`deleteMany<T>`**: Removes multiple records
103
+ - **`joins<T>`**: Executes queries with joins
104
+
105
+ #### `types.ts`
106
+
107
+ Defines all TypeScript types:
108
+
109
+ ```typescript
110
+ export interface RetryOptions {
111
+ retries?: number
112
+ factor?: number
113
+ minTimeout?: number
114
+ maxTimeout?: number
115
+ randomize?: boolean
116
+ }
117
+
118
+ export interface OperatorCondition {
119
+ operator:
120
+ | 'ILIKE'
121
+ | 'LIKE'
122
+ | '='
123
+ | '>'
124
+ | '<'
125
+ | 'IN'
126
+ | 'BETWEEN'
127
+ | '!='
128
+ | '<='
129
+ | '>='
130
+ | 'NOT IN'
131
+ | 'LIKE'
132
+ | 'NOT LIKE'
133
+ | 'IS NULL'
134
+ | 'IS NOT NULL'
135
+ | 'NOT EXISTS'
136
+ value: SimpleValue | SimpleValue[]
137
+ }
138
+
139
+ export type Conditions<T> = {
140
+ [P in keyof T]?: Condition<T[P]>
141
+ } & LogicalCondition<T>
142
+ ```
143
+
144
+ #### `utils.ts`
145
+
146
+ Utilities for building SQL queries:
147
+
148
+ - **`createSelectFields`**: Builds SELECT clause
149
+ - **`createWhereClause`**: Builds WHERE clause
150
+ - **`createOrderByClause`**: Builds ORDER BY clause
151
+ - **`createGroupByClause`**: Builds GROUP BY clause
152
+ - **`createLimitClause`**: Builds LIMIT clause
153
+ - **`createOffsetClause`**: Builds OFFSET clause
154
+ - **`generatePlaceholders`**: Generates placeholders for prepared statements
155
+ - **`generateSetClause`**: Builds SET clause for UPDATE
156
+
157
+ ### 4. Monitoring (`monitor/`)
158
+
159
+ **Responsibility**: Provide event system for monitoring and logging.
160
+
161
+ #### `monitor.ts`
162
+
163
+ - EventEmitter for database events
164
+ - Available events:
165
+ - `CONNECTION_CREATED`: New connection created
166
+ - `QUERY_START`: Query started
167
+ - `QUERY_END`: Query finished
168
+ - `QUERY_ERROR`: Query error
169
+ - `RETRY_ATTEMPT`: Retry attempt
170
+
171
+ ## 🔄 Data Flow
172
+
173
+ ### 1. Initialization
174
+
175
+ ```
176
+ 1. initDb() is called with configurations
177
+ 2. Connection pool is created (PostgreSQL/MySQL)
178
+ 3. Specific client is instantiated
179
+ 4. Client is stored in global registry
180
+ 5. CONNECTION_CREATED event is emitted
181
+ ```
182
+
183
+ ### 2. Query Execution
184
+
185
+ ```
186
+ 1. Repository method is called (e.g., findMany)
187
+ 2. Parameters are validated
188
+ 3. Utilities build the SQL query
189
+ 4. QUERY_START event is emitted
190
+ 5. Query is executed on database client
191
+ 6. Results are processed
192
+ 7. QUERY_END event is emitted
193
+ 8. Results are returned
194
+ ```
195
+
196
+ ### 3. Error Handling
197
+
198
+ ```
199
+ 1. Error occurs during execution
200
+ 2. QUERY_ERROR event is emitted
201
+ 3. Retry system is triggered (if configured)
202
+ 4. RETRY_ATTEMPT event is emitted for each attempt
203
+ 5. If all attempts fail, error is propagated
204
+ ```
205
+
206
+ ## 🛡️ Security
207
+
208
+ ### SQL Injection Prevention
209
+
210
+ - **Prepared Statements**: All queries use prepared statements
211
+ - **Parameter Binding**: Values are passed as parameters, not concatenated
212
+ - **Input Validation**: Input validation before query construction
213
+
214
+ ### Connection Security
215
+
216
+ - **Connection Pooling**: Secure connection reuse
217
+ - **Timeout Configuration**: Configurable timeouts to avoid pending connections
218
+ - **SSL Support**: SSL support for PostgreSQL
219
+
220
+ ## ⚡ Performance
221
+
222
+ ### Implemented Optimizations
223
+
224
+ - **Connection Pooling**: Efficient connection reuse
225
+ - **Batch Operations**: Batch operations for better performance
226
+ - **Query Optimization**: Optimized query construction
227
+ - **Memory Management**: Efficient memory management
228
+
229
+ ### Performance Monitoring
230
+
231
+ - **Query Timing**: Query execution time measurement
232
+ - **Connection Metrics**: Connection usage metrics
233
+ - **Error Tracking**: Error and retry tracking
234
+
235
+ ## 🔧 Extensibility
236
+
237
+ ### Adding New Databases
238
+
239
+ 1. Implement `IDatabaseClient` interface
240
+ 2. Create specific client (e.g., `mongoClient.ts`)
241
+ 3. Add type to `DBClients` enum
242
+ 4. Update `initDb.ts` to support new type
243
+ 5. Add tests for new client
244
+
245
+ ### Adding New Operators
246
+
247
+ 1. Add operator to `OperatorCondition` type
248
+ 2. Implement logic in `createWhereClause`
249
+ 3. Add tests for new operator
250
+ 4. Document usage of new operator
251
+
252
+ ### Adding New Events
253
+
254
+ 1. Add event to `MonitorEvents` enum
255
+ 2. Emit event at appropriate points
256
+ 3. Document new event
257
+ 4. Add usage examples
258
+
259
+ ## 🧪 Testing
260
+
261
+ ### Test Structure
262
+
263
+ - **Unit Tests**: Individual function tests
264
+ - **Integration Tests**: Integration tests with real database
265
+ - **Mock Tests**: Mock tests for isolation
266
+
267
+ ### Coverage
268
+
269
+ - **Functions**: 100% of functions tested
270
+ - **Branches**: 90%+ branch coverage
271
+ - **Lines**: 95%+ line coverage
272
+
273
+ ## 📊 Metrics and Monitoring
274
+
275
+ ### Collected Metrics
276
+
277
+ - **Query Performance**: Query execution time
278
+ - **Connection Usage**: Connection pool usage
279
+ - **Error Rates**: Error rates by type
280
+ - **Retry Attempts**: Number of retry attempts
281
+
282
+ ### External System Integration
283
+
284
+ - **Winston**: Winston integration for logging
285
+ - **Prometheus**: Metrics for Prometheus
286
+ - **Custom Loggers**: Custom logger support
287
+
288
+ ## 🔮 Technical Roadmap
289
+
290
+ ### Next Versions
291
+
292
+ - **MongoDB Support**: MongoDB client
293
+ - **Redis Support**: Redis client
294
+ - **Query Caching**: Query caching system
295
+ - **Connection Health Checks**: Connection health checks
296
+ - **Performance Metrics**: Detailed performance metrics
297
+ - **Migration Tools**: Data migration tools
298
+ - **Schema Validation**: Schema validation
299
+ - **GraphQL Integration**: GraphQL integration
300
+
301
+ ### Planned Improvements
302
+
303
+ - **Better Error Messages**: More descriptive error messages
304
+ - **Query Optimization**: Additional query optimizations
305
+ - **Memory Management**: Better memory management
306
+ - **Connection Pool Tuning**: Automatic connection pool tuning
307
+
308
+ ---
309
+
310
+ <div align="center">
311
+ <p>📚 For more information, see the <a href="README.md">main documentation</a></p>
312
+ <p>🔗 <a href="https://github.com/starbem/star-db-query-builder">GitHub Repository</a></p>
313
+ </div>
package/CHANGELOG.md ADDED
@@ -0,0 +1,65 @@
1
+ # Changelog
2
+
3
+ All notable changes to this project will be documented in this file.
4
+
5
+ The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.0.0/),
6
+ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0.html).
7
+
8
+ ## [1.1.0] - 2024-12-19
9
+
10
+ ### Added
11
+
12
+ - **Multi-Connection Support**: Support for multiple simultaneous connections
13
+ - **TypeScript Support**: Complete typing with TypeScript 5.8+
14
+ - **Auto Retry Mechanism**: Automatic retry system for transient errors
15
+ - **Monitoring System**: Event system for monitoring and logging
16
+ - **Batch Operations**: Optimized batch operations (insertMany, updateMany)
17
+ - **Unaccent Support**: Support for PostgreSQL unaccent extension
18
+ - **Complex Query Builder**: Fluent interface for complex queries
19
+ - **Transaction Support**: Transaction support
20
+ - **Connection Pooling**: Efficient connection management
21
+
22
+ ### Features
23
+
24
+ - **PostgreSQL Client**: Complete PostgreSQL client with extensions
25
+ - **MySQL Client**: Complete MySQL client for MySQL 5.7+
26
+ - **Generic Repository**: Generic and type-safe CRUD methods
27
+ - **Query Utils**: Utilities for building SQL queries
28
+ - **Error Handling**: Robust error handling
29
+ - **Performance Optimization**: Performance optimizations for batch operations
30
+
31
+ ### Technical
32
+
33
+ - **ESLint + Prettier**: Configuration for clean and consistent code
34
+ - **Jest Testing**: Unit and integration tests
35
+ - **Husky Hooks**: Git hooks for code quality
36
+ - **GitHub Actions**: Automated CI/CD
37
+ - **NPM Publishing**: Automated NPM publishing
38
+
39
+ ### Documentation
40
+
41
+ - **Complete API Reference**: Complete API documentation
42
+ - **Practical Examples**: Practical usage examples
43
+ - **Advanced Use Cases**: Advanced use cases
44
+ - **Monitoring Guide**: Monitoring and logging guide
45
+ - **Installation Guide**: Installation and configuration guide
46
+
47
+ ## [Unreleased]
48
+
49
+ ### Planned
50
+
51
+ - **MongoDB Support**: MongoDB support
52
+ - **Redis Support**: Redis support
53
+ - **Query Caching**: Query caching system
54
+ - **Connection Health Checks**: Connection health checks
55
+ - **Performance Metrics**: Detailed performance metrics
56
+ - **Migration Tools**: Data migration tools
57
+ - **Schema Validation**: Schema validation
58
+ - **GraphQL Integration**: GraphQL integration
59
+
60
+ ### Improvements
61
+
62
+ - **Better Error Messages**: More descriptive error messages
63
+ - **Query Optimization**: Additional query optimizations
64
+ - **Memory Management**: Better memory management
65
+ - **Connection Pool Tuning**: Automatic connection pool tuning