• Stars
    star
    164
  • Rank 230,032 (Top 5 %)
  • Language
    Clojure
  • License
    MIT License
  • Created almost 16 years ago
  • Updated almost 12 years ago

Reviews

There are no reviews yet. Be the first to send feedback to the community and the maintainers!

Repository Details

DEPRECATED: A pseudo-port of ActiveRecord to the Clojure programming language

clj-record

clj-record is a Clojure persistence library inspired by Ruby on Rails’ ActiveRecord but aimed at using LISPey functional idioms.

In short, it’s a fairly thin layer on top of clojure.java.jdbc that allows you to define model namespaces and provides model-specific validation, associations, callbacks, and attribute serialization.

Join the clj-record-dev Google Group to stay up to date or discuss changes.

Contributions and suggestions are welcome. If you’d lke to contribute patches, please include tests.

Notice

The author of clj-record regrets its API design and recommends you don’t use it. Read the blog post for more details.

How to Use It

If you’re using Leiningen or Maven, see the clj-record page on Clojars for configuration snippets.

To define a model (in this case called “employee”), you do something like this.


  (ns com.example.employee
    (:require clj-record.boot))

  (def db ...a clojure.java.jdbc db-spec...)

  (clj-record.core/init-model)

The db ref can be brought in by a :use in the ns declaration rather than being defined directly in the model namespace.

The model name is the last segment of the namespace name.

By default the table name is assumed to be the pluralized model name, with dashes changed to underscores. (In the above case it would use “employees.”)

Specify a different table name like this.


  (ns com.example.employee
    (:require clj-record.boot))

  (clj-record.core/init-model
    :table-name "employee")

For the time being, the primary key column of the table must be named ‘id’.

The (clj-record.core/init-model) macro form with no extra arguments will expand
into function definitions for basic crud operations:

  • get-record (by id)
  • find-record (by a map of attributes)
  • all-records
  • find-records (by a map of attributes)
  • find-by-sql (by a SQL string and “?” parameter values)
  • insert (from a map of attributes, returning the generated id)
  • create (from a map of attributes, returning the record itself)
  • update (from a map of attributes that must include :id)
  • destroy-record (from a map of attributes that must include :id)
  • record-count (by optional map of attributes)

See the functions of the same names in clj-record.core for documentation.
(The functions in clj-record.core take the model-name as a first argument. The functions generated in your model namespace already know what model they’re about, so they don’t take that argument. Otherwise the functions are the same.)

Additional optional arguments to init-model can generate richer functionality.

Associations

Do this.


  (ns ...)

  (clj-record.core/init-model
    (:associations
      (belongs-to account)
      (has-many subscriptions)))

Then you can do things like this.


  (let [mikey (user/get-record 2)
        subs (user/find-subscriptions mikey)]
    (doseq [subscription subs] (println (format "Mikey is subscribed to %s" (:name subscription))))
    (user/destroy-subscriptions mikey)
    (println "But not any more."))

Association names will have dashes converted to underscores when used in queries.

To override the foreign key name or model name, do this:


  (ns ...)

  (clj-record.core/init-model
    (:associations
      (belongs-to account :fk account_fk_id)
      (has-many subscriptions :fk sub_id :model subscription-model-name)))

In a belongs-to, if :model is specified and :fk is not, then the foreign key
name is inferred from the association name. For example, in


  ...
  (belongs-to mother :model person)
  ...

the foreign key name will be mother_id (not person_id).

Validations

Do this.


  (ns ...)

  (clj-record.core/init-model
    (:validation
      (:name "Longer please." #(> (count %) 3))))

Then you get validation errors like this.


  => (let [errors (user/validate {:name "POO"})]
       (errors :name)
  ["Longer please."]

Callbacks…

…work about as you’d expect. Your function is passed the record and returns the (possibly modified) record.


  (clj-record.core/init-model
    (:callbacks
      (:before-save fn-that-transforms-a-record)))

The callbacks currently available are:

  • before-save
  • before-update
  • after-load

Adding more is easy, so send patches or let me know what callbacks would be useful.

Attribute Serialization

Do this.


  (ns ...)

  (clj-record.core/init-model
    (:serialization (:grades)))

Then you can persist Clojure data structures (and many other Java types) into char/varchar columns in your database.
Attribute serialization uses clojure.core’s pr and read functions, so anything they support, clj-record supports.


clj-record is being TDD’d using clojure.test, largely with high-level full-stack tests,
so see the tests
for details of everything that works.

See TODO.txt for what else I’m thinking about,
and feel free to suggest.

Development

We use Leiningen for building and testing. Install it using their instructions.

We use MySQL with InnoDB tables as a test database. First create the database with a command like this:


  echo "create database clj_record_test" | mysql -uroot

Then create (or recreate) the test tables with lein reset-db.
Run lein test to test.
You can uncomment and modify a different db-spec in test/clj-record/test_model/config.clj to use a different RDBMS.
That’s also where test DB credentials are defined.

Thanks for Contributing

Brian Doyle for early interest and ideas.
Stephen Gilardi for making helpful changes to clojure.contrib.sql.
Raja Ramachandran for initial implementation of PostgreSQL support.
tunde ashafa for initial implementation of MySQL support and the clj-record.query API.
Jim Menard for dash-to-underscore, record counting, and foreign key and model overrides in associations.
Matt Courtney for using clj-record as part of Conjure.


Copyright 2010 John D. Hume and released under an MIT license.

More Repositories

1

appengine-clj

Clojure library to make life on Google AppEngine clean and easy
Clojure
110
star
2

FluentTime

A fluent interface in C# for working with dates and times on the .NET framework
C#
85
star
3

renum

a readable but terse enum for Ruby
Ruby
26
star
4

guestbook-clj

Tutorial app for Clojure on Google AppEngine
Clojure
21
star
5

metaprogramming_introduction

An article introducing Ruby metaprogramming fundamentals, in source code form.
Ruby
17
star
6

SimURLator

A tool for in-Simulator manual testing of iPhone apps that openURL: or handleOpenURL:
Objective-C
13
star
7

macro-madness

Presentation on Clojure Macros
Clojure
11
star
8

todo-backend-rust-iron

Rust impl of todo-backend. Not publicly hosted yet.
Rust
10
star
9

insfactor

Tool to ease inspection and refactoring of clojure code
Clojure
10
star
10

life-of-a-clojure-expression

A deep but skinny slice of Clojure innards. (presentation)
Clojure
6
star
11

constantize_attribute

Gives ActiveRecord a constantize_attribute macro allowing attribute values to be Class and Module objects, among other things
Ruby
5
star
12

ring-request-logging

Ring middleware to log requests and responses
Clojure
5
star
13

datomic-schema

convenient Clojure fns for building up a datomic schema
Clojure
3
star
14

actionhelper

A Rails plugin for mixing action-specific helper modules into your view
Ruby
2
star
15

simple_app

Simplest possible Rails 2.3.11 app for deployment spike testing.
Ruby
1
star
16

away_day_RapidFTR

1
star
17

rust-study

Sandbox for playing w/ rust-lang.
Rust
1
star
18

insfactor.el

Emacs component of insfactor
Emacs Lisp
1
star