Skip to content

Instantly share code, notes, and snippets.

@luza
Last active May 26, 2018 10:52
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save luza/1000c36ad16b8b92d23c7cb023021bfa to your computer and use it in GitHub Desktop.
Save luza/1000c36ad16b8b92d23c7cb023021bfa to your computer and use it in GitHub Desktop.
EAN13 barcode generator example plpgsql postgres
with recursive source as (
select (220000000000::bigint + round(random() * 10000000000))::bigint as code
from generate_series(1, 10000)
),
checksum_calc as (
select code, 3 as cs_mult, 0::bigint as checksum, code as interm_code from source
union
select
code,
(case when cs_mult = 3 then 1 else 3 end) as cs_mult,
interm_code % 10 * cs_mult as checksum,
interm_code / 10 as interm_code
from checksum_calc
where interm_code > 0
)
select (code::text || ((10 - sum(checksum) % 10) % 10)::text)::bigint as code
from checksum_calc group by code
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment