Kong plugins do not connect to Cassandra or PostgreSQL on their own. They work through a model layer built around classes called DAOs. Kong supports two datastores: Cassandra 3.x.x and PostgreSQL 9.5+.
The central entry point is kong.db. It ties together two things:
- A schema that describes which table in the datastore an entity maps to, along with field constraints such as foreign keys and non-null requirements. This is the same schema used for plugin configuration.
- A DAO instance tied to the database currently in use, whether Cassandra or PostgreSQL. Its methods use the schema and expose operations to insert, update, find, and delete entities of that type.
Kong's core entities—Services, Routes, Consumers, and Plugins—are exposed as DAOs through the kong.db singleton. Plugins can reach both these built-in entities and their own custom entities through kong.db.*.
For example, the core DAOs are available like this:
-- Core DAOs
local services_dao = kong.db.services
local routes_dao = kong.db.routes
local consumers_dao = kong.db.consumers
local plugins_dao = kong.dao.plugins
The DAO Lua API handles operations on a given table in the datastore, usually mapped to a Kong entity. All supported databases follow the same interface, so DAO code remains compatible across them.
Inserting a service and a plugin is straightforward:
local inserted_service, err = kong.db.services:insert({
name = "mockbin",
url = "http://mockbin.org",
})
local inserted_plugin, err = kong.db.plugins:insert({
name = "key-auth",
service_id = { id = inserted_service.id },
})
For a concrete example of DAO usage inside a plugin, the Key-Auth plugin provides a useful reference. The pattern is consistent: access the relevant DAO through kong.db, pass the entity fields to its methods, and let the DAO layer handle the underlying datastore.