|
| 1 | +import { getConnections, PgTestClient } from 'pgsql-test'; |
| 2 | + |
| 3 | +let db: PgTestClient; |
| 4 | +let teardown: () => Promise<void>; |
| 5 | + |
| 6 | +beforeAll(async () => { |
| 7 | + ({ db, teardown } = await getConnections()); |
| 8 | +}); |
| 9 | + |
| 10 | +afterAll(async () => { |
| 11 | + await teardown(); |
| 12 | +}); |
| 13 | + |
| 14 | +beforeEach(async () => { |
| 15 | + await db.beforeEach(); |
| 16 | +}); |
| 17 | + |
| 18 | +afterEach(async () => { |
| 19 | + await db.afterEach(); |
| 20 | +}); |
| 21 | + |
| 22 | +describe('RLS Demo - Data Insertion', () => { |
| 23 | + it('should insert users and products', async () => { |
| 24 | + |
| 25 | + db.setContext({ |
| 26 | + role: 'service_role', |
| 27 | + }); |
| 28 | + |
| 29 | + // Insert users |
| 30 | + const user1 = await db.one( |
| 31 | + `INSERT INTO rls_test.users (email, name) |
| 32 | + VALUES ($1, $2) |
| 33 | + RETURNING id, email, name`, |
| 34 | + ['[email protected]', 'Alice Johnson'] |
| 35 | + ); |
| 36 | + |
| 37 | + const user2 = await db.one( |
| 38 | + `INSERT INTO rls_test.users (email, name) |
| 39 | + VALUES ($1, $2) |
| 40 | + RETURNING id, email, name`, |
| 41 | + ['[email protected]', 'Bob Smith'] |
| 42 | + ); |
| 43 | + |
| 44 | + // Insert products |
| 45 | + db.setContext({ |
| 46 | + role: 'authenticated', |
| 47 | + 'jwt.claims.user_id': user1.id |
| 48 | + }); |
| 49 | + |
| 50 | + const product1 = await db.one( |
| 51 | + `INSERT INTO rls_test.products (name, description, price, owner_id) |
| 52 | + VALUES ($1, $2, $3, $4) |
| 53 | + RETURNING id, name, price, owner_id`, |
| 54 | + ['Laptop Pro', 'High-performance laptop', 1299.99, user1.id] |
| 55 | + ); |
| 56 | + |
| 57 | + db.setContext({ |
| 58 | + role: 'authenticated', |
| 59 | + 'jwt.claims.user_id': user2.id |
| 60 | + }); |
| 61 | + |
| 62 | + const product2 = await db.one( |
| 63 | + `INSERT INTO rls_test.products (name, description, price, owner_id) |
| 64 | + VALUES ($1, $2, $3, $4) |
| 65 | + RETURNING id, name, price, owner_id`, |
| 66 | + ['Wireless Mouse', 'Ergonomic mouse', 49.99, user2.id] |
| 67 | + ); |
| 68 | + |
| 69 | + expect(user1.email).toBe('[email protected]'); |
| 70 | + expect(product1.name).toBe('Laptop Pro'); |
| 71 | + expect(product1.owner_id).toEqual(user1.id); |
| 72 | + expect(product2.owner_id).toEqual(user2.id); |
| 73 | + expect(product2.name).toBe('Wireless Mouse'); |
| 74 | + }); |
| 75 | + |
| 76 | + it('should rollback to initial state', async () => { |
| 77 | + db.setContext({ |
| 78 | + role: 'service_role' |
| 79 | + }); |
| 80 | + |
| 81 | + const result = await db.any( |
| 82 | + `SELECT u.name, p.name as product_name, p.price |
| 83 | + FROM rls_test.users u |
| 84 | + JOIN rls_test.products p ON u.id = p.owner_id |
| 85 | + ORDER BY u.name, p.name` |
| 86 | + ); |
| 87 | + expect(result.length).toEqual(0); |
| 88 | + }); |
| 89 | +}); |
0 commit comments