{"id":36626537,"url":"https://github.com/viascom/nanoid-postgres","last_synced_at":"2026-01-12T09:32:36.572Z","repository":{"id":44593692,"uuid":"512870172","full_name":"viascom/nanoid-postgres","owner":"viascom","description":"Nano ID for PostgreSQL.","archived":false,"fork":false,"pushed_at":"2025-06-24T12:37:39.000Z","size":43,"stargazers_count":360,"open_issues_count":1,"forks_count":12,"subscribers_count":9,"default_branch":"main","last_synced_at":"2025-06-24T13:47:14.512Z","etag":null,"topics":["database","nanoid","postgres"],"latest_commit_sha":null,"homepage":"","language":"PLpgSQL","has_issues":true,"has_wiki":null,"has_pages":null,"mirror_url":null,"source_name":null,"license":"apache-2.0","status":null,"scm":"git","pull_requests_enabled":true,"icon_url":"https://github.com/viascom.png","metadata":{"files":{"readme":"README.md","changelog":null,"contributing":null,"funding":null,"license":"LICENSE","code_of_conduct":null,"threat_model":null,"audit":null,"citation":null,"codeowners":null,"security":null,"support":null,"governance":null,"roadmap":null,"authors":null,"dei":null,"publiccode":null,"codemeta":null,"zenodo":null}},"created_at":"2022-07-11T18:36:13.000Z","updated_at":"2025-06-24T12:37:43.000Z","dependencies_parsed_at":"2024-03-25T21:30:53.550Z","dependency_job_id":"802f3ad3-aa20-4c6f-8340-145b931eb4fb","html_url":"https://github.com/viascom/nanoid-postgres","commit_stats":null,"previous_names":[],"tags_count":3,"template":false,"template_full_name":null,"purl":"pkg:github/viascom/nanoid-postgres","repository_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/viascom%2Fnanoid-postgres","tags_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/viascom%2Fnanoid-postgres/tags","releases_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/viascom%2Fnanoid-postgres/releases","manifests_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/viascom%2Fnanoid-postgres/manifests","owner_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners/viascom","download_url":"https://codeload.github.com/viascom/nanoid-postgres/tar.gz/refs/heads/main","sbom_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/viascom%2Fnanoid-postgres/sbom","scorecard":null,"host":{"name":"GitHub","url":"https://github.com","kind":"github","repositories_count":286080680,"owners_count":28337728,"icon_url":"https://github.com/github.png","version":null,"created_at":"2022-05-30T11:31:42.601Z","updated_at":"2026-01-12T06:09:07.588Z","status":"ssl_error","status_checked_at":"2026-01-12T06:05:18.301Z","response_time":98,"last_error":"SSL_connect returned=1 errno=0 peeraddr=140.82.121.5:443 state=error: unexpected eof while reading","robots_txt_status":"success","robots_txt_updated_at":"2025-07-24T06:49:26.215Z","robots_txt_url":"https://github.com/robots.txt","online":false,"can_crawl_api":true,"host_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub","repositories_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories","repository_names_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repository_names","owners_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners"}},"keywords":["database","nanoid","postgres"],"created_at":"2026-01-12T09:32:36.020Z","updated_at":"2026-01-12T09:32:36.560Z","avatar_url":"https://github.com/viascom.png","language":"PLpgSQL","funding_links":[],"categories":[],"sub_categories":[],"readme":"# Nano ID for PostgreSQL\n\n_Inspired by the following parent project: [ai/nanoid](https://github.com/ai/nanoid)_\n\n\u003cimg src=\"./logo.svg\" align=\"right\" alt=\"Nano ID logo by Anton Lovchikov\" width=\"180\" height=\"94\"\u003e\n\nA tiny, secure, URL-friendly, unique string ID generator for Postgres.\n\n\u003e “An amazing level of senseless perfectionism, which is simply impossible not to respect.”\n\n* **Small.** Just a simple Postgres function.\n* **Safe.** It uses pgcrypto random generator. Can be used in clusters.\n* **Short IDs.** It uses a larger alphabet than UUID (`A-Za-z0-9_-`). So ID size was reduced from 36 to 21 symbols.\n* **Portable**. Nano ID was ported\n  to [over 20 programming languages](https://github.com/ai/nanoid/blob/main/README.md#other-programming-languages).\n\n## How to use\n\n```sql\nSELECT nanoid(); -- Simplest way to use this function. Creates an id, with the defaults of the created nanoid() function.\nSELECT nanoid(4); -- size parameter set to return 4 digit ids only\nSELECT nanoid(3, 'abcdefghij'); -- custom size and alphabet parameters defined. nanoid() generates ids concerning them.\nSELECT nanoid(10, '23456789abcdefghijklmnopqrstuvwxyz', 1.85); -- nanoid() could generates ids more performant with a custom defined additional bytes factor.\n```\n\n```sql\nCREATE TABLE mytable(\n    id char(21) DEFAULT nanoid() PRIMARY KEY\n);\n\nor\n\n-- To use a custom id size\nCREATE TABLE mytable(\n    id char(14) DEFAULT nanoid(14) PRIMARY KEY\n);\n\nor\n\n-- To use a custom id size and a custom alphabet\nCREATE TABLE mytable(\n    id char(12) DEFAULT nanoid(12, 'ABC123') PRIMARY KEY\n);\n```\n\n## Getting Started\n\n### Requirements\n\n* PostgreSQL 9.4 or newer\n\nExecute the file `nanoid.sql` to create the `nanoid()` function on your defined schema. The nanoid() function will only\nbe available in the specific database where you run the SQL code provided.\n\n**Manually create the function in each database:** You can connect to each database and create the function. This\nfunction can be created manually or through a script if you have many databases. Remember to manage updates to the\nfunction. If you change the function in one database, those changes will only be reflected in the other databases if you\nupdate each function.\n\n## Adding to the default template database\n\n**Use a template database:** If you often create databases that need to have the same set of functions, you could create\na template database that includes these functions. Then, when you create a new database, you can specify this template,\nand PostgreSQL will make the new database a copy of the template.\n\nHere's how to do that:\n\n1. Connect to template1 database:\n2. Then, run your `nanoid()` function creation code.\n\n*If the function is only needed for specific applications, it might be better to create it manually in each database\nwhere needed or create a custom template database that includes this function and use that template when creating new\ndatabases for these applications.*\n\nAlso, note that changes to template1 won't affect existing databases, only new ones created after the changes. Existing\ndatabases will need to have the function added manually if required.\n\nReference: [Template Databases](https://www.postgresql.org/docs/current/manage-ag-templatedbs.html)\n\n## Calculating the additional bytes factor for a custom alphabet\n\nIf you change the alphabet of the `nanoid()` function, you could optimize the performance by calculating a new\nadditional bytes factor with the following SQL statement:\n\n```sql\nWITH input as (SELECT '23456789abcdefghijklmnopqrstuvwxyz' as alphabet)\nSELECT round(1 + abs((((2 \u003c\u003c cast(floor(log(length(alphabet) - 1) / log(2)) as int)) - 1) - length(alphabet)::numeric) / length(alphabet)), 2) as \"Optimal additional bytes factor\"\nFROM input;\n\n-- The resulting value can then be used f.e. as follows:\nSELECT nanoid(10, '23456789abcdefghijklmnopqrstuvwxyz', 1.85);\n```\n\nUtilizing a custom-calculated additional bytes factor in `nanoid()`  enhances string generation performance. This factor\ndetermines how many bytes are generated in a single batch, optimizing computational efficiency. Generating an optimal\nnumber of bytes per batch minimizes redundant operations and conserves memory.\n\n## Usage Guide: `nanoid_optimized()`\n\nThe `nanoid_optimized()` function is an advanced version of the `nanoid()` function designed for higher performance and\nlower memory overhead. While it provides a more efficient mechanism to generate unique identifiers, it assumes that you\nknow precisely how you want to use it.\n\n🚫 **Warning**: No checks are performed inside `nanoid_optimized()`. Use it only if you're sure about the parameters you'\nre passing.\n\n### Function Signature\n\n```sql\nnanoid_optimized(\n    size int,\n    alphabet text,\n    mask int,\n    step int\n) RETURNS text;\n```\n\n### Parameters\n\n- `size`: The desired length of the generated string.\n- `alphabet`: The set of characters to choose from for generating the string.\n- `mask`: The mask used for mapping random bytes to alphabet indices. The value should be `(2^n) - 1`, where `n` is a\n  power of 2 less than or equal to the alphabet size.\n- `step`: The number of random bytes to generate in each iteration. A larger value might speed up the function but will\n  also increase memory usage.\n\n### Example Usage\n\nGenerate a NanoId String of length 10 using the default alphabet set:\n\n```sql\nSELECT nanoid_optimized(10, '_-0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ', 63, 16);\n```\n\n### Tips:\n\n- **Performance**: This function is optimized for performance, so it's ideal for scenarios where high-speed ID\n  generation is needed.\n- **Alphabet Set**: The larger your alphabet set, the more unique your generated IDs will be, but also consider the mask\n  and step parameters' adjustments.\n- **Customization**: Feel free to adjust the parameters to suit your specific needs, but always be cautious about the\n  values you're inputting.\n\nBy following this guide, you can seamlessly integrate the `nanoid_optimized()` function into your projects and enjoy the\nbenefits of its optimized performance.\n\n### LEAKPROOF Setting\n\n#### Default Configuration\n\nThe `nanoid()` function is configured without the `LEAKPROOF` attribute by default to ensure compatibility across\ndiverse environments, including cloud platforms and managed services, without the need for superuser privileges.\n\n#### When to Enable LEAKPROOF\n\nEnabling `LEAKPROOF` is optional and beneficial in environments that require enhanced security measures, such as those\nutilizing row-level security (RLS). This setting should be considered if you have superuser access and seek to further\nrestrict information leakage.\n\n**Note:** To apply the LEAKPROOF attribute, uncomment the LEAKPROOF line in the function definition. This setting\nis permissible only for superusers due to its implications for database security and operation.\n\n## Using MySQL/MariaDB?\n\nIf you're using MySQL or MariaDB and you found this library helpful, we have a similar library for MySQL/MariaDB, too!\nCheck out our [Nano ID for MySQL/MariaDB](https://github.com/viascom/nanoid-mysql-mariadb) repository to use the same\ncapabilities in your MySQL/MariaDB databases.\n\n## 🌱 Contributors Welcome\n\n- 🐛 **Encountered a Bug?** Let us know with an issue. Every bit of feedback helps enhance the project.\n\n- 💡 **Interested in Contributing Code?** Simply fork and submit a pull request. Every contribution, no matter its size,\n  is valued.\n\n- 📣 **Have Some Ideas?** We're always open to suggestions. Initiate an issue for discussions or to share your insights.\n\nAll relevant details about the project can be found in this README.\n\nYour active participation 🤝 is a cornerstone of **nanoid-postgres**. Thank you for joining us on this journey.\n\n## 🖥️ Authors\n\n* **Patrick Bösch** - *Initial work* - [itsmefox](https://github.com/itsmefox)\n* **Nikola Stanković** - *Initial work* - [nik-sta](https://github.com/nik-sta)\n\nSee also the list of [contributors](https://github.com/viascom/nanoid-postgres/contributors) who participated in this\nproject. 💕\n\n## License\n\nThis project is licensed under the Apache License 2.0 - see the [LICENSE](LICENSE) file for details.\n","project_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fviascom%2Fnanoid-postgres","html_url":"https://awesome.ecosyste.ms/projects/github.com%2Fviascom%2Fnanoid-postgres","lists_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fviascom%2Fnanoid-postgres/lists"}