I'm using Diesel and chrono. In my model I have a field of type NaiveDateTime which contains the now(). However, NaiveDateTime doesn't have the function now() or a similar one whereas DateTime does:
Utc::now()
How can I convert Utc::now() into NaiveDateTime?
Utc::now() returns a DateTime<Utc>. You could click into the documentation of DateTime<T> and search for NaiveDateTime. You should find that there are two methods that will return a NaiveDateTime:
fn naive_utc(&self) -> NaiveDateTime
Returns a view to the naive UTC datetime.
fn naive_local(&self) -> NaiveDateTime
Returns a view to the naive local datetime.
For instance, if you need the timestamp in UTC:
let naive_date_time = Utc::now().naive_utc();
Note that since you are using diesel, you could use diesel::dsl::now instead, which will evaluate to CURRENT_TIMESTAMP on the SQL side.
//! ```cargo
//! [dependencies]
//! diesel = { version = "1", features = ["sqlite"] }
//! ```
#[macro_use]
extern crate diesel;
use diesel::prelude::*;
use diesel::dsl;
table! {
posts (id) {
id -> Integer,
content -> Text,
published -> Timestamp,
}
}
fn main() {
let conn = SqliteConnection::establish("test.db")
.expect("Cannot open database");
diesel::insert_into(posts::table)
.values((
posts::content.eq("hello"),
posts::published.eq(dsl::now), // <------------------
))
.execute(&conn)
.expect("Insertion failed");
}
Related
How do I change the year in a DateTime<FixedOffset> instance (from the rust crate chrono)?
That is, create a new instance of DateTime<FixedOffset> that copies the month and day from the old instance.
In other words, how would I complete the following code:
fn datetime_set_year(
datetime: &DateTime<FixedOffset>,
year: &i32
) -> DateTime<FixedOffset>
The code can ignore exceptional cases like leap days (if that is possible).
The passed DateTime<FixedOffset> instance is taken apart to a Date<FixedOffset> instance and a NaiveTime instance. Then FixedOffset.ymd and .and_time create a new DateTime<FixedOffset> instance using the passed year.
Rust Playground
fn datetime_with_year(datetime: &DateTime<FixedOffset>, year: i32) -> DateTime<FixedOffset> {
let date: Date<FixedOffset> = datetime.date();
let time: NaiveTime = datetime.time();
let fixedoffset: &FixedOffset = datetime.offset();
match fixedoffset.ymd(year, date.month(), date.day()).and_time(time) {
Some(datetime_) => {
eprintln!("fixedoffset.ymd() Some {:?}", datetime_);
datetime_
}
None => {
eprintln!("fixedoffset.ymd() None");
datetime.clone()
}
}
}
Update: or use datetime.with_year(year) as recommended by #Jmb.
Doh! 😑
I'm trying to follow: https://diesel.rs/guides/getting-started but I'm using:
echo DATABASE_URL=/tmp/diesel_demo.sqlite > .env
instead of a Postgres database.
I've changed all occurrences of Pg to Sqlite, and SERIAL to INT, but get the following error:
error[E0277]: the trait bound `i32: FromSql<diesel::sql_types::Nullable<diesel::sql_types::Integer>, Sqlite>` is not satisfied
--> src/bin/show_posts.rs:14:10
|
14 | .load::<Post>(&connection)
| ^^^^ the trait `FromSql<diesel::sql_types::Nullable<diesel::sql_types::Integer>, Sqlite>` is not implemented for `i32`
How to get a result set where field value == row number?
show_posts.rs:
extern crate diesel_demo;
extern crate diesel;
use self::diesel_demo::*;
use self::models::*;
use self::diesel::prelude::*;
fn main() {
use diesel_demo::schema::posts::dsl::*;
let connection = establish_connection();
let results = posts.filter(published.eq(true))
.limit(5)
.load::<Post>(&connection)
.expect("Error loading posts");
println!("Displaying {} posts", results.len());
for post in results {
println!("{}", post.title);
println!("----------\n");
println!("{}", post.body);
}
}
up.sql:
CREATE TABLE posts (
id INTEGER PRIMARY KEY,
title VARCHAR NOT NULL,
body TEXT NOT NULL,
published BOOLEAN NOT NULL DEFAULT 'f'
)
models.rs (autogenerated):
#[derive(Queryable)]
pub struct Post {
pub id: i32,
pub title: String,
pub body: String,
pub published: bool,
}
I don't understand why Diesel expects id to be Nullable.
Adding NOT NULL to the id field in up.sql fixed it.
I have a protobuf file used to generate types in a project. One of the types looks like:
syntax = "proto3";
// ...
message myStruct {
int32 obj_id = 1;
string obj_code = 2;
string obj_name = 3;
// ... some more fields
}
// ... some more message, enum, etc ....
Then I can launch a tiny script that generates some Go code though protoc-gen-go, that gets later translated into Rust though another script using protoc-gen-rust.
The result is a Rust file that looks like:
// This file is generated by rust-protobuf 2.0.0. Do not edit
// #generated
// ...
pub struct myStruct {
// message fields
pub obj_id: i32,
pub obj_code: ::std::string::String,
pub obj_name: ::std::string::String,
// ... some more fields
}
impl myStruct {
// ... lots of constructors, getters, setters, etc
}
I don't want a better way to do generate the Rust types altogether, the project is massive and in prod, my job is not to rewrite/reorganize it but just to add some functionalities, for which I need some nice little vectors of flags to be added in a couple of structures.
I'd like to add some Vec fields in the myStruct struct, like those:
pub struct myClass {
// ... some fields like obj_id etc ...
// the fields I want to add
bool_vec: Vec<bool>,
bool_vec_vec: Vec<Vec<bool>>,
// ...
}
Is it possible to do so using the proto-buf thing, or not? If yes, how can I do it?
You could use protobuf repeated fields:
repeated: this field can be repeated any number of times (including zero) in a well-formed message. The order of the repeated values will be preserved.
Like:
message bool_vec{
repeated bool element = 1;
}
message bool_vec_vec{
repeated bool_vec element = 1;
}
message myStruct {
...
bool_vec v = 100;
bool_vec_vec vv = 101;
...
}
The documentation of RepeatedField from the protobuf C++ library (which represents repeated fields like the repeated bool here) shows that it has what we would expect from vectors: access by index and iterators. Your generated code will also have access by index and add/remove last methods.
I have an issue using this statement
m.Post(Model, binding.Form(Wish), func(wish Wish, r render.Render, db *mgo.Database) {
This worked fine if I use the struct define inside the prog like
m.Post(Model, binding.Form(Wish1{}) , func(wish Wish1, r render.Render, db *mgo.Database) {
but I need this to be an independent package.
I get "Wish is not a type" wish is the return of the binding function.
This worked with a primary Type struct. I am passing the strut as a interface{}
I am using GO with Martini.Classic() It is really complicated for me to change Martini or Binding package. Any suggestions.
This is the all code
package chlistpkg
import (
"github.com/codegangsta/martini"
"github.com/codegangsta/martini-contrib/binding"
"github.com/codegangsta/martini-contrib/render"
"labix.org/v2/mgo"
"time"
"fmt"
"html/template"
"reflect"
"adminStruct"
)
just to show the struct that I need to pass as to routine Doall
type Wish1 struct {
Name string `form:"name"`
Description string `form:"description"`
AnyDate time.Time `form:"anydate"`
Active bool `form:"active"`
Number int `form:"number"`
NumDec float32 `form:"numDec"`
}
DB Returns a martini.Handler
func DB() martini.Handler {
session, err := mgo.Dial("mongodb://localhost")
if err != nil {
panic(err)
}
return func(c martini.Context) {
s := session.Clone()
c.Map(s.DB("advent2"))
defer s.Close()
c.Next()
}
}
GetAll returns all Wishes in the database
func GetAll(db *mgo.Database, entList interface{}) interface{} {
db.C("wishes").Find(nil).All(entList)
fmt.Println("GettAll entList =", entList)
return entList
}
func Doall(Model string, Wish interface{}, Wish2 interface{}, Wishlist interface{} ) {
m := martini.Classic()
fmt.Println ("martini.Classic =", m)
m.Use(martini.Static("images")) // serve from the "images" directory as well
m.Use(render.Renderer(render.Options{
Directory: "templates",
Layout: "layout",
}))
m.Use(DB())
m.Get(Model, func(r render.Render, db *mgo.Database) {
r.HTML(200, "lista4", GetAll(db, Wishlist))
})
binding does not take a pointer. I have to pass the struct by reference on "Wish"
the issue is the return on "wish Wish" I got an error Wish is not a type
at compilation time
m.Post(Model, binding.Form(Wish), func(wish Wish, r render.Render, db *mgo.Database) {
fmt.Println("Input wish =", wish)
db.C("wishes").Insert(wish)
r.HTML(200, "lista4", GetAll(db, Wishlist))
})
m.Run()
Thanks in advance
Luis
The reason you are getting an error is that you have called your type Wish1 (with a numerical 1) but you are referring to the Wish type (which does not exist!) in your code.
Change your struct to be:
// Note: "Wish", not "Wish1"
type Wish struct {
Name string `form:"name"`
Description string `form:"description"`
AnyDate time.Time `form:"anydate"`
Active bool `form:"active"`
Number int `form:"number"`
NumDec float32 `form:"numDec"`
}
If you want to put your type into another package (tip: don't overdo the sub-packages), then it will need to become a pkgname.Wish as names are fully qualified.
Added
After a second look, you're also messing things up here:
func Doall(Model string, Wish interface{}, Wish2 interface{}, Wishlist interface{} ) {
m := martini.Classic()
fmt.Println ("martini.Classic =", m)
m.Use(martini.Static("images")) // serve from the "images" directory as well
Your parameter list needs to provide a name for each type; you can't pass Wish interface{} as a parameter as Wish is a type, not a variable name.
You should either:
func DoAll(model string, wish interface{}, wish2 interface{}, wishList interface{}) { ... }
Or, better still, stop using interface{} like this and write:
func DoAll(model string, wishList []Wish, wishes... Wish) { ... }
However, your DoAll function does not seem to be referenced elsewhere, and is creating its own Martini instance. I highly suggest thinking about why things are "split out" like this if you're just starting out. Keep it simple - e.g.
func main() {
m := martini.Classic()
m.Use(martini.Static("images"))
m.Use(DB())
m.Use(render.Renderer(render.Options{...}))
// No need for an anonymous function, which just adds clutter
m.Get("/wishes/all", GetAllWishes)
// Same goes for here
m.Post("/wishes/new", PostWish)
m.Run()
}
PS: I've fixed the formatting of your code, as it has a lot of unnecessary spacing before/after parenthesis. Make sure to use gofmt, which is included with the Go install and can be hooked into most popular editors.
I wrote a simple program using the Go Playground at golang.org.
The output is obviously:
second test
first test
Is there a way to edit the map value in place? I know I can't take the andress of a.Things[key]. So, is setting a.Things[key] = firstTest the only way to do it? Maybe with a function ChangeThing(key string, value string)?
You could do it by making the values of your map pointers to another struct.
http://play.golang.org/p/UouwDGuVpi
package main
import "fmt"
type A struct {
Things map[string]*str
}
type str struct {
s string
}
func (a A) ThingWithKey(key string) *str {
return a.Things[key]
}
func main() {
variable := A{}
variable.Things = make(map[string]*str)
variable.Things["first"] = &str{s:"first test"}
firstTest := variable.ThingWithKey("first")
firstTest.s = "second test"
fmt.Println(firstTest.s)
fmt.Println(variable.ThingWithKey("first").s)
}
You can use a pointer as the map value http://play.golang.org/p/BCsmhevGMX