@event-driven-io/pongo 0.1.1 → 0.2.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.
package/README.md ADDED
@@ -0,0 +1,214 @@
1
+ [![](https://dcbadge.vercel.app/api/server/fTpqUTMmVa?style=flat)](https://discord.gg/fTpqUTMmVa) [<img src="https://img.shields.io/badge/LinkedIn-0077B5?style=for-the-badge&logo=linkedin&logoColor=white" height="20px" />](https://www.linkedin.com/in/oskardudycz/) [![Github Sponsors](https://img.shields.io/static/v1?label=Sponsor&message=%E2%9D%A4&logo=GitHub&link=https://github.com/sponsors/oskardudycz/)](https://github.com/sponsors/oskardudycz/) [![blog](https://img.shields.io/badge/blog-event--driven.io-brightgreen)](https://event-driven.io/?utm_source=event_sourcing_nodejs) [![blog](https://img.shields.io/badge/%F0%9F%9A%80-Architecture%20Weekly-important)](https://www.architecture-weekly.com/?utm_source=event_sourcing_nodejs)
2
+
3
+ ![](./src/docs/public/social.png)
4
+
5
+ # Pongo
6
+
7
+ Pongo - Mongo but on Postgres and with strong consistency benefits.
8
+
9
+ ## Getting Started
10
+
11
+ Install Pongo as an npm module and save it to your package.json:
12
+
13
+ ```bash
14
+ npm install @event-driven-io/pongo
15
+ ```
16
+
17
+ Read also [introduction article on my blog](https://event-driven.io/en/introducting_pongo/) for more context.
18
+
19
+ ## Example
20
+
21
+ You can use Pongo syntax with explicit typing about supported syntax:
22
+
23
+ ```ts
24
+ import { pongoClient } from "@event-driven-io/pongo";
25
+ import { v4 as uuid } from "uuid";
26
+
27
+ type User = { name: string; age: number };
28
+
29
+ const connectionString =
30
+ "postgresql://dbuser:secretpassword@database.server.com:3211/mydb";
31
+
32
+ const pongoClient = pongoClient(connectionString);
33
+ const pongoDb = pongoClient.db();
34
+
35
+ const users = pongoDb.collection<User>("users");
36
+ const roger = { name: "Roger", age: 30 };
37
+ const anita = { name: "Anita", age: 25 };
38
+ const cruella = { _id: uuid(), name: "Cruella", age: 40 };
39
+
40
+ // Inserting
41
+ await pongoCollection.insertOne(roger);
42
+ await pongoCollection.insertOne(cruella);
43
+
44
+ const { insertedId } = await pongoCollection.insertOne(anita);
45
+ const anitaId = insertedId;
46
+
47
+ // Updating
48
+ await users.updateOne({ _id: anitaId }, { $set: { age: 31 } });
49
+
50
+ // Deleting
51
+ await pongoCollection.deleteOne({ _id: cruella._id });
52
+
53
+ // Finding by Id
54
+ const anitaFromDb = await pongoCollection.findOne({ _id: anitaId });
55
+
56
+ // Finding more
57
+ const users = await pongoCollection.find({ age: { $lt: 40 } });
58
+ ```
59
+
60
+ Or use MongoDB compliant shim:
61
+
62
+ ```ts
63
+ import { MongoClient } from "@event-driven-io/pongo";
64
+ import { v4 as uuid } from "uuid";
65
+
66
+ type User = { name: string; age: number };
67
+
68
+ const connectionString =
69
+ "postgresql://dbuser:secretpassword@database.server.com:3211/mydb";
70
+
71
+ const pongoClient = new MongoClient(postgresConnectionString);
72
+ const pongoDb = pongoClient.db();
73
+
74
+ const users = pongoDb.collection<User>("users");
75
+ const roger = { name: "Roger", age: 30 };
76
+ const anita = { name: "Anita", age: 25 };
77
+ const cruella = { _id: uuid(), name: "Cruella", age: 40 };
78
+
79
+ // Inserting
80
+ await pongoCollection.insertOne(roger);
81
+ await pongoCollection.insertOne(cruella);
82
+
83
+ const { insertedId } = await pongoCollection.insertOne(anita);
84
+ const anitaId = insertedId;
85
+
86
+ // Updating
87
+ await users.updateOne({ _id: anitaId }, { $set: { age: 31 } });
88
+
89
+ // Deleting
90
+ await pongoCollection.deleteOne({ _id: cruella._id });
91
+
92
+ // Finding by Id
93
+ const anitaFromDb = await pongoCollection.findOne({ _id: anitaId });
94
+
95
+ // Finding more
96
+ const users = await pongoCollection.find({ age: { $lt: 40 } }).toArray();
97
+ ```
98
+
99
+ ## How does it work?
100
+
101
+ **Pongo treats PostgreSQL as a Document Database benefiting from JSONB support.** Unlike the plain text storage of the traditional JSON type, JSONB stores JSON data in a binary format. This simple change brings significant advantages in terms of performance and storage efficiency.
102
+
103
+ Pongo uses the following table structure for storing collections:
104
+
105
+ ```sql
106
+ CREATE TABLE IF NOT EXISTS "YourCollectionName" (
107
+ _id UUID PRIMARY KEY,
108
+ data JSONB
109
+ )
110
+ ```
111
+
112
+ **Essentially Pongo takes MongoDB api and translates it to the native PostgreSQL queries.** It is a similar concept to [Marten](https://martendb.io/), [FerretDB](https://docs.ferretdb.io) and [AWS DocumentDB](https://aws.amazon.com/documentdb/).
113
+
114
+ **E.g. the MongoDB update syntax:**
115
+
116
+ ```typescript
117
+ const pongoCollection = pongoDb.collection<User>("users");
118
+
119
+ await pongoCollection.updateOne(
120
+ { _id: someId },
121
+ { $push: { tags: "character" } }
122
+ );
123
+ ```
124
+
125
+ will be translated to:
126
+
127
+ ```sql
128
+ UPDATE "users"
129
+ SET data = jsonb_set(data, '{tags}', (COALESCE(data->'tags', '[]'::jsonb) || to_jsonb('character')))
130
+ WHERE _id = '137ef052-e41c-428b-b606-1c8070a47eda';
131
+ ```
132
+
133
+ **Or for query:**
134
+
135
+ ```typescript
136
+ const result = await pongoCollection
137
+ .find({ "address.history": { $elemMatch: { street: "Elm St" } } })
138
+ .toArray();
139
+ ```
140
+
141
+ will result in:
142
+
143
+ ```sql
144
+ SELECT data
145
+ FROM "users"
146
+ WHERE jsonb_path_exists(
147
+ data,
148
+ '$.address.history[*] ? (@.street == "Elm St")'
149
+ );
150
+ ```
151
+
152
+ ## Why Pongo?
153
+
154
+ MongoDB is a decent database, yet it has issues around [ACID-complaince](https://jepsen.io/analyses/mongodb-4.2.6) and [licensing](https://www.percona.com/blog/is-mongodb-open-source), which can cause hardship for project scenarios and organisation policies.
155
+
156
+ **Pongo brings the [PostgreSQL shape-shifting capabilities](https://www.amazingcto.com/postgres-for-everything/) to:**
157
+
158
+ - benefit from **strong consistency** by using battle-tested and widely used PostgreSQL ACID-compliant database,
159
+ - **easier integration** with other parts of your system using PostgreSQL,
160
+ - **reuse your muscle memory from MongoDB** using compatible API. It will allow easier migration of existing projects,
161
+ - **cut boilerplate** and easier nested data management than traditional relational tables,
162
+ - operate **easier than crafting native PostgreSQL JSON queries**. They're powerful but not the most accessible,
163
+ - get **performance boost** with [JSONB indexing capabilities](https://pganalyze.com/blog/gin-index#postgresql-jsonb-and-gin-indexes),
164
+ - **benefit from PostgreSQL advanced capabilities** like [partitioning](https://www.postgresql.fastware.com/postgresql-insider-prt-ove), [logical replication](https://event-driven.io/en/push_based_outbox_pattern_with_postgres_logical_replication/) and [other PostgreSQL superpowers](https://event-driven.io/en/postgres_superpowers/)
165
+ - **seamless integration with Cloud RDSes** and solutions like [CockroachDB](https://www.cockroachlabs.com/docs/stable/why-cockroachdb), [Supabase](https://supabase.com/), [Vercel Postgres](https://vercel.com/docs/storage/vercel-postgres).
166
+
167
+ ## Storage
168
+
169
+ **The binary format of PostgreSQL JSONB means that data is pre-parsed, allowing faster read and write operations than text-based JSON.** You don't have to re-parse the data every time you query it, which saves processing time and improves overall performance. Additionally, JSONB supports advanced indexing options like GIN and GiST indexes, making searches within JSONB documents much quicker and more efficient.
170
+
171
+ Moreover, JSONB retains the flexibility of storing semi-structured data while allowing you to use PostgreSQL's robust querying capabilities. You can perform complex queries, joins, and transactions with JSONB data, just as you can with regular relational data.
172
+
173
+ **Contrary to common belief, JSON document data is structured.** JSON has structure, but it is not enforced for each document. We can easily extend the schema for our documents, even for specific ones, by adding new fields. We should also not fail if a field we expect to exist doesn't.
174
+
175
+ This flexibility, performance, and consistency combination makes PostgreSQL with JSONB a powerful tool. There are benchmarks showing that it can be even faster than MongoDB.
176
+
177
+ Check more in:
178
+
179
+ - [JSON Types Documentation](https://www.postgresql.org/docs/current/datatype-json.html)
180
+ - [JSON Functions and Operators](https://www.postgresql.org/docs/current/functions-json.html)
181
+ - [PostgreSQL, JSONB and GIN Indexes by](https://pganalyze.com/blog/gin-index#postgresql-jsonb-and-gin-indexes)
182
+ - [MongoDB vs PostgreSQL JSONB Benchmark](https://info.enterprisedb.com/rs/069-ALB-339/images/PostgreSQL_MongoDB_Benchmark-WhitepaperFinal.pdf)
183
+ - [How to JSON in PostgreSQL](https://ftisiot.net/postgresqljson/main/)
184
+ - [Just Use Postgres for Everything](https://www.amazingcto.com/postgres-for-everything/)
185
+
186
+ ## Is Pongo an ORM?
187
+
188
+ **It's not.**
189
+
190
+ It's focused on effective handling of the document data specifics. Node.js ORMs have capabilities to handle JSONB, e.g. DrizzleORM has good support for that for basic operations.
191
+
192
+ **Yet, they all have limited querying capabilities.** Usually for advanced ones you need to fallback to JSONPath or JSONB functions (so raw SQL). As you saw above, this syntax is not super pleasant to deal with. That's why Pongo aims to do it for you.
193
+
194
+ ## How is it different than [FerretDB](https://docs.ferretdb.io)?
195
+
196
+ [FerretDB](https://docs.ferretdb.io) plugs into the native MongoDB protocol, which allows it to be used as MongoDB and connect to tools like Mongo UI, etc. Yet, it [requires running a proxy](https://docs.ferretdb.io/quickstart-guide/docker/).
197
+
198
+ **Pongo operates on a different layer, translating the MongoDB API directly into SQL in the library code.** This can allow easier serverless integrations, such as sharing a connection pool with other PostgreSQL-based tools, etc. Of course, it won't allow using native tools based on the MongoDB network protocol.
199
+
200
+ Pongo's goal is not to replace Mongo but to reuse its muscle memory and bring the PostgreSQL capabilities and superpowers into the Node.js land.
201
+
202
+ ## Is it production ready?
203
+
204
+ What's there is safe to use, but it's far from being 100% compliant with MongoDB. Pongo is a fresh project, so some stuff can be missing.
205
+
206
+ ## Contribution
207
+
208
+ Pongo is a community project, so once you find something missing or not working, we encourage you to [send us a GH issue](https://github.com/event-driven-io/Pongo/issues/new) or [Pull Request](https://github.com/event-driven-io/Pongo/compare) extending the support or test coverage! Check also [Contributing guide](https://github.com/event-driven-io/Pongo/blob/main/CONTRIBUTING.md)
209
+
210
+ **If you think something is missing or want to get some features faster, I'm happy to take sponsoring to prioritise it. Feel free to [contact me](mailto:oskar@event-driven.io) - we'll find a way to help you!**
211
+
212
+ ## Code of Conduct
213
+
214
+ This project has adopted the code of conduct defined by the [Contributor Covenant](http://contributor-covenant.org/) to clarify expected behavior in our community.
package/dist/index.cjs CHANGED
@@ -1,2 +1,5 @@
1
- "use strict";Object.defineProperty(exports, "__esModule", {value: true}); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } function _nullishCoalesce(lhs, rhsFn) { if (lhs != null) { return lhs; } else { return rhsFn(); } } async function _asyncNullishCoalesce(lhs, rhsFn) { if (lhs != null) { return lhs; } else { return await rhsFn(); } } async function _asyncOptionalChain(ops) { let lastAccessLHS = undefined; let value = ops[0]; let i = 1; while (i < ops.length) { const op = ops[i]; const fn = ops[i + 1]; i += 2; if ((op === 'optionalAccess' || op === 'optionalCall') && value == null) { return undefined; } if (op === 'access' || op === 'optionalAccess') { lastAccessLHS = value; value = await fn(value); } else if (op === 'call' || op === 'optionalCall') { value = await fn((...args) => value.call(lastAccessLHS, ...args)); lastAccessLHS = undefined; } } return value; } var _class;var _pg = require('pg'); var _pg2 = _interopRequireDefault(_pg);var m=new Map,w= exports.getPool =t=>{let e=typeof t=="string"?t:t.connectionString,n=typeof t=="string"?{connectionString:e}:t;return _nullishCoalesce(m.get(e), () => (m.set(e,new _pg2.default.Pool(n)).get(e)))},h= exports.endPool =async t=>{let e=m.get(t);e&&(await e.end(),m.delete(t))},J= exports.endAllPools =()=>Promise.all([...m.keys()].map(t=>h(t)));var _uuid = require('uuid');var M=async(t,e)=>{let n=await t.connect();try{return await e(n)}finally{n.release()}},P= exports.executeSQL =async(t,e)=>M(t,n=>n.query(e));var p=t=>Object.entries(t).map(([e,n])=>[e,n]);var _pgformat = require('pg-format'); var _pgformat2 = _interopRequireDefault(_pgformat);var x={$eq:"$eq",$gt:"$gt",$gte:"$gte",$lt:"$lt",$lte:"$lte",$ne:"$ne",$in:"$in",$nin:"$nin",$elemMatch:"$elemMatch",$all:"$all",$size:"$size"},C={$gt:">",$gte:">=",$lt:"<",$lte:"<=",$ne:"!="},S=t=>t.startsWith("$"),y=t=>Object.keys(t).some(S),c=(t,e,n)=>{if(t==="_id")return $(e,n);switch(e){case"$eq":return _pgformat2.default.call(void 0, "(data @> %L::jsonb OR jsonb_path_exists(data, '$.%s[*] ? (@ == %s)'))",JSON.stringify(I(t,n)),t,JSON.stringify(n));case"$gt":case"$gte":case"$lt":case"$lte":case"$ne":return _pgformat2.default.call(void 0, `data #>> %L ${C[e]} %L`,`{${t.split(".").join(",")}}`,n);case"$in":return _pgformat2.default.call(void 0, "data #>> %L IN (%s)",`{${t.split(".").join(",")}}`,n.map(o=>_pgformat2.default.call(void 0, "%L",o)).join(", "));case"$nin":return _pgformat2.default.call(void 0, "data #>> %L NOT IN (%s)",`{${t.split(".").join(",")}}`,n.map(o=>_pgformat2.default.call(void 0, "%L",o)).join(", "));case"$elemMatch":{let o=p(n).map(([i,s])=>_pgformat2.default.call(void 0, '@."%s" == %s',i,JSON.stringify(s))).join(" && ");return _pgformat2.default.call(void 0, "jsonb_path_exists(data, '$.%s[*] ? (%s)')",t,o)}case"$all":return _pgformat2.default.call(void 0, "data @> %L::jsonb",JSON.stringify(I(t,n)));case"$size":return _pgformat2.default.call(void 0, "jsonb_array_length(data #> %L) = %L",`{${t.split(".").join(",")}}`,n);default:throw new Error(`Unsupported operator: ${e}`)}},$=(t,e)=>{switch(t){case"$eq":return _pgformat2.default.call(void 0, "_id = %L",e);case"$gt":case"$gte":case"$lt":case"$lte":case"$ne":return _pgformat2.default.call(void 0, `_id ${C[t]} %L`,e);case"$in":return _pgformat2.default.call(void 0, "_id IN (%s)",e.map(n=>_pgformat2.default.call(void 0, "%L",n)).join(", "));case"$nin":return _pgformat2.default.call(void 0, "_id NOT IN (%s)",e.map(n=>_pgformat2.default.call(void 0, "%L",n)).join(", "));default:throw new Error(`Unsupported operator: ${t}`)}},I=(t,e)=>t.split(".").reverse().reduce((n,o)=>({[o]:n}),e);var D="AND",u= exports.constructFilterQuery =t=>Object.entries(t).map(([e,n])=>A(n)?L(e,n):c(e,"$eq",n)).join(` ${D} `),L=(t,e)=>{let n=!y(e);return p(e).map(([o,i])=>n?c(`${t}.${o}`,x.$eq,i):c(t,o,i)).join(` ${D} `)},A=t=>t!==null&&typeof t=="object"&&!Array.isArray(t);var d=(t,...e)=>_pgformat2.default.call(void 0, t,...e);var F=t=>p(t).reduce((e,[n,o])=>{switch(n){case"$set":return U(o,e);case"$unset":return Q(o,e);case"$inc":return j(o,e);case"$push":return N(o,e);default:return e}},d("data")),U= exports.buildSetQuery =(t,e)=>d("jsonb_set(%s, %L, data || %L)",e,"{}",JSON.stringify(t)),Q= exports.buildUnsetQuery =(t,e)=>d("%s - %L",e,Object.keys(t).join(", ")),j= exports.buildIncQuery =(t,e)=>{for(let[n,o]of Object.entries(t))e=d("jsonb_set(%s, '{%s}', to_jsonb((data->>'%s')::numeric + %L))",e,n,n,o);return e},N= exports.buildPushQuery =(t,e)=>{for(let[n,o]of Object.entries(t))e=d("jsonb_set(%s, '{%s}', (COALESCE(data->'%s', '[]'::jsonb) || '[%s]'::jsonb))",e,n,n,JSON.stringify(o));return e};var _=(t,e)=>{let n=s=>P(e,s),o=B(t),i=n(o.createCollection());return{createCollection:async()=>{await i},insertOne:async s=>{await i;let l=_uuid.v4.call(void 0, );return(await n(o.insertOne(l,s))).rowCount?{insertedId:l,acknowledged:!0}:{insertedId:null,acknowledged:!1}},updateOne:async(s,l)=>{await i;let a=await n(o.updateOne(s,l));return a.rowCount?{acknowledged:!0,modifiedCount:a.rowCount}:{acknowledged:!1,modifiedCount:0}},deleteOne:async s=>{await i;let l=await n(o.deleteOne(s));return l.rowCount?{acknowledged:!0,deletedCount:l.rowCount}:{acknowledged:!1,deletedCount:0}},findOne:async s=>(await i,await _asyncNullishCoalesce(await _asyncOptionalChain([(await n(o.findOne(s))), 'access', async _2 => _2.rows, 'access', async _3 => _3[0], 'optionalAccess', async _4 => _4.data]), async () => (null))),find:async s=>(await i,(await n(o.find(s))).rows.map(a=>a.data))}},B=t=>({createCollection:()=>d("CREATE TABLE IF NOT EXISTS %I (_id UUID PRIMARY KEY, data JSONB)",t),insertOne:(e,n)=>d("INSERT INTO %I (_id, data) VALUES (%L, %L)",t,e,JSON.stringify({...n,_id:e})),updateOne:(e,n)=>{let o=u(e),i=F(n);return d("UPDATE %I SET data = %s WHERE %s",t,i,o)},deleteOne:e=>{let n=u(e);return d("DELETE FROM %I WHERE %s",t,n)},findOne:e=>{let n=u(e);return d("SELECT data FROM %I WHERE %s LIMIT 1",t,n)},find:e=>{let n=u(e);return d("SELECT data FROM %I WHERE %s",t,n)}});var E=(t,e)=>{let n=w({connectionString:t,database:e});return{connect:()=>Promise.resolve(),close:()=>h(t),collection:o=>_(o,n)}};var O=(t,e)=>E(t,e);var R=t=>{let e=O(t),n={connect:async()=>(await e.connect(),n),close:()=>e.close(),db:o=>o?O(t,o):e};return n};var f= (_class =class{__init() {this.documents=null}__init2() {this.index=0}constructor(e){;_class.prototype.__init.call(this);_class.prototype.__init2.call(this);this.findDocumentsPromise=e}async toArray(){return this.findDocuments()}async forEach(e){let n=await this.findDocuments();for(let o of n)e(o);return Promise.resolve()}hasNext(){if(this.documents===null)throw Error("Error while fetching documents");return this.index<this.documents.length}async next(){let e=await this.findDocuments();return this.hasNext()?_nullishCoalesce(e[this.index++], () => (null)):null}async findDocuments(){return this.documents=await this.findDocumentsPromise,this.documents}}, _class);require('mongodb');var g=class{constructor(e){this.collection=e}get dbName(){throw new Error("Method not implemented.")}get collectionName(){throw new Error("Method not implemented.")}get namespace(){throw new Error("Method not implemented.")}get readConcern(){throw new Error("Method not implemented.")}get readPreference(){throw new Error("Method not implemented.")}get bsonOptions(){throw new Error("Method not implemented.")}get writeConcern(){throw new Error("Method not implemented.")}get hint(){throw new Error("Method not implemented.")}set hint(e){throw new Error("Method not implemented.")}async insertOne(e,n){let o=await this.collection.insertOne(e);return{acknowledged:o.acknowledged,insertedId:o.insertedId}}insertMany(e,n){throw new Error("Method not implemented.")}bulkWrite(e,n){throw new Error("Method not implemented.")}async updateOne(e,n,o){let i=await this.collection.updateOne(e,n);return{acknowledged:i.acknowledged,matchedCount:i.modifiedCount,modifiedCount:i.modifiedCount,upsertedCount:i.modifiedCount,upsertedId:null}}replaceOne(e,n,o){throw new Error("Method not implemented.")}updateMany(e,n,o){throw new Error("Method not implemented.")}async deleteOne(e,n){let o=await this.collection.deleteOne(e);return{acknowledged:o.acknowledged,deletedCount:o.deletedCount}}deleteMany(e,n){throw new Error("Method not implemented.")}rename(e,n){throw new Error("Method not implemented.")}drop(e){throw new Error("Method not implemented.")}async findOne(e,n){return this.collection.findOne(e)}find(e,n){return new f(this.collection.find(e))}options(e){throw new Error("Method not implemented.")}isCapped(e){throw new Error("Method not implemented.")}createIndex(e,n){throw new Error("Method not implemented.")}createIndexes(e,n){throw new Error("Method not implemented.")}dropIndex(e,n){throw new Error("Method not implemented.")}dropIndexes(e){throw new Error("Method not implemented.")}listIndexes(e){throw new Error("Method not implemented.")}indexExists(e,n){throw new Error("Method not implemented.")}indexInformation(e){throw new Error("Method not implemented.")}estimatedDocumentCount(e){throw new Error("Method not implemented.")}countDocuments(e,n){throw new Error("Method not implemented.")}distinct(e,n,o){throw new Error("Method not implemented.")}indexes(e){throw new Error("Method not implemented.")}findOneAndDelete(e,n){throw new Error("Method not implemented.")}findOneAndReplace(e,n,o){throw new Error("Method not implemented.")}findOneAndUpdate(e,n,o){throw new Error("Method not implemented.")}aggregate(e,n){throw new Error("Method not implemented.")}watch(e,n){throw new Error("Method not implemented.")}initializeUnorderedBulkOp(e){throw new Error("Method not implemented.")}initializeOrderedBulkOp(e){throw new Error("Method not implemented.")}count(e,n){throw new Error("Method not implemented.")}listSearchIndexes(e,n){throw new Error("Method not implemented.")}createSearchIndex(e){throw new Error("Method not implemented.")}createSearchIndexes(e){throw new Error("Method not implemented.")}dropSearchIndex(e){throw new Error("Method not implemented.")}updateSearchIndex(e,n){throw new Error("Method not implemented.")}async createCollection(){await this.collection.createCollection()}};var T=class{constructor(e){this.pongoDb=e}collection(e){return new g(this.pongoDb.collection(e))}};var k=class{constructor(e){this.pongoClient=R(e)}async connect(){return await this.pongoClient.connect(),this}async close(){await this.pongoClient.close()}db(e){return new T(this.pongoClient.db(e))}};exports.Collection = g; exports.Db = T; exports.FindCursor = f; exports.MongoClient = k; exports.buildIncQuery = j; exports.buildPushQuery = N; exports.buildSetQuery = U; exports.buildUnsetQuery = Q; exports.buildUpdateQuery = F; exports.constructFilterQuery = u; exports.endAllPools = J; exports.endPool = h; exports.execute = M; exports.executeSQL = P; exports.getDbClient = O; exports.getPool = w; exports.pongoClient = R; exports.postgresClient = E;
1
+ "use strict";Object.defineProperty(exports, "__esModule", {value: true}); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } function _nullishCoalesce(lhs, rhsFn) { if (lhs != null) { return lhs; } else { return rhsFn(); } } async function _asyncNullishCoalesce(lhs, rhsFn) { if (lhs != null) { return lhs; } else { return await rhsFn(); } } async function _asyncOptionalChain(ops) { let lastAccessLHS = undefined; let value = ops[0]; let i = 1; while (i < ops.length) { const op = ops[i]; const fn = ops[i + 1]; i += 2; if ((op === 'optionalAccess' || op === 'optionalCall') && value == null) { return undefined; } if (op === 'access' || op === 'optionalAccess') { lastAccessLHS = value; value = await fn(value); } else if (op === 'call' || op === 'optionalCall') { value = await fn((...args) => value.call(lastAccessLHS, ...args)); lastAccessLHS = undefined; } } return value; } var _class;var _pg = require('pg'); var _pg2 = _interopRequireDefault(_pg);var m=new Map,I= exports.getPool =t=>{let e=typeof t=="string"?t:t.connectionString,n=typeof t=="string"?{connectionString:e}:t;return _nullishCoalesce(m.get(e), () => (m.set(e,new _pg2.default.Pool(n)).get(e)))},h= exports.endPool =async t=>{let e=m.get(t);e&&(await e.end(),m.delete(t))},z= exports.endAllPools =()=>Promise.all([...m.keys()].map(t=>h(t)));var _pgformat = require('pg-format'); var _pgformat2 = _interopRequireDefault(_pgformat);var _uuid = require('uuid');var $=async(t,e)=>{let n=await t.connect();try{return await e(n)}finally{n.release()}},y= exports.executeSQL =async(t,e)=>$(t,n=>n.query(e));var u=t=>Object.entries(t).map(([e,n])=>[e,n]);var x={$eq:"$eq",$gt:"$gt",$gte:"$gte",$lt:"$lt",$lte:"$lte",$ne:"$ne",$in:"$in",$nin:"$nin",$elemMatch:"$elemMatch",$all:"$all",$size:"$size"},D={$gt:">",$gte:">=",$lt:"<",$lte:"<=",$ne:"!="},L=t=>t.startsWith("$"),F=t=>Object.keys(t).some(L),c=(t,e,n)=>{if(t==="_id")return W(e,n);switch(e){case"$eq":return _pgformat2.default.call(void 0, "(data @> %L::jsonb OR jsonb_path_exists(data, '$.%s[*] ? (@ == %s)'))",JSON.stringify(C(t,n)),t,JSON.stringify(n));case"$gt":case"$gte":case"$lt":case"$lte":case"$ne":return _pgformat2.default.call(void 0, `data #>> %L ${D[e]} %L`,`{${t.split(".").join(",")}}`,n);case"$in":return _pgformat2.default.call(void 0, "data #>> %L IN (%s)",`{${t.split(".").join(",")}}`,n.map(o=>_pgformat2.default.call(void 0, "%L",o)).join(", "));case"$nin":return _pgformat2.default.call(void 0, "data #>> %L NOT IN (%s)",`{${t.split(".").join(",")}}`,n.map(o=>_pgformat2.default.call(void 0, "%L",o)).join(", "));case"$elemMatch":{let o=u(n).map(([i,r])=>_pgformat2.default.call(void 0, '@."%s" == %s',i,JSON.stringify(r))).join(" && ");return _pgformat2.default.call(void 0, "jsonb_path_exists(data, '$.%s[*] ? (%s)')",t,o)}case"$all":return _pgformat2.default.call(void 0, "data @> %L::jsonb",JSON.stringify(C(t,n)));case"$size":return _pgformat2.default.call(void 0, "jsonb_array_length(data #> %L) = %L",`{${t.split(".").join(",")}}`,n);default:throw new Error(`Unsupported operator: ${e}`)}},W=(t,e)=>{switch(t){case"$eq":return _pgformat2.default.call(void 0, "_id = %L",e);case"$gt":case"$gte":case"$lt":case"$lte":case"$ne":return _pgformat2.default.call(void 0, `_id ${D[t]} %L`,e);case"$in":return _pgformat2.default.call(void 0, "_id IN (%s)",e.map(n=>_pgformat2.default.call(void 0, "%L",n)).join(", "));case"$nin":return _pgformat2.default.call(void 0, "_id NOT IN (%s)",e.map(n=>_pgformat2.default.call(void 0, "%L",n)).join(", "));default:throw new Error(`Unsupported operator: ${t}`)}},C=(t,e)=>t.split(".").reverse().reduce((n,o)=>({[o]:n}),e);var k="AND",p= exports.constructFilterQuery =t=>Object.entries(t).map(([e,n])=>U(n)?A(e,n):c(e,"$eq",n)).join(` ${k} `),A=(t,e)=>{let n=!F(e);return u(e).map(([o,i])=>n?c(`${t}.${o}`,x.$eq,i):c(t,o,i)).join(` ${k} `)},U=t=>t!==null&&typeof t=="object"&&!Array.isArray(t);var l=(t,...e)=>_pgformat2.default.call(void 0, t,...e);var O=t=>u(t).reduce((e,[n,o])=>{switch(n){case"$set":return j(o,e);case"$unset":return q(o,e);case"$inc":return N(o,e);case"$push":return B(o,e);default:return e}},l("data")),j= exports.buildSetQuery =(t,e)=>l("jsonb_set(%s, %L, data || %L)",e,"{}",JSON.stringify(t)),q= exports.buildUnsetQuery =(t,e)=>l("%s - %L",e,Object.keys(t).join(", ")),N= exports.buildIncQuery =(t,e)=>{for(let[n,o]of Object.entries(t))e=l("jsonb_set(%s, '{%s}', to_jsonb((data->>'%s')::numeric + %L))",e,n,n,o);return e},B= exports.buildPushQuery =(t,e)=>{for(let[n,o]of Object.entries(t))e=l("jsonb_set(%s, '{%s}', (COALESCE(data->'%s', '[]'::jsonb) || '[%s]'::jsonb))",e,n,n,JSON.stringify(o));return e};var M=(t,e)=>{let n=r=>y(e,r),o=H(t),i=n(o.createCollection());return{createCollection:async()=>{await i},insertOne:async r=>{await i;let s=_uuid.v4.call(void 0, );return(await n(o.insertOne({_id:s,...r}))).rowCount?{insertedId:s,acknowledged:!0}:{insertedId:null,acknowledged:!1}},insertMany:async r=>{await i;let s=r.map(w=>({_id:_uuid.v4.call(void 0, ),...w})),a=await n(o.insertMany(s));return{acknowledged:a.rowCount===s.length,insertedCount:_nullishCoalesce(a.rowCount, () => (0)),insertedIds:s.map(w=>w._id)}},updateOne:async(r,s)=>{await i;let a=await n(o.updateOne(r,s));return a.rowCount?{acknowledged:!0,modifiedCount:a.rowCount}:{acknowledged:!1,modifiedCount:0}},updateMany:async(r,s)=>{await i;let a=await n(o.updateMany(r,s));return a.rowCount?{acknowledged:!0,modifiedCount:a.rowCount}:{acknowledged:!1,modifiedCount:0}},deleteOne:async r=>{await i;let s=await n(o.deleteOne(r));return s.rowCount?{acknowledged:!0,deletedCount:s.rowCount}:{acknowledged:!1,deletedCount:0}},deleteMany:async r=>{await i;let s=await n(o.deleteMany(r));return s.rowCount?{acknowledged:!0,deletedCount:s.rowCount}:{acknowledged:!1,deletedCount:0}},findOne:async r=>(await i,await _asyncNullishCoalesce(await _asyncOptionalChain([(await n(o.findOne(r))), 'access', async _2 => _2.rows, 'access', async _3 => _3[0], 'optionalAccess', async _4 => _4.data]), async () => (null))),find:async r=>(await i,(await n(o.find(r))).rows.map(a=>a.data))}},H=t=>({createCollection:()=>l("CREATE TABLE IF NOT EXISTS %I (_id UUID PRIMARY KEY, data JSONB)",t),insertOne:e=>l("INSERT INTO %I (_id, data) VALUES (%L, %L)",t,e._id,JSON.stringify(e)),insertMany:e=>{let n=e.map(o=>_pgformat2.default.call(void 0, "(%L, %L)",o._id,JSON.stringify(o))).join(", ");return l("INSERT INTO %I (_id, data) VALUES %s",t,n)},updateOne:(e,n)=>{let o=p(e),i=O(n);return l(`WITH cte AS (
2
+ SELECT _id FROM %I WHERE %s LIMIT 1
3
+ )
4
+ UPDATE %I SET data = %s FROM cte WHERE %I._id = cte._id`,t,o,t,i,t)},updateMany:(e,n)=>{let o=p(e),i=O(n);return l("UPDATE %I SET data = %s WHERE %s",t,i,o)},deleteOne:e=>{let n=p(e);return l("DELETE FROM %I WHERE %s",t,n)},deleteMany:e=>{let n=p(e);return l("DELETE FROM %I WHERE %s",t,n)},findOne:e=>{let n=p(e);return l("SELECT data FROM %I WHERE %s LIMIT 1",t,n)},find:e=>{let n=p(e);return l("SELECT data FROM %I WHERE %s",t,n)}});var R=(t,e)=>{let n=I({connectionString:t,database:e});return{connect:()=>Promise.resolve(),close:()=>h(t),collection:o=>M(o,n)}};var P=(t,e)=>R(t,e);var _=t=>{let e=P(t),n={connect:async()=>(await e.connect(),n),close:()=>e.close(),db:o=>o?P(t,o):e};return n};var f= (_class =class{__init() {this.documents=null}__init2() {this.index=0}constructor(e){;_class.prototype.__init.call(this);_class.prototype.__init2.call(this);this.findDocumentsPromise=e}async toArray(){return this.findDocuments()}async forEach(e){let n=await this.findDocuments();for(let o of n)e(o);return Promise.resolve()}hasNext(){if(this.documents===null)throw Error("Error while fetching documents");return this.index<this.documents.length}async next(){let e=await this.findDocuments();return this.hasNext()?_nullishCoalesce(e[this.index++], () => (null)):null}async findDocuments(){return this.documents=await this.findDocumentsPromise,this.documents}}, _class);require('mongodb');var g=class{constructor(e){this.collection=e}get dbName(){throw new Error("Method not implemented.")}get collectionName(){throw new Error("Method not implemented.")}get namespace(){throw new Error("Method not implemented.")}get readConcern(){throw new Error("Method not implemented.")}get readPreference(){throw new Error("Method not implemented.")}get bsonOptions(){throw new Error("Method not implemented.")}get writeConcern(){throw new Error("Method not implemented.")}get hint(){throw new Error("Method not implemented.")}set hint(e){throw new Error("Method not implemented.")}async insertOne(e,n){let o=await this.collection.insertOne(e);return{acknowledged:o.acknowledged,insertedId:o.insertedId}}async insertMany(e,n){let o=await this.collection.insertMany(e);return{acknowledged:o.acknowledged,insertedIds:o.insertedIds,insertedCount:o.insertedCount}}bulkWrite(e,n){throw new Error("Method not implemented.")}async updateOne(e,n,o){let i=await this.collection.updateOne(e,n);return{acknowledged:i.acknowledged,matchedCount:i.modifiedCount,modifiedCount:i.modifiedCount,upsertedCount:i.modifiedCount,upsertedId:null}}replaceOne(e,n,o){throw new Error("Method not implemented.")}async updateMany(e,n,o){let i=await this.collection.updateMany(e,n);return{acknowledged:i.acknowledged,matchedCount:i.modifiedCount,modifiedCount:i.modifiedCount,upsertedCount:i.modifiedCount,upsertedId:null}}async deleteOne(e,n){let o=await this.collection.deleteOne(e);return{acknowledged:o.acknowledged,deletedCount:o.deletedCount}}async deleteMany(e,n){let o=await this.collection.deleteMany(e);return{acknowledged:o.acknowledged,deletedCount:o.deletedCount}}rename(e,n){throw new Error("Method not implemented.")}drop(e){throw new Error("Method not implemented.")}async findOne(e,n){return this.collection.findOne(e)}find(e,n){return new f(this.collection.find(e))}options(e){throw new Error("Method not implemented.")}isCapped(e){throw new Error("Method not implemented.")}createIndex(e,n){throw new Error("Method not implemented.")}createIndexes(e,n){throw new Error("Method not implemented.")}dropIndex(e,n){throw new Error("Method not implemented.")}dropIndexes(e){throw new Error("Method not implemented.")}listIndexes(e){throw new Error("Method not implemented.")}indexExists(e,n){throw new Error("Method not implemented.")}indexInformation(e){throw new Error("Method not implemented.")}estimatedDocumentCount(e){throw new Error("Method not implemented.")}countDocuments(e,n){throw new Error("Method not implemented.")}distinct(e,n,o){throw new Error("Method not implemented.")}indexes(e){throw new Error("Method not implemented.")}findOneAndDelete(e,n){throw new Error("Method not implemented.")}findOneAndReplace(e,n,o){throw new Error("Method not implemented.")}findOneAndUpdate(e,n,o){throw new Error("Method not implemented.")}aggregate(e,n){throw new Error("Method not implemented.")}watch(e,n){throw new Error("Method not implemented.")}initializeUnorderedBulkOp(e){throw new Error("Method not implemented.")}initializeOrderedBulkOp(e){throw new Error("Method not implemented.")}count(e,n){throw new Error("Method not implemented.")}listSearchIndexes(e,n){throw new Error("Method not implemented.")}createSearchIndex(e){throw new Error("Method not implemented.")}createSearchIndexes(e){throw new Error("Method not implemented.")}dropSearchIndex(e){throw new Error("Method not implemented.")}updateSearchIndex(e,n){throw new Error("Method not implemented.")}async createCollection(){await this.collection.createCollection()}};var T=class{constructor(e){this.pongoDb=e}collection(e){return new g(this.pongoDb.collection(e))}};var S=class{constructor(e){this.pongoClient=_(e)}async connect(){return await this.pongoClient.connect(),this}async close(){await this.pongoClient.close()}db(e){return new T(this.pongoClient.db(e))}};exports.Collection = g; exports.Db = T; exports.FindCursor = f; exports.MongoClient = S; exports.buildIncQuery = N; exports.buildPushQuery = B; exports.buildSetQuery = j; exports.buildUnsetQuery = q; exports.buildUpdateQuery = O; exports.constructFilterQuery = p; exports.endAllPools = z; exports.endPool = h; exports.execute = $; exports.executeSQL = y; exports.getDbClient = P; exports.getPool = I; exports.pongoClient = _; exports.postgresClient = R;
2
5
  //# sourceMappingURL=index.cjs.map
@@ -1 +1 @@
1
- {"version":3,"sources":["../src/postgres/pool.ts","../src/postgres/postgresCollection.ts","../src/postgres/execute/index.ts","../src/main/typing/entries.ts","../src/postgres/filter/queryOperators.ts","../src/postgres/filter/index.ts","../src/postgres/sql/index.ts","../src/postgres/update/index.ts","../src/postgres/client.ts","../src/main/dbClient.ts","../src/main/client.ts","../src/mongo/findCursor.ts","../src/mongo/mongoDb.ts","../src/mongo/mongoCollection.ts","../src/mongo/mongoClient.ts"],"names":["pg","pools","getPool","connectionStringOrOptions","connectionString","poolOptions","endPool","pool","endAllPools","uuid","execute","handle","client","executeSQL","sql","entries","obj","key","value","format","Operators","OperatorMap","isOperator","hasOperators","handleOperator","path","operator","handleIdOperator","buildNestedObject","v","subQuery","subKey","subValue","acc","AND","constructFilterQuery","filter","isRecord","constructComplexFilterQuery","isEquality","nestedKey","val","sqlQuery","params","buildUpdateQuery","update","currentUpdateQuery","op","buildSetQuery","buildUnsetQuery","buildIncQuery","buildPushQuery","set","unset","inc","push","postgresCollection","collectionName","SqlFor","collectionSQLBuilder","createCollection","document","id","result","row","filterQuery","updateQuery","postgresClient","database","name","getDbClient","pongoClient","dbClient","dbName","FindCursor","documents","callback","docs","doc","Collection","collection","_options","_docs","_operations","_filter","_","_update","_newName","_indexSpec","_indexSpecs","_indexName","_indexes","_key","_replacement","_pipeline","_name","_description","_descriptions","_definition","Db","pongoDb","MongoClient"],"mappings":"AAAA,OAAOA,MAAQ,KAEf,IAAMC,EAA8B,IAAI,IAE3BC,EACXC,GACY,CACZ,IAAMC,EACJ,OAAOD,GAA8B,SACjCA,EACAA,EAA0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IsB,EAAc,KAAK,QAAQ,WAActB,CAAc,CAAC,CACrE,CACF,EENO,IAAM4C,EAAN,KAAkB,CACf,YAER,YAAYjG,EAA0B,CACpC,KAAK,YAAcmE,EAAYnE,CAAgB,CACjD,CAEA,MAAM,SAAU,CACd,aAAM,KAAK,YAAY,QAAQ,EACxB,IACT,CAEA,MAAM,OAAQ,CACZ,MAAM,KAAK,YAAY,MAAM,CAC/B,CAEA,GAAGqE,EAAoB,CACrB,OAAO,IAAI0B,EAAG,KAAK,YAAY,GAAG1B,CAAM,CAAC,CAC3C,CACF","sourcesContent":["import pg from 'pg';\n\nconst pools: Map<string, pg.Pool> = new Map();\n\nexport const getPool = (\n connectionStringOrOptions: string | pg.PoolConfig,\n): pg.Pool => {\n const connectionString =\n typeof connectionStringOrOptions === 'string'\n ? connectionStringOrOptions\n : connectionStringOrOptions.connectionString!;\n\n const poolOptions =\n typeof connectionStringOrOptions === 'string'\n ? { connectionString }\n : connectionStringOrOptions;\n\n //TODO: this should include database name resolution for key\n return (\n pools.get(connectionString) ??\n pools.set(connectionString, new pg.Pool(poolOptions)).get(connectionString)!\n );\n};\n\nexport const endPool = async (connectionString: string): Promise<void> => {\n const pool = pools.get(connectionString);\n if (pool) {\n await pool.end();\n pools.delete(connectionString);\n }\n};\n\nexport const endAllPools = () =>\n Promise.all(\n [...pools.keys()].map((connectionString) => endPool(connectionString)),\n );\n","import pg from 'pg';\nimport { v4 as uuid } from 'uuid';\nimport {\n type PongoCollection,\n type PongoDeleteResult,\n type PongoFilter,\n type PongoInsertOneResult,\n type PongoUpdate,\n type PongoUpdateResult,\n} from '../main';\nimport { executeSQL } from './execute';\nimport { constructFilterQuery } from './filter';\nimport { sql, type SQL } from './sql';\nimport { buildUpdateQuery } from './update';\n\nexport const postgresCollection = <T>(\n collectionName: string,\n pool: pg.Pool,\n): PongoCollection<T> => {\n const execute = (sql: SQL) => executeSQL(pool, sql);\n const SqlFor = collectionSQLBuilder(collectionName);\n\n const createCollection = execute(SqlFor.createCollection());\n\n return {\n createCollection: async () => {\n await createCollection;\n },\n insertOne: async (document: T): Promise<PongoInsertOneResult> => {\n await createCollection;\n\n const id = uuid();\n\n const result = await execute(SqlFor.insertOne(id, document));\n\n return result.rowCount\n ? { insertedId: id, acknowledged: true }\n : { insertedId: null, acknowledged: false };\n },\n updateOne: async (\n filter: PongoFilter<T>,\n update: PongoUpdate<T>,\n ): Promise<PongoUpdateResult> => {\n await createCollection;\n\n const result = await execute(SqlFor.updateOne(filter, update));\n return result.rowCount\n ? { acknowledged: true, modifiedCount: result.rowCount }\n : { acknowledged: false, modifiedCount: 0 };\n },\n deleteOne: async (filter: PongoFilter<T>): Promise<PongoDeleteResult> => {\n await createCollection;\n\n const result = await execute(SqlFor.deleteOne(filter));\n return result.rowCount\n ? { acknowledged: true, deletedCount: result.rowCount }\n : { acknowledged: false, deletedCount: 0 };\n },\n findOne: async (filter: PongoFilter<T>): Promise<T | null> => {\n await createCollection;\n\n const result = await execute(SqlFor.findOne(filter));\n return (result.rows[0]?.data ?? null) as T | null;\n },\n find: async (filter: PongoFilter<T>): Promise<T[]> => {\n await createCollection;\n\n const result = await execute(SqlFor.find(filter));\n return result.rows.map((row) => row.data as T);\n },\n };\n};\n\nexport const collectionSQLBuilder = (collectionName: string) => ({\n createCollection: (): SQL =>\n sql(\n 'CREATE TABLE IF NOT EXISTS %I (_id UUID PRIMARY KEY, data JSONB)',\n collectionName,\n ),\n insertOne: <T>(id: string, document: T): SQL =>\n sql(\n 'INSERT INTO %I (_id, data) VALUES (%L, %L)',\n collectionName,\n id,\n JSON.stringify({ ...document, _id: id }),\n ),\n updateOne: <T>(filter: PongoFilter<T>, update: PongoUpdate<T>): SQL => {\n const filterQuery = constructFilterQuery(filter);\n const updateQuery = buildUpdateQuery(update);\n\n return sql(\n 'UPDATE %I SET data = %s WHERE %s',\n collectionName,\n updateQuery,\n filterQuery,\n );\n },\n deleteOne: <T>(filter: PongoFilter<T>): SQL => {\n const filterQuery = constructFilterQuery(filter);\n return sql('DELETE FROM %I WHERE %s', collectionName, filterQuery);\n },\n findOne: <T>(filter: PongoFilter<T>): SQL => {\n const filterQuery = constructFilterQuery(filter);\n return sql(\n 'SELECT data FROM %I WHERE %s LIMIT 1',\n collectionName,\n filterQuery,\n );\n },\n find: <T>(filter: PongoFilter<T>): SQL => {\n const filterQuery = constructFilterQuery(filter);\n return sql('SELECT data FROM %I WHERE %s', collectionName, filterQuery);\n },\n});\n","import type pg from 'pg';\nimport type { SQL } from '../sql';\n\nexport const execute = async <Result = void>(\n pool: pg.Pool,\n handle: (client: pg.PoolClient) => Promise<Result>,\n) => {\n const client = await pool.connect();\n try {\n return await handle(client);\n } finally {\n client.release();\n }\n};\n\nexport const executeSQL = async <\n Result extends pg.QueryResultRow = pg.QueryResultRow,\n>(\n pool: pg.Pool,\n sql: SQL,\n): Promise<pg.QueryResult<Result>> =>\n execute(pool, (client) => client.query<Result>(sql));\n","type Entry<T> = {\n [K in keyof Required<T>]: [K, Required<T>[K]];\n}[keyof Required<T>];\n\ntype IterableEntry<T> = Entry<T> & {\n [Symbol.iterator](): Iterator<Entry<T>>;\n};\n\nexport const entries = <T extends object>(obj: T): IterableEntry<T>[] =>\n Object.entries(obj).map(([key, value]) => [key as keyof T, value]);\n\nexport type NonPartial<T> = { [K in keyof Required<T>]: T[K] };\n","import format from 'pg-format';\nimport { entries } from '../../main/typing';\n\nexport const Operators = {\n $eq: '$eq',\n $gt: '$gt',\n $gte: '$gte',\n $lt: '$lt',\n $lte: '$lte',\n $ne: '$ne',\n $in: '$in',\n $nin: '$nin',\n $elemMatch: '$elemMatch',\n $all: '$all',\n $size: '$size',\n};\n\nconst OperatorMap = {\n $gt: '>',\n $gte: '>=',\n $lt: '<',\n $lte: '<=',\n $ne: '!=',\n};\n\nexport const isOperator = (key: string) => key.startsWith('$');\n\nexport const hasOperators = (value: Record<string, unknown>) =>\n Object.keys(value).some(isOperator);\n\nexport const handleOperator = (\n path: string,\n operator: string,\n value: unknown,\n): string => {\n if (path === '_id') {\n return handleIdOperator(operator, value);\n }\n\n switch (operator) {\n case '$eq':\n return format(\n `(data @> %L::jsonb OR jsonb_path_exists(data, '$.%s[*] ? (@ == %s)'))`,\n JSON.stringify(buildNestedObject(path, value)),\n path,\n JSON.stringify(value),\n );\n case '$gt':\n case '$gte':\n case '$lt':\n case '$lte':\n case '$ne':\n return format(\n `data #>> %L ${OperatorMap[operator]} %L`,\n `{${path.split('.').join(',')}}`,\n value,\n );\n case '$in':\n return format(\n 'data #>> %L IN (%s)',\n `{${path.split('.').join(',')}}`,\n (value as unknown[]).map((v) => format('%L', v)).join(', '),\n );\n case '$nin':\n return format(\n 'data #>> %L NOT IN (%s)',\n `{${path.split('.').join(',')}}`,\n (value as unknown[]).map((v) => format('%L', v)).join(', '),\n );\n case '$elemMatch': {\n const subQuery = entries(value as Record<string, unknown>)\n .map(([subKey, subValue]) =>\n format(`@.\"%s\" == %s`, subKey, JSON.stringify(subValue)),\n )\n .join(' && ');\n return format(\n `jsonb_path_exists(data, '$.%s[*] ? (%s)')`,\n path,\n subQuery,\n );\n }\n case '$all':\n return format(\n 'data @> %L::jsonb',\n JSON.stringify(buildNestedObject(path, value)),\n );\n case '$size':\n return format(\n 'jsonb_array_length(data #> %L) = %L',\n `{${path.split('.').join(',')}}`,\n value,\n );\n default:\n throw new Error(`Unsupported operator: ${operator}`);\n }\n};\n\nconst handleIdOperator = (operator: string, value: unknown): string => {\n switch (operator) {\n case '$eq':\n return format(`_id = %L`, value);\n case '$gt':\n case '$gte':\n case '$lt':\n case '$lte':\n case '$ne':\n return format(`_id ${OperatorMap[operator]} %L`, value);\n case '$in':\n return format(\n `_id IN (%s)`,\n (value as unknown[]).map((v) => format('%L', v)).join(', '),\n );\n case '$nin':\n return format(\n `_id NOT IN (%s)`,\n (value as unknown[]).map((v) => format('%L', v)).join(', '),\n );\n default:\n throw new Error(`Unsupported operator: ${operator}`);\n }\n};\n\nconst buildNestedObject = (\n path: string,\n value: unknown,\n): Record<string, unknown> =>\n path\n .split('.')\n .reverse()\n .reduce((acc, key) => ({ [key]: acc }), value as Record<string, unknown>);\n","import type { PongoFilter } from '../../main';\nimport { entries } from '../../main/typing';\nimport { Operators, handleOperator, hasOperators } from './queryOperators';\n\nconst AND = 'AND';\n\nexport const constructFilterQuery = <T>(filter: PongoFilter<T>): string =>\n Object.entries(filter)\n .map(([key, value]) =>\n isRecord(value)\n ? constructComplexFilterQuery(key, value)\n : handleOperator(key, '$eq', value),\n )\n .join(` ${AND} `);\n\nconst constructComplexFilterQuery = (\n key: string,\n value: Record<string, unknown>,\n): string => {\n const isEquality = !hasOperators(value);\n\n return entries(value)\n .map(\n ([nestedKey, val]) =>\n isEquality\n ? handleOperator(`${key}.${nestedKey}`, Operators.$eq, val) // regular value\n : handleOperator(key, nestedKey, val), // operator\n )\n .join(` ${AND} `);\n};\n\nconst isRecord = (value: unknown): value is Record<string, unknown> =>\n value !== null && typeof value === 'object' && !Array.isArray(value);\n","import format from 'pg-format';\n\nexport type SQL = string & { __brand: 'sql' };\n\nexport const sql = (sqlQuery: string, ...params: unknown[]): SQL => {\n return format(sqlQuery, ...params) as SQL;\n};\n","import type { $inc, $push, $set, $unset, PongoUpdate } from '../../main';\nimport { entries } from '../../main/typing';\nimport { sql, type SQL } from '../sql';\n\nexport const buildUpdateQuery = <T>(update: PongoUpdate<T>): SQL =>\n entries(update).reduce((currentUpdateQuery, [op, value]) => {\n switch (op) {\n case '$set':\n return buildSetQuery(value, currentUpdateQuery);\n case '$unset':\n return buildUnsetQuery(value, currentUpdateQuery);\n case '$inc':\n return buildIncQuery(value, currentUpdateQuery);\n case '$push':\n return buildPushQuery(value, currentUpdateQuery);\n default:\n return currentUpdateQuery;\n }\n }, sql('data'));\n\nexport const buildSetQuery = <T>(set: $set<T>, currentUpdateQuery: SQL): SQL =>\n sql(\n 'jsonb_set(%s, %L, data || %L)',\n currentUpdateQuery,\n '{}',\n JSON.stringify(set),\n );\n\nexport const buildUnsetQuery = <T>(\n unset: $unset<T>,\n currentUpdateQuery: SQL,\n): SQL => sql('%s - %L', currentUpdateQuery, Object.keys(unset).join(', '));\n\nexport const buildIncQuery = <T>(\n inc: $inc<T>,\n currentUpdateQuery: SQL,\n): SQL => {\n for (const [key, value] of Object.entries(inc)) {\n currentUpdateQuery = sql(\n \"jsonb_set(%s, '{%s}', to_jsonb((data->>'%s')::numeric + %L))\",\n currentUpdateQuery,\n key,\n key,\n value,\n );\n }\n return currentUpdateQuery;\n};\n\nexport const buildPushQuery = <T>(\n push: $push<T>,\n currentUpdateQuery: SQL,\n): SQL => {\n for (const [key, value] of Object.entries(push)) {\n currentUpdateQuery = sql(\n \"jsonb_set(%s, '{%s}', (COALESCE(data->'%s', '[]'::jsonb) || '[%s]'::jsonb))\",\n currentUpdateQuery,\n key,\n key,\n JSON.stringify(value),\n );\n }\n return currentUpdateQuery;\n};\n","import { type DbClient } from '../main';\nimport { endPool, getPool } from './pool';\nimport { postgresCollection } from './postgresCollection';\n\nexport const postgresClient = (\n connectionString: string,\n database?: string,\n): DbClient => {\n const pool = getPool({ connectionString, database });\n\n return {\n connect: () => Promise.resolve(),\n close: () => endPool(connectionString),\n collection: <T>(name: string) => postgresCollection<T>(name, pool),\n };\n};\n","import { postgresClient } from '../postgres';\nimport type { PongoCollection } from './typing/operations';\n\nexport interface DbClient {\n connect(): Promise<void>;\n close(): Promise<void>;\n collection: <T>(name: string) => PongoCollection<T>;\n}\n\nexport const getDbClient = (\n connectionString: string,\n database?: string,\n): DbClient => {\n // This is the place where in the future could come resolution of other database types\n return postgresClient(connectionString, database);\n};\n","import { getDbClient } from './dbClient';\nimport type { PongoClient, PongoDb } from './typing/operations';\n\nexport const pongoClient = (connectionString: string): PongoClient => {\n const dbClient = getDbClient(connectionString);\n\n const pongoClient: PongoClient = {\n connect: async () => {\n await dbClient.connect();\n return pongoClient;\n },\n close: () => dbClient.close(),\n db: (dbName?: string): PongoDb =>\n dbName ? getDbClient(connectionString, dbName) : dbClient,\n };\n\n return pongoClient;\n};\n","export class FindCursor<T> {\n private findDocumentsPromise: Promise<T[]>;\n private documents: T[] | null = null;\n private index: number = 0;\n\n constructor(documents: Promise<T[]>) {\n this.findDocumentsPromise = documents;\n }\n\n async toArray(): Promise<T[]> {\n return this.findDocuments();\n }\n\n async forEach(callback: (doc: T) => void): Promise<void> {\n const docs = await this.findDocuments();\n\n for (const doc of docs) {\n callback(doc);\n }\n return Promise.resolve();\n }\n\n hasNext(): boolean {\n if (this.documents === null) throw Error('Error while fetching documents');\n return this.index < this.documents.length;\n }\n\n async next(): Promise<T | null> {\n const docs = await this.findDocuments();\n return this.hasNext() ? docs[this.index++] ?? null : null;\n }\n\n private async findDocuments(): Promise<T[]> {\n this.documents = await this.findDocumentsPromise;\n return this.documents;\n }\n}\n","import { Collection as MongoCollection, type Document } from 'mongodb';\nimport type { PongoDb } from '../main';\nimport { Collection } from './mongoCollection';\n\nexport class Db {\n constructor(private pongoDb: PongoDb) {}\n\n collection<T extends Document>(collectionName: string): MongoCollection<T> {\n return new Collection<T>(this.pongoDb.collection<T>(collectionName));\n }\n}\n","import type {\n AbstractCursorOptions,\n AggregateOptions,\n AggregationCursor,\n AnyBulkWriteOperation,\n BSONSerializeOptions,\n BulkWriteOptions,\n BulkWriteResult,\n ChangeStream,\n ChangeStreamDocument,\n ChangeStreamOptions,\n CommandOperationOptions,\n CountDocumentsOptions,\n CountOptions,\n CreateIndexesOptions,\n DeleteOptions,\n DeleteResult,\n Document,\n DropCollectionOptions,\n EnhancedOmit,\n EstimatedDocumentCountOptions,\n Filter,\n FindOneAndDeleteOptions,\n FindOneAndReplaceOptions,\n FindOneAndUpdateOptions,\n FindOptions,\n Flatten,\n Hint,\n IndexDescription,\n IndexDescriptionCompact,\n IndexDescriptionInfo,\n IndexInformationOptions,\n IndexSpecification,\n InferIdType,\n InsertManyResult,\n InsertOneOptions,\n InsertOneResult,\n ListIndexesCursor,\n ListSearchIndexesCursor,\n ListSearchIndexesOptions,\n ModifyResult,\n Collection as MongoCollection,\n FindCursor as MongoFindCursor,\n OperationOptions,\n OptionalUnlessRequiredId,\n OrderedBulkOperation,\n ReadConcern,\n ReadPreference,\n RenameOptions,\n ReplaceOptions,\n SearchIndexDescription,\n UnorderedBulkOperation,\n UpdateFilter,\n UpdateOptions,\n UpdateResult,\n WithId,\n WithoutId,\n WriteConcern,\n} from 'mongodb';\nimport type { Key } from 'readline';\nimport type { PongoCollection, PongoFilter, PongoUpdate } from '../main';\nimport { FindCursor } from './findCursor';\n\nexport class Collection<T extends Document> implements MongoCollection<T> {\n private collection: PongoCollection<T>;\n\n constructor(collection: PongoCollection<T>) {\n this.collection = collection;\n }\n get dbName(): string {\n throw new Error('Method not implemented.');\n }\n get collectionName(): string {\n throw new Error('Method not implemented.');\n }\n get namespace(): string {\n throw new Error('Method not implemented.');\n }\n get readConcern(): ReadConcern | undefined {\n throw new Error('Method not implemented.');\n }\n get readPreference(): ReadPreference | undefined {\n throw new Error('Method not implemented.');\n }\n get bsonOptions(): BSONSerializeOptions {\n throw new Error('Method not implemented.');\n }\n get writeConcern(): WriteConcern | undefined {\n throw new Error('Method not implemented.');\n }\n get hint(): Hint | undefined {\n throw new Error('Method not implemented.');\n }\n set hint(v: Hint | undefined) {\n throw new Error('Method not implemented.');\n }\n async insertOne(\n doc: OptionalUnlessRequiredId<T>,\n _options?: InsertOneOptions | undefined,\n ): Promise<InsertOneResult<T>> {\n const result = await this.collection.insertOne(doc as T);\n return {\n acknowledged: result.acknowledged,\n insertedId: result.insertedId as unknown as InferIdType<T>,\n };\n }\n insertMany(\n _docs: OptionalUnlessRequiredId<T>[],\n _options?: BulkWriteOptions | undefined,\n ): Promise<InsertManyResult<T>> {\n throw new Error('Method not implemented.');\n }\n bulkWrite(\n _operations: AnyBulkWriteOperation<T>[],\n _options?: BulkWriteOptions | undefined,\n ): Promise<BulkWriteResult> {\n throw new Error('Method not implemented.');\n }\n async updateOne(\n filter: Filter<T>,\n update: Document[] | UpdateFilter<T>,\n _options?: UpdateOptions | undefined,\n ): Promise<UpdateResult<T>> {\n const result = await this.collection.updateOne(\n filter as unknown as PongoFilter<T>,\n update as unknown as PongoUpdate<T>,\n );\n\n return {\n acknowledged: result.acknowledged,\n matchedCount: result.modifiedCount,\n modifiedCount: result.modifiedCount,\n upsertedCount: result.modifiedCount,\n upsertedId: null,\n };\n }\n replaceOne(\n _filter: Filter<T>,\n _: WithoutId<T>,\n _options?: ReplaceOptions | undefined,\n ): Promise<Document | UpdateResult<T>> {\n throw new Error('Method not implemented.');\n }\n updateMany(\n _filter: Filter<T>,\n _update: Document[] | UpdateFilter<T>,\n _options?: UpdateOptions | undefined,\n ): Promise<UpdateResult<T>> {\n throw new Error('Method not implemented.');\n }\n async deleteOne(\n filter?: Filter<T> | undefined,\n _options?: DeleteOptions | undefined,\n ): Promise<DeleteResult> {\n const result = await this.collection.deleteOne(\n filter as unknown as PongoFilter<T>,\n );\n\n return {\n acknowledged: result.acknowledged,\n deletedCount: result.deletedCount,\n };\n }\n deleteMany(\n _filter?: Filter<T> | undefined,\n _options?: DeleteOptions | undefined,\n ): Promise<DeleteResult> {\n throw new Error('Method not implemented.');\n }\n rename(\n _newName: string,\n _options?: RenameOptions | undefined,\n ): Promise<Collection<Document>> {\n throw new Error('Method not implemented.');\n }\n drop(_options?: DropCollectionOptions | undefined): Promise<boolean> {\n throw new Error('Method not implemented.');\n }\n findOne(): Promise<WithId<T> | null>;\n findOne(filter: Filter<T>): Promise<WithId<T> | null>;\n findOne(\n filter: Filter<T>,\n options: FindOptions<Document>,\n ): Promise<WithId<T> | null>;\n findOne<TS = T>(): Promise<TS | null>;\n findOne<TS = T>(filter: Filter<TS>): Promise<TS | null>;\n findOne<TS = T>(\n filter: Filter<TS>,\n options?: FindOptions<Document> | undefined,\n ): Promise<TS | null>;\n async findOne(\n filter?: unknown,\n _options?: unknown,\n ): Promise<import('mongodb').WithId<T> | T | null> {\n return this.collection.findOne(filter as PongoFilter<T>);\n }\n find(): MongoFindCursor<WithId<T>>;\n find(\n filter: Filter<T>,\n options?: FindOptions<Document> | undefined,\n ): MongoFindCursor<WithId<T>>;\n find<T extends Document>(\n filter: Filter<T>,\n options?: FindOptions<Document> | undefined,\n ): MongoFindCursor<T>;\n find(\n filter?: unknown,\n _options?: unknown,\n ): MongoFindCursor<WithId<T>> | MongoFindCursor<T> {\n return new FindCursor(\n this.collection.find(filter as PongoFilter<T>),\n ) as unknown as MongoFindCursor<T>;\n }\n options(_options?: OperationOptions | undefined): Promise<Document> {\n throw new Error('Method not implemented.');\n }\n isCapped(_options?: OperationOptions | undefined): Promise<boolean> {\n throw new Error('Method not implemented.');\n }\n createIndex(\n _indexSpec: IndexSpecification,\n _options?: CreateIndexesOptions | undefined,\n ): Promise<string> {\n throw new Error('Method not implemented.');\n }\n createIndexes(\n _indexSpecs: IndexDescription[],\n _options?: CreateIndexesOptions | undefined,\n ): Promise<string[]> {\n throw new Error('Method not implemented.');\n }\n dropIndex(\n _indexName: string,\n _options?: CommandOperationOptions | undefined,\n ): Promise<Document> {\n throw new Error('Method not implemented.');\n }\n dropIndexes(\n _options?: CommandOperationOptions | undefined,\n ): Promise<boolean> {\n throw new Error('Method not implemented.');\n }\n listIndexes(_options?: AbstractCursorOptions | undefined): ListIndexesCursor {\n throw new Error('Method not implemented.');\n }\n indexExists(\n _indexes: string | string[],\n _options?: AbstractCursorOptions | undefined,\n ): Promise<boolean> {\n throw new Error('Method not implemented.');\n }\n indexInformation(\n options: IndexInformationOptions & { full: true },\n ): Promise<IndexDescriptionInfo[]>;\n indexInformation(\n options: IndexInformationOptions & { full?: false | undefined },\n ): Promise<IndexDescriptionCompact>;\n indexInformation(\n options: IndexInformationOptions,\n ): Promise<IndexDescriptionCompact | IndexDescriptionInfo[]>;\n indexInformation(): Promise<IndexDescriptionCompact>;\n indexInformation(\n _options?: unknown,\n ):\n | Promise<import('mongodb').IndexDescriptionInfo[]>\n | Promise<import('mongodb').IndexDescriptionCompact>\n | Promise<\n | import('mongodb').IndexDescriptionCompact\n | import('mongodb').IndexDescriptionInfo[]\n > {\n throw new Error('Method not implemented.');\n }\n estimatedDocumentCount(\n _options?: EstimatedDocumentCountOptions | undefined,\n ): Promise<number> {\n throw new Error('Method not implemented.');\n }\n countDocuments(\n _filter?: Filter<T> | undefined,\n _options?: CountDocumentsOptions | undefined,\n ): Promise<number> {\n throw new Error('Method not implemented.');\n }\n distinct<Key extends '_id' | keyof EnhancedOmit<T, '_id'>>(\n key: Key,\n ): Promise<Flatten<WithId<T>[Key]>[]>;\n distinct<Key extends '_id' | keyof EnhancedOmit<T, '_id'>>(\n key: Key,\n filter: Filter<T>,\n ): Promise<Flatten<WithId<T>[Key]>[]>;\n distinct<Key extends '_id' | keyof EnhancedOmit<T, '_id'>>(\n key: Key,\n filter: Filter<T>,\n options: CommandOperationOptions,\n ): Promise<Flatten<WithId<T>[Key]>[]>;\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n distinct(key: string): Promise<any[]>;\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n distinct(key: string, filter: Filter<T>): Promise<any[]>;\n distinct(\n key: string,\n filter: Filter<T>,\n options: CommandOperationOptions, // eslint-disable-next-line @typescript-eslint/no-explicit-any\n ): Promise<any[]>;\n distinct(\n _key: unknown,\n _filter?: unknown,\n _options?: unknown,\n ): // eslint-disable-next-line @typescript-eslint/no-explicit-any\n | Promise<any[]>\n | Promise<import('mongodb').Flatten<import('mongodb').WithId<T>[Key]>[]> {\n throw new Error('Method not implemented.');\n }\n indexes(\n options: IndexInformationOptions & { full?: true | undefined },\n ): Promise<IndexDescriptionInfo[]>;\n indexes(\n options: IndexInformationOptions & { full: false },\n ): Promise<IndexDescriptionCompact>;\n indexes(\n options: IndexInformationOptions,\n ): Promise<IndexDescriptionCompact | IndexDescriptionInfo[]>;\n indexes(\n options?: AbstractCursorOptions | undefined,\n ): Promise<IndexDescriptionInfo[]>;\n indexes(\n _options?: unknown,\n ):\n | Promise<import('mongodb').IndexDescriptionInfo[]>\n | Promise<import('mongodb').IndexDescriptionCompact>\n | Promise<\n | import('mongodb').IndexDescriptionCompact\n | import('mongodb').IndexDescriptionInfo[]\n > {\n throw new Error('Method not implemented.');\n }\n findOneAndDelete(\n filter: Filter<T>,\n options: FindOneAndDeleteOptions & { includeResultMetadata: true },\n ): Promise<ModifyResult<T>>;\n findOneAndDelete(\n filter: Filter<T>,\n options: FindOneAndDeleteOptions & { includeResultMetadata: false },\n ): Promise<WithId<T> | null>;\n findOneAndDelete(\n filter: Filter<T>,\n options: FindOneAndDeleteOptions,\n ): Promise<WithId<T> | null>;\n findOneAndDelete(filter: Filter<T>): Promise<WithId<T> | null>;\n findOneAndDelete(\n _filter: unknown,\n _options?: unknown,\n ):\n | Promise<import('mongodb').WithId<T> | null>\n | Promise<import('mongodb').ModifyResult<T>> {\n throw new Error('Method not implemented.');\n }\n findOneAndReplace(\n filter: Filter<T>,\n replacement: WithoutId<T>,\n options: FindOneAndReplaceOptions & { includeResultMetadata: true },\n ): Promise<ModifyResult<T>>;\n findOneAndReplace(\n filter: Filter<T>,\n replacement: WithoutId<T>,\n options: FindOneAndReplaceOptions & { includeResultMetadata: false },\n ): Promise<WithId<T> | null>;\n findOneAndReplace(\n filter: Filter<T>,\n replacement: WithoutId<T>,\n options: FindOneAndReplaceOptions,\n ): Promise<WithId<T> | null>;\n findOneAndReplace(\n filter: Filter<T>,\n replacement: WithoutId<T>,\n ): Promise<WithId<T> | null>;\n findOneAndReplace(\n _filter: unknown,\n _replacement: unknown,\n _options?: unknown,\n ):\n | Promise<import('mongodb').WithId<T> | null>\n | Promise<import('mongodb').ModifyResult<T>> {\n throw new Error('Method not implemented.');\n }\n findOneAndUpdate(\n filter: Filter<T>,\n update: UpdateFilter<T>,\n options: FindOneAndUpdateOptions & { includeResultMetadata: true },\n ): Promise<ModifyResult<T>>;\n findOneAndUpdate(\n filter: Filter<T>,\n update: UpdateFilter<T>,\n options: FindOneAndUpdateOptions & { includeResultMetadata: false },\n ): Promise<WithId<T> | null>;\n findOneAndUpdate(\n filter: Filter<T>,\n update: UpdateFilter<T>,\n options: FindOneAndUpdateOptions,\n ): Promise<WithId<T> | null>;\n findOneAndUpdate(\n filter: Filter<T>,\n update: UpdateFilter<T>,\n ): Promise<WithId<T> | null>;\n findOneAndUpdate(\n _filter: unknown,\n _update: unknown,\n _options?: unknown,\n ):\n | Promise<import('mongodb').WithId<T> | null>\n | Promise<import('mongodb').ModifyResult<T>> {\n throw new Error('Method not implemented.');\n }\n aggregate<T extends Document = Document>(\n _pipeline?: Document[] | undefined,\n _options?: AggregateOptions | undefined,\n ): AggregationCursor<T> {\n throw new Error('Method not implemented.');\n }\n watch<\n TLocal extends Document = T,\n TChange extends Document = ChangeStreamDocument<TLocal>,\n >(\n _pipeline?: Document[] | undefined,\n _options?: ChangeStreamOptions | undefined,\n ): ChangeStream<TLocal, TChange> {\n throw new Error('Method not implemented.');\n }\n initializeUnorderedBulkOp(\n _options?: BulkWriteOptions | undefined,\n ): UnorderedBulkOperation {\n throw new Error('Method not implemented.');\n }\n initializeOrderedBulkOp(\n _options?: BulkWriteOptions | undefined,\n ): OrderedBulkOperation {\n throw new Error('Method not implemented.');\n }\n count(\n _filter?: Filter<T> | undefined,\n _options?: CountOptions | undefined,\n ): Promise<number> {\n throw new Error('Method not implemented.');\n }\n listSearchIndexes(\n options?: ListSearchIndexesOptions | undefined,\n ): ListSearchIndexesCursor;\n listSearchIndexes(\n name: string,\n options?: ListSearchIndexesOptions | undefined,\n ): ListSearchIndexesCursor;\n listSearchIndexes(\n _name?: unknown,\n _options?: unknown,\n ): import('mongodb').ListSearchIndexesCursor {\n throw new Error('Method not implemented.');\n }\n createSearchIndex(_description: SearchIndexDescription): Promise<string> {\n throw new Error('Method not implemented.');\n }\n createSearchIndexes(\n _descriptions: SearchIndexDescription[],\n ): Promise<string[]> {\n throw new Error('Method not implemented.');\n }\n dropSearchIndex(_name: string): Promise<void> {\n throw new Error('Method not implemented.');\n }\n updateSearchIndex(_name: string, _definition: Document): Promise<void> {\n throw new Error('Method not implemented.');\n }\n\n async createCollection(): Promise<void> {\n await this.collection.createCollection();\n }\n}\n","// src/MongoClientShim.ts\nimport { pongoClient, type PongoClient } from '../main';\nimport { Db } from './mongoDb';\n\nexport class MongoClient {\n private pongoClient: PongoClient;\n\n constructor(connectionString: string) {\n this.pongoClient = pongoClient(connectionString);\n }\n\n async connect() {\n await this.pongoClient.connect();\n return this;\n }\n\n async close() {\n await this.pongoClient.close();\n }\n\n db(dbName: string): Db {\n return new Db(this.pongoClient.db(dbName));\n }\n}\n"]}
1
+ {"version":3,"sources":["../src/postgres/pool.ts","../src/postgres/postgresCollection.ts","../src/postgres/execute/index.ts","../src/main/typing/entries.ts","../src/postgres/filter/queryOperators.ts","../src/postgres/filter/index.ts","../src/postgres/sql/index.ts","../src/postgres/update/index.ts","../src/postgres/client.ts","../src/main/dbClient.ts","../src/main/client.ts","../src/mongo/findCursor.ts","../src/mongo/mongoDb.ts","../src/mongo/mongoCollection.ts","../src/mongo/mongoClient.ts"],"names":["pg","pools","getPool","connectionStringOrOptions","connectionString","poolOptions","endPool","pool","endAllPools","format","uuid","execute","handle","client","executeSQL","sql","entries","obj","key","value","Operators","OperatorMap","isOperator","hasOperators","handleOperator","path","operator","handleIdOperator","buildNestedObject","v","subQuery","subKey","subValue","acc","AND","constructFilterQuery","filter","isRecord","constructComplexFilterQuery","isEquality","nestedKey","val","sqlQuery","params","buildUpdateQuery","update","currentUpdateQuery","op","buildSetQuery","buildUnsetQuery","buildIncQuery","buildPushQuery","set","unset","inc","push","postgresCollection","collectionName","SqlFor","collectionSQLBuilder","createCollection","document","_id","documents","rows","doc","result","d","row","values","filterQuery","updateQuery","postgresClient","database","name","getDbClient","pongoClient","dbClient","dbName","FindCursor","callback","docs","Collection","collection","_options","_operations","_filter","_","_newName","_indexSpec","_indexSpecs","_indexName","_indexes","_key","_replacement","_update","_pipeline","_name","_description","_descriptions","_definition","Db","pongoDb","MongoClient"],"mappings":"AAAA,OAAOA,M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C,CAC3C,MAAM,IAAI,MAAM,yBAAyB,CAC3C,CACA,kBAAkBc,EAAuD,CACvE,MAAM,IAAI,MAAM,yBAAyB,CAC3C,CACA,oBACEC,EACmB,CACnB,MAAM,IAAI,MAAM,yBAAyB,CAC3C,CACA,gBAAgBF,EAA8B,CAC5C,MAAM,IAAI,MAAM,yBAAyB,CAC3C,CACA,kBAAkBA,EAAeG,EAAsC,CACrE,MAAM,IAAI,MAAM,yBAAyB,CAC3C,CAEA,MAAM,kBAAkC,CACtC,MAAM,KAAK,WAAW,iBAAiB,CACzC,CACF,ED9eO,IAAMC,EAAN,KAAS,CACd,YAAoBC,EAAkB,CAAlB,aAAAA,CAAmB,CAEvC,WAA+B7C,EAA4C,CACzE,OAAO,IAAIyB,EAAc,KAAK,QAAQ,WAAczB,CAAc,CAAC,CACrE,CACF,EENO,IAAM8C,EAAN,KAAkB,CACf,YAER,YAAYnG,EAA0B,CACpC,KAAK,YAAcwE,EAAYxE,CAAgB,CACjD,CAEA,MAAM,SAAU,CACd,aAAM,KAAK,YAAY,QAAQ,EACxB,IACT,CAEA,MAAM,OAAQ,CACZ,MAAM,KAAK,YAAY,MAAM,CAC/B,CAEA,GAAG0E,EAAoB,CACrB,OAAO,IAAIuB,EAAG,KAAK,YAAY,GAAGvB,CAAM,CAAC,CAC3C,CACF","sourcesContent":["import pg from 'pg';\n\nconst pools: Map<string, pg.Pool> = new Map();\n\nexport const getPool = (\n connectionStringOrOptions: string | pg.PoolConfig,\n): pg.Pool => {\n const connectionString =\n typeof connectionStringOrOptions === 'string'\n ? connectionStringOrOptions\n : connectionStringOrOptions.connectionString!;\n\n const poolOptions =\n typeof connectionStringOrOptions === 'string'\n ? { connectionString }\n : connectionStringOrOptions;\n\n //TODO: this should include database name resolution for key\n return (\n pools.get(connectionString) ??\n pools.set(connectionString, new pg.Pool(poolOptions)).get(connectionString)!\n );\n};\n\nexport const endPool = async (connectionString: string): Promise<void> => {\n const pool = pools.get(connectionString);\n if (pool) {\n await pool.end();\n pools.delete(connectionString);\n }\n};\n\nexport const endAllPools = () =>\n Promise.all(\n [...pools.keys()].map((connectionString) => endPool(connectionString)),\n );\n","import pg from 'pg';\nimport format from 'pg-format';\nimport { v4 as uuid } from 'uuid';\nimport {\n type PongoCollection,\n type PongoDeleteResult,\n type PongoFilter,\n type PongoInsertManyResult,\n type PongoInsertOneResult,\n type PongoUpdate,\n type PongoUpdateResult,\n type WithId,\n} from '../main';\nimport { executeSQL } from './execute';\nimport { constructFilterQuery } from './filter';\nimport { sql, type SQL } from './sql';\nimport { buildUpdateQuery } from './update';\n\nexport const postgresCollection = <T>(\n collectionName: string,\n pool: pg.Pool,\n): PongoCollection<T> => {\n const execute = (sql: SQL) => executeSQL(pool, sql);\n const SqlFor = collectionSQLBuilder(collectionName);\n\n const createCollection = execute(SqlFor.createCollection());\n\n return {\n createCollection: async () => {\n await createCollection;\n },\n insertOne: async (document: T): Promise<PongoInsertOneResult> => {\n await createCollection;\n\n const _id = uuid();\n\n const result = await execute(SqlFor.insertOne({ _id, ...document }));\n\n return result.rowCount\n ? { insertedId: _id, acknowledged: true }\n : { insertedId: null, acknowledged: false };\n },\n insertMany: async (documents: T[]): Promise<PongoInsertManyResult> => {\n await createCollection;\n\n const rows = documents.map((doc) => ({\n _id: uuid(),\n ...doc,\n }));\n\n const result = await execute(SqlFor.insertMany(rows));\n\n return {\n acknowledged: result.rowCount === rows.length,\n insertedCount: result.rowCount ?? 0,\n insertedIds: rows.map((d) => d._id),\n };\n },\n updateOne: async (\n filter: PongoFilter<T>,\n update: PongoUpdate<T>,\n ): Promise<PongoUpdateResult> => {\n await createCollection;\n\n const result = await execute(SqlFor.updateOne(filter, update));\n return result.rowCount\n ? { acknowledged: true, modifiedCount: result.rowCount }\n : { acknowledged: false, modifiedCount: 0 };\n },\n updateMany: async (\n filter: PongoFilter<T>,\n update: PongoUpdate<T>,\n ): Promise<PongoUpdateResult> => {\n await createCollection;\n\n const result = await execute(SqlFor.updateMany(filter, update));\n return result.rowCount\n ? { acknowledged: true, modifiedCount: result.rowCount }\n : { acknowledged: false, modifiedCount: 0 };\n },\n deleteOne: async (filter: PongoFilter<T>): Promise<PongoDeleteResult> => {\n await createCollection;\n\n const result = await execute(SqlFor.deleteOne(filter));\n return result.rowCount\n ? { acknowledged: true, deletedCount: result.rowCount }\n : { acknowledged: false, deletedCount: 0 };\n },\n deleteMany: async (filter: PongoFilter<T>): Promise<PongoDeleteResult> => {\n await createCollection;\n\n const result = await execute(SqlFor.deleteMany(filter));\n return result.rowCount\n ? { acknowledged: true, deletedCount: result.rowCount }\n : { acknowledged: false, deletedCount: 0 };\n },\n findOne: async (filter: PongoFilter<T>): Promise<T | null> => {\n await createCollection;\n\n const result = await execute(SqlFor.findOne(filter));\n return (result.rows[0]?.data ?? null) as T | null;\n },\n find: async (filter: PongoFilter<T>): Promise<T[]> => {\n await createCollection;\n\n const result = await execute(SqlFor.find(filter));\n return result.rows.map((row) => row.data as T);\n },\n };\n};\n\nexport const collectionSQLBuilder = (collectionName: string) => ({\n createCollection: (): SQL =>\n sql(\n 'CREATE TABLE IF NOT EXISTS %I (_id UUID PRIMARY KEY, data JSONB)',\n collectionName,\n ),\n insertOne: <T>(document: WithId<T>): SQL =>\n sql(\n 'INSERT INTO %I (_id, data) VALUES (%L, %L)',\n collectionName,\n document._id,\n JSON.stringify(document),\n ),\n insertMany: <T>(documents: WithId<T>[]): SQL => {\n const values = documents\n .map((doc) => format('(%L, %L)', doc._id, JSON.stringify(doc)))\n .join(', ');\n return sql('INSERT INTO %I (_id, data) VALUES %s', collectionName, values);\n },\n updateOne: <T>(filter: PongoFilter<T>, update: PongoUpdate<T>): SQL => {\n const filterQuery = constructFilterQuery(filter);\n const updateQuery = buildUpdateQuery(update);\n\n return sql(\n `WITH cte AS (\n SELECT _id FROM %I WHERE %s LIMIT 1\n )\n UPDATE %I SET data = %s FROM cte WHERE %I._id = cte._id`,\n collectionName,\n filterQuery,\n collectionName,\n updateQuery,\n collectionName,\n );\n },\n updateMany: <T>(filter: PongoFilter<T>, update: PongoUpdate<T>): SQL => {\n const filterQuery = constructFilterQuery(filter);\n const updateQuery = buildUpdateQuery(update);\n\n return sql(\n 'UPDATE %I SET data = %s WHERE %s',\n collectionName,\n updateQuery,\n filterQuery,\n );\n },\n deleteOne: <T>(filter: PongoFilter<T>): SQL => {\n const filterQuery = constructFilterQuery(filter);\n return sql('DELETE FROM %I WHERE %s', collectionName, filterQuery);\n },\n deleteMany: <T>(filter: PongoFilter<T>): SQL => {\n const filterQuery = constructFilterQuery(filter);\n return sql('DELETE FROM %I WHERE %s', collectionName, filterQuery);\n },\n findOne: <T>(filter: PongoFilter<T>): SQL => {\n const filterQuery = constructFilterQuery(filter);\n return sql(\n 'SELECT data FROM %I WHERE %s LIMIT 1',\n collectionName,\n filterQuery,\n );\n },\n find: <T>(filter: PongoFilter<T>): SQL => {\n const filterQuery = constructFilterQuery(filter);\n return sql('SELECT data FROM %I WHERE %s', collectionName, filterQuery);\n },\n});\n","import type pg from 'pg';\nimport type { SQL } from '../sql';\n\nexport const execute = async <Result = void>(\n pool: pg.Pool,\n handle: (client: pg.PoolClient) => Promise<Result>,\n) => {\n const client = await pool.connect();\n try {\n return await handle(client);\n } finally {\n client.release();\n }\n};\n\nexport const executeSQL = async <\n Result extends pg.QueryResultRow = pg.QueryResultRow,\n>(\n pool: pg.Pool,\n sql: SQL,\n): Promise<pg.QueryResult<Result>> =>\n execute(pool, (client) => client.query<Result>(sql));\n","type Entry<T> = {\n [K in keyof Required<T>]: [K, Required<T>[K]];\n}[keyof Required<T>];\n\ntype IterableEntry<T> = Entry<T> & {\n [Symbol.iterator](): Iterator<Entry<T>>;\n};\n\nexport const entries = <T extends object>(obj: T): IterableEntry<T>[] =>\n Object.entries(obj).map(([key, value]) => [key as keyof T, value]);\n\nexport type NonPartial<T> = { [K in keyof Required<T>]: T[K] };\n","import format from 'pg-format';\nimport { entries } from '../../main/typing';\n\nexport const Operators = {\n $eq: '$eq',\n $gt: '$gt',\n $gte: '$gte',\n $lt: '$lt',\n $lte: '$lte',\n $ne: '$ne',\n $in: '$in',\n $nin: '$nin',\n $elemMatch: '$elemMatch',\n $all: '$all',\n $size: '$size',\n};\n\nconst OperatorMap = {\n $gt: '>',\n $gte: '>=',\n $lt: '<',\n $lte: '<=',\n $ne: '!=',\n};\n\nexport const isOperator = (key: string) => key.startsWith('$');\n\nexport const hasOperators = (value: Record<string, unknown>) =>\n Object.keys(value).some(isOperator);\n\nexport const handleOperator = (\n path: string,\n operator: string,\n value: unknown,\n): string => {\n if (path === '_id') {\n return handleIdOperator(operator, value);\n }\n\n switch (operator) {\n case '$eq':\n return format(\n `(data @> %L::jsonb OR jsonb_path_exists(data, '$.%s[*] ? (@ == %s)'))`,\n JSON.stringify(buildNestedObject(path, value)),\n path,\n JSON.stringify(value),\n );\n case '$gt':\n case '$gte':\n case '$lt':\n case '$lte':\n case '$ne':\n return format(\n `data #>> %L ${OperatorMap[operator]} %L`,\n `{${path.split('.').join(',')}}`,\n value,\n );\n case '$in':\n return format(\n 'data #>> %L IN (%s)',\n `{${path.split('.').join(',')}}`,\n (value as unknown[]).map((v) => format('%L', v)).join(', '),\n );\n case '$nin':\n return format(\n 'data #>> %L NOT IN (%s)',\n `{${path.split('.').join(',')}}`,\n (value as unknown[]).map((v) => format('%L', v)).join(', '),\n );\n case '$elemMatch': {\n const subQuery = entries(value as Record<string, unknown>)\n .map(([subKey, subValue]) =>\n format(`@.\"%s\" == %s`, subKey, JSON.stringify(subValue)),\n )\n .join(' && ');\n return format(\n `jsonb_path_exists(data, '$.%s[*] ? (%s)')`,\n path,\n subQuery,\n );\n }\n case '$all':\n return format(\n 'data @> %L::jsonb',\n JSON.stringify(buildNestedObject(path, value)),\n );\n case '$size':\n return format(\n 'jsonb_array_length(data #> %L) = %L',\n `{${path.split('.').join(',')}}`,\n value,\n );\n default:\n throw new Error(`Unsupported operator: ${operator}`);\n }\n};\n\nconst handleIdOperator = (operator: string, value: unknown): string => {\n switch (operator) {\n case '$eq':\n return format(`_id = %L`, value);\n case '$gt':\n case '$gte':\n case '$lt':\n case '$lte':\n case '$ne':\n return format(`_id ${OperatorMap[operator]} %L`, value);\n case '$in':\n return format(\n `_id IN (%s)`,\n (value as unknown[]).map((v) => format('%L', v)).join(', '),\n );\n case '$nin':\n return format(\n `_id NOT IN (%s)`,\n (value as unknown[]).map((v) => format('%L', v)).join(', '),\n );\n default:\n throw new Error(`Unsupported operator: ${operator}`);\n }\n};\n\nconst buildNestedObject = (\n path: string,\n value: unknown,\n): Record<string, unknown> =>\n path\n .split('.')\n .reverse()\n .reduce((acc, key) => ({ [key]: acc }), value as Record<string, unknown>);\n","import type { PongoFilter } from '../../main';\nimport { entries } from '../../main/typing';\nimport { Operators, handleOperator, hasOperators } from './queryOperators';\n\nconst AND = 'AND';\n\nexport const constructFilterQuery = <T>(filter: PongoFilter<T>): string =>\n Object.entries(filter)\n .map(([key, value]) =>\n isRecord(value)\n ? constructComplexFilterQuery(key, value)\n : handleOperator(key, '$eq', value),\n )\n .join(` ${AND} `);\n\nconst constructComplexFilterQuery = (\n key: string,\n value: Record<string, unknown>,\n): string => {\n const isEquality = !hasOperators(value);\n\n return entries(value)\n .map(\n ([nestedKey, val]) =>\n isEquality\n ? handleOperator(`${key}.${nestedKey}`, Operators.$eq, val) // regular value\n : handleOperator(key, nestedKey, val), // operator\n )\n .join(` ${AND} `);\n};\n\nconst isRecord = (value: unknown): value is Record<string, unknown> =>\n value !== null && typeof value === 'object' && !Array.isArray(value);\n","import format from 'pg-format';\n\nexport type SQL = string & { __brand: 'sql' };\n\nexport const sql = (sqlQuery: string, ...params: unknown[]): SQL => {\n return format(sqlQuery, ...params) as SQL;\n};\n","import type { $inc, $push, $set, $unset, PongoUpdate } from '../../main';\nimport { entries } from '../../main/typing';\nimport { sql, type SQL } from '../sql';\n\nexport const buildUpdateQuery = <T>(update: PongoUpdate<T>): SQL =>\n entries(update).reduce((currentUpdateQuery, [op, value]) => {\n switch (op) {\n case '$set':\n return buildSetQuery(value, currentUpdateQuery);\n case '$unset':\n return buildUnsetQuery(value, currentUpdateQuery);\n case '$inc':\n return buildIncQuery(value, currentUpdateQuery);\n case '$push':\n return buildPushQuery(value, currentUpdateQuery);\n default:\n return currentUpdateQuery;\n }\n }, sql('data'));\n\nexport const buildSetQuery = <T>(set: $set<T>, currentUpdateQuery: SQL): SQL =>\n sql(\n 'jsonb_set(%s, %L, data || %L)',\n currentUpdateQuery,\n '{}',\n JSON.stringify(set),\n );\n\nexport const buildUnsetQuery = <T>(\n unset: $unset<T>,\n currentUpdateQuery: SQL,\n): SQL => sql('%s - %L', currentUpdateQuery, Object.keys(unset).join(', '));\n\nexport const buildIncQuery = <T>(\n inc: $inc<T>,\n currentUpdateQuery: SQL,\n): SQL => {\n for (const [key, value] of Object.entries(inc)) {\n currentUpdateQuery = sql(\n \"jsonb_set(%s, '{%s}', to_jsonb((data->>'%s')::numeric + %L))\",\n currentUpdateQuery,\n key,\n key,\n value,\n );\n }\n return currentUpdateQuery;\n};\n\nexport const buildPushQuery = <T>(\n push: $push<T>,\n currentUpdateQuery: SQL,\n): SQL => {\n for (const [key, value] of Object.entries(push)) {\n currentUpdateQuery = sql(\n \"jsonb_set(%s, '{%s}', (COALESCE(data->'%s', '[]'::jsonb) || '[%s]'::jsonb))\",\n currentUpdateQuery,\n key,\n key,\n JSON.stringify(value),\n );\n }\n return currentUpdateQuery;\n};\n","import { type DbClient } from '../main';\nimport { endPool, getPool } from './pool';\nimport { postgresCollection } from './postgresCollection';\n\nexport const postgresClient = (\n connectionString: string,\n database?: string,\n): DbClient => {\n const pool = getPool({ connectionString, database });\n\n return {\n connect: () => Promise.resolve(),\n close: () => endPool(connectionString),\n collection: <T>(name: string) => postgresCollection<T>(name, pool),\n };\n};\n","import { postgresClient } from '../postgres';\nimport type { PongoCollection } from './typing/operations';\n\nexport interface DbClient {\n connect(): Promise<void>;\n close(): Promise<void>;\n collection: <T>(name: string) => PongoCollection<T>;\n}\n\nexport const getDbClient = (\n connectionString: string,\n database?: string,\n): DbClient => {\n // This is the place where in the future could come resolution of other database types\n return postgresClient(connectionString, database);\n};\n","import { getDbClient } from './dbClient';\nimport type { PongoClient, PongoDb } from './typing/operations';\n\nexport const pongoClient = (connectionString: string): PongoClient => {\n const dbClient = getDbClient(connectionString);\n\n const pongoClient: PongoClient = {\n connect: async () => {\n await dbClient.connect();\n return pongoClient;\n },\n close: () => dbClient.close(),\n db: (dbName?: string): PongoDb =>\n dbName ? getDbClient(connectionString, dbName) : dbClient,\n };\n\n return pongoClient;\n};\n","export class FindCursor<T> {\n private findDocumentsPromise: Promise<T[]>;\n private documents: T[] | null = null;\n private index: number = 0;\n\n constructor(documents: Promise<T[]>) {\n this.findDocumentsPromise = documents;\n }\n\n async toArray(): Promise<T[]> {\n return this.findDocuments();\n }\n\n async forEach(callback: (doc: T) => void): Promise<void> {\n const docs = await this.findDocuments();\n\n for (const doc of docs) {\n callback(doc);\n }\n return Promise.resolve();\n }\n\n hasNext(): boolean {\n if (this.documents === null) throw Error('Error while fetching documents');\n return this.index < this.documents.length;\n }\n\n async next(): Promise<T | null> {\n const docs = await this.findDocuments();\n return this.hasNext() ? docs[this.index++] ?? null : null;\n }\n\n private async findDocuments(): Promise<T[]> {\n this.documents = await this.findDocumentsPromise;\n return this.documents;\n }\n}\n","import { Collection as MongoCollection, type Document } from 'mongodb';\nimport type { PongoDb } from '../main';\nimport { Collection } from './mongoCollection';\n\nexport class Db {\n constructor(private pongoDb: PongoDb) {}\n\n collection<T extends Document>(collectionName: string): MongoCollection<T> {\n return new Collection<T>(this.pongoDb.collection<T>(collectionName));\n }\n}\n","import type {\n AbstractCursorOptions,\n AggregateOptions,\n AggregationCursor,\n AnyBulkWriteOperation,\n BSONSerializeOptions,\n BulkWriteOptions,\n BulkWriteResult,\n ChangeStream,\n ChangeStreamDocument,\n ChangeStreamOptions,\n CommandOperationOptions,\n CountDocumentsOptions,\n CountOptions,\n CreateIndexesOptions,\n DeleteOptions,\n DeleteResult,\n Document,\n DropCollectionOptions,\n EnhancedOmit,\n EstimatedDocumentCountOptions,\n Filter,\n FindOneAndDeleteOptions,\n FindOneAndReplaceOptions,\n FindOneAndUpdateOptions,\n FindOptions,\n Flatten,\n Hint,\n IndexDescription,\n IndexDescriptionCompact,\n IndexDescriptionInfo,\n IndexInformationOptions,\n IndexSpecification,\n InferIdType,\n InsertManyResult,\n InsertOneOptions,\n InsertOneResult,\n ListIndexesCursor,\n ListSearchIndexesCursor,\n ListSearchIndexesOptions,\n ModifyResult,\n Collection as MongoCollection,\n FindCursor as MongoFindCursor,\n OperationOptions,\n OptionalUnlessRequiredId,\n OrderedBulkOperation,\n ReadConcern,\n ReadPreference,\n RenameOptions,\n ReplaceOptions,\n SearchIndexDescription,\n UnorderedBulkOperation,\n UpdateFilter,\n UpdateOptions,\n UpdateResult,\n WithId,\n WithoutId,\n WriteConcern,\n} from 'mongodb';\nimport type { Key } from 'readline';\nimport type { PongoCollection, PongoFilter, PongoUpdate } from '../main';\nimport { FindCursor } from './findCursor';\n\nexport class Collection<T extends Document> implements MongoCollection<T> {\n private collection: PongoCollection<T>;\n\n constructor(collection: PongoCollection<T>) {\n this.collection = collection;\n }\n get dbName(): string {\n throw new Error('Method not implemented.');\n }\n get collectionName(): string {\n throw new Error('Method not implemented.');\n }\n get namespace(): string {\n throw new Error('Method not implemented.');\n }\n get readConcern(): ReadConcern | undefined {\n throw new Error('Method not implemented.');\n }\n get readPreference(): ReadPreference | undefined {\n throw new Error('Method not implemented.');\n }\n get bsonOptions(): BSONSerializeOptions {\n throw new Error('Method not implemented.');\n }\n get writeConcern(): WriteConcern | undefined {\n throw new Error('Method not implemented.');\n }\n get hint(): Hint | undefined {\n throw new Error('Method not implemented.');\n }\n set hint(v: Hint | undefined) {\n throw new Error('Method not implemented.');\n }\n async insertOne(\n doc: OptionalUnlessRequiredId<T>,\n _options?: InsertOneOptions | undefined,\n ): Promise<InsertOneResult<T>> {\n const result = await this.collection.insertOne(doc as T);\n return {\n acknowledged: result.acknowledged,\n insertedId: result.insertedId as unknown as InferIdType<T>,\n };\n }\n async insertMany(\n docs: OptionalUnlessRequiredId<T>[],\n _options?: BulkWriteOptions | undefined,\n ): Promise<InsertManyResult<T>> {\n const result = await this.collection.insertMany(docs as T[]);\n return {\n acknowledged: result.acknowledged,\n insertedIds: result.insertedIds as unknown as InferIdType<T>[],\n insertedCount: result.insertedCount,\n };\n }\n bulkWrite(\n _operations: AnyBulkWriteOperation<T>[],\n _options?: BulkWriteOptions | undefined,\n ): Promise<BulkWriteResult> {\n throw new Error('Method not implemented.');\n }\n async updateOne(\n filter: Filter<T>,\n update: Document[] | UpdateFilter<T>,\n _options?: UpdateOptions | undefined,\n ): Promise<UpdateResult<T>> {\n const result = await this.collection.updateOne(\n filter as unknown as PongoFilter<T>,\n update as unknown as PongoUpdate<T>,\n );\n\n return {\n acknowledged: result.acknowledged,\n matchedCount: result.modifiedCount,\n modifiedCount: result.modifiedCount,\n upsertedCount: result.modifiedCount,\n upsertedId: null,\n };\n }\n replaceOne(\n _filter: Filter<T>,\n _: WithoutId<T>,\n _options?: ReplaceOptions | undefined,\n ): Promise<Document | UpdateResult<T>> {\n throw new Error('Method not implemented.');\n }\n async updateMany(\n filter: Filter<T>,\n update: Document[] | UpdateFilter<T>,\n _options?: UpdateOptions | undefined,\n ): Promise<UpdateResult<T>> {\n const result = await this.collection.updateMany(\n filter as unknown as PongoFilter<T>,\n update as unknown as PongoUpdate<T>,\n );\n\n return {\n acknowledged: result.acknowledged,\n matchedCount: result.modifiedCount,\n modifiedCount: result.modifiedCount,\n upsertedCount: result.modifiedCount,\n upsertedId: null,\n };\n }\n async deleteOne(\n filter?: Filter<T> | undefined,\n _options?: DeleteOptions | undefined,\n ): Promise<DeleteResult> {\n const result = await this.collection.deleteOne(\n filter as unknown as PongoFilter<T>,\n );\n\n return {\n acknowledged: result.acknowledged,\n deletedCount: result.deletedCount,\n };\n }\n async deleteMany(\n filter?: Filter<T> | undefined,\n _options?: DeleteOptions | undefined,\n ): Promise<DeleteResult> {\n const result = await this.collection.deleteMany(\n filter as unknown as PongoFilter<T>,\n );\n\n return {\n acknowledged: result.acknowledged,\n deletedCount: result.deletedCount,\n };\n }\n rename(\n _newName: string,\n _options?: RenameOptions | undefined,\n ): Promise<Collection<Document>> {\n throw new Error('Method not implemented.');\n }\n drop(_options?: DropCollectionOptions | undefined): Promise<boolean> {\n throw new Error('Method not implemented.');\n }\n findOne(): Promise<WithId<T> | null>;\n findOne(filter: Filter<T>): Promise<WithId<T> | null>;\n findOne(\n filter: Filter<T>,\n options: FindOptions<Document>,\n ): Promise<WithId<T> | null>;\n findOne<TS = T>(): Promise<TS | null>;\n findOne<TS = T>(filter: Filter<TS>): Promise<TS | null>;\n findOne<TS = T>(\n filter: Filter<TS>,\n options?: FindOptions<Document> | undefined,\n ): Promise<TS | null>;\n async findOne(\n filter?: unknown,\n _options?: unknown,\n ): Promise<import('mongodb').WithId<T> | T | null> {\n return this.collection.findOne(filter as PongoFilter<T>);\n }\n find(): MongoFindCursor<WithId<T>>;\n find(\n filter: Filter<T>,\n options?: FindOptions<Document> | undefined,\n ): MongoFindCursor<WithId<T>>;\n find<T extends Document>(\n filter: Filter<T>,\n options?: FindOptions<Document> | undefined,\n ): MongoFindCursor<T>;\n find(\n filter?: unknown,\n _options?: unknown,\n ): MongoFindCursor<WithId<T>> | MongoFindCursor<T> {\n return new FindCursor(\n this.collection.find(filter as PongoFilter<T>),\n ) as unknown as MongoFindCursor<T>;\n }\n options(_options?: OperationOptions | undefined): Promise<Document> {\n throw new Error('Method not implemented.');\n }\n isCapped(_options?: OperationOptions | undefined): Promise<boolean> {\n throw new Error('Method not implemented.');\n }\n createIndex(\n _indexSpec: IndexSpecification,\n _options?: CreateIndexesOptions | undefined,\n ): Promise<string> {\n throw new Error('Method not implemented.');\n }\n createIndexes(\n _indexSpecs: IndexDescription[],\n _options?: CreateIndexesOptions | undefined,\n ): Promise<string[]> {\n throw new Error('Method not implemented.');\n }\n dropIndex(\n _indexName: string,\n _options?: CommandOperationOptions | undefined,\n ): Promise<Document> {\n throw new Error('Method not implemented.');\n }\n dropIndexes(\n _options?: CommandOperationOptions | undefined,\n ): Promise<boolean> {\n throw new Error('Method not implemented.');\n }\n listIndexes(_options?: AbstractCursorOptions | undefined): ListIndexesCursor {\n throw new Error('Method not implemented.');\n }\n indexExists(\n _indexes: string | string[],\n _options?: AbstractCursorOptions | undefined,\n ): Promise<boolean> {\n throw new Error('Method not implemented.');\n }\n indexInformation(\n options: IndexInformationOptions & { full: true },\n ): Promise<IndexDescriptionInfo[]>;\n indexInformation(\n options: IndexInformationOptions & { full?: false | undefined },\n ): Promise<IndexDescriptionCompact>;\n indexInformation(\n options: IndexInformationOptions,\n ): Promise<IndexDescriptionCompact | IndexDescriptionInfo[]>;\n indexInformation(): Promise<IndexDescriptionCompact>;\n indexInformation(\n _options?: unknown,\n ):\n | Promise<import('mongodb').IndexDescriptionInfo[]>\n | Promise<import('mongodb').IndexDescriptionCompact>\n | Promise<\n | import('mongodb').IndexDescriptionCompact\n | import('mongodb').IndexDescriptionInfo[]\n > {\n throw new Error('Method not implemented.');\n }\n estimatedDocumentCount(\n _options?: EstimatedDocumentCountOptions | undefined,\n ): Promise<number> {\n throw new Error('Method not implemented.');\n }\n countDocuments(\n _filter?: Filter<T> | undefined,\n _options?: CountDocumentsOptions | undefined,\n ): Promise<number> {\n throw new Error('Method not implemented.');\n }\n distinct<Key extends '_id' | keyof EnhancedOmit<T, '_id'>>(\n key: Key,\n ): Promise<Flatten<WithId<T>[Key]>[]>;\n distinct<Key extends '_id' | keyof EnhancedOmit<T, '_id'>>(\n key: Key,\n filter: Filter<T>,\n ): Promise<Flatten<WithId<T>[Key]>[]>;\n distinct<Key extends '_id' | keyof EnhancedOmit<T, '_id'>>(\n key: Key,\n filter: Filter<T>,\n options: CommandOperationOptions,\n ): Promise<Flatten<WithId<T>[Key]>[]>;\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n distinct(key: string): Promise<any[]>;\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n distinct(key: string, filter: Filter<T>): Promise<any[]>;\n distinct(\n key: string,\n filter: Filter<T>,\n options: CommandOperationOptions, // eslint-disable-next-line @typescript-eslint/no-explicit-any\n ): Promise<any[]>;\n distinct(\n _key: unknown,\n _filter?: unknown,\n _options?: unknown,\n ): // eslint-disable-next-line @typescript-eslint/no-explicit-any\n | Promise<any[]>\n | Promise<import('mongodb').Flatten<import('mongodb').WithId<T>[Key]>[]> {\n throw new Error('Method not implemented.');\n }\n indexes(\n options: IndexInformationOptions & { full?: true | undefined },\n ): Promise<IndexDescriptionInfo[]>;\n indexes(\n options: IndexInformationOptions & { full: false },\n ): Promise<IndexDescriptionCompact>;\n indexes(\n options: IndexInformationOptions,\n ): Promise<IndexDescriptionCompact | IndexDescriptionInfo[]>;\n indexes(\n options?: AbstractCursorOptions | undefined,\n ): Promise<IndexDescriptionInfo[]>;\n indexes(\n _options?: unknown,\n ):\n | Promise<import('mongodb').IndexDescriptionInfo[]>\n | Promise<import('mongodb').IndexDescriptionCompact>\n | Promise<\n | import('mongodb').IndexDescriptionCompact\n | import('mongodb').IndexDescriptionInfo[]\n > {\n throw new Error('Method not implemented.');\n }\n findOneAndDelete(\n filter: Filter<T>,\n options: FindOneAndDeleteOptions & { includeResultMetadata: true },\n ): Promise<ModifyResult<T>>;\n findOneAndDelete(\n filter: Filter<T>,\n options: FindOneAndDeleteOptions & { includeResultMetadata: false },\n ): Promise<WithId<T> | null>;\n findOneAndDelete(\n filter: Filter<T>,\n options: FindOneAndDeleteOptions,\n ): Promise<WithId<T> | null>;\n findOneAndDelete(filter: Filter<T>): Promise<WithId<T> | null>;\n findOneAndDelete(\n _filter: unknown,\n _options?: unknown,\n ):\n | Promise<import('mongodb').WithId<T> | null>\n | Promise<import('mongodb').ModifyResult<T>> {\n throw new Error('Method not implemented.');\n }\n findOneAndReplace(\n filter: Filter<T>,\n replacement: WithoutId<T>,\n options: FindOneAndReplaceOptions & { includeResultMetadata: true },\n ): Promise<ModifyResult<T>>;\n findOneAndReplace(\n filter: Filter<T>,\n replacement: WithoutId<T>,\n options: FindOneAndReplaceOptions & { includeResultMetadata: false },\n ): Promise<WithId<T> | null>;\n findOneAndReplace(\n filter: Filter<T>,\n replacement: WithoutId<T>,\n options: FindOneAndReplaceOptions,\n ): Promise<WithId<T> | null>;\n findOneAndReplace(\n filter: Filter<T>,\n replacement: WithoutId<T>,\n ): Promise<WithId<T> | null>;\n findOneAndReplace(\n _filter: unknown,\n _replacement: unknown,\n _options?: unknown,\n ):\n | Promise<import('mongodb').WithId<T> | null>\n | Promise<import('mongodb').ModifyResult<T>> {\n throw new Error('Method not implemented.');\n }\n findOneAndUpdate(\n filter: Filter<T>,\n update: UpdateFilter<T>,\n options: FindOneAndUpdateOptions & { includeResultMetadata: true },\n ): Promise<ModifyResult<T>>;\n findOneAndUpdate(\n filter: Filter<T>,\n update: UpdateFilter<T>,\n options: FindOneAndUpdateOptions & { includeResultMetadata: false },\n ): Promise<WithId<T> | null>;\n findOneAndUpdate(\n filter: Filter<T>,\n update: UpdateFilter<T>,\n options: FindOneAndUpdateOptions,\n ): Promise<WithId<T> | null>;\n findOneAndUpdate(\n filter: Filter<T>,\n update: UpdateFilter<T>,\n ): Promise<WithId<T> | null>;\n findOneAndUpdate(\n _filter: unknown,\n _update: unknown,\n _options?: unknown,\n ):\n | Promise<import('mongodb').WithId<T> | null>\n | Promise<import('mongodb').ModifyResult<T>> {\n throw new Error('Method not implemented.');\n }\n aggregate<T extends Document = Document>(\n _pipeline?: Document[] | undefined,\n _options?: AggregateOptions | undefined,\n ): AggregationCursor<T> {\n throw new Error('Method not implemented.');\n }\n watch<\n TLocal extends Document = T,\n TChange extends Document = ChangeStreamDocument<TLocal>,\n >(\n _pipeline?: Document[] | undefined,\n _options?: ChangeStreamOptions | undefined,\n ): ChangeStream<TLocal, TChange> {\n throw new Error('Method not implemented.');\n }\n initializeUnorderedBulkOp(\n _options?: BulkWriteOptions | undefined,\n ): UnorderedBulkOperation {\n throw new Error('Method not implemented.');\n }\n initializeOrderedBulkOp(\n _options?: BulkWriteOptions | undefined,\n ): OrderedBulkOperation {\n throw new Error('Method not implemented.');\n }\n count(\n _filter?: Filter<T> | undefined,\n _options?: CountOptions | undefined,\n ): Promise<number> {\n throw new Error('Method not implemented.');\n }\n listSearchIndexes(\n options?: ListSearchIndexesOptions | undefined,\n ): ListSearchIndexesCursor;\n listSearchIndexes(\n name: string,\n options?: ListSearchIndexesOptions | undefined,\n ): ListSearchIndexesCursor;\n listSearchIndexes(\n _name?: unknown,\n _options?: unknown,\n ): import('mongodb').ListSearchIndexesCursor {\n throw new Error('Method not implemented.');\n }\n createSearchIndex(_description: SearchIndexDescription): Promise<string> {\n throw new Error('Method not implemented.');\n }\n createSearchIndexes(\n _descriptions: SearchIndexDescription[],\n ): Promise<string[]> {\n throw new Error('Method not implemented.');\n }\n dropSearchIndex(_name: string): Promise<void> {\n throw new Error('Method not implemented.');\n }\n updateSearchIndex(_name: string, _definition: Document): Promise<void> {\n throw new Error('Method not implemented.');\n }\n\n async createCollection(): Promise<void> {\n await this.collection.createCollection();\n }\n}\n","// src/MongoClientShim.ts\nimport { pongoClient, type PongoClient } from '../main';\nimport { Db } from './mongoDb';\n\nexport class MongoClient {\n private pongoClient: PongoClient;\n\n constructor(connectionString: string) {\n this.pongoClient = pongoClient(connectionString);\n }\n\n async connect() {\n await this.pongoClient.connect();\n return this;\n }\n\n async close() {\n await this.pongoClient.close();\n }\n\n db(dbName: string): Db {\n return new Db(this.pongoClient.db(dbName));\n }\n}\n"]}
package/dist/index.d.cts CHANGED
@@ -1,4 +1,4 @@
1
- import { Document, Collection as Collection$1, ReadConcern, ReadPreference, BSONSerializeOptions, WriteConcern, Hint, OptionalUnlessRequiredId, InsertOneOptions, InsertOneResult, BulkWriteOptions, InsertManyResult, AnyBulkWriteOperation, BulkWriteResult, Filter, UpdateFilter, UpdateOptions, UpdateResult, WithoutId, ReplaceOptions, DeleteOptions, DeleteResult, RenameOptions, DropCollectionOptions, WithId, FindOptions, FindCursor as FindCursor$1, OperationOptions, IndexSpecification, CreateIndexesOptions, IndexDescription, CommandOperationOptions, AbstractCursorOptions, ListIndexesCursor, IndexInformationOptions, IndexDescriptionInfo, IndexDescriptionCompact, EstimatedDocumentCountOptions, CountDocumentsOptions, EnhancedOmit, Flatten, FindOneAndDeleteOptions, ModifyResult, FindOneAndReplaceOptions, FindOneAndUpdateOptions, AggregateOptions, AggregationCursor, ChangeStreamDocument, ChangeStreamOptions, ChangeStream, UnorderedBulkOperation, OrderedBulkOperation, CountOptions, ListSearchIndexesOptions, ListSearchIndexesCursor, SearchIndexDescription } from 'mongodb';
1
+ import { Document, Collection as Collection$1, ReadConcern, ReadPreference, BSONSerializeOptions, WriteConcern, Hint, OptionalUnlessRequiredId, InsertOneOptions, InsertOneResult, BulkWriteOptions, InsertManyResult, AnyBulkWriteOperation, BulkWriteResult, Filter, UpdateFilter, UpdateOptions, UpdateResult, WithoutId, ReplaceOptions, DeleteOptions, DeleteResult, RenameOptions, DropCollectionOptions, WithId as WithId$1, FindOptions, FindCursor as FindCursor$1, OperationOptions, IndexSpecification, CreateIndexesOptions, IndexDescription, CommandOperationOptions, AbstractCursorOptions, ListIndexesCursor, IndexInformationOptions, IndexDescriptionInfo, IndexDescriptionCompact, EstimatedDocumentCountOptions, CountDocumentsOptions, EnhancedOmit, Flatten, FindOneAndDeleteOptions, ModifyResult, FindOneAndReplaceOptions, FindOneAndUpdateOptions, AggregateOptions, AggregationCursor, ChangeStreamDocument, ChangeStreamOptions, ChangeStream, UnorderedBulkOperation, OrderedBulkOperation, CountOptions, ListSearchIndexesOptions, ListSearchIndexesCursor, SearchIndexDescription } from 'mongodb';
2
2
  import pg from 'pg';
3
3
 
4
4
  interface PongoClient {
@@ -12,11 +12,17 @@ interface PongoDb {
12
12
  interface PongoCollection<T> {
13
13
  createCollection(): Promise<void>;
14
14
  insertOne(document: T): Promise<PongoInsertOneResult>;
15
+ insertMany(documents: T[]): Promise<PongoInsertManyResult>;
15
16
  updateOne(filter: PongoFilter<T>, update: PongoUpdate<T>): Promise<PongoUpdateResult>;
17
+ updateMany(filter: PongoFilter<T>, update: PongoUpdate<T>): Promise<PongoUpdateResult>;
16
18
  deleteOne(filter: PongoFilter<T>): Promise<PongoDeleteResult>;
19
+ deleteMany(filter: PongoFilter<T>): Promise<PongoDeleteResult>;
17
20
  findOne(filter: PongoFilter<T>): Promise<T | null>;
18
21
  find(filter: PongoFilter<T>): Promise<T[]>;
19
22
  }
23
+ type WithId<T> = T & {
24
+ _id: string;
25
+ };
20
26
  type PongoFilter<T> = {
21
27
  [P in keyof T]?: T[P] | PongoFilterOperator<T[P]>;
22
28
  };
@@ -50,14 +56,27 @@ interface PongoInsertOneResult {
50
56
  insertedId: string | null;
51
57
  acknowledged: boolean;
52
58
  }
59
+ interface PongoInsertManyResult {
60
+ acknowledged: boolean;
61
+ insertedIds: string[];
62
+ insertedCount: number;
63
+ }
53
64
  interface PongoUpdateResult {
54
65
  acknowledged: boolean;
55
66
  modifiedCount: number;
56
67
  }
68
+ interface PongoUpdateManyResult {
69
+ acknowledged: boolean;
70
+ modifiedCount: number;
71
+ }
57
72
  interface PongoDeleteResult {
58
73
  acknowledged: boolean;
59
74
  deletedCount: number;
60
75
  }
76
+ interface PongoDeleteManyResult {
77
+ acknowledged: boolean;
78
+ deletedCount: number;
79
+ }
61
80
 
62
81
  declare const pongoClient: (connectionString: string) => PongoClient;
63
82
 
@@ -107,23 +126,23 @@ declare class Collection<T extends Document> implements Collection$1<T> {
107
126
  get hint(): Hint | undefined;
108
127
  set hint(v: Hint | undefined);
109
128
  insertOne(doc: OptionalUnlessRequiredId<T>, _options?: InsertOneOptions | undefined): Promise<InsertOneResult<T>>;
110
- insertMany(_docs: OptionalUnlessRequiredId<T>[], _options?: BulkWriteOptions | undefined): Promise<InsertManyResult<T>>;
129
+ insertMany(docs: OptionalUnlessRequiredId<T>[], _options?: BulkWriteOptions | undefined): Promise<InsertManyResult<T>>;
111
130
  bulkWrite(_operations: AnyBulkWriteOperation<T>[], _options?: BulkWriteOptions | undefined): Promise<BulkWriteResult>;
112
131
  updateOne(filter: Filter<T>, update: Document[] | UpdateFilter<T>, _options?: UpdateOptions | undefined): Promise<UpdateResult<T>>;
113
132
  replaceOne(_filter: Filter<T>, _: WithoutId<T>, _options?: ReplaceOptions | undefined): Promise<Document | UpdateResult<T>>;
114
- updateMany(_filter: Filter<T>, _update: Document[] | UpdateFilter<T>, _options?: UpdateOptions | undefined): Promise<UpdateResult<T>>;
133
+ updateMany(filter: Filter<T>, update: Document[] | UpdateFilter<T>, _options?: UpdateOptions | undefined): Promise<UpdateResult<T>>;
115
134
  deleteOne(filter?: Filter<T> | undefined, _options?: DeleteOptions | undefined): Promise<DeleteResult>;
116
- deleteMany(_filter?: Filter<T> | undefined, _options?: DeleteOptions | undefined): Promise<DeleteResult>;
135
+ deleteMany(filter?: Filter<T> | undefined, _options?: DeleteOptions | undefined): Promise<DeleteResult>;
117
136
  rename(_newName: string, _options?: RenameOptions | undefined): Promise<Collection<Document>>;
118
137
  drop(_options?: DropCollectionOptions | undefined): Promise<boolean>;
119
- findOne(): Promise<WithId<T> | null>;
120
- findOne(filter: Filter<T>): Promise<WithId<T> | null>;
121
- findOne(filter: Filter<T>, options: FindOptions<Document>): Promise<WithId<T> | null>;
138
+ findOne(): Promise<WithId$1<T> | null>;
139
+ findOne(filter: Filter<T>): Promise<WithId$1<T> | null>;
140
+ findOne(filter: Filter<T>, options: FindOptions<Document>): Promise<WithId$1<T> | null>;
122
141
  findOne<TS = T>(): Promise<TS | null>;
123
142
  findOne<TS = T>(filter: Filter<TS>): Promise<TS | null>;
124
143
  findOne<TS = T>(filter: Filter<TS>, options?: FindOptions<Document> | undefined): Promise<TS | null>;
125
- find(): FindCursor$1<WithId<T>>;
126
- find(filter: Filter<T>, options?: FindOptions<Document> | undefined): FindCursor$1<WithId<T>>;
144
+ find(): FindCursor$1<WithId$1<T>>;
145
+ find(filter: Filter<T>, options?: FindOptions<Document> | undefined): FindCursor$1<WithId$1<T>>;
127
146
  find<T extends Document>(filter: Filter<T>, options?: FindOptions<Document> | undefined): FindCursor$1<T>;
128
147
  options(_options?: OperationOptions | undefined): Promise<Document>;
129
148
  isCapped(_options?: OperationOptions | undefined): Promise<boolean>;
@@ -143,9 +162,9 @@ declare class Collection<T extends Document> implements Collection$1<T> {
143
162
  indexInformation(): Promise<IndexDescriptionCompact>;
144
163
  estimatedDocumentCount(_options?: EstimatedDocumentCountOptions | undefined): Promise<number>;
145
164
  countDocuments(_filter?: Filter<T> | undefined, _options?: CountDocumentsOptions | undefined): Promise<number>;
146
- distinct<Key extends '_id' | keyof EnhancedOmit<T, '_id'>>(key: Key): Promise<Flatten<WithId<T>[Key]>[]>;
147
- distinct<Key extends '_id' | keyof EnhancedOmit<T, '_id'>>(key: Key, filter: Filter<T>): Promise<Flatten<WithId<T>[Key]>[]>;
148
- distinct<Key extends '_id' | keyof EnhancedOmit<T, '_id'>>(key: Key, filter: Filter<T>, options: CommandOperationOptions): Promise<Flatten<WithId<T>[Key]>[]>;
165
+ distinct<Key extends '_id' | keyof EnhancedOmit<T, '_id'>>(key: Key): Promise<Flatten<WithId$1<T>[Key]>[]>;
166
+ distinct<Key extends '_id' | keyof EnhancedOmit<T, '_id'>>(key: Key, filter: Filter<T>): Promise<Flatten<WithId$1<T>[Key]>[]>;
167
+ distinct<Key extends '_id' | keyof EnhancedOmit<T, '_id'>>(key: Key, filter: Filter<T>, options: CommandOperationOptions): Promise<Flatten<WithId$1<T>[Key]>[]>;
149
168
  distinct(key: string): Promise<any[]>;
150
169
  distinct(key: string, filter: Filter<T>): Promise<any[]>;
151
170
  distinct(key: string, filter: Filter<T>, options: CommandOperationOptions): Promise<any[]>;
@@ -162,25 +181,25 @@ declare class Collection<T extends Document> implements Collection$1<T> {
162
181
  }): Promise<ModifyResult<T>>;
163
182
  findOneAndDelete(filter: Filter<T>, options: FindOneAndDeleteOptions & {
164
183
  includeResultMetadata: false;
165
- }): Promise<WithId<T> | null>;
166
- findOneAndDelete(filter: Filter<T>, options: FindOneAndDeleteOptions): Promise<WithId<T> | null>;
167
- findOneAndDelete(filter: Filter<T>): Promise<WithId<T> | null>;
184
+ }): Promise<WithId$1<T> | null>;
185
+ findOneAndDelete(filter: Filter<T>, options: FindOneAndDeleteOptions): Promise<WithId$1<T> | null>;
186
+ findOneAndDelete(filter: Filter<T>): Promise<WithId$1<T> | null>;
168
187
  findOneAndReplace(filter: Filter<T>, replacement: WithoutId<T>, options: FindOneAndReplaceOptions & {
169
188
  includeResultMetadata: true;
170
189
  }): Promise<ModifyResult<T>>;
171
190
  findOneAndReplace(filter: Filter<T>, replacement: WithoutId<T>, options: FindOneAndReplaceOptions & {
172
191
  includeResultMetadata: false;
173
- }): Promise<WithId<T> | null>;
174
- findOneAndReplace(filter: Filter<T>, replacement: WithoutId<T>, options: FindOneAndReplaceOptions): Promise<WithId<T> | null>;
175
- findOneAndReplace(filter: Filter<T>, replacement: WithoutId<T>): Promise<WithId<T> | null>;
192
+ }): Promise<WithId$1<T> | null>;
193
+ findOneAndReplace(filter: Filter<T>, replacement: WithoutId<T>, options: FindOneAndReplaceOptions): Promise<WithId$1<T> | null>;
194
+ findOneAndReplace(filter: Filter<T>, replacement: WithoutId<T>): Promise<WithId$1<T> | null>;
176
195
  findOneAndUpdate(filter: Filter<T>, update: UpdateFilter<T>, options: FindOneAndUpdateOptions & {
177
196
  includeResultMetadata: true;
178
197
  }): Promise<ModifyResult<T>>;
179
198
  findOneAndUpdate(filter: Filter<T>, update: UpdateFilter<T>, options: FindOneAndUpdateOptions & {
180
199
  includeResultMetadata: false;
181
- }): Promise<WithId<T> | null>;
182
- findOneAndUpdate(filter: Filter<T>, update: UpdateFilter<T>, options: FindOneAndUpdateOptions): Promise<WithId<T> | null>;
183
- findOneAndUpdate(filter: Filter<T>, update: UpdateFilter<T>): Promise<WithId<T> | null>;
200
+ }): Promise<WithId$1<T> | null>;
201
+ findOneAndUpdate(filter: Filter<T>, update: UpdateFilter<T>, options: FindOneAndUpdateOptions): Promise<WithId$1<T> | null>;
202
+ findOneAndUpdate(filter: Filter<T>, update: UpdateFilter<T>): Promise<WithId$1<T> | null>;
184
203
  aggregate<T extends Document = Document>(_pipeline?: Document[] | undefined, _options?: AggregateOptions | undefined): AggregationCursor<T>;
185
204
  watch<TLocal extends Document = T, TChange extends Document = ChangeStreamDocument<TLocal>>(_pipeline?: Document[] | undefined, _options?: ChangeStreamOptions | undefined): ChangeStream<TLocal, TChange>;
186
205
  initializeUnorderedBulkOp(_options?: BulkWriteOptions | undefined): UnorderedBulkOperation;
@@ -216,4 +235,4 @@ declare const buildUnsetQuery: <T>(unset: $unset<T>, currentUpdateQuery: SQL) =>
216
235
  declare const buildIncQuery: <T>(inc: $inc<T>, currentUpdateQuery: SQL) => SQL;
217
236
  declare const buildPushQuery: <T>(push: $push<T>, currentUpdateQuery: SQL) => SQL;
218
237
 
219
- export { type $inc, type $push, type $set, type $unset, Collection, Db, type DbClient, FindCursor, MongoClient, type PongoClient, type PongoCollection, type PongoDb, type PongoDeleteResult, type PongoFilter, type PongoFilterOperator, type PongoInsertOneResult, type PongoUpdate, type PongoUpdateResult, buildIncQuery, buildPushQuery, buildSetQuery, buildUnsetQuery, buildUpdateQuery, constructFilterQuery, endAllPools, endPool, execute, executeSQL, getDbClient, getPool, pongoClient, postgresClient };
238
+ export { type $inc, type $push, type $set, type $unset, Collection, Db, type DbClient, FindCursor, MongoClient, type PongoClient, type PongoCollection, type PongoDb, type PongoDeleteManyResult, type PongoDeleteResult, type PongoFilter, type PongoFilterOperator, type PongoInsertManyResult, type PongoInsertOneResult, type PongoUpdate, type PongoUpdateManyResult, type PongoUpdateResult, type WithId, buildIncQuery, buildPushQuery, buildSetQuery, buildUnsetQuery, buildUpdateQuery, constructFilterQuery, endAllPools, endPool, execute, executeSQL, getDbClient, getPool, pongoClient, postgresClient };
package/dist/index.d.ts CHANGED
@@ -1,4 +1,4 @@
1
- import { Document, Collection as Collection$1, ReadConcern, ReadPreference, BSONSerializeOptions, WriteConcern, Hint, OptionalUnlessRequiredId, InsertOneOptions, InsertOneResult, BulkWriteOptions, InsertManyResult, AnyBulkWriteOperation, BulkWriteResult, Filter, UpdateFilter, UpdateOptions, UpdateResult, WithoutId, ReplaceOptions, DeleteOptions, DeleteResult, RenameOptions, DropCollectionOptions, WithId, FindOptions, FindCursor as FindCursor$1, OperationOptions, IndexSpecification, CreateIndexesOptions, IndexDescription, CommandOperationOptions, AbstractCursorOptions, ListIndexesCursor, IndexInformationOptions, IndexDescriptionInfo, IndexDescriptionCompact, EstimatedDocumentCountOptions, CountDocumentsOptions, EnhancedOmit, Flatten, FindOneAndDeleteOptions, ModifyResult, FindOneAndReplaceOptions, FindOneAndUpdateOptions, AggregateOptions, AggregationCursor, ChangeStreamDocument, ChangeStreamOptions, ChangeStream, UnorderedBulkOperation, OrderedBulkOperation, CountOptions, ListSearchIndexesOptions, ListSearchIndexesCursor, SearchIndexDescription } from 'mongodb';
1
+ import { Document, Collection as Collection$1, ReadConcern, ReadPreference, BSONSerializeOptions, WriteConcern, Hint, OptionalUnlessRequiredId, InsertOneOptions, InsertOneResult, BulkWriteOptions, InsertManyResult, AnyBulkWriteOperation, BulkWriteResult, Filter, UpdateFilter, UpdateOptions, UpdateResult, WithoutId, ReplaceOptions, DeleteOptions, DeleteResult, RenameOptions, DropCollectionOptions, WithId as WithId$1, FindOptions, FindCursor as FindCursor$1, OperationOptions, IndexSpecification, CreateIndexesOptions, IndexDescription, CommandOperationOptions, AbstractCursorOptions, ListIndexesCursor, IndexInformationOptions, IndexDescriptionInfo, IndexDescriptionCompact, EstimatedDocumentCountOptions, CountDocumentsOptions, EnhancedOmit, Flatten, FindOneAndDeleteOptions, ModifyResult, FindOneAndReplaceOptions, FindOneAndUpdateOptions, AggregateOptions, AggregationCursor, ChangeStreamDocument, ChangeStreamOptions, ChangeStream, UnorderedBulkOperation, OrderedBulkOperation, CountOptions, ListSearchIndexesOptions, ListSearchIndexesCursor, SearchIndexDescription } from 'mongodb';
2
2
  import pg from 'pg';
3
3
 
4
4
  interface PongoClient {
@@ -12,11 +12,17 @@ interface PongoDb {
12
12
  interface PongoCollection<T> {
13
13
  createCollection(): Promise<void>;
14
14
  insertOne(document: T): Promise<PongoInsertOneResult>;
15
+ insertMany(documents: T[]): Promise<PongoInsertManyResult>;
15
16
  updateOne(filter: PongoFilter<T>, update: PongoUpdate<T>): Promise<PongoUpdateResult>;
17
+ updateMany(filter: PongoFilter<T>, update: PongoUpdate<T>): Promise<PongoUpdateResult>;
16
18
  deleteOne(filter: PongoFilter<T>): Promise<PongoDeleteResult>;
19
+ deleteMany(filter: PongoFilter<T>): Promise<PongoDeleteResult>;
17
20
  findOne(filter: PongoFilter<T>): Promise<T | null>;
18
21
  find(filter: PongoFilter<T>): Promise<T[]>;
19
22
  }
23
+ type WithId<T> = T & {
24
+ _id: string;
25
+ };
20
26
  type PongoFilter<T> = {
21
27
  [P in keyof T]?: T[P] | PongoFilterOperator<T[P]>;
22
28
  };
@@ -50,14 +56,27 @@ interface PongoInsertOneResult {
50
56
  insertedId: string | null;
51
57
  acknowledged: boolean;
52
58
  }
59
+ interface PongoInsertManyResult {
60
+ acknowledged: boolean;
61
+ insertedIds: string[];
62
+ insertedCount: number;
63
+ }
53
64
  interface PongoUpdateResult {
54
65
  acknowledged: boolean;
55
66
  modifiedCount: number;
56
67
  }
68
+ interface PongoUpdateManyResult {
69
+ acknowledged: boolean;
70
+ modifiedCount: number;
71
+ }
57
72
  interface PongoDeleteResult {
58
73
  acknowledged: boolean;
59
74
  deletedCount: number;
60
75
  }
76
+ interface PongoDeleteManyResult {
77
+ acknowledged: boolean;
78
+ deletedCount: number;
79
+ }
61
80
 
62
81
  declare const pongoClient: (connectionString: string) => PongoClient;
63
82
 
@@ -107,23 +126,23 @@ declare class Collection<T extends Document> implements Collection$1<T> {
107
126
  get hint(): Hint | undefined;
108
127
  set hint(v: Hint | undefined);
109
128
  insertOne(doc: OptionalUnlessRequiredId<T>, _options?: InsertOneOptions | undefined): Promise<InsertOneResult<T>>;
110
- insertMany(_docs: OptionalUnlessRequiredId<T>[], _options?: BulkWriteOptions | undefined): Promise<InsertManyResult<T>>;
129
+ insertMany(docs: OptionalUnlessRequiredId<T>[], _options?: BulkWriteOptions | undefined): Promise<InsertManyResult<T>>;
111
130
  bulkWrite(_operations: AnyBulkWriteOperation<T>[], _options?: BulkWriteOptions | undefined): Promise<BulkWriteResult>;
112
131
  updateOne(filter: Filter<T>, update: Document[] | UpdateFilter<T>, _options?: UpdateOptions | undefined): Promise<UpdateResult<T>>;
113
132
  replaceOne(_filter: Filter<T>, _: WithoutId<T>, _options?: ReplaceOptions | undefined): Promise<Document | UpdateResult<T>>;
114
- updateMany(_filter: Filter<T>, _update: Document[] | UpdateFilter<T>, _options?: UpdateOptions | undefined): Promise<UpdateResult<T>>;
133
+ updateMany(filter: Filter<T>, update: Document[] | UpdateFilter<T>, _options?: UpdateOptions | undefined): Promise<UpdateResult<T>>;
115
134
  deleteOne(filter?: Filter<T> | undefined, _options?: DeleteOptions | undefined): Promise<DeleteResult>;
116
- deleteMany(_filter?: Filter<T> | undefined, _options?: DeleteOptions | undefined): Promise<DeleteResult>;
135
+ deleteMany(filter?: Filter<T> | undefined, _options?: DeleteOptions | undefined): Promise<DeleteResult>;
117
136
  rename(_newName: string, _options?: RenameOptions | undefined): Promise<Collection<Document>>;
118
137
  drop(_options?: DropCollectionOptions | undefined): Promise<boolean>;
119
- findOne(): Promise<WithId<T> | null>;
120
- findOne(filter: Filter<T>): Promise<WithId<T> | null>;
121
- findOne(filter: Filter<T>, options: FindOptions<Document>): Promise<WithId<T> | null>;
138
+ findOne(): Promise<WithId$1<T> | null>;
139
+ findOne(filter: Filter<T>): Promise<WithId$1<T> | null>;
140
+ findOne(filter: Filter<T>, options: FindOptions<Document>): Promise<WithId$1<T> | null>;
122
141
  findOne<TS = T>(): Promise<TS | null>;
123
142
  findOne<TS = T>(filter: Filter<TS>): Promise<TS | null>;
124
143
  findOne<TS = T>(filter: Filter<TS>, options?: FindOptions<Document> | undefined): Promise<TS | null>;
125
- find(): FindCursor$1<WithId<T>>;
126
- find(filter: Filter<T>, options?: FindOptions<Document> | undefined): FindCursor$1<WithId<T>>;
144
+ find(): FindCursor$1<WithId$1<T>>;
145
+ find(filter: Filter<T>, options?: FindOptions<Document> | undefined): FindCursor$1<WithId$1<T>>;
127
146
  find<T extends Document>(filter: Filter<T>, options?: FindOptions<Document> | undefined): FindCursor$1<T>;
128
147
  options(_options?: OperationOptions | undefined): Promise<Document>;
129
148
  isCapped(_options?: OperationOptions | undefined): Promise<boolean>;
@@ -143,9 +162,9 @@ declare class Collection<T extends Document> implements Collection$1<T> {
143
162
  indexInformation(): Promise<IndexDescriptionCompact>;
144
163
  estimatedDocumentCount(_options?: EstimatedDocumentCountOptions | undefined): Promise<number>;
145
164
  countDocuments(_filter?: Filter<T> | undefined, _options?: CountDocumentsOptions | undefined): Promise<number>;
146
- distinct<Key extends '_id' | keyof EnhancedOmit<T, '_id'>>(key: Key): Promise<Flatten<WithId<T>[Key]>[]>;
147
- distinct<Key extends '_id' | keyof EnhancedOmit<T, '_id'>>(key: Key, filter: Filter<T>): Promise<Flatten<WithId<T>[Key]>[]>;
148
- distinct<Key extends '_id' | keyof EnhancedOmit<T, '_id'>>(key: Key, filter: Filter<T>, options: CommandOperationOptions): Promise<Flatten<WithId<T>[Key]>[]>;
165
+ distinct<Key extends '_id' | keyof EnhancedOmit<T, '_id'>>(key: Key): Promise<Flatten<WithId$1<T>[Key]>[]>;
166
+ distinct<Key extends '_id' | keyof EnhancedOmit<T, '_id'>>(key: Key, filter: Filter<T>): Promise<Flatten<WithId$1<T>[Key]>[]>;
167
+ distinct<Key extends '_id' | keyof EnhancedOmit<T, '_id'>>(key: Key, filter: Filter<T>, options: CommandOperationOptions): Promise<Flatten<WithId$1<T>[Key]>[]>;
149
168
  distinct(key: string): Promise<any[]>;
150
169
  distinct(key: string, filter: Filter<T>): Promise<any[]>;
151
170
  distinct(key: string, filter: Filter<T>, options: CommandOperationOptions): Promise<any[]>;
@@ -162,25 +181,25 @@ declare class Collection<T extends Document> implements Collection$1<T> {
162
181
  }): Promise<ModifyResult<T>>;
163
182
  findOneAndDelete(filter: Filter<T>, options: FindOneAndDeleteOptions & {
164
183
  includeResultMetadata: false;
165
- }): Promise<WithId<T> | null>;
166
- findOneAndDelete(filter: Filter<T>, options: FindOneAndDeleteOptions): Promise<WithId<T> | null>;
167
- findOneAndDelete(filter: Filter<T>): Promise<WithId<T> | null>;
184
+ }): Promise<WithId$1<T> | null>;
185
+ findOneAndDelete(filter: Filter<T>, options: FindOneAndDeleteOptions): Promise<WithId$1<T> | null>;
186
+ findOneAndDelete(filter: Filter<T>): Promise<WithId$1<T> | null>;
168
187
  findOneAndReplace(filter: Filter<T>, replacement: WithoutId<T>, options: FindOneAndReplaceOptions & {
169
188
  includeResultMetadata: true;
170
189
  }): Promise<ModifyResult<T>>;
171
190
  findOneAndReplace(filter: Filter<T>, replacement: WithoutId<T>, options: FindOneAndReplaceOptions & {
172
191
  includeResultMetadata: false;
173
- }): Promise<WithId<T> | null>;
174
- findOneAndReplace(filter: Filter<T>, replacement: WithoutId<T>, options: FindOneAndReplaceOptions): Promise<WithId<T> | null>;
175
- findOneAndReplace(filter: Filter<T>, replacement: WithoutId<T>): Promise<WithId<T> | null>;
192
+ }): Promise<WithId$1<T> | null>;
193
+ findOneAndReplace(filter: Filter<T>, replacement: WithoutId<T>, options: FindOneAndReplaceOptions): Promise<WithId$1<T> | null>;
194
+ findOneAndReplace(filter: Filter<T>, replacement: WithoutId<T>): Promise<WithId$1<T> | null>;
176
195
  findOneAndUpdate(filter: Filter<T>, update: UpdateFilter<T>, options: FindOneAndUpdateOptions & {
177
196
  includeResultMetadata: true;
178
197
  }): Promise<ModifyResult<T>>;
179
198
  findOneAndUpdate(filter: Filter<T>, update: UpdateFilter<T>, options: FindOneAndUpdateOptions & {
180
199
  includeResultMetadata: false;
181
- }): Promise<WithId<T> | null>;
182
- findOneAndUpdate(filter: Filter<T>, update: UpdateFilter<T>, options: FindOneAndUpdateOptions): Promise<WithId<T> | null>;
183
- findOneAndUpdate(filter: Filter<T>, update: UpdateFilter<T>): Promise<WithId<T> | null>;
200
+ }): Promise<WithId$1<T> | null>;
201
+ findOneAndUpdate(filter: Filter<T>, update: UpdateFilter<T>, options: FindOneAndUpdateOptions): Promise<WithId$1<T> | null>;
202
+ findOneAndUpdate(filter: Filter<T>, update: UpdateFilter<T>): Promise<WithId$1<T> | null>;
184
203
  aggregate<T extends Document = Document>(_pipeline?: Document[] | undefined, _options?: AggregateOptions | undefined): AggregationCursor<T>;
185
204
  watch<TLocal extends Document = T, TChange extends Document = ChangeStreamDocument<TLocal>>(_pipeline?: Document[] | undefined, _options?: ChangeStreamOptions | undefined): ChangeStream<TLocal, TChange>;
186
205
  initializeUnorderedBulkOp(_options?: BulkWriteOptions | undefined): UnorderedBulkOperation;
@@ -216,4 +235,4 @@ declare const buildUnsetQuery: <T>(unset: $unset<T>, currentUpdateQuery: SQL) =>
216
235
  declare const buildIncQuery: <T>(inc: $inc<T>, currentUpdateQuery: SQL) => SQL;
217
236
  declare const buildPushQuery: <T>(push: $push<T>, currentUpdateQuery: SQL) => SQL;
218
237
 
219
- export { type $inc, type $push, type $set, type $unset, Collection, Db, type DbClient, FindCursor, MongoClient, type PongoClient, type PongoCollection, type PongoDb, type PongoDeleteResult, type PongoFilter, type PongoFilterOperator, type PongoInsertOneResult, type PongoUpdate, type PongoUpdateResult, buildIncQuery, buildPushQuery, buildSetQuery, buildUnsetQuery, buildUpdateQuery, constructFilterQuery, endAllPools, endPool, execute, executeSQL, getDbClient, getPool, pongoClient, postgresClient };
238
+ export { type $inc, type $push, type $set, type $unset, Collection, Db, type DbClient, FindCursor, MongoClient, type PongoClient, type PongoCollection, type PongoDb, type PongoDeleteManyResult, type PongoDeleteResult, type PongoFilter, type PongoFilterOperator, type PongoInsertManyResult, type PongoInsertOneResult, type PongoUpdate, type PongoUpdateManyResult, type PongoUpdateResult, type WithId, buildIncQuery, buildPushQuery, buildSetQuery, buildUnsetQuery, buildUpdateQuery, constructFilterQuery, endAllPools, endPool, execute, executeSQL, getDbClient, getPool, pongoClient, postgresClient };
package/dist/index.js CHANGED
@@ -1,2 +1,5 @@
1
- import b from"pg";var m=new Map,w=t=>{let e=typeof t=="string"?t:t.connectionString,n=typeof t=="string"?{connectionString:e}:t;return m.get(e)??m.set(e,new b.Pool(n)).get(e)},h=async t=>{let e=m.get(t);e&&(await e.end(),m.delete(t))},J=()=>Promise.all([...m.keys()].map(t=>h(t)));import"pg";import{v4 as q}from"uuid";var M=async(t,e)=>{let n=await t.connect();try{return await e(n)}finally{n.release()}},P=async(t,e)=>M(t,n=>n.query(e));var p=t=>Object.entries(t).map(([e,n])=>[e,n]);import r from"pg-format";var x={$eq:"$eq",$gt:"$gt",$gte:"$gte",$lt:"$lt",$lte:"$lte",$ne:"$ne",$in:"$in",$nin:"$nin",$elemMatch:"$elemMatch",$all:"$all",$size:"$size"},C={$gt:">",$gte:">=",$lt:"<",$lte:"<=",$ne:"!="},S=t=>t.startsWith("$"),y=t=>Object.keys(t).some(S),c=(t,e,n)=>{if(t==="_id")return $(e,n);switch(e){case"$eq":return r("(data @> %L::jsonb OR jsonb_path_exists(data, '$.%s[*] ? (@ == %s)'))",JSON.stringify(I(t,n)),t,JSON.stringify(n));case"$gt":case"$gte":case"$lt":case"$lte":case"$ne":return r(`data #>> %L ${C[e]} %L`,`{${t.split(".").join(",")}}`,n);case"$in":return r("data #>> %L IN (%s)",`{${t.split(".").join(",")}}`,n.map(o=>r("%L",o)).join(", "));case"$nin":return r("data #>> %L NOT IN (%s)",`{${t.split(".").join(",")}}`,n.map(o=>r("%L",o)).join(", "));case"$elemMatch":{let o=p(n).map(([i,s])=>r('@."%s" == %s',i,JSON.stringify(s))).join(" && ");return r("jsonb_path_exists(data, '$.%s[*] ? (%s)')",t,o)}case"$all":return r("data @> %L::jsonb",JSON.stringify(I(t,n)));case"$size":return r("jsonb_array_length(data #> %L) = %L",`{${t.split(".").join(",")}}`,n);default:throw new Error(`Unsupported operator: ${e}`)}},$=(t,e)=>{switch(t){case"$eq":return r("_id = %L",e);case"$gt":case"$gte":case"$lt":case"$lte":case"$ne":return r(`_id ${C[t]} %L`,e);case"$in":return r("_id IN (%s)",e.map(n=>r("%L",n)).join(", "));case"$nin":return r("_id NOT IN (%s)",e.map(n=>r("%L",n)).join(", "));default:throw new Error(`Unsupported operator: ${t}`)}},I=(t,e)=>t.split(".").reverse().reduce((n,o)=>({[o]:n}),e);var D="AND",u=t=>Object.entries(t).map(([e,n])=>A(n)?L(e,n):c(e,"$eq",n)).join(` ${D} `),L=(t,e)=>{let n=!y(e);return p(e).map(([o,i])=>n?c(`${t}.${o}`,x.$eq,i):c(t,o,i)).join(` ${D} `)},A=t=>t!==null&&typeof t=="object"&&!Array.isArray(t);import W from"pg-format";var d=(t,...e)=>W(t,...e);var F=t=>p(t).reduce((e,[n,o])=>{switch(n){case"$set":return U(o,e);case"$unset":return Q(o,e);case"$inc":return j(o,e);case"$push":return N(o,e);default:return e}},d("data")),U=(t,e)=>d("jsonb_set(%s, %L, data || %L)",e,"{}",JSON.stringify(t)),Q=(t,e)=>d("%s - %L",e,Object.keys(t).join(", ")),j=(t,e)=>{for(let[n,o]of Object.entries(t))e=d("jsonb_set(%s, '{%s}', to_jsonb((data->>'%s')::numeric + %L))",e,n,n,o);return e},N=(t,e)=>{for(let[n,o]of Object.entries(t))e=d("jsonb_set(%s, '{%s}', (COALESCE(data->'%s', '[]'::jsonb) || '[%s]'::jsonb))",e,n,n,JSON.stringify(o));return e};var _=(t,e)=>{let n=s=>P(e,s),o=B(t),i=n(o.createCollection());return{createCollection:async()=>{await i},insertOne:async s=>{await i;let l=q();return(await n(o.insertOne(l,s))).rowCount?{insertedId:l,acknowledged:!0}:{insertedId:null,acknowledged:!1}},updateOne:async(s,l)=>{await i;let a=await n(o.updateOne(s,l));return a.rowCount?{acknowledged:!0,modifiedCount:a.rowCount}:{acknowledged:!1,modifiedCount:0}},deleteOne:async s=>{await i;let l=await n(o.deleteOne(s));return l.rowCount?{acknowledged:!0,deletedCount:l.rowCount}:{acknowledged:!1,deletedCount:0}},findOne:async s=>(await i,(await n(o.findOne(s))).rows[0]?.data??null),find:async s=>(await i,(await n(o.find(s))).rows.map(a=>a.data))}},B=t=>({createCollection:()=>d("CREATE TABLE IF NOT EXISTS %I (_id UUID PRIMARY KEY, data JSONB)",t),insertOne:(e,n)=>d("INSERT INTO %I (_id, data) VALUES (%L, %L)",t,e,JSON.stringify({...n,_id:e})),updateOne:(e,n)=>{let o=u(e),i=F(n);return d("UPDATE %I SET data = %s WHERE %s",t,i,o)},deleteOne:e=>{let n=u(e);return d("DELETE FROM %I WHERE %s",t,n)},findOne:e=>{let n=u(e);return d("SELECT data FROM %I WHERE %s LIMIT 1",t,n)},find:e=>{let n=u(e);return d("SELECT data FROM %I WHERE %s",t,n)}});var E=(t,e)=>{let n=w({connectionString:t,database:e});return{connect:()=>Promise.resolve(),close:()=>h(t),collection:o=>_(o,n)}};var O=(t,e)=>E(t,e);var R=t=>{let e=O(t),n={connect:async()=>(await e.connect(),n),close:()=>e.close(),db:o=>o?O(t,o):e};return n};var f=class{findDocumentsPromise;documents=null;index=0;constructor(e){this.findDocumentsPromise=e}async toArray(){return this.findDocuments()}async forEach(e){let n=await this.findDocuments();for(let o of n)e(o);return Promise.resolve()}hasNext(){if(this.documents===null)throw Error("Error while fetching documents");return this.index<this.documents.length}async next(){let e=await this.findDocuments();return this.hasNext()?e[this.index++]??null:null}async findDocuments(){return this.documents=await this.findDocumentsPromise,this.documents}};import"mongodb";var g=class{collection;constructor(e){this.collection=e}get dbName(){throw new Error("Method not implemented.")}get collectionName(){throw new Error("Method not implemented.")}get namespace(){throw new Error("Method not implemented.")}get readConcern(){throw new Error("Method not implemented.")}get readPreference(){throw new Error("Method not implemented.")}get bsonOptions(){throw new Error("Method not implemented.")}get writeConcern(){throw new Error("Method not implemented.")}get hint(){throw new Error("Method not implemented.")}set hint(e){throw new Error("Method not implemented.")}async insertOne(e,n){let o=await this.collection.insertOne(e);return{acknowledged:o.acknowledged,insertedId:o.insertedId}}insertMany(e,n){throw new Error("Method not implemented.")}bulkWrite(e,n){throw new Error("Method not implemented.")}async updateOne(e,n,o){let i=await this.collection.updateOne(e,n);return{acknowledged:i.acknowledged,matchedCount:i.modifiedCount,modifiedCount:i.modifiedCount,upsertedCount:i.modifiedCount,upsertedId:null}}replaceOne(e,n,o){throw new Error("Method not implemented.")}updateMany(e,n,o){throw new Error("Method not implemented.")}async deleteOne(e,n){let o=await this.collection.deleteOne(e);return{acknowledged:o.acknowledged,deletedCount:o.deletedCount}}deleteMany(e,n){throw new Error("Method not implemented.")}rename(e,n){throw new Error("Method not implemented.")}drop(e){throw new Error("Method not implemented.")}async findOne(e,n){return this.collection.findOne(e)}find(e,n){return new f(this.collection.find(e))}options(e){throw new Error("Method not implemented.")}isCapped(e){throw new Error("Method not implemented.")}createIndex(e,n){throw new Error("Method not implemented.")}createIndexes(e,n){throw new Error("Method not implemented.")}dropIndex(e,n){throw new Error("Method not implemented.")}dropIndexes(e){throw new Error("Method not implemented.")}listIndexes(e){throw new Error("Method not implemented.")}indexExists(e,n){throw new Error("Method not implemented.")}indexInformation(e){throw new Error("Method not implemented.")}estimatedDocumentCount(e){throw new Error("Method not implemented.")}countDocuments(e,n){throw new Error("Method not implemented.")}distinct(e,n,o){throw new Error("Method not implemented.")}indexes(e){throw new Error("Method not implemented.")}findOneAndDelete(e,n){throw new Error("Method not implemented.")}findOneAndReplace(e,n,o){throw new Error("Method not implemented.")}findOneAndUpdate(e,n,o){throw new Error("Method not implemented.")}aggregate(e,n){throw new Error("Method not implemented.")}watch(e,n){throw new Error("Method not implemented.")}initializeUnorderedBulkOp(e){throw new Error("Method not implemented.")}initializeOrderedBulkOp(e){throw new Error("Method not implemented.")}count(e,n){throw new Error("Method not implemented.")}listSearchIndexes(e,n){throw new Error("Method not implemented.")}createSearchIndex(e){throw new Error("Method not implemented.")}createSearchIndexes(e){throw new Error("Method not implemented.")}dropSearchIndex(e){throw new Error("Method not implemented.")}updateSearchIndex(e,n){throw new Error("Method not implemented.")}async createCollection(){await this.collection.createCollection()}};var T=class{constructor(e){this.pongoDb=e}collection(e){return new g(this.pongoDb.collection(e))}};var k=class{pongoClient;constructor(e){this.pongoClient=R(e)}async connect(){return await this.pongoClient.connect(),this}async close(){await this.pongoClient.close()}db(e){return new T(this.pongoClient.db(e))}};export{g as Collection,T as Db,f as FindCursor,k as MongoClient,j as buildIncQuery,N as buildPushQuery,U as buildSetQuery,Q as buildUnsetQuery,F as buildUpdateQuery,u as constructFilterQuery,J as endAllPools,h as endPool,M as execute,P as executeSQL,O as getDbClient,w as getPool,R as pongoClient,E as postgresClient};
1
+ import b from"pg";var m=new Map,I=t=>{let e=typeof t=="string"?t:t.connectionString,n=typeof t=="string"?{connectionString:e}:t;return m.get(e)??m.set(e,new b.Pool(n)).get(e)},h=async t=>{let e=m.get(t);e&&(await e.end(),m.delete(t))},z=()=>Promise.all([...m.keys()].map(t=>h(t)));import"pg";import K from"pg-format";import{v4 as E}from"uuid";var $=async(t,e)=>{let n=await t.connect();try{return await e(n)}finally{n.release()}},y=async(t,e)=>$(t,n=>n.query(e));var u=t=>Object.entries(t).map(([e,n])=>[e,n]);import d from"pg-format";var x={$eq:"$eq",$gt:"$gt",$gte:"$gte",$lt:"$lt",$lte:"$lte",$ne:"$ne",$in:"$in",$nin:"$nin",$elemMatch:"$elemMatch",$all:"$all",$size:"$size"},D={$gt:">",$gte:">=",$lt:"<",$lte:"<=",$ne:"!="},L=t=>t.startsWith("$"),F=t=>Object.keys(t).some(L),c=(t,e,n)=>{if(t==="_id")return W(e,n);switch(e){case"$eq":return d("(data @> %L::jsonb OR jsonb_path_exists(data, '$.%s[*] ? (@ == %s)'))",JSON.stringify(C(t,n)),t,JSON.stringify(n));case"$gt":case"$gte":case"$lt":case"$lte":case"$ne":return d(`data #>> %L ${D[e]} %L`,`{${t.split(".").join(",")}}`,n);case"$in":return d("data #>> %L IN (%s)",`{${t.split(".").join(",")}}`,n.map(o=>d("%L",o)).join(", "));case"$nin":return d("data #>> %L NOT IN (%s)",`{${t.split(".").join(",")}}`,n.map(o=>d("%L",o)).join(", "));case"$elemMatch":{let o=u(n).map(([i,r])=>d('@."%s" == %s',i,JSON.stringify(r))).join(" && ");return d("jsonb_path_exists(data, '$.%s[*] ? (%s)')",t,o)}case"$all":return d("data @> %L::jsonb",JSON.stringify(C(t,n)));case"$size":return d("jsonb_array_length(data #> %L) = %L",`{${t.split(".").join(",")}}`,n);default:throw new Error(`Unsupported operator: ${e}`)}},W=(t,e)=>{switch(t){case"$eq":return d("_id = %L",e);case"$gt":case"$gte":case"$lt":case"$lte":case"$ne":return d(`_id ${D[t]} %L`,e);case"$in":return d("_id IN (%s)",e.map(n=>d("%L",n)).join(", "));case"$nin":return d("_id NOT IN (%s)",e.map(n=>d("%L",n)).join(", "));default:throw new Error(`Unsupported operator: ${t}`)}},C=(t,e)=>t.split(".").reverse().reduce((n,o)=>({[o]:n}),e);var k="AND",p=t=>Object.entries(t).map(([e,n])=>U(n)?A(e,n):c(e,"$eq",n)).join(` ${k} `),A=(t,e)=>{let n=!F(e);return u(e).map(([o,i])=>n?c(`${t}.${o}`,x.$eq,i):c(t,o,i)).join(` ${k} `)},U=t=>t!==null&&typeof t=="object"&&!Array.isArray(t);import Q from"pg-format";var l=(t,...e)=>Q(t,...e);var O=t=>u(t).reduce((e,[n,o])=>{switch(n){case"$set":return j(o,e);case"$unset":return q(o,e);case"$inc":return N(o,e);case"$push":return B(o,e);default:return e}},l("data")),j=(t,e)=>l("jsonb_set(%s, %L, data || %L)",e,"{}",JSON.stringify(t)),q=(t,e)=>l("%s - %L",e,Object.keys(t).join(", ")),N=(t,e)=>{for(let[n,o]of Object.entries(t))e=l("jsonb_set(%s, '{%s}', to_jsonb((data->>'%s')::numeric + %L))",e,n,n,o);return e},B=(t,e)=>{for(let[n,o]of Object.entries(t))e=l("jsonb_set(%s, '{%s}', (COALESCE(data->'%s', '[]'::jsonb) || '[%s]'::jsonb))",e,n,n,JSON.stringify(o));return e};var M=(t,e)=>{let n=r=>y(e,r),o=H(t),i=n(o.createCollection());return{createCollection:async()=>{await i},insertOne:async r=>{await i;let s=E();return(await n(o.insertOne({_id:s,...r}))).rowCount?{insertedId:s,acknowledged:!0}:{insertedId:null,acknowledged:!1}},insertMany:async r=>{await i;let s=r.map(w=>({_id:E(),...w})),a=await n(o.insertMany(s));return{acknowledged:a.rowCount===s.length,insertedCount:a.rowCount??0,insertedIds:s.map(w=>w._id)}},updateOne:async(r,s)=>{await i;let a=await n(o.updateOne(r,s));return a.rowCount?{acknowledged:!0,modifiedCount:a.rowCount}:{acknowledged:!1,modifiedCount:0}},updateMany:async(r,s)=>{await i;let a=await n(o.updateMany(r,s));return a.rowCount?{acknowledged:!0,modifiedCount:a.rowCount}:{acknowledged:!1,modifiedCount:0}},deleteOne:async r=>{await i;let s=await n(o.deleteOne(r));return s.rowCount?{acknowledged:!0,deletedCount:s.rowCount}:{acknowledged:!1,deletedCount:0}},deleteMany:async r=>{await i;let s=await n(o.deleteMany(r));return s.rowCount?{acknowledged:!0,deletedCount:s.rowCount}:{acknowledged:!1,deletedCount:0}},findOne:async r=>(await i,(await n(o.findOne(r))).rows[0]?.data??null),find:async r=>(await i,(await n(o.find(r))).rows.map(a=>a.data))}},H=t=>({createCollection:()=>l("CREATE TABLE IF NOT EXISTS %I (_id UUID PRIMARY KEY, data JSONB)",t),insertOne:e=>l("INSERT INTO %I (_id, data) VALUES (%L, %L)",t,e._id,JSON.stringify(e)),insertMany:e=>{let n=e.map(o=>K("(%L, %L)",o._id,JSON.stringify(o))).join(", ");return l("INSERT INTO %I (_id, data) VALUES %s",t,n)},updateOne:(e,n)=>{let o=p(e),i=O(n);return l(`WITH cte AS (
2
+ SELECT _id FROM %I WHERE %s LIMIT 1
3
+ )
4
+ UPDATE %I SET data = %s FROM cte WHERE %I._id = cte._id`,t,o,t,i,t)},updateMany:(e,n)=>{let o=p(e),i=O(n);return l("UPDATE %I SET data = %s WHERE %s",t,i,o)},deleteOne:e=>{let n=p(e);return l("DELETE FROM %I WHERE %s",t,n)},deleteMany:e=>{let n=p(e);return l("DELETE FROM %I WHERE %s",t,n)},findOne:e=>{let n=p(e);return l("SELECT data FROM %I WHERE %s LIMIT 1",t,n)},find:e=>{let n=p(e);return l("SELECT data FROM %I WHERE %s",t,n)}});var R=(t,e)=>{let n=I({connectionString:t,database:e});return{connect:()=>Promise.resolve(),close:()=>h(t),collection:o=>M(o,n)}};var P=(t,e)=>R(t,e);var _=t=>{let e=P(t),n={connect:async()=>(await e.connect(),n),close:()=>e.close(),db:o=>o?P(t,o):e};return n};var f=class{findDocumentsPromise;documents=null;index=0;constructor(e){this.findDocumentsPromise=e}async toArray(){return this.findDocuments()}async forEach(e){let n=await this.findDocuments();for(let o of n)e(o);return Promise.resolve()}hasNext(){if(this.documents===null)throw Error("Error while fetching documents");return this.index<this.documents.length}async next(){let e=await this.findDocuments();return this.hasNext()?e[this.index++]??null:null}async findDocuments(){return this.documents=await this.findDocumentsPromise,this.documents}};import"mongodb";var g=class{collection;constructor(e){this.collection=e}get dbName(){throw new Error("Method not implemented.")}get collectionName(){throw new Error("Method not implemented.")}get namespace(){throw new Error("Method not implemented.")}get readConcern(){throw new Error("Method not implemented.")}get readPreference(){throw new Error("Method not implemented.")}get bsonOptions(){throw new Error("Method not implemented.")}get writeConcern(){throw new Error("Method not implemented.")}get hint(){throw new Error("Method not implemented.")}set hint(e){throw new Error("Method not implemented.")}async insertOne(e,n){let o=await this.collection.insertOne(e);return{acknowledged:o.acknowledged,insertedId:o.insertedId}}async insertMany(e,n){let o=await this.collection.insertMany(e);return{acknowledged:o.acknowledged,insertedIds:o.insertedIds,insertedCount:o.insertedCount}}bulkWrite(e,n){throw new Error("Method not implemented.")}async updateOne(e,n,o){let i=await this.collection.updateOne(e,n);return{acknowledged:i.acknowledged,matchedCount:i.modifiedCount,modifiedCount:i.modifiedCount,upsertedCount:i.modifiedCount,upsertedId:null}}replaceOne(e,n,o){throw new Error("Method not implemented.")}async updateMany(e,n,o){let i=await this.collection.updateMany(e,n);return{acknowledged:i.acknowledged,matchedCount:i.modifiedCount,modifiedCount:i.modifiedCount,upsertedCount:i.modifiedCount,upsertedId:null}}async deleteOne(e,n){let o=await this.collection.deleteOne(e);return{acknowledged:o.acknowledged,deletedCount:o.deletedCount}}async deleteMany(e,n){let o=await this.collection.deleteMany(e);return{acknowledged:o.acknowledged,deletedCount:o.deletedCount}}rename(e,n){throw new Error("Method not implemented.")}drop(e){throw new Error("Method not implemented.")}async findOne(e,n){return this.collection.findOne(e)}find(e,n){return new f(this.collection.find(e))}options(e){throw new Error("Method not implemented.")}isCapped(e){throw new Error("Method not implemented.")}createIndex(e,n){throw new Error("Method not implemented.")}createIndexes(e,n){throw new Error("Method not implemented.")}dropIndex(e,n){throw new Error("Method not implemented.")}dropIndexes(e){throw new Error("Method not implemented.")}listIndexes(e){throw new Error("Method not implemented.")}indexExists(e,n){throw new Error("Method not implemented.")}indexInformation(e){throw new Error("Method not implemented.")}estimatedDocumentCount(e){throw new Error("Method not implemented.")}countDocuments(e,n){throw new Error("Method not implemented.")}distinct(e,n,o){throw new Error("Method not implemented.")}indexes(e){throw new Error("Method not implemented.")}findOneAndDelete(e,n){throw new Error("Method not implemented.")}findOneAndReplace(e,n,o){throw new Error("Method not implemented.")}findOneAndUpdate(e,n,o){throw new Error("Method not implemented.")}aggregate(e,n){throw new Error("Method not implemented.")}watch(e,n){throw new Error("Method not implemented.")}initializeUnorderedBulkOp(e){throw new Error("Method not implemented.")}initializeOrderedBulkOp(e){throw new Error("Method not implemented.")}count(e,n){throw new Error("Method not implemented.")}listSearchIndexes(e,n){throw new Error("Method not implemented.")}createSearchIndex(e){throw new Error("Method not implemented.")}createSearchIndexes(e){throw new Error("Method not implemented.")}dropSearchIndex(e){throw new Error("Method not implemented.")}updateSearchIndex(e,n){throw new Error("Method not implemented.")}async createCollection(){await this.collection.createCollection()}};var T=class{constructor(e){this.pongoDb=e}collection(e){return new g(this.pongoDb.collection(e))}};var S=class{pongoClient;constructor(e){this.pongoClient=_(e)}async connect(){return await this.pongoClient.connect(),this}async close(){await this.pongoClient.close()}db(e){return new T(this.pongoClient.db(e))}};export{g as Collection,T as Db,f as FindCursor,S as MongoClient,N as buildIncQuery,B as buildPushQuery,j as buildSetQuery,q as buildUnsetQuery,O as buildUpdateQuery,p as constructFilterQuery,z as endAllPools,h as endPool,$ as execute,y as executeSQL,P as getDbClient,I as getPool,_ as pongoClient,R as postgresClient};
2
5
  //# sourceMappingURL=index.js.map
package/dist/index.js.map CHANGED
@@ -1 +1 @@
1
- {"version":3,"sources":["../src/postgres/pool.ts","../src/postgres/postgresCollection.ts","../src/postgres/execute/index.ts","../src/main/typing/entries.ts","../src/postgres/filter/queryOperators.ts","../src/postgres/filter/index.ts","../src/postgres/sql/index.ts","../src/postgres/update/index.ts","../src/postgres/client.ts","../src/main/dbClient.ts","../src/main/client.ts","../src/mongo/findCursor.ts","../src/mongo/mongoDb.ts","../src/mongo/mongoCollection.ts","../src/mongo/mongoClient.ts"],"sourcesContent":["import pg from 'pg';\n\nconst pools: Map<string, pg.Pool> = new Map();\n\nexport const getPool = (\n connectionStringOrOptions: string | pg.PoolConfig,\n): pg.Pool => {\n const connectionString =\n typeof connectionStringOrOptions === 'string'\n ? connectionStringOrOptions\n : connectionStringOrOptions.connectionString!;\n\n const poolOptions =\n typeof connectionStringOrOptions === 'string'\n ? { connectionString }\n : connectionStringOrOptions;\n\n //TODO: this should include database name resolution for key\n return (\n pools.get(connectionString) ??\n pools.set(connectionString, new pg.Pool(poolOptions)).get(connectionString)!\n );\n};\n\nexport const endPool = async (connectionString: string): Promise<void> => {\n const pool = pools.get(connectionString);\n if (pool) {\n await pool.end();\n pools.delete(connectionString);\n }\n};\n\nexport const endAllPools = () =>\n Promise.all(\n [...pools.keys()].map((connectionString) => endPool(connectionString)),\n );\n","import pg from 'pg';\nimport { v4 as uuid } from 'uuid';\nimport {\n type PongoCollection,\n type PongoDeleteResult,\n type PongoFilter,\n type PongoInsertOneResult,\n type PongoUpdate,\n type PongoUpdateResult,\n} from '../main';\nimport { executeSQL } from './execute';\nimport { constructFilterQuery } from './filter';\nimport { sql, type SQL } from './sql';\nimport { buildUpdateQuery } from './update';\n\nexport const postgresCollection = <T>(\n collectionName: string,\n pool: pg.Pool,\n): PongoCollection<T> => {\n const execute = (sql: SQL) => executeSQL(pool, sql);\n const SqlFor = collectionSQLBuilder(collectionName);\n\n const createCollection = execute(SqlFor.createCollection());\n\n return {\n createCollection: async () => {\n await createCollection;\n },\n insertOne: async (document: T): Promise<PongoInsertOneResult> => {\n await createCollection;\n\n const id = uuid();\n\n const result = await execute(SqlFor.insertOne(id, document));\n\n return result.rowCount\n ? { insertedId: id, acknowledged: true }\n : { insertedId: null, acknowledged: false };\n },\n updateOne: async (\n filter: PongoFilter<T>,\n update: PongoUpdate<T>,\n ): Promise<PongoUpdateResult> => {\n await createCollection;\n\n const result = await execute(SqlFor.updateOne(filter, update));\n return result.rowCount\n ? { acknowledged: true, modifiedCount: result.rowCount }\n : { acknowledged: false, modifiedCount: 0 };\n },\n deleteOne: async (filter: PongoFilter<T>): Promise<PongoDeleteResult> => {\n await createCollection;\n\n const result = await execute(SqlFor.deleteOne(filter));\n return result.rowCount\n ? { acknowledged: true, deletedCount: result.rowCount }\n : { acknowledged: false, deletedCount: 0 };\n },\n findOne: async (filter: PongoFilter<T>): Promise<T | null> => {\n await createCollection;\n\n const result = await execute(SqlFor.findOne(filter));\n return (result.rows[0]?.data ?? null) as T | null;\n },\n find: async (filter: PongoFilter<T>): Promise<T[]> => {\n await createCollection;\n\n const result = await execute(SqlFor.find(filter));\n return result.rows.map((row) => row.data as T);\n },\n };\n};\n\nexport const collectionSQLBuilder = (collectionName: string) => ({\n createCollection: (): SQL =>\n sql(\n 'CREATE TABLE IF NOT EXISTS %I (_id UUID PRIMARY KEY, data JSONB)',\n collectionName,\n ),\n insertOne: <T>(id: string, document: T): SQL =>\n sql(\n 'INSERT INTO %I (_id, data) VALUES (%L, %L)',\n collectionName,\n id,\n JSON.stringify({ ...document, _id: id }),\n ),\n updateOne: <T>(filter: PongoFilter<T>, update: PongoUpdate<T>): SQL => {\n const filterQuery = constructFilterQuery(filter);\n const updateQuery = buildUpdateQuery(update);\n\n return sql(\n 'UPDATE %I SET data = %s WHERE %s',\n collectionName,\n updateQuery,\n filterQuery,\n );\n },\n deleteOne: <T>(filter: PongoFilter<T>): SQL => {\n const filterQuery = constructFilterQuery(filter);\n return sql('DELETE FROM %I WHERE %s', collectionName, filterQuery);\n },\n findOne: <T>(filter: PongoFilter<T>): SQL => {\n const filterQuery = constructFilterQuery(filter);\n return sql(\n 'SELECT data FROM %I WHERE %s LIMIT 1',\n collectionName,\n filterQuery,\n );\n },\n find: <T>(filter: PongoFilter<T>): SQL => {\n const filterQuery = constructFilterQuery(filter);\n return sql('SELECT data FROM %I WHERE %s', collectionName, filterQuery);\n },\n});\n","import type pg from 'pg';\nimport type { SQL } from '../sql';\n\nexport const execute = async <Result = void>(\n pool: pg.Pool,\n handle: (client: pg.PoolClient) => Promise<Result>,\n) => {\n const client = await pool.connect();\n try {\n return await handle(client);\n } finally {\n client.release();\n }\n};\n\nexport const executeSQL = async <\n Result extends pg.QueryResultRow = pg.QueryResultRow,\n>(\n pool: pg.Pool,\n sql: SQL,\n): Promise<pg.QueryResult<Result>> =>\n execute(pool, (client) => client.query<Result>(sql));\n","type Entry<T> = {\n [K in keyof Required<T>]: [K, Required<T>[K]];\n}[keyof Required<T>];\n\ntype IterableEntry<T> = Entry<T> & {\n [Symbol.iterator](): Iterator<Entry<T>>;\n};\n\nexport const entries = <T extends object>(obj: T): IterableEntry<T>[] =>\n Object.entries(obj).map(([key, value]) => [key as keyof T, value]);\n\nexport type NonPartial<T> = { [K in keyof Required<T>]: T[K] };\n","import format from 'pg-format';\nimport { entries } from '../../main/typing';\n\nexport const Operators = {\n $eq: '$eq',\n $gt: '$gt',\n $gte: '$gte',\n $lt: '$lt',\n $lte: '$lte',\n $ne: '$ne',\n $in: '$in',\n $nin: '$nin',\n $elemMatch: '$elemMatch',\n $all: '$all',\n $size: '$size',\n};\n\nconst OperatorMap = {\n $gt: '>',\n $gte: '>=',\n $lt: '<',\n $lte: '<=',\n $ne: '!=',\n};\n\nexport const isOperator = (key: string) => key.startsWith('$');\n\nexport const hasOperators = (value: Record<string, unknown>) =>\n Object.keys(value).some(isOperator);\n\nexport const handleOperator = (\n path: string,\n operator: string,\n value: unknown,\n): string => {\n if (path === '_id') {\n return handleIdOperator(operator, value);\n }\n\n switch (operator) {\n case '$eq':\n return format(\n `(data @> %L::jsonb OR jsonb_path_exists(data, '$.%s[*] ? (@ == %s)'))`,\n JSON.stringify(buildNestedObject(path, value)),\n path,\n JSON.stringify(value),\n );\n case '$gt':\n case '$gte':\n case '$lt':\n case '$lte':\n case '$ne':\n return format(\n `data #>> %L ${OperatorMap[operator]} %L`,\n `{${path.split('.').join(',')}}`,\n value,\n );\n case '$in':\n return format(\n 'data #>> %L IN (%s)',\n `{${path.split('.').join(',')}}`,\n (value as unknown[]).map((v) => format('%L', v)).join(', '),\n );\n case '$nin':\n return format(\n 'data #>> %L NOT IN (%s)',\n `{${path.split('.').join(',')}}`,\n (value as unknown[]).map((v) => format('%L', v)).join(', '),\n );\n case '$elemMatch': {\n const subQuery = entries(value as Record<string, unknown>)\n .map(([subKey, subValue]) =>\n format(`@.\"%s\" == %s`, subKey, JSON.stringify(subValue)),\n )\n .join(' && ');\n return format(\n `jsonb_path_exists(data, '$.%s[*] ? (%s)')`,\n path,\n subQuery,\n );\n }\n case '$all':\n return format(\n 'data @> %L::jsonb',\n JSON.stringify(buildNestedObject(path, value)),\n );\n case '$size':\n return format(\n 'jsonb_array_length(data #> %L) = %L',\n `{${path.split('.').join(',')}}`,\n value,\n );\n default:\n throw new Error(`Unsupported operator: ${operator}`);\n }\n};\n\nconst handleIdOperator = (operator: string, value: unknown): string => {\n switch (operator) {\n case '$eq':\n return format(`_id = %L`, value);\n case '$gt':\n case '$gte':\n case '$lt':\n case '$lte':\n case '$ne':\n return format(`_id ${OperatorMap[operator]} %L`, value);\n case '$in':\n return format(\n `_id IN (%s)`,\n (value as unknown[]).map((v) => format('%L', v)).join(', '),\n );\n case '$nin':\n return format(\n `_id NOT IN (%s)`,\n (value as unknown[]).map((v) => format('%L', v)).join(', '),\n );\n default:\n throw new Error(`Unsupported operator: ${operator}`);\n }\n};\n\nconst buildNestedObject = (\n path: string,\n value: unknown,\n): Record<string, unknown> =>\n path\n .split('.')\n .reverse()\n .reduce((acc, key) => ({ [key]: acc }), value as Record<string, unknown>);\n","import type { PongoFilter } from '../../main';\nimport { entries } from '../../main/typing';\nimport { Operators, handleOperator, hasOperators } from './queryOperators';\n\nconst AND = 'AND';\n\nexport const constructFilterQuery = <T>(filter: PongoFilter<T>): string =>\n Object.entries(filter)\n .map(([key, value]) =>\n isRecord(value)\n ? constructComplexFilterQuery(key, value)\n : handleOperator(key, '$eq', value),\n )\n .join(` ${AND} `);\n\nconst constructComplexFilterQuery = (\n key: string,\n value: Record<string, unknown>,\n): string => {\n const isEquality = !hasOperators(value);\n\n return entries(value)\n .map(\n ([nestedKey, val]) =>\n isEquality\n ? handleOperator(`${key}.${nestedKey}`, Operators.$eq, val) // regular value\n : handleOperator(key, nestedKey, val), // operator\n )\n .join(` ${AND} `);\n};\n\nconst isRecord = (value: unknown): value is Record<string, unknown> =>\n value !== null && typeof value === 'object' && !Array.isArray(value);\n","import format from 'pg-format';\n\nexport type SQL = string & { __brand: 'sql' };\n\nexport const sql = (sqlQuery: string, ...params: unknown[]): SQL => {\n return format(sqlQuery, ...params) as SQL;\n};\n","import type { $inc, $push, $set, $unset, PongoUpdate } from '../../main';\nimport { entries } from '../../main/typing';\nimport { sql, type SQL } from '../sql';\n\nexport const buildUpdateQuery = <T>(update: PongoUpdate<T>): SQL =>\n entries(update).reduce((currentUpdateQuery, [op, value]) => {\n switch (op) {\n case '$set':\n return buildSetQuery(value, currentUpdateQuery);\n case '$unset':\n return buildUnsetQuery(value, currentUpdateQuery);\n case '$inc':\n return buildIncQuery(value, currentUpdateQuery);\n case '$push':\n return buildPushQuery(value, currentUpdateQuery);\n default:\n return currentUpdateQuery;\n }\n }, sql('data'));\n\nexport const buildSetQuery = <T>(set: $set<T>, currentUpdateQuery: SQL): SQL =>\n sql(\n 'jsonb_set(%s, %L, data || %L)',\n currentUpdateQuery,\n '{}',\n JSON.stringify(set),\n );\n\nexport const buildUnsetQuery = <T>(\n unset: $unset<T>,\n currentUpdateQuery: SQL,\n): SQL => sql('%s - %L', currentUpdateQuery, Object.keys(unset).join(', '));\n\nexport const buildIncQuery = <T>(\n inc: $inc<T>,\n currentUpdateQuery: SQL,\n): SQL => {\n for (const [key, value] of Object.entries(inc)) {\n currentUpdateQuery = sql(\n \"jsonb_set(%s, '{%s}', to_jsonb((data->>'%s')::numeric + %L))\",\n currentUpdateQuery,\n key,\n key,\n value,\n );\n }\n return currentUpdateQuery;\n};\n\nexport const buildPushQuery = <T>(\n push: $push<T>,\n currentUpdateQuery: SQL,\n): SQL => {\n for (const [key, value] of Object.entries(push)) {\n currentUpdateQuery = sql(\n \"jsonb_set(%s, '{%s}', (COALESCE(data->'%s', '[]'::jsonb) || '[%s]'::jsonb))\",\n currentUpdateQuery,\n key,\n key,\n JSON.stringify(value),\n );\n }\n return currentUpdateQuery;\n};\n","import { type DbClient } from '../main';\nimport { endPool, getPool } from './pool';\nimport { postgresCollection } from './postgresCollection';\n\nexport const postgresClient = (\n connectionString: string,\n database?: string,\n): DbClient => {\n const pool = getPool({ connectionString, database });\n\n return {\n connect: () => Promise.resolve(),\n close: () => endPool(connectionString),\n collection: <T>(name: string) => postgresCollection<T>(name, pool),\n };\n};\n","import { postgresClient } from '../postgres';\nimport type { PongoCollection } from './typing/operations';\n\nexport interface DbClient {\n connect(): Promise<void>;\n close(): Promise<void>;\n collection: <T>(name: string) => PongoCollection<T>;\n}\n\nexport const getDbClient = (\n connectionString: string,\n database?: string,\n): DbClient => {\n // This is the place where in the future could come resolution of other database types\n return postgresClient(connectionString, database);\n};\n","import { getDbClient } from './dbClient';\nimport type { PongoClient, PongoDb } from './typing/operations';\n\nexport const pongoClient = (connectionString: string): PongoClient => {\n const dbClient = getDbClient(connectionString);\n\n const pongoClient: PongoClient = {\n connect: async () => {\n await dbClient.connect();\n return pongoClient;\n },\n close: () => dbClient.close(),\n db: (dbName?: string): PongoDb =>\n dbName ? getDbClient(connectionString, dbName) : dbClient,\n };\n\n return pongoClient;\n};\n","export class FindCursor<T> {\n private findDocumentsPromise: Promise<T[]>;\n private documents: T[] | null = null;\n private index: number = 0;\n\n constructor(documents: Promise<T[]>) {\n this.findDocumentsPromise = documents;\n }\n\n async toArray(): Promise<T[]> {\n return this.findDocuments();\n }\n\n async forEach(callback: (doc: T) => void): Promise<void> {\n const docs = await this.findDocuments();\n\n for (const doc of docs) {\n callback(doc);\n }\n return Promise.resolve();\n }\n\n hasNext(): boolean {\n if (this.documents === null) throw Error('Error while fetching documents');\n return this.index < this.documents.length;\n }\n\n async next(): Promise<T | null> {\n const docs = await this.findDocuments();\n return this.hasNext() ? docs[this.index++] ?? null : null;\n }\n\n private async findDocuments(): Promise<T[]> {\n this.documents = await this.findDocumentsPromise;\n return this.documents;\n }\n}\n","import { Collection as MongoCollection, type Document } from 'mongodb';\nimport type { PongoDb } from '../main';\nimport { Collection } from './mongoCollection';\n\nexport class Db {\n constructor(private pongoDb: PongoDb) {}\n\n collection<T extends Document>(collectionName: string): MongoCollection<T> {\n return new Collection<T>(this.pongoDb.collection<T>(collectionName));\n }\n}\n","import type {\n AbstractCursorOptions,\n AggregateOptions,\n AggregationCursor,\n AnyBulkWriteOperation,\n BSONSerializeOptions,\n BulkWriteOptions,\n BulkWriteResult,\n ChangeStream,\n ChangeStreamDocument,\n ChangeStreamOptions,\n CommandOperationOptions,\n CountDocumentsOptions,\n CountOptions,\n CreateIndexesOptions,\n DeleteOptions,\n DeleteResult,\n Document,\n DropCollectionOptions,\n EnhancedOmit,\n EstimatedDocumentCountOptions,\n Filter,\n FindOneAndDeleteOptions,\n FindOneAndReplaceOptions,\n FindOneAndUpdateOptions,\n FindOptions,\n Flatten,\n Hint,\n IndexDescription,\n IndexDescriptionCompact,\n IndexDescriptionInfo,\n IndexInformationOptions,\n IndexSpecification,\n InferIdType,\n InsertManyResult,\n InsertOneOptions,\n InsertOneResult,\n ListIndexesCursor,\n ListSearchIndexesCursor,\n ListSearchIndexesOptions,\n ModifyResult,\n Collection as MongoCollection,\n FindCursor as MongoFindCursor,\n OperationOptions,\n OptionalUnlessRequiredId,\n OrderedBulkOperation,\n ReadConcern,\n ReadPreference,\n RenameOptions,\n ReplaceOptions,\n SearchIndexDescription,\n UnorderedBulkOperation,\n UpdateFilter,\n UpdateOptions,\n UpdateResult,\n WithId,\n WithoutId,\n WriteConcern,\n} from 'mongodb';\nimport type { Key } from 'readline';\nimport type { PongoCollection, PongoFilter, PongoUpdate } from '../main';\nimport { FindCursor } from './findCursor';\n\nexport class Collection<T extends Document> implements MongoCollection<T> {\n private collection: PongoCollection<T>;\n\n constructor(collection: PongoCollection<T>) {\n this.collection = collection;\n }\n get dbName(): string {\n throw new Error('Method not implemented.');\n }\n get collectionName(): string {\n throw new Error('Method not implemented.');\n }\n get namespace(): string {\n throw new Error('Method not implemented.');\n }\n get readConcern(): ReadConcern | undefined {\n throw new Error('Method not implemented.');\n }\n get readPreference(): ReadPreference | undefined {\n throw new Error('Method not implemented.');\n }\n get bsonOptions(): BSONSerializeOptions {\n throw new Error('Method not implemented.');\n }\n get writeConcern(): WriteConcern | undefined {\n throw new Error('Method not implemented.');\n }\n get hint(): Hint | undefined {\n throw new Error('Method not implemented.');\n }\n set hint(v: Hint | undefined) {\n throw new Error('Method not implemented.');\n }\n async insertOne(\n doc: OptionalUnlessRequiredId<T>,\n _options?: InsertOneOptions | undefined,\n ): Promise<InsertOneResult<T>> {\n const result = await this.collection.insertOne(doc as T);\n return {\n acknowledged: result.acknowledged,\n insertedId: result.insertedId as unknown as InferIdType<T>,\n };\n }\n insertMany(\n _docs: OptionalUnlessRequiredId<T>[],\n _options?: BulkWriteOptions | undefined,\n ): Promise<InsertManyResult<T>> {\n throw new Error('Method not implemented.');\n }\n bulkWrite(\n _operations: AnyBulkWriteOperation<T>[],\n _options?: BulkWriteOptions | undefined,\n ): Promise<BulkWriteResult> {\n throw new Error('Method not implemented.');\n }\n async updateOne(\n filter: Filter<T>,\n update: Document[] | UpdateFilter<T>,\n _options?: UpdateOptions | undefined,\n ): Promise<UpdateResult<T>> {\n const result = await this.collection.updateOne(\n filter as unknown as PongoFilter<T>,\n update as unknown as PongoUpdate<T>,\n );\n\n return {\n acknowledged: result.acknowledged,\n matchedCount: result.modifiedCount,\n modifiedCount: result.modifiedCount,\n upsertedCount: result.modifiedCount,\n upsertedId: null,\n };\n }\n replaceOne(\n _filter: Filter<T>,\n _: WithoutId<T>,\n _options?: ReplaceOptions | undefined,\n ): Promise<Document | UpdateResult<T>> {\n throw new Error('Method not implemented.');\n }\n updateMany(\n _filter: Filter<T>,\n _update: Document[] | UpdateFilter<T>,\n _options?: UpdateOptions | undefined,\n ): Promise<UpdateResult<T>> {\n throw new Error('Method not implemented.');\n }\n async deleteOne(\n filter?: Filter<T> | undefined,\n _options?: DeleteOptions | undefined,\n ): Promise<DeleteResult> {\n const result = await this.collection.deleteOne(\n filter as unknown as PongoFilter<T>,\n );\n\n return {\n acknowledged: result.acknowledged,\n deletedCount: result.deletedCount,\n };\n }\n deleteMany(\n _filter?: Filter<T> | undefined,\n _options?: DeleteOptions | undefined,\n ): Promise<DeleteResult> {\n throw new Error('Method not implemented.');\n }\n rename(\n _newName: string,\n _options?: RenameOptions | undefined,\n ): Promise<Collection<Document>> {\n throw new Error('Method not implemented.');\n }\n drop(_options?: DropCollectionOptions | undefined): Promise<boolean> {\n throw new Error('Method not implemented.');\n }\n findOne(): Promise<WithId<T> | null>;\n findOne(filter: Filter<T>): Promise<WithId<T> | null>;\n findOne(\n filter: Filter<T>,\n options: FindOptions<Document>,\n ): Promise<WithId<T> | null>;\n findOne<TS = T>(): Promise<TS | null>;\n findOne<TS = T>(filter: Filter<TS>): Promise<TS | null>;\n findOne<TS = T>(\n filter: Filter<TS>,\n options?: FindOptions<Document> | undefined,\n ): Promise<TS | null>;\n async findOne(\n filter?: unknown,\n _options?: unknown,\n ): Promise<import('mongodb').WithId<T> | T | null> {\n return this.collection.findOne(filter as PongoFilter<T>);\n }\n find(): MongoFindCursor<WithId<T>>;\n find(\n filter: Filter<T>,\n options?: FindOptions<Document> | undefined,\n ): MongoFindCursor<WithId<T>>;\n find<T extends Document>(\n filter: Filter<T>,\n options?: FindOptions<Document> | undefined,\n ): MongoFindCursor<T>;\n find(\n filter?: unknown,\n _options?: unknown,\n ): MongoFindCursor<WithId<T>> | MongoFindCursor<T> {\n return new FindCursor(\n this.collection.find(filter as PongoFilter<T>),\n ) as unknown as MongoFindCursor<T>;\n }\n options(_options?: OperationOptions | undefined): Promise<Document> {\n throw new Error('Method not implemented.');\n }\n isCapped(_options?: OperationOptions | undefined): Promise<boolean> {\n throw new Error('Method not implemented.');\n }\n createIndex(\n _indexSpec: IndexSpecification,\n _options?: CreateIndexesOptions | undefined,\n ): Promise<string> {\n throw new Error('Method not implemented.');\n }\n createIndexes(\n _indexSpecs: IndexDescription[],\n _options?: CreateIndexesOptions | undefined,\n ): Promise<string[]> {\n throw new Error('Method not implemented.');\n }\n dropIndex(\n _indexName: string,\n _options?: CommandOperationOptions | undefined,\n ): Promise<Document> {\n throw new Error('Method not implemented.');\n }\n dropIndexes(\n _options?: CommandOperationOptions | undefined,\n ): Promise<boolean> {\n throw new Error('Method not implemented.');\n }\n listIndexes(_options?: AbstractCursorOptions | undefined): ListIndexesCursor {\n throw new Error('Method not implemented.');\n }\n indexExists(\n _indexes: string | string[],\n _options?: AbstractCursorOptions | undefined,\n ): Promise<boolean> {\n throw new Error('Method not implemented.');\n }\n indexInformation(\n options: IndexInformationOptions & { full: true },\n ): Promise<IndexDescriptionInfo[]>;\n indexInformation(\n options: IndexInformationOptions & { full?: false | undefined },\n ): Promise<IndexDescriptionCompact>;\n indexInformation(\n options: IndexInformationOptions,\n ): Promise<IndexDescriptionCompact | IndexDescriptionInfo[]>;\n indexInformation(): Promise<IndexDescriptionCompact>;\n indexInformation(\n _options?: unknown,\n ):\n | Promise<import('mongodb').IndexDescriptionInfo[]>\n | Promise<import('mongodb').IndexDescriptionCompact>\n | Promise<\n | import('mongodb').IndexDescriptionCompact\n | import('mongodb').IndexDescriptionInfo[]\n > {\n throw new Error('Method not implemented.');\n }\n estimatedDocumentCount(\n _options?: EstimatedDocumentCountOptions | undefined,\n ): Promise<number> {\n throw new Error('Method not implemented.');\n }\n countDocuments(\n _filter?: Filter<T> | undefined,\n _options?: CountDocumentsOptions | undefined,\n ): Promise<number> {\n throw new Error('Method not implemented.');\n }\n distinct<Key extends '_id' | keyof EnhancedOmit<T, '_id'>>(\n key: Key,\n ): Promise<Flatten<WithId<T>[Key]>[]>;\n distinct<Key extends '_id' | keyof EnhancedOmit<T, '_id'>>(\n key: Key,\n filter: Filter<T>,\n ): Promise<Flatten<WithId<T>[Key]>[]>;\n distinct<Key extends '_id' | keyof EnhancedOmit<T, '_id'>>(\n key: Key,\n filter: Filter<T>,\n options: CommandOperationOptions,\n ): Promise<Flatten<WithId<T>[Key]>[]>;\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n distinct(key: string): Promise<any[]>;\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n distinct(key: string, filter: Filter<T>): Promise<any[]>;\n distinct(\n key: string,\n filter: Filter<T>,\n options: CommandOperationOptions, // eslint-disable-next-line @typescript-eslint/no-explicit-any\n ): Promise<any[]>;\n distinct(\n _key: unknown,\n _filter?: unknown,\n _options?: unknown,\n ): // eslint-disable-next-line @typescript-eslint/no-explicit-any\n | Promise<any[]>\n | Promise<import('mongodb').Flatten<import('mongodb').WithId<T>[Key]>[]> {\n throw new Error('Method not implemented.');\n }\n indexes(\n options: IndexInformationOptions & { full?: true | undefined },\n ): Promise<IndexDescriptionInfo[]>;\n indexes(\n options: IndexInformationOptions & { full: false },\n ): Promise<IndexDescriptionCompact>;\n indexes(\n options: IndexInformationOptions,\n ): Promise<IndexDescriptionCompact | IndexDescriptionInfo[]>;\n indexes(\n options?: AbstractCursorOptions | undefined,\n ): Promise<IndexDescriptionInfo[]>;\n indexes(\n _options?: unknown,\n ):\n | Promise<import('mongodb').IndexDescriptionInfo[]>\n | Promise<import('mongodb').IndexDescriptionCompact>\n | Promise<\n | import('mongodb').IndexDescriptionCompact\n | import('mongodb').IndexDescriptionInfo[]\n > {\n throw new Error('Method not implemented.');\n }\n findOneAndDelete(\n filter: Filter<T>,\n options: FindOneAndDeleteOptions & { includeResultMetadata: true },\n ): Promise<ModifyResult<T>>;\n findOneAndDelete(\n filter: Filter<T>,\n options: FindOneAndDeleteOptions & { includeResultMetadata: false },\n ): Promise<WithId<T> | null>;\n findOneAndDelete(\n filter: Filter<T>,\n options: FindOneAndDeleteOptions,\n ): Promise<WithId<T> | null>;\n findOneAndDelete(filter: Filter<T>): Promise<WithId<T> | null>;\n findOneAndDelete(\n _filter: unknown,\n _options?: unknown,\n ):\n | Promise<import('mongodb').WithId<T> | null>\n | Promise<import('mongodb').ModifyResult<T>> {\n throw new Error('Method not implemented.');\n }\n findOneAndReplace(\n filter: Filter<T>,\n replacement: WithoutId<T>,\n options: FindOneAndReplaceOptions & { includeResultMetadata: true },\n ): Promise<ModifyResult<T>>;\n findOneAndReplace(\n filter: Filter<T>,\n replacement: WithoutId<T>,\n options: FindOneAndReplaceOptions & { includeResultMetadata: false },\n ): Promise<WithId<T> | null>;\n findOneAndReplace(\n filter: Filter<T>,\n replacement: WithoutId<T>,\n options: FindOneAndReplaceOptions,\n ): Promise<WithId<T> | null>;\n findOneAndReplace(\n filter: Filter<T>,\n replacement: WithoutId<T>,\n ): Promise<WithId<T> | null>;\n findOneAndReplace(\n _filter: unknown,\n _replacement: unknown,\n _options?: unknown,\n ):\n | Promise<import('mongodb').WithId<T> | null>\n | Promise<import('mongodb').ModifyResult<T>> {\n throw new Error('Method not implemented.');\n }\n findOneAndUpdate(\n filter: Filter<T>,\n update: UpdateFilter<T>,\n options: FindOneAndUpdateOptions & { includeResultMetadata: true },\n ): Promise<ModifyResult<T>>;\n findOneAndUpdate(\n filter: Filter<T>,\n update: UpdateFilter<T>,\n options: FindOneAndUpdateOptions & { includeResultMetadata: false },\n ): Promise<WithId<T> | null>;\n findOneAndUpdate(\n filter: Filter<T>,\n update: UpdateFilter<T>,\n options: FindOneAndUpdateOptions,\n ): Promise<WithId<T> | null>;\n findOneAndUpdate(\n filter: Filter<T>,\n update: UpdateFilter<T>,\n ): Promise<WithId<T> | null>;\n findOneAndUpdate(\n _filter: unknown,\n _update: unknown,\n _options?: unknown,\n ):\n | Promise<import('mongodb').WithId<T> | null>\n | Promise<import('mongodb').ModifyResult<T>> {\n throw new Error('Method not implemented.');\n }\n aggregate<T extends Document = Document>(\n _pipeline?: Document[] | undefined,\n _options?: AggregateOptions | undefined,\n ): AggregationCursor<T> {\n throw new Error('Method not implemented.');\n }\n watch<\n TLocal extends Document = T,\n TChange extends Document = ChangeStreamDocument<TLocal>,\n >(\n _pipeline?: Document[] | undefined,\n _options?: ChangeStreamOptions | undefined,\n ): ChangeStream<TLocal, TChange> {\n throw new Error('Method not implemented.');\n }\n initializeUnorderedBulkOp(\n _options?: BulkWriteOptions | undefined,\n ): UnorderedBulkOperation {\n throw new Error('Method not implemented.');\n }\n initializeOrderedBulkOp(\n _options?: BulkWriteOptions | undefined,\n ): OrderedBulkOperation {\n throw new Error('Method not implemented.');\n }\n count(\n _filter?: Filter<T> | undefined,\n _options?: CountOptions | undefined,\n ): Promise<number> {\n throw new Error('Method not implemented.');\n }\n listSearchIndexes(\n options?: ListSearchIndexesOptions | undefined,\n ): ListSearchIndexesCursor;\n listSearchIndexes(\n name: string,\n options?: ListSearchIndexesOptions | undefined,\n ): ListSearchIndexesCursor;\n listSearchIndexes(\n _name?: unknown,\n _options?: unknown,\n ): import('mongodb').ListSearchIndexesCursor {\n throw new Error('Method not implemented.');\n }\n createSearchIndex(_description: SearchIndexDescription): Promise<string> {\n throw new Error('Method not implemented.');\n }\n createSearchIndexes(\n _descriptions: SearchIndexDescription[],\n ): Promise<string[]> {\n throw new Error('Method not implemented.');\n }\n dropSearchIndex(_name: string): Promise<void> {\n throw new Error('Method not implemented.');\n }\n updateSearchIndex(_name: string, _definition: Document): Promise<void> {\n throw new Error('Method not implemented.');\n }\n\n async createCollection(): Promise<void> {\n await this.collection.createCollection();\n }\n}\n","// src/MongoClientShim.ts\nimport { pongoClient, type PongoClient } from '../main';\nimport { Db } from './mongoDb';\n\nexport class MongoClient {\n private pongoClient: PongoClient;\n\n constructor(connectionString: string) {\n this.pongoClient = pongoClient(connectionString);\n }\n\n async connect() {\n await this.pongoClient.connect();\n return this;\n }\n\n async close() {\n await this.pongoClient.close();\n }\n\n db(dbName: string): Db {\n return new Db(this.pongoClient.db(dbName));\n }\n}\n"],"mappings":"AAAA,OAAOA,MAAQ,KAEf,IAAMC,EAA8B,IAAI,IAE3BC,EACXC,GACY,CACZ,IAAMC,EACJ,OAAOD,GAA8B,SACjCA,EACAA,EAA0B,iBAE1BE,EACJ,OAAOF,GAA8B,SACjC,CAAE,iBAAAC,CAAiB,EACnBD,EAGN,OACEF,EAAM,IAAIG,CAAgB,GAC1BH,EAAM,IAAIG,EAAkB,IAAIJ,EAAG,KAAKK,CAAW,CAAC,EAAE,IAAID,CAAgB,CAE9E,EAEaE,EAAU,MAAOF,GAA4C,CACxE,IAAMG,EAAON,EAAM,IAAIG,CAAgB,EACnCG,IACF,MAAMA,EAAK,IA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ACEiB,EACAjB,EACsB,CACtB,MAAM,IAAI,MAAM,yBAAyB,CAC3C,CACA,MAIEiB,EACAjB,EAC+B,CAC/B,MAAM,IAAI,MAAM,yBAAyB,CAC3C,CACA,0BACEA,EACwB,CACxB,MAAM,IAAI,MAAM,yBAAyB,CAC3C,CACA,wBACEA,EACsB,CACtB,MAAM,IAAI,MAAM,yBAAyB,CAC3C,CACA,MACEM,EACAN,EACiB,CACjB,MAAM,IAAI,MAAM,yBAAyB,CAC3C,CAQA,kBACEkB,EACAlB,EAC2C,CAC3C,MAAM,IAAI,MAAM,yBAAyB,CAC3C,CACA,kBAAkBmB,EAAuD,CACvE,MAAM,IAAI,MAAM,yBAAyB,CAC3C,CACA,oBACEC,EACmB,CACnB,MAAM,IAAI,MAAM,yBAAyB,CAC3C,CACA,gBAAgBF,EAA8B,CAC5C,MAAM,IAAI,MAAM,yBAAyB,CAC3C,CACA,kBAAkBA,EAAeG,EAAsC,CACrE,MAAM,IAAI,MAAM,yBAAyB,CAC3C,CAEA,MAAM,kBAAkC,CACtC,MAAM,KAAK,WAAW,iBAAiB,CACzC,CACF,EDvdO,IAAMC,EAAN,KAAS,CACd,YAAoBC,EAAkB,CAAlB,aAAAA,CAAmB,CAEvC,WAA+BC,EAA4C,CACzE,OAAO,IAAIC,EAAc,KAAK,QAAQ,WAAcD,CAAc,CAAC,CACrE,CACF,EENO,IAAME,EAAN,KAAkB,CACf,YAER,YAAYC,EAA0B,CACpC,KAAK,YAAcC,EAAYD,CAAgB,CACjD,CAEA,MAAM,SAAU,CACd,aAAM,KAAK,YAAY,QAAQ,EACxB,IACT,CAEA,MAAM,OAAQ,CACZ,MAAM,KAAK,YAAY,MAAM,CAC/B,CAEA,GAAGE,EAAoB,CACrB,OAAO,IAAIC,EAAG,KAAK,YAAY,GAAGD,CAAM,CAAC,CAC3C,CACF","names":["pg","pools","getPool","connectionStringOrOptions","connectionString","poolOptions","endPool","pool","endAllPools","uuid","execute","pool","handle","client","executeSQL","sql","entries","obj","key","value","format","Operators","OperatorMap","isOperator","key","hasOperators","value","handleOperator","path","operator","handleIdOperator","format","buildNestedObject","v","subQuery","entries","subKey","subValue","acc","AND","constructFilterQuery","filter","key","value","isRecord","constructComplexFilterQuery","handleOperator","isEquality","hasOperators","entries","nestedKey","val","Operators","format","sql","sqlQuery","params","buildUpdateQuery","update","entries","currentUpdateQuery","op","value","buildSetQuery","buildUnsetQuery","buildIncQuery","buildPushQuery","sql","set","unset","inc","key","push","postgresCollection","collectionName","pool","execute","sql","executeSQL","SqlFor","collectionSQLBuilder","createCollection","document","id","uuid","filter","update","result","row","filterQuery","constructFilterQuery","updateQuery","buildUpdateQuery","postgresClient","connectionString","database","pool","getPool","endPool","name","postgresCollection","getDbClient","connectionString","database","postgresClient","pongoClient","connectionString","dbClient","getDbClient","dbName","FindCursor","documents","callback","docs","doc","Collection","collection","v","doc","_options","result","_docs","_operations","filter","update","_filter","_","_update","_newName","FindCursor","_indexSpec","_indexSpecs","_indexName","_indexes","_key","_replacement","_pipeline","_name","_description","_descriptions","_definition","Db","pongoDb","collectionName","Collection","MongoClient","connectionString","pongoClient","dbName","Db"]}
1
+ {"version":3,"sources":["../src/postgres/pool.ts","../src/postgres/postgresCollection.ts","../src/postgres/execute/index.ts","../src/main/typing/entries.ts","../src/postgres/filter/queryOperators.ts","../src/postgres/filter/index.ts","../src/postgres/sql/index.ts","../src/postgres/update/index.ts","../src/postgres/client.ts","../src/main/dbClient.ts","../src/main/client.ts","../src/mongo/findCursor.ts","../src/mongo/mongoDb.ts","../src/mongo/mongoCollection.ts","../src/mongo/mongoClient.ts"],"sourcesContent":["import pg from 'pg';\n\nconst pools: Map<string, pg.Pool> = new Map();\n\nexport const getPool = (\n connectionStringOrOptions: string | pg.PoolConfig,\n): pg.Pool => {\n const connectionString =\n typeof connectionStringOrOptions === 'string'\n ? connectionStringOrOptions\n : connectionStringOrOptions.connectionString!;\n\n const poolOptions =\n typeof connectionStringOrOptions === 'string'\n ? { connectionString }\n : connectionStringOrOptions;\n\n //TODO: this should include database name resolution for key\n return (\n pools.get(connectionString) ??\n pools.set(connectionString, new pg.Pool(poolOptions)).get(connectionString)!\n );\n};\n\nexport const endPool = async (connectionString: string): Promise<void> => {\n const pool = pools.get(connectionString);\n if (pool) {\n await pool.end();\n pools.delete(connectionString);\n }\n};\n\nexport const endAllPools = () =>\n Promise.all(\n [...pools.keys()].map((connectionString) => endPool(connectionString)),\n );\n","import pg from 'pg';\nimport format from 'pg-format';\nimport { v4 as uuid } from 'uuid';\nimport {\n type PongoCollection,\n type PongoDeleteResult,\n type PongoFilter,\n type PongoInsertManyResult,\n type PongoInsertOneResult,\n type PongoUpdate,\n type PongoUpdateResult,\n type WithId,\n} from '../main';\nimport { executeSQL } from './execute';\nimport { constructFilterQuery } from './filter';\nimport { sql, type SQL } from './sql';\nimport { buildUpdateQuery } from './update';\n\nexport const postgresCollection = <T>(\n collectionName: string,\n pool: pg.Pool,\n): PongoCollection<T> => {\n const execute = (sql: SQL) => executeSQL(pool, sql);\n const SqlFor = collectionSQLBuilder(collectionName);\n\n const createCollection = execute(SqlFor.createCollection());\n\n return {\n createCollection: async () => {\n await createCollection;\n },\n insertOne: async (document: T): Promise<PongoInsertOneResult> => {\n await createCollection;\n\n const _id = uuid();\n\n const result = await execute(SqlFor.insertOne({ _id, ...document }));\n\n return result.rowCount\n ? { insertedId: _id, acknowledged: true }\n : { insertedId: null, acknowledged: false };\n },\n insertMany: async (documents: T[]): Promise<PongoInsertManyResult> => {\n await createCollection;\n\n const rows = documents.map((doc) => ({\n _id: uuid(),\n ...doc,\n }));\n\n const result = await execute(SqlFor.insertMany(rows));\n\n return {\n acknowledged: result.rowCount === rows.length,\n insertedCount: result.rowCount ?? 0,\n insertedIds: rows.map((d) => d._id),\n };\n },\n updateOne: async (\n filter: PongoFilter<T>,\n update: PongoUpdate<T>,\n ): Promise<PongoUpdateResult> => {\n await createCollection;\n\n const result = await execute(SqlFor.updateOne(filter, update));\n return result.rowCount\n ? { acknowledged: true, modifiedCount: result.rowCount }\n : { acknowledged: false, modifiedCount: 0 };\n },\n updateMany: async (\n filter: PongoFilter<T>,\n update: PongoUpdate<T>,\n ): Promise<PongoUpdateResult> => {\n await createCollection;\n\n const result = await execute(SqlFor.updateMany(filter, update));\n return result.rowCount\n ? { acknowledged: true, modifiedCount: result.rowCount }\n : { acknowledged: false, modifiedCount: 0 };\n },\n deleteOne: async (filter: PongoFilter<T>): Promise<PongoDeleteResult> => {\n await createCollection;\n\n const result = await execute(SqlFor.deleteOne(filter));\n return result.rowCount\n ? { acknowledged: true, deletedCount: result.rowCount }\n : { acknowledged: false, deletedCount: 0 };\n },\n deleteMany: async (filter: PongoFilter<T>): Promise<PongoDeleteResult> => {\n await createCollection;\n\n const result = await execute(SqlFor.deleteMany(filter));\n return result.rowCount\n ? { acknowledged: true, deletedCount: result.rowCount }\n : { acknowledged: false, deletedCount: 0 };\n },\n findOne: async (filter: PongoFilter<T>): Promise<T | null> => {\n await createCollection;\n\n const result = await execute(SqlFor.findOne(filter));\n return (result.rows[0]?.data ?? null) as T | null;\n },\n find: async (filter: PongoFilter<T>): Promise<T[]> => {\n await createCollection;\n\n const result = await execute(SqlFor.find(filter));\n return result.rows.map((row) => row.data as T);\n },\n };\n};\n\nexport const collectionSQLBuilder = (collectionName: string) => ({\n createCollection: (): SQL =>\n sql(\n 'CREATE TABLE IF NOT EXISTS %I (_id UUID PRIMARY KEY, data JSONB)',\n collectionName,\n ),\n insertOne: <T>(document: WithId<T>): SQL =>\n sql(\n 'INSERT INTO %I (_id, data) VALUES (%L, %L)',\n collectionName,\n document._id,\n JSON.stringify(document),\n ),\n insertMany: <T>(documents: WithId<T>[]): SQL => {\n const values = documents\n .map((doc) => format('(%L, %L)', doc._id, JSON.stringify(doc)))\n .join(', ');\n return sql('INSERT INTO %I (_id, data) VALUES %s', collectionName, values);\n },\n updateOne: <T>(filter: PongoFilter<T>, update: PongoUpdate<T>): SQL => {\n const filterQuery = constructFilterQuery(filter);\n const updateQuery = buildUpdateQuery(update);\n\n return sql(\n `WITH cte AS (\n SELECT _id FROM %I WHERE %s LIMIT 1\n )\n UPDATE %I SET data = %s FROM cte WHERE %I._id = cte._id`,\n collectionName,\n filterQuery,\n collectionName,\n updateQuery,\n collectionName,\n );\n },\n updateMany: <T>(filter: PongoFilter<T>, update: PongoUpdate<T>): SQL => {\n const filterQuery = constructFilterQuery(filter);\n const updateQuery = buildUpdateQuery(update);\n\n return sql(\n 'UPDATE %I SET data = %s WHERE %s',\n collectionName,\n updateQuery,\n filterQuery,\n );\n },\n deleteOne: <T>(filter: PongoFilter<T>): SQL => {\n const filterQuery = constructFilterQuery(filter);\n return sql('DELETE FROM %I WHERE %s', collectionName, filterQuery);\n },\n deleteMany: <T>(filter: PongoFilter<T>): SQL => {\n const filterQuery = constructFilterQuery(filter);\n return sql('DELETE FROM %I WHERE %s', collectionName, filterQuery);\n },\n findOne: <T>(filter: PongoFilter<T>): SQL => {\n const filterQuery = constructFilterQuery(filter);\n return sql(\n 'SELECT data FROM %I WHERE %s LIMIT 1',\n collectionName,\n filterQuery,\n );\n },\n find: <T>(filter: PongoFilter<T>): SQL => {\n const filterQuery = constructFilterQuery(filter);\n return sql('SELECT data FROM %I WHERE %s', collectionName, filterQuery);\n },\n});\n","import type pg from 'pg';\nimport type { SQL } from '../sql';\n\nexport const execute = async <Result = void>(\n pool: pg.Pool,\n handle: (client: pg.PoolClient) => Promise<Result>,\n) => {\n const client = await pool.connect();\n try {\n return await handle(client);\n } finally {\n client.release();\n }\n};\n\nexport const executeSQL = async <\n Result extends pg.QueryResultRow = pg.QueryResultRow,\n>(\n pool: pg.Pool,\n sql: SQL,\n): Promise<pg.QueryResult<Result>> =>\n execute(pool, (client) => client.query<Result>(sql));\n","type Entry<T> = {\n [K in keyof Required<T>]: [K, Required<T>[K]];\n}[keyof Required<T>];\n\ntype IterableEntry<T> = Entry<T> & {\n [Symbol.iterator](): Iterator<Entry<T>>;\n};\n\nexport const entries = <T extends object>(obj: T): IterableEntry<T>[] =>\n Object.entries(obj).map(([key, value]) => [key as keyof T, value]);\n\nexport type NonPartial<T> = { [K in keyof Required<T>]: T[K] };\n","import format from 'pg-format';\nimport { entries } from '../../main/typing';\n\nexport const Operators = {\n $eq: '$eq',\n $gt: '$gt',\n $gte: '$gte',\n $lt: '$lt',\n $lte: '$lte',\n $ne: '$ne',\n $in: '$in',\n $nin: '$nin',\n $elemMatch: '$elemMatch',\n $all: '$all',\n $size: '$size',\n};\n\nconst OperatorMap = {\n $gt: '>',\n $gte: '>=',\n $lt: '<',\n $lte: '<=',\n $ne: '!=',\n};\n\nexport const isOperator = (key: string) => key.startsWith('$');\n\nexport const hasOperators = (value: Record<string, unknown>) =>\n Object.keys(value).some(isOperator);\n\nexport const handleOperator = (\n path: string,\n operator: string,\n value: unknown,\n): string => {\n if (path === '_id') {\n return handleIdOperator(operator, value);\n }\n\n switch (operator) {\n case '$eq':\n return format(\n `(data @> %L::jsonb OR jsonb_path_exists(data, '$.%s[*] ? (@ == %s)'))`,\n JSON.stringify(buildNestedObject(path, value)),\n path,\n JSON.stringify(value),\n );\n case '$gt':\n case '$gte':\n case '$lt':\n case '$lte':\n case '$ne':\n return format(\n `data #>> %L ${OperatorMap[operator]} %L`,\n `{${path.split('.').join(',')}}`,\n value,\n );\n case '$in':\n return format(\n 'data #>> %L IN (%s)',\n `{${path.split('.').join(',')}}`,\n (value as unknown[]).map((v) => format('%L', v)).join(', '),\n );\n case '$nin':\n return format(\n 'data #>> %L NOT IN (%s)',\n `{${path.split('.').join(',')}}`,\n (value as unknown[]).map((v) => format('%L', v)).join(', '),\n );\n case '$elemMatch': {\n const subQuery = entries(value as Record<string, unknown>)\n .map(([subKey, subValue]) =>\n format(`@.\"%s\" == %s`, subKey, JSON.stringify(subValue)),\n )\n .join(' && ');\n return format(\n `jsonb_path_exists(data, '$.%s[*] ? (%s)')`,\n path,\n subQuery,\n );\n }\n case '$all':\n return format(\n 'data @> %L::jsonb',\n JSON.stringify(buildNestedObject(path, value)),\n );\n case '$size':\n return format(\n 'jsonb_array_length(data #> %L) = %L',\n `{${path.split('.').join(',')}}`,\n value,\n );\n default:\n throw new Error(`Unsupported operator: ${operator}`);\n }\n};\n\nconst handleIdOperator = (operator: string, value: unknown): string => {\n switch (operator) {\n case '$eq':\n return format(`_id = %L`, value);\n case '$gt':\n case '$gte':\n case '$lt':\n case '$lte':\n case '$ne':\n return format(`_id ${OperatorMap[operator]} %L`, value);\n case '$in':\n return format(\n `_id IN (%s)`,\n (value as unknown[]).map((v) => format('%L', v)).join(', '),\n );\n case '$nin':\n return format(\n `_id NOT IN (%s)`,\n (value as unknown[]).map((v) => format('%L', v)).join(', '),\n );\n default:\n throw new Error(`Unsupported operator: ${operator}`);\n }\n};\n\nconst buildNestedObject = (\n path: string,\n value: unknown,\n): Record<string, unknown> =>\n path\n .split('.')\n .reverse()\n .reduce((acc, key) => ({ [key]: acc }), value as Record<string, unknown>);\n","import type { PongoFilter } from '../../main';\nimport { entries } from '../../main/typing';\nimport { Operators, handleOperator, hasOperators } from './queryOperators';\n\nconst AND = 'AND';\n\nexport const constructFilterQuery = <T>(filter: PongoFilter<T>): string =>\n Object.entries(filter)\n .map(([key, value]) =>\n isRecord(value)\n ? constructComplexFilterQuery(key, value)\n : handleOperator(key, '$eq', value),\n )\n .join(` ${AND} `);\n\nconst constructComplexFilterQuery = (\n key: string,\n value: Record<string, unknown>,\n): string => {\n const isEquality = !hasOperators(value);\n\n return entries(value)\n .map(\n ([nestedKey, val]) =>\n isEquality\n ? handleOperator(`${key}.${nestedKey}`, Operators.$eq, val) // regular value\n : handleOperator(key, nestedKey, val), // operator\n )\n .join(` ${AND} `);\n};\n\nconst isRecord = (value: unknown): value is Record<string, unknown> =>\n value !== null && typeof value === 'object' && !Array.isArray(value);\n","import format from 'pg-format';\n\nexport type SQL = string & { __brand: 'sql' };\n\nexport const sql = (sqlQuery: string, ...params: unknown[]): SQL => {\n return format(sqlQuery, ...params) as SQL;\n};\n","import type { $inc, $push, $set, $unset, PongoUpdate } from '../../main';\nimport { entries } from '../../main/typing';\nimport { sql, type SQL } from '../sql';\n\nexport const buildUpdateQuery = <T>(update: PongoUpdate<T>): SQL =>\n entries(update).reduce((currentUpdateQuery, [op, value]) => {\n switch (op) {\n case '$set':\n return buildSetQuery(value, currentUpdateQuery);\n case '$unset':\n return buildUnsetQuery(value, currentUpdateQuery);\n case '$inc':\n return buildIncQuery(value, currentUpdateQuery);\n case '$push':\n return buildPushQuery(value, currentUpdateQuery);\n default:\n return currentUpdateQuery;\n }\n }, sql('data'));\n\nexport const buildSetQuery = <T>(set: $set<T>, currentUpdateQuery: SQL): SQL =>\n sql(\n 'jsonb_set(%s, %L, data || %L)',\n currentUpdateQuery,\n '{}',\n JSON.stringify(set),\n );\n\nexport const buildUnsetQuery = <T>(\n unset: $unset<T>,\n currentUpdateQuery: SQL,\n): SQL => sql('%s - %L', currentUpdateQuery, Object.keys(unset).join(', '));\n\nexport const buildIncQuery = <T>(\n inc: $inc<T>,\n currentUpdateQuery: SQL,\n): SQL => {\n for (const [key, value] of Object.entries(inc)) {\n currentUpdateQuery = sql(\n \"jsonb_set(%s, '{%s}', to_jsonb((data->>'%s')::numeric + %L))\",\n currentUpdateQuery,\n key,\n key,\n value,\n );\n }\n return currentUpdateQuery;\n};\n\nexport const buildPushQuery = <T>(\n push: $push<T>,\n currentUpdateQuery: SQL,\n): SQL => {\n for (const [key, value] of Object.entries(push)) {\n currentUpdateQuery = sql(\n \"jsonb_set(%s, '{%s}', (COALESCE(data->'%s', '[]'::jsonb) || '[%s]'::jsonb))\",\n currentUpdateQuery,\n key,\n key,\n JSON.stringify(value),\n );\n }\n return currentUpdateQuery;\n};\n","import { type DbClient } from '../main';\nimport { endPool, getPool } from './pool';\nimport { postgresCollection } from './postgresCollection';\n\nexport const postgresClient = (\n connectionString: string,\n database?: string,\n): DbClient => {\n const pool = getPool({ connectionString, database });\n\n return {\n connect: () => Promise.resolve(),\n close: () => endPool(connectionString),\n collection: <T>(name: string) => postgresCollection<T>(name, pool),\n };\n};\n","import { postgresClient } from '../postgres';\nimport type { PongoCollection } from './typing/operations';\n\nexport interface DbClient {\n connect(): Promise<void>;\n close(): Promise<void>;\n collection: <T>(name: string) => PongoCollection<T>;\n}\n\nexport const getDbClient = (\n connectionString: string,\n database?: string,\n): DbClient => {\n // This is the place where in the future could come resolution of other database types\n return postgresClient(connectionString, database);\n};\n","import { getDbClient } from './dbClient';\nimport type { PongoClient, PongoDb } from './typing/operations';\n\nexport const pongoClient = (connectionString: string): PongoClient => {\n const dbClient = getDbClient(connectionString);\n\n const pongoClient: PongoClient = {\n connect: async () => {\n await dbClient.connect();\n return pongoClient;\n },\n close: () => dbClient.close(),\n db: (dbName?: string): PongoDb =>\n dbName ? getDbClient(connectionString, dbName) : dbClient,\n };\n\n return pongoClient;\n};\n","export class FindCursor<T> {\n private findDocumentsPromise: Promise<T[]>;\n private documents: T[] | null = null;\n private index: number = 0;\n\n constructor(documents: Promise<T[]>) {\n this.findDocumentsPromise = documents;\n }\n\n async toArray(): Promise<T[]> {\n return this.findDocuments();\n }\n\n async forEach(callback: (doc: T) => void): Promise<void> {\n const docs = await this.findDocuments();\n\n for (const doc of docs) {\n callback(doc);\n }\n return Promise.resolve();\n }\n\n hasNext(): boolean {\n if (this.documents === null) throw Error('Error while fetching documents');\n return this.index < this.documents.length;\n }\n\n async next(): Promise<T | null> {\n const docs = await this.findDocuments();\n return this.hasNext() ? docs[this.index++] ?? null : null;\n }\n\n private async findDocuments(): Promise<T[]> {\n this.documents = await this.findDocumentsPromise;\n return this.documents;\n }\n}\n","import { Collection as MongoCollection, type Document } from 'mongodb';\nimport type { PongoDb } from '../main';\nimport { Collection } from './mongoCollection';\n\nexport class Db {\n constructor(private pongoDb: PongoDb) {}\n\n collection<T extends Document>(collectionName: string): MongoCollection<T> {\n return new Collection<T>(this.pongoDb.collection<T>(collectionName));\n }\n}\n","import type {\n AbstractCursorOptions,\n AggregateOptions,\n AggregationCursor,\n AnyBulkWriteOperation,\n BSONSerializeOptions,\n BulkWriteOptions,\n BulkWriteResult,\n ChangeStream,\n ChangeStreamDocument,\n ChangeStreamOptions,\n CommandOperationOptions,\n CountDocumentsOptions,\n CountOptions,\n CreateIndexesOptions,\n DeleteOptions,\n DeleteResult,\n Document,\n DropCollectionOptions,\n EnhancedOmit,\n EstimatedDocumentCountOptions,\n Filter,\n FindOneAndDeleteOptions,\n FindOneAndReplaceOptions,\n FindOneAndUpdateOptions,\n FindOptions,\n Flatten,\n Hint,\n IndexDescription,\n IndexDescriptionCompact,\n IndexDescriptionInfo,\n IndexInformationOptions,\n IndexSpecification,\n InferIdType,\n InsertManyResult,\n InsertOneOptions,\n InsertOneResult,\n ListIndexesCursor,\n ListSearchIndexesCursor,\n ListSearchIndexesOptions,\n ModifyResult,\n Collection as MongoCollection,\n FindCursor as MongoFindCursor,\n OperationOptions,\n OptionalUnlessRequiredId,\n OrderedBulkOperation,\n ReadConcern,\n ReadPreference,\n RenameOptions,\n ReplaceOptions,\n SearchIndexDescription,\n UnorderedBulkOperation,\n UpdateFilter,\n UpdateOptions,\n UpdateResult,\n WithId,\n WithoutId,\n WriteConcern,\n} from 'mongodb';\nimport type { Key } from 'readline';\nimport type { PongoCollection, PongoFilter, PongoUpdate } from '../main';\nimport { FindCursor } from './findCursor';\n\nexport class Collection<T extends Document> implements MongoCollection<T> {\n private collection: PongoCollection<T>;\n\n constructor(collection: PongoCollection<T>) {\n this.collection = collection;\n }\n get dbName(): string {\n throw new Error('Method not implemented.');\n }\n get collectionName(): string {\n throw new Error('Method not implemented.');\n }\n get namespace(): string {\n throw new Error('Method not implemented.');\n }\n get readConcern(): ReadConcern | undefined {\n throw new Error('Method not implemented.');\n }\n get readPreference(): ReadPreference | undefined {\n throw new Error('Method not implemented.');\n }\n get bsonOptions(): BSONSerializeOptions {\n throw new Error('Method not implemented.');\n }\n get writeConcern(): WriteConcern | undefined {\n throw new Error('Method not implemented.');\n }\n get hint(): Hint | undefined {\n throw new Error('Method not implemented.');\n }\n set hint(v: Hint | undefined) {\n throw new Error('Method not implemented.');\n }\n async insertOne(\n doc: OptionalUnlessRequiredId<T>,\n _options?: InsertOneOptions | undefined,\n ): Promise<InsertOneResult<T>> {\n const result = await this.collection.insertOne(doc as T);\n return {\n acknowledged: result.acknowledged,\n insertedId: result.insertedId as unknown as InferIdType<T>,\n };\n }\n async insertMany(\n docs: OptionalUnlessRequiredId<T>[],\n _options?: BulkWriteOptions | undefined,\n ): Promise<InsertManyResult<T>> {\n const result = await this.collection.insertMany(docs as T[]);\n return {\n acknowledged: result.acknowledged,\n insertedIds: result.insertedIds as unknown as InferIdType<T>[],\n insertedCount: result.insertedCount,\n };\n }\n bulkWrite(\n _operations: AnyBulkWriteOperation<T>[],\n _options?: BulkWriteOptions | undefined,\n ): Promise<BulkWriteResult> {\n throw new Error('Method not implemented.');\n }\n async updateOne(\n filter: Filter<T>,\n update: Document[] | UpdateFilter<T>,\n _options?: UpdateOptions | undefined,\n ): Promise<UpdateResult<T>> {\n const result = await this.collection.updateOne(\n filter as unknown as PongoFilter<T>,\n update as unknown as PongoUpdate<T>,\n );\n\n return {\n acknowledged: result.acknowledged,\n matchedCount: result.modifiedCount,\n modifiedCount: result.modifiedCount,\n upsertedCount: result.modifiedCount,\n upsertedId: null,\n };\n }\n replaceOne(\n _filter: Filter<T>,\n _: WithoutId<T>,\n _options?: ReplaceOptions | undefined,\n ): Promise<Document | UpdateResult<T>> {\n throw new Error('Method not implemented.');\n }\n async updateMany(\n filter: Filter<T>,\n update: Document[] | UpdateFilter<T>,\n _options?: UpdateOptions | undefined,\n ): Promise<UpdateResult<T>> {\n const result = await this.collection.updateMany(\n filter as unknown as PongoFilter<T>,\n update as unknown as PongoUpdate<T>,\n );\n\n return {\n acknowledged: result.acknowledged,\n matchedCount: result.modifiedCount,\n modifiedCount: result.modifiedCount,\n upsertedCount: result.modifiedCount,\n upsertedId: null,\n };\n }\n async deleteOne(\n filter?: Filter<T> | undefined,\n _options?: DeleteOptions | undefined,\n ): Promise<DeleteResult> {\n const result = await this.collection.deleteOne(\n filter as unknown as PongoFilter<T>,\n );\n\n return {\n acknowledged: result.acknowledged,\n deletedCount: result.deletedCount,\n };\n }\n async deleteMany(\n filter?: Filter<T> | undefined,\n _options?: DeleteOptions | undefined,\n ): Promise<DeleteResult> {\n const result = await this.collection.deleteMany(\n filter as unknown as PongoFilter<T>,\n );\n\n return {\n acknowledged: result.acknowledged,\n deletedCount: result.deletedCount,\n };\n }\n rename(\n _newName: string,\n _options?: RenameOptions | undefined,\n ): Promise<Collection<Document>> {\n throw new Error('Method not implemented.');\n }\n drop(_options?: DropCollectionOptions | undefined): Promise<boolean> {\n throw new Error('Method not implemented.');\n }\n findOne(): Promise<WithId<T> | null>;\n findOne(filter: Filter<T>): Promise<WithId<T> | null>;\n findOne(\n filter: Filter<T>,\n options: FindOptions<Document>,\n ): Promise<WithId<T> | null>;\n findOne<TS = T>(): Promise<TS | null>;\n findOne<TS = T>(filter: Filter<TS>): Promise<TS | null>;\n findOne<TS = T>(\n filter: Filter<TS>,\n options?: FindOptions<Document> | undefined,\n ): Promise<TS | null>;\n async findOne(\n filter?: unknown,\n _options?: unknown,\n ): Promise<import('mongodb').WithId<T> | T | null> {\n return this.collection.findOne(filter as PongoFilter<T>);\n }\n find(): MongoFindCursor<WithId<T>>;\n find(\n filter: Filter<T>,\n options?: FindOptions<Document> | undefined,\n ): MongoFindCursor<WithId<T>>;\n find<T extends Document>(\n filter: Filter<T>,\n options?: FindOptions<Document> | undefined,\n ): MongoFindCursor<T>;\n find(\n filter?: unknown,\n _options?: unknown,\n ): MongoFindCursor<WithId<T>> | MongoFindCursor<T> {\n return new FindCursor(\n this.collection.find(filter as PongoFilter<T>),\n ) as unknown as MongoFindCursor<T>;\n }\n options(_options?: OperationOptions | undefined): Promise<Document> {\n throw new Error('Method not implemented.');\n }\n isCapped(_options?: OperationOptions | undefined): Promise<boolean> {\n throw new Error('Method not implemented.');\n }\n createIndex(\n _indexSpec: IndexSpecification,\n _options?: CreateIndexesOptions | undefined,\n ): Promise<string> {\n throw new Error('Method not implemented.');\n }\n createIndexes(\n _indexSpecs: IndexDescription[],\n _options?: CreateIndexesOptions | undefined,\n ): Promise<string[]> {\n throw new Error('Method not implemented.');\n }\n dropIndex(\n _indexName: string,\n _options?: CommandOperationOptions | undefined,\n ): Promise<Document> {\n throw new Error('Method not implemented.');\n }\n dropIndexes(\n _options?: CommandOperationOptions | undefined,\n ): Promise<boolean> {\n throw new Error('Method not implemented.');\n }\n listIndexes(_options?: AbstractCursorOptions | undefined): ListIndexesCursor {\n throw new Error('Method not implemented.');\n }\n indexExists(\n _indexes: string | string[],\n _options?: AbstractCursorOptions | undefined,\n ): Promise<boolean> {\n throw new Error('Method not implemented.');\n }\n indexInformation(\n options: IndexInformationOptions & { full: true },\n ): Promise<IndexDescriptionInfo[]>;\n indexInformation(\n options: IndexInformationOptions & { full?: false | undefined },\n ): Promise<IndexDescriptionCompact>;\n indexInformation(\n options: IndexInformationOptions,\n ): Promise<IndexDescriptionCompact | IndexDescriptionInfo[]>;\n indexInformation(): Promise<IndexDescriptionCompact>;\n indexInformation(\n _options?: unknown,\n ):\n | Promise<import('mongodb').IndexDescriptionInfo[]>\n | Promise<import('mongodb').IndexDescriptionCompact>\n | Promise<\n | import('mongodb').IndexDescriptionCompact\n | import('mongodb').IndexDescriptionInfo[]\n > {\n throw new Error('Method not implemented.');\n }\n estimatedDocumentCount(\n _options?: EstimatedDocumentCountOptions | undefined,\n ): Promise<number> {\n throw new Error('Method not implemented.');\n }\n countDocuments(\n _filter?: Filter<T> | undefined,\n _options?: CountDocumentsOptions | undefined,\n ): Promise<number> {\n throw new Error('Method not implemented.');\n }\n distinct<Key extends '_id' | keyof EnhancedOmit<T, '_id'>>(\n key: Key,\n ): Promise<Flatten<WithId<T>[Key]>[]>;\n distinct<Key extends '_id' | keyof EnhancedOmit<T, '_id'>>(\n key: Key,\n filter: Filter<T>,\n ): Promise<Flatten<WithId<T>[Key]>[]>;\n distinct<Key extends '_id' | keyof EnhancedOmit<T, '_id'>>(\n key: Key,\n filter: Filter<T>,\n options: CommandOperationOptions,\n ): Promise<Flatten<WithId<T>[Key]>[]>;\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n distinct(key: string): Promise<any[]>;\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n distinct(key: string, filter: Filter<T>): Promise<any[]>;\n distinct(\n key: string,\n filter: Filter<T>,\n options: CommandOperationOptions, // eslint-disable-next-line @typescript-eslint/no-explicit-any\n ): Promise<any[]>;\n distinct(\n _key: unknown,\n _filter?: unknown,\n _options?: unknown,\n ): // eslint-disable-next-line @typescript-eslint/no-explicit-any\n | Promise<any[]>\n | Promise<import('mongodb').Flatten<import('mongodb').WithId<T>[Key]>[]> {\n throw new Error('Method not implemented.');\n }\n indexes(\n options: IndexInformationOptions & { full?: true | undefined },\n ): Promise<IndexDescriptionInfo[]>;\n indexes(\n options: IndexInformationOptions & { full: false },\n ): Promise<IndexDescriptionCompact>;\n indexes(\n options: IndexInformationOptions,\n ): Promise<IndexDescriptionCompact | IndexDescriptionInfo[]>;\n indexes(\n options?: AbstractCursorOptions | undefined,\n ): Promise<IndexDescriptionInfo[]>;\n indexes(\n _options?: unknown,\n ):\n | Promise<import('mongodb').IndexDescriptionInfo[]>\n | Promise<import('mongodb').IndexDescriptionCompact>\n | Promise<\n | import('mongodb').IndexDescriptionCompact\n | import('mongodb').IndexDescriptionInfo[]\n > {\n throw new Error('Method not implemented.');\n }\n findOneAndDelete(\n filter: Filter<T>,\n options: FindOneAndDeleteOptions & { includeResultMetadata: true },\n ): Promise<ModifyResult<T>>;\n findOneAndDelete(\n filter: Filter<T>,\n options: FindOneAndDeleteOptions & { includeResultMetadata: false },\n ): Promise<WithId<T> | null>;\n findOneAndDelete(\n filter: Filter<T>,\n options: FindOneAndDeleteOptions,\n ): Promise<WithId<T> | null>;\n findOneAndDelete(filter: Filter<T>): Promise<WithId<T> | null>;\n findOneAndDelete(\n _filter: unknown,\n _options?: unknown,\n ):\n | Promise<import('mongodb').WithId<T> | null>\n | Promise<import('mongodb').ModifyResult<T>> {\n throw new Error('Method not implemented.');\n }\n findOneAndReplace(\n filter: Filter<T>,\n replacement: WithoutId<T>,\n options: FindOneAndReplaceOptions & { includeResultMetadata: true },\n ): Promise<ModifyResult<T>>;\n findOneAndReplace(\n filter: Filter<T>,\n replacement: WithoutId<T>,\n options: FindOneAndReplaceOptions & { includeResultMetadata: false },\n ): Promise<WithId<T> | null>;\n findOneAndReplace(\n filter: Filter<T>,\n replacement: WithoutId<T>,\n options: FindOneAndReplaceOptions,\n ): Promise<WithId<T> | null>;\n findOneAndReplace(\n filter: Filter<T>,\n replacement: WithoutId<T>,\n ): Promise<WithId<T> | null>;\n findOneAndReplace(\n _filter: unknown,\n _replacement: unknown,\n _options?: unknown,\n ):\n | Promise<import('mongodb').WithId<T> | null>\n | Promise<import('mongodb').ModifyResult<T>> {\n throw new Error('Method not implemented.');\n }\n findOneAndUpdate(\n filter: Filter<T>,\n update: UpdateFilter<T>,\n options: FindOneAndUpdateOptions & { includeResultMetadata: true },\n ): Promise<ModifyResult<T>>;\n findOneAndUpdate(\n filter: Filter<T>,\n update: UpdateFilter<T>,\n options: FindOneAndUpdateOptions & { includeResultMetadata: false },\n ): Promise<WithId<T> | null>;\n findOneAndUpdate(\n filter: Filter<T>,\n update: UpdateFilter<T>,\n options: FindOneAndUpdateOptions,\n ): Promise<WithId<T> | null>;\n findOneAndUpdate(\n filter: Filter<T>,\n update: UpdateFilter<T>,\n ): Promise<WithId<T> | null>;\n findOneAndUpdate(\n _filter: unknown,\n _update: unknown,\n _options?: unknown,\n ):\n | Promise<import('mongodb').WithId<T> | null>\n | Promise<import('mongodb').ModifyResult<T>> {\n throw new Error('Method not implemented.');\n }\n aggregate<T extends Document = Document>(\n _pipeline?: Document[] | undefined,\n _options?: AggregateOptions | undefined,\n ): AggregationCursor<T> {\n throw new Error('Method not implemented.');\n }\n watch<\n TLocal extends Document = T,\n TChange extends Document = ChangeStreamDocument<TLocal>,\n >(\n _pipeline?: Document[] | undefined,\n _options?: ChangeStreamOptions | undefined,\n ): ChangeStream<TLocal, TChange> {\n throw new Error('Method not implemented.');\n }\n initializeUnorderedBulkOp(\n _options?: BulkWriteOptions | undefined,\n ): UnorderedBulkOperation {\n throw new Error('Method not implemented.');\n }\n initializeOrderedBulkOp(\n _options?: BulkWriteOptions | undefined,\n ): OrderedBulkOperation {\n throw new Error('Method not implemented.');\n }\n count(\n _filter?: Filter<T> | undefined,\n _options?: CountOptions | undefined,\n ): Promise<number> {\n throw new Error('Method not implemented.');\n }\n listSearchIndexes(\n options?: ListSearchIndexesOptions | undefined,\n ): ListSearchIndexesCursor;\n listSearchIndexes(\n name: string,\n options?: ListSearchIndexesOptions | undefined,\n ): ListSearchIndexesCursor;\n listSearchIndexes(\n _name?: unknown,\n _options?: unknown,\n ): import('mongodb').ListSearchIndexesCursor {\n throw new Error('Method not implemented.');\n }\n createSearchIndex(_description: SearchIndexDescription): Promise<string> {\n throw new Error('Method not implemented.');\n }\n createSearchIndexes(\n _descriptions: SearchIndexDescription[],\n ): Promise<string[]> {\n throw new Error('Method not implemented.');\n }\n dropSearchIndex(_name: string): Promise<void> {\n throw new Error('Method not implemented.');\n }\n updateSearchIndex(_name: string, _definition: Document): Promise<void> {\n throw new Error('Method not implemented.');\n }\n\n async createCollection(): Promise<void> {\n await this.collection.createCollection();\n }\n}\n","// src/MongoClientShim.ts\nimport { pongoClient, type PongoClient } from '../main';\nimport { Db } from './mongoDb';\n\nexport class MongoClient {\n private pongoClient: PongoClient;\n\n constructor(connectionString: string) {\n this.pongoClient = pongoClient(connectionString);\n }\n\n async connect() {\n await this.pongoClient.connect();\n return this;\n }\n\n async close() {\n await this.pongoClient.close();\n }\n\n db(dbName: string): Db {\n return new Db(this.pongoClient.db(dbName));\n }\n}\n"],"mappings":"AAAA,OAAOA,MAAQ,KAEf,IAAMC,EAA8B,IAAI,I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,MAAM,IAAI,MAAM,yBAAyB,CAC3C,CAEA,MAAM,kBAAkC,CACtC,MAAM,KAAK,WAAW,iBAAiB,CACzC,CACF,ED9eO,IAAMC,EAAN,KAAS,CACd,YAAoBC,EAAkB,CAAlB,aAAAA,CAAmB,CAEvC,WAA+BC,EAA4C,CACzE,OAAO,IAAIC,EAAc,KAAK,QAAQ,WAAcD,CAAc,CAAC,CACrE,CACF,EENO,IAAME,EAAN,KAAkB,CACf,YAER,YAAYC,EAA0B,CACpC,KAAK,YAAcC,EAAYD,CAAgB,CACjD,CAEA,MAAM,SAAU,CACd,aAAM,KAAK,YAAY,QAAQ,EACxB,IACT,CAEA,MAAM,OAAQ,CACZ,MAAM,KAAK,YAAY,MAAM,CAC/B,CAEA,GAAGE,EAAoB,CACrB,OAAO,IAAIC,EAAG,KAAK,YAAY,GAAGD,CAAM,CAAC,CAC3C,CACF","names":["pg","pools","getPool","connectionStringOrOptions","connectionString","poolOptions","endPool","pool","endAllPools","format","uuid","execute","pool","handle","client","executeSQL","sql","entries","obj","key","value","format","Operators","OperatorMap","isOperator","key","hasOperators","value","handleOperator","path","operator","handleIdOperator","format","buildNestedObject","v","subQuery","entries","subKey","subValue","acc","AND","constructFilterQuery","filter","key","value","isRecord","constructComplexFilterQuery","handleOperator","isEquality","hasOperators","entries","nestedKey","val","Operators","format","sql","sqlQuery","params","buildUpdateQuery","update","entries","currentUpdateQuery","op","value","buildSetQuery","buildUnsetQuery","buildIncQuery","buildPushQuery","sql","set","unset","inc","key","push","postgresCollection","collectionName","pool","execute","sql","executeSQL","SqlFor","collectionSQLBuilder","createCollection","document","_id","uuid","documents","rows","doc","result","d","filter","update","row","values","format","filterQuery","constructFilterQuery","updateQuery","buildUpdateQuery","postgresClient","connectionString","database","pool","getPool","endPool","name","postgresCollection","getDbClient","connectionString","database","postgresClient","pongoClient","connectionString","dbClient","getDbClient","dbName","FindCursor","documents","callback","docs","doc","Collection","collection","v","doc","_options","result","docs","_operations","filter","update","_filter","_","_newName","FindCursor","_indexSpec","_indexSpecs","_indexName","_indexes","_key","_replacement","_update","_pipeline","_name","_description","_descriptions","_definition","Db","pongoDb","collectionName","Collection","MongoClient","connectionString","pongoClient","dbName","Db"]}
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@event-driven-io/pongo",
3
- "version": "0.1.1",
3
+ "version": "0.2.0",
4
4
  "description": "Pongo - Mongo with strong consistency on top of Postgres",
5
5
  "type": "module",
6
6
  "scripts": {
@@ -47,13 +47,12 @@
47
47
  "dist"
48
48
  ],
49
49
  "peerDependencies": {
50
- "@types/uuid": "^9.0.8",
51
- "close-with-grace": "^1.3.0",
52
50
  "pg": "^8.12.0",
53
51
  "pg-format": "^1.0.4",
54
52
  "uuid": "^9.0.1"
55
53
  },
56
54
  "devDependencies": {
55
+ "@types/uuid": "^9.0.8",
57
56
  "@types/node": "20.11.30",
58
57
  "@types/pg": "^8.11.6",
59
58
  "@types/pg-format": "^1.0.5"