GithubHelp home page GithubHelp logo

planetscale-driver's Introduction

PlanetScale Serverless Driver for Rust™

Rust "version" of database-js. As stated in database-js it uses PlanetScale HTTP api for database queries. It will perfectly run on Cloudflare Workers Or Vercel Edge Functions.

Usage

cargo add planetscale-driver
# also "cargo add anyhow"

Then proceed like in examples!

Examples

Connection and simple SQL execution

use planetscale_driver::PSConnection;

let conn = PSConnection::new(
  "<host>",
  "<user>",
  "<password>",
);
    
let res = conn.execute("SELECT 1").await.unwrap();

fetch_one/fetch_all/fetch_scalar

As you can see, deserialization doesn't use field names (MAYBE IN FUTURE) so remember to write your structs correctly!

use planetscale_driver::{Database, query};

#[derive(Database, Debug)]
struct TestD {
  val: u32
}

// ...

let res: TestD = query("SELECT 1").fetch_one(&conn).await?;
println!("{:?}", res);

let res: Vec<TestD> = query("SELECT val FROM testds").fetch_all(&conn).await?;
println!("{:?}", res);

let res: bool = query("SELECT true").fetch_scalar(&conn).await?;
println!("{:?}", res);

QueryBuilder

If you want to bind safely values into your query, you should use QueryBuilder

Note: now query method is wrapper around QueryBuilder

// ...

// note: values passed to .bind function must have trait ToString 
let id = 69;
let name = "420";

// res there will be empty result, if you want to get reponse data use "execute_raw"
let res = query("INSERT INTO test(id, name) VALUES($0, \"$1\")")
  .bind(id)
  .bind(name)
  .execute(&conn)
  .await?;

Json

use planetscale_driver::{Database, DatabaseJSON, query};

#[derive(Database, Debug)]
pub struct TestD {
    pub val: u32,
    pub test: TestJSON,
}

#[derive(DatabaseJSON, serde::Deserialize, serde::Serialize, Debug)]
pub struct TestJSON {
    pub text: String,
    pub test: u32,
}

// ...

let json: TestJSON = TestJSON {
    text: "test1234321".to_string(),
    test: 1234,
};

let res: TestD = query("SELECT 1010, '$0'").bind(json).fetch_one(&conn).await?;
println!("{:?}", res);

Transactions

// ...

conn.transaction(|conn| async move {
    conn.execute("QUERY")
        .await?;

    conn.execute("OTHER QUERY")
        .await?;

    //     ^- use question mark to propagate errors "up"
    //        it's required if you want to rollback changes after error

    Ok(())
}).await?;

Features

This crate uses reqwest for making http requests. By default, this crate will use the default-tls feature of reqwest which may not build in your environment (e.g. netlify serverless functions). You can override this by disabling the default features of this crate and enabling a different reqwest tls feature like so:

planetscale-driver = {version="0.5.0", default-features=false}
reqwest= {version= "0.11.17", default-features=false, features=["rustls-tls"]}

Warning If you simply disable default features and do not enable a different tls feature, reqwest will panic at runtime.

More examples in the examples folder

If you want to run them:

PS_HOST=<host> PS_USER=<username> PS_PASS=<pscale_password> cargo run --example <example_name>

planetscale-driver's People

Contributors

filipton avatar wainwrightmark avatar

Stargazers

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

Watchers

 avatar  avatar

planetscale-driver's Issues

This Vs Sqlx?

I know I can just use sqlx to query planetscale db ,

What is the difference of using this package?

aside it uses HTTP api of planetscale.... and the query builder you created?

Why would i use this? what use case? would it fit...
i see this is a database-js counter part in rust
which is built for serverless websites

Any performance, benchmark comparison vs http and direct db connection with sqlx?

on query builder whats difference on sqlx?

Also , why not just extend on sqlx , and build on top of it? like error handling on Vitest...

I hope I can have broader info , im highly interested on using planetscale on my next project...

and I wanna know if just sqlx if enough and do i need to use this package (if recommended)

thanks

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.