bwmarrin/snowflake

Request: A function to get ID at perticular instance of time in past

msonawane opened this issue · 4 comments

Usecase: snowflake as database primary key. it will be useful to get all records inserted before 1 month.
It will be great to have a function that:

  1. given a time in past generates ID
  2. ignores node id ?

I'm sorry for not noticing this issue sooner - but here I am :)

I'm a bit confused on your use case, maybe you can give me a bit more context?

Are you wanting to generate these just for the purpose of doing a sql query? So you can query a database for all records where the IDs created with in a given time frame?

yes

Hmn, I suppose this is a bit tricky. I'm not entirely sure if this should be in the library - but I'm not opposed to it if I can come up with a good method name for it :)

Here's a example of how to accomplish this

// Generate a Go Datetime, you could use time.X funcs to get a value at a specific date/time
dt := time.Now()

// Convert it into Unix timestamp in milliseconds and offset it by the snowflake Epoch
t = (dt.UnixNano() / 1000000) - (snowflake.Epoch)

// shift it over 22 bits, this should be (nodebits + stepbits)
t = (t) << 22

// Print the result
fmt.Printf("Int64   t: %d\n", t)

How about adding a function to Node.

func (n *Node) MakeID(t time.Time, seq int64) (ID, error) {
    // ...
}