Code Monkey home page Code Monkey logo

pgtyped-rescript's Introduction

Version Actions Status Join the chat at https://gitter.im/pgtyped/community

ReScript fork of PgTyped

This is a fork PgTyped that outputs ReScript instead of TS. Most things work the same as the TS version. Here's a dedicated ReScript readme detailing the differences, and how to get started in ReScript.

PgTyped makes it possible to use raw SQL in TypeScript with guaranteed type-safety.
No need to map or translate your DB schema to TypeScript, PgTyped automatically generates types and interfaces for your SQL queries by using your running Postgres database as the source of type information.


Features:

  1. Automatically generates TS types for parameters/results of SQL queries of any complexity.
  2. Supports extracting and typing queries from both SQL and TS files.
  3. Generate query types as you write them, using watch mode.
  4. Useful parameter interpolation helpers for arrays and objects.
  5. No need to define your DB schema in TypeScript, your running DB is the live source of type data.
  6. Prevents SQL injections by not doing explicit parameter substitution. Instead, queries and parameters are sent separately to the DB driver, allowing parameter substitution to be safely done by the PostgreSQL server.
  7. Native ESM support. Runtime dependencies are also provided as CommonJS.

Documentation

Visit our documentation page at https://pgtyped.dev/

Getting started

  1. npm install -D @pgtyped/cli typescript (typescript is a required peer dependency for pgtyped)
  2. npm install @pgtyped/runtime (@pgtyped/runtime is the only required runtime dependency of pgtyped)
  3. Create a PgTyped config.json file.
  4. Run npx pgtyped -w -c config.json to start PgTyped in watch mode.

More info on getting started can be found in the Getting Started page. You can also refer to the example app for a preconfigured example.

Example

Lets save some queries in books.sql:

/* @name FindBookById */
SELECT * FROM books WHERE id = :bookId;

PgTyped parses the SQL file, extracting all queries and generating strictly typed TS queries in books.queries.ts:

/** Types generated for queries found in "books.sql" */

//...

/** 'FindBookById' parameters type */
export interface IFindBookByIdParams {
  bookId: number | null;
}

/** 'FindBookById' return type */
export interface IFindBookByIdResult {
  id: number;
  rank: number | null;
  name: string | null;
  author_id: number | null;
}

/**
 * Query generated from SQL:
 * SELECT * FROM books WHERE id = :bookId
 */
export const findBookById = new PreparedQuery<
  IFindBookByIdParams,
  IFindBookByIdResult
>(...);

Query findBookById is now statically typed, with types inferred from the PostgreSQL schema.
This generated query can be imported and executed as follows:

import { Client } from 'pg';
import { findBookById } from './books.queries';

export const client = new Client({
  host: 'localhost',
  user: 'test',
  password: 'example',
  database: 'test',
});

async function main() {
  await client.connect();
  const books = await findBookById.run(
    {
      bookId: 5,
    },
    client,
  );
  console.log(`Book name: ${books[0].name}`);
  await client.end();
}

main();

Resources

  1. Configuring pgTyped
  2. Writing queries in SQL files
  3. Advanced queries and parameter expansions in SQL files
  4. Writing queries in TS files
  5. Advanced queries and parameter expansions in TS files

Project state:

This project is being actively developed and its APIs might change. All issue reports, feature requests and PRs appreciated.

License

MIT

Copyright (c) 2019-present, Adel Salakh

pgtyped-rescript's People

Contributors

adelsz avatar bag-man avatar bradleyayers avatar darky avatar dependabot[bot] avatar elob avatar gervinfung avatar gitter-badger avatar golergka avatar jessevelden avatar jgonera avatar joecarver avatar johanholmerin avatar johnnycrazy avatar logan12358 avatar lucas-gregoire avatar mako-taco avatar maylukas avatar msakrejda avatar mudrz avatar nbarnett avatar nick-keller avatar renovate-bot avatar renovate[bot] avatar robinclowers avatar silasdavis avatar snarky-puppy avatar tamlyn avatar water-a avatar zth avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar

pgtyped-rescript's Issues

Convenience methods

It'd be nice to generate variations of every function:

e.g.

/* @name findDataSetCaseById */
SELECT * FROM test_case where id = :id! limit 1;

could generate:

  • findDataSetCaseById- a list of results
  • findDataSetCaseByIdOne - a single result, throws an exception if there isn't exactly one element
    -findDataSetCaseByIdOneOpt - a single option of a result

genType support

There are a few low-hanging bits of fruit that would enable a first-pass at genType support!

As an example of the changes necessary, here is are the manual tweaks I made to the pgtyped-rescript artifacts https://gist.github.com/sgrove/68c85bd81f3776bfa4bf9ad9baf1bb48/revisions

  1. type aliases with @genType.opaque to hide the upstream types (pgClient, Null.t) + manual type specification for the parameters rescript-association/genType#636 and rescript-association/genType#634 (comment)
  2. No labeled arguments, since genType just outputs the wrong stuff rescript-association/genType#635

With those changes, we get this behavior in TypeScript:
Screenshot 2023-08-16 at 21 12 10

It doesn't provide an all-the-way optimal experience on the other side (e.g. pgClient isn't appropriately typed):
Screenshot 2023-08-16 at 21 12 23

But it's a minor detail compared to the experience before!

Querying for an array of jsonb generates invalid rescript

Describe the bug
Selecting a column of type jsonb[] will generate invalid rescript:

/* @name findById */
SELECT examples FROM test_case where id = :id! limit 1;

generates:

open PgTyped
type Js.Json.tArray = array<Js.Json.t>

/** 'FindById' parameters type */
type findByIdParams = {
  id: string,
}

/** 'FindById' return type */
type findByIdResult = {
  /** Examples conforming to the input schema */
  examples: Null.t<Js.Json.tArray>,
}

type Js.Json.tArray is syntactically invalid

Expected behavior
The type value is fine, so maybe just munging Js.Json.tArray to jsJsontArray would be enough?

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    ๐Ÿ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. ๐Ÿ“Š๐Ÿ“ˆ๐ŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google โค๏ธ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.