Is guid a word

A GUID is a «Globally Unique ID». Also called a UUID (Universally Unique ID).

It’s basically a 128 bit number that is generated in a way (see RFC 4112 http://www.ietf.org/rfc/rfc4122.txt) that makes it nearly impossible for duplicates to be generated. This way, I can generate GUIDs without some third party organization having to give them to me to ensure they are unique.

One widespread use of GUIDs is as identifiers for COM entities on Windows (classes, typelibs, interfaces, etc.). Using GUIDs, developers could build their COM components without going to Microsoft to get a unique identifier. Even though identifying COM entities is a major use of GUIDs, they are used for many things that need unique identifiers. Some developers will generate GUIDs for database records to provide them an ID that can be used even when they must be unique across many different databases.

Generally, you can think of a GUID as a serial number that can be generated by anyone at anytime and they’ll know that the serial number will be unique.

Other ways to get unique identifiers include getting a domain name. To ensure the uniqueness of domain names, you have to get it from some organization (ultimately administered by ICANN).

Because GUIDs can be unwieldy (from a human readable point of view they are a string of hexadecimal numbers, usually grouped like so: aaaaaaaa-bbbb-cccc-dddd-ffffffffffff), some namespaces that need unique names across different organization use another scheme (often based on Internet domain names).

So, the namespace for Java packages by convention starts with the orgnaization’s domain name (reversed) followed by names that are determined in some organization specfic way. For example, a Java package might be named:

com.example.jpackage

This means that dealing with name collisions becomes the responsibility of each organization.

XML namespaces are also made unique in a similar way — by convention, someone creating an XML namespace is supposed to make it ‘underneath’ a registered domain name under their control. For example:

xmlns="http://www.w3.org/1999/xhtml"

Another way that unique IDs have been managed is for Ethernet MAC addresses. A company that makes Ethernet cards has to get a block of addresses assigned to them by the IEEE (I think it’s the IEEE). In this case the scheme has worked pretty well, and even if a manufacturer screws up and issues cards with duplicate MAC addresses, things will still work OK as long as those cards are not on the same subnet, since beyond a subnet, only the IP address is used to route packets. Although there are some other uses of MAC addresses that might be affected — one of the algorithms for generating GUIDs uses the MAC address as one parameter. This GUID generation method is not as widely used anymore because it is considered a privacy threat.

One example of a scheme to come up with unique identifiers that didn’t work very well was the Microsoft provided ID’s for ‘VxD’ drivers in Windows 9x. Developers of third party VxD drivers were supposed to ask Microsoft for a set of IDs to use for any drivers the third party wrote. This way, Microsoft could ensure there were not duplicate IDs. Unfortunately, many driver writers never bothered, and simply used whatever ID was in the example VxD they used as a starting point. I’m not sure how much trouble this caused — I don’t think VxD ID uniqueness was absolutely necessary, but it probably affected some functionality in some APIs.

Universally unique identifier

UEFI variables on Linux screenshot.png

UUID/GUID as used by UEFI variables

Acronym UUID
Organisation
  • Open Software Foundation (OSF)
  • ISO/IEC
  • Internet Engineering Task Force (IETF)
No. of digits 32
Example 123e4567-e89b-12d3-a456-426614174000
Website RFC 4122

A universally unique identifier (UUID) is a 128-bit label used for information in computer systems. The term globally unique identifier (GUID) is also used.[1]

When generated according to the standard methods, UUIDs are, for practical purposes, unique. Their uniqueness does not depend on a central registration authority or coordination between the parties generating them, unlike most other numbering schemes. While the probability that a UUID will be duplicated is not zero, it is generally considered close enough to zero to be negligible.[2][3]

Thus, anyone can create a UUID and use it to identify something with near certainty that the identifier does not duplicate one that has already been, or will be, created to identify something else. Information labeled with UUIDs by independent parties can therefore be later combined into a single database or transmitted on the same channel, with a negligible probability of duplication.

Adoption of UUIDs is widespread, with many computing platforms providing support for generating them and for parsing their textual representation.

History[edit]

In the 1980s Apollo Computer originally used UUIDs in the Network Computing System (NCS) and later in the Open Software Foundation’s (OSF) Distributed Computing Environment (DCE). The initial design of DCE UUIDs was based on the NCS UUIDs,[4] whose design was in turn inspired by the (64-bit) unique identifiers defined and used pervasively in Domain/OS, an operating system designed by Apollo Computer. Later,[when?] the Microsoft Windows platforms adopted the DCE design as «globally unique identifiers» (GUIDs). RFC 4122 registered a URN namespace for UUIDs[1] and recapitulated the earlier specifications, with the same technical content.[citation needed]
When in July 2005 RFC 4122 was published as a proposed IETF standard, the ITU had also standardized UUIDs, based on the previous standards and early versions of RFC 4122.[citation needed]

Standards[edit]

UUIDs are standardized by the Open Software Foundation (OSF) as part of the Distributed Computing Environment (DCE).[5][6]

UUIDs are documented as part of ISO/IEC 11578:1996 «Information technology – Open Systems Interconnection – Remote Procedure Call (RPC)» and more recently in ITU-T Rec. X.667 | ISO/IEC 9834-8:2014.[7]

The Internet Engineering Task Force (IETF) published the Standards-Track RFC 4122,[1] technically equivalent to ITU-T Rec. X.667 | ISO/IEC 9834-8.

Format[edit]

In its canonical textual representation, the 16 octets of a UUID are represented as 32 hexadecimal (base-16) digits, displayed in five groups separated by hyphens, in the form 8-4-4-4-12 for a total of 36 characters (32 hexadecimal characters and 4 hyphens). For example:

123e4567-e89b-12d3-a456-426614174000
xxxxxxxx-xxxx-Mxxx-Nxxx-xxxxxxxxxxxx

The four-bit M and the 1- to 3-bit N fields code the format of the UUID itself.

The four bits of digit M are the UUID version, and the 1 to 3 most significant bits of digit N code the UUID variant. (See below.) In the example above, M is 1, and N is a (10xx2), meaning that this is a version-1, variant-1 UUID; that is, a time-based DCE/RFC 4122 UUID.

The canonical 8-4-4-4-12 format string is based on the record layout for the 16 bytes of the UUID:[1]

UUID record layout

Name Length (bytes) Length (hex digits) Length (bits) Contents
time_low 4 8 32 integer giving the low 32 bits of the time
time_mid 2 4 16 integer giving the middle 16 bits of the time
time_hi_and_version 2 4 16 4-bit «version» in the most significant bits, followed by the high 12 bits of the time
clock_seq_hi_and_res clock_seq_low 2 4 16 1 to 3-bit «variant» in the most significant bits, followed by the 13 to 15-bit clock sequence
node 6 12 48 the 48-bit node id

These fields correspond to those in version 1 and 2 UUIDs (that is, time-based UUIDs), but the same 8-4-4-4-12 representation is used for all UUIDs, even for UUIDs constructed differently.

RFC 4122 Section 3 requires that the characters be generated in lower case, while being case-insensitive on input.

Microsoft GUIDs are sometimes represented with surrounding braces:

{123e4567-e89b-12d3-a456-426652340000}

This format should not be confused with «Windows Registry format», which refers to the format within the curly braces.[8]

RFC 4122 defines a Uniform Resource Name (URN) namespace for UUIDs. A UUID presented as a URN appears as follows:[1]

urn:uuid:123e4567-e89b-12d3-a456-426655440000

Encoding[edit]

The binary encoding of UUIDs varies between systems. Variant 1 UUIDs, nowadays the most common variant, are encoded in a big-endian format. For example, 00112233-4455-6677-8899-aabbccddeeff is encoded as the bytes 00 11 22 33 44 55 66 77 88 99 aa bb cc dd ee ff.[9][10]

Variant 2 UUIDs, historically used in Microsoft’s COM/OLE libraries, use a little-endian format, but appear mixed-endian with the first three components of the UUID as little-endian and last two big-endian, due to the missing byte dashes when formatted as a string.[11] For example, 00112233-4455-6677-c899-aabbccddeeff is encoded as the bytes 33 22 11 00 55 44 77 66 88 99 aa bb cc dd ee ff.[12][13] See the section on Variants for details on why the ’88’ byte becomes ‘c8’ in Variant 2.

Variants[edit]

The «variant» field of UUIDs, or the N position indicate their format and encoding. RFC 4122 defines four variants of lengths 1 to 3 bits:

  • Variant 0 (indicated by the one-bit pattern 0xxx2, N = 0..7) is for backwards compatibility with the now-obsolete Apollo Network Computing System 1.5 UUID format developed around 1988. The first 6 octets of the UUID are a 48-bit timestamp (the number of 4-microsecond units of time since 1 January 1980 UTC); the next 2 octets are reserved; the next octet is the «address family»; and the final 7 octets are a 56-bit host ID in the form specified by the address family. Though different in detail, the similarity with modern version-1 UUIDs is evident. The variant bits in the current UUID specification coincide with the high bits of the address family octet in NCS UUIDs. Though the address family could hold values in the range 0..255, only the values 0..13 were ever defined. Accordingly, the variant-0 bit pattern 0xxx avoids conflicts with historical NCS UUIDs, should any still exist in databases.[14]
  • Variant 1 (10xx2, N = 8..b, 2 bits) are referred to as RFC 4122/DCE 1.1 UUIDs, or «Leach–Salz» UUIDs, after the authors of the original Internet Draft.
  • Variant 2 (110x2, N = c..d, 3 bits) is characterized in the RFC as «reserved, Microsoft Corporation backward compatibility» and was used for early GUIDs on the Microsoft Windows platform. It differs from variant 1 only by the endianness in binary storage or transmission: variant-1 UUIDs use «network» (big-endian) byte order, while variant-2 GUIDs use «native» (little-endian) byte order for some subfields of the UUID.
  • Reserved is defined as the 3-bit variant bit pattern 111x2 (N = e..f).

Variants 1 and 2 are used by the current UUID specification. In their textual representations, variants 1 and 2 are the same, except for the variant bits. In the binary representation, there is an endianness difference.[1] When byte swapping is required to convert between the big-endian byte order of variant 1 and the little-endian byte order of variant 2, the fields above define the swapping. The first three fields are unsigned 32- and 16-bit integers and are subject to swapping, while the last two fields consist of uninterpreted bytes, not subject to swapping. This byte swapping applies even for versions 3, 4, and 5, where the canonical fields do not correspond to the content of the UUID.[1]

While some important GUIDs, such as the identifier for the Component Object Model IUnknown interface, are nominally variant-2 UUIDs, many identifiers generated and used in Microsoft Windows software and referred to as «GUIDs» are standard variant-1 RFC 4122/DCE 1.1 network-byte-order UUIDs, rather than little-endian variant-2 UUIDs. The current version of the Microsoft guidgen tool produces standard variant-1 UUIDs. Some Microsoft documentation states that «GUID» is a synonym for «UUID»,[15] as standardized in RFC 4122. RFC 4122 itself states that UUIDs «are also known as GUIDs». All this suggests that «GUID», while originally referring to a variant of UUID used by Microsoft, has become simply an alternative name for UUID, with both variant-1 and variant-2 GUIDs being extant.

Versions[edit]

For both variants 1 and 2, five «versions» are defined in the standards, and each version may be more appropriate than the others in specific use cases. Version is indicated by the M in the string representation.

Version-1 UUIDs are generated from a time and a node ID (usually the MAC address); version-2 UUIDs are generated from an identifier (usually a group or user ID), time, and a node ID; versions 3 and 5 produce deterministic UUIDs generated by hashing a namespace identifier and name; and version-4 UUIDs are generated using a random or pseudo-random number.

Nil UUID[edit]

The «nil» UUID, a special case, is the UUID 00000000-0000-0000-0000-000000000000; that is, all bits set to zero.[1]

Version 1 (date-time and MAC address)[edit]

Version 1 concatenates the 48-bit MAC address of the «node» (that is, the computer generating the UUID), with a 60-bit timestamp, being the number of 100-nanosecond intervals since midnight 15 October 1582 Coordinated Universal Time (UTC), the date on which the Gregorian calendar was first adopted outside the Catholic Church and Papal States. RFC 4122 states that the time value rolls over around 3400 AD,[1]: 3 depending on the algorithm used, which implies that the 60-bit timestamp is a signed quantity. However some software, such as the libuuid library, treats the timestamp as unsigned, putting the rollover time in 5623 AD.[16] The rollover time as defined by ITU-T Rec. X.667 is 3603 AD.[17]: v

A 13-bit or 14-bit «uniquifying» clock sequence extends the timestamp in order to handle cases where the processor clock does not advance fast enough, or where there are multiple processors and UUID generators per node. When UUIDs are generated faster than the system clock could advance, the lower bits of the timestamp fields can be generated by incrementing it every time a UUID is being generated, to simulate a high-resolution timestamp. With each version 1 UUID corresponding to a single point in space (the node) and time (intervals and clock sequence), the chance of two properly generated version-1 UUIDs being unintentionally the same is practically nil. Since the time and clock sequence total 74 bits, 274 (1.8×1022, or 18 sextillion) version-1 UUIDs can be generated per node ID, at a maximal average rate of 163 billion per second per node ID.[1]

In contrast to other UUID versions, version-1 and -2 UUIDs based on MAC addresses from network cards rely for their uniqueness in part on an identifier issued by a central registration authority, namely the Organizationally Unique Identifier (OUI) part of the MAC address, which is issued by the IEEE to manufacturers of networking equipment.[18] The uniqueness of version-1 and version-2 UUIDs based on network-card MAC addresses also depends on network-card manufacturers properly assigning unique MAC addresses to their cards, which like other manufacturing processes is subject to error. Additionally some operating system permit the end user to customise the MAC address, notably OpenWRT.[19]

Usage of the node’s network card MAC address for the node ID means that a version-1 UUID can be tracked back to the computer that created it. Documents can sometimes be traced to the computers where they were created or edited through UUIDs embedded into them by word processing software. This privacy hole was used when locating the creator of the Melissa virus.[20]

RFC 4122 does allow the MAC address in a version-1 (or 2) UUID to be replaced by a random 48-bit node ID, either because the node does not have a MAC address, or because it is not desirable to expose it. In that case, the RFC requires that the least significant bit of the first octet of the node ID should be set to 1.[1] This corresponds to the multicast bit in MAC addresses, and setting it serves to differentiate UUIDs where the node ID is randomly generated from UUIDs based on MAC addresses from network cards, which typically have unicast MAC addresses.[1]

Version 2 (date-time and MAC address, DCE security version)[edit]

RFC 4122 reserves version 2 for «DCE security» UUIDs; but it does not provide any details. For this reason, many UUID implementations omit version 2. However, the specification of version-2 UUIDs is provided by the DCE 1.1 Authentication and Security Services specification.[6]

Version-2 UUIDs are similar to version 1, except that the least significant 8 bits of the clock sequence are replaced by a «local domain» number, and the least significant 32 bits of the timestamp are replaced by an integer identifier meaningful within the specified local domain. On POSIX systems, local-domain numbers 0 and 1 are for user ids (UIDs) and group ids (GIDs) respectively, and other local-domain numbers are site-defined.[6] On non-POSIX systems, all local domain numbers are site-defined.

The ability to include a 40-bit domain/identifier in the UUID comes with a tradeoff. On the one hand, 40 bits allow about 1 trillion domain/identifier values per node ID. On the other hand, with the clock value truncated to the 28 most significant bits, compared to 60 bits in version 1, the clock in a version 2 UUID will «tick» only once every 429.49 seconds, a little more than 7 minutes, as opposed to every 100 nanoseconds for version 1. And with a clock sequence of only 6 bits, compared to 14 bits in version 1, only 64 unique UUIDs per node/domain/identifier can be generated per 7-minute clock tick, compared to 16,384 clock sequence values for version 1.[21] Thus, Version 2 may not be suitable for cases where UUIDs are required, per node/domain/identifier, at a rate exceeding about one every seven minutes.

Versions 3 and 5 (namespace name-based)[edit]

Version-3 and version-5 UUIDs are generated by hashing a namespace identifier and name. Version 3 uses MD5 as the hashing algorithm, and version 5 uses SHA-1.[1]

The namespace identifier is itself a UUID. The specification provides UUIDs to represent the namespaces for URLs, fully qualified domain names, object identifiers, and X.500 distinguished names; but any desired UUID may be used as a namespace designator.

To determine the version-3 UUID corresponding to a given namespace and name, the UUID of the namespace is transformed to a string of bytes, concatenated with the input name, then hashed with MD5, yielding 128 bits. Then 6 or 7 bits are replaced by fixed values, the 4-bit version (e.g. 00112 for version 3), and the 2- or 3-bit UUID «variant» (e.g. 102 indicating a RFC 4122 UUIDs, or 1102 indicating a legacy Microsoft GUID). Since 6 or 7 bits are thus predetermined, only 121 or 122 bits contribute to the uniqueness of the UUID.

Version-5 UUIDs are similar, but SHA-1 is used instead of MD5. Since SHA-1 generates 160-bit digests, the digest is truncated to 128 bits before the version and variant bits are replaced.

Version-3 and version-5 UUIDs have the property that the same namespace and name will map to the same UUID. However, neither the namespace nor name can be determined from the UUID, even if one of them is specified, except by brute-force search. RFC 4122 recommends version 5 (SHA-1) over version 3 (MD5), and warns against use of UUIDs of either version as security credentials.[1]

Version 4 (random)[edit]

A version 4 UUID is randomly generated. As in other UUIDs, 4 bits are used to indicate version 4, and 2 or 3 bits to indicate the variant (102 or 1102 for variants 1 and 2 respectively). Thus, for variant 1 (that is, most UUIDs) a random version-4 UUID will have 6 predetermined variant and version bits, leaving 122 bits for the randomly generated part, for a total of 2122, or 5.3×1036 (5.3 undecillion) possible version-4 variant-1 UUIDs. There are half as many possible version-4 variant-2 UUIDs (legacy GUIDs) because there is one less random bit available, 3 bits being consumed for the variant.

Collisions[edit]

Collision occurs when the same UUID is generated more than once and assigned to different referents. In the case of standard version-1 and version-2 UUIDs using unique MAC addresses from network cards, collisions are unlikely to occur, with an increased possibility only when an implementation varies from the standards, either inadvertently or intentionally.

In contrast to version-1 and version-2 UUIDs generated using MAC addresses, with version-1 and -2 UUIDs which use randomly generated node ids, hash-based version-3 and version-5 UUIDs, and random version-4 UUIDs, collisions can occur even without implementation problems, albeit with a probability so small that it can normally be ignored. This probability can be computed precisely based on analysis of the birthday problem.[22]

For example, the number of random version-4 UUIDs which need to be generated in order to have a 50% probability of at least one collision is 2.71 quintillion, computed as follows:[23]

{displaystyle napprox {frac {1}{2}}+{sqrt {{frac {1}{4}}+2times ln(2)times 2^{122}}}approx 2.71times 10^{18}.}

This number is equivalent to generating 1 billion UUIDs per second for about 86 years. A file containing this many UUIDs, at 16 bytes per UUID, would be about 45 exabytes.

The smallest number of version-4 UUIDs which must be generated for the probability of finding a collision to be p is approximated by the formula

{displaystyle {sqrt {2times 2^{122}times ln {frac {1}{1-p}}}}.}

Thus, the probability to find a duplicate within 103 trillion version-4 UUIDs is one in a billion.

Uses[edit]

File systems[edit]

Significant uses include ext2/ext3/ext4 filesystem userspace tools (e2fsprogs uses libuuid provided by util-linux), LVM, LUKS encrypted partitions, GNOME, KDE, and macOS,[24] most of which are derived from the original implementation by Theodore Ts’o.[16]

One of the uses of UUIDs in Solaris (using Open Software Foundation implementation) is identification of a running operating system instance for the purpose of pairing crash dump data with Fault Management Event in the case of kernel panic.[25]

The «partition label» and the «partition UUID» are both stored in the superblock. They are both part of the file system rather than of the partition. For example, ext2–4 contain a UUID, while NTFS or FAT32 do not.

The superblock is a part of the file system, thus fully contained within the partition, hence doing dd if=/dev/sda1 of=/dev/sdb1 leaves both sda1 and sdb1 with the same label and UUID.

In COM[edit]

There are several flavors of GUIDs used in Microsoft’s Component Object Model (COM):

  • IID – interface identifier; (The ones that are registered on a system are stored in the Windows Registry at [HKEY_CLASSES_ROOTInterface][26] )
  • CLSID – class identifier; (Stored at [HKEY_CLASSES_ROOTCLSID])
  • LIBID – type library identifier; (Stored at [HKEY_CLASSES_ROOTTypeLib][27])
  • CATID – category identifier; (its presence on a class identifies it as belonging to certain class categories, listed at [HKEY_CLASSES_ROOTComponent Categories][28])

As database keys[edit]

UUIDs are commonly used as a unique key in database tables. The NEWID function in Microsoft SQL Server version 4 Transact-SQL returns standard random version-4 UUIDs, while the NEWSEQUENTIALID function returns 128-bit identifiers similar to UUIDs which are committed to ascend in sequence until the next system reboot.[29] The Oracle Database SYS_GUID function does not return a standard GUID, despite the name. Instead, it returns a 16-byte 128-bit RAW value based on a host identifier and a process or thread identifier, somewhat similar to a GUID.[30] PostgreSQL contains a UUID datatype[31] and can generate most versions of UUIDs through the use of functions from modules.[32][33] MySQL provides a UUID function, which generates standard version-1 UUIDs.[34]

The random nature of standard UUIDs of versions 3, 4, and 5, and the ordering of the fields within standard versions 1 and 2 may create problems with database locality or performance when UUIDs are used as primary keys. For example, in 2002 Jimmy Nilsson reported a significant improvement in performance with Microsoft SQL Server when the version-4 UUIDs being used as keys were modified to include a non-random suffix based on system time. This so-called «COMB» (combined time-GUID) approach made the UUIDs non-standard and significantly more likely to be duplicated, as Nilsson acknowledged, but Nilsson only required uniqueness within the application.[35] By reordering and encoding version 1 and 2 UUIDs so that the timestamp comes first, insertion performance loss can be averted.[36]

Some web frameworks, such as Laravel, have support for «timestamp first» UUIDs that may be efficiently stored in an indexed database column. This makes a COMB UUID using version 4 format, but where the first 48-bits make up a timestamp laid out like in UUIDv1.[37][38] More specified formats based on the COMB UUID idea include:

  • «ULID», which ditches the 4 bits used to indicate version 4, and uses a base32 encoding by default.[39]
  • UUID versions 6 through 8, a formal proposal of three COMB UUID formats.[40]

See also[edit]

  • Birthday attack
  • Object identifier (OID)
  • Uniform Resource Identifier (URI)
  • Snowflake ID

References[edit]

  1. ^ a b c d e f g h i j k l m n Leach, P.; Mealling, M.; Salz, R. (2005). A Universally Unique IDentifier (UUID) URN Namespace. Internet Engineering Task Force. doi:10.17487/RFC4122. RFC 4122. Retrieved 17 January 2017.
  2. ^ «Universally Unique Identifiers (UUID)». H2. Retrieved 21 March 2021.
  3. ^ ITU-T Recommendation X.667: Generation and registration of Universally Unique Identifiers (UUIDs) and their use as ASN.1 Object Identifier components. Standard. October 2012.
  4. ^ Zahn, Lisa (1990). Network Computing Architecture. Prentice Hall. p. 10. ISBN 978-0-13-611674-5.
  5. ^ «CDE 1.1: Remote Procedure Call». The Open Group. 1997.
  6. ^ a b c «DCE 1.1: Authentication and Security Services». The Open Group. 1997.
  7. ^ «ITU-T Study Group 17 — Object Identifiers (OID) and Registration Authorities Recommendations». ITU.int. Retrieved 28 March 2023.
  8. ^ «Registry Keys and Entries for a Type 1 Online Store». Microsoft Developer Network. Microsoft.
  9. ^ Steele, Nick. «Breaking Down UUIDs».
  10. ^ «UUID Versions Explained».
  11. ^ Chen, Raymond. «Why does COM express GUIDs in a mix of big-endian and little-endian? Why can’t it just pick a side and stick with it?». The Old New Thing. Retrieved 31 October 2022.
  12. ^ Leach, Paul. «UUIDs and GUIDs».
  13. ^ «Guid.ToByteArray Method».
  14. ^ «uuid.c».
  15. ^ «Globally Unique Identifiers». Microsoft Developer Network. Microsoft.
  16. ^ a b «ext2/e2fsprogs.git — Ext2/3/4 filesystem userspace utilities». Kernel.org. Retrieved 9 January 2017.
  17. ^ «Recommendation ITU-T X.667». www.itu.int. October 2012. Retrieved 19 December 2020.
  18. ^
    «Registration Authority». IEEE Standards Association.
  19. ^ «MAC Address Setup». OpenWRT. 15 September 2021.{{cite web}}: CS1 maint: url-status (link)
  20. ^ Reiter, Luke (2 April 1999). «Tracking Melissa’s Alter Egos». ZDNet. Retrieved 16 January 2017.
  21. ^ Kuchling, A. M. «What’s New in Python 2.5». Python.org. Retrieved 23 January 2016.
  22. ^ Jesus, Paulo; Baquero, Carlos; Almaeida, Paulo. «ID Generation in Mobile Environments» (PDF). Repositorium.Sdum.Uminho.pt.
  23. ^ Mathis, Frank H. (June 1991). «A Generalized Birthday Problem». SIAM Review. 33 (2): 265–270. CiteSeerX 10.1.1.5.5851. doi:10.1137/1033051. ISSN 0036-1445. JSTOR 2031144. OCLC 37699182.
  24. ^ gen_uuid.c in Apple’s Libc-391, corresponding to Mac OS X 10.4
  25. ^ «Crashdump Restructuring in Solaris». Blogs.Oracle.com. Oracle. Retrieved 9 January 2017.
  26. ^ «Interface Pointers and Interfaces». Windows Dev Center — Desktop app technologies. Microsoft. Retrieved 15 December 2015. You reference an interface at run time with a globally unique interface identifier (IID). This IID, which is a specific instance of a globally unique identifier (GUID) supported by COM, allows a client to ask an object precisely whether it supports the semantics of the interface, without unnecessary overhead and without the confusion that could arise in a system from having multiple versions of the same interface with the same name.
  27. ^ «Registering a Type Library». Microsoft Developer Network. Microsoft. Retrieved 15 December 2015.
  28. ^ «Categorizing by Component Capabilities». Windows Dev Center — Desktop app technologies. Microsoft. Retrieved 15 December 2015. A listing of the CATIDs and the human-readable names is stored in a well-known location in the registry.
  29. ^ «NEWSEQUENTIALID (Transact-SQL)». Microsoft Developer Network. Microsoft. 8 August 2015. Retrieved 14 January 2017.
  30. ^ «Oracle Database SQL Reference». Oracle.
  31. ^ «Section 8.12 UUID Type». PostgreSQL 9.4.10 Documentation. PostgreSQL Global Development Group. 13 February 2020.
  32. ^ «uuid-ossp». PostgreSQL: Documentation: 9.6. PostgreSQL Global Development Group. 12 August 2021.
  33. ^ «pgcrypto». PostgreSQL: Documentation: 9.6. PostgreSQL Global Development Group. 12 August 2021.
  34. ^ «Section 13.20 Miscellaneous Functions». MySQL 5.7 Reference Manual. Oracle Corporation.
  35. ^ Nilsson, Jimmy (8 March 2002). InformIT. InformIT. Retrieved 20 June 2012.
  36. ^ «Storing UUID Values in MySQL». Percona. 19 December 2014. Archived from the original on 29 November 2020. Retrieved 10 February 2021.
  37. ^ «Helpers — Laravel — The PHP Framework For Web Artisans». Laravel.com.
  38. ^ Cabrera, Italo Baeza (31 January 2020). «Laravel: The mysterious «Ordered UUID»«. Medium.
  39. ^ «Universally Unique Lexicographically Sortable Identifier». GitHub. ULID. 10 May 2021.
  40. ^ Peabody, Brad; Davis, Kyzer R. (7 October 2021). «draft-peabody-dispatch-new-uuid-format-01». tools.ietf.org.

External links[edit]

Standards

  • Recommendation ITU-T X.667 (Free access)
  • ISO/IEC 9834-8:2014 (Paid)

ITU-T UUID Generator

  • Universally Unique Identifiers (UUIDs)

Technical Articles

  • Technical Note TN2166 — Secrets of the GPT — Apple Developer
  • UUID Documentation — Apache Commons Id
  • CLSID Key — Microsoft Docs
  • Universal Unique Identifier — The Open Group Library

Miscellaneous

  • UUID Decoder tool
  • A Brief History of the UUID
  • Understanding How UUIDs Are Generated

Implementation in various languages

  • Golang — google/uuid
  • PHP — ramsey/uuid
  • C++ — Boost UUID
  • Linux or C — libuuid
  • Python — uuid.py
  • Java — java.util.UUID
  • C# — System.Guid
  • JavaScript — Crypto.randomUUID


Asked by: Dr. Casimer Von

Score: 5/5
(30 votes)

A universally unique identifier (UUID) is a 128-bit label used for information in computer systems. The term globally unique identifier (GUID) is also used, often in software created by Microsoft.

What is a GUID number?

(Globally Unique IDentifier) An implementation of the universally unique ID (see UUID) that is computed by Windows and Windows applications. Using a pseudo-random 128-bit number, GUIDs are used to identify user accounts, documents, software, hardware, software interfaces, sessions, database keys and other items.

How do I generate a GUID?

Mapping the components to a GUID

  1. Convert the name into bytes. …
  2. Convert the namespace into bytes. …
  3. Concatenate them and hash using the correct hashing method. …
  4. Break up the hash into the main components of a GUID, timestamp, clock sequence, and node ID. …
  5. Insert the timestamp component into the GUID: 2ed6657de927468b.

What is GUID example?

Types of GUIDs

To identify the version of the GUID, just look at the version digit e.g version 4 GUIDs have the format xxxxxxxx-xxxx-4xxx-Nxxx-xxxxxxxxxxxx where N is one of 8,9,A, or B. This version is generated using both the current time and client MAC address.

Can GUID be same?

Theoretically, no, they are not unique. It’s possible to generate an identical guid over and over. … From there (via Wikipedia), the odds of generating a duplicate GUID: 1 in 2^128.

40 related questions found

How do you ensure GUID is unique?

How unique is a GUID? 128-bits is big enough and the generation algorithm is unique enough that if 1,000,000,000 GUIDs per second were generated for 1 year the probability of a duplicate would be only 50%. Or if every human on Earth generated 600,000,000 GUIDs there would only be a 50% probability of a duplicate.

What does GUID stand for?

Abbreviation(s) and Synonym(s): Global Unique Identification number show sources. NIST SP 800-73-4, NIST SP 800-85B.

What is a GUID value?

GUID is a 16 byte binary SQL Server data type that is globally unique across tables, databases, and servers. … As mentioned earlier, GUID values are unique across tables, databases, and servers. GUIDs can be considered as global primary keys. Local primary keys are used to uniquely identify records within a table.

How secure is a GUID?

GUIDs are designed for uniqueness, not for security. For example, we saw that substrings of GUIDs are not unique. For example, in the classic v1 algorithm, the first part of the GUID is a timestamp. … If you want something cryptographically secure, then use a cryptographically-secure random number.

What is an empty GUID?

You can use Guid.Empty . It is a read-only instance of the Guid structure with the value of 00000000-0000-0000-0000-000000000000.

What is a valid GUID?

The valid GUID (Globally Unique Identifier) must specify the following conditions: It should be a 128-bit number. It should be 36 characters (32 hexadecimal characters and 4 hyphens) long. It should be displayed in five groups separated by hyphens (-). Microsoft GUIDs are sometimes represented with surrounding braces.

What data type is a GUID?

The GUID data type is a 16 byte binary data type. This data type is used for the global identification of objects, programs, records, and so on. The important property of a GUID is that each value is globally unique. The value is generated by an algorithm, developed by Microsoft, which assures this uniqueness.

How many GUID combinations are there?

Question: How many GUID combinations are there? Answer: There are 122 random bits (128 – 2 for variant – 4 for version) so this calculates to 2^122 or 5,316,911,983,139,663,491,615,228,241,121,400,000 possible combinations.

How do I find my device GUID?

To find the graphics device GUID your will first need to run the dxdiag tool. You can run the tool by typing Win Key + R . Enter dxdiag in the box and hit «OK». Once the tool is open select «Save All Information».

What is a PC GUID?

A Globally Unique Identifier (GUID) is a unique ID that is computed by Windows and Windows applications. It’s a 128-bit number used to identify user accounts, documents, software, hardware, database entries, sessions, and other items. … GUID may also be referred to as a Universally Unique Identifier (UUID).

How long is a character GUID?

That’s 36 characters in any GUID—they are of constant length. You can read a bit more about the intricacies of GUIDs here. You will need two more in length if you want to store the braces. Note: 36 is the string length with the dashes in between.

What are the odds of guessing a GUID?

The odds of guessing any one GUID is 1 / 2^128. This assumes that each single byte of the GUID is truly random. To ensure that GUIDs are unique among hosts, most parts of a UUID are actually fixed (e.g. a MAC address).

Will we ever run out of GUIDs?

Absolutely. Even if only one GUID is generated per second, we’ll run out in a scant 9 quintillion years. That’s well before the heat death of the Universe.

What is GUID in Visual Studio?

When working in applications you might often need to use Globally Unique Identifiers (GUIDs). Unique identifiers like primary keys in a SQL database ensure that important objects like customers and invoices are not duplicated or overwritten.

What is a GUID unity?

Unity GUID is a Globally Unique Identifier for the asset. Scenes, Prefabs, and other Unity files (assets) reference to Asset GUIDs to uniquely identify files within a single project and between different projects (also, with help of code GUID can be used for cross-scene referencing for Game Objects).

What is Active Directory GUID?

GUIDs are assigned to every object that is created by Active Directory, not only User and Group objects. Each object’s GUID is stored in its ObjectGUID property. Active Directory uses GUIDs internally to identify objects. For example, the GUID is one of an object’s properties that is published in the global catalog.

What is GUID and COM stands for?

A universally unique identifier (UUID) is a 128-bit label used for information in computer systems. The term globally unique identifier (GUID) is also used, often in software created by Microsoft.

Is GUID a word?

Yes, guid is in the scrabble dictionary.

What is the use of GUID how it is generated?

A GUID (globally unique identifier) is a 128-bit text string that represents an identification (ID). Organizations generate GUIDs when a unique reference number is needed to identify information on a computer or network. A GUID can be used to ID hardware, software, accounts, documents and other items.

Which version of UUID should I use?

If you need to generate reproducible UUIDs from given names, you want a version 3 or version 5. Version 3: This generates a unique ID from an MD5 hash of a namespace and name. If you need backwards compatibility (with another system that generates UUIDs from names), use this.

Содержание

  1. Гуиды что это значит
  2. Содержание
  3. Реализация Microsoft
  4. Другие реализации
  5. Примечания
  6. Ссылки
  7. Полезное
  8. Смотреть что такое «GUID» в других словарях:
  9. GUID Меркурий. Как узнать GUID ГУИД Меркурий
  10. Что такое GUID код Меркурий
  11. Как узнать и где найти ГУИД (GUID) Меркурий. Хозяйствующего субъекта (организации).
  12. Как и где узнать GUID ГУИД предприятия (места осуществления деятельности, площадки, поднадзорного объекта) в Меркурий
  13. Если не получилось зайти в Цербер и Меркурий ХС и нет регистрации в Меркурий. Поможем зарегистрироваться в Меркурий и получить GUID организации (хозяйствующего субъекта) и ГУИД предприятия (места осуществления деятельности
  14. Как мы будем регистрировать Вашу организацию и места осуществления деятельности в Меркурий:
  15. Евангелие от GUID
  16. Евангелие от GUID
  17. I. Всегда используй GUID для уникальной идентификации строки таблицы.
  18. 1) Мне не нужно совершать дополнительных выборок, а это — увеличение производительности!
  19. 2) Объединение данных настолько просто, что получается даже у Мак-разработчиков!
  20. 3) Типо-независимость
  21. 4) Удар, удар, еще удар. (с)
  22. Ну а есть ли недостатки у GUID?

Гуиды что это значит

Эту страницу предлагается объединить с UUID.

GUID (Globally Unique Identifier) — статистически уникальный 128-битный идентификатор. Его главная особенность — уникальность, которая позволяет создавать расширяемые сервисы и приложения без опасения конфликтов, вызванных совпадением идентификаторов. Хотя уникальность каждого отдельного GUID не гарантируется, общее количество уникальных ключей настолько велико (2 128 или 3,4028×10 38 ), что вероятность того, что в мире будут независимо сгенерированы два совпадающих ключа, крайне мала. Тем не менее, случаи совпадения были: на системе Windows 95 GUID’ы ярлыка запуска DOS-программ (.pif) и программы ZipMagic 2000 совпадали.

«GUID» называют некоторые реализации стандарта, имеющего название Universally Unique Identifier (UUID).

В тексте GUID записывается в виде строки из тридцати двух шестнадцатеричных цифр, разбитых на группы дефисами, и окружённой фигурными скобками:

Содержание

Реализация Microsoft

Например, ‘22345200-abe8-4f60-90c8-0d43c5f6c0f6’ [1] соответствует шестнадцатеричному 128-битному числу 0x00523422E8AB604F90C80D43C5F6C0F6

Максимальное значение в GUID соответствует десятичному числу 340 282 366 920 938 463 463 374 607 431 768 211 455.

Microsoft применяет GUID в OLE, COM и DCOM — например, в качестве идентификаторов для классов (CLSID), интерфейсов (IID), библиотек типов (LIBID). Использование GUID гарантирует, что две (возможно, несовместимые) версии одного компонента могут иметь одно и то же имя, но быть отличимыми по GUID.

Алгоритм, который Microsoft использовала для генерации GUID, был широко раскритикован. В частности, в качестве основы для генерации части цифр GUID использовался MAC-адрес сетевого адаптера, что означало, например, что по данному документу MS Word (также получающему при создании свой уникальный GUID) можно было определить компьютер, на котором он был создан. Позже Microsoft изменила алгоритм таким образом, чтобы он не включал в себя MAC-адрес.

Другие реализации

Также GUID — основа Таблицы разделов GUID, замены MBR в EFI.

Примечания

  1. 12 Последнее 8-байтное данное при записи часто разбивается на 2+6 (подробнее см. в английской версии статьи)

Ссылки

Wikimedia Foundation . 2010 .

Полезное

Смотреть что такое «GUID» в других словарях:

guid — guid; guid·able; guid·ance; guid·er; guid·man; guid·sire; guid·wife; guid·willie; lan·guid·ly; lan·guid·ness; mis·guid·ance; pin·guid; pin·guid·i·ty; lan·guid; mis·guid·ed·ly; mis·guid·ed·ness; mis·guid·er; … English syllables

GUID — [Abk. für Global Unique Identifier], globale Identifikation … Universal-Lexikon

guid|er — «GY duhr», noun. 1. a person or thing that guides; guide; leader. 2. Guider, an adult leader associated with the Girl Guides … Useful english dictionary

GUID — Globally Unique Identifier Un GUID (abréviation de l anglais Globally Unique IDentifier) sert habituellement d identifiant unique pour un composant logiciel, par exemple un plugin. Sa taille est de 16 octets, soit 128 bits, décomposés en… … Wikipédia en Français

GUID — Ein Globally Unique Identifier (GUID) ist eine global eindeutige Zahl mit 128 Bit (das sind 16 Bytes), die in verteilten Computersystemen zum Einsatz kommt. GUID stellt eine Implementierung des Universally Unique Identifier Standards (UUID) dar.… … Deutsch Wikipedia

Guid — Ein Globally Unique Identifier (GUID) ist eine global eindeutige Zahl mit 128 Bit (das sind 16 Bytes), die in verteilten Computersystemen zum Einsatz kommt. GUID stellt eine Implementierung des Universally Unique Identifier Standards (UUID) dar.… … Deutsch Wikipedia

guid — ˈgœ̅d, ˈgu̅e̅d, ˈgid Scotland variant of good * * * guid «good», adjective, noun, interjection, adverb. Scottish. good. * * * guid Sc. form of good … Useful english dictionary

GUID — ● ►en sg. m. ►INTERNET Globally Unique IDentifier. À ce que j ai compris, c est un bidule inventé par Microsoft. Selon eux, différents types d objets ont différents types de GUID . Ça veut dire quoi, globally ? En pratique, cela sert à identifier … Dictionnaire d’informatique francophone

guid — noun A flower … Wiktionary

GUID — Globally Unique Identifier (Computing » Drivers) … Abbreviations dictionary

Источник

GUID Меркурий. Как узнать GUID ГУИД Меркурий

Что такое GUID код Меркурий

Как в нашей стране для учета организаций используется, специальный учетный номер ИНН, так и в системе ФГИС Меркурий для внутреннего учета внутри Россельхознадзор разработал специальные учетные номера Гуиды, с помощью которых учитывается каждая организация (Хозяйствующий субъект) и её места осуществления деятельности (Поднадзорные объекты, площадки, предприятия).

GUID (ГУИД) — это глобальный уникальный идентификатор , это набор символов код, состоящий из 32 символов, который идентифицирует либо саму организацию, либо её место осуществления деятельности.

Гуиды бывают нескольких уровней например:

  • GUID организации это 3й уровень
  • GUID места осуществления деятельности (поднадзорного объекта, площадки, предприятия) это 4й уровень

Как узнать и где найти ГУИД (GUID) Меркурий. Хозяйствующего субъекта (организации).

Чтобы узнать GUID самой организации, нужно будет зайти в систему Россельхознадзора Ветис Цербер по ссылке , он представляет собой единую информационную базу адресов всех организаций и их мест осуществления деятельности. Нажимаем на зеленую кнопку Цербера начать работу и нажимаем на кнопку Личный кабинет.

Далее осуществляем вход в Меркурий Цербер, войти в него можно по логину и паролю, который Вы используете для входа в Меркурий ХС. Если у Вас нет логина и пароля для входа, возможно Вы не зарегистрированы в Меркурий и тогда Вам прежде нужно будет зарегистрироваться, а потом узнавать номер гуид в Меркурий. В общем в полях имя пользователя и пароль вводим логин и пароль и нажимаем войти, возможно войти не получится, это значит, что данному пользователю в системе Ветис Паспорт не были проставлены права на право пользования системой Цербер. В этом случае узнавайте номер GUID хозяйствующего субъекта у своего местного управления Россельхознадзора.

После того как получилось осуществить вход в личный кабинет Меркурий Цербер, выбираем нужную нам организацию, по которой нужно GUID код Меркурий.

Для того, чтобы узнать гуид код Меркурий организации выбираем раздел Хозяйствующий субъект и ниже в Цербере в разделе служебная информация будет отображаться GUID Меркурий Хозяйствующего субъекта (самой организации), Вы можете его скопировать и дать своим поставщикам, чтобы они Вас находили в Меркурий.

Как и где узнать GUID ГУИД предприятия (места осуществления деятельности, площадки, поднадзорного объекта) в Меркурий

Чтобы узнать GUID предприятия (места осуществления деятельности, площадки, поднадзорного объекта) нужно зайти в раздел Площадки и выбираем нужный адрес места осуществления деятельности.

В открывшемся окне ниже отображаться поле Глобальный идентификатор в системе это и есть GUID ГУИД предприятия Вашего, который нужно отправить поставщикам для обмена в Меркурий ХС, так же иногда просят номер площадки предприятия он указан выше можете так же его скопировать и дать поставщикам своим.

Есть второй вариант как узнать GUID ГУИД предприятия в Меркурий, если в Цербер Вы зайти не можете , узнать гуид предприятия можно через личный кабинет Меркурий ХС. Заходим в личный кабинет в Меркурий ХС по ссылке выбираем нужную организацию.

В открывшемся окне будет видно все места осуществления деятельности организации, чтобы узнать гуид предприятия нажимаем на зеленый значок, в итоге сохранится текстовый файлик, где первое в строке будет это guid гуид предприятия, скопируйте содержимое этого файла или просто отправьте этот файл своим поставщикам для обмена ВСД в Меркурий ХС.

Если у Вас нет логина и пароля для входа в Меркурий или при входе в Меркурий отображается только название организации, а мест осуществления деятельности нет, то возможно, Вы либо не зарегистрированы в Меркурий, либо регистрация не завершена до конца.

Если не получилось зайти в Цербер и Меркурий ХС и нет регистрации в Меркурий. Поможем зарегистрироваться в Меркурий и получить GUID организации (хозяйствующего субъекта) и ГУИД предприятия (места осуществления деятельности

Предлагаем Вам услугу по регистрации в Меркурий и получению ГУИД организации и мест осуществления деятельности. А так же поможем зарегистрировать Ваши места осуществления деятельности

Зарегистрируем Вашу организацию и места осуществления деятельности в Меркурий, и предоставим Гуиды!

Как мы будем регистрировать Вашу организацию и места осуществления деятельности в Меркурий:

  1. Вы отправляете заявку [ЗАПОЛНИТЬ ЗАЯВКУ] на регистрацию ИП, либо Юр лица в Меркурий , чтобы мы зарегистрировали Вас в Меркурии.
  2. C Вами связывается специалист по электронной почте и уточняет информацию о Вашей организации. Мы высылаем Вам счет за регистрацию в Меркурий.
  3. Вы оплачиваете счет. Мы готовим заявление для регистрации в Меркурий и отправляем его администратору системы Меркурий, копию заявления отправляем Вам, после ждем ответа от администратора, срок ответа от 5 дней до 14 (в зависимости от занятости).
  4. После получения ответа, мы регистрируем в системе Ветис Паспорт еще 2х сотрудников для Вашей организации, по окончанию регистрации предоставляем Вам GUID и UUID Вашей организации ХС для работы с поставщиками, а так же инструкции как работать в Меркурий ХС.

Посмотрите видео, там все рассказано

Источник

Евангелие от GUID

Разбираясь с новым Visual C# 2008 (он настолько бесплатный для начинающих разработчиков, что я не удержался), нашел новое для себя слово в науке и технике — GUID.

Привожу пример интересной, как мне кажется, статьи, призывающей использовать глобально-уникальные идентификаторы во всех сферах народного хозяйства. Статья, в основном про .NET и прочий микрософт, но, думаю, будет полезна многим здесь, ибо реализации GUID есть почти во всех современных БД и языках (включая mySQL и PHP ;).

ПС: Если будет интересно, то выложу перевод второй части, где автор отвечает на комменты к первой статье.

Евангелие от GUID

В Евангелие от GUID есть только одна заповедь:

I. Всегда используй GUID для уникальной идентификации строки таблицы.

При приеме новых сотрудников в команду это — одно из первых правил, которым я их обучаю. Почти всегда поначалу они смотрят на меня с видом щенка с торчащими ушами и склоненной набок головой, как бы говоря «как это?»

Поэтому я показываю им, что в каждой таблице есть поле, являющееся уникальным идентификатором, а в большинстве случаев и первичным ключом и, обычно, кластеризованным индексом. Например, в таблице Employee у нас будет поле EmployeeGUID, уникальный идентификатор и кластеризованный первичный ключ. Тут обычно я получаю в ответ взгляд «опа, мой новый босс идиот, но я не хочу, чтобы он знал, что я так думаю». Потом приходят вопросы и комментарии вида «но я обычно делаю так»:

  1. Я использую int
  2. Я не пользуюсь GUID, потому что они такие большие
  3. Разве вы не понимаете, как трудно искать запись по такому id, в случае с int это гораздо проще
  4. Ну вы же не станете их использовать в таблице, реализующей отношение многие-ко-многим?
  5. Что произойдет, если GUID’Ы закончатся?
  6. Я не уверен, что они не будут повторяться
  7. Я никогда ни о чем подобном не слышал, поэтому, скорее всего это плохая мысль.
  8. А это не ухудшит производительность?

И начинается моя миссия по обращению. У меня хорошая статистика по обращению «думающих» людей, поэтому призываю вас прочитать эту статью и, возможно, вы тоже станете верующим в GUID!

1) Мне не нужно совершать дополнительных выборок, а это — увеличение производительности!

Существует множество причин для использования GUID в качестве первичного ключа. Главная для меня напрямую связана с тем, как я строю объектные модели. Я предпочитаю создавать «new» экземпляр объекта без совершения выборки. Так, создавая объект Order (заказ) я не буду обращаться к базе данных для получения OrderID (OrderGUID в моем мире), как я бы делал в случае с int OrderID. На этом уровне еще не слишком впечатляет, да? Подумайте вот о чем: я создаю объект Order с OrderGUID, потом объекты OrderLineItem (строки заказа) с OrderLineItemGUID без ЕДИНОГО разрыва обращения к БД. В случае с int я бы сделал 11 обращений.

2) Объединение данных настолько просто, что получается даже у Мак-разработчиков!

Следующая причина всегда использовать GUID — объединение данных (merging), оказывавшееся необходимым бессчетное количество раз. До того как я увидел свет, я тоже использовал int или что-то еще, чтобы сделать строку уникальной, но когда мне приходилось сливать данные из раных источников, я делел специальные преобразования.

DB1 (Клиент 1):
Order (таблица заказов)
OrderID = 1
CustomerID = 1

DB2 (Клиент 2):
Order
OrderID = 1
CustomerID = 1

Если Клиент 1 приобретает Клиента 2 и мне нужно слить их данные в единую БД, мне придется поменять чьи-то OrderID и CustomerID на какие-нибудь int значения, которые не используюся, после чего сделать update большому количеству записей, а, возможно и поплясать с бубном и с опорными значениями (seed values). Умножьте это на десятки таблиц, учтите миллионы строк данных, и у бедитесь, что передо мной стоит ДЕЙСТВИТЕЛЬНО сложная задача, которая потребует дофига тестирования после написания SQL и/или кода.

Однако, если я следую Евангелию от GUID:

В этом случае, все, что нужно сделать сводится к обычной вставке всех строк из одной БД в другую. Никаких преобразований, никаких замороченных тестов, просто, удобно и действенно. Недавно мне пришлось проделать эту операцию с БД двух моих клиентов AT&T и Cingular. Все «преобразование» заняло 45 минут.

Другой простой пример: представьте, что ваши клиенты часто работают удаленно в оффлайне, и вам приходится закачивать их данные в общую БД при подключении. Теперь это проще, чем у ребенка конфету отнять… © Если вы верите в GUID. Вы можете легко таскать данные между базами.

3) Типо-независимость

Третья причина, по которой я верю в GUID — это то, что я называю «типо-независимость» (Type Ignorance — это игра слов, построенная на Type Inference В .NET 3.5). Суть ее в том, что мне не важно, как хранятся данные в каждой таблице БД. Представьте, что у нас есть продукт, находящийся в коммерческом использовании уже некоторое время. В БД есть таблицы Customer, Order, OrderLineItem, Product (Товар) и Vendor (Поставщик). Теперь выяснилось, что нужно добавить «заметки» к каждому виду объекта. Для этього достаточно просто создать таблицу

Notes
NoteGUID Unique Identifier
ParentGUID Unique Identifier
Note VarChar(500)

Теперь можно вставлять заметки в эту таблицу, используя GUID самих объектов в ParentGUID. Для получения всех заметок по конкретному товару совершается простейшая выборка из notes по его GUID.

Например, чтобы получить все заметки по поставщику, достаточно создать простую связь (join) Note.ParentGUID к Vendor.VendorGUId. Не нужны никакие индикаторы типов, не нужно выдумывать, какие таблицы связывать, не нужно кучи ссылочных таблиц, чтобы понять с каким типом объекта связана строка.

Вы удивитесь, узнав насколько часто используется этот небольшой прием. Недавно мы добавили «аудит» к одному из наших приложений, в котором хотели выяснить кто что удалял, добавлял или изменял в БД. Мы просто добавили несколько строчек кода к методу DataContext SubmitChanges() (мы используем только LINQ в этом приложении) для создания соответствующей записи в таблице аудита. При создании нового объекта или типа в приложении запись в эту таблицу происходит автоматически, что позволяет нам не париться написанием специального «аудиторского» кода при добавлении новых типов данных в приложении.

4) Удар, удар, еще удар. (с)

Существует много менее очевидных причин для использования GUID, но есть одна, которую я не предвидел заранее и за которую я благодарю GUID, ибо он и только он спас миллионы долларов моему клиенту… да, я сказал МИЛЛИОНЫ!

Я разрабатывал систему управления автоматическими выплатами за размещение рекламы для крупного клиента. Они должны были иметь возможность по нажатию кнопки оплачивать счета общей суммой в миллионы долларов. В двух словах, по нажатию кнопки наша система генерирует файл с очередью и отправляет его их платежному серверу, который сгенерирует чеки… и денежки уйдут. Конечно, я использовал GUID, чтобы идентифицировать все и вся, поэтому когда платежный сервер генерировал файл сверки, я легко мог прогнать его по своей базе.

На нашем сайте была развернута рабочая БД клиента и тестовая БД, слегка устаревшая копия рабочей (на пару месяцев). В процессе тестирования кто-то на их стороне увидел один из наших тестовых файлов с очередью оплат и, не долго думая, скормил их платежному серверу. Ну, дальше вы поняли… Клиент заплатил куче действительных поставщиков контента дважды (один раз по реальному запросу, второй раз — по тестовому), а также еще и не совсем нормальным поставщикам (например тем, что уже не размещали рекламу, ведь тестовая БД устарела на пару месяцев). Вот так, без каких-либо косяков с моей стороны, я получил ужасную помойку в данных… ну по крайней мере так думал мой клиент. Однако, поскольку все мои записи о выплатах имели GUID, я мог легко выделить те записи, что пришли из тестовой базы, чтобы отменить платежи по ним. Представьте, если бы я использовал INT, у меня не было бы способа узнать из какой базы пришел запрос PaymentID = 1000, например.

Ну так как же это помогло спасти миллионы? Просто… умножьте тысячи запросов на штраф за отмену платежа ($20-30). И еще на три, поскольку такая ошибка повторилась три раза!

Ну а есть ли недостатки у GUID?

Если кратко, то да, есть. Однако они, настолько незначительны, что не могут изменить моего мнения. Наиболее очевидный из них — это написание SQL запросов вручную (кгда надо что-то найти).

SELECT * FROM ORDER WHERE ORDERID = 12

гораздо легче, чем

Еще один недостаток — небольшое снижение производительности у связей, построенных на базе gUID, по сравнению с INT. Но по моему опыту даже при использовании таблиц с многомиллионным количеством строк, это никогда не становилось проблемой. Несколько миллисикунд задержки — небольшая цена за все прелести GUIDа.

Опробуйте эту технику в каком-нибудь небольшом проекте, особенно если все еще настроены скептично. Думаю, она окажется более полезной чем вы могли мечтать.

Источник

Для этого термина существует аббревиатура «GUID», которая имеет и другие значения: см. GUID.

GUID (Globally Unique Identifier) — статистически уникальный 128-битный идентификатор. Его главная особенность — уникальность, которая позволяет создавать расширяемые сервисы и приложения без опасения конфликтов, вызванных совпадением идентификаторов. Хотя уникальность каждого отдельного GUID не гарантируется, общее количество уникальных ключей настолько велико (2128 или 3,4028×1038), что вероятность того, что в мире будут независимо сгенерированы два совпадающих ключа, крайне мала.

«GUID» называют некоторые реализации стандарта, имеющего название Universally Unique Identifier (UUID).

В тексте GUID записывается в виде строки из тридцати двух шестнадцатеричных цифр, разбитой на группы дефисами и опционально окружённой фигурными скобками:

{6F9619FF-8B86-D011-B42D-00CF4FC964FF}[1]

Реализация Microsoft

Структура идентификатора:

 GUID STRUCT
     Data1   dd
     Data2   dw
     Data3   dw
     Data4   dq
 GUID ENDS

UUID-идентификаторы часто записывают в виде текстовой строки
{G4G3G2G1-G6G5-G8G7-G9G10-G11G12G13G14G15G16}, где Gx — значение соответствующего байта структуры в шестнадцатеричном представлении[1]:

Data1 = G4G3G2G1
Data2 = G6G5
Data3 = G8G7
Data4 = G9G10G11G12G13G14G15G16

Например, ‘22345200-abe8-4f60-90c8-0d43c5f6c0f6’ соответствует шестнадцатеричному 128-битному числу 0xF6C0F6C5430DC8904F60ABE822345200

Максимальное значение в GUID соответствует десятичному числу 340 282 366 920 938 463 463 374 607 431 768 211 455.

Microsoft применяет GUID в OLE, COM и DCOM — например, в качестве идентификаторов для классов (CLSID), интерфейсов (IID), библиотек типов (LIBID). Использование GUID гарантирует, что две (возможно, несовместимые) версии одного компонента могут иметь одно и то же имя, но быть отличимыми по GUID.

Алгоритм, который Microsoft использовала для генерации GUID, был широко раскритикован. В частности, в качестве основы для генерации части цифр GUID использовался MAC-адрес сетевого адаптера, что означало, например, что по данному документу MS Word (также получающему при создании свой уникальный GUID) можно было определить компьютер, на котором он был создан. Позже Microsoft изменила алгоритм таким образом, чтобы он не включал в себя MAC-адрес.

Другие реализации

Также GUID — основа Таблицы разделов GUID, замены MBR в EFI.

Примечания

  1. 1 2 Последнее 8-байтное данное при записи часто разбивается на 2+6 (подробнее см. в английской версии статьи).

Ссылки

  • Устройство и криптоанализ UUID-генератора в ОС Windows
  • RFC: A Universally Unique IDentifier (UUID) URN Namespace

Понравилась статья? Поделить с друзьями:
  • Is guaranteed a word
  • Is grinch a word
  • Is grew up a word
  • Is greener a word
  • Is holiday a british word