Can we use Guid as a Primary Key in Sqlite Database

前端 未结 2 1409
盖世英雄少女心
盖世英雄少女心 2020-12-08 04:12

Is is possible to use GUID as primary Keys in SQLITE Database?If Possible which datatype can be used?

2条回答
  •  伪装坚强ぢ
    2020-12-08 04:43

    sqlite3 does not have a native UUID 128-bit format, per se.

    However, GUIDs can be used as keys in SQLite as either a TEXT or a binary BLOB representation.

    Based on the performance numbers posted in answer to a similar question, both binary and string UUIDs can be efficient in SQLite for Create and Query when indexed.

    see table in: https://stackoverflow.com/a/11337522/3103448

    SQLite can genarate either BLOB or TEXT 128-bit randoms numbers with randomblob(16) and hex(X) For example: lower(hex(randomblob(16)))

    With similar index perfomance, a significant trade-off becomes whether a human readable string is preferred to the smaller binary data size.

    Note: SQLite Release 3.31.0 on 2020-01-22 added the uuid.c extension module implementing functions for processing RFC-4122 UUIDs.

    uuid()        // generate a version 4 UUID as a string
    uuid_str(X)   // convert a UUID X into a well-formed UUID string
    uuid_blob(X)  // convert a UUID X into a 16-byte blob
    

    Otherwise for RFC 4122 UUID (random) Type 4 compliance do the following:

    1. Generate 16 random bytes (=128 bits)
    2. Adjust certain bits according to RFC 4122 section 4.4 as follows:

      a. set the four most significant bits of the 7th byte to 0100'B, so the high nibble is "4" b. set the two most significant bits of the 9th byte to 10'B, so the high nibble will be one of "8", "9", "A", or "B"

提交回复
热议问题