snowflake icon indicating copy to clipboard operation
snowflake copied to clipboard

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

Open msonawane opened this issue 5 years ago • 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 ?

msonawane avatar Dec 28 '19 05:12 msonawane

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?

bwmarrin avatar Feb 01 '20 04:02 bwmarrin

yes

msonawane avatar Feb 05 '20 07:02 msonawane

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)

bwmarrin avatar Feb 05 '20 20:02 bwmarrin

How about adding a function to Node.

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

codemedic avatar Aug 18 '21 20:08 codemedic