All Projects β†’ oguimbal β†’ Pg Mem

oguimbal / Pg Mem

Licence: mit
An in memory postgres DB instance for your unit tests

Programming Languages

typescript
32286 projects

Projects that are alternatives of or similar to Pg Mem

Freesql
πŸ¦„ .NET orm, Mysql orm, Postgresql orm, SqlServer orm, Oracle orm, Sqlite orm, Firebird orm, θΎΎζ’¦ orm, 人倧金仓 orm, η₯žι€š orm, 翰高 orm, ε—ε€§ι€šη”¨ orm, Click house orm, MsAccess orm.
Stars: ✭ 3,077 (+779.14%)
Mutual labels:  hacktoberfest, postgresql
tropic
🍍 Test Runner Library
Stars: ✭ 29 (-91.71%)
Mutual labels:  unit-testing, mocha
chai-exclude
Exclude keys to compare from a deep equal operation with chai expect or assert.
Stars: ✭ 33 (-90.57%)
Mutual labels:  unit-testing, mocha
Prest
PostgreSQL βž• REST, low-code, simplify and accelerate development, ⚑ instant, realtime, high-performance on any Postgres application, existing or new
Stars: ✭ 3,023 (+763.71%)
Mutual labels:  hacktoberfest, postgresql
Sazerac
Data-driven unit testing for Jasmine, Mocha, and Jest
Stars: ✭ 322 (-8%)
Mutual labels:  unit-testing, mocha
Alsatian
TypeScript testing framework with test cases
Stars: ✭ 244 (-30.29%)
Mutual labels:  hacktoberfest, unit-testing
currency-api
A demo project on how to test a node/express app with Mocha, Nock and proxyquire (MNP) and code coverage with nyc/istanbul.
Stars: ✭ 19 (-94.57%)
Mutual labels:  unit-testing, mocha
Mockbukkit
MockBukkit is a mocking framework for bukkit to allow the easy unit testing of Bukkit plugins.
Stars: ✭ 186 (-46.86%)
Mutual labels:  hacktoberfest, unit-testing
Rel
πŸ’Ž Modern Database Access Layer for Golang - Testable, Extendable and Crafted Into a Clean and Elegant API
Stars: ✭ 317 (-9.43%)
Mutual labels:  hacktoberfest, postgresql
Takeoff
A rapid development environment using docker for convenience.
Stars: ✭ 271 (-22.57%)
Mutual labels:  hacktoberfest, postgresql
Tds fdw
A PostgreSQL foreign data wrapper to connect to TDS databases (Sybase and Microsoft SQL Server)
Stars: ✭ 238 (-32%)
Mutual labels:  hacktoberfest, postgresql
Eth Gas Reporter
Gas usage per unit test. Average gas usage per method. A mocha reporter.
Stars: ✭ 330 (-5.71%)
Mutual labels:  unit-testing, mocha
Chartbrew
Open-source web platform for creating charts out of different data sources (databases and APIs) πŸ“ˆπŸ“Š
Stars: ✭ 199 (-43.14%)
Mutual labels:  hacktoberfest, postgresql
Eslint Plugin Mocha
ESLint rules for mocha
Stars: ✭ 249 (-28.86%)
Mutual labels:  hacktoberfest, mocha
Dolibarr
Dolibarr ERP CRM is a modern software package to manage your company or foundation's activity (contacts, suppliers, invoices, orders, stocks, agenda, accounting, ...). It is open source software (written in PHP) and designed for small and medium businesses, foundations and freelancers. You can freely install, use and distribute it as a standalon…
Stars: ✭ 2,877 (+722%)
Mutual labels:  hacktoberfest, postgresql
floss
Unit-testing for those hard to reach places
Stars: ✭ 26 (-92.57%)
Mutual labels:  unit-testing, mocha
Uyuni
Source code for Uyuni
Stars: ✭ 169 (-51.71%)
Mutual labels:  hacktoberfest, postgresql
Fluentassertions
A very extensive set of extension methods that allow you to more naturally specify the expected outcome of a TDD or BDD-style unit tests. Targets .NET Framework 4.7, .NET Core 2.1 and 3.0, as well as .NET Standard 2.0 and 2.1. Supports the unit test frameworks MSTest2, NUnit3, XUnit2, MSpec, and NSpec3.
Stars: ✭ 2,449 (+599.71%)
Mutual labels:  hacktoberfest, unit-testing
awesome-javascript-testing
πŸ”§ Awesome JavaScript testing resources
Stars: ✭ 28 (-92%)
Mutual labels:  unit-testing, mocha
Postgresql
Development repository for the postgresql cookbook
Stars: ✭ 326 (-6.86%)
Mutual labels:  hacktoberfest, postgresql

pg-mem is an experimental in-memory emulation of a postgres database.

❀ 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

πŸ“ Usage

Using Node.js

As always, it starts with an:

npm i pg-mem --save

Then, assuming you're using something like webpack, if you're targeting a browser:

import { newDb } from 'pg-mem';

const db = newDb();
db.public.many(/* put some sql here */)

Using Deno

Pretty straightforward :)

import { newDb } from 'https://deno.land/x/pg_mem/mod.ts';

const db = newDb();
db.public.many(/* put some sql here */)

Only use the SQL syntax parser

❀ Head to the pgsql-ast-parser repo

⚠ Disclaimer

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.

πŸ” Features

Rollback to a previous state

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:

  1. Create your schema only once (which could be a heavy operation for a single unit test)
  2. Insert test data which will be shared by all test
  3. Create a restore point
  4. Run your tests with the same db instance, executing a backup.restore() before each test (which instantly resets db to the state it has after creating the restore point)

Usage:

const db = newDb();
db.public.none(`create table test(id text);
                insert into test values ('value');`);
// create a restore point & mess with data
const backup = db.backup();
db.public.none(`update test set id='new value';`)
// restore it !
backup.restore();
db.public.many(`select * from test`) // => {test: 'value'}

Custom functions

You can declare custom functions like this:

db.public.registerFunction({
            name: 'say_hello',
            args: [DataType.text],
            returns: DataType.text,
            implementation: x => 'hello ' + x,
        })

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).

Custom types

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:

db.public.registerEquivalentType({
    name: 'macaddr',
    // which type is it equivalent to (will be able to cast it from it)
    equivalentTo: DataType.text,
    isValid(val: string) {
        // check that it will be this format
        return isValidMacAddress(val);
    }
});

Doing so, you'll be able to do things such as:

SELECT '08:00:2b:01:02:03:04:05'::macaddr; -- WORKS
SELECT '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)

Extensions

No native extension is implemented (pull requests are welcome), but you can define kind-of extensions like this:

db.registerExtension('my-ext', schema => {
    // install your ext in 'schema'
    // ex:  schema.registerFunction(...)
});

Statements like create extension "my-ext" will then be supported.

πŸ“ƒ Libraries adapters

pg-mem provides handy shortcuts to create instances of popular libraries that will be bound to pg-mem instead of a real postgres db.

  • pg-native
  • node-postgres (pg)
  • pg-promise (pgp)
  • slonik
  • typeorm
  • knex

See the wiki for more details

πŸ’₯ Inspection

Inspect a table

You can manually inspect a table content using the find() method:

for (const item of db.public.getTable<TItem>('mytable').find(itemTemplate)) {
  console.log(item);
}

Manually insert items

If you'd like to insert items manually into a table, you can do this like that:

db.public.getTable<TItem>('mytable').insert({ /* item to insert */ }))

Subscribe to events

You can subscribe to some events, like:

const db = newDb();

// called on each successful sql request
db.on('query', sql => {  });
// called on each failed sql request
db.on('query-failed', sql => { });
// called on schema changes
db.on('schema-change', () => {});
// called when a CREATE EXTENSION schema is encountered.
db.on('create-extension', ext => {});

Experimental events

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.

// called when a table is iterated entirely (ex: 'select * from data where notIndex=3' triggers it)
db.on('seq-scan', () => {});

// same, but on a specific table
db.getTable('myTable').on('seq-scan', () = {});

// will be called if pg-mem did not find any way to optimize a join
// (which leads to a O(n*m) lookup with the current implementation)
db.on('catastrophic-join-optimization', () => {});

πŸ™‹β€β™‚οΈ FAQ

Detailed answers in the wiki

🐜 Development

Pull requests are welcome :)

To start hacking this lib, you'll have to:

... 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.

Note that the project description data, including the texts, logos, images, and/or trademarks, for each open source project belongs to its rightful owner. If you wish to add or remove any projects, please contact us at [email protected].