{"id":13508905,"url":"https://github.com/bettyblocks/sql_dust","last_synced_at":"2025-04-07T12:05:36.765Z","repository":{"id":46892224,"uuid":"50567659","full_name":"bettyblocks/sql_dust","owner":"bettyblocks","description":"Easy. Simple. Powerful. Generate (complex) SQL queries using magical Elixir SQL dust.","archived":false,"fork":false,"pushed_at":"2021-09-21T23:17:19.000Z","size":189,"stargazers_count":118,"open_issues_count":9,"forks_count":14,"subscribers_count":6,"default_branch":"master","last_synced_at":"2025-03-31T10:08:09.607Z","etag":null,"topics":[],"latest_commit_sha":null,"homepage":"https://hex.pm/packages/sql_dust","language":"Elixir","has_issues":true,"has_wiki":null,"has_pages":null,"mirror_url":null,"source_name":null,"license":null,"status":null,"scm":"git","pull_requests_enabled":true,"icon_url":"https://github.com/bettyblocks.png","metadata":{"files":{"readme":"README.md","changelog":"CHANGELOG.md","contributing":null,"funding":null,"license":null,"code_of_conduct":null,"threat_model":null,"audit":null,"citation":null,"codeowners":null,"security":null,"support":null}},"created_at":"2016-01-28T08:19:47.000Z","updated_at":"2024-09-30T03:28:07.000Z","dependencies_parsed_at":"2022-09-20T12:51:57.388Z","dependency_job_id":null,"html_url":"https://github.com/bettyblocks/sql_dust","commit_stats":null,"previous_names":[],"tags_count":0,"template":false,"template_full_name":null,"repository_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/bettyblocks%2Fsql_dust","tags_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/bettyblocks%2Fsql_dust/tags","releases_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/bettyblocks%2Fsql_dust/releases","manifests_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/bettyblocks%2Fsql_dust/manifests","owner_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners/bettyblocks","download_url":"https://codeload.github.com/bettyblocks/sql_dust/tar.gz/refs/heads/master","host":{"name":"GitHub","url":"https://github.com","kind":"github","repositories_count":247648976,"owners_count":20972945,"icon_url":"https://github.com/github.png","version":null,"created_at":"2022-05-30T11:31:42.601Z","updated_at":"2022-07-04T15:15:14.044Z","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":[],"created_at":"2024-08-01T02:01:00.307Z","updated_at":"2025-04-07T12:05:36.704Z","avatar_url":"https://github.com/bettyblocks.png","language":"Elixir","funding_links":[],"categories":["ORM and Datamapping"],"sub_categories":[],"readme":"# SqlDust [![Hex.pm](https://img.shields.io/hexpm/v/sql_dust.svg)](https://hex.pm/packages/sql_dust) [![Hex.pm](https://img.shields.io/hexpm/dt/sql_dust.svg)](https://hex.pm/packages/sql_dust) [![Build Status](https://travis-ci.org/bettyblocks/sql_dust.svg?branch=master)](https://travis-ci.org/bettyblocks/sql_dust) [![Deps Status](https://beta.hexfaktor.org/badge/all/github/bettyblocks/sql_dust.svg)](https://beta.hexfaktor.org/github/bettyblocks/sql_dust) [![Inline docs](http://inch-ci.org/github/archan937/sql_dust.svg)](http://inch-ci.org/github/archan937/sql_dust)\n\nEasy. Simple. Powerful. Generate (complex) SQL queries using magical Elixir SQL dust.\n\n## Introduction\n\nEvery language has its commonly used libraries / gems / packages to interact with databases. Ruby has [ActiveRecord](https://github.com/rails/rails/tree/master/activerecord) and Elixir has [Ecto](https://github.com/elixir-lang/ecto). They provide a lot of functionality which are very useful but when it comes to quickly and easily querying tabular data they require too much hassle:\n\n* you have to describe models representing tables ([example](https://github.com/elixir-lang/ecto/blob/master/examples/simple/lib/simple.ex))\n* you have to describe how to join tables ([example](https://blog.drewolson.org/composable-queries-ecto))\n* using the query DSL requires a bit of reading and understanding how to use it\n\nActually, you do not want to waste time specifying how to join tables and thinking about table aliases when you have followed the standard naming convention. And you do not want to think about putting a condition in the `WHERE` or `HAVING` statement.\n\nThe solution is to think in **paths** (e.g. `company.tags.name`) and letting the package do the magic regarding joining table and to use `SELECT` statement aliases to determine `HAVING` statements.\n\nEnter `SqlDust`. It makes it as easy and simple as possible for the developer to generate SQL queries:\n\n* no models setup\n* no joins specifications\n* no DSL to learn\n\nJust focus on what really matters! ;)\n\n### Examples\n\nBased on standard naming conventions, `SqlDust` will determine how to join tables. You just have to specify from which resource (table) to query from and which columns to select using paths:\n\n```elixir\n$ iex -S mix\niex(1)\u003e SqlDust.from(\"users\", %{select: ~w(id first_name company.category.name)})\n{\"SELECT\\n  `u`.`id`,\\n  `u`.`first_name`,\\n  `company.category`.`name`\\nFROM users `u`\\nLEFT JOIN companies `company` ON `company`.`id` = `u`.`company_id`\\nLEFT JOIN categories `company.category` ON `company.category`.`id` = `company`.`category_id`\\n\",\n []}\niex(2)\u003e IO.puts elem(v, 0)\nSELECT\n  `u`.`id`,\n  `u`.`first_name`,\n  `company.category`.`name`\nFROM users `u`\nLEFT JOIN companies `company` ON `company`.`id` = `u`.`company_id`\nLEFT JOIN categories `company.category` ON `company.category`.`id` = `company`.`category_id`\n\n:ok\niex(3)\u003e\n```\n\nComposable queries are also possible:\n\n```elixir\n$ iex -S mix\niex(1)\u003e import SqlDust.Query\nnil\niex(2)\u003e select(\"id, last_name, first_name\") |\u003e from(\"users\") |\u003e where([\"company.id = ?\", 1982]) |\u003e to_sql\n{\"SELECT `u`.`id`, `u`.`last_name`, `u`.`first_name`\\nFROM users `u`\\nLEFT JOIN companies `company` ON `company`.`id` = `u`.`company_id`\\nWHERE (`company`.`id` = ?)\\n\",\n [1982]}\niex(3)\u003e IO.puts elem(v, 0)\nSELECT `u`.`id`, `u`.`last_name`, `u`.`first_name`\nFROM users `u`\nLEFT JOIN companies `company` ON `company`.`id` = `u`.`company_id`\nWHERE (`company`.`id` = ?)\n\n:ok\niex(4)\u003e \"users\" |\u003e adapter(:postgres) |\u003e to_sql\n{\"SELECT \\\"u\\\".*\\nFROM users \\\"u\\\"\\n\", []}\niex(5)\u003e IO.puts elem(v, 0)\nSELECT \"u\".*\nFROM users \"u\"\n\n:ok\niex(6)\u003e\n```\n\nComposable queries using [Ecto](https://github.com/elixir-lang/ecto) models are also possible (using [Ecto simple example](https://github.com/elixir-lang/ecto/blob/master/examples/simple/lib/simple.ex)):\n\n```elixir\niex(1)\u003e import Ecto.SqlDust\nnil\niex(2)\u003e Weather |\u003e to_sql\n{\"SELECT \\\"w\\\".*\\nFROM weather \\\"w\\\"\\n\", []}\niex(3)\u003e IO.puts elem(v, 0)\nSELECT \"w\".*\nFROM weather \"w\"\n\n:ok\niex(4) City |\u003e select(\"id, name, country.name\") |\u003e where([\"country.name = ?\", \"United States\"]) |\u003e to_sql\n{\"SELECT \\\"c\\\".\\\"id\\\", \\\"c\\\".\\\"name\\\", \\\"country\\\".\\\"name\\\"\\nFROM cities \\\"c\\\"\\nLEFT JOIN countries \\\"country\\\" ON \\\"country\\\".\\\"id\\\" = \\\"c\\\".\\\"country_id\\\"\\nWHERE (\\\"country\\\".\\\"name\\\" = ?)\\n\", [\"United States\"]}\niex(5)\u003e IO.puts elem(v, 0)\nSELECT \"c\".\"id\", \"c\".\"name\", \"country\".\"name\"\nFROM cities \"c\"\nLEFT JOIN countries \"country\" ON \"country\".\"id\" = \"c\".\"country_id\"\nWHERE (\"country\".\"name\" = ?)\n\n:ok\niex(6)\u003e\n```\n\n## Installation\n\nTo install SqlDust, please do the following:\n\n  1. Add sql_dust to your list of dependencies in `mix.exs`:\n\n        def deps do\n          [{:sql_dust, \"~\u003e 0.3.10\"}]\n        end\n\n  2. Ensure sql_dust is started before your application:\n\n        def application do\n          [applications: [:sql_dust]]\n        end\n\n## Usage\n\nGenerating SQL queries has never been simpler. Just invoke the `SqlDust.from/3` function. It accepts the following arguments:\n\n* `resource` (required) - Usually this is the table from which you want to query from\n* `options` (required) - A map containing info about what the query should contain (e.g. `:select`, `:where`, `:group_by`)\n* `schema` (optional) - A map containing info which overrule the defacto derived schema\n\n```elixir\noptions = %{\n  select: \"id, name, COUNT(orders.id) AS order_count, GROUP_CONCAT(DISTINCT tags.name) AS tags, foo.tags\",\n  group_by: \"id\",\n  where: [\"name LIKE '%Paul%'\", \"order_count \u003e 5\", \"foo.tags = 1\"],\n  order_by: \"COUNT(DISTINCT tags.id) DESC\",\n  limit: 5\n}\n\nschema = %{\n  customers: %{\n    tags: %{\n      cardinality: :has_and_belongs_to_many\n    }\n  }\n}\n\nSqlDust.from(\"customers\", options, schema) |\u003e elem(0) |\u003e IO.puts\n\n\"\"\"\nSELECT\n  `c`.`id`,\n  `c`.`name`,\n  COUNT(`orders`.`id`) AS `order_count`,\n  GROUP_CONCAT(DISTINCT `tags`.`name`) AS `tags`,\n  `foo`.`tags`\nFROM customers `c`\nLEFT JOIN orders `orders` ON `orders`.`customer_id` = `c`.`id`\nLEFT JOIN customers_tags `tags_bridge_table` ON `tags_bridge_table`.`customer_id` = `c`.`id`\nLEFT JOIN tags `tags` ON `tags`.`id` = `tags_bridge_table`.`tag_id`\nLEFT JOIN foos `foo` ON `foo`.`id` = `c`.`foo_id`\nWHERE (`c`.`name` LIKE '%Paul%') AND (`foo`.`tags` = 1)\nGROUP BY `c`.`id`\nHAVING (`order_count` \u003e 5)\nORDER BY COUNT(DISTINCT `tags`.`id`) DESC\nLIMIT ?\n\"\"\"\n```\n\n### Composable queries\n\nAs of version `0.1.0`, it is to possible compose queries (thanks to [Justin Workman](https://github.com/xtagon) for the request):\n\n```elixir\nimport SqlDust.Query\n\nselect(\"id, last_name, first_name\")\n  |\u003e from(\"users\")\n  |\u003e where(\"company.id = 1982\")\n  |\u003e where(\"last_name LIKE '%Engel%'\")\n  |\u003e order_by([\"last_name\", \"first_name\"])\n  |\u003e to_sql\n  |\u003e elem(0)\n  |\u003e IO.puts\n\n\"\"\"\nSELECT `u`.`id`, `u`.`last_name`, `u`.`first_name`\nFROM users `u`\nLEFT JOIN companies `company` ON `company`.`id` = `u`.`company_id`\nWHERE (`company`.`id` = 1982) AND (`u`.`last_name` LIKE '%Engel%')\nORDER BY `u`.`last_name`, `u`.`first_name`\n\"\"\"\n```\n\n### Composable queries using Ecto models\n\nAs of version `0.1.1`, it is to possible compose queries using Ecto(!) models:\n\n```elixir\nimport Ecto.SqlDust\n\nCity\n  |\u003e select(\"id, name, country.name, local_weather.temp_lo, local_weather.temp_hi\")\n  |\u003e where(\"local_weather.wdate = '2015-09-12'\")\n  |\u003e to_sql\n  |\u003e elem(0)\n  |\u003e IO.puts\n\n\"\"\"\nSELECT\n  \"c\".\"id\",\n  \"c\".\"name\",\n  \"country\".\"name\",\n  \"local_weather\".\"temp_lo\",\n  \"local_weather\".\"temp_hi\"\nFROM cities \"c\"\nLEFT JOIN countries \"country\" ON \"country\".\"id\" = \"c\".\"country_id\"\nLEFT JOIN weather \"local_weather\" ON \"local_weather\".\"city_id\" = \"c\".\"id\"\nWHERE (\"local_weather\".\"wdate\" = '2015-09-12')\n\"\"\"\n```\n\n### MySQL versus Postgres\n\nAt default, SqlDust generates queries with MySQL quotations except for when using Ecto models because then it defaults to Postgres. You can specify the adapter using the `adapter` function after having piped the Ecto model:\n\n```elixir\nimport Ecto.SqlDust\n\nCity\n  |\u003e select(\"id, name\")\n  |\u003e adapter(:mysql)\n  |\u003e to_sql\n  |\u003e elem(0)\n  |\u003e IO.puts\n\n\"\"\"\nSELECT `c`.`id`, `c`.`name`\nFROM cities `c`\n\"\"\"\n```\n\nSqlDust should automatically determine the correct database adapter of the Ecto model of course. So that will be added in the following release.\n\n### Tackling SQL injection\n\nAs of version `0.2.0`, when generating the SQL query, SqlDust returns a tuple containing the SQL query string along with a list containing values which the database should interpolate safely.\n\nEnjoy using SqlDust! ^^\n\n### Variable keys within resulting tuple\n\nAs of version `0.3.0`, SqlDust returns a tuple with an additional list of variable keys which corresponds to the passed `options[:variables]`.\n\nTo have it clear:\n\n* SqlDust will return a tuple of **two** elements when NOT having passed variables\n* SqlDust will return a tuple of **three** elements when having passed variables\n\n## Testing\n\nRun the following command for testing:\n\n    mix test\n\nAll the SqlDust features are tested in [test/sql_dust_test.exs](https://github.com/archan937/sql_dust/blob/master/test/sql_dust_test.exs), [test/sql_dust/query_test.exs](https://github.com/archan937/sql_dust/blob/master/test/sql_dust/query_test.exs) and [test/ecto/sql_dust_test.exs](https://github.com/archan937/sql_dust/blob/master/test/ecto/sql_dust_test.exs).\n\n## Nice To Have\n\n* Query from the database\n\n## TODO\n\n* Automatically derive database adapter using `Ecto.Repo`\n* Support `has through` associations\n* Support polymorphic associations\n* Add additional documentation to the README\n* Add doc tests for internal functions\n\n## License\n\nCopyright (c) 2017 Paul Engel, released under the MIT License\n\nhttp://github.com/archan937 – http://twitter.com/archan937 – pm_engel@icloud.com\n\nPermission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the \"Software\"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:\n\nThe above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.\n\nTHE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.\n","project_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fbettyblocks%2Fsql_dust","html_url":"https://awesome.ecosyste.ms/projects/github.com%2Fbettyblocks%2Fsql_dust","lists_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fbettyblocks%2Fsql_dust/lists"}