Skip to content

Instantly share code, notes, and snippets.

@jjbubudi
Last active August 29, 2015 14:26
Show Gist options
  • Save jjbubudi/4057b5b011b484785a50 to your computer and use it in GitHub Desktop.
Save jjbubudi/4057b5b011b484785a50 to your computer and use it in GitHub Desktop.
DELIMITER ;;
DROP FUNCTION IF EXISTS shard_nextval;;
CREATE FUNCTION shard_nextval() RETURNS BIGINT
BEGIN
INSERT INTO shard_seq VALUES (NULL);
SET @R_ObjectId_val = LAST_INSERT_ID();
DELETE FROM shard_seq;
RETURN @R_ObjectId_val;
END;;
DROP FUNCTION IF EXISTS next_id;;
CREATE FUNCTION next_id() RETURNS BIGINT
BEGIN
DECLARE our_epoch BIGINT DEFAULT 1325419260000;
DECLARE seq_id BIGINT;
DECLARE now_millis BIGINT;
DECLARE shard_id INT DEFAULT 1;
DECLARE result BIGINT UNSIGNED;
SELECT MOD(shard_nextval(), 1024) INTO seq_id;
SELECT ROUND(UNIX_TIMESTAMP(CURTIME(4)) * 1000) INTO now_millis;
SET result := (now_millis - our_epoch) << 23;
SET result := result | (shard_id << 10);
SET result := result | (seq_id);
RETURN result;
END;;
DELIMITER ;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment