Skip to content

Commit

Permalink
Initial commit
Browse files Browse the repository at this point in the history
  • Loading branch information
kaashyapan committed May 27, 2023
0 parents commit bb34a1a
Show file tree
Hide file tree
Showing 119 changed files with 6,010 additions and 0 deletions.
10 changes: 10 additions & 0 deletions .github/dependabot.yml
Original file line number Diff line number Diff line change
@@ -0,0 +1,10 @@
version: 2
updates:
- package-ecosystem: "gomod"
directory: "/"
schedule:
interval: "daily"
- package-ecosystem: "github-actions"
directory: "/"
schedule:
interval: "daily"
18 changes: 18 additions & 0 deletions .github/workflows/ci.yml
Original file line number Diff line number Diff line change
@@ -0,0 +1,18 @@
name: make
on:
push:
branches:
- main
pull_request:
jobs:
build:
name: test
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v4
- uses: actions/setup-go@v4
with:
go-version: '1.19'
- run: wget https://github.com/tinygo-org/tinygo/releases/download/v0.26.0/tinygo_0.26.0_amd64.deb
- run: sudo dpkg -i tinygo_0.26.0_amd64.deb
- run: make
2 changes: 2 additions & 0 deletions .gitignore
Original file line number Diff line number Diff line change
@@ -0,0 +1,2 @@
*.wasm
.vscode
21 changes: 21 additions & 0 deletions LICENSE
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
MIT License

Copyright (c) 2023 kaashyapan

Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
9 changes: 9 additions & 0 deletions Makefile
Original file line number Diff line number Diff line change
@@ -0,0 +1,9 @@
all: sqlc-gen-fsharp sqlc-gen-fsharp.wasm

sqlc-gen-fsharp:
cd plugin && go build -o ~/bin/sqlc-gen-fsharp ./main.go

sqlc-gen-fsharp.wasm:
cd plugin && tinygo build -o sqlc-gen-fsharp.wasm -gc=leaking -scheduler=none -wasm-abi=generic -target=wasi main.go
openssl sha256 plugin/sqlc-gen-fsharp.wasm

99 changes: 99 additions & 0 deletions Readme.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,99 @@
# Sqlc plugin for F#
## Codegen F# from SQL
`sqlc` is a command line program that generates type-safe database access code from SQL.
Sqlc documentation - https://sqlc.dev

**Inputs**
- DB schema.sql file
- File containing SQL statements
- Configuration file.

**Outputs**
- Models as F# data structures
- Queries as functions taking named-typed parameters
- Readers to decode DB response into F# data structures


| Target | Library | |
|-----------|-------------------|----|
|Postgres |`Npgsql.FSharp` | |
|MySql | Not supported | Models will be generated|
|Sqlite |`Fumble` | |

## Why this ?
Type safe DB access in F# is tedious with manually written data structures.\
SqlHydra is a great dotnet tool to generate F# boiler plate. Works great with ORMs.\
I found I was writing a lot of custom SQL and wanted a solution that can generate 100% of the code.

This is intended for devs who prefer to write SQL by hand.

|SqlHydra | Sqlc|
|-----------|-------------------|
|Uses a connection to the database to generate data structures| Uses schema file and SQL files|
|Postgres, Oracle, MSSql & Sqlite | Postgres & Sqlite |
|SqlHydra.Query uses Sqlkata | Handwritten Sql |
|Wraps Microsoft.Data.SqlClient. Flexible. Bring your own ADO.net wrapper| Wraps higher level F# libraries. Opinionated. Less generated code. |
|Cannot introspect queries | Wraps the pg_query Postgres SQL parser. It syntax checks the SQL & DDL statements|
|Handwritten data structures are required for custom queries| Produces exact data structures and readers for custom queries |


## How to use

- Install [Sqlc](https://docs.sqlc.dev/en/latest/overview/install.html)
- Create Schema.sql containing DDL statements. (or generate using pg_dump)
- Create Query.sql containing SQL statements with an annotation like in [docs](https://docs.sqlc.dev/en/latest/reference/query-annotations.html)
```sql
-- name: ListAuthors :many
SELECT * FROM authors ORDER BY name;
```
- Create sqlc.json & configure the options
```json
{
"version": "2",
"plugins": [
{
"name": "fsharp",
"process": {
"cmd": "/home/ubuntu/bin/sqlc-gen-fsharp"
}
}
],
"sql": [
{
"engine": "postgresql",
"schema": "schema.sql",
"queries": "query.sql",
"codegen": [
{
"out": <..target_folder...>,
"plugin": "fsharp",
"options": {
"namespace": <...Namespace...>,
"async": false,
"type_affinity": true
}
}
]
}
]
}
```
- ```sqlc generate```

See the test folder for a sample setup.



### fsharp config options
`namespace`: The namespace to use for the generated code.\
`out`: Output directory for generated code.\
`emit_exact_table_names`: If true, use the exact table name for generated models. Otherwise, guess a singular form. Defaults to *false*.\
`async`: If true, all query functions generated will be async. Defaults to *false*.
`type_affinity`: If true, all DB integers (except Bigint) will be mapped to F#int. All DB floats will be mapped to F#double. Defaults to *false*.


### TODO
- Support for enumerated column types.
- Postgis type support
- Optionally generate classes instead of records
- Autogenerate basic CRUD without writing SQL
3 changes: 3 additions & 0 deletions build.sh
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
#!bash
#
docker run -it --rm -w /src -v ~/sqlc-gen-fsharp:/src tinygo/tinygo:0.27.0 tinygo build -o sqlc-gen-fsharp.wasm -target wasi plugin/main.go
11 changes: 11 additions & 0 deletions examples/authors/mysql/Models.fs
Original file line number Diff line number Diff line change
@@ -0,0 +1,11 @@
// Code generated by sqlc. DO NOT EDIT.
// version: sqlc v1.18.0

namespace Authors

open System

type Author =
{ Id: int64
Name: string
Bio: string option }
Empty file.
Empty file.
18 changes: 18 additions & 0 deletions examples/authors/mysql/query.sql
Original file line number Diff line number Diff line change
@@ -0,0 +1,18 @@
/* name: GetAuthor :one */
SELECT * FROM authors
WHERE id = @id LIMIT 1;

/* name: ListAuthors :many */
SELECT * FROM authors
ORDER BY name;

/* name: CreateAuthor :execresult */
INSERT INTO authors (
name, bio
) VALUES (
@name, @bio
);

/* name: DeleteAuthor :exec */
DELETE FROM authors
WHERE id = @id;
5 changes: 5 additions & 0 deletions examples/authors/mysql/schema.sql
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
CREATE TABLE authors (
id BIGINT PRIMARY KEY AUTO_INCREMENT,
name text NOT NULL,
bio text
);
12 changes: 12 additions & 0 deletions examples/authors/postgres/Models.fs
Original file line number Diff line number Diff line change
@@ -0,0 +1,12 @@
// Code generated by sqlc. DO NOT EDIT.
// version: sqlc v1.18.0

namespace Authors

open System
open Npgsql

type Author =
{ Id: int64
Name: string
Bio: string option }
85 changes: 85 additions & 0 deletions examples/authors/postgres/Queries.fs
Original file line number Diff line number Diff line change
@@ -0,0 +1,85 @@
// Code generated by sqlc. DO NOT EDIT.
// version: sqlc v1.18.0

namespace Authors

open System
open Npgsql
open Npgsql.FSharp
open Authors.Readers

module Sqls =

[<Literal>]
let createAuthor =
"""
INSERT INTO authors (
name, bio
) VALUES (
@name, @bio
)
"""

[<Literal>]
let deleteAuthor =
"""
DELETE FROM authors
WHERE id = @id
"""

[<Literal>]
let getAuthor =
"""
SELECT id, name, bio FROM authors
WHERE id = @id LIMIT 1
"""

[<Literal>]
let listAuthors =
"""
SELECT id, name, bio FROM authors
ORDER BY name
"""

[<RequireQualifiedAccessAttribute>]
type DB(conn: string) =

// https://www.connectionstrings.com/npgsql

/// This SQL will insert a single author into the table
member this.createAuthor(name: string, ?bio: string) =

let parameters = [ ("name", Sql.text name); ("bio", Sql.textOrNone bio) ]

conn
|> Sql.connect
|> Sql.query Sqls.createAuthor
|> Sql.parameters parameters
|> Sql.executeNonQuery

/// This SQL will delete a given author
member this.deleteAuthor(id: int64) =

let parameters = [ ("id", Sql.int64 id) ]

conn
|> Sql.connect
|> Sql.query Sqls.deleteAuthor
|> Sql.parameters parameters
|> Sql.executeNonQuery

/// This SQL will select a single author from the table
member this.getAuthor(id: int64) =

let parameters = [ ("id", Sql.int64 id) ]

conn
|> Sql.connect
|> Sql.query Sqls.getAuthor
|> Sql.parameters parameters
|> Sql.executeRow authorReader

/// This SQL will list all authors from the authors table
member this.listAuthors() =

conn |> Sql.connect |> Sql.query Sqls.listAuthors |> Sql.execute authorReader
15 changes: 15 additions & 0 deletions examples/authors/postgres/Readers.fs
Original file line number Diff line number Diff line change
@@ -0,0 +1,15 @@
// Code generated by sqlc. DO NOT EDIT.
// version: sqlc v1.18.0

namespace Authors

open System
open Npgsql
open Npgsql.FSharp

module Readers =

let authorReader (r: RowReader) : Author =
{ Author.Id = r.int64 "id"
Name = r.text "name"
Bio = r.textOrNone "bio" }
22 changes: 22 additions & 0 deletions examples/authors/postgresql/query.sql
Original file line number Diff line number Diff line change
@@ -0,0 +1,22 @@
/* name: GetAuthor :one */
/* This SQL will select a single author from the table */
SELECT * FROM authors
WHERE id = @id LIMIT 1;

/* name: ListAuthors :many */
/* This SQL will list all authors from the authors table */
SELECT * FROM authors
ORDER BY name;

/* name: CreateAuthor :execresult */
/* This SQL will insert a single author into the table */
INSERT INTO authors (
name, bio
) VALUES (
@name, @bio
);

/* name: DeleteAuthor :exec */
/* This SQL will delete a given author */
DELETE FROM authors
WHERE id = @id;
5 changes: 5 additions & 0 deletions examples/authors/postgresql/schema.sql
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
CREATE TABLE authors (
id BIGSERIAL PRIMARY KEY,
name text NOT NULL,
bio text
);
Loading

0 comments on commit bb34a1a

Please sign in to comment.