Gathering detailed insights and metrics for @kerlos127/pg-mem
Gathering detailed insights and metrics for @kerlos127/pg-mem
Gathering detailed insights and metrics for @kerlos127/pg-mem
Gathering detailed insights and metrics for @kerlos127/pg-mem
An in memory postgres DB instance for your unit tests
npm install @kerlos127/pg-mem
Typescript
Module System
Node Version
NPM Version
TypeScript (98.69%)
JavaScript (1.16%)
CSS (0.12%)
HTML (0.03%)
Total Downloads
0
Last Day
0
Last Week
0
Last Month
0
Last Year
0
MIT License
2,186 Stars
588 Commits
105 Forks
16 Watchers
3 Branches
34 Contributors
Updated on Jul 16, 2025
Latest Version
2.6.18
Package Id
@kerlos127/pg-mem@2.6.18
Unpacked Size
1.62 MB
Size
313.49 kB
File Count
135
NPM Version
9.7.1
Node Version
16.18.0
Published on
Jul 07, 2023
Cumulative downloads
Total Downloads
Last Day
0%
NaN
Compared to previous day
Last Week
0%
NaN
Compared to previous week
Last Month
0%
NaN
Compared to previous month
Last Year
0%
NaN
Compared to previous year
9
4
54
❤ It works both in Node or in the browser.
⭐ this repo if you like this package, it helps to motivate me :)
👉 See it in action with pg-mem playground
As always, it starts with an:
1npm i pg-mem --save
Then, assuming you're using something like webpack, if you're targeting a browser:
1import { newDb } from "pg-mem"; 2 3const db = newDb(); 4db.public.many(/* put some sql here */);
Pretty straightforward :)
1import { newDb } from "https://deno.land/x/pg_mem/mod.ts"; 2 3const db = newDb(); 4db.public.many(/* put some sql here */);
❤ Head to the pgsql-ast-parser repo
The sql syntax parser is home-made. Which means that some features are not implemented, and will be considered as invalid syntaxes.
This lib is quite new, so forgive it if some obvious pg syntax is not supported !
... And open an issue if you feel like a feature should be implemented :)
Moreover, even if I wrote hundreds of tests, keep in mind that this implementation is a best effort to replicate PG. Keep an eye on your query results if you perform complex queries. Please file issues if some results seem incoherent with what should be returned.
Finally, I invite you to read the below section to have an idea of you can or cannot do.
pg-mem
uses immutable data structures (here and here),
which means that you can have restore points for free!
This is super useful if you intend to use pg-mem
to mock your database for unit tests.
You could:
backup.restore()
before each test (which instantly resets db to the state it has after creating the restore point)Usage:
1const db = newDb(); 2db.public.none(`create table test(id text); 3 insert into test values ('value');`); 4// create a restore point & mess with data 5const backup = db.backup(); 6db.public.none(`update test set id='new value';`); 7// restore it ! 8backup.restore(); 9db.public.many(`select * from test`); // => {test: 'value'}
You can declare custom functions like this:
1db.public.registerFunction({ 2 name: "say_hello", 3 args: [DataType.text], 4 returns: DataType.text, 5 implementation: (x) => "hello " + x, 6});
And then use them like in SQL select say_hello('world')
.
Custom functions support overloading and variadic arguments.
⚠ However, the value you return is not type checked. It MUST correspond to the datatype you provided as 'returns' (it won't fail if not, but could lead to weird bugs).
Not all pg types are implemented in pg-mem. That said, most of the types are often equivalent to other types, with a format validation. pg-mem provides a way to register such types.
For instance, lets say you'd like to register the MACADDR type, which is basically a string, with a format constraint.
You can register it like this:
1db.public.registerEquivalentType({ 2 name: "macaddr", 3 // which type is it equivalent to (will be able to cast it from it) 4 equivalentTo: DataType.text, 5 isValid(val: string) { 6 // check that it will be this format 7 return isValidMacAddress(val); 8 }, 9});
Doing so, you'll be able to do things such as:
1SELECT '08:00:2b:01:02:03:04:05'::macaddr; -- WORKS 2SELECT 'invalid'::macaddr; -- will throw a conversion error
If you feel your implementation of a type matches the standard, and would like to include it in pg-mem for others to enjoy it, please consider filing a pull request ! (tip: see the INET type implementation as an example, and the pg_catalog index where supported types are registered)
No native extension is implemented (pull requests are welcome), but you can define kind-of extensions like this:
1db.registerExtension("my-ext", (schema) => { 2 // install your ext in 'schema' 3 // ex: schema.registerFunction(...) 4});
Statements like create extension "my-ext"
will then be supported.
pg-mem provides handy shortcuts to create instances of popular libraries that will be bound to pg-mem instead of a real postgres db.
If you would like to hook your database, and return ad-hoc results, you can do so like this:
1const db = newDb(); 2 3db.public.interceptQueries((sql) => { 4 if (sql === "select * from whatever") { 5 // intercept this statement, and return something custom: 6 return [{ something: 42 }]; 7 } 8 // proceed to actual SQL execution for other requests. 9 return null; 10});
You can manually inspect a table content using the find()
method:
1for (const item of db.public.getTable<TItem>("mytable").find(itemTemplate)) { 2 console.log(item); 3}
If you'd like to insert items manually into a table, you can do this like that:
1db.public.getTable<TItem>('mytable').insert({ /* item to insert */ }))
You can subscribe to some events, like:
1const db = newDb(); 2 3// called on each successful sql request 4db.on("query", (sql) => {}); 5// called on each failed sql request 6db.on("query-failed", (sql) => {}); 7// called on schema changes 8db.on("schema-change", () => {}); 9// called when a CREATE EXTENSION schema is encountered. 10db.on("create-extension", (ext) => {});
pg-mem
implements a basic support for indices.
These handlers are called when a request cannot be optimized using one of the created indices.
However, a real postgres instance will be much smarter to optimize its requests... so when pg-mem
says "this request does not use an index", dont take my word for it.
1// called when a table is iterated entirely (ex: 'select * from data where notIndex=3' triggers it) 2db.on('seq-scan', () => {}); 3 4// same, but on a specific table 5db.getTable('myTable').on('seq-scan', () = {}); 6 7// will be called if pg-mem did not find any way to optimize a join 8// (which leads to a O(n*m) lookup with the current implementation) 9db.on('catastrophic-join-optimization', () => {});
Detailed answers in the wiki
numeric(x,y)
could not behave as expected.Pull requests are welcome :)
To start hacking this lib, you'll have to:
npm start
... once done, tests should appear. HMR is on, which means that changes in your code are instantly propagated to unit tests. This allows for ultra fast development cycles (running tests takes less than 1 sec).
To debug tests: Just hit "run" (F5, or whatever)... VS Code should attach the mocha worker. Then run the test you want to debug.
Alternatively, you could just run npm run test
without installing anything, but this is a bit long.
No vulnerabilities found.
Reason
no dangerous workflow patterns detected
Reason
license file detected
Details
Reason
no binaries found in the repo
Reason
0 existing vulnerabilities detected
Reason
SAST tool detected but not run on all commits
Details
Reason
Found 4/22 approved changesets -- score normalized to 1
Reason
0 commit(s) and 0 issue activity found in the last 90 days -- score normalized to 0
Reason
detected GitHub workflow tokens with excessive permissions
Details
Reason
no effort to earn an OpenSSF best practices badge detected
Reason
security policy file not detected
Details
Reason
dependency not pinned by hash detected -- score normalized to 0
Details
Reason
branch protection not enabled on development/release branches
Details
Reason
project is not fuzzed
Details
Score
Last Scanned on 2025-07-07
The Open Source Security Foundation is a cross-industry collaboration to improve the security of open source software (OSS). The Scorecard provides security health metrics for open source projects.
Learn More