Movatterモバイル変換


[0]ホーム

URL:


Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Sign up
Appearance settings
NotificationsYou must be signed in to change notification settings

sqlc-dev/sqlc-gen-typescript

Repository files navigation

Caution

Here be dragons! This plugin is still in early access. Expect breaking changes, missing functionality, and sub-optimal output. Please report all issues and errors. Good luck!

Usage

version:'2'plugins:-name:tswasm:url:https://downloads.sqlc.dev/plugin/sqlc-gen-typescript_0.1.3.wasmsha256:287df8f6cc06377d67ad5ba02c9e0f00c585509881434d15ea8bd9fc751a9368sql:-schema:"schema.sql"queries:"query.sql"engine:postgresqlcodegen:  -out:src/authorsplugin:tsoptions:runtime:nodedriver:postgres

Supported engines and drivers

Getting started

This tutorial assumes that the latest version of sqlc isinstalled and ready to use.

We'll generate TypeScript here, but otherlanguageplugins areavailable. You'll need Bun (or Node.js) installed if you want to build and run aprogram with the code sqlc generates, but sqlc itself has no dependencies.

We'll also rely on sqlc'smanaged databases,which require a sqlc Cloud project and auth token. You can get those fromthesqlc Cloud dashboard. Managed databases arean optional feature that improves sqlc's query analysis in many cases, but youcan turn it off simply by removing thecloud anddatabase sections of yourconfiguration.

Setting up

Create a new directory calledsqlc-tutorial and open it up.

Initialize a new package.

$ bun init

sqlc looks for either asqlc.(yaml|yml) orsqlc.json file in the currentdirectory. In our new directory, create a file namedsqlc.yaml with thefollowing contents:

version:"2"cloud:# Replace <PROJECT_ID> with your project ID from the sqlc Cloud dashboardproject:"<PROJECT_ID>"plugins:-name:tswasm:url:https://downloads.sqlc.dev/plugin/sqlc-gen-typescript_0.1.3.wasmsha256:287df8f6cc06377d67ad5ba02c9e0f00c585509881434d15ea8bd9fc751a9368sql:  -engine:"postgresql"queries:"query.sql"schema:"schema.sql"database:managed:truecodegen:    -out:dbplugin:tsoptions:runtime:nodedriver:pg

Replace<PROJECT_ID> with your project ID from the sqlc Cloud dashboard. Itwill look something like01HA8SZH31HKYE9RR3N3N3TSJM.

And finally, set theSQLC_AUTH_TOKEN environment variable:

export SQLC_AUTH_TOKEN="<your sqlc auth token>"

Schema and queries

sqlc needs to know your database schema and queries in order to generate code.In the same directory, create a file namedschema.sql with the followingcontent:

CREATETABLEauthors (  idBIGSERIALPRIMARY KEY,  nametextNOT NULL,  biotext);

Next, create aquery.sql file with the following five queries:

-- name: GetAuthor :oneSELECT*FROM authorsWHERE id= $1LIMIT1;-- name: ListAuthors :manySELECT*FROM authorsORDER BY name;-- name: CreateAuthor :oneINSERT INTO authors (  name, bio)VALUES (  $1, $2)RETURNING*;-- name: UpdateAuthor :execUPDATE authorsset name= $2,  bio= $3WHERE id= $1;-- name: DeleteAuthor :execDELETEFROM authorsWHERE id= $1;

If you prefer, you can alter theUpdateAuthor query to return the updatedrecord:

-- name: UpdateAuthor :oneUPDATE authorsset name= $2,  bio= $3WHERE id= $1RETURNING*;

Generating code

You are now ready to generate code. You shouldn't see any output when you runthegenerate subcommand, unless something goes wrong:

$ sqlc generate

You should now have atutorial subdirectory with three files containing Gosource code. These files comprise a Go package namedtutorial:

├── package.json├── query.sql├── schema.sql├── sqlc.yaml└── db    ├── query_sql.ts

Using generated code

You can use your newly-generated code package from any TypeScript program.Create a file namedindex.ts and add the following contents:

import{Pool}from"pg";import{createAuthor,deleteAuthor,getAuthor,listAuthors,}from"./db/query_sql";asyncfunctionmain(){constclient=newPool({connectionString:process.env["DATABASE_URL"]});awaitclient.connect();// list all authorsconstauthors=awaitlistAuthors(client);console.log(authors);// create an authorconstauthor=awaitcreateAuthor(client,{name:"Anders Hejlsberg",bio:"Original author of Turbo Pascal and co-creator of TypeScript",});if(author===null){thrownewError("author not created");}console.log(author);// get the author we just createdconstanders=awaitgetAuthor(client,{id:author.id});if(anders===null){thrownewError("anders not found");}console.log(anders);// delete the authorawaitdeleteAuthor(client,{id:anders.id});}(async()=>{awaitmain();process.exit()})();

Before this code will run you'll need to install thepg package:

$ bun install pg

The program should compile without errors. To make that possible, sqlc generatesreadable,idiomatic TypeScript code that you otherwise would've had to writeyourself. Take a look indb/query_sql.ts.

Of course for this program to run successfully you'll need to run after settingtheDATABASE_URL environment variable. And your database must have theauthors table as defined inschema.sql.

$ DATABASE_URL="$(sqlc createdb)" bun run index.ts
$ bun run index.ts

You should now have a working program using sqlc's generated TypeScript sourcecode, and hopefully can see how you'd use sqlc in your own real-worldapplications.

Configuration

PostgreSQL and node-postgres

version:'2'plugins:-name:tswasm:url:https://downloads.sqlc.dev/plugin/sqlc-gen-typescript_0.1.3.wasmsha256:287df8f6cc06377d67ad5ba02c9e0f00c585509881434d15ea8bd9fc751a9368sql:-schema:"schema.sql"queries:"query.sql"engine:postgresqlcodegen:  -out:dbplugin:tsoptions:runtime:nodedriver:pg# npm package name

PostgreSQL and postgres.js

version:'2'plugins:-name:tswasm:url:https://downloads.sqlc.dev/plugin/sqlc-gen-typescript_0.1.3.wasmsha256:287df8f6cc06377d67ad5ba02c9e0f00c585509881434d15ea8bd9fc751a9368sql:-schema:"schema.sql"queries:"query.sql"engine:postgresqlcodegen:  -out:dbplugin:tsoptions:runtime:nodedriver:postgres# npm package name

MySQL and mysql2

version:'2'plugins:-name:tswasm:url:https://downloads.sqlc.dev/plugin/sqlc-gen-typescript_0.1.3.wasmsha256:287df8f6cc06377d67ad5ba02c9e0f00c585509881434d15ea8bd9fc751a9368sql:-schema:"schema.sql"queries:"query.sql"engine:"mysql"codegen:  -out:dbplugin:tsoptions:runtime:nodedriver:mysql2# npm package name

SQLite and better-sqlite3 (Beta)

version:'2'plugins:-name:tswasm:url:https://downloads.sqlc.dev/plugin/sqlc-gen-typescript_0.1.3.wasmsha256:287df8f6cc06377d67ad5ba02c9e0f00c585509881434d15ea8bd9fc751a9368sql:-schema:"schema.sql"queries:"query.sql"engine:sqlitecodegen:  -out:dbplugin:tsoptions:runtime:nodedriver:better-sqlite3# npm package name

Development

If you want to build and test sqlc-gen-typescript locally, follow these steps:

  1. Clone the repository and install dependencies:

    git clone https://github.com/sqlc-dev/sqlc-gen-typescript.gitcd sqlc-gen-typescriptnpm install
  2. Make your desired changes to the codebase. The main source files are located in thesrc directory.

  3. If you've made changes that require updating dependencies, run:

    npm install
  4. Build the WASM plugin:
    Check theMakefile for details.

    make out.js# Ensure you have Javy installed and available in your PATHmake examples/plugin.wasm
  5. To test your local build, create a test project with asqlc.yaml file containing:

    version:'2'plugins:-name:tswasm:url:file://{path_to_your_local_wasm_file}sha256:{sha256_of_your_wasm_file}sql:-schema:"schema.sql"queries:"query.sql"engine:{your_database_engine}codegen:  -out:dbplugin:tsoptions:runtime:nodedriver:{your_database_driver}

    Replace the placeholders with appropriate values for your setup.

  6. Run sqlc in your test project to generate TypeScript code using your local plugin build:

    sqlc generate

For more details on sqlc development, refer to the sqlc core development guide. This guide provides additional information on setting up and working with sqlc in general, which may be useful for contributors to this project.
https://docs.sqlc.dev/en/latest/guides/development.html

About

No description, website, or topics provided.

Resources

Stars

Watchers

Forks

Packages

No packages published

Contributors6


[8]ページ先頭

©2009-2025 Movatter.jp