To understand how to write DSLs (internal/external) in Scala I started implementing a small subset of the SQL language.
Implemented:
- select operation with fields
- where clause with (typed) equals, in, and, or
- order
- A ‘renderer’ to create a SQL String from the given Query object
Scala SQL DSL lets you write stuff like:
scala> val q = select ("*") from ("user") where (("name","peter") and (("active", true) or ("role", "admin")))
scala> q.sql
res0: java.lang.String = select * from user where (name = 'peter' and (active = true or role = 'admin'))
Or using the parser:
scala> val sql = """select name,age from users where name = "peter" and (active = true or age = 30)""" scala> val query = p.parse(sql).get scala> AnsiSqlRenderer.sql(query) res0: java.lang.String = select name,age from users where (name = 'peter' and (active = true or age = 30))
- maven2
- maven uses the maven-scala-test plugin of which I have a for here: [http://github.com/p3t0r/maven-scalatest-plugin/] for running the specs
The spec contains various examples on how to write queries. But basically you start by:
- Import all functions/implicits in the QueryBuilder object: import QueryBuilder._
- Import the AnsiSqlRenderer object: AnsiSqlRenderer._
Written by Peter Maas
This software is licensed under the Apache 2 license, quoted below.
Licensed under the Apache License, Version 2.0 (the "License"); you may not
use this file except in compliance with the License. You may obtain a copy of
the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
License for the specific language governing permissions and limitations under
the License.