augnustin

augnustin

Are there some Ecto gurus here?

I have this SQL function which works amazingly well (using Postgres 11.6)

CREATE EXTENSION IF NOT EXISTS "unaccent";

CREATE OR REPLACE FUNCTION slugify("value" TEXT)
RETURNS TEXT AS $$
  -- removes accents (diacritic signs) from a given string --
  WITH "unaccented" AS (
    SELECT unaccent("value") AS "value"
  ),
  -- lowercases the string
  "lowercase" AS (
    SELECT lower("value") AS "value"
    FROM "unaccented"
  ),
  -- remove single and double quotes
  "removed_quotes" AS (
    SELECT regexp_replace("value", '[''"]+', '', 'gi') AS "value"
    FROM "lowercase"
  ),
  -- replaces anything that's not a letter, number, hyphen('-'), or underscore('_') with a hyphen('-')
  "hyphenated" AS (
    SELECT regexp_replace("value", '[^a-z0-9\\-_]+', '-', 'gi') AS "value"
    FROM "removed_quotes"
  ),
  -- trims hyphens('-') if they exist on the head or tail of the string
  "trimmed" AS (
    SELECT regexp_replace(regexp_replace("value", '\-+$', ''), '^\-', '') AS "value"
    FROM "hyphenated"
  )
  SELECT "value" FROM "trimmed";
$$ LANGUAGE SQL STRICT IMMUTABLE;

select * from user u
where slugify(u.administrative) = 'ile-de-france';

I have no idea how I could insert it in a ecto query, like:

    User
      |> where(slugify(:administrative, ^administrative))
      |> order_by([f], f.city)
      |> Repo.all()

Can someone help me with that? My searches for “Ecto custom SQL function” did not produce any result. :frowning:

Using 100% custom SQL query would be a pain because I need to chain it with other query criteria afterwards.

Showing Posts 1 to 7

hauleth

hauleth

Use fragment or check out my ecto_function (which is fancy way to use fragment).

augnustin

augnustin OP

Sounds promising @hauleth but where should I put the SQL function definition?

Your examples in the readme.md only use pre-defined SQL functions…

Thanks

hauleth

hauleth

From the viewpoint of Ecto/EctoFunction there is no difference between these two, so in you case it should work like that:

defqueryfunc slugify(value)

from u un user,
  where: slugify(u.administrative) == ^administrative
augnustin

augnustin OP

Yes, but I do need to tell postgres about this function definition. Any idiomatic way to do that with Ecto (or postgrex)?

hauleth

hauleth

You need to create that function in migration. You do not “tell” Postgres about function each time you want to use it.

augnustin

augnustin OP

You rock my world @hauleth :smile:

Here’s my migration:

defmodule Vae.Repo.Migrations.AddSlugifySQLFunction do
  use Ecto.Migration

  def change do
    Ecto.Adapters.SQL.query!(
      MyApp.Repo, """

CREATE EXTENSION IF NOT EXISTS "unaccent";

    """ )

    Ecto.Adapters.SQL.query!(
      MyApp.Repo, """

CREATE OR REPLACE FUNCTION slugify("value" TEXT)
RETURNS TEXT AS $$
  -- removes accents (diacritic signs) from a given string --
  WITH "unaccented" AS (
    SELECT unaccent("value") AS "value"
  ),
  -- lowercases the string
  "lowercase" AS (
    SELECT lower("value") AS "value"
    FROM "unaccented"
  ),
  -- remove single and double quotes
  "removed_quotes" AS (
    SELECT regexp_replace("value", '[''"]+', '', 'gi') AS "value"
    FROM "lowercase"
  ),
  -- replaces anything that's not a letter, number, hyphen('-'), or underscore('_') with a hyphen('-')
  "hyphenated" AS (
    SELECT regexp_replace("value", '[^a-z0-9\\-_]+', '-', 'gi') AS "value"
    FROM "removed_quotes"
  ),
  -- trims hyphens('-') if they exist on the head or tail of the string
  "trimmed" AS (
    SELECT regexp_replace(regexp_replace("value", '\-+$', ''), '^\-', '') AS "value"
    FROM "hyphenated"
  )
  SELECT "value" FROM "trimmed";
$$ LANGUAGE SQL STRICT IMMUTABLE;

    """ )
  end
end

hauleth

hauleth

You do not need to use Ecto,Adapters.SQL.query!/2 in the migrations. More - it is dangerous to do so (for example what if you will have multiple repos?). Instead use execute/{1,2}.

— All posts loaded —

Where Next? Top

Trending in Questions Top

RSP87
I’m working on a project that simulates the bumbl example in the programming phoenix book. It acts almost like an email client. We have a...
New
nseaSeb
Hello, I know there is an approach for handling lists that allows for optimized traversal, but I can’t recall the specific method (somet...
New
kpanic
Hi everyone, I am toying with the idea of building a “match maker” for giving personal help to people that wants to start coding. I sta...
New
brecabral
Documentation While reading the Scoped Routes section, I noticed that the documentation currently refers to a problem without explainin...
New
velrest
So my question is quite simple and i have found no conclusive answer on forum, google or AI. Should we use :erlang.float for Integer to ...
New
asweet-confluent
I recently noticed that Elixir’s Logger defaults its primary log level to :debug when no :logger, :level application configuration is pre...
New
apz
I’m new to elixir and just tried to install the elixirLS extension for VScode(ium) and it is throwing some errors that I would like help ...
New

Other Trending Topics Top

GenericJam
Edit: 2026 May 15 - This post is archived. Mob is alive!! Main docs: mob v0.7.11 — Documentation A bit of explanation for the slightly c...
New
JesseHerrick
Hey, I’m Jesse and I’m the main contributor behind Dexter, a full-featured, lightning-fast Elixir LSP optimized for large codebases. It s...
New
mudasobwa
I am happy to introduce the very α version of the new programming language compiled to BEAM. Welcome Cure. It has literally three kille...
New
marciok
Hi there! We created Gust: A task orchestrator inspired by Airflow. For those who have never heard about Aiflow, it’s a Python-based wor...
New
mhanberg
Hi everyone! The first release candidate for the Expert language server project is now available! We’ve published a press release detai...
New
jimsynz
Beam Bots (or just BB for short) is a framework for building fault-tolerant robotics applications in Elixir using familiar OTP patterns. ...
New

We're in Beta

About us Mission Statement

Options

Thread Display Mode




Thread Preview

Skip Thread Previews